dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def parse_answers_from_parameters(size, density, criteria, solver, file_folder):
if criteria == OptimalityCriteria.EGALITARIAN:
folder = "egal"
elif criteria == OptimalityCriteria.FIRST_CHOICE_MAXIMAL and solver != "ASP":
folder = "1stmax"
elif criteria in [OptimalityCriteria.FIRST_CHOICE_MA... | The code checks the optimality and feasibility of solutions generated by different solvers (ASP and IP) against expected answers for various problem instances. It compares solutions with answers, identifies discrepancies, and evaluates feasibility, generating detailed messages for mismatches. Special handling is applie... | def check_optimality_and_feasibility(size, density, criteria, solver, file_folder):
answers = parse_answers_from_parameters(size, density, criteria, solver, file_folder)
messages = ""
# almost 40-50 is missing the first answer
if criteria == OptimalityCriteria.ALMOST_STABLE and density == 50 and size ==... |
def _filter_data(self):
"""
Filters main edges dataframe based on slider values. Also adjusts certain dictionaries based
on filtered data.
"""
start_time = time.time()
temporary_full_edges_df = pd.read_json(self.edges_json_initial, dtype={
'source_id': str... | This method updates graph elements by applying filters, trimming data, generating tables and color mappings, and setting a shortcut flag to avoid redundant processing. It conditionally executes filtering and table generation based on the `graph_update_shortcut` flag, then compiles final graph elements for output. | def update_graph_elements(self):
"""
Updates the elements list based on graph filters/adjustments.
"""
if not self.graph_update_shortcut:
self._filter_data()
self._trim_graph()
if not self.graph_update_shortcut:
self._generate_table()
... |
def sample_data(example, n_dim):
"""
Samples example data.
Args:
example (str): string containing sample dataset name
'cube', 'table_4d', 'ball_shell', 'ball_shell2',
'sphere', and 'filled_cube' are supported
n_dim (i... | The `__init__` method initializes a `DataTour` class to process and visualize high-dimensional data. It accepts input data, labels, and parameters for rotation sampling, normalization, and subsampling. If no data is provided, it generates example datasets (e.g., 'cube', 'sphere'). The method prepares features, applies ... | def __init__(
self,
data=None,
data_v=None,
labels=None,
rot_sampling=90,
n_rot_vectors=5,
n_subsample=500,
norm="scale",
example="cube",
example_num_dim=4,
generate_new_mtx=False,
):
"""
Constructor for DataTour... |
def pospart(x):
'''
Returns a value greater than zero
'''
return max(1e-15,x)
def Jinv(hm,um,hl,hr,ul,ur,g):
'''
Input:
------
hm - Intemediate hieght field
um - Intemediate velocity field
Returns: The inverse of the Jacobian transpose and Jacobian matrix multiplied by the Jacobi... | The code implements a Newton solver to compute intermediate shock Riemann solutions for shallow water equations. Given left (ql) and right (qr) states, it iteratively solves for intermediate height (hm) and velocity (um) fields using Newton-Raphson method, with Jacobian inversion and residual evaluation. The solver con... | def GN(ql,qr,g):
'''
Description: Newton solver used to generate all shock Riemann solution
-----------
Returns:
-------
hm - Intermediate shock hieght field
um - Intermediate shock velocity field
'''
#max _iterations
max_iter = 20
#tolerance
epsilon = 1e-16
#in... |
def qinit(x,meqn,ql,qr):
#initial height fields(left and right)
hl = ql[0]
hr = qr[0]
#initial momentum fields(left and right)
hul = ql[1]
hur = qr[1]
#initial momentum fields(left and right)
ul = hul/pospart(hl)
ur = hur/pospart(hr)
q = zeros((x.shape[0],meqn))
q[... | The code implements a finite volume method to solve hyperbolic partial differential equations (PDEs) using Godunov-type solvers. It sets up a spatial grid, initializes the solution with user-defined routines, and performs time-stepping with specified boundary conditions and numerical fluxes (via `GN_solver` or `forestc... | def claw(ax, bx, mx, Tfinal, umax, ql, qr, cfl,h,
meqn=1, \
switch=1,\
GN=None,\
qinit=None, \
solver=None,
bc=None):
dx = (bx-ax)/mx
xe = linspace(ax,bx,mx+1) # Edge locations
xc = xe[:-1] + dx/2 # Cell-center locations
dt_est = ... |
def check_win(board, computer): # evaluation function
for x in range(Rows):
for y in range(Cols):
if board[x][y] == '*':
return 0
if computer:
return 1
else:
return -1
def print_matrix(matrix):
for row in matrix:
for elem in row:
... | This code implements a turn-based game where a human and computer player alternate placing markers on a grid. The human inputs moves, while the computer selects moves automatically. The game checks for win conditions after each move, displays the board, and allows replay. The board initializes with '*' symbols, placing... | def main():
global Rows
global Cols
valid_input = False
Rows = int(input("Enter number of rows : "))
Cols = int(input("Enter number of columns : "))
while not valid_input:
if Rows <= 0 or Cols <= 0:
print("!.....Bad input....!")
Rows = int(input("Enter number of ... |
def setGalaxyOne(self):
"""Set base seed for galaxy 1"""
self.seed.w0 = 0x5A4A
self.seed.w1 = 0x0248
self.seed.w2 = 0xB753
self.galaxy_number = 1
def nextgalaxy(self, make_planets=True):
"""Apply to galaxy1 seed once for galaxy 2, twice for galaxy 3 etc
Eighth ... | This function navigates to a specified galaxy (1-8), with Galaxy 9 wrapping to Galaxy 1. It initializes Galaxy 1, then advances through galaxies sequentially using a loop. The galaxy number is set via modulo 8 for wrap-around, and systems are generated for the target galaxy. | def goto_galaxy(self, galnum):
"""Goto galaxy X, where 1 <= X <= 8
Galaxy 9 == Galaxy 1"""
self.setGalaxyOne()
#Advance to further galaxies if need-be.
for _ in range(2, galnum + 1):
self.nextgalaxy()
self.galaxy_number = galnum % 8
self.makeSystems(... |
def archivo_to_df(nombre_archivo): # RETORNA EL DF DEl ARCHIVO RECIBIDO
df = pd.read_csv(nombre_archivo)
return df
def mostrar_tabla(self, transacciones_win, id_cuenta):
print("El id_cuenta es ", id_cuenta)
# SETEAMOS LA TABLA Y SUS PROPIEDADES
# GUI TABLA
# TODO: HACER ... | The code creates a GUI window to display and manage transaction history for a specific account. It loads account data, opens a new window with the account name, shows a transactions table, and includes buttons to add new transactions, refresh the table (with a TODO note), and return to the previous window. | def historial_transacciones(self, abrir_cuenta_win, id_cuenta):
# TODO: ABRIR EL CSV DE TRANSACCIONES Y GUARDARLO EN UN DF
print("RECIBI EL ID DE LA CUENTA", id_cuenta)
indice_cuenta = id_cuenta - 1 # COMO LA FUNCION RECIBE EL ID Y NO EL INDICE DEL DF DE LAS CUENTAS TENEMOS QUE RESTARLE 1
... |
def init_frame_mask(self):
"""
Load input video and mask
"""
self.image_all = []
self.mask_all = []
self.contour_all = []
cap_video = cv2.VideoCapture(self.cfg['video_path'])
cap_mask = cv2.VideoCapture(self.cfg['mask_path'])
for fid in range(self... | This code initializes a video processing class by validating input paths, extracting video metadata (frame count, resolution), applying resize settings, configuring frame parameters, and initializing components like perceptual loss networks, masks, and batch lists for subsequent processing tasks. | def __init__(self, cfg):
self.cfg = cfg
if not os.path.exists(self.cfg['video_path']):
raise Exception("Input video not found: {}".format(self.cfg['video_path']))
if not os.path.exists(self.cfg['mask_path']):
raise Exception("Input mask not found: {}".format(self.cfg['mas... |
def train_batch(self, pass_idx, batch_idx, batch_data):
"""
Train the given batch for `num_iter` iterations
"""
for loss_name in self.cfg['loss_weight']:
self.log['loss_' + loss_name + '_train'][pass_idx].append([])
best_loss_recon_image = 1e9
best_iter = 0
... | This function trains baseline models by iterating through multiple passes, processing batches of data, and calling training operations. It dynamically creates models and optimizers in 'DIP' mode, performs inference at specified intervals, and saves model checkpoints. The training logs progress and runtime, ensuring ite... | def train_baseline(self):
"""
Training procedure for all baselines
"""
for pass_idx in range(self.cfg['num_pass']):
while True:
# Get batch data
batch_data = self.data_loader.next_batch()
if batch_data is None:
... |
def analyze_section_header(binary, offset):
len_xml = uint_be(binary, offset, 4)
offset += 4
xml_b = part(binary, offset, len_xml)
# xml_s = xml_b.decode('utf-16le')
offset += len_xml
checksum = uint_le(binary, offset, 4)
assert zlib.adler32(xml_b) == checksum
offset += 4
retur... | The code reads a binary file ('coca.mdx'), parses its structure to locate the 'apple' keyword's record index, retrieves the corresponding data using parsing functions, and logs the result. The main task is to extract and display specific record information related to the keyword 'apple' from a structured binary file. | def main():
with open('./mdict/coca.mdx', 'rb') as file:
binary = file.read()
i = analyze_section_header(binary, 0)
mate_keyword, i = analyze_section_keyword(binary, i)
mate_record = analyze_section_record(binary, i, mate_keyword)
i = mate_keyword.keyword_index[b'apple']
... |
def determine_location(code):
location = None
if code.startswith('ma') or code == 'rc':
location = 'schwarzman'
elif code.startswith('sc'):
location = 'schomburg'
elif code.startswith('pa'):
location = 'lpa'
else:
logger.warning('Unsupported location provided: ' + cod... | The function retrieves and processes refinery location data based on input code and requested fields. It determines the location, checks cached/fetched data, and constructs a dictionary with 'location' or 'hours' details. For hours, it filters closure alerts, applies code-specific logic (e.g., 'rc' alerts), and builds ... | def get_refinery_data(code, fields):
data = {}
location = determine_location(code)
if location is None:
return None
logger.debug(f'Checking cache for {location}')
location_data = check_cache_and_or_fetch_data(location)\
.get('location_data')
if 'location' in fields:
data[... |
def remove_block(self, position, immediate=True):
del self.world[position]
self.sectors[self.scaler.sectorize(position)].remove(position)
if immediate:
if position in self.shown:
self.hide_block(position)
self.check_neighbors(position)
def exposed(self, po... | This function adds a block to the world at a specified position with a given texture. If a block already exists at that position, it is removed first. The block is then stored in the world dictionary, and its position is added to the appropriate sector list. If 'immediate' is True, the block is rendered if exposed and ... | def add_block(self, position, texture, immediate=True):
if position in self.world:
self.remove_block(position, immediate)
self.world[position] = texture
self.sectors.setdefault(self.scaler.sectorize(position), []).append(position)
if immediate:
if self.exposed(pos... |
def prepInput(toPrep):
for char in punctuation:
toPrep = toPrep.replace(char, '')
toPrep = toPrep.replace(char, '')
prepped = toPrep.replace("\n", '').replace(" ", '').upper()
return prepped
def toNumArray(string):
return np.asarray([assignNumeric(alpha) for alpha in string])
def getFit... | The main task of the code is to compute the fitness value of a numerical array derived from processed text data. It reads a text file, preprocesses its content, converts it into a numerical array, and evaluates its fitness using a fitness function, returning the result. | def testFitnessFunction():
testFile = open('plain-text.txt', 'r')
content = testFile.read()
content = prepInput(content)
numArray = toNumArray(content)
fitness = getFitness(numArray)
return fitness |
def find_fully_conserved_orientations(
orientations: np.ndarray,
pct_size_buffer: float = 0.85,
kmeans_ang_cutoff: float = 120,
kmeans_inertia_cutoff: float = 0.4,
angdiff_cutoff: float = 5,
angstd_cutoff: float = 17.0,
xi: float = 0.03,
njobs: int = 1,
verbose: int = 0,
debugH: ... | The function `hydrogen_orientation_analysis` classifies water clusters into types (FCW, HCW, WCW) based on hydrogen orientation patterns. It uses clustering (KMeans, OPTICS/HDBSCAN) with thresholds for angular deviation, standard deviation, and cluster size to determine if orientations align with fully, half, or weakly... | def hydrogen_orientation_analysis(
orientations: np.ndarray,
pct_size_buffer: float = 0.85,
kmeans_ang_cutoff: float = 120,
kmeans_inertia_cutoff: float = 0.4,
FCW_angdiff_cutoff: float = 5,
FCW_angstd_cutoff: float = 17,
min_samp_data_size_pct: float = 0.15,
nonFCW_angdiff_cutoff: float... |
def _check_and_setup_MSRC(self, lower_minsamp_pct, every_minsamp):
if lower_minsamp_pct > 1.0000001 or lower_minsamp_pct < 0:
raise Exception("lower_misamp_pct must be between 0 and 1")
if type(every_minsamp) is not int:
raise Exception("every_minsamp must be integer")
if... | The main task of the code is to iteratively identify and remove conserved water molecules from a dataset by clustering oxygen and hydrogen coordinates using OPTICS or HDBSCAN. It loops over varying clustering parameters (minsamp, xi), prioritizing oxygen clustering, and removes satisfactory clusters until no more valid... | def multi_stage_reclustering(
self,
Odata: np.ndarray,
H1: np.ndarray | None,
H2: np.ndarray | None,
clustering_algorithm: str = "OPTICS",
lower_minsamp_pct: float = 0.25,
every_minsamp: int = 1,
xis: list[float] = [
0.1,
0.05,
... |
def _check_and_setup_MSRC(self, lower_minsamp_pct, every_minsamp):
if lower_minsamp_pct > 1.0000001 or lower_minsamp_pct < 0:
raise Exception("lower_misamp_pct must be between 0 and 1")
if type(every_minsamp) is not int:
raise Exception("every_minsamp must be integer")
if... | The function performs multi-stage reclustering to identify conserved water molecules by iteratively clustering oxygen atoms (and optional hydrogen orientations) across varying parameters (minsamp, xi). It removes identified conserved waters from the dataset while continuing clustering without restarting, using OPTICS o... | def quick_multi_stage_reclustering(
self,
Odata: np.ndarray,
H1: np.ndarray | None,
H2: np.ndarray | None,
clustering_algorithm: str = "OPTICS",
lower_minsamp_pct: float = 0.25,
every_minsamp: int = 1,
xis: list[float] = [
0.1,
0.05... |
def _check_cls_alg_and_whichH(self):
if (
self.clustering_algorithm != "OPTICS"
and self.clustering_algorithm != "HDBSCAN"
):
raise Exception("clustering algorithm must be OPTICS or HDBSCAN")
for i in self.water_types_to_find:
if not (i in ["FCW", ... | This function performs a single clustering operation on oxygen atom coordinates (Odata) using a specified algorithm (OPTICS or HDBSCAN). It clusters oxygen atoms once, with optional hydrogen orientations (H1, H2) to identify water types (FCW, HCW, WCW). Parameters like minsamp and xi (for OPTICS) control clustering den... | def single_clustering(
self,
Odata: np.ndarray,
H1: np.ndarray | None,
H2: np.ndarray | None,
clustering_algorithm: str = "OPTICS",
minsamp: int | None = None,
xi: float | None = None,
whichH: list[str] = ["FCW", "HCW", "WCW"],
) -> None:
"""Si... |
def _get_options(args):
parser = argparse.ArgumentParser(
description="Generates Python data models from Kubernetes OpenAPI specs.",
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
)
parser.add_argument(
"--log-level",
"-l",
default="INFO",
choices=["... | The main task of the code is to generate models from specifications and clean up empty modules. It processes command-line arguments, configures logging, and executes two core functions: `_generate_models` to create models based on input specs, and `_cleanup_empty_modules` to remove unused modules. The output and specs ... | def run(args):
options = _get_options(args)
log_level = logging.getLevelName(options.log_level)
logging.basicConfig(level=log_level)
output_path = Path(options.output_path)
specs_path = Path(options.specs_path)
_generate_models(output_path, specs_path)
_cleanup_empty_modules(output_path) |
def _print(self, args):
if not args:
super().error(ErrorType.SYNTAX_ERROR,f"Invalid print call syntax", self.ip) #no
out = []
for arg in args:
val_type = self._get_value(arg)
out.append(str(val_type.value()))
super().output(''.join(out))
def _advance_to_next_statement(self):
# for ... | This function processes function calls by checking the provided arguments. If no arguments are present, it raises a syntax error. For built-in functions like PRINT, INPUT, or STRTOINT, it executes the corresponding method and advances the instruction pointer. For other functions, it pushes the current instruction point... | def _funccall(self, args):
if not args:
super().error(ErrorType.SYNTAX_ERROR,f"Missing function name to call", self.ip) #!
if args[0] == InterpreterBase.PRINT_DEF:
self._print(args[1:])
self._advance_to_next_statement()
elif args[0] == InterpreterBase.INPUT_DEF:
self._input(args[1:])... |
def _compute_indentation(self, program):
self.indents = [len(line) - len(line.lstrip(' ')) for line in program]
def _find_first_instruction(self, funcname, args = None):
func_info = self.func_manager.get_function_info(funcname)
if func_info == None:
super().error(ErrorType.NAME_ERROR,f"Unable to locat... | This code initializes an interpreter to execute a given program by tokenizing it, managing functions and environments, and processing each line in a loop until termination. It sets up the program structure, instruction pointer, and execution context, then iteratively processes instructions through the _process_line met... | def run(self, program):
self.program = program
self._compute_indentation(program) # determine indentation of every line
self.tokenized_program = Tokenizer.tokenize_program(program)
self.func_manager = FunctionManager(self.tokenized_program)
self.env_stack = []
self.result_stack = []
self.ip... |
def isLoggedIn(self, id):
if id in self.clients:
return self.clients[id]["loggedIn"]
return False
def isOnline(self, username):
for id in self.clients:
if self.isLoggedIn(id):
if username == self.getUsername(id):
return True
ret... | This code handles user login/registration by processing incoming commands. It checks if a client is logged in, assigns a username if new, verifies existing accounts, requests passwords for new accounts, and manages login conflicts. If already logged in, it returns False. | def onCommand(self, data):
id = data["id"]
command = data["command"]
if not self.isLoggedIn(id):
if not "username" in self.clients[id]:
username = command
self.clients[id]["username"] = username
if self.playersSystem.playerExists(userna... |
def _get_image(self, idx):
if self.in_memory and self.cache[idx] is not None:
return self.cache[idx]
if self.zip == None:
self.open_zip()
filename = self.imgs[idx]
try:
image = np.load(self.zip.open(filename))
except Exception as e:
... | The code normalizes a raw image by dividing by 10,000 for manageable statistics, applies optional transformations (scaling, randomization) if enabled, converts labels to tensors, and returns the processed image, transformed label, original image, and raw label as a tuple. It handles data preprocessing, augmentation, an... | def __getitem__(self, idx):
raw_image, raw_label = self._get_image(idx)
# We divide to make the numbers manageable for calculating mean and std and thus normalizing
# 10,000 is the accepted number to get a brightness level
image = raw_image.astype(np.float32) / 10000
# augmentat... |
def visualize_full_image_no_patch(
model,
dataset,
class_designation,
image_save_folder,
image_name,
):
input_path = f"{FULL_IMAGE_BASE_FOLDER}/{image_name}/sen2.npy"
label_path = f"{FULL_IMAGE_BASE_FOLDER}/{image_name}/cyan.npy"
sen2_np = np.load(input_path).astype(np.float32)
cyan_... | The code visualizes a model's performance on image datasets by generating full-image predictions, loss plots, confusion matrices, and classification histograms. It loads a trained model, processes test/train data, and saves visualizations (e.g., predicted vs actual labels) for specific classes. Metrics like accuracy an... | def visualize(
experiment_name,
class_designation,
model_architecture,
model_file,
dataset_type="test",
):
# Set the config to print to stdout
set_config("test")
model_save_folder = f"{MODEL_SAVE_BASE_FOLDER}/{experiment_name}"
image_save_folder = f"{model_save_folder}/visualize/{da... |
def __generate_starting_population(self):
population = []
for i in range(self._population_size):
new_tree = generate_random_tree(self._starting_population_min_depth, self._starting_population_max_depth,
self._classes_count, self._record_data_count, self._X_mi... | The code trains an evolutionary algorithm to optimize decision trees by iteratively generating populations, evaluating their performance, and refining them over epochs. It tracks the best-performing tree in each iteration, halting early if progress stagnates. The goal is to find the optimal decision tree model using po... | def fit(self, X_train, Y_train, log_info=True, stop_after_no_progress=100):
self._X_train = X_train
self._Y_train = Y_train
X_min = X_train.min(axis=0)
X_min = X_min.reshape(len(X_min), 1)
X_max = X_train.max(axis=0)
X_max = X_max.reshape(len(X_max), 1)
self._X_mi... |
def is_solved(self) -> bool:
return all(
self.sudoku_board[i, j]
for i in range(self.sudoku_board.size ** 2) for j in range(self.sudoku_board.size ** 2)
)
def fill_solved_options(self):
self._fill_only_option()
self._fill_block_options()
self._fill_row_opt... | This code attempts to solve a Sudoku puzzle by iteratively filling in solvable cells, marking invalid options, and checking for progress. If no progress is made or no options remain, it returns False or raises an exception. It returns True if the Sudoku is successfully solved. | def try_solve(self) -> bool:
current_table = [*self.sudoku_board]
current_options = self.sudoku_board.options_table
while not self.is_solved():
self.fill_solved_options()
self.mark_bad_options()
temp_table = [*self.sudoku_board]
temp_options = self... |
def _get_soup(self, endpoint: str) -> BeautifulSoup:
"""Get the soup for an endpoint"""
response = self._make_request("GET", endpoint)
return BeautifulSoup(response.text, "html.parser")
def _soup_next_page_link(self, soup: BeautifulSoup) -> Optional[str]:
"""Get the next page from a soup... | The function retrieves a user's ratings for a specified entity type by checking if the entity is supported, constructing a URL endpoint, fetching web content, parsing ratings, and handling pagination to collect all ratings across multiple pages. | def get_ratings(
self,
user_name: str,
mb_type: str,
):
"""
Get ratings of a user for a type of entity
"""
if mb_type not in RATING_SUPPORTED_ENTITIES:
raise UnsupportedEntityError(mb_type, RATING_SUPPORTED_ENTITIES)
endpoint = WebEndpoint... |
def vol_get_uuid_list(hostname,user,password,request_filter={}):
# Get volume uuid
rest_cmd = "/api/storage/volumes"
jData = rest_api_get(hostname,user,password,rest_cmd,request_filter)
vol_uuid_list = {}
message_error =""
print_deb("REST Number of properties: [{0}]".format(len(jData)))
d... | The code retrieves volume information from a system using provided credentials and filters, prints detailed parameters (name, UUID, SVM, size, space usage) for each volume, and handles errors by displaying relevant messages if no volumes are found or exceptions occur. | def vol_print_parameters(hostname,user,password,request_filter={}):
try:
vol_uuid_list = vol_get_uuid_list(hostname,user,password,request_filter)
print_deb(vol_uuid_list)
if (len(vol_uuid_list)==0):
print ("ERROR: No volume found")
for vol_name in vol_uuid_list:
... |
def vol_get_uuid_list(hostname,user,password,request_filter={}):
# Get volume uuid
rest_cmd = "/api/storage/volumes"
jData = rest_api_get(hostname,user,password,rest_cmd,request_filter)
vol_uuid_list = {}
message_error =""
print_deb("REST Number of properties: [{0}]".format(len(jData)))
d... | The main task of the code is to retrieve and print volume-snapshot relationships from a storage system based on filtered criteria. It constructs volume filters, fetches matching volumes, then retrieves their snapshots, and prints each volume-snapshot pair. Error handling is included for empty results or exceptions, wit... | def snap_print_list(hostname,user,password,request_filter={}):
try:
# Create the json request for get volume request
vol_request_filter={}
if ('volume.name') in request_filter :
vol_request_filter["name"]=request_filter.get('volume.name')
if ('svm.name') in request_filt... |
def vol_get_uuid_list(hostname,user,password,request_filter={}):
# Get volume uuid
rest_cmd = "/api/storage/volumes"
jData = rest_api_get(hostname,user,password,rest_cmd,request_filter)
vol_uuid_list = {}
message_error =""
print_deb("REST Number of properties: [{0}]".format(len(jData)))
d... | The function `snap_create_on_multiple_vol` creates a snapshot named `snapname` across multiple volumes on a specified host. It uses `volume_filter` to identify target volumes, retrieves their UUIDs, and applies the snapshot to each. The task involves iterating over volume UUIDs and invoking `snap_create_new` for each, ... | def snap_create_on_multiple_vol(hostname,user,password,snapname,volume_filter={}):
try:
confirm='n'
snapshot_parameters={}
snapshot_parameters["name"]=snapname
vol_uuid_list = vol_get_uuid_list(hostname,user,password,volume_filter)
print_deb(vol_uuid_list)
for vol_nam... |
def vserver_get_uuid_list(hostname,user,password,request_filter={}):
svm_uuid_list = {}
message_error =""
rest_cmd = "/api/svm/svms"
jData = rest_api_get(hostname,user,password,rest_cmd,request_filter)
dump = json.dumps(jData)
print_deb(dump)
for jkey in jData:
print_deb (jkey)
... | The main task of the code is to delete multiple virtual servers (vServers) by first retrieving their UUIDs using a filter, prompting the user for confirmation for each vServer, and then deleting the confirmed vServers using their UUIDs. The function handles errors and ensures user confirmation before performing deletio... | def vserver_delete_list(hostname,user,password,request_filter={}):
try:
confirm='n'
svm_uuid_list = vserver_get_uuid_list(hostname,user,password,request_filter)
print_deb(svm_uuid_list)
for svm_name in svm_uuid_list:
confirm=input('delete vserver [{0}] [y/n]? '.format(svm... |
def vol_get_uuid_list(hostname,user,password,request_filter={}):
# Get volume uuid
rest_cmd = "/api/storage/volumes"
jData = rest_api_get(hostname,user,password,rest_cmd,request_filter)
vol_uuid_list = {}
message_error =""
print_deb("REST Number of properties: [{0}]".format(len(jData)))
d... | The function deletes specified volumes by prompting the user for confirmation. It retrieves a list of volume UUIDs, asks the user to confirm deletion for each, and executes deletion if confirmed. Error handling catches exceptions and displays error messages. | def vol_delete_list(hostname,user,password,request_filter={}):
try:
confirm='n'
vol_uuid_list = vol_get_uuid_list(hostname,user,password,request_filter)
print_deb(vol_uuid_list)
for vol_name in vol_uuid_list:
confirm=input('delete volume [{0}] [y/n]? '.format(vol_name))
... |
def vol_get_uuid_list(hostname,user,password,request_filter={}):
# Get volume uuid
rest_cmd = "/api/storage/volumes"
jData = rest_api_get(hostname,user,password,rest_cmd,request_filter)
vol_uuid_list = {}
message_error =""
print_deb("REST Number of properties: [{0}]".format(len(jData)))
d... | This function deletes snapshots from multiple volumes on a NetApp system. It uses filters to identify target volumes, retrieves their UUIDs, lists associated snapshots, and prompts the user to confirm each deletion. If confirmed, it deletes the snapshot using its UUID. The process handles errors and ensures targeted sn... | def snap_delete_on_multiple_vol(hostname,user,password,request_filter={}):
try:
confirm='n'
# Create the json request for get volume request
vol_request_filter={}
if ('volume.name') in request_filter :
vol_request_filter["name"]=request_filter.get('volume.name')
... |
def network_ip_interface_get_uuid_list(hostname,user,password,request_filter={}):
netipif_uuid_list = {}
message_error =""
rest_cmd = "/api/network/ip/interfaces"
jData = rest_api_get(hostname,user,password,rest_cmd,request_filter)
dump = json.dumps(jData)
print_deb(dump)
for jkey in jData:
... | The function deletes network IP interfaces by retrieving their UUIDs, prompting user confirmation for each, and executing deletion if confirmed. It handles exceptions and prints errors. | def network_ip_interface_delete_list(hostname,user,password,request_filter={}):
try:
confirm='n'
netipif_uuid_list = network_ip_interface_get_uuid_list(hostname,user,password,request_filter)
print_deb(netipif_uuid_list)
for netipif_name in netipif_uuid_list:
confirm=input... |
def create_video_node(self, video_data):
# We are storing each important information in video node so that accessing the relevant information is faster
video_id = video_data["videoId"]
likes = video_data["likeCount"]
dislikes = video_data["dislikeCount"]
views = video_data["viewC... | The main task of the code is to construct an initial graph by creating video nodes from input data and establishing relationships between all pairs of videos. It generates nodes for each video, then creates relationships such as "same channel," "similar tags," "similar descriptions," and "similar titles" between every ... | def create_initial_graph(self):
for video_data in videos_data:
self.create_video_node(video_data)
video_id_list = [video_data["videoId"] for video_data in videos_data]
num_videos = len(video_id_list)
for i in range(num_videos):
for j in range(num_videos):
... |
def scalarModSpecificConv(inpt, modality, first=True, useType="test", varName="PKNut", resuse_batch_norm=False, fs=5, reguralizationMode=cc.misc.default_regularization_mode, lr=1):
#conv1
with tf.variable_scope(varName+"Conv1", reuse=(not first)) as scope:
k_h = fs; k_w = fs; c_o = 6; c_i = 1; s_h = 1; s_w = 1
co... | This code defines a neural network inference function that processes input examples through scalar and velocity-specific convolutional layers, fuses features, applies multiple convolutional and pooling operations, and returns the final output tensor conv9 for tasks like fluid dynamics modeling or similar applications. | def inference(examples, first, useType="test", modelType="vc", fs=3, reguralizationMode=cc.misc.default_regularization_mode, lr=1):
with tf.variable_scope("Encoder") as scope:
with tf.variable_scope("ScalarConvolutions") as scope:
#P specific layers
convP = scalarModSpecificConv(examples[1], "p", first, useTyp... |
def get_formatted_path(self, path:str) -> str:
formated_path = path
if formated_path.startswith(self._root.name):
formated_path.replace(self._root.name, "")
if not formated_path.startswith(PATH_SEPARATOR):
formated_path = PATH_SEPARATOR + formated_path
return form... | This function inserts a node into a tree structure at a specified path, creating missing parent nodes if allowed. It checks for cycles and handles insertion modes (child, parent, replace). If the target node doesn't exist, it constructs the path recursively. Caching is optionally applied, and the inserted node is retur... | def insert(self, path:str, node:Node, create_missing_nodes=False, cache_node=False, insert_mode=InsertMode.MAKE_CHILD) -> Node:
formated_path = self.get_formatted_path(path)
# so here target is the parent node in which our node will be inserted
target = self.get_node(formated_path, unknown_raise... |
def listofcoursenames():
namelist = []
for course in ClassCode.objects.all():
namelist.append(course.name)
return namelist
def schedulelistmaker(st, et):
classesbycourse = []
finallist = []
allclasses = ClassModel.objects.all()
courselist = ClassCode.objects.all()
lockedlist = lo... | This view handles POST requests for managing class schedules, including deleting tabs, filtering classes by time, generating schedules, and processing form submissions for adding classes, copying/pasting data, and locking/unlocking classes. It updates the database, manages global state variables, and renders the index ... | def enlistmentbuddy_view(request):
global num
global copypaste
global currentlock
global schedulelist
global st
global et
if request.method == 'POST':
deletedtabs = request.POST.get('returndeltab')
print("HERE")
print(deletedtabs)
print("HERE")
if (d... |
def init_params(self):
centers = torch.randn(self.K, self.D, dtype=self.dtype, device=self.device) * 0.1
time_means = torch.zeros(self.K, dtype=self.dtype, device=self.device)
time_vars = torch.zeros(self.K, dtype=self.dtype, device=self.device)
self.register_buffer('centers_', centers)
... | The code performs iterative soft clustering with time-aware distance computation. It initializes cluster centers, computes distances incorporating time priors, updates centers using weighted data points, and iteratively refines clusters. The process returns optimized cluster centers or includes distance metrics if spec... | def forward(self, x_list, sort_centers=True, return_dist=False, init=True):
T_list = [x.shape[0] for x in x_list]
t_range_list = [((np.arange(T) + 0.5) / T).astype(np.float32) for T in T_list]
x = torch.cat(x_list, 0)
#concat_t = np.concatenate(t_list)
#concat_t = torch.tensor(np... |
def _add_init(self) -> None:
# default constructor
self._add_function(f"{self._name}()", indent=1)
statement = join(
f"{self._name}(",
", ".join(member.get_init() for member in self._members),
") : ",
", ".join(f"{member.name}(_{member.name})" for... | This code initializes a class generator that dynamically constructs C++ class definitions based on specified flags (e.g., constructors, equality, getters/setters) and member variables. It builds a textual representation of the class, conditionally adding features like initialization, string conversion, and ordering met... | def __init__(
self,
name: str,
spaces: int,
init: bool,
to_string: bool,
printable: bool,
eq: bool,
order: bool,
getter_and_setter: bool,
*members: Member
) -> None:
self._name = name
... |
def get_route_configs(routes: List[str]) -> dict:
route_configs = []
for route in routes:
with open(os.path.join(route["path"], "route_config.yml")) as f:
route_functions = yaml.safe_load(f.read())
for function_name, function_desc in route_functions.items():
funct... | The code generates an OpenAPI 3.0.2 schema by scanning route directories, parsing configurations, and constructing paths/components. It includes authentication security schemes with JWT bearer format, aggregating route data into a structured API definition for documentation or API tooling. | def get_openapi_schema():
routes = [
dict(path=route.path, name=route.name)
for route in os.scandir(os.path.join(config.ROOT_DIR, "routes"))
if route.is_dir() and "pycache" not in route.name
]
route_configs = get_route_configs(routes)
parsed_route_configs = parse_route_configs(r... |
def load_files(self):
self.file_list = glob.glob(os.path.join(os.getcwd(), self.folder_name, "*.*"))
self.num_images = len(self.file_list)
def load_model(self):
self.model = hb.load(self.model_type, self.base_network, pretrained=True)
self.model.eval()
def configure_transform(self):
... | The main task of the code is to process image files by loading them, configuring a model and transformation pipeline, segmenting each image in the file list using the model, and finally writing the processed file list. The method orchestrates image segmentation tasks through a sequence of initialization, transformation... | def run(self):
self.load_files()
self.load_model()
self.configure_transform()
for file_path in self.file_list:
self.segment_image(file_path)
self.write_file_list() |
def load_data(args):
print(args.data_dir)
X_train_val = np.load(os.path.join(args.data_dir, 'X_train.npy'))
X_test = np.load(os.path.join(args.data_dir, 'X_test.npy'))
y_train_val = np.load(os.path.join(args.data_dir, 'y_train.npy'))
y_test = np.load(os.path.join(args.data_dir, 'y_test.npy'), al... | The main task is to train and evaluate a neural network model (Keras/QKeras) on given data, save the trained model and training history, analyze weight distributions, calculate test accuracy, and visualize pruning effects. It includes data loading, model selection, training, pruning, evaluation, and post-training analy... | def main(args):
start_time = datetime.now()
X_train, X_test, y_train, y_test = load_data(args)
model = get_qkeras_model(args) if args.quantize else get_keras_model()
history = train(model, X_train, y_train, args)
if args.prune:
model = strip_pruning(model)
model.save(create_filename(ar... |
def _get_best_feature(self, idx, feature_ids):
# get information gains of all features
best_split_vals, best_IGs, best_equal_idx, best_n_equal_idx = map(
list,
zip(
*[self._info_gain(idx, feature_id) for feature_id in feature_ids],
),
)
... | This function recursively constructs a decision tree node by splitting data based on features. It handles terminal nodes (when all labels are the same or splitting conditions fail) and internal nodes (with entropy, split values, and children). It eliminates features if all values in a child node are identical, ensuring... | def _fit_rec(self, idx, feature_ids, node):
if not node:
node = Node()
node.height = 1
node.n_samples = idx.size
# terminating cases
# 1) all labels left are the same
if np.unique(self.y[idx]).size == 1:
node.type = "terminal"
node... |
def compMove():
disable_board(True)
if not checkForWin():
bestScore = -800
bestMove = 0
for key in board.keys():
if (board[key] == ' '):
board[key] = bot
score = minimax(board, 0, False)
board[key] = ' '
if (scor... | The main task of the code is to run a Tic-Tac-Toe game with a GUI, where the player and computer take turns making moves on a 3x3 board. The function initializes the game board, handles player input via GUI events, checks for win/draw conditions, and executes the computer's move logic. It maintains game state, ensures ... | def run_game():
global BOARD_W
start=False
BOARD_W = GUI.init_game_board()
global board
board = {1: ' ', 2: ' ', 3: ' ',
4: ' ', 5: ' ', 6: ' ',
7: ' ', 8: ' ', 9: ' '}
if firstComputerMove:
start=True
while True:
if start:... |
def from_dungeon_level(table):
#returns a value that depends on level. the table specifies what value occurs after each level, default is 0.
for (value, level) in reversed(table):
if dungeon_level >= level:
return value
return 0
def is_blocked(x, y):
# first, test map tile
if map[x][y].blocked:
... | The code places monsters and items in a given room, adjusting their types and probabilities based on the dungeon level. It generates random numbers of monsters (Alien Weakling/Invader) and items (potions, weapons, armor) with level-dependent stats, placing them on unblocked tiles. Global stats like defense, power, and ... | def place_objects(room):
global stat_defense, stat_power
global stat_lifesteal, stat_hp
stat_defense, stat_power = 0, 0
stat_lifesteal, stat_hp = 0, 0
# max number of monsters per room
max_monsters = from_dungeon_level([[2, 1], [4, 4], [6, 6]])
# chance of each monster type
monster_chances = {}
m... |
def create_room(room):
global map
# go through the tiles in the rectangle and make them passable
for x in range(room.x1 + 1, room.x2):
for y in range(room.y1 + 1, room.y2):
map[x][y].blocked = False
map[x][y].block_sight = False
def place_objects(room):
global stat_defense, stat_power
global s... | The code generates a dungeon map with randomly placed rooms, corridors, and objects. It creates a grid of blocked tiles, generates non-overlapping rooms, places the player, items, and monsters, and connects rooms with tunnels. For every 5th level, it creates a boss room with a special item and a boss monster, while oth... | def make_map():
global map, objects
global stairs
objects = [player]
# fill map with 'blocked' tiles
map = [[ Tile(True)
for y in range(MAP_HEIGHT) ]
for x in range(MAP_WIDTH) ]
if (dungeon_level)%5 != 0:
rooms = []
num_rooms = 0
for r in range(MAX_ROOMS + 5 * dungeon_level):
... |
def message(new_msg, color = libtcod.white):
new_msg_lines = textwrap.wrap(new_msg, MSG_WIDTH)
for line in new_msg_lines:
if len(game_msgs) == MSG_HEIGHT:
del game_msgs[0]
game_msgs.append( (line, color) )
def make_map():
global map, objects
global stairs
objects = [player]
# fill map wi... | The main task of the code is to transition the player to the next dungeon level by resting, healing the player, incrementing the dungeon level, generating a new map, and reinitializing the field of view for the updated level. | def next_level():
global dungeon_level
message('You take a moment to rest and recover your strength.', libtcod.light_violet)
player.fighter.heal(player.fighter.max_hp/2)
message('After a moment of peace, you venture further into the mine..', libtcod.light_violet)
dungeon_level += 1
make_map()
init... |
def make_map():
global map, objects
global stairs
objects = [player]
# fill map with 'blocked' tiles
map = [[ Tile(True)
for y in range(MAP_HEIGHT) ]
for x in range(MAP_WIDTH) ]
if (dungeon_level)%5 != 0:
rooms = []
num_rooms = 0
for r in range(MAX_ROOMS + 5 * dungeon_level):
... | The code initializes a new game by setting up the player character with attributes like health and combat stats, defining the game state, inventory, and map, then generating the game environment and displaying a welcome message to start the gameplay. | def new_game():
global player, inventory, game_msgs, game_state, dungeon_level
fighter_component = Fighter(hp = 100, defense = 2, power = 5, xp = 0, death_function = player_death)
player = Object(0, 0, 'O', 'player', libtcod.Color(0, 0, 0), blocks=True, fighter = fighter_component)
player.level = 1
dungeon... |
def player_move_or_attack(dx, dy):
global fov_recompute
global game_state
global stairs
# Coord player is moving to/attacking
x = player.x + dx
y = player.y + dy
# Try to find an attackable target there
target = None
for object in objects:
if object.x == x and object.y == y:
if object.ai i... | This function handles keyboard inputs in a roguelike game, processing movement, attacks, inventory actions, and UI interactions. It toggles fullscreen, exits on ESC, moves the player with arrow keys, uses space for ranged attacks (if equipped), and processes keys like 'v' (stairs), 'g' (pickup), 'i' (use), 'd' (drop), ... | def handle_keys():
global fov_recompute, equipped_list
global key
global stairs
key = libtcod.console_check_for_keypress()
if key.vk == libtcod.KEY_ENTER and key.lalt:
libtcod.console_set_fullscreen(not libtcod.console_is_fullscreen())
elif key.vk == libtcod.KEY_ESCAPE:
return 'exit' # exit game... |
def get_full_book(self,full_book_market_dict,market):
#pprint.pprint(full_book_market_dict)
book = full_book_market_dict[market].copy()
#pprint.pprint(book)
if book is None:
return None,None,None,None
bid_price = book['bid_price']
bid_qty = book['bid_qty']
... | The main task of the code is to execute trades based on market data for BTC/USDT, ETH/USDT, and ETH/BTC pairs. It retrieves bid/ask prices and quantities, updates market and full-book data, places limit orders, and tracks cash changes to enable arbitrage or profit opportunities through cross-market trading strategies. | def make_trade(self):
#Make a trade if possible
start_cash = self.cash_tracker
try:
btc_usdt_bid_price = float(self.market_dict[self.market1]['bid_price'])
btc_usdt_ask_price = float(self.market_dict[self.market1]['ask_price'])
btc_usdt_bid_qty = float(self.... |
def build_grid_square(self, initial_state):
''' This produces either a random square lattice'''
if initial_state == 'hot':
system = np.random.choice([-1,1], size = self.dim*self.dim)
elif initial_state == 'cold':
system = np.ones(self.dim*self.dim)
x... | This code initializes a lattice model for physical simulations, setting parameters like temperature, interactions (J), external field (H), and grid type (square, line, etc.). It constructs the grid structure based on the specified type and initializes lists to track energy, magnetization, and other properties during si... | def __init__(self, temperature, pbcs = True ,intr='nn', grid_type='square' ,initial_state='hot', dim = 100, J=[1], H=0, a=2):
self.grid_type = grid_type
self.dim = dim
self.pbcs = pbcs
self.T = temperature
self.J = J
self.H = H
self.a = a
self.intr = intr
... |
def square_energy(self, N, M):
''' Calculates energy of spin interaction at site [N, M]'''
a = 0
if self.intr == 'nn':
if self.grid_type == 'square' or self.grid_type == 'triangle' or self.grid_type == 'hexagon':
a = -2*self.J[0]*self.system_array[N,M]*(np.su... | This code performs a single Monte Carlo update on a spin system, calculating energy changes (deltaE) for each spin site based on the grid type (line, square, triangle, hexagon). It updates the system's energy and flips spins according to the Metropolis algorithm, appending magnetization, energy, and squared magnetizati... | def single_update(self, T):
newE = self.current_energy
if self.grid_type == 'line':
for i in range(self.dim):
deltaE = -self.J[0]*self.square_energy(i,0)
if deltaE <= 0:
newE += deltaE
self.system_array... |
def maintain(self):
"""
Ensures the number of available units on the field does not exceed the number of the same unit in the pool.
Check if capture goal is completed
"""
for i in self.field.copy():
if self.field.count(i) > self.pool.count(i):
... | The code simulates a time-bound process where an agent performs actions like refreshing, capturing resources, or advancing time steps based on conditions involving EMP, field states, and priority/rarity checks. It iterates until the specified duration (`self.days`) is reached, then finalizes by reporting results to the... | def runSim(self):# -> tuple:
"""
Run the simulation for the specified time length.
Series of conditional statements the actions that are to be taken.
Exit the simulation once the timespan has passed and report information to parent SKK object.
"""
while self.t <= self.day... |
def find_best_snake(self):
"""
Find the best snake with the greatest fitness value
return that snake
"""
# Get list of snakes id, sorted by fitness
sorted_snakes_by_fitness = self.__get_sorted_fitness_array()
if self.debug:
with open("./temp/{}.txt".f... | The main task of the code is to evolve a population of snakes by selecting the best-performing individuals, generating a new population through specified evolution methods (selection or best snake), tracking the global best snake, incrementing the generation, and resetting population state for the next iteration. It al... | def evolve(self, evolve_by=Evolution.SELECTION):
"""
Taking the current population, we will create a new one taking all of the
data that we learnt from this population.
This method resets the current population
"""
# Find the best snake
self.best_snake = self.fin... |
def build_and_mine_block(self) -> LocalBlockOperation:
# Extract transactions
with self.lock_mining:
transactions = [self.build_coinbase_transaction()]
valid_txs, tx_to_remove, deltas = self.build_valid_transactions_for_block()
transactions.extend(valid_txs)
... | This method initiates block mining by building and committing a new block to the blockchain. It updates sequence numbers, applies transaction changes to the chainstate, removes processed transactions from the mempool, and broadcasts the mined block to all connected peers. The function includes safety checks to avoid du... | def start_to_create_block(self):
self._log("info", "Start mining")
try:
last_seq_num = self.current_seq_num
operation = self.build_and_mine_block()
# TODO: remove this sh** (is ugly but works for now)
if last_seq_num != self.current_seq_num:
... |
def get_arg(key, default=None):
# type: (str, Any) -> Any
"""Get the argument value or default"""
if default is None:
default = ""
return plugin.args.get(key, [default])[0]
def add_menu_item(method, label, **kwargs):
# type: (callable, Union[str, int], Any) -> None
"""wrapper for xbmcplu... | This function handles search operations in a plugin, including processing user queries, managing saved searches (add/delete), displaying search results, and updating the plugin's directory. It retrieves parameters like query, category, and total results, fetches HTML content, parses search results, and sets the plugin ... | def search():
# type: () -> Optional[bool]
"""Search the archive"""
query = get_arg("q")
category = get_arg("category", ku.localize(32007)) # Search
total = get_arg("total")
# Remove saved search item
if bool(get_arg("delete", False)):
pas.searches.remove(query)
xbmc.execute... |
def r_star(self, red, zeta):
c_200c = self.nu_to_c200c(red, zeta)
r200 = self.r_delta(red)
return r200 / c_200c
def nu_to_c200c(self, red, zeta):
nu = self.nu_delta(red, zeta)
diff = np.abs(nu - 1)
ind_M_star = np.where(diff == min(diff))[0][0]
M_star = self.mh[in... | This function computes the Fourier transform of an NFW (Navarro-Frenk-White) density profile in cosmology, returning the transformed field 'unfw'. It calculates parameters like halo radius (rs), concentration (c), and amplitude (a), then evaluates integrals involving sine and cosine functions of scaled wavevectors (mu)... | def nfwfourier_u(self, red, zeta):
k = self.k_array
rs = self.r_star(red, zeta)
c = self.nu_to_c200c(red, zeta)
a = self.ampl_nfw(c)
mu = np.outer(rs, k)
Si1, Ci1 = self.sine_cosine_int(mu + mu * c[:, np.newaxis])
Si2, Ci2 = self.sine_cosine_int(mu)
unfw =... |
def mass_to_radius(self):
rho_mean = self.mean_density()
r3 = 3 * self.mh / (4 * np.pi * rho_mean)
return r3 ** (1.0 / 3.0)
def fsigma(self, rad, red, zeta):
z = red
dhalo = self.delta_h / cosmo.Om(z)
lgdelta = np.log10(dhalo)
A_0 = self.coefficient(dhalo)[0]
... | This function calculates the differential number density of dark matter halos (dn/dm) by combining the mass-to-radius conversion, a sigma function (fsigma), mean density, and the absolute value of the logarithmic derivative of the mass function (dlns_dlnm), normalized by the square of the halo mass scale parameter (mh²... | def dn_dm(self, red, zeta):
rad = self.mass_to_radius()
return self.fsigma(rad, red, zeta) * self.mean_density() * np.abs(self.dlns_dlnm(rad, red, zeta)) / self.mh**2 |
def get_image_description(exifdata):
description = ""
# iterating over all EXIF data fields
for tag_id in exifdata:
# get the tag name, instead of human unreadable tag id
tag = TAGS.get(tag_id, tag_id)
data = exifdata.get(tag_id)
# decode bytes
if isinstance(data, byt... | The function processes timestamp images to extract and validate sign data from videos. It checks image metadata, sorts timestamps, uses multiprocessing to extract video clips, logs errors for invalid signs, and records files with insufficient sign data. | def process_file(args, pool, pbar, filename, results, signs, recording_count):
pbar.set_description("Processing Timestamps File: %s" % filename)
# results = []
# signs = set()
# recording_count = 0
if filename.endswith("-timestamps.jpg"):
image = Image.open(os.path.join(args.backup_dir, fil... |
def basemethod():
print("Setting the database........")
Establish_connection_to_creat_db_testDataHandOff()
def creat_table_perfDataTableLatestAddtlDebug():
con = Establish_connection_B()
cursor = con.cursor()
query = '''
CREATE TABLE IF NOT EXISTS perfDataTableLatestAddtlDebug (
TestID T... | The main task of the code is to initialize a database by creating multiple tables for storing performance data, debug logs, JMX links, and RunIDs from tools like BlazeMeter and Stomerunner. It orchestrates table creation for structured data management in performance testing or monitoring systems. | def SetupDataBase():
basemethod()
creat_table_perfDataTableLatestAddtlDebug()
creat_table_perfDataTableLatestMatchingRows()
creat_table_perfDataTableLatestLoadRunnerDebug()
creat_table_perfDataTableLatestLoadRunnerDebugMatchingRows()
creat_tables_for_jmx_link_blazemeter()
creat_tabels_to_sto... |
def basemethod():
print("Setting the database........")
Establish_connection_to_creat_db_testDataHandOff()
def creat_table_perfDataTableLatestAddtlDebug():
con = Establish_connection_B()
cursor = con.cursor()
query = '''
CREATE TABLE IF NOT EXISTS perfDataTableLatestAddtlDebug (
TestID T... | The main task of the code is to initialize database tables for Blazemeter performance testing by calling multiple table-creation functions. It sets up structures to store performance data, matching rows, JMX links, and RunIDs, enabling data collection, analysis, and tracking during testing processes. | def setupblazemetertables():
basemethod()
creat_table_perfDataTableLatestAddtlDebug()
creat_table_perfDataTableLatestMatchingRows()
creat_tables_for_jmx_link_blazemeter()
creat_tabels_to_store_RunIDs_blazemeter() |
def basemethod():
print("Setting the database........")
Establish_connection_to_creat_db_testDataHandOff()
def creat_table_perfDataTableLatestLoadRunnerDebug():
con = Establish_connection_B()
cursor = con.cursor()
query = '''
CREATE TABLE IF NOT EXISTS perfDataTableLatestLoadRunnerDebug (
... | The function `setupstomerunnertables()` initializes database structures by calling multiple methods: it executes a base method, creates tables for LoadRunner debug performance data, generates a table for matching rows, and sets up storage for StomRunner Run IDs. The primary task is to configure database tables for perf... | def setupstomerunnertables():
basemethod()
creat_table_perfDataTableLatestLoadRunnerDebug()
creat_table_perfDataTableLatestLoadRunnerDebugMatchingRows()
creat_tabels_to_store_RunIDs_stomerunner() |
def add_snake_to_board(self, growing=False):
"""This function adds all of the snakes coordinate to the board"""
for coordinate in self.prev_snake.get_coordinates():
x = coordinate[0]
y = coordinate[1]
# if coordinate within snake boundaries
if (len(self.bo... | This function validates a snake's new position after a move by checking if it stays within the board boundaries, avoids self-collision (unless growing), avoids explosions, and handles apple consumption. It returns True if valid, False otherwise, updating game state accordingly. | def check_updated_snake(self):
"""This function checks that new snake following this turn's move
is within board, didn't hit himself/bomb and if it ate an apple
Returns True if ok, False otherwise"""
# calculate x and y of new head
head_x = self.snake.get_coordinates()[0][0]
... |
def erase_explosion(self):
""" erases places where explosion appeared in the last turn """
for coord in self.explosion_coordinates:
x, y = coord
self.board[x][y] = None
self.explosion_coordinates = []
def add_bomb_to_board(self):
"""
adds bomb to board at ... | This function updates the game board by moving the snake, handling bomb explosions, checking collisions with apples/explosions, and managing growth. It returns True if the move is valid, False if the snake hits a border/explosion or invalid state. | def update_board(self, key_clicked=None):
"""This function updates the board with new objects.
:return True if succeeded and False otherwise."""
# on first use, add snake to board
# check if snake should grow from eating apples recently
growing = self.growing_turns_left > 0
... |
def get_clear_tensor(self):
return np.zeros(self.number_of_parameters)
def policy(self, s):
r = random.random()
if r <= self.get_e(s):
action = self.choose_random_action()
else:
action = self.choose_best_action(s)
return action
def phi(self, s, a):
... | The code trains a reinforcement learning agent using eligibility traces and temporal difference learning. It iterates through episodes, interacts with the environment, updates Q-values via reward and next-state Q-values, adjusts parameters (theta) with delta and eligibility traces (E), and returns the learned value fun... | def train(self, steps):
for e in range(steps):
self.E = self.get_clear_tensor()
s = self.env.initial_state()
a = self.policy(s)
next_a = a
while not s.is_terminal:
next_s, r = self.env.step(copy.copy(s), a)
phi = self.ph... |
def set_hand_array(self,image):
with self.mp_hands.Hands(model_complexity=0,min_detection_confidence=0.5,min_tracking_confidence=0.5) as hands:
# To improve performance, optionally mark the image as not writeable to
# pass by reference.
image.flags.writeable = False
... | This code processes a camera feed to detect hand gestures, converting the image to an OpenCV format, analyzing hand positions, determining gesture modes/commands, and updating the system's pose and operational mode accordingly. | def camera_callback(self,camera):
self.feed = self.bridge.imgmsg_to_cv2(camera, desired_encoding='passthrough')
hand_array = self.set_hand_array(self.feed)
self.set_pose(hand_array)
mode,command = self.set_hand_gesture(hand_array)
self.set_mode(mode,command) |
def _create_mini_batches(X: np.ndarray, y: np.ndarray, batch_size: int, shuffle: bool, drop_last: bool) -> \
Iterator[Tuple[np.ndarray, np.ndarray]]:
"""
Creates mini-batches from the input data.
:param X: The input features
:param y: The target labels
:param batch_size: The size of the min... | This method executes one training epoch by processing mini-batches of input data and labels. It performs forward passes to generate predictions, calculates categorical cross-entropy loss, and tracks correct predictions. If optimization is enabled, it conducts backpropagation. It aggregates total loss and accuracy acros... | def _run_single_epoch(self, X: np.ndarray, y: np.ndarray, optimize: bool) -> Tuple[float, float]:
"""
Run one epoch of forward and backward pass, and computes the accuracy and loss for this epoch.
:param X: The input data
:param y: The corresponding labels
:param optimize: If Tr... |
def generate_signed_url(self, blob_path):
bucket = self.client.get_bucket(self.google_bucket_name)
blob = bucket.blob(blob_path)
return blob.generate_signed_url(datetime.timedelta(seconds=300), method='GET')
def extract_frames(self,url_video, ... | The main task of the code is to process a video by extracting and predicting both its visual frames and audio components. It generates a signed URL for the input video, extracts frames into a folder, predicts each frame, extracts audio, predicts sound features, and combines results into a dictionary containing frame an... | def predict_video(self, video_blob_path):
frames_folder = video_blob_path.split('/')[-1].replace('.mp4','')
self.blob_path = frames_folder
signed_url_video = self.generate_signed_url(video_blob_path)
frames_folder = self.extract_frames(signed_url_video, frames_folder)
frames_pred... |
def hash_run_params(*args, **kwargs):
m = hashlib.sha256()
kwarg_list = [(k, kwargs[k]) for k in kwargs]
kwarg_list.sort(key=lambda x: x[0]) # Sort by key
all_params = list(args) + kwarg_list
hashable_params = []
for p in all_params:
if callable(p):
hashable_params.appe... | The function `evolve_with_disk_cache` simulates a dynamic system's evolution over time steps using a disk cache for checkpointing. It initializes parameters, loads cached results if available, and iteratively applies a time-step function to update the system's state (positions and velocities). Stability is monitored; i... | def evolve_with_disk_cache(boundary_fn, g, x_initial_fn, x_dot_initial_fn, N, step_size, n_steps, checkpoint_freq, **kwargs):
run_hash = hash_run_params(boundary_fn, g, x_initial_fn, x_dot_initial_fn, N, step_size, n_steps, checkpoint_freq, **kwargs)
filename = f"{run_hash}.pkl"
if not os.path.exists(CACH... |
def create_boundary_fn(position_fn, dposition_fn, d2position_fn, transition_timescale=1.0):
'''Adds smooth start to desired position fn for end of ribbon, and returns boundary cond for the acceleration.'''
assert np.all(position_fn(0) == 0.0)
tran = lambda t: (1 - np.exp(-1 * (t/transition_timescale)**2))
... | The main task of the code is to solve the dynamics of a ribbon-like system using given position functions and their derivatives, simulate its motion over time with specified physical parameters, generate animations of the results, and save them as HTML files. It also creates additional animations for stability and tens... | def solve_and_animate(position_fn, dposition_fn, d2position_fn, filename, g=10.0, end_mass=0.0, drag_coef=0.0, scale=1.0, total_time=10.0, transition_timescale=1.0, disk_cache=False,
N=100, step_size=0.0001, checkpoint_times=0.1):
'''Solve and save animation for given position of ribbon end, w... |
def Str_To_Hex(Input):
Hex = ""
for i in range(len(Input)):
T = hex(ord(Input[i]))[2::]
if (len(T) == 1):
Hex += '0' + T[0]
elif (len(T) == 0) :
Hex += '00'
else:
Hex += T
return Hex
def Key_Mutation(key, pc1, pc2, roundshift):
# ... | The main task of the code is to implement Triple DES (3DES) encryption using three keys (key1, key2, key3) on input data (plaintext), supporting both string and nd-array (image) formats. It converts inputs to hex, applies DES encryption-decrypt-encrypt operations sequentially with key schedules, handles padding, and re... | def TDEA_Encrypt(inspect_mode, plaintext, key1, key2, key3, ip):
# Create keys once to save time
Key1 = Str_To_Hex(key1)
Key2 = Str_To_Hex(key2)
Key3 = Str_To_Hex(key3)
Keys1 = Key_Mutation(Key1, PC1, PC2, KeyRoundShifts)
Keys2 = Key_Mutation(Key2, PC1, PC2, KeyRoundShifts)
Keys3 = Key_... |
def Str_To_Hex(Input):
Hex = ""
for i in range(len(Input)):
T = hex(ord(Input[i]))[2::]
if (len(T) == 1):
Hex += '0' + T[0]
elif (len(T) == 0) :
Hex += '00'
else:
Hex += T
return Hex
def Key_Mutation(key, pc1, pc2, roundshift):
# ... | The main task of this code is to decrypt data using a Triple DES (TDEA) algorithm with three keys. It processes both string and numpy array (image) inputs, applying DES decryption and encryption steps in sequence (decrypt with Key3, encrypt with Key2, decrypt with Key1). It supports padding, hex conversion, and returns... | def TDEA_Decrypt(inspect_mode, plaintext, key1, key2, key3, inv_ip):
# Works same as TDEA_Encrypt
Key1 = Str_To_Hex(key1)
Key2 = Str_To_Hex(key2)
Key3 = Str_To_Hex(key3)
Keys1 = Key_Mutation(Key1, PC1, PC2, KeyRoundShifts)
Keys2 = Key_Mutation(Key2, PC1, PC2, KeyRoundShifts)
Keys3 = Ke... |
def get_feedback(self):
rew=[]
for j in range(self.m): # for each task
for i in range(self.n): # for each server
if self.check_source(j,i)==1: # in that group
if self.check_avaliable(j,i)==1: # avaliable
reward=self.task[j][0]*self.task[j][1]*self.d_i[i]
-self.a... | This function updates a Q-table using Q-learning for task scheduling, considering CPU and time constraints. It iterates through tasks, selects feasible actions, adjusts Q-values based on rewards and future states, and returns the updated Q-table, total rewards, and selected actions. | def q_update(self):
actions_ava=[]
rews=[]
act=[]
rewards=np.array(self.get_feedback()).reshape(self.m,self.n)
cpu_table=self.cpu_table()
time_table=self.time_table()
# check the limitation of time and cpu
for j in range(self.m):
state_actions = self.check_action_reward(j)
a... |
def get_feedback(self):
rew = []
for j in range(self.m): # for each task
for i in range(self.n): # for each server
if self.check_source(j, i) == 1: # in that group
# h=i
if self.check_avaliable_1(j, i) == 1: # avaliable
... | The code updates a Q-table using Q-learning by selecting actions for tasks, validating them against CPU/time constraints, and adjusting Q-values based on rewards. It accumulates rewards and actions, returning the updated Q-table, total reward, and action sequence for each task iteration. | def q_update_modified(self):
actions_ava = []
rews = []
act = []
rewards = np.array(self.get_feedback()).reshape(self.m, self.n)
cpu_table = self.cpu_table()
time_table = self.time_table()
# check the limitation of time and cpu
for j in range(self.m):
... |
def get_feedback(self):
rew = []
for j in range(self.m): # for each task
for i in range(self.n): # for each server
if self.check_source(j, i) == 1: # in that group
# h=i
if self.check_avaliable_1(j, i) == 1: # avaliable
... | The main task of the code is to update a Q-table in a reinforcement learning framework by evaluating available actions under CPU and time constraints. It iterates through tasks, selects valid actions, adjusts Q-values using the Bellman equation with rewards and discount factors, and accumulates total rewards. The funct... | def q_update(self):
actions_ava = []
rews = []
act = []
rewards = np.array(self.get_feedback()).reshape(self.m, self.n)
cpu_table = self.cpu_table()
time_table = self.time_table()
# check the limitation of time and cpu
for j in range(self.m):
s... |
def get_feedback(self):
rew = []
for j in range(self.m): # for each task
for i in range(self.n): # for each server
if self.check_source(j, i) == 1: # in that group
# h=i
if self.check_avaliable_1(j, i) == 1: # avaliable
... | This function updates a Q-table using Q-learning without speed-up, considering CPU and time constraints for each task. It iterates through tasks, selects valid actions, calculates rewards, and updates the Q-values based on feedback. The process records actions and cumulative rewards, returning the updated Q-table, tota... | def q_update_without_speed_up(self):
actions_ava = []
rews = []
act = []
rewards = np.array(self.get_feedback()).reshape(self.m, self.n)
cpu_table = self.cpu_table()
time_table = self.time_table()
# check the limitation of time and cpu
for j in range(self.... |
def get_feedback(self):
rew=[]
for j in range(self.m): # for each task
for i in range(self.n): # for each server
if self.check_source(j,i)==1: # in that group
if self.check_avaliable(j,i)==1: # avaliable
reward=self.task[j][0]*self.task[j][1]*self.d_i[i]
-self.a... | This function implements a greedy algorithm to select actions that maximize cumulative rewards while adhering to CPU and time constraints. It iterates through tasks, checks available actions, verifies resource limitations, and adjusts selections when constraints are violated. The algorithm updates CPU usage tracking an... | def greedy_select(self):
actions_ava=[]
rews=[]
act=[]
rewards=np.array(self.get_feedback()).reshape(self.m,self.n)
cpu_table=self.cpu_table()
time_table=self.time_table()
# check the limitation of time and cpu
for j in range(self.m):
state_actions = self.check_action_reward(j)
... |
def get_feedback(self):
rew=[]
for j in range(self.m): # for each task
for i in range(self.n): # for each server
if self.check_source(j,i)==1: # in that group
if self.check_avaliable(j,i)==1: # avaliable
reward=self.task[j][0]*self.task[j][1]*self.d_i[i]
-self.a... | The code implements a random action selection algorithm with constraints. It evaluates available actions for each task, ensuring CPU and time limits are met. If constraints are violated, it reselects actions. The function calculates cumulative rewards from selected actions and returns their sum, optimizing task executi... | def ramdom_select(self):
actions_ava=[]
rews=[]
act=[]
rewards=np.array(self.get_feedback()).reshape(self.m,self.n)
cpu_table=self.cpu_table()
time_table=self.time_table()
# check the limitation of time and cpu
for j in range(self.m):
state_actions = self.check_action_reward(j)
... |
def get_feedback(self):
rew = []
for j in range(self.m): # for each task
for i in range(self.n): # for each server
if self.check_source(j, i) == 1: # in that group
# h=i
if self.check_avaliable_1(j, i) == 1: # avaliable
... | The main task of the code is to implement a greedy algorithm for action selection in a task scheduling scenario, prioritizing actions based on reward values while ensuring CPU and time constraints are satisfied. It iterates through tasks, checks available actions, validates resource limits, and updates rewards and CPU ... | def greedy_select(self):
actions_ava = []
rews = []
act = []
rewards = np.array(self.get_feedback()).reshape(self.m, self.n)
cpu_table = self.cpu_table()
time_table = self.time_table()
# check the limitation of time and cpu
for j in range(self.m):
... |
def get_feedback(self):
rew = []
for j in range(self.m): # for each task
for i in range(self.n): # for each server
if self.check_source(j, i) == 1: # in that group
# h=i
if self.check_avaliable_1(j, i) == 1: # avaliable
... | This function selects actions for tasks while ensuring CPU and time constraints are met. It randomly picks actions, checks if they satisfy resource limits, and reselects if constraints fail. It updates CPU usage, accumulates rewards, and returns their total sum. | def ramdom_select(self):
actions_ava = []
rews = []
act = []
rewards = np.array(self.get_feedback()).reshape(self.m, self.n)
cpu_table = self.cpu_table()
time_table = self.time_table()
# check the limitation of time and cpu
for j in range(self.m):
... |
def disable_augmentation_hook(hook_config, dataloader, total_epochs, cur_epoch, cfg, flag, logger):
"""
This hook turns off the data augmentation during training.
"""
if hook_config is not None:
DisableAugmentationHook = hook_config.get('DisableAugmentationHook', None)
if DisableAugmenta... | The main task of the code is to train a machine learning model over multiple epochs using a specified optimizer and learning rate scheduler. It handles data loading, training iteration, checkpoint management, distributed training support, and data augmentation hooks. The function also implements learning rate warmup, p... | def train_model(model, optimizer, train_loader, model_func, lr_scheduler, optim_cfg,
start_epoch, total_epochs, start_iter, rank, tb_log, ckpt_save_dir, train_sampler=None,
lr_warmup_scheduler=None, ckpt_save_interval=1, max_ckpt_save_num=50,
merge_all_iters_to_one_epoch=... |
def H1(puzzle):
left = spacesOpen(puzzle)
if left > 3:
return -left
else:
return left
def H2(puzzle, move):
# Gets the amount of merges done before the current puzzle to now
copy = myCopy2(puzzle)
numFree = H1(puzzle) # number of free spaces before move
if numFree > 5:
... | The function `evaluateh` calculates a combined heuristic value for a puzzle state by summing multiple weighted individual heuristics (H1-H7). Each heuristic evaluates different aspects of the puzzle, such as open spaces, merges, tile alignment, and adjacency. The weights (e.g., ×10, ×50) amplify certain heuristics to p... | def evaluateh(n, puzzle, move):
# debugDisplay(puzzle)
# This is the function that adds all of the hueristics together
h1 = 1.0 * H1(puzzle) # Spaces open
h2 = 1.0 * H2(n.parent.puzzle, move) # Num of merges
h3 = 1.0 * H3(puzzle) * 10 # Left to right
h4 = 1.0 * H4(puzzle) * 10 # Top to Bottom
... |
def pol2cart(rho, phi):
x = rho * np.cos(phi * pi)
y = rho * np.sin(phi * pi)
# print("r:{}, phi: {}, x: {}, Y: {}".format(rho, phi, x,y))
return np.asarray([x, y])
def log_location(self):
if self.location_record is not None:
self.location_record[self.record_write_steps_recorded] = ... | This code processes an action in a reinforcement learning environment by applying a force, simulating physics, tracking the state, and returning the next state and termination status. It validates the action, converts it to force via polar-to-Cartesian conversion, updates the environment, checks for episode termination... | def step(self, action):
# print(action)
assert self.action_space.contains(action)
self.force_applied = pol2cart(*ACTIONS[action])
self.log_location()
self._handle_physics(PHYSICS_DELTA_TIME)
state = self.render("state_pixels")
reward = 0
self.curren... |
def verifyCredentials(account_id, password):
if not Account_id_Exist(account_id):
return generateReturnDictionary(301, "Invalid account_id"), True
correct_pw = verifyPw(account_id, password)
if not correct_pw:
return generateReturnDictionary(302, "Incorrect Password"), True
return Non... | This code handles a POST request to add funds to a user's account. It verifies credentials, checks if the amount is positive, deducts a $1 transaction fee, transfers the fee to the bank, and updates the user's balance. It returns JSON responses for errors or success, ensuring valid transactions and proper account updat... | def post(self):
postedData = request.get_json()
account_id = postedData["account_id"]
password = postedData["password"]
money = postedData["amount"]
retJson, error = verifyCredentials(account_id, password)
if error:
return jsonify(retJson)
if money<... |
def verifyCredentials(account_id, password):
if not Account_id_Exist(account_id):
return generateReturnDictionary(301, "Invalid account_id"), True
correct_pw = verifyPw(account_id, password)
if not correct_pw:
return generateReturnDictionary(302, "Incorrect Password"), True
return Non... | This code handles a money transfer request by verifying user credentials, checking sender's balance, validating recipient's account, updating balances (sender, recipient, and bank), and returning success or error messages based on validation results. | def post(self):
postedData = request.get_json()
account_id = postedData["account_id"]
password = postedData["password"]
to = postedData["to"]
money = postedData["amount"]
retJson, error = verifyCredentials(account_id, password)
if error:
re... |
def verifyCredentials(account_id, password):
if not Account_id_Exist(account_id):
return generateReturnDictionary(301, "Invalid account_id"), True
correct_pw = verifyPw(account_id, password)
if not correct_pw:
return generateReturnDictionary(302, "Incorrect Password"), True
return Non... | This code handles a POST request to add a loan to a user's account. It verifies the user's credentials, retrieves their current cash and debt, updates their account by adding the specified amount to both cash and debt, and returns a success response if valid. | def post(self):
postedData = request.get_json()
account_id = postedData["account_id"]
password = postedData["password"]
money = postedData["amount"]
retJson, error = verifyCredentials(account_id, password)
if error:
return jsonify(retJson)
cash =... |
def verifyCredentials(account_id, password):
if not Account_id_Exist(account_id):
return generateReturnDictionary(301, "Invalid account_id"), True
correct_pw = verifyPw(account_id, password)
if not correct_pw:
return generateReturnDictionary(302, "Incorrect Password"), True
return Non... | This code processes a loan payment request by verifying user credentials, checking their available cash, deducting the specified amount from their account balance and debt, and returning success or error messages in JSON format. | def post(self):
postedData = request.get_json()
account_id = postedData["account_id"]
password = postedData["password"]
money = postedData["amount"]
retJson, error = verifyCredentials(account_id, password)
if error:
return jsonify(retJson)
cash =... |
def choose_difficulty(self):
sense.show_message("Difficulty:", scroll_speed=0.03)
difficulty = 5
sense.show_letter(str(difficulty))
event = sense.stick.wait_for_event(emptybuffer=True)
while event.direction != "middle":
if event.direction == "up" and difficulty < 9:
... | The code defines a game loop that initializes settings, handles user input for direction, spawns game elements, and continuously updates the game state by moving objects and redrawing them at intervals. It runs until the game ends, then triggers a finish sequence and resets the game for a new round. | def game(self):
sense.stick.direction_any = self.set_direction
while True:
print("New game")
self.choose_difficulty()
self.spawn()
self.draw()
while self.status:
sleep(self.speed)
self.move()
sel... |
def Easy():
"""Game mode with a number between 0-10"""
rng = random.Random()
t = rng.randrange(0, 11)
print("You chose the difficulty EASY. \nYou get 3 guesses.")
count = 0
maxguess = 3
for guess in range(maxguess):
n = guesscheck("easy", 10)
count += 1
v = checkguess... | The main task of the code is to present a difficulty selection menu, validate user input (E/N/H/U), and return the string representation of the corresponding function (Easy/Normal/Hard/Unrealistic) based on the choice. It recursively prompts until a valid option is selected. | def ChooseDifficulty():
"""Menu of Difficulty options"""
print("What Difficulty Would You Like To Play?")
print(" (0-10) EASY Press 'E' \n (0-100) NORMAL Press 'N' \n (0-1000) HARD Press 'H' \n (0-10000) UNREALISTIC Press 'U' \n")
print(" Then Press Enter")
diffi... |
def reset(self):
self.digital_write(self.reset_pin, 1)
self.delay_ms(50)
self.digital_write(self.reset_pin, 0)
self.delay_ms(2)
self.digital_write(self.reset_pin, 1)
self.delay_ms(50)
def send_command(self, command):
self.digital_write(self.dc_pin, 0)
self... | This code initializes an electronic paper display by sending configuration commands to set panel parameters, resolution, and VCOM settings, followed by a reset and busy-state wait to prepare the hardware for operation. | def init(self):
print('init')
self.reset()
self.send_command(0x04)
self.ReadBusy()#waiting for the electronic paper IC to release the idle signal
self.send_command(0x00) #panel setting
self.send_data(0x0f) #LUT from OTP,128x296
self.send_data(0x89) #Tem... |
def send_command(self, command):
self.digital_write(self.dc_pin, 0)
self.digital_write(self.cs_pin, 0)
self.spi_writebyte([command])
self.digital_write(self.cs_pin, 1)
def ReadBusy(self):
print('busy')
self.send_command(0x71)
while(self.digital_read(self.busy_pin)... | The code's main task is to put the device into deep sleep mode by sending power-off and deep sleep commands, followed by a delay and module exit. It first sends 0x02 to power off, waits for readiness, sends 0x07 with data 0xA5 for deep sleep, delays 2000ms, and exits the module to ensure proper shutdown. | def sleep(self):
self.send_command(0X02) # power off
self.ReadBusy()
self.send_command(0X07) # deep sleep
self.send_data(0xA5)
self.delay_ms(2000)
self.module_exit() |
def send_command(self, command):
self.digital_write(self.dc_pin, 0)
self.digital_write(self.cs_pin, 0)
self.spi_writebyte([command])
self.digital_write(self.cs_pin, 1)
def send_data(self, data):
self.digital_write(self.dc_pin, 1)
self.digital_write(self.cs_pin, 0)
... | This code sends black and red pixel data to a display device in a specific format, iterating through buffer arrays to render images. It first transmits black pixels using command 0x10, then red pixels with command 0x13, finally activating the display. The method handles dual-color output by processing buffer data in 8-... | def display(self):
self.send_command(0x10)
for j in range(0, self.height):
for i in range(0, int(self.width / 8)):
self.send_data(self.buffer_black[i + j * int(self.width / 8)])
self.send_command(0x13)
for j in range(0, self.height):
for i in ra... |
def send_command(self, command):
self.digital_write(self.dc_pin, 0)
self.digital_write(self.cs_pin, 0)
self.spi_writebyte([command])
self.digital_write(self.cs_pin, 1)
def send_data(self, data):
self.digital_write(self.dc_pin, 1)
self.digital_write(self.cs_pin, 0)
... | The code clears a display by sending black and red pixel data across its height and width in 8-pixel segments using specific commands, then activates the display. | def Clear(self, colorblack, colorred):
self.send_command(0x10)
for j in range(0, self.height):
for i in range(0, int(self.width / 8)):
self.send_data(colorblack)
self.send_command(0x13)
for j in range(0, self.height):
for i in range(0, int(self.wid... |
def __const_c(self):
"""Compute c constant.
Returns
-------
c : float
"""
return gamma((self.eta+1)/2) \
/ ((np.pi*(self.eta-2))**.5*gamma(self.eta/2))
def __const_a(self):
"""Compute a constant.
Returns
-------
a : float
... | This method computes the probability density function (PDF) values for given input points using class-specific constants and parameters. It calculates the PDF by evaluating a mathematical expression involving the input array, constants `c`, `a`, `b`, and class attributes `eta` and `lam`, returning an array of PDF value... | def pdf(self, arg):
"""Probability density function (PDF).
Parameters
----------
arg : array
Grid of point to evaluate PDF at
Returns
-------
array
PDF values. Same shape as the input.
"""
c = self.__const_c()
a =... |
def clear():
return os.system("clear")
def print_field():
"""Prints entire field"""
kill1 = 0
live1 = 0
for i in nums:
# Prints letters for columns
print_letters(i)
# Prints number for the row
print_number(i)
# Prints each cell
kill, live = print_row(i... | The code implements a turn-based game where the player navigates a ship, tracks remaining lives, and inputs coordinates to attack a fleet. It validates moves, updates game state, and checks for win/loss conditions. The loop continues until all fleet ships are sunk (win) or lives reach zero (loss), with EOF handling and... | def main():
while True:
try:
answer = input(rules).lower()
if answer == "y":
break
if answer == "n":
clear()
sys.exit(farewell())
except EOFError:
clear()
sys.exit(farewell())
while True:
... |
def getImages(self):
image_plain = Image.open("images/facingDown.png")
image_plain = image_plain.resize((25, 25), Image.ANTIALIAS)
image_flag = Image.open("images/flagged.png")
image_flag = image_flag.resize((25, 25), Image.ANTIALIAS)
self.images = {
... | This code initializes a Minesweeper game interface using Tkinter. It sets up a window with a grid of clickable cells representing the game field, displays mine count and timer labels, and adds controls for resetting, changing difficulty, or quitting. Event handlers for left/right clicks on cells and window closure are ... | def __init__(self, root, scores, x_cells, y_cells, tot_mines):
self.root = root
self.scores = scores
self.window = tk.Toplevel()
self.window.title("MineSweeper")
self.window.config(pady = 10, padx=10)
self.window.protocol("WM_DELETE_WINDOW", self.close_window)
... |
def plot_readouts(self, input_vecs, current_stage, current_epoch, alpha, gamma, theta, filepath):
f, axs = plt.subplots(2, 10)
for i in range(10):
axs[0][i].imshow(input_vecs[i].reshape(self.image_dims[0], self.image_dims[1]), cmap='gray', vmin=0, vmax=1)
axs[0][i].get_xaxis().se... | The main task of the code is to train a neural network model using competitive learning. It processes an input image array over multiple epochs, shuffling data each epoch, identifying winning neurons, and updating weights with adaptive learning rates and neighborhood sizes. Periodic readouts of training progress are sa... | def train(self, img_arr, current_stage, num_epochs, lr, readout_interval=0, readout_examples=[], readout_path=''):
'''
Takes in a (n x m) array of images, where n = number of inputs and m = number of features;
a number of epochs to train for, and a learning rate.
'''
total_iterat... |
def constructShfMsk(desc, state):
shf = [0xff] * 32
offset = 0
k = 0
s = 4 - state
for i in range(0, num(desc)):
for j in range(0, len(desc, i)):
shf[k + j] = offset + j
offset += len(desc, i)
k += s
s = 4
for j in range(0, rem(desc)):
shf[k + ... | The code generates C++ lookup tables for efficient varint encoding using SIMD instructions (SSSE3/AVX2). It constructs shuffle masks, encoded lengths, output offsets, and state arrays for x86 architectures, enabling fast variable-length integer processing in the Codecs namespace. | def generate_varintGUTables(f):
f.write("""#include <cstdint>
#include "Portability.h"
namespace Codecs {
namespace varintTables {
#if CODECS_X64 || defined(__i386__) || CODECS_PPC64
#if CODECS_SSE_PREREQ(3, 1)
extern const __m128i varintGU_SSSE3_shfl_msk_m128i[4][256][2] = {
""")
# Construct shuffle constro... |
def _write(self, str):
self.file.write(f'{str}\n')
def calc_axis(self):
xRange = (np.min(self.data[:,0]), np.max(self.data[:,0]))
yRange = (np.min(self.data[:,1]), np.max(self.data[:,1]))
diff = xRange[1] - xRange[0]
buffer = 10**(np.log10(diff) - 1)
self._write(f'xaxis... | This code initializes a graphical representation by opening a file, setting up data parameters, calculating axis ranges, and generating histograms for given data classes with specified bins. It writes a graph header, configures legends, and constructs histograms based on data distribution. | def __init__(self, filepath, data, nbins):
self.filepath = filepath
self.file = open(self.filepath, 'w')
self.nbins = nbins
self.classes = np.unique(data[:,-1])
self.data = data
self.cls_colors = []
self._write('newgraph')
self._write('legend left')
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.