dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def _check_table_exists(table_name): """ Check if table exists """ inspector = Inspector.from_engine(engine) if table_name in inspector.get_table_names(): return True return False def _create_tables(): """ Create tables """ Base.metadata.create_all(engine) def _exists_on_...
The main task of the code is to synchronize data from the 'imdb_movies' table to the 'fl_movies' table in a database, ensuring no duplicates by checking existing entries. It retrieves unprocessed rows from 'imdb_movies', filters out those already in 'fl_movies', inserts valid entries into 'fl_movies' with conflict hand...
def update_fl_database(engine=None, check_again=False): engine = engine or create_engine(DB_URI, echo=False, isolation_level="AUTOCOMMIT") if not _check_table_exists('fl_movies'): _create_tables() # get rows from imdb_movies with engine.connect() as conn: if not check_again: ...
def branch_size(branch): count = 0 if type(branch) is str: return 1 for b in branch: if type(b) is str: count += 1 if b != "" else 0 else: count += branch_size(b) return count def map_values(mapping: Dict, state: Union[List, str]): output = [] if t...
The function `parse_stages` processes a nested list structure (`state`) by mapping its elements using a provided dictionary (`mapping`), parsing each mapped element into branches, and collecting results. It calculates offsets (lengths of each sublist and their branch sizes) for tracking positions. The main task is to t...
def parse_stages(mapping: Dict, state: List[List]): output = [] offsets = [] for s in state: offsets.append(len(s)) offsets.append(branch_size(s)) unpacked = [] for s in state: unpacked.append(*s) for s in unpacked: s = map_values(mapping, s) output = outp...
def _build_recognition_net(self,input_): # Foward pass for recognition network and get potential recog_out = self.recognitionnet._build_network(input_)# shape: [batch,2N] # Outout of NN encode mu and the diag of sigma recog_mu = tf.reshape(recog_out[:,:self.N],[-1,1,self.N,1])# shape: [b...
This function computes the SVAE objective by combining variational inference with a recognition network and generator network. It calculates the local KL divergence between approximate and true posteriors, reconstructs inputs via the generator, computes log-likelihood, and optimizes the SVAE objective (log-likelihood m...
def _create_loss_optimizer(self,gaussian_global,label_global,label_stats_init,y,learning_rate,batch): """ Compute the SVAE objective using reparametrization trick for likelyhood term shape: - gaussian_global: [batch,K,N,N+1] - label_global: [batch,K,1] - ...
def process_seq(self_seq, args, isbackbone, need_mask=False): L = len(list(self_seq.values())[0]) names = list(self_seq.keys()) seqs = np.zeros([4, len(self_seq), L]) if need_mask: mask = np.ones([1, len(self_seq), L]) raw_seqs = [np.array(self_seq[k].seq).reshape(1, -1) for k in self_seq] ...
The main task of the code is to compute and save a distance matrix between query and backbone sequences using a model or recon_model. It processes input sequences, generates embeddings, calculates pairwise distances based on specified modes (e.g., hyperbolic), and outputs the results as a CSV file. The code handles par...
def save_depp_dist(model, args, recon_model=None): t1 = time.time() if model is not None: model.eval() args.replicate_seq = model.hparams.replicate_seq args.distance_ratio = model.hparams.distance_ratio args.gap_encode = model.hparams.gap_encode args.jc_correct = model.hp...
def heuristic(self, s) -> float: curr_x, curr_y = self.env.to_row_col(s) goals = self.env.get_goal_states() if not goals: return 0 h_s = float('inf') for g in goals: g_x, g_y = self.env.to_row_col(g) Manhattan_distance = abs(g_x-curr_...
This code implements an informed search algorithm (likely A*) to find a path in a FrozenLake environment. It uses a priority queue (heapdict) for open nodes and a set for closed nodes, expanding states while avoiding revisits. The heuristic guides exploration, returning the solution path, expanded nodes count, and cost...
def search(self, env: FrozenLakeEnv) -> Tuple[List[int], int, float]: self.env = env start_node = Node(env.get_initial_state()) open_list=heapdict.heapdict() open_list[start_node]=(self.heuristic(0),0) #in the open_list, the key is the node and the value a tupl...
def weighted_f(self,state, weight_h, g)-> float: g_s = (1-weight_h)*g h_s = self.heuristic(state) h_s_weighted = weight_h*h_s res = (g_s + h_s_weighted) return res def solution(self, node) -> Tuple[List[int], int, float]: actions, cost = self.actions_cost_calculus(node, [...
The code implements a weighted A* search algorithm to find an optimal path in a FrozenLake environment. It uses an open list (priority queue) and closed list to track nodes, expanding states by evaluating weighted f-values (combining cost and heuristic). The algorithm prioritizes nodes with lower f-values, updates path...
def search(self, env: FrozenLakeEnv, h_weight) -> Tuple[List[int], int, float]: self.env = env env.reset self.weight = h_weight start_node = Node(env.get_initial_state()) open_list=heapdict.heapdict() open_list[start_node]=(self.weighted_f(0,self.we...
def heuristic(self, s) -> float: curr_x, curr_y = self.env.to_row_col(s) goals = self.env.get_goal_states() if not goals: return 0 h_s = float('inf') for g in goals: g_x, g_y = self.env.to_row_col(g) Manhattan_distance = abs(g_x-curr_x) + abs(...
This code implements a depth-first search with a cost limit (f_limit) to find a solution in a state space. It calculates the f-value (node.g + heuristic) and prunes paths exceeding f_limit. If the current node is a goal state, it returns the solution; otherwise, it explores child nodes, avoiding cycles via the 'path' s...
def dfs_f(self, node, f_limit, path): new_f = node.g + self.heuristic(node.state) if new_f > f_limit: self.new_limit = min(self.new_limit, new_f) return self.failure() if self.env.is_final_state(node.state): return self.solution(node) for i in {0,1...
def heuristic(self, s) -> float: curr_x, curr_y = self.env.to_row_col(s) goals = self.env.get_goal_states() if not goals: return 0 h_s = float('inf') for g in goals: g_x, g_y = self.env.to_row_col(g) Manhattan_distance = abs(g_x-curr_x) + abs(...
The code implements an informed search algorithm (likely IDA*) to find the optimal path in a FrozenLake environment. It initializes with the start state, uses a heuristic to set a threshold, and performs depth-first search (DFS) within that limit. If a solution is found, it returns the path, total cost, and steps; othe...
def search(self, env: FrozenLakeEnv) -> Tuple[List[int], float, int]: self.env = env self.new_limit = float('inf') initial_state = self.env.get_initial_state() nodes_in_path = set() start_node = Node(initial_state) self.new_limit = self.heuristic(initial_state) ...
def relative_abundence(data): final_data = data.copy() for colname in data.columns: if sum(data[colname]) > 0: final_data.loc[:, colname] = data[colname] / sum(data[colname]) return final_data def test_groups_by_depths(A, B, OF): A_depths = [] for anomaly in A: A_depths.a...
This code performs repeated unsupervised testing using a forest model. It normalizes input data, runs the model 'times' iterations with parameters psi (sub-sample size), l (depth limit), and t (trees). For each iteration, it calculates group depths, stores results in a DataFrame, and exports them as a tab-separated fil...
def unsupervised_test(times, data, psi, l, t, distance_matrix, dir_name): data = relative_abundence(data) df = pd.DataFrame() samples = data.columns df["samples"] = samples all_depths = [] for i in range(times): OF = Forest(0, []) OF.fit(data, psi, l, t, distance_matrix) ...
def relative_abundence(data): final_data = data.copy() for colname in data.columns: if sum(data[colname]) > 0: final_data.loc[:, colname] = data[colname] / sum(data[colname]) return final_data def concat_data_frames(lst, axis): df = pd.DataFrame() for d in lst: df = pd.co...
The function simulates microbial data contamination by injecting outliers from contaminating_data into basic_data at specified percentages. It iterates multiple times, evaluates detection performance using supervised tests, and collects metrics like AUC scores, depths, and comparisons. Results are saved as CSVs, with o...
def contamination_test(times, contamination_percentage, basic_data, contaminating_data, outliers_percentage_sample, psi, l, dir_name, different_sample): # filter to common features features_intersection = pd.Series(list(set(basic_data["#OTU ID"]).intersection(set(contaminating_data["#OTU ID"])))) basic_dat...
def _init_placeholders(self): '''Initialize training inputs here''' self.X = tf.placeholder(self.dtype, shape=[None, self.get_input_dim()]) if self.use_differential_points: self.X_df = tf.placeholder( self.dtype, shape=[None, self.get_input_dim()]) self.U = t...
This method constructs a TensorFlow computation graph for a neural network model, initializing placeholders, parameters, forward passes, loss functions, gradient operations, and optimizers. It finalizes the graph, creates a session, and initializes variables to prepare for training or inference.
def _build_graph(self): ''' Builds the full computation graph. Each _method is meant to be an integration point modifiable by subclasses ''' with self.graph.as_default(): self._init_placeholders() self._init_params() self.U_hat = self._forwa...
def _reset(self): self.number_string = '' def _append_string(self, string): """Append 'string' to the intermediate result. """ if self.number_string: self.number_string += ' ' self.number_string += '{}'.format(string) def _split_to_sections(self, number): """Returns l...
The code converts a given integer into its fully worded string representation (e.g., 123 → "one hundred twenty-three"), validating the input is an integer within the range 0–1 trillion. It processes the number by splitting it into sections (thousands, millions, etc.), appending words for each section, and constructs th...
def get_string(self, input_number): """Process given input_number and return it's fully worded string representation. """ try: input_number = int(input_number) except ValueError: raise ValueError(_('Integer is required as an input. ')) # check number is i...
def roll_dices(): # returns a tuple of 2 random ints n1 = random.randint(1, 6) n2 = random.randint(1, 6) tup = (n1, n2) show_message(str(tup), WHITE, 350, 200) show_dices(tup) return tup def what_cell(x, y): # gets x and y values and returns number of cell in that position (if any) ...
The function handles a player's turn in a board game by rolling two dice, allowing the player to make moves based on the dice values (either 2 or 4 moves depending on whether the dice are the same), processing user clicks to select starting and target cells, validating legal moves, updating the board and screen, and sw...
def players_turn(board): # rolls 2 dices and shows them. gets a board and receives 2 click inputs from screen every time; # moves a pip on players turn from first cell clicked to second one clicked and updates the # screen. Does that twice if dices are different, and 4 times if dices are the same (whenever ...
def show_dices(tup): # gets a double of dices and shows them on screen pygame.draw.rect(screen, WHITE, [330, 230, 40, 40]) pygame.draw.rect(screen, WHITE, [330, 330, 40, 40]) pygame.draw.rect(screen, BLACK, [330, 230, 40, 40], 2) pygame.draw.rect(screen, BLACK, [330, 330, 40, 40], 2) for i in ...
The function simulates the computer's turn in a game by rolling dice, generating possible moves, and using the expectimax algorithm with a heuristic set to select the optimal next board state. If no valid moves exist, it retains the current board. The updated board is displayed and returned.
def computers_turn(board, depth, h_set): # gets the board, the depth to go in the expectimax algorithm, and an h_set for the computer to "play by". # makes a computer turn and returns the new board. dice1 = random.randint(1, 6) dice2 = random.randint(1, 6) tup_dices = (dice1, dice2) show_dices(...
def detect_landmarks(face, context): """Detect 5-point facial landmarks for faces in frame.""" predictor = get_landmarks_predictor() l, t, w, h = face['box'] rectangle = dlib.rectangle(left=int(l), top=int(t), right=int(l+w), bottom=int(t+h)) landmarks_dlib = predictor(context['gray'], rectangle) ...
The code processes facial features to predict gaze direction. It detects landmarks and eyes, preprocesses eye images, concatenates them, reshapes data, feeds into a neural network via TensorFlow, and stores resulting heatmaps, landmarks, and radius in the 'gaze' attribute of the face object.
def _predict(face, context): detect_landmarks(face, context) detect_eyes(face, context) if(len(face['eyes']) != 2): return eye1 = eye_preprocess(face['eyes'][0]['image']) eye2 = eye_preprocess(face['eyes'][1]['image']) eyeI = np.concatenate((eye1, eye2), axis=0) eyeI = eyeI.reshape(2...
def get_household_name(): household_name = "" valid = False while not valid: household_name = input("\n\tEnter household name: ") try: Household.is_valid_name(household_name) valid = True except ValueError as err: print(err) return household_na...
The main task of the code is to create a new household by collecting its name, participants, and chores, then adding it to a list of households if it doesn't already exist. If the household exists, it alerts the user and avoids duplication.
def create_household(all_households): # Get new household name new_household_name = get_household_name() # Check if the household already exists household_obj = household_exists(new_household_name, all_households) # Returns None if does not already exist if household_obj is None: # Get p...
def getSelectedIndices(self): """ Custom: get source model indices of the selected item(s) :return: list of QModelIndex. selected indices """ indices = self.selectionModel().selectedRows() return [self.model().mapToSource(index) for index in indices] def remove(self, ind...
The code creates a context menu for a widget, offering actions like 'add', 'remove', 'copy', 'paste', or 'clear' based on selection state and data type. It dynamically populates menu options: 'add' and 'clear' when no items are selected, 'remove'/'copy' for multiple selections, and 'add'/'paste' for single selections o...
def openContextMenu(self): """ Custom: create a right-click context menu """ contextMenu = QtWidgets.QMenu() indices = self.getSelectedIndices() # no selection if not indices: addAction = contextMenu.addAction('add entry') addAction.trigge...
def get(self, endpoint, *args, **kwargs): self.validate_session() res = requests.get(self.domain + endpoint, headers=self.header, **kwargs, auth=self.auth) if 'raw' in args: return res else: return res.json() if res.ok else False def get_item_name(self, item_type,...
This function retrieves the unique ID of a specified item (database, table, card, etc.) from an API by querying based on the item's name and optional parameters like collection, database, or table identifiers. It ensures the item exists, is not archived, and handles errors for duplicate or missing items.
def get_item_id(self, item_type, item_name, collection_id=None, collection_name=None, db_id=None, db_name=None, table_id=None): assert item_type in ['database', 'table', 'card', 'collection', 'dashboard', 'pulse', 'segment'] if item_type in ['card', 'dashboard', 'pulse']: ...
def get_db_id_from_table_id(self, table_id): tables = [i['db_id'] for i in self.get("/api/table/") if i['id'] == table_id] if len(tables) == 0: raise ValueError('There is no DB containing the table with the ID "{}"'.format(table_id)) return tables[0] def friendly_names_is_disabled(...
This function retrieves column name-to-ID or ID-to-name mappings for a specified table, using either its name or ID. It fetches database fields via an API, filters by table name, and returns a dictionary with keys/values swapped based on the 'column_id_name' flag. If no table name is provided, it infers it from the ID,...
def get_columns_name_id(self, table_name=None, table_id=None, column_id_name=False): """ Return a dictionary with col_name key and col_id value, for the given table_id/table_name in the given db_id/db_name. If column_id_name is True, return a dictionary with col_id key and col_name value...
def get_item_id(self, item_type, item_name, collection_id=None, collection_name=None, db_id=None, db_name=None, table_id=None): assert item_type in ['database', 'table', 'card', 'collection', 'dashboard', 'pulse', 'segment'] if item_type in ['card', 'dashboard', 'pulse']: ...
This function copies a pulse from a source collection to a destination collection, allowing specification of source/destination by name or ID. It handles automatic ID lookup if names are provided, constructs a new pulse name with an optional postfix if not specified, and creates a new pulse entry in the destination col...
def copy_pulse(self, source_pulse_name=None, source_pulse_id=None, source_collection_name=None, source_collection_id=None, destination_pulse_name=None, destination_collection_id=None, destination_collection_name=None, postfix=''): """ Copy the pul...
def get_item_id(self, item_type, item_name, collection_id=None, collection_name=None, db_id=None, db_name=None, table_id=None): assert item_type in ['database', 'table', 'card', 'collection', 'dashboard', 'pulse', 'segment'] if item_type in ['card', 'dashboard', 'pulse']: ...
This function archives specified items (card, dashboard, collection, pulse, segment) by sending a PUT request to an API endpoint with 'archived': True. It retrieves item IDs from names if not provided, handles type-specific parameters (e.g., table_id for segments), and verifies success via HTTP status codes. It avoids ...
def move_to_archive(self, item_type, item_name=None, item_id=None, collection_name=None, collection_id=None, table_id=None, verbose=False): """Archive the given item. For deleting the item use the 'delete_item' function.""" assert item_type in ['card', 'dashboard', 'collection', ...
def verbose_print(verbose, msg): if verbose: print(msg) def get_item_id(self, item_type, item_name, collection_id=None, collection_name=None, db_id=None, db_name=None, table_id=None): assert item_type in ['database', 'table', 'card', 'collection', 'dashboard', 'pulse', '...
The main task of the code is to create a card via a POST request to the '/api/card/' endpoint, either using a provided custom JSON configuration or by constructing a JSON from parameters like database/table details, column order, and collection information. It handles data source selection, collection placement, column...
def create_card(self, card_name=None, collection_name=None, collection_id=None, db_name=None, db_id=None, table_name=None, table_id=None, column_order='db_table_order', custom_json=None, verbose=False, return_card=False): """ Create a card using the given argument...
def get_item_id(self, item_type, item_name, collection_id=None, collection_name=None, db_id=None, db_name=None, table_id=None): assert item_type in ['database', 'table', 'card', 'collection', 'dashboard', 'pulse', 'segment'] if item_type in ['card', 'dashboard', 'pulse']: ...
The function creates a segment by defining a filter on a specified column and sending it to the '/api/segment/' endpoint. It validates table inputs, retrieves necessary IDs, constructs a segment blueprint with filtering logic, and returns the API response if requested.
def create_segment(self, segment_name, column_name, column_values, segment_description='', db_name=None, db_id=None, table_name=None, table_id=None, return_segment=False): """ Create a segment using the given arguments utilizing the endpoint 'POST /api/segment/'. Keyword...
def get_item_id(self, item_type, item_name, collection_id=None, collection_name=None, db_id=None, db_name=None, table_id=None): assert item_type in ['database', 'table', 'card', 'collection', 'dashboard', 'pulse', 'segment'] if item_type in ['card', 'dashboard', 'pulse']: ...
The main task of the code is to update a column's properties in a data model via the Metabase API using parameters like column/table IDs or names. It retrieves necessary IDs if not provided, validates inputs, and sends a PUT request to the API endpoint `/api/field/{column_id}` with the given `params`. It returns the HT...
def update_column(self, params, column_id=None, column_name=None, table_id=None, table_name=None, db_id=None, db_name=None): """ Update the column in data model by providing values for 'params'. E.g. for changing the column type to 'Category' in data model, use: params={'se...
def get_item_id(self, item_type, item_name, collection_id=None, collection_name=None, db_id=None, db_name=None, table_id=None): assert item_type in ['database', 'table', 'card', 'collection', 'dashboard', 'pulse', 'segment'] if item_type in ['card', 'dashboard', 'pulse']: ...
This function copies a card from a source collection to a destination collection by retrieving card and collection IDs, adjusting the destination card name with a postfix if needed, updating the card's collection ID and name, and creating a new card instance. It returns the ID of the newly created card.
def copy_card(self, source_card_name=None, source_card_id=None, source_collection_name=None, source_collection_id=None, destination_card_name=None, destination_collection_name=None, destination_collection_id=None, postfix='', verbose=False): ...
def get_item_id(self, item_type, item_name, collection_id=None, collection_name=None, db_id=None, db_name=None, table_id=None): assert item_type in ['database', 'table', 'card', 'collection', 'dashboard', 'pulse', 'segment'] if item_type in ['card', 'dashboard', 'pulse']: ...
The function clones a card by replacing its source table with a target table, updating filters to reference the new table. It handles both native SQL and query-based cards, ensuring column mappings match between source and target tables (same DB, column names). Parameters include card ID, target table details, new name...
def clone_card(self, card_id, target_table_id=None, target_table_name=None, new_card_name=None, new_card_collection_id=None, ignore_these_filters=None): """ Create a new card where the source of the old card is changed from 'source_table_id' to 't...
def init_midas_depth_model(midas_model_type="dpt_large", optimize=True): midas_model = None net_w = None net_h = None resize_mode = None normalization = None print(f"Initializing MiDaS '{midas_model_type}' depth model...") # load network midas_model_path = default_models[midas_model_typ...
The code generates animated images using diffusion models, supporting 2D/3D animations and video input. It processes frames with transformations, CLIP embeddings for prompt alignment, and diffusion sampling (DDIM/PLMS). Key tasks include seed management, frame interpolation, depth estimation (Midas), turbo blending for...
def do_run(): seed = args.seed print(range(args.start_frame, args.max_frames)) if (args.animation_mode == "3D") and (args.midas_weight > 0.0): midas_model, midas_transform, midas_net_w, midas_net_h, midas_resize_mode, midas_normalization = init_midas_depth_model(args.midas_depth_model) for frame_num in r...
def initialize(self): self.status = {} for n, _ in self.nbrList: self.status[n] = BASIC self.parent = None bNbr, _ = self.nbrList[0] self.name,self.status[bNbr],self.level,self.state,self.rec = 0,BRANCH,0,FOUND,0 bNbr = nodeInfo[bNbr] sendData = {} sendD...
The code processes incoming messages in a loop until `isRunning()` returns true. It receives data, checks its type, and invokes corresponding handler methods like `recv_connect`, `recv_initialte`, etc., based on message types such as `MSG.CONNECT` or `MSG.REJECT`. Unrecognized types break the loop. The main task is han...
def work(self): self.initialize() while False == self.isRunning(): ret, type1,data = self.receive() if ret == False:continue if type1 == MSG.CONNECT: self.recv_connect(data) elif type1 == MSG.INITIATE: self.recv_initialte(da...
def load_dataset(file_name): data_frame = pd.read_csv(file_name, delimiter=',', header=None) return np.array(data_frame) def create_scatter_plot(title, x, y, labels): colors = ['red', 'green', 'blue'] plt.xlabel('x axis') plt.ylabel('y axis') plt.title(title) plt.scatter(x, y, c=labels, cmap...
The main task of the code is to load a dataset, visualize its original data distribution, and apply three clustering algorithms (k-means, farthest centers, and spectral clustering) with a given $ k $, generating scatter plots to compare their clustering results. The function demonstrates and visualizes different cluste...
def task(filename, k): dataset = load_dataset(filename) create_scatter_plot('Data scatter plot for ' + filename, dataset[:, 0], dataset[:, 1], dataset[:, -1]) # algorithmn1 table, centers = k_means_clustering(dataset[:, :2], k) create_scatter_plot('K means clustering for ' + filename, dataset[:, 0]...
def conv_layer(self, bottom, kernel_size, out_channel, name, is_BN, trainable): """Construct conv-layer.""" with tf.variable_scope(name) as scope: kernel = self._variable_with_weight_decay( "weights", shape=[kernel_size, kernel_size,...
This function constructs a VGG-like CNN with 16 convolutional layers and 3 pooling stages, followed by two fully connected layers (4096 units each) with dropout, and a final classification layer. It uses batch normalization during training to build a 16-layer model for image classification tasks.
def cnn_fc(self, input_, is_train, name): """Build vgg model D with 16 layers.""" is_BN = True with tf.variable_scope(name): conv1 = self.conv_layer(input_, 3, 64, 'conv1', is_BN, is_train) conv2 = self.conv_layer(conv1, 3, 64, 'conv2', is_BN, is_train) pool1...
def _image_summary(self, x, channels): def sub(batch, idx): name = x.op.name tmp = x[batch, :, :, idx] * 255 tmp = tf.expand_dims(tmp, axis=2) tmp = tf.expand_dims(tmp, axis=0) tf.summary.image(name + '-' + str(idx), tmp, max_outputs=100) if se...
This code builds a VGG model by processing input images through a CNN with fully connected layers (cnn_fc), computes cross-entropy loss for training, and returns the final output of the fully connected layer. It also logs image summaries and integrates loss calculations for model training.
def build_model(self, is_train): """Get builded vgg model.""" with tf.name_scope("original_images"): self._image_summary(self.images, self.channel_num) out_fc = self.cnn_fc(self.images, is_train, 'fc') self.add_to_cross_entropy(self.batch_size, out_fc, self.labels, 'fcn') ...
def calculate_mallet_cords(lx): l1 = 0.029 l2 = .17186 gap = 0.05 angles, m_distances, _ = data() rad_to_use = np.interp(lx, m_distances, angles) angle_a = law_of_cosines_angle(l2,l2, lx - gap) angle_b = rads(120) - angle_a mx = find_x_mallet(lx) my = find_y_mallet(l1,l2,angle_a, angle_b) print("Y cord:...
This function calculates the adjusted coordinates of a mallet's position based on wrist rotation and side (left/right), then returns the adjusted position. If 'execute' is True, it also sets the gripper angle to the calculated rotation angle.
def find_and_set_mallet_location(self, execute=True): mx, my, rads = calculate_mallet_cords(self.mallet_distance) if execute: self.set_gripper_angle(rads) # Adjust for wrist rotation rotation = self.get_wrist_rotation() x_pos = (mx)*math.cos(rotation) if self.left: return (-x_pos, my) ...
def get_distance(self, n1, n2): return min(0.155, np.abs(self.m[n1][0] - self.m[n2][0])) def find_and_set_mallet_location(self, execute=True): mx, my, rads = calculate_mallet_cords(self.mallet_distance) if execute: self.set_gripper_angle(rads) # Adjust for wrist rotation rotation = self.get_wri...
The code's main task is to play a sequence of musical notes by processing each note's parameters, adjusting the mallet's position based on distance changes, calculating target coordinates, and executing movements to strike the note, ensuring precise timing and positioning for each note in the song.
def play_song(self, notes): for n1, n2, left in notes: self.left = left note = n1 if left else n2 # Check if mallet distance changed mallet_distance = self.get_distance(n1, n2) execute = mallet_distance != self.mallet_distance self.mallet_distance = mallet_distance mallet_locatio...
def get_or_create_book(data): """Helper function for a book. Based on data, either gets a book from the database or creates a new one. @param: data """ book = None make_new_book = False # check if at least one book by that title already exist in the database if Book.objects.filter(title=data...
This code handles book-related operations via POST and PUT requests, including creating books, associating them with users, updating book details, and removing books. It validates input data, ensures user authentication, and manages book-user relationships through functions like get_or_create_book, relate_book_to_user,...
def book(request): """Backend for books. Handles GET, POST, and PUT requests. @param: request """ if request.method == "GET": # try to get information about a certain book? return JsonResponse({"error": "Cannot GET yet."}, status=400) elif request.method == "POST": data = jso...
def handle_shelf_post(request): """Helper function to handle the POST request for the shelf form. Called by the shelf view (POST request). @param: request - the request object """ # load data from request data = json.loads(request.body) # get the user user = User.objects.get(username=request...
This code defines a Django view function `shelf` that handles HTTP requests for a "shelf" resource. It processes POST, PUT, and DELETE requests by delegating to respective helper functions (`handle_shelf_post`, `handle_shelf_put`, `handle_shelf_delete`), while rejecting GET requests with an error. The main task is to m...
def shelf(request): """View for the shelf page. Handles GET, POST, PUT, and DELETE requests.""" if request.method == "GET": return JsonResponse({"error": "Cannot GET yet."}, status=400) elif request.method == "POST": return handle_shelf_post(request) elif request.method == "PUT": ...
def getMagData(self, filter_type, return_1D_lists=None, **kwargs): #returns HJD, mag, dmag, and plot color lists. Maybe I should make this a thing in the AIJFile class also so I can just call that from this function for each file? """ Calculates magnitude of Target object for all data points added and r...
The method fits a Fourier series to astronomical light curve data from a specified filter type, returning optimized parameters (popt) and their covariance (pcov). It retrieves magnitude data, computes phase values, and uses a Fourier fitting function to determine the best-fit parameters. If enabled, it plots the fitted...
def getFourierFit(self, filter_type, lineFmt=None, showPlot=None, forceN=None, **kwargs): """ Fits a Fourier series to data added to target in filter_type :param filter_type: filter in which data to be fitted was taken :type filter_type: str :param lineFmt: matplotlib pa...
def _getRefStarInfo(self, **kwargs): #returns a list of the reference star numbers and their magnitudes for the file; you can specify specific reference stars to use if you don't want to use all of them. """ Returns the aperture number and magnitudes for reference stars in self.ref_star_dict ...
This function clips data points from a file where the reference star's magnitude exceeds sigma standard deviations from its mean, creating a new clipped .txt file with "_clipped" appended to the original name. It uses the reference star's data to determine which points to retain, updates the filename to the clipped ver...
def clipFile(self, ref_star, sigma, **kwargs): """ Clips data points from file if the magnitude of ref_star is more that sigma standard deviations away from its mean magnitude. Actually creates a new .txt file in the same directory with the same name, with _clipped appended to the end and uses this new ...
def endpoints(self): cs = np.array([[self.trajs[0].xs[0],self.trajs[0].xs[-1]], [self.trajs[0].ys[0],self.trajs[0].ys[-1]]]) xs = np.hstack([t.xs[0] for t in self.trajs] + [t.xs[-1] for t in self.trajs]) ys = np.hstack([t.ys[0] for t in self.trajs] + [t.ys[-1] for t in self.trajs]) ...
The function `getAvg` computes a simplified trajectory by averaging or taking the median of filtered paths. It filters trajectories based on length and distance, calculates median/average points using `np.median`/`np.mean`, applies the RDP algorithm (with `eps`) to simplify the path, and returns the simplified coordina...
def getAvg(self, dismax, lenlim, eps, stat='Med.'): # median self.eps = eps self.endpoints() self.getFiltered(dismax, lenlim) atleast = 4 if len(self.filtix) <= atleast: distrank = np.argsort(self.d) self.disoutix = distrank[atleast:] ...
def _create_dataloader(self, data: Dataset, **kwargs) -> DataLoader: return DataLoader( data, collate_fn=self.config.collate_fn, num_workers=self.config.dataloader_num_workers, persistent_workers=self.config.dataloader_persistent_workers, pin_memory=se...
This function performs inference on a dataset using a trained model, processing batches to generate outputs and optionally calculate metrics. It initializes a dataloader, switches the model to evaluation mode, iterates through data batches, accumulates model outputs, updates metrics if enabled, and returns the collecte...
def infer( self, dataset: Dataset, calculate_metrics: bool = False ) -> Tuple[ModelOutputsType, Dict[ClassifierType, float]]: dataloader = self._create_dataloader(dataset, batch_size=self.config.batch_size_eval) context = InferContext( trainer=self, data_loader=da...
def _set_training_state(context: BaseContext): context.model.train() if isinstance(context, BaseTrainContext): context.logger.update_top_classifier(('step', 'train')) def _forward_pass(self, context: BaseContext, data: DataType) -> Optional[Tuple[Tensor, ModelOutputsType]]: data = se...
This code trains a model for one epoch by iterating through data batches, performing forward passes, updating model parameters via backpropagation with gradient accumulation, applying learning rate scaling and gradient clipping, logging training metrics, and optionally evaluating the model and saving checkpoints at spe...
def _train_epoch(self, context: TrainContext): self._set_training_state(context) context.progress_bar.update( context.get_step_from_batch(context.get_actual_batch_i(0)) - 1 - context.progress_bar.n ) for batch_i, data in enumerate(context.data_loader): batch_i = ...
def _calculate_batches_in_epoch(self, dataset: Dataset): return int(math.ceil(len(dataset) / self.config.batch_size)) def _calculate_total_steps(self, dataset: Dataset): return self._calculate_steps_in_epoch(dataset) * self.config.epochs def _create_metrics(self) -> Dict[str, Metric]: metrics = ...
The code trains a machine learning model using provided datasets, handling resumption from checkpoints, optimizer/scheduler setup, and logging. It initializes model components, loads states if resuming, creates data loaders, and iterates over epochs with progress tracking. Each epoch configures data sampling, executes ...
def train(self, train_data: Dataset, eval_data: Dataset, resume_from: int = -1): exp_name = self.config.experiment_name batches_in_epoch = self._calculate_batches_in_epoch(train_data) total_train_steps = self._calculate_total_steps(train_data) # Initialize and wrap model, optimizer and...
def stmlsvd(T: np.ndarray, size_core: tp.Union[int, list, None] = None, perm: tp.Union[list, np.ndarray, None] = None, **varargin: bool) -> tp.List[np.ndarray]: """ Sequentially truncated Multilinear SVD. Parameters ---------- T : NumPy array Tensor. ...
The function performs Canonical Polyadic Decomposition (CPD) of a tensor using symmetric Generalized Eigenvalue Decomposition (GEVD). It computes factor matrices by applying SVD, eigen-decomposition, and tensor operations on the input tensor `T` with rank `R`. Optional parameters allow normalization of columns or retur...
def cpdgevd2(T: np.ndarray, R: int, normcols: bool = False, thirdonly: bool = False) -> tp.List[np.array]: """ Canonical Polyadic Decomposition via symmetric GEVD. Parameters ---------- T : NumPy array Tensor. R : int Rank. normcols : bool, optional...
def cheapUT(X: np.ndarray) -> np.ndarray: """ Cheap unitary transformation. Parameters ---------- X : NumPy array Input tensor. Returns ------- NumPy array Unitary transformed tensor. """ R = X.ndim - 1 if R == 1: Y = qunit(X.shape[0]).conj().T @ X ...
The code implements the Unitary Tensor ESPRIT algorithm to estimate shift-invariance eigenstructures from a tensor input. It processes the input tensor using either matrix-based or structured Kronecker projection methods for signal subspace estimation, applying unitary transformations to handle complex data. The functi...
def ute(X: np.ndarray, D: int, matrix_sse: bool = False, kron_sse: bool = False, cheap: bool = True) -> tp.List[np.ndarray]: """ Unitary Tensor ESPRIT Parameters ---------- X : np.ndarray Input tensor. D : int Model order. matrix_sse : bool, o...
def stmlsvd(T: np.ndarray, size_core: tp.Union[int, list, None] = None, perm: tp.Union[list, np.ndarray, None] = None, **varargin: bool) -> tp.List[np.ndarray]: """ Sequentially truncated Multilinear SVD. Parameters ---------- T : NumPy array Tensor. ...
The function `cpdgevd` performs Canonical Polyadic Decomposition (CPD) of a third-order tensor using Generalized Eigenvalue Decomposition (GEVD). It decomposes the input tensor `T` into rank-$ R $ factor matrices by first applying SVD, computing generalized eigenvalues, and constructing factor matrices from the resulti...
def cpdgevd(T: np.ndarray, R: int, normcols: bool = False) -> tp.List[np.array]: """ Canonical Polyadic Decomposition via GEVD (CPD-GEVD). Decomposes a third-order tensor into its canonical polyadic components via generalized eigenvalue decomposition. Parameters ---------- ...
def _handle_traceroute(args, sites_data_file: Path, sites_bad_data_file: Path): _collect_data(sites_data_file, sites_bad_data_file, args.sites) def _handle_collect(args, popular_sites_data_file: Path, bad_popular_sites_data_file: Path, popular_sites_list: list[str], frequent_...
The code sets up directories and data files for tracking popular/frequent websites, validates required input files, and initializes CSV storage for site data. It parses command-line arguments for three subcommands: `traceroute` (analyze site paths), `collect` (gather site data), and `analyze` (evaluate site status). Th...
def main(): # ######################################################## # # ################### Setting Up Files ################### # # ######################################################## # # NOTE: All I/O is relative to the directory where *this* file is target_dir = Path(__file__).parent ...
def get_unique_values_in_the_row(self, column_no): """returns the uniue values based on the column numbers send to it""" extracted_list = [row[column_no] for row in self.data_list_of_list] # print(len(extracted_list)) unique_values = set(extracted_list) return unique_values, len(...
The function identifies the column with the highest entropy by evaluating each feature's unique values. For columns with more than two unique values, it calculates entropy with a split value; for binary columns, it uses binary processing. It skips columns with only one value. The result is the column index and split va...
def get_row_with_highest_entropy(self): """ here we scroll through all arttributes and find the highest entropy :return: 1 column_no and split_value --> when the attribute column with highest entropy has multiple values ex 1,2,3,4,5,6...etc.... 2 column_no and None --> when the ...
def _wrapper_info(self, function: FunctionInfo) -> Optional[WrapperInfo]: """Information about the wrapper for one function. Return None if the function should be skipped. """ if self._skip_function(function): return None argument_names = [self._argument_name(functio...
The main task of the code is to generate C wrapper code for a given function, including its prototype and body, while handling conditional compilation guards. It writes a comment block, applies preprocessor guards if specified, and delegates to helper methods to output the function's prototype and implementation detail...
def _write_c_function(self, out: typing_util.Writable, function: FunctionInfo) -> None: """Write wrapper code for one function. Do nothing if the function is skipped. """ wrapper = self._wrapper_info(function) if wrapper is None: return ...
def _wrapper_info(self, function: FunctionInfo) -> Optional[WrapperInfo]: """Information about the wrapper for one function. Return None if the function should be skipped. """ if self._skip_function(function): return None argument_names = [self._argument_name(functio...
The main task of the code is to generate header content for a wrapper function, including its declaration and a macro definition. It checks if a wrapper exists, writes conditional compilation guards if specified, and delegates to helper methods to output the function declaration and macro. If no wrapper is found, it ex...
def _write_h_function(self, out: typing_util.Writable, function: FunctionInfo) -> None: """Write the complete header content for one wrapper. This is the declaration of the wrapper function, and the definition of a function-like macro that calls the wrapper function. ...
def _write_prologue(self, out: typing_util.Writable, header: bool) -> None: """Write the prologue of a C file. This includes a description comment and some include directives. """ out.write("""/* Automatically generated by {}, do not edit! */ /* Copyright The Mbed TLS Contributors * S...
The main task of the code is to generate a C file containing function wrapper definitions. It writes a prologue, iterates through sorted function names to output their wrappers, and appends an epilogue, structuring the file with standardized headers, function implementations, and closing directives.
def write_c_file(self, filename: str) -> None: """Output a whole C file containing function wrapper definitions.""" with open(filename, 'w', encoding='utf-8') as out: self._write_prologue(out, False) for name in sorted(self.functions): self._write_c_function(out, ...
def _header_guard_from_file_name(self, filename: str) -> str: """Preprocessor symbol used as a guard against multiple inclusion.""" # Heuristic to strip irrelevant leading directories filename = re.sub(r'.*include[\\/]', r'', filename) return re.sub(r'[^0-9A-Za-z]', r'_', filename, re.A)...
This code generates a C/C++ header file containing function wrapper declarations and macro definitions. It writes the file with a header guard to prevent multiple inclusions, structured with a prologue, sorted function declarations, and an epilogue.
def write_h_file(self, filename: str) -> None: """Output a header file with function wrapper declarations and macro definitions.""" self.header_guard = self._header_guard_from_file_name(filename) with open(filename, 'w', encoding='utf-8') as out: self._write_prologue(out, True) ...
def write_file(data): file_name = "FPUT_experiment{}{}.npy".format(dt,n_b) if os.path.exists(file_name): os.remove(file_name) np.save(file=file_name, arr=data) def run_without_graph(): data = [] for i in range(frame_count): data.append(euler_method(a,v,x).copy()) return data def ...
The main task of the code is to execute an experiment, save its results to a NumPy file using `write_file(run_without_graph())`, and subsequently generate a graph from the saved data via `graph_from_file()`. The filename is dynamically formatted with variables `dt` and `n_b`, indicating parameters for the experiment. T...
def main(): print("FPUT_experiment{}{}.npy".format(dt,n_b)) write_file(run_without_graph()) graph_from_file("FPUT_experiment{}{}.npy".format(dt,n_b))
def write_file(data): file_name = "FPUT_experiment{}{}.npy".format(dt, n_b) # Check whether a file w/ a same name under the file exist or not # This ensures particle displacements can be stored cleanly if os.path.exists(file_name): # If a same-name exists, remove the previous file os.remove(file...
The main task of the code is to simulate the FPUT experiment by generating particle displacement data, save this data into a `.npy` file using `write_file(run_without_graph())`, and subsequently generate visualizations by loading the saved data with `graph_from_file()` to plot the results.
def main(): print("FPUT_experiment{}{}.npy".format(dt,n_b)) # Save the array of particle displacements at every time fram into a text file write_file(run_without_graph()) # Extract file-stored particle displacements to generate plotting graph_from_file("FPUT_experiment{}{}.npy".format(dt,n_b))
def write_file(data): file_name = "FPUT_experiment{}{}.npy".format(dt, n_b) # Check whether a file w/ a same name under the file exist or not # This ensures particle displacements can be stored cleanly if os.path.exists(file_name): # If a same-name exists, remove the previous file os.remove(file...
The main task of the code is to execute a numerical simulation using either the Euler or 4th Order Runge-Kutta method, save particle displacement data to a file, generate visualizations and a simulation video, perform Fast Fourier Transform (FFT) analysis for modal decomposition, and output structured program status me...
def main(): print('### MAIN PROGRAM INITIATED ###') print("\nFile Name = FPUT_experiment{}{}.npy".format(dt,n_b)) if toggle_tol == 1: print("\n Tolerance = ON ") elif toggle_tol == 2: print("\n Tolerance = OFF ") if method_type == 1: print(" Solving with Euler Met...
def write_file(data): file_name = "FPUT_experiment_{}dt_{}N_ver{}.{}.npy".format(dt, n_b, method_type,toggle_tol) # Check whether a file w/ a same name under the file exist or not # This ensures particle displacements can be stored cleanly if os.path.exists(file_name): # If a same-name exists, remove th...
The main task of the code is to execute a simulation using either Euler or 4th-order Runge-Kutta methods with/without tolerance, save particle displacement data to an NPY file, generate a simulation video, plot particle positions at specific times, and compute Fast Fourier Transform (FFT) for modal analysis, all while ...
def main(): print('### MAIN PROGRAM INITIATED ###') # States the file name where the data will be saved as in an npy format readable only with numpy module # The ver shows what method is used and if tolerance is toggled or not print("\nFile Name = FPUT_experiment_{}dt_{}N_ver{}.{}.npy".format(dt,n_b,me...
def _fill_food(self, walls, food): food.fill(-1) food *= walls food += 1 self.nfood = food.sum() def _make_pill(self): pill = dict( pos=get_random_position(self.walls) ) return pill def get_random_position(map_array): """Gets a random available position in a binary map array. Ar...
This method initializes a game level by setting up food, pills, pillman, and ghosts. It adjusts ghost count and speed based on the level, places entities on the board avoiding walls, and resets the power timer.
def _init_level(self, level): """Initialises the level.""" self.level = level self._fill_food(self.walls, self.world_state['food']) self.world_state['pills'] = [self._make_pill() for _ in range(self.npills)] self.world_state['pillman']['pos'] = get_random_position(self.walls) self.nghosts = int...
def parse_map(map_array): """Parses a map when there are actions: stay, right, up, left, down. Args: map_array: 2D numpy array that contains the map. Returns: A 3D numpy array (height, width, actions) that contains the resulting state for a given position + action, and a 2D numpy array (height, widt...
This code initializes a game environment with configurable modes (e.g., 'regular', 'hunt'), setting up parameters like ghost behavior, pill mechanics, rewards, and termination conditions. It constructs the game map, initializes entities (pillman, ghosts, pills), and configures reward values and end conditions based on ...
def __init__(self, mode, frame_cap=3000): assert mode in PillEater.MODES self.nghosts_init = 1 self.ghost_speed_init = 0.5 self.ghost_speed = self.ghost_speed_init self.ghost_speed_increase = 0.1 self.end_on_collect = False self.npills = 2 self.pill_duration = 20 self.seed = 123 ...
def update_2d_pos(array_map, pos, action, pos_result): posv = array_map[pos[0]][pos[1]][action - 1] pos_result[0] = posv[0] pos_result[1] = posv[1] return pos_result def _get_food(self, posx, posy): self.reward += self.food_reward self.world_state['food'][posx][posy] = 0 self.nfood -= 1 if self....
This function moves Pillman based on the given action, updates his position on the map, checks for food collection at the new position, and identifies any pills at the same location to collect them. It adjusts action to 1-based indexing, updates position, triggers food/pill collection methods when applicable, and break...
def _move_pillman(self, action): """Moves Pillman following the action in the proto `action_proto`.""" action += 1 # our code is 1 based pos = self.world_state['pillman']['pos'] pillman = self.world_state['pillman'] update_2d_pos(self.map, pos, action, pos) if self.world_state['food'][pos[0]][p...
def _move_pillman(self, action): """Moves Pillman following the action in the proto `action_proto`.""" action += 1 # our code is 1 based pos = self.world_state['pillman']['pos'] pillman = self.world_state['pillman'] update_2d_pos(self.map, pos, action, pos) if self.world_state['food'][pos[0]][p...
This function advances the game environment by one time-step based on the given action, updating Pillman's movement, ghost interactions (collision detection and power effects), power depletion, timer progression, and level termination checks. It handles game mechanics like ghost killing, death conditions, and environme...
def step(self, action): """Advances environment one time-step following the given action.""" self.frame += 1 pillman = self.world_state['pillman'] self.pcontinue = self.discount self.reward = self.step_reward self.timer += 1 # Update world state self.world_state['power'] = max(0, self.wo...
def setIcmpType(self, icmpType): self.__icmpType = icmpType def setIcmpCode(self, icmpCode): self.__icmpCode = icmpCode def setPacketIdentifier(self, packetIdentifier): self.__packetIdentifier = packetIdentifier def setPacketSequenceNumber(self, sequenceNumber): self.__pa...
The main task of the code is to construct an ICMP Echo Request packet by setting its type (8), code (0), identifier, sequence number, payload data, and recalculating the checksum for proper network transmission.
def buildPacket_echoRequest(self, packetIdentifier, packetSequenceNumber): self.setIcmpType(8) self.setIcmpCode(0) self.setPacketIdentifier(packetIdentifier) self.setPacketSequenceNumber(packetSequenceNumber) self.__dataRaw = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefg...
def build_input_bias_array_for_selected_sessions(hparams): """ This function biuld the bias array considering all the trials in the selected sessions output: 1-D numpyarray - size:[total number of trials across all the selected sessions + (- num_history_step +1 )* n_sess , 1] """ inpt_...
The function constructs an input design matrix by concatenating bias, reward, and choice components based on the specified experimental configuration in `hparams`. It uses conditional logic to select relevant sub-functions, combines their outputs with `np.hstack`, and returns a list containing the resulting matrix. The...
def build_input_design_matrix(hparams, data): """ This fucntion builds the input design matrix output: list - size: (1, n_input_trials, n_iput_dim) """ input_design_matrix_list = [] if hparams['analysis_experiment_name'] == 'just_bias': input_design_matrix = build_input_bias_array...
def load_matches(file: Path = Path("./rio.csv")) -> List[dict]: with open(file, "r") as csv_file: fieldnames = csv_file.readline().split(",") return list(DictReader(f=csv_file, fieldnames=fieldnames)) def process_matches(matches: list) -> Teams: teams = Teams() last_stage = None for matc...
The main task of the code is to simulate a tournament by loading match data, processing teams, predicting winners between teams, updating win/loss records, and generating a summary of all matches and their outcomes. It iterates through tournament stages and rounds, logs match details, determines winners using a predict...
def main(): matches = load_matches(file=Path("./cop.csv")) teams = process_matches(matches) major = load_major() summaries = [] for team in teams.legends: logger.debug(f"{team}") for stage_name, rounds in major.items(): print_block(logger.info, f" {stage_name} ", char="*") ...
def parse_header(self): # # struct DemoFileHeader from rts/System/LoadSave/demofile.h # self.header["magic"] = self.read_blob( 0, 16 ) # char magic[16]; ///< DEMOFILE_MAGIC if not self.header["magic"].startswith(b"spring demofile"): raise Exceptio...
(The code parses a Spring demofile (sdf) by reading its header, script, demostream, and winning ally teams sections, populating `self.header` and `self.game_setup`. It handles gzip-compressed files, validates the file format, and processes structured data at specific byte offsets. Potential exceptions include invalid f...
def parse(self): """ reads data from sdf, populates self.header and self.game_setup - may raise IOError when opening a file to read or write - may raise Exception when file is not a spring demofile """ #filemagic = magic.from_file(self.filename, mime=True) #if fil...
def glob_all_src_files(target_dir='.'): """ Recurse through the target_dir and find all the .cc and .h files. """ files = glob_cc_src_files(target_dir) + glob_h_src_files(target_dir) return files def identify(header): """ String to identify submission's owner. """ ident = '(Malformed Header)' if...
The main task of the code is to verify a student's solution by checking headers, formatting, linting, building, and running the code. It ensures compliance with style guidelines, detects unmodified files when a base directory is provided, and validates correctness through compilation and execution. The function exits w...
def solution_check_simple(run=None): """ Main function for checking student's solution. Provide a pointer to a run function. """ setup_logger() if len(sys.argv) < 3: logging.error('provide target directory, program name, and optionally a base directory') sys.exit(1) target_direct...
def glob_all_src_files(target_dir='.'): """ Recurse through the target_dir and find all the .cc and .h files. """ files = glob_cc_src_files(target_dir) + glob_h_src_files(target_dir) return files def identify(header): """ String to identify submission's owner. """ ident = '(Malformed Header)' if...
The main task of the code is to verify a student's solution by checking for proper headers, formatting, linting, building, and running the code. It ensures changes were made, adheres to formatting standards, has no lint errors, and successfully builds/runs. It exits with a status code indicating success or failure.
def solution_check_make(run=None): """ Main function for checking student's solution. Provide a pointer to a run function. """ setup_logger() if len(sys.argv) < 3: logging.error('provide target directory, program name, and optionally a base directory') sys.exit(1) target_director...
def get_dats(self, dts=None): dats = [] filenames = [] for file in os.listdir(self.in_directory): dat = spio.loadmat(os.path.join(self.in_directory, file)) dats.append(dat) filename = f'{file} + dts={dts}' filenames.append(filename) return dats, filenames def binaryVecs(self, dat, dt=None): if ((s...
This code estimates mutual information (MI) and its standard deviation across multiple time points (dts) and data splits. It processes binary vectors from input data, computes MI for chunked subsets, aggregates results, saves them to files, and returns arrays of MI estimates and their standard deviations for all experi...
def get_MI_estimates(self, dts=np.asarray([0.01, 0.03, 0.1, 0.3, 1])): dats, filenames = self.get_dats(dts) allMIs = [] allstdMIs = [] for k, dat in enumerate(dats): MIs = np.zeros([len(dts), self.splits]) stdMIs = np.zeros([len(dts), self.splits]) dat_ys = [] for i in range(len(dts)): ys = self...
def get_dats(self, dts=None, get_N=False): self.dats = [] self.filenames = [] if dts is not None: if type(dts) != list: dts = [dts] for dt in dts: dats = [] filenames = [] self.dt = dt input_files = np.asarray(os.listdir(self.in_directory)) print("The following files are in your inpu...
This function estimates mutual information (MI) and its standard deviation across multiple time delays (dts) for given datasets. It processes data by converting it to binary vectors, splits data into chunks, computes MI for each chunk using MI_subset, aggregates results, and saves them in .npz files. The output are arr...
def get_MI_estimates(self, dts=np.asarray([0.01, 0.03, 0.1, 0.3, 1])): dats, filenames = self.get_dats(dts) allMIs = [] allstdMIs = [] MIs = np.zeros([len(dts), len(dats[0]), self.splits]) stdMIs = np.zeros([len(dts), len(dats[0]), self.splits]) for i in range(len(dts)): dat_ys = [] dat = dats[i] f...
def is_col_full(self,col): if self.state[0][col] !=0: #if the top entry of the column is populated - column is full return True else: return False def find_where_counter_goes_in_col(self,col,input_state=[]): if len(input_state)==0: input_state = self.state ...
This code implements a game step function for a turn-based game (likely Connect Four). It processes an action (column selection), checks if the move is legal (column not full), updates the game state, calculates reward, and handles opponent's turn if the game isn't won/drawn. It returns the new state, reward, done stat...
def step(self, action): col = action # illegal move, col is full if self.is_col_full(col): my_rew, am_i_done = self.illegal_move_punishment, True return np.array(self.state), my_rew, am_i_done, {} ## do shit # legal move carry it out find_row...
def load_level(self, level_file_name=''): if level_file_name == '': level_file_name = self.editor.screen.ids.level_name.text if level_file_name == '': return path = 'resources/levels/' + level_file_name + '.json' if not os.path.isfile(path): re...
The main task of the code is to handle level selection by loading the specified level file, updating the current level, transitioning to the play screen, and scheduling the level menu to hide after a delay. It uses the button's text to determine the level file name, loads the level, navigates to the play screen, and hi...
def play_level(self, button): level_file_name = 'level' + button.text self.current_level = int(button.text) self.load_level(level_file_name) self.go_to_play_screen() Clock.schedule_once(lambda dt: self.hide_level_menu(), 1)
def conv2d( in_planes, out_planes, kernel_size=(3, 3), stride=1, dilation=1, padding=1, bias=True, padding_mode="zeros", init_scale=1.0, ): conv = nn.Conv2d( in_planes, out_planes, kernel_size=kernel_size, stride=stride, padding=padding, ...
This code defines a U-Net architecture for image generation, initializing layers for downsampling, attention, and upsampling. It configures residual blocks, self-attention mechanisms, and convolutional layers to process input features, with parameters for channel dimensions, resolutions, and normalization. The network ...
def __init__( self, input_channels, encoded_latent_embedding_dim, # eg 64 ch, output_channels=None, ch_mult=(1, 2, 4, 8), num_res_blocks=2, attn_resolutions=(16,), dropout=0.0, resamp_with_conv=True, act=SiLU(), normalize=g...
def downsample(in_ch, with_conv): if with_conv: down = conv2d(in_ch, in_ch, kernel_size=(3, 3), stride=2) else: down = nn.AvgPool2d(2, 2) return down def _compute_cond_module(self, module, x, temp): for m in module: x = m(x, temp) return x def upsample(in_ch, with...
This code processes input data through a series of downsampling, middle, and upsampling blocks in a neural network. It applies residual blocks, attention mechanisms, and temporal embeddings to transform input features into latent embeddings, enabling tasks like image generation or feature extraction in diffusion models...
def forward(self, x, temp): # Init x = x.view(-1, 1, self.input_height, self.input_height) temp = temp.view( -1, ) B, C, H, W = x.size() # Timestep embedding temb = self.temb_net(temp) assert list(temb.shape) == [B, self.ch * 4] # Downs...
def map_keys(file_name, player_count): global semaphores with open('maps/' + (file_name or 'default.csv')) as csv_file: csv_reader = csv.reader(csv_file) next(csv_reader) # skip first row for player_cardinal, part, position, keys, repeat, action_name in csv_reader: player_index = player_count - i...
The main task of the code is to analyze video input using MediaPipe Pose to detect body landmarks, calculate movement speed based on landmark positions, determine BPM values from average speed, and send these values to a server. It supports command-line options for input handling, display, recording, flipping, and spli...
def main(): global last_frames, last_keys, frame_midpoint, bpm parser = argparse.ArgumentParser() parser.add_argument('--map', '-m', help='File to import for mapped keys') parser.add_argument('--input', '-i', help='Input video device or file (number or path), defaults to 0', default='0') parser.add_argument(...
def _get_unscraped_links(self): ''' This function prevents rescraping by comparing scraped ids with the ids of already scraped products in the SQL database. Returns: -------- links_to_scrape: list The list of unscraped links. ''' db_ids = pd.r...
The main task of the code is to scrape new product data from the Gorilla Mind website, process each product by saving data, downloading images, and uploading files to an S3 bucket, then compile all scraped data into a structured DataFrame for return.
def scrape_all_data(self): ''' This function is used scrape all new product data from the gorilla mind website and return a dataframe of the scraped data. Returns: -------- df: dataframe The dataframe of scraped data ''' links = self._get_unscraped_li...
def random_tries(items: int) -> [(float, float)]: return [(random.uniform(0.1, math.pi), random.uniform(2, 20)) for _ in range(items)] def crossover(generation: [(float, float)], width: float) -> [(float, float)]: choices = selection(generation, width) next_generation = [] for i in range(len(generation)...
The code implements a genetic algorithm over 10 epochs, evolving a population of 12 items through crossover and mutation operations. It initializes a random population, iteratively refines it, and finally displays the initial and final generations within specified height/width constraints.
def fire() -> None: epochs = 10 items = 12 height = 5. width = 10. generation = random_tries(items) generation0 = list(generation) # save to contrast with last epoch for i in range(1, epochs): results = [] generation = crossover(generation, width) mutate(generation...
def _delete_record(self, work_date: date, item: int) -> None: sql = "DELETE FROM records WHERE work_date=? AND line_item=?" with self._connect() as db: db.execute(sql, (work_date, item)) def get_timecard(self, work_date: date) -> TimeCard: """ Reruns a TimeCard object for the...
This method deletes a specified record from the database and adjusts line item numbers. It first removes the target record, then deletes all entries in the timecard for the given date, reindexes them starting from 0, and re-adds them with updated line item numbers.
def delete_record(self, work_date: date, item: int) -> None: """ Remove record from database Line item numbers will be adjusted """ self._delete_record(work_date, item) tc = self.get_timecard(work_date) for e in tc: self._delete_record(e["work_date"], ...
def usage(): tab = '\t' print('Usage:') print((tab + 'python %s [OPTIONS]' % (__file__))) print((tab + '-d | --log_dir=')) print((tab*2 + 'Log directory')) print((tab + '-u | --user_dir=')) print((tab*2 + 'User directory of Chrome')) print((tab + '-s | --start')) print((tab*2 + 'Star...
The code processes command-line arguments to configure parameters like user directory, mode, and test ranges. It reads a list of websites from a file, then executes tasks based on the specified mode (e.g., initialization, preparation, violation checking, performance testing). The tool likely analyzes website properties...
def main(argv): try: opts, args = getopt.getopt(argv, 'hm:pcu:t:s:e:r:', ['help', 'mode','proxy', 'cpp' ,'user_dir=', 'test_url=', 'start=', 'end=','round=']) except getopt.GetoptError: usage() sys.exit(2) user_dir = "user-dir" test_url = None proxy = False cpp = False ...
def pixel_length_correction(element): num_total_points = element.area skeleton = element.image diag_points, num_diag_points = find_structure(skeleton, "diag") # print(num_diag_points) mid_points, num_mid_points = find_structure(skeleton, "mid") # print(num_mid_points) num_adj_points = n...
The function `analyze_each_curv` calculates the **mean and median curvature** of a labeled element (e.g., a root or shape) from an image, adjusting for pixel resolution and potential measurement biases. It uses a sliding window (if specified) to compute curvature across subsets of the element's coordinates, trims outli...
def analyze_each_curv( element, window_size_px, resolution, output_path, name, within_element ): """Calculates curvature for each labeled element in an array. Parameters ---------- element : Iterable A list of RegionProperties (most importantly, coordinates) from scikit-image regionprops fu...
def filter_curv(input_file, output_path, save_img): """Uses a ridge filter to extract the curved (or straight) lines from the background noise. Parameters ---------- input_file : str A string path to the input image. output_path : str A string path to the output directory. save_...
The function processes an input image through a sequence of steps—filtering, binarization, particle removal, skeletonization, pruning, and curvature analysis—to compute curvature data. It generates a pandas DataFrame summarizing curvature metrics for all images, with optional image saving and within-element analysis. T...
def curvature_seq( input_file, output_path, resolution, window_size, window_unit, save_img, test, within_element, ): """Sequence of functions to be executed for calculating curvature in fibermorph. Parameters ---------- input_file : str or pathlib Path object Pat...
def extract_number_from_path(str): last_slash_pos = str.rfind('/') jpg_pos = str.find('.jpg') number = str[last_slash_pos + 1:jpg_pos] formatted_number = number.zfill(4) return formatted_number def color_features_ir(subject, task, idx): _, cropped = crop_ir_images(subject, task, idx) featu...
This code generates thermal image features for specific tasks (T1, T6, T7, T8) by processing subject data, skipping predefined exceptions, extracting IR color features, averaging every 50 rows, and saving results as CSV files with corresponding labels.
def thermol_features_generator(): tasks = ['T1', 'T6', 'T7', 'T8'] file_start = r"X:\PPGI\BP4D+_v0.2\Physiology" subject_list = os.listdir(file_start) labels = {} features_list = [] for subject_id in subject_list: for task in tasks: if (subject_id == 'F042' and task in ['T7'...
def executeUser(addr, cmd: Command): users[addr].username = cmd.params["username"] users[addr].realname = cmd.params["realname"] def executeNick(addr, cmd: Command): users[addr].username = cmd.params["nickname"] def executePrivmsg(addr, cmd: Command): target = cmd.params["target"] text = cmd.params["text"] if ta...
The function processes incoming messages by parsing the command type from the message and dispatching it to the corresponding execution handler function (e.g., executeUser, executeNick, etc.), enabling differentiated processing based on the command type.
def handleMessage(msgPair) -> None: addr, msg = msgPair cmd = parseMessage(msg) if cmd.cmdType == CmdType.USER: executeUser(addr, cmd) elif cmd.cmdType == CmdType.NICK: executeNick(addr, cmd) elif cmd.cmdType == CmdType.PRIVMSG: executePrivmsg(addr, cmd) elif cmd.cmdType == CmdType.JOIN: executeJoin(addr, cmd) ...
def extract_value(self, get_cust_value, **params): record = params.get("record") key = params.get("key") default = params.get("default") if key is None: return default if key == "####": return record value = None if get_cust_value and ke...
The main task of the code is to recursively load and transform data based on a transaction structure (`tx`), handling lists, dictionaries, and custom functions. It processes input values according to the specified `data_type` (list/dict/other), filters out invalid entries, and applies custom functions with error handli...
def load_data(self, tx, value, data_type="attribute", get_cust_value=None): if value is None: return None if data_type == "list": items = [] for i in value: item = { k: self.load_data( (v if v["type"] == "at...
def extract_value(self, get_cust_value, **params): record = params.get("record") key = params.get("key") default = params.get("default") if key is None: return default if key == "####": return record value = None if get_cust_value and ke...
This function transforms input data according to metadata specifications by extracting values from records, applying specified functions to lists/dicts, or evaluating custom lambda expressions, while handling errors with logging and returning a filtered dictionary of non-empty results.
def transform_data(self, record, metadatas, get_cust_value=None): tgt = {} for k, v in metadatas.items(): try: if v["type"] == "list": value = self.extract_value( get_cust_value, **self._get_params(record, v["src"][0]) ...
def place_poacher_on_grid(initial_grid, controlled=False): if controlled: poacher_position = random.choice(starting_locations_poacher) else: poacher_position = generate_random_entry_at_walls(initial_grid) poacher_x = poacher_position[0] poacher_y = poacher_position[1] new_grid = i...
The main task of the code is to generate a grid layout by placing a poacher, rangers, and animals based on specified parameters. It reads a base grid file, adds a controlled or random poacher, positions rangers, and distributes animals (biased or unbiased) on the grid, returning the final configured grid for a simulati...
def populate_the_grid(num_rangers=3, num_animals=80, biased_animals=True, controlled_poacher=True): # with open("Pac-Man/pacman-reinforcementlearning/layouts/baseGrid.lay") as f: # lines = [line.strip() for line in f] # f = open("layouts/baseGrid.lay") f = open("layouts/baseG...
def title_and_info(self, state, color): if state == 'federal': format_header = "TITLE - {} TITLE IX DOCUMENTATION\n\n (This is crawled data)\n\n".format(state.upper()) else: party = 'Democratic' if color == 'Blue' else 'Republic' format_header = "TITLE - {} TITLE IX D...
The code crawls and processes data from URLs listed in a CSV file, extracting text from PDFs, Word documents, and HTML pages. It dynamically writes formatted content to text files per state, accumulates headers and child links, and stores structured metadata in a JSON file. The task involves handling different file typ...
def crawl(self): for index, row in self.csv_data.iterrows(): print(row['type']) if row['state'] != self.starting_state: with open('../output_domain/federal/{}.txt'.format(self.starting_state), "w", encoding="utf-8") as f: f.write(self.formatted_data) ...
def title_and_info(self, state, color): if state == 'federal': format_header = "TITLE - {} TITLE IX DOCUMENTATION\n\n (This is crawled data)\n\n".format(state.upper()) else: party = 'Democratic' if color == 'Blue' else 'Republic' format_header = "TITLE - {} TITLE IX D...
The code initializes a class to process CSV data, logs column details, maps URLs to local paths, extracts initial state and color data to format information, sets keyword patterns for processing, and triggers a crawling process. It prepares data and patterns for further analysis or document retrieval based on the CSV c...
def __init__(self, csv_path): self.headers = {} self.csv_data = pd.read_csv(csv_path) logger.info("columns - {}".format(self.csv_data.columns)) logger.info(self.csv_data.head()) self.url_map = { 'https://www.twc.texas.gov/sites/default/files/vr/docs/title-ix-procedure...
def get_queens(board): return [(x, y) for x in range(len(board)) for y in range(len(board)) if board[y][x] == 1] def find_best_move_for_queen(queen, board): best_move = (0, 0, 0, math.inf) # x, y, offset, score for x in range(len(board)): test_board = np.copy(board) move(queen, x, test_boa...
The function determines the optimal move for a queen on a chessboard by evaluating all possible moves, selecting the one with the lowest score (likely minimizing risk or maximizing benefit), and executing it. It iterates through each queen, finds their best move, compares scores, and applies the most favorable move to ...
def make_best_move(board): best_move = (0, 0, 0, math.inf) # x, y, offset, score for q in get_queens(board): queen_best_move = find_best_move_for_queen(q, board) if queen_best_move[3] <= best_move[3]: best_move = queen_best_move move((best_move[0], best_move[1]), best_move[2],...
def make_board(): return [[7, 2, 4], [5, blank, 6], [8, 3, 1]] def print_state(state): print_board(state.board) print("\tgn = " + str(state.gn)) print("\thn = " + str(state.hn) + " ") print("\tfn = " + str(state.fn)) def a_star_search(initial_state): closed_queue = ClosedQueue() open_queue =...
The code's main task is to solve a problem using the A* algorithm. It initializes a game board, creates an initial state, and performs an A* search to find a solution. The result is a sequence of states, which are printed iteratively by backtracking through each state's parent pointer until the solution path is fully d...
def main(): print("main") board = make_board() initial_state = State(board, None) print_state(initial_state) result = a_star_search(initial_state) while result is not None: print_state(result) result = result.parent
def make_board(): dimension = 25 board = np.zeros((dimension, dimension), int) np.fill_diagonal(board, 1) return board def score_board_state(board): return sum([conflicts_for_location(q[0], q[1], board) for q in get_queens(board)]) def print_board(board): for x in board: print(x) def mak...
The main task of the code is to solve a puzzle by iteratively finding the optimal move on a board to minimize the score, tracking the best score achieved, and breaking the loop when the score reaches zero. It avoids infinite loops by detecting repeated moves and introducing random/sequential moves when stuck, while cou...
def main(): board = make_board() moves = 0 last_move = (0, 0, 0, 0) # format is (x, y, offset, score) best_score = (math.inf, board) while True: score = score_board_state(board) print_board(board) print("current score is " + str(score)) if score < best_score[0]: ...
def train(model, train_dataloader, val_dataloader, args, ith_iter = None): # train a model over train data model_save_dir = args.model_save_dir if not exists(model_save_dir): makedirs(model_save_dir) model_file = join(model_save_dir, "model.ckpt") num_batches = len(train_dataloader) ...
The main task of the code is to perform semi-supervised training of a model using both labeled and unlabeled data. It iteratively trains a model on labeled events, predicts pseudo-labels for unlabeled events, and incorporates newly labeled events into the training set based on confidence thresholds. The process involve...
def do_training(args): # function to run DEST and train a model if not exists(args.model_save_dir): makedirs(args.model_save_dir) """ ================ make dataset ================ """ tokenizer = AutoTokenizer.from_pretrained(args.model_type) if not exists(f'./temp/{args.model_type}_e2id.js...
def legal_square(x, y): """ return true if the square with coordinates (x, y) exist. """ return 0 <= x < BOARD_SIZE and 0 <= y < BOARD_SIZE def opposite_direction(d): return -d[0], -d[1] def first_free_square(board, x, y, d): """ return the first free square from the specified square in dire...
This function updates a board's state and possible moves after a player's move or undo action. It modifies the target square's status, adjusts neighboring squares' connectivity, adds/removes possible moves based on connectivity, and checks if the move ended the game.
def evaluate_new_board(board, possible_moves, move_x, move_y, player, undo_move=False): """ change the board evaluation accordingly to the new move, and play the new move if reverse=True the function will evaluate the board as if the move was undo. """ move_square = board[move_y][move_x] if undo...
def legal_square(x, y): """ return true if the square with coordinates (x, y) exist. """ return 0 <= x < BOARD_SIZE and 0 <= y < BOARD_SIZE def opposite_direction(d): return -d[0], -d[1] def first_free_square(board, x, y, d): """ return the first free square from the specified square in dire...
The function `evaluate_new_board` updates the board and possible moves after a player makes or undoes a move. It modifies the target square's state (occupied/empty), adjusts neighboring squares' connectivity status, and updates the `possible_moves` set by adding/removing positions based on connectivity. It also checks ...
def evaluate_new_board(board, possible_moves, move_x, move_y, player, undo_move=False): """ change the board evaluation accordingly to the new move, and play the new move if reverse=True the function will evaluate the board as if the move was undo. """ move_square = board[move_y][move_x] if undo...
def total_score(board, possible_moves): """ return the board score, evaluated by the difference between the positive and negative scores """ sum1 = 0 for move in possible_moves: x, y = move sum1 += board[y][x].total_score() return sum1 def evaluate_new_board(board, possible_moves...
This function implements the Minimax algorithm with alpha-beta pruning to determine the optimal move for a game, evaluating board states recursively. It prioritizes high-scoring moves, tracks node counts, and returns the best move along with its evaluation, considering depth limits and pruning to optimize performance.
def mini_max(board, possible_moves, cnt, depth=MINI_MAX_DEPTH, alpha=-math.inf, beta=math.inf, maximizing_player=False): cnt[0] += 1 # increase count of nodes if depth == 0: return total_score(board, possible_moves), -1 player_to_play = BOT_PLAYER if maximizing_player else -BOT_PLAYER if maximi...
def total_score(board, possible_moves): """ return the board score, evaluated by the difference between the positive and negative scores """ sum1 = 0 for move in possible_moves: x, y = move sum1 += board[y][x].total_score() return sum1 def evaluate_new_board(board, possible_moves...
The code implements the Minimax algorithm with alpha-beta pruning to determine the optimal move for a game. It evaluates possible moves on a board, recursively exploring the game tree while prioritizing high-score moves. The function tracks node counts, handles maximizing/minimizing players, and returns the best move w...
def mini_max(board, possible_moves, cnt, depth=MINI_MAX_DEPTH, alpha=-math.inf, beta=math.inf, maximizing_player=False): cnt[0] += 1 # increase count of nodes if depth == 0: return total_score(board, possible_moves), -1 player_to_play = BOT_PLAYER if maximizing_player else -BOT_PLAYER if maximi...
def update_pygame(): pygame.display.update() def evaluate_new_board(board, possible_moves, move_x, move_y, player, undo_move=False): """ change the board evaluation accordingly to the new move, and play the new move if reverse=True the function will evaluate the board as if the move was undo. """ ...
The function `best_move` determines the optimal move for a game (e.g., Tic-Tac-Toe) using a modified minimax algorithm with heuristic sorting. It selects the best move by evaluating potential positions, prioritizing moves with higher scores (or lower scores if minimizing). If the game starts with 8 possible moves, it r...
def best_move(board, possible_moves, max_score=True): player = BOT_PLAYER if max_score else -BOT_PLAYER best_x, best_y = 0, 0 max_score = -math.inf if max_score else math.inf if len(possible_moves) == 8: # beginning of game - play random return random.sample(possible_moves, 1)[0] cnt = [0] ...
def update_pygame(): pygame.display.update() def evaluate_new_board(board, possible_moves, move_x, move_y, player, undo_move=False): """ change the board evaluation accordingly to the new move, and play the new move if reverse=True the function will evaluate the board as if the move was undo. """ ...
The function `best_move` determines the optimal move for a player on a game board using a minimax algorithm with alpha-beta pruning. It prioritizes moves based on their heuristic scores, evaluates potential moves recursively, and selects the one yielding the highest (or lowest, depending on the player) score. If the ga...
def best_move(board, possible_moves, max_score=True): player = BOT_PLAYER if max_score else -BOT_PLAYER best_x, best_y = 0, 0 max_score = -math.inf if max_score else math.inf if len(possible_moves) == 8: # beginning of game - play random return random.sample(possible_moves, 1)[0] cnt = [0] ...
def best_move_2(board, possible_moves, bot_turn=True): max_score = bot_turn # bot wants to maximize score cnt = [0] # count nodes in search tree if len(possible_moves) == 8: # beginning of game - play random return random.sample(possible_moves, 1)[0] move = mini_max(board, possible_moves, cnt...
This function initializes and runs a Tic Tac Toe game where a player competes against a bot. It sets up the game board, handles user input (mouse clicks and keyboard keys), manages game states (starting, playing, ending), determines bot moves using an algorithm, checks for winners, and redraws the board and results. Th...
def start_game_against_bot(): board = [[Square() for i in range(BOARD_SIZE)] for j in range(BOARD_SIZE)] possible_moves = {(BOARD_SIZE // 2, BOARD_SIZE // 2)} pygame.init() pygame.display.set_caption('Tic Tac Toe') # pygame_icon = pygame.image.load('icon.png') # pygame.display.set_icon(pygame_i...
def check_eligibility(a, action_path): # check for action eligibility flag = True tmp_env, _, _, _, _ = get_current_state(action_path) obs_new, reward_new, done_new, info = tmp_env.step(a) mapping = tuple( np.ndindex(((2 * MAX_ALLOWED_WORKER) + 1, (2 * MAX_ALLOWED_WORKER) + 1, (2 * MAX_ALLOW...
The main task of the code is to perform a beam search to identify optimal policies by integrating three DQN models (economic, environmental, and social) within a tree-based search framework. It initializes environments, constructs a decision tree with pruning, evaluates candidate actions, and iteratively expands/retain...
def main(): if th.cuda.is_available(): device = 'cuda' else: device = 'cpu' # loading trained models econ_model = DQN.load("../model/economic_model") env_model = DQN.load("../model/environmental_model") social_model = DQN.load("../model/social_model") econ_env = EconomicEnv...
def get_all_pairs_from_all_exchanges(): average_prices = {} all_pairs = cache.get('binance_pairs') all_pairs.extend(cache.get('kraken_pairs')) unique_pairs = set(all_pairs) for pair in unique_pairs: b_price = get_pare_price_from_binance(pair) k_price = get_pare_price_from_kraken(pa...
This function retrieves price data for a cryptocurrency pair from a specified exchange. It handles three scenarios: fetching all pairs from all exchanges (if no parameters are provided), fetching all pairs from a specific exchange (if only exchange is provided), or fetching a specific pair from a given exchange (if bot...
def get_prices_on_exchange(pair, exchange): pair = pair.replace('/', '') if pair else None try: if not exchange and not pair: return get_all_pairs_from_all_exchanges() if exchange and not pair: return get_all_pairs_from(exchange) if exchange and pair: ...
def truncate(self, root_word: str, num_times: int) -> tuple: """ This method cuts off the ending of a word for the purposes of utilizing it for the root dictionary. It runs a certain number of times depending upon the num_times which it is given. It takes the root_word string and returns...
The main task of the code is to process a Latin sentence by tokenizing it, analyzing each word's morphological possibilities using dictionaries (frozen, irregular, root), handling punctuation, and generating chunked lists of potential sentence structures. It outputs processed possibilities, removes impossible forms, an...
def run_sciens(self, latin_sentence: str) -> list: """ This method performs the major action of the program. It is meant to take a sentence, tokenize it, denote all of the potential forms of each word, chunk it into potential sentences, and spit out those sentences in a readable format. ...
def process_frozen(self, frozen_dict_file: TextIO) -> dict: """ This method forms the frozen_dictionary field by creating a frozen_dict item and returning it to be assigned to that object. It uses the generate_frozen_word method to handle the value for each key, which is the actu...
The code initializes a Latin grammar processor by defining declension and conjugation paradigms with affixes for noun cases and verb tenses, loads dictionaries for frozen, irregular, and root words to support part-of-speech tagging, and prepares a Latin sentence for analysis. It structures grammatical rules and prepare...
def __init__(self, latin_string: str, frozen_dict_file: str = '../Project Text Files/Frozen_Word_Dictionary.txt', irregular_dict_file: str = '../Project Text Files/Irregular_Word_Dictionary.txt', root_dict_file: str = '../Project Text Files/Root_Dictionary.txt') -> Non...
def get_reaction_core(r: str, p: str, kekulize: bool = False, use_h_labels: bool = False) -> Tuple[Set, List]: """Get the reaction core and edits for given reaction Parameters ---------- r: str, SMILES string representing the reactants p: str, SMILES string representing the product ...
This function processes a reaction SMILES string to generate a ReactionInfo object containing the reaction core, bond edits, leaving group changes, and attachment atoms. It splits reactants/products, identifies mapped atoms, compares bond structures between reactant and product, and compiles edits. The result includes ...
def get_reaction_info(rxn_smi: str, kekulize: bool = False, use_h_labels: bool = False, rxn_class: int = None, mainid:str = 'xxxxxx', order: int=-1) -> ReactionInfo: """ Construct a ReactionInfo namedtuple for each reaction. ReactionInfo contains information on the reaction core, core ...