dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def increment(self): # Actually increment the program counter self.assert_d("i") # Keep track of the increment self.pc += 1 def write(self, val): self.send("w") # Send the numer 0-padded to a 14-bit binary number self.assert_d("{0:014b}".format(val)) def reset(sel...
This function writes data from a hex file into memory, ensuring the program counter starts at 0. It iterates through each memory location, skipping default values (0xffff) to optimize speed. For non-default values, it writes them to memory and increments the counter. Finally, it resets the PIC microcontroller to prepar...
def write_file(self, hf): # Check we're at the start of the memory assert self.pc == 0 pbar = ProgressBar() # For each location in the hex file, up to the maximum # location for i in pbar(range(0, hf.last_loc(self.max_location) + 1)): # Get the value for this...
def read(self): self.send("r") # Parse the binary response return int(self.get_response(), 2) def increment(self): # Actually increment the program counter self.assert_d("i") # Keep track of the increment self.pc += 1 def reset(self): # Reset the program c...
This code verifies that the contents of a hex file (hf) match the actual memory values of a device, starting from program counter (PC) 0. It iterates through each memory location up to the maximum address, checks if the expected value (from the hex file) matches the device's read value (unless the default 0xffff is pre...
def verify_file(self, hf): # Check we're at the start of the memory assert self.pc == 0 pbar = ProgressBar() # For each location in the hex file, up to the maximum # location for i in pbar(range(0, hf.last_loc(self.max_location) + 1)): # Get the value that sh...
def goto_config_word(self): # Go into config memory self.enter_config() # Increment the PC self times for i in range(7): self.increment() assert self.pc == 0x2007 def write(self, val): self.send("w") # Send the numer 0-padded to a 14-bit binary number sel...
The main task of the code is to write a configuration word to a PIC microcontroller, verify its successful writing by reading back the value, and then reset the PIC to its initial state (PC=0). This ensures proper configuration setup and system reset for subsequent operations.
def write_verify_config_file(self, hf): # Get the configuration word cword = hf.config_word() # Move the pic PC to the config word self.goto_config_word() # Write the config word, and verify it's been written self.write(cword) assert self.read() =...
def unblock_room_tiles(self, room): # go through the tiles in the rectangle and make them passable for x in range(room.x1 + 1, room.x2): for y in range(room.y1 + 1, room.y2): self.tiles[x][y].blocked = False self.tiles[x][y].block_sight = False def unblock_h_t...
The code generates a dungeon map with interconnected rooms, ensuring no overlaps. It places the player in the first room, connects subsequent rooms via tunnels, and adds entities. Stairs are placed at the last room's center for progression.
def make_map(self, max_rooms, room_min_size, room_max_size, map_width, map_height, player, entities): rooms = [] num_rooms = 0 for r in range(max_rooms): new_room = GameMap.create_room(room_min_size, room_max_size, map_width, map_height) # run through the other rooms an...
def get_next_length(self,tx): field, pos = _DecodeVarint32(tx,0) size, newpos = _DecodeVarint32(tx,pos) if (field&0x07==0): return newpos return size + newpos def apduMessage(self, INS, P1, P2, MESSAGE): hexString = "E0{:02x}{:02x}{:02x}{:02x}{}".format(INS,P1,P2,len(MESSAGE)//2,...
This code processes a transaction (tx) by splitting it into chunks, appending signatures, and sending them via APDU commands for signing. It constructs command bytes based on chunk count and signature presence, iterates through each chunk, and verifies responses. If all steps succeed, it returns the signed result; othe...
def sign(self, path, tx, signatures=[], verbose=False): max_length = 255 offset = 0 to_send = [] start_bytes = [] data = bytearray.fromhex(f"05{path}") while len(tx)>0: # get next message field newpos = self.get_next_length(tx) assert(...
def load_data_groups_subjects(condition, groups = ['AV', 'V', 'AVr'], subjects = info['subjects'], mf_param_idx = 1, max_j = 14, channel_type = 'mag', ...
The function `load_logcumul_for_classification` prepares a labeled dataset for classification by combining features derived from log-cumulants of neural data under different experimental conditions. It processes two class labels (conditions_0 and conditions_1), extracts features (e.g., mean, max, min, clipped values) f...
def load_logcumul_for_classification(conditions_0, conditions_1, log_cumulants, groups, subjects, mf_param_idx, channel_type = 'mag', n...
def crawl(directory): """ Parse a directory of HTML pages and check for links to other pages. Return a dictionary where each key is a page, and values are a list of all other pages in the corpus that are linked to by the page. """ pages = dict() # Extract all links from HTML files for f...
The code calculates PageRank for a given corpus of web pages using two methods: sampling and iterative computation. It first validates input, crawls the corpus, computes ranks via sampling, prints results, then recalculates ranks iteratively and prints them again. The task demonstrates comparing PageRank outcomes from ...
def main(): if len(sys.argv) != 2: sys.exit("Usage: python pagerank.py corpus") corpus = crawl(sys.argv[1]) ranks = sample_pagerank(corpus, DAMPING, SAMPLES) print(f"PageRank Results from Sampling (n = {SAMPLES})") for page in sorted(ranks): print(f" {page}: {ranks[page]:.4f}") ...
def read_pos_from_file(): with open("positions.txt", "r") as file: positions = file.read().split(",") set_current_xpos(positions[0]) set_current_ypos(positions[1]) def diff_in_audio(): global oldx,oldy if grid[get_current_xpos()][get_current_ypos()] == grid[oldx][oldy]: retur...
The code manages audio track transitions based on positional changes. It continuously checks the current position, compares audio differences, and triggers fade-out/fade-in threads for seamless track changes. It also handles channel muting/resuming and updates the loop state, ensuring smooth audio playback with periodi...
def start_loop(): global running, oldx, oldy while running: # check current position read_pos_from_file() # translate position to grid # diff in audio? -> change needed? if diff_in_audio(): # get channel that played old track old...
def get_tracklist(): global tracklist cmd = "cd tracklist && ls >tracklist.txt" os.system(cmd) with open("tracklist/tracklist.txt", "r") as file: data = file.read() data = data.split("\n") for i in range(0, len(data)-2): tracklist.append(data[i]) print(trackli...
The main task of the code is to initialize an audio processing system by loading track names, setting default channels, creating a grid, mapping audios to the grid, and starting an engine. It also spawns a thread to terminate the engine after 10 seconds. Key steps include: loading tracks, channel initialization, grid c...
def main(): print("hello world") # load all available tracknames get_tracklist() # initialize channels to default init_channels() # create the grid init_grid() # map the audios to the grid map_audios() # start thread that is killing engine after time given by args t = t...
def _sort_labels_threshold(dataset, threshold): if isinstance(dataset.get('boxes'), np.ndarray): boxes = dataset.get('boxes') labels = dataset.get('labels') scores = dataset.get('scores') else: boxes = dataset.get('boxes').detach().numpy() labels = dataset.get('labels').d...
The code evaluates detection accuracy by comparing predicted labels with correct labels, calculating the correct detection percentage, mean correct letters, and standard deviation of correct letters across datasets, using a threshold for label sorting and validation.
def own_testmetric(correct_labels, datasets, threshold: float = 0.0): if len(correct_labels) is not len(datasets): raise ValueError("Number of correct labels and datasets are not equal") correct_detections = 0 correct_letters_list = [] for correct_label, dataset in zip(correct_labels, datasets)...
def on_session_started(session_started_request, session): print("on_session_started requestId=" + session_started_request['requestId'] + ", sessionId=" + session['sessionId']) def on_launch(launch_request, session): return get_welcome_response() def on_intent(intent_request, session): print("on_in...
This Lambda function processes Alexa skill requests by routing events to appropriate handlers. It prints the application ID, initializes new sessions, and directs requests to on_launch, on_intent, or on_session_ended based on the request type, enabling interaction with voice assistants like Alexa.
def lambda_handler(event, context): print("event.session.application.applicationId" + event['session']['application']['applicationId']) if event['session']['new']: on_session_started({'requestId': event['request']['requestId']}, event['session']) if event['r...
def normal_user(): # Function to handle the flow for a normal user # Import new_user() and login() functions from userManager.py # Ask the user if they are a new user response = input("\nAre you a new user? (Y/N)\n\n") if response.lower() == "y": # If the user is a new user userManager.new_use...
The main task of the code is to serve as the entry point for a cinema booking system. It checks the existence of essential files (user and seating data) and prompts the user to select their role (normal user or admin). Based on the input, it routes the user to either the normal user interface or the admin login functio...
def main(): # Import is_file_empty() function from seatingManager.py seatingManager.is_file_empty() # Check if the file is empty userManager.check_user_file() # Check if the user file exists userManager.check_user_seats_file() # Check if the user seats file exists user_type = input( "W...
def countTiles(current_node, goal_node): wrong_tiles = 0 for i in range(len(current_node.status)): for j in range(len(current_node.status[i])): if current_node.status[i][j] != 'm' and current_node.status[i][j] != goal_node.status[i][j]: wrong_tiles += 1 return wrong_tiles...
This code implements an A* search algorithm to solve a puzzle (e.g., 8-puzzle) by calculating heuristic values ("tiles" or "manhattan") for nodes, prioritizing paths with lower estimated costs. It uses a priority queue to explore states, avoids revisiting boards via a set, and terminates when reaching the goal, exceedi...
def heuristic(current_node, goal_node, heuristic_type): count_nodes = count() if heuristic_type == "tiles": current_node.hx = countTiles(current_node, goal_node) elif heuristic_type == "manhattan": current_node.hx = countDistance(current_node, goal_node) current_node.fx = current_node....
def find_naive_bayes_class_probability(dataset, column4): category_probability_column4 = get_all_category_probabilities_by_class(4, dataset) print('category_probability_column4: ', category_probability_column4) column4_index = next((index for (index, d) in enumerate(category_probability_column4) if d["Cate...
This function calculates the overall probability for each class ('Sim' and 'Nao') in a Naive Bayes classifier. It computes class probabilities, extracts class-specific subsets of the dataset, determines feature probabilities for each class, and combines them by multiplying class probability with feature likelihoods. Re...
def find_naive_bayes_overall_probability(dataset, column0, column1, column2, column3): class_probability_yes = find_naive_bayes_class_probability(dataset, 'Sim') class_probability_no = find_naive_bayes_class_probability(dataset, 'Nao') custom_dataset = generate_custom_dataset(dataset) dataset_class_ye...
def find_tests(rx): global finder finder = TestFileFinder(pathinit.libdir) check_test_dir() walkdir = test_dir or pathinit.libdir walk_with_symlinks(walkdir, finder.visit, rx) return finder.files def gui_runner(files, test_filter): if build_inplace: utildir = os.path.join(os.getcwd(...
The main task of the code is to configure logging, clean stale bytecode, initialize test paths, and execute test files based on filters. It uses GUI, loop, or direct runners depending on flags, with optional reference counting and garbage collection monitoring during repeated test runs.
def main(module_filter, test_filter, libdir): if not keepStaleBytecode: os.walk(os.curdir, remove_stale_bytecode, None) # Get the log.ini file from the current directory instead of possibly # buried in the build directory. XXX This isn't perfect because if # log.ini specifies a log file, it'll...
def number_neighbors_and_symbol_locations( fp: str, ) -> tuple[list[tuple[int, set[tuple[int, int]]]], dict[tuple[int, int], str]]: with open(fp) as file: line_length = len(next(iter(file))) number_neighbors: list[tuple[int, set[tuple[int, int]]]] = [] symbol_locations: dict[tuple[int, int], st...
The code processes an input file to identify numbers and symbols, then calculates and prints two values: the sum of part numbers adjacent to symbols and the sum of gear ratios from numbers surrounding asterisks. It solves Advent of Code 2023 Day 3's puzzles, handling both parts of the challenge.
def main() -> None: fp = "aoc_2023/inputs/day_3.txt" number_neighbors, symbol_locations = number_neighbors_and_symbol_locations(fp) print(sum_part_numbers(number_neighbors, symbol_locations)) print(sum_gear_ratios(number_neighbors, symbol_locations))
def __generate_id(self): return int(shortuuid.ShortUUID(alphabet="0123456789").random(length=10)) def __bulid_st_dict(self, param): try: for i in range(len(self.edi_file_info)): i = 0 self.extract_data() if self.segment.split('-')[0] == 'BHT': ...
The code initializes an EDI file processor, parses the file into structured data (edi_parsed and index_837), tracks ST segments, generates metadata like file ID and timestamps, connects to MongoDB, and inserts parsed data into collections. It handles EDI segment extraction, status tracking, and database storage for 837...
def __init__(self, edi_file): super().__init__(edi_file) self.__count_st = 0 self.__bht_list = [] self.__id = self.__generate_id() self.edi_parsed = { 'header_section': { 'trans_src_id': self.__id, 'file_name': os.path.basename(self.edi...
def validate_user(self): if len(self.user_name_textbox.get()) < 3: messagebox.showerror('User name', 'Name must be at least 3 characters') self.user_name_textbox.delete(0, tk.END) self.user_name_textbox.focus() return if self.user_confirm_password_textb...
This code creates a GUI form for adding and deleting user records. It sets up a centered, topmost window with input fields for username, password, confirmation, and access level selection. It includes 'Add Record' and 'Delete' buttons to handle user data operations, using a combobox for access codes and validating inpu...
def create_new_user_form(self): self.root = tk.Toplevel(self.master) self.root.title('User Editor') self.root.config(bg='#D9D8D7') self.root.geometry('390x560') self.root.update_idletasks() width = self.root.winfo_width() height = self.root.winfo_height() ...
def parse_args(call): """Parse args.""" apars = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter) apars.add_argument( "--fasta", metavar="F", required=False, help="""Fasta file used as input ""...
The main task of the code is to generate peptide-protein mappings and Prosit input files from a FASTA database using enzymatic digestion parameters. It processes peptides by cleavage rules, filters valid sequences, and writes results to TSV/CSV files, including collision energy, charge, and protein associations. It als...
def main(args): """Main to run digestion.""" args = parse_args(args) # python digest.py --enzyme trypsinp --cleavages 0 --fasta /home/matthewt/data/MaxLFQ_benchmark/ups.fasta # --prosit_input ~/data/Prosit_test/ups_prosit_input.csv if args.prosit_input: writer = get_tsv_writer(args.prosit_in...
def _delta_masking_call(self, masks, batch_size=None): # TODO: we need to do batching here assert getattr(self.masker, "supports_delta_masking", None) is not None, "Masker must support delta masking!" masked_inputs, varying_rows = self.masker(masks, *self.args) num_varying_rows...
The code handles masking operations by determining if input masks are 1D (delta masks) or higher-dimensional (full masks). If 1D and delta masking is supported, it uses a specialized method; otherwise, it converts delta masks to full masks and proceeds. For non-1D masks, it directly applies full masking. The main task ...
def __call__(self, masks, batch_size=None): # if we are passed a 1D array of indexes then we are delta masking and have a special implementation if len(masks.shape) == 1: if getattr(self.masker, "supports_delta_masking", False): return self._delta_masking_call(masks, batch_s...
def reset(self, latch: bool = False): self._data[0] = _PINS_NONE[0] self._data[1] = _PINS_NONE[1] self._data[2] = _PINS_NONE[2] self._data[3] = _PINS_NONE[3] if latch: self.latch() def set_pin(self, pin: int, value: bool, latch: bool = False): assert 1 <= pin...
This code validates each pin from 1 to 20 by resetting the device, activating each pin individually, and verifying its state. It captures pins that fail verification (via AssertionError) and reports them. The process ensures proper functionality of all pins, with final reset to a stable state.
def _validate(self): self.reset(latch=True) failed_pins = [] for pin in range(1, 20 + 1): self.reset() self.set_pin(pin, True) try: self._write_verify() print(f"pin {pin} PASS") except AssertionError: ...
def _validate_chipid(self): self._read_register1() chipid = (self._register1_value & _CHIPID_MASK) >> 3 if chipid not in (5,7): raise RuntimeError("Failed to find DRV2665 or DRV2667, check wiring!") def _read_register1(self): self._register1_value = self._read_u8(_REGISTER_1)...
The code initializes an I2C communication interface with a specified chip address, verifies the chip's identity via its ID register, and reads the values of two specific registers (Register 1 and Register 2) to configure or interact with the connected device, such as a DRV2665 motor driver.
def __init__(self, i2c: I2C, address: int = DRV2665_ADDR) -> None: self._device = i2c_device.I2CDevice(i2c, address) self._validate_chipid() self._read_register1() self._read_register2()
def events(self): # catch all events here for event in pygame.event.get(): if event.type == pygame.QUIT: self.quit() quit(0) if event.type == pygame.MOUSEBUTTONDOWN: mouse_x, mouse_y = pygame.mouse.get_pos() for row,...
The code defines a game loop that runs while `self.playing` is True. It maintains the game's frame rate using `self.clock.tick(FPS)`, processes events, updates game logic, and renders the screen repeatedly until the loop ends by setting `self.playing = False`.)
def run(self): # game loop - set self.playing = False to end the game self.playing = True while self.playing: self.clock.tick(FPS) self.events() self.update() self.draw()
def community(): global name; global sub print('<<< What subreddit would you like to query? >>>\n\n<<< Enter name of subreddit [ex. Research] >>> :: ', end = '') sub = str(input()) name = sub + '.data.csv' print('\n<<< You have choosen to que subreddit: ', sub, ' >>>\n\n' + ('-----------------------...
The main task of the code is to initialize variables, prompt user confirmation, and execute a pull operation if approved. It sets up community data, time references, and handles user input to decide whether to proceed with the pull function, which likely processes data based on the provided parameters.
def start(subm, comm): sc = 0; cc = 0 global stats; stats = {} sub, name = community() after = past() before = future() print('<<< Would you like to abort? (0 = no; else = yes) >>> :: ', end='') abort = input() if abort == '0': print('\n' + ('-----------------------' * 5)) ...
def argparse_reader(): """ Parse arguments for the img analysis script @return: parse object with arguments """ parser = argparse.ArgumentParser() parser.add_argument('plateID', type=int, help='RockMaker Plate ID (4 or 5 digit code on barcode or 2nd number on RockMaker sc...
The main task of the code is to process image directories containing overlayed, overview, and batchID_## folders by mapping image paths to subwells, generating JSON files with plate metadata (ID, temperature), and optionally executing only JSON creation. It measures execution time, handles command-line arguments, and o...
def main(): """ Run image analysis on a directory of images containing overlayed, overview, and batchID_## folders """ current_directory = os.getcwd() args = argparse_reader().parse_args() t0 = ti.time() # save time to know how long this script takes (this one takes longer than step 2) p...
def build_cnn(self): """ Build the CNN. """ print("Building the CNN...") if self.config.cnn == 'vgg16': self.build_vgg16() else: self.build_resnet50() print("CNN built.") def build_rnn(self): """ Build the RNN. """ print("Building the RNN.....
The code's main task is to build a neural network model by initializing its CNN and RNN components. If in training mode, it also sets up optimizers and summary operations for monitoring. The commented-out `build_CondGan()` suggests an optional conditional GAN component that is not currently activated.
def build(self): """ Build the model. """ self.build_cnn() self.build_rnn() # self.build_CondGan() if self.is_train: self.build_optimizer() self.build_summary()
def _save_pgdd_data(): """Saves all PgDD data to JSON format in the directory `config.BUILD_PATH`. """ db_stats = pgdd.DatabaseStats() _print_db_stats(db_stats) out_dir = config.BUILD_PATH _ensure_dir_exists(out_dir) db_stats.json() pgdd.schemas() pgdd.tables() pgdd.views() ...
The main task of the code is to execute the PgDD builder module by initializing database structure components. It saves PgDD data, constructs indexes, schema/table/view/column/function lists, builds hierarchical trees for tables/views, and copies CSS files, preparing the application's database metadata representation a...
def run(): """Runs the pgdd_ui.builder module""" print("Running PgDD builder...") _save_pgdd_data() _build_db_index() _build_schema_list() _build_table_list() _build_view_list() _build_column_list() _build_function_list() _build_table_tree() _build_view_tree() _copy_css(...
def validation_step( self, batch: dict ) -> Tuple[Tensor, Tensor, Tensor]: """ Extract the feature, classify and compute the cross entropy loss between the ground truth and the prediction. Input arguments: batch: dict = batch from custom dataloader. ...
The function validates the model on the test set by computing accuracy, tracking total test loss, and checking for performance improvements. It evaluates the model in no-gradient mode, accumulates predictions and loss, computes metrics, and triggers early stopping or checkpoint saving if improvements are detected. The ...
def validation( self, testing_loader: DataLoader, epoch: int ) -> dict: """ Validate all the test set, compute the accuracy, store the total test loss and check for the improvement in the performance; if it is the case, save the new model checkpoint. ...
def get_twenties(num, tens, ones): """ If the second digit is zero, return the tens digit, otherwise return the tens digit and the ones digit. :param num: The number to be converted :param tens: ['twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety...
The code converts a number into its English word representation by determining the number's length and calling specific helper functions (`get_twenties`, `get_hundreds`, etc.) to handle ranges like 20–99, 100–999, and 1000–9999. It uses string manipulation and conditional checks to delegate tasks, ensuring correct form...
def number (num): """ It takes a number, converts it to a string, and then uses the length of the string to determine which function to call. The functions are: get_twenties() - for numbers between 20 and 99 get_hundreds() - for numbers betwee...
def make_heap(self, frequency): for key in frequency: #frequency == frequency.keys() node = HeapNode(key, frequency[key]) #node == (key, value) ex) (0,10) heapq.heappush(self.heap, node) def merge_nodes(self): count=0 while(len(self.heap)>1): node1 = heapq.heappop(self.heap) #pop out and delete elements ...
The main task of the code is to construct Huffman codes from given character frequencies. It initializes a priority queue (heap), merges nodes with the lowest frequencies to build a Huffman tree, and generates binary codes for each character. The method returns the encoded codes and the merged tree structure, enabling ...
def build(self, frequency): self.make_heap(frequency) merge=self.merge_nodes() #return merged self.make_codes() return self.codes ,merge
def does_alien_touch_wall(alien: Alien, walls: List[Tuple[int]]): """Determine whether the alien touches a wall Args: alien (Alien): Instance of Alien class that will be navigating our map walls (list): List of endpoints of line segments that comprise the walls in the maze in the fo...
The function determines if an alien's straight-line path from its current position to a waypoint intersects any wall in the maze. It checks for collisions by analyzing the alien's shape (circle, horizontal, or vertical), calculating potential path segments, and comparing them against wall segments. The code adjusts for...
def does_alien_path_touch_wall(alien: Alien, walls: List[Tuple[int]], waypoint: Tuple[int, int]): """Determine whether the alien's straight-line path from its current position to the waypoint touches a wall Args: alien (Alien): the current alien instance walls (List of tuple): List ...
def does_alien_touch_wall(alien: Alien, walls: List[Tuple[int]]): """Determine whether the alien touches a wall Args: alien (Alien): Instance of Alien class that will be navigating our map walls (list): List of endpoints of line segments that comprise the walls in the maze in the fo...
The function determines if an alien's straight-line path from its current position to a waypoint intersects any wall. It checks for initial wall contact, adjusts the path based on the alien's shape (circle, horizontal, or vertical), and models the alien's movement boundaries. It evaluates segment distances between the ...
def does_alien_path_touch_wall(alien: Alien, walls: List[Tuple[int]], waypoint: Tuple[int, int]): """Determine whether the alien's straight-line path from its current position to the waypoint touches a wall Args: alien (Alien): the current alien instance walls (List of tuple): List ...
def Sbox(rules): inputs = [] outputs = [] for i in range(2**INPUT_SIZE): res = list(map(int, str(decimalToBinary(i)))) res = res[1:] inputs.append(res) op = [] start = 0 for rule in rules: for i in range(math.ceil(INPUT_SIZE/NUM_RULES)): ...
The code evaluates the cryptographic strength of a substitution box (S-box) defined by input rules. It calculates differential uniformity (DU) and nonlinearity (NL), normalizes these metrics, and computes a reward value as their average. The function returns the reward, DU, and NL, optionally printing them.
def state_crypto_strength(rules_index, to_print): rules = [rule_list[i] for i in rules_index] inarray, outarray = Sbox(rules) decimal_repr = [] for bit_list in outarray: decimal_repr.append(BinaryTodecimal(bit_list)) DU = diff_uniformity(decimal_repr) NL = NLcalc(inarray, outarray, INPU...
def get_input(filename: str) -> List[str]: input_file_path = PosixPath(PosixPath.cwd(), filename) lines = [] with open(input_file_path, "r") as f: lines = f.readlines() return [line.strip() for line in lines] def part1(lines: List[str]) -> int: ans = 0 for line in lines: lst = li...
The main task of the code is to process input data from a file, execute two distinct processing functions (`part1` and `part2`), and print their results. It uses `argparse` to handle command-line input, reads the file content via `get_input`, and outputs the answers for "Part 1" and "Part 2" of a problem. The code is s...
def main(): parser = argparse.ArgumentParser() parser.add_argument("-i", "--input", required=True, help="Input file name") args = parser.parse_args() opts = vars(args) lines = get_input(opts["input"]) print("[+] Part 1 ans =>", part1(lines)) print("[+] Part 2 ans =>", part2(lines))
def get_s3_file_data(bucket_name, file_key): s3 = boto3.client('s3') file_data = s3.get_object(Bucket=bucket_name, Key=file_key)['Body'].read().decode() return file_data def get_prediction(email_body): sagemaker = boto3.client('runtime.sagemaker') body = [email_body] one_hot_email = one_hot_e...
The code processes an S3 event triggered by an email upload, extracts email details (sender, recipient, subject, body), classifies the email as spam with a confidence score, and sends a categorized response to the recipient. It logs email metadata and uses a prediction model to determine spam status before notifying us...
def lambda_handler(event, context): print(json.dumps(event)) s3_data = event['Records'][0]['s3'] bucket_name, email_file = s3_data['bucket']['name'], s3_data['object']['key'] raw_email = get_s3_file_data(bucket_name, email_file) email_object = email.message_from_string(raw_email, policy=default_po...
def generate_average_feature(self, labels): #extract feature/classifier u_feas, fcs = self.get_feature(self.u_data) #images of the same cluster label_to_images = {} for idx, l in enumerate(labels): label_to_images[l] = label_to_images.get(l, []) + [idx] #cal...
This code generates new training data by merging similar samples based on feature distances and a size penalty. It computes average features, selects pairs of indices to merge, creates updated training data, and adjusts the classifier's loss function with new parameters derived from the merged features. The function re...
def get_new_train_data(self, labels, nums_to_merge, size_penalty): u_feas, feature_avg, label_to_images, fc_avg = self.generate_average_feature(labels) dists = self.calculate_distance(u_feas) idx1, idx2 = self.select_merge_data(u_feas, labels, label_to_images, size_penalty, dis...
def generate_average_feature(self, labels): #extract feature/classifier u_feas, fcs = self.get_feature(self.u_data) #images of the same cluster label_to_images = {} for idx, l in enumerate(labels): label_to_images[l] = label_to_images.get(l, []) + [idx] #cal...
This code generates new constrained training data by merging selected samples while maintaining uniqueness. It calculates feature distances, selects indices for merging, and constructs new training data. It then updates the classifier's loss function with average features and adjusted parameters to enforce constraints ...
def get_new_unique_constratint_train_data(self, labels, nums_to_merge, size_penalty): u_feas, feature_avg, label_to_images, fc_avg = self.generate_average_feature(labels) dists = self.calculate_distance(u_feas) idx1, idx2 = self.select_unique_constratint_merge_data(u_feas, labels, lab...
def __generate_address__(self, street=None, number=None, zip_code=None, country=None, city=None): self.address_id += 1 return { "Id": self.address_id, "Street": street if street else self.generator.street_name(), "Number": number if number else self.random.randint(1...
The code registers auction data into a cache by creating associated entities like users, addresses, and bids. It checks if sellers and bidders exist, generating new entries if needed. Auction details, images, and category links are registered, with logging and downloader integration for image handling. The task involve...
def register(self, auction): if self.verbose: self.logger.log("Processing auction '%s'" % auction["ItemID"]) seller = auction["Seller"] if seller["UserID"] not in self.users: self.cache.register("Address", self.__generate_address__()) self.cache.register...
def folder_list(folder_id): from googleapiclient.discovery import build gdrive = build('drive', 'v3').files() res = gdrive.list(q="'%s' in parents" % folder_id).execute() return [[f['id'], f['name']] for f in res['files']] def get_boundaries(year, section_name): sections_file = '/content/drive/MyDrive/lihtc/s...
The function `get_data_for_year` retrieves data from Google Drive files for a specified year and section, applying boundaries to filter data. It iterates through files in a folder, checks for special cases (e.g., "Project Location" with specific boundaries), fetches data using `get_data_by_drive_id`, and appends result...
def get_data_for_year(drive_dir_id, sheet_name, year, section_name): data = [] for file_info in tqdm(folder_list (drive_dir_id)): f_id = file_info[0] f_name = file_info[1] print("f name is: " + f_name) boundaries = get_boundaries(year, section_name) if f_id in weird_ids and...
def folder_list(folder_id): from googleapiclient.discovery import build gdrive = build('drive', 'v3').files() res = gdrive.list(q="'%s' in parents" % folder_id).execute() return [[f['id'], f['name']] for f in res['files']] def get_year_by_name(folder_name): return re.findall(r'\d{4}$', folder_name)[0] def get...
The function aggregates data from multiple files in a Google Drive directory, processes each file by extracting the year from the filename, retrieves yearly data for a specific section, and compiles all results into a JSON file. It iterates through files, collects structured data, and writes the consolidated dataset to...
def write_all_files_to_json(drive_dir_id, section_name): data = [] for file_info in tqdm (folder_list (drive_dir_id)): year_str = get_year_by_name(file_info[1]) print(year_str) yearly_data = get_data_for_year(file_info[0], get_sheet_name(year_str), year_str, section_n...
def load_data(): for file in listImagesFiles(image_dir): img = load_image(file) if img is not None: img_data.append(img) lbl_data.append(os.path.basename(os.path.dirname(file))) else: continue overview(50) return img_data,lbl_data def categorizeL...
The code splits a dataset into training and test sets after preprocessing: normalizing image data (0-1 scale), one-hot encoding labels, and using sklearn's train_test_split with 20% test size and fixed random state.
def split_dataset(): from sklearn.model_selection import train_test_split img_data,lbl_data = load_data() img_data = np.asarray(img_data) img_data = img_data / 255.0 lbl_data= categorizeLables(lbl_data) lbl_data = np.asarray(lbl_data) lbl_data= to_categorical(lbl_data, num_classes...
def split_dataset(): from sklearn.model_selection import train_test_split img_data,lbl_data = load_data() img_data = np.asarray(img_data) img_data = img_data / 255.0 lbl_data= categorizeLables(lbl_data) lbl_data = np.asarray(lbl_data) lbl_data= to_categorical(lbl_data, num_classes...
The main task of the code is to train a convolutional neural network (CNN) model. It splits the dataset into training and test sets, constructs the CNN architecture, and trains the model using the training data with specified batch size, epochs, and callbacks. The model is validated on the test data during training to ...
def train_model(): x_train, x_test, y_train, y_test = split_dataset() model = construct_cnn() model.fit( x_train, y_train, batch_size = batch_size, epochs = epochs, verbose=1, callbacks= init_callbacks(), validation_data=(x_test,y_test))
def data_dependent_initialize(self): """ The feature network netF is defined in terms of the shape of the intermediate, extracted features of the encoder portion of netG. Because of this, the weights of netF are initialized at the first feedforward pass with some input images. Pl...
This code implements a training step for a GAN (Generative Adversarial Network), alternating between updating the discriminator (D) and generator (G). It initializes data-dependent parameters at the start, computes losses for D and G, performs backpropagation, and updates optimizers. Special handling is applied for the...
def training_step(self, batch, batch_idx): self.real_A, self.real_B = batch if self.current_epoch == 0 and batch_idx == 0: self.data_dependent_initialize() self.forward(True) # update D self.set_requires_grad(self.netD, True) self.optimizer_D.zero_grad() ...
def validRealAssignment(rightSide, nameSpace, printToErr=False): """ this function will check the right side of the real number assignment is valid or real number to assign @param rightSide: the rightSide of the assignment @param nameSpace: the namespace that contains al...
This function validates a boolean expression by checking if it evaluates to TRUE/FALSE, references a boolean variable from the namespace, or compares two valid boolean values (variables or literals) using equality operators. It ensures operands are initialized, of boolean type, and correctly formatted, returning True i...
def validBoolean(boolExpress, nameSpace, printToErr=False): """ this function will check if an expression is a valid boolean expression @param boolexpression: the expression we want to check @param nameSpace: the namespace that contains all variable type @param printToErr: ...
def validParentheses(line): """ this function will check whether or not the parentheses of a statement is correct, otherwise it is invalid @param line: the line we want to check for balance parentheses """ open = 0 for i in range(len(line)): if line[i] == "(": ...
This function validates a boolean expression's syntax, variable usage, and type correctness against a given namespace. It checks for valid parentheses, ensures the expression evaluates to a boolean, and verifies each element is either a valid boolean, an initialized boolean variable, or a properly negated valid variabl...
def validBooleanAssignment(expression, nameSpace, printToErr=False): """ this function will check the expression of the boolean assignment is valid boolean to assign @param expression: the expression to consider @param nameSpace: the namespace that contains all variable ty...
def _get_loader(args, dataset, collator, batch_size): loader = DataLoader(dataset, batch_size=batch_size, pin_memory=args.dataloader_pin_memory, num_workers=args.dataloader_num_workers, shuffle=args.s...
The code trains a model for NLP tasks (e.g., IOB tagging, speaker identification) using gradient accumulation, mixed precision, and task-specific loss functions. It initializes data loaders, optimizers, and schedulers, iterates over epochs, computes losses, and saves the best model based on evaluation metrics like loss...
def train(self): logger.info("***** Running training *****") logger.info(f" Num examples = {len(self.train_dataset)}") logger.info(f" Num Epochs = {self.args.num_train_epochs}") logger.info(f" Instantaneous batch size per device = {self.args.per_device_train_batch_size}") logg...
def _kFoldSplitIndices(self, dataset, k): ''' Helper function for k-fold cross validation. Evenly split the indices of a dataset into k groups. For example, indices = [0, 1, 2, 3] with k = 2 may have an output indices_split = [[1, 3], [2, 0]]. Please don't chang...
The code performs k-fold cross-validation for each lambda in lambda_list by splitting the dataset into k folds, training on k-1 folds, validating on the remaining fold, and averaging validation errors across all folds. It returns a list of cross-validation errors corresponding to each lambda, enabling model evaluation ...
def runKFold(self, lambda_list, X, Y, k = 3): ''' Run k-fold cross validation on X and Y with respect to each lambda. Return all k-fold errors. Each run of k-fold involves k iterations. For an arbitrary iteration i, the i-th fold is used as testing data while the rest k-...
def process_directory(self, directory_path, max_vocab=MAX_VOCAB): result_list = [] unique_words = set() dir_list = os.listdir(directory_path) random.shuffle(dir_list) # Iterate through all files in the directory for filename in dir_list: file_path = os.path.jo...
This code initializes a language model by either processing text data from a directory to generate bigram probabilities or loading precomputed probabilities from a file. It creates a vocabulary, maps words to indices, calculates bigram probabilities, and stores them for use in language modeling tasks like text generati...
def __init__(self, data_path=None, max_vocab=MAX_VOCAB): if data_path is None: """ For all the files in the wiki folder, create a list of sentences Append all the sentences in the single wiki_list """ self.unique_words, self.sentence_l...
def recommend(movie_id): if movie_id == 0: return ["failed"], [""] rating, movie = load_data() X, user_mapper, movie_mapper, user_inv_mapper, movie_inv_mapper = create_X( rating) movie_titles = dict(zip(movie['id'], movie['title'])) similar_movies = find_similar_movies( mov...
The code's main task is to generate movie recommendations by processing an input movie name. It cleans the input, retrieves the movie's ID, fetches recommended movies using a recommendation function, logs the request, and returns the list of recommended movie titles as a comma-separated string.
def get_recommendation(movie): recommended_movies, recommended_tconst = recommend(get_movie_id(clean_request(movie))) print("recieved request for ", movie) return ",".join(recommended_movies)
def get_repo_name(repo, path): if not repo: out = run_cmd(f"git -C {path} remote -v", stdout=PIPE, stderr=PIPE, quit_on_error=False) if out: regex = re.compile("https:\/\/github\.com\/.+/(.+)\.git") matchs = regex.findall(out) if matchs: repo = tex...
The main task of the code is to gather repository configuration details (name, privacy, collaborators) based on user input and flags, checking if a GitHub repository needs creation. It handles mode-specific errors, prompts for privacy settings, and determines collaborator inclusion via command-line flags or user input,...
def info_about_repo(username, token, repo, mode, collaboratorsCmdExist, path): repo_name = get_repo_name(repo, path) if not repository_creation_needed( get_github_URL({"name":repo_name, "username":username, "mode": mode}), token, path): return {"name":repo_name, "username":username} if mode == "coll...
def cache_token(username): path_token = path_input( message="Enter either path of the file that contains the access token, or enter the access toke directly:", invalid_message="Invalid path", validate=lambda x: os.path.isfile(x) if re.search("[/\/]", x) else len(x) > 0 ) if os.path.i...
The function handles token management by caching, validating, and saving a token for a given username. If a new token is provided, it validates and saves it, informing the user of the saved location. If no token exists, it attempts to cache and save one. If a token is already saved, it retrieves it. The function exits ...
def handle_token(new, username): if "token" in new : token = cache_token(username) checkTokenValidation(token) save_token(token) print("token got saved, you can either run this script with '-new token' argument again or go to "+token_path()["path"]+token_path()["file_"],"and edit the...
def handle_username(new): #self explanatory fpath = username_path()["path"]+username_path()["file_"] reg = re.compile("^([a-z0-9](?:-?[a-z0-9]){1,39})",re.IGNORECASE) if os.path.exists(fpath): with open(fpath, "r") as f: data = f.read() else: data = None if "user" in ...
This function deletes a GitHub repository using a provided token, checking if the repository exists first. It handles errors like insufficient permissions, displays a loading indicator, and aborts if the user lacks 'delete_repo' token scope.
def delete(path, name, mode:str, new): username = handle_username(new) token = handle_token(new, username) repo_name = get_repo_name(name, path) url = get_github_URL({ "username":username, "name":repo_name, "mode":mode }) create_repo = repository_creation_needed(url=url,token=token, path=path) i...
def handle_username(new): #self explanatory fpath = username_path()["path"]+username_path()["file_"] reg = re.compile("^([a-z0-9](?:-?[a-z0-9]){1,39})",re.IGNORECASE) if os.path.exists(fpath): with open(fpath, "r") as f: data = f.read() else: data = None if "user" in ...
The main task of the code is to add collaborators to a GitHub repository. It handles default values for username and token, verifies the repository's existence, and uses `handle_collaborators` to assign collaborators if the repository exists. If the repository is not found, it exits with an error message.
def add_collaborators(path, name, new, mode, username=None, token=None, repo=None): username = username if username else handle_username(new) token = token if token else handle_token(new, username) repo = repo if repo else get_repo_name(name, path) url = get_github_URL({"username": username, "name":repo...
def handle_args(path: str, command: str, mode:str, git_ignore, rm_git_ignore): if mode is None: mode = "owner" if mode == available_modes[1] and command == "create-update": print_color("You cannot choose this command (create-update) in this mode!", bg="yellow") sys.exit(ERROR_CODES["mode...
The main task of the code is to process command-line arguments, perform initial setup (like checking Git installation and creating directories), and execute Git-related operations (update, delete, create-update, clone, or pull) based on the provided command. It handles OS-specific screen clearing, argument validation, ...
def main(ctx, command, path, new, mode, name, add_collab, visibility, git_ignore, rm_git_ignore): if get_os() == "windows": # to clean the screen os.system("cls") # clears the console path, command, mode = handle_args(path, command, mode=mode, git_ignore=git_ignore, rm_git_ignore=rm_git_ignore) chec...
def load_duty_tracker(self): with open('duty_tracker.json', 'r') as file: return json.load(file) def get_next_member(self, members, current_member_id): current_index = members.index(next((m for m in members if m['id'] == current_member_id), None)) next_index = (current_index + 1) % l...
The main task of the code is to send lab maintenance reminders to the designated maintainer. It checks if today is the scheduled maintenance day, identifies the next eligible maintainer (PhD/Post-Doc), generates an email with the maintenance date, sends it, creates a calendar event for the maintenance week, and updates...
def send_lab_maintenance_reminders(self): if datetime.today().weekday() == self.maintenance_day: tracker = self.load_duty_tracker() current_maintenance_id = tracker.get('maintenance', None) eligible_members = [member for member in self.lab_members.values() if member['role'] i...
def checkIfValidMoves(htmlStoragedmoves): moves = [] previousDataPly = 0 missingDataPly, lastDataPly = None, None for item in htmlStoragedmoves: divs = item.split('<div') for div in divs[1:]: if "timestamp" in div or "data-tooltip" in div: # skip divs with timestamp ...
This code automates a chess website by scraping move data, converts positions to FEN notation, evaluates chess positions for checkmates/centipawn values, and logs game data. It uses Selenium to interact with the site, extracts move sequences, validates positions, and stores evaluations in a text file. The loop continuo...
def main(): currentPos = [] lastFen, lastPgn = "", "" moveNumber = 0 options = webdriver.ChromeOptions() options.add_argument("start-maximized") options.add_experimental_option("excludeSwitches", ["enable-automation"]) options.add_experimental_option('useAutomationExtension', False) opti...
def _get_pomodoro_by_user_id(self, user_id: int): pomodoro_from_db = self.session.query(Pomodoro).filter( Pomodoro.user_id == user_id).first() if pomodoro_from_db is None: new_pomodoro_scheme = PomodoroSchemas.Update(user_id=user_id) pomodoro_from_db = self._create_ne...
This function updates a user's Pomodoro settings in the database by retrieving the existing settings, applying changes from the provided schema, and saving the updated instance. It ensures user-specific configurations are modified and persisted.
def save_pomodoro_settings(self, pomodoro_scheme: PomodoroSchemas.Update) -> None: pomodoro_from_db = self._get_pomodoro_by_user_id( pomodoro_scheme.user_id) pomodoro_from_db = self._change_pomodoro_in_db_through_update_shceme( pomodoro_from_db, pomodoro_scheme) self._s...
def ConvertToDecimal(bin_val): return int(bin_val, 2) def ConvertToBinary16(dec_val): global expi,manti if(int(dec_val)!=dec_val): f=conversionFloat(dec_val) if(f==0): binval=bin(len(manti)-1)[2:] if(len(manti)<5): manti=manti+"0"*(5-len(manti)) ...
This code performs addition of two 16-bit registers (reg1 and reg2) and stores the result in a third register (to_store). It converts register values to decimal, sums them, and checks if the result equals 1 using conversionFloat(). If true, it sets a flag to 8 and stores 252 in the target register; otherwise, it direct...
def addF(instruction): global Registers,flag to_store = instruction[6:9] reg1 = instruction[3:6] reg2 = instruction[0:3] n=ConvertToDecimal(ConvertToBinary16(Registers[ConvertToDecimal(reg1)])[:8]) + ConvertToDecimal(ConvertToBinary16(Registers[ConvertToDecimal(reg2)])[:8]) f=conversionFloat(n) ...
def ConvertToDecimal(bin_val): return int(bin_val, 2) def ConvertToBinary16(dec_val): global expi,manti if(int(dec_val)!=dec_val): f=conversionFloat(dec_val) if(f==0): binval=bin(len(manti)-1)[2:] if(len(manti)<5): manti=manti+"0"*(5-len(manti)) ...
This function performs a subtraction operation between two registers (reg1 and reg2), stores the result in a target register (to_store), and sets a flag based on specific conditions. If the result is negative, it sets the target register to 0 and flag=8. If a conversion to float equals 1, it sets the target register to...
def subF(instruction): #done global Registers,flag to_store = instruction[6:9] reg1 = instruction[0:3] reg2 = instruction[3:6] n=ConvertToDecimal(ConvertToBinary16(Registers[ConvertToDecimal(reg1)])[:8]) - ConvertToDecimal(ConvertToBinary16(Registers[ConvertToDecimal(reg2)])[:8]) if(n<0): ...
def initialize_with_zeros(dim): w = np.zeros((dim, 1)) b = 0 return w, b def optimize(w, b, X, Y, num_iterations, learning_rate, print_cost = False): costs = [] for i in range(num_iterations): # Cost and gradient calculation grads, cost = propagate(w, b, X, Y) # ...
This code trains a logistic regression model using gradient descent on training data, evaluates it on both training and test sets, calculates accuracy, and returns the optimized parameters (weights, bias) along with cost history for analysis.
def model(X_train, Y_train, X_test, Y_test, num_iterations, learning_rate, print_cost = False): # initialize parameters with zeros w, b = initialize_with_zeros(X_train.shape[0]) # Gradient descent parameters, grads, costs = optimize(w, b, X_train, Y_train, num_iterations, learning_rate, print_cost) ...
def terminal(board): """ Returns True if game is over, False otherwise. """ # Either the player or AI won if winner(board) != None: return True # All cells were filled for row in board: for cell in row: if cell == EMPTY: return False return Fa...
The function `result` generates a new game board after applying a specified move `(i, j)` to the current board. It first verifies if the game is already over (terminal state) or if the action is invalid. If valid, it creates a deep copy of the original board, updates the specified position with the current player's sym...
def result(board, action): """ Returns the board that results from making move (i, j) on the board. """ # Check if terminal or not. Then check if there are any moves left. Then do a deep copy of the previous board and show it. if terminal(board): raise ValueError("Game over.") elif actio...
def double_dummy_playout(state): while not state.is_terminal(): if state.cur_player() == pyhanabi.CHANCE_PLAYER_ID: state.deal_random_card() continue move = double_dummy_action(state) # print('DD') # print(move) state.apply_move(move) return state.score() def deep_copy(worlds): new_worlds = {} new_...
This code performs depth-limited recursive exploration of game states, evaluating all possible moves and their outcomes. It uses double dummy playouts to score terminal states when reaching the search depth limit (M=0). For non-terminal states, it generates all legal moves, creates copies of the game worlds with each m...
def alpha_mu(worlds,M): # get this player and this player's worlds # player_id = ply % NUM_PLAYERS # worlds = all_players_worlds[player_id] # # return score if we're in a terminal state # if state.is_terminal(): # return tuple(state.score() for w in worlds) # return DD results if we're at the end of the searc...
def all_worlds(game,state): obs = state.observation(state.cur_player()) cards = possible_cards(game,obs) my_hand_size = len(obs.observed_hands()[0]) possible_hands = permutations(cards,my_hand_size) worlds = [] for hand in possible_hands: if possible(hand,obs): worlds.append(state.copy()) worlds[-1].set_h...
The PIMC function selects the optimal move in a game by evaluating each legal move's potential through Monte Carlo simulations. It generates either all possible or a limited number (k) of game worlds, applies each move to these worlds, and scores them using double dummy playouts. The move with the highest accumulated s...
def PIMC(game,state,k=None): moves = state.legal_moves() score = [0]*len(moves) if k == None: worlds = all_worlds(game,state) else: worlds = k_worlds(game,state,k) for m,move in enumerate(moves): these_worlds = [w.copy() for w in worlds] for w in these_worlds:#all_worlds(game,state): w.apply_move(move...
def all_worlds(game,state): obs = state.observation(state.cur_player()) cards = possible_cards(game,obs) my_hand_size = len(obs.observed_hands()[0]) possible_hands = permutations(cards,my_hand_size) worlds = [] for hand in possible_hands: if possible(hand,obs): worlds.append(state.copy()) worlds[-1].set_h...
This function determines the optimal action in a game by evaluating potential moves through simulated "worlds" (game states). It generates `k` possible future states (or all if `k=None`), applies each legal move to these states, and calculates a score using the `alpha_mu` heuristic with depth `M-1`. The move yielding t...
def get_alpha_mu_action(game,state,M=2,k=100): moves = state.legal_moves() score = [0]*len(moves) worlds = {} if k == None: worlds['states'] = all_worlds(game,state) else: worlds['states'] = k_worlds(game,state,k) worlds['valid'] = [True]*len(worlds['states']) worlds['score'] = [None]*len(worlds['states'])...
def buildAutoencoder(self, x_input): decodeVariables = {} with tf.variable_scope('autoencoder'): tempVec = x_input tempDim = self.inputDim i = 0 for compressDim in self.compressDims: W = tf.get_variable('aee_W_'+str(i), shape=[tempDim, comp...
This code trains a conditional GAN with pretraining phases. It initializes TensorFlow variables, builds autoencoder, generator, and discriminator networks, and alternates between pretraining the autoencoder, pretraining the GAN (separately training generator and discriminator), and joint training. It saves training sta...
def train(self, dataPath='data', modelPath='', outPath='out', nEpochs=500, discriminatorTrainPeriod=2, generatorTrainPeriod=1, pretrainBatchSize=100, batchSize=1000, pretrainEpochs=100, ...
def get_unique_letters(puzzle): return [i for i in set(''.join(break_puzzle(puzzle))) if i.isalpha()] def get_valid_permutations(puzzle): digits = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] letters = get_unique_letters(puzzle) critical_indices = get_starting_letters(puzzle, letters) poss_per...
The code solves cryptarithmetic puzzles by checking valid digit mappings for unique letters, ensuring no letter repeats a digit. It generates permutations, tests each for equation validity, and returns the correct digit-letter mapping along with the solved puzzle equation.
def solve(puzzle): letters = get_unique_letters(puzzle) if len(letters) > 10: print("INVALID EQUATION : more than one letter maps to same digit") return for poss in get_valid_permutations(puzzle): p = str.maketrans(' '.join(letters), ' '.join(poss)) if correct_vals(p,puzzle):...
def denoise(img): # find all your connected components (white blobs in your image) nb_components, output, stats, centroids = cv2.connectedComponentsWithStats(img, connectivity=8) # connectedComponentswithStats yields every seperated component with information on each of them, such as size # the followin...
The main task of the code is to process 3D planes in an image by detecting connected regions, fitting lines to floor-level segments, and visualizing them with labels. It resizes the image, iterates over plane types, filters regions by size, computes line parameters via regression, validates lines, and draws them on the...
def post_process(im, line, planes): im = cv2.resize(im, dsize=(320, 320)) im = np.array(im) planes = np.array(planes) # print(planes.shape) segment = planes # show(segment * 50) # if plane_type for plane_type in [1, 2, 3]: # continue labeled, nr_objects = ndimage.label(...
def intializeGrid(): global grid, players players = [] for i in range(noPlayers): players.append(playerColor[i]) grid = [[] for _ in range(cols)] for i in range(cols): for j in range(rows): newObj = Spot() grid[i].append(newObj) for i in range(cols): ...
The code defines a game loop for a turn-based grid game where players take turns placing atoms. It handles events like quitting, player input, and mouse clicks to update the grid. The loop manages player turns, updates the game state, applies visual effects (vibration), renders the grid, and maintains a 20 FPS frame ra...
def gameLoop(): intializeGrid() turns = 0 vibrate = 0.5 currentPlayer = 0 loop = True while loop: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.type == pygame.KEYDOWN: ...
def remove_redundant_functions(content): """ Arguments: content: string storing the source code Return type: updated string Functionality: redundant functions in a source code are removed Logic Used: Write a minimal parser that can identify functions. It just needs ...
The function preprocesses source code files by removing comments, macros, and redundant elements, then replaces specific keywords and symbols for C++, Java, and Python. It splits the cleaned content into words, counts their occurrences in each file and across all documents, and passes these counts to a TF-IDF calculati...
def preprocessing(list_of_paths,list_of_files): """ Core logic is based on the Bag_of_Words and TF-IDF Strategy( Term frequency and Inverse Document Frequency ) Arguments : list_of_paths :list of source code paths list_of_files :it consists of list of file names Functio...
def detect_platform(): try: platforms = { 'linux' : 'Linux', 'linux1' : 'Linux', 'linux2' : 'Linux', 'darwin' : 'OS X', } logger.info("[*] Detect Platform") if sys.platform not in platforms: logger.error("[x_x] Your platform currently does not support.") sys.exit(0) except Exception as e: log...
The main task of the code is to detect the operating system (macOS or Linux), log the OS type, execute platform-specific checks (check_runon_osx/linux), handle KeyboardInterrupt exceptions, and terminate services (stoppervice_osx/linux) based on the detected platform. It ensures compatibility and proper shutdown across...
def main(): try: detect_platform() if (sys.platform == 'darwin'): logger.info("[*] Darwin - MAC OS-X") check_runon_osx() if (sys.platform == 'linux') | (sys.platform == 'linux1') | (sys.platform == 'linux2'): logger.info("[*] Linux - KALI LINUX - UBUNTU") check_runon_linux() except KeyboardInterrupt...
def story(): script = {1: "*** Once upon a time, while wandering the world. Our hero " + playerName + " came upon a hole of questionable purpose. ", 2: "Not having anything else going on that day, you step down in the hole and start to look around. ", 3: "As the light fades from above, you turn you...
The main task of the code is to run a text-based game where the player inputs their name, navigates a map via keyboard events, and interacts with a story-driven scenario. The game updates the map and position, checks for an "end" condition, and allows partial restarts. The Listener captures key presses for gameplay, wh...
def main(map, position): global playerName #clear() playerName = input("*** Welcome to depth. ***\n The not so deep game. ***\n What is your name? ") navigate = story() if navigate == "end": choice = input("Game over... Enter R to restart. --This doesn't work yet-- ") #...
def max2(a, b): return (a + b + abs(a - b)) // 2 def fSelect(xs, i): if len(xs) == 0: return -1 # returns an error "Bad index" else: x = head(xs) ys = tail(xs) l = [] s = [] m = [] s.append(x) # O(n) time for y in ys: if y...
The main task of the code is to test and demonstrate the functionality of three functions: `max2()` for finding the maximum of two numbers, and `fSelect()`/`iSelect()` for selecting elements from a list at specified indices. The `main()` function prints results for various input combinations, verifying correctness thro...
def main() -> None: print("max2()-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-") print("Let a = 1 and b = 5: max2(1, 5) -> ", max2(1, 5)) print("Let a = 11 and b = 6: max2(11, 6) -> ", max2(11, 6)) print("Let a = 75 and b = 23: max2(75, 23) -> ", max2(75, 23)) print("Let a = 4 and b ...
def extraSpace(S, M, i, j): if len(S) == 0: return 0 elif M == 0: return 0 else: return M - j + i - summation(S, i, j) def badnessLine(S, M, i, j): if len(S) == 0: return 0 elif M == 0: return float('inf') else: extraSpaces = extraSpace(S, M, i, j)...
The main task of the code is to test and evaluate multiple text formatting functions (`extraSpace`, `badnessLine`, `minBad`, `minBadDynamic`, etc.) by passing different string inputs and line width parameters (`M`). It systematically runs these functions with varying configurations, comparing outputs for different word...
def main() -> None: S1 = ["What is the asymptotic running time of your algorithm?"] S1 = S1[0].split() S2 = ["Hello", "World"] print("extraSpace()-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-") M = 10 i, j = 0, len(S1) - 1 print("Let M = 10, i = 0, and j = len(S) - 1: extra...
def is_table(table: str): """Check if table exists""" command = f"SELECT * FROM pg_catalog.pg_tables WHERE schemaname = 'public';" tables = execute_sql(command) if table in tables: return True return False def new_user_table(name: str): """Create new user's table""" command = f"""...
The main task of the code is to add a new user subscription by inserting channel information into a user-specific database table. It checks if the user's table exists, creates it if necessary, then executes an SQL INSERT command to store the channel ID, name, and pattern. The function returns True on successful inserti...
def new_user_subscription(channel_id: str, channel_name: str, pattern: str, user: str): """Add new sub""" if not is_table(user): new_user_table(user) command = f""" INSERT INTO "{user}" (channel_id, channel_name, pattern) VALUES {(channel_id, channel_name, pattern)} ;""" ...
def avg_vec_of_vecs(vecs): size = len(vecs) avg_vec = [0.0] * 3 for vec in vecs: for i, x in enumerate(vec): avg_vec[i] += x / size return avg_vec def avg_distortion_c0(c0, data, size): return reduce( lambda s, d: s + d / size, (euclid_squared(c0, vec) ...
The code generates a codebook of specified size by iteratively splitting initial centroids to minimize distortion, using an average vector as the starting point and refining it until the desired number of centroids is achieved, with final values floored to integers for use in quantization tasks.
def generate_codebook(data, size_codebook, epsilon=0.00001): data_size = len(data) codebook = [] c0 = avg_vec_of_vecs(data) codebook.append(c0) avg_dist = avg_distortion_c0(c0, data, data_size) while len(codebook) < size_codebook: codebook, avg_dist = split_codebook(data, codebook, e...
def filter(bitmap, x, y, high=False): weights_low = [[1, 1, 1], [1, 1, 1], [1, 1, 1]] wegihts_high = [[0, -1, 0], [-1, 5, -1], [0, -1, 0]] weights = wegihts_high if high else weights_low pix = Pixel(0, 0, 0) for i in range(3): for j in range(3): pix += bitmap[x + i - 1, y + j -...
The code encodes a bitmap by processing low and high frequency components separately. It applies differential coding to the low component, transforms it into a byte array with Elias encoding, pads it to 8-bit chunks, and converts it to bytes. The high component is quantized using parameter `k` and converted to bytes. T...
def encode(bitmap, k): filtered_low = [ filter(bitmap, x, y) for y in reversed(range(bitmap.height)) for x in range(bitmap.width) ] filtered_high = [ filter(bitmap, x, y, True) for y in reversed(range(bitmap.height)) for x in range(bitmap.width) ] low...
def parse_bitmap(bitmap, width, height): return [(bitmap[i * 3], bitmap[i * 3 + 1], bitmap[i * 3 + 2]) for i in range(width*height)] def generate_codebook(data, size_codebook, epsilon=0.00001): data_size = len(data) codebook = [] c0 = avg_vec_of_vecs(data) codebook.append(c0) avg_dist = avg_d...
This script reads a TGA image, extracts its header/footer, parses the bitmap, reduces color depth via quantization using a generated codebook, calculates MSE/SNR metrics, and writes the modified image with original header/footer to an output file.
def main(): if len(argv) != 4: print("main.py [input image] [output image] [color number exponent]") return with open(argv[1], "rb") as f: tga = f.read() header = tga[:18] footer = tga[-26:] width = tga[13] * 256 + tga[12] height = tga[15] * 256 + tga[14] original_b...
def to_pattern_matrix(D): """Returns the Boolean matrix in the same shape as `D` with ones exactly where there are nonzero entries in `D`. `D` must be a NumPy array. """ result = np.zeros_like(D) result[D.nonzero()] = 1 return result def to_bipartite_matrix(A): """Returns the adjacency m...
The function performs the Birkhoff–von Neumann decomposition of a doubly stochastic matrix into a convex combination of permutation matrices. It iteratively identifies perfect matchings in bipartite graphs derived from the matrix, extracts the smallest non-zero entry as a coefficient, and subtracts the corresponding sc...
def birkhoff_von_neumann_decomposition(D): """Returns the Birkhoff--von Neumann decomposition of the doubly stochastic matrix `D`. """ m, n = D.shape if m != n: raise ValueError('Input matrix must be square ({} x {})'.format(m, n)) indices = list(itertools.product(range(m), range(n))) ...
def load_params(self, params_dir): """pass""" for fname in os.listdir(params_dir): full_path = os.path.join(params_dir, fname) # if 'extrinsics' in fname: if full_path.endswith('extrinsics.yaml'): try: child_frame_id, frame_id, tran...
The code initializes an object to either load real parameters from a specified directory or use fake parameters if the directory doesn't exist. It sets up attributes for vertices, edges, intrinsic data, and height values, with strict mode controlling parameter validation. The `load_params` method handles real data load...
def __init__(self, params_dir, strict_mode=False): """pass""" self.vertices = [] self.edges = [] self.intrinsics_dict = {} self.enable = os.path.exists(params_dir) self.strict_mode = strict_mode self.hesai_height = None self.origin_height = None if...
def filename(name : str): whitelist = set('abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ_') return ''.join(filter(whitelist.__contains__, name.replace(" ","_")))+ ".md" def text_for_fish(name : str): return search.run(name) def foto(name : str): results = DDGS().images( keywords=name, ...
The main task of the code is to generate a markdown file for a fish species, writing structured content including a header, descriptive text, and an image link. It creates a file in the "ryby/byry/" directory using a dynamically generated filename, inserts formatted text with a backlink, and embeds an image referenced ...
def byry(name : str): with open("ryby/byry/"+filename(name), "w") as s: s.write("## [back](../index.md) \n" +"# "+name+"\n"+text_for_fish(name) + "\n") foto(name) s.write("![zdjecie ryby :)](../fotki/"+fotoname(name)+")\n")
def brute_force_game_over(board): num_total_pieces = sum(1 for row in board for cell in row if cell != 0) if num_total_pieces < 7: # Assuming 7 is the minimum number to check for game over return 0 max_row, max_col = len(board), len(board[0]) # Check rows and columns for r in range(max_ro...
The code implements the Minimax algorithm with alpha-beta pruning for a board game. It evaluates game states recursively, choosing optimal moves for the maximizing/minimizing player by exploring legal moves, sorting them via heuristic evaluation, and pruning suboptimal branches to improve efficiency. The function retur...
def minimax(board, depth, alpha, beta, maximizingPlayer, depth_reached=0): depth_reached += 1 game_over_status = brute_force_game_over(board) if ( depth == 0 or game_over_status != 0 or not get_legal_moves(board) or not get_legal_moves(board) ): return evaluate( ...
def get_legal_moves(board): legal_moves = [] for col_index in range(N): # Iterate through each column if board[col_index][0] == 0: # Check if the top cell of the column is empty legal_moves.append(col_index) # If empty, it's a legal move return legal_moves def evaluate(board, player, ...
This code implements the minimax algorithm with alpha-beta pruning and move ordering for a game AI. It evaluates legal moves on a board, recursively determines the best move by simulating outcomes, and selects the optimal action for the given player (maximizer or minimizer) based on heuristic evaluations. If no valid m...
def AI(board, player, depth): bestMove = None bestValue = -math.inf if player == 1 else math.inf legal_moves = get_legal_moves(board) # order moves by best to worst using the heuristic legal_moves.sort( key=lambda x: evaluate(make_move(copy.deepcopy(board), x, player)[0], player), re...
def get_legal_moves(board): legal_moves = [] for col_index in range(N): # Iterate through each column if board[col_index][0] == 0: # Check if the top cell of the column is empty legal_moves.append(col_index) # If empty, it's a legal move return legal_moves def brute_force_game_over(bo...
This code implements a turn-based game between a human player and an AI, using a minimax algorithm with a specified search depth. The game alternates turns, validates human input, and evaluates the board state. It declares a winner or draw based on game-over conditions, displaying the board and results after each move.
def human_vs_ai(who_moves_first=HUMAN_PLAYER, max_depth=4): files = list("ABCDEFGHIJKLMNOPQRSTUVWXYZ") last_file = files[N - 1] board = get_blank_board() current_player = who_moves_first game_status = 0 # 0 means the game is ongoing while game_status == 0 and get_legal_moves(board): pr...
def update_mod_repo(): if not os.path.exists(MOD_REPO_NAME): subprocess.call(["git", "clone", MOD_REPO_URL]) subprocess.call(["git", "pull", "origin", "dev"], cwd=os.path.realpath(MOD_REPO_NAME)) subprocess.call(["git", "switch", "dev"], cwd=os.path.realpath(MOD_REPO_NAME)) subprocess.call(...
The main task of the code is to create a translation directory, update a module repository, generate templates, load translation data, normalize newline characters in source/target texts, and apply translations to templates via the `update` function. It prepares and processes translation files for a specified language ...
def main(): os.makedirs(os.path.join(TRANSLATION_DIRECTORY, LANGCODE), exist_ok=True) update_mod_repo() templates = generate_templates() translation_data = load_translation(os.path.join(TRANSLATION_DIRECTORY, LANGCODE), exculde_fuzzy=False) for v in translation_data.values(): v.source = ...
def glTransform(self, vertex, translate=(0, 0, 0), scale=(1, 1, 1)): '''Transforms vertex into tuple''' try: return V3( (int(round((vertex[0]+1) * self.width / 2)) + translate[0]) * scale[0], (int(round((vertex[1]+1) * self.height / 2)) + translate[1]) * scale...
This function loads and renders a 3D .obj model, applying transformations (translate/scale), calculating face normals and lighting intensity, and rendering triangles with optional texture mapping or intensity-based color. It processes each face's vertices, computes lighting, skips dark faces, and uses texture coordinat...
def glLoadObjModel(self, file_name, texture=None, translate=(0,0, 0), scale=(1,1, 1)): '''Load and Render .obj file''' #Reads .obj file model = ObjReader(file_name) model.readLines() light = V3(0, 0.4, 1) for face in model.faces: vertices_ctr = len(f...
def compute_PSNR(img1, img2, data_range): if type(img1) == torch.Tensor: mse_ = compute_MSE(img1, img2) return 10 * torch.log10((data_range ** 2) / mse_).item() else: mse_ = compute_MSE(img1, img2) return 10 * np.log10((data_range ** 2) / mse_) def compute_SSIM(img1, img2, data_r...
The code computes image quality metrics (PSNR, SSIM, RMSE) for both original (x vs y) and predicted (pred vs y) image pairs, returning them as two tuples of values. It uses data_range for PSNR/SSIM calculations, with RMSE computed separately.
def compute_measure(x, y, pred, data_range): original_psnr = compute_PSNR(x, y, data_range) original_ssim = compute_SSIM(x, y, data_range) original_rmse = compute_RMSE(x, y) pred_psnr = compute_PSNR(pred, y, data_range) pred_ssim = compute_SSIM(pred, y, data_range) pred_rmse = compute_RMSE(pred,...
def init_bet(self): if self.player.is_bot: self.bet(0, self.player.get_bet()) else: os.system('clear') bet = input("Bet: ") if bet: bet = int(bet) else: bet = self.player.BET_DEFAULT self.bet(0, bet) ...
This function simulates a Blackjack round by initializing bets and hands, handling player turns (hit/stand/double/split) for each hand, processing dealer's draw until reaching 17, resolving outcomes, displaying results, and collecting bets. It manages both human and bot players through action logic, ensuring game flow ...
def play_round(self): self.init_bet() self.init_draw() for i_player_hand, player_hand in enumerate(self.player_hands): # player's turn while True: # player round if self.sum(player_hand) >= 21: break self.display() ...
def init(self): self.reshuffle() self.player.reset() self.player_chips_history = [self.player.chips] self.earning_rate_history = [] self.earning_rate = None self.residual = None self.n_rounds = 0 def fit_chips_history(self): x = [i for i in range(len(self....
The code simulates a game with a maximum number of rounds (n_rounds_max), allowing a bot or human player to interact. It runs rounds automatically for bots or waits for user input ("e", "exit", etc.) to proceed. Progress is periodically displayed, and the loop exits when reaching the round limit, user quit, or residual...
def play_game(self, n_rounds_max=1E5, residual_threshold=2E-6, n_rounds_min=1E3): self.init() while True: if self.n_rounds == n_rounds_max: self.fit_chips_history() break if self.player.is_bot: self.play_round() else: ...
def getAllCommands(): global helpCommands return {**helpCommands[0], **helpCommands[1]} def getInvalidServiceMessage(): allCommands = getAllCommands() services = list(allCommands.keys()) serviceList = "" for service in services: serviceList += "- {}\n".format(service) return "...
This function retrieves available commands for a specified service, validates the service's existence, and returns a formatted help message listing commands with a trusted-user restriction notice.
def getHelpForService(service): allCommands = getAllCommands() if (service not in allCommands): return getInvalidServiceMessage() return "Syntax: `.{} [command]`\nAvailable commands for service {}:\n{}*Trusted users only".format(service, service, getCommands(service))
def getAllCommands(): global helpCommands return {**helpCommands[0], **helpCommands[1]} def getInvalidServiceMessage(): allCommands = getAllCommands() services = list(allCommands.keys()) serviceList = "" for service in services: serviceList += "- {}\n".format(service) return "...
This function checks if a given service is valid by comparing it against a list of all commands. If invalid, it returns an error message; if valid, it formats a response showing the correct syntax and lists available commands for that service.
def commandError(service): allCommands = getAllCommands() if (service not in allCommands): return getInvalidServiceMessage() return "Syntax: `.{} [command]`\nThis is not a valid command for {}, please pick from the following:\n{}".format(service, service, getCommands(service))
def _aggregate_and_get_out_losses(self, masks: List, attention_store: AttentionStore, indices_to_alter: List[int], attention_res: int = 16): """ Aggregates the...
This function performs iterative refinement of latent variables in a diffusion model to minimize token-specific losses. It updates latents using gradient descent until the loss falls below a threshold or reaches a maximum iteration limit, focusing on tokens with highest losses. The process tracks progress, adjusts late...
def _perform_iterative_refinement_step(self, masks: List, latents: torch.Tensor, indices_to_alter: List[int], loss: torch.Tensor, ...
def init_prompt(self, prompt: str): uncond_input = self.model.tokenizer( [""], padding="max_length", max_length=self.model.tokenizer.model_max_length, return_tensors="pt" ) uncond_embeddings = self.model.text_encoder(uncond_input.input_ids.to(self.model.device))[0] ...
This function performs DDIM inversion on an input image using a given prompt, returning the inverted latent representations. It initializes the prompt, loads the image with specified offsets, executes the inversion process, and outputs the resulting latents for further use in generative tasks.
def invert(self, image_path: str, prompt: str, offsets=(0,0,0,0), num_inner_steps=10, early_stop_epsilon=1e-5, verbose=False): self.init_prompt(prompt) image_gt = load_512(image_path, *offsets) if verbose: print("DDIM inversion...") _, ddim_latents = self.ddim_inversion(image...
def _aggregate_and_get_out_losses(self, masks: List, attention_store: AttentionStore, indices_to_alter: List[int], attention_res: int = 16): """ Aggregates the...
This code performs iterative image generation using a diffusion model with text-to-image synthesis. It refines latent variables through gradient-based optimization, leveraging attention mechanisms to align generated images with prompts. Key steps include denoising with UNet, computing losses from attention stores, and ...
def __call__( self, max_refinement_steps: int, prompt: Union[str, List[str]], attention_store: AttentionStore, indices_to_alter: List[int], attention_res: int = 16, height: Optional[int] = 512, width: Optional[int] = 512, ...
def process_variable(self, item: object) -> object: """Substitute environment variables into a string value. Return `item` as-is if not `.is_process_variable` or if `item` is not a string. For each `$NAME` and `${NAME}` in `item`, substitute with the value of the environment va...
This function recursively loads data from include files referenced in a dictionary value. It processes the INCLUDE_KEY to resolve filenames, tracks the file hierarchy in parent_filenames, and replaces the value with loaded data (or a JMESPath query result). The loop continues until no more includes are processed, retur...
def load_include_file( self, value: object, parent_filenames: list = None, ) -> tuple: """Load data if value indicates the root file or an include file. :param value: Value that may contain file name to load. :param parent_filenames: Stack of parent file names. ...
def get_filename(self, filename: str, parent_filenames: list) -> str: """Return absolute path of filename. If `filename` is a relative path, look for the file but looking in the directories containing the parent files, then the current working directory, then each path in `.include_path...
The code processes an input YAML file by resolving includes, applying variable processing, and validating data against a schema, then outputs the transformed data to a specified file or stdout.
def process_data(self, in_filename: str, out_filename: str) -> None: """Process includes in input file and dump results in output file. :param in_filename: input file name. :param out_filename: output file name. """ in_filename = self.get_filename(in_filename, []) root =...
def params(ndims, ksize, stride, padding, dilation): def ret(v): if isinstance(v, int): return ndims*[v] else: return v return ret(ksize) + ret(stride) + ret(padding) + ret(dilation) def ksize(dim, params): return params[dim] def output(input_shape, dim, ndims, params...
The function `unfold` transforms an input tensor `x` by calculating output dimensions based on given `default_params` and reshaping `x` into a new tensor `y` with computed dimensions. It uses helper functions to determine kernel sizes, output shapes, and channel counts, then initializes a zero tensor `y` and applies a ...
def unfold(default_params, x): in_shape = list(x.shape)[2:] batch_size = x.shape[0] ndims = len(x.shape)-2 _params = params(ndims, **default_params) + list(x.shape) out_shape = [ksize(dim, _params) for dim in range(ndims)] + \ [output(in_shape, dim, ndims, _params) for dim in range(ndims)] ...
def params(ndims, ksize, stride, padding, dilation): def ret(v): if isinstance(v, int): return ndims*[v] else: return v return ret(ksize) + ret(stride) + ret(padding) + ret(dilation) def ksize(dim, params): return params[dim] def output(input_shape, dim, ndims, params...
The function `fold` computes output dimensions and parameters for a convolutional operation, then returns a transformed tensor using these parameters and input `y`. It calculates spatial output shapes, channel counts, and batch dimensions, initializing a zero tensor `x1` before applying the `coln` function to process i...
def fold(default_params, x, y): in_shape = list(x.shape)[2:] batch_size = x.shape[0] ndims = len(x.shape)-2 _params = params(ndims, **default_params) + list(x.shape) out_shape = [ksize(dim, _params) for dim in range(ndims)] + \ [output(in_shape, dim, ndims, _params) for dim in range(ndims)] ...
def params(ndims, ksize, stride, padding, dilation): def ret(v): if isinstance(v, int): return ndims*[v] else: return v return ret(ksize) + ret(stride) + ret(padding) + ret(dilation) def ksize(dim, params): return params[dim] def output(input_shape, dim, ndims, params...
The code processes a 2D input tensor `x` by calculating output dimensions based on kernel sizes and default parameters. It initializes tensors `y1` and `x1`, applies transformation functions `ncol` and `coln` to compute intermediate results, and returns the transformed output `y`. The task involves reshaping, convoluti...
def test2d(x): in_shape = list(x.shape)[2:] batch_size = x.shape[0] ndims = len(x.shape)-2 _params = params(ndims, **default_params) + list(x.shape) out_shape = [ksize(dim, _params) for dim in range(ndims)] + \ [output(in_shape, dim, ndims, _params) for dim in range(ndims)] _params ...
def params(ndims, ksize, stride, padding, dilation): def ret(v): if isinstance(v, int): return ndims*[v] else: return v return ret(ksize) + ret(stride) + ret(padding) + ret(dilation) def ksize(dim, params): return params[dim] def output(dim, ndims, params): return...
This function processes a tensor `x` by determining its dimensionality, computing output shapes using predefined parameters, initializing tensors, and applying a transformation via the `ncol` function. It adjusts for different input formats (3D/4D) and returns the transformed output tensor `y2`, likely for a custom 2D ...
def test2d(x): if len(x.shape) == 4: _injest_dim = 2 elif len(x.shape) == 3: _injest_dim = 1 else: _injest_dim = 0 channel = x.shape[1] in_shape = list(x.shape)[_injest_dim:] ndims = len(x.shape)-_injest_dim _params = params(ndims, **default_params) + list(x...
def make_thicknesses(self): if "dep_top" in self.xyz.layer_params: return np.diff(self.xyz.layer_params["dep_top"].values) return get_vertical_discretization_time( self.times, sigma_background=0.1, n_layer=self.n_layer-1 ) def make_misfit(self, thi...
The code defines a method `make_inversion` that constructs an inversion process using thicknesses generated by `make_thicknesses`. It returns a `BaseInversion` object, which encapsulates an inverse problem created with a misfit function, regularization, and optimizer. The inversion is further configured with directives...
def make_inversion(self): thicknesses = self.make_thicknesses() return inversion.BaseInversion( inverse_problem.BaseInvProblem( self.make_misfit(thicknesses), self.make_regularization(thicknesses), self.make_optimizer()), self.make...