dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def get_resource(id: int) -> Resource | None: try: resource = database.session.query(Resource).filter_by(id=id).one() except NoResultFound: return None return resource def append_resource_history(resource: Resource, msg: str) -> list[tuple[datetime, str]]: history = resource.history ...
This function processes a JSON request to update a resource's message by ID. It validates the request format, retrieves the resource, updates its message and history, saves changes to the database, and returns a success response. If invalid, it returns appropriate error messages.
def msg_by_id(id): if not request.is_json: return make_response({"error": f"Unsupported request format"}, 400) if request.json is None: return make_response({"error": f"Unsupported request format"}, 400) if "data" not in request.json: return make_response({"error": f"Unsupported requ...
def clean(mat): mat = mat*0 def cost_single(x_vec, y_vec, bias, weights, nodes): error = [0]*y_vec hyp = ffp(x_vec, bias, weights, nodes) for k in range(len(y_vec)): print("k %i" %(k)) error[k] = (y_vec[k]-hyp[k])*-1.0 return error def generate_deltas(weights, deltas, nodes, error): layers = len(deltas)-1 f...
The code performs backpropagation to update neural network weights by calculating error gradients. It computes deltas from the cost error, generates gradients, and adjusts weights using gradient descent with a learning rate of 0.5. The function returns the updated gradients for each layer.
def back_propagation(sample, y_vec, bias, weights, nodes): deltas = copy.deepcopy(nodes) gradients = copy.deepcopy(weights) clean(gradients) clean(deltas) error = cost_single (sample, y_vec, bias, weights, nodes) deltas = generate_deltas (weights,deltas,nodes, error) gradients = generate_gradients(sample, g...
def _get_response_matrix_index(self): """ Returns index for response matrices. """ idx = [] dims = ['PX', 'PY', 'X', 'Y'] for beam in config.SEQUENCE_NAMES: elmts = list(self.twiss_table.loc[beam].index) idx += list(itertools.product([beam], dims, elmts)) ...
The main task of this code is to compute an error response matrix that quantifies how perturbations (errors) at various beam positions affect the orbit in a particle accelerator. It constructs a pandas DataFrame, initializes it with zeros, populates it by simulating error propagation using the Twiss table, and optional...
def _compute_error_response_matrix(self, concatenate_elements=True): """ Computes the error response matrix. This method is run interally as part of the setup_for_analysis call. It makes use of the Twiss table to build up the response matrix. Args: concatenate_elements(bool...
def _get_response_matrices_at_bpms(self): """ Returns the response matrices evaluated at all BPMs, for X and Y. Returns the error and corrector response matrices evaluated at all BPMs stored in self.twiss_table, for X and Y. Function used internally when the response matrices are to sim...
The function computes a weighted pseudoinverse of a corrector response matrix, adjusting for specified BPMs and correctors. It incorporates user-defined scaling factors for BPMs and correctors, ensuring valid inputs, and applies these weights to prioritize specific correction points. The result is a DataFrame represent...
def _compute_weighted_pseudoinverse(self, n_x, n_y=None, correct_at=None, bpm_scaling=None, corrector_scaling=None): """ Computes a weighted pseudoinverse of the corrector response matrix evaluated at all BPMs. Args...
def _get_response_matrices_at_bpms(self): """ Returns the response matrices evaluated at all BPMs, for X and Y. Returns the error and corrector response matrices evaluated at all BPMs stored in self.twiss_table, for X and Y. Function used internally when the response matrices are to sim...
This function solves a convex optimization problem to correct orbit errors by adjusting corrector strengths, subject to bounds on orbit residuals and corrector magnitudes. It minimizes a weighted sum of residual orbit norm and corrector strength norm, using CVXPY, with constraints derived from input bounds and specifie...
def convex_correction(self, orbit_bound, cs_bound, w=0.0, correct_at=None, cvxpy_options=None): """ Corrects the errors as a bounded optimzation problem. Args: correct_at(dict): Dict of the form:: correct_at = { beam1 : ...
def _knob_def_to_series(self, knob_def): """ Returns the corresponding pandas Series for a given knob defintiion. Args: knob_def(dict): Dict of the form:: {beam : {element : {dimension : value}}} where knob_def[beam][element][dim] defines the orbit ...
This function optimizes corrector strengths for implementing specified knobs using L2-minimization with constraints on corrector magnitude, parity enforcement, and orbit regularization. It processes knob definitions, constructs optimization matrices, applies regularization terms, solves the convex problem via CVXPY, an...
def knob_implementation(self, cs_bound, c_weight=None, force_parity=None, orbit_regularizer=None, knob_names=None, cvxpy_options=None): """ Prov...
def slice_twiss_table(self, section=None, keep_all_by_default=True, keyword_li=None, pattern_li=None): """ Returns a sliced Twiss table. Args: section(dict): Dict of the form:: ...
(The main task of the code is to initialize and construct essential data structures for subsequent analysis, including slicing the Twiss table, computing corrector and error response matrices, and initializing an error table. Parameters control element inclusion/exclusion rules, section definitions, and error handling,...
def build_matrices(self, section=None, keep_all_by_default=True, keyword_li=None, pattern_li=None, concatenate_elements=True): """ Initializes all structures for subsequent analysis. Args:...
def encode(self, inputs): enc = self.encoder(inputs) if self.encoder_type == 'Nonlinear': z_mean = self.encoder_mean(enc) else: z_mean = self.encoder_mean(inputs) # Note: encoder_type = 'Linear' only means that z_mean is a linear combination of the inpu...
The code processes input data in batches through a VAE to generate predictions, latent representations (z_sample, z_mean), and state population distributions. It saves these results as NumPy files, including state population fractions, predicted labels, and latent variables. If the encoder is linear, it also saves enco...
def save_traj_results(self, inputs, batch_size, path, SaveTrajResults, traj_index=0, index=1): all_prediction=[] all_z_sample=[] all_z_mean=[] for i in range(0, len(inputs), batch_size): batch_inputs = inputs[i:i+batch_size].to(self.device) ...
def _is_padded(node): """ If the node has a padding around it, then the population of the vertices of the center node will be the same as the population of each node of the quad tree. """ return ( node.nw.n == node.nw.se.n and node.ne.n == node.ne.sw.n and node.sw.n == no...
The function `_pad` checks if a node is smaller than a 2nd-level (4x4) node and not already padded with a centered pattern. If so, it centers the node and applies padding; otherwise, it returns the node unchanged.
def _pad(node): """ If node is smaller than a 2nd level (4x4) node, and is not a padded node such that the pattern is in the center, then center the node and apply padding around the node. """ if node.level <= 3 or not _is_padded(node): return _pad(_center_node(node)) else: r...
def _center_node(node): """ Center the node by adding zero padding to the boudaries. """ z = _zero_node(node.nw.level) result = _combine( _combine(z, z, z, node.nw), _combine(z, z, node.ne, z), _combine(z, node.sw, z, z), _combine(node.se, z, z, z), ) return r...
This function simulates the Game of Life for a specified number of iterations, using binary decomposition to efficiently compute intermediate states. It returns the final game state after all iterations, along with a list of all intermediate states and their corresponding iteration counts. The process involves centerin...
def _play_game(node, iterations=0): """ Play the game of life for `iterations`. This calculates the game state after the given number of iterations. """ if iterations == 0: return node iterations_binary = [int(x) for x in bin(iterations)[2:]] for _ in range(len(iterations_binary)): ...
def _zero_node(level): if level == 0: return get_dead() else: return _combine( _zero_node(level - 1), _zero_node(level - 1), _zero_node(level - 1), _zero_node(level - 1), ) def _combine(nw, ne, sw, se): level = nw.level + 1 n = nw.n...
The main task of the code is to convert a list of 2D points into a hierarchical quadtree structure. It iteratively groups points into quadrants, adjusting coordinates and combining nodes until a single root node remains, representing the spatial hierarchy of the input points.
def _list_to_tree(points): x_min = min([x for x, y in points]) y_min = min([y for x, y in points]) pattern = {(x - x_min, y - y_min): get_alive() for x, y in points} level = 0 while len(pattern) != 1: next_level = {} z = _zero_node(level) while len(pattern) > 0: x...
def _list_to_tree(points): x_min = min([x for x, y in points]) y_min = min([y for x, y in points]) pattern = {(x - x_min, y - y_min): get_alive() for x, y in points} level = 0 while len(pattern) != 1: next_level = {} z = _zero_node(level) while len(pattern) > 0: x...
The code simulates a game by reading a pattern from a file, constructing a tree structure from the points, and running the game for a specified number of iterations. It returns the original points, the final result, all intermediate states as point lists, and the time taken to execute the game simulation.
def play(filename, iterations): points, desc = read_pattern(filename) root_node = _list_to_tree(points) print("Input:", root_node) start_t = time.time() result, all_nodes = _play_game(root_node, iterations) end_t = time.time() time_taken = end_t - start_t print("Output:", result) all...
def BFS(self, start_pos, adv_pos, chess_board, max_step): if start_pos[0] == adv_pos[0] and start_pos[1] == adv_pos[1]: # checks if positions are same return False moves = ((-1, 0), (0, 1), (1, 0), (0, -1)) # r-1 => up # c + 1 => right # r + 1 => down # c -...
This function determines if a given move leads to a guaranteed loss by checking if any of the adversary's optimal responses after the move result in a winning endgame state. It uses BFS to explore adversary positions, refines them to best moves, and evaluates endgame outcomes. If any refined move causes the opponent to...
def check_if_losing_move(self, move, adv_pos, board, max_step): # get rid of all moves that can result in a losing game spec_move = move[0] adv_BFS = self.BFS(adv_pos, spec_move, board, max_step)[0] # get all possible positions for adersary refine_BFS = self.refin...
def check_endgame(self, chess_board, wall, p0_pos, p1_pos): # based off given code from world.py """ Check if the step from player can result in an endgame in a favorable manner. Returns true if ending the game and the points associate each player at the time. """ p0_r = p0_pos...
The main task of the code is to implement a depth-1 minimax algorithm for a chess-like game. It evaluates each possible move in `refined_moves` by checking if it leads to an immediate win (assigning a high score), if it allows the opponent to win (assigning a low score), or using the move's precomputed grade. It then s...
def minimax(self, depth, refined_moves, adv_pos, board, max_step, isMaximisingPlayer): # minimax of depth 1! move_value = {} for move in refined_moves: # check if current move results in win endgame = self.check_endgame(board, move[1], move[0], adv_pos) # this works to check...
def BFS(self, start_pos, adv_pos, chess_board, max_step): if start_pos[0] == adv_pos[0] and start_pos[1] == adv_pos[1]: # checks if positions are same return False moves = ((-1, 0), (0, 1), (1, 0), (0, -1)) # r-1 => up # c + 1 => right # r + 1 => down # c -...
The code determines the agent's next move and wall placement by first using BFS to explore reachable positions and possible walls. It refines these options to prioritize moves that block the opponent effectively. Then, it applies a minimax algorithm to evaluate the best strategic choice, considering future moves. The r...
def step(self, chess_board, my_pos, adv_pos, max_step): """ Implement the step function of your agent here. You can use the following variables to access the chess board: - chess_board: a numpy array of shape (x_max, y_max, 4) - my_pos: a tuple of (x, y) - adv_pos: a tupl...
def set_return_raw(self, B): self.return_raw = B def set_return_np(self, B): self.return_np = B def init_data_stats(self): """ 1. computes/estimates feature means 2. if scale=True, computes/estimates feature standard devs 3. if not binary, computes/estimates target mean...
This code initializes a data handler for SVM light format datasets, supporting memory or disk-based loading. It configures parameters like feature dimensions (D), sample count (N), and zero-based indexing. When disk=True, it requires explicit D/N/zero_based values and enables random access via mappings. When disk=False...
def __init__(self, path_data, disk, D=None, N=None, zero_based=None, binary=True, scale=True, n_to_estimate=int(10e3), set_params=True, dtype=torch.get_default_dtype(), MAXMEMGB=MAXMEMGB, seed=None): """ assumes 0. data is in svm light forma...
def create_key_matrix(key: str) -> np.ndarray: key = sanitize_str(key) lkey = len(key) n, is_square = is_total_square(lkey) # type: ignore if not is_square: raise ValueError('SQUARE_MATRIX_ERROR : Key Length must be square !!!') return create_matrix(key, [n, n]) def create_txt_matrix(txt: s...
The code decrypts a ciphertext using a matrix-based cipher (likely Hill cipher). It constructs a key matrix from the provided key, validates its invertibility, computes the modular inverse of the key matrix, and applies it to the ciphertext matrix. The result is converted back to a string. If any step fails, an error i...
def decipher(ctxt: str, key: str) -> 'str | None': try: key_mat = create_key_matrix(key) ctxt_mat = create_txt_matrix(ctxt, key_mat.shape[0]) inv = check_key_matrix(key_mat) inv_key = (inv * get_adjoint(key_mat)) % 26 txt_mat = np.round(np.dot(ctxt_mat, inv_key)).astype(int) ...
def on_session_started(session_started_request, session): """ Called when the session starts """ logger.info("on_session_started requestId=" + session_started_request['requestId'] + ", sessionId=" + session['sessionId']) def on_launch(launch_request, session): """ Called when the user launc...
This Lambda handler processes Alexa skill requests by routing events (e.g., LaunchRequest, IntentRequest) to appropriate functions. It validates the application ID, logs session details, and triggers actions like session start, launch, intent handling, or session end based on the request type, ensuring proper interacti...
def lambda_handler(event, context): """ Route the incoming request based on type (LaunchRequest, IntentRequest, etc.) The JSON body of the request is provided in the event parameter. """ logger.info("event.session.application.applicationId=" + event['session']['application']['applicationId']) ...
def toggle_power(self): current_index = POWER_MODES.index(self.current_power) if current_index == len(POWER_MODES) - 1: self.current_power = POWER_MODES[0] else: self.current_power = POWER_MODES[current_index + 1] def toggle_mode(self): current_index = MODES.inde...
The main task of the code is to validate and execute a list of device commands, update internal state attributes, and notify the home assistant system of changes. It checks for supported commands, triggers corresponding actions (e.g., toggling power/mode/fan or adjusting temperature), sends an IR signal reflecting the ...
def send_command(self, command: Iterable[str], **kwargs): """Send commands to a device.""" for item in command: if item not in SUPPORTED_COMMANDS: raise UnknownCommand if "toggle_power" in command: self.toggle_power() if "toggle_mode" in...
def is_valid_executable_path(product: PRODUCT_TYPE, exe_loc: str) -> bool: return PLUGINS[product].is_valid_executable_path(exe_loc) def _check_uncommon_executable_path(product: PRODUCT_TYPE, exe_loc: str): if not _is_common_executable_path(product, exe_loc): product_pattern_path = PRODUCT_EXE_INFO[prod...
This function prompts the user to manually input the file path for a specified product's executable. It checks for predefined naming patterns, validates the path, and saves it to a configuration file if valid. The function provides feedback on path validity and allows users to overwrite configurations with a specific c...
def _prompt_path(product: PRODUCT_TYPE) -> str: # pragma: no cover product_info = PRODUCT_EXE_INFO[product] product_name = product_info["name"] has_pattern = "pattern" in product_info and "patternpath" in product_info print(f"Cached {product} executable not found") print(f"You are about to enter ma...
def find_mapdl( version: Optional[Union[int, float]] = None, supported_versions: SUPPORTED_VERSIONS_TYPE = SUPPORTED_ANSYS_VERSIONS, ) -> Union[Tuple[str, float], Tuple[Literal[""], Literal[""]]]: """Searches for Ansys MAPDL path within the standard install location and returns the path of the latest ve...
This function identifies the installation path and version for specified products (e.g., "mapdl", "mechanical", "dyna") by delegating to product-specific finders. It returns a tuple containing the installation path and version, or empty strings if not found. The supported_versions parameter filters available versions, ...
def _find_installation( product: str, version: Optional[float] = None, supported_versions: SUPPORTED_VERSIONS_TYPE = SUPPORTED_ANSYS_VERSIONS, ) -> Union[Tuple[str, float], Tuple[Literal[""], Literal[""]]]: if product == "mapdl": return find_mapdl(version, supported_versions) elif product =...
def _has_plugin(product: str) -> bool: return product in PLUGINS def _find_installation( product: str, version: Optional[float] = None, supported_versions: SUPPORTED_VERSIONS_TYPE = SUPPORTED_ANSYS_VERSIONS, ) -> Union[Tuple[str, float], Tuple[Literal[""], Literal[""]]]: if product == "mapdl": ...
This function determines the correct executable path for a given product by checking for existing plugins, locating the installation path if not provided, prompting the user if needed, validating the path, and updating the default path. It returns the resolved executable path.
def _save_path(product: str, exe_loc: Optional[str] = None, allow_prompt: bool = True) -> str: has_plugin = _has_plugin(product) if exe_loc is None and has_plugin: exe_loc, _ = _find_installation(product) if exe_loc == "" and allow_prompt: exe_loc = _prompt_path(product) # pragma: no cover ...
def _read_executable_path_from_config_file(product_name: PRODUCT_TYPE) -> Optional[str]: """Read the executable path for the product given by `product_name` from config file""" config_data = _read_config_file() return config_data.get(product_name, None) def version_from_path(product: PRODUCT_TYPE, path: str...
This function retrieves the executable path for a specified application, checking configuration files for existing paths and versions. If a version mismatch occurs or the path isn't found, it attempts to locate the application, prompts user input if allowed, and updates defaults. It returns the valid path or None if un...
def _get_application_path( product: str, allow_input: bool = True, version: Optional[float] = None, find: bool = True, ) -> Optional[str]: _exe_loc = _read_executable_path_from_config_file(product) if _exe_loc is not None: if version is None: return _exe_loc else: ...
def list2grid(lst: list[str]) -> Tuple[dict[xy_coord, Vertex], xy_coord]: """ Turns a list of strings into a dict representing a grid of vertices of coordinate (X,Y). :param lst: A list of strings where each element of the list corresponds to a row of the XY grid :type lst: list :return: A ...
The code solves a pathfinding puzzle by calculating the shortest path from multiple starting points (low points at height 0) to a destination using breadth-first search (BFS). It fetches input data, constructs a grid, identifies endpoints, and iterates over all low points to compute path lengths. It then determines the...
def main(): puzzle = get_puzzle(year=DATE[0], day=DATE[1]) input = puzzle.input_data input_list = input.split("\n") grid, max_coord = list2grid(input_list) start_coord, end_coord = get_endpoints(grid) # updated_grid, dest_reached, path_length = breadth_first_search( # grid, start_coord,...
def grosko_and_co_2023(): """Return the grosko-and-co rating.""" draft_picks = Path("rankings/draft_day/grosko_and_co_2023.csv") draft_table = EspnDraftOrderExtractor().extract_draft_order(draft_picks) bdge_ratings = Path("rankings/bdge_rankings/2023-08-27/2023-08-27-clean.csv") bdge_table = pd.read...
This code processes and compares draft data from multiple sources (draft_table, bdge_table, adp_table) by cleaning player names, assigning positional ranks, mapping drafter aliases, and generating a comparison report. It prepares tables for analysis by standardizing names, calculating draft rounds, and aligning ranking...
def grosko_and_co_main_2023(): """Sample script.""" draft_table, bdge_table, reports_path = grosko_and_co_2023() adp_table = DraftSharksADPDraftOrderExtractor().extract_draft_order( "rankings/draft_sharks_adp/2023-08-27-1qb.html" ) draft_table["drafter"] = draft_table["drafter"].map( # typ...
def husky_supreme_2023(): """Return the husky supreme rating.""" draft_picks = Path("rankings/draft_day/2023-08-05.html") draft_table = YahooHtmlDraftOrderExtractor().extract_draft_order(draft_picks) bdge_ratings = Path("rankings/bdge_rankings/2023-08-02/2023-08-02-clean.csv") bdge_table = pd.read_c...
The main task of the code is to process and compare draft data with rankings and ADP (Average Draft Position) data for the 2023 season. It cleans player names, maps drafter team names to real names, calculates positional ranks, adjusts pick numbers, and generates a comparison report using draft, BDGE rankings, and ADP ...
def main_2023(): """Sample script.""" draft_table, bdge_table, reports_path = husky_supreme_2023() adp_table = DraftSharksADPDraftOrderExtractor().extract_draft_order( "rankings/draft_sharks_adp/2023-08-19-superflex.html" ) draft_table["drafter"] = draft_table["drafter_team_name"].map( # t...
def grosko_and_co(): """Return the grosko-and-co rating.""" draft_picks = Path("rankings/draft_day/grosko_and_co.csv") draft_table = EspnDraftOrderExtractor().extract_draft_order(draft_picks) bdge_ratings = Path("rankings/bdge_rankings/2022-08-23/rankings.html") bdge_table = BDGEDraftOrderExtractor(...
The main task of the code is to generate a comparison report between draft data and rankings data by cleaning player names in both datasets and using the `create_comparison` function to produce reports stored in the specified path.
def main_2022(): """Sample script.""" # draft_table, bdge_table, reports_path = husky_supreme() draft_table, bdge_table, reports_path = grosko_and_co() bdge_table["Name"] = _clean_player_name_col(bdge_table["Name"]) draft_table["original_name"] = draft_table["pick"].copy() draft_table["pick"] =...
def get_sample_information(entity): sample = {} sample['attributes'] = {} sample['releaseDate'] = datetime.now().strftime("%Y-%m-%d") for sample_field, sample_value in unpack_dictionary(entity.content, {}).items(): if sample_field == 'genus_species - ontology' or sample_field == 'genus_species -...
The function processes a map of entities to construct a structured dictionary. It categorizes entities into lists (e.g., samples, files) based on their type, extracts protocol details, and enriches assay and assay_data entries using collected entities and protocols. The output is a consolidated JSON-like structure with...
def get_json_from_map(entity_map): library_prep_entity = '' sequencing_entity = '' entity_dict = { 'files': [], 'samples': [], 'assays': [], 'assay_data': [], 'projects': [], 'study': [], 'sequence_processes': [] } protocols = {}...
def skip_element(element: CommentedCodeElement): """ Skip elements that are not functions or namespaces """ if not isinstance(element, CodeElementFunction): return True # struct and storage_var are considered functions but we won't generate documentation for them. need_instrumentation =...
This function extracts documentation from code elements, storing it in a dictionary with function names as keys. It processes elements in reverse order to avoid overwriting, handles namespaces recursively, and aggregates comments from preceding empty lines to build function documentation.
def get_elements_documentation(self, code_elements: List[CommentedCodeElement]): """Gets the current documentation of the functions in the file. The documentation is stored in a dictionary with the function name as key and the documentation as value. """ total_elements = len(code_element...
def get_elements_documentation(self, code_elements: List[CommentedCodeElement]): """Gets the current documentation of the functions in the file. The documentation is stored in a dictionary with the function name as key and the documentation as value. """ total_elements = len(code_element...
The main task of the code is to process a CairoModule by retrieving, removing, and re-adding documentation for its top-level elements, ensuring proper documentation handling during the module visit. It then delegates further processing to the parent class's visit_CairoModule method.
def visit_CairoModule(self, module: CairoModule): """Visit a CairoModule and fill the functions documentation.""" top_level_elements = module.cairo_file.code_block.code_elements self.get_elements_documentation(top_level_elements) self.remove_documentation(top_level_elements) self...
def compute_doubling_slope(pt : EPoint): # Note that y cannot be zero: assume that it is, then pt = -pt, so 2 * pt = 0, which # contradicts the fact that the size of the curve is odd. x_sqr = bigint_mul_mod(pt.x, pt.x,SP) y_2 = 2 * pt.y slope = bigint_div_mod( (3* x_sqr + SA), y_2, SP) return sl...
This function performs elliptic curve point doubling on a given point `pt` using modular arithmetic. It calculates the slope of the tangent line at `pt`, computes the new x-coordinate via `slope² - 2*pt.x`, then derives the new y-coordinate using `slope*(pt.x - new_x) - pt.y`, all modulo `SP`. If `pt.x` is zero, it ret...
def ec_double(pt : EPoint): if pt.x == 0: return (pt) slope= compute_doubling_slope(pt) slope_sqr = bigint_mul_mod(slope, slope,SP) new_x = bigint_div_mod(slope_sqr - 2 * pt.x, 1, SP) x_diff_slope = bigint_mul_mod(slope , ( pt.x - new_x) , SP) new_y = bigint_sub_mod(x_diff...
def bigint_sub_mod(x,y,P): sub = x - y res =bigint_div_mod(sub,1,P) return res def fast_ec_add(pt0 : EPoint , pt1 : EPoint ): if pt0.x == 0: return (pt1) if pt1.x == 0: return (pt0) slope = compute_slope(pt0, pt1) slope_sqr = bigint_mul_mod(slope, slope,SP) new_x =...
The function `ec_add` performs elliptic curve point addition. It adds two points `pt0` and `pt1` on an elliptic curve, returning the result. If the x-coordinates differ, it uses a fast addition method. If x-coordinates are equal, it checks if y-coordinates sum to zero (indicating inverses or the zero point), returning ...
def ec_add(pt0 : EPoint, pt1 : EPoint): x_diff = bigint_sub_mod(pt0.x , pt1.x, SP) if x_diff != 0: # pt0.x != pt1.x so we can use fast_ec_add. return fast_ec_add(pt0, pt1) y_sum = bigint_add_mod(pt0.y , pt1.y, SP) if y_sum == 0: # pt0.y = -pt1.y. # Note that the case...
def ec_double(pt : EPoint): if pt.x == 0: return (pt) slope= compute_doubling_slope(pt) slope_sqr = bigint_mul_mod(slope, slope,SP) new_x = bigint_div_mod(slope_sqr - 2 * pt.x, 1, SP) x_diff_slope = bigint_mul_mod(slope , ( pt.x - new_x) , SP) new_y = bigint_sub_mod(x_diff...
This code performs elliptic curve scalar multiplication by computing r*P using the double-and-add algorithm. It iterates over each bit of the scalar r (from MSB to LSB), repeatedly doubling the current result point R and conditionally adding P when the bit is set, efficiently calculating the final point on the elliptic...
def mult(P, r): # multiplication r*P # P.affine() a = r R = EPoint(0,0) k = 256 for i in range(k - 1, -1, -1): R = ec_double(R) if (bit(a, i) == 1): R = fast_ec_add(R,P) return R
def verify_point(pt: EPoint): y_sqr = bigint_mul_mod(pt.y, pt.y, SP) x_sqr = bigint_mul_mod(pt.x, pt.x, SP) x_cub = bigint_mul_mod(x_sqr, pt.x, SP) a_x = bigint_mul_mod(pt.x,SA,SP) right1 = bigint_add_mod(x_cub, a_x, SP) right = bigint_add_mod(right1, SB, SP) diff = bigint_sub_mod(y_sqr, rig...
The code verifies an ECDSA signature by checking if the computed elliptic curve point (from combining the generator point scaled by `u1` and the public key scaled by `u2`) matches the signature component `r`. It validates the public key, signature components `r` and `s`, computes `u1` and `u2` using modular division, p...
def verify_ecdsa( public_key_pt : EPoint, msg_hash, r , s): if verify_point(public_key_pt) !=1: return 0 if validate_signature_entry(r,SN) != 1: return 0 if validate_signature_entry(s,SN) != 1: return 0 gen_pt = EPoint(SGX,SGY) # Compute u1 and u2. u1 = bigi...
def random(m, s): x1 = 0x53b907251bc1ceb7ab0eb41323afb7126600fe4cb2a9a2e8a797127508f97009 y1 = 0xc7b390484e2baae92df41f50e537e57185cb18017650a6d3220a42a97727217d x2 = 0xacbc2999fb58c6e9015a12a4c5f3849e301649b2271eaaaf21906ed03cafdf45 y2 = 0x146aac3f7f74047fd45cf0098fadee5cd00f7f6871440387ba402f2390d72...
The main task of this code is to generate an ECDSA digital signature (r, s) using a secret key (sk) and a message hash (msg_hash). It computes a random value k, derives a point on the elliptic curve, extracts r from the x-coordinate, and calculates s using modular arithmetic involving the message hash, secret key, and ...
def sign_ecdsa(sk, msg_hash): gen_pt = EPoint(SGX,SGY) k = random(msg_hash,sk) pg = mult(gen_pt,k) r = bigint_mul_mod(pg.x, 1, SN) rsk = bigint_mul_mod(r, sk, SN) m_rsk = bigint_add_mod(msg_hash, rsk, SN) s = bigint_div_mod(m_rsk, k ,SN) return r,s
def gallop_B_right(run:list, target, index:int, max_offset:int, key=None, reverse:bool=False) -> int: """ Gallop right and find position to insert element of run B inside run A """ prev_offset = 0 # Value of previous offset (low boundary in binary search) offset = 1 # Value of current offset (high bo...
The function `merge_at` merges two sorted runs (A and B) in an array by first adjusting their positions using galloping techniques to find insertion points. It then merges the runs using either `merge_lo` or `merge_hi`, depending on the relative sizes of the runs, to efficiently combine them into a single sorted sequen...
def merge_at(array:list, s1:int, n1:int, s2:int, n2:int, min_gallop:int, key=None, reverse:bool=False) -> int: """ Merges two runs A and B at index s1 and s2 with length n1 and n2 """ # Find where B[0] start in A (elements in A before that are already in place) found_index = gallop_B_right(array, array[s2]...
def compute_minrun(n:int) -> int: """ Computes and return the minimum length of a run from 16 - 32 """ # As python implemetation of insertion sort is not fast enough # minrun is from range 16 to 32 instead of range 32 to 64 r = 0 # Becomes 1 if any 1 bits are shifted off # Take the first 5 bits ...
This code implements the TimSort algorithm to sort an array in-place, using a combination of insertion sort for small runs and merge sort for larger sections. It dynamically calculates minimum run sizes, manages runs via stacks, merges runs based on their sizes, and supports custom key functions and reverse sorting. Th...
def timsort(array:list, key=None, reverse:bool=False) -> None: """ Sorts an array using timsort algorithm """ n = len(array) # Length of array remaining = n # Length of array left that needs merging min_run = compute_minrun(n) # Minimum length of a run # Stacks for storing runs and powers foun...
def compute_minrun(n:int) -> int: """ Computes and return the minimum length of a run from 16 - 32 """ # As python implemetation of insertion sort is not fast enough # minrun is from range 16 to 32 instead of range 32 to 64 r = 0 # Becomes 1 if any 1 bits are shifted off # Take the first 5 bits ...
(Timsort algorithm implementation to sort an array in-place using a combination of insertion sort for small runs and merge sort for combining runs, with optimizations like galloping and run stack management to enhance efficiency. The function handles custom keys and reverse sorting, ensuring stable sorting by merging r...
def timsort(array:list, key=None, reverse:bool=False) -> None: """ Sorts an array using timsort algorithm """ n = len(array) # Length of array remaining = n # Length of array left that needs merging min_gallop = MIN_GALLOP # Minimum wins for galloping min_run = compute_minrun(n) # Minimum len...
def get_annotator(self, img): return Annotator(img, line_width=self.args.line_width, example=str(self.model.names)) def xyxy_to_xywh(xyxy): """" Calculates the relative bounding box from absolute pixel values. """ x_c = (xyxy[..., 0] + xyxy[..., 2]) / 2 # x center y_c = (xyxy[..., 1] + xyxy[..., 3]...
The main task of the code is to process and save object detection inference results, including logging detection details, visualizing bounding boxes on input images, saving annotated outputs, and tracking detected objects using DeepSORT. It handles batched inputs, formats results for different data sources (e.g., webca...
def write_results(self, idx, results, batch): """Write inference results to a file or directory.""" p, im, im0 = batch log_string = '' all_outputs = [] if len(im.shape) == 3: im = im[None] # expand for batch dim self.seen += 1 im0 = im0.copy() ...
def read_and_process_images(self, path_img_a, path_img_b): # Read images and process them to find facial landmarks image_a, image_b = cv2.imread(path_img_a), cv2.imread(path_img_b) image_a_rgb, image_b_rgb = cv2.cvtColor(image_a, cv2.COLOR_BGR2RGB), cv2.cvtColor(image_b, cv2.COLOR_BGR2RGB) ...
This function swaps specified facial features between two images. It extracts features from both images, checks their visibility, and applies bidirectional swaps using alignment and blending. If a feature is invalid or not visible, it returns None. The function handles errors by returning original images or None upon f...
def swap_features(self, path_img_a, path_img_b, features_to_swap=None): if features_to_swap is None: features_to_swap = ["right_eye", "left_eye", "nose", "lips"] if not isinstance(features_to_swap, list): raise TypeError("features_to_swap must be a list of feature names....
def create_server_folder(): if not os.path.exists(server_path): # if the server folder doesn't exist on the desktop os.mkdir(server_path) create_sub_folders() def open_dialog(from_path, to_path, index1, index2): """ The function creates a file dialog """ window.filename = filedialog.ask...
The main task of the code is to create a graphical user interface (GUI) for a file manager that facilitates file transfer between a server and a USB drive or local directories. It initializes the window, sets up labels for file paths and USB status, creates buttons for download/upload operations, and manages dynamic UI...
def main(): # Initiate window and frame create_server_folder() window.title("File Manager") window.geometry("600x320+685+480") window.resizable(width=tk.FALSE, height=tk.FALSE) window.configure(bg=bg) window.rowconfigure(ROWS) window.columnconfigure(COLUMNS) frame = tk.Frame(window, ...
def fPSO_T0(zeta,N,m,beta,f,numberOfGraphs,isWeighted): d = 2 GraphList = [] #list of the generated NetworkX Graphs radialCoordList = [] #radialCoordList[g]=NumPy array with the radial coordinates of the gth graph's nodes in the native representation of the d-dimensional hyperbolic space with curvature -zet...
The function `fPSO` generates and saves network data (edge lists, coordinates) based on the input parameter `T`. For `T=0`, it uses deterministic edge formation (`fPSO_T0`). For `0 < T < 1` and `T > 1`, it employs different methods (`fPSO_Tnot0_belowLimit`, `fPSO_TaboveLimit`) to create graphs. Results are saved in the...
def fPSO(inputParameters,directoryName,numORan,isWeighted): if inputParameters.T==0: #deterministic edge formation [Rlist,GraphList,radialCoordList,CartCoordList] = fPSO_T0(inputParameters.zeta, inputParameters.N, inputParameters.m, inputParameters.beta, inputParameters.f, inputParameters.numberOfGraphs, is...
def Encryptfile(self): file = self.Chose_file() pdf_in_file = open(file, 'rb') inputpdf = PyPDF2.PdfFileReader(file) pages_no = inputpdf.numPages output = PyPDF2.PdfFileWriter() O_file = file.split(".") output_file_name = O_file[0] Password = output_file_...
The main task of the code is to insert encrypted file metadata into a MySQL database. It retrieves the encrypted file name, generates a password from the filename, fetches the file size and date, then executes an SQL INSERT query to store these details in the 'records' table. The function connects to the database, comm...
def AddDataToDatabase(self): cnx = mysql.connector.connect(user=userdetails.user_name, password=userdetails.password, host="127.0.0.1", database="mydatabase") my_cursor = cnx.cursor(prepared=True) # query = """CREATE TABLE records( DATE_CREATION text, NAME_OF_FILE text, SIZE_OF_FILE int, PASSWOR...
def update_status(self, message, color="green"): self.status_label.config(text=message, fg=color) self.root.update_idletasks() def is_file_different(self, url): local_filename = url.split('/')[-1] local_filepath = os.path.join(self.save_path, local_filename) if not os.path.exists...
The code's main task is to download files listed in a remote 'downloads.txt' file by fetching the URL list, checking each file's status, updating the UI with progress and status messages, and handling errors. It uses a progress bar, enables/disables the download button, and shows completion/error messages via Tkinter's...
def download_process(self): selected_alias = self.url_var.get() base_url = self.urls.get(selected_alias) if not base_url: self.root.after(0, lambda: messagebox.showerror("Error", "Please select or add a URL.")) self.root.after(0, lambda: self.download_button.config(state=...
def setTimeIndex(self, Indx, update = None): if self.ntimes == 1: self.currentTimeIndex = 0 self.currentFileIndex = Indx else: self.currentFileIndex = int(Indx/self.ntimes) self.currentTimeIndex = Indx % self.ntimes if update is None: s...
This method initializes grid definition parameters for multiple grids by reading netCDF file attributes, storing grid dimensions, spacing, projection details, and corner coordinates into lists. It iterates through all grids, extracts key metadata like grid size (nx, ny), spacing (dx, dy), projection parameters (lat1, l...
def setGridDefinition(self): self.nx = [] self.ny = [] self.dx = [] self.dy = [] self.lat1 = [] self.lat2 = [] self.lon0 = [] self.lat0 = [] self.map = [None]*self.numGrids self.wd = [0.0]*self.numGrids self.ht = [0.0...
def setGrid(self, GridNo, update = None): self.currentGrid = GridNo if update is None: self.updateData() def setTimeIndex(self, Indx, update = None): if self.ntimes == 1: self.currentTimeIndex = 0 self.currentFileIndex = Indx else: self.cur...
This function processes files with a specified prefix in a given path, organizing them into time lists, setting grid/time indices, and preparing variables for netCDF data reading. It initializes file lists, iterates through grids and times, and configures variable read functions for subsequent data processing.
def name(self, path, prefix) : # If no valid path and prefix are specified, then do # # nothing # self.path = path if path == None : pass else : # If a valid path and prefix has been specified # ...
def construct_policies(num_states, num_controls=None, policy_len=1, control_fac_idx=None): num_factors = len(num_states) if control_fac_idx is None: if num_controls is not None: control_fac_idx = [f for f, n_c in enumerate(num_controls) if n_c > 1] else: control_fac_idx =...
This function performs active inference with planning by iteratively inferring hidden states, calculating expected free energy for actions, updating policies via softmax, and interacting with an environment to minimize free energy over T timesteps. It returns the final observation index, inferred state, and computed fr...
def active_inference_with_planning(A, B, C, D, obs_idx, n_actions, env, policy_len, T): """ Initialize prior, first observation, and policies """ prior = D # initial prior should be the D vector if obs_idx == None: # if obs is not provided, reset the environment obs = env.reset() else: ...
def plot_graph(): fig = go.Figure() data = data_dl() for value, ticker in zip(data,ticker_list): fig.add_trace(go.Candlestick(x = value.index, open = value['Open'], high=value['High'], low=value['Low'], close=value['Close'], name = ticker )) fig.update_layout(title="Candlestick Chart for drop Mul...
(The main task of the code is to parse command-line arguments for email and stock plotting options, validate inputs, and execute corresponding functions: sending an email or generating plots for stock hikes, drops, or general data. It checks for unknown arguments and handles plotting via specified flags.)
def main(): parser = argparse.ArgumentParser(epilog="additional position arguments:\n Specify variable overrides using <NAME>:<VALUE> syntax on command line.",description="Email or Plot Stock hike and drop",formatter_class=argparse.RawDescriptionHelpFormatter) #parser.add_argument("flow",metavar="FLOW",help="Requi...
def plot_graph(): fig = go.Figure() data = data_dl() for value, ticker in zip(data,ticker_list): fig.add_trace(go.Candlestick(x = value.index, open = value['Open'], high=value['High'], low=value['Low'], close=value['Close'], name = ticker )) fig.update_layout(title="Candlestick Chart for drop Mul...
(The main task of the code is to parse command-line arguments for email, plotting, or specific stock trend plotting (hike/drop), validate inputs, and execute corresponding actions: sending an email or generating plots via `plot_graph()`, `plot_graph_drop()`, or `plot_graph_hike()`. It checks for unknown arguments and e...
def main(): parser = argparse.ArgumentParser(epilog="additional position arguments:\n Specify variable overrides using <NAME>:<VALUE> syntax on command line.",description="Email or Plot Stock hike and drop",formatter_class=argparse.RawDescriptionHelpFormatter) #parser.add_argument("flow",metavar="FLOW",help="Requi...
def plot_graph(): fig = go.Figure() data = data_dl() for value, ticker in zip(data,ticker_list): fig.add_trace(go.Candlestick(x = value.index, open = value['Open'], high=value['High'], low=value['Low'], close=value['Close'], name = ticker )) fig.update_layout(title="Candlestick Chart for drop Mul...
The main task of the code is to parse command-line arguments for sending an email or plotting stock data (hike, drop, or general). It uses `argparse` to handle options like `--email`, `--plot`, `--plot_drop`, and `--plot_hike`, validates inputs, and executes corresponding functions: `plot_graph()`, `plot_graph_drop()`,...
def main(): parser = argparse.ArgumentParser(epilog="additional position arguments:\n Specify variable overrides using <NAME>:<VALUE> syntax on command line.",description="Email or Plot Stock hike and drop",formatter_class=argparse.RawDescriptionHelpFormatter) #parser.add_argument("flow",metavar="FLOW",help="Requi...
def displayYMenu(): print("Menu:\n" + "\t1.Add Matrices\n"+"\t2.Check Rotation\n"+"\t3.Invert Dictionary\n" +"\t4.Covert Matrix to Dictionary \n"+"\t5.Check Palindrome\n" +"\t6.Search for an Element & Merge Sort \n"+"\t7.Exit\n") def addMatrices(): matrix1 = [] matrix2 = [] matrix3 =...
The main task of the code is to create an interactive menu-driven program that allows a user to select and execute different functions (exercises) such as matrix addition, rotation check, dictionary reversal, etc., until they choose to exit. It greets the user, displays a menu, processes their input, and invokes corres...
def assignment3(): name_user = input("Please enter your name: ") print("Hello ", name_user, ", welcome to my third assignment!") choice_user = 0 while choice_user != 7: displayYMenu() choice_user = eval(input("Please enter the exersice you would like to access: ")) if choice_use...
def copy_audio_file(self): # Ask the user to select an audio file file_path = filedialog.askopenfilename(filetypes=[("Audio Files", "*.wav *.mp3 *.ogg")]) if file_path: destination_folder = "sounds" shutil.copy(file_path, destination_folder) print("File copie...
The main task of the code is to collect user inputs for a sound name and key binding, copy an audio file, update a sound_data list with metadata, save changes to a JSON file, create a new UI frame, reinitialize key listeners, and refresh the application to reflect data changes.
def add_sound(self): #Getting User Input #---could be split into its own function nameCapture = ctk.CTkInputDialog(text="Enter Sound Name:", title="Name your sound save") newName = nameCapture.get_input() keyBinder = ctk.CTkInputDialog(text="Enter a Key to bind to:", title="Name...
def get_true_count(count, shoe): decks_remaining = float(len(shoe)) / 52.0 return float(count) / decks_remaining def get_pp_ev(shoe): permutations = itertools.combinations(shoe, 2) yield_ = 0 for permutation in permutations: yield_ += evaluate_pp(permutation) return yield_ def get_plus3_...
The main task of the code is to calculate betting amounts for a card game based on the true count and shoe conditions. It determines the main bet amount (bet_amt) using a favorable count threshold and optionally adjusts side bets (pp_amt, plus3_amt) if their expected values exceed predefined thresholds. The function re...
def get_bet_amount(count, shoe, bankroll): true_count = get_true_count(count, shoe) bet_amt = 0 pp_amt = 0 plus3_amt = 0 if BET_ONLY_WHEN_FAVORABLE_COUNT: if true_count > FAVORABLE_COUNT_THRESHOLD: bet_amt = NORMAL_BET_AMOUNT else: return bet_amt, pp_amt, plus...
def fill_shoe(decks): new_deck = ['As','2s','3s','4s','5s','6s','7s','8s','9s','Ts','Js','Qs','Ks', 'Ah','2h','3h','4h','5h','6h','7h','8h','9h','Th','Jh','Qh','Kh', 'Ad','2d','3d','4d','5d','6d','7d','8d','9d','Td','Jd','Qd','Kd', 'Ac','2c','3c','4c','5c','6c','7c','8c','9c','Tc...
The code simulates a card game (likely blackjack) by managing a bankroll, shuffling a deck, and iterating through rounds until a predefined card penetration threshold is met. It calculates bets based on a card count, processes each round's outcomes (including standard bets and side bets), updates profit/loss, and adjus...
def play(): bankroll = STARTING_BANKROLL shoe = fill_shoe(DECKS_PER_SHOE) random.shuffle(shoe) starting_number_of_cards = len(shoe) count = 0.0 pnl = 0.0 while (float(len(shoe)) / float(starting_number_of_cards)) > (1 - PENETRATION): bet_amt, pp_amt, plus3_amt = get_bet_amount(count,...
def _request_new_candles(self, market: str, period: str) -> pd.DataFrame: """Request the lastest data. Procedures: 1. get the lastest time of the already dumped data (if exists). 2. request new candles until the current timestamp. 3. concat the new candles to the old...
The function updates candle data for a specified market and period by fetching new data, removing the existing latest file if it exists, and saving the new data to the directory, returning the directory path.
def _update_candles(self, market: str, period: str) -> Path: """Parse all candle data and dump them.""" data = self._request_new_candles(market=market, period=period) # delete a lastest one if it exists dir_path = self._get_market_directory(market=market, period=period) if any(d...
def make_grid(width, height): #create grid that will hold all of the tiles for a boggle game #function creates a dictionary with row/column tuple as the key..and a space as the value return {(row, col): choice(ascii_uppercase) for row in range(height) for col in range(width) } def get_d...
The main task of the code is to generate a 3x3 grid, load a dictionary of words from a file, search for valid words in the grid using the dictionary, and display the found words. The `main()` function coordinates these steps: creating the grid, loading the dictionary, finding matching words, and outputting the results ...
def main(): #this is the function that will run the whole project grid = make_grid(3, 3) #generate random board dictionary = get_dictionary('words.txt') #load a dictionary words = search(grid, dictionary) #find the words # for word in words: # prin...
def getInfoFromLink(link): href=link.get('href') if not href.startswith('https'): url='https://www.umb.edu/'+href else: url=href return {'href': link.get('href'), 'url':url, 'string': link.string } def readWebPage(url): req = urllib.request.Request(url, headers={'User-Agent': 'Mozill...
The main task of the code is to extract faculty bio page links from HTML content, filter them based on specific URL patterns, and process each bio page to update a university-by-degree count structure. It parses HTML, identifies relevant links, retrieves their content, and passes them to a function for further data agg...
def getFacultyBioLinks(countByUniversityByDegree, facultyContent): soup=BeautifulSoup(facultyContent, "lxml") links=soup.find_all('a') for link in links: href=link.get('href') if href and ('faculty_staff/bio' in href or 'cla/faculty' in href): linkInfo=getInfoFromLink(link) ...
def loadTransactions(self, transactionsFileName): D = [] with open(transactionsFileName) as fileobj: for line in fileobj: D.append(self.processLine(line)) return D def find_frequent_1_itemsets(self, D, min_sup): L1 = {} for transaction in D: ...
This code implements the Apriori algorithm for association rule mining. It loads transaction data, iteratively generates frequent itemsets (L1, L2, ...) using candidate generation, filters them by minimum support (min_sup), and extracts strong association rules using minimum confidence (min_conf). The process continues...
def __init__(self, transactionsFileName, min_sup, min_conf): # Load all the transactions from the file to the python lists, trim/ignore newline characters D = self.loadTransactions(transactionsFileName) # L has the list of all frequent itemsets L = [] # Start with finding frequen...
def VirtualQueryEx(hProcess, lpAddress, process_is32): if process_is32: lpBuffer = MEMORY_BASIC_INFORMATION32() else: lpBuffer = MEMORY_BASIC_INFORMATION64() success = windll.kernel32.VirtualQueryEx(hProcess, LPVOID(lpAddress), byref(lpBuffer), sizeof(lpBuffer)) assert success, "Virtua...
The code reads a memory page from a process, verifies if it belongs to the target image, extracts the image if valid, and returns the address of the next memory page for further processing.
def read_page(self, hProc, lpAddress): pageInfo = VirtualQueryEx(hProc, lpAddress, False) base_address = pageInfo.BaseAddress region_size = pageInfo.RegionSize next_page = base_address + region_size # Confirm we are only extracting our image if self.verify_image(...
def checkWinner(self): # Return termimnal node status for maximizer player 1-win,0-tie,-1-lose """ This function checks whether there is a winner on the board. output: winner(int): Return 0 if there is no winner. Return 1 if maxPlayer is the winner. ...
The main task of the code is to implement the **alpha-beta pruning algorithm** for the **ultimate tic-tac-toe game**, evaluating the best possible score for the current player (max or min) at a given depth. It recursively explores valid moves, updates alpha/beta bounds for pruning, and returns the optimal value (max or...
def alphabeta(self, depth, currBoardIdx, alpha, beta, isMax): """ This function implements alpha-beta algorithm for ultimate tic-tac-toe game. input args: depth(int): current depth level currBoardIdx(int): current local board index alpha(float): alpha value beta(f...
def checkWinner(self): # Return termimnal node status for maximizer player 1-win,0-tie,-1-lose """ This function checks whether there is a winner on the board. output: winner(int): Return 0 if there is no winner. Return 1 if maxPlayer is the winner. ...
The code implements the minimax algorithm for ultimate tic-tac-toe to determine the optimal move. It recursively evaluates all possible moves, alternating between max and min players, and returns the best value (max for maxPlayer, min for minPlayer) based on game state scores. It checks terminal conditions (depth limit...
def minimax(self, depth, currBoardIdx, isMax): """ This function implements minimax algorithm for ultimate tic-tac-toe game. input args: depth(int): current depth level currBoardIdx(int): current local board index isMax(bool):boolean variable indicates whether it's maxPla...
def checkWinner(self): # Return termimnal node status for maximizer player 1-win,0-tie,-1-lose """ This function checks whether there is a winner on the board. output: winner(int): Return 0 if there is no winner. Return 1 if maxPlayer is the winner. ...
The function implements the alpha-beta pruning algorithm for a game (likely Ultimate Tic-Tac-Toe), recursively evaluating game states to determine the optimal move. It checks terminal conditions (max depth, winner, or no moves left), computes scores using `evaluateDesigned`, and explores valid moves by simulating playe...
def Your_alphabeta_Agent(self, depth, currBoardIdx, alpha, beta, isMax): """ This function implements alpha-beta algorithm for ultimate tic-tac-toe game. like the one above, except it calls evaluateDesigned for score input args: depth(int): current depth level currBoardIdx(int): ...
def checkMovesLeft(self): """ This function checks whether any legal move remains on the board. output: movesLeft(bool): boolean variable indicates whether any legal move remains on the board. """ # YOUR CODE HERE for i in self.board: # go...
This function simulates a game between predefined offensive and defensive agents using either minimax or alpha-beta pruning. It determines optimal moves for each player, tracks game states, expanded nodes, and evaluates the winner. The function alternates turns, evaluates move values, selects the best move, updates the...
def playGamePredifinedAgent(self, maxFirst, isMinimaxOffensive, isMinimaxDefensive): """ This function implements the processes of the game of predifined offensive agent vs defensive agent. input args: maxFirst(bool): boolean variable indicates whether maxPlayer or minPlayer plays first....
def checkMovesLeft(self): """ This function checks whether any legal move remains on the board. output: movesLeft(bool): boolean variable indicates whether any legal move remains on the board. """ # YOUR CODE HERE for i in self.board: # go...
Your return This function simulates a game between the agent and a predefined offensive agent using alpha-beta pruning. It evaluates all possible moves, selects the optimal one (maximizing/minimizing based on player turn), updates the game board, and records each move's coordinates, board states, and expanded nodes. Th...
def playGameYourAgent(self): """processes of the game of your own agent vs predifined offensive agent. input args: output: bestMove(list of tuple): list of bestMove coordinates at each step gameBoards(list of 2d lists): list of game board positions at each move winner(int...
def checkMovesLeft(self): """ This function checks whether any legal move remains on the board. output: movesLeft(bool): boolean variable indicates whether any legal move remains on the board. """ # YOUR CODE HERE for i in self.board: # go...
The function simulates a game between a human player and an AI agent, tracking the best moves made at each step, recording the game board states, and determining the winner (1 for maxPlayer, -1 for minPlayer, 0 for tie). It alternates turns, uses alpha-beta pruning for AI decisions, validates human input, and returns t...
def playGameHuman(self): """ This function implements the processes of the game of your own agent vs a human. output: bestMove(list of tuple): list of bestMove coordinates at each step gameBoards(list of 2d lists): list of game board positions at each move winner(int): 1 ...
def file_open(input_file): """Opens a file as read and returns a list with the lines as its elements Opens a file as read only. Each line becomes an element of a list. Each line/element is a string object. Args: input_file: filepath. String instance. Returns: A list. Each line in...
The code processes an input file to extract and sum numerical parts from specific rows in a structured dataset. It opens the input file, prepares the data, iterates over predefined row indices (e.g., 25), identifies relevant numerical values in those rows, accumulates their sum, and prints the result. The task likely i...
def sandbox(): # Open input file #input_list = file_open("input_example_day03_part1.txt") input_list = file_open("input_day03.txt") # Pre-process input file lol = prepare_data(input_list) sample_row_indexes = [25] sum_of_parts = 0 for sample_row_index in sample_row_indexes: pa...
def file_open(input_file): """Opens a file as read and returns a list with the lines as its elements Opens a file as read only. Each line becomes an element of a list. Each line/element is a string object. Args: input_file: filepath. String instance. Returns: A list. Each line in...
The main task of the code is to read and process an input file containing data, preprocess it into a structured format, summarize its characteristics (type, length, and line details), extract relevant numerical parts from the data, and compute their sum for output. The code orchestrates these steps to analyze and repor...
def main(): """Whole logic Pulls and glues all the other elements of the module. """ # Open input file #input_list = file_open("input_example_day03_part1.txt") input_list = file_open("input_day03.txt") # Pre-process input file lol = prepare_data(input_list) # Report of the input ...
def uniAprox(factor=0): global dev ( inputs, expected, dev ) = get_training_set( "../datos/Spectra100 - Spectra100.csv" ) uni = UniAprox( inputs, expected, gaussian, factor ) plot(inputs, expected, uni, f"Universal Aproximator lambda = {factor}", "", "") get_metric(uni) def draw_elbow_method(): ...
The main task of the code is to evaluate and compare different configurations of neural network approximators. It tests universal approximators with varying lambda values (0, 0.001, 0.01, 0.1, 1), uses the elbow method to determine optimal neuron counts for RBF networks, and then applies RBF approximation with fixed ne...
def main(): print("Programa Cliente Iniciado") # Aproximador universal lambdas = [ 0, 0.001, 0.01, 0.1, 1] for lamb in lambdas: uniAprox(lamb) #RBF draw_elbow_method() # Para observar la mejor cantidad de neuronas # Se busca un buen lambda lambdas = [ 0, 0.001, 0.01, 0.1] ...
def read_data(infile): excel_data = pd.read_excel(infile) excel_data = excel_data.loc[(~excel_data['page'].isnull()) & (~excel_data['type'].isnull()), :] excel_data['session'] = excel_data['session'].astype(str) excel_data['page'] = excel_data['page'].astype('int') e...
The main task of the code is to generate a survey JSON by reading input data, filtering it based on a specified session, and creating paginated content with language localization, using the filtered data and provided language parameter.
def gen_survey_json(infile, session, language): data = read_data(infile) data = filter_data_by_session(data=data, session=session) gen_pages(data=data, previous_home_test_item=None, language=language)
def read_data(infile): excel_data = pd.read_excel(infile) excel_data = excel_data.loc[(~excel_data['page'].isnull()) & (~excel_data['type'].isnull()), :] excel_data['session'] = excel_data['session'].astype(str) excel_data['page'] = excel_data['page'].astype('int') e...
The code generates a JSON configuration for a survey by reading and filtering input data, randomizing items, creating pages and triggers, and structuring the JSON with specified formatting, progress settings, and response constraints.
def gen_survey_json(infile, session, previous_home_test_item, language): data = read_data(infile) data = filter_data_by_session(data=data, session=session) data = randomize_taste_order(data) pages = gen_pages(data=data, previous_home_test_item=previous_home_test_item, ...
def add_box(self, x, y, z, type, timeout=4): """ Adds a box at x, y, z coordinate in the Rviz Scene :param x: The X-coordinate where the box is to be added :param y: The Y-coordinate where the box is to be added :param z: The Z-coordinate where the box is to be added :pa...
The code's main task is to control the UR5_2 robotic arm to detect a package under its end effector, activate a vacuum gripper to pick it up, transport it to a color-matched bin, release it, update shipment status, and track package count and color data. It uses sensor feedback, gripper activation, pose tracking, and m...
def pickup(self, message): """ Callback function which makes the ur5_2 arm pick up the package from the conveyor belt when the box is placed just under the ur5_2 end effector, and takes the package over to the appropriate coloured bin and releases the package. :param message: Indicates ...
def get_sqs_data(queue_name): try: sqs = boto3.client('sqs') sqs_queue_url = sqs.get_queue_url(QueueName=queue_name)['QueueUrl'] response = sqs.receive_message( QueueUrl=sqs_queue_url, MessageAttributeNames=[ 'location', 'cuisine', 'time', 'num_people'...
The main task of the code is to process SQS messages containing user preferences (cuisine, people, time, phone number), query Elasticsearch for restaurant matches, retrieve detailed restaurant data from DynamoDB, format the results into a text message, and send SMS notifications via SNS.
def lambda_handler(event, context): es_host = 'https://search-restaurants2-xqt3bqq5fplztqekgfhoji5wgy.us-east-1.es.amazonaws.com/restaurants2' table_name = 'yelp-restaurants2' messages = get_sqs_data('Q1') logging.info(messages) dynamodb = boto3.resource('dynamodb') table = dynamo...
def greet(intent_request): session_attributes = intent_request['sessionAttributes'] response = { 'sessionAttributes': session_attributes, 'dialogAction': { 'type': 'ElicitIntent', 'message': { "contentType": "PlainText", "content": "Hey Bud...
The main task of the code is to route incoming user intents to corresponding handler functions based on the intent name. It logs intent details, checks the intent type, and executes the appropriate function (greet, thankyou, or get_restaurants) for supported intents, raising an error if the intent is unrecognized.
def dispatch(intent_request): """ Called when the user specifies an intent for this bot. """ logger.debug('dispatch userId={}, intentName={}'.format(intent_request['userId'], intent_request['currentIntent']['name'])) intent_name = intent_request['currentIntent']['name'] # Dispatch to your bot...
def __get_tab(self): return Application.get_or_create().get_tab(self.__TAB_NAME) def __agg_expander(self, outer_container): agg_expander = outer_container.expander('Aggregation', False) left_col, right_col = agg_expander.columns([1, 2]) corpora = self.__corpus_selector(left_col, 'agg', ...
The `init_gui` method initializes a graphical user interface by creating a tab container and adding multiple collapsible sections (expanders) to it. These expanders, named `agg`, `knn`, `change`, and `join`, likely organize distinct UI components or settings within the tab. The method structures the GUI layout for user...
def init_gui(self): tab = self.__get_tab() outer_container = tab.container() self.__agg_expander(outer_container) self.__knn_expander(outer_container) self.__change_expander(outer_container) self.__join_expander(outer_container)
def SeT_iNpUt_DAta(input_file_name, outputSheet): input_file = openpyxl.load_workbook(input_file_name) inputSheet = input_file.active start = 2 time = inputSheet.cell(start, 1).value # Variables to store sum variable u_sum = 0 v_sum = 0 w_sum = 0 # Iterating complete file till time value is not None ...
The code processes an input Excel file to perform octant analysis based on velocity data, generating a structured output Excel file. It extracts the filename, initializes a workbook with specific headers, calculates overall octant counts, transition counts, and longest subsequences using helper functions, then saves th...
def entry_point(input_file, mod): fileName = input_file.split("\\")[-1] fileName = fileName.split(".xlsx")[0] outputFileName = "output/" + fileName + "_OcTaNt_AnAlySis_mod_" + str(mod) + ".xlsx" outputFile = openpyxl.Workbook() outputSheet = outputFile.active outputSheet.cell(row=1, column=14).value = "Overal...
def display_message(message,x,y): Largetext = pygame.font.SysFont("comicsansbold", 60) TextSurf, TextRect = text_objects(message, Largetext) TextRect.center = (x, y) gameDisplay.blit(TextSurf, TextRect) pygame.display.update() time.sleep(0.1) def car_display(x,y): gameDisplay.blit(carimg, (x...
This code defines a game loop for a racing game where the player controls a car to avoid obstacles (Goombas, Koopas, bombs) while moving along a scrolling road. It handles player input, collision detection, score tracking, speed adjustments, and high score management. The game displays countdown messages, updates graph...
def game(goombay,goombax,score,goombaspeed,koopay,koopax,koopaspeed,bomby,bombx,bombspeed,graphics,road_y): gameDisplay.fill(black) pygame.mixer.music.stop() pygame.mixer.music.load('Music\Track_music.wav') pygame.mixer.music.play() display_message("Ready?",400,50) time.sleep(1) display_mes...
def main_menu(): os.startfile('Mario Kart Remastered Intro Screen.py') def game(goombay,goombax,score,goombaspeed,koopay,koopax,koopaspeed,bomby,bombx,bombspeed,graphics,road_y,graphics2,score2): gameDisplay.fill(black) pygame.mixer.music.stop() pygame.mixer.music.load('Music\Track_music.wav') pygam...
This function creates a Pygame button that draws a colored rectangle with text, changes color when hovered, and triggers predefined actions (main menu or game start) when clicked. It checks mouse position and click status, executes the 'action' function if specified, and renders the button's visual elements on the game...
def button(msg,x,y,w,h,ic,ac,action=None): mouse = pygame.mouse.get_pos() click = pygame.mouse.get_pressed() if x + w > mouse[0] > x and y + h > mouse[1] > y: pygame.draw.rect(gameDisplay, ac, (x, y, w, h)) if click[0] == 1 and action != None: if action == "main_menu": ...
def get_spinners_text(self): ## colour names from Spinner text spinner_01 = self.ids.colour_01_spinner.text spinner_02 = self.ids.colour_02_spinner.text spinner_03 = self.ids.mix_01_spinner.text spinner_04 = self.ids.mix_02_spinner.text data = [spinner_01, spinner_02, spinner_03, spinner_04] return dat...
The code handles the "Save" button action by checking if valid data exists to save. If not, it shows a "Nothing to save" message. If no filename is set, it triggers a save dialog. Otherwise, it proceeds to save the data.
def on_save_button_pressed(self): data = self.get_spinners_text() if data == ['Colour 1', 'Colour 2', 'Tint 1', 'Tint 2'] or \ data == [] or \ data == ["Titanium White", "Titanium White", "Titanium White", "Titanium White"]: ## pop up an information dialog saying there's nothing to save. ic("Nothing ...
def dismiss_popup(self): print("dismiss_popup...") self._popup.dismiss() def on_save_button_pressed(self): data = self.get_spinners_text() if data == ['Colour 1', 'Colour 2', 'Tint 1', 'Tint 2'] or \ data == [] or \ data == ["Titanium White", "Titanium White", "Titanium White", "Titanium White"]: ##...
This function handles a yes/no user response to determine whether to save data or reset. If the reply is True, it dismisses the popup and triggers the save action; if False, it dismisses the popup and triggers a reset. The core task is to process user confirmation and execute corresponding actions based on their choice...
def new_yes_no(self, reply): if reply == True: ## YES, we want to save the data. self.dismiss_popup() self.on_save_button_pressed() else: ## NO, we do NOT want to save the data. self.dismiss_popup() self.on_new_reset()
def print_board(board): for row in board: print(" | ".join(row)) print("-" * 9) def get_best_move(board): best_val = -math.inf best_move = (-1, -1) for i, j in get_empty_cells(board): board[i][j] = "O" move_val = minimax(board, 0, False) board[i][j] = " " ...
The code implements a Tic-Tac-Toe game where a human player (X) and an AI (O) alternate turns. The AI selects optimal moves using a `get_best_move` function. The game checks for wins or ties after each move, displays the board, and ends with a win/loss/tie message.
def play_tic_tac_toe(): board = [[" " for _ in range(3)] for _ in range(3)] players = ["X", "O"] current_player = random.choice(players) while True: print_board(board) if current_player == "X": row, col = map(int, input("Enter your move (row and column, separated by space):...
def _get_pancake_choice() -> int: param_options = ( "Pick an option: \n" + "(1): Input the pancakes unique values yourself\n" + "(2): Auto generate unordered list of pancake values\n" + "Your choice: " ) is_valid_command, input_choice = False, 0 while not is_valid_comman...
The function `get_inputs()` collects user input to generate a list of integers, either manually with validation or automatically by creating a shuffled list up to a specified max value, ensuring inputs are valid numbers and returning the resulting list for further processing.
def get_inputs() -> list[int]: """ This function will prompt user input and generate appropriate data based on user command. Possible values: (1) Manually input all values of pancakes (2) Auto generate unordered list of values with specify max value Notes: For manual, if the in...
def add_enemy(self, type_=False, add_pos=0): """Enemy Adder, Not In Wave""" enemy = self.spawn_enemy_type( self.current_l_wave, self.level_index) if type_ else NormalEnemy() self.level_index += (1 if type_ else 0) if self.current_level_w_1 is not None: if self.lev...
The code manages enemy spawning, progress tracking, and wave transitions in a game. It checks if all enemies in a wave are dead to advance progress, spawns initial enemies, handles wave transitions, and declares victory when all enemies are defeated.
def manage_enemies(self): """ Manage Enemy: - Spawning - Check Progress - Check If Wave """ if self.enemy_in_wave is not None: # Check if all enemy in wave is dead, then add progress and continue if len(self.enemy_in_wave) == 0:...
def primal_simplex(c, A, b, modified={}): status = '' n = len(c) m = len(b) # init if modified == {}: N_index = np.array(range(1, n + 1)) B_index = np.array(range(n + 1, n + m + 1)) B = np.identity(m) A = np.concatenate([A, B], axis=1) N = A[:, (N_index - 1)]...
The code determines the appropriate simplex method to apply based on initial conditions: if the primal solution is feasible and not optimal, it uses the primal simplex; if the dual solution is feasible and not optimal, it uses the dual simplex; otherwise, it employs the two-phase method. The function selects and execut...
def simplex_method(c, A, b): x_b = b z_n = -c if np.all(x_b >= 0) and np.any(z_n < 0): print(primal_simplex(c, A, b)) elif np.all(z_n >= 0) and np.any(x_b < 0): print(dual_simplex(c, A, b)) else: print(two_phase(c, A, b))
def compute_Br_mat_real(r,theta,phi,L): M = len(r) N = (L+1)**2 ret_mat = np.zeros((M,N)) k = 0 for l in range(L+1): ret_mat[:,k] = l*r**(l-1)*np.real(sph_harm(0,l,phi,theta)) k += 1 for m in range(1,l+1): tmp = 2*l*r**(l-1)*sph_harm(m,l,phi,theta) ...
This function computes the Jacobian matrix of a magnetic field model with respect to parameters like probe positions, orientations, and field coefficients. It calculates analytical derivatives of B-field components using spherical coordinates, combines them with orientation vectors, and adds numerical approximations fo...
def Jac_M_real(r,c,ay,az,bx,bz,gx,gy,dx,dy,dz,sx,sy,sz): #stepsize for the approximation in dx dy dz eps_d = 1e-6 #number of measurements num_meas = r.shape[0] L = np.int32(np.sqrt(len(c)) - 1) #number of field DoFs N = (L+1)**2 #output Matrix J = np.zeros((3*num_meas,N +18)) ...
def safe_merge(source, dest, include=None, exclude=None): """ Merges two dictionaries, converting the keys in the source dictionary from snake case to camel case where appropriate. """ def handle_match(match): return '{chr1}{chr2}'.format(chr1=match.group(1), chr2=match.group(2).upper()) ...
This function creates a pool with specified parameters, handling both hosted test and standard modes. It sets start/end dates, merges additional data, generates unique IDs, and constructs a POST request to the appropriate endpoint, returning the response JSON.
def create_pool(self, owner_key, pool_data): start_date = pool_data['start_date'] if 'start_date' in pool_data else self.date_now end_date = pool_data['end_date'] if 'end_date' in pool_data else start_date + datetime.timedelta(days=365) pool = { 'startDate': start_date, ...
def read_test_data(filename): """ Try to read test data from json file. """ try: with open(filename) as fp: try: data = json.load(fp) except ValueError as err: log.error("Unable to read file {} with test data: {}".format(filename, str(err))...
The main task of the code is to generate RPM packages and repositories using test data, with GPG signing. It checks for an existing GPG key, creates one if needed, extracts the key grip, configures GPG settings, modifies RPM macros, generates packages, and builds repositories. Errors during package generation trigger a...
def main(): if len(sys.argv) != 2: log.error("Syntax {name} test_data.json".format(name=sys.argv[0])) return 1 test_data = read_test_data(sys.argv[1]) gpg_exists = does_gpg_key_exist() if gpg_exists != 0: log.info("") log.info("Creating GPG key...") create_gpg_...
def create_scheduler(self, num_training_steps: int): warmup_steps = self.opts.warmup_steps if self.opts.warmup_steps > 0 \ else math.ceil(num_training_steps * self.opts.warmup_proportion) training_steps = self.opts.epochs * num_training_steps if self.opts.scheduler_name == SchedulerN...
This code trains a machine learning model by validating input datasets, configuring data loaders, calculating training steps/epochs, setting up learning rate schedules, logging training metrics, and iterating over epochs to train the model. It includes evaluation, early stopping, saving optimal models, and updating tra...
def train(self): self.stats.update_time() if self.train_set is None or \ (not isinstance(self.train_set, Dataset) and not isinstance(self.train_set, TorchDataset)): raise TypeError( f"Expected type `torch.utils.data.Dataset` or `datasets.arrow_dataset.Dataset...
def del_es_index(es): if len(sys.argv)<4: print("Usage: <host> <cmd> <index>") sys.exit(-1) index = sys.argv[3] indices = es.indices.get(index).keys() for ind in indices: es.indices.delete(ind) def find_terms_topN(es): if len(sys.argv)<8: print("Usage:<host><cmd><...
This function routes Elasticsearch operations based on the input command. It executes actions like deleting indices, retrieving top terms, analyzing HTTP servers, extracting mail credentials, counting documents, and managing index states (open/close) by calling corresponding functions. The command parameter determines ...
def handle_cmd(es,cmd): if cmd == "del": del_es_index(es) elif cmd == "term_topN": find_terms_topN(es) elif cmd == "http_servers": get_http_unusual_server_and_port(es) elif cmd == 'mail_users': get_mail_user_passwd(es) elif cmd == 'count': count(es) elif ...
def getValidLocations(board): validLocations = [] for col in range(COLCOUNT): if isValidLocation(board, col): validLocations.append(col) return validLocations def isTerminalNode(board): return winningMove(board, PLAYERPIECE) or winningMove(board, AIPIECE) or len(getValidLocations(board)) == 0 def winningMove(b...
This function implements the minimax algorithm with alpha-beta pruning for a Connect Four-like game. It evaluates board states recursively, choosing optimal moves by maximizing AI scores (when maximizingPlayer=True) or minimizing opponent scores (when False). It returns the best column and corresponding score, using de...
def minimax(board, depth, alpha, beta, maximizingPlayer): validLocations = getValidLocations(board) isTerminal = isTerminalNode(board) if depth == 0 or isTerminal: if isTerminal: if winningMove(board, AIPIECE): return (None, 10000000) elif winningMove(board, PLAYERPIECE): return (None, -10000000) ...
def SquareUnderAttack(self , r , c): #Determine if the enemy can attack the square r ,c self.whiteToMove = not self.whiteToMove #switch to the opponent' POV oppmoves = self.AllPossibleMoves() self.whiteToMove = not self.whiteToMove #Switch turns back for move in oppmoves: if...
The main task of the code is to generate all valid castle moves for the king at position (r,c) based on the current player's castling rights (king-side or queen-side) and ensure the king is not in check. It checks if the square is under attack, skips castling if in check, and invokes corresponding helper methods to add...
def CastleMoves(self , r , c , moves): #Generate all valid castle moves for the king at the given square (r,c) and add the to the list of moves if self.SquareUnderAttack(r,c): #If we use the "SquareUnderAtack" or "InCheck" functions we would end up with a infinity recursion return #Can't castle whil...
def AllPossibleMoves(self): #All moves without considering checks moves = [] for r in range(len(self.board)): #Number of rows for c in range(len(self.board[r])): #Number of columns in the current row turn = self.board[r][c][0] if (turn == 'w' and self.whit...
The code generates all valid chess moves by first creating possible moves, then simulating each to check if the king is attacked (in-check). Invalid moves are removed, and it determines checkmate/stalemate. It temporarily stores and restores enpassant and castling rights, ensuring only legal moves remain.
def ValidMoves(self): TempEnpassant = self.enpassant TempCastle = CastleRights(self.CurrentCastlingRight.wks , self.CurrentCastlingRight.bks , self.CurrentCastlingRight.wqs , self.CurrentCastlingRight.bqs) #Copy the current castle rights #1) Generate all possible...
def generateOldMirCommands(expID, peers, clients): output("#========================================") output("# {0} (Old Mir)".format(expID)) output("#========================================") output("\n") # both peers and clients are dictionaries with slave tags as keys # and the assigned c...
The code processes experiment configuration parameters, handles user input for existing experiments, and generates setup commands based on deployment type or legacy mode. It parses tokens to define clients/peers, manages experiment IDs, and ensures proper configuration file handling before executing or skipping the exp...
def run(expID, tokens): global lastFinished global idOffset global experimentIdDigits global skipAllExisting runOldMir = False # If oldmir is the first token, run old mir if tokens[0] == "oldmir": runOldMir = True tokens = tokens[1:] # If special value "next" is specifi...
def available_pos(self): pos = [] for i in range(board_rows): for j in range(board_cols): if self.board[i, j] == 0: pos.append((i, j)) return pos def update_state(self, pos): self.board[pos] = self.player_symbol # switch players for...
The code simulates a two-player game over a specified number of rounds, alternating turns between Player 1 and Player 2. Each player selects actions based on available positions and updates the game state. After each move, it checks for a winner and resets the game if a winner is found. After completing all rounds, bot...
def play(self, rounds=100): for i in range(rounds): if i % 1000 == 0: print("Round {}".format(i)) while not self.is_end: # Simulating p1's turn pos = self.available_pos() p1_action = self.p1.choose_action(pos, self.board, se...
def is_valid_name(string): """ param: str(user input) The function first checks if the input is of type string. If it is of type string, it then checks if the length is between 3 and 25 inclusive. Returns: False if not of type str or wrong not between 3 and 25 inclusive. True if...
The main task of the code is to validate a list of five strings (`cats`) against specific criteria using helper functions. If valid, it maps the strings to keys (`name`, `info`, `priority`, `duedate`, `done`) in a dictionary, converting the priority to an integer. If invalid, it returns error details (type/value) or th...
def get_new_task(cats, dictionary): """ param: cats (a list of strings) param: dictionary(contains mapping between the keys to categories) The functions first checks if there are 5 strings in cats It then checks if any of them aren't type str It then checks is_valid_completion(cats[4]), is_valid...
def is_valid_index(idx, in_list, start_idx = 0): """ param: idx (str) - a string that is expected to contain an integer index to validate param: in_list - a list that the idx indexes param: start_idx (int) - by default, set to 0; an expected starting value for idx that ...
The function updates a specific field in a task dictionary within a list, validating the index and field value using helper functions. It adjusts the index with start_idx, checks validity, and updates the field if valid. Returns the updated task, error codes for invalid inputs, or the invalid field key.
def update_task(info_list, idx, priority_map, field_key, field_info, start_idx = 0): """ param: info_list - a list that contains task dictionaries param: idx (str) - a string that is expected to contain an integer index of an item in the input list param: start_idx (int) - by default is set ...
def scale(data, axis=(0,)): if data is None: return None if min(data.shape) == 0: return data ranges = np.array(data.max(axis) - data.min(axis)) ranges[ranges == 0] = 1 data = (data - data.min((0,))) / ranges * 2 - 1 return data def plotar(data, col=None, size=None, *, xyz=None, ...
The function `animate` processes input data to generate structured animation parameters for visualization. It normalizes spatial coordinates (`xyz`), handles time values (numeric/datetime/categories), ensures data uniqueness, and prepares grouped animation frames with time labels and scaling. The output includes animat...
def animate(data, xyz, *, animation_frame, group=None, duration_seconds=30, tstart=None, time_codes_per_second=None, time_values=None, time_labels=None, auto_scale=True, push_data=True, return_data=True, **kwargs): if group is None: group = pd.Series(1) if not isinstance(group, l...
def run_portfolio_lvl_regression_CAPM(name, period='1M', save=True): """ Runs and evaluates quintile portfolio level regression for monthly formation dates and 1M, 6M or 12M excess return as dependent variable. Independent variable is only the index return and a constant to estimate alpha after c...
The function `est_alphas_summary` computes alphas and their p-values for portfolio or stock-level abnormal returns, adjusted for CAPM or FF5FM factors, across 1M, 6M, and 12M periods and quintiles. It calculates alphas for each quintile, the Q5-Q1 difference, and associated p-values using regression results. The output...
def est_alphas_summary(model_names, factors, lvl, save_as=None): """ Computes the alphas for either portfolio or stock level abnormal returns, unexplained by a given factors model (either CAPM or FF5FM). The function computes alphas for different periods (1M, 6M, 12M) and for different quintiles. It also c...
def show_message(myText, lockWait = False): """Prints a message on the window while looking for user input to continue. The function returns the total time it waited. If the argument 'lockWait' isn't passed, the default allows users to press any key to exit the message shown. Parameters ------...
The main task of the code is to conduct and record data from a reach-and-point task trial, varying based on block type (e.g., Baseline, Exposure) and participant group (e.g., Physical Practice, Motor Imagery). It tracks reaction times, stimulus locations, and response metrics (e.g., touch points, distances) while handl...
def run_trial(block, group, participant_info): """Parameters for different trial types of a reach and point task During motor imagery and control exposure trials, the stimulus disappears when the spacebar is lifted. During all other trials, stimulus disappears when stimulus is touched. Parameters ...
def get_participant_info(): """Collects demographics info from the participants Returns ------- dict A dictionary of participant info """ created = time.strftime("%Y-%m-%d %H:%M:%S") while True: participant_id = get_input('ID (\'test\' to demo): ') participant_id =...
This code runs a multi-phase experiment involving participant data collection and task execution. It initializes participant data, conducts familiarization, baseline, exposure (with group-specific instructions), and post-test blocks, managing equipment swaps between phases. The exposure phase repeats 10 times with brea...
def run(): """Runs the experiment from start to end """ participant_info = get_participant_info() participant_id = participant_info['id'] group = participant_info['group'] # Create data folder/files for the participant df = init_data(participant_id) # Familiarization block show_me...
def filterQuestions(storyID, questions): filteredQuestions = [question for question in questions if question.id.startswith(storyID)] # Sort questions not by ascii value as that leads to xxx-10 # being sorted before xxx-9 but my the value of the last digits. sortedQuestions = sorted(filteredQuestions, k...
The code processes a file containing directory and story IDs to generate answers for filtered questions using NLP. It loads questions, extracts named entities, and classifies answers with spaCy's model, outputting results for each question-story pair.
def qa(): file = open(sys.argv[1], "r") lines = [line.strip() for line in file.readlines()] directory = lines[0] storyIDs = lines[1:] questions = typeQuestions.getQuestions(directory) stories = namedEntityRecognition.getNamedEntities(directory) nlp = spacy.load("en_core_web_md") for i...