dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def find_best_move(board):
best_score = float("-inf")
best_move = None
for row in range(3):
for col in range(3):
if board[row][col] == " ":
board[row][col] = "X"
score = minimax(board, 0, False)
board[row][col] = " "
if scor... | The function handles the computer's turn in a Tic-Tac-Toe game by selecting the best move, updating the board and UI with "X", checking for a win or tie, and switching to the player's turn if the game continues. | def computer_turn():
global player_turn, board
computer_row, computer_col = find_best_move(board)
buttons[computer_row][computer_col].config(text="X")
board[computer_row][computer_col] = "X"
if check_winner(board, "X"):
messagebox.showinfo("Result", "Computer wins!")
reset_game()
... |
def check_winner(board, player):
for row in board:
if all(cell == player for cell in row):
return True
for col in range(3):
if all(row[col] == player for row in board):
return True
if all(board[i][i] == player for i in range(3)) or all(board[i][2 - i] == player for i ... | This function handles a player's move in a tic-tac-toe game by updating the board with "O" at the specified cell if it's the player's turn. It checks for a win or tie, displays results, and switches to the computer's turn ("X") if the game continues. | def update_button(row, col):
global player_turn, board
if board[row][col] == " " and player_turn == "O":
buttons[row][col].config(text="O")
board[row][col] = "O"
if check_winner(board, "O"):
messagebox.showinfo("Result", "You win!")
reset_game()
elif is_b... |
def chessboard_verts(image, board, crop=None):
copy = image.copy()
if crop is not None:
(x1, x2), (y1, y2) = crop
copy = copy[y1:y2, x1:x2]
# termination criteria
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 100, 0.001)
# Find the chess board corners
gray = cv... | The code visualizes and aligns detected chessboard corners in an image. It displays the image, identifies corners using a chessboard detection function, aligns them, and plots labeled points on the image. Specific vertices are highlighted with circles, and the result is saved as "board-align". The task involves visuali... | def view_board_alignment(image, board, crop=None):
plt.imshow(image)
plt.show()
plt.savefig("img")
try:
board_verts = chessboard_verts(image, board, crop)
except:
print("Could not find chessboard corners")
return
board_verts = verts_align(image, board_verts, board)
y_... |
def get_pipeline(serial):
pipeline = rs.pipeline()
config = rs.config()
pipeline_wrapper = rs.pipeline_wrapper(pipeline)
if serial is not None:
config.enable_device(serial)
pipeline_profile = config.resolve(pipeline_wrapper)
# Enable highest resolution streams for more precise measurem... | The code collects 3D vertex data of a board using depth and color frames from a sensor over multiple frames, aligns them, filters outliers, and returns the processed 3D coordinates for calibration or mapping tasks. | def collect_data(sensor, board, frame_count=150, view_from_verts=True, debug=False, zofs=0.0):
serial = sensor["serial"]
pipeline = get_pipeline(serial)
# Processing block
pc = rs.pointcloud()
align_to = rs.stream.color
align = rs.align(align_to)
# Let 3 frames go by before using them (th... |
def get_pipeline(serial):
pipeline = rs.pipeline()
config = rs.config()
pipeline_wrapper = rs.pipeline_wrapper(pipeline)
if serial is not None:
config.enable_device(serial)
pipeline_profile = config.resolve(pipeline_wrapper)
# Enable highest resolution streams for more precise measurem... | The function `run_view_board_alignment` captures and processes a color image from a sensor, skipping initial unstable frames, then aligns the image with a specified board using a cropping parameter. It retrieves the color frame, converts it to a numpy array, and passes it to `view_board_alignment` for alignment process... | def run_view_board_alignment(sensor, board):
pipeline = get_pipeline(sensor["serial"])
# Let 3 frames go by before using them (the first couple are often blank)
for _ in range(3):
frames = get_frames(pipeline)
frames = get_frames(pipeline)
color_frame = frames.get_color_frame()
color_ima... |
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('--debug', action='store_true') # default is false
parser.add_argument('--clear', action='store_true') # default is false
parser.add_argument('--zofs', type=float, default=0.0)
parser.add_argument('--frame_count', type=in... | The main task of the code is to calibrate sensors by collecting alignment data between sensors and a board, either by loading existing calibration data or creating new data. It processes command-line arguments, checks sensor/board configurations, loads or initializes calibration data, collects new data points, and save... | def main():
args = parse_args()
sensors = locations[ args.location ]
board = boards[ args.board ]
# Check that we can find the board and it's alignment
if args.debug:
for sensor in sensors:
run_view_board_alignment(sensor, board)
input("Press enter to continue")... |
def print_usage_and_exit():
eprint(f'Usage: {sys.argv[0]} parse')
eprint(f'Usage: {sys.argv[0]} function_decl <file path> <line number>')
eprint(f'Usage: {sys.argv[0]} function_snippet <file path> <line number>')
eprint(f'Usage: {sys.argv[0]} find_func_decls <file path>...')
eprint(f'Usage: {sys.arg... | This code processes C++ source files using Tree-sitter to parse and analyze code structures. It handles commands like retrieving function declarations, finding function definitions/calls, or parsing code snippets. The main tasks include validating input parameters, loading Tree-sitter parsers, and executing command-spe... | def main():
# Check usage, get arguments and perform sanity checks
if len(sys.argv) < 2:
print_usage_and_exit()
arg_cmd = sys.argv[1]
if arg_cmd in ['function_decl', 'function_snippet']:
if len(sys.argv) < 4:
print_usage_and_exit()
arg_source_file = sys.argv[2]
... |
def eprint(*args, **kwargs):
print(*args, file=sys.stderr, **kwargs)
def read_excel_file(filepath):
# Parse functions sheet (iterate over rows, parse column entries)
wb = openpyxl.load_workbook(filepath)
sheet = wb['functions']
functions = []
row_idx = 1
while sheet.cell(row=row_idx, column=... | This script processes Excel data to generate either mock libraries or fuzz test code based on command-line arguments, outputting results to a specified directory. It parses function/snippet data from an Excel file, then uses `generate_mocklib` or `generate_fuzztests` to create corresponding code files, with optional de... | def main():
# Check usage and get arguments
if len(sys.argv) < 4:
eprint('Usage: {} mocklib|fuzztests <excel sheet> <output directory> (print call info (1|0))')
sys.exit(1)
arg_cmd = sys.argv[1]
arg_excel_file = sys.argv[2]
arg_out_dir = sys.argv[3]
global print_info
print... |
def separateFiles(filenames):
cpfiles = []
ipfiles = []
for name in filenames:
solver = name.split("_")[-1]
if solver == "cp":
cpfiles.append(name)
elif solver == "ip":
ipfiles.append(name)
return(cpfiles, ipfiles)
def satUnsatNotsolvedProps(allfiles):
... | This function processes input files to categorize instances into SAT, UNSAT, and unsolved groups, calculates their percentages relative to total instances, and generates a stacked bar chart visualizing the distribution. It separates files, extracts properties, groups results, computes percentages, and uses a custom plo... | def satUnsatUnsolvedPerProps(filenames):
cpfiles, ipfiles = separateFiles(filenames)
alles = satUnsatNotsolvedProps(ipfiles)
pos = 1
ylabel = "Percent of instances"
plotname = ""
sat, unsat, notsolved, instanceNames, vals, xlabel = groupSatUnsatNotsolved(alles,pos)
instancesPerConfig = sat[... |
def startup():
"""Run enabled operations at startup."""
# train classifier
if config.getboolean("startup", "train_classifier"):
LinearSVC.train(
config["classification"]["data_path"],
config["classification"]["model_path"],
)
console.print("[green]Trained clas... | The main task of the code is to initialize a game session by retrieving start/goal configurations, confirming user-selected endpoints, and executing the gameplay loop. It handles user input, maintains command history, and processes game commands via the GameSession's classify() method until the game ends. | def main():
"""Start the program and run the main gameplay loop."""
startup()
start_menu()
# get start and goal modes from config
start_mode, goal_mode = config["endpoints"]["start"], config["endpoints"]["goal"]
# ask user to confirm endpoints
begin = "n"
while begin != "y":
st... |
def _get_prev_samples(self):
""" Get previous samples from dataset (n=batch_size) and run inference
"""
# Beyond first set of samples
if self.dataset_prev_index < 0:
self.current_index = 0
else:
# Get n samples
samples = []
for i in... | The main task of the code is to update the display by checking if the current index is out of bounds or if model output is missing. If so, it fetches previous or next samples accordingly, clears the output widget, and renders the updated images. This ensures the UI dynamically displays relevant data based on the curren... | def _update_display(self):
""" Update figure
"""
# If current index is beyond/above min/max run inference
if self.current_index < 0:
self._get_prev_samples()
elif self.current_index > (self.num_samples - self.total_images) \
or self.model_output is No... |
def query_res_lr_sql():
return get_file_paths("./static/img/linear_regression/")
def query_res_log_sql():
return query_log_sql(TABLE_RES_LOG)
def query_res_rf_sql():
#return query_log_sql(TABLE_RES_RF)
return get_file_paths("./static/img/random_forest/")
def query_res_dt_sql():
return get_file_paths... | The function determines the type of machine learning model (ml_type) and retrieves corresponding statistics by querying specific SQL functions. It returns a JSON response containing the model type and retrieved statistics. | def ml_type(ml_type=None):
if ml_type == ML_TYPE_LR:
stats = query_res_lr_sql()
elif ml_type == ML_TYPE_LOG:
stats = query_res_log_sql()
elif ml_type == ML_TYPE_RF:
stats = query_res_rf_sql()
elif ml_type == ML_TYPE_DT:
stats = query_res_dt_sql()
elif ml_type == ML_TY... |
def _draw_frame_info(self, frame_id: int, step: int, img: Optional[np.ndarray] = None) -> np.ndarray:
"""
Draw a label with information about the current frame number, processing step id and processing
step name (if given). Uses the `ALPHA` value from config.
"""
## Copy image to allow for alpha-weighted comp... | The function retrieves a zoomed-in image from a specified step, applying pixel labels and frame information if enabled. If zoom is 1, it returns the original image with labels. Otherwise, it centers the zoom, processes the image, and overlays labels before returning the modified array. | def _get_image(self, draw_label: bool, frame_id: int, step_idx: int) -> np.ndarray:
"""
Get a zoomed in version of the image.
"""
## Return drawn image if no zoom
if self.zoom == 1:
self.orig_pixels_left = 0
self.orig_pixels_top = 0
img = self._draw_frame_info(frame_id, step_idx) if draw_label else s... |
def tokenize_sentence(self, sentence, pre_process_sentence=None) -> np.ndarray:
"""
Creates an array that contains all the words that appear on the sentence, after being processed by the
fit_transform
The count vectorizer.fit_transform creates a document by term matrix with one document ... | The code computes the cosine similarity between two sentences by tokenizing them, converting each into a vector, and measuring their similarity. It returns a float score indicating how closely the given answer matches the real answer. | def get_sentence_match(self, real_answer: str, given_answer: str) -> float:
# generate a list with the words that appear on the sentence
g_tok = self.tokenize_sentence(given_answer)
given_sentence_vector = self.get_sentence_vector(g_tok)
r_tok = self.tokenize_sentence(real_answer)
... |
def _strobe_data(self, data):
"""
Send Data via I2C to the LCD by flashing the enable pin.
:param data: Data to be sent to the LCD
:type data: int
"""
# Set the enable high with the data
self.write(data | self._MASK_EN, read_check=False)
time.sleep_ms(1)
... | The function initializes an LCD by sending reset commands, configuring it to 4-bit mode, clearing the display, setting cursor behavior, and enabling the backlight to prepare for operation. | def _lcd_init(self):
"""Helper function for the initialization sequence of the LCD"""
# initial wipe of PCF data bus and controls
self.write(0)
# Allow LCD time to powerup
time.sleep_ms(20)
# Send reset 3 times over data bus while flashing the enable.
self._s... |
def _write_cmd(self, cmd):
"""
Helper function to send values to the LCD command register
:param data: full byte of data to be sent to the LCD
:type data: int
"""
self._strobe_data((self.backlight() << 3) | self._upper(cmd)) # type: ignore
self._strobe_data((self... | This function writes a custom character to a specified CGRAM location on an LCD. It first selects the CGRAM address using the provided location, then sends each of the 8 bytes from the charmap to define the character. Delays ensure proper timing, and the final cursor movement resets the display position after writing. | def custom_char(self, location, charmap):
"""Write a character to one of the 8 CGRAM locations, available
as chr(0) through chr(7).
"""
# indicate that we are writing to a CGRAM location
self._write_cmd(self._LCD_CGRAM | ((location & 0x7) << 3))
time.sleep_us(40)
... |
def _get_host_for_server(self, server_id):
return self._get_server_details(server_id)['OS-EXT-SRV-ATTR:host']
def _get_host_other_than(self, host):
for target_host in self._get_compute_hostnames():
if host != target_host:
return target_host
def _live_migrate(self, server_id, ... | The main task of the code is to test live migration of virtual machines between two hosts, ensuring the server's state (ACTIVE/PAUSED) remains consistent before and after migration. It creates a test server, identifies source/destination hosts, pauses the server if needed, performs live migration, and optionally migrat... | def _test_live_migration(self, state='ACTIVE', volume_backed=False):
"""Tests live migration between two hosts.
Requires CONF.compute_feature_enabled.live_migration to be True.
:param state: The vm_state the migrated server should be in before and
after the live migration... |
def heuBoard(board):
h={}
h["Wpawn"]=-1
h["Wrook"]=-5
h["Wbishop"]=-3
h["Wknight"]=-3
h["WQueen"]=-9
h["WKing"]=-1000
h["Bpawn"]=1
h["Brook"]=5
h["Bbishop"]=3
h["Bknight"]=3
h["BQueen"]=9
h["BKing"]=1000
sum=0
for chess in board:
sum=sum+h[chess.name]
... | This function implements a minimax algorithm with alpha-beta pruning for game tree search. It evaluates board states recursively, alternating between maximizing (odd i) and minimizing (even i) players. It returns the optimal child board and its heuristic value, pruning branches when heuristic thresholds (-500/500) are ... | def pChildren(board,i,x,y):
if i==4:
return [board,heuBoard(board)]
if i%2==1:
maxx=-10000
for b in makeChildrenB(board):
if(heuBoard(b)>500):
return [b,heuBoard(b)]
if(heuBoard(b)<-500):
return [b,heuBoard(b)]
a=pChildr... |
def calculate_split_points(file_size, noOfChunks):
return [i * file_size // noOfChunks for i in range(1, noOfChunks+1)]
def adjust_split_points(bucket_name, file_name, split_points, file_type, config):
adjusted_splits = []
for split_point in split_points:
adjusted_splits.append(adjust_split_point(bu... | The code splits a file into chunks, adjusts split points based on configuration and file type, generates a unique identifier (UUID), and sends event data to a message system (MSK) with details like bucket name, file name, adjusted splits, file type, and feed name for processing or tracking. | def split_file(bucket_name, file_name, file_size, file_type, config, feed_name):
split_points = calculate_split_points(file_size, config.get('noOfChunks',9))
print(f"split_points [{split_points}]")
adjusted_splits = adjust_split_points(bucket_name, file_name, split_points, file_type, config)
print(f"adj... |
def get_bucket_and_file(event):
bucket_name = event['Records'][0]['s3']['bucket']['name']
file_name = event['Records'][0]['s3']['object']['key']
return bucket_name, file_name
def get_file_size(bucket_name, file_name):
response = s3.head_object(Bucket=bucket_name, Key=file_name)
return response['Cont... | This Lambda function processes file uploads by determining the file's size, type, and configuration. If the file is below a specified size threshold, it triggers a single-event handling; otherwise, it splits the file into smaller parts for processing, with error handling for splitting operations. | def lambda_handler(event, context):
bucket_name, file_name = get_bucket_and_file(event)
print(f"bucket_name [{bucket_name}] file_name [{file_name}]")
file_size = get_file_size(bucket_name, file_name)
print(f"file_size [{file_size}]")
file_type, feed_name = get_file_details(file_name)
print(... |
def NB_training():
x_train, y_train, x_test, y_test = get_split_data()
NB_y_preds_train = nb_model(x_train, y_train)
report = classification_report(y_train, NB_y_preds_train)
print('Naive Bayes train')
print(report)
def gb_training():
x_train, y_train, x_test, y_test = get_split_data(... | The main task of the code is to sequentially train and evaluate multiple machine learning models (Naive Bayes, Gradient Boosting, XGBoost) by calling their respective training functions, then print their quality metrics one after another to compare performance. | def get_model_tests():
'''
calls best models to train and print quality one after another
'''
NB_training()
gb_training()
xgb_training() |
def get_flavors_from_db():
try:
query = queries["get_flavors"]
flavors = execute_query(query)
return flavors
except sqlite3.Error as e:
current_app.logger.error(str(e))
return []
def process_vote_form(form_data):
name = form_data['name']
email = form_data['email']... | The code handles user voting for ice cream flavors by rendering a vote form on GET requests, processing submitted votes on POST requests, validating email addresses, storing valid votes in a database, and displaying success/error messages with appropriate redirects. | def vote():
if request.method == 'GET':
flavors = get_flavors_from_db()
return render_template('vote.html', flavors=flavors)
else:
name, email, flavor_id = process_vote_form(request.form)
try:
# Validate email
valid = validate_email(email)
ema... |
def get_users():
query = queries["get_users"]
results = execute_query(query)
return results
def get_flavors():
query = queries["get_all_flavors"]
all_flavors = execute_query(query)
return all_flavors
def get_top_flavors():
query = queries["get_top_flavors"]
top_flavors = execute_query(qu... | The admin function checks if a user is authenticated. If not, it redirects to the login page. It retrieves user, flavor, and admin data from the database, generates HTML tables for each dataset, and renders an admin dashboard template with these tables to display user information, flavor details, top flavors, and admin... | def admin():
if 'username' not in session:
return redirect(url_for('login'))
# Get data from database
user_data = get_users()
flavor_data = get_flavors()
top_flavor = get_top_flavors()
admins = get_admins_info()
# Generate table HTML for user data, flavor data, and top flavor data
... |
def total_distance(self):
# When less than one coordinate no distance can be provided
if len(self.coordinates) < 1:
return 0
# Calculate total distance
total = 0
for coord in self.coordinates:
total += coord.distance
# Return value in kilometers... | The code saves route data as a JSON file in the specified directory. It generates a filename based on the input file's name or marks it as "current" if the last coordinate is recent. The JSON includes coordinates, total distance, time breakdown (total/moving/stopped), speed metrics (average/max/moving), and a flag indi... | def save(self, dir):
# When less than one coordinate no file will be saved
if len(self.coordinates) < 1:
return 0
# Create name
name = Path(self.file).stem
if len(self.coordinates) > 0 and self.coordinates[-1].time + REAL_TIME_MINIMUM_GAP >= time.time() :
... |
def is_call_valid(self):
return self.get_dice_dict()[self.current_call[0]] >= self.current_call[1]
def change_turn(self): # NOTE: CURRENTLY ONLY WORKS WITH 2 PLAYERS
# Swaps turn between 1 and 0
self.turn = 1 - self.turn
def reset_round(self):
self.roll_all()
self.current_call =... | This function processes a player's turn in a dice game. It handles the "dudo" (doubt) challenge logic, validates calls, removes dice from players, checks for game-ending conditions (winning by eliminating all dice), and updates game state including turn transitions and the palifico status. | def play_turn(self):
move = self.players[self.turn].get_move(self.current_call, self.palifico)
if move == "dudo":
if self.palifico:
self.palifico = False
if self.is_call_valid():
self.players[self.turn].remove_die()
if self.playe... |
def runCmd(self, cmd):
(rc, output) = self.runCommand(cmd, show_cmd=True, enable_stdout=False)
if rc != 0:
print("status {} from: {}".format(rc, cmd))
lineNum = 0
for line in output:
if lineNum > 0:
lineNum += 1
if "Test Results" in lin... | The code executes all combinations of workers and tests by generating and running commands with `run_tpch.sh`, then displays the results and elapsed time. | def runTests(self):
for w in self._workersList:
for t in self._testList:
cmd = "./run_tpch.sh -w {} -t {} {}".format(w, t, self._args.args)
self.runCmd(cmd)
self.showResults()
self.displayElapsed() |
def get_rel(arg):
if isinstance(arg, str):
arg = arg_qualify(arg)
if arg.type == IMM:
if arg.value & 3 != 0: # bitwise version of: arg.value % 4 != 0
raise ValueError('Relative offset must be a multiple of 4')
return IMM, arg.value >> 2 # bitwise version of: arg.value // 4
... | This function generates conditional jump instructions based on an offset, threshold, and comparison condition. It adjusts the offset for backward jumps or symbolic labels, creating two instructions for 'le/ge' conditions and one for others, using comparison operators like B_CMP_L, B_CMP_G, or B_CMP_E. | def i_jumpr(offset, threshold, condition):
offset_type, offset = get_rel(offset)
threshold = get_imm(threshold)
condition = get_cond(condition)
if condition in ('le', 'ge'):
if condition == 'le':
cmp_op = B_CMP_L
elif condition == 'ge':
cmp_op = B_CMP_G
#... |
def get_rel(arg):
if isinstance(arg, str):
arg = arg_qualify(arg)
if arg.type == IMM:
if arg.value & 3 != 0: # bitwise version of: arg.value % 4 != 0
raise ValueError('Relative offset must be a multiple of 4')
return IMM, arg.value >> 2 # bitwise version of: arg.value // 4
... | This function generates jump instructions with conditional comparisons, adjusting immediate offsets for a known binutils-gdb bug by shifting them left by 2 bits. It converts input parameters to appropriate internal formats, maps condition strings to comparison operators, and delegates to _jump_rels to create the final ... | def i_jumps(offset, threshold, condition):
offset_type, offset = get_rel(offset)
if (offset_type == IMM):
# This makes our assembler behave exactly like binutils-gdb, even
# though its behaviour is incorrect. binutils-gdb does not divide
# immediate offsets by 4 (i.e. it does not convert... |
def load_decoder(cpu):
if cpu == 'esp32':
mod = 'decode'
elif cpu == 'esp32s2':
mod = 'decode_s2'
else:
raise ValueError('Invalid cpu')
relative_import = 1 if '/' in __file__ else 0
decode = __import__(mod, globals(), locals(), [], relative_import)
global decode_instruc... | The function disassembles a binary file by reading its header, validating the magic number, and extracting the text/data sections. It uses the specified CPU's decoder, prints header details if verbose, and outputs the code/data sections with offsets. | def disassemble_file(filename, cpu, verbose=False):
load_decoder(cpu)
with open(filename, 'rb') as f:
data = f.read()
binary_header_struct_def = dict(
magic = 0 | UINT32,
text_offset = 4 | UINT16,
text_size = 6 | UINT16,
data_size = 8 | UINT16,
bss_size = 10... |
def print_help():
print('Usage: disassemble.py [<options>] [-m <byte_sequence> | <filename>]')
print('')
print('Options:')
print(' -c Choose ULP variant: either esp32 or esp32s2')
print(' -h Show this help text')
print(' -m <byte_sequence> Sequence of hex by... | This function processes command-line arguments to configure disassembly settings. It parses options like '-c' (CPU type), '-m' (byte sequence input), '-v' (verbose mode), and filenames. It stores parameters in variables (cpu, verbose, byte_sequence, filename) and triggers either manual byte sequence disassembly or file... | def handle_cmdline(params):
cpu = 'esp32'
verbose = False
filename = None
byte_sequence = None
while params:
if params[0] == '-h':
print_help()
sys.exit(0)
elif params[0] == '-c':
cpu = params[1]
params = params[1:] # remove first par... |
def create_H_tilda_dict(H):
H_tilda = {}
for model in H:
H_tilda.update({model: {}})
return H_tilda
def calculate_quantiles(T_Huber, forecast_errors, functional_sets, quantile_C1, quantile_C2):
C1 = {}
C2 = {}
for tau in T_Huber:
E = [forecast_errors[model][tau] for model in func... | The function implements adaptive learning (AL) for model selection, using specified methods (e.g., EN, Huber, Ensemble_EN) to identify optimal models or ensembles based on forecast errors. It processes time-series data, calculates model performance over training/test windows, and returns selected models, their forecast... | def adaptive_learning(k,
data_and_time,
csv_directory,
functional_sets,
ar_orders,
window_sizes,
specification_learning
):
"""
Input specifications (by exampl... |
def create_H_tilda_dict(H):
H_tilda = {}
for model in H:
H_tilda.update({model: {}})
return H_tilda
def calculate_quantiles(T_Huber, forecast_errors, functional_sets, quantile_C1, quantile_C2, k):
C1 = {}
C2 = {}
for tau in T_Huber:
# Step 3 (c)(iii)(2)(a): Collect the error vect... | The function `adaptive_learning` trains and evaluates multiple models (functional_sets) using adaptive learning techniques. It processes time-series data to forecast a dependent variable, calculates forecast errors, and adaptively selects optimal models based on specified loss functions (e.g., Huber, ensemble) or regul... | def adaptive_learning(k,
data_and_time,
csv_directory,
functional_sets,
ar_orders,
window_sizes,
p_norm,
L_local,
L_global
... |
def eval(self):
"""The fish evaluates its state
Currently the fish checks all responses to previous pings and evaluates
its relative position to all neighbors. Neighbors are other fish that
received the ping element.
"""
# Set of neighbors at this point. Will be reconst... | This code recursively runs a fish simulation process by evaluating and communicating at each clock tick. It maintains a specified clock speed by calculating sleep time between operations, issuing warnings if the system cannot meet the required timing. The process continues as long as `is_started` is True, with recursiv... | def run(self):
"""Run the process recursively
This method simulates the fish and calls `eval` on every clock tick as
long as the fish `is_started`.
"""
if not self.is_started:
return
start_time = time.time()
self.eval()
time_elapsed = time.t... |
def create_train_val_test_list(src_dir,suffix='.jpg'):
import os
from sklearn.model_selection import train_test_split
imgs=os.listdir(src_dir)
imgs = [img for img in imgs if img.endswith(suffix)]
train, val=train_test_split(imgs,test_size=2/6, random_state=42)
val, test=train_test_split(val,test... | This code trains a neural network for crack detection using custom datasets, configuring GPU settings, data loaders, and an SGD optimizer with CrossEntropyLoss. It performs multi-epoch training with validation, logs metrics like accuracy and mean IU, and saves the trained model weights. | def main():
img_dir=r'/raid/lcq/dataset/crack/imgs'
label_dir=r'/raid/lcq/dataset/crack/labels'
save_path='./weights/result_without_pre.plt'
bach_size=64
GPU_ID=1
epoches=400
lr=0.001
lr_change=[]
log_dir='./log'
logger=Logger(log_dir, '', 'crack')
logger.train()
if GPU_I... |
def fetch_stock_data(ticker: str, length: int) -> pd.DataFrame:
"""fetches pandas dataframe of stock prices for a given ticker
ticker (str): stock ticker
length (int): number of days of data to fetch
Raises:
TypeError: incorrect/inavlid type given to function
ConnectionError: i... | The code simulates stock price movements using historical data and the Black-Scholes model. It gathers stock data, calculates volatility, simulates future prices, and visualizes both historical and simulated price trends over time. | def run_program():
ticker = input("Stock Ticker: ").strip()
num_days_stock = int(input("Number of Days to Gather Data: ").strip())
dataframe = fetch_stock_data(ticker, num_days_stock)
stock_price = dataframe["Average"].astype(float).tail(1)[0]
interest = 0.05
sigma = calculate_black_scholes_sig... |
def warnings(self):
ai_text = self._ai.ship_distroyed()
if ai_text != "":
self._ai_warning = ai_text
font = pygame.font.SysFont('comicsans', 30)
ai_warning = font.render(self._ai_warning, True, (0,0,0))
text_poz = ai_warning.get_rect()
text_poz.c... | The main task of the code is to redraw the game window by clearing the screen with a purple background, checking if 4 pieces are placed to trigger warnings, rendering the player's and AI's grids, and updating the display for real-time visualization in a Pygame application. | def redraw_window(self):
self._window.fill((240,0,255))
if self._placed == 4:
self.warnings()
self.draw_my_grid()
self.draw_ai_grid()
pygame.display.update() |
def place_ship(self, size):
x = self._top_x_1
y = self._top_y_1
placed = False
if self._direction == 1:
for i in range(size -1, 8):
for j in range(8):
if (x + j*self._block_size + self._block_size) > self._mouse[0] > x + j*self._block_size ... | The code manages a turn-based game loop using Pygame, handling user input for ship placement (via keyboard and mouse) and initiating attacks. It tracks placed ships, processes events like key presses and mouse clicks, and alternates between player and AI attacks once all ships are placed. The loop continues until the g... | def start(self):
run = True
self._placed = 0
while run:
self._mouse = pygame.mouse.get_pos()
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygam... |
def distance(a, b):
return ((a[1] - b[1]) * (a[1] - b[1]) + (a[0] - b[0]) * (a[0] - b[0])) ** 0.5
def cos(src, a, b):
va = (a[0] - src[0], a[1] - src[1])
vb = (b[0] - src[0], b[1] - src[1])
r = dot(va, vb) / (abs(va) * abs(vb))
if r < -1:
r = -1
elif r > 1:
r = 1
return r
def translate(s, t):
return s[0] + ... | The code generates heuristic data for a grid-based system by calculating and saving location, direction, and destination arrays in a Java class. It computes coordinates within a radius, sorts them using distance and angle metrics, and outputs structured arrays for pathfinding or optimization algorithms. The generated J... | def generate_heuristics(radius_squared):
rsq = radius_squared
r = int(rsq ** 0.5)
d = r * 2 + 1
# generate all possible locations
all_loc = []
for x in range(-r, r + 1):
lim = int((rsq - x * x) ** 0.5)
for y in range(-lim, lim + 1):
if (x, y) != (0, 0):
all_loc.append((x, y))
l_dump = []
d_dump = [... |
def _inspect_container(self):
try:
return self.d.inspect_container(self.name)
except docker.errors.APIError:
pass
except requests.exceptions.ConnectionError as e:
raise IOError("Unable to communicate with docker daemon: %s\n" %
str(e)... | The code stops a container or image by first verifying its existence, preparing and executing a stop command via subprocess, and directly stopping the container if it's running, with error handling for non-existent containers/images. | def stop(self):
self.inspect = self._inspect_container()
if self.inspect is None:
self.inspect = self._inspect_image()
if self.inspect is None:
raise ValueError("Container/Image '%s' does not exists" %
self.name)
args = se... |
def _inspect_container(self):
try:
return self.d.inspect_container(self.name)
except docker.errors.APIError:
pass
except requests.exceptions.ConnectionError as e:
raise IOError("Unable to communicate with docker daemon: %s\n" %
str(e)... | This code uninstalls a Docker container and its associated image. It checks for existing containers, force-deletes if specified, removes the container/image, verifies the image exists, executes custom uninstall commands, and finally removes the image using 'docker rmi'. Error handling ensures graceful failure during co... | def uninstall(self):
self.inspect = self._inspect_container()
if self.inspect and self.force:
self.force_delete_containers()
if self.name != self.image:
try:
# Attempt to remove container, if it exists just return
self.d.stop(self.name)
... |
def _inspect_container(self):
try:
return self.d.inspect_container(self.name)
except docker.errors.APIError:
pass
except requests.exceptions.ConnectionError as e:
raise IOError("Unable to communicate with docker daemon: %s\n" %
str(e)... | The code manages container lifecycle by inspecting existing containers, pulling images if missing, constructing commands based on configuration flags, and executing them via subprocess. It handles container start, display of commands, and runs processes conditionally based on parameters like 'display' and 'spc' | def run(self):
missing_RUN = False
self.inspect = self._inspect_container()
if self.inspect:
self._check_latest()
# Container exists
if self.inspect["State"]["Running"]:
return self._running()
elif not self.args.display:
... |
def _inspect_image(self, image=None):
try:
if image:
return self.d.inspect_image(image)
return self.d.inspect_image(self.image)
except docker.errors.APIError:
pass
except requests.exceptions.ConnectionError as e:
raise IOError("Unab... | The main task of the code is to install a Docker image by first checking if it exists locally. If not, it pulls the image (with display feedback if enabled). It then constructs and executes an installation command using specified arguments and environment settings, either displaying the command or running it directly b... | def install(self):
self.inspect = self._inspect_image()
if not self.inspect:
if self.args.display:
self.display("Need to pull %s" % self.image)
return
self.update()
self.inspect = self._inspect_image()
args = self._get_args("IN... |
def _update(self):
"""Updates the team and match list"""
self._update_matches()
self._update_teams()
def _is_in_comp(self, team_number):
"""Checks if a team is in the current competition"""
in_comp = False
for team in self.teams:
if team.team_number == team_nu... | The function calculates the average balls scored by a specified team across all their matches. It first checks if the team exists in the collection and has played matches. If valid, it counts the team's matches, retrieves their total balls, and returns the average. If invalid, it returns error messages indicating the t... | def average_balls(self, team_number: int):
"""Returns the average balls scored by a team"""
self._update()
if not self._is_in_comp(team_number):
return f"{team_number} is not in the teams collection"
if not self._played_matches(team_number):
return f"{team_number}... |
def is_end_match(board):
player1_plays, player2_plays = False, False
for i in range(0, 6):
if board[i] != 0:
player1_plays = True
for i in range(7, 13):
if board[i] != 0:
player2_plays = True
return not (player1_plays and player2_plays)
def max_move_list(board): ... | The code implements the minimax algorithm for a two-player game, where player 1 (AI) aims to maximize the pebble difference (board[6] - board[13]) while player 0 (human) minimizes it. It recursively evaluates all possible moves up to a depth of 5 or until the game ends, returning the optimal move and its evaluated scor... | def minimax(depth, player, board):
# print("The player number is {}".format(player))
# print("The depth of the tree is {}".format(depth))
if depth > 5 or is_end_match(board):
# print("The match ended with the result, {}".format((board[6] - board[13], None)))
return (board[6] - board[13], Non... |
def is_end_match(board):
player1_plays, player2_plays = False, False
for i in range(0, 6):
if board[i] != 0:
player1_plays = True
for i in range(7, 13):
if board[i] != 0:
player2_plays = True
return not (player1_plays and player2_plays)
def run_turn(pit, board, pl... | This function simulates a turn-based game on a board, alternating between two players (0 and 1) using different move selection strategies based on the `bot_play` parameter. Player 0 uses `algo.choose_move` when `bot_play=0`, while player 1 uses `if_bot` in both cases. The game continues until it ends, with moves updati... | def run_genetic_with_if(board, bot, bot_play):
if bot_play == 0:
player = 0
while not is_end_match(board):
if player == 0:
while True:
move = algo.choose_move(bot, board, 0)
if move + 1: # if there's a next move
... |
def is_end_match(board):
player1_plays, player2_plays = False, False
for i in range(0, 6):
if board[i] != 0:
player1_plays = True
for i in range(7, 13):
if board[i] != 0:
player2_plays = True
return not (player1_plays and player2_plays)
def run_turn(pit, board, pl... | This function executes a Mancala-style game using AI and bot strategies. It alternates between minimax algorithm and bot move selection based on 'bot_play', updating the board state with moves, stealing pebbles when applicable, and returning the final board once the game ends. The 'bot_play' parameter determines which ... | def run_genetic_with_ai(board, bot, bot_play):
if bot_play == 0:
player = 0
while not is_end_match(board):
if player == 0:
while True:
move = algo.choose_move(bot, board, 0)
if move + 1: # if there's a next move
... |
def get_is_in_election(self):
self.is_in_election_cv.acquire()
is_in_election = self.is_in_election
self.is_in_election_cv.release()
return is_in_election
def set_is_in_election(self, value):
self.is_in_election_cv.acquire()
self.is_in_election = value
self.is_in_... | This method initiates a leader election process by setting the election state, triggering registered callbacks, sending an 'ELECTION' signal to higher nodes, waiting for confirmation, and proclaiming leadership if no confirmation is received within the timeout period. | def begin_election_process(self):
"""
Begins with the leader election process. It may execute the ELECTION_STARTED callback,
if it is set
"""
if self.get_is_in_election(): return
self.set_is_in_election(True)
if Event.ELECTION_STARTED in self.callbacks:
... |
def wait_get_received_ping_echo(self, timeout):
"""
Executes wait on received_ping_echo condvar for 'timeout' seconds. Then, it returns the value of
received_ping_echo
"""
self.received_ping_echo_cv.acquire()
self.received_ping_echo_cv.wait(timeout)
receiv... | The _poll_leader function periodically checks if the node is not the leader and there is a known leader address. It sends PING messages to the leader and waits for a response. If no response is received within 3 seconds, it logs the leader as down and initiates an election process. The function uses condition variables... | def _poll_leader(self):
"""
Private function. If the node is not the leader, it sends PING messages expecting to receive
an answer. If not, the node begins with the election process.
"""
while True:
self.is_leader_cv.acquire()
self.is_in_election_c... |
def _process_election_message(self, peer_addr):
"""
Process message of type ELECTION. It sends "Ok" to the sender and starts new election process
"""
logging.info(f'Received ELECTION message from {peer_addr}')
# Responder con OK y comenzar proceso de eleccion
... | The function continuously receives and processes messages from a peer, handling commands like 'ELECTION', 'OK', 'LEADER', 'PING', etc., by delegating to specific methods. If no message is received, it waits for the peer to reconnect, logging status updates. The core task is to manage communication with a peer, ensuring... | def _start_receiving_from_peer(self, peer_addr):
logging.info(f'Starting to receive from {peer_addr}')
while True:
msg = self.conn_manager.recv_from(peer_addr)
if msg is None:
logging.info(f'Waiting until {peer_addr} is back again')
self.conn_manag... |
def checkFleetEdges(aiSettings, aliens):
for alien in aliens.sprites():
if alien.checkEdge():
changeFleetDirection(aiSettings, aliens)
break
def shipHit(aiSettings, stats, screen, ship, aliens, bullets, sb):
if stats.shipLives == 0:
stats.gameActive = False
else:
... | The function updates alien positions, checks for collisions between the ship and aliens, and triggers game failure responses (e.g., playing a sound, handling ship hits, or checking if aliens reach the screen bottom). It coordinates alien movement, collision detection, and game state transitions when failures occur. | def updateAlien(aiSettings, aliens, ship, failSound, stats, screen, bullets, sb):
# check if the fleet is at an edge and then update its postion
checkFleetEdges(aiSettings, aliens)
aliens.update()
# loof for alien-ship collision
if pygame.sprite.spritecollideany(ship, aliens):
failSound.pla... |
def get_channels(img: NDArray3D) -> tuple[NDArray2D, NDArray2D, NDArray2D]:
blue_channel = img[:, :, 0]
green_channel = img[:, :, 1]
red_channel = img[:, :, 2]
return blue_channel, green_channel, red_channel
def scale_channel(channel: NDArray2D, scale_by: int):
channel_x = len(channel)
channel_... | The code scales each color channel (B, G, R) of a 3D image array independently by a given factor, then merges them back into a single scaled image array. | def scale_img(img: NDArray3D, scale_by: int = 2):
b, g, r = get_channels(img)
b_scaled = scale_channel(b, scale_by)
g_scaled = scale_channel(g, scale_by)
r_scaled = scale_channel(r, scale_by)
img_scaled = merge_channels(b_scaled, g_scaled, r_scaled)
return img_scaled |
def get_channels(img: NDArray3D) -> tuple[NDArray2D, NDArray2D, NDArray2D]:
blue_channel = img[:, :, 0]
green_channel = img[:, :, 1]
red_channel = img[:, :, 2]
return blue_channel, green_channel, red_channel
def convolve_channel(channel: NDArray2D,
kernel: NDArray2D) -> NDArray2D:
... | The code applies a 2D convolution operation to each color channel (blue, green, red) of an input image using the provided kernel, then merges the convolved channels back into a single 3D array representing the transformed image. | def convolve_img(img: NDArray3D,
kernel: NDArray2D) -> NDArray3D:
blue, green, red = get_channels(img)
blue_convolved = convolve_channel(blue, kernel)
green_convolved = convolve_channel(green, kernel)
red_convolved = convolve_channel(red, kernel)
convolved_img = merge_channels(
... |
def user_input(self, events):
"""Check if game is blocked and forward the actions to
the appropriate method.
Args:
events: list of events
"""
if not self.block_game:
self.handle_mouse_clicks(events)
else:
self.handle_block_game()
def dr... | The main task of the code is to process user inputs, update game state, manage timing, and check level completion while rendering the application's display. It handles events, updates the timer, stops it if needed, and checks for level completion, all while drawing the current state to the screen. | def update(self, events, screen):
"""Args:
events: list of events
screen: display of application
"""
self.user_input(events)
self.draw(screen)
self.timer.update()
self.stop_timer()
self.level_completion(screen) |
def clear_balls(self):
for ball in self.balls:
ball.obj.undraw()
self.balls.clear()
def new_ball(self):
self.balls.append(Ball(self.window, self.paddle.obj.getP1().getX()+100, self.paddle.obj.getP1().getY()-50, 10))
def win_game(self):
self.display_win()
self.pause_ga... | The function `next_level` advances the game to the next level if the current level is below 3 by clearing existing balls, updating the level display, and spawning a new ball. If the level reaches 3, it triggers the win condition. | def next_level(self):
self.clear_balls()
if self.levels.level < 3:
self.levels.next_level()
self.scoreboard.update_level()
for i in range(1):
self.new_ball()
else:
self.win_game() |
def move_paddle(self):
# If paddle is inside field
if (self.paddle.vel < 0 and self.paddle.obj.getP1().getX() > self.field_x
or self.paddle.vel > 0 and self.paddle.obj.getP2().getX() < self.field_x2):
if self.paddle.obj.getP1().getX() + self.paddle.vel < self.field_x: # If v... | The code defines a method `move_objects` that updates game elements by calling three functions: moving the paddle, moving balls, and checking for collisions. This ensures dynamic interaction between game objects, maintaining gameplay mechanics like movement and collision response. | def move_objects(self):
self.move_paddle()
self.move_balls()
self.check_collision() |
def bricks_remaining(self):
if len(self.levels.bricks) == 1 and not self.levels.bricks[0].breakable:
return False
return self.levels.bricks
def move_objects(self):
self.move_paddle()
self.move_balls()
self.check_collision()
def next_level(self):
self.clear_bal... | The main task of the code is to manage the game loop by continuously moving game objects, updating the screen at 150 FPS, and checking for game-ending conditions (no lives or bricks). It transitions to the next level if bricks remain and lives are still available, ultimately displaying a loss screen and pausing the gam... | def game_loop(self):
while True:
while self.bricks_remaining() and self.balls and self.scoreboard.lives:
self.move_objects()
update(150)
if not self.scoreboard.lives:
break
self.next_level()
self.display_loss()
s... |
def new_ball(self):
self.balls.append(Ball(self.window, self.paddle.obj.getP1().getX()+100, self.paddle.obj.getP1().getY()-50, 10))
def waiting(self):
while self.game_running is False:
update(10)
def game_loop(self):
while True:
while self.bricks_remaining() and self.ball... | The code's main task is to initialize a game by setting up the first level, creating a single ball, pausing briefly, and then starting the game loop to begin gameplay. | def setup_game(self):
self.levels.level_one()
for i in range(1):
self.new_ball()
self.waiting()
self.game_loop() |
def dis(meters, timing):
## try:
erg_total = 0
conn = sqlite3.connect(db_path)
cursor = conn.cursor() ##opens database
for row in cursor.execute("select * from record"):
erg_total += int(row[3])
erg_total = erg_total%50000
print(str(erg_total)+"egg")
dis_meters = meters-erg_total... | The code submits rowing data to a database, updates a GUI with recent entries, calculates total time/distance metrics for users, displays performance ratios, and tracks cumulative rowing days. It increments record IDs, retrieves input values, inserts data into the database, and dynamically updates labels with statistic... | def submit():
global choice
global choice2
global count_er
global control
global days
try: ##open database find recent then add 1
conn = sqlite3.connect(db_path)
cursor = conn.cursor() ##opens database
for row in cursor.execute("select * from record order by ID desc limit... |
def get_list_min_and_max_from_table(dict_table):
attributes_maximum_value = list()
attributes_minimum_value = list()
time_series = pd.DataFrame.from_dict(dict_table, orient="index")
columns = list(time_series.columns)
for column in columns:
attributes_maximum_value.append(time_series[column... | The main task of the code is to implement a naive k-P anonymity algorithm for time-series data, applying top-down clustering to achieve k-anonymity, followed by postprocessing and pattern-based anonymization. It reads input data, partitions sequences into clusters, generates generalized patterns through tree splitting,... | def main_naive(k_value=None, p_value=None, paa_value=None, dataset_path=None, output_path=None):
"""
k-P anonymity based on work of Shou et al. 2011,
Supporting Pattern-Preserving Anonymization for Time-Series Data
implementation of Naive approach
:param k_value:
:param p_value:
:param datas... |
def top_down_greedy_clustering(algorithm=None, time_series=None, partition_size=None, maximum_value=None,
minimum_value=None, time_series_clustered=None, tree_structure=None, group_label="o"):
"""
k-anonymity based on work of Xu et al. 2006,
Utility-Based Anonymization for ... | This code implements the KAPRA approach for k-anonymity on time-series data, following Shou et al. 2011. It reads input data, constructs a hierarchical tree structure, recycles underfilled nodes, forms groups via PAA-based clustering, merges groups to meet k-anonymity requirements, and outputs anonymized data with patt... | def main_kapra(k_value=None, p_value=None, paa_value=None, dataset_path=None, output_path=None):
"""
k-P anonymity based on work of Shou et al. 2011,
Supporting Pattern-Preserving Anonymization for Time-Series Data
implementation of KAPRA approach
:param k_value:
:param p_value:
:param datas... |
def data_scraper(name):
print(name)
link = "https://www.baseball-reference.com/players/" + name[0] + "/" + name + ".shtml"
driver.get(link)
war_list = []
games_list = []
pitcher = False
found = True
start_ratio = ''
yrs = []
salaries = []
notes = []
try:
tmp = dr... | This code processes team player data by reading contract files, extracting career statistics, adjusting them, and saving both original and adjusted datasets for each team. It merges scraped player stats with contract details, formats salary data, and outputs two CSV files: one with raw data and another with adjusted ca... | def construct_data(team):
df = pd.read_csv('Team Data/' + team + '-contracts.csv', converters={'career': eval})
career_wars = []
adjusted_wars = []
positions = []
games = []
ratios = []
years = []
contracts = []
for i in range(0, len(df)):
name = df.loc[i, 'Name'].split('\\')... |
def check_mandatory_param(self, job_config=None, raise_exception=False):
'''
Parameters:
- job_config: dict of config object. If no config is provided, use the dataloader's config as default
'''
job_config = job_config or self.dataloader.config
required_keys = ["sourc... | The code validates a job configuration by checking mandatory parameters, parameters specific to UPDATE/UPSERT operations, and the existence of the target table. It aggregates results into a boolean flag (`test_result`), returning `True` if all validations pass, `False` otherwise. The `raise_exception` parameter determi... | def validate_all(self, raise_exception=False):
test_result = True
self.print("Start validating job config")
self.print("Validating mandatory parameters...")
test_result &= self.check_mandatory_param(
raise_exception=raise_exception)
self.print(
"Validating... |
def object_apporach(self):
self.rate=rospy.Rate(1)
#initalize
self.ball_is_taken=False
self.choose="not"
self.cx=0
self.cy=0
self.W_buffer1=0
self.W_buffer2=0
self.W_buffer3=0
self.angle=10 #servo base angle
self.turn_wise=... | The code performs a sequence of robotic actions: detecting and approaching objects, grasping, moving upward, linear backward movement, 180° turn, descending, releasing, minor backward adjustment, 120° turn, re-grasping, repeating object approach, forward movement, and final release. The task involves manipulating objec... | def test1(self):
#object detect and approach
self.object_apporach()
#grap and up
self.grap_adv()
self.up()
# back move
self.linear_mov(-0.4)
#turn
self.turn(180)
# down and relase and back
self.down()
self.release()
... |
def turn(self, angle):# normal angle
#initialize
self.rot.angular.x = self.rot.angular.y = self.rot.angular.z = 0.0
self.rot.linear.x = self.rot.linear.y = self.rot.linear.z = 0.0
#set direction of turn
if(angle<0):
wise=-1 #cw
else:
wise=1 #c... | This code defines a robotic task to pick up objects, move them to specified target positions (green or beige), and return to a starting point. It uses predefined coordinates for poses, loops three times to handle multiple objects, and incorporates movement, grasping, and releasing actions with ROS-based navigation and ... | def test3(self):
#set point
start=GoalPose()
green=GoalPose()
beige=GoalPose()
[start.x, start.y, start.z, start.w]=[-0.610668178837,-0.193519999971,0.0494708014238,0.998775570289]
[green.x, green.y, green.z, green.w]=[2.80690463209,-0.851612960387,-0.137289560387,0.99053... |
def object_apporach(self):
self.rate=rospy.Rate(1)
#initalize
self.ball_is_taken=False
self.choose="not"
self.cx=0
self.cy=0
self.W_buffer1=0
self.W_buffer2=0
self.W_buffer3=0
self.angle=10 #servo base angle
self.turn_wise=... | The code defines a method `test4` that sequentially executes four operations: invoking `object_apporach` (likely for object-oriented processing), `grap_adv` (possibly graph or data analysis), `up` (maybe initialization or movement), and `web_cam` (handling webcam functionality). Its main task is to demonstrate or test ... | def test4(self):
self.object_apporach()
self.grap_adv()
self.up()
self.web_cam() |
def turn(self, angle):# normal angle
#initialize
self.rot.angular.x = self.rot.angular.y = self.rot.angular.z = 0.0
self.rot.linear.x = self.rot.linear.y = self.rot.linear.z = 0.0
#set direction of turn
if(angle<0):
wise=-1 #cw
else:
wise=1 #c... | The code's main task is to navigate a robotic arm to grasp and transport objects to designated target locations based on their URLs (small_beige, big_beige, big_green). It handles 5 objects, adjusting release movements for the first object at each target to avoid collisions, then returns to the starting position after ... | def final(self):
start=GoalPose()
target1=GoalPose()
target2=GoalPose()
target3=GoalPose()
t1_count=0
t2_count=0
t3_count=0
small_beige="https://postechackr-my.sharepoint.com/:i:/g/personal/kbc1106_postech_ac_kr/EUMWlJrHeBVKl3qkz6VEUrgBObjcAXi774ZPM7aKz7i... |
def turn(self, angle):# normal angle
#initialize
self.rot.angular.x = self.rot.angular.y = self.rot.angular.z = 0.0
self.rot.linear.x = self.rot.linear.y = self.rot.linear.z = 0.0
#set direction of turn
if(angle<0):
wise=-1 #cw
else:
wise=1 #c... | The main task of the code is to control a robotic arm to pick up objects, identify them via image URLs, move them to specific target positions based on their type (small_beige, big_beige, big_green), release them with position adjustments, and return to a start point for the next object. The process repeats for 5 objec... | def final2(self):
start=GoalPose()
target1=GoalPose()
target2=GoalPose()
target3=GoalPose()
t1_count=0
t2_count=0
t3_count=0
small_beige="https://postechackr-my.sharepoint.com/:i:/g/personal/kbc1106_postech_ac_kr/EUMWlJrHeBVKl3qkz6VEUrgBObjcAXi774ZPM7aKz7... |
def turn(self, angle):# normal angle
#initialize
self.rot.angular.x = self.rot.angular.y = self.rot.angular.z = 0.0
self.rot.linear.x = self.rot.linear.y = self.rot.linear.z = 0.0
#set direction of turn
if(angle<0):
wise=-1 #cw
else:
wise=1 #c... | The code controls a robotic arm to detect and manipulate objects via QR codes. It approaches, grasps, decodes QR URLs (small/big beige/green), adjusts grip angles, transports objects to pre-defined 3D target positions, releases them with count-dependent movements, and returns to the start. The loop repeats indefinitely... | def final3(self):
start=GoalPose()
target1=GoalPose()
target2=GoalPose()
target3=GoalPose()
t1_count=0
t2_count=0
t3_count=0
small_beige="https://postechackr-my.sharepoint.com/:i:/g/personal/kbc1106_postech_ac_kr/EUMWlJrHeBVKl3qkz6VEUrgBObjcAXi774ZPM7aKz7... |
def down(self):
print("down")
self.servo2_pub.publish(15)
rospy.sleep(1)
def release(self):
print("release")
self.servo_pub.publish(10)
rospy.sleep(1)
def final3(self):
start=GoalPose()
target1=GoalPose()
target2=GoalPose()
target3=GoalPose... | The code initializes a ROS node for robot control, setting up publishers for velocity, servos, and navigation actions. It handles object interaction (ball pickup/release), QR code decoding, and image processing via CvBridge. The UI allows starting/ending tasks, with functions for robot movement, positioning, and final ... | def __init__(self):
self.pub=rospy.Publisher('/cmd_vel',Twist,queue_size=1000)
self.servo_pub=rospy.Publisher('servo', UInt16, queue_size=1000)
self.servo2_pub=rospy.Publisher('servo2', UInt16, queue_size=1000)
self.ac=actionlib.SimpleActionClient('move_base', MoveBaseAction)
#se... |
def concertina(self,reverse):
cnt = 1
direct = True
seg_addr = reversed(self.segments_addr) if reverse else self.segments_addr
for i in reversed(seg_addr):
self.swirve(i, "left" if direct else "right")
cnt = cnt + 1 if cnt <= self.TURN_LENGTH else 1
di... | This code defines a `forward` method that routes execution to different movement strategies based on the `mode` parameter. If `mode` is 'concertina', 'serpentine', or 'sidewinding', it calls the corresponding method with the `reverse` flag, controlling directional behavior. The core task is to delegate motion logic to ... | def forward(self,mode="serpentine", reverse=False):
if mode == 'concertina':
self.concertina(reverse)
elif mode == "serpentine":
self.serpentine(reverse)
elif mode == "sidewinding":
self.sidewinding(reverse) |
def saml_email(request):
return request.session.get('email')
def initial(request):
auth_email = saml_email(request)
if auth_email is None and os.getenv('DISABLE_SAML') != '1':
return redirect('login_saml')
submitted = False
if request.method == 'POST':
form = ReqForm(request.POST)
... | This function handles updating a request by validating form data, checking user authorization, updating task states (e.g., completing, denying), and triggering related task transitions. It authenticates via SAML, retrieves request/task objects, applies form validation, modifies task states based on POST actions, update... | def update_request(request):
auth_email = saml_email(request)
if auth_email is None and os.getenv('DISABLE_SAML') != '1':
return redirect('login_saml')
try:
reqo = Req.objects.get(id=request.POST['request_id'])
except Req.DoesNotExist:
return initial(request)
try:
tas... |
def clear_screen():
pyautogui.hotkey('ctrl', 'shift', 'alt', 'k')
clear = lambda: subprocess.call('cls||clear', shell=True)
clear()
def use_spoon(self):
if self.spoons == 0:
print("You don't have any spoons left")
return
while True:
player = self.selec... | This method manages a player's turn in a game, allowing them to perform actions like placing cards, using specials, drawing cards, or eating bowls. It provides a menu of 7 options, validates input, and executes corresponding methods (e.g., use_spoon(), eat()). The player has 2 action points, with each valid action decr... | def turn(self):
print("Player Moves")
self.actions =2
while self.actions > 0:
clear_screen()
action_num = input(f"""{self.name} has {self.actions} moves left.
Available Moves:
1. Place Card
2. Use Special
3. Draw Card Pantry
4. Draw Card Deck
5. Wi... |
def print_hand(self):
names = [card.name for card in self.hand]
print(*names, sep=", ")
def place_card(self):
self.names = [card.name for card in self.hand]
while True:
card_to_place = input("Which card would you like to place into a bowl?: ")
if card_to_place in ... | The function draws a card from the deck, checks if the player has 5 cards (requiring confirmation), appends the card to the hand, reduces actions, and prompts the player to either place or discard the new card if actions remain. If no actions are left, it discards the card. Invalid inputs trigger re-prompts. | def draw_card_deck(self):
if len(self.hand) == 5:
confirmation = input("""You have 5 cards in your hand.
If you pick up another card, then you will have to use it immediately (if you have an action left)
or discard the card. Do you still want to draw the card? y/n: """).low... |
def add_job(self, job):
self.jobs[job] = []
self.update_job_status()
def add_server(self, server):
self.servers.append(server)
self.update_server_list()
def update_job_status(self):
for label in self.job_labels:
self.job_labels[label].destroy()
del label
... | This code continuously updates a GUI application by processing shared queues of servers, jobs, and events. It adds/removes servers, manages job assignments, updates job statuses, refreshes statistics, and displays memory usage. The loop ensures real-time synchronization of UI elements with backend data, maintaining sys... | def _loop(self):
while True:
self.root.update()
while Shared.servers.qsize() > 0:
if Shared.jobs.qsize() > 0:
self.add_job(Shared.jobs.get())
server, jobs = Shared.servers.get()
self.add_server(server)
fo... |
def run_mr_weighted_median(harmonized_data, beta_exp, beta_out, se_exp, se_out, nboot = 1000):
'''
Calculate the weighted median MR estimate.
Parameters
----------
harmonized_data : pandas.DataFrame
Dataframe containing the harmonized data.
beta_exp : str
Name of the column cont... | The function calculates a **penalized weighted median MR estimate** to assess causal effects, adjusting for heterogeneity. It uses harmonized data with exposure/outcome effect sizes and standard errors, applies a penalty to downweight unreliable instruments, computes a weighted median effect, and estimates standard err... | def run_mr_penalized_weighted_median(harmonized_data, beta_exp, beta_out, se_exp, se_out, nboot = 1000, penalty_con = 20):
'''
Calculate the penalized weighted median MR estimate.
Parameters
----------
harmonized_data : pandas.DataFrame
Dataframe containing the harmonized data.
beta_exp... |
def grab_data_fields(url, out_dir, save = True):
fields = query_ukbb(url)
if save:
# write the data-fields to the output file
with open(out_dir + '/data_fields.txt', 'w') as f:
f.write("\n".join(fields))
field_dict = get_descriptions_and_categories(fields)
# remove fields if it is a date/Age
for field,... | The main task of the code is to execute a Phenome-Wide Association Study (PheWAS) using UK Biobank data, either genotype or phenotype-based. It parses command-line arguments for input data paths, covariates, output settings, and analysis parameters. The script validates inputs, prepares directories, processes phenotype... | def main():
# Parse the command line arguments
parser = argparse.ArgumentParser(description='Run PheWAS using either genotype or phenotype data from the UKBB.')
# Arguments for PheWAS (either genotype based or phenotype)
parser.add_argument('--bfiles_directory', help='Directory containing bfiles', required=False, ... |
def clear_screen(): #clear the screen for a clean user interface
for i in range(30):
print("\n")
def attack(param_pokemon, challenger): #performs the attack sequence, requires a pokemon object, and a player object as the paramaters
if challenger == user: # if the user attacks
a... | The function handles a player's turn in a turn-based battle, processing actions like attacking, swapping Pokémon, or fleeing. It updates game state, checks for faints, and determines battle outcomes. If all player or opponent Pokémon faint, it updates win/loss stats and ends the battle. Returns True to continue the loo... | def turn(move, param_pokemon): #user's turn, returns True to while loop until the game is over
clear_screen()
back = False
while not back:
if move.lower()[0] == "a" and user_pokemon.hp >= 1:
back = attack(param_pokemon, user)
elif move.lower()[0] == "p":
... |
def clear_screen():
for i in range(30):
print("\n")
def attack(param_pokemon, challenger):
if challenger == user:
attack = input(f"{param_pokemon.challenge_display()}> ")
clear_screen()
if attack.lower()[0] == "p":
print(f"{challenger.... | The function 'turn' processes a player's move in a Pokémon battle, handling attack, swap, or flee actions. It updates game state, checks for faints, and determines battle outcomes, updating win/loss stats and coins accordingly. | def turn(move, param_pokemon):
clear_screen()
back = False
while not back:
if move.lower()[0] == "a" and user_pokemon.hp >= 1:
back = attack(param_pokemon, user)
elif move.lower()[0] == "p":
user.view_team()
back = swap(us... |
def LoadDatabaseInventory():
ifFile = os.path.isdir(DatabaseStorage)
if ifFile != True:
os.mkdir(DatabaseStorage)
else:
allDatabases = os.listdir(DatabaseStorage)
for database in allDatabases:
Databases.append(Database([database, DatabaseStorage], True))
for d... | The main task of the code is to handle user input for data processing by either reading from a file or manual entry. It creates necessary directories, prompts the user for input method (file, typing, or quit), executes corresponding functions (ReadFile() or UserInput()), and restarts the process for invalid choices, en... | def main():
# Makes necessary directory to store databases.
LoadDatabaseInventory()
#Determines user's method of input, a file or typing.
inputChoice = input("You can use q to quit.\nPlease select your choice of input of (f)ile or (t)yping: ").lower()[0]
if inputChoice == "f":
ReadFile()
... |
def makeModel(config):
numQubits = config.numQubits
dev = qml.device(config.dev, wires=numQubits, shots=1000, analytic=False)
@qml.qnode(dev)
def qcircuit(param, data):
for i in range(config.numLayers):
embeddingCircuit(config, data)
if config.fullEntangle:
... | The code trains a quantum circuit model using gradient descent with the Adam optimizer, iteratively updating parameters to minimize a cost function over batches of training data. It evaluates model accuracy on test and training sets at intervals, logging metrics like loss and accuracy to Weights & Biases (WandB) if ena... | def createAndTrain(config, WandB = False):
varInit = 0.01 * np.random.randn(config.numQubits, config.numLayers, 3)
opt = qml.AdamOptimizer()
batchSize = config.batchSize
var = varInit
qcircuit = makeModel(config)
qcircuit(var, X_train[0])
circ = qcircuit.draw()
if WandB:
wandb.lo... |
def disarm(self):
"""drone is before takeoff and is turned-off (may not be used)"""
pass
def arm(self):
"""drone is before takeoff and is ready to takeoff"""
self.client.confirmConnection()
self.client.enableApiControl(True)
self.client.armDisarm(True)
logger.info... | The main task of the code is to autonomously control a drone through a flight mission, including takeoff, target tracking via camera and directional adjustments, altitude regulation, and precision landing. It employs three stages: initial positioning and rotation toward a target, leash-based tracking and helipad approa... | def RUN(self):
"""
This is the function that initializes the drone's flight, from take-off to mission to autonomous landing.
"""
## ALGO STAGE 1
self.disarm()
self.arm()
self.takeoff()
self.mission()
camera_pose = airsim.Pose(airsim.Vect... |
def get_object(self):
return get_object_or_404(self.parent_model, id=self.parent_id)
def form_valid(self, formset, request=None):
for form in formset:
if form.cleaned_data != {}:
form_instance = form.save(commit=False)
form_instance.instance = self.get_object(... | This code processes a POST request by validating a formset, either with an existing instance (from get_object()) or without it if the instance is not found. If valid, it calls form_valid() with the formset and request; otherwise, it returns form_invalid() with the formset. | def post(self, request, *args, **kwargs):
try:
formset = self.formset(request.POST, request.FILES, instance=self.get_object(), prefix='form')
except Http404:
formset = self.formset(request.POST, request.FILES, prefix='form')
if formset.is_valid():
return sel... |
def coffeeOn():
GPIO.output(out_relay,GPIO.HIGH)
def printSensorStates():
notWet = GPIO.input(in_notWet)
print("Water Level: " + str(pingWater()))
print("Reservoir Temp: " + str(readTemp()[2:]))
print("Element Temp: " + str(readTemp()[:2]))
x=""
if(notWet):
x = "!!Critical Water ... | The function `brewCoffee()` activates a coffee machine by calling `coffeeOn()`, then continuously monitors a sensor (`in_notWet`) in a loop. It prints sensor states until the sensor detects a non-zero value (indicating a change in condition, such as water level or readiness). Once the loop exits, it deactivates the cof... | def brewCoffee():
#setupPin()
coffeeOn()
while GPIO.input(in_notWet) == 0:
printSensorStates()
coffeeOff() |
def expand_message():
"""Build all of the documents in order from MAX_DEPTH up to depth 0."""
groups = [[make_document(MAX_DEPTH, secret=letter) for letter in END_MESSAGE]]
for i in reversed(list(range(1, MAX_DEPTH))):
groups.append(group_nodes(groups[-1], i))
start_page = dict(
depth=... | The main task of the code is to process structured messages into a flattened JSON format, save it to a file, and provide user feedback. It initializes logging, expands messages into node groups, flattens the structure, writes the result to JSON, and prints success messages with optional customization instructions. | def run():
log_format = "%(levelname)s:%(message)s"
logging.basicConfig(level=logging.DEBUG, format=log_format)
# Set it up ...
node_groups = expand_message()
# ... and knock it down. boom.
flat_data = flatten_tree(node_groups)
with open(JSON_FILE, "w") as f:
json.dump(flat_data, ... |
def set_alpha_range(self):
self.alpha_range = set(range(1, self.alpha + 2))
def allocate_all(self) -> None:
"""
Allocates all users to their alpha-neighbors.
If users and facilities are same set of points,
the rows for the centers won't be updated in allocations matrix.
... | This method resets the solver's alpha parameter to a new value while preserving the existing solution. It updates the alpha range, reallocates resources, and adjusts the objective function accordingly. | def reset_alpha(self, new_alpha: int) -> None:
"""
Resets this solver with `new_alpha` as the alpha parameter,
keeping the same solution.
"""
self.alpha = new_alpha
self.set_alpha_range()
self.allocate_all()
self.update_obj_func() |
def __init_allocations(self) -> None:
self.solution.allocations = [
[0 for _ in range(self.instance.m)] for _ in range(self.instance.n)
]
def allocate_all(self) -> None:
"""
Allocates all users to their alpha-neighbors.
If users and facilities are same set of points,... | The code implements the Randomized Greedy Dispersion (RGD) heuristic to construct a facility location solution. It iteratively selects facilities to insert into the solution, using distance thresholds adjusted by a parameter β to balance dispersion. The algorithm randomly chooses initial facilities and greedily adds ot... | def construct(self, beta: float = 0) -> Solution:
"""
Randomized Greedy Dispersion (RGD) construction heuristic.
Time O(mp)
"""
# distances from each facility to current solution
# O(m)
s_dists = [math.inf] * self.instance.m
solution = Solution()
... |
def move(self, facility_in: int) -> MovedFacility:
"""
Determines the best facility to remove if `facility_in` is inserted,
and the objective function resulting from the swap.
Time O(pn)
"""
# best objective function so far
best_radius = 0
# O(p)
... | This method performs Alpha Fast Vertex Substitution (ANPCP) local search to improve a solution by iteratively swapping closed facilities with open ones, aiming to minimize the objective function (radius). It checks all closed facilities, evaluates potential swaps, and applies the best improvement (or first improvement ... | def fast_vertex_substitution(self, is_first_improvement: bool) -> Solution:
"""
Alpha Fast Vertex Substitution (ANPCP) local search heuristic.
Time O(mpn)
"""
moves = 0
is_improved = True
while is_improved:
current_radius = self.solution.get_obj_func(... |
def set_alpha_range(self):
self.alpha_range = set(range(1, self.alpha + 2))
def init_solution(self):
self.solution = Solution()
self.__init_allocations()
def randomize_solution(self) -> Solution:
self.solution.open_facilities = set(
random.sample(self.instance.facilities_inde... | The code's main task is to initialize the solution for a facility location problem. It sets alpha parameters, initializes a solution, and conditionally randomizes it if `with_random_solution` is True. If not, it sets all facilities as closed, using the instance's facility indexes. This prepares the solver's initial sta... | def __post_init__(self):
self.set_alpha_range()
self.init_solution()
if self.with_random_solution:
self.randomize_solution()
else:
self.solution.closed_facilities = set(self.instance.facilities_indexes) |
def init_solution(self):
self.solution = Solution()
self.__init_allocations()
def construct(self, beta: float = 0) -> Solution:
"""
Randomized Greedy Dispersion (RGD) construction heuristic.
Time O(mp)
"""
# distances from each facility to current solution
... | The code implements the GRASP metaheuristic to find an optimal solution by iteratively constructing candidate solutions using a randomized constructive heuristic (controlled by `beta`) and local search (fast vertex substitution). It stops after `iters` consecutive non-improving iterations or when the `time_limit` is re... | def grasp(self, iters: int, beta: float = 0, time_limit: float = -1) -> Solution:
"""
Applies the GRASP metaheuristic to the current solver,
and stops when either `iters` or `time_limit` is reached.
`iters`: Number of consecutive iterations without improvement to stop.
`beta`: ... |
def init_solution(self):
self.solution = Solution()
self.__init_allocations()
def construct(self, beta: float = 0) -> Solution:
"""
Randomized Greedy Dispersion (RGD) construction heuristic.
Time O(mp)
"""
# distances from each facility to current solution
... | The function `_grasp_iters_detailed` executes a GRASP algorithm for a specified number of iterations (`max_iters`), using a given or randomized `beta` parameter to guide solution construction. It tracks metrics such as objective function values (RGD_OF, AFVS_OF), total time, and whether a new best solution is found in ... | def _grasp_iters_detailed(self, max_iters: int, beta: float) -> pd.DataFrame:
"""
Modified method for the experiment of calibrating iterations.
To use GRASP for other purposes, see `grasp`.
"""
datalist = list()
best_solution = None
best_radius = current_radius ... |
def drawComponent(self):
for i in range(0, self.peices, 2):
pygame.draw.rect(self.surface, (120, 60, 30), [(i % 8+(i//8) % 2)*self.squareSize, (i//8)*self.squareSize, self.squareSize, self.squareSize])
pygame.draw.rect(self.surface, (245, 245, 220), [((i+1) % 8-((i+1)//8) % 2)... | The code initializes a game loop where the player selects their color (W/B), sets the computer's color, and starts the game. It ensures valid color input, draws game components, and determines turn order. If the player is Black, the computer moves first. The loop processes events while the game is active, managing play... | def playGame(self):
self.surface.fill((0, 0, 0))
while(self.playerColor != "W" and self.playerColor != "B"):
self.playerColor = input("Select Color (W/B): ")
self.drawComponent()
if self.playerColor == "W":
self.computerColor = "B"
... |
def psf2otf(psf, shape):
if np.all(psf == 0):
return np.zeros_like(psf)
inshape = psf.shape
psf = zero_pad(psf, shape, position='corner')
for axis, axis_size in enumerate(inshape):
psf = np.roll(psf, -int(axis_size / 2), axis=axis)
otf = np.fft.fft2(psf)
n_ops = np.sum(psf.si... | This code removes reflections from an image by decomposing it into two components: L1 (reflection) and L2 (original image). It uses filters, FFT-based operations, and iterative thresholding to enforce constraints, normalizing L1 within specified bounds [lb, hb] and subtracting it from the input image I to obtain L2. | def reflection_removal(I, lamda, lb, hb, L1_0=None):
N, M, D = I.shape
# filters
f1 = np.array([[1, -1]])
f2 = np.array([[1], [-1]])
f3 = np.array([[0, -1, 0],
[-1, 4, -1],
[0, -1, 0]])
sizeI2D = (N, M)
otfFx = psf2otf(f1, sizeI2D)
otfFy = psf2otf(... |
def im2double(im):
try:
N, M, D = im.shape
except:
N, M = im.shape
D = 1
y = np.zeros(im.shape, dtype=float)
for i in range(D):
min_pixel = np.min(im[:, :, i])
max_pixel = np.max(im[:, :, i])
y[:, :, i] = (im[:, :, i] - min_pixel)*1.0/(max_pixel - min_pixe... | The function suppresses high-frequency components in an image by thresholding gradients, computing a Laplacian of the gradient field, and solving a Poisson equation using a DCT-based method. It combines the thresholded Laplacian with a scaled original image to generate a smoothed output, balancing detail preservation a... | def reflectSuppress(Im, h, epsilon):
Y = im2double(Im)
m, n, r = Y.shape
T = np.zeros(Y.shape)
Y_Laplacian_2 = np.zeros(Y.shape)
for dim in range(0, r):
GRAD = grad(Y[:, :, dim])
GRAD_x = GRAD[:, :, 0]
GRAD_y = GRAD[:, :, 1]
GRAD_norm = np.sqrt(GRAD_x**2 + GRAD_y**... |
def get_lives(self):
return self.__lives_left
def get_game_letters(self):
return self.__game_letters
def correct_guess(self, guess):
for letter in self.get_game_letters():
if guess.lower() == letter[0].lower():
return True
return False
def set_lives(self, live... | The code implements a Hangman game where the player guesses letters of a hidden word. It tracks remaining lives, displays the hangman figure and guessed letters, processes correct/incorrect guesses, and checks for win/loss conditions. The game ends when the player either guesses all letters correctly or exceeds 6 incor... | def play_game(self):
print ("Hangman is a simple word guessing game. Players try to figure out an unknown word by guessing letters.\n"
"If too many letters which do not appear in the word are guessed, the player is hanged (and loses).\n"
"In this version of the game, you are allow... |
def recommend_best_approach(self, problem_description):
research_results = self.research_related_topic(problem_description)
question = f"Recommend the best approach for the following problem, considering the research: {problem_description}\n\nResearchResults:\n{research_results}"
result_encoded ... | The code processes a given task by recommending an optimal approach, researching related topics, generating code based on the recommended model, and compiling these results into a human-readable format for the user. | def process_task(self, task_description):
recommended_model = self.recommend_best_approach(task_description)
research_results = self.research_related_topic(task_description)
generated_code = self.process_coding_task(task_description, recommended_model)
final_output = f"RecommendedModel: ... |
def load_test_results() -> pd.DataFrame:
return pd.read_csv(Path(TEST_RESULTS_FOLDER, RAW_TEST_PREDS_FILENAME))
def drop_all_cols_but(df: pd.DataFrame, cols: List[str]) -> pd.DataFrame:
return df.drop(columns=df.columns.difference(cols))
def drop_cols_in_multiple_categories(df: pd.DataFrame, df_prefix_cols_only... | The code processes test results by renaming columns, filtering data, and visualizing error metrics. It generates heatmaps for mean errors across categories for multiple regression models (e.g., XGB, OLS) and plots ellipses/residuals for model performance. Key steps include data filtering, rescaling, and dynamic plottin... | def main():
TEST_RESULTS_FOLDER.mkdir(parents=True, exist_ok=True)
plt.rcParams["figure.autolayout"] = True
df = load_test_results()
renames = {**REGRESSOR_RENAMES, **DUMMY_REGRESSOR_RENAMES}
df = df.rename(columns=renames)
sns.set(font_scale=1)
for prefix, k, col_name in PREFIXS_TO_VISUALI... |
def __convert_image_to_base64_string(self, image, image_format, color_space, job_data):
"""Converts given PIL image to base64 string with given image_format and image metadata parsed from job_data.
Args:
image (PIL.PngImagePlugin.PngImageFile): Python pillow image to be converted
... | The function converts output data of types 'image', 'image_list', and 'audio' in a dictionary to base64-encoded string representations using specified formats and color spaces, modifying the original dictionary in place and returning it. It checks the output type from the description, applies corresponding conversion m... | def __convert_output_types_to_string_representation(
self,
output_data,
output_name,
output_description,
job_data
):
"""Converts parameters output data from type 'image' and 'image_list' to base64 strings.
Args:
output_data (dict): worker [OU... |
def get_current_job_data(self, job_id=None):
"""get the job_data of current job to be processed
Args:
job_id (string, optional): For single job processing (max_job_batch=1) the job_id is not required.
For batch job processing (max_job_batch>1) the job_id is requ... | The main task of the code is to process and send job results to an API server via the /worker_job_result endpoint. It prepares results with metadata, handles connection errors, and updates job status tracking. The function ensures proper formatting, authentication, and error handling during HTTP requests to the server,... | def send_job_results(self, results, job_data=None):
"""Process/convert job results and send it to API Server on route /worker_job_result.
Args:
results (dict): worker [OUTPUT] result parameters (f.i. 'image', 'images' or 'text').
Example results: ``{'images': [<PIL.Image.Ima... |
def get_current_job_data(self, job_id=None):
"""get the job_data of current job to be processed
Args:
job_id (string, optional): For single job processing (max_job_batch=1) the job_id is not required.
For batch job processing (max_job_batch>1) the job_id is requ... | The function `send_progress` sends job progress (e.g., percentage or tokens generated) and associated data to an API server asynchronously via `/worker_job_progress`. It prepares a payload with job parameters, progress, and processed output data, then uses `__fetch_async` to transmit it. Callbacks handle successful res... | def send_progress(
self,
progress,
progress_data=None,
progress_received_callback=None,
progress_error_callback=None,
job_data=None
):
"""Processes/converts job progress information and data and sends it to API Server on route /worker_job_progress asynchro... |
def get_current_job_batch_data(self):
"""get the job_datas of the current batch as list
Returns:
list: the list of job_datas of the current jobs to be processed
"""
return self.__current_job_cmd.get('job_data', [])
def __prepare_output(self, output_data, job_da... | This function sends batch progress data (e.g., percentages or token counts) and associated job information to an API server via an asynchronous HTTP request to '/worker_job_progress'. It packages progress values, job metadata, and output data into payloads, then uses multiprocessing to trigger the request. Callbacks ha... | def send_batch_progress(
self,
batch_progress,
progress_batch_data,
progress_received_callback=None,
progress_error_callback=None,
job_batch_data=None
):
"""Processes/converts job progress information and data and sends it to API Server on route /worker_jo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.