dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def gen_measurement(i): # x position [m], y position [m] z1 = amz.lat[i] z2 = amz.long[i] z5 = amz.wZsens[i] z = np.array([[z1], [z2], [z5]]) return z.astype(float) def postpross(i, x_est, p_est, x_est_cat, z, z_cat, show_animation, show_ellipse, show_final_flag): if show_animation == 1: ...
The main task of the code is to implement a Cubature Kalman Filter (CKF) over N steps. It initializes state estimates, processes measurements, updates estimates using the CKF algorithm, and optionally visualizes results. The code accumulates state and measurement data in arrays for tracking and analysis, concluding wit...
def main(): # show_final = int(input('Display final result? (No/Yes = 0/1) : ')) # show_animation = int( # input('Show animation of filter working? (No/Yes = 0/1) : ')) # if show_animation == 1: # show_ellipse = int( # input('Display covariance ellipses in animation? (No/Yes = 0/1) : ')) # e...
def read_json(filename): try: with open(filename, "r") as f: data = json.loads(f.read()) except: raise Exception(f"Error when reading {filename}") return data def create_dataframe(data): flat_data = flatten_json(data) return pandas.DataFrame(flat_data) def generate_csv(d...
The code processes all JSON files in the "data" directory by converting each to a DataFrame, generating CSV files, and measuring/Printing individual and total execution times for each file processing task.
def main(): st = datetime.datetime.now() for file in os.listdir("data"): f_st = datetime.datetime.now() data = read_json("data/" + file) df = create_dataframe(data) f_name, f_ext = os.path.splitext(file) generate_csv(df) f_et = datetime.datetime.now() f_ex...
def terminal_node(self, board, player): red_minion = 0 blue_minion = 0 red_master = 0 blue_master = 0 only_masters = True for row in board: for piece in row: if piece != 0: if not piece.master: if pie...
This function implements the alpha-beta pruning algorithm to select the optimal move for a player in a game. It evaluates terminal states, generates valid moves, and recursively applies minimax with depth limits. The best move is determined by maximizing the score while pruning suboptimal branches, returning the most f...
def choose_move(self, board, depth, player=True): self.initial_time = time() if self.terminal_node(board, player): if self.winner == player: return None elif self.winner == 2: print("EMPATE") return None else: ...
def next_obj(self): corners = [(5, 5), (95, 5), (95, 95), (5, 95)] if len(self.objs_held())==3: return corners[self.quadrant] elif len(self.attr_sort('spotted')) == 0: next_angle = self.angle() + math.pi/8 if self.radius() < 15: rad = self.radius() + 5 elif se...
The code collects coordinates of objects in four quadrants by iterating four times, retrieving non-tuple objects, updating positions, sorting held items, and appending final goals, including a fixed (5,5) coordinate.
def four_loops(self): goals = [] for n in range(0, 4): while type(self.next_obj()) is not tuple: target = self.next_obj() self.next_obj().retrieved = True self.coords = target.coords goals.append(target.coords) goals...
def get_api(self): if self.api is None: self.api = self.create_api() return self.api def process_notification(self, data): pass def dismiss_notification(self, data): notif_id = data['id'] self.logger.info(f"Dismissing notification {notif_id} ({data.get('type')})") ...
The main task of the code is to retrieve and process notifications in batches of 10 items. It repeatedly fetches notifications using an API, processes each one, and dismisses it. The loop continues until fewer than 10 notifications are returned, ensuring all notifications are handled in paginated batches.
def do_process_notifications(self): self.logger.debug("Processing notifications...") limit = 10 query = {'limit': limit} while True: notifications = self.get_api().get_notifications(query) for n in notifications: self.process_notification(n) ...
def request(self, method, path, query=None, body=None, headers=None): final_path = path if query is not None: final_path += '?' + urllib.parse.urlencode(query) final_headers = {'Authorization': 'Bearer ' + self.api_key} if headers is not None: final_headers.updat...
The main task of the code is to fetch a user's home timeline from an API endpoint by sending a GET request to '/api/v1/timelines/home' with optional parameters. It validates the response status and returns the parsed JSON data as a list, ensuring error checks are performed before processing the result.
def get_home_timeline(self, params=None): path = '/api/v1/timelines/home' r, data = self.request('GET', path, params) self.check_response_status(r, data) return self.get_check_response_json_list(r, data)
def request(self, method, path, query=None, body=None, headers=None): final_path = path if query is not None: final_path += '?' + urllib.parse.urlencode(query) final_headers = {'Authorization': 'Bearer ' + self.api_key} if headers is not None: final_headers.updat...
The main task of the code is to retrieve a status by its ID from an API. It constructs a URL path using the provided `status_id`, sends a GET request, validates the response, and returns the parsed JSON data.
def get_status(self, status_id): path = f'/api/v1/statuses/{int(status_id)}' r, data = self.request('GET', path) self.check_response_status(r, data) return self.get_check_response_json_dict(r, data)
def request(self, method, path, query=None, body=None, headers=None): final_path = path if query is not None: final_path += '?' + urllib.parse.urlencode(query) final_headers = {'Authorization': 'Bearer ' + self.api_key} if headers is not None: final_headers.updat...
The main task of the code is to retrieve notifications from an API endpoint by sending a GET request to '/api/v1/notifications', validating the response status, and returning parsed JSON data as a list.
def get_notifications(self, params=None): path = '/api/v1/notifications' r, data = self.request('GET', path, params) self.check_response_status(r, data) return self.get_check_response_json_list(r, data)
def get_status_value(self, key): if key in self.status: return self.status[key] self.status[key] = self.get_status_db().get(key) return self.status[key] def get_api(self): if self.api is None: self.api = self.create_api() return self.api def process_home_s...
The main task of the code is to fetch and process a user's home timeline from an API, implementing pagination. It retrieves statuses incrementally using the last fetched ID (`last_home_status_id`) to avoid duplicates. If existing IDs exist, it fetches up to 20 new statuses per request, stopping when fewer than 20 are r...
def do_process_home(self): self.logger.debug("Processing home timeline...") last_home_status_id = self.get_status_value('last_home_id') if last_home_status_id: limit = 20 query = {'min_id': last_home_status_id, 'limit': limit} while True: stat...
def random_graphs(pool_size): """ Generate a list of random connected graphs. Parameters: - pool_size: Size of the pool or the number of graphs in the pool. Returns: - RG: List of pool_size initial random connected graphs. Generates a list of connected graphs by repeatedly cal...
The function uses a genetic algorithm to evolve a population of graphs, iteratively improving their fixation probability. It returns the maximum fixation probabilities and corresponding graphs found at each iteration, aiming to identify the graph structure that maximizes fixation probability for a given population size...
def find_graph_with_highest_fix_prob(number_of_GA_iterations): """ For a population of size `population_size`, find out how individuals in the population should be connected in order for the population to have the highest fixation probability. Parameters: - number_of_GA_iterations: the number o...
def query_keypoint_id(self, point): lowest_distance = np.infty closest_keypoint_id = None for id, keypoint in enumerate(self.keypoints): distance = self.euclidean_distance(keypoint.pt, point) if (distance < lowest_distance): lowest_distance = distance ...
The code handles a right-click event to display SIFT features. It prints click details, queries a keypoint ID from coordinates, extracts SIFT parameters (octave, layer, scale, radius), prints image/keypoint info, and visualizes the selected SIFT feature with its descriptor.
def on_click(self, event): print("button={}, x={}, y={}, xdata={}, ydata={}\n".format( event.button, event.x, event.y, event.xdata, event.ydata)) if (event.button == RIGHT_BUTTON): keypoint_id = self.query_keypoint_id((event.xdata, event.ydata)) octave, l...
def assert_audio_file(self, file): #assert that the audio file is return True def asmr_copy(self): #check that library/asmr directory exists if os.path.isdir("library/asmr") != True: self.post("./library/asmr/ directory does not exist, copying aborted.") else: #check for d...
This code selects audio files, converts WAV to FLAC, validates them, adds valid files to a list, updates a pointer, and triggers copy/load actions. It handles user input via file dialog or passed arguments, ensuring only valid audio files are processed and stored for further use.
def asmr_select(self, *others): if len(others) == 0: ans = tk.filedialog.askopenfilenames() else: ans = (others[0],) if len(ans) == 0: return else: for file in ans: if file.endswith('.wav'): file = self....
def read_schema(filename: pathlib.Path) -> dict: """Read the OMAS gyrokinetics, and drop some of the unnecessary keys""" with open(filename) as f: gk = json.load(f) del gk["gyrokinetics"] return gk def prune(gk): """Remove the keys we're not (currently) interested in""" DROP_KEYS_CON...
The function converts an OMAS schema file into a JSON schema format by reading the schema, pruning unnecessary data, transforming it using a mapping (if enabled), and returning the structured JSON output with sorted keys.
def omas_to_json_schema(filename, mapping=False): """Read and convert OMAS schema to JSON schema""" gk = read_schema(filename) prune(gk) converted = to_json_schema(to_benedict(gk), mapping) return json.loads(converted.to_json(sort_keys=True))
def linreg_train_sgd(xtr,ytr,C, learningrate, batchsize, maxnumepochs, stopthresh, xv,yv): # what def linreg_train_sgd(xtr,ytr,C, learningrate, batchsize, maxnumepochs, stopthresh, xv,yv): # actually does w=sgdforthis(xtr, ytr, C, learningrate, batchsize, maxnumepochs, stopthresh, xv,yv) return w def linreg_...
The function `run2` trains a linear regression model using stochastic gradient descent (SGD) on training data `(xtr, ytr)` with regularization parameter `C`, then evaluates its performance. It compares the learned weights `w` to true weights `[w1, w2]`, computing their squared difference. It also calculates the mean sq...
def run2(xtr,ytr,xv,yv,w1,w2,C): learningrate=0.01 batchsize=5 maxnumepochs=1000 stopthresh=0.0001 w=linreg_train_sgd(xtr,ytr,C, learningrate, batchsize, maxnumepochs, stopthresh, xv,yv) wtrue=np.asarray([w1,w2]) print('w',w, 'true w', [w1,w2], 'diff', np.dot((w-wtrue).T,w-wtrue)) ypred=linreg_app...
def explore(self, way): for i in range(100): stock = getInfo(choice(SP500), way=way) self.buy(stock, self.buyEvaluate(stock) * 10) def maintain(self, way): if len(self.portfolio.keys()) == 0: return for i in range(100): stock =...
The code executes a trading bot's daily operations: explores/maintains the strategy, evaluates portfolio value, logs recent trades (buy/sell) with color-coded messages, and terminates the bot if its evaluation drops below 80000. If surviving, it displays the bot's status, evaluation value, and recent trade history.
def operate(self, way='fs'): self.explore(way=way) self.maintain(way=way) value = self.evaluatePortfolio(way=way) self.history['evaluation'].append((createTimeStamp(), value)) recents, recents_str = self.history['operations'][-5:], '' for each in recents: if ...
def get_monitored_pgis_list(self, monitored_pg_names: List[str]) -> Dict[int, object]: monitored_pgis = [] pgi_list = self.find_all_processes(lambda process: process.process_name in monitored_pg_names) for entry in pgi_list: pgi = entry[0] pid = entry[1].pid ...
The main task of the code is to configure instrumentation for monitored processes, collect performance metrics from them, and generate aggregated metrics. It extracts configuration settings, identifies target processes, creates a module configuration, reads raw measurements, processes them into structured metrics, and ...
def query(self, **kwargs) -> None: config = kwargs["config"] self.enable_debug_log = config["enable_debug_log"] instrumentation_enabled = config["instrumentation_enabled"] monitored_pg_names = config["monitored_pg_names"].split(",") monitored_pgis = self.get_monitored_pgis_list(...
def load_checkpoint(cp_path, model, optimizer): cp = torch.load(cp_path) model.load_state_dict(cp['model_state_dict']) Autoencoder.CENTROIDS = cp['centroids'] optimizer.params = model.parameters() return model, optimizer, cp['losses'], cp['epoch'], cp['ref_img'] def latent_dim_map(model, digit_datal...
The function evaluates a trained model by loading a checkpoint, disabling gradients, and visualizing results. It generates latent dimension maps (if latent_dim=2), plots training loss, loss histograms, creates a GIF, and samples test data, saving outputs to a directory for analysis.
def evaluate_model(model, criterion, optimizer, dataloaders, digit_dataloaders, cp_path): model, optimizer, losses, _, _ = load_checkpoint(cp_path, model, optimizer) model.eval() model.requires_grad_(False) result_dir = './mlp_img_ld{}'.format(model.latent_dim) if model.latent_dim == 2: prin...
def get_dataloaders(): img_transform = transforms.Compose([ transforms.ToTensor(), # transforms.Normalize([0.5], [0.5]), ]) dataset = MNIST('./data', transform=img_transform, download=True) digit_dataloaders = [] for i in range(10): dig_mask = dataset.train_labels == i ...
The code trains and evaluates a model (likely a GAN or VAE) on digit datasets for varying latent dimensions. It loads data, iterates through latent dimensions, initializes models, trains using Adam optimizer and a specified criterion, then evaluates performance with MSE loss, saving checkpoints for each configuration.
def main(): print("Starting run") data_loaders, digit_dataloaders = get_dataloaders() print("Datasets loaded for signal digit {} and generate digit {}".format(SIGNAL_DIGIT, GENERATE_DIGIT)) for ld in LATENT_DIMS: print("Staring run for latent dim: {}".format(ld)) model = MODEL(ld) ...
def calculate_line_distance(self): # Calculates the Distance to the Goal num = math.fabs((self.pose_goal.y - self.pose_initial.y) * self.pose.x - (self.pose_goal.x - self.pose_initial.x) * self.pose.y + (self.pose_goal.x * self.pose_initial.y) - (self.pose_goal.y * self.pose_initial.x)) den = ma...
This ROS node initializes a navigation system for a robot, subscribing to sensor data (laser, pose, yaw, bumper) and publishing movement commands. It implements a state machine (Drive to Goal, Laser Avoidance, Bumper Handling) to navigate toward a target while avoiding obstacles. The node uses laser scans for proximity...
def __init__(self): # Node Initialisation rospy.init_node("bug2") # Topic Subscribers rospy.Subscriber('process/scan', Point, self.callback_laserscan) rospy.Subscriber('process/pose', Point, self.callback_pose) rospy.Subscriber('process/yaw', Float64, self.callback_yaw) ...
def preprocess(df): df['dob'] = df.apply(lambda row: get_dob(row.age), axis=1) df['workclass'] = df['workclass'].str.replace("?", "Not working") df['occupation'] = df['occupation'].str.replace("?", "No occupation") for (columnName, columnData) in df.iteritems(): df[columnName] = df.apply(lambda row : normal...
The code performs k-anonymity on a dataset by sampling records, generalizing sensitive attributes (doblvl, wclasslvl), and applying generalization across attribute combinations to ensure privacy. It reads data, preprocesses it, samples rows, generalizes a sample tuple, and iterates over attribute pairs to apply general...
def integrate(number_of_records, k, doblvl, wclasslvl): df = pd.read_csv("adult.csv") df = preprocess(df) sample, state = sample_table(number_of_records, df) print(generalise_tuple(sample, doblvl, wclasslvl, state, k, True)) cp = [] for i in range(6): for j in range(6): cp.append((i, j)) g...
def preprocess(df): df['dob'] = df.apply(lambda row: get_dob(row.age), axis=1) df['workclass'] = df['workclass'].str.replace("?", "Not working") df['occupation'] = df['occupation'].str.replace("?", "No occupation") df['g_dob'] = df['dob'] df['g_workclass'] = df['workclass'] df['level'] = [(0, 0) for i in r...
The code generalizes a dataset using multiple levels of generalization paths. It reads and preprocesses the 'adult.csv' data, samples a subset, generates 25 (i,j) path combinations, applies generalization via `try_path()`, and saves the result to 'result.csv'. The goal is to anonymize or abstract data by applying hiera...
def multilevel_generalise(nof, k): df = preprocess(pd.read_csv("adult.csv")) samp, st = sample_table(nof, df) pth = [] for i in range(5): for j in range(5): pth.append((i, j)) generalized_table = try_path(pth, samp, k) print() # for lvl, count in (Counter(generalized_ta...
def fetch_archives(url, start_date, end_date, interval): print(f'Fetching archives for URL: {url} from {start_date} to {end_date} at intervals of {interval}') archives = [] start_timestamp = start_date.strftime('%Y%m%d%H%M%S') end_timestamp = end_date.strftime('%Y%m%d%H%M%S') cdx = WaybackMach...
The main task of the code is to process archived website content over a specified date range, extract embedded trackers and external URLs from each archive, and save the results to a CSV file. It fetches historical website snapshots, analyzes their HTML content using a tracker database, and logs findings with timestamp...
def process_archived_website(url, start_date, end_date, interval, tracker_database, csv_filename, session): archives = fetch_archives(url, start_date, end_date, interval) archive_data = [] for date, archive_url in archives: print(f'Processing archive: {archive_url} for date: {date}') html =...
def setup_ollama(settings: dict, prompt: str) -> bool: """ setup Ollama """ err: bool = False print(f"Ollama server: {settings['ollama_url']}") # check if Ollama model is available on the server err, full_model_name = check_ollama_model_available(settings) if not err: settings['model']...
The function initializes a model for inference based on the provided settings. It checks flags and model strings to determine which setup function to call (e.g., Ollama, MLX-VLM, Kosmos-2, etc.), executes the corresponding initialization, and returns an error status. If the model is unrecognized, it prints an error and...
def init_model( settings: dict, ) -> bool: """ download and init model for inference """ err: bool = False model_str: str = settings["model"] prompt: str = settings["prompt"] if settings["use_ollama"]: err = setup_ollama(settings, prompt) elif settings["use_mlx_vlm"]: ...
def empty_cells(self, self_filled, opponent_filled): """ Each empty cell will be added into cells' list :param self_filled: the state of the self_filled in current board :param opponent_filled: the state of the opponent_filled in current board :return: a list of empty cells ...
The function `choose_position` selects the optimal next move in a game (likely Tic-Tac-Toe) by evaluating possible positions. It handles three scenarios: if the board is empty, it picks a random position; if the board is full or the game is over, it returns nothing; otherwise, it uses the minimax algorithm to determine...
def choose_position(self, self_filled, opponent_filled, log_choice=False): """ Choose the next fill position """ is_board_empty = True is_board_full = True possible_positions = self.empty_cells(self_filled, opponent_filled) depth = len(possible_positions) ...
def calculate_dataset_metrics(Xtrain): N, T = Xtrain.shape[0], int(Xtrain.shape[1]/3) return N, T def Get_intinfo(T): if T > 40: nintv = 20 intvlen = int(T//nintv) else: intvlen = 5 nintv = int(T//intvlen) return intvlen, nintv def Splitview(X, T):...
This function processes multi-view data by extracting raw, Fourier-transformed, and derivative features from time-series datasets, concatenating these views, and standardizing the resulting features for training, validation, and testing. It prepares structured input for multi-view machine learning models by integrating...
def Multi_view(Xtrain_raw, Xval_raw, Xtest_raw): N, T = calculate_dataset_metrics(Xtrain_raw) intvlen, nintv = Get_intinfo(T) Xtrain_raw, Xtrain_fft, Xtrain_derv = Splitview(Xtrain_raw, T) Xval_raw, Xval_fft, Xval_derv = Splitview(Xval_raw, T) Xtest_raw, Xtest_fft, Xtest_derv = Splitview(Xtest_...
def Givetraintonode(Nodes, pronodenum, datanums): Nodes[pronodenum].trainidx = datanums return Nodes def Givevaltonode(Nodes, pronodenum, datanums): Nodes[pronodenum].testidx = datanums return Nodes def Trainnode(Nodes, pronum, Epoch, lrt, X, y, Mdlnum, mdlpath, clsnum, Xt, yt): trainidx = Nodes[pro...
This function constructs a tree structure by iteratively training nodes using provided training and validation data. It initializes a root node, trains it, splits data into true/false indices, and expands the tree by adding left/right child nodes if there are remaining samples. The process repeats until all nodes are p...
def Build_tree(Xtrain, Xval, ytrain_raw, yval_raw, Epoch, classnum, \ learnrate, savepath = "./utils/"): Tree = {} pronodenum = 0 maxnodenum = 0 Modelnum = 7 bstaccu = 0 Tree[maxnodenum] = Node(maxnodenum) Tree[pronodenum].stoptrain = False Tree = Givetraintonode(Tree, pro...
def vshape(self, layer_name): """ Find the vshape of layer. """ if ( layer_name in self.config["layers"] and "vshape" in self.config["layers"][layer_name] ): return self.config["layers"][layer_name]["vshape"] else: return No...
The function generates an image from a neural network's activation vector by reshaping, normalizing, applying a colormap, and rendering it as a visual widget, handling different data formats and configurations like rotation and scaling.
def make_image(self, layer_name, vector, colormap=None): """ Given an activation name (or function), and an output vector, display make and return an image widget. """ vshape = self.vshape(layer_name) if vshape and vshape != self._get_output_shape(layer_name): ...
def _extract_inputs(self, inputs, input_names): """ Get the input_names from the inputs """ # inputs is either a dict or a list, where index matches # the input banks. if isinstance(inputs, dict): return [inputs[name] for name in input_names] else: ...
This function propagates input data through a neural network to a specified layer, returning outputs in the requested format (numpy, list, or image). It handles multiple input banks by extracting relevant inputs, uses a pre-defined model for prediction, and raises errors with shape hints if inputs are mismatched. The o...
def predict_to(self, inputs, layer_name, format="numpy"): """ Propagate input patterns to a bank in the network. * format: (str) "numpy", "list", or "image" """ if len(self.input_bank_order) > 1: input_names = self._input_layer_names[layer_name] model = s...
def _get_act_minmax(self, layer_name): """ Get the activation (output) min/max for a layer. Note: +/- 2 represents infinity """ if ( layer_name in self.config["layers"] and "minmax" in self.config["layers"][layer_name] ): return self.c...
This method initializes or updates layer minmax ranges for a neural network. If inputs are provided, it sets input layer minmax to input extremes (or updates existing ranges) based on predictions. If inputs are None, it estimates minmax from activation functions. The 'reset' flag determines whether to reset input layer...
def initialize(self, inputs=None, reset=True): """ Set minmax for each layer based on inputs or activation functions per layer. If inputs is None, just make best guess for all layers. If inputs is not None, use these for input layer minmax, and all other layers get best...
def _get_visible(self, layer_name): if ( layer_name in self.config["layers"] and "visible" in self.config["layers"][layer_name] ): return self.config["layers"][layer_name]["visible"] else: return True def make_image(self, layer_name, vector, colorm...
The main task of the code is to preprocess neural network layers for visualization by generating images, calculating their dimensions, and handling layout parameters. It computes max widths/heights, creates images for inputs/outputs, adjusts sizes using configuration settings, and prepares error/target visualizations i...
def _pre_process_struct(self, inputs, ordering, targets): """ Determine sizes and pre-compute images. """ # find max_width, image_dims, and row_height # Go through and build images, compute max_width: row_heights = [] max_width = 0 max_height = 0 i...
def _get_input_layers(self): return tuple( [x.name for x in self._layers if self._get_layer_type(x.name) == "input"] ) def _get_output_layers(self): return tuple( [x.name for x in self._layers if self._get_layer_type(x.name) == "output"] ) def _get_level_ordering(...
This code initializes a neural network visualization tool by configuring layer relationships, topological ordering, and SVG rendering parameters. It sets up intermediary models, input/output mappings, and a detailed config dictionary for visual attributes like colors, spacing, and layout. The class prepares to generate...
def __init__(self, model, **config): self._model = model # Place to put models between layers: self._predict_models = {} # Place to map layer to its input layers: self._input_layer_names = {} # Get all of the layers, even implicit ones, in order: self._layers = to...
def _pre_process_struct(self, inputs, ordering, targets): """ Determine sizes and pre-compute images. """ # find max_width, image_dims, and row_height # Go through and build images, compute max_width: row_heights = [] max_width = 0 max_height = 0 i...
The code generates an SVG structure visualizing neural network layers, their connections, targets, and errors. It processes input data, positions layers with spacing, draws images/labels, handles visibility, and adds arrows between layers. The output includes scalable SVG elements with tooltips, labels, and dynamic sca...
def build_struct(self, inputs, targets): ordering = list( reversed(self._level_ordering) ) # list of names per level, input to output ( max_width, max_height, row_heights, images, image_dims, ) = self._pre_process_s...
def add_config_table(reportname): cus_list = embedded_collection_list() config_header_db = ['Target DB ('+ trgt_type +')','Source DB ('+ src_type +')'] config_header = ['Target Entity Name','Target SQL query','Source Entity Name','Source SQL query'] out_res = "<BR><BR><B>DB Configuration Details:</B><BR...
The code generates an HTML validation report comparing source and target data, including record counts, field validations, and mismatches. It writes results to CSV files, applies conditional formatting, and opens the generated HTML report.
def html_report_generation(report_res,reportname,tablekey,count_val): count = get_row_count() src_count = str(count[0]) trgt_count = str(count[1]) dttm_string_now = datetime.datetime.now() dttm_string = dttm_string_now.strftime("%d_%b_%Y_%H_%M_%S") out_file_name = "C:/Demo/Validation_Tool/Output...
def get_k_random_centroids(k, data_points): """ Get k centroids from random unique elements in data_points """ return np.array(random.sample(list(data_points), k)) def cluster_data(data_points, centroids): """ Clusters data_points in data_points together that have the same centroid """ clustered_data = ...
The code implements the K-means clustering algorithm to group data points into k clusters. It initializes random centroids, iteratively assigns data points to the nearest centroid, recalculates centroids from cluster means, and repeats until centroids stabilize or max iterations are reached. The function returns the fi...
def k_means(k, data_points, max_iters=100): """ Returns data_points spread over k clusters """ centroids = get_k_random_centroids(k, data_points) for _ in range(max_iters): clusters = cluster_data(data_points, centroids) new_centroids = get_centroids_from_clusters(clusters) if (centr...
def extract_type(self, entry): return entry.type def extract_fields(self, entry): return entry.fields.items() def extract_persons(self, entry): authors = [] for persons in entry.persons: for person in entry.persons[persons]: author = self.extract_fullname(pers...
This function converts BibTeX entries into a target format by extracting entry types, fields, and authors, then writing them using a writer object. It collects errors during processing and returns a success status, a message, and the error list. If an exception occurs, it logs and returns an error message.
def convert_file(self) -> tuple[bool, str, list[str]]: errors = [] try: for key in self.bibdata.entries.keys(): item = self.bibdata.entries[key] item_type = self.extract_type(item) fields = self.extract_fields(item) author...
def calculate_new_added_edges_size(dataset, test_time, prediction_time): X , Y = calculate_features(dataset.train[['time', 'target']]) test_X , test_Y = calculate_features(dataset.test[['time', 'target']]) mse = 0 best_mse = 0 best_prediction = 0 for counter in range(1, 2): z = np.poly1d(np.polyfit(X, Y, counte...
The code's main task is to predict new edges in a graph using k-means clustering on training data, determine the number of edges to add, generate these edges, and save them in a CSV file with timestamps. It processes training/test data, scales ratings, computes centroids, creates a graph, adds predicted edges, and writ...
def last_question(dataset, test_time, prediction_time): #predicting number of edges added_edges_size = calculate_new_added_edges_size(dataset, test_time, prediction_time) print(added_edges_size) #predicting new edges points = dataset.train[['source', 'target', 'rating']].values points[:,2] *= 10000 test = datase...
def format_user_mentions(text): query = "select slack_user_id, username from tbl_users" username_by_slack_user_id = { slack_user_id: username for (slack_user_id, username) in do_select(query) } for word in text.split(): if "<@U" in word and ">" in word: start_index = word.index("<@U") ...
This function processes a list of messages into structured records by formatting text elements (mentions, emojis, links, code blocks, blockquotes), applying query highlighting, and populating metadata like dates, usernames, and file info. It handles missing data with defaults, constructs HTML-formatted text, and return...
def package_messages(messages, q): records = [] for message in messages: text = message[5] text = format_user_mentions(text) text = format_emojis(text) text = format_links(text) text = format_pre(text, '```') text = format_pre(text, '`', tagclass="inline") ...
def get_db_conn(): conn = mysql.connector.connect( host=DB_HOST, database=DB_NAME, user=DB_USER, password=DB_PASSWORD, ) return conn def do_select(query, args=()): conn = get_db_conn() cursor = conn.cursor() cursor.execute(query % args) results = cursor.fetcha...
The main task of the code is to perform a paginated database search for messages using dynamic SQL queries based on user-provided filters (e.g., username, team/channel names, date ranges, text content). It constructs WHERE clauses with LIKE/NOT LIKE conditions, handles SQL matching, calculates pagination offsets, execu...
def search(): q = request.args.get("q", "") username = request.args.get("username", "") team_name = request.args.get("team_name", "") channel_name = request.args.get("channel_name", "") start_date = request.args.get("start_date", "") end_date = request.args.get("end_date", "") sql_match = re...
def do_select(query, args=()): conn = get_db_conn() cursor = conn.cursor() cursor.execute(query % args) results = cursor.fetchall() cursor.close() return results def package_messages(messages, q): records = [] for message in messages: text = message[5] text = format_user_...
The code retrieves a specific message and its context from a database, processes surrounding messages based on offset, formats user and date displays, and renders a template with navigation links for message browsing.
def context(message_id, q=None): try: if not q: q = request.form.get("q", request.args.get("q", "")) offset = request.form.get("offset", request.args.get("offset", 0)) username = request.form.get("username", request.args.get("username", "")) channel_name = request.form.ge...
def next_batch(self, x, y, batch_size): for i in np.arange(0, x.shape[0], batch_size): yield (x[i:i + batch_size], y[i:i + batch_size]) def update_gradient(self, x, y): # Firstly, we ensure that our matrix is a numpy matrix # and has reasonable dimensions. A = [np.atleast_2d(...
This code trains a model using mini-batch stochastic gradient descent (SGD). It adds a bias term to input data, shuffles the dataset each epoch, processes data in batches, updates model gradients iteratively, and periodically prints the loss after every 'step' epochs to monitor training progress.
def train(self, X, Y, epochs, batch_size=16, step=100): # Adding bias X = np.c_[X, np.ones((X.shape[0]))] for epoch in range(epochs): X, Y = shuffle(X, Y) # Stochastic gradient descent for (x, target) in self.next_batch(X, Y, batch_size): ...
def update_rolled_dice(self): for e in (self.rolled_dice_buttons): e.destroy() self.rolled_dice_buttons = [] for i in range(len(self.rolled_dice)): if (self.rolled_dice[i]=="Arrow"): img = self.arrow_img elif (self.rolled_dice[i]=="Axe"): ...
This method concludes a game turn by updating player and bot HP displays, tracking the current turn, resetting dice selections, and checking game status. If the game isn't over, it triggers the bot's turn if applicable or enables the player to roll dice again, updating UI elements accordingly.
def end_turn(self): self.game.end_turn() self.player_hp_var.set("Player HP: " + str(self.game.players[0].hp)) self.bot_hp_var.set("Bot HP: " + str(self.game.players[1].hp)) self.turn_player_var.set(f"Turn {self.game.players[self.game.current_player].turns_played+1}: {'Player' if (self.ga...
def handle_json_event(data, parent_key="", result_dict=None): """ This fucntion performs some cleanup on the result_dict to remove empty values and handles nested objects. @param data: Event data recieved from salesforce. @param parent_key: This will handle nested attribute key in event's payload. ...
The main task of the code is to process incoming event data, filter relevant fields, and apply Delta Lake operations (CREATE/UPDATE/DELETE/UNDELETE) to an S3-based Delta table, with retry logic for error handling. It dynamically constructs S3 paths using partitioning, targets specific Athena table partitions, and ensur...
def lambda_handler(event, context): # change s3 bucket path delta_path = 's3://bosa-shared-dev-data-warehouse-us-west-1/salesforce-events/' max_retries = 3 retry_delay_seconds = 5 # Specify your Athena table and partition column table_name = 'salesforce_employee' partition_column = 'entityna...
def print_board(elements): for i in range(9): if i%3==0: print() if elements[i]==-1: print("_",end=" ") else: print(elements[i],end=" ") print() def solvable(start): inv=0 for i in range(9): if start[i]<=1: continue for j in range(i+1,9): if start[j]==-1: continue if start[i]>start[j...
The code's main task is to solve the 8-puzzle problem by taking user-input start and goal states, checking if the start state is solvable, and if so, finding the solution path using the `solveEight` function. It then outputs the number of moves required to solve the puzzle or indicates if the start state is unsolvable....
def main(): global g start=list() goal=list() print("Enter start state") for i in range(9): start.append(int(input())) print_board(start) print("enter goal state") for i in range(9): goal.append(int(input())) if solvable(start): solveEight(start,goal) print("solved in {} moves".format(g)) else: p...
def _formatEarlierDate(self, yearsBack:int)->str: today_date = datetime.now() three_years_ago_date = today_date - timedelta(days=yearsBack * 365) formatted_date = three_years_ago_date.strftime("%Y-%m-%d") return formatted_date def _formatTodaysDate(self)->str: today_date = dateti...
The main task of the code is to analyze a stock's recent trend by checking if the last three days' "state" values are consistent (all "up" or all "down"). If consistent, it determines the movement direction and triggers further analysis via `_analyze()`, returning the result. If inconsistent or no data, it returns {"st...
def startStrategy(self, ticker:str)->dict: # Variable to determine how long ago the data should be grabbed from. # Decided on three so avg values do not differ to much. yearsBackData = 3 data = yf.download( ticker, start=self._formatEarlierDate(yearsBackData), ...
def getPredictImg(img): return getPredictionMaskImg(img.copy()) def maskToOrignimalImg(img, mask): """add mask to color image""" if img.shape != mask.shape: # mask = expandImageTo3chan(mask) img = expandImageTo3chan(img) # print(img.shape,mask.shape) return cv2.addWeighted(img, 1.0,...
This code demonstrates image segmentation prediction by loading an image, applying blur, generating a predicted mask, and converting it back to a segmented image. If a ground truth mask is provided, it is processed and compared. The function visualizes the original image, ground truth mask (if available), predicted mas...
def demonstratePrediction(file, gtMaskFile=None): img = loadImg(file) # img = loadGrayImg(file) simg = blurImg(img) pMask = getPredictImg(simg) pImg = maskToOrignimalImg(img, pMask) if gtMaskFile is not None: maskImg = loadImg(gtMaskFile) # maskImg = resizeImg(maskImg,256,256) ...
def argCmdParse(): parser = argparse.ArgumentParser() parser.add_argument('-s', '--source', help='source image') parser.add_argument('-d', '--dst', help='save iamge') # parser.add_argument('-c', dest='compare', action='store_true') return parser.parse_args() def demonstratePrediction(file, gtMaskFil...
The main task of the code is to process an input image file using a prediction model, generate output predictions, and save the results to a specified destination file. The active code path uses command-line arguments to determine input/output files, while the inactive block demonstrates prediction with hardcoded file ...
def main(): arg = argCmdParse() file = arg.source dstFile = arg.dst print(file, dstFile) if 0: # file = r'.\res\PennFudanPed\PNGImages\FudanPed00012.png' # maskFile = r'.\res\PennFudanPed\PedMasks\FudanPed00012_mask.png' file = r'.\res\PennFudanPed\PNGImages\PennPed00068.pn...
def heapify_wikipedia(self): # the Wikipedia heapify is a bottom up application of the top down heapify pushing low values as low as # they will go and bubbling up one level the higher values. for index in range(self.size - 1, -1, -1): self.heapify_top_down(index, self.size - 1) def...
The function `full_sort` constructs a heap using either Wikipedia-based or bottom-up heapification, validates the heap structure, prints results, generates a graph if enabled, and sorts the heap. It handles heap verification, reports invalid heaps, and outputs sorting status.
def full_sort(self, name, wikipedia=True, verify_heap=True, graph=False): if wikipedia: self.heapify_wikipedia() else: self.heapify_bottom_up() if verify_heap: invalid_heaps = self.verify_heap() if invalid_heaps: output = f"{name}...
def __filter_domain_dialogues(self, domain): domain_dialogues = [] for dialogue in self.__dialogues: if 'services' in dialogue and domain in str(dialogue['services']): domain_dialogues.append(dialogue) return domain_dialogues def __get_qa_list_from_dialogues(self, di...
This function generates random error dialogues by selecting QA pairs from a specified domain, creating non-understanding responses and system replies, and saving them to JSON. It recursively adjusts the seed if the initial selection fails, ensuring a predefined number of dialogues are created until maximum options are ...
def create_random_error_dialogues(self, domain, amount=5, seed=0): try: self.__error_dialogue_acts_copy = self.__error_dialogue_acts.copy() domain_dialogues = self.__filter_domain_dialogues(domain) qa_list = self.__get_qa_list_from_dialogues(domain_dialogues) filt...
def get_page_source(url): #object of Options class, passing headless parameter c = Options() # c.add_argument('--headless') s = Service('scraper/drivers/chromedriver-v103.exe') browser = webdriver.Chrome(service=s, options=c) browser.set_window_size(1120, 550) browser.get(url) try: ...
The main task of the code is to scrape program requirements and course data from a given URL, parse the structured information (including yearly requirements), and update a JSON database (`all_programs.json`) with the extracted program details. It retrieves the program name, organizes requirements by year, collects cou...
def add_program(program_url): soup = get_page_source(program_url) container = get_prereq_container(soup=soup) program_h2 = soup.select_one("#__KUALI_TLP h2") if(program_h2 == None): print("Error: uvic program has no program name from url %s"%program_url) return program_name = progr...
def unique_key_func(): unique_keys = set(keys_func()) return unique_keys def multiple_occurrence_func(): multiple_occurrence_list = [key for key in unique_key_func() if keys_func().count(key) > 1] return multiple_occurrence_list def random_func(): from random import choice, randint from string i...
The function aggregates values from multiple dictionaries by identifying keys present in more than one dictionary. For such keys, it selects the maximum value and appends the dictionary index (adjusted by +1) to the key. For keys unique to a single dictionary, it directly adds the value. The result is a consolidated di...
def final_func(): final_dict = {} for key in unique_key_func(): # Checking if the key occurs in more than one dictionary if key in multiple_occurrence_func(): # Finding the maximum value of the key among all dictionaries and the index max_value = float('-inf') ...
def get_regular_lr(self, epoch, iter): return [self.get_lr(epoch, iter, _base_lr) for _base_lr in self.base_lr] def _set_lr(self, lr_groups): for param_group, lr in zip(self.optimizer.param_groups, lr_groups): param_group['lr'] = lr def get_warmup_lr(self, cur_iters): if self.warmup ...
This function adjusts the learning rate during training iterations. It checks if the training is epoch-based or iteration-based. If iteration-based, it computes the regular learning rate and applies warmup logic if needed. If epoch-based, it handles warmup phases and sets the appropriate learning rate based on the curr...
def before_train_iter(self, epoch, iter): cur_iter = iter if not self.by_epoch: self.regular_lr = self.get_regular_lr(epoch, iter) if self.warmup is None or cur_iter >= self.warmup_iters: self._set_lr(self.regular_lr) else: warmup_lr = ...
def init_servos( port ): condition = True ## Connects to motors and callibrates them if ok if condition == True: global packetHandler global portHandler portHandler = port_handler.PortHandler(port) packetHandler = packet_handler.PacketHandler(0) condition = False ...
The main task of the code is to manage a robotic motion system by continuously checking the 'motion state' and 'main state' of the 'world' dictionary. It attempts to connect to servos if disconnected, then executes predefined movements (relaxing, awakening, or specific motor actions) based on the 'main state' (sleep, a...
def create_motion( world ): while world['power state']: # tries to connect every 1s if world['motion state'] == 'disconnected': try: time.sleep(1) result = init_servos(world['motor port']) if result == False: t...
def login_in_facebook(self): self.check_argv() script_name, login, passwd = sys.argv self.wait_until_item_is_clickable(By.ID, SELECTOR_FOR_LOGIN, "text_box_login") self.__driver.find_element(By.ID, SELECTOR_FOR_LOGIN).send_keys(login) self.__driver.find_element(By.ID, SELECTOR_...
The code automates logging into Facebook, navigates to the user's friend list, retrieves friend data, and stores it in both CSV and JSON formats using specified repositories. It then closes the browser session.
def workflow(self): self.__driver.get("https://www.facebook.com/") self.login_in_facebook() self.move_to_myprofile() self.move_to_friends() friends = self.get_info_about_friends() repository = CSVRepository(self.get_config()) repository.insert(friends) ...
def make_scanRBP(): print(f"{module_name} start") scanRBP_to_process = [[a,b,c,d] for (_,a,b,c,d) in scanRBP_pairs] scanRBP_to_process = [item for sublist in scanRBP_to_process for item in sublist] comparison_counts = {} for feature_type, mcriteria in motif_criteria.items(): print(f"{module_...
The function `process()` executes a series of tasks for analyzing biological sequences: it conditionally scans and plots RBP data if enabled, generates sequence logos, discovers motifs using DREME, calculates distances between elements, and clusters results. The main task is to process and visualize sequence data for m...
def process(): if config.scanRBP: make_scanRBP() plot_scanRBP() make_logos() dreme() make_distance() cluster()
def updateBranchList(): fetchOrigin() # Reset branch list local_branch_names.clear() remote_branch_names.clear() # Get local branch list for head in repo.heads: if head.name != 'HEAD': local_branch_names.append(head.name) # Get remote branch list for ref in origin.refs: if ref.name != o...
This code creates a GUI for managing GitHub branches using imgui_python. It fetches remote branches, displays local/remote branch dropdowns, allows deletion of selected branches, inputs commit messages/new branch names, and provides buttons to create branches and push changes. The loop function handles UI rendering and...
def loop(): imgui_python.ImGui_SetNextWindowSize(ctx, 700, 500, imgui_python.ImGui_Cond_FirstUseEver()) visible, open = imgui_python.ImGui_Begin(ctx, 'GitHub Reaper', True) if visible: if imgui_python.ImGui_Button(ctx, 'Fetch Origin'): updateBranchList() reapy.show_message_box('Successfully fetch...
def get_data(self,path) : data = pd.read_csv(path) new_column, y=self.sentiment_to_int(data['Sentiment']) data['label']=new_column data=data[self.columns] data=data.rename(columns={"Utterance":"review"}) return data,y def regroup_data(self,df1,df2) : frames = [df1...
The main task of the code is to train a machine learning model using K-fold cross-validation (5 splits) on combined training and test data. It tokenizes text reviews, trains the model iteratively for each fold, evaluates performance metrics, records elapsed time, and saves results and model weights. The process include...
def train_model(self) : test_data,y_test=self.get_data(self.ver_path) train_data,y_train=self.get_data(self.train_path) full_data=self.regroup_data(train_data,test_data) target_data=np.concatenate((y_train, y_test)) # Define the K-fold Cross Validator kfold = KFold(n_sp...
def findPose(self, fullpath): span = re_pose.search(fullpath).span() camPos = list(fullpath[span[0]+1:span[1]-1]) camPos.insert(2,'_') camPos = ''.join(camPos) #get 01_0 like string return self.cameraPositions[camPos][0] def load_image(self, filename): """ ...
The main task of the code is to generate a batch of test images and their corresponding features (eyes, nose, mouth) for model evaluation. It optionally filters data by pose, ensures randomness, and returns arrays of images, features, and labels (if not in testing mode), enabling efficient batch processing during model...
def test_batch(self, test_batch_size=100,Random = True, Pose = -1): test_batch_size = min(test_batch_size, len(self.indices_test)) images = np.empty([test_batch_size, IMAGE_SIZE, IMAGE_SIZE, 3]) eyel = np.empty([test_batch_size, EYE_H, EYE_W, 3], dtype=np.float32) eyer = np.empty([test_b...
def findPose(self, fullpath): span = re_pose.search(fullpath).span() camPos = list(fullpath[span[0]+1:span[1]-1]) camPos.insert(2,'_') camPos = ''.join(camPos) #get 01_0 like string return self.cameraPositions[camPos][0] def updateidx(self): if self.random: ...
This function constructs a batch of images and corresponding labels/masks for machine learning tasks. It initializes arrays for images, labels, masks, and auxiliary data (pose, identity, landmarks), then populates them by loading data from files. It handles pose range filtering, generates masks if enabled, and includes...
def next_image_and_label_mask_batch(self, batch_size, imageRange=-1,imageRangeLow = 0, labelnum=None): """Construct a batch of images and labels masks. Args: batch_size: Number of images per batch. shuffle: boolean indicating whether to use a shuffling queue. Returns: nd...
def partRotator(self, images, name, batch_size=10, reuse=False): #HW 40x40, 32x40, 32x48 with tf.variable_scope(name) as scope: if reuse: scope.reuse_variables() c0 = lrelu(conv2d(images, self.gf_dim, d_h=1, d_w=1, name="p_conv0")) c0r = resblock(c0, n...
This code defines a neural network model for facial image generation/reconstruction using an encoder-decoder architecture. It processes input images with/without code maps, resizes inputs/labels, and incorporates facial part discriminators (eyes, nose, mouth). The model uses GANs with adversarial loss, identity classif...
def build_model(self): #hold all four #Note: not true, if WITHOUT_CODEMAP is true, then here is pure images without codemap and 3 channels #mirror concatenate mc = lambda left : tf.concat_v2([left, left[:,:,::-1,:]], 3) self.images_with_code = tf.placeholder(tf.float32, [self.ba...
def sigmoid(x): return 1 / (1 + np.exp(-x)) def cross_entropy(y, output): return - y*np.log(output) - (1 - y) * np.log(1-output) def error_term(x,y,y_hat): return (y-y_hat)*sigmoid_prime(x)
The code trains a single-layer neural network using gradient descent. It initializes weights, computes predictions with a sigmoid activation, calculates cross-entropy loss, updates gradients via error terms, and adjusts weights over epochs. The learning rate scales weight updates, averaging gradients across all records...
def train_nn(features, label, epochs, learnrate): np.random.seed(42) n_records, n_features = features.shape # Initialize weights weights = np.random.normal(scale=1 / n_features**.5, size=n_features) del_w = np.zeros(weights.shape) for i in range(epochs): for x, y in zip(features.values, ...
def sigmoid(x): return 1 / (1 + np.exp(-x)) def output_error_term(y,y_hat): return (y-y_hat)*sigmoid_prime(y_hat) def hidden_error_term(out_et,w_h2o,h_out): return np.dot(out_et,w_h2o)*sigmoid_prime(h_out)
This code trains a two-layer neural network using gradient descent. It initializes weights, iterates through epochs, computes hidden/output layer activations with sigmoid, calculates error terms, updates weight deltas via backpropagation, and adjusts weights proportionally to the learning rate and average gradient. The...
def train_nn(features, label, epochs, learnrate,n_hidden): np.random.seed(42) n_records, n_features = features.shape # Initialize weights w_i2h = np.random.normal(scale=1 / n_features**.5, size=(n_features,n_hidden)) w_h2o = np.random.normal(scale=1 / n_features**.5, size=n_hidden) for i in rang...
def forward(self, image, image1, image2, image_level_label ,im_info, gt_boxes=None, ss_boxes=None, ss_boxes_rotate_1=None, ss_boxes_rotate_2=None, mode='TRAIN'): #print('forward ss_boxes ', ss_boxes.shape) self._image_gt_summaries['image'] = image self._image_gt_summaries['image_level_label'] = image_level_...
This function performs a training step by executing a forward pass, computing multiple loss components, backpropagating gradients via the provided optimizer, updating model weights, and generating summaries. It returns individual loss values and the summary for monitoring and logging during training.
def train_step_with_summary(self, blobs, train_op): #print(blobs.keys()) #print('ss_boxes', blobs['ss_boxes'].shape) self.forward(blobs['data'], blobs['data1'], blobs['data2'], blobs['image_level_labels'],blobs['im_info'], blobs['gt_boxes'], blobs['ss_boxes'], blobs['ss_boxes_rotate1'], blobs['ss_boxes_rota...
def get(self, x: int, y: int): index = self._index(x, y) return self._state[index] def _index(self, x, y): return y * self._board_size + x def check_winner(self): for cols in range(0, self._board_size): tiles_to_check = [self.get(x, cols) for x in range(0, self._board_size)] winner = self._c...
This method updates a tile's state at coordinates (x, y) to the given state if it was previously empty. It updates the internal state array, sends a network message to connected players (if not from the network and multiplayer is enabled), checks for a win condition, and ends the current turn.
def set(self, x: int, y: int, state: TileState, /, from_network=False): current_value = self.get(x, y) if current_value == TileState.EMPTY: index = self._index(x, y) self._state[index] = state if not from_network and self.multi_palyer_connection: self.multi_palyer_connection.send( ...
def insertion_sort(arr, columns): for imdb_sortedlist in range(1,len(arr)): index = imdb_sortedlist temp = arr[imdb_sortedlist] imdb_unsorted=imdb_sortedlist-1 while(imdb_unsorted>=0) and compare(arr[imdb_unsorted],temp,columns)>0: index = imdb_unsorted ...
The code reads a CSV file, extracts specified columns, and applies a selected sorting algorithm (insertion, selection, quicksort, heap, shell, or merge sort) to the data. It measures the execution time of the chosen algorithm, returns the time taken and the sorted data's first elements. The function supports six sortin...
def sorting_algorithms(file_path, columns, select): df= pd.read_csv(file_path).applymap(lambda x: x.strip() if isinstance(x, str) else x)#.apply(lambda y: y.str.strip() if y.dtype == "object" else y) #read imdb_dataset.csv data set using pandas library column_vals = [0]+ [df.columns.get_loc(column) for colu...
def inorder(self): """initiate inorder pass (needs function inorder2)""" inorder_list = [] return self.inorder2(self.root, inorder_list) def __init__(self): self.root = None def rebalance_helper(self, lyst): """Convert a sortd array or list to a BST""" if not lyst: ...
The main task of the code is to rebalance a binary search tree (BST) by reconstructing it from a sorted list generated via in-order traversal. The method resets the tree and uses a helper function to recursively build a balanced BST from the sorted elements, ensuring optimal height and performance.
def rebalance(self): """rebuild a BST with a sorted array or list""" lyst = self.inorder() self.__init__() self.rebalance_helper(lyst) return self
def _alert(msg): messagebox.showinfo(message=msg) def _save_images(dirname): images = config.get('images') if dirname and images: save_images(images) def _save_json(filename): images = config.get('images') if filename and images: save_json(images)
The main task of the code is to save images or their data in JSON format based on the selected method. It checks for available images, prompts the user to select a directory (for image files) or a filename (for JSON export), and executes the corresponding save operation using helper functions _save_images or _save_json...
def save(): if not config.get('images'): _alert('No images to save') return if _save_method.get() == 'img': dirname = filedialog.askdirectory(mustexist=True) _save_images(dirname) else: filename = filedialog.asksaveasfile(initialfile='images.json', filetypes=[('JSON',...
def countFifteensSingular(hand): calculationList = [] fifteens = 0 handVals = [] #take all values from the hand and add them to a separate list of values. for card in hand: try: handVals.append(int(card.value)) except ValueError: handVals.append(10) #m...
The function counts points for both player and computer hands, adds crib points, updates scores, and displays results. It checks for a win, handles scoring for fifteens, runs, pairs, and the crib, with logic varying based on whose turn it is.
def countPoints(hand1, hand2, topCard, cribCards): global playersTurn global computerScore global playerScore hand1.append(topCard) hand2.append(topCard) #create two variables used to count the points made by both the player and the computer this round. lastPlayerScore = playerScore...
def get_data(num_examples=500): fptr = open('cluster_data.csv', 'r') data = [] for line in fptr.readlines(): line = line.strip().split(',') data.append([int(line[0]), int(line[1])]) data = random.sample(data, num_examples) data = np.array(data) return data def normalize(data): ...
The main task of the code is to perform hierarchical clustering on normalized data using complete linkage. It retrieves and normalizes dataset, computes pairwise distances, applies hierarchical clustering with 'complete' linkage, and prints the resulting clusters.
def main(): data = get_data(50) data = normalize(data) # data = np.array([[1.5, 2.0], # [3.0, 1.0], # [3.5, 2.5], # [1.0, 0.5], # [2.5, 2.0]]) distance_matrix = create_distance_matrix(data) clusters = hierarchical_...
def init_display(): logging.info("Running Plex Display") EPD.init() EPD.Clear(0xFF) logging.info("Clearing display...") image = Image.new("1", (EPD.height, EPD.width), 255) return image, ImageDraw.Draw(image) def draw_status_info(draw, status): if status: draw.text((140, 4), f"Stream...
The code draws status information on an e-paper display, checking if Plex is online/offline, displaying activity status, update checks, and a timestamp. It initializes a display, updates text based on Plex's status, rotates the image, and renders it on an EPD screen.
def draw_text(plex): image, draw = init_display() draw.rectangle([(0, 0), (242, 44)], outline=0) if plex.check_if_alive(): draw.text((5, 5), "Plex Online", font=FONT22, fill=0) status = plex.get_activity() draw_status_info(draw, status) check_updates(draw, plex) else: ...
def CreateObjectiveFunction(self): fileobj = open(self.filename_model, "a") fileobj.write("Minimize\n") eqn = [] for i in range(0,self.WORD_LENGTH): eqn.append("x" + "_" + str(self.Round) + "_" + str(i)) for j in range(0,self.WORD_LENGTH): eqn.append("y" + "_" + str(self.Round) + "_" + str(j)) temp = ...
The code defines a method `MakeModel` that constructs an optimization model by sequentially creating an objective function, adding constraints, initializing the model, and declaring binary variables. This method orchestrates the setup of a mathematical programming model, likely for solving optimization problems, by int...
def MakeModel(self): self.CreateObjectiveFunction() self.CreateConstraints() self.Init() self.BinaryVariable()
def load_data(self): logging.info("Loading data...") # load data self.Dataset = self.DATASET.DataSet(self.path + "data/", self.dataset_params) self.Dataloader = DataLoader(self.Dataset, batch_size=int(self.train_params["batch_size"]), ...
The code trains a machine learning model using cross-validation with multiple repeats. It initializes random seeds for reproducibility, iterates over repeats and folds, trains the model for each fold, collects performance metrics, and logs detailed results per fold, repeat, and overall summary. The goal is to evaluate ...
def train_and_save(self): logging.info("Start training") np.random.seed(self.seed) torch.manual_seed(self.seed) torch.cuda.manual_seed(self.seed) self.seeds = np.random.randint(0, 1024, self.num_repeat) list_results_all = [] list_results_per_fold = [] ...
def initEventCuts(self): self.haveEE = self.brackets('ev.nEE > 0') self.haveMM = self.brackets('ev.nDMDM > 0') self.highPU = self.brackets('ev.nPV > 22') self.medPU = self.brackets('ev.nPV > 14 and ev.nPV < 23') self.lowPU = self.brackets('ev.nPV < 15') self.goodPV = self.brackets...
The code initializes an object by setting up event cuts, electron-electron cuts, and muon-muon cuts, likely for data filtering or analysis in particle physics experiments.
def __init__(self): self.initEventCuts() self.initEECuts() self.initMMCuts()
def convert_materials(scene_input): mat_inputs = scene_input["bsdfs"] mat_outputs = [] for mat_input in mat_inputs: mat_output = convert_material(mat_input) #elif mat_type != "null": # mat_output = convert_disney(mat_input) if mat_output: mat_outputs.append(ma...
The main task of the code is to convert a JSON scene file into a structured output JSON file by processing materials, entities, camera, and renderer data. It reads input from command-line arguments, validates file paths, applies conversion functions to transform the input scene data, and writes the result to a specifie...
def main(): fn = argv[1] if fn == None: print('convert file is None, ') return fn_output = argv[2] if len(fn) == 0: return if len(fn_output) == 0: fn_output = "liangairan_scene" print('converting file:' + fn) parent = os.path.dirname(fn) output_fn = os....
def download_remote_samples(namespace, workspace): """Download remote samples from Firecloud Writes: - remote_samples.txt: samples in FC """ res = firecloud_api.get_entities_tsv(namespace, workspace, "sample") with open('remote_files/remote_samples.txt', 'w') as outfile: outfile.writ...
The function `update_cohorts` updates cohort sample sets across batches by first removing existing samples/pairs in a remote system to avoid duplication. It prepares new cohort data, filters out pre-existing entries, and uploads cleaned samples, pair sets, and tumor data to the specified workspace. Key steps include do...
def update_cohorts(latest_tsca_id, namespace, workspace, google_bucket_id): """Update cohorts (sample sets that span multiple batches) This function needs to be called once for a new batch. Before updating a cohort sample set, we need to remove samples that already belong to that cohort remotely, because i...
def prepare_patients_for_metadata_export(path_to_samples_info, tsca_id): """Create participant entities file for Firecloud. Patients need to exist before you can upload their respective samples Args: path_id: path to file ending in {}.import_samples.txt tsca_id: tsca id Saves: ...
The function prepares batch metadata for Firecloud upload by orchestrating four sub-processes: patient data, batch sample sets, individual batch samples (with Google bucket ID), and cohort data (using batch info paths and Google bucket ID). It consolidates metadata from specified files into structured formats required ...
def prepare_all_data_for_metadata_export(tsca_id, path_to_batch_samples_info, paths_to_batches_info, google_bucket_id): """Prepare all batch metadata for uploading to Firecloud Args: - path_to_batch_samples_info: path to info on batch samples """ prepare_patients_for_metadata_export(path_to_...
def inputPlayerLetter(): player = input("Do you want to be X or O?") if player == 'x': EmptyList = ['X','O'] else: EmptyList = ['O','X'] return EmptyList # Have test case - check_player_letter.py <input_player_letter.txt # Function inputPlayerLetter() lets the player type wh...
The code implements a m-n-k game where players take turns placing their marks on an m×n board, aiming to form a line of k consecutive symbols. It validates input for board dimensions and k, alternates between player and computer turns, checks for wins/ties, and allows replay. The game includes functions for board drawi...
def main(): print("Welcome to m-n-k game!") while True: m = int(input("Enter number of rows, m : ")) n = int(input("Enter number of columns, n : ")) k = 0 print("k should be greater than 2 and should not be greater than m or n") while k <= 2 or k > m or k > n: ...
def rateDo(rate, tick): #utility function to trigger events at expected rate return not(tick % (mainRate/rate)) def predictionStep(self, acc, gyro, dt): # use IMU data to predict state forward d = gyro*dt/2 # build A (linearised dynamics) A = np.zeros((9,9)) A[0:3,0:3] =...
The function `runEKF` manages the Extended Kalman Filter (EKF) by executing prediction and correction steps at specified rates. It triggers prediction using acceleration/gyro data, correction for z-range measurements, and flow corrections based on pixel count and gyro data. If updates occur, it finalizes the state, add...
def runEKF(self, acc, gyro, pxCount, zrange): # main function called by main loop that takes care # of all the timings of the kalman filter steps update = False if rateDo(predictionRate, self.tick): self.predictionStep(acc,gyro,predDT) update = True if ...
def pwdToForcesMap(self, u): # wrapper for mapping: # pwd -> rotor thrust -> rotor speed -> body forces if self.config=="plus" : # plus configuration return self.omegaToThrustPlusConfig(self.thrustToOmega((self.pwmToThrust(u)))) else : # cross configuration return self.omegaToThrustCross...
The code simulates a dynamic system's state evolution until a specified time using motor inputs. It converts inputs to forces, solves ODEs via RK45 integration, updates the system's time and state, computes rotation matrices and acceleration (including gravity), and returns the final unwrapped state. Key steps: input v...
def simulate(self, until, u): # input : until: absolute time until which the simulation should last # u: PWD inputs to the 4 motors # output: returns unwrapped state if until<self.currentTime : # check time input sys.exit("are you sure you want to simulate backward in time?") Tbar = self.pwdToF...
def initPopulation(parameterList): '''Creates an inital population list of elephants using the list of chosen population parameters and using the newElephant method to create the carrying capacity amounts of elephants''' #Initializes population populationList = [] #Amount of elephants to create ...
The function `runSimulation` simulates an elephant population over a specified number of years using given parameters. It initializes the population, applies population control, and iterates yearly to update the population while recording results. If the population exceeds twice the carrying capacity or drops to zero, ...
def runSimulation(parameters): '''This function uses the given population parameters to run a simulation given the population parameters number of years and uses every created function to simulate an elephant population and their change over a course of the given years ''' #Sets a variable to the popul...
def advance(self): self.tok_idx += 1 if self.tok_idx < len(self.tokens): self.current_tok = self.tokens[self.tok_idx] return self.current_tok def expression(self): return self.bin_op(self.term, ('PLUS', 'MINUS'))
The code parses expressions by handling unary operations, integers, floats, and parentheses. It constructs AST nodes (UnaryOpNode, NumberNode) or returns syntax errors for invalid input, using a ParseResult to track success/failure and current token position.
def factor(self): res = ParseResult() tok = self.current_tok if tok.type in ('PLUS', 'MINUS'): res.register(self.advance()) factor = res.register(self.factor()) if res.error: return res return res.success(UnaryOpNode(tok, factor)) elif to...
def clone_p2p_offer(self, offer_id, amount=None): o = self.get_own_p2p_offer_by_id(offer_id) if amount is None: amount = o['data']['availableVolume']['amount'] else: amount = round(amount, 9) if o['data']['type'] == 'SALE': pd = [p['id'] for p in o['...
The main task of the code is to replace an existing P2P offer by cloning it with an optional amount adjustment, deactivating the original offer, and activating the new cloned offer. It ensures seamless replacement by handling both deactivation and activation of P2P offers while returning the updated offer data.
def replace_p2p_offer(self, offer_id, order_type, amount=None): new_offer = self.clone_p2p_offer(offer_id, amount) self.p2p_offer_deactivate(offer_id, order_type) self.p2p_offer_activate(offer_id=new_offer['data']['id'], offer_type=new_offer['data']['type']) return new_offer
def get_own_p2p_offer( self, tag: str = None, offer_id: int = None, offer_type=None, status: str = 'ACTIVE' ) -> OwnOffer: """ :param offer_type: PURCHASE | SALE :param offer_id: :param tag: example 'AS-00057073' :p...
The function updates a P2P offer's value by either deactivating a 'SALE' offer and using the user's available TON balance or recalculating the amount for non-sale offers with added fees. It replaces the existing offer with the new value and returns the updated offer data as an OwnOffer object.
def update_p2p_offer_value(self, offer_id, add_amount=None): o = self.get_own_p2p_offer(offer_id=offer_id) if o.type == 'SALE': self.p2p_offer_deactivate(o.id, o.type) amount = self.get_user_balance('TON')['available_balance'] else: amount = o.availableVolume...
def parse_args(): parser = argparse.ArgumentParser() parser.add_argument( "-c", "--checkpoint", dest="checkpoint", nargs="+", required=True, help="Path to the checkpoint to be used for the evaluation", ) parser.add_argument( "-b", "--batch-...
The code evaluates multiple pre-trained models on specified datasets using beam search, comparing their performance metrics (best, mean, highest probability) across checkpoints. It loads encoder/decoder models, processes test data, computes results, and formats them into markdown tables for comparison, outputting detai...
def main(): options = parse_args() is_cuda = use_cuda and not options.no_cuda hardware = "cuda" if is_cuda else "cpu" device = torch.device(hardware) for dataset_name in options.dataset: results = {"best": {}, "mean": {}, "highest_prob": {}} for checkpoint_path in options.checkpoint...
def calculate_score(self, state, player): horizontal = 0 vertical = 0 rightDiagonal = 0 leftDiagonal = 0 for i in range (8): for j in range (8): # get no of connected 4 horizontally for the current player if j in range (0,5): ...
This function handles a turn-based game by updating player scores and move counts, switching turns between human and computer players, and displaying win/loss/tie outcomes when all 64 moves are completed. It updates UI elements, tracks game state, and triggers appropriate result screens based on final scores.
def take_turns(self): if self.turn == HUMAN: turns = int(self.redTurns.text()) + 1 self.redTurns.setText(str(turns)) score = self.calculate_score(self.gridScene.filledCheckers, self.turn) self.redScore.setText(str(score)) self.user.setStyleSheet(u"border-ra...
def encode_string(args, word): word = word.upper() # sample length result = [0] * args.max_word_length * args.one_char_length cur_idx = -1 for character in word: number_value = ord(character) - ord('A') + 1 binary_value = bin(number_value) for i in range(args...
This code trains a neural network to classify words into predefined categories using both positive and negative samples. It constructs a model with input, hidden, and output layers, trains it on weighted data, and evaluates performance by predicting labels for test words, displaying metrics like error, accuracy, and re...
def main(args: argparse.Namespace) -> np.ndarray: # Train data words = [ "hello", "world", "neurons", "apple", "biology", "yes", ] number_of_class = len(words) train_x = [encode_string(args, x) for x in words] # Positive samples have 4 tim...
def readfile(filename): results = [] fp = open(filename, "r") for line in fp.readlines(): myline = list(map(int, line.split(" ")[:-1])) results.append(myline[:]) fp.close() return results def get_all_filenames(directoryname): files = filter( lambda x: x[-4:] == ".dat" and...
The function processes files from the "data" directory, applying different models (c_cat/k_cat for category, c_rec/k_rec for recommendation) based on a condition in each file's data. It generates DataFrames for each file's results, concatenates them separately into 'cat' and 'rec' groups, then combines both groups into...
def get_exemplar_results(c_cat, k_cat, c_rec, k_rec): allres = {fn: readfile(fn) for fn in get_all_filenames("data")} cat = [] rec = [] for filename in allres.keys(): if allres[filename][-1][1] == 0: res = exemplarmodel(filename, c_cat, k_cat) cat.append(create_df(filenam...
def readfile(filename): results = [] fp = open(filename, "r") for line in fp.readlines(): myline = list(map(int, line.split(" ")[:-1])) results.append(myline[:]) fp.close() return results def get_all_filenames(directoryname): files = filter( lambda x: x[-4:] == ".dat" and...
The function `get_prototype_results` processes data files by applying two distinct model configurations (`c_cat`, `k_cat` for "cat" tasks and `c_rec`, `k_rec` for "rec" tasks) based on a conditional check in each file's data. It reads all files from "data," categorizes them into "cat" or "rec" groups, generates results...
def get_prototype_results(c_cat, k_cat, c_rec, k_rec): allres = {fn: readfile(fn) for fn in get_all_filenames("data")} cat = [] rec = [] for filename in allres.keys(): if allres[filename][-1][1] == 0: res = prototypemodel(filename, c_cat, k_cat) cat.append(create_df(filen...
def parse_state(a_file): with open(a_file) as state_file: f = lmap(lambda x: x.strip(), state_file.readlines()) no_states = int(f[0]) state_list = [f[i] for i in range(1, no_states + 1)] parse = { ## The number of states 'count': no_states, ## states[i] is the readable ...
The main task of the code is to compute the top-k most probable state sequences for each query using the Viterbi algorithm on a given Hidden Markov Model (HMM). It parses state, symbol, and query data, then applies Viterbi with caching to efficiently find top-k paths, returning all valid sequences across queries.
def top_k_viterbi(State_File, Symbol_File, Query_File, k): state = parse_state(State_File) symbol = parse_symbol(Symbol_File, state) query = parse_query(Query_File, symbol) config = { 'state': state, 'symbol': symbol, 'k': k, 'rules': [] } ret = [] for q in...
def parse_state(a_file): with open(a_file) as state_file: f = lmap(lambda x: x.strip(), state_file.readlines()) no_states = int(f[0]) state_list = [f[i] for i in range(1, no_states + 1)] parse = { ## The number of states 'count': no_states, ## states[i] is the readable ...
This function decodes queries using a state machine and Viterbi algorithm. It parses state, symbol, and query data, then generates decoding paths for each query by creating a cache, unwinding top-k sequences, and returning the results. The process leverages predefined rules and probabilistic state transitions to resolv...
def advanced_decoding(State_File, Symbol_File, Query_File): state = parse_state(State_File) symbol = parse_symbol(Symbol_File, state) query = parse_query(Query_File, symbol) config = { 'state': state, 'symbol': symbol, 'k': 1, 'rules': gen_rules() } ret = [] ...
def viterbi_make_cache(state_data, symbol_data, observations, k): ## We need k paths, so we extend the matrix to be of size k. ## Observations +2 gives us initial and final state ## The final axis is: ## PREVIOUS_STATE - The state we came from to achieve this result ## PREVIOUS_KNESS - Are we most...
The function performs top-k Viterbi decoding on a query, generating the top k probable state sequences for each query element. It uses a cache to store intermediate results, unwinds the top k paths from the cache, and combines them into a list of sequences. The process iterates over each query, constructs Viterbi paths...
def top_k_viterbi(state, symbol, query, k): ret = [] for q in query: cache = viterbi_make_cache(state, symbol, q['symbols'], k) tmp = lmap(lambda i: top_k_cache_unwind(cache, len(q['symbols']) + 1, state['states'].index('END'), i, k), range(k)) tmp = lmap(lambda x: x[0] + [...
def align_force_to_beam(node1, node2, force_global): """Converts beam result forces to beam coordinates Beam nodes are aligned to global coordinates, but we care about the axial and shear forces This takes the end nodes of the beam and the force in global CS and converts the force to axial tension ...
This method loads beam forces from the solver, converts them to local coordinates aligned with the beam axis, and calculates axial and shear forces. It retrieves global forces for both nodes, applies coordinate transformation using node positions, stores local forces, and computes axial (tension/compression) and total ...
def _load_and_compute_forces(self): """Load beam forces, convert to local coordinates, axial and shear Sets: forces_global: [xi, yi, zi, xj, yj, zj] in solver units global coordinates forces: [xi, yi, zi, xj, yj, zj] in solver units with Z axial axial_force: Force in...
def _load_mesh_data(self): element_id = self.solver_data.GetObjectData(self.bolt.ui_beam).ElementId self.element = self.mesh.ElementById(element_id) self.nodes = self.element.Nodes def _set_grip_lengths(self): """Set the grip_length and grip_length_nodal in [mm] Computes the `gri...
The code initializes a class to process bolt analysis by loading mesh data, solver parameters, and nodal forces, then computes grip lengths and runs bolt calculations using provided analysis data and time-step information.
def __init__( self, bolt, analysis, mesh, elemental_nodal_forces, analysis_time_step ): self.bolt = bolt self.analysis = analysis self.solver_data = analysis.Solution.SolverData self.mesh = mesh self.elemental_nodal_forces = elemental_nodal_forces self.analysi...
def process_file(file_info): reformatted_comments = extract_comments(file_info) return reformatted_comments def combine_data_to_list(data1, data2): combined = [] for comment in data1: row = [comment.time_value, comment.time_stamp, comment.label, comment.get_comments()] combined.append(ro...
The main task of the code is to merge two transcripts by aligning their timestamps using specified time offsets, combine the synchronized data, sort it chronologically, and export the merged result as a unified dataset with combined labels.
def merge_transcript(file1, file2, file1_label, file2_label, time_offset1, time_offset2): # file = file_name e.g "carlsen.csv" # label = a name for the data in the file "carlsen" # time_offset = this is value is used to sync the two transcripts so comments made at the same appear together. file1_data ...
def create_note(): def generate_note() -> entity.Note: return entity.Note( music_block.x + random.randint(-cell_size, cell_size), music_block.y + random.randint(-cell_size, cell_size), ) def check_note(note: entity.Note): for r_ent in entity.rect_entities: if r_ent.b_to_crt() == note.to_bcrt(): re...
This code defines a game loop using Pygame, handling events like quitting, mouse movement, and key presses for player movement (WASD/arrow keys). It triggers note creation and power-up checks every second, manages a gravity superpower activation via the 'G' key, updates the game state, renders the screen, and maintains...
def game(): global mouse_pos, gravity_superpower_runned, gravity_superpower_ready gameRunning = True while gameRunning: for event in pygame.event.get(): if event.type == pygame.QUIT: gameRunning = False if event.type == ONE_SECOND: create_note() check_sp() if event.type == pygame.MOUSEMOTION: ...
def can_proceed_to_next_with_charging_option(self, truck, current_location, next_location, charging_stations, temperature): """ Check if the truck can proceed to the next location and then reach a charging station if needed. """ # Calculate distance from the current location to the next ...
This function calculates the total cost of a truck's route by evaluating battery consumption, charging station detours, and traffic delays. It iterates through each route segment, checks battery sufficiency, adds detour costs for charging if needed, updates battery levels, and accumulates distance/time costs. The resul...
def calculate_route_cost(self, route, charging_stations, temperature): """ Calculate the cost of a given route considering the need to charge the truck. """ total_cost = 0 total_time = 0 visited_charging_stations = [] truck = Truck(400, 0.8) # Adjust as per your ...
def can_proceed_to_next_with_charging_option(self, truck, current_location, next_location, charging_stations, temperature): """ Check if the truck can proceed to the next location and then reach a charging station if needed. """ logging.info("Checking if truck can proceed to next with ch...
The main task of the code is to calculate the total route cost for multiple trucks based on their routes and available charging stations, considering battery constraints, detours to charging stations when needed, and traffic delays. It tracks visited charging stations and returns the accumulated distance cost along wit...
def calculate_route_cost(self, routes, charging_stations): total_cost = 0 visited_charging_stations = [] for truck_id, route in routes.items(): truck_cost = 0 truck = Truck(capacity_kWh=300, consumption_rate_kWh_per_km=0.2) logging.info(f"Calculating route cos...
def generate_initial_routes(self): initial_population = [] for _ in range(self.population_size): truck_assignments = assign_customers_to_trucks(self.num_trucks, self.locations.copy()) individual_routes = {} for truck_id, truck_locations in truck_assignments.items(): ...
The code implements a genetic algorithm to optimize route planning. It initializes a population of routes, iteratively evaluates their fitness, selects individuals via tournament selection, applies crossover and mutation to generate new routes, and updates the population over generations. The process continues until th...
def run(self): # Initialize the population start_time = time.time() population = self.generate_initial_routes() process = psutil.Process() for generation in range(self.generations): # Evaluate the fitness of each individual in the population fitness_score...
def create_graph(self): """ Create a graph representing the locations with edges weighted by the road distance between locations. """ geocoded_locations = self.geocode_locations() self.graph = nx.Graph() for start in geocoded_locations: for end in geo...
The main task of the code is to optimize routes using Ant Colony Optimization (ACO). It constructs solutions iteratively, updates pheromone trails, tracks the best global solutions, and returns optimal routes alongside performance metrics like computation time and memory usage.
def optimize_routes(self): """ Perform the optimization process using Ant Colony Optimization. """ logging.info("Starting optimization...") start_time = time.time() process = psutil.Process() self.create_graph() pheromones = self.initialize_pheromone_trai...
def countries( df: pd.DataFrame, status: str | list[str], only: bool = False ) -> set[str]: """Returns set of countries for a given status only: Whether to return number of countries only having that status(es) """ df = initial_filter(df) statuses = [status] if isinstance(status, str) else stat...
The function `counts` computes and returns a dictionary of statistical metrics comparing today's and previous day's data, including counts of countries with confirmed/suspected/discarded cases, differences in case numbers, newly added countries, and travel history statistics. It calculates totals, unique country counts...
def counts(df: pd.DataFrame, prev_df: pd.DataFrame) -> dict[str, int]: """Return count variables from data df: Today's data file as a dataframe prev_df: Previous day's data file as a dataframe """ new_countries = sorted( countries(df, ["confirmed", "suspected"]) - countries(prev_df,...
def checklen(strings, n): if len(strings) != n: raise JcoTerminate(f"Should have {n} inputs, got {len(strings)}: {strings}") def tab(rows, **kwargs): return tabulate(rows, tablefmt=Format.value, headers=["", "Dec", "Hex", "Bin"]) def _one(string, *, name="A"): a = Int(string, name) if NBits.valu...
The function processes input arguments, validates their count, invokes an internal function to retrieve data rows, and constructs a table from these rows using a `tab` object.
def one(*args, **kwargs): checklen(args, 1) return tab([data.row() for data in _one(*args, **kwargs)])