dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def reprojection(self, theta): """ input: theta: angle of reprojection. output: proj: reprojection OCS image. """ print('The 3D reference model is reprojecting: %s ...' % (theta,)) reference_theta = np.zeros((self.proj_shape[0], self.proj_shape[1...
This method performs single-process alignment by iterating through 5 steps (3 coarse, 2 fine), calculating horizontal/vertical offsets for projection angles, adjusting positions via reprojection, and tracking successful/failure angles. It processes projections in steps, prints progress, and updates alignment data.
def alignment_single(self): """Single-process alignment.""" for i in range(5): step = self.step_size[i] if i < 3: print('Coarse alignment: %s, Step: %s' % (i, step)) else: print('Fine alignment: %s, Step: %s '% (i, step)) ...
def cal_pos_angle_idx(self): width = [] for roi in self.rois: width.append(roi[0][3] - roi[0][1]) pos_angle_idx = width.index(min(width)) return pos_angle_idx def positioning(self, center_h=None, center_v=None): """spatial positioning""" if center_h == None: ...
The code performs misalignment correction by determining the position angle index based on the mode (either using a start index or a calculated value), setting start and position angles, and then executing positioning and alignment operations to correct misalignment in a 3D model or image data.
def correction(self): """Misalignment correction.""" if self.pos_mode == 0: self.pos_angle_idx = self.start_angle_idx else: self.pos_angle_idx = self.cal_pos_angle_idx() self.start_angle = self.angles[self.start_angle_idx] self.pos_angle = self.angles[self...
def calculate_key(self, s_vertex): return ( min(self.gs[s_vertex], self.rhss[s_vertex]) + self.h(self.s_start, s_vertex) + self.k_m, min(self.gs[s_vertex], self.rhss[s_vertex])) def update_vertex(self, u_vertex): if not u_vertex == self.s_goal: self.rhss[u_vertex] = min([self.gs[s_next_verte...
This code computes the shortest path in a graph using a priority queue (U) by iteratively updating node costs (g and rhs) and propagating changes to neighbors. It terminates when the start node's key matches its calculated value, then reconstructs the path from start to goal by following minimum-key nodes, outputting t...
def compute_shortest_path(self): while(self.U.topKey() < self.calculate_key(self.s_start) or not self.rhss[self.s_start] == self.gs[self.s_start]): k_old = self.U.topKey() u_vertex = self.U.pop() if k_old < self.calculate_key(u_vertex): self.U.insert(u_verte...
def initialize(self): self.U = U(None) self.k_m = 0 for s_vertex in self.S: self.gs[s_vertex] = np.inf self.rhss[s_vertex] = np.inf self.rhss[self.s_goal] = 0 self.U.insert(self.s_goal, self.calculate_key(self.s_goal)) d...
This callback processes a new goal position from incoming Pose messages, updates the path planning state, computes the shortest path, checks if a valid path exists, and publishes the next target position for navigation if feasible.
def goal_callback(self,data): """Callback function which is called when a new message of type Pose is received by the subscriber.""" self.s_goal = (data.x, data.y) self.s_last = self.s_start self.initialize() self.compute_shortest_path() if(not self....
def find_arg_min(self, s_start): vertex_to_return = None minimum = np.inf for neighbor in self.neighbors(s_start): bar = self.cost(s_start, neighbor) + self.gs[neighbor] if bar < minimum: minimum = bar vertex_to_return = neighbor r...
This function updates the robot's path planning by checking if the robot is at the start position, recalculating the next goal state if needed, detecting changes in edge costs, adjusting the path cost parameter (k_m), updating affected graph vertices, and recomputing the shortest path when edge costs change. It ensures...
def main_stuff(self): if self.is_init_done: if(not self.s_start == self.s_goal): if self.gs[self.s_start] == np.inf: print("Something\'s wrong man.") return if self.robot_is_on_position: self.s_sta...
def get_training_edges(self, batch): # Instantiate empty prediction edge list training_edges = torch.empty([2, 0], dtype=torch.int64, device=self.device) # Forward pass of model, handling whether Cell Information (ci) is included with torch.no_grad(): embedding = self.apply_...
The main task of the code is to compute the training loss for a batch in a neural network model. It processes the input batch to extract edges and embeddings, applies the embedding, retrieves truth data, calculates the loss using a loss function, logs the loss value, and returns the loss tensor for optimization.
def training_step(self, batch, batch_idx): """ Args: batch (``list``, required): A list of ``torch.tensor`` objects batch (``int``, required): The index of the batch Returns: ``torch.tensor`` The loss function as a tensor """ batch.edge_index...
def pieceFinder(self, colorWanted): pieces = [] for row in self.chessMap: for col in row: x, y, color, piece = col.cget('text').split('_') x = int(x) y = int(y) if(colorWanted == color): pieces.append([x, y, ...
The code checks if the specified player's king is in a stalemate by verifying if both sides have only kings and no other pieces can move. If all pieces cannot attack any squares, it returns True, indicating a stalemate.
def checkStalemate(self, color): if (color == 'white'): allPiece = self.pieceFinder('white') amountOfWhitePieces = len(allPiece) if(amountOfWhitePieces == 1 and allPiece[0][2] == 'king'): blackPiece = self.pieceFinder('black') amountOfBlackPie...
def pieceFinder(self, colorWanted): pieces = [] for row in self.chessMap: for col in row: x, y, color, piece = col.cget('text').split('_') x = int(x) y = int(y) if(colorWanted == color): pieces.append([x, y, ...
This function identifies all enemy pieces threatening the specified player's king in a chess game. It checks each enemy piece (rook, bishop, queen, knight, pawn) to determine if they can attack the king's position, then filters their attack paths to only include squares directly between the piece and the king. It retur...
def inCheck(self, colorToCheck):#returns a list of enemy pieces threatning the king and the path showing the threat piecesThreatning = [] if(colorToCheck == 'white'): enemyPieces = self.pieceFinder('black') for piece in enemyPieces: if (piece[2] == 'rook'): #When ...
def pieceFinder(self, colorWanted): pieces = [] for row in self.chessMap: for col in row: x, y, color, piece = col.cget('text').split('_') x = int(x) y = int(y) if(colorWanted == color): pieces.append([x, y, ...
This function identifies pieces of a specified color that can move to squares under threat by checking each piece's possible moves against threatening positions. It prioritizes returning the king's position if two threats exist, otherwise iterates through all pieces, calculates valid moves, and collects positions that ...
def moveablePieces(self, color, piecesThreatning):#returns a list of pieces that can attack currently moveable = [] allPieces = None if(color == 'white'): allPieces = self.pieceFinder('white') elif(color == 'black'): allPieces = self.pieceFinder('black') ...
def inCheck(self, colorToCheck):#returns a list of enemy pieces threatning the king and the path showing the threat piecesThreatning = [] if(colorToCheck == 'white'): enemyPieces = self.pieceFinder('black') for piece in enemyPieces: if (piece[2] == 'rook'): #When ...
The function `modified_plan_move` calculates the attack squares a chess piece can move to, considering threats from opposing pieces. It generates valid moves for a given piece type (pawn, rook, etc.), checks if these squares are under attack by the opponent's pieces, and returns the list of threatened squares. For king...
def modified_plan_move(self, x, y, color, piece): attackSquares = [] if(color == 'white'): piecesThreatning = self.inCheck('white') if(piece == 'pawn'): listToEnable = self.plan_pawn_move(x, y, color) attackSquares.append([x,y]) for...
def inCheck(self, colorToCheck):#returns a list of enemy pieces threatning the king and the path showing the threat piecesThreatning = [] if(colorToCheck == 'white'): enemyPieces = self.pieceFinder('black') for piece in enemyPieces: if (piece[2] == 'rook'): #When ...
This function handles a player's turn in a chess game by checking if the player's king is in check, determining valid moveable pieces, assessing checkmate conditions, disabling UI buttons for non-moveable pieces, and updating the interface to indicate whose turn it is.
def checkPlayerTurn(self, player):#resets the board to pieces that are moveable if(player == 1): piecesThreatning = self.inCheck('white') listToEnable = self.moveablePieces('white', piecesThreatning) kx, ky, kColor, kPiece = ChessGame.P1KING.cget('text').split('_') ...
def checkIfCheck(self, colorToCheck): if(colorToCheck == 'white'): kx, ky, kColor, kPiece = ChessGame.P1KING.cget('text').split('_') kx = int(kx) ky = int(ky) piecesThreatning = self.inCheck('white') for pieces in piecesThreatning: if([...
This function handles a chess piece move by updating the board state, logging the move details, checking for check conditions, and managing special cases like pawn promotions. It updates the moved piece's location, marks the original position as empty, and logs the action with user names, piece types, and positions. It...
def executeMove(self, location): currentx, currenty, currentColor, currentPiece = ChessGame.pieceToMove.cget('text').split('_') newx, newy, newColor, newPiece = location.cget('text').split('_') if(currentColor == 'white' and currentPiece == 'king'): ChessGame.P1KING = location ...
def validate_input(self): """ Check to see if a mex with token or user with password was provided. @return True is returned if validation credention was provided else False is returned """ if (self.options.mexURL and self.options.token): # run module through...
The main task of the code is to parse command-line arguments, configure logging, validate input parameters, initialize a BQSession using either local credentials or MEX URL/token, execute setup/run/teardown phases, handle exceptions, and close the session. It ensures proper initialization and execution flow for a modul...
def main(self): parser = optparse.OptionParser() parser.add_option('--mex_url', dest="mexURL") parser.add_option('--module_dir', dest="modulePath") parser.add_option('--staging_path', dest="stagingPath") parser.add_option('--bisque_token', dest="token") parser.add_option(...
def _get_bert_features(self, x, x_feats, x_len, x_chunk_len): self.bert_batch = 8 #print("_get_bert_features()") #print("x", x.shape) input_ids = x[:,0,:,:] token_ids = x[:,1,:,:] attn_mask = x[:,2,:,:] max_seq_len = max(x_len) #print("x_len", x_len.shap...
This function calculates the negative log-likelihood loss for a sequence model using BERT features. It iterates through batches, computes the forward score via _forward_alg and the gold score via _score_sentence, accumulates their difference as loss, then returns the average loss across the batch.
def neg_log_likelihood(self, x, x_feats, x_len, x_chunk_len, y): loss_accum = torch.autograd.Variable(torch.FloatTensor([0])).cuda() feats = self._get_bert_features(x, x_feats, x_len, x_chunk_len) n = 0 #print(x.size(), x_len.size(), feats.size(), y.size()) #print(x_len) ...
def display_welcome_text(menu: str, cmd: str = None, error: str = None, output: str = None) -> None: clear() print("Welcome to the {} menu!".format(menu)) if cmd: display_cmds(cmd) if error: print(error) if output: print(output) def wait_for_valid_command(menu: str, cmd: str ...
The function provides a menu to manage appliances in a network configuration, allowing users to list, add, delete, or quit. It interacts with the network object, validates user input, and returns a success status along with output data or None.
def appliance_menu(network: NetworkConfig, menu: str, appliance_type: str, output: str = None) -> tuple[bool, str]: display_welcome_text(menu=menu, cmd=APPLIANCE_MENU, output=output) cmd = wait_for_valid_command(menu, APPLIANCE_MENU) output = None if cmd == "l": output = list_appliances(network,...
def display_welcome_text(menu: str, cmd: str = None, error: str = None, output: str = None) -> None: clear() print("Welcome to the {} menu!".format(menu)) if cmd: display_cmds(cmd) if error: print(error) if output: print(output) def wait_for_valid_command(menu: str, cmd: str ...
This function manages network link configurations by allowing users to list existing links, create new links between specified appliances, delete existing links, or quit. It validates user inputs, ensures link uniqueness, and updates the network configuration accordingly, returning success status and output messages.
def link_menu(network: NetworkConfig, output: str = None) -> tuple[bool, str]: display_welcome_text(menu="link", cmd=LINK_MENU, output=output) cmd = wait_for_valid_command(menu="link", cmd=LINK_MENU) output = None if cmd == "l": output = list_appliances(network, appliance_type="links") elif ...
def display_welcome_text(menu: str, cmd: str = None, error: str = None, output: str = None) -> None: clear() print("Welcome to the {} menu!".format(menu)) if cmd: display_cmds(cmd) if error: print(error) if output: print(output) def wait_for_valid_command(menu: str, cmd: str ...
The function `config_menu` handles user configuration commands for a network, allowing modification of routers, switches, hosts, or links. It processes commands like 'r', 's', 'h', 'l' to navigate sub-menus, 'w' to save configurations, or 'q' to exit. It returns `False` on exit, `True` otherwise, managing network state...
def config_menu(network: NetworkConfig) -> bool: display_welcome_text(menu="configuration", cmd=CONFIG_MENU) cmd = wait_for_valid_command(menu="configuration", cmd=CONFIG_MENU) output = None stay = True if cmd == "r": while stay: stay, output = appliance_menu(network, "router", "...
def display_cmds(cmds: dict) -> None: print("What would you like to do?") for cmd, desc in cmds.items(): print("{cmd}: {desc}".format(cmd=cmd, desc=desc)) def new_config() -> NetworkConfig: clear() print("Creating new config") print("Please enter the name for the new configuration:") con...
The code defines a function `start_wizard()` that initializes a network configuration tool. It displays a menu, accepts user input, and processes commands to either create a new configuration, load an existing one, or run a loaded configuration. The tool exits if no valid command is entered.
def start_wizard(): print("#################################") print("# Network-Lab Configurator 2000 #") print("# Version: 0.1 #") print("# Type q to exit any menu #") print("#################################") display_cmds(ENTRY_MENU) cmd = input() if len(cmd) ==...
def grad_hernquist_potential( x, y, x_center=1.3, y_center=4.2, Mdm=1e12, a=80, G=1 ): """ Gradient of 2D Hernquist potential with center at (1.3, 4.2). Args: x (float): x coordinate in kpc y (float): y coordinate in kpc Mdm (float, optional): Total mass in solar mass. Defau...
The code implements the Quasi-Newton method with BFGS for minimizing a 2D function. It iteratively updates the position using gradient information, approximates the Hessian matrix, and determines optimal step sizes via golden section search. The algorithm converges when the gradient change falls below a target accuracy...
def quasi_newton(f, gradf, startx, starty, target_acc=1e-6, maxit=1000): """Quasi-Newton methode for finding minimum of 2D function. Function makes use of BFGS methode for updating hessian. Args: f (callabl): Fucntion which has as input an x and y coordinate gradf (callable): Function that...
def string_front_found(string1, string2): if re.search(r"^" + re.escape(string1) + r"\b", string2): return True return False def string_found(string1, string2): if re.search(r"\b" + re.escape(string1) + r"\b", string2): return True return False def get_ingredients_from_ids(cursor, ingred...
This function searches for ingredients in a database based on a search term, categorizing matches into exact matches, prefix matches, substring matches, and general occurrences. It sorts each category by ingredient name and combines results, prioritizing exact matches first, then prefixes, substrings, and general match...
def ingredient_search(cursor, search_term): recipes = [] front_results = [] middle_results = [] back_results = [] all_other_results = [] results = [] result_ids = [] all_rows = cursor.execute("""SELECT rowid, name FROM ingredient""") for row in all_rows: if search_term.lower...
def main(): print("What do you want to do?") print("(S)earch") print("(T)itle Search") print("(I)ngredient Search") print("(Q)uit") selection = input('> ').lower() try: return Method(selection) except ValueError as error: print("Invalid option") return Method.NON...
The main task of the code is to create a command-line interface (CLI) for searching cocktail recipes in a SQLite database. It connects to "cocktailbar.db", loops to accept user input for search methods (general, title, or ingredient), queries the database using provided functions, and displays results. The CLI handles ...
def cli(): try: connection = sqlite3.connect("../cocktailbar.db") cursor = connection.cursor() while(True): print('============================================================') method = main() print() if method == Method.QUIT: ...
def get_car_coord(self, car_pose): car_x = car_pose.position.x car_y = car_pose.position.y return (car_x, car_y) def get_euler(self, pose): o = pose.orientation q = (o.x, o.y, o.z, o.w) return tf.transformations.euler_from_quaternion(q) def get_waypoint_coord(self, waypo...
This code continuously processes the car's pose and waypoints, identifies the closest ahead waypoint, adjusts velocities based on red light detection and smoothing logic, then publishes the modified waypoints for path following.
def loop(self): rate = rospy.Rate(3.8) while not rospy.is_shutdown(): if (self.pose is not None and self.waypoints is not None): car_x, car_y = self.get_car_coord(self.pose) _,_,car_yaw = self.get_euler(self.pose) rospy.loginfo("current pose (%...
def check_number(number: str) -> bool: """Checks the Number to see if contains the Country Code""" return "+" in number or "_" in number def send_message(message: str, receiver: str, coord_x: int, coord_y: int, wait_time: int) -> None: """Parses and Sends the Message""" _web(receiver=receiver, message...
The main task of the code is to schedule and send a WhatsApp message to a specified phone number at a predefined time, with validations for time format and country code, delays to ensure WhatsApp Web loads, logging of the message, and optional tab closure after sending.
def send_wha_msg( phone_no: str, message: str, time_hour: int, time_min: int, coord_x: int, coord_y: int, wait_time: int = 15, tab_close: bool = True, close_time: int = 3, ) -> None: """Send a WhatsApp Message at a Certain Time""" if not check_number(number=phone_no): ...
def compute_allele_num(train_counts,test_tped,rare_snp_set): # Input: # train_counts: the dataframe of .frq.counts file of rare variants in training dataset # test_tped: the dataframe of .tped file of test dataset of rare variants # rare_snp_set: the list consists of indexes of rare variants in which bo...
This function processes genetic data chunks in parallel to compute IBD/non-IBD scores. It retrieves common/rare variant genotypes for two individuals, checks rare SNP frequencies, and applies mode-specific scoring (inner or external). Results are aggregated and returned for each data chunk.
def compute_score_multiprocess(chunk_windows_set,start_index,indi_1_index,indi_2_index,df_geno_common_sub,df_geno_rare_sub, freq_dic,win_rare_dic,rare_frq_counts,rare_tped,mode,arr_empi_IBD_sub,arr_empi_nonIBD_sub,num_bin, epsilon_common,epsilon_rare,num_hap...
def __is_admin(self): if input("Are you an Admin? ('Y'\'N')\n").lower() == 'y': return True else: return False def __admin_selection(self): print("Options:\n- Order Coffee ('coffee')\n- Top up ingredients ('ingredients')\n" + \ "- Generate report ...
This code determines the user's role (admin or customer) and routes them to the corresponding selection method. If the user is an admin, it executes `__admin_selection()`; otherwise, it runs `__customer_selection()`. The primary task is to provide role-based access to different functionalities or interfaces within the ...
def running(self): if self.__is_admin(): self.__admin_selection() else: self.__customer_selection()
def init_args_parser(): parser = argparse.ArgumentParser() parser.add_argument( dest="image_file_path", nargs="?", type=str, help="Image file path." ) parser.add_argument( dest="stdin", nargs="?", type=argparse.FileType("rb"), help="Read image from stdin.", ...
This code converts an image to ASCII art by reading input from stdin or a file, selecting a character set (preset/custom/default), and generating ASCII output. It supports options like black-yellow conversion, single-character replacement, on-screen display, and saving the result.
def main(): args = init_args_parser() if not args.stdin.isatty(): image = read_image_from_stdin(args.stdin.buffer) else: image = read_image_from_path(args.image_file_path) if args.preset: ascii_chars = get_predefined_charset(args.preset) elif args.charset: print(f"U...
def rectangleObj(C1, C2, fill, zValue, stayInFrame=True,collision=False): Xsteps = C2[0] - C1[0] Ysteps = C2[1] - C1[1] if (Xsteps == 0) or (Ysteps == 0): return lineObj(C1, C2, fill, zValue, stayInFrame) Ydir = int(Ysteps / abs(Ysteps)) Xdir = int(Xsteps / abs(Xsteps)) pointArr = [] ...
The code defines a game loop (`gameFrame()`) that manages a LED matrix game. It initializes game objects (shapes, text, lines) with colors, positions, and collision properties, handles user input for movement/rotation, updates game state, and renders objects. Objects collide and stay within bounds, with collision detec...
def gameFrame(): # MAKE YOUR GAME IN THIS FUNCTIONS (will be called every frame) # the object acts as a incompressible / indestructible entity that can translate in space # the object structure is defined as follows # assume the object's origin to be at the origin of cartesian system then make a dictio...
def offscreen_right(self): return self.left_of_ball() >= constants.SCREEN_RIGHT_BORDER def respawn(self): self.hideturtle() self.goto(constants.MIDDLE, constants.MIDDLE) self.showturtle() self.set_random_heading() def offscreen_left(self): return self.right_of_ball() <= c...
This function checks if the object is offscreen on the right or left. If so, it increments the corresponding paddle's score and respawns the object. The main task is handling scoring and respawning when the object moves out of bounds.
def go_offscreen(self, right_paddle, left_paddle): if self.offscreen_right(): right_paddle.scoreboard.increment_score() self.respawn() elif self.offscreen_left(): left_paddle.scoreboard.increment_score() self.respawn()
def __add_max_strenght_properties(self, *varargs:list[list or np.ndarray], cntrl_shear:bool=False): ''' # DESCRIPTION: Internal method to exctract and store the strenght properties # INPUTS: ## Required - *varargs: n block each containing the strenght values of the laminate. The number o...
The `FPF` method verifies a laminate's ply stackup under applied loads (forces, moments) using failure criteria (Tsai-Wu, MaxStress, MaxStrain). It calculates stress distributions, evaluates ply safety margins, and identifies the first failing ply. It computes reserve factors and margins for top, bottom, and average la...
def FPF(self, *varargs:list[list or np.ndarray], N_in:list or np.array, M_in:list or np.array, \ print_stress_state:bool=False, V_in:str or np.array='None', criteria:str='TsaiWu', F12:float or int="-.5/(FxtFxcFytFyc)**.5", \ print_margins:bool=False, cntrl_external_actions:int=0, T_in:int or float=0...
def __round(self, input:float or int, digits:int = 3, lower_limit:float = 1e-22) -> float or int: ''' # DESCRIPTION: this method is used to round the output values. Independetly on the number of zeros the final digits are always the same. e.g. 10.3454 -> 10.34, 1.3454 -> 1.34, 0.0013454 -> 0.00134 # I...
The code initializes a laminate structure by processing input ply data, validating formats, converting units (GPa/MPa), and computing mechanical properties. It extracts ply properties, generates stiffness matrices (Q, Qstar), calculates laminate stiffness matrices (A, B, D, H), and stores attributes like thickness, den...
def __init__(self, *varargs:list[str, list or np.ndarray, list or np.ndarray], mech_prop_units:str='GPa', hide_text:bool=False): ''' # DESCRIPTION: In the init method the single plies are defined and their properties exctracted # INPUTS: ## Required - *varargs: variable number of three-...
def load_tg_dataset(name='communities'): graphs, features, edge_labels = load_graphs(name) return nx_to_tg_data(graphs, features, edge_labels) def deduplicate_edges(edges): edges_new = np.zeros((2,edges.shape[1]//2), dtype=int) # add none self edge j = 0 skip_node = set() # node already put into...
This function loads and preprocesses graph datasets (e.g., Cora, PubMed) from torch_geometric, with caching support. It handles dataset-specific configurations, computes shortest paths, generates link masks, and optionally removes features. If caching is enabled, it loads precomputed data; otherwise, it processes the d...
def get_tg_dataset(args, dataset_name, use_cache=True, remove_feature=False): # "Cora", "CiteSeer" and "PubMed" print('Start getting data') if dataset_name not in ['grid','communities','protein','email','ppi']: if dataset_name in ['Cora','CiteSeer','PubMed']: dataset = tg.datasets.Planet...
def table_exist(self, tbl=None): qry=f"SELECT count(*) FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE='BASE TABLE'" qry=f"{qry} AND TABLE_NAME='{tbl}'" rst = self.execute(qry) if rst[0][0]==0: return False return True def truncate_table(self, tbl=None): qry...
This function checks if a table exists; if it does, it truncates it, otherwise it creates the table using provided parameters.
def create_truncate_table(self, tbl=None, tbl_str=None, distby=None): if self.table_exist(tbl=tbl): return self.truncate_table(tbl=tbl) return self.create_table(tbl=tbl, tbl_str=tbl_str)
def folder_in_243(self, folder=None): dirlist=list(filter(None, folder.split('/'))) tbl=dirlist[0] if not self.table_exist(tbl=tbl): logger.error(f"For dir {folder} under 243, table {tbl} does not exist!!!") return False mydir=f"/mnt{folder}" qry=f"SELECT ...
The function checks if a folder exists in specific database tables (243 and 241). If not in 241, it logs the folder as new and processes it via `new_file_new_dir_243`. If in 241, it queries both tables to count data files, logs results, and returns `new_file_in_243_not_241` for further processing. The task involves val...
def new_file_list(self, folder=None): if not self.folder_in_243(folder=folder): return False, None if not self.folder_in_241(folder=folder): logger.info(f"The dir {folder} is new (not in 241).") return self.new_file_new_dir_243(folder=folder) newfiles=list() ...
def move_u(self) -> bool: front = self._snake[-1] front = (front[0], front[1] + 1) return self._step(front) def move_l(self) -> bool: front = self._snake[-1] front = (front[0] - 1, front[1]) return self._step(front) def move_d(self) -> bool: front = self._snake[-1...
The code defines a `move` method that directs an object's movement based on an integer action input (0-3). It delegates to specific directional methods (`move_u`, `move_l`, `move_d`, `move_r`) corresponding to up, left, down, right. If the action is invalid, it returns `False` to indicate failure.
def move(self, action: int) -> bool: if action == 0: return self.move_u() if action == 1: return self.move_l() if action == 2: return self.move_d() if action == 3: return self.move_r() return False
def posn(self, angle, arm_length): dx = int(math.cos(math.radians(angle)) * arm_length) dy = int(math.sin(math.radians(angle)) * arm_length) return (dx, dy) def _circular(self, r, origin): return (tuple([x - r for x in origin]), tuple([x + r for x in origin])) def _plot_schedule(self, dr...
This function renders a clock display on a given device, showing time, AM/PM indicators, current schedule information, and temperature. It calculates hour/minute/second hand positions, draws circular elements, labels, and plots schedules on an ellipse. The output includes textual elements like schedule name, date, time...
def draw_display(self, device, draw_type, args, temperature, is_debug): with canvas(device) as draw: if draw_type == DrawType.CLOCK: an_lineheight, margin, height_max, cx, base_angle, \ R, sch_plot_R, R_ratio, label_text, \ clock_frame_color, needle_co...
def is_usedup(self): return len(self.active_schedules) == 0 def update_settings(self, day): """ organize yaml settings An item which expected realtime update, describe here istead of __init__ """ with open(self.config_path, "r") as f: params = yaml.load(f) ...
The main task of the code is to continuously monitor and update display information based on schedules and sensor data. It processes active schedules, reads tank temperature using a sensor, and redraws the display whenever time changes. Debug features include memory tracking, schedule logging, and temperature validatio...
def core_process(self, draw_type): if DEBUG: import tracemalloc tracemalloc.start() self.active_schedules = None today_last_time = "Unknown" tank_temp = None args = draw_type.preprocessor() self.logger.debug('check {}'.format(self)) # De...
def get_page_table(self) -> WebElement | None: try: page_table = self.driver.find_element(By.ID, "hosp") self.logger.info(f"getting table tag element for page {self.page}") return page_table except Exception: self.logger.error(f"An error occurred getting...
The main task of the code is to scrape data from multiple pages of a website by repeatedly fetching page tables, extracting information from view buttons, and aggregating structured data (identifiers, locations, contacts, etc.) into a dictionary. The loop continues until all pages are processed or a test condition limi...
def scrape_mh_data(self) -> Dict[str, List[Any]]: while True: page_table = self.get_page_table() page_body = self.get_table_body(page_table) # get all view button along with their associated attributes view_buttons = self.get_page_view_buttons(page_body) ...
def render_world(self): # Stores the blocks to be rendered in a list for y in range(player.pos["y"]+self.render*self.size, player.pos["y"]-(self.render+1)*self.size, -self.size): for x in range(player.pos["x"]-self.render*self.size, player.pos["x"]+(self.render*self.size), self.size): point = f"x{x}y{y}"...
The code initializes a game world with block rendering, handling player movement via keyboard input, and updating the display. It sets up block types, a render range, and initializes the game window with a loading message before entering a loop to process events and maintain the game's frame rate.
def __init__(self, size:int, window:pg.Surface) -> None: clock = pg.time.Clock() running = True self.window = window self.data = {} self.render = 30 # Renders only these many blocks around the player self.blocks = { "stone" : stone.img , "cobblestone": cobblestone.img, "diamondore" : d...
def screenPrint(msg): txt_output.insert(tk.END, f"{msg} \n") txt_output.see("end") def pack(data): global sequenceID packet = Packet.Packet(data) packet.ID = sequenceID sequenceID = not sequenceID return packet def sendPacket(packet, psa): screenPrint(f"--Sending ID: {packet.ID}--") ...
The code handles a TCP three-way handshake by sending a SYN-ACK packet, receiving an ACK response, updating the global ACK variable with the received data, and initiating a timer for connection management. It sets a sequence ID to False, prints diagnostic messages, and manages packet transmission/reception to establish...
def synack(psa): global ACK, sequenceID sequenceID = False screenPrint(f'--SYNACK ID: {sequenceID}') synackPacket = pack(SYN_ACK) sendPacket(synackPacket, psa) ackPacket = receivePacket(synackPacket, psa) ACK = ackPacket.data screenPrint(f"--ACK: {ACK}--") startTimer()
def pack(data): global sequenceID packet = Packet.Packet(data) packet.ID = sequenceID sequenceID = not sequenceID return packet def screenPrint(msg): txt_output.insert(tk.END, f"{msg} \n") txt_output.see("end") def sendPacket(packet, psa): screenPrint(f"--Sending ID: {packet.ID}--") ...
The code transmits a filename by extracting the last segment from a path string, encoding it into a packet, printing a transmission status, and sending/receiving the packet via a specified communication channel (psa).
def transmitFileName(psa): names = filename.get().split('/') namePacket = pack(names[len(names) - 1].encode()) screenPrint("--Transmitting File Name--") sendPacket(namePacket, psa) receivePacket(namePacket, psa)
def screenPrint(msg): txt_output.insert(tk.END, f"{msg} \n") txt_output.see("end") def pack(data): global sequenceID packet = Packet.Packet(data) packet.ID = sequenceID sequenceID = not sequenceID return packet def sendErrorPacket(packet, psa): errorPacket = Packet.Packet(b'\x11\x22\x33...
The main task of the code is to transmit packets from a file data stream, simulating data errors or packet loss based on predefined error modes (DATAERRORSIM/PACKETLOSSSIM), sending corrupted/dropped packets or valid packets accordingly, and waiting for acknowledgments after each transmission. It manages error state tr...
def transmitFile(fileData, psa): global ERRORCLEARED, dataErrors for index, packetData in enumerate(fileData): screenPrint(f"--Transmitting Packet [{index}] of [{len(fileData) - 1}]--") packet = pack(packetData) # Corrupt DATAERROR % of packets if ERRORSIM == DATAERRORSIM and ((...
def screenPrint(msg): txt_output.insert(tk.END, f"{msg} \n") txt_output.see("end") def pack(data): global sequenceID packet = Packet.Packet(data) packet.ID = sequenceID sequenceID = not sequenceID return packet def sendPacket(packet, psa): screenPrint(f"--Sending ID: {packet.ID}--") ...
The code terminates a data transmission by sending an end-of-transmission (EOT) packet, receiving a confirmation packet, calculating the total transmission duration using a start time, and printing both the completion status and elapsed time.
def terminateStream(psa): screenPrint("--File Sent--") eosPacket = pack(END_TRANSMISSION) sendPacket(eosPacket, psa) receivePacket(eosPacket, psa) transmissionTime = time.perf_counter() - startTime screenPrint(f"--Transmission Time: {transmissionTime} seconds--")
def parseErrorField(): global ERRORSIM print(ERRORSELECT.get()) if ERRORSELECT.get() == ERRORLIST[NOERRORSIM]: ERRORSIM = NOERRORSIM elif ERRORSELECT.get() == ERRORLIST[DATAERRORSIM]: ERRORSIM = DATAERRORSIM else: ERRORSIM = PACKETLOSSSIM def screenPrint(msg): txt_output....
The main task of the code is to transmit a selected file from a client to a server by validating inputs, segmenting the file, sending a synchronization signal, transmitting the file name and data packets, and notifying the server of transmission completion while tracking data errors throughout the process.
def sendFile(): global filename, dataErrors parseErrorField() dataErrors = 0 # Ensure that a file has been selected, and the IPs have been input if filename.get() == '': screenPrint("--Please Select A File--") return if clientAddr.get() == '' or serverAddr.get() == '': s...
def check_if_file_exists(document_storage_connstr, translated_container, source_blob_url, target_language, source_language): blob_service_client = BlobServiceClient.from_connection_string(document_storage_connstr) blob_container_client = blob_service_client.get_container_client(translated_container) ...
The main task of the code is to process queue messages containing document translation requests. It logs message details, extracts source/target language and blob URL, checks for existing translations, deletes them if needed, initiates document translation via Azure's DocumentTranslationClient (with optional glossary u...
def main(msg: func.QueueMessage, outputQueueItem: func.Out[str]) -> None: logging.info('Python queue trigger function processed a queue item: %s', msg.get_body().decode('utf-8')) result = json.dumps({ 'id': msg.id, 'body': msg.get_body().decode('utf-8'), 'expiration...
def find_modulus(veclen: int, minimum: int) -> int: if veclen < 1 or minimum < 1: raise ValueError() start: int = (minimum - 1 + veclen - 1) // veclen for i in itertools.count(max(start, 1)): n: int = i * veclen + 1 assert n >= minimum if is_prime(n): return n raise AssertionError("Unreachable") def find...
The function computes a modulus and primitive root based on the input vector's length and minmod, then applies a transformation to the vector using these parameters, returning the transformed vector along with the computed root and modulus.
def find_params_and_transform(invec: List[int], minmod: int) -> Tuple[List[int],int,int]: mod: int = find_modulus(len(invec), minmod) root: int = find_primitive_root(len(invec), mod - 1, mod) return (transform(invec, root, mod), root, mod)
def find_params_and_transform(invec: List[int], minmod: int) -> Tuple[List[int],int,int]: mod: int = find_modulus(len(invec), minmod) root: int = find_primitive_root(len(invec), mod - 1, mod) return (transform(invec, root, mod), root, mod) def transform(invec: List[int], root: int, mod: int) -> List[int]: if len(in...
This function performs circular convolution of two non-negative integer vectors using modular arithmetic. It validates input lengths and values, transforms vectors with a custom algorithm, computes element-wise modular multiplication, then applies an inverse transformation to produce the result.
def circular_convolve(vec0: List[int], vec1: List[int]) -> List[int]: if not (0 < len(vec0) == len(vec1)): raise ValueError() if any((val < 0) for val in itertools.chain(vec0, vec1)): raise ValueError() maxval: int = max(val for val in itertools.chain(vec0, vec1)) minmod: int = maxval**2 * len(vec0) + 1 temp0,...
def create_recipe(): name, ingredients, cooking_time = collect_recipe_details() # Validate inputs if not validate_input(name, max_length=50, alpha=True) or \ not validate_input(cooking_time, numeric=True): print("Invalid input. Please check your recipe details.") return rec...
This code defines a main function for a recipe management system, presenting a menu loop with options to create, view, search, edit, or delete recipes. It processes user input to call corresponding functions, handling "Quit" or "6" to exit, close the database session, and terminate the loop. The primary task is to prov...
def main(): while True: print("\nMain Menu:") print("1. Create Recipe") print("2. View All Recipes") print("3. Search Recipes by Ingredients") print("4. Edit Recipe") print("5. Delete Recipe") print("6. Quit") choice = input("Enter your choice...
def visualize_tour(tour, style='bo-'): if len(tour) > 1000: plt.figure(figsize=(15, 10)) start = tour[0:1] visualize_segment(tour + start, style) visualize_segment(start, 'rD') def name(algorithm): return algorithm.__name__.replace('_tsp', '') def distance_tour(aTour): return sum(distance_points(aTo...
The code evaluates a Traveling Salesman Problem (TSP) algorithm by executing it on a list of cities, verifying the solution's validity (all cities visited once), visualizing the tour, and printing metrics: algorithm name, number of cities, tour length, and execution time.
def tsp(algorithm, cities): t0 = perf_counter() tour = algorithm(cities) t1 = perf_counter() assert Counter(tour) == Counter(cities) # Every city appears exactly once in tour visualize_tour(tour) print("{}: {} cities --> tour length {:.0f} (in {:.3f} sec)".format(name(algorithm), len(tour), dis...
def visualize_tour(tour, style='bo-'): if len(tour) > 1000: plt.figure(figsize=(15, 10)) start = tour[0:1] visualize_segment(tour + start, style) visualize_segment(start, 'rD') def name(algorithm): return algorithm.__name__.replace('_tsp', '') def distance_tour(aTour): return sum(distance_points(aTo...
The code defines a function `tsp` that executes a given traveling salesman problem (TSP) algorithm on a list of cities, measures its runtime, validates the tour's correctness (all cities visited once), visualizes the tour, and prints the algorithm's name, number of cities, tour length, and execution time in a formatted...
def tsp(algorithm, cities): t0 = perf_counter() tour = algorithm(cities) t1 = perf_counter() assert Counter(tour) == Counter(cities) # Every city appears exactly once in tour visualize_tour(tour) print("{}: {} cities --> tour length {:.0f} (in {:.3f} sec)".format(name(algorithm), len(tour), dis...
def _draw_sample(self): """Draw a random sample from the configuration space Returns: ndarray: Sampled coordinates, size (2,). """ sample = np.random.random_sample(2)*10 return sample def _is_close(self,p, threshold): test = sum([np.linalg.norm(p - t) <= thres...
The main task of the code is to generate a graph with 80 nodes by randomly sampling positions while ensuring nodes are sufficiently spaced and non-overlapping. It constructs an adjacency matrix (`self.graph`) where distances between connected nodes are stored, applying constraints to avoid excessive connections and mai...
def create_graph(self): """Create the nodes and connections in the graph. Fills out the class attributes self.nodes and self.graph with the corresponding values. """ # FIXME do something with seed np.random.seed(4) amount = 80 closeness_threshold = 0.8 i =...
def get_parameter(ssm_client, **kwargs): return ssm_client.get_parameter(**kwargs) def get_number_of_pending_and_running_jobs(token): pending_job_ids, running_job_ids = get_all_pending_and_running_job_ids(token) return len(pending_job_ids), len(running_job_ids) def get_asg_healthy_instances_in_service(asg_c...
The code retrieves a secure token from AWS SSM, fetches pending/running job counts, calculates runner load based on healthy ASG instances, and publishes metrics to CloudWatch. It logs job statistics and overall runner load for monitoring, using parameters like tags and runners per instance to contextualize data.
def handler(event, context): ssm_client = boto3.client('ssm', region_name=REGION) result = get_parameter(ssm_client, Name=TOKEN_SSM_PATH, WithDecryption=True) token = result['Parameter']['Value'] pending_jobs, running_jobs = get_number_of_pending_and_running_jobs(token) tag_log = " with {} {}".form...
def _mark_sinks(topo): """ Marks sink areas in a DEM. Parameters ---------- topo : numpy array Eelvation data Returns ------- sink : numpy array Bool array. True value indicate cell is (in) a sink. """ # compute the slopes in every direction at each cell slope...
The function `fill_sinks` fills depressions (sinks) in a Digital Elevation Model (DEM) by iteratively setting each sink's elevation to the minimum value of its adjacent higher neighbors. It operates on a copy of the input array unless specified otherwise. Sinks are identified, and their elevations are adjusted recursiv...
def fill_sinks(topo, copy=True): """ Fills sink areas in a DEM with the lowest adjacent elevation. Parameters ---------- topo : numpy array Elevation data copy : bool, optional When True, operates on a copy of the `topo` array. Set to False if memory is a concern. Retur...
def get_bcp_properties( data: list[str], atPair: list[str] = ["C1", "H2"] ): # pylint:disable=dangerous-default-value """Get BCP Properties for BCP between two atoms in list Args: data: lines of a .sum file atPair: list of atom labels for which to find BCP, e.g. ['C1','H2'] Returns: ...
The function extracts BCP (bond critical point) properties from molecular data based on specified atomic pairs. It processes input data, adjusts indices for zero-based lists, retrieves BCP properties, calculates distances between atomic coordinates and BCP positions, and compiles results into a nested dictionary. The o...
def extract_requested_bcp_props( data: list[str], atomList: list[str], bcpId: list[list[int]], subatomLabels: list[str], atomicProps: dict, ) -> dict: """Get BCP dict for requested bcps Args: data: lines of .sum file atomList: list of atom labels in molecule. e.g. ['C1','H2'...
def _find_bcp_match(data, originAtomXYZ, negXAtomLabel, originAtomLabel, atomDict): """ Finds the atoms connected to the origin atom, and arranges the BCPs in a clockwise sense (assuming -x atom going into page) Args: data: the lines of a .sum file stored as a list originAtomXYZ - np.ar...
This function identifies a molecular position (posYPoint) aligned with the positive y-axis. It processes vscc (valence shell charge concentration) data, averaging coordinates when multiple entries exist, or uses BCP (bond critical point) matching for reorientation. Logic varies based on vscc count and attached atom typ...
def _get_posy_point_aiida( data, cc_dict, atomDict, attachedAtom, negXAtomLabel, default_stats=True ): # pylint:disable=too-many-arguments # ccProps = qt.get_cc_props(FolderData,attachedAtom,is_folder_data=True) for key in list(cc_dict.keys()): keynum = int("".join(filter(str.isdigit, key))) ...
def _find_bcp_match(data, originAtomXYZ, negXAtomLabel, originAtomLabel, atomDict): """ Finds the atoms connected to the origin atom, and arranges the BCPs in a clockwise sense (assuming -x atom going into page) Args: data: the lines of a .sum file stored as a list originAtomXYZ - np.ar...
This function calculates a point on the +y axis for molecular orientation by analyzing valence shell charge concentrations (vscc) and bond critical points (bcp). It prioritizes vscc data, averages coordinates for dual vscc entries, and defaults to bcp matching against reference structures when vscc is insufficient. The...
def _get_posy_point( sumFileNoExt, atomDict, attachedAtom, negXAtomLabel, default_stats=True ): """returns point to put on +y axis matching definition in rotate_substituent.""" ccProps = qt.get_cc_props(sumFileNoExt, attachedAtom) if len(ccProps) > 0: vscc = qt.identify_vscc(ccProps, atomDict, a...
def _get_posy_point_aiida( data, cc_dict, atomDict, attachedAtom, negXAtomLabel, default_stats=True ): # pylint:disable=too-many-arguments # ccProps = qt.get_cc_props(FolderData,attachedAtom,is_folder_data=True) for key in list(cc_dict.keys()): keynum = int("".join(filter(str.isdigit, key))) ...
The function `rotate_substituent_aiida` rotates a molecular substituent into a defined coordinate system by aligning specified atoms to the origin, negative x-axis, and positive y-axis. It processes a `.sum` file, adjusts coordinates using helper functions, and returns rotated 3D coordinates (as a 3xN array) and atomic...
def rotate_substituent_aiida( sum_file_folder, atom_dict, cc_dict, originAtom=1, negXAtom=2, posYAtom=0 ): # pylint:disable=too-many-arguments """ Rotates a substituent to the defined coordinate system. Args: sum_file_folder (aiida FolderData): FolderData object containing .sum file ...
def _get_posy_point( sumFileNoExt, atomDict, attachedAtom, negXAtomLabel, default_stats=True ): """returns point to put on +y axis matching definition in rotate_substituent.""" ccProps = qt.get_cc_props(sumFileNoExt, attachedAtom) if len(ccProps) > 0: vscc = qt.identify_vscc(ccProps, atomDict, a...
The function reorients a molecule's geometry by aligning specified atoms to a coordinate system: placing `originAtom` at (0,0,0), `negXAtom` along the -x axis, and determining the +y axis via lone pair or BCP analysis. It processes a sum file, computes transformations, and returns the adjusted coordinates in a pandas D...
def rotate_substituent(sumFileNoExt, originAtom, negXAtom, posYAtom=0): """ Rotates a substituent to the defined coordinate system. Args: sumFileNoExt (string): name of a sum file, without the .sum extension originAtom (int): the integer number of the atom to place at the origin neg...
def _get_table( data: list[str], tableHeader: str, ignored: int = 0, endString: str = "Total" ) -> pd.DataFrame: """Given lines of sum file and table header, return pandas dataframe of requested table Args: data: lines of sum file tableHeader: string containing non-atom columns of table to ...
The function `extract_sub_props` processes a `.sum` file's data to extract and organize chemical properties (atomic, BCP, group, VSCC) into a nested dictionary. It uses atom indices to determine group properties, BCPs between specified atoms, and VSCC values for selected atoms. Results are structured under keys 'Group'...
def extract_sub_props( data: list[str], subAtoms: list[int], sumFileNoExt: str, groupProps: bool = True, bcpId=[[1, 2]], lapRhoCpAtoms=[], ): # pylint:disable=dangerous-default-value # pylint:disable=too-many-arguments """returns a dictionary of all group properties - bcp, group, atomic...
def write_log(data): now = datetime.datetime.now() timestamp = now.strftime("%Y-%m-%d %H:%M:%S") write = f"echo -e \"{data}: {timestamp} \n\" >> {logdir}" os.system(write) def check_keys(): valid = 0 rand = int(random.randint(1, 4)) key_depth = int(key_max / rand) test_depth = int(rand...
The main task of the code is to test encryption and decryption functionality by creating a temporary plaintext file, encrypting it, decrypting it, and verifying the decrypted data matches the original. It handles file operations, error checking, and ensures proper cleanup by removing test files upon success or failure.
def write_test(): plain_test_path = "/tmp/encore-test.dec" enc_test_path = "/tmp/encore-test.enc" command = f"echo \"This is some data\" > {plain_test_path}" write_log(command) os.system(command) if os.path.exists(plain_test_path) == True: print("Test data written to:", plain_test_path) ...
def _validate_names_arg(self, names): """Utility method to validate and set default value of the `names` argument used in most methods""" if names is None: names = not self.is_nparray if names: self.assert_names_available() return names...
The main task of the code is to generate a list of string representations of trees in a forest structure, with options to include single-node trees and use node names or indices for traversal. It constructs indented tree visualizations by recursively walking through nodes, formatting each level with appropriate indenta...
def get_trees_str_list(self, all=False, names=None # type: bool ): """ Returns a list of string representation of the various trees in this forest TODO maybe use https://github.com/caesar0301/treelib ? Or networkX ...
def _validate_names_arg(self, names): """Utility method to validate and set default value of the `names` argument used in most methods""" if names is None: names = not self.is_nparray if names: self.assert_names_available() return names...
The `to_str` method generates a string representation of a forest structure (QDForest) with varying levels of detail based on the `mode` parameter. It returns a compact summary, detailed headers, or full tree structures, using parameters like `names` (to use names instead of indices) and `mode` ("compact", "headers", o...
def to_str(self, names=None, # type: bool mode="headers" # type: str ): """ Provides a string representation of this forest. :param names: an optional boolean indicating if this method should return names instead of indices. By default ...
def db_connection(): try: conn = sqlite3.connect('sys.db') except sqlite3.error as e: print(e) return conn def insert_users(role, first_name, middle_initial, last_name, street_number, street_name, apt_number, city, province, postal_code, SSN, email, gender): conn = db_connection() c ...
The main task of the code is to insert a new patient's information into a database by first creating a user entry and then adding patient-specific details. It connects to the database, inserts user data via `insert_users`, handles potential errors, and inserts patient data including insurance, birth date, and age. Fina...
def insert_pat(insurance, date_of_birth, age, role, first_name, middle_initial, last_name, street_number, street_name, apt_number, city, province, postal_code, SSN, email, gender): conn = db_connection() c = conn.cursor() entry = insert_users(role, first_name, middle_initial, last_name, street_number, stree...
def db_connection(): try: conn = sqlite3.connect('sys.db') except sqlite3.error as e: print(e) return conn def insert_users(role, first_name, middle_initial, last_name, street_number, street_name, apt_number, city, province, postal_code, SSN, email, gender): conn = db_connection() c ...
The main task of the code is to insert a guardian record into the 'guardian' table, linking the guardian to a user via the user's ID. It first inserts a user (if not already existing) using `insert_users`, then inserts the guardian details. If the user already exists, it retrieves their ID and inserts the guardian reco...
def insert_guard(insurance, date_of_birth, age, looks_over, role, first_name, middle_initial, last_name, street_number, street_name, apt_number, city, province, postal_code, SSN, email, gender): conn = db_connection() c = conn.cursor() entry = insert_users(role, first_name, middle_initial, last_name, street...
def db_connection(): try: conn = sqlite3.connect('sys.db') except sqlite3.error as e: print(e) return conn def insert_users(role, first_name, middle_initial, last_name, street_number, street_name, apt_number, city, province, postal_code, SSN, email, gender): conn = db_connection() c ...
The function inserts a new employee into the database by first inserting user details (role, name, address, etc.) into the "users" table and then inserting the employee's type, salary, and branch ID into the "employee" table. It handles errors by returning messages if insertions fail. For receptionists ("recep"), it as...
def insert_emp(emp_type, salary, branch_ID, role, first_name, middle_initial, last_name, street_number, street_name, apt_number, city, province, postal_code, SSN, email, gender): conn = db_connection() c = conn.cursor() entry = insert_users(role, first_name, middle_initial, last_name, street_number, street_...
def _read_file(self): file = open("0.txt", "r") choose = random.randint(1, 2) if self._mode == 'E': if choose == 2: file.close() file = open("1.txt", "r") elif self._mode == 'M': file.close() if choose == 1: ...
The main task of the code is to generate a valid game configuration by repeatedly restarting and backtracking until a solvable state is achieved, then displaying the player's grid and the game grid. It uses deep copying, backtracking validation, and restarts to ensure solvability before outputting the final grids.
def create_game(self): self._read_file() self.player_grid = copy.deepcopy(self._grids) condition = self._backtrack() while not condition: self._start_over() self._read_file() condition = self._backtrack() self.player_print() print('') ...
def __update_image_selection(self, directory): self.current_image_path = directory self.current_gui_image = ImageTk.PhotoImage( Image.open(self.current_image_path).resize(self.image_dim) ) self.image_label.configure(image=self.current_gui_image) self.image_label.Image = self.current_gui_...
The code updates the image selection and plot based on a given class/selection. It retrieves the image directory using the selection name, updates the image selection, and then refreshes the plot to reflect the new selection. This method is likely triggered by a button click to switch between different image classes or...
def select_class_button_f(self, selection): self.__update_image_selection(get_image_dir(name=selection)) self.__update_plot()
def make_entry(self, message): """ Make an entry in the cache df using new message """ msg = {"Received Times": message["Received Times"], "Detector": message["detector_name"]} stamped_time_obj = self.times.str_to_datetime(message["sent_time"], fmt="%y/%m/%d %H:%M:%S:%f") msg["St...
The code subscribes to a heartbeat topic, processes incoming messages by validating their format, timestamps valid heartbeat messages, updates entries, cleans old data, performs checks, and displays results. It ignores non-heartbeat messages and handles interruptions gracefully.
def subscribe(self): """ Subscribe and listen heartbeats """ # Initiate hop_stream stream = Stream(until_eos=False) try: with stream.open(self.heartbeat_topic, "r") as s: print("wait please") for message in s: print(...
def isComplete(self): #check for completed assignment if(self.isSolved): return True for rowi in range(height): for coli in range(width): if(self.assignment[rowi][coli] == 0): #if anything is unassigned, not complete return False self.isSolved = True #else is comple...
The code implements a backtracking algorithm to solve a constraint satisfaction problem (CSP). It recursively assigns values to unassigned variables, checking consistency with the current assignment. If a valid assignment is found (via `isComplete()`), it returns the solution. If not, it backtracks by resetting the var...
def findSolution(self): #check if assignment complete if self.isComplete(): return self.assignment currVar = self.selectUnassignedVariable() #get next unassigned variable # print(currVar[0], ",", currVar[1], end="\r", flush=True) for val in self.domain[currVar[0]][currVar[1]]:#for each value...
def createStates(filepath): #create 2D matrices for initial state and goal state from file state = [[]] #initial state matrix with open(filepath, 'r') as fp: char = '' #keeping track of number row = 0 #keeping track of matrix row for c in fp.read(): if c.isnumeric(): char += c elif c...
The code's main task is to solve a Constraint Satisfaction Problem (CSP) using backtracking. It reads input files containing initial and goal states, initializes a CSP with domains and assignments, and employs a backtracking algorithm to find a valid solution. If a solution is found, it is printed; otherwise, a "no sol...
def main(): root = None #user input for filenames filepath = "" while True: filepath = input("Enter filepath for input file. Enter EXIT to end code: ") if filepath == "EXIT": print("Goodbye :)") exit(0) try: root = createStates(filepath) #read in initial and goal states ...
def rekonstruksiImage(img): img2=repairWithClahe(img) face_bounding_boxes = face_recognition.face_locations(img2) if len(face_bounding_boxes)==0: img2=repairRotation(img) face_bounding_boxes = face_recognition.face_locations(img2) if len(face_bounding_boxes)==0: img2=i...
The main task of the code is to extract and align faces from an image. It detects faces using face_recognition, resizes them, and applies alignment via an API if enabled. If no faces are detected initially, it attempts reconstruction. If alignment fails, it uses MTCNN as an alternative. The function returns an array of...
def extract_face_from_image(image_path, required_size=(224, 224),needAlign=True): # load image and detect faces noFace=True face_images = [] img = plt.imread(image_path) face_bounding_boxes = face_recognition.face_locations(img) if len(face_bounding_boxes)==0: print("wajah tidak terdete...
def extract_face_from_image(image_path, required_size=(224, 224),needAlign=True): # load image and detect faces noFace=True face_images = [] img = plt.imread(image_path) face_bounding_boxes = face_recognition.face_locations(img) if len(face_bounding_boxes)==0: print("wajah tidak terdete...
The main task of the code is to detect faces in images from a specified directory, compare them using either face encodings (if `fr=True`) or cosine similarity scores (if `fr=False`), identify matching faces, and return the top 3 most similar unique faces along with their filenames. It processes each image, extracts fa...
def loadImageDetectFace(path, fr=False): ftr,nmFiles,idImgs,scoreFace,idNumber =[],[],[],[],0 for nmFile in os.listdir(path): print("nmFile ...." + nmFile) image_path = path+"/"+nmFile extracted_face = extract_face_from_image(image_path, ...
def get_slack_data(date): cursor = True request_body = { "channel": SLACK_CHANNEL, "latest": generate_timestamp(date + timedelta(days=1)), "oldest": generate_timestamp((date)), "limit": 200, } messages = [] while cursor: response = requests.get( "h...
The code generates a cache by retrieving Slack data for the current date and the previous `lookback` days, parsing and saving user data for each date. It initializes the current date at midnight, iterates backward through each day, fetches data, processes it, and stores it for historical analysis or storage.
def generate_cache(lookback): current_date = datetime.now().replace(hour=0, minute=0, second=0, microsecond=0) for counter in range(lookback + 1): date = current_date - timedelta(days=counter) data = get_slack_data(date) parse_save_user_data(data, date) save_data(data, date)
def fetch_events(self, page=1): self.log.info(f"Fetching events page:{page}") resp = requests.get( f"https://api.github.com/orgs/{self.org}/events?per_page=100&page={page}", headers=self.headers, ) if resp.status_code == 422: self.log.warning("Last pag...
The code scrapes data for an organization by fetching events, merge events, and open pull requests from multiple users, handling exceptions during data retrieval. It logs progress and errors, then compiles the results into `self.data` for return.
def scrape(self): self.log.info(f"Scraping {self.org}") self.fetch_events(1) self.log.info(f"Scraping open pull requests for {len(self.data)} users") for user in self.data.keys(): try: self.fetch_merge_events(user) except Exception as e: ...
def parse_rules(self, raw_data): """Parse Packets based on rules Args: raw_data (str): Raw Packets Returns: allow/discard: Allow or discard packets """ start = time.process_time() self.parse_L2(raw_data) allowed = False # Curren...
This code filters network packets using MAC address rules, modifies packet headers based on source/destination MACs, tracks allowed/discarded packets, and logs detailed packet information. It continuously monitors internal/external sockets, applies filtering logic, and forwards packets accordingly while maintaining per...
def run(self, internal_MAC, external_MAC): """Runner to take packets and filter based on rules""" clock = time.time() while True: try: all_socks = [self.internal_socket, self.external_socket] interface_sockets, _, _ = select.select(all_socks, [], []...
def convert_to_date_type(date: str): ''' date string to _date type ''' return datetime.strptime(date, '%Y-%m-%d').date() def prepare_data(dateKey: str, mealKey: str, start_date: str, end_date: str): ''' This is the place where major operations are being done\n dateKey: to get the Day ids\n ...
The code's main task is to retrieve and display users categorized by a specified type (`active`, `superactive`, or `bored`) within a given date range. It validates that the `start_date` is earlier than `end_date`, prepares user data, filters users by type, and outputs the result. If dates are invalid, it raises an erro...
def run( user_type: str = typer.Argument("active", help="active or superactive or bored"), start_date: str = typer.Argument("2016-09-01", help="Prefered format: YYYY-MM-DD"), end_date: str = typer.Argument("2016-09-08", help="Prefered format: YYYY-MM-DD") ): #run function code starts from here ...
def generate_result(input_data, executable=Path("python/cbtw.py")): p = Popen([executable], stdout=PIPE, stdin=PIPE, stderr=PIPE) output_json = p.communicate(input=input_data)[0] return json.loads(output_json) def compute_money(data, attributions): consultants = data["consultants"] missions = data["...
The code tests a deterministic solution for assigning consultants to missions, ensuring it outperforms a naive approach in total earnings while preventing consultants from handling multiple missions. It reads input data, computes results, compares earnings against a naive method, and validates constraints. Your return
def test_deterministic_solution(input_file): with open(input_file) as fd: content = fd.read() input_data = json.loads(content) output = generate_result(content.encode()) solution_money = compute_money(input_data, output) naive_solution = get_naive_matches( input_data["consultants"], ...
def input_data_generator(consultant_nb=10, mission_nb=10): return { "consultants": list(consultant_generator(consultant_nb)), "missions": list(mission_generator(mission_nb)), } def generate_result(input_data, executable=Path("python/cbtw.py")): p = Popen([executable], stdout=PIPE, stdin=PIPE...
This function tests the optimality of a solution against a naive approach by generating random input data, computing the solution's monetary value, and comparing it to a naive solution's value. It ensures the solution is at least as profitable as the naive method and validates that consultants are not assigned to multi...
def test_random_inputs(execution_number): input_data = input_data_generator(randint(1, 50), randint(1, 50)) content = json.dumps(input_data) output = generate_result(content.encode()) solution_money = compute_money(input_data, output) naive_solution = get_naive_matches( input_data["consultan...
def rankRoutes(self, currentGen): fitnessResults = {} for i in range(0, len(currentGen)): fitnessResults[i] = self.routeFitness(currentGen[i]) sorteds = sorted(fitnessResults.items(), key = operator.itemgetter(1), reverse=True) # print(sorteds) return sorteds def selection(self, popRanked): selectionResu...
The code evolves a population in a genetic algorithm by ranking current individuals, selecting the fittest, creating a mating pool, breeding offspring, and applying mutations to generate the next generation.
def nextGeneration(self, currentGen): popRanked = self.rankRoutes(currentGen) selectionResults = self.selection(popRanked) matingpool = self.matingPool(currentGen, selectionResults) children = self.breedPopulation(matingpool) nextGeneration = self.mutatePopulation(children) return nextGeneration
def initialPopulation(self, populations): population = [] for i in range(0, self.popSize): population.append(self.createRoute(populations)) return population def nextGeneration(self, currentGen): popRanked = self.rankRoutes(currentGen) selectionResults = self.selection(popRanked) matingpool = self.matin...
The code implements a genetic algorithm to find the optimal route through a set of locations. It evolves a population over generations, selects the best route, geocodes locations to extract coordinates and IDs, calculates distances between consecutive points, and compiles results into a structured dictionary with route...
def geneticAlgorithm(self): start_time = time.time() lat = [] lng = [] place_id = [] population = self.population[1:len(self.population)] pops = self.initialPopulation(population) for i in range(0, self.generations): pops = self.nextGeneration(pops) final_distance = float(1/self.rankRoutes(pops)[0][1...
def get_regions_from_content_xml(content_xml, region_type='version'): '''content_xml a lxml etree node for the text For each region of type region_type, yields { 'xml': the xml element for that region, 'text': the plain text content of that region, 'sentence': the sentence number/cod...
The main task of the code is to process a list of manuscript IDs (text_ids) by replacing vregions in their parent versions with the corresponding content from each manuscript. It then invokes a callback function (ms_wreading_callback) for each wregion in the modified parent version, passing the updated region data alon...
def parse_mss_wregions(text_ids, ms_wreading_callback): ''' text_ids: a list of mss ids (AbstractedText) wregions_callback: a callback with the signature: (region_data, version_siglum, ms_siglum, ms_index) region_data = see get_regions_from_content_xml() For each MS in text_ids, the callba...
def add_house(self): if self.last_house_top and self.screen.get_rect().contains(self.last_house_top): delivery = self.houses_since_delivery >= Game.DELIVERY_FREQUENCY # Time for another delivery # Randomly determine if the delivery is at top or bottom rand_num = random.randi...
The code runs the main game loop, handling events like quitting, adding cars, scoring, and collisions. It updates sprites, checks for player-car/house collisions, manages game states (e.g., game over, restart), and renders the game screen. The loop processes input, updates game objects, detects collisions, handles deli...
def run_game_loop(self): collide_did_occur_car = False collide_did_occur_house = False running = True while running: # Add another house once the previous one is fully on the screen self.add_house() # Process events for event in pygame....
def start_time(): global current current = current_ms() def init_global(): # global callsite_cache callsite_cache.clear() function_cache.clear() extern_func_required.clear() def stop_time(msg): global current delta = current_ms() - current print("[%dms] %s" % (delta, msg)) curren...
The code analyzes a binary to generate a control flow graph (CFG), identifies functions that make system calls, and returns related data. It loads or creates the CFG using angr, processes syscall locations, extracts export functions, builds a call graph, and determines functions with syscalls, returning instructions, s...
def loadCfg(binary_path, binary_name): start_time() init_global() insn, base_addr = syscalls.init(binary_path) stop_time("Syscall Init") addrs = syscalls.find_syscall_locations(insn) stop_time("Syscall locations") sys_addrs = [x for x in addrs] try: if binary_name in cfg_name...
def processLib(binary_path, output_path): print("processing lib", binary_path) binary_name = binary_path.split("/")[-1] insn, addrs, syscaller = loadCfg(binary_path, binary_name) insn_to_syscall = {} used_syscalls = {} for fnc in syscaller: insn_list = set() for sysc in syscalle...
The function analyzes a binary executable to identify and record system calls (syscalls) used by specific external functions. It loads the binary with angr, processes required functions from input files, maps each function to its associated syscalls by checking loaded libraries, and outputs the results as a sorted JSON...
def processExe(binary_path, output_path, required): processLib(binary_path, output_path[:-5] + "-all.json") binary_name = binary_path.split("/")[-1] start_time() init_global() try: program = angr.Project(binary_path, load_options={"auto_load_libs": False}) except: print("...
def processLib(binary_path, output_path): print("processing lib", binary_path) binary_name = binary_path.split("/")[-1] insn, addrs, syscaller = loadCfg(binary_path, binary_name) insn_to_syscall = {} used_syscalls = {} for fnc in syscaller: insn_list = set() for sysc in syscalle...
The code recursively processes a binary and its dependent shared libraries, generating JSON outputs in the specified directory. It avoids reprocessing by tracking solved libraries and ignoring certain binaries. It uses `ldd` to resolve dependencies, creates output directories, and recursively calls itself for each shar...
def processAll(binary_path, output_path, required): binary_name = binary_path.split("/")[-1] if binary_name in solved_librays or binary_name in ignore_set: return solved_librays.add(binary_name) needed = os.popen("ldd "+binary_path) neededso = re.findall(r'[>](.*?)[(]', needed.read()) al...
def RecursionChild(parentobj,nodes): for child in parentobj: # print(child.id) data = [child.id,child.parent.id,1,child.name,False] nodes.append(data) if child.childs.all().count()>0: RecursionChild(child.childs.all(),nodes) def Children(nodes, rq): rlt = [] for i...
The code handles AJAX requests for dynamic tree operations (open, search, add, copy, move). It retrieves navigation nodes from the database, recursively builds a hierarchical tree structure, and prepares JSON responses based on the command. The function processes request parameters, constructs node data, and returns st...
def TreeAjax(request): nodes = [] root_obj = Navigation.objects.filter(parent_id= None) for root in root_obj: children = root.childs.all() RecursionChild(children,nodes) # while children.count()>0: # for chil in children: # print(chil) # ...
def weight(self): orderWeight = 0 for item in self._lineItems: orderWeight += item.amount return orderWeight def sales(self): orderSales = 0 for item in self._lineItems: orderSales += item.total return orderSales def tax(self): return self....
This code generates a formatted string representation of an order, displaying address, shipping method, itemized line items, weight, sales total, taxes, shipping cost, and overall total. It constructs a structured output with headers, item listings, and summary calculations for readability.
def __str__(self): string = f'address: \n{self._address} \n\nshipping: \n{self._shippingMethod}\n\n' string += ' Item Cost Quantity Total\n' string += '--------------------------------------------------------------------------' if self._li...
def build_tree(data): pqueue = build_queue(data) if not pqueue: return None # From the queue, build the tree until the tree is the only node left while pqueue.get_size() > 1: # Removes first and second node and saves it left_child = pqueue.pop() right_child = ...
The main task of the code is to test Huffman encoding and decoding by displaying the original data size/content, encoded data size/content, and decoded data size/content. It validates the compression/decompression process and checks data integrity while handling edge cases like empty input, integers, or null values.
def test_huffman(data): if data == "" or type(data) == int or data == None: return tree_code = build_tree(data) # Build the tree # Original string info print ("The size of the data is:", format(sys.getsizeof(data))) print ("The content of the data is: {}\n".format(data)) encoded_huf...
def screen_animation(type='OUT', color_from=BACKGROUND, color_target=BLACK): animation_in = [ Button_round(text='', btn_color=(color_target[0]*0.10, color_target[1]*0.10, color_target[2]*0.10), btn_size=(WIDTH*0.05, HEIGHT*0.05)), Button_round(text='', btn_color=(color_target[0]*0.15, color_target[1...
This code displays an informational screen with game rules and instructions, including a title, text lines, and an "Okay" button. It handles user interaction to proceed to the next step (setting players) when the button is clicked, using animations, text rendering, and event handling.
def info(): pg.display.flip() screen_animation(type='IN', color_target=BLUE) SCREEN.fill(BACKGROUND) second = 0 game_info = Button(font_family=roboto_regular, btn_color=BLUE, btn_size=[WIDTH*0.90, HEIGHT*0.90], text='') title = Text(font_family=roboto_light_italic, size=50,color=WHITE, text='Sa...
def screen_animation(type='OUT', color_from=BACKGROUND, color_target=BLACK): animation_in = [ Button_round(text='', btn_color=(color_target[0]*0.10, color_target[1]*0.10, color_target[2]*0.10), btn_size=(WIDTH*0.05, HEIGHT*0.05)), Button_round(text='', btn_color=(color_target[0]*0.15, color_target[1...
The main task of the code is to perform a pre-game animation sequence with color transitions and countdown text, followed by initializing game rounds for each player and checking the winner. It animates the screen for a specified duration, updates visual elements, and triggers game mechanics via the Sapien function for...
def pre_game(seconds_animation=3): target_screen = (BLUE, BLACK, (119,136,153), WHITE) letters = (WHITE, BLACK, BLACK) for i in range(seconds_animation): screen_animation(color_from=target_screen[i], color_target=target_screen[i+1]) pg_blit( Text(text=str(-i+3), font_family=permanentmarker,...
def pg_blit(to_blit): text = pg.font.Font(to_blit.font_family, to_blit.size).render(to_blit.text, True, to_blit.color) text_rect = text.get_rect(center=(to_blit.x_axis, to_blit.y_axis)) # IF ITS A TEXT, IT WILL ONLY BLIT TEXT if type(to_blit) == Text: return SCREEN.blit(text, text_rect) elif...
The main task of the code is to display a main menu screen with a welcome message, "New Game" and "Quit Game" buttons, handling user interactions to either start the game (via info() function) or exit the application, using Pygame for rendering and event management.
def main_screen(): SCREEN.fill(BACKGROUND) welcome = Text(text='Sapien', font_family=permanentmarker, size=140, color=BLUE, y_ax=position_y_quarter1) game_btn = Button(text='New Game', color=BLACK, btn_color=GREEN, x_ax=position_x_quarter1, y_ax=position_y_quarter3) quit_btn = Button(text='Quit Game', c...
def superUser(self, faker): try: User.objects.create_superuser( 'admin', faker.email(), 'A', 'admin') self.stdout.write(self.style.SUCCESS( 'Superuser created successfully')) except: self.stdout.write(self.style.WARNING( ...
This code generates fake data for a sports application using Faker, creating a superuser, teams, coaches, players, and match statistics to populate a database for testing or development purposes.
def handle(self, *args, **kwargs): faker = Faker() # Create superuser with admin role self.superUser(faker) # Create team data self.createTeamData(faker) teams = Team.objects.all() # Create coaches self.createCoaches(teams, faker) # Create pla...
def get1GramsProb(self, discount): N1GramCounts = self.getNGrams(1) Z = len(self.corpus.tokens) + self.smoothing * len(self.corpus.vocab) unigrams = dict(map(lambda kv: (kv[0], (kv[1] - discount)/ Z), N1GramCounts.items())) return unigrams def getNGrams(self, N): NGramCounts = di...
The code computes backoff probabilities for N-grams by combining discounted probabilities and backoff weights. For N=1, it returns discounted unigram probabilities. For higher N, it checks if bigram counts exceed a threshold; if so, it uses discounted bigram probabilities. Otherwise, it applies backoff weights to the p...
def getBackoffProb(self, N, backoff): discount = backoff["discount"] threshold = backoff["threshold"] discountedunigramprob = self.get1GramsProb(discount) if N ==1: return discountedunigramprob bkprob = dict() bigramcounts = self.getNGrams(2) discount...
def majority_class(examples): classes = [example[-1] for example in examples] print("++++++++++++++++", classes) print("================", max(set(classes), key=classes.count)) return max(set(classes), key=classes.count) def same_class(examples): classes = [example[-1] for example in examples] r...
The main task of the code is to recursively build a decision tree by selecting the best feature to split examples, creating tree nodes for each split, and handling base cases where all examples share the same class or no features remain. It returns a tree node representing the decision tree structure, with children nod...
def build_tree_1(examples, features): tree_node = TreeNode(majority_class(examples)) # print("tree_node: ", tree_node) # if examples all have same class, then return leaf node predicting this class if same_class(examples): return tree_node # if no more features to split on, then return leaf n...
def majority_class(datas): classes = [data[-1] for data in datas] return max(set(classes), key=classes.count) def same_class(datas): classes = [data[-1] for data in datas] return (len(set(classes)) == 1) def best_feature(features, datas): # Return index of feature with lowest entropy after split ...
This function builds a decision tree recursively by selecting the best feature to split the data, creating child nodes for each feature value, and using majority class labels for leaf nodes when all data points share the same class or no features remain for splitting.
def build_tree_1(datas, features): tree_node = TreeNode(majority_class(datas)) # if datas all have same class, then return leaf node predicting this class if same_class(datas): return tree_node # if no more features to split on, then return leaf node predicting majority class if not features...
def playGame(numTimes): res = [] for i in range(numTimes): for i in range(10): draw = np.random.uniform(0, 1) if (draw < rtrue): res.append(1) else: res.append(0) return res def betaFormPrior(r): if(r<0.5): return 2 ...
The code computes the difference between the final and initial posterior probability distributions over a range of parameters (`rSweep`) after iteratively updating them with game data. It initializes priors, updates posteriors using Bayesian inference for each game, and returns the element-wise difference between the f...
def posteriorEvolution(numGames, rSweep): initial = [] prevIterPost = [] completePost = [] priorVals = [] for i in range(numGames): currData = playGame(1) prevIterPost = completePost if (i == 0): for r in rSweep: priorVals.append(betaFormPrior(r)) ...
def getFrames(self, _mesh): #figure out if we're using armature keyframes or mesh keyframes #get the mesh as an object: mesh = self.selectedObj armature = mesh.find_armature() if armature != None: mesh.select = False armature.selec...
This code exports a 3D mesh to a file, handling both static and animated models. It retrieves the active object's mesh, checks for animation frames, and writes data to the specified path. If enabled, it also exports armature information. The task involves preparing mesh data, managing animation frames, and saving the o...
def execute(self, context): props = self.properties filepath = self.filepath filepath = bpy.path.ensure_ext(filepath, self.filename_ext) self.selectedObj = bpy.context.scene.objects.active#save a reference to this for matrix_world self.selectedName = self.selectedObj.nam...
def get_courses_for_skills(relevant_skills_dict): query = """select cdc.course_title, cdc.id from curriculum_designer_skill inner join curriculum_designer_course_course_skills cdccs on curriculum_designer_skill.id = cdccs.skill_id inner join curriculum_designer_course cdc on cdc.id = cdccs.course_id...
The function `recommend()` identifies missing skills in a curriculum, finds associated skills, retrieves relevant courses, and formats them into a JSON structure for API use.
def recommend(): courses_for_skills = get_courses_for_skills( find_skills_associated_to_missing_skills( find_missing_skills_from_curriculum())) # print(courses_for_skills) json_dict = utils.transform_courses_for_skills_API_form(courses_for_skills) return json_dict
def fix_maze_boundary(self): # Make sure that the maze is bounded. for i in range(self.num_rows): self.maze[i,0] |= 8 self.maze[i,-1] |= 2 for j in range(self.num_cols): self.maze[0,j] |= 1 self.maze[-1,j] |= 4 def fix_wall_inconsistency(self, verb...
The code initializes a maze visualization system using Turtle graphics. It accepts a 2D numpy array maze where walls are encoded as 4-bit values, or generates a new maze if none is provided. Key tasks include setting up the window dimensions, validating maze boundaries, resolving wall inconsistencies, and registering t...
def __init__(self,dimension=2, maze = None): ''' maze: 2D numpy array. passages are coded as a 4-bit number, with a bit value taking 0 if there is a wall and 1 if there is no wall. The 1s register corresponds with a square's top edge, 2s register the right edge, 4...
def moveUpRight(distance): global angleSize turnRobot(angleSize) driveRobot(distance) def moveDownRight(distance): global angleSize turnRobot(-angleSize) driveRobot(distance) def moveLeft(distance): turnRobot(179) driveRobot(distance) def moveRight(distance): turnRobot(0) driv...
This code defines a method to print block letters A-E in uppercase using predefined movement commands. It handles both lowercase and uppercase inputs, calculates geometric parameters like cross-bar lengths and angles, and executes precise directional movements to render each letter's shape in a "BLOCKLETTER" font style...
def letterPrint(self, letter): #Does the actual printing of the letter # Current letters implemented are [A,B,C,D,E] # All letters will be printed in caps and "BLOCKLETTER" font if ((letter=='a') or (letter=='A')): moveUpRight(fontSize) moveDownRight(fontSize/...
def read_packet(self) -> bytes: headers = b"" newChar = b"" while newChar != b".": headers += newChar newChar = sys.stdin.buffer.read(1) length = int(headers) content = b"" for i in range(length): content += sys.stdin.buffer.read(1) return content def do_GET(self, path) -> HttpResponseStrict: s...
The code processes an HTTP request by reading the method, path, and body from incoming packets. It generates a response (defaulting to 404) using `do_GET` or `do_POST` based on the method. The response is formatted into status, headers, and content, then sent as separate packets.
def handle_request(self): method = self.read_packet() path = self.read_packet().decode("UTF-8") body = self.read_packet().decode("UTF-8") res: HttpResponseStrict = { "status": 404, "headers": {}, "content": b"" } if method == b"GET": res = self.do_GET(path) if method == b"POST": res = self....