dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def codetoidx(code): return (int(code[1])-1)*8 + (ord(code[0]) - ord('A')) def turn(board): if (board.count('X') + board.count('O')) % 2 == 0: return 'X' else: return 'O' def checkidx(boards, tkn): global movesCache, holePos if (boards, tkn) in movesCache: return movesCache[(boards, ...
The main task of the code is to process command-line inputs for a board game, determine valid moves based on the current player's token, and use the alphabeta algorithm to calculate the optimal move sequence with a depth-limited search, outputting the score and moves. It handles board configuration, player turn logic, ...
def main(): global holePos, MAX_DEPTH def_board = '.' * 27 + 'OX' + '.' * 6 + 'XO' + '.' * 27 board = def_board tkn = '' idxs = [] if(len(sys.argv) >= 2): if(len(sys.argv[1]) > 2): board = sys.argv[1].upper() elif(sys.argv[1].isdigit()): idxs.append(in...
def opp_color(color): if color == Color.BLACK: return Color.WHITE elif color == Color.WHITE: return Color.BLACK else: raise ValueError def sort_by_eval(self, boards, color): """ Return list of board in ascending order by eval value """ evals = {} ...
The main task of the code is to implement an alpha-beta pruning algorithm with transposition tables and move ordering for Othello game AI. It recursively evaluates board states by exploring available moves, prioritizing high-value positions to optimize search efficiency, and returns the optimal move value while storing...
def alpha_beta(self, board, depth, color, turn_flag, alpha=-np.inf, beta=np.inf): """ Alpha beta search Parameters ------- board : ndarray depth : int color : Color turn_flag : bool """ new_board = EvalOthelloBoard(board.copy()) "...
def update_action_layer(self, previous_proposition_layer): """ Updates the action layer given the previous proposition layer (see proposition_layer.py) You should add an action to the layer if its preconditions are in the previous propositions layer, and the preconditions are not pairwis...
The code's main task is to expand a current layer by first setting actions based on previous layer's propositions and mutex propositions, then establishing mutex actions, and finally defining new propositions and their mutex relations in the proposition layer. This process builds hierarchical layers in a planning algor...
def expand(self, previous_layer): """ Your algorithm should work as follows: First, given the propositions and the list of mutex propositions from the previous layer, set the actions in the action layer. Then, set the mutex action in the action layer. Finally, given all t...
def DetectChanges(frameworkDependencyDict): visited_files = list() libNameChanges = list() for framework, libraries in frameworkDependencyDict.items(): for libraryDict in libraries: libNameChanges.extend(WalkDictTree(libraryDict, visited_files)) return libNameChanges def ResolveExecu...
The function `PerformChanges` modifies framework dependencies by replacing specified name patterns using Xcode tools. It detects changes, copies missing frameworks, adjusts file permissions, and applies name replacements to binaries and dependencies. It returns 0 on success or 1 if any operation fails, ensuring correct...
def PerformChanges( frameworkDependencyDict, replaceFromToPairs=None, executable_path="/tmp/klayout" ): libNameChanges = DetectChanges(frameworkDependencyDict) #print(libNameChanges) cmdNameId = XcodeToolChain['nameID'] cmdNameChg = XcodeToolChain['nameCH'] if replaceFromToPairs is None: r...
def is_leaf(tree): """Returns True if the given tree's list of branches is empty, and False otherwise. """ return not branches(tree) def tree(label, branches=[]): """Construct a tree with the given label value and a list of branches.""" if change_abstraction.changed: for branch in branch...
The code defines a function `square_tree` that recursively transforms a tree structure by squaring the value of each node's label while preserving the tree's hierarchical structure. It handles leaf nodes by squaring their label directly and applies the same operation to all branches of non-leaf nodes, ensuring every el...
def square_tree(t): """Return a tree with the square of every element in t >>> numbers = tree(1, ... [tree(2, ... [tree(3), ... tree(4)]), ... tree(5, ... [tree(6, ... [tree(7)]), ... tree(8)])]) >>> print_tree(square_tree(numbers)) 1 4 9 16 25 ...
def tree(label, branches=[]): """Construct a tree with the given label value and a list of branches.""" if change_abstraction.changed: for branch in branches: assert is_tree(branch), 'branches must be trees' return {'label': label, 'branches': list(branches)} else: for br...
The function `copy_tree` creates a deep copy of a given tree structure, ensuring that modifications to the original tree do not affect the copied tree. It recursively duplicates each node's label and all its branches, producing an independent tree with the same hierarchical structure and values. This is primarily used ...
def copy_tree(t): """Returns a copy of t. Only for testing purposes. >>> t = tree(5) >>> copy = copy_tree(t) >>> t = tree(6) >>> print_tree(copy) 5 """ return tree(label(t), [copy_tree(b) for b in branches(t)])
def load_mismatch_neigh(data_id:int, kmer_size:int, n_miss:int) -> tuple: """ Load the saved neighbours and kmer set using pickle package. """ assert (data_id==0) or (data_id==1) or (data_id==2), "Data_id should be in the range [0,1,2]. Please try again." file_name = 'neigh_'+str(data_id)+'_'+str(km...
The function `load_or_compute_neigh` loads or computes k-mer neighbors and a k-mer set for a specified dataset. It validates the dataset ID (0, 1, or 2), attempts to load precomputed data, and if unsuccessful, generates the k-mer set from training/test data, computes mismatch neighbors, and saves the results using `pic...
def load_or_compute_neigh(data_id:int, kmer_size:int,n_miss: int) -> tuple: """ Load or compute the neighbours and kmer_set for th given dataset. """ assert (data_id==0) or (data_id==1) or (data_id==2), "Data_id should be in the range [0,1,2]. Please try again." try: neigh,kmer_set = load_mi...
def remove_border(img): img_cp = img.copy() top_border = img_cp[:29, :, :] top_border = threshold_border(top_border) # canny_cut_image_horizontal(top_border) bottom_border = img_cp[195:, :, :] bottom_border = threshold_border(bottom_border) # canny_cut_image_horizontal(bottom_border) le...
The function tints specific regions of an image based on color masks (light/dark blue) and a background mask, applying multiplier values to adjust brightness. It isolates and modifies these regions separately, then combines them to produce a grayscale image with adjusted lighting and background tones.
def tint_cloth(img, light_multiplier, dark_multiplier, background_multiplier): img = remove_border(img) light_mask = mask_light_blue(img) dark_mask = mask_dark_blue(img) full_mask = mask_full(img) img_cp = img.copy() img_cp = np.array([img_cp[:, :, 0], img_cp[:, :, 1], img_cp[:, :, 2]]) img...
def label(self, face, x, y): offset = self.OFFSET return self.sides[offset[face] * 9 + x * 3 + y] def set_label(self, face, x, y, color): offset = self.OFFSET self.sides[offset[face] * 9 + x * 3 + y] = color def sanity_check(self): z2 = lambda sx: 0 if sx == "-" else 2 ...
This code rotates a face of a Rubik's cube (or similar puzzle) by rearranging its color labels and updating adjacent faces. It handles left ("l") or right ("r") rotations, adjusting the face's pebbles and propagating changes to neighboring faces. The process involves slicing/reversing pebble positions, fetching current...
def rotate(self, face, lr): pebbles = None face_left = self.FACE_LEFT[face] if lr == "l": pebbles = list(face_left) elif lr == "r": pebbles = list(reversed(face_left)) adj = [self.label(face, x, y) for x, y in pebbles] pebbles = pebbles[2:] + peb...
def random_network(network, usemetropolis = False, ): # initialize the heinous input struct web = cmfinder.mfinder_input() # setup the network info network, stats, web.Edges, web.NumEdges = mfinder_network_setup(network) # parameterize the analysis if not...
This function calculates motif participation in a network by analyzing node and link participation in motifs of specified size, handling weighted/unweighted networks, randomization, and statistical methods. It sets up network parameters, performs motif detection, and returns participation statistics while enforcing con...
def motif_participation(network, links = False, motifsize = 3, randomize = False, usemetropolis = False, stoufferIDs = False, allmotifs = False, weighte...
def random_network(network, usemetropolis = False, ): # initialize the heinous input struct web = cmfinder.mfinder_input() # setup the network info network, stats, web.Edges, web.NumEdges = mfinder_network_setup(network) # parameterize the analysis if not...
This function analyzes the roles of nodes and links in a network based on motif structures. It calculates role statistics using the mfinder library, considering parameters like motif size (2-3 for unipartite, up to 6 for bipartite), randomization, weighting, and Stouffer's method. It initializes network data, validates...
def motif_roles(network, links=False, motifsize = 3, randomize = False, usemetropolis = False, stoufferIDs = False, networktype = "unipartite", allroles = False, weighted = False, ...
def motif_participation(network, links = False, motifsize = 3, randomize = False, usemetropolis = False, stoufferIDs = False, allmotifs = False, weighte...
The code analyzes a network's motif participation and roles, computing statistical measures for node/edge involvement in motifs of specified size. It optionally assesses motif structure significance via randomization (if nrandomizations > 0) and returns comprehensive motif statistics, including roles and participation ...
def pymfinder(network, links=False, motifsize = 3, stoufferIDs = False, allmotifs = False, nrandomizations = 0, randomize = False, usemetropolis = False, networktype = "unipartite", weighted = F...
def getVaultSecrets(vault): secret_engines = [] # List All Secret Engines in the Vault secret_engines = listVaultSecretEngines(vault) for x in range(len(secret_engines)): listAllVaultSecrets(vault, secret_engines[x], "/") return vault_secrets def readSecret(vault, secret_engine, secret): ...
The function migrates secrets from an old vault to a new vault by retrieving all secrets from the old vault, iterating through each secret's key and path, reading the secret value, and writing it to the new vault. It handles errors by catching exceptions and printing an error message with details if migration fails.
def migrateVaultSecrets(old_vault, new_vault): try: secret_list = getVaultSecrets(old_vault) for key in secret_list: for secretpath in secret_list[key]: secret_value = readSecret(old_vault, key, secretpath) writeSecret(new_vault, key, secretpath, secret_va...
def print_values(self): print(f"{self.name} Voltage: {self.channel.voltage}v") print(f"{self.name}\t{self.status}") def log_moisture_change(self): current_moisture=self.calculate_moisture() if ((current_moisture not in self.previous_moisture and self.get_time_elapsed_in_seco...
The code's main task is to monitor and manage irrigation based on moisture levels. It prints current values, logs moisture changes, checks if moisture is below a dry threshold or if the system is absorbing, and triggers irrigation if conditions are met. This ensures optimal watering by responding to real-time moisture ...
def run(self): self.print_values() self.log_moisture_change() if self.calculate_moisture() <= self.dry_level or self.status.state == State.Absorbing: self.irrigate()
def autentikasi_user(self,username,password): if (username not in self.users): return { 'status': 'ERROR', 'message': 'User Tidak Ada' } if (self.users[username]['password']!= password): return { 'status': 'ERROR', 'message': 'Password Salah' } tokenid = str(uuid.uuid4()) self.sessions[tokenid]={ 'userna...
The code processes commands for a messaging system, handling authentication, sending/receiving messages, managing groups, file transfers, and retrieving user/group lists. It parses input data, validates commands, logs actions, and delegates tasks to corresponding methods like authentication, message sending, or group c...
def proses(self,data): j=data.split(" ") try: command=j[0].strip() if (command=='auth'): username=j[1].strip() password=j[2].strip() logging.warning("AUTH: auth {} {}" . format(username,password)) return self.autentikasi_user(username,password) elif (command=='send'): sessionid = j[1].s...
def grouptoggle(self, groupframe): groupframe.pack(side=tk.BOTTOM, anchor=tk.SW, fill=tk.X) def singlechat(self, frame, auth): userbutton = [] userchat = [] users = chatClient.proses("getallusers") users = json.loads(users) # users = [*users] for x in range(len(...
The code defines a `chat` method that initializes a GUI interface for a chat application using Tkinter. It sets up a frame with left and right panels: the left panel displays a welcome message, a group chat section, and a "New Group" button, while the right panel manages user and group chats. The method authenticates t...
def chat(self, auth): self.auth = auth # canvas = tk.Canvas(root, height=700, width=1000, bg="#22223b") # canvas.pack() # base frame self.frame = tk.Frame(root, bg="#4A4E69") self.frame.place(relwidth=0.8, relheight=0.8, relx=0.1, rely=0.1) # left frame ...
def nine_lines(): three_lines() three_lines() three_lines() def three_lines(): new_line() new_line() new_line() def new_line(): print('.')
The main task of the code is to simulate clearing the screen by printing multiple lines. It calls `nine_lines()` twice (18 lines), `three_lines()` twice (6 lines), and `new_line()` once (1 line), totaling 25 lines to push previous content out of view, mimicking a screen-clearing effect without using system-specific com...
def clear_screen(): nine_lines() nine_lines() three_lines() three_lines() new_line()
def fetch_from_s3(): s3_client, bucket_name, analysis_folder_name, txt_file_folder, question_sets_folder_name = aws_connection() key_path1 = question_sets_folder_name + 'qa_df_set_a_qa.csv' response1 = s3_client.get_object(Bucket=bucket_name, Key=key_path1) # Get the object containing the text file co...
The code processes a dataset by fetching data from S3, removes an unnecessary column, and iterates through each row to perform a similarity search on questions to gather contextual information. It then generates OpenAI-based answers using the context and corresponding questions, appending these responses to the dataset...
def qa_using_ks(): df = fetch_from_s3() df = df.drop(columns=['Unnamed: 0'], axis=1) df["context"] = "" for index, row in df.iterrows(): # Query OpenAI for each row and update the 'Technical Document' colum df.at[index, 'context'] = similarity_search( query=row['question...
def reset(self): self.write(self.REG_PWR_MGMT_1, [0x80]) time.sleep(0.01) # device reset bit is cleared when device reset is complete return self.readbyte(self.REG_PWR_MGMT_1) == 0x41 def read_id(self): return self.readbyte(self.REG_WHO_AM_I) def initialize(self): # disab...
This code initializes a sensor device via SPI, configuring gyroscope and accelerometer settings (e.g., DLPF, full-scale ranges) and verifying the device ID. It sets up communication parameters, disables I2C, opens the SPI bus, resets the device, reads the ID, and performs initialization to ready the sensor for data col...
def __init__(self, bus=1, cs=2): # gyro digital low pass filter configuration parameters # see register 26 documentation # Note bit 7 should be set to 0 by the user self._dlpf_cfg = 0x1 # 1kHz sample rate # gyro configuration # see register 27 documentation self...
def usage(argv): cmd = os.path.basename(argv[0]) print('usage: %s <config_uri> [var=value]\n' '(example: "%s development.ini")' % (cmd, cmd)) sys.exit(1) def create_all_tables(engine): Base.metadata.create_all(engine) def create_users(DBSession): type = [ { "type": "gen...
This code initializes a database by dropping existing tables, creating new ones, and populating initial data (users, masters) using configuration settings and transaction management. It processes command-line arguments, parses options, sets up logging, and executes database schema operations and data insertion within a...
def main(argv=sys.argv): if len(argv) < 2: usage(argv) config_uri = argv[1] options = parse_vars(argv[2:]) setup_logging(config_uri) settings = get_appsettings(config_uri, options=options) engine = create_dbengine(settings) Base.metadata.drop_all(engine) create_all_tables(engin...
def list_domains(config): domains_raw = os.listdir('/dev/shm/') domains = [] for domain in domains_raw: try: domain_list = os.listdir("/dev/shm/" + domain) if config['ram_filename'] in domain_list: domains.append(domain) except NotADirectoryError: ...
This function injects kernel shellcodes into a Windows domain by validating the domain, retrieving configuration offsets, patching first and second-stage shellcode with the ntoskrnl base address, verifying Windows version compatibility, fetching SSDT syscall addresses, and executing injection at predefined kernel entry...
def inject_domain(domain, config, offsets): if domain not in list_domains(config): raise InvalidDomain first_stage_sh = read_first_stage(config) second_stage_sh = read_second_stage(config) first_stage_offsets = offsets[config['first_stage_profile']] second_stage_offsets = offsets[config['sec...
def plane_from_3_points(p1, p2, p3): """Find plane equation ax+by+cd+d=0, return [a,b,c,d]""" a = (p2[1] - p1[1]) * (p3[2] - p1[2]) - (p3[1] - p1[1]) * (p2[2] - p1[2]) b = (p2[2] - p1[2]) * (p3[0] - p1[0]) - (p3[2] - p1[2]) * (p2[0] - p1[0]) c = (p2[0] - p1[0]) * (p3[1] - p1[1]) - (p3[0] - p1[0]) * (p2[...
The function computes the interpolated value at a given point within a tetrahedron defined by four nodes and their associated values. It checks if the point coincides with a node, returns the corresponding value, or if inside the tetrahedron, calculates a weighted average using distances to nodes, edges, and faces to d...
def tetrahedron_average(point, nodes, values, check=False): """Find point value from nodes of tetrahedron""" point = np.array(point) [p1, p2, p3, p4] = nodes p1, p2, p3, p4 = np.array(p1), np.array(p2), np.array(p3), np.array(p4) f1 = plane_from_3_points(p2, p3, p4) # Check is point is on the no...
def node_binary_search(self, x_pos): """Search for x position in range""" low, high = 0, len(self.yz_node) while True: if high >= low: mid = (low + high) // 2 # print(low, high, mid) if abs(self.yz_node[mid][1] - x_pos) <= self.elem_siz...
The function retrieves data (liquid fraction, temperature, gradients) at a specific x-position by spatially averaging nearby nodes within a tolerance. It identifies active nodes via binary search and radial expansion, assuming tetrahedron elements, then computes averages and gradients for ice front analysis, returning ...
def get_ice_front_data(self, x_pos, info=False): """Get data of specific point by spacial linear average of element nodes""" # find approximate range of x_pos in nodes ###################### global anchor_node,active_node ###################### anchor_node = self.node_bin...
def getLEB(self) -> int: ret: int = 0 digit: int = 0 while True: b: int = self.mem[self.idx] self.idx += 1 ret += ((b & 0x7f) << digit) digit += 7 if b < 0x80: break return ret def getString(self) -> str: ...
This code initializes an object to validate a binary file's structure. It checks file existence, opens it via memmap, verifies endianness, ensures the first section is 'dylink'/'dylink.0', processes section data, and validates alignment. Errors are logged in 'msg' if checks fail, setting 'valid' to False.
def __init__(self, file: str): self.valid: bool = True self.msg: str = "" if not os.path.exists(file): self.valid = False self.msg += f"Error: '{file}' doesn't exist." return try: self.mem = np.memmap(file, dtype=np.uint8) except ...
def create_new_file(self): shutil.copyfile( f"src/{self.output_class}_template.tex", f"src/{self.file_name}.tex", ) def add_contact_info(self): # Read in your .tex file tex_file_dir = f"src/{self.file_name}.tex" tex_file = open(tex_file_dir, "rt") ...
The main task of the code is to automate document generation by creating a new file, adding contact information, and organizing data entries into user-defined sections. It retrieves configured section order and titles, iterates through the DataFrame to populate each section with matching entries, and structures the out...
def automate(self): self.create_new_file() # Create new file self.add_contact_info() # Retrieve contact information # Retrieve user-configured section-ordering and titling sections_ordered = self.get_section_order() section_titles = self.get_section_titles() for secti...
def handle_showing_quiz_name(self, win, background): win.fill(background) font = pygame.font.SysFont(None, int(self.height / 10)) rendered_font = font.render(str(self.kahoot_name), True, "black") win.blit(rendered_font, (self.x + self.width / 2 - rendered_font.get_width() / 2, self.y)) ...
This code handles rendering different game screens by checking flags like show_quiz_name, show_countdown, etc., and calling corresponding methods to display quiz names, countdowns, choices, or leaderboards on the provided window and background.
def handle_game(self, win, background): if self.show_quiz_name: self.handle_showing_quiz_name(win, background) if self.show_countdown: self.handle_showing_countdown(win, background) if self.show_choices_screen: self.handle_choices(win, background) i...
def make_directory_if_not_exists(path): '''Crea un directorio si este no existe''' os.makedirs(path,exist_ok=True) def copy_file(from_path:str,to_path:str,replace_if_exists=False,move=False): '''Copia, mueve o reemplaza un archivo o directorio de from_path a to_path''' if is_file(from_path): ...
This function extracts a ZIP archive from given bytes to a specified path. It identifies the first file's name, ensures proper directory structure, creates necessary folders, extracts files, copies the primary file to the target path (replacing existing files), and deletes the extracted copy to avoid duplication.
def unzip_bytes(data:bytes,path:str): '''unzipea un archivo en el path especificado a traves de los bytes''' z = zipfile.ZipFile(io.BytesIO(data), "r") # z.read(path) # Reads the data from "foo.txt" #z.read(z.infolist()[0]) # Reads the data from the first file filename = z.infolist()[0].fil...
def get_cursor(collection, arguments, colletion_name): """get cursor based on request.args """ if len(arguments) > 2: return None parsed_dict = parse_args(dict(arguments), colletion_name) if parsed_dict is None: #cannot parse args return None # print(parsed_dict) cursor = col...
This function handles PUT requests for updating or inserting books/authors. It validates input arguments, checks for existing documents, and updates them if found. If no match, it inserts a new document. It ensures correct data formatting and aborts on errors like invalid arguments or missing data.
def books_or_arthors_put_func(collection, collection_name, js_dict=None): """function used in PUT of books/authors """ #number of arg must be 1 if len(request.args) != 1: abort(400) cursor = get_cursor(collection, request.args, collection_name) if cursor is None: abort(400) r...
def get_js_dict(): """helper function to get json file """ if (request.content_type == 'application/json') ^ (request.get_json() is not None): abort(415) return request.get_json() def insert_book_or_author(collection, collection_name, js_dict=None): """insert a single document into collecito...
This function handles HTTP POST and DELETE requests for managing a single book in a database. On POST, it inserts a book (or author) using data from a JSON payload. On DELETE, it removes a book based on the request. It interacts with a database collection named 'books' via helper functions `insert_book_or_author` and `...
def book_func(): """function for posting or deleting a single book """ database = client.get_db() if request.method == 'POST': js_dict = get_js_dict() return insert_book_or_author(database.books, 'books', js_dict) if request.method == 'DELETE': return delete_wrapper(database....
def get_js_dict(): """helper function to get json file """ if (request.content_type == 'application/json') ^ (request.get_json() is not None): abort(415) return request.get_json() def insert_book_or_author(collection, collection_name, js_dict=None): """insert a single document into collecito...
The main task of the code is to handle HTTP POST and DELETE requests for managing author data in a database. It inserts a new author via POST using `insert_book_or_author` or deletes an author via DELETE using `delete_wrapper`, interacting with the 'authors' collection in the database.
def author_func(): """function for posting or deleting a single author """ database = client.get_db() if request.method == 'POST': js_dict = get_js_dict() return insert_book_or_author(database.authors, 'authors', js_dict) if request.method == 'DELETE': return delete_wrapper(d...
def get_cursor(collection, arguments, colletion_name): """get cursor based on request.args """ if len(arguments) > 2: return None parsed_dict = parse_args(dict(arguments), colletion_name) if parsed_dict is None: #cannot parse args return None # print(parsed_dict) cursor = col...
This function handles HTTP requests for book data: retrieves books via GET (with query parameters), updates books via PUT, and creates new books via POST, interacting with a database and returning JSON responses.
def books_func(): """function for get/post/put books """ database = client.get_db() if request.method == 'GET': cursor = get_cursor(database.books, request.args, 'books') if not cursor: abort(400) res = list(cursor) return Response( response=json.d...
def get_cursor(collection, arguments, colletion_name): """get cursor based on request.args """ if len(arguments) > 2: return None parsed_dict = parse_args(dict(arguments), colletion_name) if parsed_dict is None: #cannot parse args return None # print(parsed_dict) cursor = col...
The function `authors_func` handles HTTP requests (GET, PUT, POST) for managing authors in a database. It retrieves authors via GET, updates them via PUT using a helper function, and adds new authors via POST. The function interacts with a MongoDB collection, processes query parameters, and returns JSON responses for G...
def authors_func(): """function for get/post/put authors """ database = client.get_db() if request.method == 'GET': cursor = get_cursor(database.authors, request.args, 'authors') if not cursor: abort(400) res = list(cursor) return Response( respons...
def replay_trace_with_nonce_retrieval(trace, response_nonce_set, oracle_pair, show_debug=None): global debug local_debug = debug if show_debug is not None: local_debug = show_debug real_nonces = {} session = requests return_value = None for request, response in trace: req_ur...
The code identifies the minimal prefix of a list of pairs (`pairs`) required to successfully replay a trace involving an `oracle_pair`, using a set of nonces (`response_nonce_set`). It iteratively tests subsets of the pairs, pruning unnecessary elements by checking if a candidate trace (excluding the current prunable e...
def prune_after(pairs, response_nonce_set, oracle_pair): minimal_prefix = [] prunable_postfix = pairs[:] while len(prunable_postfix) > 0: if debug: print("Testing %d/%d (%s)..." % (len(minimal_prefix) + 1, len(minimal_prefix) + len(prunable_postfix), prunable_postfix[0...
def prepare_response_nonces(response_nonces): response_nonce_set = {} for res, val, id, key in response_nonces: if res not in response_nonce_set: response_nonce_set[res] = [] response_nonce_set[res].append((val, id, key)) return response_nonce_set def replay_trace_with_nonce_retr...
The function identifies a valid matching from possible_matches by analyzing nonces in request/response pairs, checking for oracle pairs, and attempting to replay the trace. It returns the first valid match, success status, oracle pair, nonces, and trace details if replay succeeds, otherwise continues searching. Debuggi...
def find_valid_matching(possible_matches, trace1): first_match, found, trace, request_nonces, response_nonces, oracle_pair = None, False, None, None, None, None i = 1 for possible_match in possible_matches: if first_match is None: first_match = possible_match request_nonces, resp...
def determine_file_names(): file1 = "" file2 = "" output_file = "" return file1, file2, output_file def parse_input_files(file1, file2): pairs1 = pa.parse_file(file1) print("Pairs before pruning: %d" % len(pairs1)) pairs1 = prune_before(pairs1) pairs2 = pa.parse_file(file2) print("P...
The main task of the code is to process two input files by parsing their traces, identify potential matches between them, refine these matches through pruning, and save the resulting matched pairs along with relevant nonces to an output file. The process involves determining file names, extracting traces, matching them...
def main(): file1, file2, output_file = determine_file_names() trace1, trace2 = parse_input_files(file1, file2) possible_matches = ma.match_two_traces(trace1, trace2) first_match, found, oracle_pair, request_nonces, response_nonce_set, response_nonces, found_trace = \ find_valid_matching(possib...
def navigate_to_video(authorHandle, videoId): print('move browser') print("https://www.tiktok.com/@" + authorHandle + "/video/" + videoId+'?enter_from=video_detail&is_copy_url=1&is_from_webapp=v1') driver.get("https://www.tiktok.com/@" + authorHandle + "/video/" + videoId+'?enter_from=video_detail&is_copy_u...
The main task of the code is to process a social media post by navigating to its video, retrieving and structuring its comments (including nested comments), and updating the post object with the processed comments for further use. The function returns the modified post with scaffolded comment data.
def process_individual_post(post): print('navigate') navigate_to_video(post['username'], post['id']) comments = get_comments() reveal_nested_comments(comments) print('scaffold') comments = scaffold_comments2() post['comments'] = comments; return post
def get_date_input(): invalid_input = True while invalid_input: date = input("Date (YYYY-MM-DD): ") format = "%Y-%m-%d" res = True try: res = bool(datetime.strptime(date, format)) except ValueError: res = False if res: invalid_i...
This code adds a new occurrence record to a database, generating a unique confirmation code, collecting metadata (date, location, species), linking to a living creature record, and associating it with a user's ID (oid). It ensures code uniqueness, inserts records into multiple tables (occurrence, location, living_creat...
def add_occurrence_record(oid): bor = input("Basis of record: ") date = get_date_input() print("This confirmation code can be used to modify records in the future.") confirmCodes = execute_sql('SELECT confirmCode FROM occurrence_record') code_list = [] for row in confirmCodes: code...
def execute_sql(sql_statement): statements = sql_statement.split(';') with db_connect.cursor() as cursor: for statement in statements: cursor.execute(statement) db_connect.commit() result = cursor.fetchall() return result def get_str_input(valid_val_list, prompt): invalid_inp...
This function modifies an observation record by allowing users to update specific fields (date, URL, season, location, creature measurements) after selecting a confirmation code. It retrieves existing records, displays modification options, collects user input, executes SQL updates, and shows the revised record.
def modify_observation_record(oid): valid_code_list = [] valid_codes_stmt = "SELECT confirmCode FROM occurrence_record NATURAL JOIN observes WHERE observes.oid='{}'".format(oid) valid_codes_sql = execute_sql(valid_codes_stmt) for row in valid_codes_sql: valid_code_list.append(row['confirmCode'])...
def read_excel(filename, column, row): #Read a single cell value from an Excel file return pd.read_excel(filename, skiprows=row - 1, usecols=column, nrows=1, header=None, names=["Value"], engine='openpyxl').iloc[0]["Value"] def extractIter(filename): #extract advanced data such as iterations #we need a few ...
The function `parseOne` parses data from an Excel file specified by `filename`, `run`, and `datasheet`, extracting metadata like date, work week, TOS version, suite, and hardware configuration. It structures this data into a predefined schema, inserts it into a MongoDB collection, and links related modules. Error handl...
def parseOne(filename, run, datasheet): #similar function to parse only one file #start = time.time() wbDir = os.path.join(directory, filename, run, datasheet) try: #things we cna get from the excel sheet date = run[0:10].replace("_",'/') ww = float(read_excel(wbDir, "A", 1).re...
def containsLEX(self, itemset, item): """This method checks if the item "item" is in the itemset.""" return item in itemset def save(self, rule, support): """Save rule in the current top k set""" # we get a pointer to the node in the red black tree for the # rule having...
The main task of the code is to expand the left-hand side of a rule I→J by adding items c not already present in I or J, ensuring c meets minimum support requirements and lexicographical order. It iterates through sequences to collect valid candidates, calculates confidence for new rules I∪{c}→J, and saves them if they...
def expand_l(self, rule): """This method search for items for expanding left side of a rule I --> J with any item c. This results in rules of the form I U{c} --> J. The method makes sure that: - c is not already included in I or J - c appear at least minsup time in tidsIJ before last o...
def containsLEX(self, itemset, item): """This method checks if the item "item" is in the itemset.""" return item in itemset def save(self, rule, support): """Save rule in the current top k set""" # we get a pointer to the node in the red black tree for the # rule having...
This method expands the right side of a rule I → J by adding items c, ensuring c is not in I/J, meets minimum support, and is lexicographically larger than J's items. It scans sequences containing I → J, checks post-first-occurrence items, filters invalid c, and builds new rules I → J ∪ {c} with sufficient support and ...
def expand_r(self, rule): """This method search for items for expanding right side of a rule I --> J with any item c. This results in rules of the form I --> J U{c}. The method makes sure that: - c is not already included in I or J - c appear at least minsup time in tidsIJ after the first...
def save(self, rule, support): """Save rule in the current top k set""" # we get a pointer to the node in the red black tree for the # rule having support jus lower than support + 1 tmp_node = Rule() tmp_node.rule(None, None, 0, support+1, None, None, None, None, None) ...
The main task of the code is to generate association rules with one item in the antecedent and one item in the consequent from frequent items. It iterates through all item pairs, calculates their transaction support, and checks if rules meet minimum support and confidence thresholds. Valid rules are saved and registere...
def start(self): """Start the algorithm""" # We will now try to generate rules with one item in the # antecedent and one item in the consequent using # frequent items. # for each pair of frequent items i and j such that i != j for item_i in range(self.db.min_item, self.db.max_item ...
def scan_database(self): "Scan the database to count the occurrence of each item" for tid, sequence in enumerate(self.db.database): for j, itemset in enumerate(sequence): for i, item in enumerate(itemset): # if item not in self.item_co...
The code's main task is to execute an algorithm for mining frequent itemsets or association rules. It initializes counters, sets a minimum support threshold, scans the database to count item occurrences, runs the algorithm to generate rules, prunes excess rules, and returns the final set of rules (`k_rules`). The proce...
def run_algorithm(self): "Main method" self.total_removed_count = 0 self.not_added = 0 log.info("Run algorithm") # set minsup = 1 (will be increased by the algorithm progressively) self.min_supp_relative = 1 # scan the database to count the occurrence of each ...
def angle_range_pi(theta): theta = theta%(2*math.pi) if theta > math.pi or theta < -math.pi: theta = theta - 2*math.pi if theta > 0 else theta + 2*math.pi return theta def angle_range_2pi(theta): if theta < 0: theta = theta + 2*math.pi return theta def move2goal(x_goal, y_goal, theta_goal,pix2_...
The code subscribes to ARUCO marker and task goals, processes angle ranges, and sequentially moves a robot toward each goal using adjusted angular values. It handles ROS shutdown signals, clears goal lists after execution, and employs a loop to achieve navigation tasks by interpreting pose data and adjusting movement p...
def main(): global hola_x, hola_y, hola_theta, x_goals, y_goals, theta_goals rospy.Subscriber("/detected_aruco", Pose2D, aruco_feedback_Cb) rospy.Subscriber("/task2_goals", PoseArray, task2_goals_Cb) signal.signal(signal.SIGINT, signal_handler) while not rospy.is_shutdown(): for x_goal, y_goal, theta_goal in ...
def init_chat(self): self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM ) svr = SERVER if self.args.d == None else (self.args.d, CHAT_PORT) self.socket.connect(svr) self.sm = csm.ClientSM(self.socket) reading_thread = threading.Thread(target=self.read_input) r...
The code initializes a chat session, prompts the user for their name, authenticates them, and processes messages in a loop until the system state becomes offline, with periodic output and delays between operations.
def run_chat(self): self.init_chat() self.system_msg += 'Welcome to ICS chat\n' self.system_msg += 'Please enter your name: ' self.output() while self.login() != True: self.output() self.system_msg += 'Welcome, ' + self.get_name() + '!' self.output() ...
def critical_log_event(event, log_stream_name): """ :param event: The processed event that will be logged : type event: Dictionary : type log_group_name: String : type log_stream_name: String : return : None """ log_str = 'CRITICAL: ' + str(event.get_event_attributes()) print(log_st...
This function writes event logs to Amazon CloudWatch Logs using a log stream name derived from an environment variable. It categorizes logs based on event severity: 'Critical' triggers critical_log_event, 'Major' uses warn_log_event, and all others default to info_log_event, ensuring structured logging of events with a...
def write_to_cw_logs(event): log_stream_name = str(os.environ.get('EventsCLoudWatchLogGroup'))+"-MGN-Events" if event.get_event_severity() == 'Critical': critical_log_event(event, log_stream_name) elif event.get_event_severity() == 'Major': warn_log_event(event, log_stream_name) else: ...
def update_mouse_angle(): position_x, position_y = pygame.mouse.get_pos() mouse_angle = math.degrees( math.atan2( (player.y + level.bubble_height / 2) - position_y, position_x - (player.x + level.bubble_width / 2), ) ) if mouse_angle < 0: mouse_angle = 180...
The code runs a game loop for a bubble-shooting game, handling user input, updating game state (level progression, bubble movement), checking win/lose conditions, rendering graphics, and managing levels. It initializes game elements, processes events, updates physics, and redraws the screen at 60 FPS until the player w...
def main(): clock = pygame.time.Clock() run = True current_level = 1 counter = 0 level.load_level(current_level) bubble_to_shoot.reinitialize( SCREEN_WIDTH / 2 - BUBBLE_WIDTH / 2, SCREEN_HEIGHT - 2.5 * BUBBLE_WIDTH, 500, 90, random.choice(tuple(level.colo...
def predict(sentence): bag = bagOfWords(sentence) res = model.predict(np.array([bag]))[0] results = [[i, r] for i, r in enumerate(res) if r > 0.25] results.sort(key=lambda x: x[1], reverse=True) return_list = [] for result in results: return_list.append({"intent": classes[result[0]], "p...
The code processes user input to generate responses based on intent detection. It predicts the user's intent, checks confidence levels, and provides tailored replies (e.g., COVID stats, vaccination info, time/date). If uncertain, it prompts retry. For "covid" queries, it fetches state-specific data; for vaccination, it...
def startApp(sentence): # while True: # sentence = input("You: ") results = predict(sentence) resp = response(results, intents) print(results) if float(results[0]["probability"]) < 0.75 and resp['tag'] != "vaccination_by_pincode": reply = "Unable to detect, Please try again" else: ...
def isFinished(self) -> bool: return self.turn > self.maxTurn def executePlay(self): me = self.choosePlay(); self.sendPlay(me); self.server.waitMessage(); them = self.receivePlay(); self.myPlays.append(me); self.theirPlays.append(them); self.processResults...
The main task of the playMatch method is to repeatedly execute plays until the match is finished, then return the winner.
def playMatch(self) -> int: while not self.isFinished(): self.executePlay() return self.getWinner()
def derivation(axiom, steps): derived = [axiom] # seed for _ in range(steps): next_seq = derived[-1] next_axiom = [rule(char) for char in next_seq] derived.append(''.join(next_axiom)) print(_) return derived def set_turtle(alpha_zero): r_turtle = turtle.Turtle() # recur...
The code collects user-defined production rules for an L-system, inputs an axiom and iteration count, generates the L-system model, and uses turtle graphics to visualize the result based on parameters like segment length, initial heading, and angle increment.
def main(): rule_num = 1 while True: rule = input("Enter rule[%d]:rewrite term (0 when done): " % rule_num) if rule == '0': break key, value = rule.split("->") SYSTEM_RULES[key] = value rule_num += 1 axiom = input("Enter axiom (w): ") iterations = int...
def average_poses(poses): center = poses[..., 3].mean(0) z = normalize(poses[..., 2].mean(0)) y_ = poses[..., 1].mean(0) x = normalize(np.cross(z, y_)) y = np.cross(x, z) pose_avg = np.stack([x, y, z, center], 1) return pose_avg def normalize(v): return v / np.linalg.norm(v) def render_p...
The function generates a spiral path of camera poses for rendering, using the average of input poses and parameters derived from depth ranges and radii. It calculates focal length, depth ranges, and radial distances, then constructs a spiral trajectory with `render_path_spiral`, returning the resulting poses as a numpy...
def get_spiral(c2ws_all, near_fars, rads_scale=1.0, N_views=120): c2w = average_poses(c2ws_all) up = normalize(c2ws_all[:, :3, 1].sum(0)) dt = 0.75 close_depth, inf_depth = near_fars.min() * 0.9, near_fars.max() * 5.0 focal = 1.0 / (((1.0 - dt) / close_depth + dt / inf_depth)) zdelta = near_fars...
def center_poses(poses, blender2opencv): poses = poses @ blender2opencv pose_avg = average_poses(poses) pose_avg_homo = np.eye(4) pose_avg_homo[:3] = pose_avg pose_avg_homo = pose_avg_homo last_row = np.tile(np.array([0, 0, 0, 1]), (len(poses), 1, 1)) poses_homo = \ np.concatenate([p...
The main task of the code is to load and process camera poses and image data for a neural rendering application. It reads camera parameters from 'poses_bounds.npy', aligns them with image paths, adjusts focal lengths and poses for downsampling, generates ray directions, and prepares training/test rays and RGB values by...
def read_meta(self): poses_bounds = np.load(os.path.join(self.root_dir, 'poses_bounds.npy')) self.image_paths = sorted(glob.glob(os.path.join(self.root_dir, 'images_4/*'))) if self.split in ['train', 'test']: assert len(poses_bounds) == len(self.image_paths), \ 'Misma...
def _draw_cell(self, cell, i, j): #calculate the x/y position of the Cell based on i, j, the cell_size, and the x/y position of the Maze itself. The x/y position of the maze represents how many pixels from the top and left the maze should start from the side of the window. if self._win is None: ...
This method generates a grid of Cell objects, populates them with coordinates, draws each cell, and initializes maze setup by breaking walls, resetting visited status, and solving the maze.
def _create_cells(self): #fill a self._cells list with lists of cells. Each top-level list is a column of Cell objects. Once matrix is populated it should call its _draw_cell() method on each Cell. self.cells = [] for i in range(self.num_cols): col_cells = [] for j in ran...
def _decode_action(self, action_id): legal_ids = self._get_legal_actions() # ic(action_id) assert action_id in legal_ids if action_id in legal_ids: return ACTION_LIST[action_id] return ACTION_LIST[np.random.choice(legal_ids)] def get_state(self, id): return se...
This function executes a single action step in a game, updates the game state, records the action, and returns the new state and game status. It handles action decoding, state transitions, and player turn updates, returning the current state and whether the game has ended.
def step(self, action): # Start accessing actions assert self.cur_player == 1 # Perform one-step update # ic(action) if not self.training_agent.use_raw: action = self._decode_action(action) # Record the action for human agent self.action_recorder.appe...
def _add_remote_link(jira, issue, gh_issue): """ Add the JIRA "remote link" field that points to the issue """ gh_url = gh_issue['html_url'] jira.add_remote_link( issue=issue, destination={ 'url': gh_url, 'title': gh_issue['title'], }, globalId...
This function searches for an existing JIRA issue linked to a GitHub issue via a remote link. If none is found, it checks for manually synced issues by matching GitHub issue titles with JIRA keys and verifying descriptions. If `make_new` is True, it retries with delays to avoid race conditions when creating new JIRA is...
def _find_jira_issue(jira, gh_issue, make_new=False, retries=5): """Look for a JIRA issue which has a remote link to the provided GitHub issue. Will also find "manually synced" issues that point to each other by name (see README), and create the remote link. If make_new is True, a new issue will be cr...
def _find_jira_issue(jira, gh_issue, make_new=False, retries=5): """Look for a JIRA issue which has a remote link to the provided GitHub issue. Will also find "manually synced" issues that point to each other by name (see README), and create the remote link. If make_new is True, a new issue will be cr...
The main task of the code is to add a new label from a GitHub event to the corresponding Jira issue if the label is valid and not already present. It retrieves the GitHub issue, finds the matching Jira issue, checks the label's validity, and updates the Jira issue's labels accordingly.
def handle_issue_labeled(jira, event): gh_issue = event['issue'] jira_issue = _find_jira_issue(jira, gh_issue, gh_issue['state'] == 'open') if jira_issue is None: return labels = list(jira_issue.fields.labels) new_label = _get_jira_label(event['label']) if _check_issue_label(new_label)...
def _find_jira_issue(jira, gh_issue, make_new=False, retries=5): """Look for a JIRA issue which has a remote link to the provided GitHub issue. Will also find "manually synced" issues that point to each other by name (see README), and create the remote link. If make_new is True, a new issue will be cr...
This function removes a specified label from a Jira issue when it is removed in a GitHub event. It retrieves the GitHub issue, locates the corresponding open Jira issue, validates the label, and updates the Jira issue's labels by removing the specified label if present.
def handle_issue_unlabeled(jira, event): gh_issue = event['issue'] jira_issue = _find_jira_issue(jira, gh_issue, gh_issue['state'] == 'open') if jira_issue is None: return labels = list(jira_issue.fields.labels) removed_label = _get_jira_label(event['label']) if _check_issue_label(remo...
def _markdown2wiki(markdown): """ Convert markdown to JIRA wiki format. Uses https://github.com/Shogobg/markdown2confluence """ if markdown is None: return '\n' # Allow empty/blank input with tempfile.TemporaryDirectory() as tmp_dir: md_path = os.path.join(tmp_dir, 'markdown.md') ...
This function synchronizes edited GitHub comments to Jira by updating an existing Jira comment if it matches the old GitHub content, or creating a new Jira comment if no match is found. It retrieves the GitHub comment, maps it to Jira, checks for existing comments, and updates/creates comments to maintain consistency b...
def handle_comment_edited(jira, event): gh_comment = event['comment'] old_gh_body = _markdown2wiki(event['changes']['body']['from']) jira_issue = _find_jira_issue(jira, event['issue'], True) # Look for the old comment and update it if we find it old_jira_body = _get_jira_comment_body(gh_comment, o...
def _find_jira_issue(jira, gh_issue, make_new=False, retries=5): """Look for a JIRA issue which has a remote link to the provided GitHub issue. Will also find "manually synced" issues that point to each other by name (see README), and create the remote link. If make_new is True, a new issue will be cr...
This function synchronizes GitHub issue edits with Jira by updating the Jira issue's description, summary, and components; resolving links; and adding an edit comment. It retrieves the GitHub issue, maps it to the corresponding Jira issue, applies field updates, manages component changes, resolves issue links, and logs...
def handle_issue_edited(jira, event): gh_issue = event['issue'] issue = _find_jira_issue(jira, gh_issue, True) fields = { 'description': _get_description(gh_issue), 'summary': _get_summary(gh_issue), } _update_components_field(jira, fields, issue) issue.update(fields=fields) ...
def is_finished(self): if np.all(self.player_pieces[0] == 84) or np.all(self.player_pieces[1] == 84): return True return False def is_win(self, player): if np.all(self.player_pieces[player] == 84): return True return False def get_distance(self, piece0, piece1): ...
This code evaluates a board state's value between -100 and 100, where 100 means player 0 is certain to win and -100 means player 1 is certain to win. It checks if the game is finished, returning 100/-100 for wins. For unfinished games, it calculates scores by comparing distances between player pieces using weighted val...
def evaluate(self, distance): """ we will make in the end calc the value of current Board, the value is between -100 and 100, like: 100 mean the first player certainly will win -100 mean the second player certainly will win 0 mean draw 50 mean th...
def delete_user_command(message, delay=60): def delete_message(): time.sleep(delay) # if message and message.text.startswith('/'): try: bot.delete_message(message.chat.id, message.message_id) except Exception as ex: send_message_and_delete(ADMIN, f'Deleting u...
The code defines a `hello` function that responds to a message by sending an introduction and instructions for an English teacher bot. It cancels a global `champion_timer` if active and triggers `get_champion` for a specific group chat to manage user interactions or tasks.
def hello(message): global champion_timer delete_user_command(message) send_message_and_delete(message.chat.id, 'Hello! 😎\nI am a English teacher bot 🇬🇧\n' 'If you want to learn some new words,\njust press /play and try me 😉\n' ...
def default_course_session_lab(self, course_id, session_id, lab_id): course_id = course_id or self.course_id session_id = session_id or self.session_id lab_id = lab_id or self.lab_id assert course_id is not None, "must set course_id" assert session_id is not None, "must set se...
The main task of the code is to generate and print a formatted grade report for a user's course session. It retrieves the grade tree data, constructs a table displaying the total grade, lab grades, and task grades with descriptions, and prints the structured output. The function uses default course/session values if no...
def print_grade_tree(self, course_id=None, session_id=None, user_id=None): course_id, session_id, _ = self.default_course_session_lab(course_id, session_id, None) print (course_id, session_id) gt = self.get_user_session_gradetree(course_id, session_id, user_id) course = self.get_course(c...
def default_course_session_lab(self, course_id, session_id, lab_id): course_id = course_id or self.course_id session_id = session_id or self.session_id lab_id = lab_id or self.lab_id assert course_id is not None, "must set course_id" assert session_id is not None, "must set se...
The `submit_task` method submits a task's code and variables for grading. It retrieves function definitions and variable values from the provided namespace, encodes them, and sends them via a POST request. Upon successful submission, it parses the grading response, formats the grade, feedback, and submission timestamp ...
def submit_task(self, namespace, course_id=None, session_id=None, lab_id=None, task_id=None, user_id=None, display_html=True): """ call this function with namespace=globals() """ user_id = user_id if user_id is not None else self.user_id course_id, session_id,...
def status(self, table: str): return self._execute( """ SELECT rowid, * FROM Status ORDER BY position """ ) def table(self, table: Union[str, int]): sql = f"""SELECT rowid, name FROM List WHERE {"rowid" if isinstance(tab...
This code updates a database entry based on form data, handling table/status changes by inserting/deleting entries, and adjusting positions of related entries when moving within the same table. It compares old/new values, updates fields if changed, and ensures proper position ordering.
def update(self, form, table): statuses = self.status(table) old_table = self.table(table) table_id = old_table["rowid"] rowid = int(form["rowid"]) new_table = self.table(int(form["table"])) old_status = [s for s in statuses if s["rowid"] == int(form["old_status"])][0] ...
def is_enum(item: docScraper.TableOfContentItem): if not hasattr(pyfbsdk, item.Name): if item.Name == "Enumeration": return True return False item_object = getattr(pyfbsdk, item.Name) return type(item_object) == type def is_method(item: docScraper.TableOfContentItem, child: Memb...
The code generates a structured table of contents (TOC) for Python documentation, categorizing items (classes, functions, enums) with icons, avoiding duplicates, and including nested members (methods, properties). It parses documentation pages, filters out private/constructor members, constructs URLs, and saves the res...
def generate_python_toc(version: int): python_docs = docScraper.Documentation("pyfbsdk", version, bUseCache=True) items = [] items_name_map = set() for item in python_docs.TableOfContents: is_function = item.RelativeUrl.startswith("namespacepyfbsdk.html") if is_function: ic...
def waymo_find_best_match_id(frame, camera_label, rrr=False, iou_thresh=0.5): for projected_labels in frame.projected_lidar_labels: if projected_labels.name == open_dataset.CameraName.FRONT: break target_bbs = [] for label in projected_labels.labels: target_bbs.append(waymo_label...
The function processes Waymo TFRecord ground truth data, extracting front-camera labels, calculating collision risk for objects using acceleration/brake thresholds, and structuring detected objects with bounding boxes and risk scores into a dictionary. It filters files via `gt_list`, counts objects, and returns the str...
def readWaymoGroundtruth(gt_dir, RRR=False, acc_to_brake=-7.5, t_reaction=0.1, # 10 Hz ts=0.1, risk_thresh=-1, gt_list = None): groundtruth = {} waymo_frame_map = {} gtfiles = [o...
def forensic_questions(): try: print("Opening Forensic Questions") run_command("nano Desktop/Forensic Question 1") run_command("nano Desktop/Forensic Question 2") input("Press enter to continue") except Exception as e: print(e) def packages(): packagemanager = "" ...
The code executes a series of functions to perform system analysis tasks, including forensic checks, package management, firewall configuration, SSH settings, and service status verification. After completing these steps, it clears the output and prints "Basics completed" to indicate the process is finished.
def all(): forensic_questions() packages() firewall() ssh() services() clear() print("Basics completed")
def unique_name_check(self): """ :return: checking if the name is unique or not """ try: check = True while check: name = input("Enter a unique name for your address book: ") for contact_name in self.contact_book: ...
The main task of the code is to add a new address book entry by generating a unique name, populating it with contacts via `add_contacts`, and performing actions on the contact list using `contact_list_action`, all while handling exceptions to log errors.
def add_new_address_book(self): """ :return: adding a new address book """ try: contact_list = [] name = self.unique_name_check() self.add_contacts(name, contact_list) self.contact_list_action(name, self.contact_book[name]) except ...
def add_new_address_book(self): """ :return: adding a new address book """ try: contact_list = [] name = self.unique_name_check() self.add_contacts(name, contact_list) self.contact_list_action(name, self.contact_book[name]) except ...
This function provides a menu-driven interface for managing an address book, allowing users to create new address books, access existing ones by name, export contact data to CSV files, or exit the program. It loops until the user selects "EXIT," handling input validation and invoking corresponding methods for each acti...
def address_book_action(self): """ :return: traversing the address book to perform specific actions """ check_bool = True while check_bool: try: choice = int(input("Press the corresponding number according to your action required: " ...
def preprocessing(input_img_path,ph_height,ph_width,ph_form='WHC'): input_image = cv2.imread(input_img_path) # HWC BGR # Resize the image and convert to array of float32 resized_image = cv2.resize(input_image,(ph_width, ph_height), interpolation = cv2.INTER_CUBIC) print(resized_image.shape) if ph_fo...
The code performs object detection using a YOLOv2-tiny model on an input image. It loads pre-trained weights, preprocesses the image, runs inference to generate predictions, applies postprocessing (NMS) with specified thresholds, and saves the annotated output image. It also freezes the model graph and exports it as a ...
def main(_): # Definition of the paths weights_path = './yolov2-tiny-voc_352_288_final.weights' input_img_path = './horses.jpg' output_image_path = './output.jpg' # If you do not have the checkpoint yet keep it like this! When you will run test.py for the first time it will be created automat...
def usage(): print ("\nThis is the usage function\n") print ('Usage: '+sys.argv[0]+' -i <file1> [option]') def software1(filename): input = [] with open(filename) as openfileobject: for line in openfileobject: line = line.rstrip("\n") input.append(line) input = [int(i) fo...
The main task of the code is to process command-line arguments for generating specific text files. It prints user details, parses options like --help and --test-data, and triggers software1() and software2() functions with the provided test data argument to create "software1.txt" and "software2.txt" files. The code han...
def main(argv): print("Name: Rajat Nagpal") print("Email Id: jfnlp@example.com") print("SR No.: 04-03-02-10-42-18-1-15533") print("Course: M.Tech Systems Engineering (2nd year)") try: opts, args = getopt.getopt(argv, '', ['help', 'test-data=']) if not opts: print ('No opt...
def draw_spelling_list(spelling_list): global spelling_listbox spelling_listbox=Listbox(window, height=17, width=14, font=('Arial 14')) spelling_listbox.grid(column=3, row=1, pady=35, padx=5, sticky=N) for item in spelling_list: spelling_listbox.insert(END, item) def add_word_window(): ...
The code defines a function `draw_action_buttons` that generates UI buttons for managing a spelling list. It creates "Add Word," "Remove Word," and "Hide List" buttons, each linked to respective functions. The "Add" and "Remove" buttons use lambda to trigger windows, while "Hide List" may have an error in its command a...
def draw_action_buttons(): spelling_listbox = draw_spelling_list(spelling_list) # Action Buttons add_word_button = Button(window, text="Add Word", width=15, command=lambda: add_word_window()) add_word_button.grid(column=3, row=3, sticky=N) remove_word_button = Button(window, text="Remove Word", wi...
def create_spelling_list_from_file(filename): spelling_list = [] #Add a try catch here for "FileNotFoundError" directory = os.path.dirname(os.path.realpath(__file__)) filepath = os.path.join(directory, filename) # Open file to read spelling words spelling_file = open(filepath) # Read ...
The main task of the code is to initialize and run a GUI-based Hangman game using Tkinter. It sets up the window, loads a spelling list from a file, and draws game elements like the hangman, keyboard, buttons, and labels. The code configures the interface, prepares game data, and starts the main event loop to enable us...
def main(): global spelling_list global window global MAX_NUM_GUESSES global FILENAME window = Tk() window.title("Spelling List Hangman - Lauren Snyder - CSE111") window.configure(background="white") window.geometry("1065x685") style = ttk.Style() style.theme_use('clam...
def pygame_init(self): try: # pygame.init() self._display_surf = pygame.display.set_mode( self.disp_size, pygame.HWSURFACE | pygame.DOUBLEBUF) pygame.display.set_caption("Hex Game ({:d} x {:d})".format(self.x_dim, self.y_dim)) except: # pyg...
This code executes a Pygame game loop, initializing the environment, processing events, updating game logic, rendering frames, and cleaning up resources. It runs continuously until self._running is False, then returns self._replay.
def execute(self): if not self.pygame_init(): self._running = False while self._running: event = pygame.event.poll() self.on_event(event) self.on_loop() self.render() self.cleanup() return self._replay
def _get_puzzle_group(self): bs = BeautifulSoup(self.driver.page_source, features="html.parser") return bs.find('div', id="puzzle-wrapper").find('g', id="puzzle-group") def _extract_puzzle(puzzle_group): children = puzzle_group.find_all(lambda tag: tag.name == "circle") max_length = int(len(chil...
The main task of the code is to initialize a game board by embedding a puzzle section into a full-sized grid, optionally reflecting and rotating it, then converting the board to integers. It retrieves the puzzle group, extracts the puzzle, embeds it into the board, applies reflection/rotation if enabled, and returns th...
def _initialize_board(self, size) -> np.ndarray: puzzle_group = self._get_puzzle_group() puzzle_section = _extract_puzzle(puzzle_group) whole_board = _embed_puzzle_in_full_sized_board(puzzle_section, puzzle_group.find_all(), size) if self.reflect_board: whole_board = _swap...
def _navigate_driver_to_level(self, level_number) -> None: level_id = 'Problem ' + str(level_number) DriverWait(self.driver, 5).until(element_to_be_clickable((By.XPATH, '//*[@id="footer"]/button[2]'))).click() DriverWait(self.driver, 5).until(element_to_be_clickable((By.XPATH, "//*[contains(text...
The code retrieves and prepares a game board for a specified level, handling web interactions to navigate to the level, check turn status, initialize the board structure, and manage passing logic if required. It ensures the board is correctly updated and returns the completed numpy array representing the puzzle state.
def get_board(self, level_number, size=11, pass_if_required=True) -> np.ndarray: """ :param level_number: int level to be played :param size: int size of the game (square of according side length) puzzle will be embedded accordingly that logic works and all ot...
def delay_print(s): for c in s: sys.stdout.write(c) sys.stdout.flush() time.sleep(0.05) def SoundCloud(): try: #PLAYLIST EXTRACTION username = input('\nEnter Soundcloud Username: ') howmany = input('Enter how many songs User liked: ') time.sleep(1) delay_print('\nVibi...
The code's main task is to prompt the user to select a streaming service (SoundCloud or Spotify) and direct them to the corresponding function based on their input, with error handling for invalid choices.
def main(): delay_print('Oyama Productions\n') time.sleep(2.5) delay_print('\nPlease choose a streaming service...\n') print('1 - SoundCloud') print('2 - Spotify') option = input('??? : ') if option == '1': SoundCloud() elif option == '2': spotify() else: pr...
def parse_arguments() -> argparse.Namespace: """Parse command-line arguments""" parser = argparse.ArgumentParser( description="Specify arguments for running Minecraft Virtual Intelligence" ) parser.add_argument( "-f", "--file", help="Path to YAML configuration file", ...
The main task of the code is to create or load a configuration object (`Config`) based on command-line arguments. It parses input arguments, loads a config file if specified, or initializes default configurations. It then updates the config with additional key-value pairs from the arguments and returns the finalized co...
def get_config() -> Config: arguments = parse_arguments() if arguments.file is not None: config = parse_config(arguments.file) else: config = Config(engine=EngineConfig(), ppo=PPOConfig()) update_config(config, arguments.key_value_pairs) return config
def findAllStops(): global allStops for key in data: allStops.add(key) for stop in data[key]: allStops.add(stop) def generateAdjList(): adjList = {} paths = {} for stop in targets: adjList[stop] = [] paths[stop] = {} dist, path = dijkstra(data, st...
The code processes a graph structure by generating an adjacency list and matrix, then allows user interaction to view the matrix, find cycles, or retrieve specific paths. It continuously accepts commands like "matrix", "cycles", "path", or "exit" to display graph data or terminate the session. The main task involves gr...
def main(): findAllStops() adjList, paths = generateAdjList() matrix = generateAdjMatrix(adjList) while True: command = input("... ") if command == "matrix": print(matrix) print("") if command == "cycles": printShortestPaths(adjList) ...
def getFirstLastSetObj(): ''' gets the first and the last obj of a set deck ''' vc = TempDeck.objects.all() return [ vc.first(),vc.last()] def getObj(id): c = VocabCard.objects.get(pk=id) return c def getTotalCount(set_number): if set_number>0 and set_number<10000: total_count = ...
This function determines the next card in a sequence by parsing the current card ID, checking if it's the last card, and retrieving the subsequent card's ID. It constructs navigation context including previous/next IDs, current card data, and progress counters, then renders the 'card_slider.html' template with this inf...
def card_slider_next(request,card_id): ''' returns the next card_id for the current card_id given by the card_slider_main to navigate to the next card ''' list_ids = list(map(int,card_id.split('_'))) prev_id = list_ids[0] current_id = list_ids[1] set_number = list_ids[...
def getFirstLastSetObj(): ''' gets the first and the last obj of a set deck ''' vc = TempDeck.objects.all() return [ vc.first(),vc.last()] def getObj(id): c = VocabCard.objects.get(pk=id) return c def getTotalCount(set_number): if set_number>0 and set_number<10000: total_count = ...
The function `card_slider_prev` generates the previous card identifier and context data for navigation in a slider interface. It processes the input `card_id` to extract current and next IDs, set number, and count. It determines the previous card using `prev_in_order`, checks if the current card is the first in the set...
def card_slider_prev(request,card_id): ''' returns the previous card_id for the current card_id given by the card_slider_main to navigate back to the previous card ''' list_ids = list(map(int,card_id.split('_'))) current_id = list_ids[0] next_id = list_ids[1] set_number = list_...
def basal_metabolic_rate(weight_pound, height_inches, age, gender): """This function calculate the bmr for both men and women by using the first and second function to convert the unit first.""" weight = weight_kgs(weight_pound) height = height_cms(height_inches) if gender == "M": bmr = 66 + 13....
The function calculates daily estimated energy expenditure by summing basal metabolic rate (BMR), physical activity energy, and thermal effect of food, then rounding to two decimal places.
def daily_energy_expenditure(activity_level, weight_pound, height_inches, age, gender, calories_intake): """ This function calculates the daily estimated energy expenditure by adding the function third,fourth and fifth.""" total_energy = basal_metabolic_rate(weight_pound, height_inches, age, gender) + physical_...
def hydrogen_output(carbon): hydrogens = 2 * carbon + 2 return hydrogens def draw_hydrogen(t): t.pendown() t.forward(100) t.penup() t.forward(20) draw_letter(t, 'H') def draw_molecule(t): for i in range(carbon): draw_letter(t,'C') t.forward(10) t.right(90) ...
The main task of the code is to generate a visual representation of an alkane molecule using Python's turtle graphics. It positions the turtle, calculates hydrogen count via `hydrogen_output(carbon)`, draws hydrogen atoms, the molecular structure, and the letter 'H', combining chemical visualization with graphical rend...
def main(): # Create screen and turtle. t = turtle.Turtle() t.pensize(3) screen = turtle.Screen() screen.title('Alkane') #position the turtle in the left part of the screen (width, height) = screen.screensize() newx= -width/2 newy = 0 t.penup(); t.goto(newx,newy) ...
def __process_same_day(self, transactions: List[Transaction]) -> List[Transaction]: return self.__process_x_days(transactions, 0) def __process_30_days(self, transactions: List[Transaction]) -> List[Transaction]: return self.__process_x_days(transactions, 30) def __process_normal(self, transactions: Lis...
This function processes a list of transactions for a single asset type by sorting them chronologically, filtering out same-day duplicates, removing entries within 30 days of each other, and then generating hold pools and taxable records from the remaining transactions. It returns these two lists as results.
def __process_single_asset_type(self, transactions: List[Transaction]) \ -> Tuple[List[HoldPool], List[TaxableRecord]]: if len(transactions) <= 0: return list(), list() transactions_ascending = sorted(transactions, key=lambda x: x.date) transactions_without_same_day = ...
def initiate_game(): global domino_set global stock_pieces global computer_pieces global player_pieces global status global snake domino_set = create_domino_set() while True: stock_pieces, computer_pieces, player_pieces = distribute_domino_set(domino_set) domino_snake_o...
The main task of the code is to manage a turn-based game loop, displaying the game state, handling player moves, updating the game field, checking win/draw conditions, and terminating the game when a win or draw is detected. It uses global variables to track status and coordinates game flow between player and computer ...
def main(): global status initiate_game() while True: show_playing_field(stock_pieces, computer_pieces, player_pieces, snake, status) move = prompt_for_move(snake, status, computer_pieces, player_pieces) update_playing_field(status, move) game_status = game_is_over(snake, co...
def string_to_matrix(user_input_): # Convert 9-char length string to 3x3 matrix. list_ = list(user_input_) return [[list_[i], list_[i + 1], list_[i + 2]] for i in [0, 3, 6]] def print_game(game_state_): print("---------") print(f"| {game_state_[0][0]} {game_state_[0][1]} {game_state_[0][2]} |") ...
The code runs a tic-tac-toe game by converting user input into a game matrix, alternating between "X" and "O" turns, validating moves, updating the board, and checking for win/draw conditions. It prints the game state after each move and terminates when a player wins or the game ends in a draw.
def main(): user_input = "_________" # e.g. XXXOO__O_ to enter a game state, exit to stop game. game_state = string_to_matrix(user_input) print_game(game_state) turn = "X" while True: user_input = input() if is_move_valid(user_input, game_state): row, column = ...
def getFee(amount,value): feePercentage = 0.0 fee = (int(amount) * float(value)) * feePercentage return fee def getAvailableCash(userName): account_details = getAccountDetails(userName) return account_details['available_cash'] def getOwnedStock(userName,symbol): ownedStock = supabase.table('StockTradingGame...
The function processes a stock purchase by calculating transaction costs, verifying sufficient funds, updating user's stock holdings (either inserting new entries or updating existing ones), logging the trade, adjusting available cash, and adding the transaction fee to the bank funds.
def setPurchasedStock(userName,symbol,amount,value): fee = getFee(amount,value) transactionValue = (int(amount) * float(value)) + fee setTransactionValue = round(transactionValue,2) availableCash = getAvailableCash(userName) if getAvailableCash(userName) < transactionValue: return 'Insufficient Funds' o...
def getFee(amount,value): feePercentage = 0.0 fee = (int(amount) * float(value)) * feePercentage return fee def getOwnedStock(userName,symbol): ownedStock = supabase.table('StockTradingGame_OwnedStocksDB').select("*").eq('user_name', userName).eq('stock_symbol', symbol).execute() if ownedStock.data == []: ...
The function enables a user to sell a specified stock, deducts transaction fees, updates their owned stock quantity, adjusts available cash, and logs the trade. It checks if the user owns the stock, validates the sell amount against holdings, updates or deletes the stock entry in the database, and adds the transaction ...
def setSellStock(userName,symbol,amount,value): fee = getFee(amount,value) transactionValue = (int(amount) * float(value)) - fee ownedStock = getOwnedStock(userName,symbol) if ownedStock == []: return 'Unable to sell. Stock Not owned.' updateAmount = int(ownedStock['stock_amount']) - int(amount) costPer...
def _frequency_to_bins(self, frequency, quantize_fn: str = "floor"): """Convert frequency in Hz to pitch bins""" return self._cents_to_bins( self._frequency_to_cents(frequency), quantize_fn) def _argmax(self, logits: torch.Tensor): """Decode pitch using argmax""" # Get pitch ...
The function converts model output logits into pitch and periodicity values by masking out-of-range frequencies, then decoding pitch using specified methods (argmax or locally_normal) and periodicity using entropy or max methods, returning transposed results.
def _postprocess(self, logits: torch.Tensor): """ Convert model output to pitch and periodicity """ # Convert frequency range to pitch bin range minidx = self._frequency_to_bins( torch.as_tensor( [self.f_min], dtype=logits.dtype, ...
def _convert_action(self, action): """given some action, convert it first into the controller state SimpleHvac.Xt and then into control inputs to the cabin and hvac. action is a MultiDiscrete space and thus an array of integers. """ assert self.action_space.contains( ...
This code simulates one time step of an environment, processing an action to update HVAC and cabin states, calculating reward metrics (comfort, energy, safety), and returning the new observation, reward, termination status, truncation flag, and additional info. The environment does not terminate but may be truncated ba...
def step( self, action: ActType ) -> Tuple[ObsType, SupportsFloat, bool, bool, dict[str, Any]]: self.episode_clock += 1 c_x = self._convert_action(action) cab_t = estimate_cabin_temperature_dv1(self.b_x) self._step_hvac(c_x, cab_t) self._step_cabin(c_x) rew...
def check_products_stock(): banner() print("\t Our product list\n") tabulate_view(db.carts) carts_name = db.carts["Name"] for name in carts_name: cart_index = db.carts["Name"].index(name) if name not in db.products["Name"]: print(f'"{name}" is out of stock!') ...
This function manages a customer's shopping cart interface, allowing them to view their cart, add/update/delete products, and checkout. It checks product stock before displaying the cart, then loops through menu options to handle cart operations until the user logs out.
def consumer_menu(): if len(db.carts["Index"]) > 0: check_products_stock() while True: banner() print("\t Your current carts\n") tabulate_view(db.carts) print("""Welcome dear customer List Menu : 1. Add Product to Carts 2. Update Product in Carts 3. Delete Product in Ca...
def banner(): os.system('cls') print("""\t\tTokoIndo ========================================""") def tabulate_view(data): print(tb(data, headers='keys', tablefmt='grid'), end="\n\n") def input_number(text = "Enter the corresponding number : ", required=True): while True: user_input = input(text...
The code provides a seller menu for managing products, allowing users to add, update, delete products, or log out. It loops continuously, displaying the product list and menu options, then executing the selected action via corresponding functions until the user chooses to log out.
def seller_menu(): while True: banner() print("\t Your product list\n") tabulate_view(db.products) print("""List Menu : 1. Add New Product 2. Update Product 3. Delete a Product . Log-Out\n""") menu_number = input_number() if menu_number == 1: add_new_p...
def check_url(text): url_pattern = "http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+" urls = re.findall(url_pattern, text) return urls def email_predict(email_text): predicted_label = email_pipeline.predict([preprocess_email(email_text)]) # Print the predicted label (1 for...
The code predicts URLs or emails in the input text. If URLs are detected, it returns URL predictions; otherwise, it returns email predictions. It uses `check_url` to find URLs, `email_predict` for email detection, and `url_predict` for detailed URL analysis. The function prioritizes URL predictions when available, othe...
def final(text): urls=check_url(text) ans=email_predict(text) if len(urls)!=0: x = "URL Predictions: \n\n" for i in urls: x=x+url_predict(i)+"\n" return x return ans+"\n"
def nn_layer_conv(input_tensor, input_dim, filter_dim, output_dim, layer_name, act=tf.nn.relu): """Helper for making a convolutional neural net layer Does convolution, bias add, relu, and max_pool. Also sets up handy name scoping. """ with tf.name_scope(layer_name): with tf.name_scope("weights"...
This code implements a convolutional neural network (CNN) for classifying MNIST digits. It defines a 2-layer CNN with ReLU activation, max-pooling, and dropout regularization, followed by a fully connected output layer. The model is trained using Adam optimization with cross-entropy loss over 20,000 steps, evaluating a...
def main(): """Main function""" print("Loading MNIST data") mnist = input_data.read_data_sets("MNIST_data", one_hot=True) print("Data loaded") sess = tf.InteractiveSession() ### Data specification img_x = 28 img_y = 28 img_color_channels = 1 # greyscale images num_pixels = img_...
def _get_messages(self) -> list[Message]: messages = self.message_repository.get_messages_to_send() return messages def _send_messages(self, messages) -> list: messages_sent = [] for message in messages: try: message_str = self._create_message_str(message) ...
The code's main task is to read messages from a source, send them (or simulate sending in test mode), log progress, and update message statuses, handling exceptions by logging errors.
def run(self): try: logging.info("Reading messages from source...") messages = self._get_messages() logging.info(f"Sending {len(messages)} messages...") messages_sent = self._send_messages(messages) if not self.configuration.test_mode_enabled else messages ...
def set_logger(self, test_dir): """ Initialize logger and test directory """ formatter = logging.Formatter('%(asctime)s %(message)s') file_handler = logging.FileHandler(test_dir + self.config["file"]["log_path"] + "Architecture_retraining.log") stream_handler = logging.St...
The code processes a test directory by initializing logging, loading a pre-trained model, and performing retraining to adapt the model to new data or tasks.
def process(self, test_dir): self.set_logger(test_dir) self.load_model() self.retrain()
def update_mouse_driving(self): drive_dir = (self.drive_forwards - self.drive_back) if (drive_dir > 0.1) and self.cozmo.is_on_charger: # cozmo is stuck on the charger, and user is trying to drive off - issue an explicit drive off action try: # don't wait for acti...
This function handles keyboard input to control movement, speed, and animations. It updates driving (WASD), lift (RF), and head (TG) states based on key presses. Shift/Alt modify speed settings. On key release, digits trigger animations, and space triggers speech. Updates relevant systems only when states change.
def handle_key(self, key_code, is_shift_down, is_ctrl_down, is_alt_down, is_key_down): '''Called on any key press or release Holding a key down may result in repeated handle_key calls with is_key_down==True ''' # Update desired speed / fidelity of actions based on shift/alt being hel...
def create_socket(): try: #Creating following 3 global variables global host global port global s #This is socket variable which is named s #Assigning values to these 3 global variables host = "" port = 9999 s = socket.socket() # Cr...
The main task of the code is to set up a server socket by creating a socket, binding it to a specific address and port, and then accepting incoming client connections. This sequence initializes a network server capable of receiving and handling client requests.
def main(): create_socket() bind_socket() socket_accept()
def correctTrajectoryFluctuations(data_array,navangles): na = cp.asnumpy(navangles) una = np.unique(na) idx = np.argsort(-1*na) interleaves = len(una) factor = (int(math.ceil(data_array.shape[1] / interleaves)) % int(interleaves)) - round(data_array.shape[1] / interleaves) # print(na[idx[0:20]...
The function processes navigation data by transforming, filtering, and compressing signals using SVD to extract dominant motion patterns, then returns the processed signal and adjusted sampling time.
def estimateGatingSignal(nav_data,nav_tstamp,navangles,acq_tstamp): data_array = cp.asarray(np.concatenate(nav_data,axis=1)) data_array= cp.reshape(data_array,(nav_data[0].shape[0],len(nav_data),nav_data[0].shape[1])) number_channels = data_array.shape[0] data_array = cp.abs(cufft(data_array,...
def eprint(*args, **kwargs): print(*args, file=sys.stderr, **kwargs) def _parse_params(xml): return {p.get('name'): p.get('value') for p in xml.iter('property')} def estimateGatingSignal(nav_data,nav_tstamp,navangles,acq_tstamp): data_array = cp.asarray(np.concatenate(nav_data,axis=1)) data_array=...
The main task of the code is to perform binning of MR acquisitions using a gating signal derived from navigation data. It processes MRD acquisitions, extracts navigation angles and timestamps, estimates a respiratory waveform, and bins acquisitions into groups based on the waveform. Configurable parameters include bin ...
def BinningGadget(connection): eprint("Ready to do some Binning in Python") #connection.filter(lambda acq: acq) connection.filter(mrd.Acquisition) params = _parse_params(connection.config) if "numBins" in params: numBins = int(params["numBins"]) else: numBins = 6 ...