dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def priority(queue): #find the path with shortest distance that will be selected from the priority queue
min = math.inf
index = 0
for check in range(len(queue)):
_,value,_,_ = queue[check]
if value<min:
min = value
index = check #index of the shortest path
return ... | The code implements the A* algorithm to find a path for an agent from a starting position to a goal, considering local constraints. It uses a priority queue (open_set) and tracks visited nodes. The algorithm checks if the current node is near the goal (within a radius) and returns the path if so. Neighbors are generate... | def local_A_star(agent_start,agent_goal):
open_set = []
visited = []
start = agent_start
tcost = 0
gcost = 0
path = [start]
open_set.append((start,tcost,gcost,path))
while len(open_set)>0:
index = priority(open_set)
(shortest,_,gvalue,path) = open_set[index] #select the n... |
def priority(queue):
min = math.inf
index = 0
for check in range(len(queue)):
_,value,_,_ = queue[check]
if value<min:
min = value
index = check
return index
def local_check_visited(current,visited):
for x,y,th in visited:
if current[0]== x and curren... | This code implements a local A* pathfinding algorithm to navigate an agent from a starting position to a goal. It uses a priority queue (open_set) and tracks visited nodes, calculating tentative and total costs (tcost, gcost) for each neighbor. The algorithm checks if a node is within a specified radius of the goal and... | def local_A_star(agent_start,agent_goal):
open_set = []
visited = []
start = agent_start
tcost = 0
gcost = 0
path = [start]
open_set.append((start,tcost,gcost,path))
while len(open_set)>0:
index = priority(open_set)
(shortest,_,gvalue,path) = open_set[index]
open... |
def priority(self,queue):
min = math.inf
index = 0
for i in range(len(queue)):
_,value,_,_ = queue[i]
if value < min:
min = value
index = i
return index
def visited_checker(self,curr_node,visited):
for x,y,theta in visited:
... | This code implements the A* algorithm to find a path from a robot's start position to a goal. It uses a priority queue to explore nodes, with the priority determined by a custom function. The algorithm checks if a node is near the goal, and if so, returns the path. Neighbors are generated, and their tentative costs (g)... | def A_star(self):
queue = []
visited = []
start = self.robot_start
f = 0
g = 0
path = [start]
queue.append((start,f,g,path))
while len(queue) > 0:
index = self.priority(queue)
(shortest,_,g_value,path) = queue[index]
que... |
def priority(self,queue):
min = math.inf
index = 0
for i in range(len(queue)):
_,value,_,_ = queue[i]
if value < min:
min = value
index = i
return index
def visited_checker(self,curr_node,visited):
for x,y,theta,xt,yt,th_t i... | This function implements the A* algorithm to find the optimal path for a robot and trailer to reach a goal state. It initializes a queue with the start position, explores neighbors, calculates costs (g) and heuristics (f), and prioritizes nodes to minimize total cost. The algorithm checks if the current state is near t... | def A_star(self):
queue = []
visited = []
start = [self.robot_start[0],self.robot_start[1],self.robot_start[2],self.trailer_start[0],self.trailer_start[1],self.trailer_start[2]]
f = 0
g = 0
path = [start]
queue.append((start,f,g,path))
while len(queue) > 0... |
def score_system(industries: list[Industry]) -> \
tuple[list[Industry], list[Industry], list[Industry]]:
"""The helper function of output_score
Calculate score1 for every industry in the input list.
return a tuple contains three lists:
- first is the list contains all regular industries
... | The function processes GDP data from a file, calculates scores for regular industries using a scoring system, adjusts scores with recovery logic, and returns three lists: industry names, their corresponding score1 values, and score2 values. | def output_score(filename: str) -> tuple[list, list, list]:
"""Output the score for every industry that is regular. The items in the first output list
are the names of the industries; the items in the second output list are their score1s; the
items in the third output list are their score2s."""
global_i... |
def extract_molecules_from_pdfs(pdfs : list[tuple[str, bytes]],
target_segment_directory : str = None,
decimer_complement : bool = True,
get_text : bool = False,
text_direction : str = 'righ... | The main task of the code is to parse command-line arguments for extracting DrugHunter molecules, either from a specified URL or by year/month range. It validates inputs, handles text/segmentation options, and executes extraction functions accordingly, ensuring compatibility with different URL formats and user-specifie... | def main():
"""
Main function to handle command-line arguments and execute the appropriate extraction based on the arguments.
see -h, --help for documentation
"""
parser = ArgumentParser(description='DrugHunter extractor')
parser.add_argument('-y', '--year', type=int, help='(int) targeted y... |
def getFileName():
filename = askopenfilename()
#filename = "benchmark6.csv"
return filename
def readFile(filename):
data = pd.read_csv(filename, sep="\t")
return data
def makeGraph(graph, data):
for _, row in data.iterrows():
graph.addNode(row["Vertex1"])
graph.addNode(row["Ver... | The main task of the code is to read a file containing graph data, construct a graph structure, compute the maximum flow within the graph, and write the graph details along with the maximum flow results to a CSV file. | def main():
filename = getFileName()
data = readFile(filename)
g = Graph()
makeGraph(g, data)
mf = maxFlow(g)
writeToCSV(g, mf) |
def S_i(x: ctx_iv.ivmpf, i: int, print_val: bool = False) -> ctx_iv.ivmpf: # i >= 0
output = iv.mpf('1') # S_0 = 1
if i == 0:
return output
stored_val: dict[str, ctx_iv.ivmpf] = {}
for j in range(i): ... | The function computes a value $ M_{l,k} $ by evaluating the expression $ \frac{x(S_k + T_l)}{P_k + Q_l} $, where $ S_k, T_l, P_k, Q_l $ are results from helper functions. If `print_val` is True, it prints the computed value with formatting. The result is returned as a `ivmpf` type. | def M_lk(x: ctx_iv.ivmpf, l: int, k: int, print_val: bool = False) -> ctx_iv.ivmpf:
numerator = iv.fadd(S_i(x, k, print_val), T_i(x, l, print_val)) # S_k + T_l
numerator = iv.fmul(x, numerator) # x(S_k + T_l)
denominator = iv.fadd(P_i(x,... |
def S_i(x: ctx_iv.ivmpf, i: int, print_val: bool = False) -> ctx_iv.ivmpf: # i >= 0
output = iv.mpf('1') # S_0 = 1
if i == 0:
return output
stored_val: dict[str, ctx_iv.ivmpf] = {}
for j in range(i): ... | The function computes a mathematical expression involving inputs `a` and `b` with parameters `l` and `k`. It calculates the numerator as `a * (S_k(a) + T_l(b))` and the denominator as `P_k(b) + Q_l(a)`, then returns their division. If `print_val` is True, it also prints the result as `M_{l,k}^down`.)> | def M_lk_down(a: ctx_iv.ivmpf, b: ctx_iv.ivmpf, l: int, k: int, print_val: bool = False) -> ctx_iv.ivmpf:
numerator = iv.fadd(S_i(a, k, print_val), T_i(b, l, print_val)) # S_k(a) + T_l(b)
numerator = iv.fmul(a, numerator) # a(S_k(a) + T_l(b))... |
def get_piece(self, pos):
return self.board[pos[0]][pos[1]]
def in_check(self, team):
king_row, king_col = self.get_ranks_position(team, Rank.KING)
test_queen = Queen(team)
test_knight = Knight(team)
# get all legal moves for queen and knight from king's position
# th... | The code handles a chess piece's movement by validating the move, checking if the team is in check, executing the move if valid, and ensuring the move doesn't leave the team in check. It updates the board, marks the piece's first move status, and returns True on success or False with error messages if invalid. | def move(self, current_pos, new_pos):
piece = self.get_piece(current_pos)
if not piece:
return False
team_in_check = self.in_check(piece.get_team())
if team_in_check:
print("You're in check!")
if piece.move(self.board, current_pos, new_pos):
... |
def _generate_indices(self) -> None:
""" Creates indices for data windows """
def select(values, indices):
if values[0] == values[1] + 10:
return set(indices)
else:
return {}
ind = np.arange(self._label_channel.shape[0])
ind = ind[self._label_channel > 0]
indices = set(... | The main task of the code is to generate and prepare datasets for machine learning, including data preprocessing, windowing, wavelet transforms, and splitting into train/val/test sets. It creates labeled TensorFlow datasets from neural data, applies transformations, and stores them in the object's train, val, and test ... | def create_dataset(self,
event_length : Optional[int] = 300,
indices_noise : Optional[np.ndarray] = None,
plot_indices : Optional[bool] = True,
skip_in_repeat : Optional[int] = 100,
listen_repeat_noise : Optional[Tu... |
def _get_arp(note='C', key='major', level=4):
arpeg = _major_arp() if key == 'major' else _minor_arp()
prog = arpeg[note]
li, lj = ["_%s" % str(i) for i in (level, level + 1)]
return [note + li, prog[0] + li, prog[1] + li, note + lj]
def _produce_audio(notes, seconds=2, fs=44100):
import numpy as np... | The main task of the code is to generate and play an arpeggio based on a specified musical note, key (major/minor), and level. It retrieves the arpeggio pattern, converts it into audio, and plays the resulting sound. | def play_arpeggio(note="C", key="major", level=4):
"""plays the arpeggio given a note and key"""
arp = _get_arp(note=note, key=key, level=level)
# get audio
aud = _produce_audio(arp)
# play
_play_audio(aud) |
def gen_localdir(self, localdir):
"""
Generate local directory where track will be saved.
Create it if not exists.
"""
directory = "{0}/{1}/".format(localdir, self.get("username"))
if not os.path.exists(directory):
os.makedirs(directory)
return directo... | This code downloads a track to a specified local directory with retry logic, checking for existing files or ignored tracks. It retrieves the download link, handles errors by retrying up to max_retry times, and renames the file with the correct extension upon success. If all retries fail, it raises an error. The functio... | def download(self, localdir, max_retry):
""" Download a track in local directory. """
local_file = self.gen_localdir(localdir) + self.gen_filename()
if self.track_exists(localdir):
print("Track {0} already downloaded, skipping!".format(
self.get("id")))
r... |
def secondaryStructure(primers, cutoff, hybridization_method):
#hybridization_method: seq fold = 1, unafold = 2
newprimers=[]
for primer in primers:
if hybridization_method == 1: #seqfold
score = dg(primer[0], temp=37.0)
elif hybridization_method == 2: #unafold
score ... | The function `evaluateOverlaps` filters and selects the optimal overlapping sequence from a list by applying secondary structure analysis, self-dimer checks, and melting temperature constraints. It sorts remaining sequences by the absolute value of their third element (likely a score) and returns the top candidate if v... | def evaluateOverlaps(seq, overlapseqs, overlaptemps, deltaGThreshold, selfDimersThreshold, hybridization_method):
overlapseqs = secondaryStructure(overlapseqs, deltaGThreshold, hybridization_method)
overlapseqs = selfDimers(overlapseqs, selfDimersThreshold)
overlapseqs = meltingTemperature(overlapseqs, over... |
def create_key_square(key:str):
""" Membuat matrix alfabet 5x5 untuk kunci enkripsi berdasarkan string key"""
alfabet_key = []
for letter in key:
letter = 'i' if letter == 'j' else letter
if not letter in alfabet_key:
alfabet_key.append(letter)
sisa_alfabet = []
for i ... | The code implements the Playfair cipher encryption algorithm by processing the key and plaintext (removing non-alphabetic characters and converting to lowercase), generating a 5x5 key square, splitting plaintext into digraphs, and encrypting each pair using row, column, or rectangular rules based on their positions in ... | def playfair_encrypt(key: str, plaintext: str):
""" Fungsi enkripsi menggunakan playfair algorithm"""
key = lib.remove_punctuation(key)
key = lib.remove_number(key)
key = lib.remove_space(key)
key = lib.to_lower_case(key)
plaintext = lib.remove_punctuation(plaintext)
plaintext = lib.remove... |
def _upload_graph_and_snapshots(self, *args):
"""Upload the graph and snapshots to the robot."""
print("Loading the graph from disk into local storage...")
self._upload_filepath = "/home/spot/track"
with open(self._upload_filepath + "/graph", "rb") as graph_file:
# Load the g... | The code's main task is to control a robot's navigation by initializing systems, uploading maps, powering on the robot, setting localization, and repeatedly navigating to a specified waypoint while handling errors. It waits for an emergency stop signal, uploads graph data, powers on the robot, sets initial localization... | def route(self):
time.sleep(1)
while self._estop_client.get_status().stop_level != 4:
time.sleep(1)
self._upload_graph_and_snapshots()
self._robot.power_on(timeout_sec=20)
blocking_stand(self._robot_command_client, timeout_sec=10)
self._set_initial_localizatio... |
def mtime(filename):
"""Gets the file's mtime and tracks how many times we've called mtime()"""
app.mtime_calls += 1
return Path(filename).stat().st_mtime
def check_path(path):
"""Sanity-checks an expanded path - it must be absolute, under start_dir, and without
'..'s."""
path = str(path)
if... | The function `needs_rerun` determines if a task requires rebuilding by checking conditions like forced rebuilds, missing outputs, newer inputs, changed dependencies, or outdated depfiles. It compares file modification times and dependency statuses to decide if outputs are stale. If any condition triggers a rebuild, it ... | def needs_rerun(self, force=False):
"""Checks if a task needs to be re-run, and returns a non-empty reason if so."""
# Pylint really doesn't like this function, lol.
# pylint: disable=too-many-return-statements
# pylint: disable=too-many-branches
files_in = self.abs_files_in
... |
def augment(self, center, left, right, steering_angle, range_x=100, range_y=10):
image, steering_angle = self.choose_image(center, left, right, steering_angle)
image, steering_angle = self.random_flip(image, steering_angle)
image, steering_angle = self.random_translate(image, steering_angle, ran... | This function generates batches of preprocessed images and their corresponding steering angles for training or validation. It randomly shuffles image indices, applies data augmentation (60% chance) during training by combining center, left, and right images, preprocesses each image, and yields batches of size 'batch_si... | def generate_batch(self, image_paths, steering_angles, batch_size, is_training):
images = np.empty([batch_size, self.image_height, self.image_width, self.image_channels])
new_steering_angles = np.empty(batch_size)
while True:
index_in_batch = 0
for image_index in np.rand... |
def quaternion_product2(q1, q2):
q1 = np.reshape(q1,(1,4))
q2 = np.reshape(q2,(1,4))
Omega = skew_symmetric_4x4_B(q2)
return dot(q1, Omega)
def J_g(q):
q = np.reshape(q,(1,4))
q1, q2, q3, q4 = q[0,:]
J = array([ [-2*q3, 2*q4, -2*q1, 2*q2],
[2*q2, 2*q1, 2*q4, 2*q3],
[ 0, -4*q2, -4*q3, 0 ]])
return J
def ... | The MadgwickFilter function estimates the sensor's orientation (quaternion) relative to the earth frame by combining gyroscope data with accelerometer and magnetometer measurements (if enabled). It normalizes sensor data, calculates angular velocity derivatives, computes gradient descent steps using Jacobian matrices, ... | def MadgwickFilter(q_est, data, dt, alpha, omega_error_max,mag = True):
a_x, a_y, a_z = data[0], data[1], data[2]
g_x, g_y, g_z = data[3], data[4], data[5]
a = array([0, a_x, a_y, a_z])
a = a / norm(a) # normalization
w = array([0, g_x, g_y, g_z]) #omega
# -----------------------------------------
q_omega_dot =... |
def _full_path(self, path):
return join_paths(self.root, path)
def _metadata_names(self, path):
filename = strip_dot_enc(path)
public = self._metadata_full_path(f'{filename}.public')
private = self._metadata_full_path(f'{filename}.private')
finfo = self._metadata_full_path(f'{fi... | This code opens a file by resolving its full path, retrieving public/private metadata and file attributes, then delegating to an encryption-specific open method with the resolved path, metadata, and modification time. It returns 0 to indicate success. | def open(self, path, flags):
full_path = self._full_path(path)
public_metadata, private_metadata, _ = self._metadata_names(path)
attr = self.getattr(path)
self.enc_files.open(full_path, public_metadata, private_metadata, attr['st_mtime'])
return 0 |
def _full_path(self, path):
return join_paths(self.root, path)
def _is_file(self, path):
if not os.path.exists(self._full_path(path)):
return False
attr = self.getattr(path)
return attr['st_mode'] & stat.S_IFREG == stat.S_IFREG
def unlink(self, path):
full_path = sel... | The code renames a file or directory, updating its full path and associated metadata. If renaming a file, it handles metadata files, checks for existing files to replace, and updates encryption-related entries. For directories, it renames metadata and the directory itself. The function ensures consistent renaming acros... | def rename(self, old, new):
full_old_path = self._full_path(old)
full_new_path = self._full_path(new)
if self._is_file(old):
# Rinomino un file
if self._is_file(new):
self.unlink(new)
old_public_metadata, old_private_metadata, old_finfo = sel... |
def _add_users_to_hot_day_if_needed(self, date, users):
user_table = self._convert_date_to_hot_users_table_name(date)
all_users_set = set(self._get_all_users_available_in_hot_date(date))
self.database.executemany(
f'insert into {user_table} values (?)',
[(user_id,) for us... | The function generates a compressed snapshot of user online status for a specific date by mapping user IDs from input data to their online status, creating a boolean array for all available users on that date, and compressing this array for efficient storage or transmission. | def _get_hot_day_snapshot(self, date, data):
self._add_users_to_hot_day_if_needed(date,
[entry.user_id for entry in data])
all_users = self._get_all_users_available_in_hot_date(date)
data_dict = {entry.user_id: entry.online for entry in data}
... |
def decide_on_state(self, state):
self.inc_decide_state = self.acceptable_state(state, self.term, self.step)
for peer in self.peers:
Thread(target = self.ask_decide_on_state, args = (peer, state)).start()
clock = time.time()
while (time.time() - clock < (TIMEOUT / 2)):
... | The function determines the current state and decides the next action. If the state is valid, it selects an action and checks its validity. If invalid, it triggers an election and returns False; otherwise, returns the action. | def decide_on_state_and_action(self, state):
action_decided = False
state_decided = self.decide_on_state(state)
if state_decided:
action = self.sample_next_action()
action_decided = self.decide_on_action(action)
if action_decided == False:
self.is_elec... |
def lstm_preprocessing(target):
# df gets passed in here
con = sqlite3.connect("Data/games.sqlite")
create_training_tensor_lstm(target)
create_total_train_tensor()
# from pudb import set_trace; set_trace()
cur_szn_df = pd.read_sql_query(f"select * from \"games_2023-24_lstm\"", con, index_co... | The code trains an LSTM model for a given category using preprocessed data, trains it for 30 epochs, evaluates it across multiple thresholds (0–30), and stores confidence metrics per threshold in a dictionary for later analysis. | def train_and_test_lstm(category):
# from pudb import set_trace; set_trace()
train_dataloader, val_dataloader, test_dataloader = lstm_preprocessing(cat_to_metric[category])
num_epochs = 30
train_lstm(model, (train_dataloader, val_dataloader), num_epochs, dirpath, category)
thresholds = [0, 0.5, 1, 1... |
def load_prize_picks(date, category='all', future=False):
con = sqlite3.connect("Data/games.sqlite")
# season_df = pd.read_sql_query(f"select * from \"games_2023-24\"", con, index_col="index")
if category == 'all':
cats = ['Fantasy Score', 'Defensive Rebounds','Offensive Rebounds',
'3-PT Attempted'... | The function `load_display_evaluate_pp` loads, displays, and evaluates prize picks for a specified date and category. It calls `load_prize_picks` to retrieve data, `display_prize_picks` to show it, and `evaluate_prize_picks` to compute accuracy. The accuracy metric is printed for the given date and category, while othe... | def load_display_evaluate_pp(date, category):
load_prize_picks(date, category)
display_prize_picks(date, category)
accuracy, _, _, _ = evaluate_prize_picks(date, category)
print(f'accuracy on {date}', accuracy) |
def display_prize_picks(date, num_picks, category='all', sampling_type='total'):
print(f'{Fore.CYAN}{Style.BRIGHT}{category}{Style.RESET_ALL}')
con = sqlite3.connect("Data/games.sqlite")
df = pd.read_sql_query(f"select * from \"pp_preds_{date}\"", con, index_col="index")
num_picks_all = [3, 4, 5, 6, num... | This function evaluates prize picks for a given date and category by either retrieving player results or assessing picks using a threshold or confidence interval, depending on parameters. It first fetches prize picks data, then applies evaluation logic based on sampling type, category, and threshold inputs to analyze p... | def display_evaluate_pp(date, category, num_picks, threshold=None, sampling_type='threshold'):
# from pudb import set_trace; set_trace()
df = display_prize_picks(date, num_picks, category)
if sampling_type == 'threshold':
get_player_results(date, category='all', specific_player_df=df)
else:
... |
def __chunks(l, n):
n = max(1, n)
return (l[i : i + n] for i in range(0, len(l), n))
def get_tracking_by_batch(self, tracking_numbers=None):
tracking_numbers = tracking_numbers or []
if len(tracking_numbers) > 40:
raise TooMuchTrackingNumbers('Too much trackings in a batch')
... | This function retrieves tracking information for multiple tracking numbers in batches of 40. It retries up to 10 times with exponential backoff if errors occur, switching IPs and restarting drivers to handle failures. It aggregates results and returns them after processing all batches. | def get_all_trackings(self, tracking_numbers=None):
total_time = 0
tracking_results = []
for tracking_batch in self.__chunks(tracking_numbers, 40):
for i in range(10):
try:
start_time = time.time()
tracking_batch_result = self.g... |
def is_current_position_exist(symbol):
positions = mt5.positions_get(symbol=symbol)
return len(positions) > 0
def enter_position(symbol_input, stop_loss_pips_input, is_buy_input):
######## START TRADE INPUTS ########
is_stop_limit = False
stop_limit_price = 1.08726
######## END TRADE INPUTS ... | The main task of the code is to manage trading positions by creating an initial position if none exists, switching between long/short positions based on the profitability of the last trade, and tracking statistics like profit, win/loss trades, and win ratio. It uses global variables to maintain state and logs detailed ... | def main():
global isFirstPosition
global stat_profit
global stat_loss_trades
global stat_win_trades
if is_current_position_exist(bot_symbol) == False and isFirstPosition == True: # If there is no position and start, create one
logger.info("***************************************************... |
def comprobacion(cadena,pruebaParidad):
sinParidad = [cadena[2],cadena[4],cadena[5],cadena[6],cadena[8],cadena[9],cadena[10],cadena[11],cadena[12],cadena[13],cadena[14],cadena[16]]
p1 = [sinParidad[0],sinParidad[1],sinParidad[3],sinParidad[4],sinParidad[6],sinParidad[8],sinParidad[10],sinParidad[11]]
p2 =... | The code creates a GUI window to display and validate parity bits in a data word. It uses Tkinter to generate a table with labels (p1-p5, d1-d12) and input fields, populates data rows from a `comprobacion` function, and checks for errors using `comprobacionSimplificada`. If an error is detected, it identifies the fault... | def ventana2(hilera):
root = Tk()
root.title("Tabla No.2 Comprobacion de los bits de paridad (con primer bit de la derecha cambiado)")
data = comprobacion(hilera,1)
for r in range(0, 7):
for c in range(0, 20):
size = 10
if c > 0 and c < 12:
size = 15
... |
def b_click(b):
if b["text"] == " ":
b["text"] = player
return True
else:
return False
def addMove(bot_or_player, position):
if Check_Space(position):
board[position] = bot_or_player
if (checkDraw()):
messagebox.showinfo("Tic Tac Toe", "Draw!!")
if... | The code handles a player's move in a game by checking if a specific button (1-9) is clickable. If valid, it records the move, triggers the bot's turn, and shows an error if the button is already selected. The main task is to manage player input validation and game state updates in a turn-based game like Tic-Tac-Toe. | def start_commad(number):
if number == 1:
if (b_click(Button_1) == True):
addMove(player, 1)
botMove()
else:
messagebox.showerror("Warning", "Already selected!\n")
if number == 2:
if (b_click(Button_2) == True):
addMove(player, 2)
... |
def converge(scanners: List[Scanner]):
in_place = {scanners[0]}
while len(in_place) < len(scanners):
print('IN PLACE', [x.label for x in in_place])
for i in range(len(scanners)):
s1 = scanners[i]
for s2 in scanners[i + 1:]:
if (s1 in in_place or s2 in in_p... | The main task of the code is to read input data from "19.txt", split it into scanner data, process and align the scanners using the `converge` function, then compute and print two results (`part1` and `part2`) based on the processed scanner data. | def main():
data = open("19.txt", 'r').read()
scanners = [Scanner(scanner) for scanner in data.split("\n\n")]
converge(scanners)
print(part1(scanners))
print(part2(scanners)) |
def parse_test_dataset(file_paths, category):
"""This function iterates over all input test files and extracts record information from each single file.
Use Yield for optimization purpose causes reading when needed.
Args:
file_paths: List containing all the paths to test files.
category: ... | The function prepares a test set for protein data by processing sequences, PSSM, and distance maps through padding, batching, and tensor conversion. It iterates over parsed datasets, widens features, aligns them to a crop size, generates batches, and returns tensors for input (X), labels (y), and masks (mask), ensuring... | def prepare_test_set(path:list, modelling_group:int, crop_size, padding_value, min_bin_val, max_bin_val, num_bins, batch_size):
X = []
y = []
mask = []
for primary, evolutionary, tertiary, ter_mask in parse_test_dataset(path, modelling_group):
if (primary != None):
primary_2D = widen... |
def get_data(file_name):
positives = []
nregatives = []
all_corpus = []
labels = []
# positive_corpus= []
# negative_corpus = []
with open(file_name,encoding='utf8') as fp:
next(fp)
for line in fp:
a = line.split(',')
if a[1] == '1':
... | The main task of the code is to perform text classification on Twitter data using a Multinomial Naive Bayes model. It loads and cleans data, splits it into training/test sets, creates a Bag-of-Words vocabulary, trains the model, evaluates accuracy and confusion matrix on test data, and identifies top frequent words for... | def main():
file_name = "data/twitter.csv"
all_corpus,labels = get_data(file_name)
all_corpus_cleaned = clean_data(all_corpus)
limit = math.floor(len(all_corpus_cleaned) * 0.8)
train_corpus = all_corpus_cleaned[:limit]
train_labels = labels[:limit]
test_corpus = all_corpus_cleaned[limit:... |
def getRandomAssignedPoint():
"""
Election operation: selects a random point from the list of assigned points
Parameters
----------
N/A
Returns
-------
int
The index of the random Elected
"""
global assignedPoints,nAssignedPoints
return int(assignedPoints[ra... | This function performs clustering by iteratively assigning points to clusters based on proximity. It runs for 'i' iterations, selecting random assigned points (elected points) and finding their nearest unassigned or differently clustered points. If the nearest point is unassigned, it joins the elected cluster; if alrea... | def calculate(i):
"""
The main method
Assigns points to clusters until all points are assigned or maximum index value is reached
Parameters
----------
i : int
Number of iterations, i > 0
Returns
-------
N/A
"""
global distanceVectorIndex,nRemainingPo... |
def loadBikingData(isPredict=False):
sampleObjs = []
bikingPath = 'biking/'
# creates list of all files in directory
bikingFiles = [f for f in listdir(bikingPath) if isfile(join(bikingPath, f))]
fv = []
for file in bikingFiles:
# return object with sample attributes
sampleObj = l... | The function `setLabelsAndData` either loads pre-stored audio data and labels from `.npy` files or processes raw audio data from multiple activities (e.g., biking, running), assigns labels to each sample, aggregates them into a unified dataset, and optionally saves the processed data and labels for faster future access... | def setLabelsAndData(useStored=False, store=True, predict=False):
# use stored features if specified
if useStored:
data = np.load('data.npy', allow_pickle=True)
labels = np.load('labels.npy', allow_pickle=True)
return data, labels
# load raw audio data
biking = loadBikingData()
... |
def setLabelsAndData(useStored=False, store=True, predict=False):
# use stored features if specified
if useStored:
data = np.load('data.npy', allow_pickle=True)
labels = np.load('labels.npy', allow_pickle=True)
return data, labels
# load raw audio data
biking = loadBikingData()
... | The code evaluates multiple machine learning classifiers (Random Forest, KNN, SVM, Gradient Boosting) on a dataset. It normalizes features, computes each classifier's accuracy, and calculates the mean accuracy of the ensemble. Results are stored in a dictionary, with optional visualization and data storage. The functio... | def classify(useStored=True, store=True, visualize=False):
data, labels = setLabelsAndData(useStored=useStored, store=store)
data = normalizeFeatures(data, visualize=True)
print('normalized')
clfs = [RandomForestClassifier(n_estimators=300), KNeighborsClassifier(n_neighbors=10), SVC(kernel="rbf"),
... |
def parse_ini_files(ini_files):
'''
init all ini files
'''
aicpu_ops_info = {}
for ini_file in ini_files:
parse_ini_to_obj(ini_file, aicpu_ops_info)
return aicpu_ops_info
def check_op_info(aicpu_ops):
'''
check all ops
'''
print("==============check valid for aicpu ops in... | The main task of the code is to convert INI configuration files into a JSON file. It parses the provided INI files, validates the extracted operation information, and writes the structured data to the specified output file. If a KeyError occurs during validation, it prints an error message indicating a formatting issue... | def parse_ini_to_json(ini_file_paths_arg, outfile_path_arg):
'''
parse ini to json
'''
aicpu_ops_info = parse_ini_files(ini_file_paths_arg)
try:
check_op_info(aicpu_ops_info)
write_json_file(aicpu_ops_info, outfile_path_arg)
except KeyError:
print("bad format key value, f... |
def add_cookies(cookies): [driver.add_cookie(cookie) for cookie in cookies]
def load_data_from_json(path): return json.load(open(path, 'r'))
def add_local_storage(local_storage): [driver.execute_script(f"window.localStorage.setItem('{k}', '{v}');") for k, v in
local_storage.items(... | The function `check_cookies_and_login` attempts to reuse stored cookies and local storage for automatic login. If these credentials are invalid, it deletes them and performs a manual login. It navigates to a login page, loads saved session data if available, verifies login success by navigating to a search link, and fa... | def check_cookies_and_login():
driver.get(login_page) # you have to open some page first before trying to load cookies!
time.sleep(3)
if os.path.exists(COOKIES_PATH) and os.path.exists(LOCAL_STORAGE_PATH):
add_cookies(load_data_from_json(COOKIES_PATH))
add_local_storage(load_data_from_json... |
def check_cookies_and_login():
driver.get(login_page) # you have to open some page first before trying to load cookies!
time.sleep(3)
if os.path.exists(COOKIES_PATH) and os.path.exists(LOCAL_STORAGE_PATH):
add_cookies(load_data_from_json(COOKIES_PATH))
add_local_storage(load_data_from_json... | This code automates connecting with people on a platform (likely LinkedIn) by scrolling through search results, clicking "Connect" buttons, and paginating through results. It handles login/session checks, hides UI elements, and uses Selenium to interact with web elements, performing actions like clicking links, scrolli... | def main():
check_cookies_and_login()
if not custom_search: # that is, if you want to connect to the friend's friends, not the random custom search results
action.click(wait.until(EC.element_to_be_clickable(
(By.XPATH, '//section[@class="artdeco-card ember-view pv-top-card"]//a[@class="emb... |
def show_info(message):
msg = QtWidgets.QMessageBox()
msg.setIcon(QtWidgets.QMessageBox.Information)
msg.setText(message)
msg.setWindowTitle("Info")
msg.setStandardButtons(QtWidgets.QMessageBox.Ok)
msg.exec()
def edit_battery(self, id=None):
if not id:
id = None
if le... | The main task of the code is to stop a currently running dive by retrieving its ID from a table, checking its status, displaying a voltage update alert for associated batteries, and invoking a database method to halt the dive with adjusted battery parameters, followed by a reload of data. | def stop_dive(self):
if len(self.dive_ids) > 0:
dive_id = self.dive_ids[self.ui.table_dives.currentIndex().row()]
dive = self.db.get_dives(ids=[dive_id])[0]
if dive['running']:
show_info("Please update voltages on {}!".format(
[b for b in s... |
def get_selected_fields(catalog, stream_name):
stream = catalog.get_stream(stream_name)
mdata = metadata.to_map(stream.metadata)
mdata_list = singer.metadata.to_list(mdata)
selected_fields = []
for entry in mdata_list:
field = None
try:
field = entry['breadcrumb'][1]
... | The code synchronizes data from selected streams using a client and configuration, handling pagination/bookmarks for incremental sync. It updates the state to track progress, logs sync status, and ensures only selected streams are processed, using start_date and bookmark fields for efficient data retrieval. | def sync(client, config, catalog, state):
if 'start_date' in config:
start_date = config['start_date']
# Get selected_streams from catalog, based on state last_stream
# last_stream = Previous currently synced stream, if the load was interrupted
last_stream = singer.get_currently_syncing(state... |
def validate_size_dna(self):
size = 0
for base in self.dna:
if size == 0:
size = len(base)
elif size != len(base):
return False
return True
def validate_letetrs_dna(self):
for base in self.dna:
for l in base:
... | The code checks if a DNA sequence is "mutant" by validating its size and letters, then counting valid bases in vertical, horizontal, and diagonal sequences. If at least two valid bases are found across these directions, it returns True; otherwise, False. If the DNA is invalid, it prints an error message. | def is_mutant_x(self):
if self.validate_size_dna() and self.validate_letetrs_dna():
vertical_dna = self.create_vertical()
horizontal_dna = self.dna
diagonal_dna = self.create_diagonal()
num_base_valid = 0
num_base_valid = num_base_valid + self.get_nu... |
def keyHandler(self):
'''
Chip8 My Keys
--------- ---------
1 2 3 C 1 2 3 4
4 5 6 D q w e r
7 8 9 E a s d f
A 0 B F z x c v
'''
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.... | The main task of the code is to run a game loop that handles user input, updates game state, plays sounds, and renders the display at a controlled frame rate (300 FPS). It uses Pygame's clock to regulate speed, processes keyboard events via self.keyHandler(), triggers sound effects with self.soundTimer.beep(), executes... | def mainLoop(self):
clock = pygame.time.Clock()
while True:
clock.tick(300)
self.keyHandler()
self.soundTimer.beep()
self.execution()
self.display() |
def greeting(intent_request):
"""
GreetingIntent
"""
return close(intent_request['sessionAttributes'],
'Fulfilled',
{
"contentType": "PlainText",
"content": "Hi, what can I assist you today?"
})
def thank_you(in... | The main task of the code is to handle different intents by routing them to corresponding functions. It checks the intent name from the request and invokes `greeting()`, `thank_you()`, or `dining_suggestions()` based on the intent. If the intent is unsupported, it raises an exception. This function acts as a dispatcher... | def dispatch(intent_request):
"""
handle each intent
"""
intent_name = intent_request['currentIntent']['name']
if intent_name == 'GreetingIntent':
return greeting(intent_request)
elif intent_name == 'ThankYouIntent':
return thank_you(intent_request)
elif intent_name == 'Dini... |
def reset(self) -> None:
self.lines = []
self.modules = INITIAL_MODULES.copy()
self.globals = set()
self._current_indent = ""
def add_line(self, line) -> None:
self.lines.append(f"{self._current_indent}{line}")
def indent(self) -> typing.Generator[None, None, None]:
self.... | This code generates a class method `from_dict` that deserializes a dictionary into an instance. It validates fields, handles missing values via exceptions, applies pre/post-deserialization hooks, and ensures correct type conversion. The method checks hook signatures, processes each field's value, and raises errors for ... | def add_from_dict(self) -> None:
self.reset()
self.add_line("@classmethod")
self.add_line(
"def from_dict(cls, d, use_bytes=False, use_enum=False, "
"use_datetime=False):"
)
with self.indent():
pre_deserialize = self.get_declared_hook(__PRE_DE... |
def get_address_from_id(address_id):
address_data = get_address_data()
address = None
for row in address_data[1:28]: # skip the first row
if address_id == int(row[0]):
address = str(row[2])
return address
def find_next_stop(address1, truck_packages):
shortest_distance = 50.0
... | The code generates an optimized delivery route by iteratively selecting the nearest remaining package location from the current stop, minimizing total travel distance. It processes package data, updates the route list, removes delivered packages, and ensures the truck returns to the hub as the final stop. | def find_optimized_route(truck_packages):
optimized_route = [1] # List to hold address indexes, starting at the hub (index 1)
packages = truck_packages.copy() # Create a copy of the package list that can be modified
package_data = create_package_hash() # Get the package hash table
packages_on_truck_d... |
def inGrid(currRow, currCol):
rowIn = (currRow >= 0) and (currRow < maxRow)
colIn = (currCol >= 0) and (currCol < maxCol)
return rowIn and colIn
def vecSub(v1, v2):
#print(f"v1: {v1}")
#print(f"v2: {v2}")
return (v1[0]-v2[0], v1[1]-v2[1], v1[2]-v2[2])
def vecAngle(v1, v2):
x1s = v1[0] ** 2
... | The function processes visibility along a given direction from a viewpoint (vp), tracing a line through the grid. It checks if each destination point is visible by comparing angles between the viewpoint and previous points. If occluded, it calculates the minimum height needed for visibility and updates the AuxGrid. Vis... | def processEdge(vpRow, vpCol, direction):
rowInc = dirIncEdge[direction][0]
colInc = dirIncEdge[direction][1]
#print(f"vpRow: {vpRow}")
#print(f"vpCol: {vpCol}")
# getting viewpoint
vp = (vpRow, vpCol, AuxGrid[vpRow][vpCol])
# getting row and col of destination
destRow = vpRow + r... |
def refreshAuxAlt():
for i in range(0,len(AuxGrid)):
for j in range(0,len(AuxGrid[i])):
AuxGrid[i][j] = DEM[i][j]
def refreshZero(ll):
for i in range(0,len(ll)):
for j in range(0,len(ll[i])):
ll[i][j] = 0
def processEdge(calc, vpRow, vpCol, direction):
rowInc = dirInc... | The code processes different scenarios based on the 'case' input by initializing a VSM, refreshing auxiliary data structures, and executing specific functions like processEdge or processSlice. It then prints updated grids (AuxGrid, vizViews, vizScore, TrackerGrid) to visualize results for cases like 'oneEdge', 'NW_N_Sl... | def run(case):
myvsm = vsm()
refreshAuxAlt()
refreshZero(TrackerGrid)
refreshZero(vizViews)
refreshZero(vizScore)
################
if case == "oneEdge":
print("oneEdge")
processEdge(myvsm, srcRow, srcCol, "N")
################
elif case == "NW_N_Slice":
... |
def processEdge(vpRow, vpCol, direction):
rowInc = dirIncEdge[direction][0]
colInc = dirIncEdge[direction][1]
#print(f"vpRow: {vpRow}")
#print(f"vpCol: {vpCol}")
# getting viewpoint
vp = (vpRow, vpCol, AuxGrid[vpRow][vpCol])
# getting row and col of destination
destRow = vpRow + r... | This function processes grid data based on the input 'case' parameter by calling specific handlers (e.g., edge/slice processing) and then prints auxiliary grids, visualization views, scores, and a tracker grid for analysis. | def run(case):
################
if case == "oneEdge":
processEdge(srcRow, srcCol, "N")
################
elif case == "NW_N_Slice":
processSlice(srcRow, srcCol, "NW_N")
################
elif case == "N_NE_Slice":
processSlice(srcRow, srcCol, "N_NE")
################
... |
def refreshAux(ll):
for i in range(0,len(ll)):
for j in range(0,len(ll[i])):
ll[i][j] = DEM[i][j]
def refreshZero(ll):
for i in range(0,len(ll)):
for j in range(0,len(ll[i])):
ll[i][j] = 0
def run(case):
################
if case == "oneEdge":
processEdge(... | The main task of the code is to initialize grids and visualization elements, refresh auxiliary and zero grids, and execute operations on all slices and edges. It starts by printing "hello", sets up tuples, refreshes specific grids (AuxGrid, TrackerGrid, vizViews, vizScore), and runs "allSlices" and "allEdges" to proces... | def main():
print("hello")
t1 = (1, 2, 3)
t2 = (4, 5, 6)
#run("oneSlice")
#run("oneEdge")
refreshAux(AuxGrid)
refreshZero(TrackerGrid)
refreshZero(vizViews)
refreshZero(vizScore)
run("allSlices")
refreshAux(AuxGrid)
#AuxGrid = DEM
refreshZero(TrackerGrid)
... |
def nc_to_dict(hdf5_obj):
'''
Using h5py, extract a subset of the input HDF dataset's
attributes and data arrays
NB: this is currently hardcoded to the current (Feb 26 2019)
NSIDC OIB L1b NetCDF datasets
Arguments:
hdf5_obj: an open h5py.File (preferably in read-mode)
Output:
... | The function `unified_loader` determines how to parse SnowRadar data files based on their format. It prioritizes NetCDF (`.nc`) files using `h5py`, then attempts MATLAB v5 files via `scipy.loadmat`, and defaults to MATLAB v7/AWI formats with `h5py`. It returns a dictionary (`radar_dat`) containing parsed data from the ... | def unified_loader(sr_obj):
'''
The entry-point called by the SnowRadar class, that determines
how each different type of SnowRadar data file is parsed
Currently operates in the following decision tree:
Does the data filename end in '.nc'?
Yes: Treat as a NSIDC OIB L1b NetCDF - loa... |
def right(self, steps: int = 1):
self._direction = [1, 0]
self.forward()
def down(self, steps: int = 1):
self._direction = [0, 1]
self.forward()
def left(self, steps: int = 1):
self._direction = [-1, 0]
self.forward()
def up(self, steps: int = 1):
self._direction ... | The code defines a method `draw_square` that moves an object in a pattern resembling drawing a square or rectangle. It turns right `w` times, moves down `l` times, turns left `w` times, and moves up `l` times, likely using turtle graphics commands to trace a shape. The parameters `w` and `l` control the number of steps... | def draw_square(self, w, l):
for _ in range(w):
self.right()
for _ in range(l):
self.down()
for _ in range(w):
self.left()
for _ in range(l):
self.up() |
def right(self, steps: int = 1):
self._direction = [1, 0]
self.forward()
def down(self, steps: int = 1):
self._direction = [0, 1]
self.forward()
def left(self, steps: int = 1):
self._direction = [-1, 0]
self.forward()
def up(self, steps: int = 1):
self._direction ... | The code draws a staircase with a specified number of steps by moving right three times and down twice for each step. After completing the steps, it returns to the starting position by moving left until the x-coordinate is 0 and up until the y-coordinate is 1. | def draw_stairs(self, steps=4):
for _ in range(steps):
self.right()
self.right()
self.right()
self.down()
self.down()
while self._pos[0] > 0:
self.left()
while self._pos[1] > 1:
self.up() |
def lum(img):
l = 0.2126 * img[:,:,0] + 0.7152 * img[:,:,1] + 0.0722 * img[:,:,2]
return l
def clip(img):
img[np.where(np.isnan(img))] = 0.0
img[np.where(np.isinf(img))] = 0.0
return img
def bilateral_separation(img, sigma_s=0.02, sigma_r=0.4):
r, c = img.shape
sigma_s = max... | This code enhances image contrast by adjusting luminance components using logarithmic compression and detail preservation. It separates luminance into base and detail layers, compresses the base logarithmically according to target contrast, combines it with detail, and scales the original image channels accordingly, cl... | def durand(img, target_contrast=5.0):
L = lum(img)
tmp = np.zeros(img.shape)
for c in range(3):
tmp[:,:,c] = clip(img[:,:,c] / L)
Lbase, Ldetail = bilateral_separation(L)
log_base = np.log10(Lbase)
max_log_base = np.max(log_base)
log_detail = np.log10(Ldetail)
compression_fact... |
def parse_outcar(theoutcar:str, prototype_structure = None) -> EntryArchive:
archives = parse(theoutcar)
normalized_archives = [run_normalize(archive) for archive in archives]
for i, normalized_archive in enumerate(normalized_archives):
# symmetry = normalized_archive.results.material.symmetry.m_to_d... | The main task of the code is to generate an equation of state (EOS) workflow by parsing VASP OUTCAR files, extracting energy-volume data, constructing an EOS curve, and compiling results into an archive with calculation references. It processes multiple OUTCARs, identifies the minimum energy structure, normalizes the w... | def create_eos_workflow(OUTCAR_dir : str, structure_name : str = None) -> EntryArchive:
"""Entry with mechanical properties."""
OUTCARS = glob.glob(OUTCAR_dir+'/OUTCAR*')
list_of_archives = [parse_outcar(thisoutcar, prototype_structure = structure_name) for thisoutcar in OUTCARS if 'json' not in thisoutcar]... |
def lst_of_items(lst, name, total_1=0, total_2=0):
"""
Print items from list of dictionary,
typically representing warehouse inventories.
Parameters:
- lst1 (list): list of dictionary
Note:
The items from each warehouse are printed separately.
"""
print()
print("Items in wareho... | This function presents a menu for user interaction, allowing them to list items by warehouse, search/order items, browse categories, or quit. It validates input, loops until 'Quit' is chosen, and delegates tasks to other functions based on user selection. The user's name is used in prompts and farewell messages. | def options(name):
"""
Prompt the user to continuously select one of three options:
1. List items by warehouse
2. Search an item and place an order
3. Quit
Parameters:
- name (str): The name of the user.
Returns:
None. This function only interacts with
the user via print statem... |
def get_user_name():
"""Ask the user to provide a name."""
name = input('What is your user name?: ')
return name
def greet(name):
"""Greet the user."""
return f'Hello, {name}'
def options(name):
"""
Prompt the user to continuously select one of three options:
1. List items by wareho... | The main task of the code is to serve as the entry point for a warehouse management program. It fetches the user's name, greets them, and presents interaction options with the warehouse system. The function does not return a value but interacts with the user through print statements and input prompts. | def main():
"""
Entry point for the warehouse management program.
This function performs the following steps:
1. Fetches the user's name.
2. Greets the user.
3. Presents options for interacting with the warehouse system.
Returns:
None. The function interacts with the user via p... |
def get_user_name():
"""Ask the user to provide a name."""
name = input("What is your user name?: ")
return name
def greet(name):
"""Greet the user."""
return f"Hello, {name}"
def options(name):
"""
Prompt the user to continuously select one of three options:
1. List items by warehouse
... | The main task of the code is to serve as the entry point for a warehouse management program. It fetches the user's name, greets them, and presents interaction options with the warehouse system. The function uses print statements and input prompts for user interaction, calling helper functions to retrieve the name, gene... | def main():
"""
Entry point for the warehouse management program.
This function performs the following steps:
1. Fetches the user's name.
2. Greets the user.
3. Presents options for interacting with the warehouse system.
Returns:
None. The function interacts with the user
via print... |
def _detect_last_checkpoint(self, training_args) -> Optional[str]:
last_checkpoint = None
if (
os.path.isdir(training_args.output_dir)
and training_args.do_train
and not training_args.overwrite_output_dir
):
last_checkpoint = get_last_checkpoint(tr... | The code initializes a machine learning model by parsing configurations, setting up logging, detecting the last checkpoint, seeding for reproducibility, loading datasets, preparing the model, and processing training/evaluation/prediction datasets. | def __init__(self, config_json: Optional[str] = None, config_dict: Optional[dict] = None) -> None:
# 1. Parsing command-line variables
self.model_args, self.data_args, self.training_args = parse_arguments(config_json, config_dict)
# 2. Setup logging
self.logger = setup_logger(self.train... |
def sentences(self):
if hasattr(self, "_sentences") and self._sentences:
return self._sentences
nltk.download('punkt')
sentences = []
df = pd.read_csv(self.path)
data = df.to_dict('dict')
for about in data['about'].values():
for sentence in nltk.se... | The code generates a list of filtered sentences by applying rejection probabilities to tokens, repeating the process 30 times, and storing the result for future use. It first checks if precomputed sentences exist; if not, it creates them by excluding tokens with rejection probabilities, ensuring each resulting sentence... | def allSentences(self):
if hasattr(self, "_allsentences") and self._allsentences:
return self._allsentences
sentences = self.sentences()
rejectProb = self.rejectProb()
tokens = self.tokens()
allsentences = [[w for w in s
if 0 >= rejectProb[to... |
def prepare_input(self, image):
self.img_height, self.img_width = image.shape[:2]
input_img = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
# Resize input image
input_img = cv2.resize(input_img, (640,640))
#input_img = cv2.resize(input_img, (self.input_width, self.input_height))
... | The main task of the code is to perform object detection on an input image. It prepares the image as a tensor, runs inference using a model, processes the output to extract bounding boxes, confidence scores, and class IDs of detected objects, then returns these results for further use. | def detect_objects(self, image):
input_tensor = self.prepare_input(image)
# Perform inference on the image
outputs = self.inference(input_tensor)
self.boxes, self.scores, self.class_ids = self.process_output(outputs)
return self.boxes, self.scores, self.class_ids |
def check_4_newdata(ingested_pth:str, data_dir: str) -> set:
'''
Check for new data to ingest. Returns a list of new files.
'''
##################Check and read new data
#first, read ingestedfiles.txt
ingested_filenames = load_ingestedfiles(ingested_pth)
logger.info(f"Ingested file name list... | This function merges new data files from a source directory with an existing dataset, cleans the merged data, and saves the result if differences are detected between the current files and previously ingested files. It reads the base dataset, checks for new files, merges them, cleans the data, and stores the updated da... | def merge_multiple_dataframe(
dataset_pth: str,
src_dir: str,
dest_dir: str,
dest_data_filename: str,
dest_ingest_filename: str):
'''
Merge all files and corresponding dataset to one dataset, clean and save it for further processing.
Merging only occurrs if there is a difference betw... |
def parse_args():
parser = argparse.ArgumentParser(
description="Score input sentences with pre-trained checkpoints.",
usage="scorer.py [<args>] [-h | --help]"
)
# input files
parser.add_argument("--input", type=str, required=True, nargs=2,
help="Path to input fi... | The code sets up a distributed training environment by determining the number of GPUs, selecting a free port, and launching a process function either in parallel (multi-GPU) or single-process (CPU/single GPU) mode. It parses arguments, binds a socket to a port, infers hardware resources, and uses PyTorch's multiprocess... | def cli_main():
parsed_args = parse_args()
# Pick a free port
with socket.socket() as s:
s.bind(("localhost", 8858))
port = s.getsockname()[1]
url = "tcp://localhost:" + str(port)
parsed_args.url = url
if parsed_args.cpu:
world_size = 1
else:
world_s... |
def clear_screen(): # pragma: no cover
"""Clears the screen from any previous output."""
os.system('cls' if os.name == 'nt' else 'clear')
def edit_name(name_of_emp):
"""creates a name that can then substitute an existing one."""
name_of_emp.name = add_employee()
name_of_emp.save()
return nam... | The main task of the code is to display filtered database entries in a structured format, allowing navigation through results, editing, and deletion. It uses parameters to filter entries by fields like name, date, title, etc., and provides options for users to view, modify, or delete entries interactively. | def display_entries(subject=None, subject_2=None,
search_query=None, search_query_2=None):
"""Displays entries in a predetermined format."""
entry = Entry.select().order_by(Entry.date)
field_mapping = {
'name': Entry.name,
'date': Entry.date,
'title': Entry.titl... |
def clear_screen(): # pragma: no cover
"""Clears the screen from any previous output."""
os.system('cls' if os.name == 'nt' else 'clear')
def list_employees():
"""Prints a list of all the employee names who have an entry in
the database under their name. Then let's the user select the
employee by ... | The main task of the code is to display a search menu with multiple options for querying data, validate user input, and redirect to corresponding functions (e.g., listing employees, searching by name/dates/tasks) while maintaining a loop until a valid choice is made. It handles navigation between menu options and ensur... | def search_by_menu():
"""Displays the search menu of the app."""
search_by_options = """
Do you want to search by:
A) List of Employees
B) Search Employee Name
C) List of Dates
D) Search Between Two Dates
E) Exact Time Spent on a Task
F) Term on Task Title and/or Notes
G) Return to Menu
"""
search_by_answ... |
def initialize(): # pragma: no cover
"""create the database and the table if they don't exist"""
try:
db.connect()
db.create_tables([Entry], safe=True)
print("A connection to the database has been established.")
except OperationalError:
print("A connection to the database ... | The main task of the code is to display a work log menu allowing users to add entries, search existing entries, view all entries, or quit. It handles user input validation, executes corresponding database operations, and manages the database connection lifecycle by closing it upon exit. The menu loops until the user se... | def main_menu():
"""Displays the main menu of the app."""
initialize() # pragma: no cover
main_menu_options = """
WORK LOG with a Database
------------------------
What Would you like to do?
A) Add New Entry
B) Search in Existing Entries
C) View All Entries
D) Quit Program
"""
main_menu_answer = ''
... |
def get_key_bytes(key):
key_bytes = []
leng = len(key)
iterator = leng // 4
remainder = leng % 4
i = 0
while i < iterator:
key_bytes.append(str_to_bt(key[i * 4:i * 4 + 4]))
i += 1
if remainder > 0:
key_bytes.append(str_to_bt(key[i * 4:leng]))
return key_bytes
d... | The function encrypts input data using three optional keys through a series of transformation steps. It processes data in 4-character chunks, applying encryption sequentially with each key's bytes if provided. The result is hex-encoded. | def strEnc(data, firstKey, secondKey, thirdKey):
leng = len(data)
encData = ""
if firstKey != None and firstKey != "":
firstKeyBt = get_key_bytes(firstKey)
firstLength = len(firstKeyBt)
if secondKey != None and secondKey != "":
secondKeyBt = get_key_bytes(secondKey)
sec... |
def _write_comment(self, comment):
"""
Writes comment after //
"""
self._write_file.write(f"// {comment}\n")
def _prepare_segment_index(self, segment, index):
"""
Prepares into register D, the desired value of segment[index], for later push.
"""
# Select s... | This function generates assembly code for push/pop operations by handling the specified segment and index. For 'C_PUSH', it writes a comment, loads the segment/index value into register D, then pushes D to the stack. For 'C_POP', it writes a comment, pops the stack into D, then stores D into the specified segment/index... | def write_push_pop(self, command, segment, index):
"""
Writes to the output file the assembly code that implements the given
push or pop command.
"""
if command == "C_PUSH":
# Comment (// push)
self._write_comment(f"push {segment} {index}")
# P... |
def _write_comment(self, comment):
"""
Writes comment after //
"""
self._write_file.write(f"// {comment}\n")
def _prepare_segment_index(self, segment, index):
"""
Prepares into register D, the desired value of segment[index], for later push.
"""
# Select s... | This function generates assembly code for 'push' or 'pop' commands by handling segment/index preparation, stack operations, and register transfers. It writes comments, prepares the specified segment's value at index into register D for 'push', or transfers stack content to D and writes it to the segment/index for 'pop'... | def write_push_pop(self, command, segment, index):
"""
Writes to the output file the assembly code that implements the given
push or pop command.
"""
if command == "C_PUSH":
# Comment (// push)
self._write_comment(f"push {segment} {index}")
# P... |
def escape(rawstr):
escaped_esc = rawstr.replace( ESC, ESC+ESC )
escaped_tildes = escaped_esc.replace( START, ESC+START)
return escaped_tildes
def sz2str(sz):
assert sz < 8192
if sz < 224:
return struct.pack('B', sz)
else:
return struct.pack('>H', sz | 0xe000 )
def checksum(str, crc=CHECKSUM_INIT):
for c in ... | The main task of the code is to construct a properly escaped and checksummed data frame for transmission. It combines a payload with its length, applies byte escaping to handle special characters, and appends a 16-bit checksum to ensure data integrity during transfer. | def pack_frame(self, payload):
tx_sz_payload = len(payload)
assert tx_sz_payload >= 0
tx_escaped_frame = (START + START) + escape( sz2str( tx_sz_payload ) )
# print( 'pre:', hex(checksum( tx_escaped_frame ) ))
tx_escaped_frame += escape( payload )
return tx_escaped_frame + escape( struct.pack('>H', checksum(... |
def sync_receiver(self):
b, c = b'', b''
self.checksum = CHECKSUM_INIT
while (b,c) != (START, START):
b, c = c, self.read_byte()
if c != START:
self.checksum = CHECKSUM_INIT
def escaped_read(self, n_bytes):
out = b''
while(len(out) < n_bytes):
b = self.read_byte() # char -> out. ESC + [ESC, ~] -... | This function receives a data frame by synchronizing, reading the packet size, payload, and checksum. It validates the checksum against the received frame; if mismatched, it raises an error. If valid, it returns the payload data. | def rx_frame( self ):
global LAST_RESPONSE
LAST_RESPONSE = b''
self.sync_receiver()
c = self.escaped_read( 1 )
szpkt = struct.unpack('B', c)[0]
if szpkt > 223:
szpkt = struct.unpack( '>H', c + self.escaped_read(1) )[0] & 0x1fff
rx_payload = self.escaped_read(szpkt)
rx_checksum = struct.pack('>H', s... |
def pack_frame(self, payload):
tx_sz_payload = len(payload)
assert tx_sz_payload >= 0
tx_escaped_frame = (START + START) + escape( sz2str( tx_sz_payload ) )
# print( 'pre:', hex(checksum( tx_escaped_frame ) ))
tx_escaped_frame += escape( payload )
return tx_escaped_frame + escape( struct.pack('>H', checksum(... | The main task of the code is to send a payload via a communication port, receive a response frame, and return it. It packages the payload into a byte stream, transmits it, flushes the port, receives the response, and outputs debug logs showing the hexadecimal representations of transmitted and received data. | def command( self, payload ):
tx_bytes = self.pack_frame(payload)
debug_print(3, '-->' + str2hex(tx_bytes) )
# self.port.flushInput()
self.port.write( tx_bytes )
self.port.flush()
rx_payload = self.rx_frame()
debug_print(3, '<--' + str2hex(LAST_RESPONSE))
return rx_payload |
def check_winner(self):
winner = None
# Horizontal
for row in range(3):
if self.is_equal(self.board[row][0],
self.board[row][1],
self.board[row][2]):
winner = self.board[row][0]
# Vertical
for ... | This code implements the Minimax algorithm with Alpha-Beta pruning to determine the optimal move in a Tic-Tac-Toe-like game. It recursively evaluates all possible board states, alternating between maximizing (player 2) and minimizing (player 1) players, while pruning unnecessary branches to improve efficiency. The func... | def minimax_alphabeta(self, depth, alpha, beta, is_maximizing):
result = self.check_winner()
if result != None:
return self.scores[result]
if is_maximizing:
best_score = -math.inf
for row in range(3):
for column in range(3):
... |
def check_winner(self):
winner = None
# Horizontal
for row in range(3):
if self.is_equal(self.board[row][0],
self.board[row][1],
self.board[row][2]):
winner = self.board[row][0]
# Vertical
for ... | The code implements the minimax algorithm for a Tic-Tac-Toe-like game, recursively evaluating all possible moves. It checks for a winner, then alternates between maximizing (AI player, symbol 2) and minimizing (opponent, symbol 1) turns. For each empty cell, it simulates a move, recursively calculates the resulting sco... | def minimax(self, depth, is_maximizing):
result = self.check_winner()
if result != None:
return self.scores[result]
if is_maximizing:
best_score = -math.inf
for row in range(3):
for column in range(3):
if self.is_blank_posi... |
def rgb_image(rgb, w=IMG_W, h=IMG_H):
"""Get a blank image of the color rgb"""
return Image.new('RGBA', (w, h), rgb)
def component(name, prefix='', folder_name=COMPONENT_DIR, file_type=FILE_TYPE):
"""Get the image for the component of a given name.
prefix- the name of the component's feature (leg, segme... | The code generates a flower image by creating a white canvas, drawing a centered shape as the flower's core, and arranging petals and sepals symmetrically around it through rotational placement. Petals are uniformly spaced and colored, while sepals are positioned offset from petals with a specified radius and color. Th... | def draw_flower(petal_style, petal_color, petal_rgb, petal_num,
center_color, center_rgb, center_shape, sepal_num):
# Make a blank image
flower = rgb_image((255, 255, 255))
# Draw the center
center = component(center_shape, prefix=CENTER_PREFIX)
draw_centered(flower, center, cen... |
def store_env_channels():
all_channel_names : list[dict[str, str]] = get_channel_names()
current : dict[str, str]
for current in all_channel_names if all_channel_names else []:
current_channel : ChannelSubscription = ChannelSubscription.build_by_name(current)
persistence.store_channel(curren... | The main task of the code is to run a loop that periodically processes YouTube channels and playlists, storing environment configurations and handling loop intervals if enabled, while printing version and status updates. | def main():
print(f"yt-helper, version [{app_version}]")
store_env_channels()
store_env_playlists()
while True:
process_channels_names()
process_playlists()
if is_loop_enabled:
print(f"Sleeping for [{get_loop_wait_sec()}] seconds ...")
time.sleep(get_... |
def GenerateVersionInfo():
version_file = os.path.join(vimfiles_dir,'plugin/TagHighlight/data/version_info.txt')
args = HG + clean_info
p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(stdout,stderr) = p.communicate()
if p.returncode > 0:
sys.exit(p.returncode)
... | The main task of the code is to manage a software release process. It checks if the distribution is "clean," and if so, updates the release version, compiles binaries for Windows/Linux, packages libraries, checks in changes, and publishes the release. If not clean, it warns about Mercurial check-in and removes the vers... | def main():
version_file, clean = GenerateVersionInfo()
if clean:
new_release = UpdateReleaseVersion()
MakeMainRelease(new_release)
os.remove(version_file)
MakeWin32Compiled(new_release)
MakeLinuxCompiled(new_release)
MakeLibraryPackage(new_release)
Check... |
def Button(msg, x, y, l, h, ac, ic, function, tc): # for drawing buttons
global player_index, place, card_display, spcard_display, railway, rolloncejail, temporary, timer, timerr
global rollonce, endturn, key, n, incometax, gotojail, cround, round_complete
pygame.draw.rect(functions.gameDisplay, ic, [x, y,... | The main task of the code is to render a Monopoly-style board game interface, handle visual elements like property placements, dice rolls, player actions (e.g., mortgage, build, sell), tax calculations, and game state updates (e.g., winning conditions, bankruptcy). It draws the board, player info, property cards, butto... | def drawing():
# global variables called
global key, timer, incometax, gotojail, round_complete, cround, rent, railway, temporary, chance, rollonce, endturn, timerr, risk
functions.gameDisplay.fill(lblue)
pygame.draw.rect(functions.gameDisplay, white, [0, 0, display_height, display_height])
function... |
def calculate_vwap(self, idx):
sum_v = np.sum(self.volume_list[:idx])
sum_vxp = np.sum([i * j for i, j in zip(self.price_list[:idx], self.volume_list[:idx])])
self.abs_vwap.append(sum_vxp / sum_v)
def calculate_window_vwap(self, idx):
if idx + 1 < self.window_size:
self.sof... | The main task of the code is to execute a trading strategy based on VWAP (Volume Weighted Average Price) and signal comparisons. It evaluates market conditions, manages long/short positions, checks volume validity, and adjusts positions accordingly. The function holds, closes, or opens trades depending on signal thresh... | def trade(self, idx):
self.calculate_vwap(idx)
self.calculate_window_vwap(idx)
self.calculate_rv(idx)
if self.DoCheckFor:
r = self.check_profit(idx)
if r:
print("checking profit")
return
else:
self.DoCheckFor ... |
def create_agencies(n):
agencies = [Agency(name=fake.company(), phone_no=fake.phone_number(), email_id=fake.email(), address=fake.address()) for _ in range(n)]
Agency.objects.bulk_create(agencies)
return Agency.objects.all()
def create_agents(agencies, n):
for _ in range(n):
user = create_user()... | The code populates a database with sample data by generating entities like agencies, agents, house owners, customers, guarantors, properties, and listings. It establishes relationships between these entities and creates registrations linking customers, guarantors, and listings. The function ensures a structured databas... | def populate_db():
agencies = create_agencies(10)
create_agents(agencies, 15)
create_house_owners(20)
create_customers(30)
create_guarantors(20)
create_properties(50, HouseOwner.objects.all())
create_listings(Property.objects.all(), Agent.objects.all())
create_registrations(Customer.obje... |
def _check_hashes(self):
''' go through task and remove dead ones '''
new = []
for t in self.lthreads:
if not t.thread.is_alive():
continue
check = t.task.hash()
new.append(check)
self.hashes = new
def get_info(self):
''' return... | This code processes incoming commands in a communication thread, handling actions like stopping tasks, toggling debug mode, resynchronizing threads, resuming tasks, and retrieving information. It checks thread hashes, manages task states, and returns appropriate responses based on the received action, ensuring coordina... | def callback(self, action):
''' process command received through the communication thread '''
msg = Msg.ack
if self.debug:
Log.debug('callback received message: \"{}\"'.format(action))
self._check_hashes()
if action == Msg.stop:
self.stopreq.set()
... |
def enrich_args(args):
''' enrich and fix args '''
# fix paths
args['<local_path>'] = norm_path(args['<local_path>'])
args['--key'] = norm_path(args['--key'])
# add command-line arguments
args['cli'] = argv_to_str(sys.argv[1:]).rstrip()
# parse exclude pattern from file
if args['--expath... | This code manages a service (manager) by starting it in foreground or background based on command-line arguments, ensuring single-instance operation via PID checks, and handling task execution or relay to an existing instance. It processes arguments, logs status, and delegates actions to start or communicate with the m... | def main():
''' entry point '''
ret = True
args = docopt(USAGE, version=VERSION)
args = enrich_args(args)
if not args:
return False
front = args['--front']
debug = args['--debug']
action = json.dumps(args)
pid = get_pid(PIDPATH)
if not os.path.exists(DIRPATH):
o... |
def _verif_hostkey(self, host):
''' verify host against hostkey file '''
kh = self._knownhosts()
if not kh:
return False
return kh.lookup(host) is not None
def _connect(self):
''' connect to remote through sftp '''
if self.task.key:
t = self._con_k... | This code establishes an SFTP connection to a remote host, verifies host keys, authenticates, checks local/remote path validity, creates remote directories if needed, and configures the SFTP client for file operations. It handles errors like authentication failure, missing paths, and existing remote files, with debug l... | def connect(self):
''' connect on remote through sftp '''
if self.debug:
Log.debug('th{} initiate connection'.format(self.id))
if self.trans and self.trans.is_authenticated():
return
if not self._verif_hostkey(self.task.hostname):
err = 'hostkey verifi... |
def _init_files(self, files, ldir, rdir):
''' copy multiple files to remote '''
if self.debug:
Log.debug('th{} initfiles'.format(self.id))
for f in files:
lpath = os.path.join(ldir, f)
if self._is_excluded(lpath):
continue
rpath = o... | This function synchronizes a local directory with a remote directory by traversing the local directory structure, initializing files and subdirectories on the remote side, and creating necessary directories while skipping excluded paths. It returns True on success or False if initialization fails, raising a SyncExcepti... | def initsync(self, ldir, rdir):
''' sync local directory on remote '''
if self.debug:
Log.debug('th{} initsync dir {} with {}'.format(self.id,
ldir,
rdir))
try:
... |
def transform(pose):
"""Transform given pose in FRD (x - forward y - right z - down ) to ENU - MoCap fram (x - forward, y - forward, z - up)
Args:
pose = pose in FRD
Returns:
pose_new = pose in ENU
# If using vicon it may already be in ENU
... | The function navigates a drone to a specified waypoint using positional control. It accepts a global or relative coordinate mode, checks if the waypoint is within safety boundaries, and adjusts the drone's setpoint iteratively toward the goal using proportional control until the distance tolerance is met. If the waypoi... | def goTo(self, wp, mode='global', tol = None):
""" Drone goes to given waypoint using positional commands.
Args:
wp = [x,y,z]
mode = global or relative
[Note] if navigating using relative mode, errors do accumulate. Small tolerance may help redu... |
def check_file_exist(self, path, pattern):
for m in self.moda:
if not os.path.isfile(path + pattern + m + '.h5'):
return False
return True
def pad_raw_data(self, patch_size, pad_path, raw_path):
# input
raw_data = None
raw_file = None
if self.c... | The main task of the code is to load preprocessed padded data for model training, checking if existing files match the specified patch size. If not, it generates padded raw and target data using helper methods. It prioritizes loading from disk to avoid redundant computation, ensuring data consistency across input and t... | def load_data(self, patch_size=(32, 32, 32),
pad_path="./model/h5df_data/", raw_path="./model/h5df_data/", target_path="./model/h5df_data/"):
# pad_path="./model/h5df_data/pad_data.h5", raw_path="./model/h5df_data/raw_data.h5"):
padded = True
if self.check_file_exist... |
def removePreviews(self):
if self.layer_exists(self.previewLayer):
pdb.gimp_image_undo_freeze(self.img)
self.img.remove_layer(self.previewLayer)
pdb.gimp_image_undo_thaw(self.img)
self.previewLayer = None
gimp.displays_flush()
def updateTransformFromGUI(self):
self.xdelta = int(self.x_transform_spinne... | The code's main task is to remove existing preview layers, update transformation parameters from the GUI, and apply operations to sublayers under the userGroupLayer. It ensures a clean state by eliminating old previews, synchronizes GUI adjustments into the transform system, and propagates changes to relevant sublayers... | def okbutton(self, widget):
# remove old preview layer if it exists
self.removePreviews()
"""
if self.layer_exists(self.previewLayer):
self.img.remove_layer(self.previewLayer)
self.previewLayer = None
"""
self.updateTransformFromGUI()
self.perform_on_sublayers(self.userGroupLayer) |
def make_label(self, text):
label = gtk.Label(text)
label.set_use_underline(True)
label.set_alignment(1.0, 0.5)
label.show()
return label
def make_slider_and_spinner(self, init, min, max, step, page, digits):
controls = {'adj':gtk.Adjustment(init, min, max, step, page), 'slider':gtk.HScale(), 'spinner':gtk.... | The main task of the code is to create a GTK dialog interface for moving selections across sublayers in an image editing application. It provides UI elements to select layers, adjust X/Y transforms via sliders, preview changes, and includes controls for resetting, applying, or canceling the operation. The dialog handle... | def showDialog(self):
try:
#self.dialog = gimpui.Dialog("Move Selection for all Sublayers", "highenddialog")
self.dialog = gtk.Window()
self.dialog.connect("destroy", self.main_quit)
self.table = gtk.Table(6, 3, True)
self.table.set_homogeneous(False)
self.table.set_row_spacings(8)
self.tabl... |
def convert_cp():
print(' [**] begin load_cp ... ')
start = time.time()
f = open(os.path.join(DATA_DIR, 'body_control_points.txt'), "r")
tmplist = []
cp = []
for line in f:
if '#' in line:
if len(tmplist) != 0:
cp.append(tmplist)
tmplist = []
elif len(line.split()) == 1:
... | The code trains a facial deformation analysis model for female subjects by processing 3D mesh data, extracting deformation features, and applying recursive feature elimination (RFE) to select optimal features from deformation measurements, control points, and basis coefficients. It loads geometry data, computes deforma... | def train():
genders = ["female"]#, "male"]
for gender in genders:
# generate and load control point from txt to npy file
cp = convert_cp()
facet = convert_template()
vertex = obj2npy(gender)[0]
d_inv_mean, deform, dets, _, _ = load_d_data(vertex, facet, label=gender)
measure = convert_measu... |
def _exists_file_with_processed_data(self):
""" Check if is there already a file with processed data in the project """
return os.path.exists(self._processed_csv_file_path)
def _load_processed_data(self) -> None:
""" Load file with already processed data """
print("Load dataset.")
... | The code's main task is to load and preprocess data, either by retrieving existing processed data or processing raw data, then splitting it into training and testing sets for machine learning tasks. | def load(self) -> [LabeledData, LabeledData]:
""" Load, process, pre-process the data or load the already previously processed data.
Split data into training and testing sets.
"""
if self._exists_file_with_processed_data():
self._load_processed_data()
else:
... |
def dictionary(self, vertix, edge):
self.vertix = vertix
self.edge = edge
dic = {}
for i in self.vertix:
for j in self.edge:
if j[0] == i:
dic.setdefault(i,[]).append(j[1])
elif j[1] == i:
dic.setdefault(... | The function identifies all shortest paths between a start and end node in a graph. It constructs a graph dictionary, calculates the minimum path length, generates all possible paths, and filters those matching the shortest length, returning them as a list of lists. | def all_shortest_paths(self, v, e, start_node, end_node):
"""
Finds all shortest paths between start_node and end_node
Args:
start_node: Starting node for paths
end_node: Destination node for paths
Returns:
A list of path, where each path is a list o... |
def compute_smr_from_trade(self):
# TODO: fix this to actually compute it from trade parse
return {}
def update_cache(self):
# find the first item corresponding to the current cache and add a parse to it
# if the parse is deemed correct, then check if it is in the cache and append it if... | The main task of the code is to save the object's state by updating the SMR (likely a metric) when errors occur, persist the data to a file via cache, mark the instance as saved, and clear internal data. It handles default username assignment, error-based SMR recalculation, and file-based data persistence. | def save(self):
# update the smr
if self.username == "":
self.username = "anonymous"
if self.is_wrong:
self.current_smr = self.compute_smr_from_trade()
self.update_cache()
self.save_cache_to_file()
self.saved = True
self.clear() |
def find_within(self, within_dist, TSS):
none_within=False
windowMin = max(0, TSS - within_dist)
e_windowMin = max(0, TSS - self.exclude_wp_dist)
e_windowMax = min(TSS + self.exclude_wp_dist, self.chrSizes[self.chrom])
windowMax = min(TSS + within_dist, self.chrSizes[self.chrom])
if self.exclude_wp:
with... | This function generates random subsets of candidate regulatory elements (CREs) for a given gene, evaluates their validity using thresholds, and iterates through possible combinations. It calculates CRE weights, adjusts values with `adjust_abc`, creates a powerset iterator, and checks subsets against criteria. The goal ... | def drive_random_iter(self, i):
'''
for each gene, get the num passing using whatever cutoffs <-- can I parallelize this part of it?
initialize empty list, checked
create the iterator object by calling self.powerset_generator()
find the powerset size by calling self.find_num_in_powerset()
make an iterator o... |
def generate_random_points(num_points, x_range, y_range):
"""
Generate random points within the specified x and y ranges.
Parameters:
- num_points: Number of points to generate
- x_range: Tuple (min_x, max_x) specifying the x-axis range
- y_range: Tuple (min_y, max_y) specifying the y-axis rang... | The code generates planar graphs by creating random point networks, applying connectivity filters, and testing pathfinding algorithms (greedy, compass-based). It logs graph properties, path validity, and "stuck" states into a CSV file, iterating until 20,000 valid graphs are processed. | def main():
#for base in base_options:
# print(base)
base = ""
generate_graphs = 20000
graphs = 0
failed_graph = 0
not_stuck = 0
#frame_size = 20
frame_size = 100
#num_points = 10
num_points = 250
min_points = .5 # % of point... |
def face(node, end, graph):
global num_steps, quick_exit
A = end[1] - node[1]
B = node[0] - end[0]
C = node[1]*(end[0] - node[0]) - node[0]*(end[1] - node[1])
path = []
path.append(end)
stop = node
last = end
direction = 1
#best_crossing = None
best_crossing = distance_cal... | This function determines the next node to navigate towards based on the current recovery strategy. It selects from various pathfinding algorithms like face-based, quick face, left, nonplanar left, void, quick void, or long face, depending on the recovery mode. If no applicable strategy is active, it defaults to the end... | def unstuck(node, end, planar, graph):
global recovery, recovery_options
next_node = ()
if recovery == recovery_options[0]:
next_node = face(node, end, planar)
elif recovery == recovery_options[1]:
next_node = quick_face(node, end, planar)
elif recovery == recovery_options[2] and... |
def calc_angle(center, point1, point2):
return math.atan2(point2[1] - center[1], point2[0] - center[0]) - math.atan2(point1[1] - center[1], point1[0] - center[0])
def distance_calc(point1, point2):
return (math.sqrt(pow(point1[0] - point2[0], 2) + pow(point1[1] - point2[1], 2)))
def unstuck(node, end, planar, g... | This function navigates from a start node to an end node in a graph using a compass-based heuristic. It selects the next node by minimizing the angle between the current node, end node, and neighbors, adjusting for directional consistency. If stuck or if the next node doesn't progress toward the end, it calls an 'unstu... | def forward_compass(start, end, graph, planar):
global num_steps, step_limit, loop_recovery
loop_recovery = False
node = start
while node != end:
next_node = node
min_angle = math.pi/2
for neighbor in graph[node]:
if neighbor == end:
num_steps = num_s... |
def calc_angle(center, point1, point2):
return math.atan2(point2[1] - center[1], point2[0] - center[0]) - math.atan2(point1[1] - center[1], point1[0] - center[0])
def unstuck(node, end, planar, graph):
global recovery, recovery_options
next_node = ()
if recovery == recovery_options[0]:
next_no... | This function implements a greedy pathfinding algorithm to navigate from a start node to an end node in a graph. It selects the next node by evaluating angular directions relative to the end, prioritizing the closest direction (right or left) to minimize distance. If stuck, it employs an 'unstuck' mechanism to recover.... | def greedy_compass(start, end, graph, planar):
global num_steps, loop_recovery
loop_recovery = False
node = start
while node != end:
right_node = node
left_node = node
right_angle = math.pi/2
left_angle = -1 * math.pi/2
for neighbor in graph[node]:
if... |
def greedy(start, end, graph, planar):
global num_steps, loop_recovery
loop_recovery = False
node = start
while node != end:
#print(node, graph[node])
next_node = node
distance = distance_calc(node, end)
for neighbor in graph[node]:
if distance_calc(neighbo... | The code defines a `path` function that selects and executes a specific pathfinding algorithm based on the `base` parameter. It dispatches to different methods like `greedy`, `compass`, or `aware_compass` depending on the input, using the graph and planar data. If `base` is unrecognized, it prints an error and returns ... | def path(start, end, graph, planar):
if base == "greedy":
greedy(start, end, graph, planar)
elif base == "compass":
compass(start, end, graph, planar)
elif base == "greedy_compass":
greedy_compass(start, end, graph, planar)
elif base == "aware_compass":
aware_compass(star... |
def check_XML_root(self):
"""Validate XML root element and his attributes."""
if self.code.tag != "program" or self.code.get("language") != "IPPcode22":
ErrorMessages.exit_code(32)
for k, v in self.code.attrib.items():
if k not in ["language", "name", "description"]:... | The code loads XML source code from a file or stdin, parses it into an ElementTree object, stores the root element, and triggers validation steps by calling methods to check the XML root, sort instructions by order, and validate the code structure. | def load_source_code(self):
"""Load XML source code and send it to further validation."""
tree = None
# parse XML source
try:
if self.source == "STDIN":
tree = ET.parse(sys.stdin)
else:
tree = ET.parse(self.source)
except:
... |
def print(self):
for i in range(16):
if i % 4 == 0:
print('|', end='')
if self.ubin[i].value == 16:
print(" ", end='|')
else:
print(str(self.ubin[i].value).rjust(2, ' '), end='|')
if i % 4 == 3:
prin... | The main task of the code is to initialize a command-line interface (CLI) by printing the initial position, calculating the sum of KURANG(i) values, checking and displaying the value of X, and outputting the total of KURANG(i) + X. It prepares the environment for further operations by displaying key computational resul... | def initializeCLI(self):
print("Posisi awal:")
self.print()
self.sumOfKurang = self.findSumOfKurang()
self.checkX()
print(f"X = {self.X}")
print(f"Sum of KURANG(i) + X = {self.sumOfKurang + self.X}")
print() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.