dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def snell(theta1): ''' snells(theta1) Calculates theta2 from snells law in radians. Parameters ---------- theta1: float Angle in to refracting surface. Returns ------- theta2: float Angle out of refracting surface. inputut Script Parameters ------------...
The function `Q_g(theta1)` computes a value based on Snell's law and reflection/transmission coefficients. It calculates a complex expression involving `R1(theta1)`, `T1(theta1)`, and angles `theta1` and `theta2` (derived via Snell's law). The formula combines sine and cosine terms of doubled angles, likely modeling wa...
def Q_g(theta1): theta2 = snell(theta1) return abs(R1(theta1) * np.sin(2 * theta1) - ( T1(theta1) ** 2 * (np.sin(2 * theta1 - 2 * theta2) + R1(theta1) * np.sin(2 * theta1))) / ( 1 + R1(theta1) ** 2 + 2 * R1(theta1) * np.cos(2 * theta2)))
def snell(theta1): ''' snells(theta1) Calculates theta2 from snells law in radians. Parameters ---------- theta1: float Angle in to refracting surface. Returns ------- theta2: float Angle out of refracting surface. inputut Script Parameters ------------...
The function `Q_s(theta1)` computes a value involving reflection (`R1`) and transmission (`T1`) coefficients, using Snell's law to determine the refracted angle (`theta2`). It combines these terms with trigonometric functions of doubled angles to calculate a result, likely related to optical wave interference or polari...
def Q_s(theta1): theta2 = snell(theta1) return 1 + R1(theta1) * np.cos(2 * theta1) - ( T1(theta1) ** 2 * (np.cos(2 * theta1 - 2 * theta2) + R1(theta1) * np.cos(2 * theta1))) / ( 1 + R1(theta1) ** 2 + 2 * R1(theta1) * np.cos(2 * theta2))
def free_propagate(self, distance): ''' Describe the ray state after the ray propagate for a distance :param distance: float The distance that the ray propagate :return list [x,y,theta,intensity] ''' state = self.ray_state[-1] # if state[2]...
This code simulates a light ray passing through a lens by calculating its interaction with two curved interfaces. It computes the ray's path after entering and exiting the lens, applying refraction at each surface using Snell's law. The function updates the ray's position, direction, and refractive index states, append...
def lens(self, f, position, thick): ''' The ray goes through the two inferfaces of the lens (into the droplet and out of the droplet). Describe the ray state after going through the lens interfaces, and two ray states are appended into self.ray_state list :param f: float foca...
def free_propagate(self, distance): ''' Describe the ray state after the ray propagate for a distance :param distance: float The distance that the ray propagate :return list [x,y,theta,intensity] ''' state = self.ray_state[-1] # if state[2]...
The code simulates a light ray passing through a circular droplet, calculating its interaction with the droplet's curved interfaces. It appends two ray states to `self.ray_state`: one after entering the droplet (refracting at the curved surface) and another after exiting (refracting again). The function handles both fr...
def circle_droplet(self, radius): ''' The ray goes through the two inferfaces of the circle droplet (into the droplet and out of the droplet). Describe the ray state after going through the circle droplet interfaces, and two ray states are appended into self.ray_state list :param radius:...
def get_service(reuse_creds: bool = True) -> Resource: '''Construct or return a service for interacting with the Calendar v3 API Args: reuse_creds: Whether or not to use credentials from previous runs. Returns: A Resource object that can interact with the Calendar v3 API ''' global ...
The code identifies Zoom events in non-primary calendars, renames them, moves them to the primary calendar, and returns a list of moved event summaries. It processes events from today, checks descriptions for Zoom indicators, updates event details, and logs actions.
def move_zoom_events(given_toast=None): if given_toast: global toast toast = given_toast service = get_service() events = service.events() primary_calendar_id = service.calendars().get(calendarId="primary").execute()["id"] calendars = get_calendar_list(ids=True) new_events = [] ...
def optical_axis(self, R, K, pupil, glint1, glint2, refraction_model, interval): """Calculate optical axis of eye (Section 3.3)""" v = pupil u1 = glint1 u2 = glint2 p = [] c = [] for idx in tqdm(range(0, pupil.shape[1], interval), ...
The function `single_gaze` computes the optical and visual axes for a light ray path through an eye model, using refraction calculations and eye parameters (alpha, beta). It determines the intersection point (`g`) of the visual axis with a scene surface, returning the optical axis (`w`), position (`p`), direction (`c`)...
def single_gaze(self, v, u1, u2, refraction_model, R, K, eye_alpha, eye_beta, interval=1): w, p, c = self.optical_axis(R, K, v, u1, u2, refraction_model, interval) v = self.visual_axis(w, ...
def player_move(myAction): dest = input("Were would you like to move to?\n>") if dest in ["up", "north"]: destination = zone_map[myPlayer.location][UP] movement_handeler(destination) elif dest in ["left", "west"]: destination = zone_map[myPlayer.location][LEFT] movement_hande...
This function processes user input for a text-based game, validating commands against a list of acceptable actions and triggering corresponding game functions like movement, examination, inventory checks, dialogue, or map viewing. It ensures input compliance, handles quitting, and routes actions to appropriate game mec...
def prompt(): print(f"\n=================================") print("What would you like to do") action = input("> ") acceptable_actions = ["use","inv","inventory","move", "go", "travle", "walk", "quit", "examine", "inspect", "look", "map", "look at map", "speek", "talk", "speek to someone", "quests"] ...
def initAnts(self) : for ant in self.ants : ant.clear() ant.visitNode(self.start, 0.0) def solveAnt(self, ant) : currentNode = self.start while(currentNode != self.end): nextNode = self.findNextNode(currentNode, ant.getVisited()) if(nextNode == -1)...
The main task of the code is to execute an iteration of an Ant Colony Optimization (ACO) algorithm. It initializes ants, evaluates each ant's trail length and weight, tracks the best trail(s) with minimal weight, and updates pheromones to guide future searches. If a new optimal trail is found or a unique trail with the...
def solveIteration(self) : self.initAnts() bestTrail = [] bestTrailWeight = 1e18 for ant in self.ants : self.solveAnt(ant) if (ant.getTrailLength() >= self.minTrailLength): if (ant.getTrailWeight() < bestTrailWeight) : bestTrail...
def initPheromones(self) : for i in range(self.numberOfNodes) : for j in range(self.numberOfNodes) : weight = float(self.getEdgeWeight(i,j)) # print(i, j, weight) if (weight != -1) : self.pheromones[i][j] = 1.0/weight #magnificatio...
This code implements an Ant Colony Optimization (ACO) algorithm to find the optimal path. It initializes pheromones, iterates through a set number of steps, generates trails with associated weights, and updates the best trail found if the current trail's weight is lower. If weights are equal, it checks for unique trail...
def solve(self) : # print('\n'.join(['\t'.join([str(cell) for cell in row]) for row in self.pheromones])) self.initPheromones() # print('\n'.join(['\t'.join([str(cell) for cell in row]) for row in self.pheromones])) for i in range(self.maxIterations) : # for i in range(100) : ...
def table_consistent(self) -> bool: df = self.table upper_table = df[df.index.get_level_values(0) == UPPER] # Explore only those elements that are in the upper table for actual_index, actual_row in upper_table.iterrows(): actual_state_name = actual_index[1] for ...
The code repeatedly saves the table state to CSV files, checks for table consistency and closure, and terminates when the correct automaton is identified, finally displaying the automaton.
def run(self): iteration = 0 while self.running: self.table.to_csv(f"table_{iteration}.csv") iteration += 1 if not self.table_consistent(): continue if not self.table_close(): continue if self.correct_automato...
def load_environment_variables(env_file: str) -> None: if os.path.isfile(env_file): # Load the environment variables from the .env file dotenv.load_dotenv(dotenv_path=env_file) logger.info("Loading environment variables.") else: logger.warning("File not found. Could not load envi...
This code provides a menu-driven tool for Reddit data processing and analysis, including fetching submissions, saving raw data, text processing, and generating BoW/TF-IDF similarity matrices. It integrates with MongoDB for storage, uses spaCy for NLP tasks, and handles user interactions through a command-line interface...
def main(): print("running main") load_environment_variables(env_variables_path) menu_options = ["get reddit submissions", "save raw submissions", "process raw submissions", "save cleaned submissions", "get cleaned submissions", "make BoW matrix", "make tfidf matrix"...
def ProcessUsingThresholdSegmentation(self) -> tuple: """ Returns (label or None, template or None) """ interestingRegionsBGR = GetLargestInterestingRegions(self._rawImgRGB, self._rawImgGray) templateFound = False labelFound = False label = None template = None ...
The code processes an image to identify a label and template. It first uses threshold segmentation; if unsuccessful, it applies brute-force methods (FindLabel, MatchTemplate) with specified parameters. If both label and template are found, it renames the image and returns True; otherwise, it returns False.
def Process(self) -> bool: label, template = self.ProcessUsingThresholdSegmentation() # Else try some brute force if not label: label = FindLabel(self._rawImgBGR, 12, 0.4, 2.0, 0.1) if not template: template = MatchTemplate(self._rawImgGray, 1.0, 10.0, 0.5) ...
def main_menu(): """ Displays the main menu for the SSH Management System. This function presents a table of options to the user, including connecting to SSH, executing commands, and exiting the program. """ table = Table( title="SSH Management System", show_header=False, title_style=B...
The main task of the code is to run an SSH Management System by reading configuration settings, initializing SSH controllers and command invokers, and providing a menu-driven loop for user interactions. It allows users to connect to a remote server, execute commands (including specific tasks like neofetch and file list...
def main(): """ Main function to run the SSH Management System. This function sets up the SSH connection configuration, initializes controllers and invokes, and provides a loop for user interaction with the system's menu. """ config = configparser.ConfigParser() config.read("config.in...
def randomly_place_all_ships(): fleet = [] while len(fleet) < 1: row = random.randint(0,9) column = random.randint(0,9) horizontal = random.randint(0,1) length = 4 if ok_to_place_ship_at(row, column, horizontal, length, fleet): place_ship_at(row, column, horiz...
The main task of the code is to implement a text-based battleship game where the player inputs coordinates to shoot at a randomly placed fleet. The game tracks hits, checks if ships are sunk, and determines victory when all ships are destroyed. It handles user input validation, updates the game state, and outputs resul...
def main(): current_fleet = randomly_place_all_ships() print(current_fleet) game_over = False shots = 0 win = False while not game_over: str = input("Enter row and column to shoot (separated by a space): ") if str == "quit": game_over = True elif re.match("[0-...
def get_grid_height(grid : List): height = 1000 for column in range(len(grid[0])): current_height = 0 row = 0 while row != len(grid)-1 and grid[row + 1][column] == (0,0,0) and current_height != height: current_height +=1 row += 1 if current_height < heigh...
The function identifies all possible moves for a game piece on a grid by analyzing the highest empty segments. It sorts these segments, explores paths from each starting position using `find_paths`, and aggregates valid final states into a list. The task involves checking each segment's edges, avoiding revisited positi...
def get_all_possible_moves(grid : List,current_piece : Piece): height = get_grid_height(grid) segment = get_heighest_empty_segment(grid,height) all_final_states = [] segment = sorted(segment.items(),key= lambda tup : tup[1],reverse = True) checked = [] for ((column,row),edge) in segmen...
def create_grid(locked_postions = {}): grid = [[(0,0,0) for _ in range(10)] for _ in range(20)] for (j,i) in locked_postions: grid[i][j] = locked_postions[(j,i)] return grid def get_shape(): return Piece (4,-2,0,random.choice(shapes)) def get_all_possible_moves(grid : List,current_piece : Piece...
The code simulates a Tetris-like game loop, generating possible moves for the current piece, selecting a random move, updating the grid with locked positions, checking for loss conditions, and cycling through pieces. The main task is to manage game state, render the grid, handle piece movement, and determine game over ...
def main(): grid = create_grid() change_piece = False score = 0 level = 0 run = True current_piece = get_shape() next_piece = get_shape() locked_positions = {} # clock = pygame.time.Clock() fall_time = 0 while run: grid = create_grid(locked_positions) possi...
def _get_db_table_name(self, frame): u"""Returns the MySQL TABLE name for the given pandas.DataFrame. :param frame: pandas.DataFrame. :return MySQL TABLE name. """ return self._table_prefix + self._get_db_name(frame.index.name) def _db_table_exists(table_name, conn): u"""Hel...
This function uploads an array of pandas.DataFrames to a MySQL database by iterating through each frame, determining the corresponding table name, creating the table if it doesn't exist, and then inserting/replacing data using SQL commands. The process ensures database schema alignment with the data structure and handl...
def _upload_frames_to_db(self, ticker, frames, conn): u"""Uploads the given array of pandas.DataFrames to the MySQL database. :param ticker: Morningstar ticker. :param frames: Array of pandas.DataFrames to be uploaded. :param conn: MySQL connection. ...
def _download(self, ticker, report_type): u"""Downloads and returns a pandas.DataFrame corresponding to the given Morningstar ticker and the given type of the report. :param ticker: Morningstar ticker. :param report_type: Type of the report ('is', 'bs', 'cf'). :return pandas.Da...
The code downloads financial data (income statement, balance sheet, cash flow) for a given Morningstar ticker, returning a dictionary of pandas DataFrames. If a MySQL connection is provided, it uploads the data to the database. It also includes metadata like period range, fiscal year-end, and currency.
def download(self, ticker, conn = None): u"""Downloads and returns a dictionary containing pandas.DataFrames representing the financials (i.e. income statement, balance sheet, cash flow) for the given Morningstar ticker. If the MySQL connection is specified then the downloaded financials...
def _parse_tables(response): u"""Parses the given csv response from financials.morningstar.com. :param response: Response from financials.morningstar.com. :return: List of pairs, where the first item is the name of the table (extracted from the response) and the second item is the corre...
This function downloads key financial ratios for a given Morningstar ticker from an API, parses the CSV response into pandas DataFrames, and optionally uploads them to a MySQL database. It handles errors for invalid tickers and adjusts currency notation. The parsed data includes profitability, growth, liquidity, and ef...
def download(self, ticker, conn = None, region = 'GBR', culture = 'en_US', currency = 'USD'): u"""Downloads and returns key ratios for the given Morningstar ticker. Downloads and returns an array of pandas.DataFrames containing the key ratios for the given Morningstar ticker. If the MySQL conne...
def dR_dE(self, E, corsika_id): Z, A = self.Z_A(corsika_id) return 1.0 / Z * (E + self.m_p * A) / np.sqrt(E**2 + 2 * self.m_p * A * E) def dN_dR(self, R, corsika_id, gen): return ( self.Q(R, gen) * self.lamba_esc(R) / (1 + self.lamba_esc(R) / self.f_norm[corsi...
This function calculates the derivative of N with respect to energy (E) using the chain rule. It multiplies the derivative of N with respect to R (dN/dR) by the derivative of R with respect to E (dR/dE). The result depends on energy (E), a corsika_id identifier, and a generation parameter (gen), which likely relates to...
def dN_dE(self, E, corsika_id, gen): return self.dR_dE(E, corsika_id) * self.dN_dR( self.R(E, corsika_id), corsika_id, gen )
def get_model(modelname, X_train, X_test, y_train, y_test, method="lime"): if modelname == "lr": model, acc = model_maker( "logistic regression", X_train, y_train, X_test, y_test ) return model, acc elif modelname == "xgb": model, acc = model_maker("xgb", X_train, y_t...
The function generates SHAP values for a machine learning model to explain feature importance, saves the results as a CSV file, and stores evaluation metrics. It uses the specified model and pathology data, processes training/test datasets, and outputs feature importances with model accuracy.
def run_shap(output_dir, X_train, X_test, y_train, y_test, modelname, features, patho, tag): print("run shap with", modelname, "model and", patho, "pathology") model, acc = get_model(modelname, X_train, X_test, y_train, y_test, method="shap") shap_feature_importances = shap_maker( model, X_test, y_t...
def get_model(modelname, X_train, X_test, y_train, y_test, method="lime"): if modelname == "lr": model, acc = model_maker( "logistic regression", X_train, y_train, X_test, y_test ) return model, acc elif modelname == "xgb": model, acc = model_maker("xgb", X_train, y_t...
The function `run_lime` generates LIME-based feature importances for a specified machine learning model using training and test data. It trains the model, computes feature importance scores via LIME, stores them in a CSV file, and saves results including accuracy. The task involves model explanation, feature analysis, ...
def run_lime(output_dir, X_train, X_test, y_train, y_test, modelname, features, patho, tag): print("run lime with", modelname, "model and", patho, "pathology") model, acc = get_model(modelname, X_train, X_test, y_train, y_test, method="lime") lime_feature_importances = lime_maker( model, X_test, y_...
def read_file(self, source_file, n_texts=-1): """Reads the entire corpus from a csv file as a list of strings. Args: source_file: (str) Path to a csv file that contains the entire corpus. n_texts: (int) If provided, only the first n_texts samples will be read from the co...
The code deduplicates a text corpus from a CSV file using Locality-Sensitive Hashing (LSH) and graph-based connected component analysis. It reads the input corpus, generates hash signatures, constructs an adjacency graph, identifies unique components, and saves the deduplicated result to a new CSV file. The process eff...
def deduplicate(self, source_file, target_file, n_texts=-1): """Removes duplicates from a given text corpus. On Google Colab, Runtime is roughly 30 minutes for the entire corpus. Args: source_file: (str) Path to a csv file that contains the unprocessed corpus. ...
def calculate_stats( data: pd.DataFrame, n_samples: int, statistics: Optional[List[SummaryStatistics]] = None, ): """ Calculate the summary statistics for all models given in `data`. :param data: DataFrame which holds all $d_A^S(x)$ values. The dataframe is expected to have two columns:...
The main task of the code is to generate a statistics table and three subplots visualizing experimental data from `data/minimal_distances.csv`. It reads the dataset, calculates statistical metrics, creates a structured statistics table, and plots trends for increasing observation numbers, alongside generating a complet...
def main() -> None: """ Create the statistics table and three subplots for the experimental data in `data/minimal_distances.csv`. """ setup_matplotlib() df = pd.read_csv(experiment_settings.OUT_PATH) print(calculate_stats(df, experiment_settings.SAMPLES_PER_MODEL)) models = create_stats(...
def from_jacobian(p: Tuple[int, int, int]) -> Tuple[int, int]: z = inv(p[2], P) return ((p[0] * z**2) % P, (p[1] * z**3) % P) def jacobian_multiply(a: Tuple[int, int, int], n: int) -> Tuple[int, int, int]: if a[1] == 0 or n == 0: return (0, 0, 1) if n == 1: return a...
This function performs elliptic curve scalar multiplication using Jacobian coordinates. It converts the input point to Jacobian coordinates, multiplies it by the scalar n using efficient Jacobian arithmetic, then converts the result back to standard coordinates.
def fast_multiply(a: Tuple[int, int], n: int) -> Tuple[int, int]: return from_jacobian(jacobian_multiply(to_jacobian(a), n))
def big_endian_to_int(value: bytes) -> int: return int.from_bytes(value, "big") def fast_multiply(a: Tuple[int, int], n: int) -> Tuple[int, int]: return from_jacobian(jacobian_multiply(to_jacobian(a), n)) def encode_raw_public_key(raw_public_key: Tuple[int, int]) -> bytes: left, right = ra...
This function converts a private key (bytes) to a public key (bytes) using elliptic curve cryptography. It first interprets the private key as a number, validates it against a threshold (N), multiplies the base point G by the private key to get the public key coordinates, then encodes these coordinates into byte format...
def private_key_to_public_key(private_key_bytes: bytes) -> bytes: private_key_as_num = big_endian_to_int(private_key_bytes) if private_key_as_num >= N: raise Exception("Invalid privkey") raw_public_key = fast_multiply(G, private_key_as_num) public_key_bytes = encode_raw_public_key(raw_public_k...
def Animation(Object,vertices,animations): value = vertices for animation in animations: # Checks for animations if animation[0:9] == "Transform": value = Transform(vertices,[Object.position],int(animation[10:len(animation)]),animation[9]) vertices = value if an...
This function converts 3D vertices into 2D screen coordinates by applying player rotation, animation, and perspective projection using field of view and aspect ratio calculations. It adjusts vertex positions relative to the player's position, applies Y/X-axis rotations, calculates scaled coordinates based on depth (Zr)...
def Get_screen_position(Player, vertices,Object="None", animation="None"): # Animation if animation != "None": [vertices] = Animation(Object,[vertices],animation) Xr0 = vertices[0] - Player.position[0] Yr0 = vertices[1] - Player.position[1] Zr0 = vertices[2] - Player.position[2] if Zr0 ...
def draw_text_on_screen(text,position=(0,0),size = 40): font = pygame.font.SysFont(None, size) img = font.render(f"{text}", True, BLACK) screen.blit(img, position) def matrix_0Add_1Subtract(matrix1,matrix2,option=0): # option 0 is add, 1 is subtract a = 1 if option == 1: a = -1 Clen = le...
This code calculates joint angles (sita1, sita2, phi) and vertex positions for a robotic leg mechanism based on a target position. It uses trigonometry to determine limb orientations, updates 3D coordinates, and renders the leg's visual representation on-screen with debug information. The function handles coordinate tr...
def update(self,player,required_position=None): if(required_position!=None): [x,y,z] = [-required_position[0],required_position[1],required_position[2]] # if(self.name=="L2"): # print(int(-required_position[0])/10,int(required_position[1])/10,int(required_position[2])/10)...
def scene2LookAround(self): """Controls order of all 'look around' actions in scene 2.""" if self.lookAround1 == False: cprint(''' You walk over to the pirate and check his pulse. Dead. You notice his weapon was badly damaged in the battle. You do notice a key card in his satchel, and decide...
This code handles user interactions in a game scene by presenting six options (e.g., exploring, viewing stats, using items) and executing corresponding methods based on input. It includes a confirmation prompt for the "give up" option, triggering game over or returning to the scene. The core task is to manage player ch...
def sceneTwo(self): """Main actions for Scene 1""" action = '' while action != "1" and action != "2" and action != "3" and action != "4" and action != "5" and action != '6': action = input(''' What would you like to do? 1. Look Around. 3. Special Action. 5. Rest. 2. Show Sta...
def lstm_ortho_initializer(scale=1.0): def _initializer(shape, dtype=tf.float32, partition_info=None): size_x = shape[0] size_h = shape[1]//4 # assumes lstm. #print(shape, size_x, size_h) #input() t = np.zeros(shape) t[:, :size_h] = orthogonal([size_x, size_h])*scale t[:, size_h:size_h*2] ...
This code implements a custom LSTM cell with hypernetwork modulation. It processes input and hidden states, computes gates (input, forget, output) using hypernetwork-modulated weights and biases, applies layer normalization and recurrent dropout, and returns the new hidden state along with a combined state that merges ...
def __call__(self, x, state, timestep = 0, scope=None): with tf.variable_scope(scope or type(self).__name__): total_c, total_h = state c = total_c[:, 0:self.num_units] h = total_h[:, 0:self.num_units] hyper_state = tf.contrib.rnn.LSTMStateTuple(total_c[:,self.num_units:], ...
def drum_ortho_initializer(scale=1.0): def _initializer(shape, dtype=tf.float32, partition_info=None): size_x = shape[0] size_h = shape[1]//2 # assumes drum. t = np.zeros(shape) t[:, :size_h] = orthogonal([size_x, size_h])*scale t[:, size_h:size_h * 2] = orthogonal([size_x, size_h])*scale retu...
This code implements a custom LSTM cell with hypernetwork components. It processes input and hidden states, computes hypernetwork outputs, applies learned transformations, and generates new hidden states using update/reset gates. The function returns updated hidden states and LSTM state tuples, incorporating normalizat...
def __call__(self, x, state, timestep = 0, scope=None): with tf.variable_scope(scope or type(self).__name__): c, total_h = state h = total_h[:, 0:self.num_units] hyper_state = tf.contrib.rnn.LSTMStateTuple(c, total_h[:,self.num_units:]) w_...
def findFiles(recurse, paths): WILDCARD = "*" #process the list of input paths for root in paths: #WILDCARD IN PATH OR FILENAME #In Linux wilcard expansion done by bash so, add file to list if os.path.isfile(root): existingFiles.append(root) #Windows (& Linux w...
The main task of the code is to check input paths for existing files, process them by analyzing each file, generate XML output with UTF-8 encoding, and handle Python version differences (2.x/3.x) for proper output formatting. It wraps XML in a <results> tag if specified, writes the XML declaration, and outputs analysis...
def checkFiles(recurse, wrap, paths): # This method checks the input argument path(s) for existing files and analyses them #Find existing files in the given input path(s) findFiles(recurse, paths) # If there are no valid input files then exit program # JvdK: checkNoInput(existingFiles) #...
def parseCommandLine(): # Add arguments parser.add_argument('--verbose', action = "store_true", dest = "outputVerboseFlag", default = False, help = "report test results in verbose format") """ parser.add_argument('--recursive', '-r', action = "store_true", ...
The main task of the code is to process command-line arguments for image validation, check input files, configure verbosity settings for modules like 'boxvalidator.py', and generate a closing XML tag if specified. It parses inputs, validates file existence, and prepares output formatting based on provided flags.
def main(): # Get input from command line args=parseCommandLine() # Input images jp2In=args.jp2In # Print help message and exit if jp2In is empty if len(jp2In) == 0: printHelpAndExit() # Storing this to 'config.outputVerboseFlag' makes this value available to any m...
def initialize_brain(statelist): brain = np.zeros(statelist.shape) for i, state in enumerate(statelist): idx = state==0 s = np.sum(idx) if s > 0: brain[i, idx] = 1/s return brain def evaluate(brain, statelist, brain0=None): if brain0 is None: brain0 = initialize_brain...
The code trains a neural network (brain) through reinforcement learning by simulating games against itself and a reference brain (brain0). It iteratively plays games, updates the brain's parameters based on wins/losses, and periodically evaluates performance. The training loop runs for a specified number of rounds, adj...
def train(statelist = None, brain = None, rounds = 1_000_000, rate = 0.03): if statelist is None: print('boop!') statelist = initialize_statelist() if brain is None: brain = initialize_brain(statelist) brain0 = initialize_brain(statelist) evaluation_history = [] evaluate_step = int...
def initialize_brain(statelist): brain = np.zeros(statelist.shape) for i, state in enumerate(statelist): idx = state==0 s = np.sum(idx) if s > 0: brain[i, idx] = 1/s return brain def game(statelist, brain1, brain2, state = np.zeros(9)): winner = 0 decisions = [] ...
The function trains a neural network (brain) using reinforcement learning by iterating through states in statelist, playing games to update the brain's weights based on rewards (w), and evaluating the trained model's performance. It skips invalid states, reorders states by move count, and returns the optimized brain af...
def train_by_state(statelist = None, brain = None, rate = 0.03): if statelist is None: print('boop!') statelist = initialize_statelist() if brain is None: brain = initialize_brain(statelist) brain0 = initialize_brain(statelist) statelist_move_counter = np.sum(np.abs(statelist), axis = 1...
def add_sidebar(): st.sidebar.header("Cell Nuclei Measurements") data = get_clean_data() input_dict = {} slider_labels = [ ("Radius (mean)", "radius_mean"), ("Texture (mean)", "texture_mean"), ("Perimeter (mean)", "perimeter_mean"), ("Area (mean)", "area_mean"), ...
The main task of the code is to create a Streamlit web app named "Cancer Predictor" that uses a machine learning model to analyze cytology lab data and predict whether a mass is benign or malignant. The app allows users to input or adjust measurements via a sidebar, visualizes data with a bar chart, displays prediction...
def main(): st.set_page_config( page_title="Cancer Predictor", page_icon=":female-doctor:", layout="wide", initial_sidebar_state="expanded" ) input_data = add_sidebar() with st.container(): st.title("Cancer Predictor") st.write("This app is designed t...
def cheap_remove_redundant_constraints(A: numpy.ndarray, b: numpy.ndarray) -> List[numpy.ndarray]: """ Removes zero rows, normalizes the constraint rows to ||A_i||_{L_2} = 1, and removes duplicate rows :param A: LHS constraint matrix :param b: RHS constraint column vector :return: The processes' co...
The code's main task is to remove both strongly and weakly redundant constraints from a linear system defined by matrices $ A $ and $ b $. It first applies a quick method (`cheap_remove_redundant_constraints`) to eliminate obvious redundancies, then uses an expensive LP-based solver (`remove_strongly_redundant_constrai...
def process_region_constraints(A: numpy.ndarray, b: numpy.ndarray, deterministic_solver: str = 'gurobi') -> List[ numpy.ndarray]: """ Removes all strongly and weakly redundant constraints :param A: LHS constraint matrix :param b: RHS constraint column vector :param deterministic_solver: the exa...
def getPromoTitle(deal): return deal.select('a.color-blue.app-link')[0].text def getPromoLink(deal): links = deal.select('a') link = links[0].get('href') # get url to go to the deal page return link def getPromoInfo(deal_soup): infos = deal_soup.select('div.product-desc') info = infos[0].select(...
The code scrapes product data from Chope's best-sellers page by scrolling to load all items, parsing HTML with BeautifulSoup, extracting details like titles, links, vouchers, and images, and returning adjusted data after processing.
def get_webscrape_data(): ## selenium used to scroll to the bottom of the page options = Options() options.add_argument("--headless") driver = webdriver.Chrome(options=options) driver.get("https://shop.chope.co/collections/best-sellers") SCROLL_PAUSE_TIME = 0.5 # Get the height of the pag...
def get_request(self, query_data): file = self.get_cache_filename(query_data) if os.path.isfile(file): #logging.info("Entry exists") with open(file) as data_file: data = json.load(data_file) return data else: #logging.info("Entry ex...
This function sends a request to the SEMrush API using provided query data, handles errors (e.g., non-200 status codes, specific error messages), processes the response into a structured object, caches results if no error occurs, and returns the processed data or None on failure. It prioritizes cached results if availa...
def sem_request(self, query_data=None): cres = self.get_request(query_data) if cres is None: url = "{}".format(self.api_url) query_data["key"] = self.api_key result = requests.get(url, params=query_data) if result.status_code != 200: error_...
def form_permutation_of_numbers(self): permutations = [] permutation_object = itertools.permutations(self.numericals) for permutation in permutation_object: permutations.append(permutation) return permutations def form_permutation_of_operators(self): permutations = ...
This code initializes a class to generate and verify mathematical expressions using given numbers and operators. It creates permutations of numbers and operators, constructs all possible expressions with parentheses, evaluates them, and checks if any combination equals 24. The main task is to determine if the provided ...
def __init__(self, hand): self.hand = hand self.numericals = self.hand.numericals self.operators = ['+', '-', '*', '/'] self.parenthesis_lists = [ [], [[0, 1]], [[1, 2]], [[2, 3]], [[0, 2]], [[1, 3]], [[...
def getNameOfCsvFiles(): all_files = listdir("database") csv_files = list(filter(lambda f: f.endswith('.csv'), all_files)) return csv_files def creatingDfsDictionary(csvFileList): dictionary = {name: pd.read_csv(f'database/{name}') for name in csvFileList} dictionary = deleteColumnOnDict(dict...
The code identifies the most frequently occurring publisher in each book category across multiple CSV files. It processes each category by filtering data, calculating the mode of the 'Publisher' column, and handling cases with multiple modes. The result is a DataFrame mapping each category to its most prevalent publish...
def mostPresentPublisher(): csvFilesName = getNameOfCsvFiles() dictionary = creatingDfsDictionary(csvFilesName) dataFrame = creatingGeralDF() mostFrequentdict = {} for category in dictionary: tempDf = dataFrame.query(f'Category == "{category[:-4]}"') frequentPublisher = tempDf['Publi...
def getImageData(imgPath): isImageAlreadyStored imgData = {} with open(imgPath + '.json') as datafp: data = json.load(datafp) if ("folders" not in data): data['folders'] = ["None"] imgData["ARTIST_ID"] = data['author']['userid'] imgData["ARTIST_NAME"] = data['author']['username']...
The main task of the code is to load an image, check if it's already stored, retrieve artist data, generate a unique filename, convert and move the image to a gallery directory, insert image data into a database, and associate it with galleries. It returns the image ID on success or -1 if any step fails, logging errors...
def load_image(imgPath): imgData = getImageData(imgPath) if isImageAlreadyStored(imgData["IMAGE_INDEX"]): print("IMAGE ALREADY STORED: " + str(imgData["IMAGE_INDEX"])) return -1 (artist_id, artist_dir) = getArtistData(imgData["ARTIST_ID"], imgData[...
def LoadFNG(mode): #Obtain FNG index data from API url = "https://api.alternative.me/fng/?limit=2000&format=csv&date_format=kr" response = requests.get(url) json_text = response.text index = 0 dataStartFound = False #Turn JSON response into csv for char in json_text: if char == ...
The function `GetDataset` loads and combines financial datasets (FNG, CPI-U, FEDFunds) based on the `mode` parameter, which dictates data preparation methods like "constant", "interpolate", or "model fill". It checks if CSV files exist; if not or if `reload=1`, it loads/prepares data using specified modes. If `mode` is...
def GetDataset(reload, mode): #mode = constant, interpolate, or model fill # Check if datasets have been prepared, if not, run corresponding functions if mode == "rf" or mode == "lr": modelfill_mode = mode mode = "modelfill" if not exists("FNG_Daily.csv") or reload == 1: print("Loadi...
def GetDataset(reload, mode): #mode = constant, interpolate, or model fill # Check if datasets have been prepared, if not, run corresponding functions if mode == "rf" or mode == "lr": modelfill_mode = mode mode = "modelfill" if not exists("FNG_Daily.csv") or reload == 1: print("Loadi...
The `TrainLSTM` function trains an LSTM model using specified hyperparameters on financial data, evaluates its performance (AUC, accuracy, precision, recall, F1), and optionally simulates trading strategies based on predictions. It processes data by dropping features, splits into training/test sets, trains the model it...
def TrainLSTM(removed_features, async_mode, hp_choices, iterations, display_choice, trading_choice): # Unpack hyperparameters batch_size = hp_choices['batch_size'] epochs = hp_choices['epochs'] dropout = hp_choices['dropout'] lstm_cells = hp_choices['lstm_cells'] days_to_use = hp_choices['days_...
def GetDataset(reload, mode): #mode = constant, interpolate, or model fill # Check if datasets have been prepared, if not, run corresponding functions if mode == "rf" or mode == "lr": modelfill_mode = mode mode = "modelfill" if not exists("FNG_Daily.csv") or reload == 1: print("Loadi...
The main task of the code is to perform a hyperparameter grid search for an LSTM model using specified ranges, evaluate each combination's performance on financial data, and save metrics like AUC, accuracy, return, and risk measures to a CSV file. It iterates through all hyperparameter combinations, trains models, runs...
def HyperparameterGridSearch(r_features, hp_ranges, display_choice, trading_choice, iterations, mode): # Get our combined features dataset, specify whether to interpolate, forward-fill (constant), or model fill reload = 1 Combined_df = GetDataset(reload, mode) # Drop specified features if needed (used...
def GetTechnicalIndicatorDataset(): BTC_df, labels = CreateLabels() BTC_df = BTC_df.drop(['unix', 'symbol', 'volume BTC', 'tradecount'], axis = 1) BTC_df = BTC_df.rename(columns = {'volume USDT': 'volume', 'fng_value': 'fng', 'value': 'inflation'}) BTC_df = BTC_df[::-1] labels = labels[::-1] r...
The function trains a Random Forest classifier on financial data, adjusting datasets for model compatibility, evaluating performance via ROC curves, and optionally visualizing feature importances and trading simulations. It processes input data, trains the model with specified hyperparameters, predicts outcomes, and re...
def TrainRandomForest(removed_features, async_mode, trading_choice, display_choice, dataset_choice, hp_choices, hp_testing): reload = 1 tree_count = hp_choices[0] tree_depth = hp_choices[1] feature_count = hp_choices[2] if dataset_choice == "technical": Combined_df = GetTechnicalIndicatorD...
def GetTechnicalIndicatorDataset(): BTC_df, labels = CreateLabels() BTC_df = BTC_df.drop(['unix', 'symbol', 'volume BTC', 'tradecount'], axis = 1) BTC_df = BTC_df.rename(columns = {'volume USDT': 'volume', 'fng_value': 'fng', 'value': 'inflation'}) BTC_df = BTC_df[::-1] labels = labels[::-1] r...
The function trains a logistic regression model on financial data using specified hyperparameters, evaluates its performance with ROC metrics, and optionally runs trading simulations. It processes input data, drops features, prepares training/test sets, trains the model, predicts on test data, computes ROC AUC, and vis...
def TrainLogisticRegression(removed_features, days_to_use, async_mode, trading_choice, display_choice, dataset_choice, hp_choices, hp_testing): reload = 1 penalty = hp_choices[0] c = hp_choices[1] if dataset_choice == "technical": Combined_df = GetTechnicalIndicatorDataset() else: ...
def fetch_raw_data_from_db(): with app.app_context(): results = db.session.query(Values.id, Values.value_a, Values.value_b, Values.datetime).all() df = DataFrame(results, columns=['id', 'Value_a', 'Value_b', 'datetime']) return df def correlation(df, new_values_id_and_datetime): correlat...
The main task of the code is to compute statistical metrics (correlation, standard deviation, and max-min difference) by combining raw data fetched from a database with new input values containing IDs and timestamps.
def statistics_processes(new_values_id_and_datetime): raw_data_df = fetch_raw_data_from_db() correlation(raw_data_df, new_values_id_and_datetime) standard_deviation(raw_data_df, new_values_id_and_datetime) max_min_diff(raw_data_df)
def call_data_web_service(): response = requests.get('http://127.0.0.1:5000/params').json() a = response.get('a') b = response.get('b') print('received values:', a, b) return a, b, datetime.datetime.now() def insert_data_to_db(a, b, fetch_time): with app.app_context(): new_value = Values...
The main task of the code is to fetch data from a web service, insert it into a database, and process it for statistics. It logs the start and end times of the task and separates each execution with a delimiter.
def task_one(): print(f'start task one in: {datetime.datetime.now()}') a, b, fetch_time = call_data_web_service() new_values_id_and_datetime = insert_data_to_db(a, b, fetch_time) statistics_processes(new_values_id_and_datetime) print(f'end task one in: {datetime.datetime.now()}') print('--------...
def validate_move(column=None, row=None, game=None): valid_initial_columns = [MIN_VALUE, MAX_VALUE] matrix = game.matrix prev_value = matrix[row][column] if prev_value == 0 and MIN_VALUE <= column <= MAX_VALUE: if column in valid_initial_columns: return {'is_valid': True} eli...
The function processes a game move by validating the input, updating the game matrix with the user's code, checking for a win or tie, and handling subsequent actions. If valid, it updates the matrix, checks for a win, and returns the result. If the game is PVE, it triggers AI moves; otherwise, it switches turns. The fu...
def process_game(column=None, row=None, user=None, game=None): column, row, game = int(column), int(row), int(game) game = Game.objects.get(pk=game) result = validate_move(column, row, game) if result['is_valid']: matrix = game.matrix matrix[row][column] = game.get_user_code(user) ...
def _connect(self): try: connection = pymssql.connect( host=self.host, port=self.port, server=self.server, database=self.database, user=self.user, password=self.password ) except Con...
The code's main task is to perform SQL inserts in batches during a specified timeframe. It inserts 'rows_per_batch' rows per batch, repeating for 'nr_of_batches' times, with 'time_between_batches' seconds between each batch. The method connects to the database, executes inserts, prints progress, waits between batches, ...
def start(self): """ Perform SQL inserts during a given timeframe (job_duration). At each insert, insert 'rows_per_batch' nr of rows, at intervals of 'time_between_batches' seconds. """ self._connect() for batch_nr in range(self.nr_of_batches): self._insert...
def filterTransactions(startDate, endDate): startDate = pd.to_datetime(startDate) endDate = pd.to_datetime(endDate) transactionsList['Date'] = pd.to_datetime(transactionsList['Date']) filteredTransactions = transactionsList.loc[ (startDate <= transactionsList['Date']) & (transactionsList['Date']...
The function generates a summary DataFrame of stock portfolio performance on a given date, calculating current values, average buy prices, and gain/loss metrics for each stock. It aggregates transaction data, computes financial metrics, and structures results into a DataFrame with columns for symbols, quantities, price...
def makeSummaryDF(thisDay): # print(thisDay) transactions = filterTransactions('2000-01-01', thisDay) names = getStocksList(transactions) quantities = getCurrentQuantities(names, transactions) spentOnly = np.round(getAmountSpent(names, transactions), 2) earnedOnly = np.round(getAmountEarned(nam...
def lookupPriceFromTable(tickerSymbolList, startDate, endDate): # this is distinguished currently from the script lookupOnlyDifference because that script updates the data base each search and I'm not sure that's what we want here startDate = pd.to_datetime(startDate).date() endDate = pd.to_datetime(endDat...
The code calculates portfolio gain/loss percentages over a specified time period, comparing them to the VTI index's performance. It generates a time series showing daily portfolio value changes relative to an average baseline, normalized to percentages, and returns this series alongside adjusted VTI data for comparativ...
def generateGainLossOverTime(startDate, endDate): # stringToday = str(date.today()) # startDate = '2017-02-01' startDateObj = pd.to_datetime(startDate) endDateObj = pd.to_datetime(endDate) diffDays = pd.Timedelta(endDateObj - startDateObj).days nPoints = 50 frequency = max(round(diffDays / ...
def find_mean(X): result = 0 for i in range(np.size(X,0)): result += X[i][0] if np.size(X,0) == 0: return 0 else: return result/np.size(X,0) def create_node(X, selected_features): cost = math.inf best_feature = 0 best_split_pt = 0 for j in selected_features: for i in range(np.size(X,0)): temp_cost ...
The code recursively builds a decision tree by selecting random features, finding the optimal split point, and partitioning data into left/right subsets. It creates internal nodes with feature/split info and assigns mean target values to leaves when depth limits are reached, using a binary tree structure with node indi...
def create_tree(current_depth, node, X): if np.size(X,0) == 0: return if current_depth == depth: y_mean = find_mean(X) leaves[node] = y_mean return #draw random subset of m features selected_features = dict() F = np.size(X,1)-1 #no. of features for i in range(m): val = random.randint(1,F) while val...
def choose_bucket_prefix(template, max_len=30): """ Choose a prefix for our test buckets, so they're easy to identify. Use template and feed it more and more random filler, until it's as long as possible but still below max_len. """ rand = ''.join( random.choice(string.ascii_lowercase +...
The main task of the code is to initialize S3 test configurations by reading a specified config file, validating required sections and parameters, setting default values, configuring SSL settings, and cleaning up existing test buckets with a predefined prefix. It prepares the environment for S3-related tests by ensurin...
def setup(): cfg = configparser.RawConfigParser() try: path = os.environ['S3TEST_CONF'] except KeyError: raise RuntimeError( 'To run tests, point environment ' + 'variable S3TEST_CONF to a config file.', ) cfg.read(path) if not cfg.defaults(): ...
def get_alt_client(client_config=None): if client_config == None: client_config = Config(signature_version='s3v4') client = boto3.client(service_name='s3', aws_access_key_id=config.alt_access_key, aws_secret_access_key=config.alt_secret_key, ...
The code's main task is to clean up AWS resources by deleting S3 buckets with a specified prefix using multiple clients, removing IAM roles and their attached policies, and deleting OpenID Connect providers. It handles exceptions silently to ensure teardown processes complete without interruption, typically used for te...
def teardown(): alt_client = get_alt_client() tenant_client = get_tenant_client() nuke_prefixed_buckets(prefix=prefix) nuke_prefixed_buckets(prefix=prefix, client=alt_client) nuke_prefixed_buckets(prefix=prefix, client=tenant_client) try: iam_client = get_iam_client() list_roles_...
def _sql_to_pd(db, table): """Read sql table into pandas DataFrame.""" conn = sqlite3.connect(db) query = 'SELECT * FROM {}'.format(table) return pd.read_sql_query(query, conn) def _df_to_clean_txt(df, name, split, dataset_name): """Writes pandas speaker DataFrame to text file, with each row ...
The main task of the code is to process datasets (SQL/CSV) into text files, generating train/test splits for speakers and pre-training data excluding target speakers. It reads SQL data into a DataFrame, creates cleaned text files, and handles movie lines data by cleaning and splitting into train/test sets for downstrea...
def main(): parser = argparse.ArgumentParser() parser.add_argument('--file_type', type=str, default='sql', help='Type of file data is stored (sql or csv).') parser.add_argument('--file_name', type=str, default=None, ...
def _get_show_ap_summary(self): command = "show ap summary" raw_command_output = self._send_command(command) parsed_cisco_wlc_show_ap_summary = textfsm_extractor( self, "cisco_wlc_show_ap_summary", raw_command_output ) return parsed_cisco_wlc_show_ap_summary def _get_...
The main task of the code is to retrieve and aggregate facts about access-points (APs) connected to a Cisco Wireless LAN Controller (WLC). It compiles data such as AP MAC addresses, serial numbers, models, uptime, and interface lists from multiple parsed command outputs. The result is a list of dictionaries, each conta...
def get_ap_facts(self): """ This method will return facts for the access-points connected to this wlc The result will be a list of dictionaries, where each item in the list represents an access-point """ result = [] # Get the AP summary and their interfaces list ...
def get_show_redundancy_summary(self): command = "show redundancy summary" raw_command_output = self._send_command(command) parsed_show_redundancy_summary = textfsm_extractor( self, "cisco_wlc_show_redundancy_summary", raw_command_output ) return parsed_show_redundanc...
This function generates structured inventory data for Cisco Wireless LAN Controller (WLC) High Availability (HA) pairs. It checks the device's redundancy state (active/standby) and returns a list of two dictionaries containing model, serial number, position (1/2), and management IP addresses for primary and secondary W...
def get_multi_device_structured_inventory(self, deployment_mode): """ Structured data for switch stacks: [ { 'position': int(), 'model': str(), 'serial': str(), } , { } , ... ] :param deployment_mode: :param parsed_cisco_ios_show_inven...
def get_show_sysinfo_structured(self): command = "show sysinfo" raw_command_output = self._send_command(command) parsed_cisco_wlc_show_sysinfo = textfsm_extractor( self, "cisco_wlc_show_sysinfo", raw_command_output ) return parsed_cisco_wlc_show_sysinfo def get_show_i...
The `get_facts` method collects and returns device information as a dictionary, including uptime, vendor (hardcoded as Cisco), serial number, model, hostname, FQDN, interfaces, and OS version. It retrieves structured data from `show_sysinfo` and `show_inventory`, parses uptime, and compiles results into a standardized ...
def get_facts(self): """ Returns a dictionary containing the following information: uptime: Uptime of the device in seconds. vendor: Manufacturer of the device. serial_number: Serial number of the device. model: Device model. hostname: Hostname of the device. ...
def get_show_failover_structured(self, mate=False): if mate: command = "failover exec mate show failover" else: command = "show failover" raw_command_output = self._send_command(command) parsed_cisco_ios_show_failover = textfsm_extractor( self, "cisco...
The function retrieves structured inventory data for a switch stack in a failover setup. It validates deployment mode, failover status, and chassis information, then returns a list of devices with position, model, serial, and IP addresses. It ensures failover is active, interfaces are up, and correctly identifies prima...
def get_multi_device_structured_inventory(self, deployment_mode): """ Structured data for switch stacks: [ { 'position': int(), 'model': str(), 'serial': str(), } , { } , ... ] :return: """ if deployment_mode in [DeploymentMode...
def encode(): clear() print(banner_encode) while True: inp = input("Enter Text: ") # Check back to menu case if inp == '\\b': clear() print(banner_main) break # Check quit case check_quit(inp) # Check clear command ...
The code provides a menu-driven interface for encoding, decoding, testing, or clearing the screen. It continuously displays options, processes user input to call corresponding functions, and exits when the user selects "\q". The loop handles invalid inputs by prompting again, ensuring interactive control over operation...
def main(): print(banner_main) while True: print(menu) inp = input("Select operation:") if inp == "\q": exit() elif inp == '1': encode() elif inp == '2': decode() elif inp == '3': test() elif inp == '': ...
def gen_acc_num(): return random.randint(1000000000, 9999999999) def options(name, id): print(f'Date: {date}') print('\n') print(f'Welcome {name}, your account number is {accout_number[id]}') bankOperations()
The main task of the code is to register a new user by collecting their name, password, and re-entered password. If the passwords match, it stores the user's details in lists, generates an account number, and directs them to options. If the passwords mismatch, it prompts re-registration.
def register(): print('Please fill the form below to Register') name = input('Name: ') password = input('Password: ') retype = input('Retype Password: ') if password == retype: allowed_password.append(password) allowed_users.append(name) accout_number.append(gen_acc_num()) ...
def gen_acc_num(): return random.randint(1000000000, 9999999999) def login(): name = input("What is your name: \n") if name in allowed_users: password = input("Your Password: \n") user_id = allowed_users.index(name) if password == allowed_password[user_id]: options(name...
The code's main task is to handle user authentication in an ATM system by generating account numbers for allowed users and prompting them to either login or register. It directs users to respective functions based on their input, ensuring proper authentication flow with error handling for invalid responses.
def atm(): for i in range(len(allowed_users)): accout_number.append(gen_acc_num()) mode = input('Login (L) or Register (R): ').upper() if mode == 'L': login() elif mode == 'R': register() else: print('Invalid Response')
def draw_path(path2d, z=DRAW_Z, **kwargs): if path2d is None: return [] #return list(flatten(draw_pose(pose_from_pose2d(pose2d, z=z), **kwargs) for pose2d in path2d)) #return list(flatten(draw_pose2d(pose2d, z=z, **kwargs) for pose2d in path2d)) base_z = 1. start = path2d[0] mid_yaw = st...
The function processes a robot's motion path by adjusting it, discretizing it into time steps, optionally smoothing collisions, and simulating or executing the path with velocity/acceleration constraints.
def iterate_path(robot, joints, path, simulate=True, step_size=None, resolutions=None, smooth=True, **kwargs): # 1e-2 | None if path is None: return path = adjust_path(robot, joints, path) with LockRenderer(): handles = draw_path(path) waypoints = path #waypoints = waypoints_from_pa...
def problem1(n_obstacles=10, wall_side=0.1, obst_width=0.25, obst_height=0.5): floor_extent = 5.0 base_limits = (-floor_extent/2.*np.ones(2), +floor_extent/2.*np.ones(2)) floor_height = 0.001 floor = create_box(floor_extent, floor_extent, floor_height, color=TAN) set_point(floor,...
(The main task of the code is to perform motion planning for a robotic arm using algorithms like RRT-connect. It parses command-line arguments to configure parameters such as collision checking, obstacle count, and planning algorithm. The code initializes a robotic problem, sets up environmental constraints, and genera...
def main(): np.set_printoptions(precision=N_DIGITS, suppress=True, threshold=3) # , edgeitems=1) #, linewidth=1000) parser = argparse.ArgumentParser() parser.add_argument('-a', '--algorithm', default='rrt_connect', # choices=[], help='The motion planning algorithm to use.') pars...
def build_grid_world(self): # Get the locations of all the valid states, the neighbours of each state (by state number), # and the absorbing states (array of 0's with ones in the absorbing states) locations, neighbours, absorbing = self.get_topology() # Get the number of states ...
The code initializes a Gridworld environment for reinforcement learning, defining a 5x5 grid with obstacles, absorbing states (with specific rewards), and a start position. It constructs transition probabilities (T), reward function (R), and absorbing state mappings. The environment includes action randomness and visua...
def __init__(self): ### Attributes defining the Gridworld ####### # Shape of the gridworld self.shape = (5,5) # Locations of the obstacles self.obstacle_locs = [(1,1),(2,1),(2,3)] # Locations for the absorbing states self.absorbing_locs ...
def init_model_for_training(self): self.generator = Generator(input_dim=3,trunk_a_count=8,trunk_rfb_count=8) summary(self.generator, input_size=(TRAINING_BATCH_SIZE, 3, TRAINING_CROP_SIZE//4, TRAINING_CROP_SIZE//4)) self.generator = self.generator.to(device) if self.args.network_type == ...
This code initializes a training process by setting up model components, metrics (PSNR/LPIPS), data loaders, optimizers, and learning rate schedulers. If in 'train' mode, it launches the training loop; otherwise, it notes testing is unimplemented.
def __init__(self, args): self.args = args self.global_step = 0 self.max_epoch = args.epochs self.max_psnr = 0 self.min_lpips = float('inf') self.psnr = PeakSignalNoiseRatio(data_range=1.0).to(device) self.lpips = LearnedPerceptualImagePatchSimilarity(normalize =T...
def train_torch_epoch(self, epoch, model, loss_fn, optimizer, train_ds, k): total, correct, sum_loss = 0, 0, 0 i, prec, total_savings = 0, 0, 0 if self.loader.binary: ys, y_preds = torch.empty(size=(0, 2)).to(self.device), torch.empty(size=(0, 2)).to(self.device) elif self.lo...
The function `train_torch_fold` trains a PyTorch model over multiple epochs using provided datasets, tracking training and validation losses, precision, and other metrics. It initializes epochs based on model path names, iterates through training and validation phases, updates a board with metrics, saves checkpoints, a...
def train_torch_fold(self, model, loss_fn, optimizer, train_ds, valid_ds, epochs=0, k=0): train_losses, valid_losses, test_losses = [], [], [] train_avg_precs, valid_avg_precs, test_avg_precs = [], [], [] train_total_saves, valid_total_saves, test_total_saves = [], [], [] if not self.loa...
def train_torch_fold(self, model, loss_fn, optimizer, train_ds, valid_ds, epochs=0, k=0): train_losses, valid_losses, test_losses = [], [], [] train_avg_precs, valid_avg_precs, test_avg_precs = [], [], [] train_total_saves, valid_total_saves, test_total_saves = [], [], [] if not self.loa...
The code trains a machine learning model (PyTorch or scikit-learn) with cross-validation support. For PyTorch models, it initializes seeds, trains folds (single or multiple via cross-validation), and tracks metrics like loss and precision. For scikit-learn models, it requires parameters to train and save checkpoints. T...
def train(self, epochs=0, param=None): # TODO Add Manual Plots i = 0 if self.model_type == 'torch': torch.manual_seed(self.seed) if not self.loader.cross_valid: self.train_torch_fold(self.model, self.loss_fn, self.optimizer, ...
def yaw_from_quaternion(q): return np.arctan2(2.0*(q[0]*q[1] + q[3]*q[2]), q[3]**2 + q[0]**2 - q[1]**2 - q[2]**2) def proportional_control(self): a = Kp * (self.target_speed - self.state.v) return a def cem_steer_control(self, state: State, Lf): if Lf == 0: return 0.0 ...
This code implements a control algorithm for trajectory tracking in a robotic or autonomous vehicle system. It calculates the distance between the current pose and a target path point, adjusts the target index based on velocity and a lookahead distance (Lf), updates the vehicle's state, computes control inputs (acceler...
def cem_controll(self, pose: PoseStamped): pose_l = [pose.pose.position.x, pose.pose.position.y, pose.pose.position.z, pose.pose.orientation.x, pose.pose.orientation.y, pose.pose.orientation.z, pose.pose.or...
def clean_str(s:str) -> str: if s == None or str(s) == 'nan': return None s = re.sub("[^a-zA-Z0-9\s.-_#:,]", "", str(s)) return None if len(s) == 0 else s def is_empty(s) -> bool: return s == None or s == 'NULL' or trim(s) == '' def hash_strings(strings:List) -> str: a = [trim(s) for s in s...
The function inserts an institution into a database if it doesn't already exist, using a hash of the institution and laboratory names for uniqueness. It returns the record's ID and hash if newly created, or the existing ID if found. If inputs are incomplete or empty, it returns None.
def insert_institution(affiliation:Dict) -> List: if 'laboratory' not in affiliation and 'institution' not in affiliation: return None laboratory = clean_str(affiliation['laboratory']) institution = clean_str(affiliation['institution']) if is_empty(laboratory) and is_empty(institution): ...
def clean_str(s): if s == None or str(s) == 'nan': return None s = re.sub( r'\n', ' ', str(s), re.DOTALL) s = re.sub( r'\r\n', ' ', s, re.DOTALL) #s = re.sub( r'[^a-zA-Z0-9\s\.\-_\#\:\,]', '', s, re.DOTALL) s = re.sub( r'(^\'+|\'+$)', "", s, re.DOTALL) s = re.sub( r'\\+', "", s, re.DOTA...
The main task of the code is to insert institution-related data into a database, including institution name, laboratory, and location details, after cleaning and validation. It constructs an SQL INSERT statement using a hash ID generated from the institution and laboratory names, handling null values, and executes the ...
def insert_institution(affiliation): if 'laboratory' not in affiliation and 'institution' not in affiliation: return None laboratory = clean_str(affiliation['laboratory']) institution = clean_str(affiliation['institution']) if laboratory == None and institution == None: return None ...
def clean_str(s): if s == None or str(s) == 'nan': return None s = re.sub( r'\n', ' ', str(s), re.DOTALL) s = re.sub( r'\r\n', ' ', s, re.DOTALL) #s = re.sub( r'[^a-zA-Z0-9\s\.\-_\#\:\,]', '', s, re.DOTALL) s = re.sub( r'(^\'+|\'+$)', "", s, re.DOTALL) s = re.sub( r'\\+', "", s, re.DOTA...
This function inserts a journal entry into the 'import.Journal' database table by cleaning input name and ISSN, generating a hash ID, and executing an SQL INSERT statement with null-handling. It returns the generated hash ID for the inserted record.
def insert_journal(name, issn): journal_name = clean_str(name) journal_issn = clean_str(issn) if journal_name == None and journal_issn == None: return hash_id = hash_strings([journal_name, journal_issn]) journal = { 'hash_id': hash_id, 'journal_name': journal_name, ...
def clean_str(s): if s == None or str(s) == 'nan': return None s = re.sub( r'\n', ' ', str(s), re.DOTALL) s = re.sub( r'\r\n', ' ', s, re.DOTALL) #s = re.sub( r'[^a-zA-Z0-9\s\.\-_\#\:\,]', '', s, re.DOTALL) s = re.sub( r'(^\'+|\'+$)', "", s, re.DOTALL) s = re.sub( r'\\+', "", s, re.DOTA...
This function processes a JSON paper object by extracting and cleaning its metadata, abstract, and body text, then inserts the structured data into a database. It also handles author affiliations, citations, and related entities, ensuring proper database entries for the paper and its associations.
def insert_paper(json_paper): paper_id = json_paper['paper_id'] metadata = json_paper['metadata'] authors = metadata['authors'] bib_entries = json_paper['bib_entries'] title = clean_str(metadata['title']) body_text = None abstract = None abstract_nodes = [] text_nodes = [] # Com...
def read_files(path): file_list = [] for root, folders, docs in os.walk(path): file_list.extend( [os.path.join(root, doc) for doc in docs if '.json' in doc] ) return file_list def read_json(path): infile = open(path, "r") return convert_to_json(infile.read()) def insert_paper(json_paper): ...
This code reads JSON files from a specified folder, processes each file by extracting its contents, and inserts the extracted data into a database using the insert_paper function. It tracks and prints the number of processed files for progress tracking.
def insert_sql(): json_papers = read_files(FOLDER) i = 0 for path in json_papers: #print(path) json_paper = read_json(path) insert_paper(json_paper) i += 1 print(i)
def check_win(self, player): # TODO: Check win if (self.check_col_win(player) or self.check_row_win(player) or self.check_diag_win(player)): return True return False def check_tie(self): # TODO: Check tie for row in range(3): for col in range(3): ...
This code implements the minimax algorithm to determine the optimal move for a player in a Tic-Tac-Toe game. It recursively evaluates all possible moves, assigning scores based on win/loss/tie outcomes. For player "O", it maximizes the score; for "X", it minimizes the score. The function returns the best score and corr...
def minimax(self, player, depth): # base case if self.check_win("O"): return (10, None, None) elif self.check_win("X"): return (-10, None, None) elif self.check_tie(): return (0, None, None) elif depth == 0: return (0, None, None) ...
def check_win(self, player): # TODO: Check win if (self.check_col_win(player) or self.check_row_win(player) or self.check_diag_win(player)): return True return False def check_tie(self): # TODO: Check tie for row in range(3): for col in range(3): ...
This function implements the Minimax algorithm with alpha-beta pruning for a Tic-Tac-Toe game. It recursively evaluates all possible moves for the current player ("O" or "X"), selecting the optimal move by maximizing/minimizing scores. Base cases check for wins, ties, or depth limits. Alpha-beta pruning optimizes perfo...
def minimax_alpha_beta(self, player, depth, alpha, beta): # base case if self.check_win("O"): return (10, None, None) elif self.check_win("X"): return (-10, None, None) elif self.check_tie(): return (0, None, None) elif depth == 0: ...
def print_instructions(self): # TODO: Print the instructions to the game print("Welcome to TicTacToe!") print("This is a two player game. Take turns inserting X's and O's into the grid.") print("The first person to score three in a row of their symbol wins!") return def getDiffic...
The main task of the code is to run a game loop where two players take turns making moves on a board. It checks after each move if the current player has won or if the game is a tie, ending the loop when either condition is met. Players alternate between "X" and "O", with the game printing results and concluding with "...
def play_game(self): # TODO: Play game self.print_instructions() depth = self.getDifficultyLevel() self.print_board() player = "X" keepPlaying = True while(keepPlaying): self.take_turn(player, depth) if self.check_win(player): ...
def __calculate_speed(self, image, t): image = self.person.calculate_distance_speed(image=image, t=t) return image def __fetch_shoulders_slope(self, image): l_shoulder = self.mp_pose.PoseLandmark.LEFT_SHOULDER.value r_shoulder = self.mp_pose.PoseLandmark.RIGHT_SHOULDER.value m =...
The main task of the code is to process an image by analyzing pose landmarks, calculating movement speed, estimating shoulder slope, plotting hip angles, and drawing detected landmarks. It optionally displays the processed image for real-time visualization, aiding in posture or motion analysis.
def process_image(self, h, image, results, w, show_image=False): self.landmarks = results.pose_landmarks.landmark t = time.time() image = self.__calculate_speed(image, t) image = self.__fetch_shoulders_slope(image) image = self.plot_hip_angles(image, h, w) image = self.__...
def __setup_video_tool(self, cap, video_path): width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) fps = 15 # Use less numb of frames to make the video slower if video_path == REALTIME: output_path = 'realtime_output.mp4' ...
The main task of the code is to process a video (real-time or recorded) by capturing frames, optionally saving the processed video, uploading it to Firebase storage, and returning the upload URL while cleaning up resources. It handles video input, processing, output saving, cloud storage integration, and file cleanup.
def process_video(self, video_path=0, save_video=False, show_image=False): print('=== Process Video ===') output_path = None i = 0 # Create a VideoCapture object and read from input file # If the input is the camera, pass 0 instead of the video file name cap = cv2.VideoCa...
def trim_audio(file): music = AudioSegment.from_file(file) #First, middle and last 10s of music --> sample of 30s start = music[:10*1000] center = len(music)/2 middle = music[center-5000:center+5000] end = music[-10*1000:] sample = start + middle + end sample.export("sample.mp3", forma...
The main task of the code is to process an audio file by trimming it, extracting and saving relevant features, applying a pre-trained model to analyze the features, and returning the model's result. This workflow likely supports audio analysis tasks like speech recognition, classification, or feature-based prediction.
def main(file): trim_audio(file) save_features() result = apply_model() return result
def print_board(self, pieces): board = self.get_board(pieces) for row in board: print(row) print() def add_new_state(self, pieces): state = repr(pieces) if state not in self.states: self.states.add(state) return True return False def solve(self): pieces_queue = deque([ [self.STARTING_PIECES, ...
The main task of the code is to initialize a board with starting pieces, add the initial state to a tracking structure, and then execute a solving process. The `run` method first prints the initial board configuration, registers the starting state, and triggers the solver to process the problem. This sets up the enviro...
def run(self): self.print_board(self.STARTING_PIECES) self.add_new_state(self.STARTING_PIECES) self.solve()
def sorted_media_types(accept: str) -> List[str]: """ Example `accept`: "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8". """ alternatives = [a.split(";") for a in accept.split(",")] for a in alternatives: # provide default relative quality factor # https:...
The main task of the code is to generate an appropriate HTTP response based on the requested media type(s) in the 'accept' header. It prioritizes HTML rendering if supported, otherwise attempts serialization using the requested format. If all formats fail, it defaults to Turtle format. The function handles media type n...
def response_for(g: rdflib.Graph, accept: str): types_ = sorted_media_types(accept) for media_type in types_: if media_type == "text/html" and html_able(g): return HTMLResponse(content=make_html(g)) else: try: return Response( content=g...
def _aux_tangent_matrix(A,B): return np.vstack((np.hstack((A, np.zeros((3, 3)))), np.hstack((B, A)))) def dexp_L(x, **kwargs): return dexp_R(-x, **kwargs) def ddexp_L(x, y, **kwargs): return -ddexp_R(-x, y, **kwargs)
The function `tangent_dexp_L` computes a tangent matrix by combining the results of `dexp_L` and `ddexp_L` using an auxiliary function `_aux_tangent_matrix`. It uses a `theta` parameter, either provided or derived from the norm of the first three elements of `x`. This operation likely relates to differential geometry o...
def tangent_dexp_L(x, y, **kwargs): if 'theta' in kwargs: theta = kwargs['theta'] else: theta = np.linalg.norm(x[0:3]) return _aux_tangent_matrix(dexp_L(x, theta=theta),ddexp_L(x, y, theta=theta))
def inv_dexp_L(x, **kwargs): return inv_dexp_R(-x, **kwargs) def _aux_tangent_matrix(A,B): return np.vstack((np.hstack((A, np.zeros((3, 3)))), np.hstack((B, A)))) def ddexp_L(x, y, **kwargs): return -ddexp_R(-x, y, **kwargs)
The function computes a tangent matrix using the inverse differential exponential map (inv_dexp_L) and auxiliary operations. It calculates a parameter theta from input x, applies inv_dexp_L to x with theta, then constructs a tangent matrix via _aux_tangent_matrix, combining the result with a product involving ddexp_L(x...
def tangent_inv_dexp_L(x, y, **kwargs): if 'theta' in kwargs: theta = kwargs['theta'] else: theta = np.linalg.norm(x[0:3]) A = inv_dexp_L(x, theta=theta) return _aux_tangent_matrix(A,-A@ddexp_L(x, y, theta=theta)@A)
def _aux_tangent_matrix(A,B): return np.vstack((np.hstack((A, np.zeros((3, 3)))), np.hstack((B, A)))) def dcay_L(x): return dcay_R(-x) def ddcay_L(x,y): return -ddcay_R(-x,y)
The code computes the tangent matrix for the decay function L at point x, using the function's value and its derivative with respect to y. It calls auxiliary function _aux_tangent_matrix with dcay_L(x) and ddcay_L(x, y) to construct the tangent matrix, likely for geometric or differential analysis.
def tangent_dcay_L(x, y): return _aux_tangent_matrix(dcay_L(x),ddcay_L(x, y))
def inv_dcay_L(x): return inv_dcay_R(-x) def _aux_tangent_matrix(A,B): return np.vstack((np.hstack((A, np.zeros((3, 3)))), np.hstack((B, A)))) def ddcay_L(x,y): return -ddcay_R(-x,y)
The function `tangent_inv_dcay_L` computes a tangent matrix for the inverse of a decay function. It first calculates the inverse decay matrix `A` using `inv_dcay_L(x)`, then constructs the tangent matrix via `_aux_tangent_matrix` with `A` and the product of `-A`, the derivative of the decay function `ddcay_L(x, y)`, an...
def tangent_inv_dcay_L(x, y): A = inv_dcay_L(x) return _aux_tangent_matrix(A,-A@ddcay_L(x, y)@A)
def reset_simulation(): global current_time global traveled_paths global simulation_index simulation_index = 0 current_time = 0 traveled_paths = [] for car in cars: car.reset() render_cars() visualize_trajectory() def ask_for_user_input(promt): return simpledialog.askstri...
This function handles user selection of input trajectories by either creating a new trajectory with user-provided name or loading existing ones from disk. It resets the simulation, initializes car and trajectory lists, processes selected items from a listbox, and prepares data for rendering. It sets global flags and co...
def select_input_trajectory(): global create_new_trajectory global cars global input_trajectories reset_simulation() cars = [] input_trajectories = [] create_new_trajectory = False selected_items = [listbox.get(index) for index in listbox.curselection()] for item in selected_items: ...
def command_received(userID, textReceived): '''command_received: When the bot received a /msg, reply format''' textReceived = textReceived.lower() reply_markup="" if textReceived == "/help": text_input = "To start using the bot, type /start!\nSearch via category: /category\nSearch via brand: /br...
This function processes incoming chat messages by routing them to specific actions: executing commands, searching items by category/brand, handling search queries, adding URLs, or prompting for help. It interacts with a database, generates reply markups, and sends responses via a bot.
def on_chat_message(msg): '''on_chat_message: What to do when text received''' userId = msg['chat']['id'] textReceived = msg['text'] if '/' in textReceived[0]: # On command received command_received(userId, textReceived) elif "Category: " in textReceived: # Searches with category ...
def get_messages(room_id, page = 0): # how many msgs I want to skip before getting doc offset = page * MESSAGE_FETCH_LIMIT messages= list( messages_collection.find({'room_id': room_id}).sort('_id', DESCENDING).limit(MESSAGE_FETCH_LIMIT).skip(offset)) # for message in messages: # messag...
The function checks for unread messages in a room by comparing message timestamps with the user's last leave time. It retrieves reversed messages, verifies if a message was sent by someone else, and if the user hasn't left or left before the message was created, it marks the message as unread.
def check_unread_messages(roomID, userURL): messages = get_messages(roomID)[::-1] for message in messages: lastLeft = getUserLastLeft(roomID, userURL) if message['sender'] != userURL and lastLeft is None or lastLeft is not None and lastLeft < message['created_at']: userRead(roomID, u...
def initialize(self, bc=None): self.u = np.ones(self.resolution) * np.Inf print(self.init_value) self.u[self.source] = self.init_value for x in self.source: self.put_in_list(self.find_adjacent(x)) def solve_eikonal(self, x, u, vmx): tris = self.find_triangle(x, True) ...
This function solves the Eikonal equation on a mesh using a priority queue approach. It iteratively updates node distances (self.u) by propagating minimum values from source nodes, tracks associated triangles (tri_min), and processes neighbors when a lower distance is found. The algorithm ensures precision via epsilon,...
def find_u(self, vm): self.initialize() i = 0 while len(self.Q) > 0: temp = self.Q.pop(0) p = self.u[temp] q, tm = self.solve_eikonal(temp, self.u, vm[temp,:]) if p > q: self.u[temp] = q self.tri_min[temp,:] = tm ...
def find_plane_wave_bc(dir, grid_points, boundary=np.arange(5, 35).tolist(), normalize=True, init=True): if normalize: dir = dir / np.linalg.norm(dir) bc = [] for point in boundary: new_bc = np.inner(grid_points[point], dir) if new_bc > 0 and init==True: new_bc = np.arcco...
The code implements a Gauss-Newton optimization to determine optimal velocity matrices for a plane wave design problem. It iteratively updates the velocity matrix (vm) by minimizing the residual between predicted and observed wavefields (tau - u[xobs]), using Jacobian computations and boundary conditions. The process h...
def uni_direction_design(self, dir, boundary=np.arange(5, 35).tolist(), max_iter=10): ## Using Gauss-Newton Method to find the optimal velocity matrices count = 0 tau = find_plane_wave_bc(dir, self.mesh_points, init=False) inits = find_plane_wave_bc(dir, self.mesh_points, boundary, init=...
def find_plane_wave_bc(dir, grid_points, boundary=np.arange(5, 35).tolist(), normalize=True, init=True): if normalize: dir = dir / np.linalg.norm(dir) bc = [] for point in boundary: new_bc = np.inner(grid_points[point], dir) if new_bc > 0 and init==True: new_bc = np.arcco...
The code implements a multi-directional optimization algorithm using the Gauss-Newton method to iteratively adjust velocity matrices (vm) by minimizing the difference between computed wavefields (self.u[self.xobs]) and target wavefields (tau). It computes residuals (res) and Jacobian matrices (J) for each direction, up...
def multi_direction_design(self, dirs, boundary=np.arange(5, 35).tolist(), max_iter=10): ## Using Gauss-Newton Method to find the optimal velocity matrices count = 0 tau = [] inits = [] for dir in dirs: tau.append(find_plane_wave_bc(dir, self.mesh_points, boundary, in...
def create_argparser(): defaults = dict( dataset='', clip_denoised=True, num_samples=10000, batch_size=16, use_ddim=False, model_path="", draw_graph=True, save_svg=True, ) defaults.update(model_and_diffusion_defaults()) parser = argparse.Ar...
This code evaluates a diffusion model on the 'rplan' dataset by generating room layout predictions, comparing them to ground truth via FID scores and compatibility metrics, and analyzing diversity and compatibility across multiple sampling runs. It loads a pre-trained model, processes data in batches, saves outputs, an...
def main(): args = create_argparser().parse_args() update_arg_parser(args) dist_util.setup_dist() logger.configure() logger.log("creating model and diffusion...") model, diffusion = create_model_and_diffusion( **args_to_dict(args, model_and_diffusion_defaults().keys()) ) model....
def get_replicate_increment(self, Lx: float, Ly: float, Lz: float, n: int = 3): """Return the increment in each direction for replicating the box.""" assert n >= 1 inc...
This function generates augmented oxygen atom positions from a PDB file by applying data augmentation techniques like translation, rotation, and spatial selection within spheres/cubes. It processes multiple augmentations per input, applies periodic boundary conditions, and logs results to a file.
def gen_pts_from_pdb_one_worker(self, args: Tuple[str, int, int, str]): pdb_file: str = args[0] naug: int = args[1] idx: int = args[2] log_file = args[3] universe = mda.Universe(pdb_file) Lx, Ly, Lz = universe.dimensions[:3] oxygen = universe.select_atoms('name...
def envelope(x, decay_factor=0.9998): _x = np.abs(x) e = np.zeros_like(_x) e[0] = -1000 for i, xi in enumerate(_x): if xi >= e[i - 1]: e[i] = xi else: e[i] = decay_factor * e[i - 1] return e def derivative(x): return np.gradient(x) def post_process(d): ...
The main task of the code is to detect onsets in an audio signal by computing its envelope, derivative, and adaptive threshold, then identifying onset indices. It returns the envelope, derivative, processed signal, threshold, and onset indices (converted to time if specified). The process involves envelope extraction, ...
def detect_onsets(signal, decay_factor=0.99998, t=0.1, l=200, window_length=256, units='samples', sr=None): env = envelope(signal, decay_factor=decay_factor) deriv = derivative(env) post = post_process(deriv) thresh = adaptive_threshold(post, t, l, window_length) onset_idxs = detect_onsets_in_post(p...
def cache_files_exist(): return pathlib.Path(CONFIG["cache_file_64bit"]).exists() def read_file_content(file_path): try: return pathlib.Path(file_path).read_text() except (FileNotFoundError, UnicodeDecodeError): raise RuntimeError("Error(s) reading from file {}".format(file_path)) def parse_...
The function `check_cache()` retrieves or generates 64-bit system call data. If cache files exist, it loads the precomputed syscalls from a JSON file. Otherwise, it parses syscall names, generates 64-bit syscalls, and saves them to the cache. The function ensures syscalls are available for use, either by reusing cached...
def check_cache(): if cache_files_exist(): syscalls_64bit = json.loads( read_file_content(CONFIG["cache_file_64bit"]) ) else: syscall_names = parse_syscall_names() syscalls_64bit = generate_syscalls(syscall_names, BITNESS_64) write_file_content( CO...
def check_cache_directory(): directory = "{}/.cache/syscall_number".format(os.environ["HOME"]) if not pathlib.Path(directory).exists(): os.mkdir(directory) def check_syscall_header_file(): if not pathlib.Path(CONFIG["syscall_header_file"]).exists(): raise RuntimeError( "Install ...
The function converts a system call number (sysno) to its corresponding name by checking a cached list of syscalls. It verifies the sysno exists in the cache, then returns the matching name. If invalid, it raises a ValueError.
def sysno_to_name(sysno: int) -> str: check_cache_directory() check_syscall_header_file() syscalls = check_cache() if sysno not in syscalls.values(): raise ValueError("The syscall number you provided is not available!") for name, number in syscalls.items(): if number == sysno: ...
def white_balance(image, device): r_bg_color = torch.bincount(image[0].flatten()).argmax().detach() g_bg_color = torch.bincount(image[1].flatten()).argmax().detach() b_bg_color = torch.bincount(image[2].flatten()).argmax().detach() balanced = torch.zeros(*image.shape, device=device) balanced[0] = i...
This function preprocesses medical images by resizing, applying white balance, splitting into blocks, and saving downscaled versions using specified methods. It loads an image, adjusts its dimensions, converts it to a PyTorch tensor, processes blocks recursively, and stores results in GPU memory-optimized formats for t...
def img_preprocess(in_dir, out_dir, file_name, device, downsampling_methods, train=True): w, h = imagesize.get(in_dir) w, h = w // 5, h // 5 out = pyvips.Image.thumbnail(in_dir, w, height=h) array = out.numpy() t = torch.from_numpy(array).transpose(1, 2).transpose(0, 1).to(device) image = whi...