dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def set_up_sockets(visualization_address): context = zmq.Context() notification_port = 8000 notification_socket = context.socket(zmq.PUB) notification_socket.bind(f"tcp://{visualization_address}:{notification_port}") context = zmq.Context() drone_requester_port = 9000 drone_requester_socket...
The code sets up and runs a visualization test for a drone simulation. It initializes communication sockets, configures a visualization module, and continuously sends drone status updates and notifications using a state generator. The loop runs indefinitely, updating the simulation state at fixed intervals to mimic rea...
def perform_visualization_tests(java_home, visualization_dir, visualization_binary, assets_checksum, state_generator): visualization_address = "127.0.0.1" drone_requester_socket, drone_status_socket, drone_steering_socket, drone_utils_socket, notification_socket = set_up_sockets(visualization_address) set_...
def date_to_datetime(t) -> datetime: return _combine_date_time(t, time(0, 0, 0)) def time_to_datetime(t) -> datetime: return _combine_date_time(date.today(), t) def timestamp_to_datetime(ts): return datetime.fromtimestamp(ts) def string_to_data_time(d): if d: d = d.replace('/', '-') ...
This function converts various input types (datetime, date, time, numeric timestamps, strings) into a standardized datetime object by applying type-specific parsing methods, returning None if the input type is unsupported.
def parse(input) -> datetime: ''' parse input to datetime ''' if isinstance(input, datetime): return input if isinstance(input, date): return date_to_datetime(input) if isinstance(input, time): return time_to_datetime(input) if isinstance(input, (in...
def get_board_size(self, board_selection): if board_selection == "9x9": return 9 elif board_selection == "13x13": return 13 return 19 def get_bot(self, bot_selection): if bot_selection == 'Random': return agent.naive.RandomBot() return agent.na...
The main task of the code is to initialize and start a game by retrieving user-selected parameters (board size, player types), instantiating corresponding game bots, creating a new game state, and initiating the game with a move. It prepares the game environment and triggers the first move using the configured bots for...
def start_game(self, board_size_selector, player_one_selector, player_two_selector): #getting selections for game board_size = self.get_board_size(board_size_selector.get()) player_one_selection = player_one_selector.get() player_one_bot = self.get_bot(player_one_selection) playe...
def get_row_col_from_coords(x: int, y: int) -> tuple[int, int]: row = y // (CIRCLE_SIZE + GAP) col = x // (CIRCLE_SIZE + GAP) row = row if row < BOARD_SIZE else BOARD_SIZE - 1 col = col if col < BOARD_SIZE else BOARD_SIZE - 1 return row, col def check_valid_move(self, x: int, y: int) -> bool: ...
The code handles a click event on a grid by converting coordinates to a row/column, validating the move, marking the player's symbol, checking for completed vertical, horizontal, and diagonal lines, updating scores accordingly, switching players, and determining the game outcome if the board is full.
def handle_click(self, x: int, y: int) -> None: row, col = get_row_col_from_coords(x, y) if not self.check_valid_move(x, y): return self.mark_circle(row, col) if self.vertical_check(col): if self.current_player == 1: self.p1_score += np.count_non...
def prepare_input(self, image, ml_frame_data: ml_metadata.MLFrameData): self.img_height, self.img_width = image.shape[:2] input_img = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) # Resize input image start = time.perf_counter() input_img = cv2.resize(input_img, (self.input_width, sel...
This code performs object detection on an input image using a machine learning model. It prepares the input tensor, executes inference, processes the output to extract bounding boxes, confidence scores, and class IDs, then returns these detection results.
def detect_objects(self, image, ml_frame_data: ml_metadata.MLFrameData): input_tensor = self.prepare_input(image, ml_frame_data) # Perform inference on the image outputs = self.inference(input_tensor, ml_frame_data) self.boxes, self.scores, self.class_ids = self.process_output(outputs,...
def current_cards(self): return self.state.get(self.current_player) def place_card(self, wildcard=False): # sends card if is_card(self.current_cards(), self.field) and not wildcard: if self.current_player.type == 'bot': self.send(bot_play(self.current_cards(), self.fi...
The code handles card drawing, wildcard placement, and game state updates. It draws cards if `draw_damage` is non-zero, processes wildcards by placing them or selecting colors (bot/human), resets `wildcard`, triggers draw penalties if a wild card is placed, checks for an empty deck, and initiates a new turn.
def play(self): # process draw if self.draw_damage != 0: for cards in range(self.draw_damage): self.current_cards().append(self.deck.draw()) self.draw_damage = 0 # process wild card if self.wildcard != '': self.place_card(wildcard=T...
def get_run_path(dataset_name:str) -> Path: """Get the path to the results of a given experiment. Parameters ---------- dataset_name : str The name of the dataset, adni, mimic or simulation Returns ------- Path The path to the results of the experiment """ return ST...
The main task of the code is to evaluate a machine learning model's performance across 10 bootstrap runs on a specified dataset. It loads the model, processes test data using dataset-specific parameters, computes metrics (AUROC, AUPRC, Brier, F1), and formats the aggregated results into a string for reporting.
def get_test_results(dataset:str, exp_name:str, model_name:str): """_summary_ Parameters ---------- dataset : str _description_ exp_name : str _description_ model_name : str _description_ """ p = get_run_path(exp_name) / model_name aurocs, auprcs, briers, f1...
def enter_and_trim_rfid_df(RFID_filepath, RFID_filename): #enter, compress column names, sort and remove duplicates from RFID spreadsheet rfid_pathname = RFID_filepath + RFID_filename + '.xlsx' #combine file path and file name for RFID spreadsheet rfid_df = pd.read_excel(rfid_pathname) #read in RFID spreadsheet...
This function cross-references BORIS behavioral data with RFID tag records by matching RFID tags to BORIS events, calculating timestamps, and outputting an updated BORIS spreadsheet with RFID data. It processes RFID data, filters out 'Fish 1' entries, iterates through BORIS events to assign RFID tags and timestamps, th...
def BORIS_RFID_crosscheck_inner(boris_filename, boris_filepath, boris_date, boris_video_length, RFID_filepath, RFID_filename, output_filepath): rfid_df = enter_and_trim_rfid_df(RFID_filepath, RFID_filename) #enter, compress column names, sort and remove duplicates from RFID spreadsheet boris_video_start_time, b...
def import_gpg_private_key(gpg_private_key, passphrase): """ Import PGP key into the the local keyring """ gpg = gnupg.GPG(gnupghome='/root/.gnupg', verbose=False, use_agent=True) import_result = gpg.import_keys(gpg_private_key, passphrase=passphrase) fingerprint = import_result.fingerprints[0]...
The main task of the code is to create a signed Git commit in a repository using a GPG private key. It generates a timestamp file, configures Git user details from the GPG key, and commits the file with a signed commit message containing the current datetime. The process involves importing the GPG key, setting up the r...
def main(gpg_private_key, passphrase, repo_dir): repo = Repo(repo_dir) # Create new file to commit file_repo_path = "data/example-03/latest_datetime.txt" file_absolute_path = repo_dir + '/' + file_repo_path print(f'Creating file: {file_absolute_path}') os.makedirs(os.path.dirname(file_absolute...
def app_add(client, headers): try: num_of_bytes = headers["content-length"] except KeyError as e: return RESPONSE_400 arguments = client.read(int(num_of_bytes)).strip() arguments = unquote_plus(arguments.decode("utf-8"), "utf-8") first_last = parse_arguments(arguments) if len(fi...
This function parses a URL to determine the appropriate HTTP response. It handles virtual endpoints (VIRTUAL_ADD, VIRTUAL_READ, VIRTUAL_JSON) with method checks, delegating to app_add, app_read, or app_json. For regular URLs, it serves files from a directory (WWW_DATA), checking if the path is a directory (returning a ...
def parse_url(uri, headers, client, method): body = "" if uri == VIRTUAL_ADD: if method != "POST": return RESPONSE_405 head, body = app_add(client, headers) return head, body elif uri.startswith(VIRTUAL_READ): if method != "GET": return RESPONSE_405 ...
def choice_generate_key(): global is_generator global key_generated print("Okay, we will generate a key for you. Please be careful not to share your key!") print("Before we generate your key, pick a name for your key") while True: key_path = input("Please enter a file name for your key (we w...
The main task of the code is to present an AES algorithm interface with a menu allowing users to generate encryption keys, encrypt/decrypt files, or exit. It uses a loop to repeatedly display options, handle user input, and call corresponding functions for key generation, encryption, decryption, or returning to a previ...
def main(): print( figlet_format('AES', font="starwars")) while True: print("---------------------------------------------------------------") print("Welcome to our AES Algorithm, let us help you: ") print("Enter '1' if you want to generate key between you and your friend: ") pri...
def clean_tracking(self): self.pt=np.zeros((3,)) self.boarders=np.zeros((2,3)) self.next_pt=np.zeros((3,)) self.next_box=np.zeros((3,)) self.norm_vec=np.zeros((3,)) self.direction=np.zeros((3,)) self.points=[] self.refinement_pts=[]# collects points over ...
The main task of the code is to track a path through a hierarchical spatial structure starting from a given point `pt` and direction `norm`. It iteratively refines the path by checking if the current box is refined, calling lower hierarchy levels to track sub-voxels, and collecting all points along the trajectory withi...
def track(self,pt,norm): ## pt norm is passed through hirachy print("calculate track pt:",pt," direction: ",norm) self.clean_tracking() self.SetStartPt(pt,norm) # set next_pt to start i.e. pt self.next_box=self.GetIndex(pt) ## initialsing #self.print_info("start box: "+str(self....
def solve_deadlock(self): """ Detect global deadlock and solve by aborting youngest transaction :return: True means deadlock detected, a transaction is aborted. False means no deadlock and no action happened. """ # check whether we can start from node and return to same node ...
The main task of the code is to parse an input line into command and parameters, resolve potential deadlocks by re-executing operations until the graph has no cycles, process the parsed command with its parameters, execute operations, and increment a timestamp. It ensures deadlock-free execution by iteratively solving ...
def process_line(self, line: str): """ Parse a line and pass all paras to process_command :param line: a line from input file """ paras = re.findall(r"[\w']+", line) # print(paras) command = paras.pop(0) # if there is deadlock detected, we will execute op...
def initialize(): keys = random.sample(list(solution_dict), popsize) values = [solution_dict[k] for k in keys] population.append(dict(zip(keys, values))) def crossover_new(): # print("init:",population) p1,p2 = tournament(3) # print("test",p1,p2); set_a = [] set_b = [] all_common=[] ...
This code implements a genetic algorithm (GA) to optimize a population of binary strings. It iterates over generations, performing crossover to generate new individuals, trimming the population, and evaluating fitness based on the count of '1's. The algorithm tracks the best individual (most_fit) and prints the best so...
def GA(): length = 27 ones_count = 6 initialize() for j in range(generations): for i in range(popsize): crossover_new() trimpop() genfitness = fit_eval(population) # print("generation ", j+1, "fitnesses:") # print("Individual\t\tFitness") # for...
def initialize(): #Creates the initial population, a list of lists containing numbers 1-6 in random order for j in range (popsize): #changed range from 1,7,6 to 1,10,9 population.append(random.sample(range(1,10),9)) print("pop:",population) def crossover(): #Executes a two-point crossover from t...
The code implements a genetic algorithm (GA) to evolve a population of individuals over multiple generations. It initializes the population, iterates through generations, applies crossover to each individual, trims the population, evaluates fitness, and tracks the most fit individual. The process repeats until the spec...
def GA(): initialize() for j in range(generations): for i in range(popsize): crossover() trimpop() genfitness = fit_eval(population) #print("generation ", j+1, "fitnesses:") #print("Individual\t\tFitness") #for k in genfitness: # print("{}\...
def initialize(): #Creates the initial population, a list of lists containing numbers 1-6 in random order for j in range (popsize): #changed range from 1,7,6 to 1,10,9 population.append(random.sample(range(1,10),9)) def crossover(): #Executes a two-point crossover from two parents who are winners of...
The code implements a genetic algorithm (GA) to evolve a population over multiple generations. It initializes a population, iterates through generations, performs crossover on individuals, trims the population, evaluates fitness, and identifies the most fit individual. The process repeats for a specified number of gene...
def GA(): initialize() for j in range(generations): for i in range(popsize): crossover() trimpop() genfitness = fit_eval(population) # print("generation ", j+1, "fitnesses:") # print("Individual\t\tFitness") # for k in genfitness: # print("{...
def preprocess_text(text): """ Preprocess a string to be presented to the user. Args: text (str): The text to preprocess. Returns: (str, list) The preprocessed text, and the list of chemical entities. """ for tok in ("<inf>", "</inf>", "<sup>", "</sup>", "<hi>", "</hi>", "<sub>...
The code annotates a document's title and abstract for doping-related information, processing each sentence to extract entities like base materials, dopants, and results. It checks if sentences follow a "paradigm" pattern, prompting user input for unclear cases. The output is a dictionary with annotated sentences, incl...
def annotate_doping_basic(doc): """ Do a basic annotation of an abstract (or document)/ Doc must have the following fields: - 'abstract' - 'doi' - 'title' Args: doc (dict): The document to annotate. Must have abstract, doi, and title fields. Returns: extracted (dict)...
def detect_var_definition(string): equal_operator_position = string.find('=') if equal_operator_position == -1: var_name = None else: var_name = string[:equal_operator_position] string = string[equal_operator_position + 1:] return var_name, string def validate_syntax(string): ...
This code evaluates a mathematical expression string by removing spaces, detecting variable definitions, validating syntax, handling negative numbers, solving parentheses, computing the result, and storing it in a global dictionary if a variable name is present. It returns the computed result.
def compile(string): string = string.replace(' ', '') var_name, string = detect_var_definition(string) validate_syntax(string) string = handle_negative_numbers(string) string = solve_parenthesis(string) result = compute_string(string) if var_name is not None: VARS[var_name] = result...
def live(self): self.image_char = PhotoImage(file = "images/background_live.png") self.char_lbl=Label(self, image = self.image_char) self.char_lbl.x = self.image_char self.char_lbl.place(x=0, y=0) self.destroy_battle_widgets() self.fought.config(text = f"You fought the ...
This code simulates a battle mechanic where a character's survival depends on a calculated percentage (based on health and party size) versus a random chance. If the chance is within the calculated percentage, the fight count increases, triggering 'survive()' or 'live()' after 12 attempts. Otherwise, 'die_battle()' is ...
def fight(self): print("fight started") chance=random.randint(0,100) self.fought=Label(self,text="") self.fought.grid(row=1,column=0) self.percentage = self.health*(1+(self.partymembers-1)/self.partymembers) if self.percentage>100: self.percentage = 100 ...
def getServices(self, ignore=["frontend", "frontendexternal", "apacheservice"]): # deploys = self.getDeploy() services = [] mirrored_services = [] kubectl = client.CoreV1Api() try: response = kubectl.list_namespaced_service( namespace=self.namespace, ...
The main task of the code is to update service traffic splits by checking if services are deployed and if their splits are valid. If a service is not deployed and lacks a valid split, it triggers a split operation to divide the service into one part, ensuring proper traffic distribution and deployment readiness.
def updateSplits(self): services, _ = self.getServices() ts = self.getTrafficSplits() deploys = self.getDeploy() for svc in services: if svc not in deploys: if not self.checkSplit(svc): self.splitService(svc, 1)
def train_one_episode(self): """ Train one episode. """ # initialize recordins actions = [] values = [] log_probs = [] entropies = [] rewards = [] reward_predictions = [] states = [] state_predictions = [] ...
The main task of the code is to train a reinforcement learning model over a specified number of episodes. It records metrics like episode reward, losses (policy, value, entropy, prediction), and episode length during training. The function periodically prints training progress, updates learning rates via a schedule if ...
def learn(self, num_episodes, print_frequency = 2): """ Train the model. """ # initialize recordings data = { 'episode_length': [], 'episode_reward': [], 'loss': [], 'policy_loss': [], 'value_loss': [], 'ent...
def cut_data(data, sr): if data.shape[0] > sr: data = data[:sr] elif data.shape[0] < sr: need_len = sr - data.shape[0] add_len = need_len // 2 data = np.concatenate([add_len * [0], data, (need_len - add_len) * [0]]) return data def make_aug(wav_data, sr, background_folder, no...
The function `make_batch` generates a batch of audio data for machine learning training. It samples audio files from a DataFrame, loads and processes each audio clip (cutting, augmenting with noise/background sounds), converts them to MFCC features (using librosa or tensorflow), and pairs them with one-hot encoded labe...
def make_batch(df, lb, background_folder, noise_to_data, batch_size, sr, p_aug, mfcc_type): words = df.sample(n=batch_size) X = [] for word_path in words['path']: data, _ = librosa.load(word_path, sr=sr) data = cut_data(data, sr) data = np.expand_dims(data, 0) data = make_aug...
def generate_variables() -> list: variables = [] for i, row in enumerate(grid): for j, value in enumerate(row): variables.append(Variable(i, j, [x for x in range(1, len(grid) + 1)] if value == 0 else [value], None)) return variables def ac3(variables: list) -> bool: # Create a queue ...
The code solves a constraint satisfaction problem (e.g., Sudoku) using the AC3 algorithm for consistency checking and backtracking search. It initializes the grid, generates variables, applies AC3 to enforce constraints, and performs backtracking to find a valid solution. If unsolvable, it returns `None`; otherwise, up...
def solver(board: list[list]) -> list[list]: global grid grid = board # return grid variables = generate_variables() if not ac3(variables): return None result = backtrack(variables) if not result: return None for i in variables: grid[i.row][i.column] = i.value ...
def check_cell_row(self) -> None: """Check the cells within the row.""" self._counter_col += 1 if self._counter_col >= 9: self._counter_col = -1 self._checking = "COL" logging.info('check row %i,%i', self._check_cell_row, self._counter_col) if self._check_...
The main task of the code is to check the completeness of a grid cell, row, column, or subgrid in a structured sequence. It evaluates the current state, transitions between checking modes ("ROW", "COL", "SUB"), and returns True if the check is completed, or False otherwise, while managing internal counters and renderin...
def check_cell(self) -> bool: """Based on the current _checking state, check the required area of the grid.""" logging.info('check cell %i,%i', self._check_cell_row, self._check_cell_col) if not self._grid.is_complete_cell(self._check_cell_row, self._check_cell_col): return True ...
def draw_cells(self) -> None: """Draw all the cells.""" for row in range(0, 9): for col in range(0, 9): self.draw_cell(row, col) def draw_lines(self) -> None: """Draw the grid lines.""" right = (CELL_WIDTH*9*3)+(8*CELL_THICKNESS)+(2*(GRID_THICKNESS-CELL_THICKN...
The main task of the code is to render the game's visual state by clearing the screen, drawing grid cells, lines, numbers, checking indicators, and selected cell highlights, then updating the display with Pygame. It orchestrates the rendering of all game elements to reflect the current state for real-time visualization...
def on_render(self) -> None: """Render the game.""" self._display_surf.fill(COL_WHITE) self.draw_cells() self.draw_lines() self.draw_checking() self.draw_numbers() self.draw_checking_area() self.draw_selected_cell() pygame.display.update()
def on_init(self) -> bool: """Initialise solver.""" pygame.init() pygame.display.set_caption("Sudoku") self._display_surf = pygame.display.set_mode(self._size, pygame.HWSURFACE | pygame.DOUBLEBUF) self._running = True #...
The code defines the main game loop, initializing the application, processing events, updating game logic with elapsed time, rendering frames, and cleaning up resources when the loop ends. It maintains the game state by iterating until `_running` is False, ensuring continuous execution of event handling, game updates, ...
def on_execute(self) -> None: """Execute application.""" if not self.on_init(): self._running = False while self._running: current = time.time() elapsed = current - self._time self._time = current for event in pygame.event.get(): ...
def advance(self) -> Token: self.tok_idx += 1 if self.tok_idx < len(self.tokens): self.cur_tok = self.tokens[self.tok_idx] return self.cur_tok def power(self) -> BinOpNode: return self.bin_op(self.atom, (TT_POW,), self.factor)
This code parses unary operations (+, -) in an expression, creating a UnaryOpNode with the operator and the result of recursively parsing the subsequent factor. If no unary operator is found, it delegates to the power() method for further parsing.
def factor(self) -> NumberNode: res = ParserResult() tok = self.cur_tok if tok.type in (TT_PLUS, TT_MINUS): res.register_advancement() self.advance() factor = res.register(self.factor()) if res.error: return res return...
def pull_and_set_message_ids(self, max_results=5): self.message_ids = [] result = self.service.users().messages().list(userId='me', maxResults=max_results).execute() messages = result.get('messages') for message in messages: if message.get("id"): self.message_...
This function repeatedly checks an email inbox for a user response matching specified criteria, retrying up to a set number of times with intervals between attempts. It pulls message data, searches for a response, and returns it if found, otherwise returns None after exhausting retries.
def poll_email_and_get_response_from_user(self, items_to_match, inbox="INBOX", users=[], retry_count=20, seconds_between_retries=10, max_results=1): tries = 0 user_response = None while not user_response and tries < retry_count: print("Polling email. Try #:{}".f...
def _under_prefix(location): if 'install' not in sys.argv: return True args = sys.argv[sys.argv.index('install')+1:] for index, arg in enumerate(args): for option in ('--root', '--prefix'): if arg.startswith('%s=' % option): top_dir = arg.split('root=')[-1] ...
The code detects the presence of the 'setuptools' package, checks its installation location and type (egg or flat), and applies a patch by replacing it with a modified version if it hasn't been patched already. It skips patching if setuptools is outside a specified directory prefix or if the existing installation is al...
def _fake_setuptools(): log.warn('Scanning installed packages') try: import pkg_resources except ImportError: # we're cool log.warn('Setuptools or Distribute does not seem to be installed.') return ws = pkg_resources.working_set try: setuptools_dist = ws.find(...
def _fake_setuptools(): log.warn('Scanning installed packages') try: import pkg_resources except ImportError: # we're cool log.warn('Setuptools or Distribute does not seem to be installed.') return ws = pkg_resources.working_set try: setuptools_dist = ws.find(...
This function ensures the correct version of `distribute` (setuptools) is installed. It checks if the required version is available via `pkg_resources`; if not, it downloads and installs it. It handles version conflicts and missing distributions, providing error messages if installation fails. The `no_fake` parameter c...
def use_setuptools(version=DEFAULT_VERSION, download_base=DEFAULT_URL, to_dir=os.curdir, download_delay=15, no_fake=True): # making sure we use the absolute path to_dir = os.path.abspath(to_dir) was_imported = 'pkg_resources' in sys.modules or \ 'setuptools' in sys.modules try...
def bfs(self, debug=False): v = set() go = [self.head] while go: if debug: print(go) tmp = go.pop(0) yield tmp if not id(tmp) in v: v.add(id(tmp)) gotmp = [] for t in tmp.nodes: if id(t._to) not in v and t._to not in gotmp: gotmp....
The code minimizes a Deterministic Finite Automaton (DFA) by partitioning states into equivalence classes based on their behavior (end/start status and transitions). It creates a new DFA with merged equivalent states, preserving language recognition while reducing complexity. Transitions are mapped to the minimized sta...
def minimize(self): S = set([i for i in self.bfs()]) F = set([i for i in S if i._isEnd]) S_F = S - F G = [F, S_F] # print("BEFORE SPLIT") # print(G, len(G)) P = self._minEQ(G) # print("AFTER SPLIT") # print(P, len(P)) min_dfa = DFA() new_nodes = [DFANode() for i in range(len(...
def displayIntro(): hangmanFile = open("hangman-ascii.txt","r") lineCounter = 0 for i in hangmanFile: if(lineCounter == 23): break print(i) lineCounter += 1 hangmanFile.close() def play(): randomWord = getWord() mistakeCounter = 5 hiddenWord = ["_"] * len...
The code defines a Hangman game loop that repeatedly displays the introduction, plays the game, shows the result, and asks the user if they want to play again. The loop continues until the user inputs "no", at which point the function exits.
def hangman(): while True: displayIntro() result = play() displayEnd(result) yerOrNo = str(input("\nDo you want to play again? (yes/no) \n")) if(yerOrNo.lower() == "no"): return
def remove_greatest_variation(gris_idx, ranks, n_remove): variances = np.nanvar(ranks, axis=1) keep_idx = (-variances).argsort()[n_remove:] return np.sort(gris_idx[keep_idx]) def compute_reference_values(arr): ref_values = np.empty(arr.shape[0]) for i,_ in enumerate(ref_values): row = ar...
The main task of the code is to correct an input array by iteratively selecting a subset of less varying elements (Global Rank-Invariant Set, GRIS), computing reference values from this subset, and applying corrections to the entire array. It removes elements with the greatest variation across multiple iterations, adju...
def grsn(arr, set_size, iterations): # Transform to log space #arr = np.log2(arr) # Set up the Global Rank-Invariant Set gris_idx = np.arange(arr.shape[0], dtype=int) to_remove = arr.shape[0] - set_size chunk_size = to_remove // iterations # Find the Global Rank-Invariant Set for...
def Toy1ADAFEnergyLossRateTPP(Toy1Distance,gamma,DistanceGap,alphaViscosity,betaPressure,ADAFrInner,ADAFrOuter,ADAFTemperatureElectron,M9,Dotm,PrintIntermediateResults=False): '''This determines the absolute value of the energy-loss-rate due to triplet pair-production for an isotropically diluted distribution of AD...
The code evaluates and visualizes energy-loss rates (triplet pair-production, curvature-radiation, IC-scattering) for varying distance and gamma values. It computes these rates using dedicated functions, stores results in arrays, and generates two subplots: one with linear y-axis and log y-axis, both showing energy-los...
def _EvaluateEnergyLossRates(): ValuesForEnergyLossRateTPP=np.asarray([]) for distanceValue, gammaValue in zip(Toy1DistanceRange,gammaRange): ValuesForEnergyLossRateTPP = np.append(ValuesForEnergyLossRateTPP,Toy1ADAFEnergyLossRateTPP(distanceValue,gammaValue,5,alphaViscosity,betaPressure,ADAFrInner,ADAF...
def Toy1dgammaOverddAcceleration(Toy1ElectricFieldStrengthMax,Toy1Distance,DistanceGap,hGap): '''This gives the derivative of gamma along the Toy1Distance due to energy-gains due to electrostatic acceleration of an electron. It is in units of 1/m. Toy1Distance and DistanceGap are the distance to the centre and the ...
This function computes the derivative of gamma with respect to distance in Schwarzschild radii units by summing four physical contributions: acceleration, curvature, TPA-ADAF, and IC-ADAF effects. It scales the result by the Schwarzschild radius of mass M9, converting SI-unit-based calculations to geometric units. Para...
def Toy1RightHandSideOfDEQForGamma(Toy1Distance,gamma,Toy1ElectricFieldStrengthMax,DistanceGap,hGap,SizeGap,thetaGap,thetaOpening,alphaViscosity,betaPressure,ADAFrInner,ADAFrOuter,ADAFTemperatureElectron,M9,Dotm): '''This gives the derivative of gamma along the Toy1Distance in 1/m. The multiplication with rSchwarzs...
def send(self, reply: Reply, msg: Message): if reply is None: return if reply.type == ReplyType.IMAGE: img_path = serialize_img(reply.content) wx_id = msg.room_id if msg.is_group else msg.sender_id send_image(img_path, wx_id) elif reply.type == Rep...
The main task of the code is to process incoming messages by filtering self-sent or successfully sent messages, creating a Message object, emitting a "did_receive_message" event, and handling the message as group or single chat based on the event's response. It logs message status, ignores self-sent messages, and trigg...
def handle_message(self, raw_msg): if "wxid" not in raw_msg and raw_msg["status"] == const.SUCCESS: logger.info("message sent successfully") return # ignore message sent by self if raw_msg["id2"] == self.personal_info["wx_id"]: logger.info("message sent by sel...
def create_robot_torso(name="torso", torso_thickness=1, shoulder_width=2, pelvis_width=1.25, torso_offset=.2, head_radius=.75): torso0 = cmds.polySphere(name=name+"_0" + "_Geo", radius=torso_thickness / 2, ch=0, cuv=0)[0] torso1 = cmds.polyCube(width=torso_thickness, height=torso_thickness, depth=torso_thickne...
The main task of the code is to create a robot model by assembling its body parts (torso, head, arms, legs) using specified offsets and widths. It positions limbs relative to the torso and pelvis, parents components hierarchically, adjusts positions, groups all elements under "Robot_Geo", and returns a list of all crea...
def create_robot(): torsoInfo = create_robot_torso() torso0 = torsoInfo[0] torso1 = torsoInfo[1] head = torsoInfo[2] pelvis = torsoInfo[3] shoulder_offset_x = torsoInfo[4] shoulder_offset_y = torsoInfo[5] shoulder_width = .6 pelvis_offset_x = torsoInfo[6] pelvis_offset_y = tors...
def gen_bounds_and_constraints(): global BOUNDS, CONSTS # Generate the bounds and constraints required for the optimizer BOUNDS = np.array([[[1, NUM_UNITS[r]-(NUM_APPS-1)] for a in range(NUM_APPS-1)] \ for r in range(NUM_RESOURCES)]).reshape(NUM_PARAMS, 2).tolist() print("BOUNDS = ", BOUNDS...
The function `c_lite()` performs Bayesian optimization to determine optimal configurations. It generates bounds and constraints for optimization, creates initial configurations, and executes Bayesian optimization using these starting points. The process returns the number of iterations and the achieved objective value....
def c_lite(): #cbw #standard_test() # Generate the bounds and constraints required for optimization gen_bounds_and_constraints() # Generate the initial set of configurations init_configs = gen_initial_configs() print('init_configs = ', init_configs) # Get the baseline performance...
def to_default_timezone_datetime(self, value): """ convert to default timezone datetime """ return timezone.localtime( self.to_utc_datetime(value), timezone.get_default_timezone() ) def to_utc_datetime(self, value): """ from value to datetime with tzin...
This function converts a given value to a datetime object, handling timezone settings based on configurations. If timezone support is enabled, it uses either the default timezone or UTC depending on the TIME_ZONE setting; otherwise, it returns a naive datetime.
def to_datetime(self, value): if settings.USE_TZ: if settings.TIME_ZONE != "UTC": return self.to_default_timezone_datetime(value) else: return self.to_utc_datetime(value) else: return self.to_naive_datetime(value)
def get_connection() -> (online_module.CFConnection, 'username'): ''' Returns a CFConnection namedtuple that passed the hello message protocol of connectfour, and valid username together in a tuple of size 2. ''' while True: connection = _attempt_connection() username = _ask_user...
The code initiates an online Connect Four game by establishing a server connection, starts a new game sequence, sends AI moves, and enters a loop to handle gameplay until a win condition is met. It includes error handling for incorrect servers and ensures proper disconnection.
def online_game()->None: ''' Starts an online game with a connectfour server, asks the user for moves and loops until either the AI wins or Player wins. ''' connection = None try: connection, user_name = get_connection() game, user_col_rows = shared.new_game_sequence() on...
def empty_cells(board_state): """ """ cells = [] for x, row in enumerate(board_state): for y, cell in enumerate(row): if cell == 0: cells.append([x, y]) return cells def game_over(board_state): """ """ return check_victory(board_state, HUMAN) or ch...
The function handles a human player's turn in a game by accepting a numeric input (1-9) corresponding to a 3x3 grid position, validating the move against available cells, and updating the board if valid. It ensures the input is within bounds, checks for valid moves, and re-prompts on errors, exiting on interrupts.
def take_human_turn(c_choice, h_choice): """ """ depth = len(empty_cells(board)) if depth == 0 or game_over(board): return # Dictionary of valid moves move = -1 moves = { 1: [0, 0], 2: [0, 1], 3: [0, 2], 4: [1, 0], 5: [1, 1], 6: [1, 2], 7: [2, 0], 8: [2, 1],...
def empty_cells(board_state): """ """ cells = [] for x, row in enumerate(board_state): for y, cell in enumerate(row): if cell == 0: cells.append([x, y]) return cells def game_over(board_state): """ """ return check_victory(board_state, HUMAN) or ch...
The main task of the code is to handle the computer's turn in a game (likely Tic-Tac-Toe) by selecting a move using either random choice (for an empty board) or the minimax algorithm (for deeper states), updating the board with the chosen move, and rendering the game state. It checks for game termination conditions and...
def take_ai_turn(c_choice, h_choice): """ """ depth = len(empty_cells(board)) if depth == 0 or game_over(board): return clean() # Why does it run clean() in the middle of this function? print(f'Computer turn [{c_choice}]') render(board, c_choice, h_choice) if depth == 9: ...
def clean(): """ Clears the console """ os_name = platform.system().lower() if 'windows' in os_name: system('cls') else: system('clear') def empty_cells(board_state): """ """ cells = [] for x, row in enumerate(board_state): for y, cell in enumerate(row):...
This code implements a tic-tac-toe game where a human player and AI alternate turns. It handles symbol selection (X/O), determines starting player, validates inputs, executes game loops, and declares winners/draws. The AI's moves are determined by separate functions, while the human inputs their moves. The game ends wh...
def main(): """ Main function that calls all functions """ # Setup Game clean() h_choice = '' # X or O c_choice = '' # X or O first = '' # if human is the first # Human chooses X or O to play while h_choice != 'O' and h_choice != 'X': try: print('') ...
def build_schema(): if not os.path.exists(DATABASE_URL): connect = db_connection.get_connection() with open('./schema.sql') as f_p: print('execute script') connect.executescript(f_p.read()) connect.commit() delete_all() def import_imdb_dataset(base=0): imdb_df...
The main task of the code is to build a database schema, import IMDb dataset records, and then import TMDb dataset records using the count from IMDb. This integrates movie/TV show metadata from both sources into a structured database, likely for analysis or combined dataset applications.
def main(): build_schema() cnt = import_imdb_dataset() import_tmdb_dataset(cnt)
def ok(text): global max_credits max_credits += 1 print("+ok: "+text) credit(1) def bad(text): global max_credits max_credits += 1 print("-bad: "+text) printinfo(str(credits)+"/"+str(max_credits)+" checks passed") print("This checker tool exited with an error. Repair the problem and try again") sys.exit(-1) ...
The code reads a square matrix from a file, validates its structure (square shape, correct size, valid entries 0-2), counts zeros, ones, and twos, and returns the matrix along with these counts. It checks file existence, matrix dimensions, data integrity, and argument consistency.
def read_array(inputfile,myn): if os.path.isfile(inputfile): ok(inputfile+" exists") else: bad(inputfile+" has not been created") data = np.genfromtxt(inputfile,dtype=np.int) show_array(data) (n,cols)=data.shape if n==cols: ok("rows = cols"); else: bad("rows <> cols"); if data.size==n**2: ...
def write_array(inputfile,data): np.savetxt(inputfile,data,fmt="%d") def call_code(code,argument): call_string = "python3 "+code+" "+str(argument) # print("calling: "+call_string) status = os.system(call_string) status = int(status/256) return status def ok(text): global max_credits max_credits += 1 print("+o...
The main task of the code is to check if the exit status from executing `call_code` equals -1. If it does, the function exits with that status; otherwise, it displays the data array and reports an error, indicating the exit value should be -1 for a "winner" case.
def check_some_config(wanted,data,code,myn): # prepare final config write_array(inputfile,data) status = call_code(code,myn) if status==-1: ok("exit (winner) status "+str(status)) else: show_array(data) bad("winner = exit value should be -1 in that case")
def printinfo(text): print(" "+text) def call_code(code,argument): call_string = "python3 "+code+" "+str(argument) # print("calling: "+call_string) status = os.system(call_string) status = int(status/256) return status def read_array(inputfile,myn): if os.path.isfile(inputfile): ok(inputfile+" exists"...
The code tests a program's behavior for generating and updating a grid (likely a game) based on input parameters. It verifies that after each move, the grid contains the correct number of player tokens (1s and 2s), checks exit statuses (1, 2, or 3 for a winner), and ensures proper handling of edge cases. For specific g...
def checker(code,myn): printinfo("testing "+code+" "+str(myn)) # delete inputfile if os.path.isfile(inputfile): os.remove(inputfile) # start code for n=myn status = call_code(code,myn) # investigate the resulting inputfile data,n,zeros,ones,twos = read_array(inputfile,myn) if ones==1: ok("a single 1") i...
def isSinkA2dp(): """Checks whether current headset sink is A2DP sink""" sink_list = pulse.sink_list() if len(sink_list) < 1: logger.error("No sinks detected") return False for sink in sink_list: try: if headset["mac_address"] == sink.proplist["device.string"]: ...
The function ensures the headset is in A2DP mode by checking its current profile state. If not in A2DP, it repeatedly disconnects the headset, attempts to set the profile to A2DP, waits 5 seconds, and rechecks until success. The process logs each step, including initial checks and forced disconnections to enforce the d...
def ensureA2dp(): """Checks the card profile state and eventually sets it to A2DP""" logger.info("Checking if headset is in A2DP mode") is_a2dp = isSinkA2dp() while not is_a2dp: logger.info("Trying to disconnect headset to enforce A2DP mode") changeCardActiveProfileToA2dp(getHeadsetCard(...
def handleArguments(): """Handles CLI arguments and saves them globally""" parser = argparse.ArgumentParser( description="A tool which tries to keep a Bluetooth headset connection alive. Also available: disconnect and version info" ) parser.add_argument("--keep_alive", "-k", help="Set a flag whe...
The main task of the code is to manage Bluetooth device connections and A2DP mode based on command-line arguments. It reconnects, disconnects, or maintains a connection with optional keep-alive looping. The function ensures device connectivity, enforces A2DP mode, and logs completion upon successful connection.
def main(): handleArguments() if args.reconnect: ensureConnected() return reconnect() elif args.disconnect: ensureConnected() return disconnect() else: ensureConnected() ensureA2dp() if args.keep_alive: time.sleep(10) ...
def tonumpyarray(mp_arr): return np.frombuffer(mp_arr, dtype=float).reshape(W_SHAPE) def decode(hash: int) -> List[int]: result = [] for _ in range(6): result.append((hash & 255) * 50) hash = hash >> 8 return result def to_points(index: int) -> int: return index * 50 def get_bank_act...
This function updates a shared weight matrix (shared_w) in parallel using multiple threads. It calculates the maximum weight (max_w) for each element based on game state parameters, updates the weight, and tracks convergence by comparing the difference between the original and new weights. Each thread processes a subse...
def update(shared_w: mp.Array, convergence: mp.Array, thread_index: int): convergence[thread_index] = 0 dp = dict() W = tonumpyarray(shared_w) it = np.nditer(W, flags=['multi_index']) counter = 0 for w in it: if thread_index == 0 and counter % 10000 == 0: print('{:.1%} '...
def get_runtime(self): """Returns the number of seconds since the timer was started to when it was stopped """ return self.stopTime - self.startTime def get_totalReceivedImages(self): return self.imageCounter def get_totalLostImages(self): return self.totalLostPackets def get_per...
The code writes a file named 'useful_info.txt' containing key simulation performance metrics, including total runtime, image counts (received/lost), latency statistics, jitter, FPS, and bandwidth. It formats these values as human-readable text for analysis or record-keeping.
def write_usefulInfo(self): """Writes a file in the same directory named 'useful_info.txt' that contains some performance information about the simulation""" with open('stats/useful_info.txt','w') as txtfile: txtfile.write("TOTAL TIME SPENT ON SIMULATION: "+str(self.get_runtime())+"...
def source_row(self): return ft.Container( ft.Column( [ ft.Row( [ ft.Row( [ ft.Image( src=self.source.im...
The code sets the page title to "Source News" and returns three components: source_row, source_topics, and source_results, which likely generate the layout, topics, and results sections of the source news page.
def view_build(self): self.page.title = "Source News" return self.source_row(), self.source_topics(), self.source_results()
def _get_id_token(self) -> str: """ Get the id token, refreshing it if needed. Returns: The id token. """ # check that the id token is not about to expire (10 minutes) if self.__id_token is not None and is_token_expired(self.__id_token): self.__id_token = Non...
This function retrieves a reporting unit's data, including optional stats, layers config, and downloads. It sends an API request, processes the response, converts specific fields to integers, and links the control site if present. The result is a dictionary with the reporting unit's details, including its control unit,...
def get_reporting_unit(self, reporting_unit_id: str, include_stats=False, include_layers_config=False, include_downloads=False) -> Mapping[str, Any]: """ Get a site with its control (if it has one). Optionally also retrieving all stats, layers config, and downloads index. Args: repo...
def load_model(): freqs = None theta = None if(os.path.exists(FREQS_FILE)): with open(FREQS_FILE, 'rb') as fp: freqs = pickle.load(fp) if(os.path.exists(THETA_FILE)): with open(THETA_FILE, 'rb') as fp: theta = pickle.load(fp) return freqs, theta def tra...
The code initializes a model by attempting to load pre-trained parameters (freqs, theta). If unavailable, it trains the model from scratch, saves the trained parameters, and returns them. The main task is to ensure the model is either loaded or trained and saved for subsequent use.
def init(): # try to load model freqs, theta = load_model() # if model is not available yet, let's re-train that if (freqs is None) or (theta is None): # training model from scratch logger.info("No pre-trained model available, training now...") freqs, theta = train_model() ...
def load_image(img_file): img = io.imread(img_file) # RGB order if img.shape[0] == 2: img = img[0] if len(img.shape) == 2: img = cv2.cvtColor(img, cv2.COLOR_GRAY2RGB) if img.shape[2] == 4: img = img[:, :, :3] img = np.array(img) return img def get_textbox( detector, image, canvas_size, ...
The main task of the code is to detect and group text regions in an image using a detector, then filter and organize them into horizontal and free lists based on size thresholds and geometric criteria, returning the processed text box groupings for further handling.
def read_text( image_file, detector, device, min_size=20, text_threshold=0.7, low_text=0.3, # 0.4 before link_threshold=0.4, canvas_size=2560, mag_ratio=1.0, slope_ths=0.1, ycenter_ths=0.5, height_ths=0.5, width_ths=0.5, add_margin=0.1, optimal_num_chars=None, threshold=0.2, bbox_min_...
def extract_href_from_md_link(text): link_pattern = r'\[link\]\((https?://\S+)\)' return re.findall(link_pattern, text)[0] def extract_file_path_from_link(link): relative_path = link.replace("https://github.com/mixbytes/audits_public/blob/master/", "").replace("%20", " ") return relative_path def fix(te...
The code processes reports listed in a table by parsing Markdown and PDF links, validating file existence, reading report content, applying fixes, and aggregating parsed data with metadata into a JSON output.
def run_from_index(path): table = md.parse_table(open(path).read()) base_path = config.get("base_path", "") outputs = [] for report in table: md_link = extract_href_from_md_link(report["MD Report"]) path = extract_file_path_from_link(md_link) path = os.path.join(base_path, path)...
def parse_arguments(*args): arguments = [] for arg in args: arguments.extend(arg.split()) return arguments def parse_syntax(arguments): i = 0 if len(arguments) == 1: with open(arguments[0], 'r') as file: for line in file.read().splitlines(): args...
The main task of the code is to handle command-line arguments. If multiple arguments are provided, it parses them, processes syntax, and executes a packet processor. If only one argument is given (or none), it prints a debug message. The function orchestrates argument parsing, syntax validation, and packet processing b...
def main(args): if len(args) > 1: arguments = parse_arguments(*args[1:]) parse_syntax(arguments) packet_processor() else: print(messages.DEBUGMSG)
def parse_pie(pie, labels=None, name=None): try: import pandas if isinstance(pie, pandas.Series): pieval = pie.values pielab = pie.index.values piename = pie.name if piename is None: piename = name except (NameError, ImportError): ...
This function generates a spiral pie chart using a specified spiral type (default: Archimedes Spiral), plotting data segments with customizable parameters like color maps, figure size, edge width, and label settings. It processes input data, prepares spiral segments, creates graphical patches, and renders the chart wit...
def plot(pie, labels=None, name=None, spiral=spirals.ArchimedesSpiral(), tmin=0, tmax=4*np.pi, sort=False, n_points=1000, cmap='viridis', figsize=(10, 10), edgewidth=3, spiralkwargs={'ls':'', 'c':'w'}, axisoff=True): pieval, pielab, piename = parse_pie(pie, labels, name) t...
def get_s3_settings(self): settings = {} settings["aws_access_key_id"] = self.get_value("aws_access_key_id", os.environ.get("AWS_ACCESS_KEY_ID")) settings["aws_secret_access_key"] = self.get_value("aws_secret_access_key", os.environ.get("AWS_SECRET_ACCESS_KEY")) settings["aws_endpoint_ur...
The code initializes an object with a payload, workflow JSON, S3 utilities, and a unique request ID. It sets the job's received time, configures S3 settings, generates a UUID-based request identifier, and triggers prompt setup for processing tasks. The main task is to prepare the object for handling workflows or data p...
def __init__(self, payload, workflow_json = None): self.job_time_received = datetime.datetime.now() self.payload = payload self.workflow_json = workflow_json self.s3utils = s3utils(self.get_s3_settings()) self.request_id = str(self.get_value( "request_id", ...
def get_angle(): y_angle=get_y_rotation(mpu.accel.x, mpu.accel.y, mpu.accel.z) x_angle=get_x_rotation(mpu.accel.x, mpu.accel.y, mpu.accel.z) return x_angle,y_angle def clamp_number(val, min, max): return min if val < min else max if val > max else val def interval_mapping(x, in_min, in_max, out_min, o...
The function `bubble_position` converts angular inputs (from `get_angle()`) into 2D coordinates by mapping angles (-90 to 90) to a range defined by `point_range` and `sensitivity`, then clamping values to ensure they stay within `[0, point_range]`. It returns the adjusted `[x, y]` coordinates as integers, effectively t...
def bubble_position(): x,y=get_angle() x=int(clamp_number(interval_mapping(x,-90,90,0-sensitivity,point_range+sensitivity),0,point_range)) y=int(clamp_number(interval_mapping(y,-90,90,point_range+sensitivity,0-sensitivity),0,point_range)) return [x,y]
def gameOverCheck(self): x = self.gameFrame.find_overlapping(160, 0, 240, 80) if len(x) > 4: return True return False def gameOverAnimation(self): drawDir = "Left" counter = 0 # Cancels any queued tick functions. self.parent.after_cancel(self.ticking)...
The main task of the code is to manage a game loop for a falling block game (e.g., Tetris). It schedules recurring updates, checks if the current shape can move down, triggers game over logic if movement fails, pauses input, runs an animation, or spawns the next shape if the game continues.
def tick(self): self.ticking = self.gameFrame.after(self.tickRate, self.tick) # Determines if the shape cannot move anymore and checks if the game is over, if it is pauses input from the # user and runs the game over animation, else it spawns the next shape. if not self.current_shape.mov...
def transmit(self, data): success = False try: # print('<', str(list(data))) packet = cobs.encode(data)+bytes([0]) # print('<', str(packet)) len_sent = self.oven.write(packet) if len(packet) == len_sent: success = True ...
The function `communicate` sends a specified communication type and data, retrying up to `self.retries` times if transmission fails. It validates the response: if successful, it returns `True` and the received data (excluding the first byte); if a NACK is received, it warns and retries; otherwise, it raises exceptions ...
def communicate(self, comms_type, data=bytes()): success = False response = bytes() assert(comms_type in self.COMMS_TYPES) for attempt in range(self.retries): if not self.transmit(bytes([comms_type]) + bytes(data)): print('Warning: ({}/{}) transmission failed,...
def getLoggedUser(request): # This function will be called to check if user is logged in using session variables if 'loggedUserId' in request.session: loggedUserId = request.session['loggedUserId'] if len(User.objects.filter(id=loggedUserId)) == 1: return User.objects.get(id=logged...
The main task of the code is to handle POST/GET requests by retrieving user input values, authenticating the logged-in user, creating a voucher, executing a function multiple times based on input, and rendering a dashboard template. It processes form data, defaults to zero if inputs are missing, and performs repetitive...
def test2(request): # ... Saame thing if request.method == "POST": if request.POST["number"]: n = request.POST["number"] else: n = 0 if request.POST["number2"]: n2 = request.POST["number2"] else: n2 = 0 loggedUser = getLogge...
def extract_commons(self): try: # TODO get source initiative full_title = self.soup.select_one('.entradilla-iniciativa').text reference = self.get_reference() position = (len(reference) - reference.find('(', -15) + 2) * -1 title = full_title[:position]...
The main task of the code is to process an initiative by extracting data, checking for content changes, and handling alerts or updates. It checks for a 404 error, extracts common data, compares existing and new content, generates an ID, triggers untagging if content changes, creates alerts for final status with topics,...
def extract(self): try: check = self.soup.select_one('.entradilla-iniciativa') if check is None: # This is a 404 error, the initiative does not exist. return self.extract_commons() previous_content = self.initiative['content'] if se...
def __merge_results(self, title_result, body_result): DEFAULT_RESULT = { 'topics': list(), 'tags': list() } if len(title_result['tags']) == 0: if len(body_result['tags']) > 0: return body_result return DEFAULT_RESULT...
This function tags initiatives by extracting specified tags from their titles and content, merges results if enabled, updates initiative metadata, removes underused topics, saves changes, and triggers alerts when applicable.
def tag_initiatives(self, initiatives, tags, merge=False, send_alerts=True): total = len(initiatives) for index, initiative in enumerate(initiatives): try: log.info(f"Tagging initiative {index+1} of {total}") tipi_tasks.init() title_result = ti...
def __refresh_members(self): response = requests.get(ENDPOINT.format(method='parlamentario')) if response.ok: for member in response.json(): self.__create_or_update(member) def __refresh_parliamentarygroups(self): groups = Deputy.objects.distinct('parliamentarygroup')...
The main task of the code is to update active members for each legislative chamber ('S' and 'D') by first refreshing member data and parliamentary groups, then applying chamber-specific updates to ensure accurate representation of active members in the system.
def extract(self): self.__refresh_members() self.__refresh_parliamentarygroups() for chamber in ['S', 'D']: self.__update_active_members(chamber)
def fillRow(ticker, date, numDays): # Takes in ticker, dateObj, and number of days you want data for | returns a list of data containing all data data = [] def helper(ticker,eDate,numDays): # check if numDays is going to cause an error if(eDate > datetime.today()): print(f"Number o...
This code fills missing data in an Excel sheet's rows with stock market information. It loads a workbook, iterates through rows, and for empty last cells, retrieves ticker-specific data (open, high, low, close, volume) along with premarket high details and HOD/LOD times. It updates the row values with this data and sav...
def updatedFillRawData(inputFile, page): # assumes the headers are ticker, date, gap % , premarket high, premarket high time, HOD time, LOD time (open, high, low, close, volume) wb = openpyxl.load_workbook(inputFile) ws = wb[page] headers = list(ws['1']) numDays = int((len(headers) - 7)/5) # The head...
def can_be_processed(name): if fp.is_finished(name) or name[-2:] == "fr" or name[-2:] == "de" or name[-2:] == "es" or name[-2:] == "it" or name[-2:] == "ru": return False return True def file_can_be_processed(date): file_date = ut.convert_to_datetime(date) last_file_name = fp.get_latest_file() if(last_fil...
The code processes files in a directory by checking if they can be processed, then iterating through subdirectories to handle gzipped JSON files. It extracts data, processes articles, marks files as processed, and deletes them after processing, ensuring ordered handling of files and dates.
def process_files(): l = listdir(data_folder) l.sort() for f in l: print(f) if can_be_processed(f): fp.set_processed(f) inner_folder = data_folder+"/"+f+"/per_day" files = listdir(inner_folder) files.sort() for i in files: date = i.replace(".gz", "") if file_c...
def clean_text(text_list): text_list = remove_stopwords(text_list) return text_list def _speech_tag(word_list): return nltk.pos_tag(word_list) def _named_entities_chunk(tagged_list): return nltk.ne_chunk(tagged_list)
The code extracts named entities, specifically proper nouns (NNP), from input text by tokenizing, cleaning, tagging, chunking, and mapping words to their part-of-speech tags, returning a dictionary of lowercase proper nouns with their tag.
def named_entities(text): text_list = word_tokenize(text) cleaned = clean_text(text_list) tagged = _speech_tag(cleaned) chunk = _named_entities_chunk(tagged) items = nltk.chunk.tree2conlltags(chunk) named_entity = {} for item in items: if(item[1] == "NNP"): try: named_entity[item[0]...
def recreate_input(): inp = input("Are you really sure? (write YES and press enter if you are): ") if inp == "YES": print("Recreating DB...") db_layer.recreate_db() def process_files(): l = listdir(data_folder) l.sort() for f in l: print(f) if can_be_processed(f): fp.set_processed(f) ...
The code presents a menu for database operations, allowing users to choose between recreating the database (RC), processing news articles (PR), syncing filters (SY), or managing indexes (I). It captures user input and executes the corresponding function, providing a command-line interface for data management tasks.
def startup(): print("RC - ReCreate Database") print("PR - Process news articles") print("SY - Sync filters") print("I - Indexes") inp = input("What do you want to do?: ").upper() if inp == "RC": recreate_input() elif inp == "PR": process_files() elif inp == "I": indexes_input() elif inp ...
def get_ldap_groups(ldap_conn): '''Get LDAP groups and build a tree of the hierarchy''' base = os.environ['LDAP_GROUP_BASE'] user_base = os.environ['LDAP_USER_BASE'] log.info(f'Using group base {base}') group_filter = os.getenv('LDAP_GROUP_FILTER') if group_filter: log.info(f'Using grou...
The main task of the code is to synchronize LDAP groups and users with GitLab. It connects to an LDAP server, retrieves group/user data, and syncs this information to GitLab. If configured, it creates GitLab subgroups mirroring LDAP hierarchy; otherwise, it syncs individual LDAP groups. The code handles logging, enviro...
def main(): load_dotenv() log.setLevel(logging.DEBUG if getenvbool('VERBOSE') else logging.INFO) handler = logging.StreamHandler() handler.setFormatter(logging.Formatter( '%(message)s', datefmt='%Y-%m-%dT%H:%M:%S' )) logging.getLogger().addHandler(handler) ldap_conn = ldap_c...
def deleteSources(self): while True: toDelete = [] for scc_dict in self.superDepGraph: delScc = True for node in scc_dict: # Check if atom is SCC (then no delete) tempA = node.split(":") if(tempA[0]=='a'): delScc = False break # Check incoming...
The code iteratively checks and removes minimal parts of a model based on clauses in a dependency graph. It processes source SCCs, verifies model intersections with clauses, and applies reductions if the intersection is minimal. The loop continues until no clauses remain, returning True if the model is fully reduced to...
def solve(self, reduct): runLoop = True count = 0 # Delete empty source nodes (recursively) self.deleteSources() while runLoop: # Check each source S in super DP graph, and verify if minimal for T_S runLoop = False count=count+1 if(self.printTrace): print("ITERATION: " + str(count...
def save_if_was_not(self, city_): city_query = CityEntity.select().join(CountryEntity).where((CityEntity.name == city_.name) & (CityEntity.state == city_.state) & (CountryEntity....
The main task of the code is to determine if a location's country is already synced with Songkick, sync it if not, and save the location data. It geocodes coordinates to identify a city, checks if the corresponding country exists in the database, verifies Songkick sync status, and either prints a confirmation or initia...
def find_and_save_location(self, lat, lng): city_ = geocoder.geocode_city(lat, lng) country_by_name_query = CountryEntity.select().where(CountryEntity.name == city_.country.name) if country_by_name_query.exists(): country_: CountryEntity = country_by_name_query.get() if c...
def parens(x: str) -> str: return "(" + x + ")" def gen_typesig(self, typesig: TypeSig) -> str: return self.gen_type(typesig.annot) def gen_lit(self, lit: Lit) -> str: return str(lit.value)
The function `gen_expr` generates a string representation of an abstract syntax tree (AST) node (`expr`) according to specific formatting rules. It handles various expression types (assignments, operations, casts, function calls, attribute access, literals, variables) by recursively converting sub-expressions and combi...
def gen_expr(self, expr: Expr) -> str: match expr: case EAssign(lhs, op, rhs) | EOp(lhs, op, rhs): return " ".join([self.gen_expr(lhs), str(op), self.gen_expr(rhs)]) case ECast(target, sig): return parens(self.gen_typesig(sig)) + self.gen_expr(target) ...
def gen_var_decl(self, decl: VarDecl) -> str: suffix = "" if decl.sig: t = decl.sig.annot else: t = cast(Expr, decl.value).annot while isinstance(t, TArr): t = t.contains suffix += "[]" if decl.value: suffix += " = " + s...
The function `gen_stmt` generates string representations of programming language statements from abstract syntax tree (AST) nodes. It uses pattern matching to handle different statement types (e.g., variable declarations, loops, conditionals) and recursively converts them into target language code (e.g., C-like syntax)...
def gen_stmt(self, stmt: Stmt) -> str: match stmt: case SDecl(var_decl): return self.gen_var_decl(var_decl) + ";" case SBreak(): return "break;" case SContinue(): return "continue;" case SReturn(value): ...
def gen_var_decl(self, decl: VarDecl) -> str: suffix = "" if decl.sig: t = decl.sig.annot else: t = cast(Expr, decl.value).annot while isinstance(t, TArr): t = t.contains suffix += "[]" if decl.value: suffix += " = " + s...
This function generates code strings from abstract syntax tree (AST) nodes representing declarations. It handles variable declarations, classes, and functions, applying specific formatting rules for modifiers, types, and statement blocks. The function recursively processes declaration components, translating them into ...
def gen_decl(self, decl: Decl) -> str: match decl: case DDecl(var_decl): return self.gen_var_decl(var_decl) case DClass(mod, name, body): return ( mods(mod) + " class " + f"{name} " + block(map(self.gen_decl, body)) ) ...
def load_data(path="./data/ours-2021-05-04-clean.json"): return json.load(open(path)) def create_qa_format(data, grouped=False, binary=True): papers = [] intents = get_intents() for file, annotation in data.items(): # filename = file.split("_")[1] section = get_section_template() ...
The main task of the code is to process a dataset of papers by analyzing key statistics (total entries, unique keys, and unique identifiers), convert the data into a question-answer format, split it into training, development, and test sets, and save these subsets as JSON files for further use in machine learning tasks...
def main(): """ In the file we load, there is for each paper an object; the inner part of the object key is the filename; :return: """ data = load_data() print(str(len([key for key, value in data.items()]))) print(str(len(set([key for key, value in data.items()])))) print(str(len(set...
def explainProgram(): print("This program reads lines from csv files on stock prices and compares the closing prices of two stocks to find any correlation between the two.") def driver(): xlist = readCSV('GBTC.csv') ylist = readCSV('ADBE.csv') corr = correlation(xlist, ylist) return c...
The main task of the code is to execute a program that first explains its purpose, runs a core processing function (`driver()`) to compute a correlation value (`corr`), and then displays the results using `displayresults(corr)`. The program's workflow involves explanation, data processing, and result visualization.
def main(): explainProgram() corr = driver() displayresults(corr)
def print_line(self, prefix, next_hop): if self.ts_format == 'dump': d = self.ts else: d = self.org_time if self.verbose: d = str(d) else: d = datetime.utcfromtimestamp(d).\ strftime('%m/%d/%y %H:%M:%S') if self.pk...
The function processes BGP4MP messages by setting metadata like type, timestamp, and peer details. It distinguishes between state change events (logging old/new states) and message events (processing UPDATE messages). For updates, it extracts BGP attributes, withdrawn routes (prefix/length), and NLRI (prefix/length), a...
def bgp4mp(self, m, count): self.type = 'BGP4MP' self.ts = m.ts self.num = count self.org_time = m.ts self.peer_ip = m.bgp.peer_ip self.peer_as = m.bgp.peer_as if (m.subtype == BGP4MP_ST['BGP4MP_STATE_CHANGE'] or m.subtype == BGP4MP_ST['BGP4MP_STATE_CH...
def __generate_candidate(self, transactions: list, L, K) -> dict: # frequent 1-itemset if K == 1: uniqe_items = set( [item for transaction in transactions for item in transaction] ) supports = defaultdict(int) for transaction in tran...
The code implements a modified Apriori algorithm to generate frequent itemsets from transaction data. It iteratively builds candidate sets, prunes them using support thresholds adjusted by `min_sup` and `alpha`, and collects frequent itemsets (`L`) until no new candidates remain. The process starts with initial candida...
def fit(self, transactions: list, min_sup: float, alpha: float = 0.0): self.min_sup = int(len(transactions) * min_sup) # frequent set L = [] # candidate set candidates = self.__generate_candidate(transactions, L, K=1) C, support = candidates['Itemset'], candidates['S...
def __is_firefox_installed() -> bool: firefox_path: str if sys.platform == 'win32': logging.info('Windows system detected') system_drive: Optional[str] = os.getenv("SystemDrive") if system_drive is None: raise Exception() firefox_path = os.path.join( syste...
The main task of the code is to collect installed browser extensions from Firefox, Chrome, and Edge for current users. It checks each browser's installation status, retrieves extension data via helper functions, and aggregates results into a list of ExtensionInfo objects, returning them for further processing.
def get_extension_info() -> list[ExtensionInfo]: extension_info_list: list[ExtensionInfo] = [] user_list: list[str] = [u.name for u in psutil.users()] if __is_firefox_installed(): extension_info_list.extend( __get_firefox_installed_extensions(user_list)) if __is_chrome_installed(): ...
def drawgrid(grid): print("\n"*100) for y in range(len(grid)): for x in range(len(grid[y])): if grid[0] == x and grid[1] == y: print('P', end=" ") elif abs(x-position(0, 0)[0])>1 or abs(y-position(0, 0)[1])>1: print('0', end=' ') else: ...
The code implements a turn-based grid game where a player navigates a maze using directional inputs (8,4,5,6) to move up, left, down, or right. The player avoids walls/doors, checks win conditions, and progresses through levels by reaching specific positions. Moves are limited, and the game tracks remaining moves, tran...
def game(board1): global currentlevel global moves global grid x = 1 y = 1 board = board1 drawgrid(board) key = "" porta_parser = open("config.txt") lines = porta_parser.readlines() moves_conf = lines[7] digits = moves_conf[7:] moves = int(digits) while moves > 0:...
def pathWithinCache(self, cache:SciDDCacheManagerBase=None) -> pathlib.Path: ''' Returns the subpath within the cache where this resource should be placed/found for the given cache manager. A SciDD is an "abstract" representation of the data. A file (in this case) can be located in multiple caches managed by t...
The method `downloadTo` downloads a resource from a URL to a specified directory, decompressing it if compressed. It checks the cache first; if the file exists, it returns the cached path. Otherwise, it handles download errors, resolves 404s by checking common compressed extensions, streams the file to disk, and sets t...
def downloadTo(self, path:Union[pathlib.Path,str]=None) -> pathlib.Path: ''' Download the resource to the specified directory. It will be decompressed if it’s compressed from the source. :param path: the path to download the file to; does not include the filename :returns: the full :py:attr:`filepath` to the f...
def prepare_images(reset=False, source=TRAIN_FILE, target_dir=TRAIN_DIR): os.makedirs(target_dir, exist_ok=True) vidcap = cv2.VideoCapture(source) n_frames = int(vidcap.get(cv2.CAP_PROP_FRAME_COUNT)) for i in progress(range(n_frames), step=5000): prepare_image(i, vidcap, target_dir, reset) ...
The code trains a neural network model for image processing. It prepares images, splits ground truth data, generates image pairs, trains the model using batch generators, saves the trained model, records training history, and visualizes validation curves. Key steps include data preparation, model instantiation, trainin...
def train_model(self): prepare_images() ground_truth = train_val_split_ground_truth() image_pairs = create_image_pairs_with_speed(ground_truth) plot_train_val_split(ground_truth) self.model = neural_factory() self.model.summary() train_pairs, val_pairs = get_train...
def model_creation(self): self.model = neural_factory() # # model.summary() '''Uncomment to check the model Summary''' # train_pairs, val_pairs = get_train_val_image_pairs(image_pairs) model_name = '3' wts = self.model.load_weights(f'...
The code generates a video visualizing speed data by initializing a video capture, creating segments, generating frames, and releasing the video resource. It first creates a model, processes the input video file, splits it into segments, constructs frames from these segments, and releases the video capture object to fr...
def create_speed_video(self): #Call to make video of speeds self.model_creation() vidcap = cv2.VideoCapture(TRAIN_FILE) segment = create_segment_rec(vidcap) frames = create_video_rec(segment, vidcap) vidcap.release()
def split_layer(self, input_x, stride, layer_name): with tf.name_scope(layer_name) : layers_split = list() for i in range(cardinality) : splits = self.transform_layer(input_x, stride=stride, scope=layer_name + '_splitN_' + str(i)) layers_split.append(split...
This code implements a residual layer in a neural network, processing input through splitting, bottleneck transformation, dimension transition, and merging steps. It handles dimension adjustments via padding or stride changes, applies residual connections by adding transformed features to padded inputs, and uses ReLU a...
def residual_layer(self, input_x, out_dim, layer_num, res_block=blocks): # split + transform(bottleneck) + transition + merge for i in range(res_block): # input_dim = input_x.get_shape().as_list()[-1] input_dim = int(np.shape(input_x)[-1]) if input_dim * 2 == out_di...
def send_data_to_flask(self, data): try: response = requests.post(f'{FLASK_SERVER_URL}/send_data', json=data) response.raise_for_status() # Raise an exception for bad responses print(response.json()) # Print the response from the server, if needed except requests.ex...
The code captures audio input via a microphone, converts it to text using Google's Speech Recognition API, displays the text in a GUI, sends it to a Flask server, handles recognition errors, measures ambient noise levels (decibels), and triggers alerts if decibel thresholds are exceeded.
def start_speech_to_text(self): recognizer = sr.Recognizer() with sr.Microphone() as source: print("Say something:") recognizer.adjust_for_ambient_noise(source) audio = recognizer.listen(source) try: text = recognizer.recognize_google(audio) ...
def gaussian_blur(image, kernel_size): kernel = gaussian_kernel(kernel_size, sigma=math.sqrt(kernel_size)) return convolution(convert_to_grayscale(image), kernel) def sobel_edge_detection(blurred_img, filter): new_image_x = convolution(blurred_img, filter) new_image_y = convolution(blurred_img, np.flip(...
This function performs Canny edge detection on a binary image. It applies Gaussian blur to reduce noise, computes gradient magnitude and direction using a Sobel filter, applies non-max suppression to thin edges, thresholds the gradient with weak, low, and high values, and uses hysteresis to connect edges. It returns th...
def detect_canny_edges(img_bw, kernel_size=7, low=5, high=20, weak=50): blurred_image = gaussian_blur(img_bw, kernel_size) edge_filter = np.array([[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]]) gradient_magnitude, gradient_direction = sobel_edge_detection(blurred_image, edge_filter) canny_edges = non_max_suppress...
def create_hallways(self): # for i inr random integer between 0 and grid_size seed_node = (random.randint(0, self.grid_size), random.randint(0, self.grid_size)) self.hospital_graph.add_node(seed_node, type = 1) self.add_hallway_nodes(seed_node, self.grid_size) def calculate_hospital_node...
This code initializes a hospital layout using a grid graph, setting up medical roles, specialties, hallways, and nodes to model the hospital's structure and functionality.
def __init__(self, grid_size, instructions): self.grid_size = grid_size self.grid_graph = nx.grid_2d_graph(grid_size, grid_size) self.hospital_graph = nx.Graph() self.medical_role = instructions[0] self.specialty = instructions[1] self.create_hallways() self.calcu...
def calc_projected_retenion_month_tp(df): projected_retenion_month = [] wt_avg_ret_rt = calc_weighted_avg_retention_rate_tp(df) avg_ret_12_mths = calc_avg_retain_first_12_month_tp(df) for i in range(0, 60): if wt_avg_ret_rt[i] == 0: projected_retenion_month.append(projected_retenion...
This function calculates expected subscription duration (in months) and corresponding LTV without ad revenue for specified periods (3M, 6M, etc.) or all durations. It uses projected retention data and revenue figures from a given path, returning computed metrics as values or lists based on user input.
def calc_exp_dur_subs_mnths_and_LTV_CF_tp(df,path,given_inp=False): projected_retenion_month = calc_projected_retenion_month_tp(df) duration = 0 if given_inp == True: print('options 3M, 6M, 9M, 1Y, 2Y, 3Y, 4Y, 5Y, ALL') duration = input('Enter the Duration from above options') if durati...
def calc_projected_retenion_month_tp(df): projected_retenion_month = [] wt_avg_ret_rt = calc_weighted_avg_retention_rate_tp(df) avg_ret_12_mths = calc_avg_retain_first_12_month_tp(df) for i in range(0, 60): if wt_avg_ret_rt[i] == 0: projected_retenion_month.append(projected_retenion...
The function calculates the expected subscription duration in months and Lifetime Value (LTV) with and without ad revenue for a given plan and duration input. It computes these metrics using projected retention data, with options for specific time frames (3M, 6M, etc.) or all periods. Results are returned as single val...
def calc_exp_dur_subs_mnths_and_LTV_LC_tp(df,plan_cd,path, given_inp=False): projected_retenion_month = calc_projected_retenion_month_tp(df) duration = 0 if given_inp == True: print('options 3M, 6M, 9M, 1Y, 2Y, 3Y, 4Y, 5Y, ALL') duration = input('Enter the Duration from above options') ...
def calc_projected_retenion_month_bpsp(df, bill_part): projected_retenion_month = [] wt_avg_ret_rt = calc_weighted_avg_retention_rate_bpsp(df, bill_part) avg_ret_12_mths = calc_avg_retain_first_12_month_bpsp(df, bill_part) if bill_part == 'AMAZON': for i in range(0, 52): if wt_avg_r...
This function calculates expected subscription duration and Lifetime Value (LTV) without advertising revenue for specified timeframes (3M, 6M, etc.) or all periods. It uses projected retention data and revenue calculations, returning aggregated metrics for selected durations or comprehensive results for all periods.
def calc_exp_dur_subs_mnths_LTV_w_wo_revenue_CF_bpsp(df, bill_part,path, given_inp=False): projected_retenion_month = calc_projected_retenion_month_bpsp(df, bill_part) duration = 0 if given_inp == True: print('options 3M, 6M, 9M, 1Y, 2Y, 3Y, 4Y, 5Y, ALL') duration = input('Enter the Duratio...
def calc_projected_retenion_month_bpsp(df, bill_part): projected_retenion_month = [] wt_avg_ret_rt = calc_weighted_avg_retention_rate_bpsp(df, bill_part) avg_ret_12_mths = calc_avg_retain_first_12_month_bpsp(df, bill_part) if bill_part == 'AMAZON': for i in range(0, 52): if wt_avg_r...
This function calculates expected subscription duration (in months) and Lifetime Value (LTV) metrics with/without ad revenue for specified timeframes (3M, 6M, etc.) using projected retention data. It returns duration, LTV without ad revenue, and LTV with ad revenue (adding 1.95x ad revenue). For 'ALL', it returns resul...
def calc_exp_dur_subs_mnths_LTV_w_wo_revenue_LC_bpsp(df, bill_part,path, given_inp=False): projected_retenion_month = calc_projected_retenion_month_bpsp(df, bill_part) duration = 0 if given_inp == True: print('options 3M, 6M, 9M, 1Y, 2Y, 3Y, 4Y, 5Y, ALL') duration = input('Enter the Duratio...
def calc_projected_retenion_month_sm(df, month): projected_retenion_month = [] wt_avg_ret_rt = calc_weighted_avg_retention_rate_sm(df, month) avg_ret_12_mths = calc_avg_retain_first_12_month_sm(df, month) for i in range(0, 60): if wt_avg_ret_rt[i] == 0: projected_retenion_month.appe...
The function calculates expected subscription duration (in months) and Lifetime Value (LTV) metrics for a given time frame (e.g., 3M, 6M, 1Y) or all durations. It uses projected retention data, multiplies by base revenue (from `calc_conf_rev_bp`) and ad revenue (from `calc_ad_rev`), returning values rounded to 1 or 2 d...
def calc_exp_dur_subs_mnths_LTV_w_wo_revenue_sm(df, month,path,given_inp=False): projected_retenion_month = calc_projected_retenion_month_sm(df, month) duration = 0 if given_inp == True: print('options 3M, 6M, 9M, 1Y, 2Y, 3Y, 4Y, 5Y, ALL') duration = input('Enter the Duration from above opti...
def armor_f1(bl): return lambda x: 1 + 0.005 * (x - bl) ** 1.75 def normal_armor(bl): return lambda x: armor_f1(bl)(x) * (1 - S(x - bl, 70, 80)) + armor_f2(bl)(x) * S(x - bl, 70, 80) def armor_f2(bl): return lambda x: 1 + 0.4 * (x - bl) ** 0.75
The function `f(x)` adjusts the input `x` by subtracting a value `bl`, applies tiered armor-related transformations to `x` using conditional formulas based on `x`'s value ranges (e.g., 25–35, 35–50, etc.), scales results with specific coefficients, and returns the modified `y`. The adjustments involve piecewise functio...
def f(x): x -= bl y = armor_f1(0)(x) # x <= 25 y[25 < x] = (1.0 + 0.0125 * (x[25 < x] - 25)) * armor_f1(0)(x[25 < x]) y[35 < x] = (1.125 + (2/30) * (x[35 < x] - 35)) * armor_f1(0)(x[35 < x]) y[50 < x] = (1.375 + 0.005 * (x[50 < x] - 50)) * normal_armor(0)(x[50 < x]) y[10...
def google_sign_in(driver: webdriver.Chrome) -> None: ''' signs into google account ''' driver.get(properties["url"]["google_sign_in_url"]) # open google sign in page logging.debug(f'{properties["url"]["google_sign_in_url"]} opened') email_text = wait_and_find_element_by_xpath(driver, properties...
The code automates joining a Google Meet session via a headless Chrome browser, using a virtual display and audio sink. It initializes necessary services, signs into Google, navigates to the provided URL, joins the meeting, and monitors its status. On failure, it gracefully terminates processes, cleans up resources, an...
def main(url: str, output: str): start_pulseaudio() # start virtual display for headless display = Display(visible=False, size=(1366, 768)) display.start() opt = get_chrome_options(True) opt.add_argument("--lang=en-GB") driver = webdriver.Chrome(ChromeDriverManager().install(), options=op...
def has_event_started(driver: webdriver.Chrome, sink_name: str, display: Display) -> bool: """ returns boolean whether event has started """ if wait_and_find_element_by_xpath(driver, properties["xpath"]["event_started_text"], 2): return True elif wait_and_find_element_by_xpath(driver, proper...
The code automates a headless browser session to access a URL, log in, join an event, record the session, and manage audio settings. It initializes a virtual display, configures Chrome with specific options, waits for event/session start, records the meeting, switches to audio-only mode, and ensures proper cleanup on s...
def main(url: str, output: str) -> None: start_pulseaudio() # start virtual display for headless display = Display(visible=0, size=(1366, 868)) display.start() opt = get_chrome_options(allow_cam_mic=False) opt.add_argument("--window-size=1366,868") driver = webdriver.Chrome(ChromeDriverMa...
def join_meet(driver: webdriver.Chrome, audio_device: str) -> None: join_btn = wait_and_find_element_by_xpath(driver, properties["xpath"]["join_meet_btn"],4) if join_btn: join_btn.click() logging.debug("Clicked on 'Join my meeting'") save_nd_ctn_btn = wait_and_find_element_by_xpath(drive...
This code automates joining and recording online meetings via Chrome. It initializes a virtual display, launches a browser, navigates to a meeting URL, joins the session, records audio/video, monitors the meeting's active state, and cleans up resources. The script handles errors by terminating processes and releasing s...
def main(url: str, output: str): start_pulseaudio() # start virtual display for headless display = Display(visible=False, size=(1366, 768)) display.start() opt = get_chrome_options(True) opt.add_argument("--lang=en-GB") driver = webdriver.Chrome(ChromeDriverManager().install(), options=op...
def join_meet(driver: webdriver.Chrome, audio_device: str) -> None: """ joins the meet """ ''' sign_in_ele = wait_and_find_element_by_xpath(driver, "//*[contains(text(),'Sign in')]") if sign_in_ele: email_id_text = wait_and_find_element_by_xpath(driver, '//*[@id="i0116"]') email_...
The main task of the code is to automate joining a video meeting (likely Zoom or similar) using a headless Chrome browser with virtual display/audio setup. It initializes necessary services, navigates to a URL, handles meeting join流程, monitors the session, and performs cleanup on success/failure, including process term...
def main(url: str, output: str): start_pulseaudio() # start virtual display for headless display = Display(visible=False, size=(1024, 576)) display.start() opt = get_chrome_options(allow_cam_mic=True) opt.add_argument("--window-size=1024,576") opt.add_argument("--lang=en-GB") driver =...
def __init_working_set() -> list: """ Initialize the working set, taking data from xlsx file. :return: A list of lists. Each one represents a historical series. """ working_set = [] # Initialise an empty list for each series for i in range(0, COLUMNS): working_set.append([]) # op...
The main task of the code is to identify the maximum Spearman and Pearson correlation values between various weather data series and hospitalization data. It iterates through each dataset, calculates correlations between raw data, variation patterns, peak trends, and hospitalizations, updating the highest correlation v...
def main(): working_set = __init_working_set() spearman_max = [0.0, None] pearson_max = [0.0, None] hosp = Series(working_set[I_HOSPITALIZATIONS]) for i in working_index: # create a dataset with dates, current weather condition and hospitalizations series = Series(working_set[i]) ...