dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def jacob0(S, q): Js = np.zeros((6, S.shape[1])) T = np.eye(4) for i in range(S.shape[1]): T = T @ twist2ht(S[:, i], q[i]) Js[:, i] = adjoint(S[:, i], T) return Js def calc_fkine_space(S, M, q): T = np.eye(4) for i in range(S.shape[1]): s = S[:, i] t = q[i] ...
The code performs inverse kinematics (IK) to adjust a robot's joint angles iteratively, using the Jacobian matrix's inverse to minimize the error between the current and target end-effector poses. It repeatedly calculates the Jacobian, computes joint adjustments (deltaQ), updates joint variables, and re-evaluates the p...
def calc_ik(get_poses_f, get_joint_variables_f, S, M, targetPose): currentPose = get_poses_f() #(robot) currentQ = get_joint_variables_f() #(robot) while np.linalg.norm(targetPose - currentPose) > 0.001: J = jacob0(S, currentQ) deltaQ = np.invert(J) @ (targetPose - currentPose) curr...
def atiku_neutral_location(): return neutral_location(atiku_df, atiku_tweet_df, atiku_model) def obi_neutral_location(): return neutral_location(obi_df, obi_tweet_df, obi_model) def tinubu_neutral_location(): return neutral_location(tinubu_df, tinubu_tweet_df, tinubu_model)
The function `get_neutral_locations` determines and returns specific neutral locations based on the input candidate's name. It checks if the candidate is 'abubakar', 'obi', or 'tinubu' (case-insensitive) and calls corresponding helper functions (`atiku_neutral_location`, `obi_neutral_location`, `tinubu_neutral_location...
def get_neutral_locations(candidate: str): if candidate.lower() == 'abubakar': return atiku_neutral_location() elif candidate.lower() == 'obi': return obi_neutral_location() elif candidate.lower() == 'tinubu': return tinubu_neutral_location()
def atiku_positive_location(): return positive_location(atiku_df, atiku_tweet_df, atiku_model) def obi_positive_location(): return positive_location(obi_df, obi_tweet_df, obi_model) def tinubu_positive_location(): return positive_location(tinubu_df, tinubu_tweet_df, tinubu_model)
The function determines the candidate's name and returns corresponding positive locations by calling specific functions: atiku_positive_location() for 'abubakar', obi_positive_location() for 'obi', and tinubu_positive_location() for 'tinubu'.
def get_positive_locations(candidate: str): if candidate.lower() == 'abubakar': return atiku_positive_location() elif candidate.lower() == 'obi': return obi_positive_location() elif candidate.lower() == 'tinubu': return tinubu_positive_location()
def atiku_negative_location(): return negative_location(atiku_df, atiku_tweet_df, atiku_model) def obi_negative_location(): return negative_location(obi_df, obi_tweet_df, obi_model) def tinubu_negative_location(): return negative_location(tinubu_df, tinubu_tweet_df, tinubu_model)
The function `get_negative_locations` retrieves specific negative locations based on the input candidate's name. It uses conditional checks to determine which predefined function to call: `atiku_negative_location()` for 'abubakar', `obi_negative_location()` for 'obi', and `tinubu_negative_location()` for 'tinubu', retu...
def get_negative_locations(candidate: str): if candidate.lower() == 'abubakar': return atiku_negative_location() elif candidate.lower() == 'obi': return obi_negative_location() elif candidate.lower() == 'tinubu': return tinubu_negative_location()
def vertex_equall(v1, v2): result = True result &= np.isclose(v1[0], v2[0]) result &= np.isclose(v1[1], v2[1]) result &= np.isclose(v1[2], v2[2]) return result def find_intersection_points(x1, y1, r1, x2, y2, r2): """ find intersection point between two circles """ d = np.sqrt((x2 - x1)**2 +...
The code aligns two triangles by rotating one to match the other's orientation. It identifies shared vertices, calculates edge distances, finds intersection points between edges, and generates potential rotated triangles. It then checks their orientation relative to the original and returns the correctly aligned triang...
def rotate_to_align(triangle, neighbor): same = False if np.array_equal(triangle, neighbor): same = True if same: return triangle result = [] z_value = triangle[0][2] # find same vertices and edge equal_vertices_indices = [] if vertex_equall(triangle[0], neighbor[0]): ...
def gamma_ij(edge_i: complex, edge_j: complex, edge_k: complex, z: complex) -> float: r_ij, r_ki, r_jk, s = gamma_func(edge_i, edge_j, edge_k, z) if abs(s) < 0.00001: return 0.0 return (r_jk * r_ki) / s def gamma_jk(edge_i: complex, edge_j: complex, edge_k: complex, z: complex) -> float: r_ij, ...
The function computes a complex interpolator by combining logarithmic ratio interpolations of input arrays with gamma factors derived from edge points. It calculates gamma values (g_ij, g_jk, g_ki) using edge points and a complex parameter z, then constructs l_t by weighting log_ratio_interpolator results with these ga...
def log_ratio_interpolator_primary(edge_i: complex, edge_j: complex, edge_k: complex, t: np.ndarray, u: np.ndarray, v: np.ndarray, w: np.ndarray, z: complex) -> np.ndarray: g_ij = gamma_ij(edge_i, edge_j, edge_k, z) g_jk = gamma_jk(edge_i, edge_j, edge_k, z) g_ki = gamma_ki(edge_i, edge_j, edge_k, z) l...
def tokenize(self): filepath = "../hack-examples/" + self.filename with open(filepath, mode = 'r', encoding = "utf-8") as f: self.tokens = [line.strip().replace(' ', '') for line in f if line.strip()[:2] != "//" and line.strip()] for i in range(len(self.tokens)): ...
The main task of the code is to execute a sequence of operations: tokenizing input data, updating relevant variables, generating code based on the processed data, and writing the final output. This method orchestrates data transformation from input to output through tokenization, variable updates, code generation, and ...
def run(self): self.tokenize() self.update_variables() self.generate_code() self.write_output()
def predict(self, features): return np.argmax(self._predict_proba(features), axis=1) def _predict_proba(self, features): """Predict class probabilities for X in 'soft' voting.""" probas, weights = self._collect_probas(features) return np.average(probas, weights=weights, axis=0) def plot_...
The function `compute_metrics` evaluates a model's classification performance by computing precision, recall, F1-score, confusion matrix, and ROC-AUC metrics for both binary and multiclass scenarios. It calculates ROC curves, saves them as CSV files, and computes micro/macro averages. Metrics are returned for model eva...
def compute_metrics(self, features, target, args, round_id, label): n_classes = target.unique().shape[0] pred = self.predict(features) pred_proba = self._predict_proba(features) target = target.to_numpy() if n_classes > 2: # multiclass case target_bin = label_binariz...
def _load_checkpoint(self, subreddit_name: str, sort: str, time_filter: str) -> int: """Loads the last processed index from a single file using a specific key with time filter.""" checkpoint_filename = "checkpoint.json" checkpoint_key = f"{subreddit_name}_{sort}_{time_filter}" try: ...
The code retrieves top threads from a specified Reddit subreddit, saves each thread and its comments as JSON files, and uses checkpoints to avoid reprocessing. It handles API interactions, logs progress, and supports sorting, time filters, and limit parameters to customize data retrieval.
def retrieve_threads( self, subreddit_name: str, sort: str = "top", time_filter: str = "all", limit: int = "1000", log_progress: bool = True, ) -> None: """High-level method to retrieve top threads and handle API interaction.""" last_processed_index = ...
def build_networks(): shape = (Args.sz, Args.sz, 3) # Learning rate is important. # Optimizers are important too, try experimenting them yourself to fit your dataset. # I recommend you read DCGAN paper. # Unlike gan hacks, sgd doesn't seem to work well. # DCGAN paper states that they used Adam...
The main task of the code is to train a GAN (Generative Adversarial Network) using a dataset stored in an HDF5 file. It builds the generator, discriminator, and GAN networks, optionally loads pre-trained weights, logs training loss to a CSV file, and processes a specific range of data batches (15000–30000) from the 'fa...
def train_gan(dataf): gen, disc, gan = build_networks() # Uncomment these, if you want to continue training from some snapshot. # (or load pretrained generator weights) load_weights(gen, "snapshots/9.gen.hdf5") load_weights(disc, "snapshots/9.disc.hdf5") logger = CSVLogger('loss.csv') # yeah,...
def train_autoenc(dataf): ''' Train an autoencoder first to see if your network is large enough. ''' f = h5py.File(dataf, 'r') faces = f.get('faces') opt = Adam(lr=0.001) shape = (Args.sz, Args.sz, 3) enc = build_enc(shape) enc.compile(optimizer=opt, loss='mse') enc.summary() ...
The code's main task is to pretrain an autoencoder, train a GAN using provided data, and generate images. It creates necessary directories, tests the generator's memorization capability via autoencoder pretraining, trains the GAN, and finally generates outputs using the trained model. The process aims to validate if a ...
def main(argv): if not os.path.exists(Args.snapshot_dir): os.mkdir(Args.snapshot_dir) if not os.path.exists(Args.anim_dir): os.mkdir(Args.anim_dir) # test the capability of generator network through autoencoder test. # The argument is that if the generator network can memorize the input...
def random_dd(self, mat): return self.make_diagonal_dominant(mat) def lower_dd(self, mat): for r in range(self.n): mat[r, r+1:] = 0 return self.make_diagonal_dominant(mat) def upper_dd(self, mat): for r in range(self.n): mat[r, :r] = 0 re...
The function `generate_A` creates an n×n random matrix and returns a specific type of matrix based on the `self.method` parameter. It uses conditional logic to call different private methods (`random_dd`, `lower_dd`, etc.), each generating a distinct matrix structure (e.g., lower triangular, symmetric, tri-diagonal). T...
def generate_A(self): mat = np.random.rand(self.n, self.n) if(self.method == "Random"): return self.random_dd(mat) elif(self.method == "Lower"): return self.lower_dd(mat) elif(self.method == "Upper"): return self.upper_dd(mat) elif(sel...
def generate_A(self): mat = np.random.rand(self.n, self.n) if(self.method == "Random"): return self.random_dd(mat) elif(self.method == "Lower"): return self.lower_dd(mat) elif(self.method == "Upper"): return self.upper_dd(mat) elif(sel...
The code generates a random matrix `A` and vector `b`, ensuring `A` is invertible. If `A` is singular, it recursively regenerates the matrix up to 100 attempts, incrementing a counter (`gmc`) each time. The method aims to produce a valid invertible matrix for further computations like solving linear systems.
def generate_matrix(self): self.A = self.generate_A() #print(self.A) self.b = np.random.rand(self.n, 1) if(not self.check_invertibility() and self.gmc < 100): print("Generated matrix is Singular!") self.gmc += 1 self.generate_matrix()
def generate_matrix(self): self.A = self.generate_A() #print(self.A) self.b = np.random.rand(self.n, 1) if(not self.check_invertibility() and self.gmc < 100): print("Generated matrix is Singular!") self.gmc += 1 self.generate_matrix()...
The code generates a system matrix (A) and vector (b) with a spectral radius within a valid range (less than 1) for convergence. It repeatedly generates new systems (up to 100 attempts) if the initial matrix fails, printing status updates. On success, it returns the valid matrix and vector; otherwise, it reports genera...
def generate_system(self, n): self.n = n self.generate_matrix() while(self.spc < 100): if(self.will_converge()): print("System generated successfully!") break else: print("Generated matrix has spectral radi...
def get_arguments(): parser = argparse.ArgumentParser(description='periodic macchanger') parser.add_argument('-i', '--interface', help = 'interface to edit', default = 'wlp6s0', required = False) parser.add_argument('-m', '--mac', help = 'new mac address', default = '00:11:22:33:44:55', required = False) ...
The main task of the code is to change a network interface's MAC address either once (if `time_interval` is 0) or repeatedly at set intervals (if `time_interval` > 0). It uses `get_arguments()` to parse inputs, `change_mac()` to alter the MAC address, and `start_loop()` to manage periodic changes. The function acts as ...
def main(): args = get_arguments() if args.time_interval == 0: change_mac(random_mac(), args.interface) else: start_loop(args)
def set_general_opts(self, args): """ :param args: defined dic with arguments for virulencefinder :result Creates first folder in given outputPath (default: .). """ self.outputPath = os.path.abspath(args.outputPath) os.makedirs(self.outputPath, exist_ok=True) if ...
The main task of the code is to initialize configuration settings for a virulence detection tool. It sets up directories, loads environment variables from a config file, and applies command-line arguments to configure general options, virulence finder parameters, virdb settings, and species-specific configurations.
def __init__(self, args: Namespace) -> None: # Directoy of config.py substracted the last dir 'cge' self.virulence_finder_root = os.path.dirname(os.path.realpath(__file__))[:-3] self.env_var_file = os.path.join( self.virulence_finder_root, "cge", Config.ENV_VAR_FILENAME ) ...
def get_xml_attribute(convert_func, xml_node, attribute_name, default_value, print_warning=True): if not attribute_name in xml_node.attrib and print_warning: print('Warning: Attribute {!r} was not found inside xml node {!s}[{!r}]. Set it to its default value {!r}.'.format( attribute_name, xml_no...
The function parses XML test suite data to generate a test summary report. It extracts metrics like test counts, durations, and timestamps, calculates success/failure rates, validates attributes, and constructs HTML components including a navigation bar, progress bars, and formatted summary text for visualization.
def generate_total_test_summary(xml_testsuites_node): # Parse the testsuites node attributes. total_abs_test_count = get_xml_attribute(int, xml_testsuites_node, 'tests', 0) total_abs_fail_count = get_xml_attribute(int, xml_testsuites_node, 'failures', 0) total_abs_disabled_count = get_xml_attribute(int,...
def get_xml_attribute(convert_func, xml_node, attribute_name, default_value, print_warning=True): if not attribute_name in xml_node.attrib and print_warning: print('Warning: Attribute {!r} was not found inside xml node {!s}[{!r}]. Set it to its default value {!r}.'.format( attribute_name, xml_no...
The function generates HTML listings for individual test results from an XML `testsuites` node, parsing attributes like test counts, failures, and execution time. It creates progress bars, checks for unknown XML attributes, and constructs HTML blocks for each test suite. The output includes the generated HTML and a lis...
def generate_single_test_result_listings(xml_testsuites_node): html_single_test_result_listing = '' collected_testsuite_ids = [] # Generate HTML for the single test result listings. xml_testsuite_nodes = xml_testsuites_node.findall('./testsuite') if len(xml_testsuite_nodes) == 0: print('War...
def generate_single_test_result_listings(xml_testsuites_node): html_single_test_result_listing = '' collected_testsuite_ids = [] # Generate HTML for the single test result listings. xml_testsuite_nodes = xml_testsuites_node.findall('./testsuite') if len(xml_testsuite_nodes) == 0: print('War...
The main task of the code is to convert an XML test report file into an HTML file. It parses the XML, validates its structure, extracts test results, generates HTML components (navbar, sidebar, summaries), and combines them using a template to create a formatted HTML output, which is then written to the specified desti...
def generate_html(report_file, destination_file): # Parse XML. xml_tree = ET.parse(report_file) xml_root = xml_tree.getroot() # Check if the root element 'testsuites' exists. xml_testsuites_nodes = xml_root.findall('.') if len(xml_testsuites_nodes) == 0: print('Error: The xml file {!r} ...
def roi_grid_pool(self, batch_dict): """ Args: batch_dict: batch_size: rois: (B, num_rois, 7 + C) point_coords: (num_points, 4) [bs_idx, x, y, z] point_features: (num_points, C) point_cls_scores: (N1 + N2 + N3 +...
The code processes input data through proposal generation, RoI pooling (grid, point, voxel), feature fusion, and classification/regression heads. During training, it assigns targets, handles pseudo/valid features, and computes losses. In inference, it generates predicted boxes. The main task is 3D object detection usin...
def forward(self, batch_dict): """ :param input_data: input dict :return: """ targets_dict = self.proposal_layer( batch_dict, nms_config=self.model_cfg.NMS_CONFIG['TRAIN' if self.training else 'TEST'] ) if self.training: targets_d...
def get_config(self): self.config = json.load(open(self.config_path, "r")) if self.custom_config != "": self.config = self.__update(self.config, self.custom_config) self.byte_order = self.config['byte_order'] self.byte_order_symbol = ">" if self.byte_order == 'big' else ">" d...
This code initializes an object with a file-like object (flo) and additional keyword arguments. It updates instance attributes, retrieves configuration data, and parses headers (binary, auxiliary) and data types from the file to prepare for processing its contents.
def __init__(self, flo, **kwargs): self.__dict__.update(kwargs) self.flo = flo # File Like Object self.get_config() self.__get_header() self.__get_binary_header() self.__get_aux_headers() self.__set_data_type()
def average_desc(train_df, points3D_df): train_df = train_df[["POINT_ID","XYZ","RGB","DESCRIPTORS"]] desc = train_df.groupby("POINT_ID")["DESCRIPTORS"].apply(np.vstack) desc = desc.apply(average) desc = desc.reset_index() desc = desc.join(points3D_df.set_index("POINT_ID"), on="POINT_ID") return ...
The main task of the code is to estimate camera poses using RANSAC P3P from image descriptors, compare predicted poses with ground truth data, compute rotation/translation errors, and visualize results via point cloud display. It processes 3D model descriptors, loads images, performs pose estimation for each frame, sav...
def main(cameraMatrix, distCoeffs): # Process model descriptors desc_df = average_desc(train_df, points3D_df) kp_model = np.array(desc_df["XYZ"].to_list()) desc_model = np.array(desc_df["DESCRIPTORS"].to_list()).astype(np.float32) if os.path.isfile("undistortCameraPose.pkl"): print('Already...
def write_vma_rmise(file_handle, model_type='ho'): try: result_file_name = 'ma_result_100' result_100 = load_result(result_file_name) except: result_100 = None try: result_file_name = 'ma_result_200' result_200 = load_result(result_file_name) except: res...
The code generates a LaTeX table named 'rmise_<model_type>_table.tex' in the specified directory. It writes RMISE results for a given model type by calling helper functions to populate the table's content and format its header/footer. The task involves creating structured output files for comparative analysis of model ...
def write_rmise_table(model_type='ho'): file_name = 'rmise_'+model_type+'_table.tex' with open(os.path.join(RES_DIR, 'table', file_name), 'w') as table_handle: write_vma_rmise(table_handle, model_type) write_var_rmise(table_handle, model_type) write_rmise_header_tail(os.path.join(RES_DIR, 't...
def write_vma_three_metrics(file_handle, model_type='ho'): try: result_file_name = 'ma_result_100' result_100 = load_result(result_file_name) except: result_100 = None try: result_file_name = 'ma_result_200' result_200 = load_result(result_file_name) except: ...
This function generates a LaTeX table containing three metrics for a specified model type (default 'ho'). It creates a file named 'three_metric_<model_type>_table.tex' in the 'table' directory, writes metric data using two helper functions, and appends a header/footer. The table is structured for academic reporting, li...
def write_three_metric_table(model_type = 'ho'): file_name = 'three_metric_' + model_type + '_table.tex' with open(os.path.join(RES_DIR, 'table', file_name), 'w') as table_handle: write_vma_three_metrics(table_handle, model_type) write_var_three_metrics(table_handle, model_type) write_three_...
def handle_data(data): isQuality = int(data['project_data']['isQuality']) numOfIterations = 2000 if isQuality else 1000 isQuantity = int(data['project_data']['isQuantity']) container = data['container'] boxes = data['boxes'] initBoxes = [Box(box) for box in boxes] initBoxes.sort(key=lambda ...
The code processes input data to generate and sort container packing solutions. It parses JSON input, extracts parameters, computes solutions via iterations, sorts them by preference, and returns a dictionary of optimized packing configurations.
def algo(): data = json.loads(sys.argv[1]) boxes, container, numOfIterations, isQuantity = handle_data(data) solutionList = get_solutions(numOfIterations, boxes, container, isQuantity) solutionList = sort_by_preference(solutionList, isQuantity) solutionDict = dict_solutions_from_list(solutionLis...
def normalize(data): return unicodedata.normalize('NFKD', data).encode('ascii', 'ignore').decode('utf-8') def extract_date(line): date = None m = re.match(date_re, line) if has_groups(m): date = datetime.datetime.strptime(m.group('date'), '%m/%d/%Y %I:%M %p') return date def lineitem_start...
The main task of the code is to parse an invoice document by extracting key information such as the order date and item details from each page. It initializes a structured dictionary with headers, page count, and an empty items list. For each page, it processes lines of text to identify dates (formatting them) and item...
def parse_document_detail(invoice): document = { 'header': ['DATE', 'STYLE', 'COLOR', 'SIZE', 'QUANTITY', 'COST'], 'order_date': 'None', 'items': [], } document['page_count'] = len(invoice.pages) for pid in range(len(invoice.pages)): page = invoice.pages[pid] l...
def gather_document_stuff(): docpath = '' csvpath = '' while len(docpath) == 0: docpath = input('Your PDF document to read: ') docpath = Path(docpath) while len(csvpath) == 0: csvpath = input('The CSV import file to write for Excel: ') csvpath = Path(csvpath) return docp...
This code processes PDF invoices by extracting text and converting them into CSV or JSON format. It uses command-line arguments to specify input documents, output format, destination file, and interactive mode. The program handles file operations, ensures data formatting, and cleans up resources after processing.
def main(): desc = """ This program may be used to read a very particular type of PDF invoice, extract the necessary text, and create a CSV-formatted document that may be imported into various spreadsheets. If a destination file is not provided, then the text document is written to stdout. """ ...
def assign_triangles_to_pixels(vertices2d, depths, image_size, faces, face_inds=None): depth_buf = tf.ones(image_size) * float('inf') inds = tf.zeros(image_size, dtype=tf.int32) valid = tf.zeros(image_size, dtype=tf.bool) if face_inds is None: face_inds = [tf.range(tf.shape(faces)[0])] for...
This code renders a 3D trimesh with textures and lighting into a 2D image by projecting vertices, computing visible faces via ray-triangle intersection, interpolating vertex properties (normals, albedo, shininess), sampling textures/normal maps, and applying Lambertian and Phong BRDF models. It combines diffuse/specula...
def render(self, trimesh, light, ambient_light=0.2): all_verts = trimesh.vertices all_faces = trimesh.faces texture = trimesh.texture_map normal_map = trimesh.normal_map if texture is not None or normal_map is not None: all_tex_faces = trimesh.texture_faces ...
def get_sites_from_site_tag(site_tag): """ get the sites based on the site tag :param site_tag:[str] 'md' or 'lg' for medium (Schuylkill) or large (DRB) :return:[list] list of sites """ if site_tag == 'md': site_codes = get_subset_in_zarr() elif site_tag == 'lg': site_codes =...
The code benchmarks the performance of writing data to Zarr, Parquet, and CSV formats by running each method `n_trials` times on a subset of data defined by the `tag` parameter, then saves the average timings to a file named `write_{tag}.out` for comparison analysis.
def time_write(n_trials, tag): # get subset from full zarr print(tag) sites_tag, start_date, end_date = tag.split('_') out_file = f"results/write_{tag}.out" sites = get_sites_from_site_tag(sites_tag) df = get_df_from_zarr(sites, start_date, end_date) write_zarr_time = time_function(write_za...
def get_title(driver): return driver.find_element_by_xpath('//yt-formatted-string[@class="style-scope ytd-video-primary-info-renderer"]').text def get_channel_info(driver): container = driver.find_element_by_xpath('//ytd-channel-name[@id="channel-name"]') channel = container.find_element_by_xpath('.//a[@cla...
The main task of the code is to scrape YouTube video metadata using Selenium. It extracts details like title, channel info, views, likes, description, and upload date from a specified video URL, compiles them into a structured dictionary, and appends it to a list for storage or output. The script uses Firefox driver, w...
def main(): url_matcher = "^https?:\/\/[^#?\/]+" video_id_matcher = "watch\?v=[-\w]+" driver = webdriver.Firefox() actions = ActionChains(driver) url = 'https://www.youtube.com/watch?v=DM-nn2jijtM' data = [] driver.get(url) time.sleep(4) title = get_title(driver) channelI...
def generateDataloader(batch, in_lang, out_lang, path, max_s_len=20, device='cuda'): pairs, lang1, lang2 = populateLangs(in_lang, out_lang, path, max_s_len) n = len(pairs) input_t = np.zeros((n, max_s_len), dtype=np.int32) output_t = np.zeros((n, max_s_len), dtype=np.int32) for idx, (s1, s2) in en...
This code trains a sequence-to-sequence model for translation between two languages using encoder-decoder architecture. It initializes models, optimizers, and loss function, then trains them over multiple epochs with a custom training loop. After training, it evaluates model performance with random examples and visuali...
def train(in_lang, out_lang, path, max_s_len=20, batch=32, n_epochs=50, learning_rate=1e-3, hidden_size=128, dropout_p=0.1, device='cuda'): dataloader, pairs, lang1, lang2 = generateDataloader(batch, in_lang, out_lang, path, max_s_len, device) start = time.time() encoder = Encoder(lang1.n_words, hidden_si...
def preprocessRead(pileupread, readHash, whichfile): #Add the read readHash[pileupread.alignment.query_name + str(pileupread.alignment.is_read1)] = pileupread def getPreprocessedRead(reads, readname, whichfile): if readname in reads: pileupread = reads[readname] printRea...
This function processes a single nucleotide variant (SNV) by analyzing aligned reads from two BAM files. It validates reads against the SNV position, filters out duplicates, and aggregates statistics on read counts, allele frequencies, and quality metrics. If sufficient reads pass validation, it outputs the SNV's resul...
def processSNV(prevSNV, curSNV, nextSNV): global lastChrom global totalChroms #Collect summary statistics global totalChroms global totalSNVsSkipped global totalSNVsCounted global grandTotalReadsSkipped global grandTotalReadsSkippedRef global grandT...
def _format_input( self, data, pre_period, post_period, model_args, ucm_model, post_period_response, alpha, ): """Check and format all input arguments supplied to CausalImpact(). See the documentation of CausalImpact() for details ...
The code's main task is to dispatch execution to either `_run_with_data` or `_run_with_ucm` based on the presence of `self.data`, formatting input parameters into `kwargs` and passing them to the appropriate method. It prepares model arguments, periods, and estimation settings for analysis, handling data-driven or UCM-...
def run(self): kwargs = self._format_input( self.params["data"], self.params["pre_period"], self.params["post_period"], self.params["model_args"], self.params["ucm_model"], self.params["post_period_response"], self.params["alpha...
def show_products() -> None: Product('', '', '', 0, 0, 0, '').show_products() def buy_products() -> None: show_products() ide = int(input('Choose the id of the product to buy or 0 to cancel: ')) if ide != 0: product = Product('', '', '', 0, 0, 0, '') quantity_purchased = int(input('Type ...
This code provides a menu-driven interface for managing products and sales records, allowing users to view products, add new products, update existing ones, process purchases, display sales records, filter products, and handle payments. It interacts with a database through classes like Product and Sale, offering functi...
def main(): # This is the main menu while True: print(''' 1. Show products 2. Add product 3. Buy products 4. Show records 5. Show all records 6. Update a product 7. Show/Display barcodes 8. Show products by filter 9. Show products i...
def check_filename_extension(self): if self.filename is None: self.filename = 'default.sdb' else: if self.filename.split('.')[-1] != 'sdb': self.filename += '.sdb' def launch(self): print(f'S2K LAUNCHER: Using API in {self.client} mode.') if self.p...
The main task of the code is to initialize a system by performing three key steps: verifying the filename's extension for validity, launching the application or process, and setting up a model (likely a machine learning model or system component). This method orchestrates pre-launch checks, application startup, and mod...
def setup(self): self.check_filename_extension() self.launch() self.setup_model()
def greedy_stoch(mat, k=1): size = mat.shape[0] order = np.argsort(mat.ravel()) chromosome = np.ma.masked_all(size, dtype=np.int64) # print(chromosome) fit = 0 for i in range(size): cycle = True offset = size - i offset = offset if offset < k else k while cycle: ...
The code initializes a population for an optimization problem by generating individuals using greedy, nearest neighbor, and random methods. It appends these individuals to the problem's population list, each with their chromosome, fitness value, and adjacency matrix. The process ensures a diverse starting population fo...
def initialize(problem): print("initializing...") print("---------------") print("greedy...") start = time.time() for i in range(problem.lambdaa // 20): print(i) chromosome, _ = greedy_stoch(problem.dMatrixAlt, 3) # fitness = self.fitness(chromosome) individual = (con...
def calc_shared_fitness_parameters(radius, shape, nb_cities): ds = np.arange(0, radius) ds = ds/radius ds = ds**shape ds = np.concatenate((ds, np.ones(nb_cities - radius + 1))) ds = 1 - ds return ds def initialize(problem): print("initializing...") print("--------...
The code implements an evolutionary algorithm to solve the Traveling Salesman Problem (TSP). It reads a distance matrix, initializes a population, and iteratively evolves solutions through selection, recombination, mutation, and elimination. The algorithm tracks mean and best fitness values across generations, reports ...
def optimize(self, filename, plot_name='plot'): """The evolutionary algorithm's main loop""" # Create empty lists to be filled with values to report progress mean_fit_values = [] best_fit_values = [] # Read distance matrix from file. file = open(filename) distanc...
def makeserversocket( self, port, backlog=5 ): #-------------------------------------------------------------------------- """ Constructs and prepares a server socket listening on the given port. """ s = socket.socket( socket.AF_INET, socket.SOCK_STREAM ) s.setsockopt( sock...
The main task is to run a server that listens for client connections, manages peer communication via RabbitMQ, and processes data between master and compute nodes. The master node sends initialization data to compute nodes, while compute nodes receive, process, and store messages from RabbitMQ. The loop handles threadi...
def mainloop( self ): #-------------------------------------------------------------------------- s = self.makeserversocket( self.serverport ) s.settimeout(None) self.__debug( 'Server started: %s (%s:%d)' % ( self.myid, self.serverhost, self.serverport ) ) pulseIndex ...
def next_player(player): if player == max_player_pawn: return min_player_pawn else: return max_player_pawn def get_possible_moves(pawn, board_state): possible_moves = [] for i, row in enumerate(board_state): for j, sq in enumerate(row): if sq == pawn: ...
The code recursively constructs a game tree up to a specified depth. Starting from a given node, it generates all possible moves for the current player, creates child nodes for each valid move, and recursively builds subtrees for each child, decrementing the depth until it reaches zero.
def build_tree(node, depth): if depth == 0: return player_to_move = next_player(node.player_to_move) moves = get_possible_moves(node.player_to_move, node.game_state) for move in moves: new_board_state = move_pawn(node.game_state, move[0], move[1], node.player_to_move) child_node...
def game_over(board_state): max_flag, min_flag = True, True for pos in max_winning_setup: if board_state[pos[0]][pos[1]] != 1: max_flag = False break for pos in min_winning_setup: if board_state[pos[0]][pos[1]] != 2: min_flag = False break ...
The code simulates a game using the minimax algorithm with alpha-beta pruning, evaluating moves up to a specified depth. It alternates between max and min players, builds a game tree, tracks nodes visited, and updates the board state iteratively. The function returns round count, nodes visited, and total time after 300...
def play(initial_board_state, depth, max_strat, min_strat, pruning): current_board_state = initial_board_state current_pawn = max_player_pawn round_count = 0 nodes_visited = 0 start_time = time.time() while round_count < 300: if game_over(current_board_state): return round_c...
def get_flag_loc(logic_table: list, flag: int) -> list: """Find and return the flag location""" block_index_x = 0 block_index_y = 0 for row in logic_table: for cell_logic in row: if cell_logic == flag: position = [block_index_x, block_index_y] return...
The code implements a pathfinding algorithm to determine a route from a source to a destination in a grid represented by `logic_table`. It uses a queue to explore possible moves via BFS, checks for valid paths, and prints or visualizes the successful route if found. If no path exists, it outputs an unreachable message.
def path_find(logic_table: list): """Path find main""" src_loc = get_flag_loc(logic_table, SRC_FLAG) dst_loc = get_flag_loc(logic_table, DST_FLAG) queue = get_first_moves(src_loc, logic_table) successful_route = find_successful_route(logic_table, queue, src_loc, dst_loc) if successful_route ...
def Contains(self, target, nodes): for node in nodes: r = node[0] if target[0] >= r.x and target[0] <= r.x + r.width and target[1] >= r.y and target[1] <= r.y + r.height: return node return None def FindMinDistance(self, nodes, goal): if nodes is not None...
The code implements the A* algorithm to find the shortest path from a start node to a goal node. It initializes open and closed sets, calculates G (cost from start) and H (heuristic to goal) scores, and iteratively selects the node with the minimum F score (G+H). When the goal is reached, it reconstructs the path by ba...
def AStar(self, start, goal): openSet = [] closeSet = [] # G score and H score if self.Contains(goal, self.map_nodes) is None: goal = self.Contains(goal, self.mixed_nodes) else: goal = self.Contains(goal, self.map_nodes) if self.Contains(start, se...
def CalcEntropy(self, rect): area = rect.width * rect.height a = 0.0 for o in self.domain.obstacles: a = a + rect.CalculateOverlap(o) p = a / area return self.Entropy(p) def CalMinGain(self, partitions, entropy, rx, ry, rwidth, rheight, type): maxIg = 0 ...
This code decomposes a spatial node into child nodes based on obstacle presence. It checks if a node is 'free', 'obstacle', or 'mixed' by analyzing overlaps with obstacles. For 'mixed' nodes, it calculates entropy and information gain to determine optimal horizontal or vertical splits, creating child nodes recursively....
def Decompose(self, node): cell = 'free' r = node[0] rx = r.x ry = r.y rwidth = r.width rheight = r.height area = rwidth * rheight partitions_h = [] partitions_v = [] for o in self.domain.obstacles: if (o.CalculateOverlap(r) >= ...
def Contains(self, target, nodes): for node in nodes: r = node[0] if target[0] >= r.x and target[0] <= r.x + r.width and target[1] >= r.y and target[1] <= r.y + r.height: return node return None def FindMinDistance(self, nodes, goal): if nodes is not None...
This code implements the A* algorithm to find the shortest path from a start node to a goal node in a graph. It uses openSet and closeSet to track nodes for exploration and those already evaluated, updating G (path cost) and H (heuristic) scores. If the goal is reached, it reconstructs the path by backtracking through ...
def AStar(self, start, goal): openSet = [] closeSet = [] # G score and H score if self.Contains(goal, self.map_nodes) is None: goal = self.Contains(goal, self.mixed_nodes) else: goal = self.Contains(goal, self.map_nodes) if self.Contains(start, sel...
def main_game(self): self.bg.scroll_background() self.player_sprite.draw(self.SCREEN) self.enemy_group.draw(self.SCREEN) self.enemy_group.update() self.player_sprite.update() if (len(self.enemy_group) < 2): if random.randint(0, 1) == 0: new_pos...
The code defines a state_manager method that directs the program's flow by invoking different game-related functions based on the current state, such as "main_game," "menu," "pause," or "game_end," ensuring appropriate game behavior transitions.
def state_manager(self): if self.state == "main_game": self.main_game() elif self.state == "menu": self.menu() elif self.state == "pause": self.pause() elif self.state == "game_end": self.end_game()
def symbol_format(self,symbol): return re.sub("[^0-9a-zA-Z]+", "/", symbol) def place_order(self, market: str, side: str, price: float, size: float, type: str = 'limit', reduce_only: bool = Fa...
This function creates a market order for a specified symbol and quantity, retrieves the average fill price post-execution, and returns the order details. If an error occurs during order placement, it returns an exception message in a dictionary.
def create_market_order(self,symbol,side,quantity): symbol = self.symbol_format(symbol) try: order = self.place_order(symbol,side,0,quantity,"market") order['price']=self.get_order_status(order["id"])["avgFillPrice"] return order except: return {'m...
def pre_process(img): # preprocess_img (2) img = square(img) if img.shape[0] <= 1080: # img = resize_im(img) cv2.resize(img, (1080 , 1080)) else: img = cv2.resize(img, (1080 , 1080)) im = img #canny img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY) img = cv2.resize(img, (1080 , 1080)) img =...
The `main_classify` function processes an image through localization, feature extraction, and classification with voting. It first preprocesses the image, localizes regions of interest, and crops them. Features are extracted from the cropped regions, which are then classified by `predict_ndc` to generate three predicti...
def main_classify(img): # run all process # localize img, im = pre_process(img) result = localize(img) local_im = crop_localize(result, im) # classify feavec = create_fea(local_im) ans1, ans2, ans4 = predict_ndc(feavec) # voting ans = [] for z in range(0, len(ans1)): test_list = [ans1[z]...
def writeInfoGlass(db, project_cost, ws_read_manufacturing): #necesitamos algunos parametros, en este caso, los tomamos de la base de datos with db_session: thickness = str(ws_read_manufacturing.cell(row = 7, column = 2).value) cristal = db.Crystals_Parameters.get(thickness = thickness) ...
The code calculates project costs by retrieving operational parameters (royalty, insurance, euro value) from a database, defaulting to zero or 700 if missing. It writes glass, profile, component, and sealing costs to a spreadsheet using these parameters, then sums component and sealing costs to update the project's sta...
def computation(db, wb_read, project_cost): ws_read_manufacturing = wb_read["Manufacturing"] #necesitamos algunos parametros basicos para costear with db_session: from Projects.costs import getParameter warning = ' Aviso: el royalty asociado a la importacion de productos no se ...
def calc_schedule_probability(self) -> float: return math.prod(self.schedule_probability) def calc_discounted_reward(self) -> float: return (Node.gamma ** self.depth) * self.calc_reward() * self.likelihood def calc_quality(self): return calc_quality(self.state) def calc_expected_utility(self) ->...
This code initializes a Node in a state search tree, tracking state transitions, action history, probabilities, and expected utility. It copies the state, updates depth and action lineage, checks action viability, calculates likelihoods, and determines if the node should be pruned as a leaf based on probability thresho...
def __init__(self, parent: Node = None, state: WorldState = None, action: str = "", **kwargs): # flag used to indicate an abrupt override/pruning of a branch and force the current node to become a leaf node. self.force_leaf = False # id, which will aim to represent the ID/occurance/step' in the...
def get_centroid(self, data, lower_hsv, upper_hsv, centroid_key): mask, img_masked = self.threshold_hsv(data, lower_hsv, upper_hsv) if centroid_key is 1: density = cv2.countNonZero(mask) #print('the densit is ' + str(density)) if density < 5000 : return [1,1] # Crop the image ...
This code processes an image to detect road and crosswalk centroids, uses PID control for steering, and manages robot navigation states. It stops the robot if a crosswalk is detected, waits for a pedestrian to pass, then resumes driving. Time checks ensure safe transitions between states, with image analysis guiding mo...
def img_processor(self, data): img = self.bridge.imgmsg_to_cv2(data, "passthrough") #find the centroid of the road and also check whether there is a crosswalk indicator for us to stop before. self.centroid_road = self.get_centroid(img, self.lower_hsv_road, self.upper_hsv_road, self.road_key) if(time.ti...
def get_content_path(self): return self.content_path def handle_assets(self): print(f"{datetime.now()} -- ", "Handling assets folder.") # handle static folder shutil.rmtree(self.static_path / 'assets') shutil.copytree(self.assets_path, self.static_path / 'assets', dirs_exist_ok=...
The main task of the code is to process source files using kramdown, separating outputs into templates (`.kd` files) or the static directory. It handles assets, processes documentation snippets, and structures content for rendering, ensuring organized file distribution based on type.
def handle_content(self) : """ Takes the source files processes them through kramdown and .:. put the processed files into the templates (kd files) or static directory (all the rest). """ print(f"Processing content folder {self.get_content_path()}") self.handle...
def rollout(self, env : ProcgenGym3Env, avg_goal): nenvs = self.num_actors mb_obs, mb_raw_rews, mb_acts, mb_vals, mb_dones, mb_logprobs = [], [], [], [], [], [] _, obs, _ = env.observe() dones = [False for _ in range(nenvs)] obs = self.process_obs(obs) score = None ...
The code trains a reinforcement learning agent in a ProGen environment using HER (Hindsight Experience Replay). It rolls out episodes, updates goal buffers with computed scores, trains neural networks via batched data, logs metrics with WandB, and saves the model if reward improves. The main task is optimizing policy v...
def train2(self, env : ProcgenGym3Env): max_rew = -1000 goal_buffer = torch.ones([5, self.num_timesteps, self.num_actors], device=self.device) * 30.0 for i in range(self.num_iters): print("Rolling out...") mean_goal = torch.mean(goal_buffer, dim=0) + 1 obs, re...
def parse_pcd_headers(data: str) -> PCDHeaders: # Search for a pattern in the 'data' string using a regular expression result1 = re.search(r'[\r\n]DATA\s(\S*)\s', data, re.I) # Extract information from the substring of 'data' starting from result1.end() - 1 result2 = result1.groups()[-1] if result...
The main task of the code is to parse a PCD point cloud file, extract 3D point coordinates and attributes (e.g., color, intensity), compute spatial bounds, and fragment points into 3D grid cells based on configurable sizes. It handles different data fields, creates PointAttributes objects, and organizes fragments in a ...
def parse_point_cloud(file_name): headers = PCDHeaders() string_data = "" offset: Dict[str, int] = {} min_x, min_z, min_y = math.inf, math.inf, math.inf max_x, max_z, max_y = -math.inf, -math.inf, -math.inf row_size, column_size, stack_size = 0.2, 0.2, 0.2 if file_name == '15M_pcd.pcd': ...
def parse_pcd_headers(data: str) -> PCDHeaders: # Search for a pattern in the 'data' string using a regular expression result1 = re.search(r'[\r\n]DATA\s(\S*)\s', data, re.I) # Extract information from the substring of 'data' starting from result1.end() - 1 result2 = result1.groups()[-1] if result...
The main task of the code is to parse a PCD point cloud file, fragment points into spatial segments based on configurable grid sizes, assign hierarchical levels to points, and convert the fragmented data into structured JSON format with metadata. It processes input PCD files, distributes points into fragments, normaliz...
def parse_point_cloud(file_name): global min_x, max_x, min_y, max_y, min_z, max_z headers = PCDHeaders() string_data = "" row_size, column_size, stack_size = 0.2, 0.2, 0.2 if file_name == '15M_pcd.pcd': row_size, column_size, stack_size = 10, 10, 5 levels = [1, 2, 5] spatial_data: ...
def createInitialPopulation(populationSize,cityList): population = [] for _ in range(populationSize): population.append(createRoute(cityList)) return population def createNN(first,cityList): route = [] route.append(first) route.append(findNearest(first,cityList)) cityList.remove(rout...
This function implements a genetic algorithm to solve a routing problem, evolving routes over generations. It initializes a population, applies selection, crossover, and mutation, and optimizes routes using swap operations. Progress is tracked by recording the best route's distance. The algorithm visualizes the optimal...
def geneticAlgorithmPlot(population, popSize, eliteSize, mutationRate, generations): pop = createInitialPopulation(popSize, population) progress = [] first = population[0] population.remove(first) route = createNN(first,population) print("nn finished") route = swapOpt(route) #del pop[:(p...
def swap(route, j, k): for i in range(0,(k-j + 1)//2): tmp = route[j+i] route[j+i] = route[k-i] route[k-i] = tmp return route def createRoute(first,cityList): route = [] route.append(first) route.append(findNearest(first,cityList)) cityList.remove(route[1]) k = 1 ...
The code generates random cities, creates a route, and iteratively swaps city positions to minimize the total travel distance using a visualization. It employs a local search algorithm to optimize the path for the Traveling Salesman Problem (TSP), plotting each iteration's route and distance until no further improvemen...
def main(): cityList = [] x = [] y = [] random.seed(123) for i in range(0,100): cityList.append(City(x=int(random.random() * 200), y=int(random.random() * 200))) x.append(cityList[i].x) y.append(cityList[i].y) first = cityList[0] print(swap([1,2,3,4],1,2)) plt.sca...
def alignment(self): limit = self.limitFlock /2 desiredSep = Vec2(0, 0) neighborCount = 0 for agent in self.game.get_gameobjects(): if (agent != self): if (self.distanceFrom(agent) < limit): desiredSep = desiredSep + agent.get_posi...
The code calculates the combined force for flocking behavior by summing alignment, cohesion, separation, and target forces, returning the aggregated vector to influence agent movement.
def flocking(self): aligment = self.alignment() cohesion = self.cohesion() separation = self.separation() target = self.goal() all_forces = aligment + cohesion + separation + target # print("*************************") # print("aligment: ", aligment) # p...
def seek(self, target): """Seek Behavior.""" displacement = target - self.pos force = displacement.direction * self.max_velocity seekforce = force - self.velocity return seekforce def flee(self, target): """Flee Behavior.""" displacement = target - self.pos ...
This code updates an agent's movement based on its current behavior state (seeking, fleeing, wandering, or flocking), applies corresponding force calculations, enforces screen boundary constraints by resetting position if out-of-bounds, and updates velocity/position with delta time, ensuring maximum speed limits.
def update(self, deltatime): """Update agent logic.""" # print(self.indseek, self.indflee, self.indwander, self.inFlock) if self.indseek is True: self.force = self.seek(self.targetpos) elif self.indflee is True: self.force = self.flee(self.targetpos) elif ...
def doConnect(self): self.secure_channel_timeout = 100000 self.session_timeout = 100000 if not self.isConnected: self.connect() if self.isInitialized: return True self.remotesub = self.create_subscription(1000, self.remoteHandler) try: ...
The code's main task is to continuously attempt to connect to a server while `scanEnabled` is active. It handles connection failures by retrying with delays, logging errors if reconnection fails, and maintaining a loop to ensure persistent connectivity checks.
def ping(self): while self.scanEnabled: try: self.doConnect() except: self.unConnect() while not self.isConnected: try: self.doConnect() except: self.un...
def dump_predictions(self, probability=False, vetting=False ): # write current patient data to SQL table if not isinstance(self.thread_lock, bool): # we assume that if thread_lock is set it is a multiprocessing.lock Or threading.Lock obj with self.thread_lock: se...
This function processes a file for predictions, managing memory and cache constraints. It checks available memory and cache size to decide whether to process the file immediately or cache it. If memory is insufficient or cache is full, it dumps predictions; otherwise, it increments a counter and returns an empty JSON a...
def transform_predict(self, file, probability=False, vetting=False, hca=False): # ensure file can be read into memory if not dump & reset counter if psutil.virtual_memory().available - (os.path.getsize(file) * 2 ) < (1024*10): return self.dump_predictions(probability, vetting) # ...
def delete_outlier_age(): df = extract_data() outlier_age_free_df = df[df['Age'] <= 110] return outlier_age_free_df def format_join_date(): df = delete_outlier_age() df['Join Date'] = pd.to_datetime(df['Join Date']) formated_date = df['Join Date'].dt.strftime('%Y-%m-%d').tolist() return form...
This function loads cleaned user data into a database dimension table. It processes a DataFrame by removing age outliers, formatting dates and genders, then iteratively inserts user records into the UserDimension table with specific fields like UserID, JoinDate, Age, and Gender_ID, before committing and closing the dat...
def load_users_to_dim(): df = delete_outlier_age() df["Join Date"] = format_join_date() df["Gender_ID"] = format_genders() df.columns = df.columns.str.strip() cur = conn.cursor() for index, row in df.iterrows(): cur.execute("""INSERT INTO UserDimension (UserID, JoinDate, Age, ActivePr...
def KE_Dump(data): return bytearray(json.dumps({"payload":data}), 'utf-8') def KE_Load(msg): msg = msg.decode() return json.loads(msg)["payload"] def KE_BuildKey(data): h = '' for n in data: for i in n: h += str(i) s = sha256(h.encode('utf-8')) return int(s.hexdigest(), 16) def keyConfirm(self, key): #Bit...
The main task of the code is to handle a key exchange protocol by sending a KE request, receiving server responses, processing training data, updating weights, and confirming keys. It loops until key confirmation or error, sending results back to the server while adhering to KE instructions.
def mainloop(self): #Send request for KE self.clientsocket.send(KE_Dump(KE_CONFIRMATION_CODE)) print("Initiating Key Exchange") #Receive response with confirmation and first set of input vectors data = KE_Load(self.clientsocket.recv(KE_BUFF)) ke = 1 if data == KE_CONFIRMATION_CODE else 0 while ke: # Re...
def confirm(self): data = KE_Load(self.clientsock.recv(KE_BUFF)) if data == KE_CONFIRMATION_CODE: self.clientsock.send(KE_Dump(KE_CONFIRMATION_CODE)) print("KE Confirmed") return 1 else: print("Confirmation Code was not recieved.") return 0 def KE_RandSet(l=KE_SIZE): r = [] for i in range(KE_LAYE...
The code implements a key exchange protocol using iterative synchronization between a server and client. It trains a model (weights) by sending data to the client, receiving responses, and adjusting weights when matches occur (t=1). Upon meeting convergence criteria, it builds and confirms a key. The loop tracks steps ...
def run(self): start = time.time() ke = self.confirm() converged = self.syncAt #Min to sync c = 0 #Number of times matched steps = 0 while ke: steps += 1 c = c + 1 x = KE_RandSet(1) s = KE_Train(self.weights, x) p = x[:] p.append(s) self.clientsock.send(KE_Dump(p)) t = KE_Load(self...
def orthonorm_tox(v): temp = v3.vector(v.x, v.y, v.z) return temp.normalized(temp) def orthonorm_toy(v): temp = v3.vector(v.x, v.y, v.z) a = orthog_toy(temp) return a.normalized(a) def orthonorm_toz(v): temp = v3.vector(v.x, v.y, v.z) a = orthog_toz(temp) return a.normalized(a)
This code transforms a 3D vector `w` into 2D coordinates by projecting it onto an orthonormal basis derived from a reference vector `ref`. It calculates orthogonal vectors (x, y, z) from `ref`, then returns a 2D vector composed of the dot products of `w` with the y and negative z components of this basis, effectively m...
def sphere_to_2D_plane(ref,w): xmult = orthonorm_tox(ref) xmult = v3.vector(xmult.x, xmult.y, xmult.z) ymult = orthonorm_toy(ref) ymult = v3.vector(ymult.x, ymult.y, ymult.z) zmult = orthonorm_toz(ref) zmmult = v3.vector(zmult.x, zmult.y, zmult.z) return v.vector(ymult.dot(w), -zmult.dot(w))
def check_valid_activation(choice): if choice not in ['relu', 'lrelu', 'prelu']: raise ValueError(f"'{choice}' is not a valid activation function. Choose among ['relu', 'lrelu', 'prelu'].\n") def conv_block(in_channels, out_channels, activation='relu', do_BN=True, *args, **kwargs): """ Partial encod...
This code defines a UNet neural network for image segmentation, initializing configurable parameters like input channels, filter depths, activation functions, and upsampling modes. It constructs encoder and decoder blocks with convolutional layers, a bottleneck, and optional skip connections. The architecture supports ...
def __init__(self, n_input_channels=2, start_kernel=64, max_filter_depth=512, depth=5, act_fn_encoder='relu', act_fn_decoder='relu', act_fn_bottleneck='relu', up_mode='transpose', do_BN=False, bias_conv_layer=True, outer_skip=True, outer_skip_BN=False): """ UNet network...
def custom_cmap(lift: float = 0.1, gamma: float = 1, gain: float = 1) -> ListedColormap: cmap1 = plt.cm.plasma cmap2 = plt.cm.inferno n = 256 colors1 = cmap1(np.linspace(0.0, 1, n)) colors2 = cmap2(np.linspace(0, 1, n)) colors = np.zeros((n, 4)) colors[:, :3] = 0.4 * colors1[:, :3] + 0.6 * c...
This function generates both light and dark versions of a matplotlib figure by modifying color schemes, spines, ticks, labels, and elements like text and plots. It saves the dark version as SVG and the light version as SVG/PDF, handling special cases like 3D plots and user-defined color overrides.
def save_light_dark_all( fig: plt.Figure | None = None, name: str = "figure", loc: str = "./", override_alpha: bool = False, override_cmap: bool = False, custom_map: bool | ListedColormap = None, ): """for making light and dark versions of a figure all at once. The idea is to drop in this fu...
def read_input(inFileName): with open(inFileName, 'r') as infile: csv_reader = csv.reader(infile.read().splitlines()) return next(csv_reader) def write_suggestions(suggestions, outFileName): print(suggestions) with open(outFileName, 'w') as outfile: for suggestion in suggestions: ...
The function `make_suggestion` reads input data from a specified file, generates suggestions using the `get_suggestions` function, and writes the resulting suggestions to an output file. Its primary task is to process input data, transform it into suggestions, and save the outcomes in a designated file, facilitating au...
def make_suggestion(inFileName, outFileName): input = read_input(inFileName) write_suggestions(get_suggestions(input), outFileName)
def Usage(argv): print(argv[0], ' opts <number-of-iterations>') print(' --help Show this help') print(' --equal Assume equal loads, not indicated loads') print(' --master All work on the master') print(' --slaves No work on the master') print(' --slave1 ...
The code processes command-line arguments to configure allocation policies (e.g., 'optimized', 'equal'), reads current system resource allocations, constructs a topology, adjusts load weights based on policy, and computes optimized/integer allocations. It iterates, printing allocation states, to manage resource distrib...
def main(argv): equal = False policy = 'optimized' cmdloads = None min_alloc = 1 # Every instance has at least one core try: opts, args = getopt.getopt( argv[1:], "h", ["help", "equal", "master", "slaves", "slave1", "loads=", "min="]) except getopt.error as msg: print(msg) ...
def get_meetings(date, key, secret): host_ids = get_active_hosts(date, key, secret) series_info = get_series_info(host_ids, key, secret) params = { "from": date, "to": date, "type": 2, # completed meetings "api_key": key, "api_secret": secret, "page_size": ...
The main task of the code is to retrieve completed meeting session data from an API by iterating over meetings from a specific date, extracting session details using API parameters, and yielding each meeting document along with its corresponding session documents. It uses pagination, authentication, and delays to manag...
def get_sessions_from(date, key, secret): url = "/metrics/meetingdetail" params = { "api_key": key, "api_secret": secret, "type": 2, # completed meetings "page_size": 100, # max page size "page_number": 1, } for meeting_doc in get_meetings(date, key, secret):...
def ReadNameValuePairs(data, logs): pos = 0 size = len(data) items = {} if size < 4: return while pos < (size - 4): nv = NameValue.parse(data[pos:]) items[nv.name] = (nv.value if nv.value_len != 0xFFFFFFFF else '') pos += nv.name_len + nv.value_len + 8 if items: l...
The code parses Android 'com.android.providers.settings.data' files, extracting WiFi settings with passwords and other system/secure/global settings. It reads input files, processes structured data, and exports results in CSV/JSON formats, handling XML for WiFi configurations while validating input/output paths and man...
def main(): usage = "Parser for 'com.android.providers.settings.data' "\ "which includes wifi settings with passwords"\ "\n--------------------------------------------"\ "\nUsage: providers_settings_parser.py input_file output_folder"\ "\nExample: providers_settings_p...
def InitializeWeights(nodes): """Initialize weights with random values in [-1, 1] (including bias)""" layers, weights = len(nodes), [] for i in range(1, layers): w = [[np.random.uniform(-1, 1) for k in range(nodes[i-1] + 1)] for j in range(nodes[i])] weights.append(np.matrix(w)...
This function trains a neural network with specified hidden layers, updating weights via backpropagation over given epochs. It tracks training and testing accuracy, calculates cost at intervals, plots cost vs. epoch, and returns final weights.
def NeuralNetwork(X_train, Y_train, epochs=10, nodes=[], lr=0.15): hidden_layers = len(nodes) - 1 weights = InitializeWeights(nodes) cost_list = list() epoch_list = list() for epoch in range(1, epochs+1): weights = Train(X_train, Y_train, lr, weights) if(epoch % 10 == 0): ...
def create_wordcloud(slider_range, dataframe, index_to_time): if slider_range[0] == slider_range[1]: hist = {} hist['none'] = 1 else: # Do some linear interpolation low = slider_range[0] low_low = math.floor(low) low_high = math.ceil(low) low_low_y = ...
The function handles candidate visibility and generates word clouds based on debate type and user input (time/topic). It sets display styles for candidates (Biden, Trump, Harris, Pence) depending on the debate (PD1, PD2, VPD). Word clouds (wc1-wc4) are created using time or topic parameters, with temporary placeholders...
def handle_wordcloud_event(debate, time_or_topic, time1, time2, topic1, topic2, time_vp, topic_vp, both, candidate1, candidate2, times, index_to_time): # Handle who is visible and who isn't if debate == 'PD1' or debate == 'PD2': biden_style = {'display': 'inline-block'} trump_style = {'display':...
def beliefs(word, feature_params, transition_params): # Returns a numpy array of size (w-1) x k x k, psi = chain_potentials(word,feature_params,transition_params) delta_bwd, delta_fwd = message_passing(psi) k = delta_fwd.shape[1] delta_fwd = np.concatenate(([np.zeros(k)], delta_fwd)) delta_bwd = np...
The code predicts character labels for each word in Y_train by computing probabilistic beliefs from input features (X_train) and transition parameters, converting pairwise probabilities to single-character probabilities, and mapping these to predicted characters using the provided alphabet.
def predict(Y_train,X_train,alphabet,feature_params,transition_params): # Returns a list of predictions, where each prediction is a list of predicted character labels of a word. predictions = [] for i in range(len(Y_train)): belief = beliefs(X_train[i],feature_params,transition_params) pairwise_...
def beliefs(word, feature_params, transition_params): # Returns a numpy array of size (w-1) x k x k, psi = chain_potentials(word,feature_params,transition_params) delta_bwd, delta_fwd = message_passing(psi) k = delta_fwd.shape[1] delta_fwd = np.concatenate(([np.zeros(k)], delta_fwd)) delta_bwd = np...
The function computes the gradient of a loss function with respect to feature parameters in a Conditional Random Field (CRF) model. It initializes a gradient matrix, iterates over training data to calculate beliefs and probabilities, and updates the gradient based on the difference between predicted and true labels. Th...
def feature_grad(Y_train,X_train,alphabet,feature_params,transition_params): # Returns a flattened k x n numpy array,where k is the size of the alphabet and n is the length of the feature vector. # Initialize a state gradient table of size k x n with zeros gradient = np.zeros((len(alphabet), len(X_train[0][1]))...
def background(self, r, g, b): self.screen.fill((r, g, b)) def draw_halls(self): for hall in self.sim.halls: self.rectangle(hall.start, (hall.length, 5), cos=hall.angle_cos, sin=hall.angle_sin, color=(218,218, 250)) def draw_peds(self, timer): for hall in self.sim.halls: ...
The code's main task is to render a scene by drawing the background, halls, pedestrians, and status information. The `draw` method updates the display with a colored background, renders static hall structures, animates pedestrian movement using the timer, and overlays real-time status data, likely for a simulation or v...
def draw(self, timer): # Fill background self.background(*self.bg_color) self.draw_halls() self.draw_peds(timer) # Draw status info self.draw_status()
def get_lat_lon_city(city_name, state_code, country_code="us"): api_call = (f"http://api.openweathermap.org/geo/1.0/direct?q={city_name},{state_code},{country_code}" # Calls the f"&limit={5}&appid={api_key}") # Calls the # api based on the city and state entered. Country defaulted to US. r...
The main task of the code is to create a weather application that allows users to input a city/state or zip code to retrieve and display current weather and forecast data. It handles user input validation, fetches geographic coordinates, retrieves weather information via API calls, and formats the output, while managin...
def main(): # This is the main function of the program print("***Welcome to the Weather App***") # Prints the welcome message while True: choice = input("Do you want to search by 'city' or 'zip'? Enter 'quit' to exit: ") # Requests user input to # start the forecast search by city or zip ...
def extract_data(puzzle_input): data = {} seeds = [int(x) for x in puzzle_input.pop(0).split(':')[1].split()] key = "" for l in puzzle_input: if l[0].isalpha(): key = l.split()[0] else: l_data = [int(x) for x in l.split()] add_or_append(data, key, l_d...
The main task of the code is to solve a two-part puzzle by processing input data from a file. It reads and parses seed-soil mapping data, calculates the minimum transformed value for individual seeds (Part 1), and computes the minimum transformed value for seed pairs (Part 2) using conversion maps. The code extracts in...
def main(): puzzle_input = [] with open('day5/input.txt', encoding='utf8') as f: for l in f: fixed_l = l.strip() if fixed_l: puzzle_input.append(fixed_l) seeds,data = extract_data(puzzle_input) part1 = min([seed_to_soil(x,data) for x in seeds]) print(f...
def find_start(maze: List[str]) -> Tuple[int, int]: for y, row in enumerate(maze): for x, colum in enumerate(row): if colum == 'S': return (y,x) def valid_paths(y:int , x:int, maze: List[str]) -> List[Tuple[int,int]]: potential_coords = [(y-1,x),(y,x-1),(y,x+1),(y+1,x)] ...
The code solves a puzzle with two parts: Part 1 calculates the length of a path from a starting position, dividing it by two and rounding up. Part 2 counts how many grid points lie inside a polygon formed by the path and the start position, excluding points on the path itself.
def main(): with open('day10/input.txt', encoding='utf8') as f: puzzle_input = [x.strip() for x in f] s_pos = find_start(puzzle_input) s_paths = valid_paths(*s_pos, puzzle_input) travel_path = traverse_path(*s_paths[0], [s_pos], puzzle_input) print(f"Part 1: {ceil(len(travel_path)/2)}") ...
def save_ProfileInfo(self, file_format: str = "json", filename: str = None, save_path=None, final_filename=None): """ Dump Base Profile Info Args: file_format (str, optional): `json` or `txt`. Defaults to "json" save_path (str, optional): dir path. Defaults to ./username...
The main task of the code is to save all information of a target Instagram profile, including profile details, posts, followers, and followees, with the depth of data collection adjustable via the `level` parameter (default: "high"). It uses specified methods to dump data in JSON format, handling different levels of de...
def save_Everything(self, level: str = "low"): """ Dump/Save all information of the target instagram profile Args: level (str, optional): `all`/`high`, `mid`, `low` are the only possible values. Defaults to "high". """ if not level in ("all", "mid", "low", "high"): ...
def get_columns_count(self) -> int: """ Loop through the first row and count the number of columns until it faces empty column and stops. Then return the counter as number of columns. so line order null """ column_count = 0 while True: ...
This method fetches all data from a sheet, either using user-specified row/column counts or automatically determining them. It returns a generator to yield data in ranges, optimizing performance by avoiding manual end-of-sheet detection.
def fetch_all(self, rows_count: int = None, columns_count: int = None) -> Generator: """ Fetch all data in the data. ------------------------------------ -> Params rows_count : int columns_count: int <- Return ...
def count_down(self): start_time = pygame.time.get_ticks() text = '3' while True: self.handle_events() screen.fill(black) current_time = pygame.time.get_ticks() if 1000 < current_time - start_time < 2000: text = '2' ...
This code implements a snake game loop, handling movement, collision detection, scoring, and time limits. It initializes game elements, processes user input, updates the game state, renders graphics, and transitions between game states (win/game over) based on conditions like snake death or time expiration.
def play_game(self): self.count_down() print("start play_game") surface = pygame.Surface(screen.get_size()) surface = surface.convert() drawGrid(surface) snake = Snake() food = Food() self.score = 0 if self.mode == 'hard': sna...
def _check_exit_conditions(self): if ((self.mode == ScrapeMode.LAZY and self.counter > 1) or (( self.mode == ScrapeMode.SMART or self.mode == ScrapeMode.VERBOSE) and self.counter > self.max_depth + 1)): # Adding one here for good measure. return True return False def _trunc...
This code processes URLs from a queue, checking domain constraints based on the scraping mode. It fetches responses for valid URLs, skips external links unless in verbose mode, and handles each response while tracking progress and exit conditions.
def scrape(self): while len(self.urls): self.counter += 1 if self._check_exit_conditions(): break url = self.urls.popleft() self.scraped_urls.add(url) print(colorize( f'🔥[{self.counter}] Processing {self._truncate(url, ...
def calculate_BSDF(EC_voltage,blind_height,bling_angle): # Another part to balabala optical_standard_path = r"D:\EP96\out\build\x64-Debug\Products\examples\standards\W5_NFRC_2003.std" optical_standard = pywincalc.load_standard(optical_standard_path) glazing_system_width = 4.0772 # width of the glazin...
This code sets up window construction actuators and applies shading control based on blind height. It retrieves construction handles, initializes actuators, calculates BSDF properties, and toggles window shades (shaded/clear) using actuator values. The logic adjusts each window's thermal properties dynamically accordin...
def on_begin_zone_timestep_before_init_heat_balance(self, state) -> int: if not self.handles_set: ###### Set construction using construction actuator ## 1) Get construction handle self.CFS_Glz_Win1 = self.api.exchange.get_construction_handle(state, "CFS_Glz_Win1") ...
def camel_case_to_words(name: str): """ This method will take a camel case string and will break it into words :param name: :return: """ words = [word for word in split(r'(?=[A-Z])', name) if word] return ' '.join(words) def add_instance_changes(data_source, cls, class_name, class_folder_n...
The function constructs a hierarchical data source dictionary from a processed CSV DataFrame, organizing classes and their associated property groups, file paths, and queries. It processes each row to extract class names, property details, and generates structured entries for HTML templates, handling both standard and ...
def build_datasource_for_html_template(processed_csv_file: pd.DataFrame) -> dict: """ This method will build a data source dictionary from a given application profile dataframe :param processed_csv_file: :return: """ data_source = {} for index, row in processed_csv_file.iterrows(): ...
def output_file_name_generator(city, state): if ' ' in state: state = state.split(' ') state = '-'.join(state) return dir_path + "/" + city + '_' + state + '.csv' def get_data(filename, sort): data_list = [] if sort is not None: sort_csv(filename, filename, sort) with open...
The main task of the code is to handle a search request by retrieving user input from the query parameters, generating or fetching data from a file, applying pagination and sorting, and rendering the paginated results in an HTML template. It processes the URL to manage pagination and sorting parameters, ensures data ex...
def search(request): url = request.get_full_path() # taking the complete url of the current request to implement pagination query into it # query = (request.GET['q']).split(', ') # getting the user input from the request query query = (request.GET.g...
def can_be_power(number): for base in available_numbers_desc: if base == 1: continue exponent = round(math.log(number, base)) if base**exponent == number: return (base, exponent) return None def find_largest_denominator(number): for divisor in available_number...
The main task of the code is to decompose a given number into a sequence of mathematical steps (factorization, power representation, addition) to reach a target value in `available_numbers`, recording each transformation in the `steps` list. The function recursively applies operations like dividing by the largest denom...
def solve(number, steps=[]): if number in available_numbers: return steps else: power = can_be_power(number) if power: base, exponent = power steps.append(f"{base}^{exponent}={number}") return solve(base, steps) divisor = find_largest_denominat...
def error(self,e,kill=True): self.g.log("[WARNING] Error logged as: %s"%(e), self.g.red) if kill: self.g.log("[INFO] Driver Station has stopped, press any key to exit.", self.g.orange) self.g.render_stack() pygame.display.update() while True: ...
The main task of this code is to initialize a MiniFRC Driver Station application by loading configuration settings from a config.txt file, setting up serial communication parameters, detecting and configuring joysticks via Pygame, and preparing the system for operation. It reads configuration values for COM ports, baud...
def __init__(self): #setup self.inputs = [] self.g = gui() self.g.log("MiniFRC Driver Station v%s"%(str(version))) #config things self.legacy_packet = False self.enable_joysticks = False self.baudrate = 9600 self.precision = 1 self.autopor...
def parser(): arg_parser = argparse.ArgumentParser(description="YOLO Object Detection") arg_parser.add_argument("--darknet_data_directory", default="data", help="path to darknet data directory") arg_parser.add_argument("--train_backup", type=str, default="", ...
The main task of the code is to prepare data and setup for training a Darknet model. It parses arguments, retrieves data from cloud storage, splits it into training/test sets, generates directory files, downloads pretrained weights, and finalizes configuration. The code ensures data readiness, structure, and model init...
def main(): args = parser() check_arguments_errors(args) darknet_data_dir = args.darknet_data_directory os.chdir(darknet_data_dir) metadata, data, labels, annotations = get_data_from_cos(args.data_limit) split_train_test_data(metadata, data, labels, annotations) append_dir_content_in_file("t...
def _getSegment(self, node): """ Find the segment of a branch or end node by iterating over its predecessors Parameters ---------- node : list of node coordinates 3D: [z, y, x] 2D: [y, x] Returns ------- segmentList : list of nodes in the s...
This code performs a depth-first search (DFS) on a graph to identify segments, track branch/end points, and calculate statistics. It iteratively explores nodes, detects cycles, retrieves segments at branch/end points, and updates statistics. Post-processing removes small segments, filters border/end points, and annotat...
def dfs_iterative(self): """ Iterate over the graph in a depth-first-search. If a branch or end point is found, retrieve the segment and calculate its statistics """ startTime = time.time() visited, stack = set(), [self.start] while stack: vertex = sta...
def generateExportLoadSQL(configuration_yaml, schema_yaml): # Create empty file sql_file_name = 'tpch-load.sql' sql_file_path = createSQLFile(sql_file_name, configuration_yaml) # Get table name target_table_name = configuration_yaml['table_name'] # Iterate over partitions partition...
The function generates SQL files for TPCH dataset setup by calling multiple sub-functions to create load scripts, primary keys, alteration commands, indexes, and analysis queries based on provided configuration and schema YAML files.
def generateExportDataSetupSQLFilesTPCH(configuration_yaml, schema_yaml): generateExportLoadSQL(configuration_yaml, schema_yaml) generateExportPkeysSQL(configuration_yaml, schema_yaml) generateExportAlterSQL(configuration_yaml, schema_yaml) generateExportIndexSQL(configuration_yaml, schema_yaml) gen...
def get_previous_weeks(cur, tablename, collect_date): """Gets all weeks previous (including current) collection date if any Arguments: cur (cursor object): a Psycopg cursor object. tablename (string): name of any of the three relations: hospital_info, hospital_data, ...
The function `get_covid_change` calculates and ranks the change in COVID-19 cases for either states or hospitals between the current collection date and the previous week. It retrieves data for the specified date and the prior week, computes the difference in cases, and sorts the results by the magnitude of change. The...
def get_covid_change(conn, collect_date, nshow, property): """Rank the states/hospitals by the number of cases since the last week Arguments: conn (connection object): a Psycopg connection object. collect_date (datetime.date): collection date of interest nshow (int): number of observati...
def getRandomSubset(Attribute,wordIndex,N_Samples): #For Equal number of Positive Sentiment Attribute and Negative Sentiment Attribute Random_pos = list() Random_neg = list() half_attr = int(len(Attribute)/2) for i in range(0,half_attr): Random_pos.append(i) for i in range(half_attr,len(Attribute)): Random...
The code implements a **Random Forest algorithm** using **Feature Bagging**. It trains multiple decision trees (N_Trees) on random subsets of attributes (N_Attr) from the training data, then aggregates predictions via majority voting for classification. It evaluates accuracy on both training and test datasets, tracking...
def FeatureBagging(Examples,Attribute,wordIndex,ExamplesTest,N_Trees,N_Attr): #RootList to Store Nodes of each tree RootList = list() N_Attr = min(len(Attribute),N_Attr) ListAns = list() for i in range(0,N_Trees): #Getting Random 1000 Attributtes ans coresponding words Attributes_Sample, wordIndexSample = g...
def funcID3(Examples,Attributes,wordIndex): Root = TreeNode() #Count no. of GoodExamples and Bad Examples countGood = makeCountOfGoodReviews(Examples) countBad = len(Examples) - countGood Root.examples_pos = countGood Root.examples_neg = len(Examples) - countGood maxLabel = 1 if countGood >= countBad else -1...
The code trains a decision tree on given data, evaluates its accuracy on training/test sets, and performs tasks based on the 'choice' parameter: analyzing attribute usage (1), handling noise (2), pruning (3), or building a random forest (4). It calculates tree height, accuracy metrics, and handles noisy data or model o...
def run(Examples,Attribute,wordIndex,ExamplesTest,choice): print('Training of Data Started -----------------') Root = funcID3(Examples,Attribute,wordIndex) MaxHeight,Leafs = height(Root) print('Decision Tree Created --------------------') print("Height of New Decision Tree : " + str(MaxHeight)) countTrue = ...
def register_player(self, conn, client_socket): conn.sendto(b'Please, enter your username:', client_socket) try: username = conn.recv(1024).decode() empty_username_flag = True for player in self.players_list: if username == player.username: ...
The main task of the code is to handle client connections in a game server. It continuously accepts connections, sends a success message, registers players, initializes their stash, and runs the game loop for each client. The thread processes one client at a time, returning True after completing the game session for a ...
def game_thread(self): while True: conn, client_socket = self.sock.accept() with conn: print(f'Set connect with client: {client_socket}. Waiting for register...') conn.sendto(b'Connection success.', client_socket) player = self.register_pla...
def step(self, player: MiffyPlayer, action: int): player_id = self.get_player_id(player) # reset current boardstep (clear player) from the boardstep) current_boardstep = self.game_board[self.board_status[player_id]] current_boardstep.clear_step() # find new boardstep se...
This code simulates a turn-based game where players take turns performing random actions (1-6 steps) until a winner is determined or 100 turns pass. It tracks the active player, updates the game state, checks for a win, switches players, and resets the game. The main task is to simulate gameplay, determine the winner, ...
def simulate(self): MAX = 100 turn = 0 while turn <= MAX: turn += 1 action = random.randint(1, 6) # TODO try a new seed print(f"new turn for: {self.active_player}, {action} steps further") self.step(self.active_player, action) print(se...
def experiment(model_type='CNN', learning_rate=0.0001, dropout_rate=0.5, weight_decay=0.01, num_epochs=50, verbose=False): # Use GPU if it is available. device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") # Inpute Batch size: BATCH_SIZE = 32 # Convert images to tensor transform = trans...
The main task of the code is to compare the performance of a Feedforward Neural Network (FNN) and a Convolutional Neural Network (CNN) on image data. It trains both models with identical hyperparameters, records their accuracy histories, and visualizes the results to analyze their effectiveness in image-related tasks.
def compare_arch(): print(" Experiement 1: FNN AND CNN IMAGE COMPARISON\n") FNNM,acc_histFNN = experiment(model_type='FNN',learning_rate= 0.0001,dropout_rate=0.0,weight_decay= 0.00,num_epochs= 50,verbose= False) CNNM,acc_histCNN = experiment(model_type='CNN',learning_rate= 0.0001,dropout_rate=0.0,w...
def renderAll(self): for panel in self.panels: panel.render() def getInput(self): current_panel = self.getCurrentPanel() key = current_panel.win.getch() return key def handleInput(self, key): if key == ord('q'): # Exit fantasia self.quit = True...
The main task of the code is to create a loop that continuously renders all elements, captures user input, and processes the input until a quit condition is met. It handles real-time interactions by updating the display, retrieving input, and executing corresponding actions in a cycle.
def run(self): while(not self.quit): self.renderAll() key = self.getInput() self.handleInput(key)
def read(self,file): read = pd.read_csv(file) return read def read_cpt(self,checking): file_list = [] with open(checking) as f: while True: line = f.readline() if not line: break if line != '\n': ...
The code initializes a probabilistic model by loading training/test data, CPT (Conditional Probability Table), and Bayesian network structure. It sets up query parameters, prepares variables for rejection/likelihood sampling, and initializes timing metrics. The `check_query()` validates the query, while `get_rejection_...
def __init__(self,train,test,cpt_file,structure_file,query,size): self.train = self.read(train) self.test = self.read(test) self.cpt = self.read_cpt(cpt_file) self.structure = self.read_structure(structure_file) self.size = int(size) self.query = query se...
def _make_distr_jsons_for_get_tests(self): _num_distrs = random.randint(15, 23) _citype_template = "TEST%02dDSTR%s" _client_template = "TEST_CLIENT_%02d" _result = list() for _i in range(0, _num_distrs): _client = _client_template % (_i%3) if _i%3 else None ...
The test method verifies the functionality of retrieving and deleting distributives via an API endpoint. It creates test data with specific versions, sends GET requests to fetch distributives by version, checks response validity, and ensures each returned distributive matches expected attributes (citype, path, checksum...
def test_get_distributives__version(self): _all_distrs = self._make_distr_jsons_for_get_tests() for _i in range(len(_all_distrs), len(_all_distrs)*2): _distr = self._make_distr_json(_i, citype="TEST%02dDSTR" % _i) _distr["version"] = _all_distrs[int(_i/2)].get("version") ...
def _make_distr_jsons_for_get_tests(self): _num_distrs = random.randint(15, 23) _citype_template = "TEST%02dDSTR%s" _client_template = "TEST_CLIENT_%02d" _result = list() for _i in range(0, _num_distrs): _client = _client_template % (_i%3) if _i%3 else None ...
This test verifies the functionality of retrieving and deleting distributives via checksum. It generates test data, adds checksums, saves distributions, queries the GET endpoint to ensure correct responses match checksum criteria, validates response structure, and deletes entries to confirm data removal. It checks for ...
def test_get_distributive__checksum(self): _all_distrs = self._make_distr_jsons_for_get_tests() for _distr in _all_distrs: _b_distr = self._add_verify_distr(_distr) _b_distr.checksum.append(self._md5(':'.join([_distr.get("path"), "alternative"]))) # try to save - an...