dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def _update_params(self, X_train_batch, y_train_batch, lr): nabla_W = [np.zeros_like(W) for W in self.weights] nabla_b = [np.zeros_like(b) for b in self.biases] for x, y in zip(X_train_batch, y_train_batch): delta_nabla_W, delta_nabla_b = self._backprop(x, y) nabla_W = ...
The code implements stochastic gradient descent (SGD) for training a neural network. It shuffles training data, divides it into mini-batches, updates model parameters using gradients from each batch (except the last), and evaluates validation accuracy on the final batch per epoch. The process repeats for specified epoc...
def fit(self, X, y, epochs=10, batch_size=128, lr=1e-4): """Run stochastic gradient descent (SGD) on training data Arguments: X {N x layers[0] array} -- All training data y {N x layers[-1] array} -- All training labels Keyword Arguments: epoc...
def logistic_func(self,z): return 1 / (1 + np.exp(-z)) def l2_logiklihood(x, weights, y, penalty): z = np.dot(x, weights) reg_term = (1 / (2 * penalty)) * np.dot(weights.T, weights) return -1 * np.sum((y * np.log(logistic_func(z))) + ((1 - y) * np.log(1 - logistic_func(z)))) + reg_term def ...
This code trains a logistic regression model using gradient descent with cross-validation. It iteratively updates weights by minimizing cross-entropy loss with optional L1/L2 regularization. The model splits data into folds, evaluates performance on training/validation sets per iteration, tracks costs, and stops early ...
def train(self, x_in, y_in, folds,learningrate=0.05, iterations=100, regularization = None, penalty = 0.01): tol = 10**-6 self.x_splits = x_in self.y_splits = y_in self.learningrate = learningrate self.iterations = iterations self.folds = folds tolerance = tol * n...
def rotation_velocity(self, rng): ''' Set rotation velocity randomly, rotation velocity is a composition of two sinusoidal velocities ''' # Sinusoidal velocity forward = [-0.3, -0.35, -0.4, -0.45, -0.50, -0.55, -0.60, -0.65] backward = [0.75, 0.8, 0.85, 0.90] fr...
The code simulates a controlled movement of a cup using a pre-trained model. It initializes the model, sets random rotation velocities, starts the simulation, and iterates through steps to update the cup's state. At each step, it selects actions based on the current state, applies them, and checks if the cup returns to...
def run(self): # Load model from training self.model = load_model(f"models/{MODEL_NAME}.model") # Set rotation velocity randomly rng = np.random.default_rng() velReal = self.rotation_velocity(rng) # Start simulation, process objects/handles self.start_simulation...
def check_file_in_storage(self, image_url, image_data): if self.check_exists is not None and isinstance(self.check_exists, dict): if self.check_exists['key'] in image_data: data_loaded = image_data[self.check_exists['key']] if self.check_exists['json'] and isinstance(data_loaded, basestring): dat...
The code processes image URLs from a queue by checking their file type against allowed types, determining if they need thumbnail generation based on storage status, and executing the appropriate callback. It handles synchronization via a semaphore and logs progress, ensuring thread safety and efficient resource managem...
def get_urls_from_dict(self, key, callback): # Suspend execution of the calling thread for the given number of seconds sleep(0.1) try: image_data = self.queue.get() image_url = image_data[key] split_image = image_url.split('.') image_type = split_image.pop().lower() if image_type in ALLOWED_TYPE...
def get_args(): parser = argparse.ArgumentParser(description='Process some integers.') arg = parser.add_argument arg('--data_path', default=Path('data')) arg('--model-name', type=str, default='densenet121') arg('--exp-suffix', type=str, default='bce_wp_fbn_SUB_ACC16') arg('--cell-type', ...
The code trains a neural network model for a classification task using GPU acceleration. It loads and preprocesses data, initializes a model with specified parameters, and performs multi-stage training: pretraining, fine-tuning the classifier head, full model fine-tuning, and validation phase training. The process uses...
def main(): args = get_args() print(args) gpus = args.gpus os.environ['CUDA_DEVICE_ORDER'] = 'PCI_BUS_ID' os.environ['CUDA_VISIBLE_DEVICES'] = gpus device = 'cuda' n_gpu = len(gpus.split(',')) set_seeds(args.seed) WELL_TYPE = 'treatment' CELL_TYPE = args.cell_type d...
def context_agent(objective: str, task: str, top_results_num: int): """ Retrieves context for a given query from an index of tasks. Args: query (str): The query or objective for retrieving context. top_results_num (int): The number of top results to retrieve. Returns: list: A l...
The `execution_agent` function executes a task aligned with a given objective by synthesizing context from prior tasks, documents, and Wikipedia. It constructs a prompt incorporating the objective, task, historical context, and retrieved information, optionally requesting internet or Wikipedia searches if needed. The f...
def execution_agent(objective: str, task: str) -> str: """ Executes a task based on the given objective and previous context. Args: objective (str): The objective or goal for the AI to perform the task. task (str): The task to be executed by the AI. Returns: str: The response g...
def print_to_file(text: str, mode: chr): with open('task_list.txt', mode) as f: f.write(text) def simplify_search_results(search_results): simplified_results = [] for result in search_results: simplified_result = { "position": result.get("position"), "title": result.g...
The main task of the code is to perform web searches using Google API, SERPAPI, or a browser (DuckDuckGo) based on the specified mode, extract relevant links, scrape their content, and return summarized results along with raw data. It handles errors by switching search methods, aggregates scraped text, and ensures a de...
def web_search_tool(query: str, task: str, num_extracts: int, mode: str, summary_mode: bool): links = [] search_results = [] results = [] # Google API search if mode == "google": url = "https://www.googleapis.com/customsearch/v1" params = { "key": GOOGLE_API_KEY, ...
def print_to_file(text: str, mode: chr): with open('task_results.txt', mode) as f: f.write(text) def execution_agent(objective: str, task: str) -> str: """ Executes a task based on the given objective and previous context. Args: objective (str): The objective or goal for the AI to perfo...
The main task of the code is to process a queue of tasks by executing each task, handling internet searches if required, enriching results, updating document embeddings, storing outcomes, generating new tasks, and managing task prioritization and reporting. It continuously loops through tasks, processes them, and maint...
def main(): loop = True while loop: # As long as there are tasks in the storage... if not tasks_storage.is_empty(): # Print the task list print("\033[95m\033[1m" + "\n*****TASK LIST*****" + "\033[0m\033[0m") print_to_file("\n*****TASK LIST*****\n", 'a') ...
def get_user_by_assertion_id(assertion_id): assertion_collection = myDB["Assertions"] query = {'_id': ObjectId(assertion_id)} output = {'user': 1, '_id': False} user_by_assertion_id = assertion_collection.find_one(query, output) return user_by_assertion_id.get("user") def get_badge_by_assertion_i...
The main task of the code is to update a user's badge status in the "User_Badge_Details" and "Assertions" collections based on the provided parameters (assertion_id, issuer_id, badge_status_id, comments). It sets fields like modified time, badge status, reviewer, and comments, and triggers auto-adding major/master badg...
def update_user_badge_status(assertion_id, issuer_id, badge_status_id, comments): modified_time_utc = datetime.now(timezone.utc) user_badge__details_collection = myDB["User_Badge_Details"] assertions_collection = myDB["Assertions"] badge_user = get_user_by_assertion_id(assertion_id) badge = get_bad...
def get_user_by_assertion_id(assertion_id): assertion_collection = myDB["Assertions"] query = {'_id': ObjectId(assertion_id)} output = {'user': 1, '_id': False} user_by_assertion_id = assertion_collection.find_one(query, output) return user_by_assertion_id.get("user") def get_badge_by_assertion_i...
The function updates user badge details and assertions based on the provided badge status. If the status changes, it updates timestamps, links, and user roles in both collections, then triggers auto-adding major/master badges. If unchanged, it updates only specific fields. Finally, it returns the updated user badge det...
def update_user_badge_mapping(assertion_id, badge_status, work_link, comments, public_link, user_id, is_badge_status_changed, issuer_id): user_badge__details_collection = myDB["User_Badge_Details"] assertions_collection = myDB["Assertions"] badge_user = get_user_by_assertion_i...
def get_loaders(args): normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) train_t1 = transforms.Compose([ transforms.RandomResizedCrop(224, scale=(0.2, 1.)), ]) train_t2 = transforms.Compose([ transforms.RandomAppl...
The code trains an ensemble of ResNet models on poisoned data, iteratively optimizing each model with SGD and cosine annealing. It evaluates validation performance, stops training when metrics stabilize, then uses the ensemble to test on unseen data. Non-poisoned test samples are saved to a file. The task focuses on de...
def main(): global logger args = parser.parse_args() args.save = os.path.join(os.path.dirname(args.poison_dir), f'patch_search_poison_classifier_topk_{args.topk_poisons}_ensemble_{args.model_count}_max_iterations_{args.max_iterations}_{args.eval_data}') os.makedirs(args.save, exist_ok=True) logger ...
def get_model(arch, wts_path): if 'moco_vit' in arch: model = vits.__dict__[arch.replace('moco_', '')]() model.head = nn.Identity() sd = torch.load(wts_path)['state_dict'] sd = {k.replace('module.', ''): v for k, v in sd.items()} sd = {k: v for k, v in sd.items() if 'base_enc...
The main task of the code is to detect poisoned images in a dataset using an iterative clustering and patch-based approach. It performs feature clustering with K-means, generates candidate patches from clusters, evaluates their impact on test images via Grad-CAM, and iteratively identifies top suspicious images based o...
def main(): np.random.seed(10) torch.manual_seed(10) global logger args = parser.parse_args() args.save = os.path.dirname(args.weights) match = re.search(r'\d+', os.path.basename(args.weights)) ckpt = match.group(0) if match else 'final' dir_name = f'patch_search_iterative_search_test_...
def paused(): # pygame.mixer.music.pause() largeText = pygame.font.SysFont("comicsansms", 115) textSurf, textRect = textObjects("Paused", largeText) textRect.center = ((displayWidth/2), (displayHeight/2)) gameDisplay.blit(textSurf, textRect) while pause: for event in pygame.eve...
The code defines a game loop for a 2D game where a player controls a spaceship to avoid moving ducks. It handles user input for movement and pausing, updates duck positions, checks for collisions between the ship and ducks, and resets duck parameters upon dodging. The loop also manages game state, displays graphics, an...
def gameLoop(): """ This a function for the game loop (to keep running) """ global pause # pygame.mixer.music.load('jazz.wav') # pygame.mixer.music.play(-1) duckStartX = random.randrange(0, displayWidth) duckStartY = -600 duckSpeed = 4 duckWidth = 50 duckHeight = 50 ...
def solve_place_ball(komo, position, q_conf_ref_pose, collision_box = True, force_orientation = True): # collsion avoidance if collision_box: komo.addObjective([0,1.], ry.FS.distance, [box_name, "ball"], ry.OT.ineq, .5e2, [-.05]) komo.addObjective([0,1.], ry.FS.distance, [box_name, "grapper_han...
This function plans and executes a robotic motion path to move an object to a target location using KOMO, checking collision constraints. If constraints exceed thresholds, it triggers error handling by resetting the robot or returning failure. It returns True on success, False if constraints are violated or resets occu...
def calculate_execute_komo(self, target, collision_box = True): waypoints = 15 horizon_seconds = 3. komo = self.C.komo_path(1., waypoints, horizon_seconds, False) constraints = solve_place_ball(komo, target, self.S_verbose.get_q(), collision_box = collision_box) if constraints...
def box_position_feasable(self): q1 = Quaternion(self.box_t.getQuaternion()) q = Quaternion( self.box.getQuaternion()) qd = q.conjugate * q1 phi = math.atan2( 2 * (qd.w * qd.x + qd.y * qd.z), 1 - 2 * (qd.x**2 + qd.y**2) ) theta = math.asin ( 2 * (qd.w * qd.y - qd.z * qd.x) ) ...
The code simulates a robotic movement task, checking feasibility of box positions, executing motions to start/end points, calculating distance/angle rewards, penalizing excessive deviation, rewarding precise positioning, and tracking success/failure metrics for reinforcement learning.
def step(self, action, show_simulation = False): reward = 0 game_over = False sucess = False if not self.box_position_feasable(): game_over = True self.exec_fails+=1 return reward, game_over, self.score start, direction = start_direction(self...
def create_definition(col): definition = '{col_name} {col_def}'.format( col_name=col['name'], col_def=column_definition(col) ) return definition def index_type(key): if key.get('using'): return ' USING {}'.format(key['using']) return '' def reference_definition(col): defi...
The code generates SQL-like column and constraint definitions from a table structure. It processes columns, primary keys, indexes, unique constraints, and foreign keys, combining them into a comma-separated string for database schema creation.
def create_definitions(table): defs = [] for col in table['columns']: defs.append(create_definition(col)) for keyname in ['primary key', 'index', 'key', 'unique']: if table.get(keyname): key = table[keyname] state = ' ' + keyname.upper() state += index_typ...
def print_intro(): intro = ('Welcome to Wolmorse. \nThis program encodes and decodes Morse code.') print(intro) return intro def get_input(): mode = str(input('Would you like to encode(e) or decode(d):')) mode = mode.lower() while (mode != "e" or mode != "d"): if mode == "d": ...
The main task of the code is to execute a program that prints an introduction, retrieves user input (message and mode), and processes the message by either encoding or decoding it based on the mode ('e' for encode, 'd' for decode). After processing, it calls a `repetition` function, likely to repeat the operation or di...
def main(): print_intro() message, mode = get_input() if (mode == 'e'): encode(message) elif (mode == 'd'): decode(message) repetition()
def _build_from_curpus(self, vocab_path): id2token = {} with open(vocab_path, 'r') as f: words = f.read().strip().split('\n') for id, word in enumerate(words): id2token[id] = word.split()[0] train_bow = self._read_from_bow( vocab_path.replace(...
The main task of the code is to rebuild a vocabulary for a text dataset. It checks if a pre-existing vocabulary file exists; if not, it generates one based on word frequency (default 50). Then, it loads and processes training, validation, and test data files into structured formats (data, labels, text) using the `_file...
def _rebuild_vocab(self, frequence=50): train_path = os.path.join(self.base_path, "raw/train.txt") valid_path = os.path.join(self.base_path, "raw/valid.txt") test_path = os.path.join(self.base_path, "raw/test.txt") if os.path.exists(os.path.join(self.base_path, "raw/data.vocab")): ...
def get_batches(self, batch_size=512, rand=True): n, d = self.train_data.shape self.word_count = self.train_data.sum(axis=1).A.squeeze() batchs = n // batch_size while True: idxs = np.arange(self.train_data.shape[0]) if rand: np.random.shuffle(id...
This code trains a neural network for topic modeling by optimizing a loss function combining likelihood, KLD divergence, and regularization terms. It processes data in batches, updates model parameters via backpropagation, dynamically adjusts hyperparameters (rho, alpha), and evaluates topic coherence and perplexity pe...
def train(self): self.t_begin = time.time() self.train_generator = self.get_batches(self.batch_size) data_size = self.train_data.shape[0] n_batchs = data_size // self.batch_size self.best_coherence = -1 ones = torch.ones(self.batch_size).to(device) loss_all = []...
def load_model(self, model_filename='model.pkl'): model_path = os.path.join(self.model_path, model_filename) self.Net.load_state_dict(torch.load(model_path)) with open(f'{self.model_path}/topic_num.txt', 'r') as f: self.topic_num = int(f.read()) self.adj_matirx = self.to_np(...
The main task of the code is to evaluate a topic model's performance by loading the model, setting it to evaluation mode, updating topic selection, running evaluations, generating samples, and assessing coherence metrics. It initializes a high baseline coherence value, executes evaluation steps, and likely compares res...
def test(self): self.load_model() self.Net.eval() self.best_coherence = 999 self.update_topic_select() self.evaluate() self.sample() self.eval_level()
def __calculate_moving_direction(self, exit_cell): delta_x = self.pos_x - exit_cell.pos_x delta_y = self.pos_y - exit_cell.pos_y tangent_radians = math.atan2(delta_y, delta_x) self.look_angle_alpha = math.degrees(tangent_radians) def is_grid_free_for_body_cells(grid, body_cells): for...
The code calculates valid body cells for an agent in a grid environment by iterating up to four times. It checks if the agent's shape (based on position, angle, and size) fits in the grid without collisions. If free, it stores the body cells; otherwise, it attempts reverse steps to adjust position until a valid configu...
def calculate_body_cells(self, grid, exit_cell): self.__calculate_moving_direction(exit_cell) tries = 0 while True: tries += 1 if tries > 4: break self.shape.calculate_cells(pos_x=self.pos_x, pos_y=self.pos_y, angle_degrees=self.lo...
def get_size(): """get the size of the matrix, defensively get an int between 3 and 6.""" print("") print("{:*^75}".format(" Welcome to game 2048! ")) print("") print("Please enter the size of the game you want.") size = input("It should between 3 to 6, end with Enter: ") try: ...
The main task of the code is to implement a 2048 game where the player moves numbered tiles on a grid to merge identical numbers, aiming to reach 2048. The function initializes the game board, processes user inputs for directional moves, updates the matrix, adds new random tiles after valid moves, checks for game end c...
def main(): size = get_size() game_matrix = game_init(size) game_matrix = random_generate(game_matrix) print("Use up/down/left/right to move the numbers, same number" " merge into one when they touch. Add them up to reach 2048!") print("") while not end_game(game_matrix): print...
def apply_window(image_stack, window, rescale = False): window_width = window[0] window_center = window[1] img = image_stack.copy() img_min = window_center - window_width//2 #minimum HU level img_max = window_center + window_width//2 #maximum HU level img[img<img_min] = img_min #set img_min for ...
The main task of the code is to generate an oblique axial image from a 3D axial stack by applying a specified windowing (and optional masking) to the input data, then using the `generate_avg_oblique_2` function to compute an average oblique slice at a given angle. The result is returned as a single 2D image representat...
def generate_single_patient_image(axial_stack, angle, window, mask = False): windowed_stack = apply_window(axial_stack, window) # Generate the axial stack if mask: windowed_stack = apply_mask(axial_stack,window) avip = generate_avg_oblique_2(windowed_stack, 0, angle) return avip
def do_first_check(self): db = self.db if not db.get_agreement_count(): logger.info('No pending agreements found in the local database.') return block_num = db.get_latest_block_number() agreements, conditions = db.get_pending_agreements(block_num - self.last_n_bl...
The code monitors blockchain events by continuously checking new block ranges, processing agreement-related events, and updating the last processed block. It runs in a loop until disabled, handles errors gracefully, and pauses between checks to avoid overload.
def run_monitor(self): self.do_first_check() while True: try: if not self._monitor_is_on: return _from, _to = self.get_next_block_range() for event_log in self.get_agreement_events(_from, _to): self._han...
def how_many_pages(gender): page = 1 soup = transform_url(gender,page) compteur = 0 while True: try: if soup.find("button",{"title":"Page suivante","class":"e1c9s0c21 css-1younqe e18fm3l50"})["disabled"] == "": compteur += 1 except: page += 1...
The main task of the code is to scrape data for both "man" and "woman" genders across multiple pages. It iterates through each gender, retrieves data from each page using `page_getter`, updates the provided dictionary `dico` with the collected data, and finally dumps the updated dictionary into a JSON file before retur...
def scrape(dico): genders = ["man",'woman'] for gender in genders: for i in range(1,how_many_pages(gender)+1): dico = page_getter(gender,i,dico) json_dump(dico) return dico
def shortest_path_function(self, bot_start = None, captain = None): if bot_start == None: bot_start = self.bot_start if captain == None: captain = self.captain self.path = [] q = deque() q.append(bot_start) prev = {bot_start: bot_start} vi...
The code simulates a bot's movement on a grid, navigating a precomputed shortest path to reach a target (captain) while avoiding aliens. The bot moves step-by-step along the path, checking for collisions with aliens or the captain. If the bot encounters an alien, it fails; if it reaches the captain, it succeeds. Aliens...
def move_bot_1(self): t = 0 bot_1_path_counter = 1 ded = False self.shortest_path_function() curr_row, curr_col = self.bot_start while t < 1000: t += 1 # exists = True if len(self.path) > 0 else False exists = len(self.path) >...
def clear_path(self): for i in range(self.D): for j in range(self.D): self.grid[i][j].path = False def shortest_path_function(self, bot_start = None, captain = None): if bot_start == None: bot_start = self.bot_start if captain == None: captain ...
The main task of the code is to navigate a bot through a grid to reach the "captain" while avoiding aliens. The bot calculates the shortest path iteratively, updates its position, checks for collisions with aliens or the captain, and moves aliens. The process repeats up to 1000 steps, returning whether the bot reached ...
def move_bot_2(self): self.reached_captain = False t = 0 curr_row, curr_col = self.bot_start row, col = self.bot_start while t < 1000 and (row, col) != self.captain: t += 1 self.clear_path() self.shortest_path_function((curr_row, curr_col)) ...
def get_neighbors(row, col, D, buffer = 1): if buffer > 1: l = [(row, col)] for i in range(buffer): l.append([(row - i, col), (row + i, col), (row, col - i), (row, col + i)]) else: l = [(row, col), (row - 1, col), (row + 1, col), (row, col - 1), (row, col + 1)] neighbor ...
The function `move_bot_3` navigates a bot through a grid to reach the captain while avoiding alien-adjacent cells. It calculates the shortest path, updates the bot's position, and simulates alien movements. If the bot collides with an alien or fails to reach the captain within 1000 steps, it switches to a fallback stra...
def move_bot_3(grid, bot_start, alien_pos, captain): # we're going to be adding the buffer to the aliens by simply adding their adjacent cells to the alien_pos list D = len(grid[0]) # a list containing positions of aliens and their neighboring cells (nsew) neighbor_cells = [(row, col) for x, y in alien...
def move_bot_strategy_1(grid, bot_position, captain_position): # Bot plans the shortest path to the Captain, ignoring aliens' movement path = shortest_path_to_captain(grid, bot_position, captain_position) return path[1] if len(path) > 1 else bot_position def move_bot_strategy_2(grid, bot_position, captain_p...
The code defines a function `move_bot` that directs a bot's movement on a grid based on a specified strategy. It selects between three strategies (1, 2, or 3) to determine the bot's path toward the captain's position, delegating execution to corresponding helper functions. The main task is to navigate the bot using str...
def move_bot(grid, bot_position, captain_position, strategy): if strategy == 1: return move_bot_strategy_1(grid, bot_position, captain_position) elif strategy == 2: return move_bot_strategy_2(grid, bot_position, captain_position) elif strategy == 3: return move_bot_strategy_3(grid, b...
def get_neighbors(self, row, col, buffer = 1): l = [] for i in range(1, buffer + 1): l.extend([(row - i, col), (row + i, col), (row, col - i), (row, col + i)]) neighbor = [(x, y) for x, y in l if self.is_valid(x, y)] return neighbor def move_bot(self, row, col, curr_row, cur...
The main task of the code is to navigate a bot to reach the captain while avoiding aliens by dynamically updating the grid with alien neighbors, finding the shortest path, and handling collisions. If the bot fails to reach the captain within 1000 steps or encounters aliens, it reverts to a secondary strategy (move_bot_...
def move_bot_3(self): t = 0 curr_row, curr_col = self.bot_start row, col = self.bot_start # since the alien_pos list is going to be changing and we don't know if we're going to be successful with this strat, # let's put the original alien_pos in another list in case we w...
def generate_grid_with_bot_aliens_and_captain(D, num_aliens): grid = [['blocked' for _ in range(D)] for _ in range(D)] # Place bot start_row, start_col = random.randint(1, D-2), random.randint(1, D-2) grid[start_row][start_col] = 'open' bot_position = (start_row, start_col) # Place aliens ...
The code simulates multiple scenarios where a bot navigates a grid with aliens, using a specified strategy to either save the captain or ensure survival. It tracks the success rates of saving the captain and achieving survival across all simulations, returning their probabilities as fractions of total instances.
def simulate_multiple_instances(num_instances, D, num_aliens, strategy): success_save_captain = 0 success_survival = 0 for _ in range(num_instances): grid, bot_position, captain_position = generate_grid_with_bot_aliens_and_captain(D, num_aliens) aliens_order = [(i, j) for i in range(1, D-1)...
def _set_current_lora(self, lora_name): self.lora_name = lora_name self.model.set_adapter(lora_name) def load_model(self, model_name, force=False, **kwargs): if not force and model_name == self.model_name: return self.unload_model() self._initialize_model_and_tokeniz...
This function loads a LoRA (Low-Rank Adaptation) adapter into a pre-trained model. It checks validity of inputs, avoids redundant operations if the same LoRA is already loaded, and ensures the base model matches when `replace_model` is False. If necessary, it loads the base model and applies the LoRA adapter, then sets...
def load_lora(self, lora_name, replace_model=True): if self.model is None or lora_name is None: raise ValueError("Model and LORA name must be specified.") if lora_name == self.lora_name: return if lora_name in self.loras: self._set_current_lora(lora_name) ...
def moveAppender(self,moves,y,colour): if (y.piece == "Pawn" ): if (colour == "Black"): moves.append(Pieces(y.piece,y.colour,y.xLocation , y.yLocation - 1)) if (y.xLocation >= 1 and y.xLocation <= 7): moves...
The code determines if a player's king is in checkmate by simulating all legal moves for their pieces. It checks if any move allows the king to escape check. If no valid move exists to avoid check, the function returns True (checkmate); otherwise, it returns False.
def isCheckMate(self,colour): isLegal = False isCapture = False moves = [] boardCopy = copy.deepcopy(self.boardPieces) """ kingPiece = None for x in self.boardPieces: for y in x: if (y.piece == "King" and y.colour == colour): ...
def check_privileges() -> None: if not os.environ.get("SUDO_UID") and os.geteuid() != 0: warn("You need to run this script with sudo or as root.") sys.exit(1) def setup(nix_shell: str) -> None: info("Setup all repos for the experiments...") # clone repository for YCSB remove_folder(ROOT...
The main task of the code is to execute a workflow requiring the Nix package manager. It checks user privileges, verifies `nix-shell` is installed, sets up the environment, starts services, runs experiments on specified databases, and performs cleanup. If `nix-shell` is missing, it warns the user and exits. The script ...
def main() -> None: check_privileges() nix_shell = shutil.which("nix-shell", mode=os.F_OK | os.X_OK) if nix_shell is None: warn( "The nix package manager is required!" ) sys.exit(1) setup(nix_shell=nix_shell) start_services(nix_shell=nix_shell) execute_experim...
def check_privileges() -> None: if not os.environ.get("SUDO_UID") and os.geteuid() != 0: warn("You need to run this script with sudo or as root.") sys.exit(1) def setup() -> None: info("Setup all docker images and repos for the experiments...") # clone repository for flame graphs remove...
The main task of the code is to execute a series of steps for experimental analysis: check system privileges, initialize setup, install required packages, generate comparison graphs for specified I/O methods ('basic', 'select', 'poll', 'epoll'), and collect the resulting visualizations. The function orchestrates an end...
def main() -> None: check_privileges() experiments = ['basic', 'select', 'poll', 'epoll'] setup() install_required_packages() generate_graphs(experiments=experiments) collect_generated_plots(experiments=experiments)
def cleanup_file_path(self, path): return path.replace('\\', '/').replace(" ", "_").replace(':', '_') def get_readable_ctime(self): return time.strftime("%d-%m-%Y %H_%M_%S") def append_log(self, text, level=None): level = self.LOGGING_LEVELS[1] if level is None else level log_str = self.get_log_prefix_format(le...
The code initializes file-based logging by constructing a log file path using a provided directory, log name prefix, and timestamp. It creates a deque to store log entries and records an initialization message indicating the logging location.
def init_file_writing(self, LOG_PATH, LOG_FILE_NAME_PREFIX): self.file_path = self.cleanup_file_path(LOG_PATH+os.sep+LOG_FILE_NAME_PREFIX+ "_"+self.get_readable_ctime()+".log") self.log_queue = deque([]) self.append_log("Initialized logging at path {}".format(self.file_path), self.LOGGING_LEVELS[0])
def create_mainframe(self): self.mainframe = tk.Frame(self, height=(self.config.side+150), width=self.config.side, bg="black") self.mainframe.pack(expand=True) self.gameTitle = tk.Label(self.mainframe, font = ("Arial", 36, "bold"), text = "BATTLESHIP", fg = "white", bg = "black") self.gameTitle.pack(side = 'to...
This code initializes a GUI frame for a game configuration, linking to the game's configuration data. It sets up the frame's layout, configures grid properties for responsiveness, creates subframes, and triggers an initial board update. The main task is to establish a configurable interface component within a game appl...
def __init__(self, parent, Game): self.game = Game self.config = Game.config #CONFIG FRAME super().__init__(parent) self.configure(bg="black") self.grid(row=0, column=0, sticky="nsew") parent.grid_rowconfigure(0, weight=1) parent.grid_columnconfigure(0, weight=1) #CONFIG BUTTON #self.buttonPixel ...
def dupicate_check(drink_name): cocktail = Cocktail.objects.filter(name__exact=drink_name, cocktail_tag__exact='o') if cocktail: return cocktail return None def search_by_id(self, ID_drink): url = self.build_url('lookup.php?i=' + ID_...
This function fetches cocktail data from a given URL, handles API errors, checks for duplicates, and returns a list of cocktail objects. It retrieves JSON data, validates the response, and processes each drink entry by either reusing existing records or creating new ones via ID lookup, compiling the results into a list...
def get_cocktails_endpoint(self, url): cocktails = [] try: response = requests.get(url) response.raise_for_status() api_data = response.json() except requests.exceptions.RequestException as e: print(f'Error: {e}') return None if...
def build_url(self, endpoint): return self.base_url + endpoint def dupicate_check(drink_name): cocktail = Cocktail.objects.filter(name__exact=drink_name, cocktail_tag__exact='o') if cocktail: return cocktail return None def search_by...
The function searches an external API for cocktails using provided ingredients, processes the response, checks for duplicates, and returns a list of unique cocktail data. It handles exceptions, validates API responses, and constructs cocktail objects from retrieved data.
def search_in_external_api(self, selected_ingredients): selected_ingredients = [str(conv) for conv in selected_ingredients] api_params = ','.join(selected_ingredients) url = self.build_url('filter.php?i=' + api_params) cocktails = [] try: response = requests.get(url)...
def SetClickForce(devicename, force): ''' Set the ClickForce of a device using xsetwacom. Values are in the range 1 - 21. ''' if force == None: force = xswGetDefault(devicename, "ClickForce") elif force > 21: force = 21 elif force < 1: force = 1 return xswSet(dev...
The main task of the code is to clean up after a drag operation by resetting dragging flags, updating click force based on the drag line, and setting the press curve using obtained points.
def DragFinished(self): ''' Clean up after finished drag. ''' self.DraggingCP = False self.DraggingCF = False if self.ClickForceLine != None: SetClickForce(self.DeviceName, int(self.ClickForceLine * 20.0) + 1) points = self.GetPoints() if points != N...
def UpdateDeviceMode(self): ''' Update the device mode combo box. ''' self.DeviceMode = xswGet(self.DeviceName, "Mode") if self.DeviceMode == None: self.ModeCombo.set_sensitive(False) else: self.ModeCombo.set_sensitive(True) self.ModeCombo.set_...
The main task of the code is to update child widgets in a UI to reflect current settings by calling three specific methods: UpdateDeviceMode, UpdateClickForce, and UpdateTPCButton. This ensures the graphical interface elements remain synchronized with the application's internal state and configuration parameters.
def UpdateChildren(self): ''' Update the child widgets to reflect current settings. ''' self.UpdateDeviceMode() self.UpdateClickForce() self.UpdateTPCButton()
def update_canvas(self): canvas = self.scene_array (y, x) = next(self.iter) patch = self.scene[y:y+self.patch_size, x:x+self.patch_size] if patch.shape[0] != 20: return patch_position = (y % self.scene_height, x % self.scene_width) (prediction, back, cycles) = get_pred...
The main task of the code is to continuously update and display an image with markers in a loop, creating a real-time animation effect by scheduling the `update_image` method to call itself every 10 milliseconds. It updates the canvas, displays the image, draws markers, and handles potential errors silently.
def update_image(self): try: # Update the image array (in this example, randomly changing pixels) self.update_canvas() # Display the updated image self.display_image() self.draw_markers() # Schedule the next update after 1000 millisecon...
def print_pause(string): ''' function that pauses after printing a given string ''' print(string) time.sleep(2) def BabaYaga_house(): #TO DO: Joe add more exploration to the story and then add this function to the first_choice() choice = input("You see on the horizon a house suspended at...
The function `first_choice()` prompts the user to decide whether to exit a cave (Y/N). If "Y", it advances the story by describing a field of flowers and invoking `BabaYaga_house()`. If "N", it generates a random creature, describes an encounter with it, and triggers `fight_monster(creature)`, creating branching narrat...
def first_choice(): ''' function that asks for users input & returns different outcomes depending on the scenario ''' choice = input("Do you to exit the cave? Type Y/N \n") if choice == "Y": print_pause("You find yourself in a field of flowers") BabaYaga_house() #TO DO: A...
def greet_user(username): print_pause("Hello, " + username + "!") def print_pause(string): ''' function that pauses after printing a given string ''' print(string) time.sleep(2) def first_choice(): ''' function that asks for users input & returns different outcomes depending on t...
The code's main task is to initialize a game scenario by greeting characters, describing the player's items, and prompting the first choice in a text-based adventure. It sets up the environment, introduces elements like items in the cave, and transitions to user interaction via the first_choice() function.
def intro(): greet_user('Arcade') #calling the function greet_user('Ellen') greet_user('Sophie') greet_user('Joe') string_items = ', '.join(items) print_pause("You find yourself in a dark cave and you only have a " + string_items + " in your hand") first_choice()
def load_image_into_numpy_array(image): (im_width, im_height) = image.size return np.array(image.getdata()).reshape((im_height, im_width, 3)).astype(np.uint8) def run_inference_for_single_image(image, graph): with graph.as_default(): with tf.Session(config=config) as sess: # Get handles to inp...
The code uploads multiple images, processes each using a CNN model to detect license plates with high confidence scores (>0.99), crops detected regions, extracts plate numbers via image processing, and generates an HTML table displaying filenames, plate names, and detected license plate numbers for visualization.
def upload(): if request.method == 'POST': start_time = time.time() files = request.files.getlist("file[]") res = [] cnn = CNN() cnn.CNN_initialize() model = cnn.getModel() for k,image_path in enumerate(files): image = Image.open(image_path) ...
def draw_bomb(self, screen): pygame.draw.ellipse(screen, Color.RED, self.inflate(0.5)) def bomb_neighbors(self): return len([cell for cell in self.neighbors() if cell.status & Status.BOMB]) def draw_number(self, screen): font = pygame.font.SysFont(None, int(Config.CELL)) text = font.rend...
This code renders a game cell's visual state on the screen. It checks the cell's status to draw a bomb, number, cover, or flag based on conditions like openness, bomb presence, neighboring bombs, game loss status, and debug mode. The logic ensures correct visuals for gameplay elements like revealing tiles, flags, and b...
def draw(self): screen = self.board.game.screen if self.status & Status.BOMB: self.draw_bomb(screen) elif self.bomb_neighbors() > 0: self.draw_number(screen) if not self.status & Status.OPEN: if not (self.board.lose and (self.status & Status.BOMB)): ...
def __str__(self, margins={}): b = self.boardToString(margins=margins) top = '\n'*margins.get('top', 0) bottom = '\n'*margins.get('bottom', 0) scores = ' \tScore: %5d Best: %5d\n' % (self.score, self.best_score) return top + b.replace('\n', scores, 1) + bottom def readMove(self): """ read and return a mo...
The code implements a game loop for a 2048-like game, executing moves based on a specified strategy (random, priority, or MCTS), tracking moves, time, and score. It handles pausing, saving progress, and returning the final score, total time, and number of moves upon game completion or interruption.
def loop(self, strategy=None, delay=None, max_depth=None, max_iters=None): """ main game loop. returns the final score. """ pause_key = self.board.PAUSE margins = {'left': 4, 'top': 4, 'bottom': 4} start_time = time.time() number_of_moves = 0 try: while True: # only print if there's a delay or h...
def regular_polygon(sidelength, n): points = np.zeros((n, 2)) i = np.arange(n, dtype=np.int32) A = sidelength / (2 * np.sin(np.pi / n)) points[:, 0] = A * np.sin(i * 2 * np.pi / n) points[:, 1] = A * np.cos(-i * 2 * np.pi / n) return points def rotate(points, angle, center=None): if cente...
The code calibrates an image by detecting Fourier spots using a specified template (hexagonal, 2nd-order-hexagonal, or ring). It calculates scaling factors based on the image size and lattice constant, adjusts min/max scales, and invokes `detect_fourier_spots` to identify spots. The function returns the calibrated scal...
def calibrate(self, image, return_spots=False): if self.template.lower() == 'hexagonal': k = min(image.shape[-2:]) / self.lattice_constant * 2 / np.sqrt(3) template = regular_polygon(1., 6) symmetry = 6 elif self.template.lower() == '2nd-order-hexagonal': ...
def get_questions() -> List[QuizQuestion]: return quiz().questions def get_answers() -> List[QuizAnswer]: return [QuizAnswer.from_dict(user) for user in db("quiz_answers")] def get_question(id: int) -> Optional[QuizQuestion]: if 0 <= id < len(quiz().questions): return quiz().questions[id] return...
The code calculates user scores in a quiz by ranking answers against correct estimations, assigning scores based on proximity, and aggregating results per user. It processes all answers, computes mean scores, and returns a sorted list of users by score along with question statistics and counts.
def user_scores() -> QuizUserScores: count: Dict[int, int] = {q.id: 0 for q in get_questions()} all_answers_per_q: Dict[int, List[float]] = {} for answer in get_answers(): question = get_question(answer.question) if question.estimation: if question.id not in all_answers_per_q: ...
def answered(user_id: int, question_id: int) -> bool: return any(answer.question == question_id and user_id == answer.user for answer in get_answers()) def get_user(id: int) -> Optional[QuizUser]: val = db("quiz_users").search(Query().id == id) if val: return QuizUser.from_dict(val[0]) return No...
The function `add_answer` validates an answer's length, checks if the user has already answered the question, verifies user and question existence, ensures the question is currently enabled, and inserts the answer into the database if all conditions are met. It returns the answer as a dictionary or `None` if any valida...
def add_answer(user_id: int, question_id: int, answer: str) -> Optional[QuizAnswer]: if len(answer) > 1000 or len(answer) < 1: return None if answered(user_id, question_id): return None if get_user(user_id) is None or all(question.id != question_id for question in get_questions()): r...
def setup(self): self.dbfile = 'stockscroll.sqlite' conn = sqlite3.connect(self.dbfile) cur = conn.cursor() create_options = '''CREATE TABLE IF NOT EXISTS "Options" ( "name" TEXT, "scroll_delay" INTEGER, "port_delay" INTEGER, "w...
This code initializes a GUI application for stock data visualization. It sets up the window, configures display settings, initializes plotting components, prepares stock symbols, and starts a loop to fetch and update stock quotes in real-time, using predefined delays and layout parameters.
def __init__(self, root): self.root = root self.setup() # Options: 0-name, 1-scroll_delay, 2-port_delay, 3-win_x, 4-win_y, 5-win_dx, 6-win_dy root.geometry('%dx%d+%d+%d' % (self.options[5], self.options[6], self.options[3], self.options[4])) self.root.title('StockScroll') default...
def get_field(self, s): if self.oj_format: return 'oj-' + s return s def get_paragraphs(self, s, stack, res): match_num = self.re_checker.start_with_number_and_point(s) match_num_par = self.re_checker.start_with_number_and_parenthesis(s) match_lett = self.re_checker.s...
This function processes HTML elements by iterating through siblings of 'current', trimming text, and collecting paragraphs into 'res', while skipping tables and specific 'p' elements with a 'normal' class. It then adjusts the stack level to maintain structural integrity during text extraction.
def get_recitals(self, current, stack, res): while current != None: try: if current.name != 'table': if not (current.name == 'p' and self.get_field('normal') in current['class']): break except: pass s...
def get_field(self, s): if self.oj_format: return 'oj-' + s return s def get_paragraphs(self, s, stack, res): match_num = self.re_checker.start_with_number_and_point(s) match_num_par = self.re_checker.start_with_number_and_parenthesis(s) match_lett = self.re_checker.s...
This function extracts notes from HTML elements by starting at a specific horizontal rule (`<hr>`), iterating through subsequent siblings, trimming text, and processing paragraphs until encountering a document separator or end marker. It then adjusts the stack level to maintain structural hierarchy during data extracti...
def get_notes(self, soup, stack, res): current = soup.find( 'hr', attrs={"class": self.get_field("note")}).find_next_sibling() while current != None: try: if self.get_field('doc-sep') in current['class'] or self.get_field('doc-end') in current['class']: ...
def get_field(self, s): if self.oj_format: return 'oj-' + s return s def get_paragraphs(self, s, stack, res): match_num = self.re_checker.start_with_number_and_point(s) match_num_par = self.re_checker.start_with_number_and_parenthesis(s) match_lett = self.re_checker.s...
The code extracts annexes from HTML content by identifying elements with specific classes, processes their titles and associated text, and structures them hierarchically in a stack. It iterates through sibling elements, trims text, and appends data while managing nesting levels to maintain document structure.
def get_annexes(self, soup, stack, res): docseps = soup.find_all(attrs={'class': self.get_field('doc-sep')}) self.total_annexes = len(docseps) for sep in docseps: ti = sep.find_next_sibling().find( attrs={"class": self.get_field("doc-ti")}) s = self.re_cle...
def get_field(self, s): if self.oj_format: return 'oj-' + s return s def go_back_untill_same_level(self, stack, level, res): self.add_to_dic(stack, res, 0) while stack[-1][0] >= level: stack.pop() def get_paragraphs(self, s, stack, res): match_num = self.r...
This function traverses HTML elements to extract article content, using a stack to track structure. It checks element classes to determine stopping points, cleans text, and either adds article fragments to the stack at level 6 or processes paragraphs. It navigates siblings and parent elements to locate the next potenti...
def get_articles(self, art, stack, res): current = art while current != None: try: if self.get_field('final') in current['class'] or self.get_field('ti-section-1') in current['class']: break except: pass s = self.re...
def get_field(self, s): if self.oj_format: return 'oj-' + s return s def get_articles(self, art, stack, res): current = art while current != None: try: if self.get_field('final') in current['class'] or self.get_field('ti-section-1') in current['cla...
The main task of the code is to parse HTML content using BeautifulSoup, extract structured text fragments (parts, titles, chapters, etc.), and organize them into a hierarchical stack structure while adjusting levels to maintain correct nesting. It identifies fragments by type, cleans text, and collects associated artic...
def get_body(self, soup, stack, res): ti_secs = soup.find_all( attrs={"class": self.get_field("ti-section-1")}) if len(ti_secs) == 0: self.get_articles(soup.find( attrs={"class": self.get_field("ti-art")}), stack, res) else: for ti in ti_secs: ...
def get_introduction(self, soup, stack, res): current = soup.find(attrs={"class": "doc-ti"}) if current == None: self.oj_format = True current = soup.find(attrs={"class": "oj-doc-ti"}) while current != None: try: if current.name != 'p': ...
The code parses an HTML document into a structured dictionary with five sections: introduction, recitals, body, notes, and annexes. It uses BeautifulSoup to extract content, assigns each part to specific dictionary positions, and adds full text to the body section before returning the organized result.
def convert(self, text: str) -> dict: res = {"document": [{}, {}, {}, {}, {}]} soup = BeautifulSoup(text, 'html.parser') self.oj_format = False current = self.get_introduction(soup, [( 0, {"parent_key": "introduction", "name": "introduction", "text": "introduction"})], res["d...
def prepare_date(self, date): """Add time information to passed date. Args: date (string): 'yyyy-mm-dd' formated date string Eg: start_datetime, end_datetime = self.prepare_date('2020-03-01') start_datetime = '2020-03-01T00:00:00Z"' end_datetime ...
The code processes satellite imagery for specified locations and dates, detecting objects using a model. It returns GeoJSON-formatted results with detections and total counts, leveraging cached or provided extents for each location.
def infer(self, date, extents=None): """ Infer based on the extents provided or on the cached extents Args: date (str): date in 'yyyy-mm-dd' format extents (None, optional): list of extents in [left, bottom, right, top] format Returns: dictionary...
def reorganize_social_groups(self): for row in self.grid.cells: for cell in row: if len(cell.herds) > 1: merged_herd = [] for herd in cell.herds: if herd is not None and hasattr(herd, "__iter__"): ...
This code simulates social group interactions in a grid-based environment. It iterates through each cell, reorganizes social groups, and triggers conflicts: if multiple prides exist, they fight; if one pride and one herd exist, the pride hunts the strongest herbivore. The function manages territorial disputes and preda...
def struggle(self): for row in self.grid.cells: for cell in row: self.reorganize_social_groups() if len(cell.prides) > 1: self.fight_between_prides(cell.prides[0], cell.prides[1]) elif (len(cell.prides) == 1) and (len(cell.herds) =...
def giveSomeCellsWater(self): for row in self.grid.cells: for cell in row: if cell.type == "ground" and random.random() < WATER_CHANCE: cell.type = "water" def populateMapWithErbastAndCarviz(self, erbast_prob, carviz_prob): for row in self.grid.cells: ...
The code simulates an ecosystem over multiple days by initializing grid states, executing daily processes (growth, movement, grazing, etc.), and tracking changes. It generates heatmaps to visualize vegetation, predator (carviz), and prey (erbast) density evolution, then animates these changes. Final plots display terra...
def start(self): self.giveSomeCellsWater() self.populateMapWithErbastAndCarviz(0.1, 0.9) self.gridStatuses = [self.grid] changes = [] for day in range(NUMDAYS): self.growing() self.move() self.grazing() self.struggle() s...
def get_job_output_dir(self): """Return the path to current output directory.""" return self.get_jobdir()/"output" def get_jobdir(self): """Return a job directory name, e.g., job0, job1, etc. The job directory is a sibling of the output directory. """ assert self.job_ind...
The main task of the code is to advance to the next job in a processing pipeline by incrementing the job index, creating a new job directory, and copying output files from the previous job's output directory to the current job's input directory. This ensures sequential data flow between jobs, where the output of one jo...
def next_job(self): """Advance to the next job and copy output to input.""" # Save previous output directory prev_output_dir = self.get_job_output_dir() # Move to the next job and create the directories self.job_index += 1 assert not self.get_jobdir().exists() se...
def get_job_output_dir(self): """Return the path to current output directory.""" return self.get_jobdir()/"output" def get_jobdir(self): """Return a job directory name, e.g., job0, job1, etc. The job directory is a sibling of the output directory. """ assert self.job_ind...
The function concatenates all output files from a job into a single text file and returns the filename. It creates a consolidated output by sequentially copying contents from each individual output file into a newly created file, then resolves and returns the full path of this concatenated file.
def get_output_concat(self): """Concatenated output/part-* output files and return filename.""" basename = self.get_job_output_dir().name + ".txt" concat_filename = self.get_jobdir()/basename with concat_filename.open("w") as outfile: for filename in self.get_job_output_filen...
def get_job_input_dir(self): """Return the path to current input directory.""" return self.get_jobdir()/"input" def get_job_output_dir(self): """Return the path to current output directory.""" return self.get_jobdir()/"output" def get_job_mapper_exe(self): """Return the mapper ex...
The code sequentially executes a series of MapReduce jobs using Hadoop. It runs each job with specified input/output directories and mapper/reducer executables, then progresses to the next job unless it's the final one, which it marks as complete and exits.
def run(self): """Execute each job, in order.""" while True: # Run one MapReduce job hadoop( input_dir=self.get_job_input_dir(), output_dir=self.get_job_output_dir(), map_exe=self.get_job_mapper_exe(), reduce_exe=sel...
def get_exes(): """Return two lists: mapper exes and reducer exes. Valid filenames are map1.py ... map9.py and reduce1.py ... reduce9.py. Note that map0.py and reduce0.py are the document count MapReduce program, which are tested separately. """ mapper_exes = [] ...
This code initializes a MapReduce pipeline by setting up job directories, copying input data, and executing mapper/reducer tasks. It ensures output directories are cleaned, enforces keyspace constraints, and runs the pipeline to process data through specified executables.
def __init__(self, input_dir, output_dir, enforce_keyspace=False): # pylint: disable=too-many-arguments """Create and execute MapReduce pipeline.""" self.job_index = 0 self.output_dir = pathlib.Path(output_dir) self.enforce_keyspace = enforce_keyspace # Get map and reduc...
def get_balance_factor(self, node): """Calculates the balance factor of the given node in order to make rotations""" return self.get_height(node.right) - self.get_height(node.left) def simple_right_rotation(self, node): """Rotate node to the right once""" aux1 = node.left aux2 = ...
This code maintains tree balance by performing rotations on unbalanced nodes. It checks the balance factor of a node and applies simple or double rotations (left/right) to restore balance, ensuring the AVL tree property is preserved during insertions or deletions.
def balance(self, node): """Performs rotations on the nodes when they unbalance the tree""" factor = self.get_balance_factor(node) if factor == -2: if self.get_balance_factor(node.left) == -1: self.root = self.simple_right_rotation(node) else: ...
def load_tp_states(n_max, A_magic, en_magic): com_momenta = np.load("com_momenta-n_max_"+str(n_max)+"-A_magic_"+str(A_magic)+".npy") hh_channel_states = np.load("hh_channel_states-n_max_"+str(n_max)+"-A_magic_"+str(A_magic)+".npy") pp_channel_states = np.load("pp_channel_states-n_max_"+str(n_max)+"-A_magic_...
The code constructs matrices F, V, and T₂ for nuclear physics calculations by iterating over momentum states and channel states. It computes single-particle (f_h/f_p) and interaction (v_pp_hh, v_hh_hh, v_pp_pp) matrix elements using helper functions, then derives T₂ from v_pp_hh divided by a combination of f_h and f_p ...
def matrix_setup(n_max, A_magic, en_magic, grid_spacing): """Sets up F, V, and T_2 as matrices.""" com_momenta, hh_channel_states, pp_channel_states, ph_com_momenta, ph_channel_states = load_tp_states(n_max, A_magic, en_magic)#make_tp_states(n_max, A_magic, en_magic) r_factor, s_factor, r_exp, s_exp, q_squ...
def getDayIndex(data): for i in range(len(data.iloc[1])-1): try: parse(data.iloc[1][i]) return i except: continue return -1 def getTrainData(data, k, priceIndex): lenData = len(data) #chieu dai data l = int((lenData*k)/3) # 3*l = chieu dai tap train, l...
The main task of the code is to train a time series forecasting model using historical data from a CSV file, evaluate its performance on a test set, and compute error metrics (RMSE, MAE, MAPE). It splits data into training/test sets, trains a custom model, predicts future values, and measures training/testing durations...
def main(link, num1, num2, num3, num4): # link = r"C:\Users\thanh\Downloads\test.csv" startTrain = timeit.default_timer() data = pd.DataFrame(pd.read_csv(link)) # print(data) d = num1 t = num2 k = num3 priceIndex = num4 dayIndex = getDayIndex(data) #train = data.iloc[range(0, in...
def get_days_past(self) -> int: """ Returns the number of days since the start. """ return self._days_past def get_rooms(self) -> dict[str, Room]: """ Returns all rooms with room name as keys with a corresponding room instance. """ return self._rooms def g...
The main task of the code is to advance the game to the next day by applying effects from a list of items to plants, adding fertiliser and possum repellent to the inventory every 3 days, progressing all plants, checking win/loss conditions, and returning the game state as 'Win', 'Loss', or 'Normal'
def next(self, applied_items: list[tuple[str, int, Item]]) -> str: """ Move to the next day, if there are items in the list of applied items (room name, position, item to be applied) then apply all affects. Add fertiliser and possum repellent to the inventory every 3 days. Progress all p...
def save_image(self): """ Saves imported image. :return: None. """ file_path, _ = QFileDialog.getSaveFileName( self, "Save Image", "", "PNG(*.png);;JPEG(*.jpg *.jpeg);;All Files(*.*)" ) pix = self.grab(self.image_board.geometry()) pix.save(fil...
This method connects UI components to their corresponding functions, linking sliders, buttons, and combo boxes to actions like setting brush size, opening color panels, saving/importing images, adding text, and toggling between pen/eraser modes. It ensures user interactions trigger the appropriate logic in the applicat...
def connect_ui(self): """ Connects Ui with custom methods. :return: None. """ self.brush_size_slider.valueChanged.connect(self.set_pen_size) self.color_pushbutton.clicked.connect(self.open_color_panel) self.save_pushbutton.clicked.connect(lambda: self.save_image(...
def time_stamp(file_name, event, time_dict=time_dict): # Purpose: # To add a time stamp to the 'time_dict' # Variables: # file_name = name of file being processed # event: is either 'open file' or 'close file' # time_dict = is the dict being written to. # Uses the following functions...
This function processes multiple files from a zip folder by splitting lines using specified delimiters, removing quotes, and saving processed data to files when a row threshold is met. It coordinates tasks like timestamping, row preparation, and error tracking, while managing file operations and performance metrics.
def process_files(write_when=1500, break_at=60000000): # Purpose: # The Master Mind that coordinates the many functions of the processing. # Calling this function will initiate the processing # Variables: # zip_files[] = are the files folder names that you would like to pass through this. ...
def S(octet): assert (yield tx) == 1 assert (yield dut.tx_ack) == 1 yield dut.tx_data.eq(octet) yield dut.tx_ready.eq(1) while (yield tx) == 1: yield yield dut.tx_ready.eq(0) assert (yield tx) == 0 assert (yield dut.tx_ack) == 0 yield f...
The function `O` processes an octet and a list of bits by sequentially yielding results from generator `S` applied to the octet, then from generator `D` applied to each bit in the list, and finally from generator `E`. Its main task is to chain and delegate generation tasks to these helper functions in a specific order.
def O(octet, bits): yield from S(octet) for bit in bits: yield from D(bit) yield from E()
def compute_ground_loss(self, examples, log_prefix=''): """Compute loss and accuracy on ground examples.""" # examples (..., 1+W*H+1) preds = self.embed_predict(examples[..., :-1]) # (..., V) preds = F.reshape(preds, (-1, VOCAB)) # (N, V) targets = F.flatten(examples[..., -1]) # (N,) loss = F.so...
The code computes forward inference for unification tasks by processing ground and invariant examples. It embeds inputs, extracts features via convolutions, applies attention mechanisms to align features, and aggregates predictions across invariants. The process involves reshaping tensors, computing unified embeddings,...
def forward(self, ground_examples: np.ndarray): """Compute the forward inference pass for given stories.""" # ground_examples (B, 1+W*H+1) self.log = dict() # --------------------------- # Invariant ground prediction self.compute_ground_loss(self.inv_examples, log_prefix='ig') # Ground examp...
def compute_ground_loss(self, examples, log_prefix=''): """Compute loss and accuracy on ground examples.""" # examples (..., 1+L+1) preds = self.embed_predict(examples[..., :-1]) # (..., V) preds = F.reshape(preds, (-1, VOCAB)) # (..., V) targets = F.flatten(examples[..., -1]) # (...,) loss = F....
The code computes forward inference for unifying ground and invariant examples using RNNs, attention mechanisms, and variable maps. It embeds inputs, calculates task-specific representations, applies bidirectional RNNs, and generates unified embeddings via attention. Predictions are made by combining these embeddings w...
def forward(self, ground_examples): """Compute the forward inference pass for given stories.""" # ground_examples (B, 1+L+1) self.log = dict() # --------------------------- # Invariant ground prediction self.compute_ground_loss(self.inv_examples, log_prefix='ig') # Ground example prediction ...
def draw_strokes(data, svg_filename, factor=0.2, padding=50): """ little function that displays vector images and saves them to .svg :param data: :param factor: :param svg_filename: :param padding: :return: """ min_x, max_x, min_y, max_y = utils.get_bounds(data, factor) dims = (padding + max_x - min_x, paddin...
The main task of the code is to convert stroke-based dataset entries into SVG and PNG images, organized by dataset splits (train/valid/test) and configurations. It loads stroke data, renders SVGs using specified parameters, and converts them to PNGs via two rendering modes (v1/v2), saving outputs in structured director...
def main(**kwargs): data_base_dir = kwargs['data_base_dir'] render_mode = kwargs['render_mode'] npz_dir = os.path.join(data_base_dir, 'npz') svg_dir = os.path.join(data_base_dir, 'svg') png_dir = os.path.join(data_base_dir, 'png') model_params = get_default_hparams() for dataset_i in range(len(model_params['da...
def _blendHelixComponentsIntoCoolant(block, solventName="coolant"): """OpenMC doesn't support helixes, so blend them all into coolant""" helixComponentNames = [] for component in block: if isinstance(component, complexShapes.Helix): helixComponentNames.append(component.getName()) if ...
This function generates OpenMC geometry cells and universes for a reactor block, handling special components like DerivedShape, ensuring proper regions, materials, and buffers to prevent particle loss. It creates lattice structures, processes component materials, and assembles cells into a block universe, returning the...
def _writeBlockGeometry(self, block, blockBottomPlane, blockTopPlane): """Create openmc inputs for an armi block""" blockCellsInAssembly = [] blockWithoutHelices = _blendHelixComponentsIntoCoolant(block) blockHasDerivedShapeComponent = any( [ isinstance(compon...
def writeGeometry(self): """Write the openmc geometry, materials, and plots input file.""" runLog.info("Writing geometry, materials, and plots...") core = self.r.core self.materials = openmc.Materials() emptyMaterial = openmc.Material() self._writeCoreGeometry() ...
The main task of the code is to serve as a wrapper method that generates all necessary OpenMC input files by sequentially writing the geometry, simulation settings, and tally definitions. This method orchestrates the creation of complete OpenMC input data through three specialized sub-methods, ensuring all critical com...
def write(self): """Wrapper that writes all OpenMC input files""" self.writeGeometry() self.writeSettings() self.writeTallies()
def initial_hint(self, answer: str) -> str: return GPTHelper().call_api_for_initial_hint(answer) def guess(self, word) -> None: guess = Guess(word) self.current_guess = guess.word self.process_guess(guess) if self.gameover or self.lives == 0: self.lose() if ...
The code's main task is to manage a game loop where the player submits guesses until they win or lose. It starts with an initial hint, repeatedly calls `self.guess()` while lives remain, and breaks the loop if the game ends. Finally, it triggers `self.lose()` to conclude the game, ensuring minimal functionality to dete...
def play(self) -> None: """For every round, submit a guess. Break the loop if you win, else `lose`.""" print(self.initial_hint(self.answer.word)) while self.lives > 0: if self.gameover: break elif self.lives == 0: break self.gue...
def _xor_difference(data, size=1): ans = int.from_bytes(data[:-size], 'big') ^ int.from_bytes(data[size:], 'big') return ans.to_bytes(len(data) - size, 'big') def _search_yara(matches, binary, constants, size=['fullword']): rules = constants_to_rules(constants, size) for match in yara.compile(source=rul...
This function searches for YARA patterns in a binary using XOR transformation. It applies XOR difference to the binary and constants, then identifies matches. If valid XOR keys are found (non-repeating, non-zero), it updates matches with original constants and XOR keys, adjusting for endianness. Results are added to th...
def _search_yara_xor(matches, binary, constants, xor_size=1): if len(binary) < xor_size + 4: return _binary = _xor_difference(binary, xor_size) _constants = [] for constant in constants: if len(constant['value']) >= xor_size + 4: _constants.append({ 'name': co...
def _search_yara(matches, binary, constants, size=['fullword']): rules = constants_to_rules(constants, size) for match in yara.compile(source=rules).match(data=binary): matches[match.meta['id']].add(match) def _search_yara_xor(matches, binary, constants, xor_size=1): if len(binary) < xor_size + 4: ...
The function `find_const` searches for predefined constants in a binary using YARA rules, supporting fullword, dword, and qword matches, as well as XOR-encrypted variations up to a specified size. It returns a list of results, either summarizing constant names or providing detailed matches with offsets and formats. The...
def find_const(binary, constants, summary=False, xor_size_max=1): '''Find constants in binary Parameters ---------- binary: bytes Target binary to search for. constants: List[Dict] Constants you want to find. summary: boolean (optional) Only get the name of constants. De...
def deal(): return deck.pop() def card_value(card_name): card_rank = card_name.split(" of ") return card_values[card_rank[0]] def player_deal(player_value_local): playing = True current_value = player_value_local #While loop to ensure that the player gets as many hits as he wants while play...
This function initializes a Blackjack game round by dealing cards to the dealer and player, calculates their hand values, checks for immediate wins (e.g., blackjack), allows the player to take actions, and then determines the winner based on final hand values, returning outcomes like "Player", "Dealer", or "Tie"
def start_current_game(): #Sets the dealer/player value to 0 dealer_value_global = 0 player_value_global = 0 #Clears the list to ensure we get brand new cards player_cards.clear() dealer_cards.clear() #Add 2 cards to dealer and player in the correct order of the blackjack rules dealer_...
def place_kings(): king_brd = list() for rank_white in range(4): for file_white in range(rank_white+1): if (rank_white == file_white): for rank_black in range(8): for file_black in range(rank_black+1): diff_list = [abs(rank_white -...
The code's main task is to generate legal chess positions for tablebases by first placing kings on a pawnless board, then creating four-piece unique positions from these king placements. It subsequently generates five-piece positions, specifically focusing on the KQRkq configuration for experimental purposes, using der...
def start(): #place the kings first on pawnless tablebase king_positions = place_kings() print("Kk length",len(king_positions)) write_pos(king_positions,"Kk") #create 4 piece unique legal position piece_4 = generate_nvsm(king_positions) #create 5 piece unique legal positions. Only KQRkq cr...
def resampling(data_dir, dataset, classification): ''' Oversample the imbalanced dataset Args: data_dir: the path of IDRID file dataset: the type of dataset, train, validation or test classification: type of classification Return: the list of new balanced labels ''' ...
The function processes a dataset by resampling training data, reading labels, preparing images, and generating three TFRecord files for train, validation, and test sets. It combines resampling, label extraction, image preparation, and TFRecord writing to organize data for machine learning workflows, returning the outpu...
def creating_action(data_dir, classification): ''' Combine resampling, read_labels and write_tfrecord Args: data_dir: the path saving dataset classification: type of classification Return: three tfrecord files for train set, validation set and test set ''' # Read labels...
def add_page(self, page_name=None, update=True): container = None if page_name: section = str('layout-Child-%s-0' % (page_name[len('layout-Tabs-'):])) progname = ConfigManager.get_conf(section, 'prog') pwd = ConfigManager.get_conf(section, 'pwd') container...
The code initializes the UI for a terminal emulator by setting the window title, configuring fullscreen mode, creating UI components like containers, buttons, and tabs, connecting event handlers for user interactions, and restoring saved layout configurations. It sets up the main window structure, loads the application...
def init_ui(self): self.set_title(t('Terra Terminal Emulator')) if ConfigManager.get_conf(self.name, 'fullscreen'): self.is_fullscreen = True else: self.is_fullscreen = False self.slide_effect_running = False self.losefocus_time = 0 self.set_has_...
def key_event_compare(conf_name, event): key_string = ConfigManager.get_conf('shortcuts', conf_name) if ((Gdk.ModifierType.CONTROL_MASK & event.state) == Gdk.ModifierType.CONTROL_MASK) != ('<Control>' in key_string): return False if ((Gdk.ModifierType.MOD1_MASK & event.state) == Gd...
This function handles keyboard events to toggle scrollbars, move terminal cursors, split or close terminals, manage pages (rename/close/switch), navigate between pages, and execute clipboard operations in a terminal application. It uses key bindings to trigger specific UI actions, including fullscreen toggling and reor...
def on_keypress(self, widget, event): if self.key_event_compare('toggle_scrollbars_key', event): # Toggle value ConfigManager.set_conf('terminal', 'show_scrollbar', not ConfigManager.get_conf('terminal', 'show_scrollbar')) TerraHandler.execute_ui_event_handlers() ...
def check_visible(self): if not terra_utils.is_on_visible_screen(self): active_monitor = self.screen.get_monitor_workarea(self.screen.get_primary_monitor()) terra_utils.set_new_size(self, active_monitor, self.monitor) def init_transparency(self): self.set_app_paintable(True) ...
This code initializes a terminal window GUI by loading a GTK UI file, setting up event handlers for screen changes, configuring transparency, and displaying the window based on configuration settings. It ensures the UI file exists, connects to monitor changes, and prepares the interface for interaction.
def __init__(self, name, monitor): main_ui_file = os.path.join(TerraHandler.get_resources_path(), 'main.ui') if not os.path.exists(main_ui_file): msg = t('UI data file is missing: {}') sys.exit(msg.format(main_ui_file)) super(TerminalWin, self).__init__() self.s...
def subtaskA(data, outputname): #fetch data THREAD_SEQUENCE = data["THREAD_SEQUENCE"].tolist() RelQBody = data["RelQBody"].tolist() RelQSubject = data["RelQSubject"].tolist() RELC_ID = data["RELC_ID"].tolist() RelCText = data["RelCText"].tolist() #scores score_record = [] #rank r...
The function `excu_lda` loads a dataset from "test_use.csv" and sequentially executes three subtasks (A, B, C) related to LDA processing. Each subtask takes the data and outputs predictions to specified files. The main task involves applying LDA-based analysis to the dataset through these subtasks, likely for topic mod...
def excu_lda(): data = pd.read_csv(os.path.join(cur_dir, "test_use.csv"), engine='python') print("---lda subtaskA----") subtaskA(data, "lda_subtaskA.pred") print("---lda subtaskB----") subtaskB(data, "lda_subtaskB.pred") print("---lda subtaskC----") subtaskC(data, "lda_subtaskC.pred")
def determineValue(self): global max_int #if (self.board.lastHeight >= self.board.height): # return (self.depth + 1) * (-max_int) if (self.board.checkAnyT(self.playerNum)): return (self.depth+1) * max_int else: return 0 def generateChildren(self): global ma...
This code initializes a game state node, setting attributes like depth, player number, board state, and value. It adjusts the node's value using `determineValue()` if within limits, generates child nodes recursively if depth > 0, or calculates terminal rewards via `getRewards()`. The structure supports game tree explor...
def __init__(self, depth, playerNum, board, value, index): global max_int self.playColumn = 0 self.depth = depth self.playerNum = playerNum self.board = board self.value = value self.average = 0 if (abs(value) < max_int): self.value = self.determineValue()...
def random_swap(list, n): clist = deepcopy(list) for _ in range(n): a = random.randint(sr, len(list)-1) b = random.randint(sr, len(list)-1) temp = list[a] list[a] = list[b] list[b] = temp return clist def fitness(population, i): f_list = [1/(evaluation(order)+1) f...
This code implements a genetic algorithm to solve a path optimization problem on a map. It initializes a population of city permutations, iteratively evolves them through generations, tracks specific iterations, and visualizes progress if enabled. The goal is to find the minimal-cost route, returning the best solution ...
def perform(map, specific_iteration, animate): bfi.clear() cities = deepcopy(map.verticies) population_num = 10 population = [random_swap(cities, 2) for _ in range(population_num)] p_fitness = fitness(population, 1) specific_population = population if specific_iteration == 1 else None specif...
def pidx(self, p): pm = self.prms[-1] while p > pm: pm = self._erat2_next() return self._updpcoeff(p) def getreg(self, p): return self.regs % p def regop(self, p, m): m %= p if m == 0: return 0 pidx = self.pidx(p) if pidx < 0: ...
The code updates a register value by calculating the difference between a new value and the current register value, ensuring the new value is valid (0 ≤ m < p). If valid, it applies an operation (regop) to update the register and applies modulo self.pa to maintain constraints.
def setreg(self, p, m): if m >= p or m < 0: raise ValueError(f'invalid value reg{p}:={m}') self.pidx(p) sm = self.getreg(p) if sm == m: return self.regs += self.regop(p, m - sm) self.regs %= self.pa
def chksym(self, c, la1 = True): if la1: tt, tv = self.la1tok else: tt, tv = self.ctok return tt == 'symbol' and tv == c def stctx(self, st = None): if st is None: st = self.stat elif isinstance(st, int): st = self.stback(st) ...
This function parses a function definition or call by checking token types and keywords. It sets up a context for function arguments, processes built-in functions, validates their existence, and adds them to the program. It handles state transitions for argument sequences and error checking for invalid functions or unk...
def p_func(self): tt, tv = self.ctok if tt == 'word' and self.chksym(KW_BR1): ctx = self.stctx() ctx['name'] = tv ctx['args'] = [] self.stpush() self.stgo('argseq') self.ntok() self.ntok() elif self.chksym(KW_BR2...
def stctx(self, st = None): if st is None: st = self.stat elif isinstance(st, int): st = self.stback(st) if not st in self.ctxs: self.ctxs[st] = {} return self.ctxs[st] def chksym(self, c, la1 = True): if la1: tt, tv = self.la1tok ...
This function parses a sequence of arguments by checking the current token type. If the token is a word or digit, it appends the value to a context's argument list and handles potential closing brackets. If a closing bracket is found, it pops the context. Otherwise, it raises an error for invalid arguments, ensuring pr...
def p_argseq(self): tt, tv = self.ctok if tt == 'word' or tt == 'digit': ctx = self.stctx('func') ctx['args'].append(tv) if self.chksym(KW_BR2): self.stpop() self.ntok() elif self.chksym(KW_BR2, False): self.stpop() ...
def stctx(self, st = None): if st is None: st = self.stat elif isinstance(st, int): st = self.stback(st) if not st in self.ctxs: self.ctxs[st] = {} return self.ctxs[st] def stpop(self): if len(self.ststk) == 0: self.rerr('unbalance ...
The code processes a 'digit' token by capturing context values, appending a token pair to a sequence in the context, and advancing the token stream. If the token isn't a digit, it raises an error. The main task is handling digit-based pair parsing in a tokenizer/parser, managing context states and sequence storage.
def p_pair(self): tt, tv = self.ctok if tt == 'digit': sctx = self.stctx() dctx = self.stctx(1) if not 'seq' in dctx: dctx['seq'] = [] dctx['seq'].append((sctx['1st'], tv)) self.stpop() self.ntok() else: ...
def chksym(self, c, la1 = True): if la1: tt, tv = self.la1tok else: tt, tv = self.ctok return tt == 'symbol' and tv == c def stctx(self, st = None): if st is None: st = self.stat elif isinstance(st, int): st = self.stback(st) ...
This function parses a conditional expression in a grammar, handling two cases: 1) When a digit is followed by a label (KW_LBL), it creates a context for a pair and navigates states. 2) When encountering a special keyword (KW_SPL), it processes a sequence, constructs a program with the sequence, and transitions to an o...
def p_condi(self): tt, tv = self.ctok if tt == 'digit' and self.chksym(KW_LBL): ctx = self.stctx('pair') ctx['1st'] = tv self.stpush() self.stgo('pair') self.ntok() self.ntok() elif self.chksym(KW_SPL, False): ct...
def chksym(self, c, la1 = True): if la1: tt, tv = self.la1tok else: tt, tv = self.ctok return tt == 'symbol' and tv == c def stctx(self, st = None): if st is None: st = self.stat elif isinstance(st, int): st = self.stback(st) ...
This function parses operators in a programming language context. It handles digit labels by creating a context, pushing states, and transitioning to 'pair' processing. For newlines or EOF, it retrieves sequences, constructs operator lists, and adds them to the program's operation list via lambda functions. Errors are ...
def p_opr(self): tt, tv = self.ctok if tt == 'digit' and self.chksym(KW_LBL): ctx = self.stctx('pair') ctx['1st'] = tv self.stpush() self.stgo('pair') self.ntok() self.ntok() elif tt == 'newline' or tt == 'eof': ...
def __getNextInstr(self) -> Instruction: return self.__getInstrAtPC(self.pc + 1) def __setReg(self, indx: int, code: str, forceLocal: bool = False) -> None: # if the top indx is a local, set it if indx in self.locals: if self.__needsDefined(indx): self.__newLocal(indx...
This function parses a table structure from a sequence of LOADK and SETLIST instructions, constructing a string representation of the table by caching register values and appending elements during SETLIST operations. It then assigns the completed table to a specified register, forcing local scope, and handles any remai...
def __parseNewTable(self, indx: int): # TODO: parse SETTABLE too? tblOps = [Opcodes.LOADK, Opcodes.SETLIST] instr = self.__getNextInstr() cachedRegs = {} tbl = "{" while instr.opcode in tblOps: if instr.opcode == Opcodes.LOADK: # operate on registers ...
def __getCurrInstr(self) -> Instruction: return self.__getInstrAtPC(self.pc) def __getNextInstr(self) -> Instruction: return self.__getInstrAtPC(self.pc + 1) def __getInstrAtPC(self, pc: int) -> Instruction: if pc < len(self.chunk.instructions): return self.chunk.instructions[pc] ...
This function processes conditional jumps in code by determining the jump type (if/while/until), constructing appropriate syntax, and managing scopes. It checks jump destinations to identify loop structures, adds comparison expressions, and inserts keywords like 'repeat' for loops, adjusting code structure by modifying...
def __condJmp(self, op: str, rkBC: bool = True): instr = self.__getCurrInstr() jmpType = "if" scopeStart = "then" # we need to check if the jmp location has a jump back (if so, it's a while loop) jmp = self.__getNextInstr().B + 1 jmpToInstr = self.__getInstrAtPC(self.pc ...
def __loadLocals(self): for i in range(len(self.chunk.locals)): name = self.chunk.locals[i].name if isValidLocal(name): self.locals[i] = name elif "(for " not in name: # if it's a for loop register, ignore self.__makeLocalIdentifier(i) def __ma...
This code initializes a code chunk's execution context by setting up local variables, scopes, and instruction parsing. It handles function prototype creation for non-head chunks, populates local variables, and processes each instruction in the chunk while managing scope boundaries. Configuration flags control local tra...
def __init__(self, chunk: Chunk, headChunk: bool = True, scopeOffset: int = 0): self.chunk = chunk self.pc = 0 self.scope: list[_Scope] = [] self.lines: list[_Line] = [] self.top = {} self.locals = {} self.traceback = {} self.unknownLocalCount = 0 ...
def pre_processing(): df = pd.read_csv("data/Tweets.csv") # read from CSV file # Drop columns drop_columns = ["tweet_id", "airline_sentiment_confidence", "negativereason", "negativereason_confidence",\ "airline_sentiment_gold", "name", "tweet_coord", "user_timezone", "negativereason_...
The code processes text data for sentiment analysis, optionally incorporating BERT features. It splits data into train/val/test sets, applies TF-IDF and FastText embeddings, tunes Random Forest and MLP classifiers, and evaluates their performance using F1 scores. The main task is to compare model effectiveness with/wit...
def main(params): parser = argparse.ArgumentParser() parser.add_argument('--use_bert', type=int, default=False, help='Use BERT features') args = parser.parse_args(params) use_bert = bool(args.use_bert) df = pre_processing() if use_bert: print("Use BERT features") bert_out_df ...
def gen_toys_and_fit( b_true='default', s_true_i='default', f_sig_dist='default', g_bg_dist='default', nsim=int(1e4)): if isinstance(b_true,str) and (b_true.lower()=='default'): b_true = _b_true_default if isinstance(b_true, int): b_true = float(b_true) if not isin...
This function computes statistical properties of observed experiments using pre-simulated toy models, calculating maximum likelihood estimates, log-likelihoods, test statistics, p-values, and confidence limits for each experiment. It processes observed event counts and values to derive upper/lower limits on parameters ...
def obs_stats(Nevts,x_obs,d=None, p0=0.1,**kwargs): """ Calculate statistics of one or more observed experiments (without knowing the true identity of the events, like in the toys). Inputs: Nevts: 1D Numpy array (NOT a scalar) of dtype int. The length of this array is the number ...
def eventbuild(event, dist): # (c) 2021 Madelyn Sita # determine travel times using obspy mtimes = mars.get_travel_times(source_depth_in_km= depth, distance_in_degree=dist, phase_list=['P','S']) # ray parameters & incidence angles at the station Pp = mtimes[0].ray_param ; Pa = mtimes[0].incident_an...
This function processes seismic event data for 'S0325ab' by building event parameters, calculating amplitudes using fault characteristics, adjusting data with observed values, and saving results to CSV files. It checks a counter 'n' to either create a new file or append data, ensuring proper handling of seismic wavefor...
def eventoutput(depth,rank): #----------- S0325AB ------------------- print('325ab') Pp, Sp, Pa, Sa = eventbuild('325a', 38.4) data325ab, Pe, Se = getamp(-45.6, strike_325ab, dip_325ab, rake_325ab, [Pp, Sp]) data325ab = autofault(data325ab, obsP=-1.35e-9, obsSV=-4.06e-9, obsSH=0.25e-9, errP=1.75e-1...