dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def query(self, method: str = 'get', data=None, headers=None, iri: str = None): if headers is None: headers = {} if data is None: data = {} http_method = getattr(self.client, method) response = http_method(self.build_url(self.resource_name, iri), data=data, heade...
This method performs a DELETE HTTP request by serializing provided data into JSON, constructing appropriate headers, and invoking a query method with these parameters. It handles default values for data and headers, ensuring the DELETE operation is executed with properly formatted payload and headers.
def delete(self, data=None, headers=None): if headers is None: headers = {} if data is None: data = {} return self.query(method="delete", data=json.dumps(self.serialize(data)), headers=self.build_headers(headers))
def query(self, method: str = 'get', data=None, headers=None, iri: str = None): if headers is None: headers = {} if data is None: data = {} http_method = getattr(self.client, method) response = http_method(self.build_url(self.resource_name, iri), data=data, heade...
The main task of the code is to retrieve data related to a specified IRI using a GET request, process the response, and populate a model instance with the retrieved data. It handles headers, serializes the current object, constructs request headers, executes the query, and returns a populated model instance. This funct...
def get_relation(self, model, iri: str, headers=None): if headers is None: headers = {} resource = self.query(method="get", data=json.dumps(self.serialize()), headers=self.build_headers(headers), iri=iri) return model().populate(data=resource)
def post(self, data=None, headers=None): if headers is None: headers = {} if data is None: data = {} return self.query(method="post", data=json.dumps(self.serialize(data)), headers=self.build_headers(headers)) def serialize(self, data=None, filters=None): if filte...
The main task of the code is to create an object by serializing input data, sending it via a POST request, printing the response, and populating a new object with the received response data. It handles optional input data, ensures a default empty dictionary if none is provided, and returns a populated instance based on...
def create(self, data=None): if data is None: data = {} response = self.post(self.serialize(data)) print('response', response) return self.populate(data=[response])
def find_revision(self, issue_title, project_upsource): self.log.info(f'Finding a revision for {str(issue_title)} Issue') revision_id = None try: revision_list = self.review.get_filtered_revision_list(issue_title, project_upsource) except Exception as e: raise In...
The code integrates code review issues from a product system (product_onevizion) into a project management system (project_upsource). It retrieves issues, checks for existing reviews, finds corresponding revisions, and creates reviews if needed. Finally, it verifies open reviews in the project to ensure synchronization...
def integrate_product(self, product_onevizion, project_upsource): issue_list = self.issue.get_list_for_review(product_onevizion) if len(issue_list) == 0: self.log.info('No Code Review Issue found.') for issue in issue_list: issue_id = issue[self.issue.issue_fields.ID] ...
def is_code(line, indent_depth = 4): '''returns the indent depth, 0 means not code in markup''' if line.startswith(' ' * indent_depth): return len(line) - len(line.lstrip(' ')) return 0 def process_code(read_filehandle, text_filehandle, line, linenum, sourcefile, codedir, name, index, indent_depth):...
The main task of the code is to process a markdown file by splitting it into a plain-text version (removing code snippets and markdown non-words for spell-checking) and isolating code blocks into separate files. Each code snippet is saved in a specified directory with surrounding C++ context, marked by tokens for filte...
def main(): """ This script ended up ugly, so in case somebody wants to reimplement, here is the spec that grew by time. What it should do it take a markdown file, and split it into more files. A targetfile should have the same number of lines as the original, with source code snippets and markdown non...
def getprogdir(): """ If the application is run as a bundle, the PyInstaller bootloader extends the sys module by a flag frozen=True and sets the app path into variable _MEIPASS'. Cx_freeze requires lookup of the sys.execuatable PyInstaller Version 5.0 will change to __file__ as a full abspath. ...
The main task of the code is to initialize a program by setting up directories, loading configuration files, merging menu items from predefined and custom sources, and launching a tray application with the aggregated menu. It handles both development and production environments by checking for custom menu configuration...
def klipchop(): global progdir, configdir, configpath progdir = Path(getprogdir()) configdir = Path.home() / f'.{__appname__}' configpath = configdir / f'{__appname__}.yaml' if configpath.exists(): configload() menu = readmenuconfig(progdir / 'transforms' / 'menu.config') devcusto...
def get_token(): auth = {"username": API_USERNAME, "password": API_PASSWORD} response = requests.post(f"{API_URL}/v2/login", json=auth) response.raise_for_status() token = response.json() return token def create_job(token: str) -> str: lcabyg_project = base64.b64encode(PROJECT_PATH.read_bytes())...
The main task of the code is to authenticate using a token, create a job, and download its results. It first retrieves an authentication token, then creates a new job with that token, and finally downloads the results associated with the created job. The commented-out lines suggest potential future functionality for re...
def main(): token = get_token() #job_ids = get_jobs(token) #get_statuses(token, job_ids) job_id = create_job(token) download_results(token, job_id)
def api_submit_job(self, job: NewJob) -> Job: res = self._smart_call(raw_api.post_job, payload=job.to_dict()) return Job.from_json(res) def api_get_job(self, job_id: str) -> Job: res = self._smart_call(raw_api.get_job_by_id, job_id=job_id) return Job.from_json(res) def api_get_job_output...
The function submits a job, monitors its status at regular intervals until completion, retrieves the output, handles failures by raising an exception if the job fails, optionally marks the job as finished, and returns the job status along with the output data as a byte blob.
def submit_job(self, job: NewJob, pool_interval: float = 1, auto_mark_as_finished: bool = True) -> Tuple[Job, bytes]: job_row = self.api_submit_job(job) while not job_row.status.worker_done(): job_row = self.api_get_job(job_row.id) time.sleep(pool_interval) output_blob ...
def click_button_xpath(self, xpath): button = self.wait_and_find_element_xpath(xpath) self.driver.execute_script("arguments[0].click();", button) def wait_and_find_element_xpath(self, xpath): self.wait_for_element_xpath(xpath) return self.driver.find_element(By.XPATH, xpath) def input_xp...
This function automates manual Twitter login via Selenium by navigating to the site, clicking login buttons (with fallback XPaths), verifying banners, inputting email/password, and handling potential screen name requirements through conditional checks.
def twitter_login_manual(self): print("...manual log in...") self.driver.get(SeleniumTwitterBot.url) # click login button from homepage try: self.click_button_xpath(SeleniumTwitterBot.enter_login_button_xpath) except: self.click_button_xpath(SeleniumTwitte...
def _get_flow_token(self, report_type, screen_name=None, user_id=None, tweet_id=None): # if user id is not provided if screen_name is not None and user_id is None: logger.info("query to get user id...") user_id = self.bot.id_from_screen_name(screen_name) if user_id is not...
The function reports a Twitter profile or tweet by processing user-defined options, validating flow tokens, and handling selection steps. It checks parameters like user_id, screen_name, and tweet_id based on report_type, skips irrelevant choices, and completes the report if all steps succeed, returning 200 on success.
def _report( self, option_name, report_type, target=None, user_id=None, screen_name=None, tweet_id=None, context_msg=None, ): """ Report a single twitter profile or tweet. Parameters: option_name (str): a short string s...
def load_cookies(self, cookies_filepath): print("...loading cookies...") cookies = pickle.load(open(cookies_filepath, "rb")) print(cookies) for cookie in cookies: # if 'expiry' in cookie and cookie['expiry'] < time.time(): # cookie['expiry'] = int(time.time()) ...
The main task of the code is to handle Twitter login via cookies or manual entry. It checks for existing cookies, loads them, and navigates to the homepage, refreshing if needed. If cookies fail, it triggers manual login. It ensures the user is on the homepage, handling phone number verification if required, and saves ...
def twitter_login(self): # cookie refreshment? expiration? what will happen when one of the cookies expire? if os.path.exists(self._cookie_path): self.driver.get(SeleniumTwitterBot.home_url) try: self.load_cookies(self._cookie_path) sleep(1) ...
def __check(self,type): if self.__isAtEnd(): return False return self.__peek().type == type def __advance(self): if not self.__isAtEnd(): self.current += 1 return self.__previous() def __error(self,token,message): self.lox.parseError(token,message) ...
The code's main task is to validate a data type using `self.__check(type)`. If valid, it progresses to the next state via `self.__advance()`. If invalid, it raises an error with the current state (`self.__peek()`) and provided message, ensuring type-specific error handling during data processing or parsing.
def __consume(self,type,message): if self.__check(type): return self.__advance() raise self.__error(self.__peek(),message)
def __advance(self): if not self.__isAtEnd(): self.current += 1 return self.__previous() def __isAtEnd(self): return self.__peek().type == TokenType.EOF def __previous(self): return self.tokens[self.current-1] def __peek(self): return self.tokens[self.current]
The main task of the code is to synchronize the parser by advancing through tokens until it encounters a semicolon or a new line starting with a statement keyword (e.g., CLASS, FUN, VAR, etc.), at which point it stops advancing to align with the next valid code structure.
def __synchronize(self,token,message): # discard tokens until reaching the end self.__advance() while (not self.__isAtEnd()): if self.__previous().type == TokenType.SEMICOLON: return match self.__peek().type: # stop advance until reac...
def __advance(self): # current points to the next char char = self.source[self.current] self.current += 1 return char def __add_simple_token(self,type:TokenType): self.__add_token(type,None) def __match(self,expected:str): if (self.reach_end): return False if ...
This function scans and classifies individual tokens from the input, handling punctuation, operators (including multi-character ones like !=, ==, <=, >=), comments, whitespace, strings, numbers, and identifiers. It adds appropriate tokens to the token list or handles errors for unexpected characters.
def __scan_token(self): c = self.__advance() match c: case '(': self.__add_simple_token(TokenType.LEFT_PAREN) case ')': self.__add_simple_token(TokenType.RIGHT_PAREN) case '{': self.__add_simple_token(TokenType.LEFT_BRAC...
def _should_notify(latest_ver, proj_history): if latest_ver in proj_history: # Processed this version before. return False timestamp = proj_history.get(NOTIFIED_TIME_KEY_NAME, 0) time_diff = datetime.today() - datetime.fromtimestamp(timestamp) if git_utils.is_commit(latest_ver) and time...
The function processes project version updates by checking if a new version exists, determining if a notification is needed, and sending an email with upgrade details if so. It updates a history dictionary with the latest version and notification timestamp, handling errors during email sending. If versions match or no ...
def _process_results(args, history, results): for proj, res in results.items(): if 'latest' not in res: continue latest_ver = res['latest'] current_ver = res['current'] if latest_ver == current_ver: continue proj_history = history.setdefault(proj, {}) ...
def get_current_version(self): """Returns the latest version name recorded in METADATA.""" return self.metadata.third_party.version def _fetch_latest_commit(self): """Checks upstream and gets the latest commit to master.""" url = 'https://api.github.com/repos/{}/{}/commits/master'.forma...
The code checks for updates of a package by comparing the current version with the latest version. If the current version is a Git commit, it fetches the latest commit; otherwise, it fetches the latest version. It then prints both versions, indicating whether an update is available.
def check(self): """Checks update for package. Returns True if a new version is available. """ current = self.get_current_version() if git_utils.is_commit(current): self._fetch_latest_commit() else: self._fetch_latest_version() print('Curr...
def _do_update(args): updater, _ = check_update(args.path) if updater is None: return if not has_new_version(updater) and not args.force: return full_path = fileutils.get_absolute_project_path(args.path) if args.branch_and_commit: git_utils.checkout(full_path, args.remote_na...
The code defines an 'update' function that handles the update command by attempting to execute '_do_update' with provided arguments. It catches 'subprocess.CalledProcessError' exceptions, generates an error message using '_message_for_calledprocesserror', and prints a formatted error message with a colored 'Failed to u...
def update(args): """Handler for update command.""" try: _do_update(args) except subprocess.CalledProcessError as err: msg = _message_for_calledprocesserror(err) print( '{}\n{}'.format( msg, color_string( 'Failed to upgr...
def parse_args(): """Parses commandline arguments.""" parser = argparse.ArgumentParser( description='Check updates for third party projects in external/.') parser.add_argument( '--history', help='Path of history file. If doesn' 't exist, a new one will be created.') pars...
The main task of the code is to serve as the entry point for a program that parses command-line arguments, checks for updates based on those arguments, and sends notifications. It orchestrates three key operations: argument parsing, update verification, and notification delivery, all driven by the parsed input paramete...
def main(): """The main entry.""" args = parse_args() _check_updates(args) send_notification(args)
def check_if_its_softwares_files(self, entry, name): for softwares_extension in softwares_extensions: if name.endswith(softwares_extension) or name.endswith(softwares_extension.upper()): dest = dest_dir_softwares move_file_func(dest, entry, name) log...
The code defines a method `on_modified` that triggers when files are modified in a download directory. It scans the directory, iterates through entries, and checks each file to categorize it as software, video, image, or document by calling specific validation methods. The main task is monitoring file changes and class...
def on_modified(self, event): with scandir(download_dir) as entries: for entry in entries: name = entry.name self.check_if_its_softwares_files(entry, name) self.check_if_its_video_files(entry, name) self.check_if_its_image_files(entry, ...
def tokenize_train_file(fname): """ Tokenize the raw train data(unlabeled). """ split_fname = fname.split('/') new_fname = '/'.join([el if idx != len(split_fname) - 1 else 'parsed_' + el for idx, el in enumerate(split_fname)]) if os.path.exists(new_fname): return new_fname with open(fname, ...
The main task of the code is to process text datasets by tokenizing training and test files, building a vocabulary from the training data, and converting both datasets into binary formats for machine learning. It handles labeled/test data by mapping labels and generating structured input files for model training and ev...
def main(): train_fname = './data/datasets/{}/train.txt'.format(args.dataset) test_fname = './data/datasets/{}/test.txt'.format(args.dataset) test_label_fname = './data/datasets/{}/test_label.txt'.format(args.dataset) vocab_fname = './data/vocab.txt' vocab_size = args.vocab_size parsed_train_fn...
def get_urls(url_template, first, last): """ Get URLs of webpages containing letters. Helper method for main(). :param url_template: string template of letter webpage URLs :param first: first index that goes into URL template :param last: last index that goes into URL template :return: list of U...
The main task of the code is to generate URLs for webpages containing letters, handle a website-specific URL anomaly, extract text content from the first five letters, and save the collected corpus data into a file named 'vangogh_letters.txt'.
def main(): """ Get URLs of webpages containing letters. Get text content of letters from said webpages. Save corpus data to a file. """ # Get URLs to get letter texts from url_template = 'http://vangoghletters.org/vg/letters/let{}/letter.html' urls = get_urls(url_template, 1, 902) # Ac...
def get_versions_from_tags(): """ Use Git to get all tags and parse them to extract all version info. """ process = subprocess.run(["git", "for-each-ref", "--sort=refname", "--format=%(creatordate:unix);%(object);%(objectname);%(refname)"], stdout=subprocess.PIPE, universal_newlines=True) v...
The main task of the code is to process Git version information, validate repository state, generate output files, and return error/warning status. It retrieves version tags, checks for local changes, validates head state, writes version data to a file, and handles exceptions to return error codes, messages, and warnin...
def run(target_file): global warning_msgs error_code = 0 error_msg = None warning_msgs = [] versions = get_versions_from_tags() head_sha1 = get_head_sha1() head_versions = get_head_versions(versions, head_sha1) (workingtree_changes, index_changes) = get_head_has_local_changes() tr...
def broadcastTxn(self, txn: Transaction, nodesList: List) -> None: for node in self.nodesList: if node.id != self.id: node.txQueue.put(txn) # adding it to own mempool directly self.blockchain.mempool[txn.getHash()] = txn def processTxns(self, threshold = Threshold.TXN...
This function broadcasts a transaction to a list of nodes, then continuously processes transactions and blocks until the blockchain's current balance matches a predefined genesis transaction amount. It leverages a loop to repeatedly check balance status, execute transaction/block processing, and mine new blocks via pro...
def broadcastAndRunTillSettled(self, txn: Transaction, nodesList: List): pid = os.getpid() print(pid, ": balance = ", self.blockchain.currentBalance) self.broadcastTxn(txn, nodesList) nVotingNodes = len(nodesList) - 1 while(True): print(pid, ": loop again..") ...
def broadcastTxns(self) -> None: pid = os.getpid() #with self.nTxns.get_lock(): # if self.nTxns.value >= txnLimit: #print(pid, ": (broadcastTxn)nTxns = ", self.nTxns.value) # stop # return if self.nTxns.value >= txnLimit + self.nNodes: ...
The code's main task is to run a node in a blockchain network by continuously broadcasting transactions, processing incoming transactions and blocks, and mining new blocks via proof-of-work when the mempool is non-empty. It terminates when the transaction count reaches a predefined limit plus the number of nodes, ensur...
def startRunning(self) -> None: pid = os.getpid() while(True): #for i in range(0, 100): # wait for some time # time.sleep(random.randint(1, 3)) # broadcast transaction(s) #print(pid, ": broadbast begin") #stop = True #with s...
def df_to_ls(df): ''' dataframe to dataframe of Linestrings :param: wr route only dataframe :return: save and return dataframe of linestrings ''' num_rows = df.shape[0] current_row = 1 out_df = pd.DataFrame() while current_row < num_rows: nflId = df['nflId'].iloc[current_row]...
The function assigns routes to line strings in the input DataFrame by rotating each route based on the 'running_right' direction, identifies the closest route using a helper function, removes the 'running_right' column, and returns the updated DataFrame. If a precomputed CSV file exists for the game ID, it loads and re...
def assign_routes_wrte(wrte_df): #wrapper function to assign all routes and use all functions above filename = r'C:\Users\Mitch\Documents\UofM\Fall 2018\NFL\Data\wrteRoutes_{}.csv'.format(int(wrte_df['gameId'].iloc[0])) if os.path.exists(filename): return pd.read_csv(filename) ls_df = df_to_ls(w...
def rotate_route(ls, running_right): #I wanted all routes to be seen as if they were running up from the left side of the ball #need to find where they were orignially run from and transform accordingly coords = list(ls.coords) centroidx, _ = ls.centroid.xy starting_point = coords[0] running_rig...
This function processes NFL play route data by loading game-specific CSV files, filtering routes for a given play, and visualizing comparisons between proposed and labeled routes. It generates plots to compare LineString paths, applying transformations like rotation and resizing, and outputs figures for each route comp...
def game_play_id_routes(gameId, playId, running_right, routeInd=None): routeID = [routeInd] if routeInd is not None else list(range(5)) route_df = pd.read_csv(r'C:\Users\Mitch\Documents\UofM\Fall 2018\NFL\Data\Routes_{}.csv'.format(gameId)) play_df = route_df.loc[route_df['playId'] == playId] route_l...
def df_to_ls(df): ''' dataframe to dataframe of Linestrings :param: wr route only dataframe :return: save and return dataframe of linestrings ''' num_rows = df.shape[0] current_row = 1 out_df = pd.DataFrame() while current_row < num_rows: nflId = df['nflId'].iloc[current_row]...
The function assigns routes to running backs by either loading pre-existing route data from a CSV file or generating it by processing the input DataFrame. It rotates LineStrings based on the 'running_right' flag, finds the closest route for each, drops unnecessary columns, and returns the updated DataFrame with assigne...
def assign_routes_rb(rb_df): filename = r'C:\Users\Mitch\Documents\UofM\Fall 2018\NFL\Data\rbRoutes_{}.csv'.format(int(rb_df['gameId'].iloc[0])) if os.path.exists(filename): return pd.read_csv(filename) ls_df = df_to_ls(rb_df) ls_df['route'] = ls_df.apply(lambda row: find_closest_route_rb(rotate...
def __remove_from_kratos(self, email: str) -> None: try: kratos_id = self.__get_kratos_id(email) if kratos_id: self.kratos_identities_count += 1 print(f"Kratos id for the email {email} : {kratos_id}") self.__delete_kratos_user_as_admin(kra...
The code processes a user by removing them from Kratos, checking their presence in a database, and updating tracking metrics. If the user exists in the database, it marks them as deleted, increments deletion counters, and logs the action. If not, it increments a counter for users not found in the database. The function...
def __process_user(self, email: str) -> None: # Remove user from Kratos self.__remove_from_kratos(email) if self.__is_user_present(self.__db_conn, email): self.total_users += 1 # Mark user as deleted in DB self.__mark_user_deleted(email) print(f"D...
def check_Scenario1(pred_tag: str, pred_val: str, grount_truth: list): # scenario 1: both entity type and entity boundary strictly match COR_list = [1 for true_tag, true_val in grount_truth if true_tag == pred_tag and true_val == pred_val] if len(COR_list) > 0: grount_truth.remove((pred_tag, pred_va...
The code evaluates a single case by comparing predicted and ground truth slot-tagged entities using metrics from SemEval-2013 Task 9.1. It calculates strict, exact, partial, and type-level metrics (correct, incorrect, partial, missed, spurious) and derives precision, recall, and F1 scores. The function handles scenario...
def evaluate_one(prediction: list, ground_truth: list, text: str): """ Evaluate single case Calculate detailed partial evaluation metric. See Evaluation of the SemEval-2013 Task 9.1 :param prediction (list): [(slot tag, slot content), (slot tag, slot content), (slot tag, slot content), ...] :param g...
def pose_to_occupancy_grid(self, pose): resolution = self.occupancy_grid.info.resolution origin_x = self.occupancy_grid.info.origin.position.x origin_y = self.occupancy_grid.info.origin.position.y pose_x = pose.position.x pose_y = pose.position.y grid_x = int((pose_x - ...
The code generates an optimal path from waypoints by converting each pose to an occupancy grid, determining the best order of points, converting the ordered grid back to poses, and publishing the resulting path.
def get_path(self): matrix_representation = [self.pose_to_occupancy_grid(pose) for pose in self.waypoints] path = self.find_best_order(matrix_representation) converted_path = [self.occupancy_grid_to_pose(pose[0], pose[1], pose[2], pose[3]) for pose in path] self.publish_p...
def whitespace(input): global i if(not space(input[i])): #print("ERROR -- whitespace") return False elif(not space(input[i+1])): i = i + 1 return True else: i = i + 1 return whitespace(input); def domain(input): global i if(not element(input)): ...
This code validates a server response string by checking for specific sequences ("250", "HELO", domain, "pleased to meet you"), proper whitespace, and line endings (CRLF), returning True if all conditions are met, otherwise False.
def serverHelo(input): global i if(input[0:3] != "250"): return False i = i + 3 if(not whitespace(input)): return False if(input[i : i+4] != "HELO"): return False i = i + 4 if(not whitespace(input)): return False if(not domain(input)): return False...
def previous_eg(self,event=None): if self.id == 1: self.id = self.number_rows-1 self.complete_example = self.get_complete_example(self.id) self.refresh_front_card() else: self.id-=1 self.complete_example = self.get_complete_example(sel...
The code defines a method `load_buttons` that creates and positions several GUI buttons on a window. These include navigation buttons (previous, forward) for example traversal, a play audio button to trigger audio playback, and a back button to return to the main menu. Each button is configured with specific images, co...
def load_buttons(self): self.previous_button_image= PhotoImage(file='images/back_button.png', width=40, height=67) self.previous_button= Button(self.listening_window, image=self.previous_button_image,command= lambda: self.previous_eg(), borderwidth=0) self.previous_button.place(relx=0.399, rely=...
def get_current_eg(self,id): obj = self.db_obj.get_eg_by_id(id) return obj def load_card(self): self.flashcard_canvas = Canvas(width=800, height=518, background=BACKGROUND_COLOR, highlightthickness=0) self.my_flashcard_image = PhotoImage(file="images/card_front.png") self.new_ima...
This code initializes a GUI application for an English learning tool. It sets up a window with specific styling, connects to a database, retrieves data, and loads UI components like cards and buttons for interactive grammar learning. The mainloop starts the application's event loop for user interaction.
def __init__(self, window): self.grammar_window = window self.db_obj = DB_Actions() self.grammar_window.title("ENGLISH APP") self.grammar_window.config(background=BACKGROUND_COLOR, height=728, width=1200) self.grammar_window.resizable(True,True) self.id = 1 self.c...
def get_current_word(self,id): obj = self.db_obj.get_word_by_id(id) return obj def get_complete_example(self,id): obj = self.db_obj.get_complete_example(id) return obj def get_current_meaning(self,id): obj = self.db_obj.get_meaning(id) return obj def load_card(self): ...
This code initializes a GUI application for a pronunciation learning tool. It sets up a window with specific dimensions and background, initializes audio mixer for sound playback, loads data (words, meanings, examples) from a database, and prepares UI components (cards, buttons) for interactive learning. The mainloop s...
def __init__(self, window): mixer.init() self.pronunciation_window = window icon = main.InsertIcon(self.pronunciation_window) self.db_obj = DB_Actions() self.pronunciation_window.title("PRONUNCIATION WINDOW") self.pronunciation_window.config(background=BACKGROUND_COLOR, h...
def load_text_area(self): self.textarea = ScrolledText(self.listening_window,foreground='black',background="#F8F3EA") self.textarea.config(state=DISABLED) self.textarea.place(relx=0.01, rely=0.12, relwidth=0.99, relheight=0.66) def get_complete_example(self,id): obj = self.db_obj.get_com...
This code initializes a GUI listening window with audio capabilities, sets window properties, loads text areas and buttons, retrieves data from a database, and configures UI elements like titles and icons. It prepares the interface for interaction with database records and audio features.
def __init__(self, window): mixer.init() self.listening_window = window icon = main.InsertIcon(self.listening_window) self.db_obj = DB_Actions() self.listening_window.title("LISTENING WINDOW") self.listening_window.config(background=BACKGROUND_COLOR, height=728, width=120...
def evaluate_step(self, input_batch): self.model.eval() with torch.no_grad(): images = input_batch['images'] out = self.model(images) pred_vertices = out["pred_coord"][-1] gt_points = input_batch["points_orig"] if isinstance(gt_points, list)...
The code evaluates a model on a test dataset by computing metrics like Chamfer distance and F1 scores. It loads data using a DataLoader, processes batches, runs evaluation steps, tracks metrics with AverageMeter, logs results periodically, and outputs final test metrics with step counts.
def evaluate(self): self.logger.info("Running evaluations...") self.evaluate_step_count = 0 test_data_loader = DataLoader(self.dataset, batch_size=self.options.test.batch_size * self.options.num_gpus, num_workers=self....
def load_data(num_records_per_class=200): data, labels = load_digits(return_X_y=True) (n_samples, n_features), n_digits = data.shape, np.unique(labels).size print(f"# digits: {n_digits}; # samples: {n_samples}; # features {n_features}") all_train_sets = [] classes = [5.0, 6.0, 9.0] for cls in c...
This code performs hyperparameter tuning for clustering and dimensionality reduction algorithms by evaluating multiple configurations on data subsets. It loads or generates data, runs statistical analysis to identify optimal parameter combinations, and saves results. The main tasks include: 1) Evaluating clustering/dim...
def full_run(quantiative_data_p="quantiative_data.json", best_quantiative_data_p="quantiative_data.json"): if os.path.exists(quantiative_data_p): with open(quantiative_data_p, "r") as f: all_hyper_params_results = json.load(f) else: full_data, target_names = load_data(num_records_per...
def apply_algs_with_all_hyper_params_configs(self): self.data_subsets, self.external_tags = self.get_subsets(self.data, self.num_of_iterations_for_statistical_analysis) for alg_name in tqdm(self.algs): self.all_hyper_params_res...
This function evaluates multiple algorithms with all hyperparameter configurations, selects optimal hyperparameters and external variables using metrics like silhouette and MI, identifies the best-performing algorithm, and optionally saves the best models and their results if 'save_best' is True.
def algs_evaluation_pipeline(self, save_best=False): """ :param save_best: whether to save best models and theirs results or not :return: None """ self.apply_algs_with_all_hyper_params_configs() best_hps = {} if self.algs_type == DIM_REDUCTION: from vi...
def update_gossip_targets(self): self.n_gossip_targets = max(1, int(math.log(1 + self.members.size(), 2))) def update_neighbors_removed(self, node_id): need_full_update = False if (node_id in self.left_neighbors): self.left_neighbors.remove(node_id) if (node_id in self.he...
The code removes a specified node from the member list, updates gossip targets, handles neighbor removals, and logs the updated member list post-removal.
def remove_member(self, node_id): self.members.remove(node_id) self.update_gossip_targets() self.update_neighbors_removed(node_id) self.log_member_list("post-remove")
def send_join_msg(self): join_msg = self.make_join_msg() join_target = self.ip while (join_target == self.ip): join_target = self.known_ips[random.randint(0, len(self.known_ips) - 1)] self.join_src = join_target self.env.send_data(self.get_id(), join_target, join_msg)...
This code initializes a node in a distributed system, setting up its environment, neighbors, and callbacks for periodic tasks like gossiping membership, failures, heartbeats, and rejoin checks. It tracks node status, manages membership lists, and prepares for fault detection and recovery, ensuring the node can particip...
def __init__(self, ip, known_ips, env): self.env = env self.ip = ip self.start_time = env.get_time() self.known_ips = known_ips self.send_join_msg() self.left_neighbors = [] self.right_neighbors = [] self.heartbeat_times = {} self.members = Removab...
def run_simple_test(test_pattern): return run_test("simple", test_pattern, "simple_log___VM_ID__.txt") def run_realistic_test(test_pattern): return run_test("realistic", test_pattern, "vm__VM_ID__.log") def print_final_result(result): bar_str = "****" for _ in range(0, len(result)): bar_str += "...
The main task of the code is to execute and validate two sets of test patterns—simple and realistic—by running corresponding test functions. It checks if all tests pass, reporting "ALL TESTS PASSED" if both sets succeed, or "TESTS FAILED" if any test in either set fails. The function iterates through predefined pattern...
def run_correctness_tests(): simple_passing = True print("Running simple tests...") for pattern in SIMPLE_TEST_PATTERNS: print("\tTest pattern: %s" % pattern) result = run_simple_test(pattern) if (result == False): simple_passing = False if simple_passing: pri...
def errors_test(n_neighbors, weights, leaf_size, p): is_good = True my_model = model.KnnKdtreeRegressor( n_neighbors=n_neighbors, weights=weights, leaf_size=leaf_size, p=1 ) x, y = generate_test() x_train, x_test, y_train, y_test = train_test_split(x, y, train_size=...
The code runs multiple tests to validate a custom machine learning model against scikit-learn's implementation. It executes error checks, random dataset comparisons, and California housing dataset tests, verifying output consistency. If tests pass, it prints success messages and results; otherwise, it reports failures....
def tests(test_num=1, n_neighbors=10, weights='uniform', leaf_size=30, p=1): if test_num <= 0: raise Exception('Not enough tests') print('Number of tests:', test_num) print() print('errors_test is in progress') is_good = errors_test(n_neighbors, weights, leaf_size, p) if is_good: ...
def preprocess(image, case): """ It takes an image, resizes it, and then applies a perspective transform to it Args: image: The image to be preprocessed case: True if the image is a scanned image, False if it's a photo Returns: The preprocess function returns the following: """ ...
The function `check_solution` processes a Sudoku image by preprocessing, detecting the grid, recognizing digits, solving the puzzle, and overlaying the solution on the original image. It returns `True` if the Sudoku is successfully solved and overlaid, otherwise `False`. Key steps include image inversion, grid point de...
def check_solution(output_filename) -> bool: """ It takes a screenshot of the sudoku board, preprocesses it, finds the grid points, finds the digits, creates a sudoku matrix, solves the sudoku, and then overlays the solution on the original image Returns: a boolean value. """ case = "Fals...
def find_ball_in_frame(self, img): mask = self.segment_ball(img) if self.cur_frame < 90: points = self.find_edge_points(mask) final_center, final_radius = self.fit_circle_to_edge(points) else: self.upper_threshold = 170 edge = BallDitector2D.find_e...
This function processes all frames in a directory to detect and track a ball's position and radius. It reads each frame, identifies the ball's center and radius, stores these values in arrays, and saves the results. The function skips the first frame and processes subsequent frames to track the ball's movement across f...
def find_ball_all_frames(self): file_list = os.listdir(self.ball_frames_dir) # file_list.sort() radii = [] centers = [] for i, file in enumerate(file_list): if i < 1: continue self.cur_frame = i if i == 28: pass prin...
def color_thresholding(image, color_masks): # initialize a blank image blank = np.zeros(image.shape[:2], dtype=np.uint8) # save the width and height of the image height, width = image.shape[0],image.shape[1] # create a rectangular mask that will display the approx. lower 2/3rd of the image # thi...
The main task of the code is to preprocess video frames to identify road lanes by detecting and averaging edge lines, creating a polygon mask representing the road, and generating lane-specific masks for further processing. It applies color thresholding, edge detection, and line averaging to determine road boundaries, ...
def get_preprocessing_mask(self): '''initial attempt at determining where the road is.''' left_images = [] right_images = [] self.averaged_lines = [] frames = self.first_few_frames.copy() for frame in frames: thresh_img = color_thresholding(frame, self.get_col...
def piece_count(state): wp = len(state.pieces(chess.PAWN, chess.WHITE)) bp = len(state.pieces(chess.PAWN, chess.BLACK)) wn = len(state.pieces(chess.KNIGHT, chess.WHITE)) bn = len(state.pieces(chess.KNIGHT, chess.BLACK)) wb = len(state.pieces(chess.BISHOP, chess.WHITE)) bb = len(state.pieces(ches...
This code evaluates a chess board state's utility by combining material balance, piece mobility, checkmate status, attack potential, and endgame phase evaluations. It calculates weighted contributions from material differences, pawn-adjusted endgame scores, and positional factors to determine an overall utility value f...
def utility(state): pieces = piece_count(state) whiteMaterial = material(state, "WHITE") blackMaterial = material(state, "BLACK") whiteMaterialWithoutPawns = whiteMaterial - len(state.pieces(chess.PAWN, chess.WHITE))*PAWN_WEIGHT blackMaterialWithoutPawns = blackMaterial - len(state.pieces(chess.PAWN...
def crawl(directory): """ Parse a directory of HTML pages and check for links to other pages. Return a dictionary where each key is a page, and values are a list of all other pages in the corpus that are linked to by the page. """ pages = dict() # Extract all links from HTML files for f...
The main task of the code is to calculate and print PageRank values for web pages in a given corpus using two methods: sampling and iteration. It first validates input, crawls the corpus, computes ranks via sampling with specified parameters, prints results, then recalculates ranks iteratively and prints them again, sh...
def main(): if len(sys.argv) != 2: sys.exit("Usage: python pagerank.py corpus") corpus = crawl(sys.argv[1]) # corpus = crawl(DIRECTORY) ranks = sample_pagerank(corpus, DAMPING, SAMPLES) print(f"PageRank Results from Sampling (n = {SAMPLES})") for page in sorted(ranks): print(f" ...
def overlay_y_on_x(x, y): x_ = torch.zeros(x.shape[0],X,x.shape[2]).cuda() x_[range(x.shape[0]), y,:] = (torch.abs(x).max()) x=torch.cat((x_,x), 1) x=torch.cat((x,x_), 1) return x def PNN_optics(self, x,x1, k): if k==0: x=torch.cat((x, x), 2) x=self.Pad(x) else: ...
The code trains a neural network model using positive and negative samples generated by overlaying labels on input data. It iterates over epochs and batches, computes loss through custom layers, tracks loss values, and logs training/validation accuracy periodically. The model uses contrastive learning principles, resha...
def train(self, train_loader,val_loader): k=0 print('Start Training ...') for i in range(self.num_epochs): self.loss_list=[0] * self.N_layer for j, data in enumerate(train_loader, 0): x, y = data x, y = x.cuda(),y.cuda() x=torch.r...
def change_costume(self): # Change costume only if threshold exceeded if self.costume_step_counter > self.costume_switching_threshold: # Reset counter and increase costume index self.costume_step_counter = 0 self.costume_index += 1 # If it's the last cos...
The code's main task is to update an object's state by changing its costume and handling movement. If the object is moving, it calls the move method; otherwise, it changes its motion state. This ensures visual and behavioral updates based on the object's current movement status.
def update(self): self.change_costume() if self.is_moving: self.move() else: self.change_motion()
def input(self): self.movement_vector = self.game_state.player_movement_vector self.movement_direction = self.game_state.player_movement_direction def change_costume(self): if self.is_moving: # Change costume only if threshold exceeded if self.step_counter > self.costume_...
The code defines an `update` method that orchestrates three key actions: capturing input, modifying the object's appearance (costume), and executing movement. Its primary task is to update the object's state by processing input, altering its visual form, and initiating motion, likely for animation or interactive applic...
def update(self): self.input() self.change_costume() self.move()
def deobfuscate_value(obfuscation_key, value): """ De-obfuscate a given value parsed from the chainstate. :param obfuscation_key: Key used to obfuscate the given value (extracted from the chainstate). :type obfuscation_key: str :param value: Obfuscated value. :type value: str :return: The d...
The main task of the code is to parse and decode Bitcoin UTXO (Unspent Transaction Output) data from a LevelDB database, handling obfuscation keys and version-specific decoding. It iterates through entries, decrypts values using XOR with the obfuscation key, decodes UTXO data based on the blockchain version, and yields...
def parse_ldb(fin_name, version=0.15, types=(0, 1)): counter = 0 if 0.08 <= version < 0.15: prefix = b'c' elif version < 0.08: raise Exception("The utxo decoder only works for version 0.08 onwards.") else: prefix = b'C' # Open the LevelDB db = plyvel.DB(fin_name, compres...
def init_windows(screen, n): logo_height = len(LOGO) logo_width = max(len(r) for r in LOGO) logo = Window( screen, logo_height, logo_width, max_lines=len(LOGO), border=False ) content_height = n + 2 # Includes border content_width = n * 2 - 1 + 4 # Includes border and space ...
The code implements a terminal-based game similar to 2048, where the player merges tiles on an n×n grid using arrow key inputs. The main tasks include initializing the game screen, handling user input for tile movement, updating the grid state, and checking win/loss conditions. The game starts with two random tiles, an...
def main(screen, n=4): # This is the only time the whole screen is ever refreshed. But if you # don't refresh it, screen.getkey will clear it, because curses is awful. screen.refresh() # Turn off visible cursor. curses.curs_set(False) # Create screen objects. content, logo = init_windows(s...
def get_database(self): all_data = pd.read_csv(os.path.join('/home/jeremy.levy/Jeremy/copd_osa/SHHS_Causal/', 'data_dimensionality_reduction.csv')) if self.short_sample is True: all_data = all_data.sample(200) t = all_data[t_baseline].val...
The code trains a machine learning model using specified data loaders, optimizes it with Adam, and evaluates the best validation loss. It then loads the optimal model weights, performs inference on validation data, and prints the results. The main task is model training, validation, and evaluation with result output.
def run(self): train_dataloader, val_dataloader, _, _ = self.get_database() model = self.get_model() optimizer = torch.optim.Adam(model.parameters(), lr=self.params['learning_rate']) best_val_loss = self.train_model(train_dataloader, val_dataloader, optimizer, model) self.write...
def init_client_dict(): for i in range(1, APPROX_TOTAL_CLIENTS + 1): CLIENT_DICT[i] = { "available": 0, "held": 0, "total": 0, "locked": False, } def deposit(writer, provided_id=None): tx_id = gen_tx_id() client_id = None if provided_id: ...
The main task of the code is to generate a specified number of weighted random transactions (deposit, withdrawal, dispute, resolve, chargeback) and record them in a CSV file, while maintaining client account balances in another CSV. It initializes client data, clears existing output files, processes transactions with p...
def main(number_of_txs): init_client_dict() # Reset the csv files if os.path.exists(TX_FILE_PATH): os.remove(TX_FILE_PATH) if os.path.exists(REC_FILE_PATH): os.remove(REC_FILE_PATH) with open(TX_FILE_PATH, "w", newline="") as csvfile: wrt = csv.writer(csvfile, delimiter=","...
def h(s,xtar,ytar,n): x= s//n y=s%n return abs(xtar-x)+abs(ytar-y) def pop(tree,dict,g): temp = tree[0] tree[0] = tree[len(tree)-1] del(tree[len(tree)-1]) return temp,siftdown(tree,dict,g) def insert(address, tree,dict,g): tree.append(address) return siftup(tree,len(tree)-1...
The code implements an A* pathfinding algorithm to find a path from a starting position `(xstart, ystart)` to a target position `(xtar, ytar)` on a grid (`board`). It uses a heuristic function `h()` to estimate the cost to the target, tracks distances (`g`), and maintains open/closed sets for exploration. If a path is ...
def loop(board,xstart,ystart,xtar,ytar,n,num,hue): counter=0 orig = copy.deepcopy(board) prev =0 s = xstart*n+ystart x=s//(n) y=s%(n) g={s:prev} if(s in hue): f = hue[s]+g[s] else: f = h(s,xtar,ytar,n)+g[s] openf = {s:f} openhead = [s] closedf=dict()...
def h(s,xtar,ytar,n): x= s//n y=s%n return abs(xtar-x)+abs(ytar-y) def pop(tree,dict,g): temp = tree[0] tree[0] = tree[len(tree)-1] del(tree[len(tree)-1]) return temp,siftdown(tree,dict,g) def insert(address, tree,dict,g): tree.append(address) return siftup(tree,len(tree)-1...
The function `loop` implements an A* pathfinding algorithm to find the shortest path from a starting position to a target position on an `n x n` grid. It avoids obstacles ('B') by exploring adjacent cells, using a heuristic `h` to prioritize directions. The path is recorded via a parent map, and if successful, it write...
def loop(board,xstart,ystart,xtar,ytar,n,num): counter=0 orig = copy.deepcopy(board) prev =0 s = xstart*n+ystart x=s//(n) y=s%(n) g={s:prev} f = h(s,xtar,ytar,n)+g[s] openf = {s:f} openhead = [s] closedf=dict() parent={s:s} #print("%s %s %s %s" %(xstart,ystart,xtar,y...
def xy_to_state(state_x, state_y, n): return (state_x*n)+state_y def state_to_xy(state, n): return state//(n), state%(n) def reveal(state_x, state_y, game_board, board, n): if (state_x > 0) and (game_board[state_x-1][state_y] != 'X'): game_board[state_x-1][state_y] = board[state_x-1][state_y] ...
This function implements an A* pathfinding algorithm to navigate a grid from a start to a target position, dynamically revealing the board as the agent moves, handling obstacles by recalculating paths, and recording the exploration and results in a file if no path is found or a path is successfully found.
def r_astar(board, xstart, ystart, xtar, ytar, n, num): # The board that is visible to the agent -- Starts blank game_board = [['U']*n for _ in range(n)] state = xy_to_state(xstart, ystart, n) state_x, state_y = state_to_xy(state, n) game_board[xstart][ystart] = 'S' goal_state = xy_to_...
def read_shellcode(input_file) -> bytes: with open(input_file, 'rb') as f: return f.read() def manage_shellcode_encoding(input_file, output_file=None): print(f"\n[#] ENCODING") shellcode = read_shellcode(input_file) encoded_shellcode = encode_shellcode(shellcode) print(f"[+] Encoded shel...
The code's main task is to encode shellcode from an input file, verify the encoding/decoding process, and generate a NASM decoder. It parses command-line arguments for input/output files and templates, reads shellcode, encodes it (ensuring no null bytes), decodes it to validate correctness, and produces a NASM assembly...
def main(): parser = argparse.ArgumentParser() parser.add_argument("-i", "--input", help="File containing shellcode to encode", required=True) parser.add_argument("-it", "--input-template", help="Template for the NASM decoder", default="decoder_template.txt", required=False) parser.add_argument("-o", "...
def read_shellcode(input_file) -> bytes: with open(input_file, 'rb') as f: return f.read() def manage_shellcode_encoding(input_file, output_file=None): shellcode = read_shellcode(input_file) encoded_shellcode = encode_shellcode(shellcode) print(f"[+] Encoded shellcode (HEX): {encoded_shellcode...
The main task of the code is to encode shellcode from an input file, optionally saving the encoded result to an output file, and verifying the encoding/decoding process by asserting that decoding the encoded shellcode reconstructs the original input.
def main(): parser = argparse.ArgumentParser() parser.add_argument("-i", "--input", help="File containing shellcode to encode", required=True) parser.add_argument("-o", "--output", help="Store the encoded shellcode in this file", required=False) args = parser.parse_args() input_file = args.input ...
def prepare_profile_data(institution, major, num_people, num_year, visited_names): valid_profiles = [] while len(valid_profiles) < num_people: collect_grad_profile(institution, major, visited_names) profile_data = read_profile_from_file(institution, major, visited_names) for alumni_name ...
The code gathers alumni profiles for specified majors from an institution, aggregates data across multiple majors if provided, and analyzes both current institutional status and historical trends of graduates using the collected profiles.
def analyze_grad_profile(institution, majors, num_people=50, num_year=10): alumni_profiles = [] visited_names = {} for major in majors: alumni_profiles += prepare_profile_data(institution, major, num_people, num_year, visited_names) if len(majors) > 1: major_name = "combined" else: ...
def isValidDate(dateStr): # Maximum possible string: "Sep 2019 - Oct 2021" if len(dateStr) > 19: return False # Given String like "Developed Quickshift, 2008", should return False if not checkIfValidMonth(dateStr): return False found = False for i in range(3,len(dateStr)): ...
The code processes a list of experience entries to extract and structure key details like position, company name, employment dates, location, and additional info. It splits entries to validate and trim dates, merges intervals, and appends tagged data to a new list. If valid intervals exist, it includes dates; for singl...
def add_tag_to_experience_list(curr_experience): new_experience_list = [] timeIntervals = [] for i in range(len(curr_experience)): curr_info = curr_experience[i] time = curr_info.split("·")[0].strip() if isValidDate(time): timeInterval = trim_time(time) timeIn...
def change_major(scraper, major): inputElement = scraper.driver.find_element('id', 'people-search-keywords') for i in major: inputElement.send_keys(i) time.sleep(random.uniform(0.2, 0.5)) inputElement.send_keys('\n') time.sleep(5) def change_num_year(scraper, numYear): currYear = dat...
The code scrapes LinkedIn to find alumni from a specified institution, applying filters for major, graduation year, and number of profiles. It uses a scraper to navigate to a Google search result page, adjusts filters if provided, collects alumni data, and saves results to a file while tracking visited profiles to avoi...
def find_grad_from_institution(institution, major, numYear, numPeople, visited_names): if numPeople == 0: return scraper = LinkedinScraper(True) scraper.start() scraper.driver.maximize_window() query = institution + " alumni linkedin" url = get_links_on_google(query)[0] scraper.drive...
def get_education_without_tags(html): to_ret = [] education_area = False curr_education = [] for line in html: if 'id="education"' in line: education_area = True # if experience_area: # print("Found Education") if education_area: regex_for_indi...
The code extracts education and experience information from HTML content. It first tries to retrieve education data without HTML tags; if empty, it uses a method that includes tags. It performs a similar process for experience, using the same fallback method. The function returns tuples containing the extracted data an...
def parse_background_info(html): education, found_education = get_education_without_tags(html) if len(education) == 0: education = get_education_with_tags(html) experience, found_experience = get_experience_without_tags(html) if len(experience) == 0: experience = get_education_with_tags(...
def Newton_optimize(self, max_iter=50, tol=1e-10): alpha_list = 1 / (4 ** numpy.arange(0, 10)) x = numpy.random.rand(self.dim) for i in range(max_iter): grad = self.grad_full(x) if numpy.linalg.norm(grad) <= tol: break hessian = self.hessian(x...
The code loads and splits a dataset into clusters and devices, computes optimal parameters using Newton optimization, and calculates properties like condition number (kappa) from the Hessian matrix. It stores data splits, optimal weights, and performance metrics for federated learning or distributed optimization tasks.
def load_dataset(self, X_tot, X_test, Y_tot, Y_test): self.X_tot = X_tot self.X_test = X_test self.Y_tot = Y_tot self.Y_test = Y_test _, self.dim = self.X_tot.shape # split data among clusters self.X = self.split_data(self.m, self.X_tot) self.Y = self.spl...
def train(self, instance_list): """Fit parameters for hidden markov model Update codebooks from the given data to be consistent with the probability tables Transition matrix and emission probability matrix will then be populated with the maximum likelihood estimate of...
The function trains a Hidden Markov Model (HMM) using a semi-supervised approach via the Baum-Welch algorithm. It initializes the model with labeled data if provided; otherwise, it sets random initial parameters. The algorithm iteratively enhances the model using unlabeled data by computing forward/backward probabiliti...
def train_semisupervised(self, unlabeled_instance_list, labeled_instance_list=None): """Baum-Welch algorithm for fitting HMM from unlabeled data The algorithm first initializes the model with the labeled data if given. The model is initialized randomly otherwise. Then it runs Baum-Welc...
def acceleration(x1, T1): v1 = velocity(x1, T1) dv1 = v1[1:] - v1[:-1] dT1 = displacement(T1) return dv1 / noDivideByZeroArray(dT1[:len(dv1)]) def displacement(x1): return x1[1:] - x1[:-1] def noDivideByZeroArray(x): res = [] for i in x: res.append(noDivideByZero(i)) return res
This code calculates jerk, the rate of change of acceleration, by dividing the difference in acceleration values (da1) by corresponding time intervals (dT1), using a safety function to prevent division by zero errors.
def jerk(x1, T1): a1 = acceleration(x1, T1) da1 = a1[1:] - a1[:-1] dT1 = displacement(T1) return da1 / noDivideByZeroArray(dT1[:len(da1)])
def get_table_header_items(self, table_header_coord: ItemCoordinate): table_header_items = ( Query(self.pdf_raw_data) .select(lambda x: x) .where( lambda x: ( table_header_coord.y1 <= x.y1 and x.y2 <= table_heade...
This code identifies and collects repeating table headers across multiple PDF pages by matching text content and coordinates. It processes each page to detect header labels, checks for consecutive text matches, calculates header dimensions, and adjusts positions based on mandatory columns. The result is a list of heade...
def repeating_table_headers(self, table_header_coord: ItemCoordinate, column_list, mandatory_column): table_header_items = self.get_table_header_items(table_header_coord) header_label_list = [obj for obj in table_header_items] total_page = self.pdf_page_size() header_coord_list = [] ...
def get_sectors_ascii(filename): content=get_bin_file(filename) hexcontent = binascii.hexlify(content).decode("utf-8") n = 32 chunks = [hexcontent[i:i+n] for i in range(0, len(hexcontent), n)] return chunks def get_uid_from_file(filename): chunks = get_sectors_ascii(filename) return chunks[0...
The function generates signed ASCII data by modifying specific sectors of a file. It retrieves file sectors, extracts a unique identifier (UID), generates keys from the UID, and inserts these keys into predefined sectors (4*i+3) by prepending them to the sector's data. The modified chunks are returned, effectively sign...
def generate_signed_ascii(filename): chunks=get_sectors_ascii(filename) uid=get_uid_from_file(filename) keys=generate_keys(uid) key=0 for i in range(0,16): sector=4*i+3 chunks[sector]=keys[i] + chunks[sector][12:] return chunks
def calculate_left_child_pos(parent_x, parent_y, childDepth): leftChild_x = parent_x - ((window_width - x_padding) / pow(2, childDepth)) / 2 leftChild_y = parent_y + node_radius * 4 return (leftChild_x, leftChild_y) def calculate_right_child_pos(parent_x, parent_y, childDepth): rightChild_x = parent_x +...
This function deletes a node with a specified value from a binary tree, recursively searching left or right based on value comparisons. If the node is found, it handles deletion by either removing a leaf node or replacing it with the minimum/right subtree value or maximum/left subtree value, then updates the tree's gra...
def deleteNode(rootNode, value, rootPositionX, rootPositionY, nodeDepth, canvas, window): if rootNode is None: showinfo(title="Delete", message="Node not found") return None if value < rootNode.value: leftChild_X, leftChild_Y = calculate_left_child_pos(rootPositionX, rootPositionY, node...
def update_vector(self, name): dy, dx = self.compute_dydx(name) self.vectors[name]['y1'] = self.vectors[name]['y0'] + dy self.vectors[name]['x1'] = self.vectors[name]['x0'] + dx def compute_track(self, update_cog = False): dy_co, dx_co = self.compute_dydx("course") dy_cu, dx_cu =...
The function calculates a course vector's angle using trigonometry, aligns it with the current vector's endpoint, updates the course parameters, computes the track, and generates a diagram. It adjusts the course angle based on the current's speed, track angle, and sine relationships to determine the necessary heading f...
def solve_course(self, s, time): #Set the current at the origin of the track vector for dim in ['x0', 'y0']: self.vectors["current"][dim] = self.vectors["track"][dim] self.update_vector('current') #Set the course at the end of the current self.vectors['course'] = {'c'...
def update_vector(self, name): dy, dx = self.compute_dydx(name) self.vectors[name]['y1'] = self.vectors[name]['y0'] + dy self.vectors[name]['x1'] = self.vectors[name]['x0'] + dx def compute_track(self, update_cog = False): dy_co, dx_co = self.compute_dydx("course") dy_cu, dx_cu =...
The code calculates a vessel's track vector using course and current data, updates the current vector's position to the course end, computes the updated track with course over ground (COG), and generates a diagram at the specified time.
def solve_track(self, time): self.vectors['track'] = {'c':0, 's':0, 't':self.vectors['course']['t'], 'x0':self.vectors['course']['x0'], 'y0':self.vectors['course']['y0'], 'x1': -1, 'y1': -1} #Set the current at the end of the course self.vectors["current"]['x0'] = self.vectors["course"]['x1'] ...
def hasPrefix(command): if command.startswith('67'): code['addr_prefix']='67' command = command[2:] if command.startswith('66'): code['oper_prefix']='66' command = command[2:] elif command.startswith('66'): code['oper_prefix']='66' command = comm...
The function parses a hexadecimal string representing x86 machine code instructions, processing prefixes, opcode, mod/RM bytes, SIB, displacement, and immediate data. It sequentially applies parsing steps, returning early if components are absent, and raises an exception if parsing is incomplete, ensuring full disassem...
def Parse(hexString): # sets each field in code dictionary. hexString = hasPrefix(hexString) hexString = hasRex(hexString) hexString = setOpcode(hexString) if hexString=='': #zero arg command or special 1,2 arg and done. return # handels mod/rm, SIB, and disp hexString...
def handleTwoArgsExcep(commandName, arg1, arg2): returnCode = "" # exceptions: # bsr/bsf - imul # xchg (r2a) type_, opcodeKey, D =getOperType(arg1, arg2) if commandName=='bsr' or commandName=='bsf' or commandName=='imul': if type_=='r|r': #r|r -> bsf[r2r]+reg1+reg2 ...
This function processes assembly commands with two operands, determining operand types and generating machine code. It handles special cases like 'bsr', 'imul', and 'xchg' with 'a' in arguments, then selects appropriate opcodes and prefixes. It manages immediate values, memory operands, and register operations, using h...
def handleTwoArgs(assemCommand): returnCode = "" commandName, args = assemCommand.split(" ", 1) arg1, arg2 = args.split(",") if commandName in {'bsr','bsf','imul'} or\ (commandName=='xchg' and (('a' in arg1) or ('a' in arg2))): returnCode = handleTwoArgsExcep(commandName, arg1, arg2) ...
def Parse(hexString): # sets each field in code dictionary. hexString = hasPrefix(hexString) hexString = hasRex(hexString) hexString = setOpcode(hexString) if hexString=='': #zero arg command or special 1,2 arg and done. return # handels mod/rm, SIB, and disp hexString...
The code disassembles a binary input into instructions by parsing it, handling zero-argument commands, converting binary displacement/data fields to reversed hex, and processing one- or two-argument commands via helper functions. It returns parsed instructions or values based on the binary's structure and command type....
def DisAssembler(binary): Parse(binary) #now figure it out! # exceptions: # zero arg commands if code['specialCommand_0arg']!='': return(code['specialCommand_0arg']) if code['disp']!='': # binary disp to reversed hex disp code['disp']=reverseBits(code['disp']).lower(...
def getArgNum(rest): # returns the number of arguments if ' ' not in rest: # no args return 0 elif ',' in rest: # two args return 2 else: # one arg return 1 def handleNoArg(assemCommand): return bin2hex(noArgCommands[assemCommand]) def handleOneArg(as...
The main task of the code is to convert an assembly command into its corresponding binary representation based on the number of arguments it contains. It determines the argument count using `getArgNum`, selects the appropriate handler function (`handleNoArg`, `handleOneArg`, or `handleTwoArgs`), processes the command, ...
def Assembler(assemCommand): # storing the final binary code here commandBin = "" # how many arguments does it have? n_arg = getArgNum(assemCommand) if n_arg == 0: commandBin = handleNoArg(assemCommand) elif n_arg == 1: commandBin = handleOneArg(assemCommand) else: ...
def is_game_over(board): # We go through our groups for group in groups_to_check: # If any of them are empty, they're clearly not a # winning row, so we skip them. if is_group_complete(board, group[0], group[1], group[2]): if are_all_cells_the_same(board, group[0], group[1], group[2]): ret...
The code implements a simple two-player tic-tac-toe game. It initializes a 3x3 board, alternates turns between "X" and "O", takes user input for moves, updates the board, and checks for game end conditions. The loop continues until the game is over, then displays the final board and declares the game ended.
def play_game(): board = [ [".", ".", "."], [".", ".", "."], [".", ".", "."] ] player = "X" while not is_game_over(board): print(print_board(board)) print("It's " + player + "'s turn.") # `input` asks the user to type in a string # We then need to convert it to a number using `int` ...
def is_game_over(board): # We go through our groups for group in groups_to_check: # If any of them are empty, they're clearly not a # winning row, so we skip them. if is_group_complete(board, group[0], group[1], group[2]): if are_all_cells_the_same(board, group[0], group[1], group[2]): ret...
The code implements a tic-tac-toe game where two players take turns entering moves on a 3x3 grid. It initializes the board, alternates between "X" and "O" players, updates the board with each move, and checks for game end conditions until the game concludes, then displays the final board and "Game over!"
def play_game(): board = [ [".", ".", "."], [".", ".", "."], [".", ".", "."] ] player = "X" while not is_game_over(board): print(print_board(board)) print("It's " + player + "'s turn.") # `input` asks the user to type in a string # We then need to convert it to a number using `int` ...
def __get_value_from_row(self, row, index): return row[index].value if row[index].value else None def __add_directors(self, business, book): # Get the director properties and create the directors director_sheet = book.sheet_by_name(SheetName.DIRECTOR.value) iter_director_rows = iter(dire...
This method creates a Business object from a data row by extracting properties like identifier, legal name, dates, and IDs. It saves the business, associates directors, addresses, and filings using helper methods, commits the database transaction, and returns the created business instance.
def __create_business_from_row(self, row, book): # Get the business properties and create the business business = Business(identifier=self.__get_value_from_row(row, 0), legal_name=self.__get_value_from_row(row, 1), legal_type=self.__get_value_from_...
def load_snapshot(ckpt, session=None, var_list=None, reshape=False): session = session or tf.get_default_session() reader = pywrap_tensorflow.NewCheckpointReader(ckpt) vs = var_list or tf.trainable_variables() for variables in tqdm.tqdm(list(split_by_params(vs))): values = [ value ...
The main task of the code is to restore model parameters from a saved checkpoint by detecting the file format (e.g., .ckpt, .hdf5, .npy) and using the corresponding loader function (load_snapshot, load_variables, or load_weights) to restore the model's variables in a TensorFlow session.
def restore(self, sess, save_path): if save_path.endswith(".ckpt") or os.path.isfile( save_path + ".data-00000-of-00001" ): load_snapshot( save_path, session=sess, var_list=self.var_list, reshape=self.reshape, ...
def main(): while True: clock.tick(144) # set fps to 144 for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if pygame.mouse.get_pressed()[0]: # clicked left mouse button pos = pygame.mouse....
The code implements a lobby menu for a multiplayer game, handling UI elements like a "Ready?" button to signal player readiness, displaying connected clients, and updating the lobby interface. It uses Pygame for rendering, checks for user input, manages network communication via a 'network.send' call, and maintains the...
def lobby_menu(): global client, connected_clients, lobby_id start_new_thread(receive_data, ()) ready_button = Button((92, 184, 92), 200, 255 + 8 * 31, 400, 55, text='Ready?') while True: screen.fill((36, 81, 149)) if client.lobby_leader: pygame.display.set_caption(f'PixelDra...
def lobby_menu(): global client, connected_clients, lobby_id start_new_thread(receive_data, ()) ready_button = Button((92, 184, 92), 200, 255 + 8 * 31, 400, 55, text='Ready?') while True: screen.fill((36, 81, 149)) if client.lobby_leader: pygame.display.set_caption(f'PixelDra...
The main task of the code is to present a multiplayer game menu where users input their username and optionally a lobby key to join or create a private lobby. It handles keyboard/mouse input, displays interactive buttons, manages network connections, and transitions to the lobby menu upon successful connection, while r...
def main_menu(): global client, connected_clients, lobby_id username = '' lobby_key = '' hint_text = 'Enter your name here' input_rect = pygame.Rect(200, 200, 400, 44) key_hint_text = 'Enter key to join a private lobby' key_input_rect = pygame.Rect(200, 270, 400, 44) key_input_selected =...
def calculateDistance(rocket,initialVelocity=0,time=0): a=calculateAcceleration(rocket) vi=initialVelocity*time t2 = time*time return vi+(1/2*a*t2) def calculateFinalVelocity(rocket, vi=0,t=1): vf = vi+calculateAcceleration(rocket)*t return vf def calculateFuel(rocket): return rocket["fuel...
The code calculates the total distance a rocket travels while its fuel is positive. It iteratively adds the distance from each time step, updates the rocket's velocity, and reduces fuel until exhaustion, returning the cumulative distance.
def sumDistance(rocket): sum=0 vi=0 while rocket["fuel"] >0: sum = sum+calculateDistance(rocket,vi,1) vi=calculateFinalVelocity(rocket, vi) rocket["fuel"]=calculateFuel(rocket) return sum
def pickAttackTo(country,player): return eval("P"+str(player)).attackToCountry(player,countryD,bookArmiesBonusList,{player:playerD[player]},country) def rollDice(dT,attackingPlayer,attackFrom,defendingPlayer,attackTo): attackNumDice=3 if countryD[attackFrom]["armies"]==3: attackNumDice=2 elif co...
This function simulates a turn-based attack in a board game, allowing a player to attack neighboring countries using dice rolls. It manages battle outcomes, army movements, and captures territories. If a country is captured, it updates army counts, transfers cards from the defender, and places new armies. The function ...
def attackNeighboringCountry(t,player): dT=cTurtle.Turtle() dT.ht() countryCaptured=False #attackFrom=playerModuleNames[player-1].attackFromCountry(player,countryD,bookArmiesBonusList,{player:playerD[player]}) attackFrom=eval("P"+str(player)).attackFromCountry(player,countryD,bookArmiesBonusList,{pl...
def _onehot(self,y,n_classes): """ Encode labels into one-hot representation Parameters ---------- y : array, shape =[n_examples] Target values. Returns ------- onehot ; array , shape = [n_eaxmples,n_labels]. """ one...
The code trains a neural network using gradient descent with backpropagation, initializing weights, processing mini-batches, updating weights via regularization, and tracking training/validation accuracy and cost per epoch. It returns the trained model instance.
def fit(self, X_train,y_train,X_valid,y_valid): """ Learn weights from training data. Parameters ---------- X_train : array, t shape =[n_examples, n_features] input layer with original features. y_train : array, shape =[n_examples] Target class la...
def _create_placeholders(self): with tf.name_scope("input_data"): self.user_input = tf.placeholder(tf.int32, shape = [None,], name = "user_input") self.item_input = tf.placeholder(tf.int32, shape = [None,], name = "item_input_pos") self.item_input_recent = tf.placeholder(tf.i...
The code defines a method `build_graph` that constructs a computational graph for a machine learning model. It sequentially creates placeholders for input data, variables for model parameters, a loss function to optimize, and an optimizer to update the variables during training. This setup forms the foundational struct...
def build_graph(self): self._create_placeholders() self._create_variables() self._create_loss() self._create_optimizer()
def check_squareness(A): """ Makes sure that a matrix is square :param A: The matrix to be checked. """ if len(A) != len(A[0]): raise ArithmeticError("Matrix must be square to inverse.") def check_non_singular(A): det = determinant(A) if det != 0: ...
The function `invert_matrix` computes the inverse of a square, non-singular matrix using Gaussian elimination. It performs row operations to transform the input matrix into the identity matrix while applying the same operations to an identity matrix, resulting in the inverse. The process involves scaling rows, eliminat...
def invert_matrix(A, tol=None): """ Returns the inverse of the passed in matrix. :param A: The matrix to be inversed :return: The inverse of the matrix A """ # Section 1: Make sure A can be inverted. check_squareness(A) check_non_singular...
def write_env_file(self, name, model='kraken', zr_flag=True, zr_range_flag=True,beam=None, custom_r=None,append=False,sigma=None): """ Input name : string Full path of save location for env file model : string which model to use ('kraken', 'bellhop') zr_f...
The function `run_model` simulates acoustic field propagation using specified models (e.g., Kraken, Bellhop), generating environment files, executing model-specific binaries, and reading output data to compute the complex pressure field (`x`) and receiver positions (`pos`). It handles model configuration, mode computat...
def run_model(self, model, dir_name, name, beam=None,zr_flag=True,zr_range_flag=True, custom_r=None, tilt_angle=0,normal_krak=False,precomputed_modes=False,point_source=True,beam_pattern=None,vand=True): """ Inputs model - string dir_name - string Folder in which to store the...
def v1_endpoints(self): return ['rules', 'schedules', 'sensors', 'resourcelinks'] def post_v1(self, endpoint, payload): url = f"https://{self.bridge_ip}/api/{self.bridge_user}/{endpoint}" try: r = requests.post( url, headers=self.headers, ...
This code defines a `post` method that routes a POST request to either `post_v1` or `post_v2` based on whether the given `endpoint` exists in the list of v1 endpoints. If the endpoint is in the v1 list, it uses `post_v1`; otherwise, it uses `post_v2`. The method ensures proper handling of different API versions by dyna...
def post(self, endpoint, payload): return self.post_v1(endpoint, payload) \ if endpoint in self.v1_endpoints() \ else self.post_v2(endpoint, payload)
def get_settings(): if not LightsSettings.objects.all().exists(): LightsSettings().save() return LightsSettings.objects.all().first() def _get_scenes_for_room(self): r = self.bridge.search('scene') if not r['success']: self._failure( 'getting existing scenes f...
This code initializes a class to manage smart home devices in a room, configuring settings, bridges, and device data. It extracts room details, scenes, lights, switches, sensors, and buttons, while setting up scene names, button actions, and device suffixes for handling multiple devices. The instance prepares to contro...
def __init__(self, request, room, devices): self.s = get_settings().__dict__ self.bridge = Bridge(self.s) self.request = request self.room = room self.room_name = room['metadata']['name'] self.room_name_min = self.room_name.replace(' ', '') self.scenes = self._ge...
def _get_resourcelink(self, type): r = self.bridge.search('resourcelinks') if not r['success']: self._failure( 'getting Resource Links', r['errors'] ) name = f"{self.room_name_min}{type}" if name in [x['name'] for x in r['records']....
This function removes switch configurations associated with a room. It first attempts to locate a 'Switches' resource, then a 'Switch' resource if the former fails. If neither is found, it warns the user about missing configurations. If found, it deletes the records and returns a success message.
def remove_switch_configuration(self): self.pluralise = 'Switch Configuration' config = self._get_resourcelink('Switches') if not config: config = self._get_resourcelink('Switch') if not config: message = ( "I couldn't find a switch con...
def _get_resourcelink(self, type): r = self.bridge.search('resourcelinks') if not r['success']: self._failure( 'getting Resource Links', r['errors'] ) name = f"{self.room_name_min}{type}" if name in [x['name'] for x in r['records']....
This method removes a sensor configuration by locating the appropriate resource link (either 'Sensors' or 'Sensor'), deleting associated records if found, and displaying a warning if no configuration exists for the specified room. It ensures cleanup of sensor-related data and provides feedback on success or absence of ...
def remove_sensor_configuration(self): self.pluralise = 'Sensor Configuration' config = self._get_resourcelink('Sensors') if not config: config = self._get_resourcelink('Sensor') if not config: message = ( "I couldn't find a sensor conf...
def payload__scene(self, scene_name, lamps_only): action_template = { 'target': {'rid': None, 'rtype': 'light'}, 'action': { 'on': {'on': True}, 'dimming': { 'brightness': self.s[f"{scene_name.lower()}_brightness"] }, ...
The code creates daily scenes and associated transition rules for a smart home system. It checks for existing scenes and rules, generates scene names (including lamp-specific variants), and posts new scenes/rules via a bridge API if they don't already exist. The task ensures automated lighting configurations are set up...
def create_daily_scenes(self): self.pluralise = 'Daily Scenes' r = self.bridge.search('rules') if not r['success']: self.failure('getting rule data', r['errors']) rule_names = [x['name'] for x in r['records'].values()] # Create Scenes for time_of_day in self....
def get_token(): headers = { 'Host': 'login.microsoftonline.com', 'Content-Type': 'application/x-www-form-urlencoded' } body = { 'client_id': client_id, 'scope': 'https://graph.microsoft.com/.default', 'client_secret': client_secret, 'grant_type': 'client_cre...
The code's main task is to interact with SharePoint by parsing a subfolder path, retrieving access tokens and drive IDs, listing drive items either from the root or a specified subfolder path, and cleaning up temporary directories. It uses command-line arguments for flexibility and handles both root and subfolder listi...
def main(): parser = argparse.ArgumentParser(description='Demo for Sharepoint.') parser.add_argument('subfolder', nargs='?', type=str, default='', help="Prefix e.g.(folder1/folder2)") args = parser.parse_args() subfolder = args.subfolder access_token = get_token() access...
def get_token(): headers = { 'Host': 'login.microsoftonline.com', 'Content-Type': 'application/x-www-form-urlencoded' } body = { 'client_id': client_id, 'scope': 'https://graph.microsoft.com/.default', 'client_secret': client_secret, 'grant_type': 'client_cre...
(The code interacts with OneDrive to list files/folders, either from the root or a specified subfolder, using an access token for authentication, and removes temporary directories afterward.)
def main(): parser = argparse.ArgumentParser(description='Demo for OneDrive.') parser.add_argument('subfolder', nargs='?', type=str, default='', help="Prefix e.g.(folder1/folder2)") args = parser.parse_args() subfolder = args.subfolder relative_path = subfolder access_tok...
def perturbWeight(self): # generate a single perturbation of the current statWeights learnRate = self.hyperParams['learnRate'] retWeights = [] for statCat in self._statWeights: curArr = [] for idx in range(len(statCat)): delta = 2 * (np.random.rand...
This method evaluates multiple perturbed stat weight configurations by comparing their performance against each other using pairwise scoring. It iterates through all combinations of generated pick weights, calculates a score for each matchup, and selects the configuration with the highest score as the new stat weight, ...
def singleIteration(self): # This method under construction # todo: make sure it takes into account multiple stats statWeightsLoc = [] # new stat weights to evaluate pickWeightsLoc = [] # new player pick weights to evaluate idxMax = self.hyperParams['perturbs'] for idx in...
def selected(self, row, col) -> bool: if self.selected_piece: result = self.if_moved(row, col) if not result: self.selected_piece = None self.selected(row, col) piece = self.board.flat[row][col] if piece != 0 and piece.color == self.playe...
This function randomly selects a gray piece with available moves on the board, triggers its movement to the first valid position, and checks for a tie. It iterates through the board, applies random volatility, and performs actions based on piece properties and move availability.
def random_movement(self) -> None: for row in range(ROWS): for col in range(COLS): if random.choice(volatility): p = self.board.flat[row][col] if isinstance(p, Piece) and p.color == GRAY and (self.board.get_available_moves(p) != {}): ...
def random_movement(self) -> None: for row in range(ROWS): for col in range(COLS): if random.choice(volatility): p = self.board.flat[row][col] if isinstance(p, Piece) and p.color == GRAY and (self.board.get_available_moves(p) != {}): ...
The code updates the game state by drawing the board setup, handling a player's random move if the player is GRAY, checking for a tie, resetting the game if tied, and rendering available moves.
def update(self) -> None: self.board.draw_setup() if self.player == GRAY: tie_game = self.random_movement() if tie_game: print("No Game Winner! Tie Game") self.reset(self.window) self.draw_available_moves(self.available_moves)
def generate_bit_mask(self, b): """Generate a bit mask of b bits to truncate a digest. Args: b: number of bits to make the mask Returns: an integer that represents the bit mask. """ return int('1' * b, 2) def get_truncated_sha1_hash(self, s): """Generate a...
The code initializes an object to process a user-provided string using a bitmask of specified size. It computes a truncated SHA-1 hash of the string, generates a bitmask, and triggers an experiment. The main task involves setting up cryptographic hashing and bitmasking parameters for further processing or analysis in t...
def __init__(self, user_string, bit_mask_size): self.original_string = user_string self.bit_count = bit_mask_size self.bit_mask = self.generate_bit_mask(bit_mask_size) self.original_string_truncated_hash = self.get_truncated_sha1_hash(self.original_string) self.run_experiment()
def removeExtraSpaces(self, text): # remove multible spaces text = re.sub(' +', ' ', text) # remove spaces at the end and start of string text = re.sub(r'\A +| +$', '', text) return text def getInQuotation(self, text): """ return sentence in quotations if there ar...
The code extracts key elements from a question to aid search queries by identifying quoted text, named entities, titles, and noun phrases, combining them into a list of unique, relevant components for improved search accuracy.
def __call__(self, question : str): """ Extract everything helpful for search queries """ question = self.removeExtraSpaces(question) doc = self.nlp(question) important_stuff = [] inQuot = self.getInQuotation(question) important_stuff.extend(inQuot) ...
def handle_events(self): """ Handle pygame events. Closes the program when the window is closed """ for event in pygame.event.get(): if event.type == pygame.QUIT: self.active = False def update_animations(self): """ Depending on the current ste...
This method updates the game state each frame by handling events, updating animations, drawing game elements, and refreshing the display using Pygame.
def update(self): """ Called each frame, updates the game state. """ self.handle_events() self.update_animations() self.draw() # Update the window pygame.display.update()