dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def unzip_file(self, file_path): path = "" with zipfile.ZipFile(file_path, 'r') as zip_ref: all_items = zip_ref.namelist() for item in all_items: split_path = item.split("/") if len(split_path) == 2 and '' in split_path: path = ...
The code traverses directories starting at `self.root`, filters out specific subdirectories, processes files by checking if they are ZIP archives (unzipping them if so), reads non-hidden files, and classifies/moves their content. It also aggregates content from directories and classifies/moves them, stopping after the ...
def sort_files(self): for dirpath, dirnames, filenames in os.walk(self.root): dirnames[:] = [d for d in dirnames if os.path.join(dirpath, d) not in self.paths_of_course_folders and not d.startswith('.') and not d.startswith('#')] for filename in filenames: full_path = os....
def revert_to_commit(self, filepath, commit_hash): full_path = self._full_path(filepath) try: self.repo.git.checkout(commit_hash, full_path) print(f"Reverted {filepath} to commit {commit_hash}") return 1 except Exception as e: print(f"Failed to rev...
This function processes commands to perform actions like reverting a file to a specific commit, sorting files, or adding folders. It splits the input command, checks the first word to determine the action, and executes corresponding methods. Error handling catches exceptions, returning 0 on failure, while success retur...
def process_command(self, command): try: commands = command.strip().split() if commands[0].lower() == 'revert' and len(commands) == 3: filepath, commit_hash = commands[1], commands[2] return self.revert_to_commit(filepath, commit_hash) elif com...
def process_command(self, command): try: commands = command.strip().split() if commands[0].lower() == 'revert' and len(commands) == 3: filepath, commit_hash = commands[1], commands[2] return self.revert_to_commit(filepath, commit_hash) elif com...
This code handles file writing operations, processes commands if the file is a command file, and manages synchronization with Google Drive for non-special files. It writes data to a file, checks for specific file types to skip processing, identifies sorted directories, and either updates Google Drive or moves the file ...
def write(self, path, buf, offset, fh): if path == self.command_file: # Process command written to the command file. If command processing returns True, return buffer length; otherwise, -1. return len(buf) if self.process_command(buf.decode()) else -1 else: # Positio...
def readFile(fileName): '''Reads in a GEDCOM file and prints input and output lines''' current_tag = '' current_date = '' Lines = [] try: file = open(fileName, 'r') for line in file: temp = '-->'+ line #print('-->', line, end='') line = line.strip(...
The main task of the code is to read input data from a file, process it to generate an "individuals" table, and create a "families" table, likely for organizing and displaying structured information about individuals and their family relationships.
def main(): readFile(INPUT_FILE) individualsTable() familiesTable()
def preprocess_image(self, batched_inputs): """ Normalize, pad and batch the input images. """ images = [self.normalizer(x["image"].to(self.device)) for x in batched_inputs] images = ImageList.from_tensors(images, self.size_divisibility) images_whwh = list() for ...
This code processes input data through a neural network for object detection or similar tasks. It handles both training and inference modes: during training, it extracts features, prepares targets, generates predictions, and computes losses using a criterion. In inference, it performs diffusion sampling to generate res...
def forward(self, batched_inputs, k=0, do_postprocess=True): """ Args: batched_inputs: a list, batched outputs of :class:`DatasetMapper` . Each item in the list contains the inputs for one image. For now, each item in the list is a dict that contains: ...
def reset(self, start_cell=(0, 0, 0)): """ Reset the maze to its initial state and place the agent at start_cell. :param tuple start_cell: here the agent starts its journey through the maze (optional, else upper left) :return: new state after reset """ print("RESET CALLED...
The code simulates a single game where the model predicts the next move. It initializes the game state, iterates up to 20 steps, and returns the final state, reward, and status (WIN/LOSE) once the game concludes.
def play(self, model, start_cell=(0, 0, 0)): """ Play a single game, choosing the next move based a prediction from 'model'. :param class AbstractModel model: the prediction model to use :param tuple start_cell: agents initial cell (optional, else upper left) :return Status: ...
def set_xticks(axis, ticks_loc: np.ndarray, ticks: t.Union[np.ndarray, list] = None, label: str = ''): axis.set_xticks(ticks_loc) if ticks is None: ticks = ticks_loc.astype(int) axis.set_xticklabels(ticks) if label: axis.set_xlabel(label) def set_yticks(axis,...
This function visualizes attention masks from AG-UNet by plotting input data, intermediate attention gate activations (with masks), and output data in a vertical arrangement. It converts tensors to NumPy arrays, averages channels if needed, creates a grid of subplots, and overlays attention masks as heatmaps on corresp...
def plot_attention_masks(self, tag: str, inputs: torch.Tensor, outputs: torch.Tensor, gate_inputs: dict, gate_masks: dict, step: int = 0, ...
def normalize(inputs: np.ndarray): ''' normalize array x to [0, 1] ''' return np.maximum(inputs, 0) / np.max(inputs) def set_xticks(axis, ticks_loc: np.ndarray, ticks: t.Union[np.ndarray, list] = None, label: str = ''): axis.set_xticks(ticks_loc) if ticks is None: ...
The main task of the code is to visualize Grad-CAM heatmaps by overlaying them on input images. It converts tensors to NumPy arrays, generates heatmaps using a colormap, superimposes them on images with transparency, adds colorbars, and saves the visualizations under a specified tag. The function handles image normaliz...
def plot_gradcam(self, tag: str, images: torch.Tensor, cams: torch.Tensor, titles: t.List[str] = None, step: int = 0, mode: int = 1): if len(images.shape) == 4: images = torch.mean(images, dim=1) ...
def order_flowers(intent_request): """ Performs dialog management and fulfillment for ordering flowers. Beyond fulfillment, the implementation of this intent demonstrates the use of the elicitSlot dialog action in slot validation and re-prompting. """ logger.debug(get_slots(intent_request)) ...
The code routes user intents to corresponding handler functions (e.g., OrderFlowers, Greeting) based on the intent name. If the intent is unsupported, it raises an exception. It logs intent details for debugging and ensures proper workflow execution by dispatching requests to appropriate business logic functions.
def dispatch(intent_request): """ Called when the user specifies an intent for this bot. """ logger.debug('dispatch userId={}, intentName={}'.format(intent_request['userId'], intent_request['currentIntent']['name'])) intent_name = intent_request['currentIntent']['name'] # Dispatch to your bot...
def embedding_layer(samples): dict_vector = [] vec_array = [] for element in samples: if element in dict_array: vec_array.append(dict_array[element]) else: vec_array.append(np.random.randn(50)) for each_element in vec_array: for each_vector in each_elemen...
This code trains a neural network model using batch processing. It performs forward and backward passes to update model parameters, computes loss, and evaluates model performance on a validation set every 20,000 samples. The function returns a list of validation loss values recorded during training.
def train(train_data, train_labels, valid_data, valid_labels): loss_values = [] for epoch in range(number_of_epochs): index = 0 # for each batch for data, labels in zip(train_data, train_labels): # Same thing about [hidden_layers] mentioned above is valid here also ...
def get_most_similar_user(self, userid, K_number_user, similarity_name): userid_in_rat = self.ratings.userid.unique().tolist() if similarity_name == 'pearson': print("===similarity is being calculated by pearson...===") similarity_score = [(self.pearson_correlation_score(userid...
The code generates item recommendations for a user by aggregating weighted ratings from similar users, calculating scores based on similarity, and returning top-K ranked items. It uses user similarity scores, historical item interactions, and weighted aggregation to prioritize items not previously rated by the target u...
def get_recommendations(self, userid, K_number_user, sim_name, topK = None): total = {} sum_similarity = {} list_user_nearest = self.get_most_similar_user(userid, K_number_user, sim_name) print("===recommending...===") for similarity_score, user_id in tqdm(list_user_near...
def get_most_similar_item(self, itemid, K_number_item, similarity_name): itemid_in_rat = self.ratings.itemid.unique().tolist() if similarity_name == 'pearson': print("===similarity is being calculated by pearson...===") similarity_score = [(self.pearson_correlation_score(itemid...
The code generates user recommendations for a given item by aggregating weighted ratings from similar items. It identifies the nearest items using similarity scores, collects user interactions with these items, and calculates weighted ratings for users who haven't interacted with the original item. These ratings are no...
def get_recommendations(self, itemid, K_number_item, sim_name, topK = None): total = {} sum_similarity = {} list_item_nearest = self.get_most_similar_item(itemid, K_number_item, sim_name) print("===recommending...===") for similarity_score, item_id in tqdm(list_item_nearest): #...
def HDL_driver(): hdl_value = input_HDL() answer = check_HDL(hdl_value) output_HDL_result(hdl_value, answer) return hdl_value def LDL_driver(): ldl_value = input_LDL() answer = check_LDL(ldl_value) output_LDL_result(ldl_value, answer) return ldl_value def total_cholesterol_driver(): ...
The code defines a menu-driven interface for a Blood Calculator, allowing users to select options for analyzing HDL, LDL, or Total Cholesterol. It runs in a loop, taking user input to trigger corresponding analysis functions or exit. The main task is to provide a user interface for cholesterol-related calculations.
def interface(): print("Blood Calculator") print("Options:") print("9 - Quit") print("1 - Analyze HDL") print("3 - Analyze LDL") print("5 - Analyze Total Cholesterol") keep_running = True while keep_running: choice = input("Enter choice: ") if choice == '9': r...
def transform_categorical_column_using_label_encoder(df: pd.DataFrame, column: str) -> tuple: if df[column].dtype != 'object': return df, None le = LabelEncoder() df[column] = le.fit_transform(df[column]) le_name_mapping = dict(zip(le.classes_, le.transform(le.classes_))) return df, le_na...
This function preprocesses multiple datasets by removing empty columns, applying numeric/categorical imputation and encoding, and using random oversampling for imbalanced data, then saving transformed datasets as pickle files.
def preprocessing_all_datasets(datasets_path: str, transformed_datasets_path: str, y_sampling_min_num: int = 10) -> None: """ Preprocessing all datasets in the given path: Removing columns where all samples' value is nan/empty Apply 'mean' nu...
def recent_readings_range_check(db, dev_id): """ Checks if the most recent readings (number is based on configuration value num_continuous_readings_to_check) are all within range or all outside of range for temp and humidity. Args: db: Connection to our MongoDB database ...
This function processes a POST request for sensor readings by storing the data in MongoDB, checking if recent temperature and humidity readings are within or out of predefined ranges, and triggering appropriate handling functions based on the range status of each parameter.
def post_readings(msg_body: ReadingsMsgBody): # Note the docstring is picked up by the OpenAPI doc tools, thus only include info # that makes sense from an API end-user's perspective. """ Process a POST request for resource 'readings'. """ if TRACE_MESSAGE_PROCESSING: print('==> post_rea...
def convert_list_to_ndarray(self): self.ndarray_of_smapled_points = np.array(self.sampled_points) def generate_kdTree(self): self.kd_tree = cKDTree(self.ndarray_of_smapled_points, leafsize=25) def create_roadmap(self, grid): # remember to clear self.list_of_n_neighbor (...
The main task of the code is to generate random sample points within a 250x250 grid while avoiding obstacles. It repeatedly selects random coordinates, checks if they collide with obstacles from the `patch` object, and appends valid points to `self.sampled_points` until reaching `self.total_sample_points`. After sampli...
def sample(self, patch, grid): sample_point = 0 while sample_point < self.total_sample_points: x = random.randint(1, 249) y = random.randint(1, 249) flag = False point = [x,y] for obstacle in patch.give_obstacle_info(): if point...
def full_fit(): f = Fitter() data = np.array(generate(10**5)) fmin, par, corrmtx = f.fitTo(data, init_full_fit()) print(fmin) print(corrmtx) print(' mass: {:>7.2f} +- {:>4.2f} MeV'.format(par[0]['value']*10**3, par[0]['error']*10**3)) print('width: {:>7.2f} +- {:>4.2f} MeV'.format(par[1]['...
The main task of the code is to execute different functions based on command-line arguments. If the argument is 'full', 'ucoh', or 'scan', it runs `full_fit()`, `uncoh_fit()`, or `noncoh_phase_scan()` respectively. If invalid, it prints an error. If no argument is provided, it defaults to running `uncoh_fit()`.)
def main(): """ """ if len(sys.argv) == 2: if sys.argv[1] == 'full': full_fit() elif sys.argv[1] == 'ucoh': uncoh_fit() elif sys.argv[1] == 'scan': noncoh_phase_scan() else: print('Wrong command') return else: ...
def get_data(filename: str): with open(filename, "r") as file: data = [line for line in file.readlines()] return data def solve_part1(data: list[str]) -> int: passports = get_passport_data(data) return sum([is_passport_valid_part1(pp) for pp in passports]) def solve_part2(data: list[str]) -> in...
The main task of the code is to read input data from "d4_input.txt", compute solutions for Day 4, Part 1 and Part 2, and print the results along with their respective execution times. It measures runtime for each part separately using time.perf_counter().
def main(): data = get_data("d4_input.txt") start = time.perf_counter() print("Solution Day 4, Part1:", end="\t") print(solve_part1(data), end="\t") print(f"Runtime: {time.perf_counter()-start:.3f} ") start = time.perf_counter() print("Solution Day 4, Part2:", end="\t") print(solve_par...
def get_data(filename: str) -> list[int]: with open(filename, "r") as file: data = [int(line) for line in file.readlines()] return data def solve_part1(data: list[int]) -> int: window_length = 25 # 5 for sample, 25 for input for i in range(window_length, len(data)): if not is_sum_of_num...
The main task of the code is to execute two solutions for a programming problem, reading input data from "d9_input.txt", calculating and printing the results for Part 1 and Part 2, along with their respective runtimes. It measures performance using `time.perf_counter()` and outputs solutions in a formatted manner.
def main(): data = get_data("d9_input.txt") start = time.perf_counter() print("Solution Day 9, Part1:", end="\t") print(solve_part1(data), end="\t") print(f"Runtime: {time.perf_counter()-start:.3f} ") start = time.perf_counter() print("Solution Day 9, Part2:", end="\t") print(solve_par...
def get_data(filename: str): with open(filename, "r") as file: data = [line.strip() for line in file.readlines()] return data def solve_part1(data: list[str]) -> int: id_max = 0 for boarding_pass in data: id_value = get_id(boarding_pass) id_max = max(id_max, id_value) return...
The main task of the code is to read input data from a file, execute two solutions (Part 1 and Part 2) for a problem, measure and display the runtime of each solution, and print the results with their respective execution times.
def main(): data = get_data("d5_input.txt") start = time.perf_counter() print("Solution Day 5, Part1:", end="\t") print(solve_part1(data), end="\t") print(f"Runtime: {time.perf_counter()-start:.3f} ") start = time.perf_counter() print("Solution Day 5, Part2:", end="\t") print(solve_par...
def highest_block_mongo(self): """Find the highest numbered block in the mongo database.""" highest_block = crawler_util.highestBlock(self.block_db) logging.info("Highest block found in mongodb:{}".format(highest_block)) if highest_block is None or highest_block == 0: return ...
The main task of the code is to synchronize MongoDB with the Ethereum blockchain by iterating through blocks from geth, fetching transaction data for each block, and storing it in MongoDB. It uses multiple threads to add blocks concurrently, continuously checks the highest blocks in both geth and MongoDB, and processes...
def run(self): """ Run the process. Iterate through the blockchain on geth and fill up mongodb with block data. """ logging.debug("Processing geth blockchain:") logging.info("Highest block found as: {}".format(self.max_block_eth)) # Make sure the databas...
def get_block_detail(self, block): if block: # Filter the block block["_id"] = int(block["number"], 16) # block["number"] = int(block["number"], 16) # block["timestamp"] = int(block["timestamp"], 16) # block["difficulty"] = int(block["difficulty"], 16)...
The function processes a blockchain block by retrieving its details, transactions, and receipts, then saves them individually if non-empty. It handles exceptions by retrying after a delay if an error occurs during processing.
def deal_block(self, block): try: if block: block, transactions, receipts = self.get_block_detail(block) if block is not None and len(block) > 0: self.save_block(block) if transactions is not None and len(transactions) > 0: ...
def logo(self): for i in external: try: nama=i.split('|')[0] followers=i.split('|')[1] following=i.split('|')[2] except: pass banner() print('') prints(Panel(f"""[white][[red]•[white]] [ye...
This code defines a menu-driven interface for account cracking/checking. It allows users to input targets, perform API searches, check account statuses from files, and display results (live/checkpoint) with details. Options include mass cracking, individual checks, and exiting.
def menu(self): self.logo() c=input(f' {P}[{M}•{P}] Pilih : {C}') if c=='': self.menu() elif c in ('1','01'): cetak(nel(f"""[white][[red]•[white]] Masukan jumlah target""")) m=int(input(f' {P}[{M}•{P}] Jumlah : {C}'));print('') cetak(nel(...
def get_frame_targets_from_time_targets(time_targets_ms, output_fps=24): """ Gets frame targets from a list of time targets Arguments: time_targets_ms: the timestamps of desired frames fps: the desired output frame rate Returns: frame indices associated with each timestamp """ ...
The code tests frame easing by adjusting frame timings in a video using exponential easing functions. It calculates retargeted frame times for specific intervals, applies easing transitions, removes off-pace frames, and saves the adjusted video. The goal is to demonstrate smooth time-warp effects, comparing original an...
def test_frame_easing(output_file="C:\\Users\\dcyoun\\Documents\\GitHub\\frame-playground\\output\\easing_test.avi"): """ Tests frame easing """ output_fps = 24 blend_frames = 1 video_duration_ms = 12000 start_time_ms = 1000 retarget_duration_before = 10000 retarget_duration_after = 5000 ...
def __SaveLocally(self, data: Description): # pragma: no cover dataset_id = DataSets.index(data.dataset.name) for item in data.items: worker_property = WorkerProperty(item.code, item.value) self.collection_descriptions[dataset_id].historical_collection.append(worker_property) de...
The main task of the code is to save and process data while managing worker availability. It checks if the worker is available, temporarily disables it to prevent concurrent operations, saves data locally, evaluates its state, processes it, cleans up properties, and re-enables the worker. The method ensures data handli...
def SaveData(self, data: Description): # pragma: no cover if not self.is_available or not self.status: # If worker is off or busy return self.is_available = False self.__SaveLocally(data) cd_statuses = self.__EvaluateDataState() self.__ProcessData(cd_sta...
def get_obj_name(lines: str) -> str: matches: List[str] = findall(r"(?<=\*\n).*\s{3}", lines) line_with_name = matches[0].strip() matches = findall(r"\s{3}\S+?\s{3}", line_with_name) object_name = matches[0].strip() if LOGGING_ENABLED: logger.debug(f"Obj Name: {object_name}") return obje...
The code processes a file by reading its contents, extracting specific attributes like object name, radius, rotation rate, and other properties using helper functions, then stores these extracted data into a JSON file named after the object. It also includes logging for debugging and success tracking.
def process_file(filepath: str, counter: int = -1) -> None: if LOGGING_ENABLED: logger.debug(f"About to parse: {filepath}") lines: List[str] = [] # Read in the input file with open(filepath) as f: lines = f.readlines() concatted_lines = "".join(lines) obj_name = get_obj_name(conc...
def get_data_from_house(house_number : str): watt_df = list() for file in os.listdir(house_number): if (regex.compile("channel_[0-9]+.dat").match(file)): # read file from data and return dataframe temp = read_entries_from(house_number + '/' + file) #temp = read_entri...
The main task of the code is to retrieve energy consumption and appliance on/off data for a specific house, filter out non-movable appliances, generate temporal events from the on/off data, and save these events to a CSV file. The code also includes commented-out sections for potential HTML and JSON output, but these a...
def main(): watt_df, on_off_df = get_data_from_house(house_number = house_1) #watt_df.to_html('temp.html') # Remove appliances that are automatically on and therefore cannot be moved on_off_df = remove_appliances(on_off_df) events = get_temporal_events(on_off_df) write_dataframe_to_...
def blackWhiteBoxPattern(array, left, right): # repeat it until there is no middle boxes if (left >= right or left == 0): return else: # swap the black and white boxes temp = array[left] array[left] = array[right] array[right] = temp blackWhiteBoxPattern(array...
The code tests four tasks: (1) Rearranging arrays with `blackWhiteBoxPattern` to group 'B's and 'W's, (2) Identifying fake coins via `findFakeCoin` using a search algorithm, (3) Comparing quicksort and insertion sort's swap/operation counts on arrays, and (4) Calculating medians with `findMedian`. Each section runs mul...
def main(): # Question 1 print("Test of -Question 1-") array = ['B', 'B', 'B', 'B', 'B', 'W', 'W', 'W', 'W', 'W'] print("Array is:") print(array) print("After:") blackWhiteBoxPattern(array, 1, 8) print(array) array2 = ['B', 'B', 'W', 'W'] print("Array is:") print(array2) ...
def leftmost_minimum(arr, rows): if len(arr) == 1: # append the leftmost minimum in rows array rows.append(min(arr[0])) else: if (len(arr) % 2) == 1: # if array's length is odd leftmost_minimum(arr[0:(len(arr) // 2)], rows) # append the leftmost minimum in rows ...
The main task of the code is to test five functions through multiple test cases: 1) Find leftmost minimums in rows of a 2D array, 2) Find the kth largest element in two merged arrays, 3) Identify the maximum-sum contiguous subarray, 4) Check if graphs are bipartite, and 5) Calculate item gains and determine the best pu...
def main(): # Question 1 print("Test of -Question 1-") arr = [[10, 17, 13, 28, 23], [17, 22, 16, 29, 23], [24, 28, 22, 34, 24], [11, 13, 6, 17, 7], [45, 44, 32, 37, 23], [36, 33, 19, 21, 6], [75, 66, 51, 53, 34]] print("Special array is:") for row in arr: for item in row: ...
def getFilesInDirectory(path, extension='bson.gz'): """ Recursively fetches a list of file paths with the specified extension in a path """ files = [] for r, d, f in os.walk(path): for filename in f: if filename[((len(extension)+1)*-1):] == ('.' + extension): ...
The main task of the code is to perform bulk ingestion of data files into an Elasticsearch index, handling errors like version conflicts, logging error details, and recording the total ingestion time. It uses Elasticsearch's streaming_bulk helper, processes BSON data iteratively, and saves encountered errors to a JSON ...
def bulkIngest(es, dataPath): global OP_TYPE dataFiles = getFilesInDirectory(dataPath) print('Files to be ingested = ' + str(dataFiles)) errors = [] # Bulk ingest print('\nBeginning bulk ingest on index ' + INDEX + '...') startTime = time.time() # See https://elasticsearch-py.readthedo...
def get_player(): return session['turn'] def is_winner_move(row, col): return row_check(row) or col_check(col) def toggle_turn(): session['turn'] = get_other_player()
This code handles a player's move in a tic-tac-toe game by updating the board at the specified coordinates with the current player's symbol, checking if the move results in a win, setting the winner if applicable, toggling the turn, and redirecting to the game view for the next player's turn.
def move(row, col): turn = get_player() session['board'][row][col] = turn if is_winner_move(row, col): session['winner'] = turn toggle_turn() return redirect(url_for('ttt.game'))
def get_edge_sorting_function(entity_store): def outcome(edge): return edge.get_higher_vertex(entity_store).y return outcome def update_active_walls(active_walls, scan_y, y_sorted_2d_edges, entities_2d): n_popped_edges = 0 for edge in y_sorted_2d_edges: if is_edge_scanned(scan_y, edge, entities_2d): active_w...
This function processes 2D entities to render them by scanning horizontal lines (scan_y) from top to bottom. It identifies intersections between scan lines and active walls, sorts these intersections, and paints them using a batch drawing system. Walls that don't intersect the scan line are deactivated. The process ens...
def paint_with_surface_removal(entities_2d, entities, x_c, y_c): batch = Batch() y_sorted_2d_edges = list(entities_2d.edges.values()) y_sorted_2d_edges.sort(key=get_edge_sorting_function(entities_2d), reverse=True) active_walls = set() for scan_y in range(y_c, -y_c - 1, -1): update_active_walls(active_walls, sca...
def inputsuhu(): hasil=proxy.query() hitungsuhu() print() print("*******INPUT AIR QUALITY INDEX******") ids = int(input("Masukkan id suhu: ")) aqi = int(input("Masukkan AQI (Air Quality Index): ")) suhu = int(input("Masukkan suhu: ")) proxy.inputaqi(ids, aqi, suhu) print("************************************")...
The code presents a menu for managing Jakarta's pollution data, allowing users to publish, view, or quit. It recursively loops, clearing the screen and re-displaying options until the user selects 'Q' to exit. Choices 'A' and 'B' trigger input and calculation functions, respectively, before restarting the menu.
def menu(): print("*******JAKARTA POLLUTION NEWS*******") print() choice = input(""" A: Publish Air Quality Index B: View Air Quality Index Q: Quit Masukkan pilihan: """) print("************************************") print() os.system('cls') if choice == "A" or choice...
def create_sec_tree(): sec_data = sec_tree_data() # print(sec_data) tree = Node() insert_data_to_tree(tree, sec_data) # print(sec_data) return tree def insert_sec_data(node: Node, name: str): # print(node.data, node.store_sec_tree) if node.data == len(name): print(node.store_sec_...
This function inserts a name into a trie-like structure by comparing the first character of the name with the current node's data. If they match, it either creates or uses an existing secondary tree to store the name. If not, it recursively inserts the name into the left or right subtree based on the comparison. The ma...
def insert_data(node: Node, name: str): if node.data == name[0]: if not node.link_sec_tree: node.link_sec_tree = create_sec_tree() insert_sec_data(node.link_sec_tree, name) elif node.data < name[0]: insert_data(node.right, name) else: insert_data(node.left, name)
def _get_bezier_n_points(x_len, complexity): """ Compute optimum number of trajectory points for the bezier curve :param x_len: (int) length of the bezier curve :param complexity: (int) order of complexity of the bezier curve :return: (int) """ return _math.ceil((x_len / (2 * (complexity - 1...
This function generates a Bezier wave by creating control points with random noise, constructing Bezier curves between them, and combining segments into a continuous wave. It uses tensor operations to sample points along a path defined by control points, producing a smooth waveform with specified complexity and randomn...
def _generate_bezier_wave(x_len, mean=1.0, std=0.2, complexity=5, controls=[0.25, 0.75], **kwargs): n_points = _get_bezier_n_points(x_len, complexity) bezier_len = _get_bezier_len(n_points, complexity) step = round(bezier_len / complexity) points_x = _torch.tensor( [ 0, *...
def _generate_cubic_spline_wave(x_len, mean=1.0, std=0.2, complexity=5, **kwargs): x = _np.arange(0, x_len, (x_len - 1) / (complexity - 1)) y = _np.random.normal(loc=mean, scale=std, size=(complexity, )) cs = _interpolate.CubicSpline(x, y) return _torch.as_tensor(cs(_np.arange(x_len))) def _generate_bez...
The code implements a time-warping transformation on a 2D tensor using cubic spline or Bezier curves. It generates temporal warping patterns, applies cumulative scaling, and interpolates input data along the specified axis. The function supports two backends for different warping methods, with a warning for the slower ...
def time_warp(x, axis=0, backend="cubic_spline", **kwargs): assert x.ndim == 2, "This operation only supports 2D Tensor" if axis: x = x.t() spatial_len, temporal_len = x.size() if backend == "cubic_spline": waves = _torch.stack([_generate_cubic_spline_wave(temporal_len, **kwargs) fo...
def preprocess_training_data(df_train): print(f" preprocess_training_data(): Preprocessing Training Data") df_train_transformed = transform_train_data_with_year_week(df_train) print(f"preprocess_training_data(): df_train_transformed:\n {df_train_transformed.head()}") df_train_svd_smoothed = smoothing_t...
The code predicts weekly sales using historical Walmart data by preprocessing training/test data, applying SVD smoothing, encoding categorical variables, and generating predictions via a model (with parameter α=5). It outputs results to "mypred.csv".
def predict_sales(train_csv, test_csv): """ :param train_csv: Training data from historical Walmart sales :return: predicted sales """ print("STEP 1: CALLING PREPROCESSING LOGIC:\n=============================\n") print(f"predict_sales(): Preprocessing the Training data.") df_train = pd.re...
def verify_rate(rate): return rate in ACCEPT_RATE_VALUES def get_selected_ing_from_post(post_data): selected_list = [post_data[key] for key in post_data if (key != 'rate_value' and post_data[key] != \ FIRST_SELECT_OPTION_VALUE)] selected_dict = dict() for key in selected_list: ...
The main task of the code is to process a user's recipe rating by validating the input, appending the rated recipe data to a CSV file, updating a database counter, and triggering a machine learning process when the counter reaches 5. It handles errors gracefully and redirects the user back to the rating page.
def rate_recipe(): try: rating = float(request.form['rate_value']) if verify_rate(int(rating)): ingredient_df = pd.DataFrame.from_dict(get_selected_ing_from_post(request.form)[0]) ingredient_df = ingredient_df.assign(rating=rating) old_df = pd.read_csv(CSV_FILE_PA...
def loadgff(path, sep='\t', header=None, comment='#', genecol = 'Gene', strandcol = 'Strand', parentcol='Parent', genesplit = '-t26', parentsplit = 'Parent=',idsplit = 'ID=', names = ["Seqid", "Source", "Type", "...
This function analyzes genetic variants' effects on annotated gene sequences by aligning variants to reference sequences, determining their impact (e.g., nonsynonymous/synonymous), and saving results per gene. It processes GFF annotations, filters variants within gene regions, compares alleles to the reference, and out...
def snpeffect(samplename,genos,savepath, gff, REF, zerobase=False, skip=False, verbos=False, info_cols = None, parents = None, Start_column = 'Start', Sample_column = 'Sample', Gene_column = 'Gene', variant_column = 'Isva...
def xas_get_entry_from_offset(self) -> Optional[int]: """Returns: Node or pointer entry for current offset and node, else None. Never returns 0. """ if not self.xas_valid(): return None entry = int(self.xas_node.slots[self.xas_offset]) if self.xa_is_no...
This function traverses an XArray structure by repeatedly fetching entries from an offset, validating nodes, and handling pointers. It adjusts offsets, navigates parent nodes, and constructs subtype objects until a valid entry is found or corruption is detected, returning the entry or None.
def xas_descend( self, ) -> Optional[interfaces.objects.ObjectInterface]: entry = None while not entry: entry = self.xas_get_entry_from_offset() if not entry: self.xas_offset += 1 while not self.xas_offset_valid(): ...
def xa_is_node(self, entry: int) -> bool: return self.xa_is_internal(entry) and entry > 0x1000 def xa_to_node( self, entry: int ) -> interfaces.objects.ObjectInterface: return get_object("xa_node", entry - 0b10, self.context) def xas_descend( self, ) -> Optional[interfaces.object...
The function iterates through entries in an XArray, yielding subtype objects. It handles node traversal by descending through entries and yields each found entry. If the entry is a pointer, it constructs and yields a subtype object. Otherwise, it logs a potential corruption warning. The main task is to list all XArray ...
def xa_for_each( self, ) -> Iterable[interfaces.objects.ObjectInterface]: """Lists all the entries in the XArray. Yields: Subtype objects """ entry = int(self.xarray.xa_head) if self.xa_is_node(entry): self.xas_node = self.xa_to_node(entry) ...
def selection(currentNode, mapping, endGame): max = np.NINF selection = None move = '' for child in currentNode.children: child_ucb = ucb1(child) if child_ucb > max: max = child_ucb if endGame: move = mapping[child] selection = child ...
The code implements the Monte Carlo Tree Search (MCTS) algorithm to select an optimal move in a chess game. It generates legal moves, creates child nodes for each, and performs simulations (10 iterations) by selecting, expanding, playing out, and backpropagating rewards. The final move is chosen based on the best node ...
def mcts(currentNode, mcts_player): legalMoves = list(currentNode.state.legal_moves) possibleMoves = [currentNode.state.san(i) for i in legalMoves] move_map = dict() for i in possibleMoves: state = chess.Board(currentNode.state.fen()) # Get FEN Notation of Board state.push_san(i) # Push ...
def selection(currentNode): #SELECTION # if player == "white": selection = None ucb_value = -np.infty for child in currentNode.children: child_ucb = ucb1(child) if child_ucb > ucb_value: ucb_value = child_ucb selection = child return selection def expansio...
This function implements the Monte Carlo Tree Search (MCTS) algorithm for a chess game. It builds a tree of possible moves from the current board state, performs 200 simulations involving selection, expansion, playout, and backpropagation, and selects the move with the highest UCB1 value from the resulting nodes. The g...
def mcts(currentNode, kriegspiel=False): legalMoves = list(currentNode.board_state.legal_moves) possibleMoves = [currentNode.board_state.san(i) for i in legalMoves] move_map = dict() for i in possibleMoves: # Get FEN Notation of Board state = chess.Board(currentNode.board_state.fen()) ...
def makeTissueMasks(overwrite=False,precomputed=False): if config.isCifti: prefix = config.session+'_' if hasattr(config,'session') else '' fmriFile = op.join(buildpath(), prefix+config.fmriRun+'.nii.gz') else: fmriFile = config.fmriFile WMmaskFileout = op.join(outpath(), 'WMmask....
The main task of the code is to preprocess fMRI data using a configurable pipeline. It loads tissue masks, processes volumetric or Cifti data, applies regression, filtering, and other operations defined in 'steps', handles NaN values, generates plots if enabled, and saves the preprocessed data in NIfTI or Cifti format....
def runPipeline(): Flavors = config.Flavors steps = config.steps sortedOperations = config.sortedOperations timeStart = localtime() print('Step 0 : Building WM, CSF and GM masks...') masks = makeTissueMasks(overwrite=False) maskAll, maskWM_, maskCSF_, maskGM_ = masks if conf...
def outpath(): if not op.isdir(config.outDir): mkdir(config.outDir) outPath = op.join(config.outDir,'denoise_'+config.pipelineName) if not op.isdir(outPath): mkdir(outPath) outPath = op.join(outPath,config.subject) if not op.isdir(outPath): mkdir(outPath) if hasattr(config, 'session') and config...
This function computes functional connectivity (FC) matrices from fMRI time series data using Pearson correlation. It processes both original and denoised time series, handling directory creation, file existence checks, and scrubbing of censored time points. The FC matrices are saved as .txt files, with denoised versio...
def computeFC(overwrite=False): prefix = config.session+'_' if hasattr(config,'session') else '' FCDir = config.FCDir if hasattr(config,'FCDir') else '' if FCDir and not op.isdir(FCDir): makedirs(FCDir, exist_ok=True) tsDir = op.join(outpath(),config.parcellationName,prefix+config.fmriRun+config.ext...
def buildpath(): return op.join(config.DATADIR, config.subject,'MNINonLinear','Results',config.fmriRun) def outpath(): if not op.isdir(config.outDir): mkdir(config.outDir) outPath = op.join(config.outDir,'denoise_'+config.pipelineName) if not op.isdir(outPath): mkdir(outPath) outPath = op.join(outPa...
This function computes functional connectivity (FC) matrices for multiple subjects, sessions, and runs using preprocessed fMRI time series data. It retrieves, standardizes, and merges time series data across runs/sessions, applies a connectivity measure (e.g., correlation), and saves the resulting FC matrices along wit...
def getAllFC(subjectList,runs,sessions=None,parcellation=None,operations=None,outputDir=None,isCifti=False,fcMatFile='fcMats.mat', kind='correlation',overwrite=True,FCDir=None,mergeSessions=True,mergeRuns=False,cov_estimator=None): if (not op.isfile(fcMatFile)) or overwrite: if cov_estimator is...
def computeFC(overwrite=False): prefix = config.session+'_' if hasattr(config,'session') else '' FCDir = config.FCDir if hasattr(config,'FCDir') else '' if FCDir and not op.isdir(FCDir): makedirs(FCDir, exist_ok=True) tsDir = op.join(outpath(),config.parcellationName,prefix+config.fmriRun+config.ext...
The function `plotFC` generates and visualizes Pearson correlation matrices for functional connectivity (FC) from fMRI data, comparing original and denoised datasets. It checks if the output file exists or if overwrite is enabled, computes FC if needed, loads the matrices, creates a figure with two subplots displaying ...
def plotFC(displayPlot=False,overwrite=False): print("entering plotFC (overwrite={})".format(overwrite)) savePlotFile=config.fmriFile_dn.replace(config.ext,'_'+config.parcellationName+'_fcMat.png') if not op.isfile(savePlotFile) or overwrite: computeFC(overwrite) prefix = config.session+'_' if ...
def buildpath(): return op.join(config.DATADIR, config.subject,'MNINonLinear','Results',config.fmriRun) def checkXML(inFile, operations, params, resDir, isCifti=False, useMostRecent=True): fileList = sorted_ls(resDir, useMostRecent) for xfile in fileList: if fnmatch.fnmatch(op.join(resDir,xfile), op...
This function executes an fMRI data processing pipeline, handling file path configuration, precomputation checks, and parallel/job submission. It organizes operations, manages scrubbing/denoising steps, generates job scripts for cluster execution, and performs cleanup/plotting. The core task is to run or submit fMRI pr...
def runPipelinePar(launchSubproc=False,overwriteFC=False,cleanup=True,do_makeGrayPlot=False,do_plotFC=False): if config.queue: priority=-100 config.suffix = '_hp2000_clean' if config.useFIX else '' if config.isCifti: config.ext = '.dtseries.nii' else: config.ext = '.nii.gz' ...
def quit(self): sys.exit() def add_message(self, message): # print(message) self.chat_box.config(state=tk.NORMAL) self.chat_box.insert(tk.END, message + "\n") self.chat_box.config(state=tk.DISABLED) def get_answer(self,user_input): if(USE_PREDEFINED_COMMANDS is True and s...
This function handles user input by retrieving and clearing text from an entry widget. It checks if the message is an exit command, displays the user's message, generates a response, and updates the chat interface with both messages and scrolling to the bottom.
def send_message(self, event=None): message = self.entry.get().strip() self.entry.delete(0, tk.END) if message: if(str(message).lower()=="exit" or str(message).lower()=="end"): self.quit() self.add_message(f"You: {message}") # Process user inp...
def register(): try: with open('usr.json', 'r') as f: usr_json = json.load(f) usr_name = usr_json['username'] usr_password = decrypt(usr_json['key'], usr_json['password']) return usr_name,usr_password.decode('utf-8') except: usr_name = input("Enter...
The code implements a password manager login system that authenticates user credentials, loads or initializes a JSON database, and provides a menu-driven interface for inserting, searching, updating, and deleting data entries.
def login(): print("""Password Manager Login""") usr_name,usr_password = register() username = input("Username : ") password = getpass.getpass("Password : ") if username == usr_name and password == usr_password: try: with open('data.json', 'r') as f: json_dict = j...
def _get_applicationinsights_url(api_version, app_id, query): ''' returns the url for REST Call ''' if not api_version: api_version = "v1" host = f"https://api.applicationinsights.io/{api_version}/apps/{app_id}/{query}" return host def _get_applicationinsights_url_header(api_key): ''...
The code's main task is to monitor an application's state via Application Insights by querying its API, parsing response data, and returning a Nagios-compatible metric indicating the system's status. It constructs a URL, sends a GET request, processes JSON response tables to extract timestamps and boolean values, evalu...
def probe(self): try: self.url = _get_applicationinsights_url('v1', self.app_id, "query?your_query_here") self.headers = _get_applicationinsights_url_header(self.api_key) payload = {} response = requests.request("GET", self.url, headers=self.headers, data = paylo...
def get_k(self): def sum_k(length,d,k=[]): #k iterates thrgouh dimensional quadrature levels if len(k) == d:# and sum(k)>=max(d,self.l-d+1): yield k.copy() else: for i in range(1,length+1): k.append(i) yi...
This function generates sparse grid points and their corresponding weights by iterating over indices k and j. For each (k, j) pair, it computes a point and weight using _cc_sparse_grid_point_weight, then yields them as a tuple. The method dynamically produces these pairs for further processing or analysis in a memory-e...
def cc_sparse_grid_point_weights(self): for k in self.get_k(): for j in self.get_j(k): point, weight = self._cc_sparse_grid_point_weight(j,k) yield point, weight
def stag(tagname, attributeDict={}): global indent attributes='' for attr in attributeDict: attributes = attributes + f' {attr}="{attributeDict[attr]}"' print(' ' * indent + f'<{tagname}{attributes}>') indent += 2 def inertial(): stag('inertial') ctag('mass', {'value': 1}) ctag('...
The code defines a 3D table and floor structure for a simulation. It creates visual and collision boxes for the table's legs and base, then adds a green floor with collision properties. A fixed joint connects the table to the floor, ensuring stability. The function uses parameters like tableWidth, tableDepth, and wall ...
def table(): stag('link', {'name': 'table'}) inertial() visualBox('black', 0, -(tableDepth+wall)/2, 0, tableWidth, wall, tableHeight) collisionBox( 0, -(tableDepth+wall)/2, 0, tableWidth, wall, tableHeight) visualBox('black', 0, (tableDepth+wall)/2, 0, tableWidth, wall, tableHeight) collis...
def stag(tagname, attributeDict={}): global indent attributes='' for attr in attributeDict: attributes = attributes + f' {attr}="{attributeDict[attr]}"' print(' ' * indent + f'<{tagname}{attributes}>') indent += 2 def inertial(): stag('inertial') ctag('mass', {'value': 1}) ctag('...
This function creates a 'man' link attached to a rod, defining its inertial, visual, and collision properties. It connects the man to the rod via a continuous joint (for the first man) or a fixed joint (for subsequent men), positioning it with specified offsets. The task involves generating modular robotic arm componen...
def man(rodIndex, manIndex, color, xOffset, yOffset): stag('link', {'name': f'rod{rodIndex}_man{manIndex}'}) inertial() visualBox(color, 0, 0, -manOffset, manDepth, manWidth, manHeight) collisionBox( 0, 0, -manOffset, manDepth, manWidth, manHeight) etag('link') if manIndex == 0: co...
def stag(tagname, attributeDict={}): global indent attributes='' for attr in attributeDict: attributes = attributes + f' {attr}="{attributeDict[attr]}"' print(' ' * indent + f'<{tagname}{attributes}>') indent += 2 def inertial(): stag('inertial') ctag('mass', {'value': 1}) ctag('...
This function creates a robotic rod structure with a prismatic joint, defining its visual and inertial properties. It positions multiple 'man' components along the rod's length at calculated intervals, enabling linear movement simulation.
def rod(index, color, xOffset, manCount, manDistance): stag('link', {'name': f'rod{index}'}) inertial() visualCylinder('silver', xOffset, 0, 0, rodDiameter, rodLength, f'{math.pi/2:f} 0 0') etag('link') prismaticJoint(f'rod{index}_joint', 'table', f'rod{index}', tran_limit(manCount, manDistance)) ...
def get_all_entry_names() -> str: """ Returns a list of all names in the search index. Returns: str: A list of all names in the search index, IN HTML. """ search_client = SearchClient(SEARCH_ENDPOINT, SEARCH_INDEX_NAME, AzureKeyCredential(SEARCH_ACCESS_KEY)) result = search_client.s...
The main task of the code is to convert text from a search index into speech using Azure Blob Storage. It accepts a keyword via HTTP requests, retrieves matching text, generates a `.wav` audio file, uploads it to Azure, and returns the file details via HTML responses. If the keyword is invalid or missing, it displays e...
def pdf_to_speech(req: func.HttpRequest) -> func.HttpResponse: """ HTTP trigger function that generates speech from text and stores it in Azure Blob Storage. The function expects a keyword as a query parameter or in the request body. If the keyword is found in the index, the function generates speech fr...
def _load_coco_annotations(self): return [self.load_anno_from_id(_id) for _id in self.ids] def _cache_images(self): print( "\n********************************************************************************\n" "You are using cached images in RAM to accelerate training.\n" ...
This code initializes a dataset handler for COCO-style annotations, loading image metadata, class labels, and annotations. It processes images (with optional caching) and separates background blocks from object classes using `getBackground`, enabling object detection or segmentation tasks by organizing image data and a...
def __init__(self, data_dir, name, img_size, preprocess=None, cache=False, ): super().__init__() self.data_dir = data_dir self.name = name self.img_size = img_size self.preproces...
def add_dns_address(dns): dns_to_spoof[dns+"."]=spoof_address print("Table containing DNS addresses to spoof was updated: \"" + dns + ".\"" + " was added.") def set_spoof_address(ip): global spoof_address spoof_address=ip print("Spoof address was set to: " + ip) def print_dns_help_list(): print(...
This function handles DNS-related commands by executing actions based on the input command list. It adds DNS addresses, sets spoofing addresses, displays help information, initiates DNS spoofing, or delegates ARP commands. The logic routes tasks to appropriate functions like add_dns_address(), set_spoof_address(), prin...
def dns_command_handler(cmd): if cmd[0]=="add": add_dns_address(cmd[1]) elif cmd[0]=="set" and cmd[1]=="spoof" and cmd[2]=="address": set_spoof_address(cmd[3]) elif cmd[0]=="help": print_dns_help_list() print_arp_help_list() elif cmd[0]=="spoof": start_dns_spoof()...
def get_interface(): global intface return intface def find_gateway_router(): print("Searching for gateway router...") global dns_server_ip global dns_server_mac global Target2 gws=conf.route.route("0.0.0.0")[2] # pkt = Ether(src=host_mac_addr)/IP(src=host_ip_addr)/UDP()/DNS(rd=1, qd=...
This code implements an ARP spoofing tool for DNS manipulation. It initializes network settings, identifies the gateway router, poisons ARP tables between targets, and enters a loop to handle user commands for attacks like DNS spoofing.
def main_dns(): global Target1 global Target2 print("Welcome to ARP_H4X0R_1337 (name subject to change). Type 'help' for a list of commands.") print("Default interface set as: " + get_interface()) find_gateway_router() poison(Target1, Target2, 0, 10) while (True): cmd = raw_input()....
def event_filter_fn(evt_pat: EvtPattern, pat_idx: int) -> ast.FunctionDef: """Generate the statement to filter out events that don't satisfy the pattern. Something like: ```py def match_{i}(events, evt_idx, match_indices): # {if prop1 is False, return a False value early} # {if prop2 is...
The code generates functions to filter events based on a sequence pattern. It creates individual event match functions for each pattern, a dispatcher function (`match_event`) that routes to the correct match function using `pat_idx`, and a pre-filter function. The dispatcher uses conditional checks to call the appropri...
def generate_match_fns(seq_pat: SeqPattern) -> list[ast.FunctionDef]: """Generate the statement to filter out events that don't satisfy the pattern. Something like: ```py def match_seq_pre(seq): ... def match_event(pat_idx, events, i, match_indices): if pat_idx == 0: re...
def drawBackground(self, canvas): canvas.create_rectangle(0, 0, self.width, self.height, fill='deep sky blue') #pencil gif SOURCE: https://gph.is/st/Y9xlJ8M canvas.create_image(70, 70, image=ImageTk.PhotoImage(self.image)) canvas.create_text(248, 70, text='Draw Something!', ...
The main task of this code is to redraw the game screen based on the current state. It draws the background first, then conditionally renders different UI elements: start page, word bank, look-away prompt, word selection, or gameplay. During gameplay, it toggles between brush tools and displays game-over or win screens...
def redrawAll(self, canvas): self.drawBackground(canvas) if self.starting: self.drawStartPage(canvas) elif self.wordBanking: self.drawWordBankPage(canvas) elif self.lookAwaying: self.drawLookAwayPage(canvas) elif self.wording: self....
def obtener_json_desde_archivo(self, nombre_json): try: with open(nombre_json, "r", encoding="utf-8") as archivo: return json.load(archivo) except FileNotFoundError: raise FileNotFoundError def obtener_datos_desde_html(self, html): meses = { ...
The code downloads and processes order data from a web interface by authenticating with provided credentials, scraping paginated order details, categorizing them into successful/failure groups, and updating a progress bar. It handles pagination, extracts order information, validates product data against predefined quan...
def descargar_datos(self, barra_progreso): print(ascii_amnesia) credenciales = self.obtener_json_desde_archivo(r"archivos\datos\credenciales.json") urls = self.obtener_json_desde_archivo(r"archivos\datos\urls.json") payload = {'log': credenciales["usuario"],'pwd':credenciales[...
def descargar_datos(self, barra_progreso): print(ascii_amnesia) credenciales = self.obtener_json_desde_archivo(r"archivos\datos\credenciales.json") urls = self.obtener_json_desde_archivo(r"archivos\datos\urls.json") payload = {'log': credenciales["usuario"],'pwd':credenciales[...
The main task of the code is to initiate data download, process the retrieved data into JSON and CSV formats, generate an Excel file, and update a UI element with information about failed orders. It coordinates downloading data, storing it in structured formats, and reflecting download outcomes in the user interface.
def iniciar_descarga_datos(self, barra_progreso, etiqueta_pedidos_fallidos): self.diccionario_pedidos = self.descargar_datos(barra_progreso) self.escribir_json_lista_diccionarios(self.diccionario_pedidos) self.escribir_archivos_csv(self.diccionario_pedidos,self.obtener_json_desde_archivo(r"archi...
def parse_args(): parser = argparse.ArgumentParser( description="Convert list of comma separated values into Q3.13 format.") parser.add_argument('trainInput', help='Input file name with train instances') parser.add_argument('testInput', help='Input file name with test instances') parser.add_argu...
The code processes training and test data by parsing arguments, loading instances, classifying test data based on training data, and saving results to an output file. Its main task is to perform classification on given datasets and store the outcomes for further analysis or evaluation.
def main(): args = parse_args() training_instances = load_instances(args.trainInput) test_instances = load_instances(args.testInput) classification_data = classify_set(training_instances, test_instances) dump_contents(classification_data, args.output)
def nested_diff( key_type: str, indent: int, key: str, value: Any = None, ch_value: Any = None ) -> str: plain_before = plain_after = "" if key_type == "changed_nested_1": plain_after = plain_diff( key_type="added", key=key, indent=indent, value=ch_val...
This function generates a formatted string highlighting differences between two nested dictionaries. It recursively compares key-value pairs, identifies changes (added, missing, modified), and constructs a structured output with indentation for readability. Nested dictionaries are handled via recursive calls, while non...
def get_diff_str_nested( dict1: Dict[str, Any], dict2: Dict[str, Any], indent: int = 2 ) -> str: diff_view = get_diff_view(dict1, dict2) diff_str = "{\n" if indent == 2 else "" for key, val in diff_view.items(): key_type = val["type"] value = val["value"] ch_value = val["changed...
def generate_question_board(self, full_board: str, difficulty: int) -> tuple: """Returns a randomly generated question board and the solution to the same board, the difficulty represents the number of number squares removed from the board.""" self.board = copy.deepcopy(full_board) if difficu...
The main task of the code is to generate a question board with a specified difficulty level, create its corresponding solution board, and return both in code format. It achieves this by calling `generate_question_board` with a randomly generated complete board and the given difficulty, then converting both the generate...
def generate_question_board_code(self, difficulty: int) -> tuple: """Calls the generate_question_board method and returns a question board and its solution in code format.""" self.board, _solution_board = self.generate_question_board( self.__generate_random_complete_board(), difficulty ...
def parse_options(options_str): if not options_str: return {} try: return dict(map(str.strip, arg.split('=')) for arg in options_str.split(',') if '=' in arg) except: print('arg string format error:', options_str) raise def merge_dict(d1, d2): dm = d1....
This code compiles Markdown files containing LaTeX math expressions and \include directives, converting them into images using LaTeX rendering. It processes \begin/\end blocks, inline/display math, and included files, embedding generated PNGs into the output Markdown. The function handles options, escapes, and image re...
def compile(src_md, output_md, **tex2png_options): output_md = open(output_md, 'w') src = open(src_md) line = 'none' while line: line = src.readline() # \begin \end syntax begin_stmt = begin_re.match(line) if begin_stmt: # extra configs to tex2png() ...
def canWrite(self, varId, trxId): sites = self.getAvailSitesHoldingVarId(varId) if not sites: return False for site in sites: if not site.lock_manager.canWrite(varId, trxId): return False for op in self.waitingOperations: if op....
This code handles a write operation by checking if the transaction is allowed to write to a variable. If permitted, it acquires a write lock, updates the variable's value, and logs the write intent. If not permitted, it logs the operation as on-hold and queues it for later processing.
def write(self, operation: Operation): trxId = operation.txn_id varId = operation.var_id writeToVal = operation.var_val if self.canWrite(varId, trxId): # print("[OK_TO_WRITE]", operation) self._addWriteLock(varId, trxId) self._writeValue(varId, writeTo...
def readROValue(self, operation: Operation): trxId = operation.txn_id varId = operation.var_id trx = self.idToTransactions.get(trxId) if len(trx.data) != 0 and varId in trx.data: print('[INFO]', f'T{trx.id} reads x{varId}: {trx.data[varId]}') else: print(...
This code handles read operations in a transaction system. It checks if the transaction is read-only, processes it via readROValue if so, otherwise verifies variable access permissions. If allowed, it reads the value and adds a read lock; if not, it queues the operation for later processing.
def read(self, operation: Operation): trxId = operation.txn_id trx = self.idToTransactions.get(trxId) if trx.is_read_only: self.readROValue(operation) return varId = operation.var_id if self.canRead(varId, trxId): self.readValue(operation) ...
def read(self, operation: Operation): trxId = operation.txn_id trx = self.idToTransactions.get(trxId) if trx.is_read_only: self.readROValue(operation) return varId = operation.var_id if self.canRead(varId, trxId): self.readValue(operation) ...
This method handles read/write operations for transactions. It checks if the transaction is aborted; if so, it skips execution. Otherwise, it performs the read or write action and triggers deadlock detection and resolution.
def readOrWrite(self, operation: Operation): trx = self.idToTransactions.get(operation.txn_id) if trx.status == TransactionStatus.ABORTED or trx.status == TransactionStatus.ABORTING: print('[RW_FAIL]', f'T{trx.id} can\'t be executed because it is aborted or will be aborted') retu...
def prepare_request(self, tweet_id, username, context, auth_object=None): if auth_object is None: auth_object = self.get_auth_object() referrer = "retweets" if context == "retweeted_by" else "likes" headers = { 'authority': 'twitter.com', 'sec-ch-ua': '"Chromi...
This function generates HTTP requests to interact with tweets (retweet/like) by preparing URLs, headers, and parameters for each tweet. It conditionally uses Chrome driver-based authentication or database-stored credentials to handle interactions, then sends these requests to perform social media interactions like retw...
def get_tweets_users(self, tweets, context): interactions_request_list = [] if not self.enable_chrome_driver: for tweet in tweets: url, headers, params = self.prepare_request(tweet["id"], tweet["username"], context) interaction_request = dict() ...
def user_process(user:dict) -> dict: '''uses fuzzywuzzy to pick best matching movie title from user input ''' user_processed = {} for movie, rating in user.items(): best_match, score = process.extractOne(movie, list(movies_filter(ratings_to_R(ratings))['title'].values), scorer=fuzz.token_se...
The code generates top-N recommendations using Non-negative Matrix Factorization (NMF) by processing user input, handling missing data, and formatting results. It transforms a user dictionary into a structured DataFrame, fills missing values, applies an NMF-based recommendation model, and returns the highest-ranked rec...
def nmf_predict(user:dict, n_recs=10, fillNanValue=0.0) -> pd.DataFrame: '''successive use of functions to make recommendation. see used functions descriptions for details ''' user_processed = user_process(user) user_df = user_dicttoDF(user_processed) user_df_filled = fill_user_df(user_df, fill...
def user_dicttoDF(user:dict) -> pd.DataFrame: '''creates a dataframe from a userdict that matches the feature dimension of the ratings dataframe ''' user = convert_user(user) movieIds = list(ratings_to_R(ratings).columns) empty_list = [np.nan]*len(movieIds) ratings_dict = dict(zip(movieI...
The function `nmf_predict` generates top-N (default 10) recommendations for a user using a recommendation model. It converts the input user dictionary into a DataFrame, fills missing values with a specified value, retrieves recommendations via a model, formats the results, and returns the top `n_recs` entries. The proc...
def nmf_predict(user:dict, n_recs=10, fillNaValue=0.0) -> pd.DataFrame: '''successive use of functions to make recommendation. see used functions descriptions for details ''' user_df = user_dicttoDF(user) user_df_filled = fill_user_df(user_df, fillNaValue) recs = get_recs(user_df_filled) output ...
def board_copy(a, b): for i in range(0, 9): for j in range(0, 9): b[i][j] = a[i][j] def random_fill_cuda(board, mask, rng_states, tx): for i in range(0, 9): dims = get_square_dims(i) sb = board[dims[0][0]:dims[0][1], dims[1][0]:dims[1][1]] sbm = mask[dims[0][0]:dims[0...
This CUDA kernel performs a parallel Monte Carlo simulation on a 9x9 board, using random number generation and energy calculations to iteratively update board states. Threads coordinate via atomic operations on shared memory, updating the board based on temperature-dependent probabilities. The simulation halts when a s...
def kernel(init_board, mask, rng_states, output): tx = cuda.threadIdx.x board = cuda.local.array((9, 9), int16) board_copy(init_board, board) output_access = cuda.shared.array(1, int64) cuda.atomic.compare_and_swap(output_access, 0, 1) cuda.syncthreads() b = cuda.local.array((9, 9), int16...
def _avoid_my_neck(my_body: dict, possible_moves: set) -> set: """ my_body: List of dictionaries of x/y coordinates for every segment of a Battlesnake. e.g. [{"x": 0, "y": 0}, {"x": 1, "y": 0}, {"x": 2, "y": 0}] possible_moves: List of strings. Moves to pick from. e.g. ["up", "down",...
The function `choose_move` determines the next move for a Battlesnake by analyzing the game board data. It filters possible moves to avoid collisions with the snake's own body, walls, and other snakes using helper functions. It prioritizes safe directions, defaults to random choices if no valid moves remain, and return...
def choose_move(data: dict) -> str: """ data: Dictionary of all Game Board data as received from the Battlesnake Engine. For a full example of 'data', see https://docs.battlesnake.com/references/api/sample-move-request return: A String, the single move to make. One of "up", "down", "left" or "right". ...
def get_read_set_import_job(request: CheckOmicsWorkflowTaskRequest) -> CheckOmicsWorkflowTaskResponse: boto3.client('omics') response = omics_client.get_read_set_import_job( id=request.task_params['id'], sequenceStoreId=request.task_params['sequence_store_id'] ) logger.info(response) ...
This Lambda function processes workflow tasks by evaluating the task_type in the event request. It invokes specific handlers for "GetReadSetImportJob", "GetRun", or "GetVariantImportJob" and returns structured responses. If an unsupported task_type is detected, it generates a failure response with an error message. The...
def lambda_handler(event: CheckOmicsWorkflowTaskRequest, context): logger.info(f"Event Object: {event}") request = CheckOmicsWorkflowTaskRequest(**event) if request.task_type == "GetReadSetImportJob": task_response = get_read_set_import_job(request) elif request.task_type == "GetRun": ...
def sample_h(self, v, seed=None): """Sample the hidden variables given the visible ones""" probas = self.prob_h(v) return self.sample_binary(probas=probas, seed=seed) def sample_v(self, h, seed=None): """Sample the visible variables given the hidden ones""" probas = self.prob_v(h...
The function computes the gradient of the coupling term in a probabilistic model using contrastive divergence. It samples hidden units $ h $ from visible inputs $ v $, then reconstructs visible units $ v' $ from $ h $. The gradient is derived by summing the difference between the outer product of $ v' $ and $ h $, and ...
def compute_gradient_w(self, v, seed=None): """Compute the gradient of the coupling term using contrastive divergence""" h = self.sample_h(v, seed) v_prime = self.sample_v(h, seed) return np.sum(batched_outer(v_prime, h) - batched_outer(v, h), axis=0)
def prob_h(self, v: np.ndarray): """Compute the probability of all hidden nodes being equal to 1 given all the visible nodes""" return sigmoid( np.tensordot( v, self.w, axes=[[-1], [0]] ) # allows both batched an non-batched entries. + self.b ...
The function computes the gradient of the hidden linear term in a probabilistic model using contrastive divergence. It calculates the difference between the model's estimated hidden probabilities (from sampled visible data) and the data's true hidden probabilities, then sums these differences to update model parameters...
def compute_gradient_b(self, v, seed=None): """Compute the gradient of the hidden linear term using contrastive divergence""" prob_h_data = self.prob_h(v) h = self.sample_h(v, seed) v_prime = self.sample_v(h, seed) prob_h_model = self.prob_h(v_prime) return np.s...
def compute_gradient_w(self, v, seed=None): v_k = v for i in range(self.k): v_k, h_k = self.step_gibbs(v_k) prob_h_data = self.prob_h(v) prob_h_model = self.prob_h(v_k) return torch.sum( batched_outer(v, prob_h_data) - batched_outer(v_k, prob_h_model), d...
The main task of the code is to perform a gradient ascent step on model parameters (a, b, w) by computing gradients, negating them to align with likelihood maximization, and updating parameters using an optimizer with a specified learning rate. The function computes individual gradients, assigns them with negative sign...
def SGD_step(self, v, lr=0.001, weight_decay=0, seed=None): gradient_w = self.compute_gradient_w(v, seed) gradient_a = self.compute_gradient_a(v, seed) gradient_b = self.compute_gradient_b(v, seed) self.optim.zero_grad() self.a.grad = -1 * gradient_a # Adam optimizer assumes yo...
def compute_gradient_w(self, v, seed=None): v_prime, h = self.step_gibbs(v, seed) prob_h_data = self.prob_h(v) prob_h_model = self.prob_h(v_prime) return torch.sum( batched_outer(v, prob_h_data) - batched_outer(v_prime, prob_h_model), dim=0 ) def compute_gradient_a(...
This function performs a single step of Stochastic Gradient Descent (SGD) to update model parameters (w, a, b) using computed gradients. It calculates gradients for each parameter, applies L2 weight decay if specified, and updates parameters by subtracting the gradient multiplied by the learning rate.
def SGD_step(self, v, lr=0.001, weight_decay=0, seed=None): gradient_w = self.compute_gradient_w(v, seed) gradient_a = self.compute_gradient_a(v, seed) gradient_b = self.compute_gradient_b(v, seed) if weight_decay != 0: gradient_w = gradient_w + weight_decay * self.w ...
def compute_gradient_w(self, v, seed=None): """Compute the gradient of the coupling term using contrastive divergence""" h = self.sample_h(v, seed) v_prime = self.sample_v(h, seed) return np.sum(batched_outer(v_prime, h) - batched_outer(v, h), axis=0) def compute_gradient_a(self, v, see...
The main task of the code is to perform a gradient descent update on a model's parameters (weights `w`, biases `a`, and `b`) using gradients computed from a minibatch of visible variables `v`. It calculates gradients for each parameter via `compute_gradient_w`, `compute_gradient_a`, and `compute_gradient_b`, then appli...
def gradient_step(self, v, seed=None): """Update the parameters using a minibatch of visible variables""" gradient_w = self.compute_gradient_w(v, seed) gradient_a = self.compute_gradient_a(v, seed) gradient_b = self.compute_gradient_b(v, seed) self.w = self.optim.update(self.w, ...
def get_rng(self, seed=None): """Either use the rng setup at instantiation or obtain a new one with a fixed seed""" if seed is None: return self.rng else: return np.random.default_rng(seed) def batched_array(array, batch_size): for first in np.arange(0, len(ar...
The main task of the code is to train a model by iterating over a batch of visible variables, shuffling them, dividing them into minibatches, and performing a gradient step on each minibatch to update model parameters via mini-batch gradient descent.
def train_epoch(self, v, batch_size, seed=None): """Train by going once over a batch of visible variables, dividing it into minibatches""" self.get_rng(seed).shuffle(v, axis=0) for v_batch in batched_array(v, batch_size=batch_size): self.gradient_step(v_batch)
def show_board(self): cls() print("".join(self.board)) def print_records(self): print(f"{' -> '.join(map(lambda x: (list(x)[0] + ':' + str(list(x.values())[0])), self.records))}") def check_size(_position) -> bool: check_false = [False for number in _position if number > 3 or number < 0] ...
This code runs a turn-based game loop where players input positions to mark their moves on a board. It checks for valid moves, updates game state, switches turns, and determines if a player has won or the game is a draw. After ending, it asks if the players want to restart the game.
def start(self): self.show_board() while True: # print records self.print_records() # wait input _input = input(f"Player '{self.turn}' - key in position: ") try: _position = tuple(map(int, _input.split(","))) pri...
def parse_output_file_path(arg: argparse.Namespace) -> str | None: raw_ : str = arg.o # output; refined_ : str = os.path.realpath(raw_) # to refine the provided pathname for further processing; sep_ : str | None = return_seperator(refined_) components: list[str] = refined_.split(sep_) pre_output_fi...
The main task of the code is to handle image conversion based on user input, either for a single file or multiple files from a directory. It validates input paths, checks file formats, manages output directories, and executes conversion tasks using argparse for command-line arguments. The function supports both file-mo...
def run_program(parser: argparse.ArgumentParser) -> None: screen.welcome_screen() # display the welcome screen; print('\n', end='') # move a line below; input_path: str | None = None output_path: str | None = None args_namespace: argparse.Namespace = parser.parse_args() # instantiating argument...
def wait_for_qr(self): last_qr = None qr_number = 0 while not self.w.is_qr_scanned(): logging.info("Checking QR code") try: qr = self.w.get_qr() except TimeoutException: # Check if the app was loading the ready screen and is rea...
The code's main task is to automate WhatsApp operations by initializing a session, waiting for a QR code scan, performing data scraping, updating task status to 'DONE' upon completion, and handling exceptions by setting the status to 'ERROR' with an error message before exiting.
def run(self): try: self.w = Whatsapp(screenshot_folder="/tmp") self.wait_for_qr() self.do_scrape() self.folder.set_status(Status.DONE) self.quit() except Exception as e: self.folder.set_status(Status.ERROR, message=f"{type(e)}: {e}...
def getAxes(self): (magno_x, magno_z, magno_y) = self.bus.read_3s16int(self.AxisXDataRegisterMSB) # print(magno_x, magno_y, magno_z) if (magno_x == -4096): magno_x = None else: magno_x = round(magno_x * self.scale, 4) if (magno_y == -4096):...
This method generates a string representation of an object's attributes, including its X, Y, Z axes values, declination, and heading. It concatenates these values into a formatted multi-line string for readability and returns it.
def __str__(self): ret_str = "" (x, y, z) = self.getAxes() ret_str += "Axis X: "+str(x)+"\n" ret_str += "Axis Y: "+str(y)+"\n" ret_str += "Axis Z: "+str(z)+"\n" ret_str += "Declination: "+self.getDeclinationString()+"\n" ret_str += "Hea...
def stopServer(): global serverSocket if serverSocket: serverSocket.close() serverSocket = None def handle_root(client): wifiSta.active(True) ssids = sorted(ssid.decode('utf-8') for ssid, *_ in wifiSta.scan()) send_header(client) client.sendall("""\ <html> <s...
This code initializes a web server on an ESP device's Wi-Fi access point, handling HTTP requests to configure settings or serve content. It binds to a specified port, accepts client connections, parses incoming HTTP requests, and routes them to appropriate handlers for root pages, configuration, or not-found errors. Th...
def startServer(port=80): global serverSocket addr = socket.getaddrinfo('0.0.0.0', port)[0][-1] stopServer() wifiSta.active(True) wifiAp.active(True) wifiAp.config(essid=ap_ssid, password=ap_pass, authmode=ap_auth) serverSocket = socket.socket() serverSocket.bind(addr) serverSock...
def getProfiles(file="profiles.json"): ''' returns a list of dicts of all known profiles [{"ssid": "SSID", "pass": "PASSWORD", "dhcp": true | false, }, ... ] ''' # Try opening the prifiles file try: print("[WifiMgr] Load known profiles: %s" %(file)) with open(file) as f: ...
The main task of the code is to establish a Wi-Fi connection using stored profiles by scanning for available networks, comparing them with known configurations, and attempting to connect with appropriate credentials. It handles both encrypted and open networks, activates the STA interface if connected, and starts a web...
def getConnection(): """ return a working WLAN(STA_IF) interface or none """ # First check if there already is any connection: if wifiSta.isconnected(): return wifiSta connected = False try: # ESP might take some time to connect to wifi time.sleep(3) wifiSta.active(...
def available_paths(self): paths = [path for name, path in self.board.paths.items() if (any([self.board.paths[path2].owner == self.name for path2 in path.neighbors]) or any([self.board.spots[spot].owner == self.name for spot in path.spots])) and path.owner == ...
The code selects an optimal path to build by filtering unowned paths with unowned neighboring spots, prioritizing those that extend the longest road. It checks resource availability and turn state, then randomly chooses a path from the filtered list to claim, aiming to maximize road length.
def choose_path_to_build(self): if not (self.roads and ((self.resources["brick"] and self.resources["lumber"]) or self.board.turn <= 0)): return paths = self.available_paths() if paths: ideal = lambda path: (all(spot.owner in UNOWNED for spot in [self.board.spots[name] fo...
def longest_road(self): longest = 0 for name, path in self.board.paths.items(): if path.owner == self.name: path.visited = True longest = max(longest, self.longest_road_helper(path, 1)) path.visited = False return longest def most_harbo...
The main task of the code is to generate a feature vector representing a player's game state in a board game. It aggregates attributes like resources, settlements, roads, development cards, and calculated probabilities based on tile ownership and terrain types, combining them into a list for analysis or AI decision-mak...
def get_self_state(self): x = [self.knights, self.longest_road(), self.most_harbors(), self.largest_army()] + \ [self.resources[resource] for resource in self.resources] + \ [self.settlements, self.cities, self.roads] + \ [len(self.available_spots_for_settlement()), len(self....
def choose_dev_card(self): cards = [card for card in self.dev_cards if self.dev_cards[card] > 0 and card != "victory_point"] if cards: return choice(cards) def move_robber(self): # stealing disabled for the sake of simplicity tile = self.choose_tile_to_occupy() robber_tile =...
This function plays a development card by selecting one, decrementing its count, applying specific effects based on the card type (e.g., moving the robber, stealing resources, building roads, or gaining resources), and returning True if a card was successfully played, otherwise False.
def play_dev_card(self): card = self.choose_dev_card() if card is not None: self.dev_cards[card] -= 1 if card == "knight": self.move_robber() self.knights += 1 elif card == "monopoly": resource = self.choose_resource() ...
def build_road(self): path = self.choose_path_to_build() if path is None: return False self.roads -= 1 path.build_level = 1 if self.board.turn > 0: self.resources["brick"] -= 1 self.resources["lumber"] -= 1 path.owner = self.name ...
The code selects an action probabilistically based on a given distribution, executes the corresponding method (e.g., building roads, buying development cards), and records the action. The distribution is weighted with a 5% uniform chance and 95% based on input probabilities, ensuring diverse yet guided decision-making ...
def move(self, distribution): instruction = np_choice(len(distribution), p=0.05 / len(distribution) + 0.95 * distribution) if instruction == 0: self.build_road() elif instruction == 1: self.build_settlement() elif instruction == 2: self.build_city() ...
def loadEyeConfig(filename: str) -> List[EyeConfig]: try: f = open(filename) params = json.load(f) # Use the directory name the config file is in for the eye name if none was specified in the config file if params.get('name') is None: params['name'] = Path(filename).parent.name.replace(" ", "")...
The main task of the code is to generate a C++ header file containing eye-related maps (angle, distance, displacement) and image data (iris, sclera, eyelids) based on a configuration file. It validates the output directory, processes configuration parameters, creates map files, and writes a structured header file with ...
def generateEyeCode(outputDir: str, configFile: str): if not os.path.exists(outputDir): sys.stderr.write(f'The path {outputDir} does not exist') exit(1) if not os.path.isdir(outputDir): absolutePath = os.path.abspath(outputDir) sys.stderr.write(f'{outputDir} is not a directory (absolute: {absolutePa...
def getFrontier(pose, costmap, logger): fCache = FrontierCache() fCache.clear() mx, my = costmap.worldToMap(pose.position.x, pose.position.y) freePoint = findFree(mx, my, costmap) start = fCache.getPoint(freePoint[0], freePoint[1]) start.classification = PointClassification.MapOpen.value ...
The main task of the code is to identify the farthest frontier from the robot's current position, set it as a waypoint, and send it to the FollowWaypoints action server for navigation. It handles frontier detection, distance calculation, goal submission, and result handling, with recursive calls to continue exploration...
def moveToFrontiers(self): frontiers = getFrontier(self.currentPose, self.costmap, self.get_logger()) if len(frontiers) == 0: self.info_msg('No More Frontiers') return location = None largestDist = 0 for f in frontiers: dist = math.sqrt(((f[0...
def getSizeX(self): return self.map.info.width def getSizeY(self): return self.map.info.height def getCost(self, mx, my): return self.map.data[self.__getIndex(mx, my)] def getFrontier(pose, costmap, logger): fCache = FrontierCache() fCache.clear() mx, my = costmap.worldToMap(pose.p...
This callback processes a costmap message by converting it into a 2D grid, counts cells marked as 'unknown' (cost=255), and logs the count. It then determines and logs the number of frontiers in the map using the `getFrontier` function, aiding in pathfinding or exploration tasks in robotics.
def costmapCallback(self, msg): self.costmap = Costmap2d(msg) unknowns = 0 for x in range(0, self.costmap.getSizeX()): for y in range(0, self.costmap.getSizeY()): if self.costmap.getCost(x, y) == 255: unknowns = unknowns + 1 self.get_logge...
def get_profits(bot, coins, ftx, email): positions = consolidate_positions(email) profits = {} print("start pulling prices") prices = get_prices(bot, coins, ftx) price_directory = {} """Process prices""" for i in prices: coin = i[0] price = i[1] price_directory.update...
The function updates user metrics in Firestore by calculating profits, identifying the best and worst positions, and storing all-time and 24-hour profit data. It retrieves profit data, processes positions, and uploads key metrics for a given user's trading activity.
def update_metrics(bot, coins, ftx, email): profits = get_profits(bot, coins, ftx, email) """Finds and uploads best position held by user onto firestore""" best_position = get_best_position(profits, email) best_position_data = {'value': best_position[1], 'coin': best_position[0]} override_...
def __on_initiate(self, SRUP_initiate_message): # print("INITIATE MESSAGE Received") SRUP_response_message = pySRUPLib.SRUP_Response() status = None try: self.__fetch_check_file(SRUP_initiate_message.url, SRUP_initiate_message.digest, self....
This code processes incoming MQTT messages by verifying SRUP protocol messages, checking sender IDs, sequence numbers to prevent replay attacks, and routing valid messages to appropriate handler methods based on their type (action, data, initiate, etc.), while ignoring invalid or self-generated messages.
def __on_message(self, client, userdata, msg): # First check if the message is even for us... # Remembering that server's are wild... topic = None ch_topic = msg.topic if ch_topic[0:5] == 'SRUP/': topic = ch_topic[5:] # First check if the message is for us (o...
def _is_finished(self, depth): if (depth >= self.max_depth or self.n_class_labels == 1 or self.n_samples < self.min_samples_split): return True return False def _best_split(self, X, y): split = {'score':- 1, 'feat': None, 'thresh': None} n_features = ...
This function recursively constructs a decision tree by selecting the best feature-threshold split, partitioning data into left/right subsets, and creating child nodes until stopping criteria are met. It returns a tree node containing split details and child nodes, with leaf nodes holding the most common class label wh...
def _build_tree(self, X, y, depth=0): self.n_samples, self.n_features = X.shape self.n_class_labels = len(np.unique(y)) # stopping criteria if self._is_finished(depth): most_common_Label = np.argmax(np.bincount(y)) return Node(value=most_common_Label) # ...
def _battery_voltage_valid(self): # Todo: Make it depend on the battery configuration if get_vbat_voltage() > 3.0: return True else: return False def do_state_transition(self, to_state): state_trans_has_happened = False if self.state == St...
The code manages state transitions in a system based on sensor inputs and conditions. It checks the current state and evaluates conditions like pyro/battery status, armed status, and BW insertion to transition between states such as SYSTEMS_CHECK, ERROR_MODE, IDLE_MODE, PREPERATION_MODE, ARMED_MODE, LAUNCHED_MODE, and ...
def check_state_transition(self): if self.state == States.SYSTEMS_CHECK: if not is_pyro_inserted() or not self._battery_voltage_valid(): self.do_state_transition(States.ERROR_MODE) elif is_pyro_inserted() and self._battery_voltage_valid(): ...
def sentence_tokenizer(fullText: str, thresh: int) -> list: """ Tokenizes the input text file into sentences :param fullText: input text :return: list of sentences """ # lower case it fullText = fullText.lower() # tokenize hashtags fullText = re.sub(r"#(\w+)", r"<HASHTAG> ", fullText...
The code calculates perplexity for language models using Witten-Bell and Kneser-Ney smoothing on a text corpus. It splits sentences into training and test sets, constructs n-gram models, computes perplexity for each test and training sentence, and writes average and per-sentence perplexity results to output files.
def get_all_perps(path: str): # path = "corpus/Pride and Prejudice - Jane Austen.txt" in_text = open(path, "r", encoding="utf-8") sentences = in_text.read() sentences = sentence_tokenizer(sentences, 1) # remove all sentences with less than NGRAM_SIZE tokens sentences = [sentence for sentence in ...