dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def _parse_frame_to_segment(self, frame_to_seg): """Handles frame_to_seg file format""" return int(frame_to_seg) if frame_to_seg != 'all' else frame_to_seg def _determine_img_folder(self): """Identifies folder of interest and returns path""" if os.path.isdir(self.__path): ret...
The code initializes an `Experiment` object by setting instance variables from input parameters, creating experiment directories, and loading existing segmentation data. It processes channel and frame information, determines image paths, and checks for multichannel data. The method ensures the experiment directory exis...
def __init__(self, date, exp_ID, path, parse_ID, separator, channel_info, channel_to_seg, frame_interval, frame_to_seg, exp_note): """ Initialize the Experiment object with the provided parameters, creates experiment directory if it doesn't yet exist and creates/updates experim...
def _get_column_as_list(self, column_name): """Checks for existing df and column; pops existing column and returns it as a list""" if self.__df is None: raise ValueError("Dataframe 'df' is not initialized. Please run 'segment_cells' first.") if column_name in self.__df.columns: ...
The function performs frame-by-frame cell labeling on ROI data using parameters like search radius, connectivity thresholds, and weighting factors for IOU/visual features. It generates a dataframe with a 'Label' column, updates experiment data, and optionally exports results to CSV. It also populates the 'labeling_tool...
def label_cells(self, to_label='ALL', search_radius=100, min_connectivity=100, iou_weight=0.6, visual_weight=0.4, must_overlap=True, export_df=True): """ Performs frame-by-frame cell labeling on cell ROI data for given with the given parameters. Populates 'labeling_tools' fol...
def is_train_test_file_exists(self) -> Boolean: try: logging.info("Checking Avalability of Training and Test file") is_train_file_exists = False is_test_file_exists = False is_train_file_exists = os.path.exists(self.dataingestionArtifact.train_file_path...
The main task of the code is to validate dataset schema and check for data drift after confirming train/test file existence. It generates a DataValidationArtifact with validation status, schema/report paths, and logs results. If successful, it returns the artifact; otherwise, it raises an exception.
def initiate_data_validation(self) -> DataValidationArtifact: try: is_available = self.is_train_test_file_exists() if is_available: self.validate_dataset_Schema() validation_status = self.validate_dataset_Schema() self.is_dat...
def create_debug_log(self): '''Take debug log argument and create a file handler to record the debug and info data Returns: Name of logfile that information will be written to ''' # If the logfile already exists, delete the old log file if os.path.exists(self._debug...
The main task of the code is to generate a network topology from testbed data by connecting devices, discovering neighbors via CDP/LDLP protocols, handling credentials and aliases, and outputting the structured data into a YAML file. It returns an intermediate dictionary representing the finalized testbed topology with...
def _generate(self): """The _generate is called by the testbed creator - It starts here Takes testbed information and writes the topology information into a yaml file Returns: dict: The intermediate dictionary format of the testbed data. """ if self._debug_lo...
def read_var(self,line): sections = self.split_comma(line)[1:] #get everthing but init for sec in sections: self.values.append([None,self.get_val(sec,0),None]) def split_comma(self,astr): #So Ive had issues with split so insted lets make our own method parts = [] accum = "" for char in astr: if char !=...
This function processes assembly code lines to update memory addresses and handle variables/instructions. It splits input into lines, tracks addresses, processes labels (lines starting with ".") by updating address based on operands, and processes instructions by checking if they belong to a special group (TWINS) to ad...
def secound_pass(self,asm_str): lines = asm_str.split('\n') addr = 0 for line in lines: if line[0] == "@": self.values.append([None,None,line]) #no need to load nones continue if line[0] == ".": self.values.append([None,None,line]) self.read_var(line) addr += len(self.split_comma(line)) ...
def read_c_code(self): C_file = open(self.file_name + '.c','r') cstring = C_file.read() C_file.close() return cstring def pre_process(self,c_code): #this method removes comments and handles macros cline = c_code.split('\n') p_code = "" for line in cline: if len(line) == 0: p_code += '\n' cont...
The main task of the code is to compile C code into assembly by preprocessing, generating intermediate code via `middle_end`, combining it with global declarations, writing the assembly output, assembling it into hexadecimal format using `jz_101_assembler`, and producing secondary output. The process transforms source ...
def run(self): c_code = self.read_c_code() c_code = self.pre_process(c_code) m = middle_end(c_code) self.asm = self.asm + m.run() + self.global_decl self.write_assembly() b = jz_101_assembler() b.run(self.asm) self.write_hex(b) self.write_secondary_output(b)
def v_ID(self,n,Store = False): #Each ID has a value associated with it #For stack varibles that amount is the vars distence #From the stack Top for global vars it is the pointer #to its location in global memory var = self.search_st(n.name) value = str(self.register_pointer) if var[3] == "stack": offs...
This code defines a `Store` method that dispatches storage operations to specific node visitor methods based on the type of input node `n`. It checks the node's class name and calls corresponding visitor functions (e.g., `v_ID`, `v_UnaryOp`) with a `True` flag to indicate storage mode, differing from loading operations...
def Store(self,n): #So storeing a value takes diffrent code then loading it #so these methods call the node visitors with the caviate that they #store rather then load if n.__class__.__name__ == "ID": self.v_ID(n,True) return if n.__class__.__name__ == "UnaryOp": self.v_UnaryOp(n,True) return if...
def prep(self,asm_str): #strip off spaces and comments lines = asm_str.split('\n') accum = "" for line in lines: m_accum = "" for char in line: if char not in (' ','#'): m_accum += char else: if char == ' ': continue if char == '#': break if len(m_accum) != 0: acc...
The code's main task is to assemble a given assembly language string into machine code. It processes the input through three stages: preprocessing (`prep`) to format the input, a first pass (`first_pass`) for initial assembly tasks like symbol resolution, and a second pass (`second_pass`) to complete the assembly proce...
def run(self,asm_str): #take in a string of assembly code as assemble it asm_str = self.prep(asm_str) self.first_pass(asm_str) self.secound_pass(asm_str)
def remove_block(self, position, immediate=True): """ Remove the block at the given `position`. Parameters ---------- position : tuple of len 3 The (x, y, z) position of the block to remove. immediate : bool Whether or not to immediately remove block from ...
This function adds a block to a 3D world at a specified position with a given texture. It removes any existing block at that position, stores the texture in a dictionary, and organizes the block into sectors for rendering. If `immediate` is True, it checks if the block is exposed, renders it, and updates neighboring bl...
def add_block(self, position, texture, immediate=True): """ Add a block with the given `texture` and `position` to the world. Parameters ---------- position : tuple of len 3 The (x, y, z) position of the block to add. texture : list of len 3 The coordinate...
def convert_coordinates(normalized_coordinates, image_width, image_height): final = [] for a, poly in normalized_coordinates: pixel_coordinates = [] for i in range(0, len(poly)): x = int(poly[i][0] * image_width) y = int(poly[i][1] * image_height) pixel_c...
This code crops an image multiple times (repeatnum) based on normalized scratch labels, adjusting crop boundaries to ensure minimum dimensions. It calculates scratch areas, determines random crop regions, normalizes labels, and saves cropped images with adjusted labels in the specified output folder.
def crop(image_path, normlabels, output_folder, repeatnum): alllabels = [] for i in range(repeatnum): image = cv2.imread(image_path) image_height, image_width, _ = image.shape output_folder_photos = output_folder labels = convert_coordinates(normlabels, image_width, ima...
def _list_objects(self, bucket_name): """ Returns a list of 1000 objects from the given bucket in Bolt/GS :param bucket_name: bucket name :return: list of 1000 objects """ blobs = self._gs_storage_client.list_blobs(bucket_name, max_results=1000) blob_names = [] ...
The main task of the code is to process HTTP requests by extracting parameters like 'bucket' and 'requestType', configure performance test settings (e.g., number of keys, object size), generate or retrieve object keys, and execute corresponding performance tests (e.g., upload, download, list) against Bolt/GS. It return...
def process_event(self, request): """ process_event extracts the parameters (requestType, bucket) from the HTTP Request, uses those parameters to run performance testing against Bolt/GS and returns back performance statistics. :param request: request object :return: performance ...
def battle(q_table): p1 = Person('p1', 1000, 150, 100, 100) p2 = Person('p2', 2000, 200, 100, 150) rounds = 0 wins = 0 losses = 0 # list of all attributes of fighters from p1's perspective (discrete values) curr_state1 = get_state(p1, p2) while rounds < 200: # TODO SWITCH ACTIONS...
The main task of the code is to train a reinforcement learning agent (Q-learning) to optimize battle strategies between two characters (p1 and p2) by iteratively updating a Q-table. The agent learns to choose actions (attacks) based on current health states, balancing exploration and exploitation. The Q-table maps heal...
def main(): # Q table of current hp's and actions, but eventually all other stats # TODO INCLUDE TOTAL DAMAGE OUTPUT TAKING INTO ACCOUNT HEALTH AND USE THAT AS THE POSITION # Q table: p1.health, p2.health, p1 move choice q_table = np.random.uniform(-1, 1, (HEALTH + 1, HEALTH + 1, 2)) print('Before ...
def NbOutingEdges(self): x = 0 y = 0 a = [] # We count the number of edges (i,j) going out from each vertex (if the value of the adjacency matrix is positive at (i,j)) for i in range(0,self.NbNodes): for j in range(0,self.NbNodes): if self.adj_mat[i][...
This code initializes a graph object with attributes like number of nodes, adjacency matrix, vertex coordinates, and eigenvalues. It sets up graph properties, calculates edge counts, constructs transfer matrices, and determines eigenvalues for spectral analysis, preparing the graph for further computations or simulatio...
def __init__(self,Nb_nodes,A,coord_list,Num_eigenval=None, DVertices=None,min = None,max = None): self.NbNodes = Nb_nodes self.adj_mat = A self.vertices = coord_list self.num_eigval = Num_eigenval if (DVertices==None): self.DCondition = np.zeros(Nb_nodes, dtype=int) ...
def admm_initialize(self, rho=1, seed='zero'): ''' Initialize the ADMM algorithm. Parameters: rho (float) : value of rho seed (int) : random seed for initialization ''' self.rho = rho self.primal_residual = [] self.objective1 = [] order_K = self....
The code implements an imitation learning algorithm (ADMM or PGD) to optimize control policies by iteratively updating variables, tracking residuals/objectives, and returning computed values $ F $ and $ P $ derived from polynomial monomials and their variable coefficients. For ADMM, it performs multi-step updates with ...
def imitate(self, algorithm, iterations=100, verbose=False, seed='zero', step_length=1): ''' Run the imitation learning algorithm Parameters: algorithm (str) : choose from either 'admm' or 'pgd' iterations (int) : number of iterations verbose (bool) : Turn verbos...
def check_username(): FrameWidgetC.frame_obj['20'].offdisplay() FrameWidgetC.frame_obj['10'].offdisplay() username = EntryWidget.ent_obj['000100'].get_by_expression() print("check_username called: ", username) global username_status obj = "" if username != "": obj = SelectSqlObj('rad...
This code checks if a user exists, destroys UI components, validates username/password, inserts new user data into SQL tables, and updates the interface with creation confirmation.
def method(self, event): if "000200" in LabelWidget.label_obj: print("user exist") else: print("user available") for widget in FrameWidgetC.frame_obj['20'].winfo_children(): widget.destroy() for widget in FrameWidgetC.frame_obj['10'].winfo_children(): ...
def print_final_statistics(truck_list, package_lists): """ Prints the final stats of the trucks, distance traveled, and number of remaining packages. :param list[Truck] truck_list: the list of truck objects :param list[list[str]] package_lists: the list of lists of package ids :return: """ ...
The main task of the code is to manage a command-line interface (CLI) for a package delivery tracking system. It presents a menu allowing users to view truck statistics, package details (single/all), and time-based package snapshots, looping back to the menu after each action until the user selects "Exit." The function...
def control(truck_list, package_lists, package_hash): """ Main control for the CLI. Serves the main menu and controls the actions taken by each menu choice. After each menu choice, the program is looped back to the main menu. Once the control method is invoked, the program does not leave this method ...
def get_cli_args(): """Using command line when two argument are added""" parser = argparse.ArgumentParser() parser.add_argument('-host', dest='HOST', help='Please specify species name', required=False) parser.add_argument('-gene', dest='GENE', help='Please...
The main task of the code is to process command-line arguments, retrieve gene data, and generate output. It fetches host and gene names from arguments, defaults to "Homo_sapiens" if no host is provided, retrieves gene-related data including tissue lists, prints status messages, and outputs structured results using the ...
def main(): """Business Logics""" argvs = get_cli_args() temp_host_name = argvs.HOST temp_gene_name = argvs.GENE host_name = modify_host_name(temp_host_name) \ if temp_host_name is not None else "Homo_sapiens" message, tissue_list = get_gene_data(temp_gene_name) print(message) pr...
def get_raw_list_of_lower_strings_from_series( self, series: ExtendedSeries) -> List[str]: """Self Evident :param series: """ self.raw_list_of_values = [ value.lower() for value in series.trim_spaces().mark_no_responses().group_na_values()...
The main task of the code is to process an input series by converting it to a list of lower-case strings, extracting nouns, removing synonyms, and then counting the unique occurrences of the remaining elements. The function returns a Counter object representing the frequency of these processed unique items.
def count_series(self, series: ExtendedSeries) -> Counter: self.get_raw_list_of_lower_strings_from_series(series=series) self.get_nouns_from_raw_list() self.remove_synonyms() return self.count_unique_occurrences()
def __get_edges_coordinates_csv_file_name(self) -> str: return self.__get_base_file_name() + '_edges_coordinates.csv' def __throw_error_if_file_exists_in_storage(self, file_name: str) -> None: if ((self.__storage_path / file_name).exists()): raise Exception(f'{file_name} already exists in st...
The main task of the code is to save the coordinates of graph edges (identified by OSMIDs) into a CSV file. It retrieves OSMIDs, fetches their latitude and longitude, writes them into a CSV with headers, and provides progress updates during the process, ensuring the output file does not already exist in the storage dir...
def __save_edges_coordinates_to_csv_file(self) -> None: save_file_name = self.__get_edges_coordinates_csv_file_name() self.__throw_error_if_file_exists_in_storage(save_file_name) print(f'Downloading edges coordinates to: {save_file_name}') osmids = self.__get_edges_start_end_osmids() ...
def random_prime(digits): num = random_num(digits) while not is_prime(num): num += 1 return num def compute_e(p, q): ''' conditions: 1 < e < phi(n) && e and phi(n) should be co prime ''' phi = compute_phi(p, q) values = [] # storing all possible values of e for i in ra...
The code implements a basic RSA encryption algorithm. It generates two random primes (p, q), computes modulus n = p*q, selects a public exponent e, and derives the private exponent d. Each character in the input text is encrypted by converting it to its ASCII value, raising it to the power of e modulo n, and converting...
def encrypt(plain_text): p = random_prime(2) q = random_prime(2) n = p*q e = choice(compute_e(p, q)) d = compute_d(e, p, q) encrypted = [] for char in plain_text: encrypted.append(chr((ord(char) ** e) % n)) return "".join(encrypted)
def _set_camera(self): p.resetDebugVisualizerCamera(self.camera_distance, 0, -89.99, [0,0,0]) def _put_new_nodes(self, current_node): new_nodes = self._generate_new_nodes(current_node) for node in new_nodes: if not node.get_config() in self.close_list: self.open_list....
The code implements A* path planning for a PR2 robot in a simulated environment using PyBullet. It initializes the environment, sets up collision detection, and performs search using a priority queue. The algorithm expands nodes from a start configuration toward a goal, checking for collisions. If a path is found, it r...
def search(self, use_gui=True, map='pr2playground.json'): # init PyBullet connect(use_gui=use_gui) robots, obstacles = load_env(map) base_joints = [joint_from_name(robots['pr2'], name) for name in PR2_GROUPS['base']] self.collision_fn = get_collision_fn_PR2...
def generate(p = 500): pop = [] for i in range(p): # Generate_random_rule() return a random tree with rule as a pop pop.append(generate_rule.generate_random_rule()) # Return a list with lots of tree roots return pop def f(s): # Generate a boolean array by evaluating the given tree w...
This code implements an evolutionary algorithm (EA) to optimize a population over n generations. It initializes a population, evaluates fitness, and iteratively selects parents via tournament selection, applies crossover and mutation to generate offspring, and replaces the weakest individuals if offspring show improved...
def run_ea(p, n): # Init first population population = generate(p) # Fitness is this generation fitness value, fitnesses is a list to set average fitness of each generation population fitness, fitnesses = [f(s) for s in population], [] # Start evolving for k in range(n): print(...
def kali(a, b): if b != 0: return a + kali(a, b-1) else: return 0 def hitung(fungsi, a, b): if fungsi == kali: return kali(a,b) elif fungsi == pangkat: return pangkat(a,b) def pilih_fungsi(pilihan): if(pilihan == 1): return kali elif(pilihan == 2): ...
The main task of the code is to demonstrate function calls and dynamic operations. It executes mathematical operations (multiplication, exponentiation) using defined functions, dynamically selects functions via `pilih_fungsi`, and combines results of nested function calls, printing outputs like 14, 35, 125, etc., to il...
def main(): print(kali(7, 2)) print(hitung(kali, 5, 3)) print(hitung(pangkat, 5, 3)) f = pilih_fungsi(1) print(f(7, 3)) g = pilih_fungsi(2) print(g(5, 2)) print(f(g(2,3), g(3,2)))
def isConstant(char): return char.isupper() and len(char) == 1 def isVariable(char): return char.islower() and len(char) == 1 def checkOccurs(var, exp): if exp.find(var) == -1: return False return True def getInitialPredicate(expression): return expression.split("(")[0] def getAttributes(exp...
This function performs unification of two logical expressions (exp1, exp2), returning a list of variable substitutions if they can be unified. It handles constants, variables, and structured terms with predicates/attributes. It checks equality, constant mismatches, variable occurs checks, predicate matches, attribute c...
def unify(exp1, exp2): if exp1 == exp2: return [] if isConstant(exp1) and isConstant(exp2): if exp1 != exp2: print(f"{exp1} and {exp2} are constants. Cannot be unified") return [] if isConstant(exp1): return [(exp1, exp2)] if isConstant(exp2): r...
def negate(term): return f'~{term}' if term[0] != '~' else term[1] def split_terms(rule): exp = '(~*[PQRS])' terms = re.findall(exp, rule) return terms def contradiction(query, clause): contradictions = [ f'{query}v{negate(query)}', f'{negate(query)}v{query}'] return clause in contradictions or ...
The code performs resolution refutation to prove a query's validity by adding its negation to the knowledge base and deriving contradictions. It iterates through clauses, resolves compatible terms, and generates new clauses. If a contradiction arises, it confirms the query is true via the negation's inconsistency, reco...
def resolve(kb, query): temp = kb.copy() temp += [negate(query)] steps = dict() for rule in temp: steps[rule] = 'Given.' steps[negate(query)] = 'Negated conclusion.' i = 0 while i < len(temp): n = len(temp) j = (i + 1) % n clauses = [] while j != i: ...
def genActions(graph, edges, cars): pop_nodes = getPopNodes(graph) pop_edges = getPopEdges(pop_nodes, edges) car_ids = getCarIDs(cars) actions = list(product(pop_edges, car_ids)) pruned_actions = pruneActions(actions, graph) return pruned_actions def chooseAction(actions, q_table, iteration): ...
The code implements Q-learning to optimize decision-making in a graph-based environment. It iteratively selects actions, simulates their impact on the graph, calculates rewards, and updates the Q-table to maximize cumulative rewards. Each iteration runs until a terminal state is reached, with rewards summed and stored....
def q_learning(graph, edges, cars, q_table, iterations): sums_rewards = [] for i in range(iterations): done = True sum = 0 print("iteration:", i) while done: actions = genActions(graph, edges, cars) action = chooseAction(actions, q_table, i) gr...
def create_model_architecture(self, HR_TARGET_SIZE): HR_SHAPE = HR_TARGET_SIZE + (3,) print('HR shape:', HR_SHAPE) generator = 1 discriminator = 1 # initialize the generator and discriminator. generator = self.make_generator() discriminator = self.make_discriminator() # discriminator in generator_mode...
This code generates high-resolution images using a pre-trained generator model (SRWGANGP) by processing low-resolution test images (32x32). It saves generated images, nearest-neighbor upscaled versions, and original high-resolution references in specified directories. The task includes loading model weights, configurin...
def create_images(self): file_path_test_list_32 = [os.path.join(self.TEST_32_DATA_GENERATOR_PATH, 'test', x) for x in os.listdir(os.path.join(self.TEST_32_DATA_GENERATOR_PATH, 'test'))] file_path_test_list_128 = [os.path.join(self.TEST_128_DATA_GENERATOR_PATH, 'test', x) for x in os.listdir(os.path.join(self.TEST_1...
def start_epoch_threads(self, data_gen_thread_func, file_path_list_lr, file_path_list_hr, train_step, final_training): queue_batches = JoinableQueue(self.MAX_QUEUE_SIZE) # calculate number of batches per data thread to generate # and overall number of batches self.num_batches_per_thread, self.num_batches = s...
The main task of the code is to train a deep learning model (likely a GAN) using multi-threaded data loading, with separate training and validation phases. It initializes file paths for low/high-resolution image datasets, sets up logging for PSNR and loss metrics, and executes training/validations loops over epochs. Th...
def train_thread(self, file_path_train_imgs_lr, file_path_train_imgs_hr, file_path_valid_imgs_lr, file_path_valid_imgs_hr, final_training=False): file_path_train_list_lr = [os.path.join(file_path_train_imgs_lr, 'train', x) for x in os.listdir(os.path.join(file_path_train_imgs_lr, 'train'))] file_path_train_list_hr ...
def create_model_architecture(self, HR_TARGET_SIZE): HR_SHAPE = HR_TARGET_SIZE + (3,) print('HR shape:', HR_SHAPE) generator = 1 discriminator = 1 # initialize the generator and discriminator. generator = self.make_generator() discriminator = self.make_discriminator() # discriminator in generator_mode...
The main task of the code is to train a generator and discriminator model for image super-resolution. It sets up the model architecture with a high-resolution target size (128x128), optionally pretrains the generator, loads pre-trained weights if specified, and executes training using provided low- and high-resolution ...
def train(self): # 128x128 HR self.curr_HR_size = self.LR_TARGET_SIZE[0] * 4 HR_TARGET_SIZE = (self.curr_HR_size, self.curr_HR_size) self.generator_model_train, self.discriminator_model = self.create_model_architecture( HR_TARGET_SIZE = HR_TARGET_SIZE) if self.PRETRAIN_GENERATOR: self.tr...
def create_norm(m): """ Function to generate our discretized norm based on the parameter m Parameters ---------- m : integer number of grid points used Returns ------- norm : callable norm(x) = h**2 * ||x||_2 """ h = 1/(m+1) def norm(v): sol = h * n...
This function solves a linear system using a multigrid method with damped Jacobi smoothing. It iteratively applies V-cycles, performing pre- and post-smoothing steps, to converge toward the solution of $ C \mathbf{u} = \mathbf{f} $. The algorithm tracks residual norms and iterations until the residual meets a tolerance...
def multigrid_jacobi(C,nu, f, u_guess, m, omega, nu1, nu2, level,maxIter=100, tol=1e-12): """ Function to run use multigrid as a solver with damped jacobi as a smoother. In this case we try to solve the initial system. Parameters ---------- nu : positive real number regularization para...
def create_norm(m): """ Function to generate our discretized norm based on the parameter m Parameters ---------- m : integer number of grid points used Returns ------- norm : callable norm(x) = h**2 * ||x||_2 """ h = 1/(m+1) def norm(v): sol = h * n...
The code solves an optimal control problem's optimality system using an iterative stationary method. It computes the solution iteratively via the formula $ u_{n+1} = -\frac{1}{\nu}A^{-2}u_n + \frac{1}{\nu}A^{-1}(y_d - A^{-1}f) $, leveraging fast Poisson solvers and matrix decompositions. The process continues until the...
def solver_stationary(u_guess,nu, y_d, f, m, maxIter=1000, tol=1e-12): """ Function to use a stationary solver for the initial optimality system using the iteration process u_{n+1} = -1/nu A^{-2} u_n + 1/nu (A^-1*(y_d- A^-1 *f)) Parameters ---------- u_guess : ndarray ...
def create_norm(m): """ Function to generate our discretized norm based on the parameter m Parameters ---------- m : integer number of grid points used Returns ------- norm : callable norm(x) = h**2 * ||x||_2 """ h = 1/(m+1) def norm(v): sol = h * n...
The function `solver_stationary_fixedRight` solves a linear system of the form $(\nu I + A^{-2})u = \text{right\_side}$ iteratively, using a fast Poisson solver and Laplace decomposition for efficiency. It employs a stationary iteration method with a regularization parameter $\nu$, starting from an initial guess `u_gue...
def solver_stationary_fixedRight(u_guess,nu, right_side, m, maxIter=500, tol=1e-12): """ This is a method to use the iteration of the stationary solver for an arbtrary right-hand side of the equation. It is used to solve systems of the form (nu*Id + A^{-2})*u = right_side and used ...
def create_norm(m): """ Function to generate our discretized norm based on the parameter m Parameters ---------- m : integer number of grid points used Returns ------- norm : callable norm(x) = h**2 * ||x||_2 """ h = 1/(m+1) def norm(v): sol = h * n...
The function `vcycle_stat` performs one V-cycle of the multigrid method to solve a linear system using stationary smoothing. It applies pre-smoothing, recursively solves a coarser grid problem via restriction and interpolation, then post-smooths the solution. At the finest level, it directly solves the system using `np...
def vcycle_stat(nu, nu1, nu2, m, u_guess, f, level): """ Function to run one vcycle of the multigrid method using the stationary method as a smoother. In this case we try to solve the initial system. Parameters ---------- nu : positive real number regularization parameter nu1 : int...
def create_norm(m): """ Function to generate our discretized norm based on the parameter m Parameters ---------- m : integer number of grid points used Returns ------- norm : callable norm(x) = h**2 * ||x||_2 """ h = 1/(m+1) def norm(v): sol = h * n...
This function solves a linear system using a multigrid method with stationary smoothing. It iteratively applies pre/post-smoothing steps (nu1/nu2) via recursive v-cycles, reducing residuals until tolerance (tol) is met or maxIter is reached. It returns the solution, residual history, and iteration count for the given m...
def multigrid_stat(nu, f, u_guess, m, nu1, nu2, level, maxIter=50,tol=1e-12): """ Function to run use multigrid as a solver with the stationary method as a smoother. In this case we try to solve the initial system. Parameters ---------- nu : positive real number regularization paramete...
def sortProcessors(self): proc_set = set(self.queryProcessors) sorted_processors = sorted([proc for proc in proc_set], key=lambda obj:type(obj).__name__) if len(sorted_processors) > 1: return sorted_processors elif len(sorted_processors) == 1: if isinstance(sorte...
The code retrieves an entity by ID using two query processors, merges results, and returns an appropriate object (Image, Annotation, Collection, Manifest, or Canvas) based on data type and content, handling empty cases and merging logic with fallbacks.
def getEntityById(self, entityId: str) -> IdentifiableEntity: self.queryProcessors = self.sortProcessors() rqp_df = self.queryProcessors[0].getEntityById(entityId) tqp_df = self.queryProcessors[1].getEntityById(entityId) if tqp_df.empty and rqp_df.empty: return None ...
def fit(self): n_samples, n_features = self.X.shape K = np.zeros((n_samples, n_samples)) for i in range(n_samples): for j in range(n_samples): K[i, j] = self.rbf_kernel(self.X[i], self.X[j]) alpha = np.zeros(n_samples) b = 0.0 for _ in range...
This code evaluates a machine learning model using specified resampling strategies (oversampling, undersampling, SMOTE), computes training/test accuracy, generates classification reports, balanced accuracy, confusion matrices, and cost-based net benefit metrics to assess model performance and misclassification costs.
def run_model(self, X_test, y_test, resampling_strategy=None): # Apply preprocessing and resampling based on the chosen strategy if resampling_strategy == 'over': ros = RandomOverSampler(random_state=42) self.X, self.y = ros.fit_resample(self.X, self.y) elif resampling_st...
def split_data(self, resampling_strategy=None): X_train, X_test, y_train, y_test = train_test_split(self.X, self.y, test_size=0.25, random_state=42) if resampling_strategy == 'over': ros = RandomOverSampler(random_state=42) X_train, y_train = ros.fit_resample(X_train, y_...
The main task of the code is to run a linear regression model using gradient descent. It splits data, normalizes features, trains the model with regularization (ldpara), plots cost convergence, calculates performance metrics, and generates an ROC curve for evaluation.
def run_model(self, ldpara=0, resampling_strategy=None): X_train, X_test, y_train, y_test = self.split_data(resampling_strategy) X_train, mean, std = self.normalize_train(X_train) X_test = self.normalize_test(X_test, mean, std) self.theta = np.ones(X_train.shape[1], dtype=np.float64) ...
def normalize_train(self, X): mean = np.mean(X, axis=0) std = np.std(X, axis=0) X = (X - mean) / std X = self.add_X0(X) return X, mean, std def normalize_test(self, X, mean, std): X = (X - mean) / std X = self.add_X0(X) return X def gradient_descent(self, ...
This code performs k-fold cross-validation on a dataset, applying specified resampling strategies (over-sampling, under-sampling, or SMOTE) to address class imbalance. It normalizes training and test data, trains a linear model via gradient descent with a given regularization parameter, and evaluates performance metric...
def run_kfold(self, k, ldpara, resampling_strategy=None): kf = KFold(n_splits=k, shuffle=True, random_state=11) fold_count = 1 for train_idx, test_idx in kf.split(self.X): print(f"Fold {fold_count}:") X_train_fold, X_test_fold = self.X.iloc[train_idx], self.X.iloc[test_...
def approximate_hilbert_kernel(self): w0 = np.ones(self.sigmas.size, dtype=np.float64) opt_res = minimize(self._hilbert_dgs_diff, x0=w0, args=(self.xx, self.yy, self.sigmas)) self.dg_weigths = opt_res.x #### np.save(self.file_saving_ws, self.dg_weigths) self.H_approxed = self.sum...
This code initializes an object to set up a 2D grid with given coordinates, computes Gaussian kernels, rotates coordinates based on specified directions, approximates Hilbert kernels, and prepares parameters for subsequent calculations, including normalization.
def __init__(self, cent_x, cent_y, xx, yy, directions, sigmas, sgmGauss, params={}): self.sgmGauss = sgmGauss self.params = params self.xx = np.copy(xx) # self.yy = np.copy(yy) # self.Nx, self.Ny = xx.shape self.x = np.copy(self.xx[:, 0]) self.y = np.copy(self...
def get_candidates(con): cur = con.cursor() cur.execute("SELECT * FROM 'candidates'") db = cur.fetchall() con.commit() return to_list(db) def get_setting(con, setting): cur = con.cursor() cur.execute("SELECT * FROM settings WHERE setting =?", (setting,)) setting = cur.fetchall() con...
The main task of the code is to validate and record a user's vote. It checks credentials, verifies the code's validity, ensures the user hasn't voted before, confirms the vote corresponds to an existing candidate, and inserts the vote into the database if all conditions are met.
def insert_vote(con, userid, code, vote): cur = con.cursor() candidates = get_candidates(con) codeExpiration = int(get_setting(con, "code_duration")) cur.execute("SELECT * FROM 'auth' WHERE userid = ?", [userid]) try: credentials = cur.fetchall()[0] except IndexError: return "c...
def load(): g = RDF.Model() for dirpath, dirnames, filenames in os.walk(os.getcwd()): for filename in filenames: if filename.endswith('.nt') or filename.endswith('.ttl'): print >>sys.stderr, 'Loading %s ...' % os.path.join(dirpath, filename), g.load('file:' + ...
The main task of the code is to process a graph or dataset by loading it, extracting responsibilities and citations, performing inference, validating results, and serializing the final output to standard output. The function sequentially executes these steps to analyze and transform the input data into a structured for...
def main(): g = load() extract_responsibility(g) extract_citations(g) infer(g) validate(g) sys.stdout.write(serialize(g))
def log(message, prefix_newline=False): """Logging function, provides a hook to suppress or redirect log messages.""" print(('\n' if prefix_newline else '') + '{0:.2f}'.format(time.time()) + ': ' + str(message)) sys.stdout.flush() def run_microtrait_local(self, options): ''' Build the comman...
The main task of the code is to execute the microtrait analysis on input genomic data by validating parameters, staging input files, running the analysis with specified configurations, copying predefined result files, and generating a KBase report containing the outputs. The process involves data staging, analysis exec...
def run_microtrait(self, params): ''' Main entry point for running the microtrait as a KBase App ''' #print(json.dumps(self.scratch, indent=1)) # 0) validate basic parameters if 'input_ref' not in params: raise ValueError('input_ref field was not set in para...
def create_file(self, output_file): with open(output_file, "w", encoding="utf-8") as outfile: outfile.write("") def _print_timestamp_format(self, result, output_file, input_file, model_name, timetitle_list): self._write_output( result, output_file, input_f...
The main task of the code is to print processed results to an output file in a specified format ("timestamp" or "plain"). It creates the output file if needed, selects the appropriate formatting method based on the input format parameter, and raises an error for invalid formats. The function delegates formatting logic ...
def print_output(self, result, output_file, input_file, model_name, timetitle_list = None, format=None): self.create_file(output_file) if format is None or format == "timestamp": self._print_timestamp_format(result, output_file, input_file, model_name, timetitle_list) if format is No...
def CheckWinner(service_id): """ Checks if the caller is the winning provider for a specific service after the consumer has chosen a provider. Args: service_id (str): The unique identifier of the service. Returns: bool: True if the caller is the winning provider, False otherwis...
The function deploys a Kubernetes service if the user is the winner, returning the external IP upon success. If not the winner, it denies access. It handles exceptions by raising a 500 error with detailed messages.
def deploy_service_endpoint(service_id: str): try: if CheckWinner(service_id): create_k8s_resource_from_yaml(f"descriptors/examples/{YAMLFile.federated_service}") # Wait for the service to be ready and get the external IP external_ip = wait_for_service_ready("federated-s...
def train_fnc(train_model, data_loader, optim, dicefnc): train_model.train() tr_dc = 0 tr_loss = 0 counter = 0 for i, (x, y_mask) in enumerate(data_loader): x, y_mask = x.to("cuda", dtype=torch.float), y_mask.to("cuda", dtype=torch.float) if y_mask.max() > 0: x[x < -1000...
This code trains a 3D UNet model for segmentation using Dice loss, with validation, learning rate scheduling, and model saving. It iterates over epochs, trains on data loaders, tracks metrics, and plots training/validation performance.
def train_loop_seg(train_loader, val_loader, args): input_channels = next(iter(train_loader))[0].shape[1] print(input_channels) model = UNet3D() model.cuda() print(model) optimizer = torch.optim.SGD(model.parameters(), args.lr, momentum=0.9, weight_decay=0.0, nesterov=False) scheduler = Redu...
def on_session_started(session_started_request, session): """ Called when the session starts """ print("on_session_started requestId=" + session_started_request['requestId'] + ", sessionId=" + session['sessionId']) def on_launch(launch_request, session): """ Called when the user launches the ski...
This code handles Alexa skill requests by routing them to appropriate functions based on their type (e.g., LaunchRequest, IntentRequest). It checks the session status, validates the application ID (commented out), and delegates to on_launch(), on_intent(), or on_session_ended() to process the request, enabling interact...
def lambda_handler(event, context): """ Route the incoming request based on type (LaunchRequest, IntentRequest, etc.) The JSON body of the request is provided in the event parameter. """ print("event.session.application.applicationId=" + event['session']['application']['applicationId']) ...
def q_15(): """ Loads the dataset, performs the preprocessing and plot the singular values plot. """ X, y = load_data("kc_house_data.csv") w, s = fit_linear_regression(X, y) plot_singular_values(s) def q_16(): """ Fit a model and test it over the data. Splits the data into train and ...
The main task of the code is to execute functions for questions 15 and 16, load housing data from "kc_house_data.csv", and perform feature evaluation on the dataset. The `main()` function orchestrates these steps sequentially: first running `q_15()` and `q_16()`, then loading features (`X`) and target (`y`) from the CS...
def main(): """ Main function of the program, will execute question 15 and 16 and than load's the data and execute feature evaluation function """ q_15() q_16() X, y = load_data("kc_house_data.csv") feature_evaluation(X, y)
def MakingRequest(url: str) -> str: URL = 'https://www.x-rates.com/table/?from=USD&amount=1' r = requests.get(URL) if r.status_code == 200: soup = BeautifulSoup(r.text, 'html.parser') print("\033[92m Request was successfully done. The status code: {}".format(r.status_code)) USDollarE...
The code fetches exchange rate data from a URL, processes it into a dictionary and DataFrame, then saves the structured data as JSON and CSV files for storage and analysis.
def finalExecutionOfExchangeRate(): URL = 'https://www.x-rates.com/table/?from=USD&amount=1' MakingRequest(URL) ConvertingListComprehensionToDicionary() DictionaryDataCurrencyValues = DictionaryOfExchangeRate() SaveToJSONfile(DictionaryDataCurrencyValues) dfUSDollarExchangeRates = DataFrameOfExc...
def letter_count(pairing, m): rcount, pcount, scount, lcount, ycount = 0, 0, 0, 0, 0 """ if len(pairing) != m: print(len(pairing), m) raise ValueError("Invalid pairing length.") """ for letter in pairing: if letter == "R": rcount += 1 if letter == "P": ...
The code generates a string of length `m` using characters R, P, S, L, Y, adhering to input counts. It employs a multi-step strategy: first, constructing a "PRRR" pattern with heuristics for Y placement, then filling remaining characters trivially. It includes recursive adjustments, random shuffling guided by a mask, a...
def generate_initial_pairing(i, m, r_counts, p_counts, s_counts, l_counts, y_counts, level): if r_counts[i] + p_counts[i] + s_counts[i] + l_counts[i] + y_counts[i] != m: raise ValueError("Invalid input counts for R, P, S, L and Y.") pairing = "" # Create a mask for shuffling only certain i...
def replace_character(original_string, index, new_character): if 0 <= index < len(original_string): # Create a new string with the character replaced new_string = original_string[:index] + new_character + original_string[index + 1:] return new_string else: # Handle the case where...
The code processes an initial pairing by iteratively replacing 'X' characters with 'P' or 'S', then evolves the pairing through random mutations and selection. It maintains a list of candidate pairings, adjusting a threshold to prioritize higher fitness. When candidates exceed a limit, the fittest are retained, and mut...
def process_initial_pairing(i, m, pairing, level): x_indexes = [] for i in range(m): if pairing[i] == 'X': pairing = replace_character(pairing, i, random.choice(('P', 'P', 'P', 'S'))) x_indexes.append(i) pairing = pairing[:-1] # Get a list of decent candidates s...
def check_win_condition(pairing, m): processed_pairing = process_tournament(pairing, m) if "S" not in processed_pairing: return False if "R" in processed_pairing: return False return True def masked_shuffle(initial_string, mask): if len(initial_string) != len(mask): raise...
The code generates a pairing string of length `m` composed of 'R', 'P', and 'S' characters, ensuring counts match input values. It prioritizes creating "PRRR" groups, then adds remaining 'R'/'P', followed by 'S'. A mask is used to shuffle specific regions while preserving group structures. The pairing is validated agai...
def generate_initial_pairing(i, m, r_counts, p_counts, s_counts, level): if r_counts[i] + p_counts[i] + s_counts[i] != m: raise ValueError("Invalid input counts for R, P, and S.") pairing = "" # Create a mask for shuffling only certain indexes mask = '0' * m count = 0 # Cr...
def replace_character(original_string, index, new_character): if 0 <= index < len(original_string): # Create a new string with the character replaced new_string = original_string[:index] + new_character + original_string[index + 1:] return new_string else: # Handle the case where...
The main task of the code is to evolve a pairing string through iterative mutations and selection based on fitness thresholds. It replaces 'X's with random characters, evaluates fitness, adjusts selection thresholds dynamically, and maintains a population of candidate pairings. The process continues until the fitness r...
def process_initial_pairing(i, m, pairing, level): x_indexes = [] z_characters = [] for i in range(m): if pairing[i] == 'X': pairing = replace_character(pairing, i, random.choice(('P', 'S', 'R', 'L', 'Y'))) x_indexes.append(i) if pairing[i] == 'Z': z_chara...
def _darwin(llvm_version, arch): major_llvm_version = _major_llvm_version(llvm_version) suffix = "darwin-apple" if major_llvm_version == 9 else "apple-darwin" return "clang+llvm-{llvm_version}-{arch}-{suffix}.tar.xz".format( llvm_version=llvm_version, arch=arch, suffix=suffix) def _windows(llvm_vers...
The main task of the code is to generate and print the pre-built distribution filename for a specified LLVM version, tailored to the host system's OS (Darwin/Windows/Linux), version, and architecture by calling OS-specific helper functions.
def main(): """Prints the pre-built distribution file name.""" if len(sys.argv) != 2: sys.exit("Usage: %s llvm_version" % sys.argv[0]) llvm_version = sys.argv[1] os, version, arch = host_os_key.os_version_arch() if os == "darwin": print(_darwin(llvm_version, arch)) elif os ==...
def add_centered_textbox(self, prs, slide, text): slide_width = prs.slide_width slide_height = prs.slide_height textbox_width = Inches(6) textbox_height = Inches(1) left = (slide_width - textbox_width) / 2 top = (slide_height - textbox_height) / 2 # Centers the textbox v...
The code generates a PowerPoint presentation with user-defined slides, applying chosen background and textbox colors cyclically, adding job ID information, text content, and images, then saving the file with a specified name.
def create_presentation(self): if len(self.slides) == 0: messagebox.showerror("Error", "Please create the required number of slides") return if not hasattr(self, "choose_fill_color"): messagebox.showerror("Error", "Please select a text color first.") retu...
def add_centered_textbox(self, prs, slide, text): slide_width = prs.slide_width slide_height = prs.slide_height textbox_width = Inches(6) textbox_height = Inches(1) left = (slide_width - textbox_width) / 2 top = (slide_height - textbox_height) / 2 # Centers the textbox v...
The code generates a PowerPoint presentation by creating slides with customizable background and textbox colors, adding text and images based on user inputs, and saving the final file with a specified name.
def create_presentation(self): if len(self.slides) == 0: messagebox.showerror("Error", "Please create the required number of slides") return if not hasattr(self, "choose_fill_color"): messagebox.showerror("Error", "Please select a text color first.") retu...
def V2Cuda(x): if use_cuda: return x.cuda() else: return x def _train_classifier(self,maxiter): ## Train classifer batch_size = 64 train_idx = np.arange(int(self.data_joint_train_seq.size()[0])) criterion = nn.BCELoss() val_loss = [] measure_...
The code estimates mutual information (MI) between variables x and y using a neural network classifier. It initializes a classifier, splits data into training/evaluation sets, trains the model on joint and marginal distributions, and computes MI via the classifier's learned representations. The result is returned as a ...
def get_mi(self, x, y, x_shuffle_dim=None): self.classifier = V2Cuda(Classifer(input_dim=( x.size()[1], y.size()[1] ), hidden_size= self.hidden_size*2, embed_size=self.hidden_size )) self.optimizer_order = optim.Adam(self.classifier.parameters(),lr=self.lr,weight_decay = 1e-4) train_partition ...
def _load_yaml(self) -> None: with open(self.path, "r") as f: args = yaml.load(f, Loader=yaml.SafeLoader) self.config = _Config(**args) def _create_parser(self) -> None: self.parser = argparse.ArgumentParser() def _add_parser_args(self) -> None: self.__add_parser_args([], sel...
The code initializes an object by loading YAML data from a specified path. If `create_parser` is True, it creates a command-line argument parser, adds arguments, and parses them. The main tasks are loading configuration data and optionally setting up argument parsing for further processing.
def __init__(self, path: str, create_parser: bool = False) -> None: self.path = path self._load_yaml() if create_parser: self._create_parser() self._add_parser_args() self._parse_args()
def check_for_string(question, title): output = easygui.enterbox(question, title=title) if type(output) != str: option_control() return output def typo_checker(text1, text2): if text1 == text2: return True for mistake1 in range(1, len(text1)): test = text1[0:mistake1] + text1...
The main task of the code is to delete a specified card from a dictionary. It prompts the user for the card name, checks for typos, confirms deletion via a GUI dialog, and removes the card if confirmed. The function uses `check_for_string` to get input, `typo_checker` to validate matches, and `easygui` for user interac...
def delete_card(): target = check_for_string("what card do you want to delete?", "delete card") for name, card in cards.items(): if typo_checker(target, name) == True: if easygui.buttonbox(f"do you want to delete\n {format_card(name, card)}", choices=["yes", "no"]) == "yes": ...
def check_for_string(question, title): output = "" while type(output) != str or output in cards or output == "": #checking to make sure input is valid output = easygui.enterbox(question, title=title) return output def check_for_number(question, title): output = easygui.integerbox( ...
The main task of the code is to collect user input for a new monster card's name and four statistics (speed, strength, cunning, stealth), validate the inputs, and add the card to a dictionary if confirmed. It uses helper functions to ensure proper input types and verifies the card details before storage.
def add_new_card(): card = {} name = check_for_string("what is the monsters name?", "add new card") #getting new cards name for stat in ["speed", "strength", "cunning", "stealth"]: card[stat] = check_for_number(f"what is the {stat} of {name}?", f"inputing {s...
def check_for_string(question, title): output = easygui.enterbox(question, title=title) if type(output) != str: option_control() return output def check_for_number(question): output = easygui.integerbox(question, upperbound=25, lowerbound=0) if type(output) != int: option_control() ...
The main task of the code is to collect user-input data for a new monster card, validate the inputs, and store them in a dictionary. It prompts for a monster's name, then gathers and validates numerical values for four attributes: speed, strength, cunning, and stealth. After populating a card dictionary with these valu...
def add_new_card(): card = {} name = check_for_string("what is the monsters name", "add new card") for stat in ["speed", "strength", "cunning", "stealth"]: card[stat] = check_for_number(f"what is the {stat} of {name}") cards[name] = check_if_card_right(name, card)
def check_for_string(question, title): output = easygui.enterbox(question, title=title) if type(output) != str: option_control() return output def typo_checker(text1, text2): if text1 == text2: return True for mistake1 in range(1, len(text1)): test = text1[0:mistake1] + text1...
The main task of the code is to search for a card by prompting the user for input, checking for typos in card names, confirming matches via a GUI button, and validating the selected card. It iterates through a dictionary of cards, uses typo detection to identify potential matches, and verifies user intent through inter...
def search_for_card(): query = check_for_string("what card are you looking for", "search for card") for name, card in cards.items(): if typo_checker(name, query) == True: if easygui.buttonbox(f"are you after {name}", choices=["yes", "no"]) == "yes": check_if_card_right(name, ...
def importImages(self, modality): middenImages = load('Phase3/Data/'+modality+'/MiddenImages.npy') rotated90MiddenImages = load('Phase3/Data/'+modality+'/Rotated90MiddenImages.npy') rotated180MiddenImages = load('Phase3/Data/'+modality+'/Rotated180MiddenImages.npy') rotated270MiddenImage...
This code initializes a machine learning model for image classification, loading multi-modal data (Thermal, RGB, LiDAR, Fused) and associated binning data. It sets up training/test loaders, initializes models, and executes training based on the specified 'setting' parameter (e.g., passive learning, active uncertainty, ...
def __init__(self, setting, indices): # global variables self.transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize([0.485, 0.456, 0.406],[0.229, 0.224, 0.225])]) self.labelingBudget = 300 self.accuracy = 0 self.class0Accuracy = 0 self.class1Accuracy...
def __forward_prop__(self, x): """ Perform forward propagation and return network output """ out = x for layer in self.layers: out = layer.output(out) return out def __backward_prop__(self, deltas, eta, nesterov): """ Perform backward propagati...
The function trains a neural network using provided training and validation data, a specified loss function, and evaluation metric over a given number of epochs. It performs forward and backward propagation, updates weights with a learning rate and Nesterov momentum, computes training/validation loss/accuracy, and trig...
def train( self, train: tuple, validation: tuple, metric: Metric, loss: Loss, epochs=25, eta=10e-3, verbose=True, callbacks: List[Callback] = [], nesterov=0, ): """ Train network with given data and labels for requested ...
def getLogger(): return logging.getLogger("mnstatus") def dtnow(): """Get datetime for now in UTC timezone.""" return datetime.datetime.now(datetime.timezone.utc) def _doget( self, url, params=None, verify=True, call_back=None, timeout=HTTP_TIMEOUT ): _L = getLogger() t_start = d...
The function retrieves object metadata from a DataONE Node (MN) by sending a GET request to list objects, parsing the XML response to extract total counts and date ranges, and returns a structured result containing status, elapsed time, counts, and timestamp information.
def objectInfoFromMN(self): _L = getLogger() url = urllib.parse.urljoin(self.base_url, self.version + "object") params = {"start": 0, "count": 2} result = { "method": "mn.listObjects", "elapsed": 0, "url": url, "status": 0, "mes...
def getLogger(): return logging.getLogger("mnstatus") def dtnow(): """Get datetime for now in UTC timezone.""" return datetime.datetime.now(datetime.timezone.utc) def _doget( self, url, params=None, verify=True, call_back=None, timeout=HTTP_TIMEOUT ): _L = getLogger() t_start = d...
The main task of the code is to retrieve object information from a CN (likely a data repository) by making a GET request to list objects. It constructs a URL, sends a request with parameters, parses the XML response to extract the total object count and date ranges, logs details, and returns a structured result contain...
def objectInfoFromCN(self): _L = getLogger() list_objects_url = urllib.parse.urljoin(self.cn_url, "v2/object") params = {"start": 0, "count": 2, "nodeId": self.node_id} result = { "method": "cn.listObjects", "elapsed": 0, "url": list_objects_url, ...
def set_whisker(self, angle): self.angle = angle self.whisker_vertices = self.whisker_base + \ np.vstack([(0, 0), a2xy(np.pi - self.angle, self.whisker_len)]) def set_whisker_model(self, angle): self.whisker_model_vertices = self.whisker_model_base + \ np.vstack([(0, 0), ...
This code initializes a class instance representing an object with a box shape and whiskers. It sets box dimensions based on the 'type' parameter (still/normal/large), defines whisker properties, and initializes positions. The box's points are stored, and the object's position is adjusted via move_box(0).
def __init__(self, name, type, stime): self.name = name self.type = type self.stime = stime sidewidth = 0.8 sideheight = 1.5 center = [0, 1] still_box = np.array([ (-sidewidth, -sideheight), (sidewidth, -sideheight), (sidewidt...
def get_source_module_data( *, source_type: str, legalserver_data: Dict | None = None, legalserver_matter_uuid: str | None = None, legalserver_site: str | None = None, custom_field_list: List | None = None, ) -> List: """Helper function to check and then collect source data for populating ...
The main task of the code is to populate a DAList of Person objects with adverse party details from LegalServer data. It retrieves data via an API call if not provided, maps fields like names, addresses, contact info, and custom attributes to each Person object, handling both individual and organizational records. It e...
def populate_adverse_parties( *, adverse_party_list: DAList, legalserver_data: dict | None = None, legalserver_matter_uuid: str = "", legalserver_site: str = "", ) -> DAList: """Take the data from LegalServer and populate a list of LegalServer Adverse Partyrecords into a DAList of Persons. ...
def get_source_module_data( *, source_type: str, legalserver_data: Dict | None = None, legalserver_matter_uuid: str | None = None, legalserver_site: str | None = None, custom_field_list: List | None = None, ) -> List: """Helper function to check and then collect source data for populating ...
The function populates a DAList of Individuals with non-adverse party data from LegalServer. It retrieves data via an API call if not provided, iterates through the source data, and maps each item's attributes (e.g., name, DOB, relationship type, addresses, phone numbers) to corresponding fields in the DAList. It handl...
def populate_non_adverse_parties( *, non_adverse_party_list: DAList, legalserver_data: dict | None = None, legalserver_matter_uuid: str = "", legalserver_site: str = "", ) -> DAList: """Take the data from LegalServer and populate a list of LegalServer Non-Adverse Party records into a DAList ...
def populate_assignments( *, assignment_list: DAList, legalserver_data: dict | None = None, legalserver_matter_uuid: str = "", legalserver_site: str = "", ) -> DAList: """Take the data from LegalServer and populate a list of LegalServer Assignment records into a DAList of DAObjects. Thi...
This function populates an Individual object with user data from the current primary assignment on a case. It first ensures the assignment list is populated, then identifies the active "Primary" assignment, retrieves user details via LegalServer (using provided data or site/UUID), and updates the Individual object with...
def populate_primary_assignment( *, primary_assignment: Individual, assignment_list: DAList, legalserver_data: dict | None = None, legalserver_matter_uuid: str = "", legalserver_site: str = "", user_custom_fields: List | None = None, ) -> Individual: """ This is a keyword defined fun...
def populate_assignments( *, assignment_list: DAList, legalserver_data: dict | None = None, legalserver_matter_uuid: str = "", legalserver_site: str = "", ) -> DAList: """Take the data from LegalServer and populate a list of LegalServer Assignment records into a DAList of DAObjects. Thi...
This function identifies the earliest active Pro Bono assignment from a list, extracts its user data, and populates an Individual object with details like user UUID, start date, and custom fields. It first ensures the assignment list is populated, filters for unended Pro Bono assignments, selects the earliest by start ...
def populate_first_pro_bono_assignment( *, legalserver_first_pro_bono_assignment: Individual, assignment_list: DAList, legalserver_data: dict | None = None, legalserver_matter_uuid: str = "", legalserver_site: str = "", user_custom_fields: List | None = None, ) -> Individual: """ Thi...
def populate_assignments( *, assignment_list: DAList, legalserver_data: dict | None = None, legalserver_matter_uuid: str = "", legalserver_site: str = "", ) -> DAList: """Take the data from LegalServer and populate a list of LegalServer Assignment records into a DAList of DAObjects. Thi...
This function populates an Individual object with data from the latest active Pro Bono assignment on a case. It processes an assignment list to identify the most recent unended Pro Bono assignment, updates the Individual's user UUID and start date, retrieves user details via get_user_details, and populates the object w...
def populate_latest_pro_bono_assignment( *, legalserver_latest_pro_bono_assignment: Individual, assignment_list: DAList, legalserver_data: dict | None = None, legalserver_matter_uuid: str = "", legalserver_site: str = "", user_custom_fields: List | None = None, ) -> Individual: """ T...
def populate_assignments( *, assignment_list: DAList, legalserver_data: dict | None = None, legalserver_matter_uuid: str = "", legalserver_site: str = "", ) -> DAList: """Take the data from LegalServer and populate a list of LegalServer Assignment records into a DAList of DAObjects. Thi...
This function populates a DAList of Individuals with users having active Pro Bono assignments from a case. It filters assignments by type ("Pro Bono") and checks for non-ended status (end_date is None). For each valid assignment, it retrieves user details via get_user_details, populates Individual objects, and appends ...
def populate_pro_bono_assignments( *, pro_bono_assignment_list: DAList, assignment_list: DAList, legalserver_data: dict | None = None, legalserver_matter_uuid: str = "", legalserver_site: str = "", user_custom_fields: List | None = None, ) -> DAList: """ This is a keyword defined fun...
def crawl_company(stock_name): first_page = driver.get('http://www.tsetmc.com/Loader.aspx?ParTree=15') time.sleep(3) second_page = driver.find_element_by_xpath('//*[@id="rainbow_global_1"]').click() time.sleep(3) third_page = driver.find_element_by_xpath('//*[@id="TseTab1Elm"]/div[3]/div[1]').click(...
The code's main task is to gather and process stock-related data by calling functions to crawl company information, scrape key features, retrieve historical data, and fetch historical records with specific parameters (3, 37) for a given stock name.
def crawl_scrape(stock_name): crawl_company(stock_name) scrape_features(stock_name) crawl_history() crawl_scrape_history(stock_name, 3, 37)
def compute_stats (self, data_coord, data_box, data_atype, natoms_vec, mesh, reuse = None) : avg_zero = np.zeros(self.ndescrpt).astype(np.float64) std_ones = np.ones ...
The main task of the code is to initialize and configure a machine learning model for molecular dynamics or physics simulations. It sets up TensorFlow placeholders, computes model statistics, builds interaction networks for energy/force predictions, defines loss functions, and configures distributed training with Adam ...
def build (self, data, lr) : self.ntypes = len(self.sel_a) assert (self.ntypes == len(self.sel_r)), "size sel r array should match ntypes" assert (self.ntypes == data.get_ntypes()), "ntypes should match that found in data" self.batch_size = data.get_batch_s...
def make_place (self) : self.coord = tf.placeholder(tf.float64, [None, self.natoms[0] * 3], name='t_coord') self.box = tf.placeholder(tf.float64, [None, 9], name='t_box') self.type = tf.placeholder(tf.int32, [None, self.natoms[0]], name = "t_type") self.tnatoms = t...
This code tests the correctness of computed derivatives (dw) by comparing analytical gradients with numerical derivatives. It perturbs each weight component, computes loss changes, and calculates relative/absolute differences. The goal is to validate gradient accuracy in a neural network model, ensuring the implemented...
def test_dw (self, data) : self.make_place () feed_dict_test0 = self.make_feed_dict0 (data) w0 = np.ones (self.ndescrpt) self.net_w_i = np.copy(w0) t_ll, t_dw = self.comp_fl (self.coord, self.box, self.type, self.tnatoms, name = "test_0") self....
def make_place (self) : self.coord = tf.placeholder(tf.float64, [None, self.natoms[0] * 3], name='t_coord') self.box = tf.placeholder(tf.float64, [None, 9], name='t_box') self.type = tf.placeholder(tf.int32, [None, self.natoms[0]], name = "t_type") self.tnatoms = t...
This code tests the correctness of analytical derivatives (dw_0) against numerical derivatives computed via finite differences. It perturbs each weight in the descriptor network, calculates the loss (ll) with modified weights, and compares the numerical gradient (num_v) with the analytical gradient (ana_v). Absolute an...
def test_virial_dw (self, data) : self.make_place () feed_dict_test0 = self.make_feed_dict0 (data) w0 = np.ones (self.ndescrpt) self.net_w_i = np.copy(w0) t_ll, t_dw = self.comp_vl (self.coord, self.box, self.type, self.tnatoms, name = "test_0")...
def RandomMotifs(Dna, k, t): # place your code here. s = len(Dna[0]) rm = [] for i in range(0,t): init_index = random.randint(1,s-k) rm.append(Dna[i][init_index:init_index+k]) return rm def ProfileWithPseudocounts(Motifs): t = len(Motifs) k = len(Motifs[0]) profile = ...
The main task of the code is to implement the Gibbs sampling algorithm for motif discovery. It iteratively refines a set of motifs by randomly selecting a position, generating a profile from the remaining motifs (with pseudocounts), and replacing the selected motif with a new one generated using the profile. The proces...
def GibbsSampler(Dna, k, t, N): BestMotifs = [] # output variable # your code here Motifs = RandomMotifs(Dna, k, t) BestMotifs = Motifs for j in range(1,N): i = random.randint(0,t-1) ReducedMotifs = [] for j in range(0,t): if j != i: ReducedMotifs....
def Profile(Motifs): t = len(Motifs) k = len(Motifs[0]) profile = {} profile = Count(Motifs) for symbol in "ACGT": for j in range(k): profile[symbol][j] = profile[symbol][j]/t return profile def ProfileMostProbableKmer(Text, k, Profile): max_probability = 0 most_proba...
(GreedyMotifSearch identifies the best set of k-length motifs from t DNA strings by iterating through all possible starting positions in the first string. For each position, it constructs motifs using a profile-based approach, selecting the most probable k-mer for subsequent strings. It updates the best motifs if the c...
def GreedyMotifSearch(Dna,k,t): #this is the actual greedy algorithm, which has 6 dependencies of the previous code BestMotifs = [] for i in range(0, t): BestMotifs.append(Dna[i][0:k]) n = len(Dna[0]) for m in range(n-k+1): Motifs = [] Motifs.append(Dna[0][m:m+k]) for j i...
def ProfileWithPseudocounts(Motifs): t = len(Motifs) k = len(Motifs[0]) cont=CountWithPseudocounts(Motifs) for i in range(k): su=0 for symbol in "ACGT": su=su+cont[symbol][i] for symbol in "ACGT": cont[symbol][i] = cont[symbol][i]/su profile=cont r...
The function performs Greedy Motif Search with pseudocounts to find the best set of k-length motifs in t DNA sequences. It initializes candidate motifs, iterates over all possible starting positions in the first DNA string, constructs motifs using pseudocount-based profiles, and selects the set with the lowest score. P...
def GreedyMotifSearchWithPseudocounts(Dna,k,t): BestMotifs = [] for i in range(0, t): BestMotifs.append(Dna[i][0:k]) n = len(Dna[0]) for m in range(n-k+1): Motifs = [] Motifs.append(Dna[0][m:m+k]) for j in range(1, t): P = ProfileWithPseudocounts(Motifs[0:j]) ...
def RandomMotifs(Dna, k, t): Motifs = [] n = len(Dna[0]) num = random.randint(0,n-k) for i in range (t): Motifs.append(Dna[i][num:num+k]) return Motifs def ProfileWithPseudocounts(Motifs): t = len(Motifs) k = len(Motifs[0]) cont=CountWithPseudocounts(Motifs) for i in range(k)...
The GibbsSampler function iteratively refines a set of motifs by randomly selecting a DNA string, generating a new motif using a profile from the remaining motifs, and updating the set if the new score is lower. It repeats this N times to approximate the optimal motif set, leveraging probabilistic sampling to improve a...
def GibbsSampler(Dna, k, t, N): BestMotifs = [] # output variable Motifs = RandomMotifs(Dna, k, t) #print(Motifs) BestMotifs = Motifs for j in range(N): i = random.randint(0,t-1) new_Motif = [] for k1 in range(t): if k1!=i: new_Motif.append(Motifs[...
def RandomMotifs(Dna, k, t): Motifs = [] n = len(Dna[0]) num = random.randint(0,n-k) for i in range (t): Motifs.append(Dna[i][num:num+k]) return Motifs def ProfileWithPseudocounts(Motifs): t = len(Motifs) k = len(Motifs[0]) cont=CountWithPseudocounts(Motifs) for i in range(k)...
The main task of the code is to find the best set of k-length motifs (one from each of t DNA sequences) with the lowest score using a randomized iterative approach. It starts with random motifs, generates a profile with pseudocounts, creates new motifs from the profile, and updates the best motifs if the new score is l...
def RandomizedMotifSearch(Dna, k, t): M = RandomMotifs(Dna, k, t) BestMotifs = M while True: Profile = ProfileWithPseudocounts(M) M = Motifs(Profile, Dna) if Score(M) < Score(BestMotifs): BestMotifs = M else: return BestMotifs
def create_csv_file(file_name): with open(file_name, 'w', newline='') as csvfile: writer = csv.writer(csvfile) field = ['Time_Difference', 'side_to_side', 'keyboard'] writer.writerow(field) def create_final_data(data): dataclean = clean_data(data) keyboard = keyboard_type(dataclean[0...
The main task of the code is to execute a test workflow: create a CSV file named "test.csv", generate processed data from mock input using create_final_data(), save the data into the CSV file via save_data(), and print status messages to indicate test initiation and completion. This function validates the end-to-end pr...
def run_test(): print("Running test") file_name = "test.csv" create_csv_file(file_name) data = create_final_data(mock_data) save_data(file_name, data) print("Finished test")
def create_csv_file(file_name): with open(file_name, 'w', newline='') as csvfile: writer = csv.writer(csvfile) field = ['Time_Difference', 'side_to_side', 'keyboard'] writer.writerow(field) def create_final_data(data): dataclean = clean_data(data) keyboard = keyboard_type(dataclean[0...
The code's main task is to save processed data into a CSV file. It creates a CSV named "saving.csv", generates final data from the input `data_p`, and writes this data to the file. The function prints status messages indicating the start and completion of the save process.
def run_save(data_p): print("Running save") file_name = "saving.csv" create_csv_file(file_name) data = create_final_data(data_p) save_data(file_name, data) print("Finished save")
def slide_inference(self, img, img_meta, rescale): """Inference by sliding-window with overlap. If h_crop > h_img or w_crop > w_img, the small patch will be used to decode without padding. """ h_stride, w_stride = self.test_cfg.stride h_crop, w_crop = self.test_cfg.crop...
This code performs image segmentation inference using either sliding or whole-image mode. It processes input images, applies post-processing (e.g., flipping), computes segmentation maps with softmax/sigmoid, and calculates losses if ground truth is provided. The output is a segmentation map with optional loss metrics.
def inference(self, img, img_meta, rescale, **kwargs): """Inference with slide/whole style. Args: img (Tensor): The input image of shape (N, 3, H, W). img_meta (dict): Image info dict where each dict has: 'img_shape', 'scale_factor', 'flip', and may also contain ...
def import_object_class(db_map, class_name): """Imports an object class. Args: db_map (DatabaseMapping): a database map class_name (str): object class name """ successes, errors = import_object_classes(db_map, (class_name,)) if errors: print("Encountered errors while importi...
(The main task of the code is to import data from multiple netCDF files into a Spine database. It connects to the database, sets up required classes/parameters, processes each file (validating and importing data), and commits changes. Invalid files are skipped, and the database connection is closed properly.)
def process_files(file_names, url, class_name, parameter, alternative): """Opens given netCDF files and imports their contents to a Spine database. Args: file_names (Iterable of str): paths to input .nc files url (str): database URL class_name (str): object class name parameter ...
def checkbox_event(self, widget): for frame in self.frame_list: if frame['task'] == widget and frame['task'].get() == 'Done': frame['task'].configure(font=font_body_16_overstrike, text_color=text_tertiary) update_status(table_name=self.table_name, status=frame['task']...
This method adds a task frame to a GUI with a checkbox for task status and a delete button. It creates a CTkFrame, configures layout, adds a checkbox linked to a StringVar for status toggling between 'Done'/'To Do', binds checkbox events, adds a delete button with click handling, adjusts checkbox styling based on statu...
def add_task_frame(self, task_name, task_status): task_var = StringVar(value=task_status) frame = ctk.CTkFrame(self.task_scrollable_frame, fg_color=widget_color) frame.columnconfigure(0, weight=1) frame.grid(row=len(self.frame_list), column=0, padx=40, pady=(0, 10), sticky='ew') ...
def create_error_label(master): error_label = ctk.CTkLabel(master, text='', text_color=text_error, font=font_error) return error_label def create_entry_widget(master, text, icon=None, valid_icon=None, show='', validate_command=None): frame = ctk.CTkFrame(master, fg_color=widget_color, corner_radius=18) ...
This code initializes a login interface with email and password fields, validation, a "Forgot Password" link, and a switch to register option, handling user input and navigation within a GUI application.
def __init__(self, master, forgot_password_command, switch_to_register_frame, **kwargs): super().__init__(master, **kwargs) self.forgot_pass_command = forgot_password_command self.switch_to_command = switch_to_register_frame self.show_password = False self.acc_signin = AccountSig...
def create_error_label(master): error_label = ctk.CTkLabel(master, text='', text_color=text_error, font=font_error) return error_label def create_entry_widget(master, text, icon=None, valid_icon=None, show='', validate_command=None): frame = ctk.CTkFrame(master, fg_color=widget_color, corner_radius=18) ...
This code initializes a GUI interface for changing a password. It sets up email and password input fields with validation, error labels, and toggle buttons for showing/hiding passwords. It includes 'Cancel' and 'Change Password' buttons, binds events for password visibility toggling, and links the 'Change Password' act...
def __init__(self, master, cancel_button_command, **kwargs): super().__init__(master, **kwargs) self.cancel_button_command = cancel_button_command self.change_pass = ChangePassword() self.old_show_password = False self.new_show_password = False # Configure frame grid lay...
def create_error_label(master): error_label = ctk.CTkLabel(master, text='', text_color=text_error, font=font_error) return error_label def create_entry_widget(master, text, icon=None, valid_icon=None, show='', validate_command=None): frame = ctk.CTkFrame(master, fg_color=widget_color, corner_radius=18) ...
This code initializes a registration UI with fields for fullname, email, and password, including validation, error labels, and buttons. It sets up event bindings for password visibility toggle, account switch, and registration submission, using a grid layout for responsive design.
def __init__(self, master, switch_to_signin, **kwargs): super().__init__(master, **kwargs) self.acc_registration = AccountRegistration() self.switch_to_command = switch_to_signin self.show_password = False # Configure frame grid layout self.columnconfigure(0, weight=1) ...
def create_banner(master, banner_label, color): frame = ctk.CTkFrame(master, fg_color=color, corner_radius=0,) label = ctk.CTkLabel(frame, text=banner_label, text_color=text_secondary, font=font_body_16, width=30) label.grid(row=0, column=0, padx=20, pady=5, sticky='nsew') count = ctk.CTkLabel(frame, ...
This code initializes a task management GUI interface with a header, 'To Do'/'Done' banners, a 'New Task' button, and a scrollable task area. It sets up layout configurations, binds a sign-out action, and prepares components for dynamic task handling.
def __init__(self, master, table_name, **kwargs): super().__init__(master, **kwargs) self.configure(fg_color='transparent', corner_radius=0) self.table_name = table_name self.toplevel_window = None self.frame_list = [] # Configure frame grid layout self.columncon...
def make_target_obj_from_contig(target, indexed_contig): try: data = indexed_contig[target.pos] return Variant(target.chrom, target.pos, data[0], data[1], target.reference).normalize() except: return target.normalize() def precleaning(genome_indexed_contig, variants_list, target_pos, pil...
The function `phase_nearby_variants` identifies and phases genetic variants (SNVs/indels) near a target position in a DNA contig. It filters variants based on quality thresholds, removes conflicting or non-phasable variants, and applies greedy phasing to determine if the target variant can be phased with nearby variant...
def phase_nearby_variants( target, contig, pileup, basequalthresh, snv_neighborhood, indel_neighborhood, indel_repeat_thresh, mut_frac_thresh, hard, to_complex, ): # no indel reads or contig construction failure if contig.failed: return NullVariant(target.chrom, ...
def _step_forward(self, actions): self._step_actions(actions) self._step_collisions() player1_reward, player2_reward, done = self._step_check_victory() return player1_reward, player2_reward, done def _step_render_frame(self): self._reset_screen() self._render_ball() ...
The main task of the code is to process agent actions in a multiplayer or singleplayer game environment, advance the game state over multiple steps (controlled by frameskip), calculate rewards, check if the episode is done, and return the updated observation, reward, termination status, and debug info. It handles both ...
def step(self, actions): """ This function is a modification of the Openai gym step function for two players. ARGUMENTS: tuple, action: The actions that both agents took (multiplayer mode) or int, action: The action that the player agent took (singleplayer mode) ...
def scoreSectors(df): goodSectors = getAboveAverageSectors(df) scores = {} for sector in sectors: scores[sector] = [] for k, v in goodSectors.items(): if sector in v: scores[sector].append(k) return scores def findVolumeTrends(startDay, count, cutOff): cou...
The code processes financial data for a given day, printing sector scores, volume trends (±20% daily changes), and price trends (±3% daily changes) from CSV files. It identifies and displays stocks meeting these criteria, highlighting significant movements in volume and price for analysis.
def outPutData(day, date): print(date + ':') print('Sector Scores:') for k, v in scoreSectors(pd.read_csv(str(day) + '.csv')).items(): print(k, len(v)) print('') print('Volume went up +-20% each day') for k, v in findVolumeTrends(day, 4, 0.2).items(): if not v == []: ...
def loadCsv(filename): lines = csv.reader(open(filename, "r")) dataset = list(lines) for i in range(len(dataset)): dataset[i] = [float(x) for x in dataset[i]] return dataset def splitDataset(dataset, splitRatio): trainSize = int(len(dataset) * splitRatio) trainSet = [] copy = list(dataset) while len(trainSet)...
The code implements a Naive Bayes classifier to predict iris flower classes. It loads the iris.csv dataset, splits it into training (67%) and test sets, trains the model using summary statistics by class, predicts test set outcomes, and calculates accuracy. The final output is the model's accuracy percentage on the tes...
def main(): filename = 'Naive Bayes - 2.7/iris.csv' splitRatio = 0.67 dataset = loadCsv(filename) trainingSet, testSet = splitDataset(dataset, splitRatio) print('Split {0} rows into train={1} and test={2} rows'.format(len(dataset), len(trainingSet), len(testSet))) # prepare model summaries = summarizeByClass(tra...
def get_device_by_mountpoint(mountpoint): """ This accepts a mountpoint and returns the device assignment: /dev/sda1 and mountpoint """ partitions = psutil.disk_partitions(all=False) for p in partitions: if p.device.startswith('/dev/sd') and p.mountpoint.startswith(mountpoint): ...
The function `log_drive_report` logs detailed information about a selected plot drive, including its name, total size, available plots, serial number, temperature, and mount point. It retrieves disk usage data using `psutil` and formats the output with a predefined template for structured logging.
def log_drive_report(): """ Logs a drive report of our newly selected plot drive """ templ = "%-15s %6s %15s %12s %10s %5s" log.info(templ % ("New Plot Drive", "Size", "Avail Plots", "Serial #", "Temp °C", "Mount Point")) usage = psutil.disk_usage(get_device_by_mountpoint...
def get_device_by_mountpoint(mountpoint): """ This accepts a mountpoint and returns the device assignment: /dev/sda1 and mountpoint """ partitions = psutil.disk_partitions(all=False) for p in partitions: if p.device.startswith('/dev/sd') and p.mountpoint.startswith(mountpoint): ...
This function sends an email notification when a new plotting drive is selected, including details about the current drive's usage, previous drive stats, drive health, and server-wide plot capacity. It checks configuration settings to enable/disable notifications and compiles system data like drive size, available plot...
def send_new_plot_disk_email(): usage = psutil.disk_usage(get_device_by_mountpoint(get_plot_drive_to_use())[0][0]) current_plotting_drive = read_config_data('plot_manager_config', 'plotting_drives', 'current_plotting_drive', False) if read_config_data('plot_manager_config', 'notifications', 'new_plot_drive'...
def get_device_by_mountpoint(mountpoint): """ This accepts a mountpoint and returns the device assignment: /dev/sda1 and mountpoint """ partitions = psutil.disk_partitions(all=False) for p in partitions: if p.device.startswith('/dev/sd') and p.mountpoint.startswith(mountpoint): ...
The main task of the code is to send a daily email update containing system and storage metrics. It checks if daily notifications are enabled, then emails configured recipients with details about drive usage, device health, plot counts, and storage projections using a pre-defined HTML template.
def send_daily_update_email(): usage = psutil.disk_usage(get_device_by_mountpoint(get_plot_drive_to_use())[0][0]) if read_config_data('plot_manager_config', 'notifications', 'daily_update', True): for email_address in system_info.alert_email: send_template_email(template='daily_update.html',...
def get_current_coins(): with open(new_coin_log, 'rb') as f: f.seek(-2, os.SEEK_END) while f.read(1) != b'\n': f.seek(-2, os.SEEK_CUR) last_line = f.readline().decode() current_coins = (int((re.search((r"[0-9]{8,13}"), last_line).group(0)).strip('0'))) return (cu...
The code monitors Chia coin transactions by scanning log files for confirmed balance entries, extracting timestamps and coin identifiers, and comparing them against stored values. It alerts users via logs, notifications, and emails when new coins are detected, while avoiding duplicates by checking against existing reco...
def check_for_chia_coins(): log.debug('check_for_chia_coins() Started') coin_pattern = re.compile(r'\bConfirmed balance amount is') with open (chia_log, 'rt') as my_chia_logfile: for line in my_chia_logfile: if coin_pattern.search(line) != None: new_coin = [] ...
def get_all_available_system_space(type): """ Return Systems drive space information (total, used and free) based on plot_size """ partitions = psutil.disk_partitions(all=False) drive_space_available = [] for p in partitions: if p.device.startswith('/dev/sd') and p.mountpoint.startswith(...
The function `update_receive_plot` determines the optimal drive for receiving incoming plots, updates the netcat receive script and configuration if the drive changes, and handles remote transfer checks. It logs status, sends notifications, and ensures the script directs plots to the correct drive using netcat, with fu...
def update_receive_plot(): """ This utilizes the get_plot_drive_to_use() function and builds out our netcat receive_plot.sh script that is called by our plotting server when it is ready to send over a new plot. The plotting server sends the plot 'in the blind' so-to-speak, this function determines ...
def init_argparser(): with open('offlined_drives', 'r') as offlined_drives_list: offlined_drives = [current_drives.rstrip() for current_drives in offlined_drives_list.readlines()] parser = argparse.ArgumentParser(description=program_descripton, formatter_class=RawFormatter) parser.add_argument('-v',...
The main task of the code is to handle command-line arguments for system monitoring and maintenance tasks, including sending daily/plot reports, checking temperatures, managing offline/online drives, and updating plot counts. It routes arguments to corresponding functions, ensuring system status updates and notificatio...
def main(): parser = init_argparser() args = parser.parse_args() if args.daily_report: send_daily_email() elif args.plot_report: space_report() elif args.update_daily: update_daily_plot_counts() elif args.check_temps: temperature_report() elif args.offline_hdd...