dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def preprocess(features, annotations, action, dct):
new_features = []
new_labels = []
# Each feature array is (# of frames, # of features) dimensional
for feat_arr, annot_arr in zip(features, annotations):
length = len(feat_arr) - len(feat_arr) % 100
# Instead of taking all the features,... | The code initializes a machine learning framework by loading a base program, configuring device settings (CPU/GPU), handling dataset loading and preprocessing for different experiments (e.g., 'crim13' or 'mars_an'), setting up data loaders, and preparing for training or evaluation. It also manages experiment-specific p... | def __init__(self, base_prog, **kwargs):
self.base_program_name = base_prog
print(self.base_program_name)
self.__dict__.update(kwargs)
if torch.cuda.is_available():
self.device = 'cuda:0'
print(self.device)
else:
self.device = 'cpu'
... |
def var_loss(z_var_stack, itr, annotation, image, keep_probability, istrain):
tensor_list = []
for i in range(itr):
z_curr = tf.reshape(tf.slice(z_var_stack, [i,0,0,0,0], [1,FLAGS.batch_size,1,1,64 ]), [FLAGS.batch_size,1,1,64])
logits, _ = inference(image,keep_probability, z_curr ,0... | The main task of the code is to train a deep learning model for image segmentation using adversarial training and latent variables. It defines placeholders for input images, annotations, and latent variables (z), computes losses involving adversarial components (advloss_g/advloss_d), variance loss, and gradient-based u... | def main(argv=None):
keep_probability = tf.placeholder(tf.float32, name="keep_probabilty")
image = tf.placeholder(tf.float32, shape=[None, IMAGE_SIZE, IMAGE_SIZE, 3], name="input_image")
annotation = tf.placeholder(tf.float32, shape=[None, IMAGE_SIZE, IMAGE_SIZE, 3], name="annotation")
z = tf.placeholde... |
def gen_next_all_potential_moves(token_position):
potential_movements = []
potential_movements.append(vertical_movement(token_position, "up"))
potential_movements.append(vertical_movement(token_position, "down"))
potential_movements.append(horizontal_movement(token_position, "left"))
potential_movem... | This function generates valid moves for a token by filtering potential movements based on adjacency, avoiding overlaps with own tokens, removing explored positions, and excluding opponent token positions according to type interactions, returning the final list of permissible moves. | def gen_possible_moves(token_position, token_type, opponent_token_array, adjacent_token_list, my_token_array, explored_pos_lst, show_text=False):
potential_movements = gen_next_all_potential_moves(token_position)
truly_adjacent = adjacent_token_list.copy()
if show_text == True:
print("**Originally h... |
def gen_next_all_potential_moves(token_position):
potential_movements = []
potential_movements.append(vertical_movement(token_position, "up"))
potential_movements.append(vertical_movement(token_position, "down"))
potential_movements.append(horizontal_movement(token_position, "left"))
potential_movem... | This function generates valid moves for a token by filtering potential movements based on adjacency, swing moves, unexplored positions, and opponent token interactions. It combines potential moves with swing moves not in original movements, removes adjacent moves blocked by own tokens, excludes explored positions, and ... | def gen_move_failure(token_position,token_type, opponent_token_array, adjacent_token_list, my_token_array, explored_pos_lst):
potential_movements = gen_next_all_potential_moves(token_position)
truly_adjacent = adjacent_token_list.copy()
if len(adjacent_token_list) != 0:
for adjacent_pos in adjacent_... |
def solve_payoff(best_actions, opponent_actions, player_pos, opponent_pos, opponent_throws_left, my_throw_range, op_throw_range, my_defeated_token_num, enemies_defeated, player ,my_throws_left):
'''
Generate the payoff matrix (M*N) based on player's potential actions (M) and enemy's potential actions (N), the s... | This function determines the optimal action for a player in a strategy game by evaluating potential moves (offensive throws, defensive maneuvers, token movements) using a payoff matrix. It considers factors like remaining throws, token positions, and threats, prioritizing actions that minimize risk and maximize strateg... | def make_decision(player_pos, opponent_pos, opponent_throws_left, my_throw_range, op_throw_range, my_defeated_token_num, enemies_defeated, player, my_throws_left):
'''
Generate our player's next action based on the solving payoff matrix.
'''
if opponent_pos:
if (opponent_throws_left <= 0) and (m... |
def gen_next_all_potential_moves(token_position):
'''
Generate all coordinate tuples of next potential slide movement of current token and store them into a list.
:param token_position: the coordinate of current token
:return: a list contains all coordinate tuples of next potential slide movement
'... | The function generates all valid moves for a token on a hexagonal board by filtering potential movements based on adjacency, swing rules, explored positions, blocks, and opponent tokens. It first identifies possible moves, adjusts for adjacent tokens, adds swing moves, then removes invalid positions (already explored, ... | def gen_possible_moves(token_position,
token_type,
block_array,
opponent_token_array,
prev_position,
adjacent_token_list,
my_token_array,
explored_pos_lst,
... |
def gen_next_all_potential_moves(token_position):
'''
Generate all coordinate tuples of next potential slide movement of current token and store them into a list.
:param token_position: the coordinate of current token
:return: a list contains all coordinate tuples of next potential slide movement
'... | The function generates and returns a list of valid moves for a token based on the board state, filtering out invalid positions such as explored spots, blocks, and opponent tokens according to game rules. It considers adjacency, swing moves, and token-type interactions (e.g., 'r' vs. 's', 's' vs. 'p', 'p' vs. 'r') to ex... | def gen_move_failure(token_position, token_type, block_array,
opponent_token_array, prev_position, adjacent_token_list,
my_token_array, explored_pos_lst):
'''
This function has the same logic with "gen_possible_moves" function except the return value is a little bit dif... |
def gen_possible_moves(token_position, token_type, opponent_token_array, adjacent_token_list, my_token_array, explored_pos_lst, show_text=False):
potential_movements = gen_next_all_potential_moves(token_position)
truly_adjacent = adjacent_token_list.copy()
if show_text == True:
print("**Originally h... | The function `evasive_attack` generates a strategic move to evade threats while progressing toward a goal. It calculates possible moves, filters out positions adjacent to the closest threat, and selects the move closest to the token's target goal. The task is to return a "Move" command directing the token to the safest... | def evasive_attack(my_token_list, opponent_token_array, adjacent_token_list, my_token_array):
explored_pos_lst = explored_pos_lst = [my_token_list[1]]
token_pos = my_token_list[1]
token_type = my_token_list[0]
threat_list = my_token_list[3]
escape_opts = gen_possible_moves(my_token_list[1], my_token... |
def boarder_check(position):
if (position[0] < -4) or (position[0] > 4):
return False
if position[0] == 4:
if not(-4 <= position[1] <= 0):
return False
elif position[0] == 3:
if not(-4 <= position[1] <= 1):
return False
elif position[0] == 2:
if no... | This function generates a list of possible "THROW" actions for a player's tokens, targeting positions that either overlap with enemy-allowed coordinates or are reachable by enemy tokens. It filters valid coordinates based on throw ranges, board boundaries, and token interactions, prioritizing moves that could block ene... | def covering_throw(my_token_array, enemy_token_array, faction, my_throw_range, my_throws_left, enemy_throw_range, enemy_throws_left):
# Warning: Might result in friendly kill
if my_throws_left <= 0:
return
if faction == "upper":
allowed_r_coord = [i for i in range(4 - my_throw_range, 5... |
def gen_possible_moves(token_position, token_type, opponent_token_array, adjacent_token_list, my_token_array, explored_pos_lst, show_text=False):
potential_movements = gen_next_all_potential_moves(token_position)
truly_adjacent = adjacent_token_list.copy()
if show_text == True:
print("**Originally h... | This function performs a recursive depth-first search (DFS) with A* prioritization to find a path from a token's current position to the nearest goal. It generates possible moves, sorts them by proximity to the goal, explores unvisited positions, and recursively searches until the goal is reached or no moves remain. If... | def recursive_DFS_path_finding(token_position, goal, token_type, opponent_token_array, prev_position, adjacent_token_list, my_token_array,explored_pos_lst,hist_stack, path_found, origin):
'''
Construct a recursive A* search in a DFS search manner to find the path towards the nearest goal from the token's curren... |
def gen_possible_moves(token_position,
token_type,
block_array,
opponent_token_array,
prev_position,
adjacent_token_list,
my_token_array,
explored_pos_lst,
... | The code implements a recursive A* search using DFS to find a path from a token's current position to the nearest goal. It generates possible moves, sorts them by proximity to the goal, and explores each recursively. If no valid moves exist, it attempts reserve moves. Upon reaching the goal, the path is recorded in `pa... | def recursive_DFS_path_finding(token_position, goal, token_type, block_array,
opponent_token_array, prev_position,
adjacent_token_list, my_token_array,
explored_pos_lst, hist_stack, path_found,
or... |
def gen_possible_moves(token_position,
token_type,
block_array,
opponent_token_array,
prev_position,
adjacent_token_list,
my_token_array,
explored_pos_lst,
... | The function determines the optimal movement path for a token using DFS, comparing newly found paths with existing ones. It updates the token's position based on path availability, length, and historical data, ensuring efficient navigation toward a goal while avoiding obstacles and opponent tokens. | def make_move_recursive(my_token_list, goal, prev_pos, my_token_array,
block_array, opponent_token_array, adjacent_token_list,
last_hist_stack, move_hist_array):
'''
Update current token's moving route stack by applying DFS and make the optimal move for the token.... |
def calculate_distance(start, goal):
distance = math.sqrt((start[0]-goal[0])**2+(start[1]-goal[1])**2+(start[0]-goal[0])*(start[1]-goal[1]))
return distance
def gen_next_all_potential_moves(token_position):
potential_movements = []
potential_movements.append(vertical_movement(token_position, "up"))
... | This function identifies the optimal escape route for a token by analyzing potential cover positions, filtering available moves, and calculating the closest safe path to avoid opponent tokens. | def run_for_cover(my_token_list, opponent_token_array, adjacent_token_list, my_token_array):
token_type = my_token_list[0]
token_position = my_token_list[1]
potential_cover_lst = []
dist_to_cover = []
if token_type == "r":
for my_token in my_token_array:
if my_token[0] == "s":
... |
def approx_function(N,parameters,INPUT,T):
groups_to_vaccinate = insight(parameters,INPUT)
threshold, alpha = thresholds(parameters,INPUT,T)
v_approx = np.zeros((n_obj,2*n_groups))
approx_optimal = np.zeros(n_obj)
for i in range(n_obj):
N_temp = N
v_temp = np.zeros(2*n_groups)
... | The function `delta_2` computes optimal vaccination strategies by comparing approximate and numerical solutions across multiple objectives. It initializes arrays for differences, optimal/approximate vaccination values, and groups to vaccinate. It first generates approximate solutions using `approx_function`. Then, for ... | def delta_2(N,parameters,INPUT,T):
difference = np.zeros(n_obj)
v_opt = np.zeros((n_obj,2*n_groups))
v_approx = np.zeros((n_obj,2*n_groups))
numerical_optimal = np.zeros(n_obj)
groups_to_vaccinate = np.zeros((n_obj,2*n_groups))
v_approx1, approx_optimal1, groups_to_vaccinate1 = approx_func... |
def approx_function(N,parameters,INPUT,T):
groups_to_vaccinate = insight(parameters,INPUT)
threshold, alpha = thresholds(parameters,INPUT,T)
v_approx = np.zeros((n_obj,(m-1)*n))
approx_optimal = np.zeros(n_obj)
for i in range(n_obj):
N_temp = N
v_temp = np.zeros((m-1)*n)
... | The main task of the code is to compute and compare optimal vaccination strategies by iterating over multiple objectives. It initializes arrays for results, calls an approximation function, and iteratively evaluates numerical solutions using a `delta` function. For each objective, it checks thresholds, calculates diffe... | def delta_2(N,parameters,INPUT,T):
difference = np.zeros(n_obj)
v_opt = np.zeros((n_obj,(m-1)*n))
v_approx = np.zeros((n_obj,(m-1)*n))
numerical_optimal = np.zeros(n_obj)
groups_to_vaccinate = np.zeros((n_obj,(m-1)*n))
v_approx1, approx_optimal1, groups_to_vaccinate1 = approx_function... |
def CreateNewNodes(self):
if not self.current_round in self.starting_list:
return
for node_id in self.starting_list[self.current_round]:
if node_id in self.byzantine_nodes:
self.CreateNewNode(node_id, self.byzantine_nodes[node_id])
else:
... | This code simulates a distributed system by iteratively processing nodes in rounds. It manages node creation, message broadcasting, message routing, input handling, and output logging. Each round updates node states, processes messages, generates JSON outputs for visualization, and validates expected results. The loop ... | def Run(self):
self.CreateNewNodes()
while self.HasRunningNode():
print("round {}".format(str(self.current_round)))
logging.info("Current round {}".format(str(self.current_round)))
self.CreateNewNodes()
self.TurnOffNodes()
logging.debug("Curren... |
def get_pos_moves(self):
moves = []
for r in range(len(self.board)):
for c in range(len(self.board[r])):
if self.check_for_right_move(r,c):
piece = self.board[r][c]
if "pawn" in piece:
self.get_pawn_moves(r, c, m... | This function filters valid moves by simulating each potential move, checking if it leaves the player's king in check. If a move causes check, it's removed. It then determines checkmate or stalemate if no valid moves remain, updating corresponding flags. Finally, it returns the list of valid moves after processing. | def get_valid_moves(self):
moves = self.get_pos_moves()
for i in range(len(moves)-1, -1, -1):
self.make_move(moves[i])
self.white_move = not self.white_move
if self.is_check():
moves.remove(moves[i])
self.white_move = not self.white_move
... |
def init_folders(general_dir):
task_1 = os.path.join(TEST_DATA_RESULTS_DIR, general_dir, 'answer', 'task1')
task_2 = os.path.join(TEST_DATA_RESULTS_DIR, general_dir, 'answer', 'task2')
zip_file = 'UWB_' + general_dir
zip_file = os.path.join(TEST_DATA_RESULTS_DIR, zip_file)
folder_to_zip = os.path.... | The code's main task is to evaluate translation quality across multiple languages (English, German, Latin, Swedish) using word embeddings. It processes command-line arguments to configure parameters like embedding type, dimension, normalization, and thresholding. The script runs default evaluation tasks for each langua... | def main():
global ver_xform, individual_xform, transdict_length, compute_trans_qual, normalization, thirdspace, transdict_path, transdict_base, transdict_limit, general_folder, compare_gold
# clmet_t1 = os.path.join(EMBEDDINGS_EXPORT_PATH, 'fasttext-min-count-5', 'clmet_t1','lower_fasttext.clmet_t1.100_window-... |
def get_object(self, queryset=None):
return self.request.user
def get_profile_form(self):
form_kwargs = {'instance': self.object.profile}
if self.request.method == 'POST':
form_kwargs['data'] = self.request.POST
form_kwargs['files'] = self.request.FILES
return Pro... | This code handles a POST request by retrieving an object, validating two forms (main and profile), and either saving them via form_valid or returning invalid responses via form_invalid if validation fails. | def post(self, request, *args, **kwargs):
self.object = self.get_object()
form = self.get_form()
profile_form = self.get_profile_form()
if form.is_valid() and profile_form.is_valid():
return self.form_valid(form, profile_form)
else:
return self.form_invali... |
def __getAllPaths(self, root_path, extensions):
if isinstance(extensions, str):
file_list = [path.name for path in Path(root_path).rglob(extensions)]
path_list = [str(path) for path in Path(root_path).rglob(extensions)]
else:
file_list, path_list = [], []
... | The main task of the code is to extract data from .txt annotation files and image files (png/jpg/jpeg) under a given root path. It processes image metadata into a DataFrame, updates the dataset, maps annotations to corresponding images using filenames, and refines annotation data through a DFRefiner to organize structu... | def extract(self, path:str):
"""extract data from .txt annotation files and update super attributes
Args:
path (str): root path for the all annotation & image files
"""
image_paths, image_files = self.__getAllPaths(path, ['png', 'jpg', 'jpeg'])
image_df = self.__getI... |
def check_bottom(self):
for alien in self.aliens:
if alien.rect.bottom >= self.settings.screen_height:
return True
return False
def re_set_aliens(self):
self.aliens.empty()
self.lasers.lasers.empty()
self.create_fleet()
self.sh... | This code updates alien positions, checks for game-over conditions by detecting aliens reaching the bottom, resets aliens, handles collisions between aliens and the ship, updates lasers, draws game elements, and updates the scoreboard with high score, current score, and remaining ships. | def update(self):
for alien in self.aliens: alien.update()
if self.check_bottom():
if self.settings.ship_limit > 1:
self.settings.ship_limit -= 1
else:
self.game.game_over()
self.score = 0
self.re_set_aliens()
... |
def _get_turn(self):
"""
:return:
Returns which player should make a move.
"""
return self.turns_played % 2
def _add(self, cell, player):
"""
GUI and backend management of plays without validity checks. Change the hex color. Set owner in board graph.
Add m... | The code adds a stone to the board for the current player (player1 or player2) based on the turn. If `first` is True, it directly adds the stone; otherwise, it performs a validity check before adding. The function handles initial placement or subsequent moves, ensuring correct player assignment and optional validation. | def add_piece(self, cell, first=False):
"""
Add a stone on the board. No check if first pieces. Validity check afterwards.
:param cell: Tuple (x,y).
:param first: First turn or not
:return:
"""
if self._get_turn() == 0:
self._add(cell, self.player1) if... |
def _check_if_first_piece(self, cell):
"""
First piece must be played in the center of the board. HARDCODED for current board.
:param cell:
:return:
"""
# Center cell for standard board. Hardcoded
center_cell = (16, 9)
if self.turns_played == 0:
... | The main task of the code is to validate and execute a move in a hexagonal game by checking if the target cell is open or if it's the first move for a player. It ensures proper turn order and placement rules before adding a stone to the specified cell. | def play_piece(self, cell):
"""
Play a stone in a hex. Performa all validity checks.
:param cell: Tuple (x,y).
:return:
"""
if len(self.player1.move_list) == 0:
self._check_if_first_piece(cell)
elif len(self.player1.move_list) > 0 and len(self.player2.... |
def get_all_configurations(state):
new_matrix = deepcopy(state.positions)
m = np.array(new_matrix)
score = state.points
#print(score)
x = compute_score(state.city, np.flip(m, 0))
#print(x)
if x > score:
score = x
m = np.rot90(m)
x = compute_score(state.city, m)
#print(... | The code implements a heuristic search algorithm to find the maximum score achievable in a state-based problem with time constraints. It explores states by prioritizing those with higher potential scores (using a heuristic), avoiding revisits via a closed set, and terminating after 175 seconds. The solution tracks the ... | def find_solution(state):
open_set = []
closed_set = set()
open_set.append(state)
start = time.time()
max_score = 0
while open_set:
if time.time() - start > 175:
return str(max_score)
curr_state = open_set.pop(0)
if curr_state.police == 0:
#p... |
def parse(input_: str) -> List[int]:
return [int(line) for line in input_.splitlines()]
def solve_part1(numbers: Sequence[int]) -> int:
return find_invalid_number(numbers, preamble_length=25)
def solve_part2(numbers: Sequence[int]) -> int:
invalid_number = solve_part1(numbers)
contiguous_range = find_co... | The main task of the code is to read input from standard input, parse it into numerical data, compute two solutions using separate functions, and print both results. The `main()` function orchestrates this workflow by first capturing input, parsing it into a list of numbers, then applying `solve_part1` and `solve_part2... | def main() -> None:
input_ = sys.stdin.read()
numbers = parse(input_)
print(solve_part1(numbers))
print(solve_part2(numbers)) |
def parse(input_: str) -> Rules:
return {
" ".join(line.split()[:2]): [
(match[1], int(match[0]))
for match in re.findall(r"(\d+) (\w+ \w+) bags?", line)
]
for line in input_.splitlines()
}
def solve_part1(rules: Rules) -> int:
return count_bags_containing("sh... | The main task of the code is to read input from standard input, parse it into rules, solve two problem parts using these rules, and print the results of both solutions. The `main()` function orchestrates reading input, parsing, and executing the two solution functions, `solve_part1` and `solve_part2`, which likely comp... | def main() -> None:
input_ = sys.stdin.read()
rules = parse(input_)
print(solve_part1(rules))
print(solve_part2(rules)) |
def retrieve_champion_names_string() -> str:
'''
Request champions from database
'''
# Connect to the database with a socket
DB = environ.get("DATABASE", "localhost")
database = create_connection((DB, 5555))
send_data(database, globals.DATA, "")
champions = recieve_data(database)
re... | This function handles a player's champion selection in a game. It retrieves available champions, prompts the player to choose one via a socket, validates the selection against the current champion list, and adds the chosen champion to the player's team if valid. The process repeats until a valid selection is made, with... | def select_champion(self, waiting_player: Player) -> None:
# Receive champions from database
champions = retrieve_champion_names_string()
self.print_champs(champions)
waiting_player.print(
f"[{waiting_player.color}]Wait for Player {self.num} to select champion..."
)
... |
def update_tick(self):
self.current_tick = utils.get_tick(self.session)
self.log(self.current_tick, 1)
return self.current_tick
def update_orderbook(self):
for ticker in self.tickers:
self.orderbook[ticker] = utils.get_orderbook(self.session, ticker)
... | The code processes market data updates by checking the current tick against an update interval. If not aligned, it updates order books, positions, and other financial data, computes alpha (likely for trading signals), and triggers the trading algorithm if enabled. The main task is to synchronize data updates and execut... | def run(self):
tick = self.current_tick
if tick == self.update_tick():
return
self.update_orderbook()
self.update_orderbook_full()
self.update_last()
self.update_position()
self.update_tender()
self.compute_alpha()
... |
def check_action_viability(self, action, state):
# TODO: This should work for any state
"""
Current implementation has the 8 directions in the action definition
:param action: tuple of (player, 'Builder'/'Building', X move, Y move)
Steps:
If move:
1. Get curre... | This function executes a game step for the current player. For player 1, it validates the action against the current state, evolves the state if valid, and checks end conditions. For player 2, it uses an opponent agent to select an action, evolves the state, and checks end conditions. It returns the new state, reward, ... | def step_play(self, action):
if self.current_player == 1:
# TODO: Edit this for new check_action_viability (using self.state)
viability, info = self.check_action_viability(action, self.state)
if not viability:
print('NO VIABILITY', info)
return... |
def _populate_node (
self,
row: GraphRow,
*,
debug: bool = False, # pylint: disable=W0613
) -> Node:
"""
Private method to populate a Node object from the given Parquet row data.
"""
# lookup to make sure that we don't overwrite if the src node
# ... | The code processes a stream of graph rows to build a graph partition. It iterates through rows, creating new nodes when `edge_id` is negative and validating node/edge consistency. If a row's source name mismatches the current node, it raises an error. Otherwise, it constructs edges for the latest node, handling validat... | def parse_rows (
self,
iter_load: typing.Iterable[typing.Tuple[int, GraphRow]],
*,
debug: bool = False,
) -> None:
"""
Parse a stream of rows to construct a graph partition.
"""
for row_num, row in track(iter_load, description=f"parse rows"):
#... |
def set_franka_angles_target(self, angles, env_n):
angles = np.clip(angles, a_min = self.franka_lower_limits, a_max=self.franka_upper_limits, dtype = np.float32)
self.target_angles[env_n] = angles
self.gym.set_actor_dof_position_targets(self.envs[env_n], self.franka_handles[env_n], np.array(angl... | This function sets target joint angles for a Franka robot in a simulation, executes the movement via repeated simulation steps, and monitors a timeout to prevent infinite loops. It calculates and prints the movement duration and angular error in degrees, ensuring the robot reaches the target angles within 40 steps or e... | def set_franka_angles(self, angles, env_n, skip_timeout = False):
self.set_franka_angles_target(angles, env_n)
# state_tensor = torch.tensor(self.target_angles, dtype=torch.float32)
# self.gym.set_dof_position_target_tensor(self.sim, gymtorch.unwrap_tensor(state_tensor))
# self.sim_ste... |
def resize(img, fx, fy) -> np.ndarray[Any, np.dtype[np.generic]]:
"""
Resizes the image by a factor of fx horizontally and fy vertically and returns an image
Arguments:
img - Image being resized
fx - X scale
fy = Y scale
"""
return cv.resize(img, None, fx=fx, fy=fy)
def make_ver_mask(im... | The main task of the code is to process a video file by applying two edge detection techniques (Canny edge detection and white mask detection) to each frame, combine the results, and overlay them on the original video frames for real-time visualization. The code reads the video, resizes frames, applies preprocessing, d... | def main():
cv.namedWindow('edge')
cap = cv.VideoCapture("../20230605_163120.mp4")
frame_count = cap.get(cv.CAP_PROP_FRAME_COUNT)
end = False
curr_frame = 0
while (curr_frame + 2) < int(frame_count) and not end:
start_time = timer()
# To speed process, the software only runs ... |
def advanced_cond_wrapper(text_to_reply_to: str, cond: str) -> bool:
'''
str, str -> bool
Wrapper for dealing with advanced conditions,
checks if text_to_reply_to satisfies the condition
Syntax:
- & q: is a str or a str struct such that each side of a boolean operator is either a str... | The function `reply_to` determines if a Reddit bot should reply to a given post or comment based on predefined conditions. It checks if the message contains the bot's username, avoids self-replying, respects opt-out lists, and adheres to reply delay thresholds. If conditions are met, it generates and sends a reply usin... | def reply_to(msg_obj: str,
bot_config: dict,
reply_to_self: bool = False
) -> bool:
'''
str, dict, dict, bool -> bool
Returns a boolean indicating whether a reply was successfully made
msg_obj: A praw object representing a post or comment
Repli... |
def predictimage(imagelist,model):
pred_dict = {0:"jute",1:"maize",2:"rice",3:"sugarcane",4:"wheat"}
image_prediction = []
for num,image in enumerate(imagelist):
image = preprocess_image(image)
prediction = model.predict(image.reshape(-1,224,224,3))
pred = pred_dict[np.argmax(predic... | The code predicts crop types from images in a DataFrame, calculates each crop's area using land area data, and estimates production by multiplying crop area with predefined yield rates, returning a DataFrame with crop areas and corresponding production values. | def predict_production(df):
imagelist = df.imagelist.values
cropdict = {'jute':0,'maize':0,'rice':0,'sugarcane':0,'wheat':0}
prediction = predictimage(imagelist,model=build_model())
df['prediction_images'] = prediction
each_crop_area_df = cropwisearea(df['LandArea(in Acre)'].values,df['prediction_im... |
def read_excel_data():
path = os.path.join("D:\SIH","Ann-Aztecs","satellliteimage.xlsx")
ex_df = pd.read_excel(path)
return ex_df
def search_all_images(ex_df):
main_path = os.path.join("D:\SIH","Ann-Aztecs","satimage")
df = ex_df.copy()
imagelist = [os.path.join(main_path,(str(df['ImageId'][i])+... | The main task of the code is to process agricultural data by reading Excel files, searching for images, integrating farmer production records, predicting production outcomes using a model, displaying results via Streamlit, and generating a bar chart visualization to analyze and present the predicted data. | def data2020():
ex_df = read_excel_data()
df = search_all_images(ex_df)
df = read_farmer_production(df)
result = predict_production(df)
st.write(result)
plot_bar(result) |
def load_data2():
data = pd.read_csv('book_data.csv', encoding='latin-1')
data = data.dropna()
for i in data.index:
data['label'][i] = data['label'][i].replace('[', '')
data['label'][i] = data['label'][i].replace(']', '')
data['label'][i] = data['label'][i].split(' ')
if('' i... | The code classifies an input message by finding the k=4 nearest neighbors in a book dataset using Euclidean distance, returning the top label(s) from the closest books. It loads book names and coordinates, converts the message to a test vector, computes distances, retrieves nearest labels, and extracts the first elemen... | def toBook(message):
k = 4
book_name, book_kord = load_data2()
test_data = toChance(message)
r = k_nearest_labels(euclidian_dist(book_kord, test_data), book_name, k)[0]
temp = []
for i in range(len(r)):
temp.append(r[i][0])
return temp |
def get_property(line):
if ":" not in line: return line.lstrip().rstrip()
try:
x, line = line.split(": ")
return line.rstrip().lstrip()
except:
print(line)
raise Exception("received invalid line")
def createMap(data):
m = Map()
item_metadata, tier, ilvl, descr = data... | The function `from_description` parses an item's description to identify its class (e.g., "Maps" or "Incubators") and returns an instance of the corresponding subclass (via `createMap` or `createIncubator`). If the class is unrecognized, it returns `None`. | def from_description(desc):
"""
returns an Item (or subclass) from a copy/pasted description
of an item
"""
raw = desc.split("\n")
for line in raw:
if "Item Class" in line:
item_class = get_property(line)
if item_class == "Maps":
return createMap(desc)
... |
def login():
print("============== Login to your account ===============")
isLoginSuccessful = False
while isLoginSuccessful == False:
accountNumberFromuser = int(input("What is your account number? \n"))
password = input("What is your password? \n")
for accountNumber, userDetails i... | The code prompts the user to select if they have an account (1 for yes, 2 for no), validates the input, and directs them to a login or registration function. It loops until a valid option is chosen, ensuring proper user account management flow. | def init():
isValidOptionSelected = False
while isValidOptionSelected == False:
haveAccount = int(input("Do you have an account with us: 1 (yes) 2 (no) \n"))
if haveAccount == 1:
isValidOptionSelected = True
login()
elif haveAccount == 2:
isValidOption... |
def projM(self, u):
'''
projection operator on magnitude constraint in r-space
constraint is on amplitude of complex tensor
args:
u = torch float tensor of size N * 1 * H * W * 2
returns:
outputs = torch float tensor of size N * 1 * H * W * 2
''... | The code implements forward iterations for phase retrieval algorithms (HIO, RAAR, gRAAR, dRAAR, GPS, dpGPS) by applying domain-specific updates to input tensors. It processes parameters like `u`, `z`, `y` with projections, FFTs, and proximal operators, returning updated tensors based on the algorithm type. Boundary con... | def forward(self, **kwargs):
'''
iteration of phase retrieval algorithms
for [HIO, RAAR, gRAAR, dRAAR], if toggle is True, boundary push is performed
kwargs:
u = torch float tensor of size N * 1 * H * W * 2 (for HIO, RAAR, gRAAR, dRAAR)
beta = float (for... |
def warm_up_motion():
# to enforce proper y-axis scaling, must add one point with value 360
# conveniently, the cams should turn from 0 to 360 degrees over the full timespan
clickPos(cam1_joint)
setValue(0, 2*math.pi, 360)
clickPos(cam2_joint)
setValue(0, 2*math.pi, 360)
def clickPos(pt):
py... | The code generates motion data for robotic followers and joints by calculating spherical coordinates from 2D positions and angles, storing keyframes for 20 steps. If `dry=True`, it prints the data; otherwise, it applies the values to joints via `clickPos` and `applyThetaVals` for physical deployment. | def deploy_motion_study(dry=False):
if not dry:
warm_up_motion()
follower1_vals = []
follower2_vals = []
green_angle_vals = []
red_angle_vals = []
# must be at most 100 keyframes because fusion limits steps from 1 to 100
# 50 gives a good spacing
for (theta, s) in getThetaS(20):
... |
def get_solution_status(self) -> int:
"""Returns the status of the solution. Use the constants defined in cplex_constants.py."""
return self.cplex_model.solution.get_status()
def get_objective_value(self) -> float:
"""Returns the value of the objective function. In case of infeasible solution, r... | The main task of the code is to save a linear programming solution's key metrics—such as objective value, total distance, energy, and solution time—into a specified file. It also writes drone deployment details at each time step if the solution status indicates feasibility. The function formats these data points in a s... | def save_solution(self, file_name: str) -> None:
"""Saves the solution of the linear program to a file.
It saves the objective function value, time to reach the solution, and the deployment of drones at each time step.
Args:
file_name (str): Name of the file to save the solution.
... |
def define_all_variables(self) -> None:
"""Defines all the variables of the linear program. Uses the function define_variable to save the information of the variables in the corresponding lists. Later the variables must be added to the cplex model."""
# Defining the variables z_t_p for all t \in T and p... | The main task of the code is to construct a linear programming model using the CPLEX solver. It defines decision variables, constraints, and the objective function, then adds them to the CPLEX model. The method first initializes variables and constraints, maps them to the CPLEX instance, and sets the objective function... | def build_model(self) -> None:
"""Builds the linear program by defining all the variables, constraints and objective function and adding them to the cplex model."""
self.define_all_variables()
self.define_all_constraints()
self.set_variables_to_cplex()
self.set_constraints_to_cp... |
def ardict():
with open('angelsandrejects.json', 'r') as f:
ardict = json.loads(f.read())
return ardict
def bigasslistmake(ardict):
bigasslist = []
realbigasslist = []
bigasslist.append(makeAIStrichords())
bigasslist.append(makeAIStetrachords())
bigasslist.append(makeAISpentachords(a... | The main task of the code is to generate a dictionary from processed data, convert it into a structured format, and save it as a JSON file. The function initializes a dictionary using `ardict()`, processes it into a list with `bigasslistmake()`, transforms the list into a dictionary with `dictmake()`, and writes the fi... | def main():
angrejdict = ardict()
allAIS = bigasslistmake(angrejdict)
w = dictmake(allAIS)
with open("calculatordict.json", 'w') as f:
json.dump(w, f, indent = 4) |
def get_tiles(self):
return [
(row, column)
for row in range(self.height)
for column in range(self.width)
]
def get_contiguous(self, source):
checked = {source}
to_be_checked = {source}
contiguous = {source}
while to_be_checked:
... | The code identifies contiguous wall tiles in a maze. It iteratively selects a tile, finds all contiguous tiles, removes them from the set, and adds the group to the walls list if the tile is a wall (value 1). The result is a list of wall tile groups. | def get_walls(self):
tiles = set(self.get_tiles())
walls = []
while tiles:
tile = tiles.pop()
contiguous = self.get_contiguous(tile)
tiles.difference_update(contiguous)
if self.get_tile(self.maze, tile) == 1:
walls.append(contiguous... |
def get_contiguous(self, source):
checked = {source}
to_be_checked = {source}
contiguous = {source}
while to_be_checked:
checking = to_be_checked.pop()
destinations = self.get_destinations(checking)
for destination in destinations:
cont... | This code initializes a maze-solving class by setting up the maze structure, defining movement directions, identifying entrance/exit points, and determining solvability. It constructs neighbor relationships, initializes distance tracking, and calculates the shortest path from entrance to exit using precomputed distance... | def __init__(self, maze, distances=None):
self.maze = maze
self.moves = [(-1, 0), (1, 0), (0, -1), (0, 1)]
self.height = len(maze)
self.width = len(maze[0])
self.entrance = (0, 0)
self.exit = (self.height - 1, self.width - 1)
self.neighbors = dict()
self.d... |
def calculateSigma(*args):
global sigma
try:
freq = float(frequency.get())
len = float(length.get())
c=3*(10**8)
freq=freq*(10**6)
lambd=c/freq
num = (4*3.14159)*(len**4)
den = 3*(lambd**2)
sigma=(num/den)
print(sigma)
except ValueError... | The main task of the code is to process radar data by calculating radar cross sections, generating coordinate arrays for reflectors, and creating a Tkinter GUI window with grid layout configurations. It initializes global variables, invokes computation functions, and sets up a new frame for displaying results with spec... | def processData():
global a
global filename
global intensityArray
intensityArray = []
newframe=tk.Toplevel(root)
calculateSigma() #Calculate Radar Cross Section
createCoordinateArray() #Creates array for X and Y coordinates of reflectors.
findK(newframe)
for child in newframe.... |
def request_join(ch, method, properties, body):
global NODEID
NODEID = allocate_new_nodeid()
if (os.fork() == 0):
rabbit_connect(NODEID)
def accept_join(ch):
ch.stop_consuming()
queue_name = QUEUE_NAME
prepare_join(ch, queue_name)
def action_show():
show = f"I'm {NODEID}. My predec... | This callback function processes incoming messages in a DHT (Distributed Hash Table) system. It handles commands like 'new', 'join', 'show', 'remove', and 'put' to manage node coordination, key-value storage, and data distribution. The core task is determining where to store keys based on node ID ranges, ensuring prope... | def callback(ch, method, properties, body):
body=body.decode('utf-8')
if 'new' in body:
request_join()
elif 'join' in body:
accept_join(ch)
elif 'show' in body:
action_show()
elif 'remove' in body:
targetNode = int( body.split(" ")[1] )
if NODEID == targetNode... |
def normalize(rl, args):
for i in range(len(rl)):
rl[i] = normalize_res(rl[i], args)
return rl
def by_resource_name(res):
if res is None:
return ""
return "{}::{}::{}".format(res['apiVersion'],
res['kind'],
res['metadata']['... | The code compares two YAML files, identifying added, removed, and modified resources. It normalizes the data, tracks differences in resource keys, and prints a detailed report showing changes, including specific resource updates with their differences. The result is the total count of changes (added + removed + modifie... | def compare(args):
j0 = normalize(list(yaml.safe_load_all(open(args.orig))), args)
j1 = normalize(list(yaml.safe_load_all(open(args.new))), args)
q0 = {by_resource_name(res): res for res in j0 if res is not None}
q1 = {by_resource_name(res): res for res in j1 if res is not None}
added, removed, co... |
def open_file():
#Asks user for file name and returns file object
while True:
file_name = input("Input file name: ")
try:
file = open(file_name)
return file
except:
print("Error opening file. Please try again.")
def get_region_data(file):
#Takes data file, asks user for region and returns dictionary w... | The main task of the code is to open a CSV file, extract region data, print it, and optionally generate a plot if the user confirms. It executes the algorithm by sequentially calling functions to handle file input, data processing, output, and visualization based on user input. | def main():
#main function. Implements algorithm in header
#calling functions
csv_file = open_file()
reg_data = get_region_data(csv_file)
print_data(reg_data)
if input("Input 'yes' if you want to plot results: ") == 'yes':
plot_data(reg_data) |
def load_mentions_with_attributes(pin, full_key=True):
"""
Create a mapping of all mentions to all their associated attributes.
This is necessary due to the structure of eHOST XML documents in which
these entities are stored in separate XML tags.
"""
if full_key:
key = pin
else:
... | The code compares annotations from two files (pin1, pin2) by matching spans and attributes. It calculates true positives (tp), false positives (fp), and false negatives (fn), logs matches/non-matches in a report, tracks attribute agreements, and returns metrics, reports, and unmatched tags for evaluation. | def count_agreements(pin1, pin2, report_string, matching):
ann1 = load_mentions_with_attributes(pin1)
ann2 = load_mentions_with_attributes(pin2)
tags1 = convert_file_annotations(ann1)
tags2 = convert_file_annotations(ann2)
matched = []
non_matched = []
tp = fp = fn = 0
... |
def load_mentions_with_attributes(pin, full_key=True):
"""
Create a mapping of all mentions to all their associated attributes.
This is necessary due to the structure of eHOST XML documents in which
these entities are stored in separate XML tags.
"""
if full_key:
key = pin
else:
... | The code compares two annotation sets (ann1, ann2) to calculate agreement metrics (TP, FP, FN) by matching spans and attributes. It generates a report detailing matched spans, unmatched annotations, and attribute overlaps, returning counts, attribute data, and classification of matched/non-matched tags for evaluation. | def count_agreements_relaxed(pin1, pin2, report_string, matching):
ann1 = load_mentions_with_attributes(pin1)
ann2 = load_mentions_with_attributes(pin2)
#TO ADD FILTERS TO THE ANNOTATIONS - NOT USED FOR PRESCRIPTIONS
#ann1 = filter_annotations(ann1)
#ann2 = filter_annotations(ann2)
tag... |
def get_all_annotated_attributes(files1, files2):
"""
Update the set of attributes to evaluate.
"""
global ATTRS
global IGNORE_ATTRS
for f in files1:
d = convert_file_annotations(load_mentions_with_attributes(f))
flat_list = [item for sublist in d for item in sublist if item... | This function calculates inter-annotator agreement between two sets of annotated files (ann1 and ann2) for a given batch. It compares spans (with strict or relaxed matching) and attributes (if enabled), aggregating true positives, false positives, and false negatives. It computes precision, recall, F-score, and attribu... | def batch_agreement(batch, ann1, ann2, files1, files2, report_dir=None, matching='relaxed', compare_attributes=True, ignore_attributes=[]):
"""
ann_dir_1 and ann_dir_2 are tuples of the form:
('Annotator1_Name','Dir_1')
('Annotator2_Name','Dir_2')
report_dir: specifies the output directory f... |
def get_game_as_string(self, game):
result = ''
for t in game:
for c in t:
result += c
return result
def can_move(self, source, destination):
if len(source) == 0 or len(destination) == MAX_HEIGHT:
return False
color_in_tube = self.count_col... | The function recursively solves a tube-pouring game by exploring all valid moves between tubes, avoiding cycles via visited states tracking, and returns the solution path as a list of moves [i,j] if the game is solved. | def solve_game(self, current_game, visited_tubes, answer):
visited_tubes.append(self.get_game_as_string(current_game))
for i, t1 in enumerate(current_game):
for j, t2 in enumerate(current_game):
if (i == j):
continue
if (self.can_move(t1, t... |
def convertToString(self, tubes):
result = []
for t in tubes:
new_tube = []
for c in t:
new_tube.append(str(c))
result.append(new_tube)
self.tubes = result
def solve_game(self, current_game, visited_tubes, answer):
visited_tubes.append(... | The code solves a puzzle involving moving items between tubes by recursively exploring possible configurations. It converts tubes to a string, iterates through each tube, and attempts to find a valid solution path using `solve_game`. If a solution is found, it records steps, updates positions, and optionally visualizes... | def solve(self):
self.convertToString(self.tubes)
for i, t in enumerate(self.tubes):
if (i < len(self.tubes) - 1):
answer = []
new_game = copy.copy(self.tubes)
self.solve_game(new_game, [], answer)
# answers are p... |
def userInputYorNFunction(userInput):
#checking the userInput
userTester = ['y','n','Y','N']
#if there input is not there than its traping them
while userInput not in userTester:
userInput = input("Please Enter (Y | N): ")
userInput.lower()
clear()
return userInput
def findWidthAndHi... | The main task of the code is to implement a maze game where the user navigates through a generated maze, collects items, and tracks their score. The game allows multiple plays, validates user inputs, and appends the final score and username to a list for a leaderboard. The function returns the updated list with new gam... | def theWholeMazeGame(totalList):
#setting vars to be global in this function
copyList = totalList
mazeGamePlay = input("\n\tDo you wish to enter? ")
#making sure the input is what i want it to be
mazeGamePlay = userInputYorNFunction(mazeGamePlay)
#calling the width and height function
wid... |
def getStubsAmount(data):
stubsAmount = requests.get('https://mlb21.theshow.com/dashboard', headers= data)
soup = BeautifulSoup(stubsAmount.text, 'html.parser')
stubsAmount = soup.find('div', {'class': 'well stubs'}).text.strip().replace('Stubs Balance\n\n', '').replace(',','').replace('Wallet\n... | The code automates buying/selling actions via a web driver, checking order success by comparing pre/post-stub/sellable amounts. If no change occurs, it triggers a reCAPTCHA solver. It retries up to 5 times on errors, playing an alert sound and prompting for updated headers if failed. Main task: execute trade orders wit... | def doRecaptcha(playerURL, webDriver, data, order):
attempts = 0
while True:
try:
webDriver.get(playerURL)
if order == 'buy':
stubsBefore = getStubsAmount(data)
placeBuyOrder(playerURL, getStubsAmount(data), data)
... |
def getHeaders():
filename = 'headers.json'
with open(filename) as f:
headers = json.load(f)
return headers
def getTotalSellable(playerURL, data):
playerPage = requests.get(playerURL, headers= data)
soup = BeautifulSoup(playerPage.text, 'html.parser')
totalSel... | The code automates executing sell orders on a game platform by scraping completed orders, checking for sellable cards, and placing sell orders. It handles errors with retries, plays sounds for alerts, and prompts for updated headers. It processes multiple pages of orders, verifies sellability, and manages reCAPTCHA if ... | def doSellOrders(currentHeaders):
#time.sleep(120)
print("Executing sell orders....")
#get data from completed orders table
attempts = 0
while True:
try:
completedPage = requests.get('https://mlb21.theshow.com/orders/completed_orders', header... |
def setup(self):
self.root = tk.Tk()
self.root.geometry("300x380")
self.root.resizable(True, True)
self.root.title('Enter video information')
def createVariables(self):
self.url = tk.StringVar()
self.start_HH = tk.StringVar()
self.start_MM = tk.StringVar()
self.start_SS = tk.StringVar()
self.stop_HH ... | This code initializes a Tkinter GUI application by setting up a window with input fields, variables, and buttons. It configures frame properties, creates entry fields using provided defaults, and starts the main event loop to display the interface. | def __init__(self, defaults: Dict[str, Union[str, int]] = {}) -> None:
self.boxes: list[tk.Frame] = []
self.box_kw = dict(fill='x', expand=True)
self.frame_kw = dict(padx=10, pady=10, **self.box_kw)
self.setup()
self.createVariables()
self.createEntryFields(defaults=defaults)
self.createButton()
self.... |
def scrapePageNumbers(page_url):
page_html = load_page(page_url)
soup = BeautifulSoup(page_html, "html.parser")
return getPageList(soup)
def getLastPage(page_list):
last_page = 1
for page in page_list:
if page["page_number"] > last_page:
last_page = page["page_number"]
return... | This code scrapes GPU availability data from BestBuy's website using multithreading, processes paginated results, clears an existing database table, and inserts new data. It reads URLs from a YAML config, scrapes product info from multiple pages, and stores results in a database. The task involves concurrent web scrapi... | def bestbuy_gpu_webscraper():
print("starting webscraper..")
with open("config.yml", "r") as yml:
cfg = yaml.safe_load(yml)
page_url = cfg["input"]["url"]
# createGPUCSV("./output/output.csv")
page_list = scrapePageNumbers(page_url)
last_page = getLastPage(page_list)
futures = []... |
def create_output_panel(self):
# A lock is used to ensure only one thread is
# touching the output panel at a time
with self.panel_lock:
# Creating the panel implicitly clears any previous contents
self.panel = self.window.create_output_panel('exec')
# Enable... | The main task of the code is to execute a command-line process for the active file, managing process termination, argument configuration, and output handling. It terminates any existing process, retrieves execution arguments, starts a new subprocess with redirected output, and initiates a thread to read the process out... | def run_impl(self, test=False, compile_=False):
self.create_output_panel()
if self.proc is not None:
self.proc.terminate()
self.proc = None
filename = self.window.active_view().file_name()
args = self.get_arguments(filename, test, compile_)
if not args:
... |
def get_vc_test_project(filename):
if "fos" in filename.lower():
dirname = os.path.dirname(filename)
rel_dir = os.path.join("..", "..", "Futil", "bld")
futil_tester = os.path.join(_get_vs_project_dir(dirname, rel_dir), "FutilLibTester.vcxproj")
return futil_tester
if "smarteston... | The function `get_vc_project` determines the correct Visual Studio project file based on the input filename. It prioritizes `Tester.cpp` files by delegating to `get_vc_test_project`, handles `smartestonelib`-related paths to return a specific `.vcxproj` file, and otherwise searches for the first non-`Tester.vcxproj` pr... | def get_vc_project(filename):
if filename.endswith("Tester.cpp"):
return get_vc_test_project(filename)
if "smartestonelib" in filename.lower():
dirname = os.path.dirname(filename)
rel_dir = os.path.join("..", "bld")
smartestonelib_project = os.path.join(_get_vs_project_dir(dirna... |
def __run(self) -> None:
with open('trending_categories.txt', 'r') as file:
lines: List[str] = file.readlines()
for link in lines:
try:
self.trending_videos.append(self.__scrape(link))
except Exception as e:
print(e)... | The main task of the code is to process video data by running operations, categorizing videos by duration, writing results to a file, and dumping final data, while printing the count of non-live videos. | def main(self) -> None:
self.__run()
self.__process()
self.__categorize_by_duration()
self.__write_to_file()
self.__dump()
print('Total videos without live videos: ', len(self)) |
def __accept_cookies_homepage(self):
try:
self.driver.find_element(
by=By.XPATH, value="//*[@id=\"content\"]/div[2]/div[6]/div[1]/ytd-button-renderer[2]/yt-button-shape/button").click()
except Exception:
pass
def __scrape(self) -> None:
time.sleep(5)
... | The main task of the code is to navigate to a specified URL using a web driver, handle cookie acceptance on the homepage, and execute scraping, data processing, and dataset preparation steps to gather and organize information from the webpage. | def main(self) -> None:
self.driver.get(self.URL)
time.sleep(2)
try:
self.__accept_cookies_homepage()
except:
pass
time.sleep(2)
self.__scrape()
self.__process()
self.__prepare_dataset() |
def train_step(self, batch):
self.model.train()
imgs, labels = batch
imgs = imgs.to(self.device)
labels = labels.to(self.device)
if self.config.get('use_amp', False):
with self.amp_context():
outputs = self.model(imgs)
loss = self.lo... | The main task of the code is to train a machine learning model over multiple epochs, performing training and validation steps for each epoch. It tracks training and validation metrics, saves checkpoints based on performance, resets metrics after each epoch, and generates convergence plots to visualize metric trends ove... | def train(self):
for epoch in range(self.config['n_epochs']):
# train
for batch in tqdm(self.train_loader, desc=f'train epoch {epoch}', leave=True):
self.train_step(batch)
# val
for batch in tqdm(self.val_loader, desc=f'validation epoch {epoch}'... |
def get_execute_database(sql_insert_query):
if mydb is None:
return False
cursor = mydb.cursor()
try:
cursor.execute(sql_insert_query)
result = cursor.fetchall()
return result
except Exception as e:
return e
mydb.close()
def combine_result_data(result):
al... | The code retrieves exam results and metadata from a database using an exam pin, processes the data to calculate average time per question and emotion percentage, and returns structured results including subject name, exam creation time, and computed metrics. | def get_exam_result_from_database(examPin):
get_result_query = "SELECT total_score, emotion, exam_items_time_stamp FROM Results WHERE exam_pin='" + examPin + "'"
get_subject_query = "SELECT exam_subject, created_at FROM Examination WHERE exam_pin='" + examPin + "'"
result = get_execute_database(get_result_... |
def __read_assembly_file(self, assembly_file_path):
with open(assembly_file_path, "r") as assembly_file:
assembly_file_lines = assembly_file.readlines()
assembly_instructions = []
for line in assembly_file_lines:
# Remove comments and empty lines from the sta... | The code's main task is to initialize an object by reading assembly instructions from a file, generating an output file path without the extension, and translating the assembly instructions into memory records for processing. | def __init__(self, assembly_file_path):
self.assembly_instructions = self.__read_assembly_file(assembly_file_path)
self.output_file_path = self.__get_file_path_without_extension(assembly_file_path)
self.memory_records = self.__translate_assembly_instructions() |
def additional_basis(c, e):
n = len(c)
V=list()
V.append([0]*n)
for k in range(1,n-1):
v_k=list()
if c[0] != 0:
v_k.append(-c[k]/c[0])
elif c[k] < 0:
v_k.append(sys.float_info.max)
else:
v_k.append(-sys.float_info.max)
for i in ... | This code computes a rotation matrix to align the vector `c` with the z-axis by sequentially applying Givens rotations. It constructs a transformation matrix `M` through iterative rotations, then combines it with an additional rotation and its inverse to finalize the alignment. The resulting matrix is applied to `self.... | def rotateTo(self, c):
self.normal=numpy.array(c)
n = len(c)
e = numpy.zeros(n)
e[-1] = 1
v = additional_basis(c, e)
M = numpy.identity(n)
for i in range(1, n-1):
for j in range(n-1, i-1, -1):
theta = numpy.arctan2(v[i][j], v[i][j-1])
m = R(j,j-1,theta,n)
v = numpy.matmul(v, m)
M = num... |
def loadNearestMap():
print("Load nearest bike routes file")
obj = {}
with open(NEAREST_MAP_FILE, "r") as file:
csv_reader = reader(file)
next(csv_reader, None)
for restaurantUid, nearestBikeRouteUid in csv_reader:
obj[int(restaurantUid)] = nearestBikeRouteUid
return ... | The main task of the code is to load restaurant, bike route, and nearest map data from JSON files, clear the READY_FILE, and insert the data into a database using dedicated insertion functions. This prepares the data for subsequent processing or analysis. | def main():
restaurants = loadJson(RESTAURANTS_FILE)
bikeRoutes = loadJson(BIKE_ROUTES_FILE)
nearestMap = loadNearestMap()
writeFile(READY_FILE, "")
insertRestaurants(restaurants)
insertBikeRoutes(bikeRoutes)
insertNearestMap(nearestMap) |
def _get_labels(self, user_id=1):
return [
label[0]
for label in self._session.query(MachineLearningLabels.label_id)
.filter(MachineLearningLabels.user_id == user_id)
.all()
]
def load_models(self, user_id=1):
label_obj_lst = (
self._se... | The main task of the code is to either load pre-trained models or train new ones based on label changes. It identifies label columns in the input DataFrame, checks if existing models for the user match the current labels, and returns loaded models if unchanged. If labels differ or recalculation is forced, it trains new... | def get_models(
self,
df,
user_id=1,
n_estimators=100,
max_features=400,
random_state=42,
bootstrap=True,
recalculate=False,
):
labels_to_learn = [c for c in df.columns.values if "labels_Label_" in c]
label_name_lst = [to_learn.split("l... |
def to_csv(fType, fName):
print(f'Creating csv file in {filepath}')
df.sample(10).to_csv(filepath + fName + '.' + fType, index=False)
print(f'file available at {filepath}{fName}.{fType}')
def to_txt(fType,fName):
print(f"Creating txt file in {filepath}")
gen_csv() if not os.path.isfile(csvFile) else... | The main task of the code is to process command-line arguments to generate output files in CSV, TXT, or JSON formats. It uses sys.argv to determine the file type and name, then calls corresponding functions (to_csv, to_txt, to_json) based on the specified format. If an invalid file type is provided, it prints an error ... | def process():
"""
program uses sys.argv with try except block for producing output in csv, txt, json file format
"""
fType = sys.argv[1]
fName = sys.argv[2]
if fType == 'csv':
to_csv(fType, fName)
elif fType == 'txt':
to_txt(fType, fName)
elif fType == 'json':
to... |
def get_ind(seq):
# helper function to get the index corresponding to sequence seq
return int(seq, 2)
def prod_creator(start, stop):
# returns a function that calculates one of the factors in the f_k
return lambda seq, pi, memo: pi_seg(start, stop, seq[start:stop], pi, len(seq), memo=memo)
def f_creator... | The code generates an array by calculating combinatorial sums of products for each element in `all_k`. For each element, it computes possible recombination locations, adjusts them with boundary values, calculates products between consecutive locations using `prod_creator`, applies `f_creator` to each product, and sums ... | def make_f_array_2(all_k):
arr = []
num_locations = get_ind(all_k[-1])
for i in all_k:
num_recombinations = num_locations - get_ind(i)
possible_recombination_locations = list(combinations(range(1, num_locations + 1), num_recombinations))
to_sum = []
for r in possible_recombi... |
def load_weights():
network.load_weights(args.from_checkpoint)
print('Loaded previously trained model checkpoint')
def writeSettings():
f = open(results_path + '/settings.txt', 'w')
f.write('x: ' + str(args.x) + "\n")
f.write('y: ' + str(args.y) + "\n")
f.write('run-id: ' + str(args.run_id) + "\... | The main task of the code is to train a reinforcement learning model by iterating through episodes, updating the running reward, logging metrics (episode reward, running reward, total moves) with TensorFlow summaries, saving model checkpoints periodically, and finally storing the trained model. It uses a progress bar f... | def main():
if args.from_checkpoint:
load_weights()
writeSettings()
running_reward = 0
with writer.as_default():
with tqdm.trange(n_iterations) as t:
for iteration in t:
initial_state = tf.constant(env.reset(), dtype=tf.float32)
episode_rewar... |
def _get_current_tle_file(self, url: str, force_fetch=False):
tle_path = self._get_tle_path_from_url(url)
tle_path_exists = os.path.exists(tle_path)
if not force_fetch and tle_path_exists and not self._is_out_of_date(tle_path):
logging.info("%s is up-to-date, skipping download.", tle... | The main task of the code is to download and parse TLE (Two-Line Element) orbital data from predefined URLs. The `refresh_urls` method iterates through a list of URLs, forces a download if specified, retrieves TLE files, and parses them into structured data. This ensures up-to-date satellite tracking information is mai... | def refresh_urls(self, force_fetch = False):
"""Downloads all defined TLE information from TLE_SOURCES and other defined sources."""
urls = self.urls
for url in urls:
self._get_current_tle_file(url, force_fetch=force_fetch)
self.parse_tlebulk(self._get_tle_path_from_url(... |
def init_glove_vectors():
#!wget http://nlp.stanford.edu/data/glove.6B.zip
#!unzip glove.6B.zip
#!ls -lrt
return
def context(oe):
import pandas as pd
import numpy as np
import re
import nltk
from nltk.tokenize import word_tokenize
from nltk.corpus import stopwords
#from google.colab import files
... | The code performs concept extraction from input 'oe' by initializing GloVe vectors, extracting context words, retrieving concept results, and finalizing output. It processes 'oe' to identify context and key concepts, then combines them into a structured result. | def concept_extraction(oe):
init_glove_vectors()
context_words = context(oe)
temp = conceptio_results(oe)
concept_words = temp[0]
result = temp[1]
final(oe, context_words, concept_words, result) |
def install_pillow_dependencies(interactive, drymode=False):
"""Install Pillow dependencies. Returns stderr, stdout.
"""
conf = get_gnu_linux_distro_conf()
distro = conf.get("name")
distro_version = conf.get("version")
pkg_cmd = conf.get('pkg-cmd')['interactive'] if interactive else \
c... | The main task of the code is to install the Pillow library by first installing its dependencies (including OpenJPEG2) and then using pip to install Pillow itself. The function supports dry-run mode for simulation, printing required commands without executing them, and handles interactive installation if needed. It also... | def install_pillow(interactive, drymode=False):
"""Install Pillow dependencies, then install Pillow."""
if drymode:
print('Run the following command as root to install needed dependencies:')
install_pillow_dependencies(interactive, drymode)
if drymode:
print('To have jpeg support, run as... |
def _create_cells(self):
for c in range(self._columns):
cols = []
for r in range(self._rows):
cols.append(Cell(self._win))
self._cells.append(cols)
for c in range(self._columns):
for r in range(self._rows):
self._draw_cell(... | This code initializes a maze generator by setting up a grid of cells with specified dimensions and positions. It configures randomization using a seed, creates the cell structure, defines entrance/exit points, generates maze pathways via wall-breaking recursion, and resets visited status for traversal algorithms. The c... | def __init__(
self,
x1,
y1,
rows,
columns,
cell_size_x,
cell_size_y,
win=None,
seed=None
):
self._cells = []
self._x1 = x1
self._y1 = y1
self._rows = rows
self._col... |
def setup_hooks(self):
"""
Function to set up hooks from the .ui file into this class.
"""
# Tube count
self.tube_count_label = self.findChild(QtWidgets.QLabel, 'tube_count_label')
self.tube_count_line = self.findChild(QtWidgets.QLineEdit, 'tube_count_line')
# Fl... | The code initializes a MainWindow GUI, loading a UI file, setting up attributes, connecting hooks/validators, configuring UI elements, and displaying a port selection popup for Arduino integration, preparing the interface for user interaction with specified units for volume and time. | def __init__(self, testing=False):
super(MainWindow, self).__init__()
uic.loadUi(UI_PATH, self)
self.testing = testing
self.colosseum = None
self.monitor_thread = None
self.setup_hooks()
self.setup_validators()
self.setup_params_table()
self.setu... |
def optimize_measured_mutual_info(
prep_node,
meas_wires=None,
dev_kwargs={},
qnode_kwargs={},
**opt_kwargs,
):
"""Optimizes the network's arbitrary qubit measurements to minimize the :meth:`qnetti.measured_mutual_info_cost_fn`.
See the :meth:`qnetti.optimize` method for details regarding th... | The function computes the qubit characteristic matrix for a multi-qubit quantum state, combining von Neumann entropy (diagonal entries) and mutual information (off-diagonal entries) via optimization. It uses `optimize_vn_entropy` and `optimize_mutual_info` to determine optimal measurement settings, returning the matrix... | def optimize_characteristic_matrix(
prep_node,
use_measured_mutual_info=False,
meas_wires=None,
dev_kwargs={},
qnode_kwargs={},
mi_opt_kwargs={},
vn_opt_kwargs={},
):
"""Obtains the qubit characteristic matrix for a given multi-qubit state preparation.
Mathematically, the qubit char... |
def hasZeroes(x,y):
#this function handles if a zero is passed as a or b
if x == 0 and y == 0:
print('undefined')
return True
if x == 0:
a = y//abs(y)
print("%s = 0 + %s*%s" % (a*y,a,y))
return True
elif y == 0:
a = x//abs(x)
print("%s = 0 + %s*%s" % (a*x,a,x))
return True
return False
def areEqual... | The code computes the greatest common divisor (GCD) of two integers x and y as a linear combination of x and y using the extended Euclidean algorithm. It calculates coefficients m and n such that GCD(x, y) = m*x + n*y, handles negative values, and prints the resulting equation. The function also checks for edge cases l... | def printCombination(x,y):
#prints the linear combination and computes the gcd from m and n values
#m and n are calculated for abs value of both x and y
print("\nGreatest Common Divisor as a Linear Combination:\n", end = '\t')
#first check if x or y == 0
if hasZeroes(x,y):
return
#check if x == y
if areEqual(... |
def get_patient_count(time_series_dir):
return sum(1 for entry in os.scandir(time_series_dir) if entry.is_file())
def calc_missing_rates(stats, duration, patient_count):
missing_rates = {
'patient_level_per_itemid': {key: 0 for key in ITEMIDS},
'record_level_per_itemid': {key: 0 for key in ITEMI... | The main task of the code is to calculate and save missing rate statistics for medical time-series data across different durations. It processes CSV files in parallel, aggregates ITEMID occurrence counts at patient and record levels, computes missing rates, and saves results to CSV. In "run" mode, it handles all files ... | def main():
mode = "run"
for duration in constants.DURATIONS:
time_series_dir = TIME_SERIES_DIR_TEMPLATE.format(duration)
patient_count = get_patient_count(time_series_dir)
if mode == "run":
stats = {
# v: The number of occurrences of ITEMID in all csv
... |
def conv2d_fixed_padding(inputs, filters, kernel_size, data_format, strides=1):
"""Strided 2-D convolution with explicit padding."""
if strides > 1:
inputs = fixed_padding(inputs, kernel_size, data_format)
return tf.keras.layers.Conv2D(
filters=filters, kernel_size=kernel_size,
stri... | The code constructs the Darknet53 feature extractor, applying convolutional layers, batch normalization, and leaky ReLU activation. It sequentially processes inputs through residual blocks with increasing filters, downsampling via strides, and returns three feature maps (route1, route2, inputs) for multi-scale object d... | def darknet53(inputs, training, data_format):
"""Creates Darknet53 model for feature extraction."""
inputs = conv2d_fixed_padding(inputs, filters=32, kernel_size=3,
data_format=data_format)
inputs = batch_norm(inputs, training=training, data_format=data_format)
inputs =... |
def darknet53(inputs, training, data_format):
"""Creates Darknet53 model for feature extraction."""
inputs = conv2d_fixed_padding(inputs, filters=32, kernel_size=3,
data_format=data_format)
inputs = batch_norm(inputs, training=training, data_format=data_format)
inputs =... | The main task of the code is to process a batch of input images through a YOLOv3 model to detect objects, generating bounding boxes for each image. It normalizes inputs, applies Darknet-53 for feature extraction, constructs detection layers with different anchor scales, concatenates outputs, and performs non-max suppre... | def __call__(self, inputs, training):
"""Add operations to detect boxes for a batch of input images.
Args:
inputs: A Tensor representing a batch of input images.
training: A boolean, whether to use in training or inference mode.
Returns:
A list containing cl... |
def mdp_to_value_model(mdp):
pi_, optimal_value_function = emdp.algorithms.tabular.solve_mdp(mdp)
import pdb;pdb.set_trace()
return make_value_model(optimal_value_function)
def make_option_model(option_reward_vector, option_transition_model) -> onp.ndarray:
num_states = option_reward_vector.shape[0]
... | This code defines and optimizes multiple options in a Markov Decision Process (MDP) using subgoal-based value functions. It initializes a custom MDP with three options, modifies reward structures for each option, computes subgoal-specific value models, derives option policies and termination conditions, constructs tran... | def main():
mdp = emdp.chainworld.toy_mdps.dadashi_fig2d()
num_options = 3
mdp.rs = onp.zeros((num_options, *mdp.reward.shape))
mdp.rs[0, 0, 0] = 1
mdp.rs[1, 0, 1] = 1
mdp.rs[2, 1, 0] = 1
mdp_value_fn = mdp_to_value_model(mdp)
option_policies = []
option_terminations = []
... |
def random_region_name():
return random_name()
def random_city_name():
return ''.join(
[
random_c1().capitalize(),
random_v1(),
random_c1(),
random_v1(),
'-',
random.choice(['ulu', 'uk', 'aruk', 'ayuk'])
]
)
def random_c... | The function generates fictional subregion details based on the specified type. It creates names for 'geo' regions using adjectives and geographic terms, or for 'provinces', 'cities', and 'houses' using standardized formats. It also generates a champion's name and title, then returns a dictionary with the subregion's n... | def create_subregion(region_name, type_):
if type_ == 'geo':
adj = random.choice([
"Grey", "Terrible", "Unending", "Sprawling",
"Madness-inducing", "Vast", "Misty", "Dank", "Blasted",
"Inhospitable", "Barren", "Bleak", "Desolate", "Hostile",
"Stark", "Windswep... |
def find_region(region_name):
return [v for v in REGIONS if v['name'] == region_name][0]
def contained_regions(region_name):
return [v for v in REGIONS if v['parent'] == region_name]
def join_and(segs):
if len(segs) == 0:
return 'something'
if len(segs) == 1:
return segs[0]
return ',... | The code generates a recursive, structured verse asserting the supremacy of a region's champion, incorporating subregions and a chain of prior champions. It constructs a persuasive narrative by recursively processing subregions, appending formatted assertions about each champion's might, and chaining historical victori... | def verse(region_name, chain):
queue = []
region = find_region(region_name)
intro = random.choice(["Yea, and let", "And let"]) if chain else "Let"
x = ''
x += "{} it not be doubted that {} {} the mightiest of all in {}.\n\n".format(
intro, region['champion'], region['tense'], region_name
... |
def check_metric_fields_length(metric):
if len(metric["fields"]) > 1:
logging.error(
"Metric has more than one field. Run FieldExpander before Formatter",
extra={"metric": metric},
)
raise ValueError(
"Metric has more than one field. Run FieldExpander befo... | This function processes a list of metrics by applying specified formats. It checks each metric's fields, converts the field value to a float or string based on the format, defaults to string if unspecified, and merges tags from the format into the metric. Metrics without a matching format are logged and skipped. The mo... | def format_metrics(self, metrics, formats):
for metric in metrics:
check_metric_fields_length(metric)
metric_id = get_metric_id(metric)
format = build_metric_format(
formats, self.formats_compiled, metric_id, combine=self.combine_formats
)
... |
def check_metric_fields_length(metric):
if len(metric["fields"]) > 1:
logging.error(
"Metric has more than one field. Run FieldExpander before Formatter",
extra={"metric": metric},
)
raise ValueError(
"Metric has more than one field. Run FieldExpander befo... | This function filters metrics by removing outliers based on predefined boundaries. It checks each metric's field value against min/max thresholds, skips metrics with missing boundaries or string values, logs removed outliers, and returns the filtered list of valid metrics. | def remove_outliers(self, metrics, boundaries):
metrics_filtered = []
metrics_removed = []
for metric in metrics:
check_metric_fields_length(metric)
metric_id = get_metric_id(metric)
metric_boundaries = build_metric_format(
formats=boundaries,
... |
def refresh_config(self):
if self._external_config:
self.config = self._load_config(PIPELINE_CONFIG_DEFAULT)
def remove_none(self, metrics):
# Remove all None values from metrics
number_metrics_initial = len(metrics)
metrics = [metric for metric in metrics if metric is not No... | The code processes a list of metrics by filtering out None values, executing a processing method if metrics exist, and logging processing time and count metrics. It returns processed results or None if no valid metrics are present. | def process(self, metrics):
start_time = time.perf_counter()
number_of_metrics = len(metrics)
self.refresh_config()
metrics = self.remove_none(metrics)
if metrics:
results = self.process_method(metrics)
else:
logger.info(
f"No met... |
def load_yaml_file(filepath):
with open(filepath, "r") as file:
return yaml.safe_load(file)
def precompile_regex_keys(formats):
return {key: re.compile(key) for key in formats.keys()}
def format_metrics(self, metrics, formats):
for metric in metrics:
check_metric_fields_length(metric... | The method processes input metrics by loading and compiling format configurations from a YAML file, applying formatting rules to the metrics, and returning the processed result. It precompiles regex patterns for efficiency, uses a 'combine_formats' flag if specified, and ensures metrics are structured according to the ... | def process_method(self, metrics):
formats = load_yaml_file(self.config["formats_filepath"])
self.formats_compiled = precompile_regex_keys(formats)
self.combine_formats = self.config.get("combine_formats", False)
metrics = self.format_metrics(metrics, formats)
return metrics |
def load_yaml_file(filepath):
with open(filepath, "r") as file:
return yaml.safe_load(file)
def precompile_regex_keys(formats):
return {key: re.compile(key) for key in formats.keys()}
def remove_outliers(self, metrics, boundaries):
metrics_filtered = []
metrics_removed = []
for m... | The code processes input metrics by loading boundary configurations from a YAML file, compiling regex patterns from these boundaries, removing outliers in the metrics based on the boundaries, and returning the cleaned metrics. | def process_method(self, metrics):
boundaries = load_yaml_file(self.config["boundaries_filepath"])
self.boundaries_compiled = precompile_regex_keys(boundaries)
metrics = self.remove_outliers(metrics, boundaries)
return metrics |
def _compute_hull(self, points: list[QPointF], side: Side) -> HullNode:
"""
Returns a node in a linked list which represents a convex hull.
The node returned by this function is the furthest node on the opposite side of the hull that is
being calculated (i.e. if this is a left hull, the ... | This code computes the convex hull of a set of 2D points using a divide-and-conquer algorithm. It sorts points by x-coordinate, constructs the hull via recursive subdivision, and traverses nodes clockwise to form a polygon. The result is visualized as red lines on a view, with elapsed computation time displayed. Key st... | def compute_hull(self, points: list[QPointF], pause, view):
self.pause = pause
self.view = view
assert type(points) == list and type(points[0]) == QPointF
t1 = time.time()
points_by_x = sorted(points, key=lambda point: point.x())
t2 = time.time()
t3 = time.tim... |
def _plot_profile(self) -> None:
""" Plots profile of an observable.
Returns:
None.
"""
full_simulation_profile = self._full_simulation.calc_profile()
ml_simulation_profile = self._ml_simulation.calc_profile()
if self._profile_type == ProfileType.LONGITUDINA... | The main task of the code is to generate and save plots for a profile (either longitudinal or lateral) and its first and second moments. It determines the profile type, prints progress updates, and sequentially calls private methods to plot the base profile and its moments, ensuring appropriate visualizations are creat... | def plot_and_save(self) -> None:
""" Main plotting function.
Calls private methods and prints the information about progress.
Returns:
None.
"""
if self._profile_type == ProfileType.LONGITUDINAL:
profile_type_name = "longitudinal"
else:
... |
def _manufacture_callbacks(self) -> List[Callback]:
"""
Based on parameters set by the user, manufacture callbacks required for training.
Returns:
A list of `Callback` objects.
"""
callbacks = []
# If the early stopping flag is on then stop the training when... | This method trains and validates a model using either K-fold cross-validation (if specified) or a single training run with a validation split. It processes input data, conditions, and noise to return a list of History objects tracking training/validation metrics across epochs. | def train(self, dataset: np.array, e_cond: np.array, angle_cond: np.array, geo_cond: np.array,
verbose: bool = True) -> List[History]:
"""
For a given input data trains and validates the model.
If the numer of K-fold splits > 1 then it runs K-fold cross validation, otherwise it ru... |
def show_header():
print("""\033[32m""" + """
oo dP oo
88
88d8b.d8b. dP .d8888b. 88d888b. .d8888b. .d8888b. .d8888b. 88 dP .d8888b. """ + """\033[33m"... | The main task of the code is to process command-line arguments and execute corresponding actions like 'migrate', 'flush', 'map', or 'help' based on user input. It checks for valid commands, handles folder paths, and triggers specific functions for database operations or assistance, ensuring proper error handling for un... | def main():
if len(sys.argv) > 1:
commands = ['command', 'action', 'folder']
args = dict(zip(commands, sys.argv))
action = args['action']
if 'folder' in args:
folder = args['folder']
else:
folder = None
if action in confi... |
def load_model(filepath, gpu):
checkpoint = torch.load(filepath)
weights = get_weights(checkpoint['structure'])
model = getattr(models, checkpoint['structure'])(weights=weights)
model.class_to_idx = checkpoint['class_to_idx']
model.classifier = get_classifier(checkpoint['hidden_layer1'], len(model.c... | The code performs image classification using a pre-trained model. It loads the model from the specified path, maps category IDs to names, and uses the `view_classify` function to predict and display the top `topk` categories for the input image, leveraging GPU acceleration if enabled. | def predict(image_path, model_path, topk, category_names, gpu):
model, _ = load_model(model_path, gpu)
cat_to_name = get_cat_to_name(category_names)
view_classify(image_path, model, cat_to_name, gpu, topk) |
def initialisation():
pygame.init()
global LETTER_SIZE,NUM_LETTERS,MYFONT_GRID,MYFONT_WORDS,MYFONT_OUT,WIDTH,HEIGHT,GRID_WIDTH,GRID_HEIGHT,TIME_FONT,SCORE_FONT
LETTER_SIZE=40
NUM_LETTERS=15
MYFONT_GRID=pygame.font.SysFont('comicsansms',LETTER_SIZE-10)
MYFONT_WORDS=pygame.font.SysFont('comicsans... | The main task of the code is to implement a word search game using Pygame. Players find hidden words on a grid by clicking letters, with real-time scoring and time tracking. Upon completing all 10 words, a victory screen displays the score and offers options to restart or exit. The game handles grid rendering, user int... | def main():
pygame.init()
previous_game_time=pygame.time.get_ticks()//1000
initialisation()
print(pos_words)
Game_Over=False
count=0
i=0
completed_words=[]
while not Game_Over:
pygame.time.Clock().tick(10)
time=display_time(previous_game_time)
score=calculate_... |
def time_wrapper(path_in):
"""
Returns results: a list containing [min cost, str1, str2, time taken]
Parameter path_in: input file
Precondition: the input file is exist and valid
"""
start_time = time.time()
results = run_algorithm(path_in) # call algorithm
end_time = time.time()
t... | The code's main task is to execute an algorithm, measure its execution time and memory usage, and output results. It reads command-line arguments, runs the algorithm via `time_wrapper`, appends memory usage data, and writes results to a specified output. The process involves timing, resource monitoring, and result logg... | def main():
"""
Program Entry Point
Read sys commands -> start timer and algorithm -> append memory -> output results
"""
args = sys.argv[1:] # read commands
results = time_wrapper(args[0])
results.append(str(process_memory())) # [min cost, str1, str2, time taken, memory used]
output... |
def get_db_matches(directory, db_file):
matches = []
with open(db_file, "r") as file:
for line in file.readlines():
line = line.strip()
if line == "":
continue
tmp = shlex.split(line)
try:
dir_in = tmp[0]
sho... | The function `do_nav` navigates a file system by matching input characters (`chars`) against database entries and folder contents. It prioritizes exact matches from a main database, then a local database, and finally returns folder items starting with the given characters, enabling efficient directory navigation based ... | def do_nav(chars, pwd):
db_matches = get_db_matches(pwd, DB_FILE)
folder_db_matches = get_folder_db_matches(pwd)
folder_items = list_folder(pwd)
# for debug
#print("pwd:", pwd)
#print("chars:", chars)
# first check if the char matches in what is in the main db
# immediatly cd (return l... |
def get_db_matches(directory, db_file):
matches = []
with open(db_file, "r") as file:
for line in file.readlines():
line = line.strip()
if line == "":
continue
tmp = shlex.split(line)
try:
dir_in = tmp[0]
sho... | The main task of the code is to handle two operational modes: in "lf" mode, it manipulates process groups, file descriptors, and stdin/stdout redirection to interact with a program (likely "lf" file browser), capturing input and executing commands; in the default mode, it retrieves and prints database/folder match data... | def main():
pwd = Path(os.getcwd())
db_matches = get_db_matches(pwd, DB_FILE)
folder_db_matches = get_folder_db_matches(pwd)
folder_matches = get_folder_matches(pwd)
parser = argparse.ArgumentParser()
parser.add_argument('-m', '--mode', help='mode of the program', type=str)
args = parser.pa... |
def get_pwd():
with open("/etc/machine-id", "r") as f:
pwd = f.read()
for i in range(0, 7):
my_string_bits = pwd.encode('utf-8')
secret_thing = hashlib.sha256(my_string_bits)
pwd = secret_thing.hexdigest()
pwd = pwd[0:32]
pwd_bytes =pwd.encode('ascii')
pwd_base64_b... | The main task of the code is to adjust time allocation by subtracting a requested duration from the remaining time ("yt_time_left") and updating the current time ("yt_time_current"), while validating that the requested time does not exceed the available time. It then immediately triggers a guard command to apply the ch... | def cmd_request():
pwd = get_pwd()
state = read_state(pwd)
time_to_request = int(sys.argv[2])
if time_to_request > state["yt_time_left"]:
print("Trying to request more time, than is left")
exit(1)
state["yt_time_left"] -= time_to_request
state["yt_time_current"] = time_to_req... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.