dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def initialize_board(): board = [[EMPTY] * N for _ in range(N)] board[2][2] = BLACK board[2][3] = WHITE board[3][2] = WHITE board[3][3] = BLACK return board def print_board(board): print(" 0 1 2 3 4 5 ") for i in range(N): row = str(i) + " " for j in range(N): ...
The main task of the code is to implement a game of Othello where a human player competes against an AI using the Minimax algorithm. The human inputs moves, while the AI calculates optimal moves via Minimax. The game alternates turns, validates moves, and ends when no legal moves remain, displaying the winner or tie ba...
def play_othello_vs_AI(): board = initialize_board() current_player = BLACK while True: print_board(board) print("Actual player:", "X" if current_player == BLACK else "O") if current_player == WHITE: row, col = get_min_max_move(board, current_player) ...
def draw_text(self, text, size, fillcolor, x, y, align="n", font_name=None, ): font = pg.font.Font(font_name, size) text_surface = font.render(text, True, fillcolor) text_rect = text_surface.get_rect() if align == "nw": text_rect.topleft = (x, y) elif align == "ne": ...
This method renders the game's visual elements by drawing the background, map, sprites (excluding obstacles and bullets), player usernames, debug info, overlays, and bullets using a camera system. It updates the display with pygame's flip method to reflect all rendered components in real-time.
def game_draw(self): # background self.screen.fill((255, 255, 255)) # map image self.screen.blit(self.map.image, self.camera.apply_rect(self.map.rect)) # all sprites except players and walls (players drawn after and walls don't have an image) for sprite in self.all_spri...
def sample_prime(bitsize): lower = 1 << (bitsize-1) upper = 1 << (bitsize) while True: candidate = random.randrange(lower, upper) if is_prime(candidate): return candidate def is_prime(num): if (num < 2): return False for prime in SMALL_PRIMES: if num == prime: ret...
The function generates a prime number $ q $ of the form $ q = k_1 \times k_2 \times \text{order\_divisor} + 1 $, where $ k_1 $ is a prime with at least `min_bitsize` bits, and $ k_2 $ ranges from 0 to 127. It returns $ q $ along with the prime factors of $ k_1 $, $ k_2 $, and `order_divisor` to track the components use...
def find_prime(min_bitsize, order_divisor): while True: k1 = sample_prime(min_bitsize) for k2 in range(128): q = k1 * k2 * order_divisor + 1 if is_prime(q): order_prime_factors = [k1] order_prime_factors += prime_factor(k2) ord...
def sample_prime(bitsize): lower = 1 << (bitsize-1) upper = 1 << (bitsize) while True: candidate = random.randrange(lower, upper) if is_prime(candidate): return candidate def is_prime(num): if (num < 2): return False for prime in SMALL_PRIMES: if num == prime: ret...
The code finds a prime number `q` of the form `q = k1 * k2 * order_divisor + 1`, where `k1` is a prime with at least `min_bitsize` bits, and `k2` is an integer between 0 and 127. It returns `q` along with its prime factors derived from `k1`, `k2`, and `order_divisor`, likely for cryptographic key generation requiring s...
def find_prime(min_bitsize, order_divisor): while True: k1 = sample_prime(min_bitsize) for k2 in range(128): q = k1 * k2 * order_divisor + 1 if is_prime(q): order_prime_factors = [k1] order_prime_factors += prime_factor(k2) ord...
def is_power_of(x, base): p = 1 while p < x: p = p * base return p == x def find_prime_field(min_bitsize, order_divisor): q, order_prime_factors = find_prime(min_bitsize, order_divisor) g = find_generator(q, order_prime_factors) return q, g def is_prime(num): if (num < 2): return Fal...
The code generates parameters for a finite field with specified subgroup orders. It ensures the field size (q) meets a minimum bit-size requirement and that the subgroup orders (order2, order3) divide q-1. It returns the prime field size (q) and two roots of unity (omega2, omega3) corresponding to subgroups of orders o...
def generate_parameters(min_bitsize, order2, order3): assert(is_power_of(order2, 2)) assert(is_power_of(order3, 3)) order_divisor = order2 * order3 q, g = find_prime_field(min_bitsize, order_divisor) assert(is_prime(q)) order = q - 1 assert(order % order2 == 0) assert(order % o...
def is_power_of(x, base): p = 1 while p < x: p = p * base return p == x def find_prime_field(min_bitsize, order_divisor): q, order_prime_factors = find_prime(min_bitsize, order_divisor) g = find_generator(q, order_prime_factors) return q, g def is_prime(num): if (num < 2): return Fal...
The function generates cryptographic parameters for a finite field, ensuring order2 is a power of 2 and order3 is a power of 3. It computes a prime field size q, a primitive root g, and roots of unity ω2 and ω3 with orders dividing q-1, returning q, ω2, and ω3 for group-theoretic or cryptographic applications.
def generate_parameters(min_bitsize, order2, order3): assert(is_power_of(order2, 2)) assert(is_power_of(order3, 3)) order_divisor = order2 * order3 q, g = find_prime_field(min_bitsize, order_divisor) assert(is_prime(q)) order = q - 1 assert(order % order2 == 0) assert(order % o...
def minus(): global down down += 1 def what(): mchobby = input("""what do you do/what are you? [a] builder, [b] pvp, [c] redstone user, [d] none of the above \n """) if mchobby == "a": save_data["mchobby"] = "builder" plus() mob() elif mchobby == "b":...
The code's main task is to collect user experience input, store it in a dictionary, and trigger subsequent functions. It prompts the user to select their experience level (1/2 years, 3/5 years, or 6+ years), updates the 'exp' key in save_data with the chosen value, and calls either 'minus()', 'plus()', or 'what()' base...
def start(): experience = input("""what is your experience? [a]1/2 years , [b]3/5 years or [c] 6 or more \n """) if experience == "a": save_data["exp"] = "1/2 years" minus() what() elif experience == "b": save_data["exp"] = "3/5 years" plus() what() ...
def save_game(save_data): with open("save.json", "w") as file: json.dump(save_data, file) def forest(): spiderattack = input("SPIDERS ARE CRAWLING TO YOU WHAT IS YOUR ACTION\n[f]ight,[r]un\n") if spiderattack == "fight" or spiderattack =="f": data["path"] = "fight" save_game(data) ...
The code's main task is to let the player choose between two initial paths: entering a forest or a cave. It updates the game data with the selected path, saves progress, prints a confirmation message, and directs execution to the corresponding location function (forest() or cave()) based on user input.
def gamestart(): pathdecide = input("there is a forest on your left and a water cave behind you wich way do you go?\n[l]eft,[b]ehind\n") if pathdecide == "l" or pathdecide =="left": data["path"] = "forest" save_game(data) print("you decide the forest") forest() elif ...
def read_file(file_name="train.txt"): file = open(file_name, "r") input_nodes, hidden_nodes, output_nodes = np.array((file.readline()).split(" ")).astype('int') num_training_ex = int((file.readline())) data_set = file.read().splitlines() data_set = [line.split() for line in data_set] data_set ...
The code defines a neural network model with one hidden layer, trains it using backpropagation on normalized input data, and saves the trained weights. It initializes weights randomly, performs forward propagation to compute initial MSE, updates weights via backpropagation over 1000 epochs, and stores the final weights...
def model(): input_nodes, hidden_nodes, output_nodes, num_training_ex, data_set = read_file() X = data_set[: , :-output_nodes] Y = data_set[: , -output_nodes:] X = normalize(X) #W1 is 2D_matrix of shape (hidden_nodes , input_nodes) #(10,8) W1 = np.random.randn(hidden_nodes , i...
def tournament_selection(population, tourney_size): tourney = random.sample(population, 2) if random.random() < 0.9: return min(tourney, key=lambda chromosome: chromosome.get_solution().total_distance) return max(tourney, key=lambda chromosome: chromosome.get_solution().total_distance) def recombina...
The main task of the code is to generate a new population for the next generation using a genetic algorithm. It preserves elites from the current population, selects parents via tournament selection, recombines them with optional mutation, fills the new population with offspring, sorts it, and returns the updated popul...
def genetic_algorithm(population, next_gen_size): new_pop = [] #inserting elites for i in range(next_gen_size//100): new_pop.append(population[i]) #filling in with children mutate = False if random.random() <= 0.2: mutate = True while len(new_pop) < next_gen_size: p1 ...
def get_problem_set(filename): with open(filename, 'r') as f: dataset = [line.split() for line in f] m, n, t = tuple([int(i) for i in dataset[0]]) #depot list D = [] for i in range(t): d = [i] + [float(j) for j in dataset[1+t+n+i][1:3]] + [float(j) for j in dataset[1+i]] + [m] ...
The code executes a genetic algorithm to solve a problem (p23) by initializing a population of 100 individuals, evolving it over 10 generations through selection, crossover, and mutation, then outputting the best solution's details and visualizing it.
def main(): C, D = get_problem_set(p23) population = initial_population(C, D, 100) sort_pop(population) for i in range(10): population = genetic_algorithm(population, 100) print('Gen ', i+1) pop_info(population) print('-----------------') population[0].get_solution()....
def vad_samples( _logger: loguru.Logger, chunks: Generator[npt.NDArray[np.float32], Any, None], chunk_size: int, max_size: int, start: int, blanks: mp.Queue | None ) -> Generator[Tuple[int, np.ndarray[Any, np.dtype[np.float32]]], None, None]: """ Skip samples until VAD activates, then cache them ...
The function `run_transx` transcribes audio chunks using a Whisper model, processes speech segments by joining similar results and filtering unwanted phrases, then formats and outputs transcriptions (e.g., VTT/MPV) to a queue. It handles voice activity detection, real-time transcription, and logging, stopping when sign...
def run_transx( transx_config: TransXConfig, whisper_config: WhisperConfig, start_int: int, model: WhisperModel, gigo_phrases: List[str], chunk_gen: Generator[npt.NDArray[np.float32], None, None] ): _logger = transx_config['_logger'] _format = transx_config['format'] stop = transx_conf...
def transx_prep( _logger: loguru.Logger, whisper_config: WhisperConfig ): gigo_phrases = [] with open('gigo_phrases.txt', 'r') as f: gigo_phrases = list(map(lambda x: x.strip().translate(str.maketrans('', '', string.punctuation)).casefold(), f.read().splitlines())) _logger.info('Loading Whisper mo...
This function processes an audio stream from a URL by converting it to PCM format via FFmpeg, transcribing and translating it using Whisper and TransX models, handling synchronization with a pipe, and managing process cleanup. It initializes required processes, aligns timestamps for live streams, generates audio chunks...
def transx_from_audio_stream( transx_config: TransXConfig, whisper_config: WhisperConfig, sync_pipe: _ConnectionBase | None, ): """ Get a stdout stream from ffmpeg based on the provided url and generated translations from it as fast as possible. """ _logger = transx_config['_logger'] close...
def irt(data, val_data, lr, iterations): """ Train IRT model. You may optionally replace the function arguments to receive a matrix. :param data: A dictionary {user_id: list, question_id: list, is_correct: list} :param val_data: A dictionary {user_id: list, question_id: list, is_correct: list}...
The main task of the code is to train an Item Response Theory (IRT) model using provided datasets, evaluate its performance on validation and test sets, and visualize results. It loads training, validation, and test data, sets a learning rate and iterations, trains the model, plots negative log-likelihood curves for tr...
def main(): train_data = load_train_csv("../data") val_data = load_valid_csv("../data") test_data = load_public_test_csv("../data") ##################################################################### # Tune learning rate and number of iterations. With the implemented # # code, report the vali...
def get_pawn_moves(self, r, c): pawn_moves = [] if self.white_to_move: # moving white pawn # just pawn move if self.board[r - 1, c] == ".": if r == 1: # promotion for p in self.friend_pieces[1:-1]: pawn_moves.append(...
The function `get_possible_moves` iterates through an 8x8 chessboard to collect all potential moves for the player's pieces. For each piece (excluding '.' and foe pieces), it identifies the type (pawn, bishop, knight, rook, queen, king) and calls corresponding helper methods to generate possible moves. These moves are ...
def get_possible_moves(self): # moves returned may be invalid all_possible_moves = [] for i in range(8): for j in range(8): current_piece = self.board[i, j] if current_piece == "." or current_piece in self.foe_pieces: continue ...
def generateTxt(db): print("Generating a txt file based on the inputted Schema...") command = 'docker exec -it schemacrawler sh -c "/generateParsableTxt.sh ' + db + '"' try: subprocess.check_call(command, stderr=subprocess.DEVNULL, stdout=subprocess.DEVNULL) except: print("dataAtlas.py...
The function `beginAtlasing` automates mapping database schemas by generating a text file from input schemas (using SchemaCrawler), parsing tables/keys, mapping relationships, creating a structured database file, and generating a schema diagram. If `db2` is provided, it processes two databases, combines their parsed da...
def beginAtlasing(db, db2): if db2 is None: # Step 1: Generate a txt file based on the inputted schema (without relations) using SchemaCrawler generateTxt(db) # Step 2: Parse the generated txt file to get a list of table names and keys parsedTxt = beginParseTxt(db) # Step 3...
def display_combat_options(num_battles_displayed, gui=False): '''A function which displays 'num_battles_displayed' most recent combats and asks the user to make a selection. Parameters ---------- num_battles_displayed : int The number of most recent combats to be displayed Returns ------- Combat : Combat Obj...
This function resumes a combat scenario by loading a selected combat file, adjusting the combatant order for the next round, and saving the updated combat state back to the file.
def resume_combat(): '''A function to resume a combat from a file ''' selection, selected_file = display_combat_options(3) combat = get_combat_based_on_selection(selection, selected_file) combat = round_order(combat.combatants, combat) write_combat_to_file(combat)
def player_characters(): '''Create list of Character objects to represent the player characters Returns ------- pcs : list list of Character objects ''' pc_list = ['Dennis Le Menace', 'Pierre', 'Ronan', 'Dame Romaine'] pcs = [] for pc in pc_list: # pc_init = int(randint(1,20)) # pc_init = 0 # if pc ==...
The code simulates a combat scenario by reading character data from a file, combining player and non-player characters, sorting them by initiative (descending), resolving ties, determining combat round order, and writing the results to a file.
def test_combat(): f = open('test_combat.txt', 'r') combatants = [] combatants.extend(player_characters()) combatants.extend(nonplayer_characters(f)) combatants.sort(key=lambda x:x.initiative, reverse=True) combatants = tiebreaker(combatants) combat = round_order(combatants, None, f) write_combat_to_file(combat...
def player_characters(): '''Create list of Character objects to represent the player characters Returns ------- pcs : list list of Character objects ''' pc_list = ['Dennis Le Menace', 'Pierre', 'Ronan', 'Dame Romaine'] pcs = [] for pc in pc_list: # pc_init = int(randint(1,20)) # pc_init = 0 # if pc ==...
The code tests a tiebreaker mechanism for combatants by reading characters from a file, combining them with player characters, sorting them by initiative, and applying a tiebreaker function to resolve equal initiative values.
def test_tiebreak(): f = open('test_tiebreak.txt', 'r') combatants = [] combatants.extend(player_characters()) combatants.extend(nonplayer_characters(f)) combatants.sort(key=lambda x:x.initiative, reverse=True) combatants = tiebreaker(combatants) f.close()
def player_characters(): '''Create list of Character objects to represent the player characters Returns ------- pcs : list list of Character objects ''' pc_list = ['Dennis Le Menace', 'Pierre', 'Ronan', 'Dame Romaine'] pcs = [] for pc in pc_list: # pc_init = int(randint(1,20)) # pc_init = 0 # if pc ==...
The main task of the code is to initiate a combat sequence by gathering player and non-player characters, resolving tiebreakers to determine order, establishing round-based combat structure, and persisting the combat setup to a file for later processing or reference.
def start_combat(): '''A function to start a new combat ''' combatants = [] combatants.extend(player_characters()) combatants.extend(nonplayer_characters()) combatants = tiebreaker(combatants) combat = round_order(combatants) write_combat_to_file(combat)
def get_new_or_existing_combat_input(): '''A function to verify a user's input for new or existing combat. Loops until valid input found. Returns ------- n/e: str A string representing the user's selection ''' while True: new_or_existing = input('\nCombat:\n1) [N]ew\n2) [E]xisting\n: ').lower() if new_or_...
The main task of the code is to prompt the user to choose between starting a new combat or resuming a saved combat from a file. Based on the input, it either calls `start_combat()` for a new game or `resume_combat()` to continue an existing session, managing the flow of the application accordingly.
def main(): '''A function to ask the user if they want to start a new combat or continue a saved combat from a file ''' new_or_existing = get_new_or_existing_combat_input() if new_or_existing == 'n': start_combat() else: resume_combat()
def fetchDetails(opType, dict_row): try: if opType == 'node': nodelabel = dict_row['nodelabel'] nodename = dict_row['nodename'] properties = json.loads(dict_row['properties']) timestamp = int(dict_row['timestamp']) return {'nodeLabel': nodelabel, '...
The function processes data in batches by fetching details from each row, categorizing records into create/update/skip lists via bulk operations, and executing node/edge operations based on the opType, logging success/failure counts and handling batched updates/inserts.
def processData(df, batch_size, opType): total_record_count = df.count() record_list = []; searchRecordList = [] cntr = 0 if total_record_count > 0: for row in df.rdd.toLocalIterator(): try: dict_row = row.asDict() if dict_row.get('properties',None) !=...
def preparation(self, simulation_time, output_folder, sequences_file, Metadata_file): ''' Initiate all parameters used in each simulation run Args: simulation_time (int): simulation run ID, e.g., Simulation# 1 output_folder (str): dir to store the simulation outputs sequ...
This code runs a viral rebound simulation for a specified number of repetitions. It initializes viral populations, tracks progeny pool sizes, and stores results in a folder. If rebound fails after all attempts, it logs the failure. If successful, it records viral load tracking data. The simulation uses metadata files a...
def job(self, simulation_time): ''' Run each simulation Args: simulation_time (int): simulation run ID, e.g., Simulation# 1 Returns: The outputs and metadata of this simulation run stored in one separate folder. ''' # create the result folde...
def mutator(input_file, output_file, mutation_rate, rng): seq_lib = read_fasta_file(input_file) seq_names = list(seq_lib.keys()) with open(output_file, "w") as f: for seq_name in seq_names: seq = seq_lib[seq_name][:].seq seq_mut = mutate(seq, mutation_rate, rng) ...
The function simulates viral evolution across generations by applying mutation, recombination (20% of population), fitness calculation, and replication. It processes input sequences, applies mutation/recombination rates, drug pressure, and fitness parameters (e.g., resistance/compensatory mutation effects), then genera...
def each_generation(sequences_file, snv, rec, score_info, ref, treatment, p, r, c, MB_DRM, R, rng): ''' Simulate the viral evolution by generations. In each generation, viral genomes will go through four steps: 1) mutation 2) recombination (20% of the entire population) 3) fitness calculation ...
def stochastic_function(seed): # generate RNG rng = np.random.default_rng(seed) return rng def each_generation(sequences_file, snv, rec, score_info, ref, treatment, p, r, c, MB_DRM, R, rng): ''' Simulate the viral evolution by generations. In each generation, viral genomes will go through four steps...
This function simulates viral population evolution under treatment by iteratively generating progeny sequences across generations. It monitors for viral suppression (population <100 for 3+ generations) or rebound (population growth exceeding 300,000 for 3+ generations). Upon meeting termination criteria, it saves rebou...
def each_repeat(self, Metadata_file, simulation_time, output_folder, sequences_file, p, r, c, MB_DRM, redo_count, switch): # generate a random seed switch = False rng = stochastic_function(self.child_states [self.simulation_time_list.index...
def close_popups() -> None: # Check and close up any possible popup logger.info("Check and close up any possible popup") popups = driver.find_elements(*Search.popup) if popups and popups[-1].is_displayed(): popups[-1].click() def select_category(category: str = '1') -> None: # select categories Select(driver.fi...
The main task of the code is to automate searching for medical support resources on the National Multiple Sclerosis Society's website by navigating to a URL, closing popups, selecting filters like category, support type, distance, and zip code, then executing a search query using a web driver.
def main() -> None: url: str = "https://www.nationalmssociety.org/Resources-Support/Find-Doctors-Resources?" driver.get(url) close_popups() select_category() select_support_type() select_distance() select_zipcode() search()
def separator_check(pl_step_list: list[str], size_string: str) -> tuple[str, str]: """ Checks current input of player step for correct separator. Parameters: ------- pl_step_list (list[str]): List of a strings; size_string (str): String. Returns: ------- Tuple: ...
The function `matrix_save` takes an integer `num` to determine which matrix (first, second, or default) to process. It prompts the user for matrix dimensions, validates separators, ensures numeric values, checks size ranges, and collects matrix elements. It returns validated rows, columns, and the matrix as a tuple. Th...
def matrix_save(num: int) -> tuple[int, int, list[list[int | float]]]: """ Implements user sizes and its matrix input. Parameters: ------- num (int): A decimal integer (key). Returns: ------- Tuple: rows (int): A decimal integer; cols (int): A decimal in...
def delirium_profit_calc(self): return self.fixed_weight_profit_calc(self.delirium_df, ["Delirium Orb"], 10, 20, 30 * self.primal_lifeforce_unit_price) def scarab_profit_calc(self): return self.fixed_weight_profit_calc(self.scarab_df, ["Rusted", "Polished", "Gilded", "Winged"], 10, 20, 30 * self.wild_li...
This function calculates profit information for specified item classes by dispatching to class-specific profit calculation methods (delirium, scarabs, essences), then parsing and returning the formatted output using a shared parsing method.
def profit_calc(self, item_class): if(item_class == "Delirium Orbs"): profit_info = self.delirium_profit_calc() if(item_class == "Scarabs"): profit_info = self.scarab_profit_calc() if(item_class == "Essences"): profit_info = self.essence_profit_calc() ...
def h_heuristic(curr_node, end_node): """Calculates approximate distance between two nodes Used to calculate the distance between two points on a graph, which will be used to determine f values in the A* algorithm :arg curr_node (node object) - current node who's h is being calc...
This code initializes a pathfinding algorithm by creating nodes from coordinate-color pairs, designating start and end points, setting up heuristic and cost values, and executing the A* algorithm to find a path.
def start_algo(lst_coords): global start, end, node_objects_list, all_objs_node, green, blue, open_nodes for pos, color in lst_coords: x = pos[0] y = pos[1] if color == green: node_new = Node(x, y, color, g=0, width=node_w, height=node_h) start = node_new ...
def normalize_image(f_img, channel_selection="all"): channel = 3 channel_selection = channel_selection.lower() if channel_selection == "red": channel = 0 elif channel_selection == "green": channel = 1 elif channel_selection == "blue": channel = 2 img = f_img.copy().astyp...
The function `find_centers` detects and extracts centers of circular patterns from an image, organizing them into a grid structure defined by `nx` (columns) and `ny` (rows). It normalizes and thresholds the input image, identifies ellipses (likely circular features), computes pairwise distances between centers, and ite...
def find_centers(f_img, config): nx, ny = config.pattern_detection.num_points img = normalize_image(f_img, config.circle_detection.channel_selection) img = threshold_image(img, config.circle_detection) ellipses = find_ellipses_direct(img, config.circle_detection, show=config.show_images) ctrs = li...
def _rotate( self, direction: int ) -> bool: """Executes rotation action if possible Args: direction (int): Direction of rotation. -1 left, 1 right. Returns: bool: True if move has been performed, False otherwise. """ new_piec...
This function positions a game piece at a specified horizontal coordinate and rotation, then drops it until collision. It calculates the horizontal movement delta from the current position, applies the given rotation, moves the piece horizontally, and descends it vertically until it can no longer move down.
def perform_action_coords(self, x_pos: int, rotation: int): """Instead of doing individual moves, the agent just chooses a horizontal coordinate and rotation for the piece and drops it. Args: x_pos (int): Horizontal position of the piece. rotation (int): Amount of rotati...
def _move_down(self): return self._move(0) def _leave_piece(self): """The active piece is dropped into the grid, updating its values. """ for i in range(self.active_piece.shape[0]): for j in range(self.active_piece.shape[1]): if self.active_piece[i][j]: ...
The function performs post-decision checks in a game, applying gravity to drop the active piece. If dropping fails, it fuses the piece into the grid, checks for cleared lines, generates a new piece, and updates the score. It returns whether the game continues and the score delta, handling game state transitions and sco...
def post_checks(self, no_gravity: bool = False) -> Tuple[bool, float]: """Post decision checks. Checks for gravity activation. If gravity is activated, the piece is dropped one row. If this move is not possible, the piece is fused into the grid and a new active piece appears, as well as...
def _move_left(self): return self._move(-1) def _move_right(self): return self._move(1) def _rotate_left(self): return self._rotate(-1) def _rotate_right(self): return self._rotate(1)
This method executes a specified game action based on the integer decision parameter. It triggers movement or rotation functions (left/right) when decision is 0-3, otherwise performs no action.
def perform_action(self, decision: int): """Execution of action by game logic. Args: decision (int): Identifier for the action. Possible values: - 0: Move left - 1: Move right - 2: Rotate left (counter-clockwise) - 3: Rotate ri...
def search_events_by_state(state_abbr): #Crawl the events in the state event_text = make_request_using_cache_crawl(state_abbr) event_soup = BeautifulSoup(event_text, 'html.parser') event_rows = event_soup.find_all(class_='event')[:150] month_dict = {'January':'01', 'February':'02', 'March':'03', 'Ap...
The main task of the code is to provide an interactive event search tool that allows users to list events by U.S. state, group them by city or type, view detailed event information, find nearby restaurants and parking, and generate visualizations. It processes commands like 'list', 'more', 'nearby', 'plot', and 'help' ...
def run_event_search(): list_events = [] category_events = [] print('Hi there! Welcome to this event search tool! (Enter "help" to browse commands supported)') command = input('Please enter your command: ') while command != 'exit': command_ls = command.replace('=',' ').split() if co...
def Gblur(size, sig, image): kern = generateGaussian(size, sig, sig) blur = cv2.filter2D(image, -1, kern) return blur def threshold(image, thresh): image[image < thresh] = 0 image[image >= thresh] = 1 return image def nonMax(image, mag): image = Gblur(3, 1, image) low = 50 high = 150...
The code computes oriented edge detection by applying a series of directional filters to a magnitude image, combining results through subtraction and addition, then applying non-max suppression, thresholding, and converting to a binary edge map for image analysis.
def getOrientEdges(mag, filters, image, thresh): mag = Gblur(3, 1, mag) list_mag = [] for i in range(len(filters)): temp = cv2.filter2D(mag, -1, filters[i]) list_mag.append(temp) l = list_mag[0].copy() for j in range(1, len(list_mag)): l = (l - list_mag[j]) + list_mag[j] ...
def Gblur(size, sig, image): kern = generateGaussian(size, sig, sig) blur = cv2.filter2D(image, -1, kern) return blur def getMagTh(grad_x, grad_y): np.seterr(divide='ignore', invalid='ignore') new_x = np.amax(grad_x, axis=2) new_y = np.amax(grad_y, axis=2) img_mag = np.sqrt(np.power(new_x, 2...
This code computes edge detection by calculating gradient magnitudes using custom kernels, combining results with non-max suppression and thresholding to highlight edges in an image.
def getGradientEdges(image, kernel, thresh): y1 = kernel x1 = y1.T y2 = kernel * (-1) x2 = y2.T im_x1 = cv2.filter2D(Gblur(3, 1, image), -1, x1) im_y1 = cv2.filter2D(Gblur(3, 1, image), -1, y1) im_x2 = cv2.filter2D(Gblur(3, 1, image), -1, x2) im_y2 = cv2.filter2D(Gblur(3, 1, image), -1, ...
def update_task( self, status: TaskStatus | None = None, output_file_path: Path | str | None = None, errors: ErrorsDict | None = None, ) -> None: """ Updates the task with the provided parameters. Args: status (TaskStatus | None, optional): The st...
The code's main task is to execute a process by first updating the task status to "IN_PROGRESS," validating the task's integrity, processing the task to generate a result file, and finally marking the task as "COMPLETED" with the output file path. This structured workflow ensures proper task tracking, validation, execu...
def execute(self): self.update_task(status=TaskStatus.IN_PROGRESS) self.validate_task() result_file_path = self.process_task() self.update_task(status=TaskStatus.COMPLETED, output_file_path=result_file_path)
def download_data(fid, destination): print('cleaning already existing files ... ', end='') try: shutil.rmtree(destination) print('√') except: print('✕') print('creating data directory ... ', end='') os.mkdir(destination) print('√') print('downloading dat...
The main task of the code is to download and process 3D medical imaging data, train neural networks on three orthogonal planes (XY, YZ, ZX), evaluate classification performance for each plane, combine predictions through multiplication, and log results. It generates binary images, splits data, trains models with softma...
def main(): # ------- Comment This if already downloaded -------- # destination = os.path.join(BASE_DIR, DATA_DIR) download_data(DATASET_ID, destination) generate_bw_images() X_train_xy, X_test_xy, y_train_xy, y_test_xy = load_data('XY') X_train_yz, X_test_yz, y_train_yz, y_test_yz = load_data...
def get_list_images(dir_name: str, image_path: str, postfix: str) -> list: list_images = [] for root, dirs, files in os.walk(f'{image_path}/{dir_name}'): for dir in dirs: list_images = glob.glob(os.path.join(f'{image_path}/{dir_name}/' + dir, postfix)) return list_images def get_coord(i...
The code processes image-label pairs from specified directories by loading images and labels, extracting coordinates, cropping regions of interest, and saving the processed data and labels into binary files for a dataset.
def set_data(dir_name: str) -> None: image_path = 'data/leftImg8bit' label_path = 'data/gtFine' list_images = get_list_images(dir_name, image_path, '*_leftImg8bit.png') list_labels = get_list_images(dir_name, label_path, '*_gtFine_labelIds.png') for im_path, la_path in zip(list_images, list_labels...
def attack_damage(self): base_damage = ( self.average_dice_damage() + self.attack_stat + self.weapon.magic_bonus() ) if self.attempting_bigger_hit(): return base_damage + 10 else: return base_damage + self.subclass.style_damage(self.weapon) def chance_...
The function calculates the average total attack damage by combining base damage (multiplied by hit chance) and critical strike damage (multiplied by critical chance), summing both components to determine the expected damage output per attack.
def average_attack_damage(self): attack_damage = self.attack_damage() * self.chance_to_hit() critical_damage = self.average_dice_damage() * self.chance_to_critical() return attack_damage + critical_damage
def bonus_to_hit(self): base_bonus = ( self.attack_stat + self.proficiency_bonus + self.weapon.magic_bonus() ) style_bonus = self.subclass.style_bonus(self.weapon) ability_modifier = -5 if self.attempting_bigger_hit() else 0 return base_bonus + style_bonus + ability_m...
This function calculates the damage dealt by a secondary weapon, considering factors like weapon type, bonuses, hit chance, and critical hits. It checks for specific conditions such as the presence of a shadow blade or dual-wielding status, then computes damage using hit chance and critical strike multipliers, returnin...
def second_weapon_damage(self): if self.subclass.shadow_blade: bonus_to_hit = self.bonus_to_hit() + self.bonus_weapon.magic_bonus() hit_chance = chance_to_hit( bonus_to_hit, self.enemy_armour_class, self.advantage ) else: hit_chance = self....
def second_weapon_damage(self): if self.subclass.shadow_blade: bonus_to_hit = self.bonus_to_hit() + self.bonus_weapon.magic_bonus() hit_chance = chance_to_hit( bonus_to_hit, self.enemy_armour_class, self.advantage ) else: hit_chance = self....
This function calculates bonus attack damage based on the character's subclass and mastery status. If using two weapons, it returns the second weapon's damage. If Great Weapon Master is active, it calculates average damage multiplied by critical chance, rounded to 8 decimals. Otherwise, returns 0.
def bonus_attack_damage(self): if self.subclass.two_weapons: return self.second_weapon_damage() elif self.great_weapon_master: return round(self.average_attack_damage() * self.chance_to_critical(), 8) return 0
def chance_of_a_hit(self): attacks = self.subclass.number_of_attacks(self.level) return chance_of_an_instance(self.chance_to_hit(), attacks) def chance_of_a_critical(self): return chance_of_an_instance( self.chance_to_critical(), self.number_of_attacks() ) def chance_to_hit(s...
The function calculates total ability damage by combining base damage, attack chance, critical hit chance, and extra effects like Booming Blade, then rounds the result to 8 decimal places.
def ability_damage(self): damage_on_hit = self.subclass.damage_on_a_hit() * ( self.chance_of_a_hit() + self.chance_of_a_critical() ) per_hit_chance = self.chance_to_hit() + self.chance_to_critical() damage_per_hit = ( self.subclass.damage_per_hit() * self.number_o...
def bonus_attack_damage(self): if self.subclass.two_weapons: return self.second_weapon_damage() elif self.great_weapon_master: return round(self.average_attack_damage() * self.chance_to_critical(), 8) return 0 def ability_damage(self): damage_on_hit = self.subclas...
The main task of the code is to calculate and return the total damage output by combining a character's average attack damage multiplied by attack count, plus bonus damage from abilities, with the result rounded to 8 decimal places.
def damage_output(self): bonus_damage = self.bonus_attack_damage() + self.ability_damage() return round( self.average_attack_damage() * self.number_of_attacks() + bonus_damage, 8 )
def booming_blade_damage_on_move(self): return (self.subclass.booming_blade_damage() + 4.5) * self.chance_to_hit() def damage_output(self): bonus_damage = self.bonus_attack_damage() + self.ability_damage() return round( self.average_attack_damage() * self.number_of_attacks() + bonus_...
The function `damage_data` calculates and returns a dictionary containing key combat statistics, including base damage output, additional damage when moving (if applicable via the `booming_blade_damage_on_move` method), number of attacks, and proficiency bonus. It conditionally adds extra movement-based damage based on...
def damage_data(self): extra_damage_on_move = ( self.booming_blade_damage_on_move() if self.subclass.war_magic else 0 ) return { "damage": self.damage_output(), "damageIfMoves": self.damage_output() + extra_damage_on_move, "numberOfAttacks": self.n...
def __initialize_keyword_processor(self): self.term_keyword_processor = flashtext.KeywordProcessor(case_sensitive=False) for term in self.corpus.get_terms(): self.term_keyword_processor.add_keyword(keyword=term) def initialize_running_stats(self): running_stats = CorpusRunningStats( ...
The main task of the code is to process documents in an OffsetCorpus to build running statistics (CorpusRunningStats) by iterating through documents and categories. It initializes necessary components, checks if the corpus is an OffsetCorpus, and updates running stats with document offsets. If the corpus type is unsupp...
def build(self, verbose: bool = True) -> CorpusRunningStats: self.__initialize_keyword_processor() running_stats = self.initialize_running_stats() offset_df = self.__build_offset_df() for i, row in self.__iter_docs_and_cats(verbose=verbose): if isinstance(self.corpus, Offset...
def get_bop(patterns, min_n=3, max_n=10): notes = [[y[0] for y in x['notes']] for x in patterns] extracted = [extraction.extract_pattern_grams(nt, min_n=3, max_n=10) for nt in notes] return extracted def average_tfidf(distributions, tabs): set_tabs = list(set(tabs)) tab_num_scores = Counter(tabs) ...
The code evaluates a pattern extraction pipeline by computing recall and precision metrics using TF-IDF distributions, filtered patterns, and superstring matching, returning these metrics alongside pattern lengths.
def complete_pipeline(patterns, tab_num_scores, centones_tab, min_n, max_n, min_freq, exclude_monopatterns, prefer_superstrings, match_superstrings=False, tfidf_thresh=0): tabs = [p['tab'] for p in patterns] set_tabs = set(tabs) # Get Bag of Patterns extracted = get_bop(patterns, min_n=min_n, ...
def _fresh_screen(self): """ Draw the elements that will be drawn on each new screen :return None: """ # Draw the ship to the screen self.ship.blitme() # Draw the images that represent lives to the screen self._display_lives() self._display_score(...
This method updates the game screen by redrawing background, stars, bullets, and aliens when active. It handles game states: displaying gameplay elements if started, showing the play button and high score if not started, and triggering game-over visuals if the game ends. The display is refreshed to show changes, ensuri...
def _update_screen(self): """ Update images on the screen and flip to the new screen :return None: """ # Fill the screen with the background color self.screen.fill(self.settings.bg_color) self.stars.draw(self.screen) # Redraw the screen during each pass th...
def _check_events(self): """ Respond to key presses and mouse events :return None: """ for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.KEYDOWN: self._check_keydown_events(e...
The main task of the code is to execute the game loop, handling events, updating game elements like the ship, bullets, aliens, and lives, and rendering the screen at 240 FPS until the game ends. It continuously checks for game status and updates the display while the game is active.
def run_game(self): """ Start the main loop for the game :return None: """ while True: self._check_events() if not self.game_over and self.game_started: self._display_lives() self._create_alien() self.ship.up...
def counter(): bg_img = init_bg() # User drops a photo img_path = input("Drop photo here: ") img = cv.imread(img_path[1:-1]) # Process Image img_gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY) img_cropped = crop_img(img_gray) img_inv = invert_img(img_cropped) # Difference and Threshold...
The code processes an image to count and visualize fried items (e.g., fries) using OpenCV. It converts the image to grayscale, crops, inverts, and subtracts a background image. Adaptive thresholding isolates contours, which are drawn on the image. The final output displays the counted fries with a labeled count.
def main(): fry_count, img = counter() # SHOW THE RESULTS bg_img = init_bg(c=fry_count) img_gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY) img_cropped = crop_img(img_gray) img_inv = invert_img(img_cropped) diff_img = cv.absdiff(img_inv, bg_img) thresh = cv.adaptiveThreshold(invert_img(diff_...
def takeoff(self): # assert self.drone( TakeOff() >> FlyingStateChanged(state="hovering", _timeout=5) ).wait().success() print("---------------------------------------------------SUCCESSFUL TAKEOFF---------------------------------------------------------------------"...
This code manages real-time video streaming and drone control via a GUI. It processes user inputs to start/stop streaming, trigger drone takeoff/landing, and display video feeds. The loop continuously reads camera frames, handles GUI events, and updates the interface, terminating when the 'Exit' event is triggered.
def run(self): window_name = "Olympe Streaming" main_thread = next( filter(lambda t: t.name == "MainThread", threading.enumerate()) ) # while self.drone.connect(): while main_thread.is_alive(): _, img = self.cap.read() self.e...
def moveRightLeft(self, waitSuccess, forwardBackward, range): print("---------------------------------------------MOVING RIGHT OR LEFT---------------------------------------------------------------------") distance = float(range) self.stopmove() self.drone(extended_move_by(forwardBackwar...
The main task of the code is to calculate and execute a drone's movement parameters for scanning items on a rack. It computes horizontal and vertical displacements (dX, dY), determines level height, adjusts direction based on 'point_2', moves to the middle of the first level, and initiates scanning movements across mul...
def scanItem(self): self.X0 = self.dX_left_Right_Top self.X1 = abs(self.dX_rightTop) # x after reach end self.Y0 = self.dY_leftBottom_afterTakeoff self.Y1 = self.dY_left_Right_Top self.Y2 = self.dY_rightTop print(self.X0, " ", self.X1, " ", self.Y0, " ", self.Y1...
def scanItem(self): self.X0 = self.dX_left_Right_Top self.X1 = abs(self.dX_rightTop) # x after reach end self.Y0 = self.dY_leftBottom_afterTakeoff self.Y1 = self.dY_left_Right_Top self.Y2 = self.dY_rightTop print(self.X0, " ", self.X1, " ", self.Y0, " ", self.Y1...
The main task of the code is to manage autonomous drone operations by continuously monitoring its flight state, activating scanning tags for items/racks based on signals, executing movement instructions, and handling errors by landing the drone. It uses conditional logic to trigger scanning, navigation, and rack-switch...
def fullyAutonomous(self): takeoffStatus = self.drone.get_state(FlyingStateChanged)["state"] if takeoffStatus != FlyingStateChanged_State.landed : print(takeoffStatus) try: while self.drone_in_operation == True: if self...
def initialize_with_zeros(dim): w = np.zeros((dim, 1)) b = 0. assert(w.shape == (dim, 1)) assert (isinstance(b, float) or isinstance(b, int)) return w, b def optimize(w, b, X, Y, num_iterations, learning_rate, print_cost=False): costs = [] for i in range(num_iterations): grads, cost...
The code trains a logistic regression model using gradient descent on training data, evaluates it on test data, and returns model parameters, costs, and accuracy. It initializes weights/bias, performs optimization, predicts class labels, calculates train/test accuracy, and stores results in a dictionary. Key steps: gra...
def model(X_train, Y_train, X_test, Y_test, num_iterations=2000, learning_rate=0.5, print_cost=False): num_features = X_train.shape[0] m_train = X_train.shape[1] w, b = initialize_with_zeros(num_features) # Gradient descent (≈ 1 line of code) parameters, grads, costs = optimize(w, b, X_train, Y_tr...
def initialize_parameters_deep(layer_dims): np.random.seed(3) parameters = {} L = len(layer_dims) # number of layers in the network for l in range(1, L): parameters['W' + str(l)] = np.random.randn(layer_dims[l], layer_dims[l - 1]) / np.sqrt(layer_dims[l-1]) parameters['b' + str(l)] = ...
This code trains a deep neural network with multiple layers using gradient descent. It initializes parameters, iterates through forward and backward propagation to compute gradients, updates parameters, and optionally plots the cost over iterations. The function returns the optimized parameters after completing the spe...
def L_layer_model(X, Y, layers_dims, learning_rate = 0.0075, num_iterations = 3000, print_cost=False):#lr was 0.009 np.random.seed(1) costs = [] parameters = initialize_parameters_deep(layers_dims) for i in range(0, num_iterations): AL, caches = L_model_forward(X, parameters) cost = com...
def end_of_line(self): return self.cursor >= self.source_length() def ignore_whitespaces(self): while not self.end_of_line() and self.current_char().isspace(): if isnewline(self.current_char()): self.increment_line() self.advance_cursor() def match_to...
The main task of the code is to read and return the next valid token from the input source. It skips whitespace, checks for end-of-line, identifies the token using `match_token()`, raises an error if no token is found, and advances the cursor past the token's value for subsequent processing.
def next_token(self): if self.end_of_line(): return None self.ignore_whitespaces() token = self.match_token() if not token: raise Exception('Unexpected token: "{}", line: {}, column: {}'.format( self.remaining_source(), self.line, self.c...
def pdf_page_selected(self, event=None): """ Shows the selected PDF page on the canvas """ current_page = int(self.pdf_page_var.get()) start = int(self.start_page.get()) end = int(self.end_page.get()) if not start <= current_page <= end: self.pdf_page_var.set(start)...
The main task of the code is to clear and reset table-related data structures, set default values for table parameters, update UI elements, and disable the extract button. It resets `border_values_dict`, `header_dict`, sets `number_of_models` and `pages_per_table` to 1, triggers page selection, fills values, and clears...
def clear_table_data(self): """ Clears the current table data """ self.border_values_dict.clear() self.header_dict.clear() self.number_of_models = 1 self.pages_per_table.set(1) self.pdf_page_selected() self.fill_values() self.extract_button.config(state='...
def set_columns_names(self): """ Opens a TopLevel widget to collect the columns names """ start_page = int(self.start_page.get()) # Searches for a known table columns_names_dict = { 'Table 1A': { '1': ('Line No.', 'Nominal Composition', 'Product Form', 'Spec...
The code extracts table data from PDF images using predefined header and border coordinates. It checks for column-header alignment, adjusts column names if mismatches occur, initiates data extraction, and saves the structured data as CSV.
def extract_table(self): """ Method to extract the tables values """ if not self.pdf_file_images or not self.header_dict: return headers_data_match = True """ {'1': {'Top Border': 175, 'Bottom Border': 681, 'Left Border': 53, 'Right Border...
def print_log(message): print(message) with open(PATHS.LOG_FILE, 'a+') as f: f.write(str(message) + '\n') def remove_from_conf(self, update, context): print_log(datetime.datetime.now()) if self.conf is {}: update.message.reply_text( "i'm not sending updates to...
This code handles errors in a Telegram bot by logging exceptions, re-raising them, and specifically managing cases like unauthorized access (removing chat IDs), chat migration (updating config with new chat IDs), and other network/telegram errors (logging and ignoring). It ensures the bot's configuration stays consiste...
def process_error(self, update, context): print_log(datetime.datetime.now()) print_log(f"error raised!: {context.error}") try: raise context.error except Unauthorized: # remove update.message.chat_id from conversation list self.remove_from_conf(update,...
def parse_ip(self, val): ip_address = None prefix = None cidr = None patern = r'^([0-9]+(?:\.[0-9]+){3})([/\s]+([0-9]+))?$' matched = re.search(patern, str(val).strip()) if matched: match_ip = self.clean_ip(matched.group(1).strip()) match_prefix = ...
The function retrieves network information for a given IP address, including its binary representation, class, subnet details, netmask, wildcard, and total hosts. It constructs and returns a dictionary with this data, either in a simplified or detailed format based on the 'simple' parameter.
def get_info(self, ip, simple=True): """ Get Information IP address from IP with or without CIDR @param ip: string (E.g 192.168.0.1 or 192.168.0.1/24) @param simple: boolean (If True will return as simple mode) @return: dict """ ip_address, prefix, cidr = self.par...
def xtime(a): if a & 0x80: a = a << 1 a = a ^ 0x1B else: a = a << 1 return a & 0xFF def xor_cols(a,b): return a^b def mix_columns(s): for r in s: mix_column(r)
This code implements the inverse MixColumns transformation in AES decryption, modifying each column of the state matrix 's' using GF(2^8) operations. It calculates intermediate values u and v via xtime and XOR, then updates column elements with these values. The final call to mix_columns(s) may indicate a subsequent st...
def inv_mix_cols(s): for col in s: u = xtime(xtime(xor_cols(col[0] , col[2]))) v = xtime(xtime(xor_cols(col[1] , col[3]))) col[0] = xor_cols(col[0], u) col[1] = xor_cols(col[1], v) col[2] = xor_cols(col[2], u) col[3] = xor_cols(col[3], v) mix_columns(s)
def get_hex(value): str = value.encode('utf-8') hex_str = str.hex() return hex_str def matrix_from_bytes(text): "converts byte array to 4 * 4 matrix" a = [] for i in range(0, len(text), 4): a.append(list(text[i:i+4])) return a def key_generation(key): w = matrix_from_bytes(key) ...
The code implements a block cipher encryption algorithm (likely AES) by converting plaintext and key to hexadecimal, generating a key schedule, and applying multiple rounds of substitution, shifting, mixing columns, and adding round keys. It returns the encrypted ciphertext as a hexadecimal string.
def encrypt(plaintext: str, key: str): data = bytearray.fromhex(get_hex(plaintext)) key = bytearray.fromhex(get_hex(key)) matrix = matrix_from_bytes(data) key_schedule = key_generation(key) add_round_key(matrix, key_schedule, round=0) # print('Matrix after initial round key added:') # pri...
def GenKeys(master_key): key_columns = bytes2matrix(master_key) for i in range(10): for j in range(4): if j == 0: last_word = list(key_columns[-1]) # print(last_word) w_4 = xor_words(key_columns[i*4], g_function(last_word, i+1)) ...
This code implements the AES-128 encryption algorithm by converting input text and key to bytes, generating round keys, and applying 10 rounds of transformations including substitution, shifting, mixing columns, and adding round keys to produce ciphertext.
def encrypt(plaintext, key): ''' this function takes input-text(string) and 128-bit key(string) as parameters and returns cipher-text(string) as output ''' # convert from string data type. key = key.encode('utf-8') keys_generated = GenKeys(key) # print(len(keys_generated)) # 11 keys for 10+1 rounds ...
def get_hex(value): str = value.encode('utf-8') hex_str = str.hex() return hex_str def matrix_from_bytes(text): "converts byte array to 4 * 4 matrix" a = [] for i in range(0, len(text), 4): a.append(list(text[i:i+4])) return a def key_generation(key): w = matrix_from_bytes(key) ...
This code decrypts AES-encrypted data using a specified key by applying inverse AES operations: converting input hex strings to bytearrays, generating a key schedule, performing inverse substitution, shift rows, mix columns, and round key additions across 10 rounds. It prints intermediate states after the 1st and 9th r...
def decrypt(cipher: str, key: str): cipher = bytearray.fromhex(cipher) key = bytearray.fromhex(get_hex(key)) matrix = matrix_from_bytes(cipher) key_schedule = key_generation(key) add_round_key(matrix, key_schedule, round=10) inv_shift_rows(matrix) inv_sub_bytes(matrix) print("\n Matrix...
def bytes2matrix(text): """ Converts a 16-byte array into a 4x4 matrix. """ a = [] for i in range(0, len(text), 4): a.append(list(text[i:i+4])) return a def GenKeys(master_key): key_columns = bytes2matrix(master_key) for i in range(10): for j in range(4): if j ==...
This function decrypts AES-encrypted data using a 128-bit key by applying inverse AES rounds: it converts the ciphertext matrix, performs inverse substitution, shifting, and mixing operations, applies round keys in reverse order, and reconstructs the original plaintext from the decrypted matrix.
def decrypt(cipher, key): ''' this function takes cipher-text(string) and 128-bit key(string) as parameters and return original text as output ''' # cipher = cipher.encode('utf-8') cipher = bytes2matrix(cipher) key = key.encode('utf-8') keys_generated = GenKeys(key) cipher = add_round_key(cipher, ...
def negate(clause): literals = clause.split("OR") negations = [] for literal in literals: literal = literal.strip() # remove trailing spaces # if the literal is affirmative, add a "-" to the beginning if len(literal) == 1: negations.append("-" + literal) # if ...
The code implements the **propositional logic resolution algorithm** to determine if a statement `alpha` is entailed by a knowledge base. It negates `alpha`, combines it with the knowledge base, and iteratively resolves clause pairs to derive new clauses. If a contradiction (e.g., an empty clause) is derived, it return...
def pl_resolution(knowledge_base, alpha): negative_alpha = negate(alpha) clauses = [] clauses.extend(knowledge_base) clauses.extend(negative_alpha) new_clauses = [] clause_pairs = [] records = [] record = [] while True: n = len(clauses) for i in range(n): ...
def calculate_checksum(number): checksum = 0 digit_count = get_digit_count(number) for i in range(0, digit_count): current_digit = get_nth_digit(number, digit_count - i) # multiply digits in odd places by two if (i % 2 == 1): current_digit *= 2 # if the product...
The code validates a credit card number by checking its checksum, length, and starting digits. It determines if the card is AMEX, MASTERCARD, VISA, or INVALID based on predefined criteria: 15-digit cards starting with 34/37 for AMEX, 16-digit cards starting with 5 for MASTERCARD, and 13/16-digit cards starting with 4 f...
def main(): # Prompt for input card_number = get_int("Number: ") # Calculate checksum is_valid_checksum = calculate_checksum(card_number) % 10 == 0 # Check card length digit_count = get_digit_count(card_number) # Check starting digits first_digit = get_nth_digit(card_number, 1) se...
def getRPoint(img): #Takes the .shape of the img to get all the width and height values in an array, and then finds random x and y point shape = img.shape valid = False while valid is False: randomX = random.randint(0, shape[0]) randomY = random.randint(0, shape[1]) if img[abs(rando...
The function implements a Rapidly-exploring Random Tree (RRT) algorithm to find a path from a starting node to a goal position within an image-based map. It iteratively generates random points, connects them to the nearest existing node via line segments, and validates collisions. If a line is valid, the new node is ad...
def RTT(node, goal, img, stepSize = 30): nodes : list[Node] = [node] i = 0 triesCounter = 0 count = 0 start = time.time() while i < 500: if count == 60: print(str((time.time()-start)/60)," seconds for each node evaluated") elif count == 30: print(str((tim...
def load_model(model_config, device): if 'detection_model' not in model_config: return load_detection_model(model_config, device) return get_wrapped_detection_model(model_config, device) def train(teacher_model, student_model, dataset_dict, ckpt_file_path, device, device_ids, distributed, config, args):...
The code loads configurations, initializes CUDA settings, loads teacher/student models, trains the student model (if not testing-only), evaluates both models on test data, and optionally performs fault simulation testing using FI_manager if configured. It handles logging, distributed training setup, and model checkpoin...
def main(args): log_file_path = args.log if is_main_process() and log_file_path is not None: setup_log_file(os.path.expanduser(log_file_path)) #distributed, device_ids = init_distributed_mode(args.world_size, args.dist_url) distributed, device_ids = False, None logger.info(args) # cuda...
def get_type_family(dtype): return get_type_family(dtype=dtype) def check_if_datetime_feature(self, X: Series): type_family = self.get_type_family(X.dtype) # TODO: Check if low numeric numbers, could be categorical encoding! # TODO: If low numeric, potentially it is just numeric instead ...
This code identifies and categorizes feature types in a DataFrame by analyzing each column's data type, unique values, and patterns. It marks columns with only one unique value for removal, detects datetime or text features, and organizes remaining columns into type families (e.g., numeric, categorical). The result is ...
def get_feature_types(self, X: DataFrame): self.features_init = list(X.columns) self.features_init = [feature for feature in self.features_init if feature not in self.features_to_remove] for column in self.features_init: mark_for_removal = False col_val = X[column] ...
def printIntro(): print("This program simulates a game of racquetball between two") print('players called "A" and "B". The abilities of each player is') print("indicated by a probability (a number between 0 and 1) that") print("the player wins the point when serving. Player A always") print("has th...
The main task of the code is to simulate a series of games between two players (A and B) with given probabilities of winning each game. It retrieves input values (probabilities and number of games), simulates the games, and outputs the results by displaying the number of wins for each player.
def main(): printIntro() probA, probB, n = getInputs() winsA, winsB = simNGames(n, probA, probB) printSummary(winsA, winsB)
def find_request_from_walk(root): for node in ast_walk(root): if hasattr(node, 'name'): name = node.name if name == 'requests': yield node def find_statement_node(expr): state = expr while not state.is_statement and hasattr(state, 'parent'): state = st...
This code parses a Python file to identify and extract request-related exit points, including function names, line numbers, and processed request/response details, returning them as a list of Point objects.
def get_exit_points(file_name): with open(file_name, "r") as source: ast_node = astroid.parse(source.read()) exit_points = list() for node in find_request_from_walk(ast_node): point = Point() scope_func = node.scope() statement = find_statement_node(node) if isinst...
def stddev_to_variance(stddev, multivariate=True) -> tf.Tensor: """Convert a standard deviation vector or cholesky decomposition of the covariance matrix to a variance vector or covariance matrix, respectively.""" stddev = tf.convert_to_tensor(stddev) if multivariate: tf.assert_greater(tf.rank(s...
The code computes the mean and standard deviation of a Gaussian distribution proportional to the product of two input Gaussian distributions. It calculates weighted averages of the original means and variances, handling both univariate and multivariate cases. For multivariate, it uses matrix operations involving covari...
def gaussian_pdf_product(mean1, stddev1, mean2, stddev2, multivariate=True) -> Tuple[tf.Tensor, tf.Tensor]: """The product of the PDFs of two gaussian distributions is proportionate to a gaussian PDF whose mean and variance are weighted averages of the means and variances, respectively,...
def get_correct_pattern_string(self): """Creates row object based off correct pattern in order to display that pattern to the user""" r = row.Row() for index, color in enumerate(self.correct_pattern): r.set_peg(index, peg.Peg(color)) return r.get_text() def new_row(self): ...
The main task of the code is to initialize a Mastermind game by creating color objects, generating a random secret pattern, displaying gameplay instructions, and setting up the game loop for player interaction. It defines color mappings, tracks remaining guesses, and provides visual feedback on color codes and rules, w...
def __init__(self, debug=False): ### Create Color Objects self.colors = { "Red" : color.Color(255, 80, 80), "Orange" : color.Color(255, 165, 0), "Yellow" : color.Color(255, 255, 0), "Green" : color.Color(60, 255, 60), "Blue" : color.Color(100...
def read_data_file(fname): rows = read_csv_rows(fname) tups = [] n_withdrawn = 0 n_single = 0 for row in rows: if (len(row)) < 4: continue paper,withdrawn,primary,secondary = row[:4] if withdrawn == 'False': if secondary and not primary: ...
The function verifies if paper-room assignments match the rooms of primary and secondary authors by reading data from three files, checking assignments for each paper, and reporting the count of plenary papers where assignments align. It processes entries to ensure consistency between paper and person room allocations,...
def verify_rooms(data_file, paper_file, people_file): data = read_data_file(data_file) paper_rooms = read_paper_or_people_rooms(paper_file, 'papers', 1) people_rooms = read_paper_or_people_rooms(people_file, 'people', 2) all_plenary = [] for paper,primary,secondary in data: paper_room = get_...
def assign_people_missing_from_XY(reviewers, partion2): roomX, roomY, cutZ = partion2 revs = set(reviewers) missing = list( (revs - set(roomX)) - set(roomY) ) # print('missing:', missing) # print('roomX, roomY sizes:', len(roomX), len(roomY)) shuffle(missing) for rev in missing: if l...
The function assigns papers to rooms by first addressing missing reviewers in partition2, classifying papers into categories (A, B, C, X, Y) based on partitions, and then distributing these categorized papers into rooms.
def assign_papers_to_rooms(reviewers, papers, partition1, partition2): assign_people_missing_from_XY(reviewers, partition2) pid_lists = classify_papers_ABCXYZ(papers, partition1, partition2) paper_rooms = assign_pids_to_rooms(pid_lists) # pidsA, pidsB, pidsX, pidsY return paper_rooms
def partition_graph(graph): split = partition_kl_bisection(graph) room0 = list(split[0]) room1 = list(split[1]) cut_edges = list(nx.edge_boundary(graph, room0)) return room0, room1, cut_edges def make_subgraph_from_cut(graph, partition): roomA, roomB, cutC = partition subgraph = nx.Graph() ...
This function performs multiple trials to find the optimal graph partitioning that minimizes the cut cost between two subgraphs. It iteratively splits the graph into partitions, evaluates their cut cost, and retains the configuration with the lowest cost. When successful, it assigns papers to rooms based on the best pa...
def partition_ABXY_trials(graph, reviewers, papers, num_trials=1000): min_cut_cost = 9999999 # a big number min_paper_rooms = None min_partitions = None for i in range(num_trials): partition1 = partition_graph(graph) subgraph = make_subgraph_from_cut(graph, partition1) partition2...
def read_assignments(fname): reviewers = set() papers = {} singles = {} with open(fname) as f: lines = f.readlines() lines = lines[1:] # skip header for line in lines: parts = line.split(',') if len(parts) < 4: continue parts = [p.strip() for p in part...
The main task of the code is to process a CSV file containing reviewer-paper assignments, generate a graph representation, run multiple trials to partition papers into four rooms (A, B, X, Y), validate the partitions, and output the results to files. It handles command-line arguments for customizing input file and tria...
def main(): fname = 'fake-data.csv' ntrials = 1000 if len(sys.argv) > 1: fname = sys.argv[1] if len(sys.argv) > 2: ntrials = int(sys.argv[2]) print(f'Reading {fname} ...') reviewers, papers, singles = read_assignments(fname) print('Input reviewers and papers:', len(reviewers)...
def fsize_calc(filepath): try: return os.stat(filepath)[6] except OSError: Say("stat error %s" % filepath) return -1 def fash_calc(filepath): md5 = hashlib.md5() with open(filepath,'rb') as f: for chunk in iter(lambda: f.read(8192), b''): md5.update(chunk) ...
This function scans a directory to identify duplicate files and folders using hash comparisons. It recursively checks subdirectories, marks duplicates, and moves them to a specified location if there are unique files or at the top level. It returns a boolean indicating whether unique content exists in the subtree, affe...
def scan_folder(currDir): """ at any level, if the total unmatched > 0, *all* duplicates, including folders, are moved at that level. only if total match ( unmatched ==0 ) is the case will the moving be left to the parent level. returns hasUnique - indicates the subtree is not "bulk m...
def load(read_from_path): global Scans, Bhash, Bfold Bug("read from %s" % read_from_path) with open(read_from_path, 'rb') as f: Scans, Bhash, Bfold = pickle.load(f) def dump_scans(): import json json.dump(Scans, sys.stdout, indent=2) def scan_folder(currDir): """ at an...
The code processes command-line arguments for file scanning and duplicate detection, loads/saves scan data, handles file movement, and outputs JSON results with duplicate information. It uses argparse for options like read/write paths, scan depth, hidden files, and debug settings, then performs folder scanning, logging...
def main(): global Conf, Say, Bug par = argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter, description=HELP) par.add_argument('-r', '--read', action='store', help="store file read path. use '.' for default" ) par.add_argument('-w', '--write', action='store', ...
def inst_fetch(lines): global pc, data global bo_bits, index_bits, tag_bits, data_copy, cachesize, blocksize, n, SA array = [] for i in lines: array.append(i.split()) MCode = '' for i in array: for j in range(len(i)): if i[j] == str(hex(pc)): ...
The code simulates a pipeline processor by reading instructions from a file, decoding operations, executing ALU tasks, managing data caches, and performing write-backs. It processes each instruction line through stages like instruction fetch, decoding, ALU operations, and data handling, updating global state variables....
def CachePipeline(): global clock, Control, cap global memory file = open("instruction.mc","r") lines =file.readlines() n = len(lines) IR = inst_fetch(lines); IR = UpdateSAInst(lines) lines = lines[1:] IR = int(IR, 16) Operation = pipelinedecode(IR); inst_fetch(lines); IR = UpdateSA...
def initMemory(): global TextMemory, DataMemory file = open("instruction.mc","r") lines =file.readlines() if (lines): for i in range(len(lines)): if lines[i]!='\n': array = [] array.append(lines[i].split()) if(int(array[0][0], 16) >= 0...
The main task of the code is to configure pipeline and register settings via user input, execute either pipelined or non-pipelined processing based on the configuration, and output performance metrics like total cycles, CPI, instruction counts, hazard statistics, and cache access details. It handles user prompts for en...
def main(): initMemory() global knobPipeline, knobDataFor, knobRegister, knobPipelineRegister, knobSpecial, specialInst, multiClock, instcount knobPipeline = input('Enter "on/off" to Enable/Disable Pipeline : ') knobPipeline.lower() knobRegister = input('Enter "on/off" to Enable/Disable Printing reg...
def p1345textEC(self): tg = random.choice(self.tags) payload = tg + ' ' + random.choice(self.events) + random.choice( self.payloads) + ">" + self.get_random_txt() + self.end_tag(tg) return payload def p51345(self): payload = random.choice(self.closers) + random.choice(self.ta...
The function `get_simple_payload` generates a randomized string by combining random elements from `spaces`, `events`, `payloads`, and `closers`. It uses a modulo operation on a random integer to select between four methods (`p1345textEC`, `tags+simple`, `p51345`, or `nested_tag`), constructing a payload with varying st...
def get_simple_payload(self): simple = self.spaces + random.choice(self.events) + random.choice( self.payloads) + random.choice(self.closers) rnd = random.randint(4, 8) rnd = rnd % 4 if rnd == 1: payload = self.p1345textEC() elif rnd == 2: payl...
def __get_uncertainty(self, data): prob = np.sum(data[:,-1]) / data.shape[0] return 0 if prob == 0 or prob == 1 else self.core(prob) def __traversal(self, data, uncert): optimun_info = None for i in range(0, data.shape[1] - 1): values = [row[i] for row in data] va...
This function recursively constructs a decision tree by partitioning data based on calculated uncertainty. If the recursion depth exceeds the maximum allowed depth or no further splits are possible, it creates a leaf node. Otherwise, it splits the data, recursively builds left and right subtrees, and returns a decision...
def __build_tree(self, data, depth): uncert = self.__get_uncertainty(data) if depth >= self.max_depth: return Leaf(data, uncert) info = self.__traversal(data, uncert) if info is None: return Leaf(data, uncert) left, right = self.__partition(data, info) ...
def insert_value_in_place(self, row_index, column_index, value): self.number_inserted += 1 self.board[row_index, column_index] = value self.markup_depth[row_index, column_index] = 0 place_markups = np.copy(self.markup[row_index, column_index, :]) removed_markups = self.remove_val...
This function implements a backtracking algorithm to solve a constraint satisfaction problem (e.g., Sudoku). It recursively tries valid values in the cell with the fewest possibilities, checks consistency, and backtracks when contradictions arise, using markup depth to prioritize cells for efficient solution.
def solve(self): if(self.number_inserted == self.dim_x*self.dim_y): return True next_guess_index = np.where(self.markup_depth == np.amin( self.markup_depth[np.where(self.markup_depth > 0)])) row_index = next_guess_index[0][0] column_index = next_guess_index[1][0]...
def history_delete_all(self): ''' Deletes all history ''' self._history = [] def process_command(self,cmd_str:str): ''' Processes command entries in stock transaction input file. Expected formats of commands are '!<COMMAND>#Argument1#Argument2#Argument3...' ...
The main task of the code is to rebuild an object's state by reading transactions from a specified file (CSV or JSON), applying stock splits, and generating a hash digest for data integrity. It optionally clears history, skips adding transactions to the current session's history, and processes special commands within t...
def rebuild(self,file_name=None,clear_history=False): ''' Re-builds this object based on the associated file name. Optionally a different file name can be specified from which to re-build the data ''' if file_name: fname = file_name else: f...
def history_delete_last(self): ''' Deletes last item in history ''' if len(self._history) > 0: _ = self._history.pop() def rebuild(self,file_name=None,clear_history=False): ''' Re-builds this object based on the associated file name. Optionally a diffe...
The main task of the code is to undo the last transaction (addition or sale) by rebuilding the stock data state from the last file state and the current session buffer, excluding the last operation. It deletes the last history entry, rebuilds the data, then reapplies remaining transactions without re-adding them to his...
def undo(self): ''' Undoes the last addition or sale. This requires re-building the entire stock data state from the last file state and the current session buffer sans the last operation ''' if len(self._history) > 0: self.history_delete_last() s...
def _getSourcePath(self, name: str): return f'{self.cache}/{self.options[name]}' def _sourceQOFhd(self): url = self.sourceURL['qofHD'] logger.info(f'Downloading QOF 2020/2021 High Dep data from {url}') qofHD = [] with tempfile.TemporaryDirectory() as tmp: urllib.reque...
The main task of the code is to aggregate data from multiple sources into a single DataFrame by horizontally concatenating results from five private methods, save the combined data as a Parquet file at a specified path, log the operation, and return the consolidated DataFrame for further processing or analysis.
def _sourceQOF(self): path = self._getSourcePath('qof') qof = pd.concat([ self._sourceQOFhd(), self._sourceQOFcv(), self._sourceQOFres(), self._sourceQOFls(), self._sourceQOFmh()], axis=1) logger.info(f'Writing QOF data to {path}') qof.to_parquet(path)...
def eof(): global content_index global content return content_index >= len(content) def peek(): global content_index global content return content[content_index] def advance(): global content_index val = peek() content_index = content_index + 1 return val def scan_digits(): ...
This function scans input tokens, skipping whitespace, and categorizes them into types like identifiers, keywords, operators, or errors. It returns a dictionary with "type" and "val" fields, handling numbers, keywords (e.g., 'print', 'intdcl'), and symbols. If an invalid character is found, it prints an error and exits...
def scanner(): global content_index global content ans = {} while not eof() and (peek() == ' ' or peek() == '\n'): advance() if eof(): ans["type"] = '$' else: if peek() in '0123456789': ans = scan_digits() else: ch = advance() i...
def logout(self): """ show cursor """ curses.curs_set(1) self.api.set_token() self.state['obj'] = {} self.user.logged_out() def nav(self, d_x, d_y, load=False): """ navigates through selected part of application """ if self.nav_sect == NAV_SECT_TABS: ...
The function processes key inputs to control navigation and actions in an application. It handles quit/logout commands, translates key presses to navigation movements, delegates input to the current page if not consumed by navigation, and manages tab-section switching. It returns False only for quit, otherwise True, en...
def key_input(self, char): if char == ord(KEY_QUIT): return False # quit the app if char == ord(KEY_LOGOUT): self.logout() return True pass_input = True d_x, d_y, done_nav = nav_key(char) if done_nav: pass_input = False # this i...
def set_statusbar(self, items=None): self.state['statusbar'] = [[KEY_QUIT, "quit"], [KEY_LOGOUT, "logout"]] + \ ([] if items is None else items) self.gui_statusbar() def gui_header(self): color = curses.color_pair(NC_COLOR_HEADER[0]) | curses.A_BOLD if not self.win['head...
The main task of the code is to draw the main application window by clearing the screen, hiding the cursor, and invoking methods to render the status bar, header, and page components. It orchestrates the GUI setup using curses for terminal-based interface management.
def draw_gui(self): """ calls other methods to draw the main application window """ self.scr.clear() self.scr.refresh() # hide cursor curses.curs_set(0) self.set_statusbar() self.gui_header() self.gui_page()
def get_main_maps(data: DotDict) -> PagerInfo: """ Returns main 4v4 map data as a list of dicts formatted as Discord embeds. """ if not data.regularSchedules.nodes: return empty_embed('Map Schedule') pages = [] announcement = None for i, node in enumerate(data.regularSchedules.nodes): ...
The function `format_all` generates a dictionary of `PagerInfo` objects, each corresponding to different modes (MAIN, SR, CHALLENGE, EGGSTRA), by calling specialized functions (`get_main_maps`, `get_sr_shifts`, etc.) on the input `DotDict` data. Its main task is to aggregate and categorize embed data into mode-specific...
def format_all(data: DotDict) -> dict[str:PagerInfo]: """ Returns a dict containing all embed data. """ return { Mode.MAIN: get_main_maps(data), Mode.SR: get_sr_shifts(data), Mode.CHALLENGE: get_challenges(data), Mode.EGGSTRA: get_eggstra_shifts(data) }
def getCurrentCustomer(self, ID): try: self.cIndex = self.customerData['ID'].index(str(ID)) self.currentCustomer = self.customerData['Customers'][self.cIndex] self.cFlag = True except ValueError: print('The selected customer does not exist within the datab...
The code modifies a customer's reservation by canceling their existing booking and rebooking with new dates. If the new reservation fails, it reverts to the original dates. It checks if the customer exists, retrieves their details, cancels the old reservation, re-adds the customer, and attempts the new dates. If unsucc...
def modifyReservation(self, ID, newInDate, newOutDate): #find customer by ID index, go to that customer if self.getCurrentCustomer(ID): rooms = self.currentCustomer.returnCustomerRooms() if rooms: #Store old data incase modification not successful ...
def file_import(file): ''' This function imports a file and stores its contents in an array Inputs: file (path): The file to be imported Returns: inputs (array): Array containing the values in the file ''' with open(file,'r') as vals: inputs= np.array(list(map(lambda f...
The main task of the code is to perform cross-validation to determine an optimal bandwidth for a model, predict y-values using this bandwidth on either original or new input data, save predictions to an output file, and optionally generate a plot. It imports data, computes optimal parameters, applies predictions, and m...
def main (xin, yin, output, k_folds, plot = None, xout = None): ''' This is the main function containing all the others Inputs: xin (path): The path to the original x values yin (path): The path to the original y values output (path): The path foe the output file to be created ...
def copy_images(data: Path, image_dir: Path, verbose) -> int: """Copy images from a directory to a new directory. Args: data: Path to the directory of images. image_dir: Path to the output directory. verbose: If True, print extra logging. Returns: The number of images copied...
The main task of the code is to process images into a NerfStudio dataset by copying and downscaling images, running COLMAP for 3D reconstruction, and generating a transforms.json file. It checks dependencies, creates directories, logs progress, and handles COLMAP output to prepare data for neural radiance field trainin...
def main(self) -> None: """Process images into a nerfstudio dataset.""" install_checks.check_ffmpeg_installed() install_checks.check_colmap_installed() self.output_dir.mkdir(parents=True, exist_ok=True) image_dir = self.output_dir / "images" image_dir.mkdir(parents=True,...
def convert_video_to_images( video_path: Path, image_dir: Path, num_frames_target: int, verbose: bool = False ) -> Tuple[List[str], int]: """Converts a video into a sequence of images. Args: video_path: Path to the video. output_dir: Path to the output directory. num_frames_target: ...
This code processes a video into a NerfStudio dataset by converting it to images, downscaling them, running COLMAP for structure-from-motion, and generating a transforms.json file. It checks dependencies, creates directories, handles image extraction, and logs results.
def main(self) -> None: """Process video into a nerfstudio dataset.""" install_checks.check_ffmpeg_installed() install_checks.check_colmap_installed() self.output_dir.mkdir(parents=True, exist_ok=True) image_dir = self.output_dir / "images" image_dir.mkdir(parents=True, ...
def get_insta360_filenames(data: Path) -> Tuple[Path, Path]: """Returns the filenames of the Insta360 videos from a single video file. Example input name: VID_20220212_070353_00_003.insv Args: data: Path to a Insta360 file. Returns: The filenames of the Insta360 videios. """ i...
The main task of the code is to convert an Insta360 video into a Nerfstudio dataset by extracting and downscaling images, running COLMAP for 3D reconstruction, and generating a transforms.json file. It checks dependencies, processes video frames, handles COLMAP pipeline execution, and logs results, ensuring output dire...
def main(self) -> None: """Process video into a nerfstudio dataset.""" install_checks.check_ffmpeg_installed() install_checks.check_colmap_installed() self.output_dir.mkdir(parents=True, exist_ok=True) image_dir = self.output_dir / "images" image_dir.mkdir(parents=True, ...
def sortingChoice(s): c = -1 if s == 'P': c = 0 elif s == 'S': c = 1 elif s == 'G': c = 2 elif s == 'C': c = 3 return c def sortingDirection(s): c = -1 if s == 'A': c = 0 elif s == 'D': c = 1 return c def quicksort(n, para, dir)...
The code reads plant treatment data from a file, cleans and converts it into numerical values, calculates growth metrics, sorts the data based on user-specified parameters (e.g., Plant ID, Status, Growth, Concentration) in ascending or descending order, formats the results with headers, and writes them to a user-define...
def main(): # Accept input from the user. outputID = input("Enter a file name for the reorganized data: ") reoorgCode = input("Enter a code for the reorganization: ") # Open the input and output files. inputFile = open("plant_treatment_data.txt", "r") outputFile = open(outputID, 'w') # Re...
def _create_treeview(self): verscrlbar = ttk.Scrollbar(self, orient="vertical", command=self.treev.yview) self.treev.configure(xscrollcommand = verscrlbar.set) self.treev["columns"] = ("1", "2", "3", "4", "5", "6", "7") self.treev['show'] = 'headings' self.treev.column("1", width...
This code initializes a GUI page for displaying and filtering trade data using Tkinter. It sets up styles, a table (Treeview), filters (dates, delay, ticks, company names, trade types, members), and buttons to analyze data or apply filters. The page allows users to view trades, apply criteria, and navigate back to the ...
def __init__(self, parent, controller): ttk.Frame.__init__(self, parent, style="TFrame") #styles for use in this page style = ttk.Style() style.configure("m.TButton", background="#121212", foreground="#ededed", ...
def get_score(response, task): score = 0 if "response_call_sign" in response: denum = len(call_signs) + len(colours) + len(numbers) - 1 if response["response_call_sign"] == task["task_call_sign"]: score += len(call_signs) / denum else: denum = len(colours) + len(numbers) ...
The main task of the code is to conduct an auditory masking trial by presenting target and masker stimuli, recording participant responses, calculating scores, and logging experimental parameters and results. It manages trial progression, stimulus processing (reversal, channel selection), task configuration, and data s...
def run_masking_trial(response=None): global THIS_TRIAL global task if response is not None: response["score"] = get_score(response, task) results_file.write(response, tag="response") if THIS_TRIAL <= seq.n_trials: print(THIS_TRIAL - 1, "Response:", response["response_col...