dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def load_access_token_in_env(): """ This functions loads the Github access token stored in the ".env" file and makes it available to use later in the program by simply accessing the token (e.g., with os.environ). Parameters ---------- No parameter necessary. However, it assumes that the sec...
The main task of the code is to authenticate a GitHub user, open a CSV file, and repeatedly call a function `func` with multiple repository names to gather and write data into the CSV file, likely for analysis or reporting purposes.
def main(): load_access_token_in_env() client = authenticate_user() csv_writer = open_csv_file() repo = "PyGithub/PyGithub" func(csv_writer=csv_writer, client=client, repo_name=repo) repo = "chromium/chromium" func(csv_writer=csv_writer, client=client, repo_name=repo) repo = "imr...
def load_access_token_in_env(): """ This functions loads the Github access token stored in the ".env" file and makes it available to use later in the program by simply accessing the token (e.g., with os.environ). Parameters ---------- No parameter necessary. However, it assumes that the sec...
The main task of the code is to process a list of npm repository URLs by extracting repository names, authenticating with an access token, and writing processed data to a CSV file using a function `func`. The script loads credentials, initializes a client, reads URLs from a text file, extracts repository names, and pas...
def main(): load_access_token_in_env() client = authenticate_user() csv_writer = open_csv_file() with open("npm_repos.txt") as file: for line in file: repo_url = line.rstrip() repo = repo_extract_from_url(repo_url) print (repo) func(csv_write...
def compute_reaction_scores(self,genome_ref,weigh_all_events_equally = 1,weights = None): reaction_genes = {} anno_api = annotation_ontology_api() output = anno_api.get_annotation_ontology_events({ "input_ref" : genome_ref, }) events = output["events"] for eve...
The code performs gapfilling on a metabolic model by adding reactions and reversing existing ones to enable biomass production under specified media conditions. It validates inputs, retrieves models/media, extends the model with penalties, applies media constraints, optimizes flux, and saves results. The process ensure...
def run_gapfill_metabolic_model(self,params,ctx): params = self.validate_args(params,["workspace","fbamodel_id","fbamodel_output_id"],{ "media_ids" : ["Complete"], "nogrow_media_ids" : [], "fbamodel_workspace" : params["workspace"], "media_workspace" : params["wor...
def setupUi(self): """ Construct window's ui elements and create buttons and menu actions connections. Call setupUi method from imported, generated by puic GUI file constructing window's ui elements, then create connections between button and menu action elements and methods Pa...
This __init__ method initializes a GUI application by setting up UI components, connecting signals to handlers, creating background workers for tasks like login/logout/calculation, loading data/images, and configuring recent file actions. It prepares the interface, establishes network session, and links UI elements to ...
def __init__(self): """ Call parent init method and UI construct methods Parameters ---------- None Returns ------- None """ super().__init__() self.ui = Ui_MainWindow() self.dialog_window = Ui_Dialog() self.recen...
def is_valid_path(board: Board, path: Path, words: Iterable[str]) -> Optional[str]: """ :param: board: a 2d list of strings which are the values of the cubes :param: path: a list of 2d tuples which are the path on the board :param: words: a set containing all the possible words :return: True if the ...
This function recursively finds valid paths on a board to form words of a specific length. It checks if the current path forms a valid word, explores adjacent cells, and accumulates valid paths in 'legal_paths' while respecting constraints on word repetition and path length. It adjusts the remaining length 'n' based on...
def find_length_n_words_helper(n, board, visited_locations, words, current_location, legal_paths, is_length_n_words = True, should_use_same_word_twice = True): if(n == 0): return if(n == 1): word = is_valid_path(board, visited_locations, words) if(word): if(should_use_same_wo...
def to_token(self, word): """ Checks word type and returns tuple of type, word :param word: string :return: tuple """ if self.is_num(word): return NUM, word elif self.is_label(word): return LABEL, word elif self.is_op(word): ...
The main task of the code is to process a line by removing comments, splitting it into words, and converting each word into a token using `to_token`, returning a list of tokenized words.
def tokenize_line(self, line): """ Returns list of word codes and words. :param line: string :return: list """ return [self.to_token(word) for word in self.split(self.remove_comment(line))]
def load_pretrain(self): state_dict = torch.load("trained-vit.pt", map_location=torch.device('cpu')) self.vit.load_state_dict(state_dict, strict=False) def to_cuda(self): self.vit.cuda(self.gpu) self.vit = torch.nn.parallel.DistributedDataParallel(self.vit, device_ids=[self.gpu], find_un...
This code initializes a Vision Transformer (ViT) model with specified parameters, loads pre-trained weights, configures GPU acceleration, sets up an optimizer, defines a cross-entropy loss function, and enables mixup/cutmix data augmentation if active. It prepares the model for training by handling hardware setup, opti...
def __init__(self, args, gpu): self.args = args self.gpu = gpu self.patch_size = int(self.args.input_size/self.args.num_patches) # 32/8=4 self.vit = ViT( image_size = self.args.input_size, patch_size = self.patch_size, num_classes = self.args.num_clas...
def check_game(game, profile, version, opponent, first_game_id, last_game_id, creator, game_type): return ( profile in game.players_by_name and (opponent is None or opponent in game.players_by_name) and (version is None or game.players_by_name[profile].version == version) ...
The code filters a list of games using the `check_game` function based on parameters like profile, version, opponent, and game type. It then generates and displays multiple statistical reports, grouping data by opponent, version, game type, and their combinations, sorted by the specified criteria. The main task is to p...
def show_report(games, profile, version, opponent, first_game_id, last_game_id, sort_by, creator, game_type): games = [v for v in games if check_game(v, profile, version, opponent, first_game_id, last_game_id, creator, game_type)] show_stats_by_game_type(games, profile, sort_by) show_stats_by_opponent(games...
def mutate(args, scale_f): return numpy.random.normal(args, numpy.array([f(v) for f, v in zip(scale_f, args)])) def function(iteration, args): start = time.time() current_config = copy.deepcopy(config) for k, v in options_index.items(): current_config[k] = v['convert'](args[v['in...
This function implements a genetic algorithm to iteratively find the minimum value of a given function. It mutates individuals in the current generation, evaluates their fitness, selects top performers, and generates a new generation through crossover. The process repeats, updating the minimum value and yielding it alo...
def generate_minimums(function, iteration, generation, minimum, max_generation_size, scale_f): while True: mutations = [mutate(v, scale_f) for v in generation] results = sorted(((function(iteration[0], v), v) for v in mutations), key=lambda v: v[0]) if minimum[0] > results[0][0]: ...
def collect_data(paths): for path in paths: players_path = os.path.join(path, 'players.json') if not os.path.exists(players_path): continue result_path = os.path.join(path, 'result.json') if not os.path.exists(result_path): continue task_path = os.path...
The main task of the code is to process game data from specified file paths, calculate statistics, and display results. It sorts input files by time, collects game data, computes statistics, prints them to the console, and visualizes the stats with a player name from command-line arguments.
def main(): paths = sorted(sys.argv[2:], key=get_time) games = list(collect_data(paths)) stats = get_stats(games) print_stats(stats) show_stats(stats, player=sys.argv[1])
def batchify(data, input_lang, output_lang, batch_size, shuffle_data=True): if shuffle_data == True: shuffle(data) number_of_batches = len(data) // batch_size batches = list(range(number_of_batches)) longest_elements = list(range(number_of_batches)) for batch_number in range(number_of_batch...
This function trains and tests an encoder-decoder model over specified epochs, adjusting learning rates according to a schedule. It trains on batches of sequence data, tracks training/test losses, evaluates model performance periodically, and saves weights if specified. The function handles batch preparation, model opt...
def train_and_test(epochs, test_eval_every, plot_every, learning_rate, lr_schedule, train_pairs, test_pairs, input_lang, output_lang, batch_size, test_batch_size, encoder, decoder, loss_criterion, trim, save_weights): times = [] losses = {'train set':[],...
def normalizeString(s): s = s.replace("<","").replace(">","") s, website_list = getWebsites(s) s = removeAbnormalChars(s) s = tokenCheckerAndSplit(s) s, pronoun_list, number_list = createTokens(s) return s, (website_list, pronoun_list, number_list) def evaluate(encoder, decoder, sentence, i...
The code's main task is to generate a prediction from an input sentence using an encoder-decoder model. It normalizes the input, evaluates it with the model, replaces special tokens with original values, unnormalizes the output, and removes the end-of-sentence token before returning the final prediction.
def predict (sentence, encoder, decoder, input_lang, output_lang, output_language_name, cutoff_length=128): sentence, (website_list, pronoun_list, number_list) = normalizeString(sentence) prediction = evaluate(encoder, decoder, sentence, input_lang, output_lang, cutoff_length=128) prediction = replace_tokens(pred...
def update_board(self, scrabble_board): """Updates the board when a player plays a word""" # Reset the board for i in self.board_gui_list: self.canvas.delete(i) self.board_gui_list.clear() # Loop over the columns for i in range(15): # Loop over...
The main task of the code is to validate a user-submitted word against a Scrabble dictionary and board rules. If valid, it adds the word to the board, updates game state (scores, letters), and refreshes the GUI. It handles wildcards, checks dictionary validity, board placement feasibility, displays errors if invalid, a...
def submit_word(self): """When the user submits a word, check if it is valid. If it's valid, add it to the board""" submitted_word = '' word_with_wilds = '' # Add letters from the play area to the word to submit for c in self.board.play_area_list: # If the index c...
def display_stock_dashboard(): """Display comprehensive stock info within the main application window.""" input_value = stock_code_entry.get() if not input_value: messagebox.showerror("Error", "Please enter a stock code or company name.") return # Check if input is a company name, and i...
The function `confirm_choice()` determines the user's selected menu option from a listbox and executes the corresponding action by calling specific functions like `display_stock_dashboard()`, `display_news_window()`, or `exit_program()`, based on the selected index (0-5). It routes the user's choice to the appropriate ...
def confirm_choice(): choice = menu_listbox.curselection()[0] if choice == 0: # Stock Dashboard display_stock_dashboard() elif choice == 1: # Display Stock Price vs Time Graph display_stock_price_vs_time() elif choice == 2: # Stock Analysis on Stock Parameters display_stock_an...
def build_inverted_index(docs): inverted_index = {} docs_count = 0 id2doc = {} with open(docs, "r", encoding="utf-8") as reader: for i, line in enumerate(reader.readlines()): doc_text = line.strip() inverted_index_add(inverted_index, i, get_postings(doc_text)) ...
This code initializes an inverted index and related structures for text processing, including building term-document mappings, calculating document frequencies (DF) and inverse document frequencies (IDF), generating a term-document matrix, and creating language models for documents and the collection. It sets up founda...
def __init__(self, docs): self._doc_name = os.path.splitext(docs)[0] self._index, self._docs_count, self._id2doc = build_inverted_index(docs) self._term2id, self._id2term = term2id(self._index) self._df_str, self._df_id = self._get_document_frequency() self._idf_dict = self._cal...
def _query_wf_idf_and_vec(self, query): query_postings = get_postings(query) term_id_wf_idfs = {} out_of_dict_words = set() vec = np.zeros((len(self._index)),dtype=np.int) term_id_wf = {} tfs = {} for term, posting in query_postings.items(): if term no...
The code performs vector space query processing by calculating document scores using cosine similarity between query and document vectors. It computes term weights (IDF, TF-IDF), normalizes vectors, ranks documents by score, and outputs detailed calculation logs, query vectors, and ranked results to files for analysis.
def vector_query_and_rank(self, query): docs_scores = [] term_id_wf_idfs, out_of_dict_words, vec, q_tfs, q_wfs = self._query_wf_idf_and_vec(query) doc_tfs = {} doc_wfs = {} doc_norms = {} for doc_id in range(self._docs_count): doc_tfs[doc_id] = {} ...
def get_next_bracket(data, idx, bracket_type=OPEN_BRACKET): try: idx = idx + data[idx:].index(bracket_type) except ValueError as ve: idx = -1 finally: return idx def get_resource_namespace(data): reverse = data[::-1] for idx, c in enumerate(rev...
The main task of the code is to parse Terraform (.tf) files by reading their content, identifying resource blocks via bracket positions, extracting resource namespaces, and processing key-value pairs within those blocks. It iteratively navigates through the syntax, updating data and namespace variables, ultimately retu...
def __parse_terraform(self): """ Takes as input a directory OR file path Finds all the .tf files in the directory Parses the Terraform and build a dictionary :return: :rtype: """ with open(self.input_loc, "r+") as f: data = f.read() dat...
def __parse_terraform(self): """ Takes as input a directory OR file path Finds all the .tf files in the directory Parses the Terraform and build a dictionary :return: :rtype: """ with open(self.input_loc, "r+") as f: data = f.read() dat...
This code initializes a class to parse Terraform configuration files, generate auto.tfvars and variables.tf content, and manage input/output paths. It sets logging, processes main.tf, and prepares variable definitions for Terraform projects.
def __init__(self, input_loc="../test/example/main.tf", output_file=None, auto_vars_file="default.auto.tfvars", vars_file="variables.tf", loglevel=logging.INFO, sort=True): logging.basicConfig(level=loglevel) self.input_loc = input_loc self.variables = {} ...
def current_target(self): if self.elapsed >= len(self.sizes): return None else: return self.sizes[self.elapsed] def log_time(self, time, click_offset, originDistance): size = self.current_target() timestamp = self.timestamp() print("%s; %s; %d; %d; %d; %d;...
The function checks if a click position is within a specified distance threshold of a target position. If valid, it calculates the offset between the positions, logs the event with timing and distance data, increments an elapsed counter, and returns True. If the distance exceeds the threshold, it returns False.
def register_click(self, target_pos, click_pos, originDistance): dist = math.sqrt((target_pos[0]-click_pos[0]) * (target_pos[0]-click_pos[0]) + (target_pos[1]-click_pos[1]) * (target_pos[1]-click_pos[1])) if dist > self.current_target(): return False else: ...
def createParentPopulation(self): pool = deque(range(self._currentArchiveSize)) elite, selectionPool = [], deque() rank, populationSize = 1, self._populationSize archivePopulation, parentPopulation = self._archivePopulation, self._parentPopulation extractBestRank = self.extractB...
This code implements an evolutionary algorithm to optimize a population by iteratively generating parent/offspring populations, mutating them, and updating an archive. It terminates when the best fitness exceeds minFitness or after maxRepeat iterations, with potential reforms if fitness stagnates.
def run(self, maxRepeat=9999, minFitness=0.999): self.initialize() self._currentArchiveSize = self._populationSize createParentPopulation, createOffspringPopulation = self.createParentPopulation, self.createOffspringPopulation mutateOffspringPopulation, updateArchivePopulation = self.mut...
def verify_valid_gdb_subprocess(self): """Verify there is a process object, and that it is still running. Raise NoGdbProcessError if either of the above are not true.""" if not self.gdb_process: raise NoGdbProcessError("gdb process is not attached") elif self.gdb_process.pol...
The function retrieves and returns parsed responses from GDB, blocking until a response is received or a timeout occurs. It handles platform-specific logic (Windows/Unix), validates GDB subprocess status, and raises exceptions for timeouts or errors. Responses include stream type ('stdout'/'stderr') metadata, with opti...
def get_gdb_response( self, timeout_sec=DEFAULT_GDB_TIMEOUT_SEC, raise_error_on_timeout=True ): """Get response from GDB, and block while doing so. If GDB does not have any response ready to be read by timeout_sec, an exception is raised. Args: timeout_sec (float): Maxim...
def convert_to_word_list(text): ''' import re text = "These are indeed interesting, an obvious understatement, times. What say you?" t_split = re.split(', | |;|?|.', text) print = t_split print(t_split) return "hello" pass for x in delimiters: words.append( ''' # wor...
The code processes a given text string by converting it into a word list, filtering words longer than 5 characters, mapping word lengths, counting character frequencies, and identifying the most used character, then printing these results.
def run_word_proc(): words = "These are indeed interesting, an obvious understatement, times. What say you?" #word = words.lower() print(convert_to_word_list(words)) print(words_longer_than(5,words)) print(words_lengths_map(words)) print(letters_count_map(words)) print(most_used_character(wo...
def getFinalHeirarchy(self): # Creating a nested dictionary from the scene heirarchy data selection = pm.selected()[0] finalHierarchyDict = {selection.name() : self.selectionHierarchy(selection.name())} return finalHierarchyDict def dictToXml(self, hierarchicalDict, parent = None): ...
The main task of the code is to generate an XML structure from a hierarchy dictionary. It creates an XML root element "DAGData" with the "Car" namespace, converts a hierarchical dictionary into XML nodes using `dictToXml`, formats the XML with `prettify`, and returns the constructed ElementTree object for further proce...
def writeXmlData(self): # Creating the tree structure in XML with Car: as namespace self.rootNode = et.Element("DAGData") self.rootNode.set("xmlns:Car", "NameSpace") self.finalHierarchyDict = self.getFinalHeirarchy() self.dictToXml(self.finalHierarchyDict, self.rootNode) ...
def cleanup_folder(self, path: str): """Cleans up single folder off of a created bleed files. Args: path (string): folder path """ self._printOutput(f"** cleanup starting in {path}") data = self._get_folder_contents(path, True) for img in data.images: ...
The code processes a specified folder recursively by performing a "bleeding" operation on its items, merging the processed items into PDF documents, and executing cleanup tasks before and after the operation to maintain folder integrity.
def run(self, path: str): """[summary] Runs bleeding operation in folder specified by path (recursively), and merging bleeded items to pdf document(s). Running cleanup operation before/after execution. Args: path (string): root folder to start with """ ...
def send_help(self, evt, cmd=None): if not cmd: response = "yea im too lazy to write help for now" self._reply(evt, response) return def register(self, evt, args): print("register") if len(args) != 3: self.send_err(evt) return ...
The code processes user messages in direct channels by parsing command-line arguments and triggering corresponding actions like sending help, registering, or retrieving grades, or handling errors for unrecognized commands.
def parse_commands(self, events): for event in filter(lambda x: x["type"]=="message" and "user" in x.keys(), events): if event["channel"].startswith("D"): args = event["text"].split() if args[0] == "help": self.send_help(event) elif...
def test_train_split(self, X, n): np.random.shuffle(X) l = (int)(X.shape[0] * (n - 1) / n) self.X_train, self.X_test = X[:l,:], X[l:,:] self.y_test = self.X_test[:, 2] def predict_rating(self, user, movie): x = np.dot(self.U[user], self.M[movie]) if(self.bias == True): ...
The code trains a collaborative filtering model using stochastic gradient descent (SGD) to optimize user and movie feature vectors (U, M) and bias terms (alpha, beta). It iteratively updates parameters to minimize prediction errors on a training set, validates performance, and stops early if validation error stops impr...
def train(self, X,Y): Wrapper.preprocess(self, X, Y) self.U = np.empty((self.u_len + 1, self.dim)) self.M = np.empty((self.m_len + 1, self.dim)) self.alpha = np.zeros(self.u_len+1) self.beta = np.zeros(self.m_len+1) initial_val = np.random.uniform(-0.01,0.01) for ...
def print_menu(): print("1. Create an account\n2. Log into account\n0. Exit") def generator_bs(): print("Your card has been created\nYour card number:") inn = 400000 bin_bank = ''.join(random.sample(string.digits, 9)) new_card = str(inn) + str(bin_bank) list_num = [int(a) for a in (str(inn) + st...
The main task of the code is to implement a menu-driven system for generating and storing card/PIN data in a database. It allows users to create new cards (with PINs) and insert them into a table, handle card input operations, and exit via a loop that processes user choices until option 0 is selected.
def main_menu(): card_dict = {} print_menu() choose_menu = int(input()) print() while choose_menu != 0: if choose_menu == 1: user_card = generator_bs() user_pin = generator_pin() card_dict[user_card] = user_pin cur.execute(f"""INSERT INTO card(...
def _check_app_id_error(appid: str) -> str: """ Returns an ErrorDetail if the app ID is invalid, or None if it is valid. """ if len(appid.split(".")) < 3: return ErrorDetail.MALFORMED_APP_ID elif not re.match("[_\w\.]+$", appid): return ErrorDetail.MALFORMED_APP_ID try: ...
The function determines the verification status of an app ID by checking error conditions, Redis sets for manual verification, website validation, and login provider records, returning details like verification result, method, and associated metadata.
def get_verification_status(appid: str): """ Gets the verification status of an app ID. Returns: - "verified": True or False - "method": "none", "manual", or "website" - "website": For "website" method, the domain name of the website that verified the app (e.g. "gnome.org"). - "login_provid...
def get_last_experiment_dir(config): run_config = config.get('hydra', {}).get('run', {}) # We don't want not call custom resolver in OmegaConf which is not registered by hydra in this script run_dir = eval(str(run_config)).get('dir', None) if run_dir is None: return None runs_dir = Path(run_...
(The code evaluates a model on specified data splits by loading a pre-trained model from an experiment directory, generating predictions, calculating F1 scores, and saving results to CSV files. It handles configuration, model loading, prediction generation, and output management, with optional command-line argument sup...
def evaluate(splits, experiment_dir=None, output_dir=None): config = OmegaConf.load('config/train.yaml') if experiment_dir is None: experiment_dir = get_last_experiment_dir(config) if experiment_dir is None: print('Failed to find directory with an experiment. Please specify it using ...
def read_source_file(filepath): with open(filepath, 'rb') as f: file_data = f.read() try: code = file_data.decode('utf-8') except UnicodeDecodeError: encoding_info = chardet.detect(file_data) code = file_data.decode(encoding_info['encoding']) return co...
This function extracts method declarations from a source file by parsing method signatures and bodies using regex. It filters out methods based on modifiers, commented-out status, argument matches, and naming conventions. Valid methods yield their signature, body, and file path for further processing.
def get_file_declarations(self, filepath): """ Iterates method signature and body. Regex to find signature is splitted in two to make them simpler and faster to evaluate """ code = read_source_file(filepath) for m in self._signature_pat.finditer(code): modifi...
def _get_cell(self, column: int, row: int) -> Cell: box_num, box_c, box_r = self._column_row_to_boxnum(column, row) cell = self.boxes[box_num].get_cell(box_c, box_r) return cell def find_values_column(self, column: int, used_values) -> None: for r in range(1, self.max_value + 1, 1): ...
The main task of the code is to determine valid values for a specific Sudoku cell by checking its column, row, and 3x3 box for existing numbers. It collects used values, removes them from the cell's possibilities, and attempts to set a valid value. If the cell already contains a valid number, it returns False; otherwis...
def solve_cell(self, column: int, row: int) -> bool: cell = self._get_cell(column, row) if 1 <= cell.value <= self.max_value: return False used_values: Set[int] = set() self.find_values_column(column, used_values) self.find_values_row(row, used_values) self.f...
def are_valid_rows(self) -> bool: rtnval: bool = True for i in range(1, self.max_value + 1, 1): rtnval = rtnval & self.valid_row(i) return rtnval def are_valid_columns(self) -> bool: rtnval: bool = True for i in range(1, self.max_value + 1, 1): rtnval = r...
This code checks if a Sudoku board is valid by verifying that all rows, columns, and 3x3 subgrids contain no duplicate numbers. It combines the results of three helper methods using logical AND to ensure all sections meet validity criteria, returning True only if all are valid.
def valid(self) -> bool: ok_rows = self.are_valid_rows() ok_columns = self.are_valid_columns() ok_boxes = self.are_valid_boxes() return ok_rows & ok_columns & ok_boxes
def cluster_index_2(X): global_mean = np.mean(X, axis=0) sum_squared_distances = (((X - global_mean) ** 2).sum(axis=1)).sum() # Sum of squared distances of each sample from the global mean centroids, labels, inertia = k_means(X, 2) ci = inertia / sum_squared_distances return ci, labels def M...
The main task of the code is to compute the p-value for k-means++ clustering (k=2) of a data matrix X, comparing its cluster index to Monte Carlo simulations. It uses eigenvalues of the sample covariance matrix, applying soft/hard thresholding (method 2/1) or direct eigenvalue use (method 0). The function scales data, ...
def sigclust(X, mc_iters=100, method=2, verbose=True, scale=True, p_op=True, ngrains=100): """ Return tuple (p, clust) where p is the p-value for k-means++ clustering of data matrix X with k==2, and clust is a (binary) array of length num_samples = X.shape[0] whose Nth value is the ...
def domain_sampler(n_sample, low=[rb[0], tb[0]], high=[rb[1], tb[1]]): r = tf.random.uniform(shape=(n_sample, 1), minval=low[0], maxval=high[0], dtype=DTYPE) t = tf.random.uniform(shape=(n_sample, 1), minval=low[1], maxval=high[1], dtype=DTYPE) return r, t def train_step(self, r, t, b): with tf.Grad...
This code trains a neural network using two Adam optimizers with exponentially decaying learning rates. It alternates between minimizing losses (loss_a, loss_b, loss_m) and a multiplicative loss (loss_mul), logging metrics like errors, objective values, and runtime. Training proceeds for specified epochs, saving model ...
def learn(self, epochs=10000, n_sample=1000): ir, dr = 1e-7, 1e-1 lr_schedule = tf.keras.optimizers.schedules.ExponentialDecay(ir, decay_steps=epochs, decay_rate=dr, staircase=False) self.optimizer = tf.keras.optimizers.Adam(learning_rate=lr_schedule) lr_schedule_mul = tf.keras.optimizer...
def domain_sampler(n_sample): t = tf.random.uniform(shape=(n_sample, 1), minval=tb[0], maxval=tb[1], dtype=DTYPE) return t def train_step(self, r, t, b, g): with tf.GradientTape() as tape: loss_a = length(self.net) * g loss_b = tf.reduce_mean(boundary(s.net, t)**2) L ...
This code trains a neural network using an exponentially decaying learning rate, iteratively minimizing losses (loss_a, loss_b) through domain sampling. It logs training metrics (loss, errors, runtime), updates model weights periodically, and saves checkpoints with evolving parameters (beta). The algorithm adjusts a sc...
def learn(self, epochs=10000, n_sample=1000): lr_schedule = tf.keras.optimizers.schedules.ExponentialDecay(1e-3, decay_steps=epochs, decay_rate=1e-3, staircase=False) self.optimizer = tf.keras.optimizers.Adam(learning_rate=lr_schedule) print("{:>6}{:>12}{:>12}{:>12}{:>18}".format('iteration', 'l...
def create_rooms(self, row, col): self.ls = [[row + 1, col], [row - 1, col], [row, col + 1], [row, col - 1]] if row <= len(self.room_list) - 1 and col <= len(self.room_list[row]) - 1: try: if type(self.room_list[row][col]) == Room: pass eli...
This code initializes a game environment by setting up configurable room states, creating a player object, binding keyboard input for combat, generating adjacent rooms from a random starting position, initializing time tracking, and preparing the game display. It establishes the foundational structure for a room-based ...
def __init__(self): ### Init states of rooms - configurable self.size = 5 self.room_cap = 10 ### Other room data self.room_count = 0 self.room_list = [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]] self.arch_exists = False ...
def _maxLength(self, inputs): max_l = 0 for d in inputs: if len(d) > max_l: max_l = len(d) return max_l + 20 def _createInputs(self, inp): return pad_sequences( inp, maxlen=self.sentence_length, padding="post", truncating="post", value=0 ) ...
The main task of this code is to initialize a convolutional neural network (CNN) model for text classification or trait prediction. It sets up parameters for embedding layer tuning or learning from scratch, configures convolutional and dense layers, and prepares training data inputs/outputs. The model can handle single...
def __init__( self, train_inputs, train_outputs, specific=True, weights=None, voc_dim=60000, features_number=200, window_size=5, filters_number=100, hidden_units=50, batch_size=32, sentence_length=None, train_zeros=F...
def isUrlInvalid(self): #Use this function to add conditions where url is not valid #add them to a list and check if self.target_url matches one of the #invalid conditions, in this case end execution immediately invalid_url_patterns = { 'endswith': ['instagram.com/', 'inbox/'...
This code automates Instagram content scraping based on URL type. It checks for invalid URLs, handles reels/stories profiles, logs in if needed, navigates to target URLs, and scrapes posts/stories/media. It supports recursive downloads of user profiles' posts, saving images/videos or URLs to files. The script adapts to...
def run(self): #load the page at the beginning of the execution and wait for 3 seconds for page to load #before handling any logic check if url is invalid, case in which no process should be run self.isUrlInvalid() if 'reel' in self.target_url: print("WARNING: Reel URL Provi...
def set_model_path(self): ''' Description: set the path to the model used by this instance of 'VariationalAutoencoder'. (The name of the model is given by 'model_details_dict[model_name]' during class instantiation.) Inputs: -None Return: ...
The main task of the code is to create a timestamped directory for the current model to avoid conflicts if it does not already exist. It sets the model path, appends a timestamp to the model name and path, defines a subdirectory for saved models, creates the directory, and updates related attributes.
def make_model_path(self): ''' Description: creates a directory for the present model if it does not exist. This directory is timestamped to avoid conflicts. Inputs: -None Return: -None ''' self.set_model_path() if not...
def set_model_details_path(self): ''' Description: set the path to 'model_details.json', which stores all structure and training details of the model used by this instance of 'VariationalAutoencoder'. Inputs: -None Return: -None ...
This code initializes a Variational Autoencoder (VAE) by configuring model parameters from a dictionary, setting default hyperparameters, constructing TensorFlow placeholders, building the encoder-decoder network graph, defining loss functions, and initializing optimizers and savers for training and inference. It ensur...
def __init__(self, model_details_dict): ''' Description: initializer for the 'VariationalAutoencoder' class. Inputs: -'model_details_dict' (dict) = input dictionary containing the architecture of the variational autoencoder. We don't give a strict account of th...
def get_random_detection_category(self): if self.detections: return random.choice(self.detections) def check_if_detection_exist(self,name='asphalt'): return name in self.detections def get_random_binary_mask(self,name=None,return_path=False): if not name: name = self.get_...
The function retrieves or generates a clipped image by applying a binary mask to an image, using specified or random categories and masks. It ensures the clipped image exists by creating directories and applying the mask if needed, then returns the file path.
def get_single_clip(self,category=None,binary_mask=None): if not category: category = self.get_random_detection_category() if self.check_if_detection_exist(category): if not binary_mask: binary_mask = self.get_random_binary_mask(category) clip_catego...
def add(heap, newValue): """ add : Heap * Comparable -> NoneType add inserts the element at the correct position in the heap. """ if heap.size == len(heap.array): heap.array = heap.array + ([None] * len(heap.array)) heap.array[heap.size] = newValue siftUp(heap, heap.size) h...
The function `testHeap` tests a min-heap implementation by creating a heap from input data, inserting elements, displaying the heap structure, and modifying specific elements. It initializes a heap, populates it with test data, verifies its size, and demonstrates updates to heap values, showcasing heap operations like ...
def testHeap( testData ): """ testHeap : TupleOfComparable -> NoneType Create a min heap, fill it with the test data, and display it. """ print( "testHeap(", testData, "):" ) heap = Heap(len(testData), less) for i in range(len(testData)): add(heap, testData[i]) print("Heap siz...
def createBoard(): #initialize a 2d array with piece objects board = [] for r in range(row): r = [] for c in range(col): piece = Piece(False) r.append(piece) board.append(r) #go through and find n amount of unique bomb spots and changge those pieces ...
This code initializes a Pygame game, creates and displays a board, and runs a loop to handle user inputs (QUIT, ESCAPE, 'r' key) and mouse clicks. It manages game states, checks win/loss conditions, updates the board, and renders visuals. The main task is to run an interactive board game with reset functionality and re...
def run(): #initiliaze game variables and pygame, show first board pygame.init() playing = True board = createBoard() show(board) pygame.display.flip() #main game loop while True: #listener for player input for event in pygame.event.get(): if event.type == QUI...
def check_next_row(self,column): 'searches for next empty slot in column from the bottom up' for i in range(self.ROWS-1,-1,-1): #iterates thru [5,0] backwards if self.array[i][column] == 0: #empty slot in column found return i #return row # of empty slot ...
This function places a player's piece in the specified column by finding the lowest empty row, updates the game grid and display, checks for a winning condition, ends the game if a winner is found, and switches players otherwise.
def drop_piece(self,column): empty_row = self.check_next_row(column) if empty_row != None: self.array[empty_row][column] = self.player #update array self.draw_circle(self.array,empty_row,column) #update display self.check_win() #check for 4 in a row ...
def prototype_select(self): self.prototypes_idxs = list(map(int, input('Enter numbers: ').split())) self.prototypes = self.dataNorm.iloc[[idx for idx in self.prototypes_idxs]] #calculate average prototype self.averageProt = pd.DataFrame( data = self.prototypes.sum()...
The code's main task is to evaluate and evolve an EMF (Electromotive Force) model through multiple iterations. It starts by selecting prototypes, calculates an initial EMF using predefined parameters, displays recommendations based on this EMF, and then iteratively evolves the EMF model for the specified number of iter...
def evaluate(self, iterations): self.prototype_select() exampleEMF = self.calculate_EMF([0, 1, 2, 3, 4, 5, 6], 1) self.display_recommendations(exampleEMF) for i in range(1, iterations + 1): self.evolve_EMF(i)
def check_order(self, input_main, input_item, check_first_data, ulang_belanja): """ Fungsi ini bertujuan untuk meminta konfirmasi customer apabila mereka hendak melakukan perubahan data Args: input_main(str): secara default berisi 'YA' ulang_bela...
This function controls data modification operations in a menu-driven system, allowing users to update item names, quantities, prices, delete items, reset data, or add new items. It uses conditional logic to execute specific actions via the WriteData class, displays data recaps, and loops back for further updates. Error...
def ubah(self, id_pembeli, input_main, input_item, check_first_data, ulang_belanja, input_menu_update): """ Fungsi ini berperan sebagai flow control dari semua pilihan menu untuk perubahan data Returns: No Returns """ #coba jalankan lin...
def read_data( args ): nalt_parser = naltparser.NAltLineParser( args, with_group=False, with_position=False) region = nalt_parser.parse_whole() return region.M, np.arange(len(region.M[0])), np.arange(len(region.M)) def do_export_ralt(M, sample_idx, site_idx, indv_idx, args): cerr('[I - exporting sampl...
This function processes genetic data by reading input files, calculating sample missingness, sorting samples by missingness, and either exporting results or performing quality control based on the 's' argument in the provided arguments.
def ralt2exhqc( args ): cerr('[I - reading input files]') start_time = time.monotonic() M, sample_idx, site_idx = read_data( args ) cerr('[I - reading %d sites for %d samples in %d secs]' % (len(site_idx), len(sample_idx), time.monotonic() - start_time)) # create sample missingness in...
def get_random_action_set(self, parse=False): action = Action() if parse: return action.get_parse() return action def get_land_type(self, pos): # print (f">> pos: {pos}") color_code = self.get_color_code_with_pixel(self.get_color(pos)) # print (f">> color: {co...
This code handles an avatar's action in a game environment by determining its current land type, checking for survival conditions, updating its state, analyzing surroundings, and applying actions. If no land is present, the avatar dies. Otherwise, it processes vision data and executes the action set.
def act(self, avatar_index=0, randomize=True, action_set=None): if randomize or (action_set is None): action_set = self.get_random_action_set() landed_on = self.get_land_type(self.island.avatars[avatar_index].pos.ints()) if landed_on is None: # print (self.island.avatars[...
def init_pxls(self): w = self.size.width() if len(self.pxls) < w: for i in range(w): self.pxls.append(dict()) def get_point_dimetry(x, y, z): return (y-x) * sqrt(3) / 2, (x + y) / 2 - z return -x / (2 * sqrt(2)) + y, x / (2 * sqrt(2)) - z def brez(self, qp, p1...
This code generates a 2D projection of a 3D surface defined by self.func(x, y), using dimetric projection. It calculates coordinate bounds, maps values to screen dimensions, and draws top/bottom boundaries with Bresenham's algorithm, differentiating between red (bottom) and blue (top) lines. The reverse parameter contr...
def f2(self, qp, reverse=False): x1 = -2 x2 = 2 y1 = -4 y2 = 5 n = 100 miny = minx = 1000000 maxy = maxx = -minx top = [self.size.height()] * (self.size.width()) bottom = [0] * (self.size.width()) self.init_pxls() for i in range(n):...
def __get_og_share(self): grp_agg = self.data.groupby(self.agg)[self.share].sum() grp_agg = grp_agg.to_frame("share_sum") # Merge into temporary DataFrame. tmp = self.data.merge(grp_agg, left_on=self.agg, right_index=True) # Return shares. return 1 - tmp["share_sum"] def ...
The main task of the code is to fit an Aggregated Multinomial Logit (AMM) model to structured data, compute elasticities, and handle nested or non-nested structures. It processes input data with specific columns, constructs model formulas based on nesting levels, estimates parameters using OLS, and calculates price and...
def fit(self, data, RHS, share, agg=None, nests=None, grp_unit="liters", price_var="price_liter"): """ Fit AMM-model to data and calculate elasticities. The type of model is specified through the `nests` parameter. If `nests` is None (the default) an Aggregated Logit Model i...
def print_option_conditions(self): print("Option is a Call C1, with expiry {} and strike price {} on an underlying call C2.".format(self.T1,self.E1)) print("Where C2 has expiry {} and strike price {} on an underlying asset S".format(self.T2,self.E2)) return def Value_tree_method(self): ...
This code initializes a financial option model for a "call on call" derivative. It sets parameters like strike price (E2), expiry (T2), and timesteps (M) from an asset object, then prompts user input for a second call option's expiry (T1) and strike (E1). The method prepares to calculate the option value using binomial...
def __init__(self,asset,E): self.type = "Call on call" self.E2 = float(E) #strike price of underlying call C2 self.T2 = asset.T #expiry time of underlying call C2(comes from the asset tree final time) self.M = asset.M #number of timesteps self.p = asset.p #probability from the...
def print_option_conditions(self): print("Option is a Call C1, with expiry {} and strike price {} on an underlying put P2.".format(self.T1,self.E1)) print("Where P2 has expiry {} and strike price {} on an underlying asset S".format(self.T2,self.E2)) return def Value_tree_method(self): ...
This code initializes a "Call on put" option class, setting parameters like strike price (E2), expiry time (T2), and timestep data from an underlying asset. It collects user inputs for a call option's expiry (T1) and strike (E1), then prepares to calculate the option's value using a binomial tree method by calling `Val...
def __init__(self,asset,E): self.type = "Call on put" self.E2 = float(E) #strike price of underlying put P2 self.T2 = asset.T #expiry time of underlying put P2(comes from the asset tree final time) self.M = asset.M #number of timesteps self.p = asset.p #probability from the as...
def print_option_conditions(self): print("Option is a Put P1, with expiry {} and strike price {} on an underlying call C2.".format(self.T1,self.E1)) print("Where C2 has expiry {} and strike price {} on an underlying asset S".format(self.T2,self.E2)) return def Value_tree_method(self): ...
The code initializes a put option with parameters from an asset object and user inputs, setting up a binomial tree model to calculate the option's value. It stores strike price, expiry, and time steps, then invokes methods to print conditions and compute the value tree for the put option P1.
def __init__(self,asset,E): self.type = "Put on call" self.E2 = float(E) #strike price of underlying call C2 self.T2 = asset.T #expiry time of underlying call C2(comes from the asset tree final time) self.M = asset.M #number of timesteps self.p = asset.p #probability from the ...
def print_initial_conditions(self): #to check initial conditions entered correctly print("delta_t = {}".format(self.delt)) print("Expiry time T = {}".format(self.T)) print("Interest rate is {}".format(self.r)) print("Volatility (sigma) is {}".format(self.sigma)) print("Ca...
This code initializes a financial model for simulating asset price movements over time, setting parameters like time step size (delt), expiry time (T), interest rate (r), volatility (sigma), and a case identifier for probability calculation methods. It calculates the number of time steps (M) and initializes the asset's...
def __init__(self,delt,T,r,sigma,case,S_0): self.delt = float(delt) #each timestep difference so we want M*delt = T self.T = float(T) #expiry time i.e. 5 years self.r = float(r) #interest rate self.sigma = float(sigma) #standard deviation self.case = int(case) #this refers to th...
def init_board(): """ initialize board as a list of lists where - means empty """ board = [["-", "-", "-"], ["-", "-", "-"], ["-", "-", "-"]] return board def display_board(board): """ display tic tac toe board """ print("\n") for row in range...
The main task of the code is to implement a two-player Tic Tac Toe game. It initializes the board, alternates turns between "X" and "O", updates the board after each move, checks for a win or draw condition, and displays results. The game loop continues until a player wins or the board is full, ending with a thank-you ...
def play_tictactoe(): """ play tic tac toe """ is_game_over = False # is the game finished board = init_board() # initialize board current_player_symbol = "X" # "X" goes first display_board(board) # display board # continue to play until game is over while not is_game_over...
def set_dungeon_info(self): if self.dungeon_lvl == 11: self.fight_num = DECADENT_NEST_FIGHT_NUM self.castle_menu = DECADENT_NEST_CASTLE_MENU_SRC self.difficulty_src = DECADENT_NEST_DIFFICULTY_SRC self.begin_btn = BEGIN_BTN_SRC self.battle_select_instan...
The main task of the code is to automate interactions with the game "Pockie Ninja" using a headless browser. It navigates to the game site, performs actions like selecting cards, closing interfaces, and farming, looping until a specified number of fights are completed. The loop restarts automatically after reaching the...
def main_loop(self): try: with sync_playwright() as self.p: self.browser = self.p.chromium.launch(headless=self.headless) print("OPENED BROWSER") self.page = self.browser.new_page() self.page.goto("https://pockieninja.online/") ...
def performance_all9(predLab, trueLab, toleranceFP_bef, toleranceFP_aft, numLabelsPerHour): ''' fucntion that returns 9 different performance measures of prediction on epilepsy - on the level of seizure episodes (sensitivity, precision and F1 score) - on the level of seizure duration, or each sample (sens,...
The code calculates performance metrics for four label smoothing methods (no smoothing, moving average, moving average+merging, Bayesian) on predicted labels compared to true labels, returning performance scores and smoothed labels. It evaluates each method's effectiveness in reducing false positives and improving accu...
def calculatePerformanceAfterVariousSmoothing(predLabels, label, probabilityLabels,toleranceFP_bef, toleranceFP_aft, numLabelsPerHour, seizureStableLenToTestIndx, seizureStablePercToTest, distanceBetweenSeizuresIndx, bayesWind, probThresh): numTypes=4 #no smooth, movignAvrg, MmovingAvrg+merging, bayes numPerf=...
def getPage(page): try: c = urllib2.urlopen(page) except: print("Could not open %s" % page) return BeautifulSoup(c.read(), features="html.parser") def toolsSection(soup, items): table = soup.find("table") headers = table.findAll("th") rows = table.findAll("tr") heads = [] ...
The code crawls the D&D 5e Wiki's "items" section, extracting item data from linked pages while excluding specified blacklisted categories. It processes each valid link, handling special cases like "/tools" with dedicated functions, and compiles results into a dictionary. The function returns this structured data, omit...
def items(): items = {} page = "http://dnd5e.wikidot.com/" soup = getPage(page) blacklist = ["/wondrous-items", "/currency", "/siege-equipment", "/firearms"] processH2 = ["/armor"] for itemGroup_ in soup.find(id="toc76").find_next_sibling().findAll("a", href=True): lin...
def delete_userless_histories(app, cutoff_time, info_only=False, force_retry=False): # Deletes userless histories whose update_time value is older than the cutoff_time. # The purge history script will handle marking DatasetInstances as deleted. # Nothing is removed from disk yet. history_count = 0 s...
The main task of the code is to manage library and dataset cleanup in a system by processing command-line arguments. It handles operations like deleting userless histories, purging deleted datasets, and removing data from disk, based on specified time thresholds and flags. The script orchestrates these actions through ...
def main(): """ Managing library datasets is a bit complex, so here is a scenario that hopefully provides clarification. The complexities of handling library datasets is mostly contained in the delete_datasets() method in this script. Assume we have 1 library dataset with: LibraryDatasetDatasetAssocia...
def PawnMove(movecount,Row,Column,StrGrid): array=[] multiplier=SignChange(movecount) if movecount%2==0 and Column==6 and StrGrid[Column-multiplier][Row]=='empty' and StrGrid[Column-multiplier*2][Row]=='empty': array.append(str(Row)+'+'+str(Column-(multiplier*2))) if movecount%2==...
The function `ValidMove` determines if a chess move is valid by delegating to piece-specific validation functions (e.g., `PawnMove`, `RookMove`) based on the input piece type. It checks the move's legality using the board state (`StrGrid`) and move count (`movecount`), ensuring adherence to each piece's movement rules.
def ValidMove(movecount,Row,Column,Strpiece,StrGrid): if Strpiece[1:]=='pawn': return PawnMove(movecount,Row,Column,StrGrid) elif Strpiece[1:]=='rook': return RookMove(movecount,Row,Column,StrGrid) elif Strpiece[1:]=='knight': return KnightMove(movecount,Row,Column,StrGrid) elif ...
def bKingPosition(): for Row in range(8): for Column in range(8): if StrGrid[Column][Row]=='bking': return str(Row)+'+'+str(Column) def wKingPosition(): for Row in range(8): for Column in range(8): if StrGrid[Column][Row]=='wking': return s...
This function checks if the current king (black or white) is in a valid move position based on the given parameters. It draws the king's position, highlights the square in red if valid, updates the display, and returns True if valid; otherwise, returns False.
def Check(movecount,row,column,Strpiece,StrGrid): bkingpos=bKingPosition() wkingpos=wKingPosition() if Strpiece[0]=='w': krow=int(bkingpos[0]) kcolumn=int(bkingpos[2]) OneSqaure(movecount,krow,kcolumn) screen.blit(bking,(5+krow*60,5+kcolumn*60)) if bki...
def signup(): global name, pin, cb # Use global variables name = input("Please create your username: ") pin = input("Please create your six-digit pin: ") if len(pin) != 6: print("Invalid! Pin must be six digits.") signup() else: print("Sign up successful") print("Th...
The main task of the code is to present a menu allowing users to choose between signing up or logging in, and then recursively loop back to the menu unless the user selects "Yes" to exit. It handles invalid inputs with error messages and ensures the program continues running until the user explicitly chooses to finish.
def mainmenu(): optionone = int(input("Choose 1 to sign up and Choose 2 to log in: ")) if optionone == 1: signup() elif optionone == 2: login() # Call the login function else: print("Option is not available") exit_choice = input("Are you finished? (Yes or No) ") if exit...
def doubleHandOption(self, player, strike): if strike == 3: print("ASSUMING NO") return False else: output = "" allPossibleValue = player.calculateValue(player.getPlayerDeck(0)) # print(f"Your cards player {player.getPlayerNumber()} -> ") ...
This code initializes a game by processing each player's turn, handling doubling or hitting actions, then executing the house's turn, determining winners, and broadcasting results to all players.
def __init__(self, amountOfPlayers, playerList): game = Game.Game(amountOfPlayers, playerList) playersList = game.getPlayersList() for player in playersList: isHouse = player.getHouseFlag() if not isHouse: if player.checkDouble(): fla...
def do_round(round_num, roll_dice): print(f"Starting round {round_num}") round_score = 0 num_dice = 6 while True: print(f"Rolling {num_dice} dice...") roll = roll_dice(num_dice) display_formatted_roll(roll) if GameLogic.calculate_score(roll) == 0: zilch() ...
The main task of the code is to manage a game with multiple rounds. It initializes a total score, iterates through the specified number of rounds, calculates each round's score using `do_round`, accumulates valid scores into `total_score`, and calls `complete_round` for updates. If a round returns `-1`, the game termin...
def start_game(number_of_rounds, roll_dice): total_score = 0 for round_num in range(1, number_of_rounds + 1): round_score = do_round(round_num, roll_dice) if round_score == -1: break total_score += round_score complete_round(round_num, total_score, round_score) en...
def invite_to_play(): print("Welcome to Ten Thousand") print("(y)es to play or (n)o to decline") choice = input("> ") return choice == "y" def start_game(number_of_rounds, roll_dice): total_score = 0 for round_num in range(1, number_of_rounds + 1): round_score = do_round(round_num, roll_...
The code defines a function `play_dice` that initiates a dice game. It checks if the user accepts an invitation to play; if so, it starts the game with a specified number of rounds using a provided roller function. If declined, it handles the decline. The main task is to orchestrate game initiation based on user input,...
def play_dice(roller=GameLogic.roll_dice, num_rounds=20): accepted = invite_to_play() if accepted: start_game(num_rounds, roller) else: decline_game()
def game_over(self): return self.stand or self.state == WIN_STATE or self.state == LOSE_STATE def check_reward(self): if not self.game_over(): return 0 if self.state == WIN_STATE: return 1 return -1 def act_hit(self): # Give player a card ca...
The main task of the code is to simulate a game sequence by following a given policy, recording each state and its corresponding reward until the game ends. The function returns a list of tuples representing the sequence of states and rewards from the initial state to the terminal state, based on actions determined by ...
def simulate_sequence(self, policy): """ Simulate a sequence based on the passed in policy :param policy: the policy function that gives an action based on user's sum :return: a sequence of states from the original state to terminal """ episode = [] whi...
def game_over(self): return self.stand or self.state == WIN_STATE or self.state == LOSE_STATE def check_reward(self): if not self.game_over(): return 0 if self.state == WIN_STATE: return 1 return -1 def act_hit(self): # Give player a card ca...
The main task of the code is to simulate one step in a game by executing the given action (HIT or STAND), check if the game is over, update the game state accordingly, and return the new state along with the calculated reward. If the current state is already terminal, it returns None and the reward instead.
def simulate_one_step(self, action): """ Simulate one step based on the passed in action :param action: the action to take at the current state :return: a sequence of states from the original state to terminal """ # If the current state is already terminal, return None ...
def __get_all_phone_links(self): """ Write the phone links in 'links' file for each brand. :return: the phone links list """ phone_links = [] brands = self.__get_brand_links() logging.info('Got ' + len(brands).__str__() + ' brands.') for key in brands: ...
The code's main task is to crawl phone links, either by reading from a file or fetching them, then writing phone details. It checks for an existing 'links' file; if absent, it retrieves all phone links and writes them in a separate thread. Finally, it processes the links to extract and write phone details, ensuring eff...
def crawl(self): brands = {} phone_links = [] links_file = Path('links') if links_file.is_file(): logging.info('links file exists, reading phone links from file') with open('links') as f: phone_links = f.read().splitlines() else: ...
def estimate_pose(depth, mask, camera, view_matrix): """ In: depth: Numpy array [height, width], where each value is z depth in meters. mask: Numpy array [height, width], where each value is an obj_id. camera: Camera instance. view_matrix: Numpy array [16,] of float64, representi...
The code performs pose estimation for validation/test sets by processing depth images and masks. It estimates object poses using predicted and ground-truth masks (for validation), saves results as PLY files and pose data, and ensures directory structures for output.
def main(): args = parser.parse_args() if args.val: dataset_dir = "./dataset/val/" print("Pose estimation for validation set") elif args.test: dataset_dir = "./dataset/test/" print("Pose estimation for test set") else: print("Missing argument --val or --test") ...
def get_list_of_videos(youtube): days_before = int(input("Videos in last _____ days.\t")) query = input("Enter your search query:\t") video_list_details = youtube.search().list(q = query,part="snippet",type="video",order='viewCount',publishedAfter=getting_date_time(days_before),maxResults=50).execute() ...
The main task of the code is to fetch YouTube video data using the YouTube Data API, process it into a structured DataFrame, clean the data, and extract a list of video URLs for further use.
def main(): youtube = build("youtube","v3",developerKey=api_key) video_list_details = get_list_of_videos(youtube) df = create_df(video_list_details) df = clean_df(df) return df["VIDEO URL"].tolist()
def get_default_path(): return os.path.join(DEFAULT_OUT_DIR, f'result_{now_str()}.txt') def write(f, value): f.write(f'{value}\n') def write_result(f, result): write(f, '--------------------------------------') write(f, 'File path:') write_with_indent(f, result.file_path) write(f, 'Sheet tile:'...
The function `write_results` saves a list of results to a specified file path or a default location. It writes a header, iterates through each result to log them, and adds a footer. The path is created if missing, ensuring structured output storage.
def write_results(results: list, path: str = None): if path is None: os.makedirs(DEFAULT_OUT_DIR, exist_ok=True) path = get_default_path() with open(path, encoding='utf_8', mode='w', newline='') as f: write(f, '=============== RESULT ===============') for result in results: ...
def clip_coords(self, coords): # TODO: should this all be in pixel space? coords = np.clip(coords, 0.0, 1.0) return coords def eval_state(self, new_coords, input_patches): new_similarity = self.patch_similarity(input_patches, new_coords) delta_similarity = new_similarity - self.s...
The function propagates coordinates in a grid by rolling them along row and column axes, adjusting positions with delta values, evaluating new states, and selecting optimal coordinates and similarity values iteratively for a specified number of steps.
def _propagate(self, input_patches, reverse_propagation=False): if reverse_propagation: roll_direction = 1 else: roll_direction = -1 sign = float(roll_direction) for step_i in range(self.num_propagation_steps): new_coords = self.clip_coords(np.roll(sel...
def get_patches_for(self, img): return make_patch_grid(img, self.patch_size) def update_with_patches(self, input_patches, reverse_propagation=False): self._propagate(input_patches, reverse_propagation=reverse_propagation) self._random_update(input_patches) def normalize_patches(self, patches): ...
The main task of the code is to process an input image by extracting patches, normalizing them, and updating the model using these patches. The `reverse_propagation` flag determines whether the update follows a forward or backward pass, likely for training or inference. The function prepares input data and triggers a m...
def update(self, input_img, reverse_propagation=False): input_patches = self.get_patches_for(input_img) self.update_with_patches(self.normalize_patches(input_patches), reverse_propagation=reverse_propagation)
def generate_real_samples(n=100): # Generate inputs in [-1.5, 1.5] X1 = 3 * (np.random.rand(n) - 0.5) # Get the outputs f(x) X2 = f(X1) # Stack the arrays X1 = X1.reshape(n, 1) X2 = X2.reshape(n, 1) X = np.hstack((X1, X2)) # Now generate the class labels Y = np.ones((n, 1)) r...
This code trains a GAN by alternatingly updating the discriminator with real/fake samples and the generator via the GAN model. It generates real/fake data batches, trains the discriminator on both, then trains the generator using inverted labels. Performance is logged every 10 epochs.
def train(g_model, d_model, gan_model, latent_dim, fr, n_epochs=1000, n_batch=128): # Determine half the size of one batch, for updating the discriminator half_batch = int(n_batch / 2) # Manually enumerate epochs for i in range(n_epochs): # Prepare real samples x_real, y_real = generate_...
def calculateDimensions(self): currentFont = font.Font(font=self.font) txtlines = self.txt.split("\n") txtwidth = max([currentFont.measure(i) for i in txtlines]) txtheight = currentFont.metrics("linespace") * len(txtlines) width = max( (self.borders["right"] + self.bo...
This code initializes a customizable button widget with features like shape, color, borders, shadows, text, and interactivity. It sets up visual properties, handles resizing, and binds events for clicks, hover, and configuration changes, enabling a styled, interactive GUI button with dynamic styling and user interactio...
def __init__( self, master, shape: Literal["rect", "circle"] = "rect", width: int = 100, height: int = 100, cornerRadius: int = 0, shadowLength: int = 0, shadowHasBorder: bool = True, borders: Borders = {}, buttonColor: str = "#e7e3db", ...
def drawShadowBorders(self, update=False): if not update: self.shadowBorder = self.createShape( 0, self.shadowLength, self.width, self.height, fill=self.shadowBorderColor, ) else: self.upd...
The main task of the code is to update the graphical interface by invoking methods that redraw shadows, borders, buttons, and text elements. Each called method (e.g., `drawShadow`, `drawButton`) likely refreshes its respective visual component with the `update=1` parameter, ensuring the interface reflects the latest st...
def updateDrawing(self): self.drawShadowBorders(update=1) self.drawShadow(update=1) self.drawButtonBorders(update=1) self.drawButton(update=1) self.drawText(update=1)
def save_high_score(): """Save high score to file in current dir.""" with open('high_score.txt', 'w') as contents: save_it = str(Bg.high_score) contents.write(save_it) def update_score(): """Update the players score label.""" score_label = Label(score_frame, bg='o...
This function displays a popup confirming a correct answer, increments question and score counters, updates the high score if applicable, and proceeds to the next question by refreshing the game state with new questions and answer choices.
def correctly_answered(): """Pop up box if answered correctly.""" messagebox.showinfo(Bg.window_title, str(Bg.answer) + ' is correct\n\n' 'Well done, you earned a point.') Bg.qcount += 1 # Next question. Bg.answr_count += 4 # Update highscore. if...
def check_end_game(): """Check if game over, if so get rating and end game.""" get_rating() if Bg.qcount > Bg.total_questions: messagebox.showinfo(Bg.window_title, 'Game Over\n\nYou scored ' + str(Bg.your_score) + ' out of ' + str(Bg.total_que...
This function handles incorrect answers by displaying a message box, updating game counters, checking game end conditions, and redisplaying the question and answer choices for the next attempt.
def wrong_answer(): """Pop up box if answered incorrectly.""" messagebox.showinfo(Bg.window_title, str(Bg.wrong) + ' is wrong\n\n' 'You get no points for that.') Bg.qcount += 1 Bg.answr_count += 4 check_end_game() display_quest_count() display_...
def update_score(): """Update the players score label.""" score_label = Label(score_frame, bg='orange', font=('Helvetica', 14, 'bold'), text='Your Score: ' + str(Bg.your_score) + ' Highscore: ' + str(Bg.high_score...
This function handles the action when button A is clicked. It checks if the user's answer matches the correct option (Bg.choy[0]). If correct, it increments the score, updates the display, and triggers a correct response. If incorrect, it records the wrong answer and triggers an error response.
def clkd_but_a(): """Answer button A was clicked.""" if Bg.answer == Bg.choy[0]: Bg.your_score += 1 update_score() correctly_answered() else: Bg.wrong = Bg.choy[0] wrong_answer()
def update_score(): """Update the players score label.""" score_label = Label(score_frame, bg='orange', font=('Helvetica', 14, 'bold'), text='Your Score: ' + str(Bg.your_score) + ' Highscore: ' + str(Bg.high_score...
The function handles button B's click event by checking if the selected answer matches the correct option. If correct, it increments the score, updates the display, and triggers a correct response. If incorrect, it records the wrong answer and triggers an error response, managing quiz feedback and scoring logic.
def clkd_but_b(): """Answer button B was clicked.""" if Bg.answer == Bg.choy[1]: Bg.your_score += 1 update_score() correctly_answered() else: Bg.wrong = Bg.choy[1] wrong_answer()
def update_score(): """Update the players score label.""" score_label = Label(score_frame, bg='orange', font=('Helvetica', 14, 'bold'), text='Your Score: ' + str(Bg.your_score) + ' Highscore: ' + str(Bg.high_score...
The function handles a button click event for option C. It checks if the selected answer matches the correct answer (Bg.choy[2]). If correct, it increments the score, updates the display, and triggers a correct feedback function. If incorrect, it records the wrong answer and triggers an incorrect feedback function.
def clkd_but_c(): """Answer button C was clicked.""" if Bg.answer == Bg.choy[2]: Bg.your_score += 1 update_score() correctly_answered() else: Bg.wrong = Bg.choy[2] wrong_answer()
def update_score(): """Update the players score label.""" score_label = Label(score_frame, bg='orange', font=('Helvetica', 14, 'bold'), text='Your Score: ' + str(Bg.your_score) + ' Highscore: ' + str(Bg.high_score...
The function handles a button D click event by checking if the user's answer matches the fourth option in `Bg.choy`. If correct, it increments the score, updates the display, and triggers a correct response. If incorrect, it records the wrong answer and triggers an error response. The task is to validate user input and...
def clkd_but_d(): """Answer button D was clicked.""" if Bg.answer == Bg.choy[3]: Bg.your_score += 1 update_score() correctly_answered() else: Bg.wrong = Bg.choy[3] wrong_answer()
def autoLagoonFinder(intWater, numLagoon, cp): '''finds all the lagoons for the given atoll image Inputs: intwater and number of lagoons, and center points of lagoons outputs: label image, # lagoons found, which ones found based on center points''' waters = cleanbinary(intWater, 256) label_wate...
The code iteratively refines water regions by eroding pixels along lines between points read from a file, aiming to meet a condition where all elements in `cpTF` are True. It modifies the input water image (`intWater`) by zeroing out pixels along calculated paths, repeatedly calling `autoLagoonFinder` to update water r...
def manualLagoonFinder(intWater, numLagoon, cp): #change to always add the lines to intwater waters, label_water_img_bySize, numWater, cpTF = autoLagoonFinder(intWater, numLagoon, cp) water1 = np.copy(intWater) f= open("lagoon_closer.txt","a+") f.seek(0, 0) n = 1 while n < 70 and n...
def detectCombat(self, IDString): if self.map: return if IDString in self.mapIdentifiers: map = self.mapIdentifiers[IDString] if map == "Infected_Space_Elite": # add exceptions for all other maps that have unique entities to identify map difficulty ...
The code reads a combat log file, splits it into individual combat sessions based on time gaps, creates temporary files for each session, and prepares the data for analysis by storing structured combat information. It processes timestamps, detects combat IDs, and manages file writing to organize log entries for further...
def readCombat(self): combatID = 0 newCombat = True combatDelta = datetime.timedelta(seconds=100) lastTime = None firstLine = True parsedLines = 0 self.map = None with open(self.path, "r") as file: start = timer.time() for line in f...
def resetParser(self): self.warpCoreBreach = None self.combatlog = [] self.playerdict = {} self.playerList = [] self.NPCs = [] self.tableArray = [] self.otherCombats = {} self.splicedCombatlog = [] self.uiDictionary = {} self.counter2 = 0 ...
The main task of the code is to process combat logs by resetting the parser, enabling depth analysis, analyzing combat data, generating UI tables, and returning structured outputs like damage/heal tables, maps, difficulty data, and charts for visualization or further processing.
def reReadCombatFull(self): self.resetParser() self.depthAnalysis = True self.combatLogAnalysis() self.generatedUItables() return self.uiDictionary, self.dmgTableIndex, self.healTableIndex, self.uiInputDictionary, self.otherCombats, self.map, self.difficulty, self.damageChart, se...
def setPath(self, path): self.path = path def readCombat(self): combatID = 0 newCombat = True combatDelta = datetime.timedelta(seconds=100) lastTime = None firstLine = True parsedLines = 0 self.map = None with open(self.path, "r") as file: ...
The function processes combat data from a given file path by setting the path, reading combat details, generating UI tables, and returning multiple data structures including UI dictionaries, damage/healing indices, input dictionaries, combat statistics, maps, difficulty levels, and various charts for visualization.
def readCombatwithUITables(self, path): self.setPath(path) self.readCombat() self.generatedUItables() return self.uiDictionary, self.dmgTableIndex, self.healTableIndex, self.uiInputDictionary, self.otherCombats, self.map, self.difficulty, self.damageChart, self.DPSChart, self.NPCDamageCh...
def resetParser(self): self.warpCoreBreach = None self.combatlog = [] self.playerdict = {} self.playerList = [] self.NPCs = [] self.tableArray = [] self.otherCombats = {} self.splicedCombatlog = [] self.uiDictionary = {} self.counter2 = 0 ...
The main task of the code is to read and analyze combat data from a specified file path, generate UI-related tables, and return structured combat statistics including damage/healing tables, DPS charts, NPC damage data, and other parsed information for further processing or visualization.
def readCombatFull(self, path): self.resetParser() self.depthAnalysis = True self.setPath(path) self.readCombat() self.generatedUItables() return self.uiDictionary, self.dmgTableIndex, self.healTableIndex, self.uiInputDictionary, self.otherCombats, self.map, self.difficul...
def resetParser(self): self.warpCoreBreach = None self.combatlog = [] self.playerdict = {} self.playerList = [] self.NPCs = [] self.tableArray = [] self.otherCombats = {} self.splicedCombatlog = [] self.uiDictionary = {} self.counter2 = 0 ...
The function `readCombatShallow` parses combat data from a specified file path, initializes parsing settings (e.g., disabling depth analysis), and returns parsed elements like combat logs, map details, difficulty, and damage statistics. It resets the parser, sets the file path, and executes a combat read operation to e...
def readCombatShallow(self, path): self.resetParser() self.depthAnalysis = False self.setPath(path) self.readCombat() return self.otherCombats, self.map, self.difficulty, self.damageChart, self.DPSChart, self.NPCDamageChart, self.NPCDPSChart
def resetParser(self): self.warpCoreBreach = None self.combatlog = [] self.playerdict = {} self.playerList = [] self.NPCs = [] self.tableArray = [] self.otherCombats = {} self.splicedCombatlog = [] self.uiDictionary = {} self.counter2 = 0 ...
The method processes combat data from a temporary file by resetting the parser, enabling depth analysis, reading combat data, generating UI tables, and returning structured data including UI dictionaries, damage/healing indices, input dictionaries, combat stats, maps, difficulty levels, and damage/DPS charts for displa...
def readTempFileCombatFull(self, otherCombat): self.resetParser() self.depthAnalysis = True self.readCombatFromTempfile(otherCombat) self.generatedUItables() return self.uiDictionary, self.dmgTableIndex, self.healTableIndex, self.uiInputDictionary, self.otherCombats, self.map, se...
def _send_beacon(self): website = '%s?profile=%s' % (self.profile['server'], self._encode_string(json.dumps(self.profile))) return requests.get(website) def _next_instructions(self, beacon): soup = BeautifulSoup(beacon.content, 'html.parser') instructions = soup.find(id='instructions') ...
The code's main task is to continuously send beacons, retrieve and process instructions, and manage sleep intervals in an infinite loop. It initializes a results list, prints beacon status, sends a beacon, fetches next instructions, handles them to determine sleep duration, and repeats. Errors are caught, logged, and h...
def start(self): while True: try: self.profile['results'] = [] print('[*] Sending beacon for %s' % self.profile.get('paw', 'unknown')) beacon = self._send_beacon() instructions = self._next_instructions(beacon=beacon) sl...
def add_user(username, email, full_name, institution, aws_username): try: roles = [] user_id = 0 if institution in paying_members: roles.append('wos_gold') elif institution in btaa_members: roles.append('wos') elif institution in trial_member...
The main task of the code is to handle a Cognito authentication callback by exchanging an authorization code for tokens, retrieving user information, determining the user's institution based on their username, and creating or updating a user record in the system with tokens and metadata. It redirects to a dashboard wit...
def cognito_callback(): code = request.args.get('code') token_args = { "code": code, "grant_type": "authorization_code", "redirect_uri": util.config_reader.get_cognito_redirect_uri(), "client_id": util.config_reader.get_cognito_client_id() } headers = { "Content-...
def get_exllama_params(self): stop_string = self.get_stop_strings() exllama_params = { 'max_new_tokens': self.settings_win.max_new_tokensSpin.value(), 'temperature': self.settings_win.temperatureSpin.value(), 'top_p': self.settings_win.top_pSpin.value(), ...
The main task of the code is to initiate asynchronous text generation using a specified backend (exllama/llama.cpp) by creating a separate thread. It prepares parameters, updates the UI status, connects result handlers, and enables read-only mode for history. The thread processes input messages, streams results, and tr...
def launch_backend(self, message, backend): # Get the exllama and cpp parameters from their respective methods exllama_params = self.get_exllama_params() cpp_params = self.get_llama_cpp_params() self.statusbar.showMessage("Status: Generating...") # Create a thread to run the te...
def get_current_backend(self): # Use a dictionary to map the check boxes to the backend names check_boxes = { self.cppCheck: LLAMA_CPP, self.cppServerCheck: LLAMA_CPP_SERVER, self.exllamaCheck: EXLLAMA, self.tsServerCheck: TS_SERVER, self.rwkvC...
This method handles text generation mode switching by updating UI elements and preparing input for a backend. It maps the selected mode to the appropriate input widget, retrieves the input text, and processes it differently based on the mode. In "chat_mode," it formats the input with HTML line breaks, appends it to the...
def textgen_switcher(self, textgen_mode): self.textgen_mode = textgen_mode backend = self.get_current_backend() # Use a dictionary to map the textgen modes to the input widgets input_widgets = { "default_mode": self.defaultTextInput, "notebook_mode": self.notebo...
def setup(args): """ Creates a buffer of frames with space for 2, times the rate. Creates an eit object for impedance processing. """ global eit, frames_buffer, images_buffer, rate, Nbuff, INVERSE_SOLUTION_METHOD, image_x_pixels, image_y_pixels from time import time # Initialize the buffer ...
This function tests a tomographic reconstruction algorithm on real data from an Excel file. It reads input frames, processes them iteratively to generate images and tidal maps, visualizes results using matplotlib, and optionally saves output data. The code measures execution time, handles image normalization, and plots...
def _test_real_data(): from time import time import pandas as pd data_to_save = [] SHOW_IMAGE = True SAVE_DATA = False data = pd.read_excel("Chedi_frames_only.xlsx").to_numpy() # print(data.shape) # (30688, 16) # 30688/(16) = 1918.0 n = 1900 rate = 15 t0 = time() setup(arg...
def cell_canonical(self,threshold=1e-12): """ transform the iMPS into the right canonical form: . . . --G--G--- . . . | | , where --G--- -- --s--G-- -s- | | = | and | | = | --G--- -- --s--G-- ...
The main task of the code is to generate a canonical form for each site in a quantum system. It first canonicalizes the cell, then iteratively applies single-site SVDs from both ends toward the center (right then left), ensuring consistency after each step. This process enforces a canonical structure across all sites, ...
def site_canonical(self,threshold = 1e-12): """generating the canonical form for each site""" self.cell_canonical(threshold) if self.L>=2: """for i in range(self.L-2,-1,-1): self.two_site_svd(i) self.check_consistency()""" ...
def calculate_norm(self): trans = self.transfer_matrix() assert isinstance(trans,linalg.LinearOperator), 'wrong type' shape = trans.shape if shape[0]>3: lam,v = linalg.eigs(trans,2) else: lam,v = scipy.linalg.eig(trans * np.identity(shape[...
This function initializes a tensor network by storing input tensors in self.B, extracting their dimensions into chi and d arrays, initializing identity matrices in self.s, calculating the initial norm, enforcing site canonical form, and verifying consistency and canonical structure for subsequent operations like tensor...
def construct_from_tensor_list(self,tensor_list): self.B=[] for i in range(len(tensor_list)): self.B.append(tensor_list[i]) self.L = len(self.B) self.s = [None]*self.L self.chi = np.zeros(self.L,dtype = int) self.d = np.zeros(self.L,dtype = int) fo...
def getAllPossibleMoves(self): moves = [] for r in range(len(self.board)): for c in range(len(self.board[r])): turn = self.board[r][c][0] if (turn == "w" and self.whiteToMove) or (turn == "b" and not self.whiteToMove): piece = self.board[r]...
The code generates valid moves by removing those that leave the king in check. It temporarily stores en passant status, iterates through all possible moves, simulates each move, checks for check conditions, and removes invalid moves. It then determines checkmate or stalemate if no valid moves remain, restores en passan...
def getValidMoves(self): tempEnPassantPossible = self.enPassantPossible moves = self.getAllPossibleMoves() for i in range(len(moves)-1, -1, -1): self.makeMove(moves[i]) self.whiteToMove = not self.whiteToMove if self.inCheck(): moves.remove(m...
def recalculate_list_of_list_zoom_positions(self,zoom_delta,mouse_x,mouse_y,length_list,list_x,list_y): new_list_x = [] #empty list of lists to store new x positions new_list_y = [] #empty list of lists to store new y positions for i in range(length_list): #go through the whole of both lists of ...
The code applies a zoom transformation to compound lines by recalculating their points and midpoints based on the mouse position and zoom delta, then renders the updated lines.
def apply_zoom_compound_lines(self,zoom_delta,mouse_x,mouse_y): self.compound_line_points_x,self.compound_line_points_y = self.recalculate_list_of_list_zoom_positions(zoom_delta,mouse_x,mouse_y,self.num_compound_lines,self.compound_line_points_x,self.compound_line_points_y) #zoom the points that make up the co...
def get_automatic_scaling_boundaries(self,border_fraction_x,border_fraction_y): extremes_defined,extreme_north,extreme_south,extreme_east,extreme_west = self.get_extreme_positions() #get the extreme positions in global coordinates #if we could not find any extremes (likely due to their being objects), w...
This function determines the scaling parameters (pixels per unit, start coordinates) for visualizing nodes based on the specified mode. It supports automatic scaling (fitting all nodes with border fractions), manual scaling (user-defined start coordinates and scale), and semi-automatic scaling (user-defined start coord...
def determine_scale(self,scale_mode='automatic',pixels_per_unit=1,start_x=0,start_y=0,extra_x=1,extra_y=1,border_fraction_x=0.1,border_fraction_y=0.1): if scale_mode=='automatic': #automatic scaling mode, fit in all the nodes self.pixels_per_unit,self.start_x,self.start_y = self.get_automatic_scalin...
def init_lines(self): #lines, these are well, lines self.num_lines = 0 #number of lines stored self.line_info_name = 'none' #name of the info stored with the lines self.line_info_type = 'none' #type of the info stored with the lines #arrays of line properties #relating to...
The main task of the code is to create and configure multiple lines with specified attributes (width, color, names, info) and positions. It initializes line storage, assigns properties, sets start/end node positions, calculates midpoints, and marks lines as assigned, likely for a graphics or data visualization system.
def create_lines(self,lines_width,lines_colour,lines_name,info_name,info_type,lines_info,lines_start_node_type='none',lines_start_node_index=-1,lines_end_node_type='none',lines_end_node_index=-1,line_coords_prefer=False,lines_start_x_coord=[],lines_start_y_coord=[],lines_end_x_coord=[],lines_end_y_coord=[]): se...