dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def _add_transaction(self, amount, date): """Process GUI input for adding a transaction and update the selected account.""" try: self._selected_account.add_transaction(amount, self._session, date) self._session.commit() logging.debug("Saved to bank.db") except...
This code handles adding a transaction by retrieving the input amount and date, saving the transaction, clearing the input form, updating the transaction list and summary, and re-enabling the add button.
def add_callback(amount): date = date_entry.get_date() self._add_transaction(amount, date) for widget in self._add_transaction_frame.winfo_children(): widget.destroy() self._add_transaction_frame.grid_forget() self._list_transactions() ...
def _refresh_current(self): """Refresh the current status data.""" self.current_status = self._get_current_status() self.status = self.current_status.status self.timestamp = self.current_status.updated self.level = self._get_level_from_status(self.status) def _get_status(self): ...
This method checks if the status from a universal hub has changed, validates the new status data, logs updates, reports errors for invalid data, and updates the stored status if a valid change is detected. It returns a boolean indicating whether the status changed.
def check_status(self): """Check for a new status value on universal hub.""" self._refresh_current() # Get new values new_status = self._get_status() new_level = self._get_level_from_status(new_status) self.logger.info('Status: current=%s, new=%s', self.status, new_statu...
def get_height(dictionary, name = 'camera'): from osgeo import gdal import struct ##### open DEM file and get projection information DemDs = gdal.Open(dictionary['dem_file_tif']) gt=DemDs.GetGeoTransform() dem_band=DemDs.GetRasterBand(1) ##### identify pixel position of point in raster m...
The main task of the code is to generate input parameters for a georeferencing tool (e.g., PRACTISE) by processing DEM and image files. It converts DEMs to WGS84, calculates camera/target coordinates, derives orientation angles, and stores parameters in a JSON file for further processing. The function prepares geospati...
def create_input(dem_file_in, img_file_in, out_dir, name_of_run, yaw, pitch, roll, hFOV, vFOV, img_rows, img_cols, dem_parameters, camera_utm_lon, camera_utm_lat, camera_offset): # import required libraries and submodules of georef_webcam import collections, json, os, subprocess from osgeo import gdal ...
def sendServer(self, client, data): json_string = json.dumps(data) encrypted_data = self.a3E.start_encryption(json_string, self.getting_key()) content = bytes(encrypted_data, "utf-8") client.send(content) def recvServer2(self, client): try: # Initialize an empty strin...
The code handles user login by collecting email/password, sending them to a server, and processing the response. It updates authentication, auction, and bid data if login succeeds, displays status messages, and manages exceptions.
def login(self, client): try: email: str = str(input("Enter email: ")) password: str = str(input("Enter password: ")) data_form = [email, password] new_data = {"type": "login", "data": data_form} # print(new_data) self.sendServer(client, n...
def setPlayer(): name = input('What is your name?\n') gameState.setPlayer(Player(name)) def selectOpponent(): printOpponentChoices() index = None while True: index = input('\nEnter a number to select your opponent: ') if index.isdigit(): index = int(index) - 1 ...
The main task of the code is to run a turn-based game where a player interacts with an opponent, making choices (1-4) that influence experience and points. The loop processes player input, opponent actions, random chance, and updates game state until the player exits. It handles different choices, updates scores, check...
def runGame(): scene1() setPlayer() scene2() selectOpponent() printGameStartMessage(gameState.player.name, gameState.opponent.name) while not gameState.status == 'exit': playerChoice = getPlayerChoice() opponentAction = getOpponentAction() chance = randint(0, 100) ...
def __check_all_tables_are_local(self,query): all_local = True query_duckdb = transpile(query, read=constants.BIGQUERY, write=constants.DUCKDB)[0] for table in parse_one(query_duckdb).find_all(exp.Table): if not table.name in self.__metadata_dict: raise ValueError("Th...
The code executes a query by selecting between DuckDB and BigQuery based on whether all referenced tables are local. If all tables are local, it prioritizes DuckDB for execution; otherwise, it uses BigQuery. This decision ensures optimal performance by leveraging DuckDB for local data and BigQuery for external data sou...
def exec_query(self,query): if self.__check_all_tables_are_local(query): #All things equal duckDB is prioritized return self.__exec_query_duckdb(query) else: return self.__exec_query_bq(query)
def parse_bool(s: str) -> bool: if s.lower() == "true": return True elif s.lower() == "false": return False else: raise ValueError(f"Could not parse '{s}' as true/false") def write_memory(self, memory: Memory) -> None: cmd = memory.to_mt() result = self.send_cmd(cmd) ...
The main task of the code is to read a CSV file containing memory configurations for a radio, parse each row into structured Memory objects with validated parameters, write these memories to the radio, and finally tune the radio to channel 1. It handles data conversion, error checking during parsing, and uses progress ...
def write_memories(self, csv_path: Path) -> None: # Read CSV file memories = [] with csv_path.open() as csv_file: reader = DictReader(csv_file) for row in reader: try: mem = Memory( channel=int(row["channel"]), ...
def isRealHand(hand): if (hand.size > 5) or (hand.size < 1): return 0 if hand.size==1: return 1 if hand.size==2: if isPair(hand): return 1 else: return 0 if hand.size==3: if isThreeOfAKind(hand): return 1 else: ...
This function validates if a given hand is a legal play in a card game, checking against the previous hand and control status. It ensures the hand is real, matches size requirements, and adheres to specific ranking rules (e.g., pairs, straights, flushes). It returns 1 if valid, 0 otherwise, with control=1 allowing any ...
def validatePlayedHand(hand, prevHand, control): if not isRealHand(hand): return 0 if control==1: return 1 #can play any real hand with control if hand.size != prevHand.size: return 0 #must be same size if not in control hand.sort() prevHand.sort() if hand.size ...
def RandomPick(): global activeMusic, musicManager, artistSelector, musicSelector, currentArtist while True: artistSelector = random.randint(0, len(musicManager["Artists"])-1) musicManager["Musics"] = os.listdir(musicList+musicManager["Artists"][artistSelector]) musicSelector...
The main task of the code is to handle skipping to the next music track, managing music/artist selection logic based on mixedMode status, updating playback state, and ensuring proper navigation through music lists while avoiding repetition. It tracks previous tracks, adjusts selectors, and triggers music loading/proces...
def Skip(): global activeMusic, musicManager, artistSelector, musicSelector, started, musicProgress, currentArtist if activeMusic not in musicManager["prevMusics"] and activeMusic != "": musicManager["prevMusics"].append(activeMusic) musicProgress = 0 if mixedMode: if musicManager["...
def prepare_sequence(seq, to_ix, max_len_sent, pad=True): idxs = [to_ix[w] if w in to_ix.keys() else len(to_ix.keys()) for w in seq] if (len(idxs) < max_len_sent) and pad: idxs = pad_with_zeros(idxs, max_len_sent, len(to_ix)) return idxs def eval_model(model, loss_function, validation_data, word_to_...
The function `train_model` trains a neural network model on sequence tagging tasks (e.g., NER) using batched training data. It iterates over epochs, processes input sentences and tags in batches, computes loss via a specified function, and updates model parameters using an optimizer. It tracks training loss and accurac...
def train_model(model, optimizer, loss_function, max_epochs, training_data, word_to_ix, tag_to_ix, validation_data, max_len_sent, batch_size=128): print('train model : \n') # early stopping params rounds_without_improvement = 0 patience = 5 best_acc = -1 for epoch in range(max_ep...
def baseline_tag_sentence(sentence, perWordTagCounts, allTagCounts): """Returns a list of pairs (w,t) where each w corresponds to a word (same index) in the input sentence. Each word is tagged by the tag most frequently associated with it. OOV words are tagged by sampling from the distribution of all ta...
The function `tag_sentence` tags each word in a given sentence with a corresponding part-of-speech tag using a specified model. It supports four models: baseline (using word/tag frequency counts), HMM (transition/emission probabilities), and two BiLSTM variants (with or without case information). The function routes in...
def tag_sentence(sentence, model): """Returns a list of pairs (w,t) where pair corresponds to a word (same index) in the input sentence. Tagging is done with the specified model. Args: sentence (list): a list of tokens (the sentence to tag) model (dict): a dictionary where key is the model ...
def prepare_sequence(seq, to_ix, max_len_sent, pad=True): idxs = [to_ix[w] if w in to_ix.keys() else len(to_ix.keys()) for w in seq] if (len(idxs) < max_len_sent) and pad: idxs = pad_with_zeros(idxs, max_len_sent, len(to_ix)) return idxs def prepare_sequence_case_base(seq, to_ix, max_len_sent, pad=T...
This function trains a sequence model for classification tasks using batched training data, computes loss and accuracy, and implements early stopping based on validation performance. It processes input sequences, handles padding, and updates model parameters via backpropagation. If validation data is provided, it evalu...
def train_model_case_base(model, optimizer, loss_function, max_epochs, training_data, word_to_ix, tag_to_ix, validation_data, max_len_sent, batch_size=128): print('train model : \n') # early stopping params rounds_without_improvement = 0 patience = 5 best_acc = -1 for e...
def process_data(train_data, val_data, train_percentage): max_len_sent = [] # create validation set if not given: if val_data is None: train_split_lens = math.floor(int(len(train_data) * train_percentage)) validation_lens = len(train_data) - train_split_lens # create list in the size...
The main task of the code is to train a BiLSTM model for sequence tagging using annotated data. It processes input data, initializes loss and optimizer, and trains the model over multiple epochs with optional validation. The function handles different input representations, splits training data if no validation is prov...
def train_rnn(model_dict, train_data, val_data=None): """Trains the BiLSTM model on the specified data. Args: model (dict): the model dict as returned by initialize_rnn_model() train_data (list): a list of annotated sentences in the format returned by load_annotated_...
def rho_interpolation(features, rho): features0, features1 = balance_masks(features == 0, features == 1) return np.logical_or( subsample_mask(features0, 1 - rho), subsample_mask(features1, rho) ) def cap_mask(mask, N): """Cap the magnitude of `mask` to `N` by subsampling.""" if sum(mask) > N: return s...
The code generates a binary mask to separate distractor features based on discriminator labels (0/1), using interpolation parameters rho0 and rho1. It creates masks for each class, expands them to the full dataset, caps their sizes, balances their distributions, ensures non-overlapping, and validates statistical proper...
def condition_mask(discriminator_features, distractor_features, rho0, rho1, N): # Masks for each of `discriminator` in {0, 1}. distractor_mask0 = rho_interpolation( distractor_features[discriminator_features == 0], rho0 ) distractor_mask1 = rho_interpolation( distractor_features[discriminator_features ...
def resize(self): self.size = int(math.sqrt(3/8*math.pi*self.mass)) def v_set(self, s_x, s_y): speedVector = math.sqrt(math.pow(s_x, 2) + math.pow(s_y, 2)) factor = 0 if (self.type == 'photon'): if (speedVector == GLOBAL.LIGHT_SPEED): factor = 1 e...
This code handles a collision between two particles by merging the smaller one into the larger. It conserves momentum by calculating new velocities based on combined mass, resizes the larger particle, marks the smaller for deletion, and returns a flag (0 or 1) indicating which particle was deleted.
def collision(self, particle): #make it bigger if (self.mass>particle.mass): self.mass+= particle.mass self.resize() #momentum transfer speedX = (self.p_x + particle.p_x)/self.mass speedY = (self.p_y + particle.p_y)/self.mass self.v...
def collision(self, particle): #make it bigger if (self.mass>particle.mass): self.mass+= particle.mass self.resize() #momentum transfer speedX = (self.p_x + particle.p_x)/self.mass speedY = (self.p_y + particle.p_y)/self.mass self.v...
This function calculates gravitational forces between particles in a spherical universe, applying different collision thresholds based on particle types (e.g., photons, matter, anti-matter). It skips self-interaction and deleted particles, computes distances with wrap-around logic, and updates a global gravity array. O...
def macro_gravity(self, index, particles): if (self.deleted): return for i in range (len(particles)): if i == index: # don't calculate gravity on self continue elif (particles[i].deleted): #if deleted skip continue ...
def check_rawray_install(): if not check_game_install(): return False rawray_path = get_rawray_path() if not rawray_path or not rawray_path.is_dir(): typer.echo(f"RawRay not installed?") return False return True def get_game_path(): global config if config and "game_...
This function injects a modified LuaJIT debugger into specified Lua 5.1 DLL files within a game's binaries directory, enabling debugging capabilities. It checks for Rawray installation, locates game and Rawray paths, then uses a helper module to inject the debugger DLL into target Lua binaries, enhancing the game's run...
def debugger_inject(): if not check_rawray_install(): return import helpers.debugger_injector game_path = get_game_path() rawray_path = get_rawray_path() paths = (game_path / 'binaries/lua51.dll', game_path / 'binaries_dx12/lua51.dll') luajit2_path = rawray_path / 'addons/debugger/dbg...
def _load_config(self): with open(self.config_path, 'r') as file: self.config = json.loads(file.read()) def load_gh_user_repos(self): from urllib.request import urlopen if "github_users" not in self.config: return self._make_repos_path() for user, p...
The main task of the code is to parse command-line arguments for downloading mod sources, loading a config file, and either updating repositories or modifying a launch configuration. It processes `-c` for the config file path, `-u` to update/pull mods, and `-l` to adjust `launch.json` with mod paths. The code initializ...
def main(self): import argparse parser = argparse.ArgumentParser(description='Downloads mod sources') parser.add_argument('-c', metavar='--config', type=pathlib.Path, dest="config_path", nargs='?', required=True, help='input config.json file') parser.add_argument('-u', dest="update", ac...
def get_graph_cliques(matches, all_images_paths): unstructured_cliques = find_cliques(matches, remaining_images=all_images_paths) cliques = filter_nested_lists(unstructured_cliques, result=[]) return cliques def get_matches_by_image(all_matches, image_path): res = [] for img_path1, img_path2 in all_...
The function groups images into cliques based on match relationships, identifies the largest clique, expands it by adding images that meet a match threshold, creates a bucket for this clique, and recursively processes remaining images. It aims to organize images into buckets by analyzing and filtering matches to ensure...
def bucket_images(matches, images_to_bucket): if not images_to_bucket: return cliques = get_graph_cliques(matches, all_images_paths=images_to_bucket.copy()) if not cliques: return largest_clique = max(cliques, key=len) images_to_bucket = [img for img in images_to_bucket if img not in...
def check_for_nodes(self): # check for empty list if self.head == None: print('*** Empty List ***') return False else: return True def remove_first(self): if self.check_for_nodes() is False: return self rem_val = self.head.value # ...
This method removes a node with a specified value from a linked list. It checks if the list is empty, removes the head node if the value matches, iterates through the list using a runner to find and remove the target node, and handles the last node case. If the value isn't found, it notifies the user. The method return...
def remove_value(self, val): # removes node with this value if self.check_for_nodes() is False: return self if self.head.value == val: # check to see if value is first in the list self.remove_first() return self runner = self.head # set up a ...
def incsize(self,m=1): for i in range(m): self.elbows.append([self.size+i+1,self.size+i+1]) self.size += m self.__init__(self.size,self.elbows,1) def mindroop(self,location): crosses = [b.location for b in self.boxes if b.filling == 3] bumps = [b.location...
The code implements a left insertion step in a grid-based permutation algorithm. It adjusts the position (`pos`) of an element based on box fillings (4, 5, 6) and pipe crossings. If the element's target column exceeds grid size, it expands the grid. It iteratively moves `pos` downward/upward to avoid conflicts, swaps p...
def leftinsertionstep(self,biletter,latex=0): b = biletter[0] if b > self.size: self.incsize(b-self.size) k = biletter[1] i = b for t in range(self.size): check = [box for box in self.boxes if box.location == [b,t+1] and box.fill...
def incsize(self,m=1): for i in range(m): self.elbows.append([self.size+i+1,self.size+i+1]) self.size += m self.__init__(self.size,self.elbows,1) def mindroop(self,location): crosses = [b.location for b in self.boxes if b.filling == 3] bumps = [b.location...
The main task of the code is to insert a letter (`biletter`) into a structured grid (`self.boxes`) following specific rules. It adjusts the grid size if needed, identifies a valid position based on filling states (4, 5, 6), and navigates through potential pipe crossings. The function iteratively modifies the position (...
def rightinsertionstep(self,biletter,latex=0): b = biletter[0] if b > self.size: self.incsize(b-self.size) k = biletter[1] i = b for t in range(self.size-1,-1,-1): check = [box for box in self.boxes if box.location == [b,t+1] and...
def find_tuning_frequencies(tune="standard"): """ Function finds the frequencies of all the notes of a same tuning set. It does so with help from the tone difference relative to the standard tuning. """ guitar_tuning_pitches = [] # For each note of the tuning set, calculate (from the tone diffe...
This function identifies the closest frequency in a specified guitar tuning to an input frequency, then returns the matched frequency, its corresponding musical note (with octave), and related tuning data. It calculates the nearest note using pitch index math, determines adjacent higher/lower notes, and provides the gu...
def get_target_note(instrument_pitch, tune="standard"): """ Function searches the closest matching frequency from a given guitar tune and a given input frequency. It then returns that frequency and the given guitar tune's frequency and string representations of notes. """ # comparison func...
def subtrees(tree: Tree) -> List[Tree]: _, st = tree return st def show_attr(attr: Attr) -> str: done_mark = "x" if attr["done"] else " " s = "[" + done_mark + attr["priority"] + "] " s += attr["label"] for t in attr["tags"]: s += " #" + t return s def attributes(tree: Tree) -> Attr:...
The function recursively traverses a tree structure to collect and format leaf node information into a buffer string. It appends attributes, tags, and hierarchical addresses of leaves, filtering by urgency and completion status. Subtrees are processed with prioritization, skipping non-urgent or completed nodes based on...
def show_leaves(tree: Tree, tags: list = None, address=" ", buffer="", urgent_only=True, show_done=False): if tags is None: tags = [] if not subtrees(tree): buffer += show_attr(attributes(tree)) + ''.join((" #" + t) for t in tags) + address + "\n" else: tags = tags + attributes(tree...
def loadDataFiles(): """ Load the time series in data_files. Return input_df_set, the dictionary that contains the Pandas DataFrames for each of the files in data_files. The keys correspond to the file names in data_files. """ global input_df_set; # No need to load the data if it is already i...
The function computes and returns a DataFrame containing similarity (e.g., ZNCC, Pearson, SSIM) and dissimilarity (e.g., MSE, NRMSE) metrics between time series from two input files. It smooths data using a specified window, handles missing values, ensures alignment, and saves results as CSV. Metrics quantify correlati...
def getSimilarityMetrics(file1, file2, window) -> pd.DataFrame: """Compute the similarity metrics between the time series contained in two data files (file1 and file2). Note that file1 and file2 may be equal. If required, the data is smoothed using a filter (window). Similarity metrics considered here ...
def performAction(self, agentName, action): cost_s = self.shark_cost_s cost_m = self.shark_cost_m if "fish" in agentName: cost_s = self.fish_cost_s cost_m = self.fish_cost_m wrong_penalty = cost_m * 3 x = self.agentData[agentName]["x"] y = self.age...
The code processes agents' actions, calculates rewards based on food collection, checks for agent deaths or environment termination conditions, and returns observations, rewards, terminations, truncations, and info for each agent in a multi-agent environment.
def step(self, actions): """ step(action) takes in an action for each agent and should return the - observations - rewards - terminations - truncations - infos dicts where each dict looks like {agent_1: item_1, agent_2: item_2} The action order sh...
def delete_files(folder): for filename in os.listdir(folder): file_path = os.path.join(folder, filename) try: if os.path.isfile(file_path) or os.path.islink(file_path): os.unlink(file_path) elif os.path.isdir(file_path): shutil.rmtree(file_path...
The code generates a video from predicted images for each batch in a specified range. It processes batches from 'initial' to 'final' (determined by 'k' or default 1-13), deleting prior files, running inference, and compiling resulting images into MP4 videos using OpenCV. Each batch's output images are sorted, written f...
def get_prediction_graph_video(folder, k=None): if k: initial = k final = k+1 else: initial = 1 final = 13 for i in range (initial, final): delete_files(folder) create_dir(folder) inference(i, folder) x = os.listdir(folder) x.sort() ...
def sample_dev(self): select_index = random.sample(range(len(self.train_y)), self.eval_size) test_tr_x = self.train_x[select_index] test_tr_y = self.train_y[select_index] return test_tr_x, test_tr_y def adjust_learning_rate(self, optimizer, epoch, lr_decay=0.5, lr_decay_epoch=50): ...
The code trains a model using Adam optimizer with learning rate decay, iterating over batches to compute negative log-likelihood loss, backpropagating gradients, and clipping norms. It evaluates model performance on test/validation data after each epoch, tracks metrics (precision, recall, F1), and saves the best model ...
def train(self): self.test_train_x, self.test_train_y = self.sample_dev() optimizer = optim.Adam(filter(lambda p: p.requires_grad, self.model.parameters()), lr=self.lr, weight_decay=self.weight_decay) num_each_epoch = int(np.round(len(self.train_y) / self.batch_...
def replay(self): # restoring default values self.score = 0 self.word_value = "" self.is_game_over = False self.running = False self.uninitialize() # and packing plus misc self.reinitialize() def start_run(self, *args, **kwargs): if not self.is_gam...
The code initializes a typing game GUI with a score tracker, word display, input field, and timer. It sets up event bindings for starting the game, handling user input, and aborting. The game reads words from a file, displays a random word, and tracks time remaining, preparing to start the game upon key press.
def __init__(self, parent): tk.Frame.__init__(self, parent) self.parent = parent #mainframe and stuff self.configure(bg=cfg.default_bg) self.pack(expand=True) self.score = 0 self.central_frame = tk.Frame(self, bg=cfg.default_bg) self.central_frame.grid(...
def _left_rotate(self, x): y = x.right B = y.left y.parent = x.parent y.left = x if y.parent is None: self.root = y elif y.parent.left is x: y.parent.left = y else: y.parent.right = y x.parent = y x.right = B ...
This function checks and fixes the balance of an AVL tree node by recursively traversing upwards. It performs left or right rotations based on the node's balance factor and its children's balances, ensuring the tree remains height-balanced after insertions/deletions.
def check_fix_AVL(self, node): if node is None: return if abs(node.balance()) < 2: self.check_fix_AVL(node.parent) return if node.balance == 2: if node.right.balance() >= 0: self._left_rotate(node) else: ...
def get_series_from_src(tvdb, src_dir): dirs = os.listdir(src_dir) series_names = [] series_rejects = [] count = 0 for directory in dirs: count += 1 if SHOWS_TO_SKIP is not None and count <= SHOWS_TO_SKIP: continue series = get_series(tvdb, directory) if s...
The code's main task is to map TV show episodes from a source directory to a destination directory using the TVDB API. It retrieves series and episode data, processes them, and collects mappings and rejections for organization. The function returns episode mappings, series rejections, and episode rejections for further...
def plan(src_dir='/Volumes/EricRandiShare/iTunes_Library/TV Shows', dest_dir='/Volumes/video/TV Shows'): api_key = os.environ.get('TVDB_API_KEY') pin = os.environ.get('TVDB_PIN') tvdb = tvdb_v4_official.TVDB(api_key, pin) series, series_rejects = get_series_from_src(tvdb, src_dir) mappings = [] ...
def selection(population): qk = cumulated(population) indices = [0,0] while indices[0] == indices[1]: # choosing two numbers at random and putting them in list selection_rand selection_rand = np.random.rand(2).tolist() indices.clear() for number in selection_rand: ...
The code generates a new population from an old one using elitism, crossover, and mutation. It preserves elite chromosomes, applies ordered crossover (OX) to create offspring, selects feasible ones, and replaces parents if offspring are better. It mutates non-elite chromosomes with inverted displacement mutation, ensur...
def nextpop(old_population): new_population={} # adding elites to new_population for i in range(number_of_elites): chromosome = literal_eval(list(old_population)[i]) new_population[str(chromosome)] = old_population[str(chromosome)] # performing crossover until population size ...
def New_Population(): population = {} # creating a dictionary for i in range(population_size): chromosome = New_Chromosome() while (str(chromosome) in population): # to ensure no duplicates in population chromosome = New_Chromosome() population[str(chromosome)] = calc_fitne...
The code implements a genetic algorithm (GA) to evolve a population over multiple generations. It initializes a population, iteratively generates new populations via selection (nextpop), and tracks the best chromosomes in each generation. The main task is to optimize solutions by evolving the population through generat...
def GA(): old_population = New_Population() # creating initial sorted population print("Initial Population Best Chromosome(s)") print_best_chromosomes(old_population) for i in range(number_of_generations): new_population = nextpop(old_population) old_population = new_population ...
def initialize_parameters_deep(layer_dims): """ Arguments: layer_dims -- python array (list) containing the dimensions of each layer in our network Returns: parameters -- python dictionary containing your parameters "W1", "b1", ..., "WL", "bL": Wl -- weight matrix of shape (...
The main task of the code is to train a deep L-layer neural network using gradient descent. It performs forward propagation to compute predictions, calculates the cost, executes backward propagation to compute gradients, and updates parameters iteratively. The model learns to map input data $X$ to labels $Y$ by minimiz...
def L_layer_model(X, Y, layers_dims, learning_rate = 0.0075, num_iterations = 3000, print_cost=False): """ Implements a L-layer neural network: [LINEAR->RELU]*(L-1)->LINEAR->SIGMOID. Arguments: X -- data, numpy array of shape (num_px * num_px * 3, number of examples) Y -- true "label" vector (c...
def _create_directories(self): os.makedirs(self.assets_directory, exist_ok=True) def _download_page(self) -> str: url = self.url_with_http print('<<<<<<< Downloading URL Page: %s >>>>>>>' % url) response = requests.get(url, verify=True) return response.content.decode('UTF-8') def...
The code downloads a webpage's HTML content, parses it with BeautifulSoup, extracts and saves linked resources (CSS, JS, images), counts hyperlinks, and returns a dictionary with the number of links and images downloaded.
def run(self) -> Dict[int, int]: self._create_directories() self.html_content = self._download_page() self.soup = BeautifulSoup(self.html_content, 'html.parser') self._download_css() self._download_js() image_counts = self._download_img() self._save_index_file()...
def search_by_list(self): # Warehouse self.warehouse_text = StringVar() self.warehouse_label = Label( self.input_frame, text="Almacen", font=("bold", 10) ) self.warehouse_label.place(relwidth=0.15, relheight=0.5) self.warehouse_entry = Entry(self.input_frame, ...
The code defines a method `set_search` that determines which search function to execute based on the value of `self.default_search`. If the value is "Lista", it triggers `search_by_list`; if "Articulo", it uses `search_by_code`; otherwise, it defaults to `search_by_name`. The method acts as a dispatcher, routing search...
def set_search(self, *args): if self.default_search.get() == "Lista": self.search_by_list() elif self.default_search.get() == "Articulo": self.search_by_code() else: self.search_by_name()
def PrintDeviceInfo(nodemap, cam_params): """ This function prints the device information of the camera from the transport layer; please see NodeMapInfo example for more in-depth comments on printing device information from the nodemap. :param nodemap: Transport layer device nodemap. :param cam_num: Camera number...
The main task of the code is to initialize a camera object, retrieve and print device information, load camera settings, and return the initialized camera along with updated parameters. It processes input parameters, configures the camera, and prepares it for operation by setting essential properties and models.
def OpenCamera(cam_params): # Load camera camera = cam_params["camera"] # Initialize camera object camera.Init() # Retrieve TL device nodemap nodemap_tldevice = camera.GetTLDeviceNodeMap() # Print device information PrintDeviceInfo(nodemap_tldevice, cam_params) cam_params['cameraModel'] = GetModelName(came...
def predict(self, x_in): return self.forward(x_in) def get_global_importance(self, y): feature_global_importances = {} if self.num_classes > 2: importances = self.weights.cpu().detach().numpy() for i, v in enumerate(importances[:, y]): feature_global_impor...
The code generates a horizontal bar chart visualizing the top `num_f` feature importances for a given instance, combining global and local importance scores. It calculates feature contributions, sorts them by magnitude, and plots them with color-coding (blue for negative, red for positive values), annotating each bar w...
def plot_bars(self, normalized_instance, instance, num_f): import matplotlib.pyplot as plt y = self.predict(normalized_instance) if self.num_classes > 2: y = np.argmax(y[0].cpu().detach().numpy()) feature_global_importance = self.get_global_importance(y) local_impor...
def authenticate_user(username): connection = create_db_connection() cursor = connection.cursor() query = "SELECT * FROM users WHERE username = %s" cursor.execute(query, (username,)) result = cursor.fetchone() cursor.close() connection.close() return result is not None def authenticat...
This code implements an SMTP server that accepts incoming email connections, processes standard SMTP commands (HELO, AUTH, MAIL, RCPT, DATA), authenticates users, extracts email content, and stores messages in a database. It handles client interactions, validates commands, and manages message parsing and storage while ...
def smtp_server(): # Create SMTP server socket smtp_server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) smtp_server_socket.bind((HOST, SMTP_PORT)) smtp_server_socket.listen(1) print('SMTP server listening on {}:{}'.format(HOST, SMTP_PORT)) while True: # Accept incoming SM...
def read_input(file_name="input.txt"): try: with open(file_name, "r") as f: lines = f.readlines() num_list = [] for line in lines: numbers = [int(number) for number in line.strip().split()] num_list.append(numbers) return num_...
The main task of the code is to read input data, compute results for Part 1 and Part 2 using the input, print both results, and return a success status (0). It orchestrates data processing and output for a problem split into two distinct parts.
def main(): input_data = read_input() print("Part 1:", part1(input_data)) print("Part 2:", part2(input_data)) return 0
def get_card_number() -> int: while True: try: number = int(input("Number: ")) if number > 1000000000000 or number < 9999999999999999: return number except: print("Please enter correct card number ") def check_number(number: int) -> bool: m...
The code validates a credit card number by checking its validity and determining its type (MASTERCARD, AMERICAN EXPRESS, VISA) based on the starting digits. It retrieves the card number, verifies it, extracts the first digits, and uses conditional checks to print the corresponding card type or "INVALID" if the number f...
def main() -> None: card_number = get_card_number() if check_number(card_number) == False: print("INVALID") else: first_numbers = get_first_numbers(card_number) if first_numbers > 50 and first_numbers < 56: print("MASTERCARD"); elif first_numbers == 37 or first_nu...
def set_trader_prices(keys,trader_dictionary,global_prices,sigma, pf=5000): ''''Sets the trader prices at each time step depending on what type of trader it is''' for key in keys: epsilon = np.random.uniform(-sigma,sigma) if(trader_dictionary[key].type == 'chartist'): ...
The function distributes information in a network by triggering avalanches at nodes exceeding an info threshold. It updates trader prices, calculates global prices, tracks avalanche sizes and price deltas, and logs average/max info metrics. The process involves random node selection, avalanche handling, and updating gl...
def distribute_info(trader_dictionary, network,max_info,global_prices, alpha, sigma, beta, pf, info_list): """Distributes info after randomly selecting node (that exceeds the threshold)""" keys = list(trader_dictionary.keys()) set_trader_prices(keys,trader_dictionary,global_prices,sigma, pf) ...
def create_trader_network(num_traders, avg_degree, rewiring_probability,percent_fund,percent_chart, phi): """Creates a small world network of traders""" traders = create_traders(num_traders, percent_fund, percent_chart, phi) network = nx.watts_strogatz_graph(n=len(traders), k=avg_degree, p=rewiring_probab...
The main task of the code is to simulate information diffusion and price dynamics over a network (small-world or Barabási-Albert) across multiple days. It tracks avalanches (sudden changes) in information propagation, updates global prices, and records daily avalanche sums, returning time-series data on avalanches, pri...
def run_simulation(network_params,network,max_info,global_prices,alpha,sigma, beta, pf, info_list,avalanches, num_days): '''Generates a time series as well as any other necessary outputs from the simulation''' if network == 'small_world': network, trader_dictionary = create_trader_network(network_para...
def _check_keydown_events(self, event): """event checks when keys are pressed""" if event.key == pygame.K_ESCAPE: # check game exit by typing 'esc' sys.exit() elif event.key == pygame.K_LEFT: # check move left self.ship.moving_left = True elif event.key == pygame.K_RIGHT: # check move right self.ship.m...
This function processes user input events in a Pygame game. It checks for quit signals, keyboard presses/releases, and mouse clicks. When the game is active, it moves the ship's x-coordinate to match the mouse position within the screen bounds, enabling mouse-controlled movement.
def _check_events(self): """event loop to listen to user input""" for event in pygame.event.get(): # watch for keyboard and mouse events if event.type == pygame.QUIT: # check game exit by hitting 'x' sys.exit() elif event.type == pygame.KEYDOWN: # check if key is pressed down self._check_keydown_even...
def _check_events(self): """event loop to listen to user input""" for event in pygame.event.get(): # watch for keyboard and mouse events if event.type == pygame.QUIT: # check game exit by hitting 'x' sys.exit() elif event.type == pygame.KEYDOWN: # check if key is pressed down self._check_keydown_even...
The main task of the code is to run the game's main loop, handling events, updating game state, and rendering the screen. It limits FPS using `clock.tick`, checks user input via `_check_events`, updates the screen with `_update_screen`, and conditionally updates physics if the game is active.
def run_game(self): """start main loop for game""" while True: self.dt = self.clock.tick(self.settings.fps) # limit game fps self._check_events() # check user input self._update_screen() # screen updater if self.stats.game_active: self._update_physics()
def _create_cells(self): for i in range(self._num_cols): col_cells = [] for j in range(self._num_rows): col_cells.append(Cell(self._win)) self._cells.append(col_cells) for i in range(self._num_cols): for j in range(self._num_rows): self._draw_cell(i, j) def _break_entranc...
This code initializes a maze structure by setting up grid parameters, creating cells, and configuring entrance/exit points and wall-breaking logic to generate a solvable maze. It stores coordinates, cell dimensions, and window info, then calls methods to construct the maze layout, break walls recursively, and reset vis...
def __init__( self, x1, y1, num_rows, num_cols, cell_size_x, cell_size_y, win=None, ): self._cells = [] self._x1 = x1 self._y1 = y1 self._num_rows = num_rows self._num_cols = num_cols self._cell_size_x = cell_size_x self._cell_size_y = cell_size_y self._...
def processIssues(issues): issueList='' if issues is not None: for issue in issues: issueKey = issue.find('key') if issueList == '': issueList = (issueKey.text) if issueKey is not None else '' else: issueList = issueList + ';' + (issue...
The code processes XML test cases, extracts metadata (title, priority, labels, etc.), and converts them into structured CSV format. It handles three test types (plain, bdd, steps), formats details accordingly, appends data to a DataFrame, and saves it to a file. Precondition handling and incremental issue ID tracking a...
def handleTestCases(root, issueID, outputfile, repoName): testcases = root.findall('testCases/testCase') baseRepoName= repoName for testcase in testcases: folder = testcase.find('folder') testRepoName = folder.text if folder is not None else '' if baseRepoName is not None and test...
def get_latest_path(self): global num_of_points_in_path num_of_points_in_path = len(self.path()) return self.path() def bang(self): #collision detection at 0.7m from sensor. reason why is corner of 0.5,0.5. if(len(self.coll) != 0): for i in self.coll : ...
The code's main task is to control a drone to follow a predefined path by switching to OFFBOARD mode, arming the drone, and continuously publishing target positions. It checks if the drone has reached each goal coordinate, updates the target, and ensures the drone transitions to the next coordinate while maintaining th...
def fly(self): rospy.wait_for_service("/mavros/cmd/arming") arming_client = rospy.ServiceProxy("/mavros/cmd/arming", CommandBool) rospy.wait_for_service("/mavros/set_mode") self.set_mode_client = rospy.ServiceProxy("/mavros/set_mode", SetMode) self.set_mode_client.call() ...
def pick_parrent(population): number_of_rows = population.shape[0] random_slice = np.random.choice(number_of_rows,size=Globals.pick_size,replace=False) pick_population = population[random_slice, :] parrent = get_best(pick_population) return parrent def crossover(p1,p2): child = np.zeros_like(p1)...
The main task of the code is to evolve a population in a genetic algorithm by selecting two parents, performing crossover to generate a new chromosome, applying mutation, and storing the result in the next generation. This process iterates for the entire population size, creating a new population of mutated offspring f...
def evolve_population(population): next_population = np.empty_like(population) for i in range(Globals.population_size): p1 = pick_parrent(population) p2 = pick_parrent(population) new_chromosome = crossover(p1,p2) next_population[i] = mutate_chromosome(new_chromosome) return...
def update_monitor(window, led, start_time): """Update the window with information from the chambers.""" if time.time() > led["last_updated"] + 1: # Blink the LED led["color"] = "green" if led["color"] == "white" else "white" window["-LED-SPOT-"].Widget.itemconfig(led["obj"], fill=led["c...
The main task of the code is to create a graphical user interface (GUI) for monitoring and controlling bioreactor chambers. It displays chamber statuses, media levels, and timestamps, allows users to add/change media in individual or all chambers, includes a runtime indicator, and provides real-time updates through eve...
def start_monitoring_window(start_time): """Display information for the chambers and allow user control.""" # Set the font and the theme of the GUI default_font = 'Roboto 12' sg.theme('LightGray1') # Define the layout of the monitoring window, however this must be done # after the settings have...
def reset_chambers(): """Reset the chambers if requested. This is useful since the software is set up to run on a loop until told to stop, meaning there may be multiple trials run in between stopping the software. Thus, the chambers need to be reset in between trials. """ for chamber in chamber...
The main task of the code is to orchestrate a cyclical process involving chamber resets, user settings input, time synchronization, monitoring initiation, and wash cycle prompts. It runs in a loop until a shutdown signal is received, handling user cancellations and maintaining system state variables for chamber timing ...
def main(): """Top level function.""" while not shutdown['main']: # Reset the chambers reset_chambers() # Reset shutdown variable shutdown['settings'] = False # Load the GUI that can input the user settings get_user_settings() # If the user cancels, pas...
def get_valuation_price(counter): if counter in market_prices: return market_prices[counter] market_prices[counter] = get_current_market_price(counter) return market_prices[counter] def get_sales_proceeds(qty, price): return round(qty * price * (1 - (trade_commission_percentage / 100)), 2) def ...
This method calculates financial statistics for an open position, including forecasted sales proceeds, profit, profit percentage relative to cost, and profit scenarios across multiple price points. It uses current and projected prices to evaluate potential outcomes for a given investment quantity and cost, returning up...
def compute_open_position_statistics(self): current_price = get_valuation_price(self.symbol) self.forecast_sales_proceeds = get_sales_proceeds(self.qty, current_price) self.forecast_profit = round(self.forecast_sales_proceeds - self.cost, 2) if self.cost != 0.0: self.forecast...
def form_initial_model(path, times, read_range) : bio_file = open(path, "r") #creates list of data data = read_sensor_data(bio_file, times, read_range) #creates ensamble model model = train_base_model(data) bio_file.close() pickle.dump(model, open('model.sav', 'wb')) def read_data(pa...
The function `form_models` loads or trains a base model and an MLP model. It first attempts to load the base model from a file; if unsuccessful or if training is required, it trains the base model using `form_initial_model`. Similarly, it loads the MLP model, and if that fails or training is needed, it reads data with ...
def form_models(path, read_range, times, already_trained) : success = True base_model = None mlp = None # tries to get base model try : base_model = pickle.load(open('model.sav', 'rb')) except : success = False # trains base model if needed if not already_trained or not...
def read_sensor_data(bio_file, times, read_range = 10000) : rssi_current = 0 bio_file.readline() #output list bio_test = [] #data over given seconds - fills with rssi value of -85 rssi_avg_minute = [-85] * 20 rate_of_change = [-85] * 3 deviations = [-85] * 5 attribute_list = ...
The code trains and evaluates a machine learning model (MLP) using sensor data. It loads training/test data from JSON files, preprocesses it, trains a base model, uses it to form the MLP, tests the MLP on new data, and evaluates accuracy while plotting results.
def run_program() : random.seed(None) already_trained = True # interaction times times = [ (150,515), (1285,1575), (1987,2010), (2315,2385), (2930,3210), (3500,3905), (4340,4600), (5090,5287) ] # file read data path = "C:...
def load_cffixed_mphys_ds(flight_number, source_date, instrument): path_src = make_mphys_path( source_date=source_date, flight_number=flight_number, instrument=instrument, kind="source", revision="*", ) revision = parse.parse(MPHYS_FILENAME_FORMAT, path_src.name)["rev...
This function calculates the time offset between two datasets (masin and mphys) for a specific flight and instrument. It aligns the data using a window method, visualizes the correlation before/after offset adjustment, computes the offset via interpolation, applies it to the mphys dataset, and stores the result. The pr...
def _calc_offsets_for_flight_instrument( ds_masin, flight_number, instrument, path_offsets, source_date, window_method ): ds_mphys = load_cffixed_mphys_ds( source_date=source_date, flight_number=flight_number, instrument=instrument ) if not MPHYS_VAR in ds_mphys: # some mphys files don't...
def load_masin_ds(flight_number, version="0.7"): # path_masin = f"/gws/nopw/j04/eurec4auk/public/data/obs/MASIN/EUREC4A_TO-{flight_number}_MASIN-1Hz_*_v{version}.nc" path_masin = f"/gws/nopw/j04/eurec4auk/data/obs/flight{flight_number}/MASIN/EUREC4A_TO-{flight_number}_MASIN-1Hz_*_v{version}.nc" ds = xr.open...
(The main task of the code is to process flight data with selected offsets, comparing original and offset-adjusted measurements across instruments. It loads MASIN and instrument data, extracts time windows, generates comparison plots for each flight, and optionally saves processed data to NetCDF files. The function ite...
def process_with_selected_offsets( path_offsets, offset_source, instruments, source_date, flight_numbers, masin_version, window_method, ceda_revision=None, ): # make plots with the best offset for flight_number in tqdm(flight_numbers, desc="flight"): ds_masin = load_masi...
def load_masin_ds(flight_number, version="0.7"): # path_masin = f"/gws/nopw/j04/eurec4auk/public/data/obs/MASIN/EUREC4A_TO-{flight_number}_MASIN-1Hz_*_v{version}.nc" path_masin = f"/gws/nopw/j04/eurec4auk/data/obs/flight{flight_number}/MASIN/EUREC4A_TO-{flight_number}_MASIN-1Hz_*_v{version}.nc" ds = xr.open...
The function calculates offsets for specified flight instruments, skipping pre-existing offsets if `only_compute_missing` is True. It iterates over flight numbers and instruments, loads data, checks for existing offsets, and computes new ones using `_calc_offsets_for_flight_instrument` when needed. It handles exception...
def calc_offsets(source_date, path_offsets, flight_numbers, instruments, masin_version, window_method, only_compute_missing=True): for flight_number in tqdm(flight_numbers, desc="flight"): ds_masin = load_masin_ds(flight_number=flight_number, version=masin_version) ds_masin.attrs["flight_number"] = ...
def optional_debugging(with_debugger): """ Optionally catch exceptions and launch ipdb """ if with_debugger: import ipdb return ipdb.launch_ipdb_on_exception() else: class NoDebug: def __enter__(self): pass def __exit__(self, *args, ...
The code processes command-line arguments to either calculate instrument offsets for a given date or apply existing offsets to data. It supports options for recalculation, specifying instruments, flight numbers, and offset computation methods. The script requires either --calc (to compute offsets) or --process-with (to...
def main(): only_compute_missing = True import argparse argparser = argparse.ArgumentParser() argparser.add_argument( "source_date", help="date-string describing when the source data is from" ) argparser.add_argument("offset_fn", help="filename to save offsets to") argparser.add_arg...
def getSize(d): digit = str(d) long = len(digit) return long def prefixMatched(number,d): k = getSize(d) prefix = getPrefix(number,k) if prefix == d: return True else:return False def sumOfDoubleEvenPlace(number): summ = 0 for i in range(1, getSize(number) + 1): di...
The code validates a credit card number by checking its length (13-16 digits), prefix (Visa, MasterCard, etc.), and applying the Luhn algorithm to verify the sum of digits. It returns True if valid, False otherwise.
def isValid(number): if getSize(number) >=13 and getSize(number)<=16: if prefixMatched(number,4): card = "Visa" elif prefixMatched(number,5): card = "MasterCard" elif prefixMatched(number,37): card = "American Express" elif prefixMatched(number, 6)...
def forward_prop(self, X): Z1 = self.W1.dot(X) + self.b1 A1 = self.ReLU(Z1) Z2 = self.W2.dot(A1) + self.b2 A2 = self.softmax(Z2) return Z1, A1, Z2, A2 def get_predictions(self, A2): return np.argmax(A2, 0) def test_prediction(self, index, X_dev, Y_dev): print("tes...
This function evaluates a model's accuracy on a development set by iterating through specified samples. It compares predicted outputs (A2) against true labels (Y_dev), incrementing a correct count (k) for matches. If predictions are incorrect and less than 3 errors have been logged, it calls `test_prediction` for debug...
def verif_pred_test(self, index, X_dev, Y_dev): k = 0 o = 0 for i in range(index): _, _, _, A2 = self.forward_prop( X_dev[:, i, None]) test = self.get_predictions(A2) if test == Y_dev[i]: k = k + 1 elif o < 3: self.t...
def _it_is_expired(task, current_date_time): """Checks if the task expiration time is greater than current_date_time. Args: task: A firestore document current_date_time: A datetime object representing the current date & time Returns: expiration_timestamp > current_date_time; """ if task.get('o...
This function processes Firestore tasks by checking their expiration status and handling them based on their type. For "Delayed Forwarding" tasks, it sends them to success if time is due, otherwise updates the timestamp. For long-running tasks, it checks operation status via API clients or URLs, sending to success/erro...
def _process_task(project, collection, task, current_date_time): """Checks if it's time to process the task. Depending on the type of tasks it the processing will differ: - Delayed Forwarding: send to success topic if it's time, updatime time otherwise - Long Running Task (otherwise): check status of long r...
def _obtain_batch_predict_slot(transaction, db): current_timestamp = datetime.datetime.now(pytz.utc) try: db.collection(FST_PREDICT_COLLECTION).document(COUNTER_DOCUMENT).create( {COUNTER_FIELD: 0, COUNTER_LAST_INSERT: current_timestamp, }) logger.info('Counter document did not exi...
This function processes incoming messages by either executing batch predictions using a GCP model or throttling them based on resource availability. It checks for available slots in Firestore, runs predictions if available, enqueues operations for tracking, and handles errors. If throttled, it delays message processing...
def _start_processing(throttled, msg, model_gcp_project, model_location, model_id, model_date, model_api_endpoint, client_class_module, client_class, enqueue_topic, success_topic, error_topic, source_topic, gcp_project, delay_in_sec...
def _process_task(project, collection, task, current_date_time): """Checks if it's time to process the task. Depending on the type of tasks it the processing will differ: - Delayed Forwarding: send to success topic if it's time, updatime time otherwise - Long Running Task (otherwise): check status of long r...
This function processes a list of Firestore tasks up to a specified maximum limit, handling each task by executing _process_task. It logs and routes tasks to an error queue on exceptions, then deletes the task from Firestore. The process stops once the maximum task count is reached or all tasks are processed.
def _process_tasks(project, collection, task_list, max_tasks, current_date_time): """Iterates over the task_list to process each task. Args: project: String representing the GCP project to use collection: A string representing the firestore collection task_list: A firestore documents array to be proces...
def _load_metadata(table): """Loads the metadata info from BQ. Args: table: A string representing the full address of the BQ table containing metadata Returns: A pandas dataframe containing the metadata info """ query = f""" select a.model_date as model_date, b.model_id as model_id from...
The main task of the code is to process incoming Pub/Sub messages by triggering a prediction workflow. It decodes event data, retrieves model metadata (date, ID, location), and initializes parameters for processing. The `_start_processing` function is called with these parameters to handle prediction tasks, including e...
def main(event: Dict[str, Any], context=Optional[Context]): """Triggers the message processing. Args: event (dict): The dictionary with data specific to this type of event. The `data` field contains the PubsubMessage message. The `attributes` field will contain custom attributes if there ...
def get_header_rlp_array(block: dict) -> list: rlp_array = [] required_fields = ( "parentHash", "ommers/ommersHash/sha3Uncles/uncleHash", "coinbase/miner/feeRecipient", "stateRoot", "transactions/transactionsTrie/transactionsRoot", "receiptRoot/receiptsRoot/recei...
The function generates the RLP encoding of a blockchain block by collecting its header, transactions, and ommers (uncles) data. It checks for required fields like "transactions" or "transactionsTrie" and raises errors if critical data is missing. The RLP array is built with formatted values, then encoded into bytes for...
def get_block_rlp(block: dict) -> bytes: rlp_array = [] rlp_array.append(get_header_rlp_array(block)) txs_rlp_array = [] if "transactions" in block: for t in block["transactions"]: txs_rlp_array.append(format_value_for_rlp("transaction", t)) elif "transactionsTrie" in block: ...
def print_usage(): EXAMPLE_PARENT_HASH, EXAMPLE_STATE_ROOT, EXAMPLE_BLOCK_HASH = ( "0x3b8fb240d288781d4aac94d3fd16809ee413bc99294a085798a589dae51ddd4a", "0xca3149fa9e37db08d1cd49c9061db1002ef1cd58db2210f2115c8c989b2bdf45", "0x3559e851470f6e7bbed1db474980683e8c315bfce99b2a6ef47c057c04de7858",...
The code reads a block's JSON data from a file, computes its hash and RLP (Recursive Length Prefix) encoding, and validates them against expected values in the block. It checks if the calculated hash matches the provided "blockHash" or "hash" field and verifies the RLP against the "rlp" field if present. Discrepancies ...
def main() -> None: if len(sys.argv) != 2: print_usage() raise Exception("Incorrect number of arguments") (_, block_json_path) = sys.argv block = None with open(block_json_path, "r") as f: block = json.load(f) pprint(block) block_hash = get_block_hash(block) print(...
def setup(): # Setup Database print("SETTING UP DATABASE") browser.open(args.url + "/setup.php") browser.select_form('form[action="#"]') browser.submit_selected() # Login print("LOGGING IN") browser.open(args.url) browser.select_form('form[action="log...
The code's main task is to discover and report system inputs via crawling and guessing techniques. It collects visited links, parsed URLs, form inputs, cookies, and guesses pages using common words. In test mode, it identifies sensitive data, unsanitized inputs, delayed responses, and HTTP errors, summarizing findings ...
def discover(args, test=False): """ Output a comprehensive, human-readable list of all discovered inputs to the system. Techniques include both crawling and guessing. """ global browser global visited global parse_urls global form_inputs global cookies global combs global skiplin...
def esat(T): return 0.611e3 * np.exp(17.2694 * (T - 273.16) / (T - 35.86)) def qsat(T,p): return 0.622 * esat(T) / p def jarvis_stewart(self): # calculate surface resistances using Jarvis-Stewart model if(self.sw_rad): f1 = 1. / min(1.,((0.004 * self.Swin + 0.05) / (0.81 * (0.004 * s...
This function calculates land surface energy and water fluxes, including aerodynamic resistance (ra), saturation vapor pressure, soil moisture effects, and skin temperature (Ts) using an implicit equation. It computes latent heat fluxes (LE) partitioned into vegetation, soil, and liquid components, sensible heat (H), g...
def run_land_surface(self): # compute ra ueff = np.sqrt(self.u ** 2. + self.v ** 2. + self.wstar**2.) if(self.sw_sl): self.ra = (self.Cs * ueff)**-1. else: self.ra = ueff / max(1.e-3, self.ustar)**2. # first calculate essential thermodynamic variables ...
def statistics(self): # Calculate virtual temperatures self.thetav = self.theta + 0.61 * self.theta * self.q self.wthetav = self.wtheta + 0.61 * self.theta * self.wq self.dthetav = (self.theta + self.dtheta) * (1. + 0.61 * (self.q + self.dq)) - self.theta * (1. + 0.61 * self.q) ...
This code initializes a comprehensive atmospheric model by setting physical constants, plant parameters, meteorological variables (temperature, moisture, CO2, wind), and switches for components like radiation, land surface, and cumulus schemes. It prepares diagnostic variables, runs initial calculations for radiation, ...
def init(self): # assign variables from input data # initialize constants self.Lv = 2.5e6 # heat of vaporization [J kg-1] self.cp = 1005. # specific heat of dry air [J kg-1 K-1] self.rho = 1.2 # density of a...
def statistics(self): # Calculate virtual temperatures self.thetav = self.theta + 0.61 * self.theta * self.q self.wthetav = self.wtheta + 0.61 * self.theta * self.wq self.dthetav = (self.theta + self.dtheta) * (1. + 0.61 * (self.q + self.dq)) - self.theta * (1. + 0.61 * self.q) ...
The main task of the code is to execute a time step in a simulation by running various model components—radiation, surface layer, land surface, cumulus parameterization, and mixed-layer models—conditional on their respective switches. It collects statistics, stores output, and performs time integration for specific mod...
def timestep(self): self.statistics() # run radiation model if(self.sw_rad): self.run_radiation() # run surface layer model if(self.sw_sl): self.run_surface_layer() # run land surface model if(self.sw_ls): self.run_...
def init(self): # assign variables from input data # initialize constants self.Lv = 2.5e6 # heat of vaporization [J kg-1] self.cp = 1005. # specific heat of dry air [J kg-1 K-1] self.rho = 1.2 # density of a...
(The code's main task is to simulate a model over multiple time steps by initializing variables, performing time integration for each step via `timestep()`, and then cleaning up memory by removing unnecessary variables post-simulation.)
def run(self): # initialize model variables self.init() # time integrate model for self.t in range(self.tsteps): # time integrate components self.timestep() # delete unnecessary variables from memory self.exitmodel()
def parseConfigFile(filename): global id_algo global ntrials global nevals global envChangeEvery global numHiddens global environment global fullyRandom global storingRate global biasCorr global numHiddenLayers global stepsize global noiseStdDev global sampleSize global ac_bins global ac_noise_std globa...
The main task of the code is to execute an evolutionary strategy (ES) algorithm for training a neural network policy in a reinforcement learning environment. It processes command-line arguments to configure parameters like the environment, neural network architecture, and training settings. If no configuration file is ...
def main(argv): global ac_bins global ac_noise_std global connection_type global hidden_dims global nonlin_type global nonlin_out global init_type global id_algo global ntrials global nevals global numHiddens global numHiddenLayers global environment global fullyRandom global envChangeEvery global stori...
def build_url_table(): index_path = '/home/guillermo/Portal/py/md_converter/test1/ARTPLATSWS/index.html' table = {} with open(index_path, 'r', encoding='utf-8') as file: html = file.read() soup = BeautifulSoup(html, "html.parser") links = soup.find_all('a') for link in link...
This code converts HTML files from a source directory to Markdown format in a destination directory, preserving the folder structure. It replaces filenames using a predefined table, generates a table of contents (ToC) structure, and handles errors. Non-HTML files are copied directly. The process includes logging errors...
def run_conversion(): if os.path.exists(destination_folder): shutil.rmtree(destination_folder) os.makedirs(destination_folder) n = 0 n_errors = 0 table = build_url_table() toc_structure = extract_toc_structure(index_file) toc_tree = create_toc_tree(toc_structure) filename_len = 2...
def handle_heading(self, tag): level = int(tag.name[1]) if tag.get('id') == 'title-heading': self.has_title = True title = tag.get_text().strip() # Parse title removing unwanted part match = re.search(r'[^:]+:\s(.*?)$', title) if match: ...
The code parses HTML content using BeautifulSoup, removes specified sections (breadcrumb, page sections, attachments, footer), and processes remaining tags (headings, paragraphs, links, etc.) to convert them into markdown format, finally cleaning up newline characters in the output.
def convert(self, html): soup = BeautifulSoup(html, "html.parser") # Remove unwanted sections breadcrumb = soup.find('div', id="breadcrumb-section") if (breadcrumb): breadcrumb.decompose() page_sections = soup.find_all("div", {"class": "pageSection"}) attachm...
def handle_heading(self, tag): level = int(tag.name[1]) if tag.get('id') == 'title-heading': self.has_title = True title = tag.get_text().strip() # Parse title removing unwanted part match = re.search(r'[^:]+:\s(.*?)$', title) if match: ...
The code processes HTML content by removing specified sections and elements, then converts remaining tags like headings, paragraphs, links, and images into markdown format, finally cleaning up redundant newlines in the output.
def convert(self, html): soup = BeautifulSoup(html, "html.parser") # Remove unwanted sections breadcrumb = soup.find('div', id="breadcrumb-section") if (breadcrumb): breadcrumb.decompose() page_sections = soup.find_all("div", {"class": "pageSection"}) attachm...
def get_at_position(self, position): if self.is_correct_position(position): return self.board[int(position.y)][int(position.x)] return None def set_at_position(self, position, value): if self.is_correct_position(position): self.board[int(position.y)][int(position.x)] = va...
The main task of the code is to handle the action when an empty tile is clicked. It reveals the tile if it's hidden or flagged, and recursively reveals all neighboring tiles if the clicked tile has no adjacent bombs, creating a chain reaction of tile revelations.
def clicked_empty_tile(self, position): if self.get_at_position(position) in [self.EM_HID, self.EM_FLA]: self.set_at_position(position, self.EM_VIS) if self.count_bombs_at_pos(position) == 0: for neighbour in self.neighbours: self.clicked_empty_tile(ne...
def run_msfvenom(msfvenom_command: str) -> str: msf_sc = subprocess.run(msfvenom_command, shell=True, capture_output=True).stdout.decode() return msf_sc def grep_shellcode(msf_sc: str) -> str: sc = re.sub("\n", "", msf_sc) sc = re.findall("\[byte.*\]", sc)[0][5:-1].strip() return sc def get_sc_size(...
The main task is to generate an obfuscated Nim program that injects shellcode into a target application. It processes shellcode input (via MSFVenom or direct input), applies obfuscation, injects the shellcode size and application path into a Nim code skeleton, compiles the code into an executable or DLL, and cleans up ...
def main(): args = generate_cli_args() # Get shellcode # NOTE: Why not a function? if args.msfvenom_command: msf_sc = run_msfvenom(args.msfvenom_command) # Run msfvenom sc = grep_shellcode(msf_sc) # Get shellcode elif args.shellcode: raw_sc = args.shel...
def preprocess(self, data): #Our dataset only has continuous data norm_data = np.clip((data - self.range[0]) / (self.range[1] - self.range[0]), 0, 1) categorical_data = np.floor(self.bin_size*norm_data).astype(int) return categorical_data def entropy(self, n_pos, total): n_neg = total - n_pos if n_pos == 0:...
This code trains a decision tree classifier by preprocessing input features, calculating initial entropy from labels, and recursively building the tree structure using the decsion_tree method with feature indices and concatenated data.
def train(self, X, y): #training logic here #input is array of features and labels self.train_X=X self.train_Y=y categorical_data = self.preprocess(X) # counts = np.count_nonzero(y) # print(np.count_nonzero(y)) # print(y.size) self.entropyS = self.entropy(np.count_nonzero(y), y.size) examples = np.c...
def init_game(): global game_over global game_speed global snake_dir global head_pos_x global head_pos_x global head_pos_y global head_pos_y global snake_pos_lst global game_screen global is_space global score game_over = False game_speed = GAME_SPEED_START snake...
This function handles snake movement and game logic based on keyboard input. It updates the snake's direction, moves the head position, checks for collisions with the body or screen edges (ending the game if detected), manages food consumption (increasing score and speed), and handles pause/resume, restart, and directi...
def game_action(key: pygame.key): global head_pos_x global head_pos_y global snake_dir global snake_pos_lst global is_space global game_speed global score tail = snake_pos_lst[0] if (key == pygame.K_DOWN) and (snake_dir != 'up'): snake_dir = 'down' elif (key == pygame.K_...
def draw_ball(rand_new=False): global pos_ball_x global pos_ball_y if rand_new: pos_ball_x = random.randint(10, SCREEN_WIDTH - 5) pos_ball_x -= pos_ball_x % PEDAL_1_LENGTH pos_ball_y = random.randint(10, SCREEN_HEIGHT - 5) pos_ball_y -= pos_ball_y % PEDAL_1_LENGTH pygam...
The main task of the code is to run a game loop that handles user input, updates game elements (ball, pedals, score), renders the game screen, and maintains the game speed using Pygame. It processes keyboard events, checks for exit commands, and continuously redraws the game state until the game ends.
def play_game(): global game_over global game_screen global head_pos_x global head_pos_y global game_speed draw_ball() key = None while not game_over: game_screen.fill(SCREEN_COLOR) game_action(key) draw_pedals() draw_ball() draw_score() p...
def draw_food(rand_new=False): global pos_food_x global pos_food_y global food_color global food_size if rand_new: pos_food_x = random.randint(10, SCREEN_WIDTH - 5) pos_food_x -= pos_food_x % SNAKE_SIZE pos_food_y = random.randint(10, SCREEN_HEIGHT - 5) pos_food_y -=...
The main task of the code is to run a game loop that handles user input, updates game state, and renders the game screen by drawing the snake, food, and score, while maintaining the game speed and checking for termination events like quitting or pressing the escape key.
def play_game(): global game_over global game_screen global head_pos_x global head_pos_y global game_speed draw_food(True) key = None while not game_over: game_screen.fill(SCREEN_COLOR) game_action(key) draw_snake() draw_food() draw_score() ...
def initArrays(): global count count = 0 n = 9 arr = [None] * n # Print all binary strings generateAllBinaryStrings(n, arr, 0) def playGame(board): global lastMove moves = 0 while numOfWins(board) == 0: action = random.choice(range(9)) while board[action] == 'X': ...
The code trains a Q-learning agent on a grid-based environment through 10,000 episodes, updating the Q-matrix by playing and resetting the game state each time. It visualizes the final Q-values as a heatmap, showing state-action relationships with specified learning parameters.
def main(): initArrays() board = ["_" for i in range(9)] episodes = 10000 for _ in range(episodes): playGame(board) board = resetBoard(board) plt.imshow(q_matrix, cmap='hot', aspect='auto', interpolation='nearest') plt.title( "State number vs Action taken on grid, learn...
def generate_key_pair(p, q): # find modulus n = p * q # public key = (n, e), where e is not a factor of n(their gcd is 1) # and 1 < e < phi, phi = (p-1)(q-1) e, phi = 2, (p - 1) * (q - 1) while e < phi and gcd(e, phi) != 1: e += 1 public_key = (n, e) private_key = (n, modinv...
The main task of the code is to demonstrate RSA encryption and decryption using two large prime numbers (p and q). It generates a public-private key pair, encrypts a numerical message with the public key, and decrypts the ciphertext with the private key, verifying the round-trip of secure message transmission.
def main(): # first prime number (p) p = 20988936657440586486151264256610222593863921 # second prime number (q) q = 67280421310721 msg = int(input('Enter msg (numerical):')) public_key, private_key = generate_key_pair(p, q) cipher = encrypt(msg, public_key) print('Encrypted msg: ', c...
def _runStartScreen(self): playy, playx, pdy, pdx = self.startscreen.shape[0]*0.57, self.startscreen.shape[1]*0.27, 120, 80 playbox = (int(playy), int(playx), int(playy+pdy), int(playx+pdx)) insy, insx, idy, idx = self.startscreen.shape[0]*0.52, self.startscreen.shape[1]*0.42, 200, 80 i...
This code determines the current game mode and executes corresponding methods: 'startscreen' initializes the start screen, 'showinstructions' displays instructions, 'playgame' runs the game loop, and 'gameover' shows the game over screen, acting as a state controller for different game phases.
def run(self): if self.mode == 'startscreen': self._runStartScreen() if self.mode == "showinstructions": self._runInstructionsScreen() if self.mode == "playgame": self._rungame() if self.mode == 'gameover': self._gameOverScreen()
def truncThresh(pr, delta): ''' Find a threshold L such that pr([-L,L]) >= 1-delta. Parameters ---------- pr : Prob A probability meausure delta : nonegative number Probability of deviation Returns ------- Number in [0,1] A number L such that pr([-L,L]) >= 1...
The code computes the minimal noise scaling factor $ R $ such that a mechanism answering $ k $ queries with noise distributed as $ pr $, scaled by $ R $, satisfies $(\epsilon, \delta)$-differential privacy (DP). It uses binary search on $ R^{-1} $ to find the smallest $ R $ ensuring the deviation from the true answer m...
def optimalNoise(pr, k, epsilon, delta, startR, accurate): ''' Given an epsilon, delta, a number of queries k, and a probability distribution pr, find an upper bound on the lowest R such that the mechanism that answers k 1-sensitive queries using noise pr with magnitue scaled by R is (epsilon,delt...
def number_of_common_friends_map(graph, user): """Returns a map (a dictionary), mapping a person to the number of friends that person has in common with the given user. The map keys are the people who have at least one friend in common with the given user, and are neither the given user nor one of the g...
Your return The code calculates the influence score for each person who shares at least one friend with the given user but is neither the user nor their direct friend. It iterates through each such person's common friends with the user, sums the reciprocal of the number of friends each common friend has, and maps the...
def influence_map(graph, user): """Returns a map (a dictionary) mapping from each person to their influence score, with respect to the given user. The map only contains people who have at least one friend in common with the given user and are neither the user nor one of the users's friends. See the ...
def extract_election_votes(filename, column_names): ''' Input: filename and a list of column names. Returns: a list of integers that contains the values in those columns from every row (the order of the integers does not matter). ''' # initiate empty list list = [] # ...
The main task of the code is to analyze Iranian election data (2009) by extracting vote counts for specified candidates, generating histograms of digit distributions, calculating mean squared error (MSE) between observed and uniform distributions, and comparing the MSE to simulated samples. It evaluates statistical ano...
def main(): # Code that calls functions you have written above # e.g. extract_election_vote_counts() etc. # This code should produce the output expected from your program. extract_election_votes("election-iran-2009.csv", ["Ahmadinejad", "Rezai", "Kar...
def get_romeo_and_juliet_graph(): """Builds and returns the romeo and juliet graph """ rj = nx.Graph() rj.add_edges_from([("Nurse", "Juliet"), ("Juliet", "Capulet"), ("Capulet", "Paris")]) rj.add_edges_from([("Juliet", "Tybalt"), ("Capulet", "Tybalt")]) rj.add_edges_from([...
The code's main task is to analyze and compare two recommendation algorithms (`rec_number_common_friends` and `recommend_by_influence`) on social graphs. It first evaluates these algorithms on the Romeo and Juliet graph (Problem 4), identifying users with identical or differing recommendations. It then applies both met...
def main(): # practice_graph = get_practice_graph() # Comment out this line after you have visually verified your practice # graph. # Otherwise, the picture will pop up every time that you run your program. # draw_practice_graph(practice_graph) rj = get_romeo_and_juliet_graph() # Comment ou...
def get_valid_locations(board): valid_locations = [] for col in range(COLUMN_COUNT): if valid_location(board, col): valid_locations.append(col) return valid_locations def if_gameover(board): return winning_move(board, PLAYER_DISC) or winning_move(board, AI_DIS...
The code implements the **minimax algorithm with alpha-beta pruning** to determine the optimal move for a player (AI or human) in a board game (e.g., Connect Four). It evaluates all valid moves recursively, considering future game states, and selects the move with the highest (for maximizing player) or lowest (for mini...
def minimax(board, search_depth, alpha, beta, maximizingPlayer): # Get valid locations for disc drops valid_locations = get_valid_locations(board) # Check if game is over is_gameover = if_gameover(board) # Initialize result to None result = None...
def _search_calcyanin_concurrent(fastas:list, srcs:list, glyx3_hmm:Hmm, gly1_hmm:Hmm, gly2_hmm:Hmm, gly3_hmm:Hmm, nter_fa:str, domz:int=10000,...
The code searches for calcyanin sequences in FASTA files using HMM profiles (Glyx3, Gly1-3) and an N-termini database. It iteratively updates HMMs and the N-ter database with newly identified calcyanins, repeating until no new sequences are found or max iterations are reached. The process combines HMM-based searches, B...
def search( out:str, fastas:list, srcs:list, glyx3:Hmm, gly1:Hmm, gly2:Hmm, gly3:Hmm, nterdb:str, domz:int=10000, glyx3_evalue_threshold:float=1e-30, glyx3_coverage_threshold:float=0.60, glyzip_evalue_threshold:floa...
def verify_recaptcha(self): ''' Checks recaptcha ''' recaptcha_challenge = self.get_argument('recaptcha_challenge_field', '') recaptcha_response = self.get_argument('recaptcha_response_field', '') recaptcha_req_data = { 'privatekey': self.config.recaptcha_private_key, ...
This code updates a user's bank password by validating the provided old password. If valid, it checks reCAPTCHA (if enabled) and then sets the new password. If validation fails, it displays an error message.
def post_bankpassword(self): ''' Update user's bank password ''' old_bankpw = self.get_argument('old_bpassword') user = self.get_current_user() if user.validate_bank_password(old_bankpw): if self.config.recaptcha_enabled: self.verify_recaptcha() el...
def setUpDatabase(db_name): ''' Takes in db_name and returns cur, conn Connects to database (in this case final.db) Establishes cur and conn variables for later use with the database ''' path = os.path.dirname(os.path.abspath(__file__)) conn = sqlite3.connect(path+'/'+db_name) cur = conn...
The main task of the code is to execute a data analysis workflow by setting up a database connection, retrieving Spotify-related metrics (price, volume, variance, streams), generating visualizations, and writing results to a text file. It coordinates functions like `get_Spotify_Price`, `retrieve_Streams`, and `visualiz...
def main(): ''' Takes in nothing and returns None Used to set up and run all the code above Utilizes cur, conn, and calculations 1-4 variables as well as final.db string To make sure each function has the necessary variables to run properly ''' cur, conn = setUpDatabase('final.db') calcu...
def _create_lock(): wait_lock = WAIT_LOCK with Transaction() as transaction: while wait_lock > 0: transaction.execute('SELECT LOCKED AS "LOCKED", LOCKEDBY AS "LOCKEDBY" FROM DATABASECHANGELOGLOCK') current_lock = transaction.fetchone() if isinstance(current_lock.get...
The code performs database migration by applying changes from a changelog file. It initializes a transaction, acquires a lock, reads migration entries, executes each migration, and handles errors by rolling back. On success, it releases the lock and closes the transaction, ensuring atomic updates with proper error hand...
def migrate(app, changelog, context=None): global current_context current_context = context print('\nExecuting Update') Transaction.init(app) Transaction.connect(app) try: _create_lock() print(f"Reading from {app.config.get('DB_DATABASE', 'hub')}.DATABASECHANGELOG") ...
def get_train_dataloader(self) -> DataLoader: """ Returns the training [`~torch.utils.data.DataLoader`]. Will use no sampler if `self.train_dataset` does not implement `__len__`, a random sampler (adapted to distributed training if necessary) otherwise. Subclass and override this...
The main task of the code is to train a machine learning model by setting up optimizers, schedulers, and distributed training configurations. It handles model initialization, hyperparameter search with Optuna, gradient accumulation, loss tracking, and checkpointing. The training loop executes forward/backward passes, a...
def train(self, model_path: Optional[str] = None, trial: Union["optuna.Trial", Dict[str, Any]] = None): """ Main training entry point. Args: model_path (:obj:`str`, `optional`): Local path to the model if the model to train has been instantiated from a local path. If...
def clusterColor(image): print('clustering') (height, width, d) = image.shape #Choose 5 Centers for Clusters r1 = random.randint(0,255) b1 = random.randint(0,255) g1 = random.randint(0,255) r2 = random.randint(0,255) b2 = random.randint(0,255) g2 = random.randint(0,255) r3 = rand...
The code performs K-means clustering on an image to identify five dominant colors, then recolors the left half of the image using the closest cluster color for each pixel. It subsequently applies 3x3 pixel patches from training data to the test image, using the clustered colors for recoloring. The process involves colo...
def basicAgent(image,greyImage): #Run K-clustering, 5 Colors color1, color2, color3, color4, color5 = clusterColor(image) #print cluster colors print(color1) print(color2) print(color3) print(color4) print(color5) #Recolor left half of color image based on Kclustering colors pri...
def _read_le_int32(self): result, = unpack_le_int32_from(self.binary, self.cursor) self.cursor += 4 return result def _read_inputs(self): read_input = self._read_input return [read_input() for i in range(self._read_varint())] def _read_outputs(self): read_output = self._r...
The main task of the code is to deserialize a transaction by reading its version, inputs, outputs, and locktime from a data source, then constructing and returning a `Tx` object with these components.
def read_tx(self): '''Return a deserialized transaction.''' return Tx( self._read_le_int32(), # version self._read_inputs(), # inputs self._read_outputs(), # outputs self._read_le_uint32() # locktime )
def _read_nbytes(self, n): cursor = self.cursor self.cursor = end = cursor + n assert self.binary_length >= end return self.binary[cursor:end] def _read_le_uint32(self): result, = unpack_le_uint32_from(self.binary, self.cursor) self.cursor += 4 return result def _...
The main task of the code is to parse and construct a transaction input (TxInput) object by reading specific binary data fields: a 32-byte previous hash, a little-endian 32-bit unsigned integer for the previous index, variable-length script bytes, and a little-endian 32-bit unsigned integer sequence. This method extrac...
def _read_input(self): return TxInput( self._read_nbytes(32), # prev_hash self._read_le_uint32(), # prev_idx self._read_varbytes(), # script self._read_le_uint32() # sequence )
def _read_le_uint64(self): result, = unpack_le_uint64_from(self.binary, self.cursor) self.cursor += 8 return result def _read_outpoint(self): return TxOutPoint( self._read_nbytes(32), # hash self._read_le_uint32() # idx ) def _read_uint256(self): ...
The function `_read_contract_out` parses and returns a `TxContractOutput` object by reading specific fields from input data, including contract type, outpoint, value, maximum supply, and metadata, using helper methods to extract structured information from a blockchain transaction.
def _read_contract_out(self): return TxContractOutput( self._read_le_uint64(), # contract_type self._read_outpoint(), # outpoint self._read_uint256(), # value self._read_uint256(), # max supply self._read_varbytes(), # metadata )
def _read_le_uint64(self): result, = unpack_le_uint64_from(self.binary, self.cursor) self.cursor += 8 return result def _read_contract_out(self): return TxContractOutput( self._read_le_uint64(), # contract_type self._read_outpoint(), # outpoint self....
This function parses a transaction output by reading a contract type, determining if it's a contract, and constructing a TxOutput object with a le_int64 value, varbytes, and contract output if applicable.
def _read_output(self): _cursor = self.cursor contract_type = self._read_le_uint64() contract_out = None is_contract = contract_type & CONTRACT_FLAG and MAX_CONTRACT_TYPE >= contract_type self.cursor = _cursor if is_contract: contract_out = self._read_contract_out() ...
def _map_type(self, qtype) -> str | dict | None: if 'mainsnak' not in qtype: return None snak = qtype['mainsnak'] if 'datavalue' not in snak: return None type_id = snak['datavalue']['value']['id'] # TODO: add type references as quoted type annotations! ...
This function transforms Wikidata-style input data into a structured entity representation. It extracts claims, maps types, generates links, processes labels/descriptions, handles reverse properties, and adds metadata. The output includes entity details, reverse relationships, and standardized formatting for use in kno...
def _to_entity(self, qdata: dict) -> dict: claims = qdata.get('claims') or qdata.get('statements') or {} qid: str = qdata['id'] types = { typ for qtype in aslist(claims.get('P31')) # instanceOf if (typ := self._map_type(qtype)) if qtype.get('rank') == 'norm...