dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def create_grid(locked_positions):
grid = [[(0, 0, 0) for _ in range(10)] for _ in range(20)]
for i in range(len(grid)):
for j in range(len(grid[i])):
if (j, i) in locked_positions:
c = locked_positions[(j, i)]
grid[i][j] = c
return grid
def valid_space(sh... | The code defines a 'battle' function that manages a two-player Tetris-style game, handling game loop logic, player input, piece movement, line clearing, scoring, and loss conditions. It initializes two game threads, processes events, updates game states, checks for valid moves, and saves scores when players lose. The f... | def battle():
global game, scores
r1 = random.randrange(0, 50)
r2 = random.randrange(0, 48)
game = [GameThread(1, block_size*10, int(height/2 - block_size*10), r1, r2),
GameThread(2, width-block_size*20, int(height/2 - block_size*10), r1, r2)]
run_game = True
end = True
while run... |
def create_stream():
stream = []
for _ in range(4):
temp = Piece(0, 0, random.choice(shapes))
temp.rotation += random.randint(0, 10)
stream.append(temp)
return stream
def check_active():
active = False
i = 0
for index, each in enumerate(buttons):
if each.active:
... | The main task of the code is to implement a menu interface with keyboard navigation, allowing users to select options via arrow keys and confirm choices with Space/Enter. It manages active buttons, handles quit/escape events, and returns selection status. Visual elements like "rain" animations are rendered alongside th... | def main_menu():
global run
rain = [create_stream() for _ in range(15)]
offset = [block_size * random.randrange(3, 10) for _ in range(len(rain))]
while run:
clock.tick(30)
active, i = check_active()
for event in pygame.event.get():
if event.type == pygame.QUIT:
... |
def create_stream():
stream = []
for _ in range(4):
temp = Piece(0, 0, random.choice(shapes))
temp.rotation += random.randint(0, 10)
stream.append(temp)
return stream
def generate_string():
settings = []
if hold:
settings.append('On')
else:
settings.append... | The code implements an options menu in a Pygame application, allowing users to navigate and toggle settings (e.g., fullscreen, music, keyboard layout) via arrow keys. It handles input events, updates visual elements, and modifies global variables to reflect user choices, returning True/False based on navigation actions... | def options():
global music, hold, azerty, win, width, height, block_size, fullscreen
selection = 0
rain = [create_stream() for _ in range(15)]
offset = [block_size * random.randrange(3, 10) for _ in range(len(rain))]
while True:
settings_string = generate_string()
settings_string.ap... |
def start_day_gmt(att_time_obj, attendance_time):
start_day = datetime.strptime(str(att_time_obj.date()) + " 00:00:00", '%Y-%m-%d %H:%M:%S')
return start_day + get_gmt_delta(attendance_time)
def end_day_gmt(att_time_obj, attendance_time):
end_day = datetime.strptime(str(att_time_obj.date()) + " 23:59:59", '... | The main task of the code is to retrieve and process an employee's attendance records within a specific time range, adjusting for time zones. It collects check-in and check-out timestamps, combines them with a given punch state, and returns a dictionary of these time-state pairs. The function also deletes the retrieved... | def get_db_punch(employee_id, attendance_time, punch_state, att_time_obj):
start_day = start_day_gmt(att_time_obj, attendance_time)
end_day = end_day_gmt(att_time_obj, attendance_time)
att_time_obj_db = att_time_obj + get_gmt_delta(attendance_time)
in_att = request.env['hr.attendance'].... |
def is_db_exist(db_name):
request.env.cr.execute("SELECT 0 FROM pg_database where datname = '" + db_name + "'")
check_db = request.env.cr.fetchone()
if check_db:
return True
return False
def get_gmt_delta(attendance_time):
hdiff = hour_diff(attendance_time) or '0'
mdiff = minute_diff(att... | The code processes attendance data from a machine, validating inputs like machine ID, direction, and database. It checks for valid employee and device credentials, parses JSON data, determines check-in/check-out states, and prevents duplicate entries. The function then routes processing based on the direction parameter... | def generate_attendance(self, **params):
machine_id = params.get('stgid')
param_direction = params.get('direction')
db_name = params.get('db')
if db_name is not None:
if not is_db_exist(db_name):
return Response('{"status":"error","message": "Invalid db"}... |
def _parse_clear(self):
"""
Runs clear operations and prints CLEAR STDOUT.
"""
self.pen_location = [0, 0]
self.color = [0, 0, 0, 255]
self.is_pen_down = False
print('CLR;')
def _parse_pen_state(self, substr):
"""
Sets pen to be UP or DOWN and print... | This function parses a data stream of commands by identifying opcodes (e.g., CLEAR, SET PEN STATE, SET COLOR, MOVE PEN), extracting their parameters from the stream string, and executing corresponding internal methods. It processes the stream sequentially, advancing the index based on opcode length, logging debug infor... | def parse_stream(self, stream_str):
"""
Parses a stream string and run its commands and their
adjacent parameters.
Arguments:
stream_str {str} - data stream of actions be taken.
"""
i = 0
while i < len(stream_str):
# Opcode is C... |
def __button_click(self, val):
"""Plays coind drop sound using play_coin() function. Method responsible for entering the amount by user to purchase the item. It also returns information on display screen
about the remaining amount to pay.
Parameters
----------
... | The code creates a payment window for a selected product, displaying its price and allowing users to insert coins via buttons. It centers the window on the screen, includes a display for the product info, and provides 'Pay' and 'Resign' buttons to confirm payment or cancel. The window is linked to a previous window, wh... | def __init__(self, master, product_number):
"""Creates the window with buttons(coins) and display screen
Parameters
----------
master: "reference" to previous winndow
product_number: int
product number chosen by the user
... |
def ReadUnixMsTime(unix_time_ms): # Unix millisecond timestamp
'''Returns datetime object, or empty string upon error'''
if unix_time_ms not in (0, None, ''):
try:
if isinstance(unix_time_ms, str):
unix_time_ms = float(unix_time_ms)
return datetime.datetime(1970,... | The main task of the code is to parse an ODL (OneDrive Log) binary file, extract structured data including timestamps, function names, parameters, and metadata, handle decompression of compressed logs, map obfuscated parameters using a provided `map` and `dkey`, and return the parsed data as a pandas DataFrame. It vali... | def process_odl(filename, map):
odl_rows = []
basename = os.path.basename(filename)
try:
dkey = [dkey_dict[key] for key in dkey_dict if key in os.path.dirname(filename)][0]
except Exception:
dkey = ''
try:
f = open(filename, 'rb')
except Exception as e:
log.error(... |
def read_keystore(keystore_path):
global dkey_dict
global utf_type
encoding = guess_encoding(keystore_path)
with open(keystore_path, 'r', encoding=encoding) as f:
try:
j = json.load(f)
dkey = j[0]['Key']
version = j[0]['Version']
utf_type = 'utf32'... | The main task of the code is to parse ODL log files (and related formats) from a specified directory, aggregate their contents into a unified DataFrame, and handle obfuscation mappings. It scans for files with extensions like `.odl`, `.odlgz`, and `.aodl`, processes them using `process_odl`, and merges results into a s... | def parse_odl(rootDir, key='', pb=False, value_label=False, gui=False):
filenames = []
obfuscation_maps = []
map = {}
df = pd.DataFrame()
for path, subdirs, files in os.walk(rootDir):
filematch = ([os.path.join(path, file) for file in files if file.endswith(('.odl', '.odlgz', '.odlsent', '... |
def generate_pop():
return problem.generate_population()
def print_pop(p, g):
print(f"Generation: {g}\tString: {p[0].dna}\t Fitness: {p[0].fitness}")
def compute_fitness(p):
for i in p:
i.fitness = problem.problem(i)
return p
def selection(population):
# sort the population in increasing ord... | The code implements a genetic algorithm to find a solution where the population's best individual achieves a fitness score of zero. It initializes a population, iteratively computes fitness, selects individuals for the next generation, and terminates when the target fitness is reached, printing the population at each g... | def main():
global POPULATION_SIZE
global problem
# current generation
generation = 1
found = False
problem = problems(0)
# create initial population
population = generate_pop()
print_pop(population, generation)
while not found:
population = compute_fitness(populat... |
def generate_population():
return [gene() for _ in range(t.pop)]
def compute_fitness(p):
for i in range(t.pop):
# TODO change code to follow comb
p[i].fitness = t.problem.problem(p[i].dna)
return p
def next_generation(p):
return compute_fitness(selection(p))
def calc_average_fitness(pop)... | The main task of the code is to run multiple genetic algorithm tests on six different problems, varying parameters like population size, generations, crossover, and mutation rates. It tracks average fitness over generations, stops early if no improvement occurs, and stores results in a dataframe. Finally, it saves each... | def main():
global t
nubmer_of_runs = 10
min_pop_size = 10
max_pop_size = 1000
min_gens = 100
max_gens = 1000
min_xover = 0.1
max_xover = 0.7
min_muts = 0.001
max_muts = 0.3
lower = 0
upper = 500
problem_number = 0
for p in range(6):
# instance of the t... |
def signup():
"""The function Signs Up the page with given requisites"""
send_keys(Xpath.first_name, user2.first_name)
send_keys(Xpath.last_name, user2.last_name)
send_keys(Xpath.phone, user2.phone)
send_keys(Xpath.email, user2.email)
send_keys(Xpath.password, user2.password)
driver.find_ele... | The code automates a hotel booking process on PHPTRAVELS by signing up, logging in, searching for hotels in Yerevan, selecting a hotel, booking a room, and finalizing the reservation. It handles multiple browser windows, uses explicit waits for URL/title changes, and returns the final confirmation URL after completing ... | def actions():
global parent_window
signup()
WebDriverWait(driver, 10).until(
EC.url_changes('https://www.phptravels.net/signup')
)
login()
driver.implicitly_wait(10)
choose_hotel()
driver.implicitly_wait(10)
search_from_hotels()
WebDriverWait(driver, 10).until(
... |
def update_user_features(self, learning_rate):
for i in range(0, self.user_count):
for j in range(0, self.features):
self.user_features[i, j] += learning_rate * self.user_feature_gradient(user_row=i, wrt_user_idx=j)
def update_item_features(self, learning_rate):
for i in rang... | The code trains a model by iteratively updating user and item features using gradient descent for a specified number of iterations. In each iteration, both user and item features are adjusted based on the learning rate to minimize prediction errors. The Mean Squared Error (MSE) is calculated and printed after each iter... | def train_model(self, learning_rate=0.0001, iterations=1000):
for i in range(iterations):
self.update_user_features(learning_rate=learning_rate)
self.update_item_features(learning_rate=learning_rate)
print(self.MSE()) |
def check_tie(self):
# TODO: Check tie
#Checks to see if there are no more spaces left
if self.check_win("X") == True or self.check_win("O") == True:
return False
for i in range(3):
for j in range(3):
if self.board[i][j] == "-":
... | This code implements the minimax algorithm for a tic-tac-toe game, recursively evaluating all possible moves to determine the optimal strategy. It returns the best score and corresponding move coordinates for the current player, with "O" maximizing scores and "X" minimizing them. The function checks game states (win, t... | def minimax(self, player, depth):
if self.check_tie() == True:
return 0, None, None
if self.check_win("X") == True:
return -10, None, None
if self.check_win("O") == True:
return 10, None, None
if depth == 0:
return 0, None, None
... |
def check_tie(self):
# TODO: Check tie
#Checks to see if there are no more spaces left
if self.check_win("X") == True or self.check_win("O") == True:
return False
for i in range(3):
for j in range(3):
if self.board[i][j] == "-":
... | This function implements the Minimax algorithm with alpha-beta pruning for a Tic-Tac-Toe AI. It evaluates all possible moves recursively, alternating between players "X" and "O", to determine the optimal next move by maximizing/minimizing scores. It checks for wins, ties, and depth limits, updating alpha/beta values to... | def minimax_alpha_beta(self, player, depth, alpha, beta):
if self.check_tie() == True:
return 0, None, None
if self.check_win("X") == True:
return -10, None, None
if self.check_win("O") == True:
return 10, None, None
if depth == 0:
return 0... |
def print_instructions(self):
# TODO: Print the instructions to the game
#prints out the rules of the game
print("Welcome to Tic Tac Toe!")
print("Player 1 is X and Player 2 is O")
print("Take turns placing X and Os inorder to get 3 in a row!")
def print_board(self):
# TO... | The main task of the code is to run a game loop that alternates players, takes turns, updates the board, checks for a win or tie, and ends the game when a player wins or the game ties. It uses methods like `print_instructions`, `print_board`, `change_player`, `take_turn`, `check_win`, and `check_tie` to manage gameplay... | def play_game(self):
# TODO: Play game
#uses all the methods up above to run the game until a tie or a winner
self.print_instructions()
self.print_board()
play = True
player = "O"
while play:
player = self.change_player(player)
self.take_tu... |
def _check_keydown_events(self, event):
if event.key == pygame.K_RIGHT:
self.ship.moving_right = True
elif event.key == pygame.K_LEFT:
self.ship.moving_left = True
elif event.key == pygame.K_q:
sys.exit()
elif event.key == pygame.K_SPACE:
self._fire_bullet()
elif event.key == pygame.K_s:
self._... | The main task of the code is to handle user input events in a Pygame application. It checks for quit events to exit the game, processes keyboard key presses and releases by calling specific methods, and detects mouse clicks to trigger the play button functionality by passing the mouse position to another method. This f... | def _check_event(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:
self._check_keydown_events(event)
elif event.type == pygame.KEYUP:
self._check_keyup_events(event)
elif event.type == pygame.MOUSEBUTTONDOWN:
mouse_pos = pyg... |
def _check_event(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:
self._check_keydown_events(event)
elif event.type == pygame.KEYUP:
self._check_keyup_events(event)
elif event.type == pygame.MOUSEBUTTONDOWN:
mouse_pos = pyg... | The code defines a game loop that continuously checks for events, updates game elements (ship, bullets, meteors) if the game is active, and renders the screen, maintaining the game's state and visuals in real-time. | def run_game(self):
while True:
self._check_event()
if self.stats.game_active:
self.ship.update()
self._bullet_update()
self._super_bullet_update()
self._meteor_update()
self._screen_update() |
def enemy_targets(enemies):
for x in enemies:
print(str(enemies.index(x)+1) +") " + x.name + " "+ str(x.health) +
"/"+ str(x.MAX_health))
def get_target():
valid_input = False
while (valid_input is False):
print()
choice = input("Who will you target? ")
if (parse_... | The function handles a player's turn in a game, allowing them to attack enemies, use items (heal/harm allies/enemies), or charge enemies. It validates choices, applies damage/healing, and grants experience upon enemy defeat. | def player_turn(player, enemies, heroes, choice):
if(choice == 1):
enemy_targets(enemies)
choice = get_target()
while (choice > len(enemies) or choice < 1):
print("Invalid choice. Try again.")
choice = get_target()
damage = random.r... |
def d(self, x):
return "".join(map(self._dual, x))
def e(self, x):
return x[::-1]
def e_s(self, x):
return self.g(self.i(x)) if self.left(x) <= self.right(x) else self.i(self.g(x)) | The function `d_s` transforms the input `x` by sequentially applying three methods: first `e_s`, then `e`, and finally `d`, returning the result of this chained transformation. | def d_s(self, x):
return self.d(self.e(self.e_s(x))) |
def d(self, x):
return "".join(map(self._dual, x))
def e(self, x):
return x[::-1]
def e_p(self, x):
return self.i(self.g(x)) if self.left(x) <= self.right(x) else self.g(self.i(x)) | The code defines a method `d_p` that transforms an input `x` by sequentially applying three functions: `e_p`, `e`, and `d`. The primary task is to process `x` through these nested operations, likely as part of a neural network or data transformation pipeline. The output is the result of `self.d` applied to the composit... | def d_p(self, x):
return self.d(self.e(self.e_p(x))) |
def side_bar():
with st.sidebar:
game_on_display()
start_game_button()
reset_game_button()
def theme_components():
cols=st.columns(5)
word_button_name=translation.get_button_name('themeWord')
image_button_name=translation.get_button_name('themeImage')
cols[1].button(word_butt... | The main task of the code is to initialize a multilingual game interface by setting up UI components, themes, timer controls, and interactive elements based on the detected language code from the session state, while organizing layout elements like sidebars, alphabet buttons, and game displays. | def main():
global translation
print(st.session_state['language_code'],'---')
translation=translations(st.session_state['language_code'])
side_bar()
theme_components()
display_random_theme()
start_game_display()
set_timer_range()
timer_components()
alphabet_buttons()
lasting... |
def cli_args(self, output_dir) -> list:
args = ""
args += f" -c {self.com_mean}"
args += f" -m {self.msg}"
args += f" -r {self.rate}"
if self.reliability == RELIABILITY.RELIABLE:
args += " --reliable"
if self.durability == DURABILITY.TRANSIENT_LOCAL:
... | This function generates command-line instructions for performance testing based on middleware and transport type. It constructs commands by evaluating arguments, transport (Zero Copy/Shmem), and communication middleware (e.g., RMW Apex, CycloneDDS). It selects appropriate command generation functions, handles unsupport... | def cli_commands(self, perf_test_exe_cmd, output_dir) -> list:
args = self.cli_args(output_dir)
commands = []
if len(args) == 1:
commands.append(perf_test_exe_cmd + args[0])
elif len(args) == 2:
sub_args, pub_args = args
if self.transport == TRANSPORT... |
def getExperiments(yaml_experiments: list) -> 'list[ExperimentConfig]':
experiments = []
for experiment in yaml_experiments:
config_matrix = coerce_dict_vals_to_lists(experiment)
config_combos = config_cartesian_product(config_matrix)
experiment_configs = [ExperimentConfig(**args) for ar... | The main task of the code is to parse log data from experiments defined in a YAML configuration, concatenate results into unified dataframes, and generate structured DatasetConfig objects with theme variations. It processes each dataset by extracting experiments, handling missing logs, creating configuration combinatio... | def getDatasets(yaml_datasets: dict, log_dir) -> dict:
datasets = {}
for dataset_id, dataset_details in yaml_datasets.items():
test_name = dataset_details.get('test_name', DEFAULT_TEST_NAME)
experiments = getExperiments(dataset_details['experiments'])
dataframes = []
headers = []... |
def fetch_block(provider: HTTPProvider, block_num):
w3 = Web3(provider)
w3.toWei
return w3.eth.get_block(block_num)
def trace_block(provider: HTTPProvider, block_num, tracer, timeout=120):
params = [block_num, {
'disableStack': True,
'disableMemory': True,
'disableStorage': True,... | The main task of the code is to trace Ethereum transactions or blocks using a specified tracer (e.g., ac_tracer2), fetch results via an RPC provider, process access lists or opcode data, and output the results as JSON to a file or console. It supports block/tx tracing, customizable tracers, timeout settings, and summar... | def main():
parser = argparse.ArgumentParser(description='Trace helper')
parser.add_argument('--rpc', '-r', help='RPC server url, required', required=True)
parser.add_argument('--tx', help='transaction hash or block number, required', required=True)
parser.add_argument('--tracer', '-t', help='tracer nam... |
def gen_contabs(start_contab):
"""sequentially marginalize contabs as dictated by gen_sets_down"""
n = start_contab.sparse_dim()
contabs = [None]*(n+1)
contabs[n] = (tuple(range(n)), start_contab)
yield contabs[n]
start_bitset = (1<<n)-1
for var_count, x in gen_sets_down(start_bitset, n):
... | The function computes local scores for given data using a specified scorer, incorporating constraints from 'musts' and 'bans'. It generates contingency tables, derives conditional tables, calculates scores, and returns processed results. | def data2local_scores(valcounts, data, scorer, musts={}, bans={}):
contabs = gen_contabs(data)
condtabs = gen_condtabs(contabs, valcounts)
local_scores = gen_local_scores(condtabs, scorer, musts, bans)
return get_local_scores(local_scores) |
def gen_lorenz_data(num_samples, normalize=True):
integration_dt = 0.005
data_dt = 0.025
skipped_samples = 1000
T = (num_samples + skipped_samples) * data_dt
X = gen_lorenz_system(T, integration_dt)
if normalize:
X -= X.mean(axis=0)
X /= X.std(axis=0)
X_dwn = resample(X, num_... | The code generates synthetic data by embedding Lorenz dynamics into a high-dimensional space, adding noise at varying SNR levels, and comparing DCA and PCA reconstructions of the original dynamics. It saves parameters, noisy data, and transformed projections for analysis across different signal-to-noise ratios. | def generate_syn(T, N, noise_dim, snr_vals, num_samples=10000, random_seed=42):
"""
:param T: window size of DCA
:param N: dimension of observations
:param noise_dim: dimension of subspace for noise
:param snr_vals: signal-noise ratio
:param num_samples: number os time stamps
:param random_s... |
def decoderscores(x_mean, x_vars, x, threshold=1e-6, debug=False):
"""
:param x_mean: batch_size x x_dim
:param x_vars: batch_size x x_dim
:param x: batch_size x x_dim
:return: scores batch_size x batch_size
"""
batch_size = x.shape[0]
x_mean_tiled = torch... | The function `estimate_mutual_information` computes variational lower/upper bounds on mutual information between variables `x` and `y` using specified estimators (e.g., NWJ, InfoNCE, TUBA, MINE). It leverages critic scores, decoders, or baselines to calculate the estimate, returning a scalar value. The method adapts to... | def estimate_mutual_information(estimator, x, y, critic_fn=None, baseline_fn=None, decoder=None, device='cuda:0', debug=False, *args, **kwargs):
"""
Estimate variational lower/upper bounds on mutual information.
:param estimator: string specifying estimator, one of: 'nwj', 'infonce_lower', 'infonce_upper', ... |
def normalize(X):
Minimum = np.amin(X, axis=1, keepdims=True)
Maximum = np.amax(X, axis=1, keepdims=True)
return (X - 0.5 * (Minimum + Maximum)) / (0.5 * (Maximum - Minimum))
def initialize_graphs(Ws, Bs, X, Y, boundry_samples):
min_x = np.amin(X, axis=1)
max_x = np.amax(X, axis=1)
length = max_x - min_x
... | The code implements gradient descent optimization for a neural network, training it to minimize loss by iteratively updating weights (Ws) and biases (Bs) using backpropagated gradients. It normalizes input data, visualizes the decision boundary and loss curve during training, and prints iteration progress including los... | def run_gradient_descent(X, Y, initial_Ws, initial_Bs, learning_rate, iterations):
# fixes the exploding gradient problem and speeds up learning
Xn = normalize(X)
Ws = initial_Ws
Bs = initial_Bs
losses_axis = []
iterations_axis = []
boundry_samples = 50
fig, axs, boundary_graph, loss_graph, boundary_... |
def normalize(X):
Minimum = np.amin(X, axis=1, keepdims=True)
Maximum = np.amax(X, axis=1, keepdims=True)
return (X - 0.5 * (Minimum + Maximum)) / (0.5 * (Maximum - Minimum))
def initialize_graphs(W, b, X, Y, boundry_samples):
min_x = np.amin(X, axis=1)
max_x = np.amax(X, axis=1)
length = max_x - min_x
... | The code performs gradient descent optimization for logistic regression, normalizing input data, updating weights and bias iteratively using calculated gradients, and visualizing the decision boundary and loss progression. It prints loss and accuracy every 10 iterations, updating graphs dynamically to monitor model per... | def run_gradient_descent(X, Y, initial_W, initial_b, learning_rate, iterations):
# fixes the exploding gradient problem and speeds up learning
Xn = normalize(X)
W = initial_W
b = initial_b
losses_axis = []
iterations_axis = []
boundry_samples = 50
fig, axs, boundary_graph, loss_graph, boundary_X = in... |
def normalize(X):
Minimum = np.amin(X, axis=1, keepdims=True)
Maximum = np.amax(X, axis=1, keepdims=True)
return (X - 0.5 * (Minimum + Maximum)) / (0.5 * (Maximum - Minimum))
def initialize_graphs(W, b, X, Y, boundry_samples):
min_x = np.amin(X, axis=1)
max_x = np.amax(X, axis=1)
length = max_x - min_x
... | This function performs gradient descent optimization for a logistic regression model, updating weights (W) and bias (b) iteratively to minimize the loss. It normalizes input data, computes predictions using the sigmoid function, calculates gradients, and adjusts parameters via the learning rate. The process includes vi... | def run_gradient_descent(X, Y, initial_W, initial_b, learning_rate, iterations):
# fixes the exploding gradient problem and speeds up learning
Xn = normalize(X)
W = initial_W
b = initial_b
losses_axis = []
iterations_axis = []
boundry_samples = 50
fig, axs, boundary_graph, loss_graph, boundary_X = in... |
def angle(center, point):
"""Return the angle (radian) of point from center of the radian circle.
------p
| /
| /
c|a/
"""
dx = point.x - center.x
dy = point.y - center.y
if dx == 0:
if dy < 0:
return pi * 3 / 2
return pi / 2
if dy == 0:
... | The function determines which points in a graph are visible from a given point, considering obstacles (edges) and polygon boundaries. It checks visibility by sorting points by angle, managing intersecting edges, and handling collinear cases. The 'scan' parameter allows partial checks for efficiency in visibility graph ... | def visible_vertices(point, graph, origin=None, destination=None, scan='full'):
"""Returns list of Points in graph visible by point.
If origin and/or destination Points are given, these will also be checked
for visibility. scan 'full' will check for visibility against all points in
graph, 'half' will c... |
def edge_distance(p1, p2):
"""Return the Euclidean distance between two Points."""
return sqrt((p2.x - p1.x)**2 + (p2.y - p1.y)**2)
def unit_vector(c, p):
magnitude = edge_distance(c, p)
return Point((p.x - c.x) / magnitude, (p.y - c.y) / magnitude)
def point_in_polygon(p, graph):
"""Return true if ... | The function `closest_point` computes the nearest point on a polygon's edge to an interior point `p`, then extends this point outward by a specified `length` to lie outside the polygon. It first identifies the closest edge point using projection, adjusts for edge endpoints, and calculates the direction vector. For vert... | def closest_point(p, graph, polygon_id, length=0.001):
"""Assumes p is interior to the polygon with polygon_id. Returns the
closest point c outside the polygon to p, where the distance from c to
the intersect point from p to the edge of the polygon is length."""
polygon_edges = graph.polygons[polygon_id... |
def generate_image(brompt):
response = openai.Image.create(
prompt=brompt,
n=1,
size="1024x1024",
)
print(response["data"][0]["url"])
generate_file(response["data"][0]["url"], brompt)
def generate_distances(word):
local_dict = {}
for k in word_vecs:
added = 0
... | The code reads a text file line by line, using each line as a prompt to generate images. It extracts the first and second words of each prompt, computes distance arrays for these words, generates order arrays from the distances, and writes these orders to text files. The process iterates through all lines, printing lin... | def generate_from_text(filename):
with open(filename, "r") as file:
lines = file.readlines()
for i, line in enumerate(lines):
PROMPT = line
print (i)
print (PROMPT)
generate_image(PROMPT)
distance_array_1 = generate_distances(get... |
def read_config(self):
if os.path.exists(self.config_file):
with open(self.config_file, 'r') as f:
self.config = yaml.safe_load(f)
else:
self.config = {'mode': 2, 'circuits': {}}
return self.config
def setup_events(self):
for circuit_name in self.c... | The code initializes a system by reading configuration settings, setting up GPIO handling, starting an event scheduler, and registering events like LED blinking. It configures hardware interaction and event management for automated tasks. | def __init__(self, config_file=CONFIG_FILE):
self.config_file = config_file
self.read_config()
self.gpio_handler = GPIOHandler()
self.event_scheduler = EventScheduler()
self.event_scheduler.start()
self.events = {}
self.setup_events()
self.add_led_blink_... |
def parse_args():
parser = argparse.ArgumentParser()
# Names, paths, logs
parser.add_argument("--ckpt_path", default="./ckpt")
parser.add_argument("--log_path", default="./log")
parser.add_argument("--task_name", default="test")
# Data parameters
parser.add_argument("--a_dim", default=74, ... | The code trains a machine learning model for a task (classification/regression) by iterating over epochs, performing training and evaluation on datasets, logging metrics, and saving the best model based on validation/test accuracy. It initializes the model, optimizer, and data loaders, manages GPU/parallel settings, tr... | def main():
opt = parse_args()
# Set random seed
random.seed(opt.seed)
np.random.seed(opt.seed)
torch.manual_seed(opt.seed)
torch.cuda.set_device("cuda:" + opt.cuda)
# Set Logger
os.makedirs(os.path.join(opt.ckpt_path, opt.task_name), exist_ok=True)
os.makedirs(os.path.join(opt.log... |
def getFriends(self):
return self.friends
def addBook(self, book):
''' adds the book if they don't already have it'''
if self.hasBook(book):
print("This person already has that book")
else:
self.getBooks().append(book)
if self.getBookHistory().find(boo... | This code transfers a specified book from a friend's collection to the current person (self), removes it from the friend, adds it to self, and updates the book's rating and annotation status based on user input. | def giveBook(self, book):
''' removes the book from the person who has it and adds it to self'''
curr_person = self.getFriends().getFront()
for i in range(self.getFriends().getSize()):
curr_book = curr_person.getData().getBooks().getFront()
for j in range(curr_person.getD... |
def setup_default_scene(scene_data, texture=None):
mesh_root_path = ''
loader = DictLoader(scene_data, mesh_root_path)
entity_list = loader.entity_list # list of entities to export
create_bin(scene_data['scene']['table_dims'])
scene.add_default_camera()
set_assigned_materials(scene_data, textur... | The code generates a synthetic 3D dataset by randomly arranging and transforming 3D mesh objects from specified groups into scenes, applying textures, rendering images/depth maps, and saving them in HDF5 files. It handles object scaling, rotation, spacing, random removals, and sharding for efficient storage. | def generate_dataset(args, folders, n, shard_prefix=''):
# Group by the first two components of the name
groups = defaultdict(list)
for x in folders:
groupname = '_'.join(x.split('_')[:2])
groups[groupname].append(x)
current_shard = 0
current_shard_size = 0
h5_file = None
... |
def __get_parent_index(self, i):
"""Find the index in the array of the element which is the parent of element[i] """
return (i - 1)//2
def __check_heap_property(self, index):
"""check heap propert is ok at index 'index' """
elt = self.elements[index]
children = self.__get_childre... | This code inserts a new node into a heap structure by appending it to the list and then bubbling it up to maintain the heap property. It swaps the node with its parent until the heap property is satisfied, ensuring the structure remains valid. | def insert(self, node):
""" insert new node """
current_len = len(self.elements)
# add it
self.elements.append(node)
index = current_len
parent_index = self.__get_parent_index(index)
# cheeck heap property is ok
while parent_index >= 0 and not self.__check... |
def get_size(self):
"""total size"""
return len(self.elements)
def __check_heap_property(self, index):
"""check heap propert is ok at index 'index' """
elt = self.elements[index]
children = self.__get_children(index)
#get the children and find ones that are wrong
... | The code removes the minimum element from a heap by replacing it with the last element, popping the last element, and then bubbling down the new root to restore the heap property. It checks and swaps with the smaller child until the heap property is satisfied, ensuring efficient removal while maintaining the structure. | def remove(self):
""" remove the top (min) element """
num_elements = self.get_size()
if num_elements == 0:
return None
else:
root = self.elements[0]
last = self.elements[-1]
self.elements[0] = last
self.elements.pop()
... |
def train_epoch(self):
self.model.train()
epoch_loss = 0
tot_len = len(self.train_dataloader)
for idx, batch in enumerate(self.train_dataloader):
idx += 1
loss = self.get_loss(batch)
loss.backward()
if idx % self.iters_to_accumulate == 0... | The main task of the code is to train a machine learning model over multiple epochs, recording training and validation metrics, adjusting the learning rate via a scheduler, and implementing early stopping based on validation loss. The code saves the best model checkpoint when validation loss improves, resets patience c... | def train(self):
records = []
best_loss = float('inf')
patience = self.patience
for epoch in range(1, self.n_epochs + 1):
start_time = time.time()
record_vals = [epoch, self.train_epoch(), self.valid_epoch(),
self.optimizer.param_grou... |
def select(query, params=None):
conn = db_connect()
# create a cursor object to interact with the database
cursor = conn.cursor()
# execute the query
cursor.execute(query, params)
result = cursor.fetchone()
# close the cursor and the connection
cursor.close()
db_disconnect(conn)
return resul... | The function retrieves flight details (date, time, duration) for each ID, calculates flight time windows, filters corresponding weather data from a DataFrame, inserts this data into a PostgreSQL database, and links it to flights. It processes multiple flights, appending weather data to a table and establishing flight-w... | def relevant_weather(df, id_list):
id_query = "SELECT flight_date, flight_time_utc FROM flights WHERE id= %s"
# loop through each id and get the flight date and time
for id in id_list:
flight_info = select(id_query, (id,))
current_date = flight_info[0]
current_time = flight_info[1]
# query how lon... |
def normpath(pathname):
"""
normpath
"""
if not pathname:
return ""
return os.path.normpath(pathname.replace("\\", "/")).replace("\\", "/")
def filectime(filename):
"""
filectime - get the creation date
"""
if os.path.isfile(filename) or os.path.isdir(filename):
unixt... | This function recursively lists directories within a specified path, filtering by a regex pattern, and sorts them by name or creation time. It returns a list of matching directory paths, optionally including subdirectories if recursion is enabled. | def listdir(dirname=".", filter=r'.*', recursive=True, sortby="name"):
"""
listdir - list all directoriesin dirname
"""
res = []
dirname = normpath(dirname)
if os.path.isdir(dirname):
try:
# Some dir could not be accessible
items = os.listdir(dirname)
... |
def randcolor(alpha=255):
"""
randcolor
"""
return (randint(255), randint(255), randint(255), alpha)
def singleSymbol( options ):
return {
"type": "singleSymbol",
"forceraster": 0,
"symbollevels": 0,
"enableorderby": 0,
"symbols": {"symbol": SimpleLine(option... | The function `renderer_v2` generates a renderer configuration for geometric features (POINT, LINE, POLYGON) based on input geometry type and optional styling parameters. It returns a dictionary with properties like symbol type, color, size, and style, defaulting to single-symbol renderers. For LINE and POLYGON, it chec... | def renderer_v2(geomtype="POINT", options=None):
geomtype = upper(geomtype)
if geomtype == "POINT":
return {
"forceraster": 0,
"symbollevels": 0,
"type": "singleSymbol",
"enableorderby": 0,
"symbols": {
"symbol": {
... |
def remove(files, env={}):
"""
remove
"""
res=True
if isinstance(files, str) and "*" in files:
files = sformat(files,env)
files = glob.glob(files)
for item in listify(files):
item = sformat(item, env)
try:
if os.path.isfile(item):
os.r... | The function renames a file from 'filesrc' to 'filedest', overwriting the destination file if it exists and 'overwrite' is True. It creates necessary directories for the destination path and handles exceptions, returning True on success or False on failure. | def rename(filesrc, filedest, overwrite=True):
"""
rename
"""
try:
if file(filedest) and overwrite:
remove(filedest)
mkdirs(justpath(filedest))
os.rename(filesrc, filedest)
return True
except Exception as ex:
print(ex)
return False |
def singlebandgray(minValue, maxValue):
return {
"brightnesscontrast": {"brightness": 0, "contrast": 0},
"huesaturation": {"colorizeBlue": 128, "colorizeGreen": 128,
"colorizeOn": 0, "colorizeRed": 255, "colorizeStrength": 255, "grayscaleMode": 0,
... | This function processes raster and vector files to generate a map layer configuration dictionary. It handles geospatial metadata, projections, extent, data types, and styling options for GDAL/OGR layers. For rasters, it reads geotransforms, adjusts coordinate systems, and applies rendering pipelines. For vectors, it ex... | def GDAL_MAPLAYER(filename, layername=None, options=None):
"""
GDAL_MAPLAYER
"""
maplayer = {}
if "|" in filename:
filename, layerid = filename.split("|", 1)
layerid = leftpart(layerid, "|") # if any other |
_, layerid = layerid.split("=", 1)
layerid = int(layerid)
... |
def _put(self, path, data):
return self._http('PUT', path, True, data)
def _XmlBuild(self, ElementType, ElementData, WithHeaders=True): # noqa
xml = ""
if WithHeaders:
xml += "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
xml += "<osm version=\"0.6\" generator=\""
... | This function handles uploading OpenStreetMap (OSM) data to a server by performing create, modify, or delete actions based on the 'action' parameter. It ensures a changeset is open, removes timestamps, adds the changeset ID, and sends HTTP requests. For 'create', it validates non-existence of the OSM object before crea... | def _do_manu(self, action, OsmType, OsmData):
if not self._CurrentChangesetId:
raise Exception(
"You need to open a changeset before uploading data"
)
if "timestamp" in OsmData:
OsmData.pop("timestamp")
OsmData["changeset"] = self._CurrentChang... |
def _DomGetAttributes(self, DomElement): # noqa
"""
Returns a formated dictionnary of attributes of a DomElement.
"""
result = {}
for k, v in DomElement.attributes.items():
if k == "uid":
v = int(v)
elif k == "changeset":
v... | The function `_DomParseChangeset` parses a DOM element into a `ChangesetData` dictionary by extracting attributes, tag, and discussion information, then returns the aggregated data. | def _DomParseChangeset(self, DomElement):
"""
Returns ChangesetData for the changeset.
"""
result = self._DomGetAttributes(DomElement)
result["tag"] = self._DomGetTag(DomElement)
result["discussion"] = self._DomGetDiscussion(DomElement)
return result |
def _DomGetAttributes(self, DomElement): # noqa
"""
Returns a formated dictionnary of attributes of a DomElement.
"""
result = {}
for k, v in DomElement.attributes.items():
if k == "uid":
v = int(v)
elif k == "changeset":
v... | The main task of the code is to parse a DOM element into a RelationData structure by extracting attributes, tag, and member information from the provided DomElement. It aggregates these values into a dictionary and returns it for relation data representation. | def _DomParseRelation(self, DomElement):
"""
Returns RelationData for the relation.
"""
result = self._DomGetAttributes(DomElement)
result["tag"] = self._DomGetTag(DomElement)
result["member"] = self._DomGetMember(DomElement)
return result |
def ChangesetCreate(self, ChangesetTags={}):
"""
Opens a changeset.
If `ChangesetTags` are given, this tags are applied (key/value).
Returns `ChangesetId`
"""
if self._CurrentChangesetId:
raise Exception("Changeset already opened")
if "created_by" no... | This function manages automatic flushing of data in a changeset. It uploads data in chunks of size `autosize`, creates a new changeset when needed, and closes it after a specified number of uploads (`automulti`). If `force` is True, it ensures all remaining data is flushed. The process repeats until the data buffer is ... | def _changesetautoflush(self, force=False):
autosize = self._changesetautosize
while ((len(self._changesetautodata) >= autosize) or
(force and self._changesetautodata)):
if self._changesetautocpt == 0:
self.ChangesetCreate(self._changesetautotags)
... |
def _DomParseNode(self, DomElement):
"""
Returns NodeData for the node.
"""
result = self._DomGetAttributes(DomElement)
result["tag"] = self._DomGetTag(DomElement)
return result
def _DomParseWay(self, DomElement):
"""
Returns WayData for the way.
"... | The main task of the code is to parse OpenStreetMap (OSM) XML data into a structured list of dictionaries. Each dictionary contains an element type ("node", "way", or "relation") and its parsed data, extracted using DOM parsing. The function processes child nodes of the root "osm" element, delegating detailed parsing t... | def ParseOsm(self, data):
"""
Parse osm data.
Returns list of dict:
#!python
{
type: node|way|relation,
data: {}
}
"""
data = xml.dom.minidom.parseString(data)
data = data.getElementsByTagName("osm")[0]... |
def _DomParseNode(self, DomElement):
"""
Returns NodeData for the node.
"""
result = self._DomGetAttributes(DomElement)
result["tag"] = self._DomGetTag(DomElement)
return result
def _DomParseWay(self, DomElement):
"""
Returns WayData for the way.
"... | The main task of the code is to parse OSM Change (XML) data into a structured list of dictionaries. Each dictionary represents an action (create/delete/modify) on a node, way, or relation, containing its type and parsed data. The function processes XML elements, skips text nodes, and uses helper methods to extract deta... | def ParseOsc(self, data):
"""
Parse osc data.
Returns list of dict:
#!python
{
type: node|way|relation,
action: create|delete|modify,
data: {}
}
"""
data = xml.dom.minidom.parseString(data)
... |
def csv_reader():
global booklist
try:
with open("books.csv") as file:
reader = csv.reader(file)
for row in reader:
booklist.append(Book(row[0], row[1], row[2], row[3]))
except:
with open("books.csv", "w") as file:
pass
def menu_number_vali... | The main task of the code is to run a book tracker application that allows users to manage their book collection via a menu-driven interface. It repeatedly displays options for viewing books, adding/deleting books, updating page numbers, adding notes, rating books, or exiting. User inputs are validated and trigger corr... | def main():
csv_reader()
while True:
print("WELCOME TO BOOK TRACKER!!! :)")
print(' Enter "1" to view books, page numbers, notes, and ratings')
print(' Enter "2" to add a book')
print(' Enter "3" to delete a book')
print(' Enter "4" to change the page ... |
def _search_rom(self, seed: bytearray) -> tuple: # (bytearray, array)
"""Internal routine used by scan for device discovery; works like DS2480B w/o interleaving"""
if self.reset(True): # False when any devices present; tests for stuck bus
return None, None
# set search mode: read ... | This function scans a one-wire bus for connected devices, resolving address conflicts by branching through possible device addresses. It returns a list of valid multi-format device addresses, optionally filtered by a specified family code. The scan uses a binary tree search approach, starting from all-zero addresses, a... | def scan(self,family=None) -> list:
"""Scan bus for devices present and return a list of valid multi-format addresses for each."""
# if family defined, searches only for devices matching that family.
# searches "zero branch" first; i.e. left-to-right binary tree
# walks back con... |
def is_asset_downloaded(asset_name):
return os.path.exists(get_asset_path(asset_name))
def get_asset_url(asset_name):
return _get_asset(asset_name)["url"]
def get_asset_path(asset_name):
return os.path.join(get_asset_dir(), _get_asset(asset_name)["filename"])
def is_asset_executable(asset_name):
return ... | The code's main task is to download an asset if it hasn't been downloaded yet. It checks the download status, prints a message if downloading, and uses `download_file` with the asset's URL, file path, and executable-specific permissions (0o775) to fetch and save the asset. | def download_asset(asset_name):
if not is_asset_downloaded(asset_name):
print(f"downloading asset: {asset_name}")
download_file(
url=get_asset_url(asset_name),
filename=get_asset_path(asset_name),
mode=0o775 if is_asset_executable(asset_name) else None
) |
def create_order(self, domains: List[str]) -> ACMEOrder:
resp = self.transport.post(
url=self.server + ACME_ENDPOINT_NEW_ORDER,
content={
"identifiers": [{"type": "dns", "value": domain} for domain in domains]
},
)
# we are interested in the a... | This code handles DNS-01 ACME challenges for given domains by creating DNS records, notifying the ACME server, and waiting for validation. It generates key authorizations, updates DNS zones, and ensures all challenges are fulfilled before stopping the DNS server and returning the finalized order. | def dns_challenge(self, domains: List[str]) -> ACMEOrder:
order = self.create_order(domains)
self.dns = ACMEDNS()
for auth in order.authorizations:
# we need to fulfill all authorizations here
authorization = self.get_authorization(auth)
domain = authorization... |
def create_order(self, domains: List[str]) -> ACMEOrder:
resp = self.transport.post(
url=self.server + ACME_ENDPOINT_NEW_ORDER,
content={
"identifiers": [{"type": "dns", "value": domain} for domain in domains]
},
)
# we are interested in the a... | The code handles ACME HTTP-01 challenges by creating an order, configuring DNS, generating challenge tokens, launching a server to respond to ACME validation requests, and waiting for all challenges to be validated. It then stops the DNS server and returns the finalized order. | def http_challenge(self, domains: List[str], record: str) -> ACMEOrder:
order = self.create_order(domains)
dns_zone = build_http_challenge_zones(domains, record)
self.dns = ACMEDNS(dns_zone)
self.dns.start()
tokens = dict() # type: Dict[str, Dict[str, str]]
for auth in ... |
def __edit(self, resource, body, id=None):
old_version = self.__get(resource, id)
for key in body:
old_version[key] = body[key]
status_code = self.r.put(self.__url(resource, id), json=old_version).status_code
if id:
id_string = ' {}'.format(id)
else:
... | This function processes nested data structures by recursively applying operations. If the input is a dictionary with nested dicts/lists, it traverses each key, appending it to the resource path. For non-nested dicts, it calls `__edit`, and for non-dict iterables, it iterates and calls `__create` on each element, using ... | def __triage_and_apply(self, object, resource=''):
if isinstance(object, dict):
if any(isinstance(object[key], (dict, list)) for key in object):
for key in object:
self.__triage_and_apply(object[key], '{}/{}'.format(resource, key))
else:
... |
def create_patient():
#set variable to help with error checking - to determine if an instance of the Patient class has been created
patient_exists = False
#create variable to determine if the user wants default or custom data
#set to default 'n' to align with original assignment
c_patient... | The main task of the code is to allow users to input or select patient and procedure data, display the information, and repeat the process. It creates a Patient object, offers default or custom procedure entries, stores procedures in a list, and displays patient/procedure details. The loop enables repeated execution un... | def main():
#set variable to loop the program
again = 'y'
while again == 'y':
#create variable to determine if the user wants default or custom data
#set to default 'n' to align with original assignment
c_procedure = 'n'
#Create an empty list to store procedures in
... |
def find_impt_number(phrase):
valid_number = False
wordList = phrase.split()
wordList_length = len(wordList)
number = 0
if "calories" in wordList:
for i in range(wordList_length):
if wordList[i] == "calories":
number = int(wordList[i-1])
valid_num... | The code processes phrases from an SRT file to extract numerical values and determine coordinates in an SVG file. It identifies three cases: "spike/max/mode" (finding peaks), "more than" (drawing rectangles from a start coordinate to the end), and "fewer than" (drawing rectangles between start and end coordinates). It ... | def main():
#Read the SRT file
srtFile = open('prototype/output.txt')
phrases_in_file = srtFile.readlines()
# #take in a string, convert to lowercase
# phrase = str(input("Input a phrase: "))
# phrase = phrase.lower()
# number = 0
#open the SVG file and read it line by line
sv... |
def configure(auto=None, path=None, version=None, pandoc_types_version=None):
global _configuration
# In the default configuration, we set auto to `True`.
if auto is None and \
path is None and \
version is None and \
pandoc_types_version is None:
auto = True
if auto is Tru... | This function converts a document into various formats (e.g., markdown, JSON, doc, epub) using pandoc, writes it to a temporary file, handles binary/text outputs, and returns the result while cleaning up temporary files. | def write(doc, file=None, format=None, options=None):
if _configuration is None:
configure()
if options is None:
options = []
tmp_dir = tempfile.mkdtemp()
filename = None
if file is not None and not hasattr(file, 'write'):
filename = file
file = open(filename, 'wb')
... |
def __add_max_strenght_properties(self, *varargs:list[list or np.ndarray], cntrl_shear:bool=False):
'''
# DESCRIPTION:
Internal method to exctract and store the strenght properties
# INPUTS:
## Required
- *varargs: n block each containing the strenght values of the laminate. The number o... | The code's main task is to verify a laminate's ply stackup and identify the first failing ply under given loads using failure criteria (Tsai-Wu, MaxStress, or MaxStrain). It calculates in-plane and out-of-plane stresses, compares them against material strength/strain limits, and computes margins, reserve factors, and f... | def FPF(self, *varargs:list[list or np.ndarray], N_in:list or np.array, M_in:list or np.array, \
print_stress_state:bool=False, V_in:str or np.array='None', criteria:str='TsaiWu', F12:float or int="-.5/(FxtFxcFytFyc)**.5", \
print_margins:bool=False, cntrl_external_actions:int=0, T_in:int or float=0... |
def __round(self, input:float or int, digits:int = 3, lower_limit:float = 1e-22) -> float or int:
'''
# DESCRIPTION:
this method is used to round the output values. Independetly on the number of zeros the final digits are always the same. e.g. 10.3454 -> 10.34, 1.3454 -> 1.34, 0.0013454 -> 0.00134
# I... | The code initializes a laminate structure by processing input ply blocks, validating their mechanical properties, converting units (GPa/MPa), and computing stiffness matrices (Q, Qbar, A, B, D) for classical laminated theory (CLT) and first-order shear deformation theory (FSDT). It organizes ply data, calculates thickn... | def __init__(self, *varargs:list[str, list or np.ndarray, list or np.ndarray], mech_prop_units:str='GPa', hide_text:bool=False):
'''
# DESCRIPTION:
In the init method the single plies are defined and their properties exctracted
# INPUTS:
## Required
- *varargs: variable number of three-... |
def advance(self):
self.pos += 1
if self.pos < len(self.tokens):
self.current_token = self.tokens[self.pos]
else:
self.current_token = None
def expression(self):
"""
Handles the parsing of expressions.
"""
return self.binary_operation(self.... | This function parses variable declarations with optional type annotations and initializations. It processes a variable name, checks for a type keyword using 'as', and handles assignment with expressions, literals, or input prompts. It constructs VarAssignNode (with value) or VarDeclNode (without value) based on presenc... | def var_declaration(self):
# Assume current token is the variable identifier
var_name = self.current_token[1]
self.advance() # Consume identifier
if self.current_token is not None and self.current_token[1] == "as":
self.advance() # Consume 'as'
if self.current_... |
def advance(self):
self.pos += 1
if self.pos < len(self.tokens):
self.current_token = self.tokens[self.pos]
else:
self.current_token = None
def expression(self):
"""
Handles the parsing of expressions.
"""
return self.binary_operation(self.... | This code parses a "factor" in an expression, handling numbers, variables, parenthesized expressions, and unary operators. It advances tokens, constructs AST nodes (NumberNode, VarAccessNode), and recursively processes sub-expressions. The TODO indicates incomplete handling of unary operations, which should return a Un... | def factor(self):
"""
Parses a factor which can be a number, a variable, or an expression in parentheses.
"""
token = self.current_token
if token[0] in (TT_PLUS, TT_MINUS): # Unary plus or minus
self.advance()
factor = self.factor()
# TODO: re... |
def displayMenu():
print("\n-------------------- WELCOME ! --------------------")
# Display drinks
print("\n- BEVERAGE")
for code, item in items.items(): # For loop to loop through the items that are categorised as drink
if item["itemCategory"] == "Drink":
print(f"{item['itemID']}: ... | The code defines a function `begin()` that displays a menu with two options: starting a selection process or quitting. It validates user input, executes corresponding actions (e.g., calling `userSelection()` for option "1" or exiting for "0"), and handles invalid inputs by prompting retry or exit. If invalid input is e... | def begin():
displayMenu() # Callback to function to display menu
print("\n--------------------")
print("1: Begin selection")
print("0: Quit")
print("--------------------")
option = (input("- Please enter: ")) # User input to start selection of items
# Conditional statements to validate user in... |
def payload_connection(data_readed):
with grpc.insecure_channel('srv_persistor:50051') as channel:
stub = sales_record_pb2_grpc.SalesRecordStub(channel)
request = sales_record_pb2.PayloadRequest(payload=str(data_readed))
result = stub.SendSalesPayload(request)
print(f'result:{resu... | The main task of the code is to read data from a file repository based on an environment variable, process it using different connection modes (payload, unary, or stream) determined by another environment variable, and measure the execution time. The code initializes a file repository, reads data, checks the connection... | def main():
file_repository = FileRepository(os.environ["DIR_FILE"])
data_readed = file_repository.read_data()
conn_mode = os.environ["CONNECTION_MODE"]
start_time = time.time()
if(conn_mode=="0"):
print("Ping start!")
payload_connection(data_readed)
print("Ping finish!") ... |
def sample_dpp(evalue, evector, k=None):
"""
sample a set Y from a dpp. evalue, evector are a decomposed kernel, and k is (optionally) the size of the set to return
:param evalue: eigenvalue
:param evector: normalized eigenvector
:param k: number of cluster
:return:
"""
if k == None:
... | The function initializes weights for a polytope in machine learning, supporting methods like DPP (Determinantal Point Process), random hyperplane, random assignment, and k-means. For DPP, it generates weight vectors by subtracting control/patient samples, computes a kernel matrix, samples eigenvalues/vectors, and assig... | def hydra_init_weight(X, y, k, index_pt, index_cn, weight_initialization_type):
"""
Function performs initialization for the polytope of mlni
Args:
X: the input features
y: the label
k: number of predefined clusters
index_pt: list, the index for patient subjects
index... |
def validate_bot_choice_input(input):
if input not in ['Y', 'N']:
print_chars("Hmm, let's try again. Please type 'Y' to use Hari's Wordle Bot while playing, or 'N' if you would like to play without using Hari's Wordle Bot: \n")
return validate_bot_choice_input(input())
return input
def get_sec... | The main task of the code is to initialize and start a Wordle game, allowing users to choose whether to play with a bot assistant. It retrieves a secret word, validates input, and enters a main game loop with parameters determined by user choice and debug mode, while handling invalid inputs by raising exceptions. | def play_game(debug):
print_chars("Let's play Wordle!\n")
print_chars("Would you like to play with Hari's Wordle Bot? (Y/N)\n")
bot_choice = validate_bot_choice_input(input())
if bot_choice == 'Y' or bot_choice == 'N':
secret_word = get_secret_word()
if debug:
print_chars("S... |
def get_candidate_starter_words(num_words):
random_candidate_start_words = random.sample(CANDIDATE_STARTER_WORDS[1:], num_words)
return [CANDIDATE_STARTER_WORDS[0]] + random_candidate_start_words
def update_tracking_maps(guess_word, clue_str, possibilities_map, known_letters_map):
yg_letters = []
y_lett... | The function suggests the next optimal guess word for a Wordle game by analyzing previous guesses, updating tracking maps, narrowing down possible words, and selecting the best candidate. If only one word remains, it reveals the solution. Otherwise, it recommends top options to maximize information gain in subsequent g... | def suggest_next_guess_word(guess_number, guess_word, clue_str, possibilities_map, known_letters_map, possible_words):
if guess_number == 1:
next_guess_words = get_candidate_starter_words(10)
best_guess_word = next_guess_words[0]
else:
print_chars(BOT_SPEAKING + "Give me a second to thin... |
def update_tracking_maps(guess_word, clue_str, possibilities_map, known_letters_map):
yg_letters = []
y_letters = []
for i in range(0, len(clue_str)):
result = clue_str[i]
letter = guess_word[i]
if result == 'B':
# remove letter from possibilities map unless the letter is... | This code tests a bot's ability to guess secret words by simulating guesses against a list of candidate words. It tracks the number of guesses required for each secret word, calculates an average guess count, and determines the win rate (success within 6 guesses). The bot uses clue feedback, possibility maps, and memoi... | def test_bot():
print("Testing Bot....")
results = []
guess_memo_table = {}
# sampled_candidate_secret_words = random.sample(CANDIDATE_SECRET_WORDS, 200)
for secret_word in CANDIDATE_SECRET_WORDS:
guess_number = 1
guess_word = CANDIDATE_STARTER_WORDS[0]
clue_str = get_result_... |
def validate_secret_word(secret_word):
if secret_word not in CANDIDATE_SECRET_WORDS:
print_chars("Hmm, " + secret_word + " is not a a valid secret word. Try choosing another word: \n")
return validate_secret_word(input())
return secret_word
def update_tracking_maps(guess_word, clue_str, possibil... | The function enables Hari's Wordle Bot to guess a user-provided secret word within six attempts. It starts with a predefined guess, updates possible words based on user feedback (G/Y), and iteratively selects the next optimal guess. If the bot successfully identifies the word, it announces the victory; otherwise, it ad... | def play_against_bot():
print_chars("Go ahead and choose a secret word for Hari's Wordle Bot to guess:\n")
secret_word = validate_secret_word(input())
possible_words = CANDIDATE_SECRET_WORDS
possibilities_map = init_possibilities_map()
known_letters_map = {}
guess_number = 1
guess_result = '... |
def validate_guess_result(guess_result):
if len(guess_result) != 5:
print_chars("Hmm, " + guess_result + " is not a five letter string containing only 'B', 'G', and 'Y'. Try entering the result again: \n")
new_guess_result = input()
return validate_guess_result(new_guess_result)
for lett... | This function guides a Wordle game by processing user guess outcomes, updating possible word lists based on feedback, and recursively suggesting or prompting the next guess until the user wins or exhausts all attempts. | def main_loop(guess_word, guess_number, possibilities_map, known_letters_map, possible_words):
print_chars("How did your " + ORDINAL_NUMBERS_STRING_MAP[guess_number] + " guess go? (Type 'B' for blank, 'G' for green, and 'Y' for yellow)\n")
guess_result = validate_guess_result(input())
if guess_result == 'GG... |
def get_candidate_starter_words(num_words):
random_candidate_start_words = random.sample(CANDIDATE_STARTER_WORDS[1:], num_words)
return [CANDIDATE_STARTER_WORDS[0]] + random_candidate_start_words
def validate_word(word):
if word not in CANDIDATE_GUESS_WORDS:
print_chars("Hmm, " + word + " is not a f... | The main task of the code is to initiate a bot that interacts with the user by presenting candidate starter words, prompting the user to select or input a word, validating the choice, and then launching a main processing loop with the selected word and initial parameters for further interaction or game logic. | def start_bot():
candidate_starter_words = get_candidate_starter_words(10)
print_chars(BOT_SPEAKING + "Hello!\n")
print_chars(BOT_SPEAKING+ "Let's get started by giving you a few options for a starter word. Here are some good options: \n")
for word in candidate_starter_words:
if (word == candida... |
def entropy(self, node):
labels, counts = np.unique(self.y[:,node.ids], return_counts=True)
probs = counts / node.ids.shape[0]
node.entropy = 0 if np.any(probs == 0) else -np.sum(probs*np.log(probs))
return node.entropy
def set_label(self, node):
labels, counts = np.unique(self.y... | The code builds a decision tree using BFS. It processes nodes level by level: if a node's entropy is zero or max depth is reached, it's labeled as a leaf; otherwise, it splits into children. Children are added to the queue for further processing, ensuring hierarchical tree construction. | def build_tree(self):
# build tree in bfs manner
queue = [self.root]
while len(queue) != 0:
node = queue.pop(0)
if self.entropy(node) == 0 or node.depth >= self.max_depth: # leaf node
self.set_label(node)
else: # internal node
s... |
def processDataToCSV(category):
# Process the product_review dataset to panda.DataFrame
product_review_df = getDF('D:\\Amazon\\review\\' + category + '.json.gz')
# clean the data, select the data we want
# https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.drop.html
product_review_df = product_r... | The main task of the code is to generate product recommendations for a given category using collaborative filtering based on review data. It processes product reviews, computes average ratings, identifies top-performing products, builds a reviewer-product rating matrix, and recommends products with high correlation sco... | def recommendByCategory(category):
# Run the processDataToCSV to generate a new XXXXXX_product_detail_review.csv
if(os.path.exists('D:/Amazon/processed_data/' + category + '_product_detail_review.csv')):
print('product detail review exists')
else:
processDataToCSV(category)
product_detail_review_... |
def _get_client_token(event):
"""
Extracts client token from the request
:param event:
:return: client_token
:rtype: str
"""
if 'authorizationToken' in event:
authorization_header = event.get('authorizationToken')
token_prefix = 'Bearer '
if not authorization_header... | The function authorizes API requests by validating a client token, creating an IAM policy for authenticated users, and generating a context if valid. If validation fails, access is denied. It extracts, decodes, and verifies the token, then constructs an authentication response with the policy and user context, logging ... | def _authorize_request(event, context):
"""
- validates the provided token in the request
- if is valid
- it creates the IAM Policy to authorize the authenticated user
- if something goes wrong during the workflow it
denies the access to the API resources
:param event:
:param contex... |
def split_data_train_test(X, y, test_size):
"""Creates train/test split given a dataframe
Args:
data (pd.DataFrame): parkinsons data
Returns:
pd.DataFrame: training and test splits
"""
if stratify:
x_train, x_test, y_train, y_test = train_test_split(
X, y, test... | The function evaluates classification accuracy by iteratively removing features from a dataset, using SVM to test performance after each removal. It identifies the column whose removal yields the highest accuracy, repeating trials for reliability. Results are saved as CSV, and plots are generated to visualize performan... | def predict_minus_feature(df, removed_col=""):
"""Takes the dataset, separates the data from the labels and finds the best configuration
through elimination of features and classifying the data to see if and which column being removed
provides the best classification accuracy.
Collects prediction accur... |
def load_scanned_numbers():
print("Loading scanned numbers from file...")
if os.path.exists('scanned.txt'):
with open('scanned.txt', 'r') as file:
scanned = set(line.strip() for line in file)
print(f"Loaded {len(scanned)} numbers.")
return scanned
print("No scanne... | The code processes a numerical range using msieve, handling command-line arguments for range (`-R`), mode (`-M` for file-based or `-M` for external processing), and hexadecimal range (`-H`). It loads scanned numbers, iterates through sub-ranges, and processes each number in a loop until the entire range is completed. T... | def main():
parser = argparse.ArgumentParser(
description='Process a range of numbers using msieve.',
formatter_class=argparse.RawTextHelpFormatter # This will help in displaying the help text as it is written
)
parser.add_argument(
'-R', '--range',
type=str,
... |
def get_country_id(CountryName):
table = boto3.resource('dynamodb').Table('AdvgCountries')
country_record = table.query(
IndexName='Name-index',
KeyConditionExpression=Key('Name').eq(CountryName)) # dynamo is case-sensitive
if country_record['Count'] == 1:
return country_record[... | The code retrieves the next question for a specific country from a DynamoDB table. It queries the table using the country's ID and the next question number (current +1). If found, it returns the question text; otherwise, it logs an error, updates game stats, ends the game, and returns a predefined end message. | def get_next_question(countryname, stats, handler_input):
#return next question
table = boto3.resource('dynamodb').Table('AdvgStories')
speak_output = GAME_END
#retrieve the next question for the particular country
question_record = table.query(KeyConditionExpression=Key('CountryId').eq(get_cou... |
def get_country_id(CountryName):
table = boto3.resource('dynamodb').Table('AdvgCountries')
country_record = table.query(
IndexName='Name-index',
KeyConditionExpression=Key('Name').eq(CountryName)) # dynamo is case-sensitive
if country_record['Count'] == 1:
return country_record[... | This function retrieves a Yes/No response from a DynamoDB table based on the player's country and question number, updates game stats (money/energy), checks game-over conditions, and generates a spoken response using Polly voice. It increments turn counters, applies stat changes, warns players of low resources, or ends... | def getYesorNoResponse(handler_input, textType):
#retrieve the questions details
table = boto3.resource('dynamodb').Table('AdvgStoryDetails')
speak_output = GAME_END
try:
#retrieve the Yes or No response for the question
question_record = table.query(KeyConditionExpression=Key('Country... |
def include_display(handler_input):
#APL Directive Code
if supports_apl(handler_input):
handler_input.response_builder.add_directive(
RenderDocumentDirective(
document=load_apl_document("main.json"),
datasources=load_apl_document("datasources.json")
... | The main task of the code is to handle a yes/no intent by retrieving a pre-defined response from a database, checking if the game is ongoing, and reprompting the user with a random question if the game continues. If an error occurs, it logs the issue and provides a fallback response. The function constructs and returns... | def handle(self, handler_input):
# type: (HandlerInput) -> Response
response_builder = handler_input.response_builder
include_display(handler_input)
# retrieve response to user from database
speak_output = getYesorNoResponse(handler_input, 'YesResponseText')
... |
def include_display(handler_input):
#APL Directive Code
if supports_apl(handler_input):
handler_input.response_builder.add_directive(
RenderDocumentDirective(
document=load_apl_document("main.json"),
datasources=load_apl_document("datasources.json")
... | The code handles a "No" intent by generating a response to prompt the user again with a random yes/no question if the game is not over. If an error occurs, it logs the issue and provides an alternative prompt asking the user to specify a country to visit. | def handle(self, handler_input):
# type: (HandlerInput) -> Response
response_builder = handler_input.response_builder
include_display(handler_input)
speak_output = getYesorNoResponse(handler_input, 'NoResponseText')
try:
if is_game_over(handler_input.attributes_mana... |
def include_display(handler_input):
#APL Directive Code
if supports_apl(handler_input):
handler_input.response_builder.add_directive(
RenderDocumentDirective(
document=load_apl_document("main.json"),
datasources=load_apl_document("datasources.json")
... | The main task of the code is to handle a launch request by determining if the user is returning or new. If returning, it checks for an active adventure to continue or prompts for a new one; if new, it welcomes them and initiates a new adventure. The code constructs a response with appropriate messages and reprompts bas... | def handle(self, handler_input):
# type: (HandlerInput) -> Response
logger.info("In LaunchRequestHandler")
response_builder = handler_input.response_builder
include_display(handler_input)
#is returning user
if is_returning_user(handler_input):
#if active adve... |
def include_display(handler_input):
#APL Directive Code
if supports_apl(handler_input):
handler_input.response_builder.add_directive(
RenderDocumentDirective(
document=load_apl_document("main.json"),
datasources=load_apl_document("datasources.json")
... | This code handles starting or continuing an adventure session in a voice-based interactive game. It checks if the user is returning with an active adventure, continues their progress, or starts a new one with country-specific audio greetings. It manages session states, delivers tailored questions, and uses SSML for loc... | def handle(self, handler_input):
# type: (HandlerInput) -> Response
response_builder = handler_input.response_builder
include_display(handler_input)
try:
#if user is already on the session, find current adventure stats and ask the next Yes/No question
if is_user_... |
def update_clusters(self, medoids):
"""!
Forms cluster with specified medoids by calculation distance from each point to medoids.
"""
self.belong = [0] * len(self.data)
self.clusters = [[] for i in range(len(medoids))]
for idx_point in range(len(self.data)):
... | The code performs a local search optimization for clustering by iteratively selecting random medoids, updating clusters, optimizing configurations, and tracking the best solution. It repeats this process multiple times to explore configurations, updating the optimal medoids when a lower cost is found. Finally, it retur... | def process(self):
random.seed()
for _ in range(0, self.numlocal):
# set (current) random medoids
self.current = random.sample(range(0, len(self.data)), self.number_clusters)
# update clusters in line with random allocated medoids
self.update_clusters(se... |
def __check_person(self, person):
# Check person exists in tree
check = (len([1 for x in self._family_list if x==person])==1)
return check == 1
def add_relationship(self, child:str, parents:list):
'''Store information about a parent/child relationship'''
if parents is not Non... | This method adds a person to a family tree, ensuring they are not already present. It links the person to specified parents and optionally assigns a status. If the person exists, it raises an error. | def add_member(self, person:str, parents:list=None, status:int=None):
''' Add a person to the family tree and add any included parental and status information '''
# Check family member not yet added
if not self.__check_person(person):
self._family_list += [person]
else:
... |
def __check_person(self, person):
# Check person exists in tree
check = (len([1 for x in self._family_list if x==person])==1)
return check == 1
def add_relationship(self, child:str, parents:list):
'''Store information about a parent/child relationship'''
if parents is not None... | The main task of the code is to add a person to a family tree, checking if they already exist, and if not, appending them to the family list. It then establishes parent-child relationships via `add_relationship` and optionally sets a status using `add_status` if provided. The method ensures no duplicate entries and rai... | def add_member(self, person:str, parents:list=None, status:int=None):
''' Add a person to the family tree and add any included parental and status information '''
# Check family member not yet added
if not self.__check_person(person):
self._family_list += [person]
else:
... |
def _get_possible_initial_genomes(self, gene_frequency):
''' Generate the set of initial independent genomes '''
# Get the list of people with independent genomes
key_people = self.__independent_genomes
logger.debug('Key people are: {}'.format(', '.join(key_people)))
# Generat... | The code simulates genome transmission by initializing genomes based on recessive prevalence, generating transmission chains from relationships, and creating a simulation using these components. It calculates gene frequency from recessive prevalence, seeds initial genomes, and constructs transmission pathways to model ... | def simulate(self, recessive_prevalence=None):
#logger.info('Starting simulation')
print('Starting simulation')
# Get initial genomes to seed with
if recessive_prevalence is None:
recessive_prevalence = self._recessive_prevalence
assert(recessive_prevalence is not N... |
def initialize_parameters(input_size, hidden_size, output_size):
np.random.seed(42)
weights_hidden = np.random.randn(input_size, hidden_size)
bias_hidden = np.zeros((1, hidden_size))
weights_output = np.random.randn(hidden_size, output_size)
bias_output = np.zeros((1, output_size))
return weight... | This function trains a neural network using stochastic gradient descent (SGD) to minimize mean squared error (MSE) on training data while monitoring validation performance. It initializes parameters, iterates through epochs, processes each training sample individually, computes forward passes, updates weights via backp... | def train_model(X_train, y_train, X_test, y_test, hidden_size, learning_rate, epochs):
input_size = X_train.shape[1]
output_size = y_train.shape[1]
weights_hidden, bias_hidden, weights_output, bias_output = initialize_parameters(input_size, hidden_size, output_size)
for epoch in range(epochs):
... |
def custom_sobel(img, axis='x'):
if axis == 'x':
kernel = np.array([[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]])
elif axis == 'y':
kernel = np.array([[-1, -2, -1], [0, 0, 0], [1, 2, 1]])
else:
raise ValueError("Invalid axis. Use 'x' or 'y'.")
return custom_filter2D(img, kernel)
def cust... | This code computes optical flow between two images I1 and I2 using the Lucas-Kanade method. It calculates spatial gradients (Ix, Iy) and temporal gradient (It), then solves a least-squares problem over a sliding window to estimate motion vectors (u, v) at each pixel, returning horizontal and vertical flow components. | def lucas_kanade_optical_flow(I1, I2, window_size=5):
Ix = custom_sobel(I1, axis='x')
Iy = custom_sobel(I1, axis='y')
It = I2 - I1
half_window = window_size // 2
u = custom_zeros_like(I1, dtype=np.float32)
v = custom_zeros_like(I1, dtype=np.float32)
for y in range(half_window, I1.sha... |
def calculate_info_gain(data, used_attr):
attr_info_gain = dict()
# Get the data count for each class: fraud and non-fraud
counts_data = data.select(["isFraud"]).groupBy("isFraud").count()
total_count = counts_data.rdd.reduce(lambda x,y: x[1]+y[1])
entropy = calculate_entropy(counts_data,total_count... | This function builds a decision tree by recursively splitting training data based on information gain. It creates leaf nodes when data is pure, attributes are exhausted, or depth/nodes limits are reached. For each split, it selects the best attribute, handles discrete/continuous values, and adds edges to the tree. Cont... | def build_tree(train_data, used_attr, distinct_attr_val):
count_classes = train_data.select(["isFraud"]).groupBy("isFraud").count()
#Leaf 1: if there is only one class in the data, it is a leaf
#Leaf 2: if all attributes have been used in the decision tree, it is a leaf
# find the class wit... |
def square(file,rank):
return chr(file-1 + ord('a')) + chr(rank + ord('0'))
def from_coords(x,y):
file = min(8,x//80+1)
rank = min(8,8-y//80)
return (file, rank)
def draw(self, board):
self.screen.blit(self.background, (0,0))
self.board = board
self.draw_pieces(board)
... | This code handles user input for a game, allowing a player to select and move pieces by clicking on the board. It waits for mouse clicks to select a piece and then a destination square, returning the move as coordinates. It also supports quitting or undoing moves via keyboard events. | def get_move(self, moves):
self.selected = None
while True:
for e in pygame.event.get():
if e.type == pygame.MOUSEBUTTONDOWN:
(mouseX, mouseY) = pygame.mouse.get_pos()
left_click = e.button == 1
... |
def buildConfigIndexesList(target_cluster,datacenter,indexVarsPath):
global config_dict
global index_cluster_dict
global sizeIndex_dict
index_temp_dict=[]
size_dict = {}
temp_dict = {}
if target_cluster not in index_cluster_dict.keys() and target_cluster not in sizeIndex_dict.keys():
... | The main task of the code is to load customer and configuration data, determine target clusters based on environment regions, build index configurations, check if indexes exist in clusters, and allocate resources. It processes different environments (dev/stage/prod) and regions (cne/cnn), using conditional logic to sel... | def main():
global base_dict
global index_cluster_dict
global allocate_cluster_dict
global allocateExistInCluster
temp_dict = dict()
global customer_dict
global config_dict
global base_inventory_path
global allocate_vars_path
try:
logger.info("Loading Main Global Index V... |
def train_epoch(self, train_loader, epoch=None):
"""
Method for the training of one single epoch.
:param train_loader: data loader for training data
:param epoch: index of epoch
:return: training loss value averaged across training batches and a dictionary containing useful info... | The code trains a machine learning model using a training loader and validates it with a validation loader, tracking metrics like loss and validation scores. It implements early stopping based on a patience parameter, logs training details periodically, and saves the best model if a validation metric improves. It uses ... | def train(self, train_loader, val_loader, val_metric=None, n_epochs=500, early=None, verbose=10, save_path=None):
"""
Method for the train of the model.
:param train_loader: data loader for training data
:param val_loader: data loader for validation data
:param val_metric: valid... |
def get_single_voxel(
voxels: tuple[np.ndarray, ...], index: int
) -> tuple[np.int64, ...]:
"""
Given a set of voxels return just one voxel at index.
"""
return (
voxels[0][index],
voxels[1][index],
voxels[2][index],
)
def is_edge_voxel(voxel: np.ndarray, voxel_grid_dimen... | The function identifies and classifies 3D voxel structures into four categories (cavity, pocket, pore, hub) by analyzing surface voxel connectivity. It first detects direct surface voxels adjacent to exposed regions, then expands to neighboring surface voxels. Using BFS, it groups connected surface voxels: no groups im... | def get_agglomerated_type(
query_indices: set[int],
buried_voxels: tuple[np.ndarray, ...],
exposed_voxels: tuple[np.ndarray, ...],
voxel_grid_dimensions: np.ndarray,
) -> tuple[set[int], str]:
"""
Find "surface" voxels, being buried voxel in direct contact with an exposed voxel. Four possibilite... |
def breadth_first_search(
voxels: tuple[np.ndarray, ...],
searchable_indices: set[int],
performant: bool = utils.using_performant(),
) -> set[int]:
"""
Given a set of voxels and list of possible indices to add,
add indices for all ordinal neighbors iteratively until no more such neighbors exist.... | The function categorizes buried solvent voxels into hubs, pores, pockets, cavities, and occluded regions by agglomerating them via BFS. It identifies each group's type based on size and surface characteristics, then returns five dictionaries mapping unique IDs to corresponding VoxelGroup objects, each containing struct... | def get_pores_pockets_cavities_occluded(
buried_voxels: VoxelGroup, exposed_voxels: VoxelGroup, voxel_grid: VoxelGrid
) -> tuple[
dict[int, VoxelGroup],
dict[int, VoxelGroup],
dict[int, VoxelGroup],
dict[int, VoxelGroup],
dict[int, VoxelGroup],
]:
"""
Agglomerate buried solvent voxels in... |
def verify_product(product_id):
view_response = get_product_data(product_id).json()
verify_product_id_after_view_api(view_response, product_id)
verify_product_title(view_response, EXPECTED_PRODUCT_TITLE)
verify_product_price(view_response, EXPECTED_PRODUCT_NEXUS6_PRICE)
print("Success, Product veri... | The main task of the code is to verify product parameters by first authenticating a user via login to obtain a cookie, then retrieving and validating product information based on item counts and product IDs, ensuring the product data meets required criteria before proceeding with further operations. | def verify_product_param_api():
verify_product(verify_items_count_and_get_product_id(get_user_cookie_via_login())) |
def correct_z_imu(self,
x_nom_prev: NominalState,
z_imu: ImuMeasurement,
) -> CorrectedImuMeasurement:
"""Correct IMU measurement so it gives a measurmenet of acceleration
and angular velocity in body.
Hint: self.accm_correction... | The main task of the code is to predict the system's nominal and error states based on a previous nominal state, previous error state Gaussian, and a raw IMU measurement. It first corrects the IMU measurement using the previous nominal state, then predicts the new nominal state and updated error state Gaussian using th... | def predict_from_imu(self,
x_nom_prev: NominalState,
x_err_gauss: ErrorStateGauss,
z_imu: ImuMeasurement,
) -> Tuple[NominalState, ErrorStateGauss]:
"""Method called every time an IMU measurement is received
... |
def reset(self):
obs = self.env.reset()
self.score = 0
self.step_count = 0
self.end_reason = ''
self.last_observation = obs
self.is_done = False
if self.agent is not None:
self.render()
agent_lib.G.assert_map(obs['glyphs'], obs['chars'])
... | The main task of the code is to repeatedly initialize and run an agent's main loop, handling "ReloadAgent" exceptions by restarting the process. It ensures rendering updates are applied in each iteration, and ultimately triggers a reload of the agent after completing the loop. The core goal is to maintain and re-run th... | def main(self):
self.reset()
while 1:
try:
self._init_agent()
self.agent.main()
break
except ReloadAgent:
pass
finally:
self.render()
self.agent = None
reload_agen... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.