dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def ga_init(cfg): n_best=20 #with open("{}.trans".format(f)) as trans, open("{}.scores".format(f)) as scores, open( # "{}.ref".format(f)) as refs, open("{}.src".format(f)) as srcs, open( # "{}.tgt_words_exp".format(f)) as dict_tgts: with open(cfg.sources()) as srcs, open(cfg.translatio...
The code performs Minimum Bayes Risk (MBR) decoding on machine translation outputs using a COMET model. It processes source texts and multiple translation candidates, computes embeddings with the model, and selects the best candidate per source by maximizing MBR scores. The script handles model loading, input parsing, ...
def mbr_command() -> None: parser = ArgumentParser(description="Command for Minimum Bayes Risk Decoding.") parser.add_argument("-s", "--sources", type=Path_fr) parser.add_argument("-t", "--translations", type=Path_fr) parser.add_argument("-r", "--ref", type=Path_fr) parser.add_argument("-m", "--muta...
def remove_salt_pepper_noise( preds ): r"""Postprocess and remove salt-n-pepper noise.""" pattern = [ [1, 1, 0, 1, 1], [1, 1, 0, 1], [0, 0, 1, 0, 0], [0, 0, 1, 0], ] replace = [] for i in range(len(pattern)): replace.append( [pattern[i][0] for ...
The function processes predicted ECG QRS node masks by removing salt-and-pepper noise, filtering low-confidence nodes, enforcing minimum RR intervals between beats, and recovering missing beats for long RR gaps. It logs node counts, saves detailed node data to CSV if enabled, and records performance scores at each post...
def process_pred_mask( subject, df, annot=None, persist_verbose=False ): r"""Postprocess prediction.""" # subject = subject[:subject.find('.csv')] r"""Postprocess rule: (S): Remove Salt-n-pepper noise. """ list_pred_mask = df['pred_mask'].values revised_pred_mask = remove_salt_peppe...
def train_model( self, train_df: DataFrame, ) -> NoReturn: """ Trains the machine learning model. It takes the data in pandas DataFrame format, preprocesses it, builds a model on top it, trains it, and saves it. Args: train_df: DataFrame ...
The main task of the code is to execute a machine learning pipeline by training, testing, or both, based on input flags. It loads training/test datasets, handles errors, and invokes corresponding methods (train_model, test_model, or train_and_test_model) while logging progress and exceptions. The function ensures contr...
def run( self, train: bool = False, test: bool = False, train_and_test: bool = False, ) -> NoReturn: """ Runs the entire project as a pipeline. To run, we can give options either to run the entire pipeline, or to run only a part of it ...
def makeMoveUnderPolicy(board, Net, gamma, eps): movesToDo = nn2048helper.checkMoves(board) if len(movesToDo) == 0: return None, 0, 0 if random.random() <= eps: move = random.choice(movesToDo) newBoard, rewToNet, reward = nn2048helper.makeMove(board, move) return newBoard, re...
The code simulates a 2048 game using a neural network policy, collecting board states and adjusted scores (combining neural network predictions and new gains) for training. It initializes or randomizes the board based on episode number, applies moves via the network, accumulates rewards, and logs data until the game en...
def run(self): overallScore = 0 if self.epNum <= 50: board = nn2048helper.initBoard() else: if random.random() <= 0.3: board = nn2048helper.initBoard() else: board = nn2048helper.randomBoard(random.randint(2, 12)) board,...
def _extraction_method_linux(self, archive: str) -> str: larchive = archive.lower() if larchive.endswith(".zip"): return "unzip {0} -d {1}" elif larchive.endswith(".tar.xz"): return "tar -xf {0} -C {1}" elif larchive.endswith(".tar.gz"): return "tar -x...
This code extracts a file to a specified directory using OS-specific methods, creates the destination path, executes the extraction command, and optionally deletes the source file after extraction.
def extract(self, src: str | Path, dst_dir: Path, delete_src=False): if self.IS_POSIX: extraction_method = self._extraction_method_linux(str(src)) else: extraction_method = self._extraction_method_windows(str(src)) extraction_cmd = extraction_method.format(src, dst_dir) ...
def mktmp(self) -> Path: tmp = self.SUBPACK_DIR.joinpath("tmp") tmp.mkdir(exist_ok=True, parents=True) return tmp def print(self, *args): print(" ", *args, flush=True) def download(self, url: str, dst: str | Path): logger.info("download(%s) ->\n\t%s", url, dst) urlli...
This function downloads an archive file from a given URL, saves it temporarily, extracts its contents to a specified directory (or the default path), and optionally deletes the source archive after extraction.
def download_extract(self, archive_url: str, archive_type: str, extract_dir: Optional[Path]=None, delete_src=True): ark_file = str(self.mktmp().joinpath(f"{self.name}.{archive_type}")) self.print(f"downloading {self.name}...") self.download(archive_url, ark_file) self.print("ext...
def assert_input(input_text, default_return = None) -> bool: if input_text == "Y" or input_text == "y" or input_text == "yes": return True if input_text == "N" or input_text == "n" or input_text == "no": return False if default_return is not None and input_text == "": return defaul...
The code initializes a model by gathering datasets (default or user-specified) and industry demographics, generating predictions for disability proportions per industry, printing results, and providing tailored advice based on user-selected industry and input preferences.
def init_model(): use_default = assert_input(input("Would you like to use default datasets?\n(Y/n)?: "), True) print_warnings = assert_input(input("Would you like to use print warnings?\n(Y/n)?: "), True) datasets: list[dataset.ThesisDataset] = [] if use_default: for key, value in default_data...
def word_to_modules(word,alphabet): '''split a parametric word to a list of string modules according the content of alphabet''' modules=[] module='' for character in word: if character in alphabet : modules.append(module) module=character else : ...
This code uses turtle graphics to generate a 3D pattern based on input 'words' and 'alphabet' parameters. It processes modules representing movement, rotation, and drawing commands to create a branching structure, applying probabilistic rotations, coordinate translations, and polygon filling. The turtle navigates 3D sp...
def draw_turtle(words,alphabet): '''draw the 3d pattern according to alphabet parameters : patterns (string list), alphabet (list of strings) ''' #environment sigma=pi/158#standard variation of rotation angle T=[0,0,-0.5] #tropism vector e=0.2 # susceptibility to bending T=list(e*array(T...
def word_to_modules(word,alphabet): '''split a parametric word to a list of string modules according the content of alphabet''' modules=[] module='' for character in word: if character in alphabet : modules.append(module) module=character else : ...
This function generates a 3D fractal pattern using turtle graphics principles, processing input strings with L-system-like rules. It applies stochastic rotations, branching, and scaling to create organic structures, then visualizes the result in 3D space using matplotlib. The code handles path drawing, state saving/res...
def draw_matplotlib3d(words,alphabet): '''draw the 3d pattern according to alphabet parameters : patterns (string list), alphabet (list of strings) ''' #environment sigma=pi/16#standard variation of rotation angle T=[0,0,-0.5] #tropism vector e=0.5 # susceptibility to bending T=list(e*ar...
def word_to_modules(word,alphabet): '''split a parametric word to a list of string modules according the content of alphabet''' modules=[] module='' for character in word: if character in alphabet : modules.append(module) module=character else : ...
This function generates a 3D fractal pattern using turtle graphics based on input modules and an alphabet. It interprets commands like 'F' (forward), '^'/'&'/'|' (rotations), and '['/']' (branching) to draw a plant-like structure with stochastic variations. Parameters control movement, orientation, and visual propertie...
def draw_turtlestatic(words,alphabet): '''draw the 3d pattern according to alphabet parameters : patterns (string list), alphabet (list of strings) ''' #environment sigma=pi/36#standard variation of rotation angle T=[-0.02,0,-1] #tropism vector e=0.22 # susceptibility to bending T=list(e...
def __convert_to_graph(self): # init directed graph object graph = nx.DiGraph() num_nodes = self.matrix.shape[0] # add node to graph for node_idx in range(num_nodes): graph.add_node(node_idx) # add weighted edge to graph for row in range(num_nodes): ...
This code initializes a graph-based embedding model by converting a matrix into a graph structure, setting up node mappings, embedding parameters (size, order), and preparing negative sampling configurations. It constructs a sampling table, resets the model, and prepares for training with specified ratios and graph pro...
def __init__(self, matrix, embedding_size=8, negative_ratio=5, order='second', ): """ :param matrix: numpy ndarray (need to convert to nx_graph) :param embedding_size: :param negative_ratio: :param order: """ super().__init__() assert order in {'first', '...
def add_newlines(tag, context): if not guess_layout: return prev = context.prev if prev is _DOUBLE_NEWLINE: return if tag in double_newline_tags: context.prev = _DOUBLE_NEWLINE chunks.append('\n' if prev is _NEWLINE else '\n\n') ...
The function recursively traverses an XML-like tree structure, processing text content by adding newlines based on node tags and accumulating text (including `tree.text` and, if enabled, `tree.tail`) into a context. It handles both the current node's text and its children, ensuring proper formatting and text aggregatio...
def traverse_text_fragments(root_tree, tree, context, handle_tail=True): add_newlines(tree.tag, context) add_text(root_tree, tree, tree.text, context) for child in tree: traverse_text_fragments(root_tree, child, context) add_newlines(tree.tag, context) if handle_tail:...
def set_attrs(self, **kwargs): """Sets attributes from kwargs """ for k,v in kwargs.items(): self.__log.debug(f"Setting attr '{k}'") setattr(self, k,v) def load(self): if not self.__req: raise ConnectionError("Offline mode, cannot load Managed Object")...
This code initializes a class instance to represent a data model element, setting attributes like name, distinguished name (dn), and parent relationships. It optionally loads data from an APIC (Application Policy Infrastructure Controller) if specified, using `load()`, and configures internal state for tracking existen...
def __init__(self, class_name = None, dn = None,rn = None,parent_dn = None, class_meta = None, request_handler = None, load = False, **kwargs): self.__log = logging.getLogger() self.__class_name = class_name self.__class_meta = class_meta self.__dn = dn self.__rn = rn se...
def evaluate_bool(block): if block.symbol == Sym.LESS: return evaluate_int(block.children[0]) < evaluate_int(block.children[1]) elif block.symbol == Sym.EQUAL: return evaluate_int(block.children[0]) == evaluate_int(block.children[1]) elif block.symbol == Sym.AND: return evaluate_bool...
This function interprets a block of code by recursively processing its children based on the block's symbol. It handles sequences (SEQ) by iterating through children, assignments (GETS) by evaluating the right-hand side, and bindings (BOOL/INT_BINDING) by setting variables with evaluated boolean/int values. Other symbo...
def g_interpreter(block): if block.symbol == Sym.PASS: pass elif block.symbol == Sym.SEQ: for c in block.children: g_interpreter(c) elif block.symbol == Sym.GETS: g_interpreter(block.children[0]) elif block.symbol == Sym.BOOL_BINDING: block.children[0].var.set...
def baseline_random_search(g : CFG, p: Program, s : Sym = -1, int_regs : int = 1, bool_regs : int = 1): for i in range(int_regs): p.add_int_local() for i in range(bool_regs): p.add_bool_local() return random_block_search(g, p, s) def g_interpreter(block): if block.symbol == Sym.PASS: ...
The main task of the code is to generate a computational block via `baseline_random_search` that transforms an input value of 2 into an output of 2. The program iteratively sets the input to 2, executes the search to construct a block, interprets it, and checks if the output matches the input. If successful, the loop b...
def main(): p = Program( {int: [Box(int, "X")], bool : [] }, {int : [Box(int, "Y")], bool : []}, ) p.ins[int][0].set(21) p.block = baseline_random_search(Generative, p) # b = Block(Sym.GETS) # a = Block(Sym.INT_BINDING) # y = Block(Sym.WINDOW_INT) # y.var = p.outs[int][0]...
def determinant(self, matrix): num_of_rows = len(matrix) num_of_columns = len(matrix[0]) if num_of_rows == 1: # base case matrix 1x1 return matrix[0][0] if num_of_rows == 2: # base case matrix 2x2 return matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0] ...
This function calculates the inverse of a matrix. It first computes the determinant; if zero, it prints that the matrix is non-invertible. Otherwise, it generates the matrix of cofactors, transposes it, scales each element by the reciprocal of the determinant, truncates values, and returns the resulting inverse matrix ...
def inverse_matrix(self): determinant = self.determinant(self.matrix) if determinant == 0: print("This matrix doesn't have an inverse.") else: matrix_of_cofactors = self.calculate_matrix_of_cofactors() t_matrix = matrix_of_cofactors.transpose("1") ...
def get_centers_from_state_dict(state_dict): fc = None for key in MODEL_FC_KEYS: if key in state_dict: fc = state_dict[key].squeeze() break if fc is not None: return fc.detach() def get_centers_from_checkpoint(checkpoint): data = torch.load(checkpoint, map_locatio...
The main task of the code is to construct a hierarchical graph structure by clustering class centers derived from a model, using agglomerative clustering. It builds a directed tree where leaf nodes represent input classes (wnids) and internal nodes represent aggregated semantic concepts, connecting them based on cluste...
def build_induced_graph(wnids, checkpoint, model=None, linkage='ward', affinity='euclidean', branching_factor=2, dataset='CIFAR10', state_dict=None): num_classes = len(wnids) assert checkpoint or model or state_dict, \ 'Need to specify either `checkpoint` or `method` or `state_dict`.' ...
def get_root(G): roots = list(get_roots(G)) assert len(roots) == 1, f'Multiple ({len(roots)}) found' return roots[0] def get_new_adjacency(G, nodes): adjacency = set(tuple(adj) for adj in G.adj.values()) children = next(iter(adjacency)) while children in adjacency: k = random.randint(2,...
The code generates a new candidate node for a graph by filtering non-root nodes, finding their adjacency, converting to WordNet synsets, extracting meanings, and checking if the candidate is fake based on part-of-speech. It returns the candidate, a fake flag, and adjacency nodes.
def get_new_node(G): """Get new candidate node for the graph""" root = get_root(G) nodes = list(filter(lambda node: node is not root and not node.startswith('f'), G.nodes)) children = get_new_adjacency(G, nodes) synsets = [wnid_to_synset(wnid) for wnid in children] candidate = get_wordnet_mean...
def sendMsg(self, socket, msg): encode = (msg+'\0').encode('utf-8') socket.send(encode) def gameLoop(self): win = False tie = False self.board = board.Board() initial_board = self.board.serialize_board() self.sendMsg(self.player1, "Game Starting.....") sel...
This code sets up a server to handle two-player connections. It creates a socket, binds it to a port, accepts two client connections, assigns roles (Player 1 and Player 2), sends connection confirmation messages, and initiates a game loop if both players are connected. If connection fails, it logs an error and disconne...
def run(self): self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.socket.bind((self.ip, self.port)) self.socket.listen() print(f'Server Listening on {self.ip}:{self.port}') self.player1, addr1 = self.socket.accept() print(f'Player 1 connected from: {add...
def train_base_model(noGrid=True, fixedData=False, HAPT=False): x_train = pd.read_csv("../offlineModels/HAPT_Data_Set/Train/X_train.txt", sep=' ', index_col=False, header=None) y_train = pd.read_csv("../offlineModels/HAPT_Data_Set/Train/y_train.txt", sep=' ', index_col=False, header=None) x_test = pd.read_c...
The main task of the code is to train a HAPT base model, save it, modify the model by cutting its head, convert it into a transferable TFLite model named 'Hapt_neighbors.tflite', and finally export the modified model as a TFLite file for offline use. The process involves model training, structure adjustment, and format...
def main(): saved_basemodel_dir = '../offlineModels/NN/Hapt_neighbors' # model = keras.models.load_model(saved_basemodel_dir) model = train_base_model(HAPT=True) model.save(saved_basemodel_dir) model = cutOffHead(model) createTransferModel(model, modelname='Hapt_neighbors.tflite') conve...
def get_contact( self, resource_name=None, first_name=None, last_name=None, email_address=None ): if resource_name: return ( self.service.people() .get( resourceName=resource_name, personFields="names,emailAddresses,...
The main task of the code is to either update an existing contact's group memberships or create a new contact with specified details. It checks if a contact exists, retrieves/creates a contact group, updates the contact's memberships to include both the specified group and "myContacts," and executes the update. If the ...
def upsert_contact( self, first_name, last_name, email_address, contact_group_name=None ): """Update contact if already exists, otherwise create.""" contact = self.get_contact( first_name=first_name, last_name=last_name, email_address=email_address ) i...
def split_sentences(text): processed = replace_abbreviations(text) return [undo_replacement(sentence) for sentence in get_sentences(processed)] def join_words(words, separator=" "): return separator.join(words) def merge_syntactic_units(original_units, filtered_units, tags=None): units = [] for i in...
The function `clean_text_by_sentences` processes input text by splitting it into sentences, preprocessing each sentence (likely cleaning or tokenizing), joining words within each processed sentence, and then merging the original and processed sentences to retain structural integrity while applying text cleaning. Its ma...
def clean_text_by_sentences(text): original_sentences = split_sentences(text) filtered_sentences = [join_words(sentence) for sentence in preprocess_documents(original_sentences)] return merge_syntactic_units(original_sentences, filtered_sentences)
def check_config(r, t, L): check = True if get_sigma_cr_applied(r, t, L) > get_sigma_cr_column(r, t,L) or \ get_sigma_cr_applied(r, t, L) > get_sigma_cr_shell(r, t) or \ get_sigma_cr_applied(r, t, L) > mat.get("sigma_y")*1e6: check = False return check def get_mass(r, t, L): ...
The function evaluates structural configurations (radius, thickness, length) for viability under material properties and pressure. It filters valid configurations, calculates their masses, identifies the optimal viable setup, and returns viable configurations, the optimal choice, and the count of invalid configurations...
def buckling_opt(mass_total, R_lst, t_lst, L_lst, mat): global E_mat, rho, v, p, m_total m_total = mass_total #total mass E_mat = mat.get("E") * 10 ** 9 #materials young's modulus rho = mat.get("rho") #kg/m^3 v = mat.get("nu") #poission ratio p = 2.4 * (10 ** 6) *...
def create_sqlalchemy_engine( conn_dict: dict, custom_conn_str=None, connect_args={}, ): """ Function to create sqlalchemy enginefrom connection dictionary. conn_dict : Dictionary with server, database, uid and pwd information. custom_conn_str : String with custom ...
This function uploads a Pandas DataFrame to a database table using SQLAlchemy or alternative methods (Redshift/Oracle), handling parallel uploads via chunking and multiple strategies ('multi', 'execute_many', 'spark', 'single'). It connects to the database, attempts data insertion with error recovery, and returns the t...
def parallel_to_sql( df, table_name, schema, mode, conn_dict, custom_conn_str, connect_args, chunksize, method, dtypes_dict, spark_mode="append", ): """ Function to upload data to database table with sqlalchemy in parallel. df : Pandas data...
def display_board(): print(board[0] + " | " + board[1] + " | " + board[2]) print(board[3] + " | " + board[4] + " | " + board[5]) print(board[6] + " | " + board[7] + " | " + board[8]) def handle_turn(player): print(player + "'s turn.") #asking user to decide where thet want to place their X or O position = input(...
The main task of the code is to run a game loop where players take turns making moves on a board, check for a win or tie condition after each move, switch players, and declare the winner or announce a tie once the game ends.
def play_game(): #display the intial board display_board() while game_still_going: handle_turn(current_player) check_if_game_over() #other player's turn now flip_player() #game ends if winner == "X" or winner == "O": print(winner + " won!") elif winner == None: print("It's a tie...")
def addCommand(self, direction): self.addToListBox("Adding: "+direction,"black") self.command.append(direction) self.plot(direction,"black") def run(self): print("Command array:", self.command) #command split -> move + rotate(- +) + liftoff + land + flip + etc #switch or ...
This code initializes a GUI frame for drone control, setting up buttons for movement commands (forward, back, rotate), takeoff/land actions, and a command list with scrolling. It configures a dark theme, integrates matplotlib for plotting, and links to a drone object and image queue for real-time data visualization and...
def startFrame(self, drone, q): print('ManualFrame() initialized') # Let's create the fonts that we need. font_large = font.Font(family='Georgia', size='24', weight='bold') font_small = font.Font(family='Georgia', size='12') self.drone = drone self.label_text = t...
def _check_attr(self, name: str): if getattr(self, name) is None: raise CalculatorError("Attribute '{}' is None. Please set it.".format(name)) if name == "metadata" and "shape" not in self.metadata: raise CalculatorError("There is no key 'shape' in the metadata.") def show_light_...
The main task of the code is to display windows overlaid on a dark-subtracted light image. It verifies the presence of required attributes, generates a FacetGrid plot of the processed light image, draws specified windows onto the plot's axes, and returns the resulting FacetGrid for further use or display.
def show_windows(self, *args, **kwargs) -> FacetGrid: """Show the windows on the dark subtracted light image.""" self._check_attr("light") self._check_attr("windows") facet = self.show_light_sub_dark(*args, **kwargs) draw_windows(self.windows, facet.axes) return facet
def squeeze_shape_and_extents(self) -> None: """Squeeze the shape and extents so that it only has the dimension with length > 1.""" self._check_attr("metadata") shape = self.metadata["shape"] n = len(shape) # get the index of the dimension > 1 index = {i for i in range(n)...
This function automatically processes data using a standard protocol by calculating dark/light images, detecting peaks, determining windows, computing intensities, and assigning coordinates/Q-values, while validating input parameters and handling errors during computation.
def auto_process(self, num_wins: int, hw_wins: int, diameter: int, index_filter: slice = None, *args, **kwargs) -> None: """Automatically process the data in the standard protocol. The calculation results are saved in attributes. Parameters ---------- num_w...
def _check_attr(self, name: str): if getattr(self, name) is None: raise CalculatorError("Attribute '{}' is None. Please set it.".format(name)) if name == "metadata" and "shape" not in self.metadata: raise CalculatorError("There is no key 'shape' in the metadata.") def show_frame(...
This function displays windows on a specific frame by creating a FacetGrid plot. It verifies the presence of the 'windows' attribute, generates a frame plot using show_frame, draws the windows onto the plot's axes, and returns the resulting FacetGrid object for further manipulation or display.
def show_windows_on_frame(self, index: int, *args, **kwargs) -> FacetGrid: """Show the windows on the frame at the index.""" self._check_attr("windows") facet = self.show_frame(index, *args, **kwargs) draw_windows(self.windows, facet.axes) return facet
def run(args: argparse.Namespace) -> None: if args.lang not in VALID_LANGS: raise ValueError(f'invalid language! expected {VALID_LANGS}, got="{args.lang}"') all_commands = get_all_commands(args.lang, args.test, args.day, args.actual) subprocess.run(['clear']) for command, input_path in all_comm...
The code defines a command-line interface (CLI) with three subcommands: `run`, `setup`, and `submit`. It parses arguments for each subcommand, such as specifying language, year, day, test/actual mode, input files, and submission parameters. Based on the user's chosen subcommand, it routes execution to the corresponding...
def main() -> None: ap = argparse.ArgumentParser() subparser = ap.add_subparsers(dest='subcommand') run_ap = subparser.add_parser('run') run_ap.add_argument('--lang', action='store', default='all') run_ap.add_argument('--year', action='store', type=int, default=TODAY.year) run_ap.add_argument(...
def create_convolutional_graph(self, x_input): expanded_x = tf.expand_dims(x_input, -1) pooled_outputs = self.create_conv_layer(expanded_x) dropout_pooled_outputs = self.add_dropout(pooled_outputs) self.training_prob = self.create_predictions(dropout_pooled_outputs, ...
The main task of the code is to construct a computational graph for a convolutional neural network. It initializes convolutional layers using input data, defines training and test loss functions based on predicted probabilities and actual labels, and creates a training operation to optimize the model. This setup prepar...
def setup_graph(self): self.create_convolutional_graph(self.x_input) self.training_loss = self.create_loss_function(self.training_prob, self.y_input) self.test_loss = self.create_loss_function(self.test_prob, ...
def create_word_dict(self): """Loads the data from the emoticon labeled tweets, and then processes these using word to vec Parameters: ----------- embedding_dim: int size of vectors to embed words in sentence_length: int maximum length of sentence...
This code initializes a neural network model for text classification, setting up placeholders for input data, class labels, and sequence lengths. It configures parameters for convolutional layers (filter sizes, num_filters) and training (learning rate, epochs). Depending on the 'tokenization' argument (word/char), it p...
def __init__(self, sequence_length, num_classes, embedding_size, filter_sizes, num_filters, learning_rate=.01, batch_size=100, num_epochs=1000, dropout_keep_prob=.6, tokenization='word'): self.sequence_length = sequence_length self.num_classes = num_cla...
def update_user(app, id): with app.app_context(): old_user = rd.read_user(id) new_user = ft.fetch_user(id) setattr(old_user, 'avatar_url', new_user['avatar_url']) setattr(old_user, 'country_code', new_user['country_code']) setattr(old_user, 'cover_url', new_user['cover']['url...
The code updates user statistics by iterating through rulesets, comparing current and historical data to track streaks, play time, scores, and other metrics. It updates daily records, adjusts streaks based on activity, and synchronizes user and ruleset attributes in the database, ensuring accurate tracking of gameplay ...
def update_user_statistics(app, user): with app.app_context(): id = user.__dict__['id'] update_user(app, id) was_active = False for ruleset in sc.rulesets: updated_statistics = ft.fetch_user(id, ruleset) old_ruleset = rd.read_ruleset(id, ruleset) ...
def logs_path(relative): return os.path.join('logs', relative) def get_data_filenames(): file_names = [f for f in os.listdir(data_path('')) if os.path.isfile(data_path(f))] filtered = [f for f in file_names if re.search(FILE_FORMAT_REGEX, f) is not None] # get all file names which don't match the correc...
The main task of the code is to process recently formatted data files by validating preprocessing, generating visualizations, and sending email notifications with logs and figures. It configures logging to track issues, sorts files by date, resets logging for specific files, and logs successful processing. The workflow...
def main(): # this log tracks malformed files, overwritten for specific date's files logging.basicConfig(filename=logs_path('baselog.log'), level=logging.INFO, format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p::') # get all the file names which are correctly formatted ...
def convert_category_annotations(orginal_category_info): categories = [] num_categories = len(orginal_category_info) for i in range(num_categories): cat = {} cat['id'] = i + 1 cat['name'] = orginal_category_info[i][1] cat['original_id'] = orginal_category_info[i][0] ...
The code converts OpenImages dataset annotations from CSV files to COCO JSON format for a specified subset (train/val/test). It loads category, image metadata, and bounding box annotations, processes them into structured COCO format, and saves the result as a JSON file. The function also optionally returns the processe...
def convert_openimages_subset(annotation_dir, image_dir, subset, return_data=False): # Select correct source files for each subset category_sourcefile = 'class-descriptions-boxable.csv' if subset == 'train': image_sourcefile = 'train-images-boxable-with-rotation.csv' annotation_sourcefi...
def set_parameter(self, current_iteration_number): if self.flag: self.epsilon = 0 else: self.epsilon = (self.n - current_iteration_number) / self.n def random_with_possibility(epsilon): r = random.random() return r < epsilon def compute_action_from_q_values(self, state): ...
This code implements an epsilon-greedy action selection strategy in reinforcement learning. It randomly chooses an action with probability ε (exploration) or selects the action with the highest Q-value (exploitation) based on the current state, adjusting parameters according to the iteration number to balance explorati...
def get_action(self, state, current_iteration_number): self.set_parameter(current_iteration_number) if random_with_possibility(self.epsilon): action = random.choice(self.action) else: action = self.compute_action_from_q_values(state) return action
def discretize_state(state): discrete_state = (min(2, max(-2, int((state[0]) / 0.05))), min(2, max(-2, int((state[1]) / 0.1))), min(2, max(-2, int((state[2]) / 0.1))), min(2, max(-2, int((state[3]) / 0.1))), min(2, max(-2, int((state[4]) / 0.1))), min(2, max(-2, int((stat...
This code trains a Q-learning agent in a given environment by iterating through episodes, updating the Q-table with rewards, tracking cumulative rewards and their averages, and saving the Q-table after training. It resets the environment, discretizes states, selects actions, and terminates episodes when done, logging p...
def train(self, env): iterations, rewards, average_rewards = list(), list(), list() next_state, info = env.reset(seed=42) score = 0 for i in range(self.n): while True: state = next_state state = discretize_state(state) action = ...
def average(network,list_nodes,how,method): ''' Returns the average longitude or latitude of the nodes ---------- Parameters: network: object Graph object contains the network list_nodes: list list of names (str) of the nodes how: str lgn or lat lgn for the average longitude, lat for the average...
The code generates four optimized courier paths for vaccine delivery in Auckland, starting and ending at Auckland Airport. It uses a precomputed distance matrix from a network and rest homes data, splits destinations into regional groups (east/west, north/south), manually adjusts each group's order, and solves for path...
def main(): '''Produces 4 courier paths for vaccines delivery in Auckland from Auckland Airport Note: the network.graphml and rest_homes.txt files must be exactly the same as the ones given ''' #Get the network auckland = read_network('network.graphml') #List of destinations including Auckland Airport at the s...
def reset_clusters(self): return [[] for i in range(0,self.K)] def getNearestCentroid(self,sample): dist=[] for centroid in self.centroids: dist.append(self.eculedian_distance(sample,centroid)) return np.argmin(dist) def checkConvergence(self, prevCentroids, currentCentroids)...
This code performs K-means clustering by iteratively assigning data points to nearest centroids, updating centroids as cluster means, and checking for convergence. It repeats until maximum iterations or centroid stability, then returns cluster assignments for each data point.
def fit(self): for _ in range(0, self.max_iter): self.clusters = self.reset_clusters() for nodeIndex,sample in enumerate(self.data): centroidIndex = self.getNearestCentroid(sample) self.clusters[centroidIndex].append(sample) prevCentroids = se...
def reset_clusters(self): return [[] for i in range(0,self.K)] def getNearestCentroid(self,pixel): dist=[] if self.distance_metric=="L2": for centroid in self.centroids: dist.append(self.eculedian_distance(pixel,centroid)) else: for centroid in sel...
The code implements K-means clustering on an image, dynamically adjusting clusters by updating centroids using L2 (mean) or L1 (median) norms, handling empty clusters, and early stopping upon convergence. It returns labeled pixel clusters and final centroids.
def Kmeans(self): length=self.img.shape[0] width=self.img.shape[1] for iter in range(0,max_iter): self.clusters = self.reset_clusters() for i in range (0,length): for j in range(0,width): imgPixel=self.img[i,j] cent...
def getHeartList(): heartList = models.Heartrate.query.all() foundDeletable = False for i in range(0,(len(heartList))): timeDif = (datetime.utcnow() - heartList[i].time).total_seconds() print(timeDif) if timeDif > heartrateRemovalTime: print("This user needs deletion!") db.session.delete(heartList[i]) ...
This code handles heart rate data retrieval and updates. It processes GET requests to display heart rate information (either a list or specific entries) using accuracy levels (Low/Medium/High), and POST requests to add/update data. It validates data freshness, returns templates with heart rate details, or error message...
def heart_code(code): accuracyMap = { 1 : "Low", 2 : "Medium", 3 : "High" } if request.method == 'GET': if code == "": heartRateInfoList = getHeartList() for i in range(0,(len(heartRateInfoList))): heartRateInfoList[i].accuracy = accuracyMap[heartRateInfoList[i].accuracy] return render_template...
def readFile(afile): Lfile = open(afile,"r") dictionary = {} dictionary["angle"] = int(Lfile.readline()) dictionary["iteration"] = int(Lfile.readline()) dictionary["axiom"] = Lfile.readline() for line in Lfile: Llist = line.split(":") dictionary[Llist[0].strip()] = Llist[1].strip...
The main task of the code is to read data from a file into a dictionary, validate an "angle" value from the dictionary, and pass the dictionary along with a turtle graphics object to an accumulation function for further processing or visualization.
def prep(afile,turtle): dictionary = readFile(afile) validation(int(dictionary.get("angle"))) accum(dictionary,turtle)
def isValidHex(string): return re.search("^0x[0-9a-fA-F]{2}$", string) is not None def _getAddrForMessageN(data, messageNumber): messagesAddress = messagesStartAddr # Keeping looping until the nth message is found while messageNumber: byte = data[messagesAddress] if(byte == 0): ...
The function processes user commands to interact with a virtual machine's state, handling tasks like printing dictionaries, setting random seeds, viewing/modifying variables and list areas, and retrieving messages. It supports numeric and hexadecimal input, updates VM data, and uses global variables for state tracking.
def _process_hash_commands(data, pc, userInput): global randomseed buffer="" strippedInput = userInput.strip().lower() # Give yourself all the items #for x in range(80,159): # vm_listarea[x]=0xff match strippedInput.split(): # Prints the dictionary case ['#dict' | '#d...
def _getAddrForMessageN(data, nthMessage): messagesAddress = messagesStartAddr # Do I subtract 1... # Keeping looping until the nth message is found while nthMessage: byte = data[messagesAddress] if(byte == 0): print("ERROR didn't find nth string") break ...
This function processes a virtual machine instruction to print a message from data. It calculates the message index (nthMessage) using operands, retrieves the message address, prints it, and logs the operation. The program counter (pc) is updated and returned for the next instruction.
def vm_fn_messagec(data, opCode, pc): cmdAddress=pc # Get the first operand pc=pc+1 operand1 = data[pc] operand2 = None nthMessage = 0 # If the 7th bit is set in the opCode # then there is only one operand, otherwise # there are two if not (opCode & int("01000000",2)): ...
def update_history(self, result): if (len(self.success_history) < settings.update_zone_window): self.success_history.append(result) else: self.success_history.pop(0) self.success_history.append(result) def update_success_rate(self): self.success_ratio_within_w...
This method updates episode history, success rate, and logs metadata. It triggers algorithm-specific callbacks (DDPG, PPO, SAC, etc.) based on the current training algorithm. After resetting step variables (actions, rewards, positions), it logs the distance to the goal. The function also manages window restarts, zone u...
def on_episode_end(self): self.update_history(self.success) self.update_success_rate() if(os.name=="nt"): msgs.meta_data = {**self.game_config_handler.cur_game_config.get_all_items()} self.populate_episodal_log_dic() if(msgs.algo == "DDPG"): self.ddpg_cal...
def addToLog(self, key, value): if key not in self.allLogs: self.allLogs[key] = [] self.allLogs[key].append(value) def ddpg_add_noise_action(self, actions): noise_t = np.zeros([1, self.action_space.shape[0]]) a_t = np.zeros([1, self.action_space.shape[0]]) noise_t[0][...
The code executes a reinforcement learning step by applying an action to a drone simulation, updating the environment state, checking for success/collision/termination, computing rewards, and returning the next state, reward, done flag, and metadata. It supports multiple algorithms (e.g., DDPG, PPO) and includes profil...
def step(self, action): #changed from _step msgs.success = False msgs.meta_data = {} try: if (msgs.mode == 'train'): self.airgym.client.simPause(False) #print("ENter Step"+str(self.stepN)) #print(f"action taken: {ac...
def compute_pruned_count(model, perc=0.1, layer=None): if layer or layer ==0: # count nb of filters nb_filters = model.layers[layer].output_shape[3] else: nb_filters = np.sum([model.layers[i].output_shape[3] for i, layer in enumerate(model.layers) if 'con...
The main task of the code is to prune a Keras model by removing a specified percentage of weights or units using L1 pruning and multiple layers. It calculates the number of pruned elements, applies L1-based pruning, and adjusts the model structure to return a pruned Keras Model object with reduced parameters while main...
def prune_model(model, perc, opt, layer=None): """Prune a Keras model using different methods Arguments: model: Keras Model object perc: a float between 0 and 1 Returns: A pruned Keras Model object """ n_pruned = compute_pruned_count(model, perc, layer) #...
def _update_timestamps(self): """Updates all of the timestamps for each word across all responses.""" new_start_sec, new_end_sec = self.get_updated_seconds() counter = 0 for response in self.responses: for word in response.alternatives[0].words: word.start_tim...
This class processes speech recognition results by updating timestamps, clustering pauses with KMeans, and applying LDA to identify topics in transcripts, enabling analysis of speech structure and thematic content.
def __init__(self, responses, num_topics=8): """Class to more easily get information out of speech responses. Parameters ---------- responses : list of google.cloud.speech_v1.types.SpeechRecognitionResult Each response represents a single 'chunk' of the speech. num_...
def read_input(): report = [] for line in sys.stdin: line = line.rstrip() history = [int(x) for x in line.split(" ")] report.append(history) return report def part1(report): result = 0 logging.debug("Part 1: Start") for history in report: next_num = extrapolate_n...
The code's main task is to process an input report by first reading it, then executing two functions (`part1` and `part2`) on the report. It configures logging to capture errors and ensures the report is analyzed or transformed by the specified functions.
def main(): logging.basicConfig(stream=sys.stderr, level=logging.ERROR) report = read_input() part1(report) part2(report)
def read_input(): data = [] for line in sys.stdin: line = line.rstrip() items = line.split(" ") hand = items[0] bid = int(items[1]) data.append({"hand": hand, "bid": bid}) return data def part1(data): result = calc_total_winnings(data, False) print(f"Part 1:...
The main task of the code is to process input data through two functions, part1 and part2. It first configures logging to capture errors, reads input data using read_input(), then executes part1 and part2 on the data. The code likely solves two related problems or performs sequential analysis on the dataset.
def main(): logging.basicConfig(stream=sys.stderr, level=logging.ERROR) data = read_input() part1(data) part2(data)
def read_input(): maps = {} map_name = "" for line in sys.stdin: line = line.rstrip() if line.startswith("seeds: "): seeds = [int(x) for x in line[7:].split(" ")] elif line.endswith(" map:"): map_name = line.split(" ")[0] maps[map_name] = [] ...
The code's main task is to process an almanac data structure by first reading input, then executing two parts of a solution: part1 and part2. Logging is configured to capture errors. The function initializes logging, loads input data, and sequentially applies two processing steps to the almanac.
def main(): logging.basicConfig(stream=sys.stderr, level=logging.ERROR) almanac = read_input() part1(almanac) part2(almanac)
def build_md_tree(mres, mdid, connection_id): """ Build the tree reading from MD """ global products_count products_count = 0 headers = { 'accept': 'application/json', 'authorization': 'Basic %s' % connection_id, 'Connection': 'close' } rs = requests.Session() r...
The function extracts product tree data from MagicDraw using given IDs, generates diagrams/csv files if enabled, and renders a LaTeX section template with metadata, tree structures, and product data, outputting the result to a specified file in the requested format.
def do_md_section(sysid, levelid, connection_str, output_format, output_file, compact, doc_handler, dotree): """ Given the MD ids, dump the content in the output file and produce the product tree diagrams :param sysid: MagicDraw subsystem id :param levelid: MagicDraw level id (package id containing the ...
def tree_slice(ptree, outdepth): """ Returns a subproduct with depth equal to outdepth :param ptree: input product tree :param outdepth: depth of the subproduct tree :return: sub product tree """ if ptree.depth() == outdepth: return ptree # copy the tree but stopping at given dep...
The function generates a visual representation of a product tree in a mixed landscape-portrait format, calculating dimensions based on node hierarchy and compactness. It writes the structured tree diagram to a file, adjusting layout parameters like block height, width, and spacing for readability, then outputs the resu...
def make_tree_landmix1(ptree, filename, scope, compact): """ First level landscape, and then portrait :param ptree: tree to render in a graphic form :param filename: filename to save the text source for the tree graph :param scope: :return: none """ print("Writing Mixed (1 level) ...
def tree_slice(ptree, outdepth): """ Returns a subproduct with depth equal to outdepth :param ptree: input product tree :param outdepth: depth of the subproduct tree :return: sub product tree """ if ptree.depth() == outdepth: return ptree # copy the tree but stopping at given dep...
This function generates a multi-level product tree diagram (landscape then portrait) by calculating dimensions based on tree structure and compactness. It writes the result to a file, including headers, the tree layout, and footers, adjusting spacing and sizing according to node depth and compact mode parameters.
def make_full_tree(ptree, filename, scope, compact): """ First level landscape, and then portrait :param ptree: :param filename: :param scope: :return: none """ print("Writing Mixed (2 levels) Landscape Full Product Tree in ", filename) # calculating diagram size first_level = t...
def do_md_section(sysid, levelid, connection_str, output_format, output_file, compact, doc_handler, dotree): """ Given the MD ids, dump the content in the output file and produce the product tree diagrams :param sysid: MagicDraw subsystem id :param levelid: MagicDraw level id (package id containing the ...
The function generates documentation in specified formats (Markdown/CSV) by processing subsystem data, generating product trees, handling partial outputs, and creating GitHub-compatible content based on input parameters like output format and CSV exclusivity.
def generate_document(connection_str, output_format, token_path, compact, csvonly, partial): """Given system and level, generates the document content""" md_trees = [] subsystem_info = get_yaml() subsystem_id = subsystem_info['subsystem']['id'] doc_handler = subsystem_info['subsystem']['doc'] ...
def get_player_pool(self,file_name): player_pool = pd.read_csv(file_name) player_pool['name'] = player_pool['first_name']+' '+player_pool['last_name'] player_pool = player_pool[player_pool['injury_status']!='O'] player_pool = player_pool.set_index('name') position_pool = {} ...
The function generates daily player features for NHL positions (F, D, G) by calculating statistics using a provided function, combining results, and exporting them to a CSV file. It retrieves player pools and groups, computes position-specific stats, derives features, and concatenates/saves data for analysis.
def write_daily_features_file(self,feat_path,date,stat_func,include_actual=False,**func_args): #Calculates player pools and groups player_pool = self.get_player_pool(f"{self.player_pool_path}/DFF_NHL_cheatsheet_{date.strftime('%Y-%m-%d')}.csv") player_groups = self.get_player_group(date) ...
def get_player_pool(self,file_name): player_pool = pd.read_csv(file_name) player_pool['name'] = player_pool['first_name']+' '+player_pool['last_name'] player_pool = player_pool[player_pool['injury_status']!='O'] player_pool = player_pool.set_index('name') position_pool = {} ...
The main task of the code is to generate and combine player statistics features across multiple dates using a specified statistical function, then aggregate and save the results as a CSV file. It iterates through dates, retrieves player data, computes position-specific features, concatenates them, and exports the combi...
def write_combined_features(self,file_name,start_date,end_date,stat_func,**func_args): df_list = [] while start_date <= end_date: try: player_pool = self.get_player_pool(f"{self.player_pool_path}/DFF_NHL_cheatsheet_{start_date.strftime('%Y-%m-%d')}.csv") playe...
def jump(self): self.position.setY(self.position.y()+1) self.collision, index = self.collisionCheck(self, self.game.platform_list) self.position.setY(self.position.y()-1) #first checks if player is on a platform #only if it is, then the player can jump (so one can't keep jumping ...
This code updates a game player's physics and movement based on pressed keys, applying gravity, acceleration, and friction. It handles collision detection with platforms, triggers level completion when hitting a goal platform, and manages screen scrolling. If the player falls off the screen, the game resets. It also up...
def update(self, keys_pressed): #setting up player movement by the pressed keys #movement itself happens later self.acceleration = QVector2D(0, P_GRAVITY) if Qt.Key_Left in keys_pressed: self.acceleration.setX(self.acceleration.x() - P_ACC) if Qt.Key_Right in keys_pr...
def get_similar_question_sql(self, question: str, **kwargs) -> list: """ This method is used to get similar questions and their corresponding SQL statements. Args: question (str): The question to get similar questions and their corresponding SQL statements for. Returns: ...
The main task of the code is to generate a SQL query using an LLM by gathering related SQL examples, database schemas, documentation, and constructing a prompt. It submits this prompt to the LLM, logs the response, extracts the SQL, and returns it to answer the given question.
def generate_sql(self, question: str, **kwargs) -> str: """ Example: ```python vn.generate_sql("What are the top 10 customers by sales?") ``` Uses the LLM to generate a SQL query that answers a question. It runs the following methods: - [`get_similar_question_sq...
def generate_sql(self, question: str, **kwargs) -> str: """ Example: ```python vn.generate_sql("What are the top 10 customers by sales?") ``` Uses the LLM to generate a SQL query that answers a question. It runs the following methods: - [`get_similar_question_sq...
The main task of the code is to generate an SQL query from a user's question using Vanna.AI, optionally execute it to retrieve data, and return the SQL query along with the results as a pandas DataFrame. It also supports automatic training of the AI model on the question-query pair if enabled.
def ask( self, question: Union[str, None] = None, auto_train: bool = True, ) -> Union[ Tuple[ Union[str, None], Union[pd.DataFrame, None], ], None, ]: """ **Example:** ```python vn.ask("What are the top 10 cu...
def convert_input_string_to_coordinates(self, first, second): fir_y = filter_y[int(first[1])] fir_x = ltn[first[0]] sec_y = filter_y[int(second[1])] sec_x = ltn[second[0]] return [fir_y, fir_x, sec_y, sec_x] def check_move(self, oldcol, oldrow, newcol, newrow): if self.c...
This function processes user input for a chess move, validating the format of start and end positions, converting them to coordinates, and checking move validity. It handles standard moves and castling, returning results or False for invalid inputs.
def get_move_input(self, start, end=""): print("\nNewMove: {} -> {}\n".format(start, end)) if(type(start) == type(end) == str and end != ""): if start[0] not in COLS or end[0] not in COLS or start[1] not in ROWS or end[1] not in ROWS: print("Wrong input handed, P...
def reset_history(self): self.log = [] def serialize_demonstrations(self,demon_triples): demon_text = "" for tp in demon_triples: demon_text += self.generate_demonstration_text(tp) + '\n' demon_text.strip() if demon_text == "": demon_text = "None." return demo...
The code's main task is to generate a response using a language model (LLM) by processing input triples and a relation. It serializes triples into demonstration text, combines it with relation-specific text, and queries the LLM. The result is logged and returned alongside the LLM's history, enabling tasks like relation...
def forward(self, r, triples): #Here tpe_id not a int id, but like '/m/08966' self.LLM.reset_history() self.reset_history() demonstration_text = self.serialize_demonstrations(triples) r_text = self.relation_text(r) final_response = self.LLM.get_response((demonstration_text, r_tex...
def reset_history(self): self.log = [] self.candidate_answers = [] self.selected_demonstrations = [] self.scores = [] def generate_demonstration_text(self, triple): h,r,t = triple demonstration_text = "" if self.args.query == 'tail': if t != "": ...
This code processes a question and entity (tpe) by generating candidate answers, using a Large Language Model (LLM) to score them via demonstration-based reasoning. It initializes the LLM, iteratively feeds analogy/supplement demonstrations, and evaluates candidate scores by prompting the LLM. The task involves ranking...
def forward(self, question, tpe): #Here tpe_id not a int id, but like '/m/08966' self.LLM.reset_history() self.reset_history() final_order = [] tpe_str = self.ent2text[tpe] candidate_ids = self.all_candidate_answers['\t'.join([str(self.ent2id[tpe]),str(self.rel2id[question])])] ...
def get_label_weight_ratio(data): content = open('{}'.format(data)).readlines() labels = [] for item in content: d = ujson.loads(item) labels.append(d['label']) labels = np.array(labels) labe = np.array([np.where(r==1)[0][0] for r in labels]) unique, counts = np.unique(labe, retu...
The code trains a neural network model for classification, using cross-validation or train-validation splits. It loads data, configures a model with class-weighted loss, and trains it with Adam optimization. It supports loading pre-trained weights, early stopping, and inference mode. Hyperparameters and training times ...
def run(): print(torch.__version__) num_folds = args.cv num_samples = sum(1 for line in open(args.data)) loss_weights = get_label_weight_ratio(args.data) #num_samples = sum(1 for line in open(os.path.join(args.data, 'train'))) #loss_weights = get_label_weight_ratio(os.path.join(args.data, 'val')...
def readColumnHeaders(filePath): colHeaders = [] colData = {} fp = open(filePath, 'r') line = fp.readline() fp.close() commentIndex = line.find("#") if (commentIndex == 0): # header colHeaders = line.lstrip("# ").rstrip("\n").split(',') if (options.debug): ...
The main task of the code is to generate a ZDR bias plot using noise monitoring and vertical pointing data from specified files. It parses command-line options for file paths, plot dimensions, time ranges, and data processing parameters. The script reads input data, processes it with calibration settings, and renders a...
def main(): # globals global options # parse the command line usage = "usage: %prog [options]" parser = OptionParser(usage) parser.add_option('--debug', dest='debug', default=False, action="store_true", help='Set debugging on') ...
def load_tiles(self, tile_dir): # Loop through the files and folders in the folder for root, subfolder, filename in os.walk(tile_dir): # Check if there is a folder inside the folder # for dir in subfolder: # # If there is a folder inside the folder, take the image...
The main task of the code is to generate an image by loading tile data from a directory, printing relevant information, processing the tiles to fit them together, and returning the final composed image. The commented-out lines suggest additional potential steps like sample loading, grid creation, and saving, but the ac...
def generate(self): self.load_tiles(self.tile_directory) self.print_info() self.fit_tiles() # self.load_samples() # self.create_tiles() # self.resize_image() # self.create_grid() # self.fill_grid() # self.save_image() return self.image
def load_img(img_path): try: # Load the image using cv2 image = cv2.imread(img_path) print_msg(f"Loaded image {img_path}", SUC, True) return image except Exception as e: print_msg(f"Error loading image {img_path}\n{e}", ERR) return None def load_imgs(folder_path...
The code generates a mosaic image by replacing tiles of the input image with resized tiles from a specified folder. It crops input and tile images to squares, splits the input into tiles, resizes output tiles to match, and combines them into a mosaic, saving the result as 'test.jpg'.
def mosaic(input_img_filename, tile_imgs_foldername): input_img = load_img(input_img_filename) tile_imgs = load_imgs(tile_imgs_foldername) # Crop images to squares input_img = square_crop(input_img) print(input_img.shape) output_tiles = crop_to_square(tile_imgs) # Split the image into til...
def load_img(img_path): try: # Load the image using cv2 image = cv2.imread(img_path) print_msg(f"Loaded image {img_path}", SUC, True) return image except Exception as e: print_msg(f"Error loading image {img_path}\n{e}", ERR) return None def load_imgs(folder_path...
The main task of the code is to generate a mosaic image by replacing each tile of the input image with a resized tile from a provided folder. It involves loading and cropping images, splitting the input image into tiles, resizing the tile images to match the input tile size, and reassembling them into a final mosaic im...
def mosaic(input_img_filename, tile_imgs_foldername): input_img = load_img(input_img_filename) tile_imgs = load_imgs(tile_imgs_foldername) # Crop images to squares input_img = square_crop(input_img) print(input_img.shape) output_tiles = crop_to_square(tile_imgs) # Split the image int...
def create_train_and_test(mat): random.shuffle(mat) n = int(len(mat) / 2) test_mat = mat[:n] train_mat = mat[n:] return train_mat, test_mat def create_rules(mat): rules_list = [] for i in range(len(mat)): for j in range(i + 1, len(mat)): # create all possible pairs of po...
The code computes empirical training and test errors using AdaBoost with rules derived from a matrix. It splits the input matrix into training and test sets, generates rules from the training data, trains an AdaBoost model with 8 iterations, calculates errors on both datasets using the trained rules and weights, and re...
def compute_empirical_errors(mat): train_mat, test_mat = create_train_and_test(mat) # randomize every iter rules_train = create_rules(train_mat) #### train #### n = train_mat.shape[0] # number of points p_weights = np.zeros(n) # point weights p_weights.fill(1 / n) # initial weights ru...
def _check_fleet_edges(self): for alien in self.aliens.sprites(): if alien.check_edges(): self._change_fleet_direction() break def _ship_hit(self): from time import sleep if self.stats.ships_left > 0: self.stats.ships_left -= 1 ...
The code updates alien movement by checking fleet edges and updating their positions. It detects collisions between the player's ship and aliens, triggering a ship hit response. Finally, it checks if any aliens have reached the bottom of the screen, likely for game-over conditions.
def update_aliens(self): self._check_fleet_edges() self.aliens.update() if pygame.sprite.spritecollideany(self.ship, self.aliens): self._ship_hit() self._check_aliens_bottom()
def guess_letter(self, user_input): """ Checks if user letter input is correct or not, increments or decrements points accordingly """ if ( user_input in self.guessed_letters or user_input in self.guessed_correct_letters ): self.game_hi...
The main task of the code is to manage a Hangman game loop, handling user guesses for letters/words, applying hints via API, tracking scores, and logging game results to a worksheet when the player wins. It displays game state, enforces rules, and updates progress while maintaining timing and input validation.
def play(self): """ Starts the game and depending on the user input "word", "letter", it calls the corresponding functions guess_word() or guess_letter(). Also if user selects the hint option it calls the api to get the definition of the hangman word. """ # Starts...
def maybeEvaluate (self, prod): #recursively evaluate if possible for i in range(len(prod)): if isinstance(prod[i], Alternation) or isinstance(prod[i], Repeat) or isinstance(prod[i], Optional): prod[i] = self.maybeEvaluate(prod[i].evaluate()) return prod def matchSublists (s...
The function `genRandSentence` generates a random sentence by recursively replacing non-terminal symbols in a production rule (`prod`) with randomly chosen valid sublists until only terminal symbols remain. It checks for replaceable sublists, selects one at random, updates `prod`, and repeats the process. Once no furth...
def genRandSentence (self, prod): if type(self.maybeEvaluate(prod)[0]) == list: prod = prod[0].copy() #print("PROD",prod) validProds = self.matchSublists(prod) #first find the possible matches (replacements) if len(validProds) > 0: #if there are some, we can keep producing ...
def events(self): for event in pygame.event.get(): if event.type == pygame.QUIT: self.running = False pygame.quit() exit() if event.type == pygame.MOUSEBUTTONDOWN: clicked_on_board = self.clicked_on_board() ...
This code runs a game loop that continuously processes events, updates the game state, and renders graphics while the 'running' flag is True. The loop repeats until 'running' is set to False, ensuring the application remains active and responsive.
def run(self): while self.running: # self.clock.tick(self.fps) self.events() self.update() self.draw()
def format(time: int) -> str: seconds, formatted_seconds = time, "" for period, period_seconds in ( ('y', 31557600), ('d', 86400), ('h', 3600), ('m', 60), ('s', 1), ): if (seconds >= period_seconds): formatted_seconds += str(int(seconds / period_seconds)) formatted_s...
This code draws a terminal-based interface to display and update session time using curses. It handles interrupts, adjusts text to fit the terminal, and loops until completion. After finishing, it displays "done!" and waits 15 seconds, likely for an alarm. The code includes TODOs for improving time updates and dynamic ...
def _draw(self, stdscr) -> None: signal(SIGINT, self.sigint_handler) use_default_colors() try: curs_set(False) except error: # fails on some terminals pass while self.done is False: stdscr.clear() # BUG: stdscr.getmaxyx() never updates; maybe sleep(1) is the issue ...
def load_audio(full_path): data, sampling_rate = sf.read(full_path, dtype='int16') return data, sampling_rate def _sample_interval(self, seqs, seq_len=None): N = max([v.shape[-1] for v in seqs]) if seq_len is None: seq_len = self.segment_size if self.segment_size > 0 else N ...
This code loads and preprocesses audio files for a machine learning model. It handles resampling, padding, normalization, and caching. It trims audio to match code lengths, pads if necessary, converts to tensors, computes mel spectrograms, and extracts features like fundamental frequency (f0) and speaker IDs. The metho...
def __getitem__(self, index): filename = self.audio_files[index] if self._cache_ref_count == 0: audio, sampling_rate = load_audio(filename) if sampling_rate != self.sampling_rate: # raise ValueError("{} SR doesn't match target {} SR".format( # ...
def get_timestamp(date_time_instance): return int(datetime.datetime.timestamp(date_time_instance)) def get_last_commit(conn): date_time = None with conn.cursor() as cur: cur.execute('use ' + event_schema + ';') result = cur.fetchall() conn.commit() sql = 'select commit_date f...
The code updates a database with processed social media data by analyzing keywords using AWS Comprehend. It connects to two RDS databases, retrieves the latest timestamp, processes each keyword (e.g., 'tesla', 'apple'), and records the current time as the latest commit. The task involves fetching, analyzing, and storin...
def lambda_handler(event, context): commit_conn = pymysql.connect(host=rds_host, user=rds_user, passwd=rds_password, db=event_schema, connect_timeout=5, cursorclass=pymysql.cursors...
def getCountries(self): country_names = [] locations = self.getCordinates() print("Loading...") for lat, lon in zip(locations['latitude'], locations['longitude']): geolocator = Nominatim(user_agent="Final Project") try: location = geolocator.rever...
The code generates a CSV file containing earthquake data for a specific year. It collects country names, coordinates (latitude/longitude), depth, and magnitude from separate methods, compiles them into a pandas DataFrame, and saves the data as 'earthquake_data_YYYY.csv', where YYYY is the year. The task is to organize ...
def generate_CSV(self): countries = self.getCountries() coordinates = self.getCordinates() depth = self.getDepth() magnitude = self.getMagnitudes() csv_prep = {'Country': countries.values.tolist(), 'Latitude': coordinates['latitude'].values.tolist(), ...
def get_all_spectra_len(ztfname): url = BASEURL+'api/sources/'+ztfname+'/spectra' status, response = api('GET',url) return len(response['data']['spectra']) def get_all_spectra_id(ztfname): ''' Info : Query all spectra corresponding to a source, takes input ZTF name Returns : list of spectrum js...
This function retrieves and returns a spectrum ID from Fritz based on user selection or automatic choice if enabled. It checks for available spectra, lists their details (name, date, ID), and prompts the user to choose one. If no spectra are found, it returns "No Spectra Found". The 'auto' parameter allows automatic se...
def get_required_spectrum_id(ztfname, auto=False): ''' Info : Requests spectrum from Fritz based on user selection Input : ZTFname, auto (if True and only one spectrum on Fritz, returns it without prompt) Returns : spectrum ID on Fritz ''' flag = 0 spec = (get_all_spectra_len(ztfname)...
def calculate_shares(self, paid, outcome): obj_func = lambda s: np.abs(self.price(s, outcome) - paid) return fmin_cobyla(obj_func, paid/self.p[outcome], []) def register_x(self, x): self._x.append(x) def _new_x(self, shares, outcome): new_x = self.x new_x[outcome] += shares ...
The main task of the code is to calculate and record the purchase of shares based on the given 'paid' amount and 'outcome', update the market value, log the transaction details in '_book' and '_history', and return the number of shares bought.
def buy_shares(self, name, paid, outcome): shares = self.calculate_shares(paid, outcome) self.register_x(self._new_x(shares, outcome)) self._book.append({'name':name, 'shares':shares, 'outcome':outcome, 'paid':pa...
def get_file_btree(self, file, zoomlvl): bw = BigWig(file) bw.getZoomHeader() tree = bw.getTree(-2) return tree, bw def get_leaf_nodes(self, tree, bw, zoomlvl): findexOffset = bw.header.get("fullIndexOffset") offset = 48 root = self.read_node(tree, offset, endian ...
This code adds genomic data from a file to a quadtree index structure. It maps files to counters, processes chromosome data, calculates spatial dimensions, and inserts genomic intervals into per-chromosome quadtree indexes for efficient spatial querying.
def add_to_index(self, file, zoomlvl = -2): tree, bw = self.get_file_btree(file, zoomlvl) df = self.get_leaf_nodes(tree, bw, zoomlvl) chrmTree = self.get_file_chr(bw) self.file_mapping[file] = self.file_counter self.file_counter += 1 self.file_objects[file] = bw ...
def get_candidate_entities(self, document): ''' Returns a list of entities according to spacy's ner tagger. These entities are candidates for the questions Params: * document : string Returns: * list<str> ''' entities = self.ner_ta...
The main task of the code is to generate a dictionary of questions and their corresponding answers from a given document. It processes the document by extracting candidate keywords, calculating their TF-IDF scores, ranking them, and then forming questions based on these ranked keywords. The output is a structured dicti...
def get_questions_dict(self, document): ''' Returns a dict of questions in the format: question_number: { question: str answer: str } Params: * document : string Returns: * dict ''' # find candidate keywords...
def read_table_function() -> TableFunction: print("\nChoose the method you want to read the table:") print("0\tread from console") print("1\tread from file") print("2\tread from existing function") line = input("(enter the number) ").strip() if line == "0": return read_table_function_fro...
The code performs interpolation on a table function, then extrapolates to a specified point, printing results. It reads the table function, interpolates values, retrieves an extrapolation point, and outputs the interpolated result alongside the extrapolation point. Error handling ensures exceptions are captured and dis...
def run(): try: table_function = read_table_function() interpolation_result = interpolate(table_function) extrapolation_point = read_extrapolation_point() print_interpolation_result(interpolation_result, extrapolation_point) except Exception as e: print(f'Some error occur...
def my_Metropolis_Gaussian(p, dp, z0, sigma, d, n_samples=1000, burn_in=0, m=1): """ Metropolis Algorithm using a Gaussian proposal distribution. p: distribution that we want to sample from (can be unnormalized) dp: the derivative of p z0: Initial sample sigma: standard deviation of the proposal...
The function performs forward propagation by updating data samples $ X $ and parameters $ \Theta = (C, W, b) $ using gradient-based dynamics with stochastic terms. It applies Metropolis-Hastings sampling to $ X $, updates parameter velocities (Cv, Wv, bv) with exponential decay, additive noise, and drift terms derived ...
def forward_propagation( parameters, X, Z, dt, lam_one, eta, lam, gamma, sigma , dc_dF_dnu, dw_dF_dnu, db_dF_dnu): """ Implement forward propagation (see formulas for dX, dTheta) Arguments: parameters -- current value of Theta = ( C, W, b ) X -- samples of the current distribution mu, array of ...
def initialize_parameters( n_y, n_n, num_layers): """ Arguments: n_z -- the number of features in the input data n_y -- the number of features of the output data n_n -- number of neurons in each layer L -- the number of layers Returns: parameters -- python dictionary containing para...
The function trains a deep neural network with multiple layers using gradient descent. It initializes parameters, performs forward and backward propagation, updates weights via specified rules (dt, lam, eps), tracks training/validation errors, and returns optimized parameters (C, W, b). It also plots error trends and n...
def deep_nn_model(z, Y, zV, YV, num_layers, n_n, dt = 0.01, ds = 0.01, lam = 0.1, eps = 0.1, num_epochs = 1000, print_cost= False ): """ Implements a L-layer neural network. Arguments: z -- data, numpy array of shape (number of features, number of examples) Y -- true "label" ...
def initialize_parameters( n_y, n_n ): """ Arguments: n_y -- the number of features in the data n_n -- the number of neurons (number of samples of nu) Returns: parameters -- python dictionary containing parameters "C", "W", "b" C -- weight scalars of shape (n_n, 1) ...
The code implements a 1-layer neural network to learn a distribution μ by minimizing a cost function involving Wasserstein distance and potential terms. It trains using gradient updates with hyperparameters like learning rate and regularization, iteratively refining parameters to approximate the target distribution Z. ...
def nn_model(Z, n_n, n_x, minibatch_size = 32, dt = 0.05, lam_one = 0.01, eta = 0.2, lam = 0.1, gamma = 0.5, sigma = 0.4, num_epochs = 1000, print_cost=True ): """ Implements a 1-layer neural network. Arguments: Z -- data, samples of the distribution mu_star, numpy array of shape...
def PerformDischarge(self, cycle, formSettings): if (formSettings['cellType'] == "NiCd"): vMin = settings.niCdVMin * formSettings['numberOfCells'] elif (formSettings['cellType'] == "NiMH"): vMin = settings.niMHVMin * formSettings['numberOfCells'] elif (formSettings['cell...
This code automates a discharge-charge cycle process, iterating up to a specified maximum number of cycles. It performs discharge and charge operations, checks for errors, saves graphs if requested, and terminates early if capacity increases fall below a threshold or if operations return None. The loop includes rest pe...
def AutoCycle(self, formSettings): dischargeT = lastDischargeT = 0 for i in range(1, formSettings['maximumCycles']+1): dischargeT = self.PerformDischarge(i, formSettings) print("DischargeT %s"%dischargeT) if dischargeT is None: break ...
def _get_tag_(self, entry:str) -> str: t = re.match(r'\.\d{3}\.', entry) if t: # print(f"==>{t.group()}") t = t.group()[1:-1] return f"{t}" else: return '' def _get_control_field_data_(self, entry:str, raw:bool=True) -> str: fields = entry....
This code converts a list of data entries into an XML-like structured format. It skips invalid 'FORM=' entries, processes control fields (tags 000-008) with specific formatting, and handles other tags by extracting subfields. The output includes record tags and properly nested elements based on entry type and MARC stan...
def _convert_(self, entries:list) ->list: record = [] if entries: record.append(f"<record {self.ns}>") for entry in entries: # Sirsi Dynix flat files contain a 'FORM=blah-blah' which is not valid MARC. if re.match(r'^FORM*', entry): continue ...
def fetch(self, method, url, base_url=True): url = self.base_url + url if base_url else url print("fetch(): url: {0}".format(url)) resp = requests.request(method, url, params={"token": self.user_token}) if resp.status_code == 204: return resp,...
The main task of the code is to collect all releases associated with a specific label by paginating through an API. It fetches releases in batches (75 per page), processes each release using `collect_release`, appends valid results to a list, and saves them periodically to a JSON file. The loop continues until there ar...
def collect_releases(self, label_id, label): releases = [] page = 0 per_page = 75 url = self.base_url + "/labels/{0}/releases?page={1}&per_page={2}" url = url.format(label_id, page, per_page) while True: resp, body = self.fetch("GET", url, base_url=False) ...
def _eval_cnn(self, loader): self._network.eval() y_pred, y_true = [], [] for _, (_, inputs, targets) in enumerate(loader): inputs = inputs.to(self._device) with torch.no_grad(): outputs = self._network(inputs)["logits"] predicts = torch.topk( ...
The code evaluates model performance on a test set using CNN and Mahalanobis (Maha) methods. It computes CNN accuracy via `_evaluate`, then conditionally calculates Maha accuracy if `full_cov` or `diagonal` flags are set. Returns CNN, NME (unimplemented as None), and Maha accuracies.
def eval_task(self): y_pred, y_true = self._eval_cnn(self.test_loader) cnn_accy = self._evaluate(y_pred, y_true) if self.args["full_cov"] or self.args["diagonal"]: y_pred, y_true = self._eval_maha(self.test_loader, self._init_protos, self._protos) maha_accy = self._evalu...
def shuff(data,split_percentage): """The function shuffles the given data set and returns the data as DataFrame""" data=data.values # np.random.shuffle(data) train,test=np.split(data,[int(split_percentage*len(data))]) x_train=train[:,0:-1] y_train=train[:,-1] x_test=test[:,0:-1] y_test=te...
The function splits input data into training and test sets, trains a model using the training data, predicts test outcomes, calculates accuracy, and returns the accuracy percentage as a formatted string.
def NB_complete_implementation(data,split_percentage): data_set=shuff(data,split_percentage) x_train=data_set[0];y_train=data_set[1] x_test=data_set[2];y_test=data_set[3] test_predictions=predictions(x_train,y_train,x_test) final_answer=accuracy(test_predictions,y_test) return f"The model is {f...
def validate_cookie_policy(self) -> None: r'''Helper function to validate cookie policy Function checks if the cookie are already accepted. If not, click on the Cookie Policy Accept button ''' self.driver.get(ppmi_main_webpage) if (cookie := self.driver.get_cookie('idaC...
The main task of the code is to handle user login to the PPMI platform. It checks if the user is already logged in by verifying the presence of a specific element. If not logged in, it inputs the provided email and password into the login form, clicks the login button, and checks for error messages to determine login s...
def login(self, email: str, password: str) -> None: r'''Help function to log to PPMI Function checks if user is already logged in. If not, enter email and password in the corresponding fields Parameters ---------- email : str User's email pas...
def init_database(): global database # Ignore this. This line is needed to overwrite the value of a global variable from a function. database = Database() def show_main_menu(): print('''*********************** * Library Manager * *********************** 1. Add book 2. Remove book 3. Search book by name 4. Searc...
The main task of the code is to initialize a database and run an infinite loop that repeatedly displays the main menu and prompts the user for commands, enabling continuous interaction with a database-driven application.
def main(): init_database() while True: show_main_menu() prompt_user_cmd()
def subsample(dataset,ratio): sample = list() n_sample = round(len(dataset)* ratio) while len(sample) < n_sample: index = randrange(len(dataset)) sample.append(dataset[index]) return list(sample) def build_tree(train, max_depth , min_size, n_features): # Creating root node root ...
The main task of the code is to implement a random forest algorithm. It builds multiple decision trees using subsampled training data, trains each tree with specified parameters (max depth, min size, feature count), and aggregates predictions via bagging. The function returns a list of predictions generated by combinin...
def random_forest(train, test, max_depth, min_size, sample_size, n_trees, n_features): trees = list() for i in range(n_trees): sample = subsample(train, sample_size) tree = build_tree(sample, max_depth,min_size, n_features) trees.append(tree) predictions = [bagging_predict(trees, row...
def get_color(self,square) -> int: return layout_if.layout[square[0]][square[1]] def logg(self,stri): if self.logging: print(stri) def tryplace(self,am,square): can = True if am==2: can = can and (layout_if.layout[square[0]+0][square[1]+0] == 0) can = ...
This function attempts to enclose the enemy's base area using two 3x3 blocks by checking all valid positions for block placement. It verifies if the blocks can block access to the target square, records valid configurations, and returns whether any such enclosing solution exists.
def twoblock(self, cornersquare) -> bool: # try to lock this self.enemybasearea square in with 2 3x3 blocks # return self.asol ([0] and [1] leftunderpoints of 3x3 blocks) # return self.asolprison (the enclosed squares) cornersquares = set([cornersquare]) opensquare = self.enemyst...
def update_local_sheet(): global entire_sheet global date_amount global schedule_message_info global modlist_message_info entire_sheet = sheet1.get_all_values() date_amount = int (get_cell_entry(2, 7)) schedule_message_info = get_cell_entry(3, 7) modlist_message_info = get_cell_entry(4, ...
The main task of the code is to update a schedule by archiving past events, populating upcoming events with existing or new entries, and returning the structured schedule data. It processes historical data, identifies future dates, updates an online sheet with ordered event details, and returns dates, names, and author...
def get_schedule_dates(): update_local_sheet() dates = [row[0] for row in entire_sheet] names = [row[1] for row in entire_sheet] authors = [row[2] for row in entire_sheet] old_ops = [dates, names, authors] next_sundays = get_next_n_sundays(date_amount) ops = [] # Go through all the ...
def build_ubuntu_python(gpu=None): if gpu==None: gpu = input("Do you want to build with CUDA? [y/N] ").lower() == "y" TARGET_VERSION = ubuntu_python_version IMAGE_BASE = "nvidia/cuda:11.8.0-runtime-ubuntu22.04" if gpu else "ubuntu:22.04" CUDA_VERSION = "cuda11" if gpu else "" target_image = RE...
The code defines a `build` function that selects and executes specific build processes based on the provided `image` parameter. It dispatches to different helper functions like `build_ubuntu_python` or `build_ubuntu_python_aitool` depending on the image type, which includes variations for AI tools (TensorFlow, PyTorch)...
def build(image, gpu=None): if image == "ubuntu_python": build_ubuntu_python(gpu) elif image == "ubuntu_python_tensorflow": build_ubuntu_python_aitool(AI_TOOL.tensorflow, gpu) elif image == "ubuntu_python_pytorch": build_ubuntu_python_aitool(AI_TOOL.pytorch, gpu) elif image == "u...
def init_game_data(): """ Initializes game data according to game type selected by user(new or load) :return: tuple with game data (map, left treasures amount, player position and trapped state) :rtype: tuple """ current_data = () is_trapped = False while not current_data: ...
The code runs a game cycle by initializing game data, then looping until all treasures are collected or the player is trapped. It checks win/loss conditions, scans the player's surroundings, updates the game state, and prints the map once the loop ends.
def run_game_cycle(): """ Runs game cycle """ current_data = init_game_data() game_map, treasures_left, player_position, is_trapped = current_data while True: if treasures_left == 0: print('Congrats! You have collected all treasures!') break elif ...
def read_config(file): with open(file, "r") as stream: _config = yaml.safe_load(stream) return _config def msg(err_message, log=None): tstamp = strftime("[%Y:%m:%d %H:%M:%S] ", localtime()) echo_click(tstamp + err_message + "\n", log=log) def recursive_merge_config(config, overwrite_config): ...
The main task of the code is to update a configuration file by recursively merging new values (from 'merge') into an existing configuration (from 'in_config'), then writing the updated configuration to a specified output file ('output_config'), with optional logging. If 'output_config' is not provided, it overwrites th...
def update_config(in_config=None, merge=None, output_config=None, log=None): """Update config with new values""" if output_config is None: output_config = in_config config = read_config(in_config) msg("Updating config file with new values", log=log) recursive_merge_config(config, merge) ...
def snake_base(rel_path): return os.path.join(os.path.dirname(os.path.realpath(__file__)), rel_path) def msg(err_message, log=None): tstamp = strftime("[%Y:%m:%d %H:%M:%S] ", localtime()) echo_click(tstamp + err_message + "\n", log=log) def update_config(in_config=None, merge=None, output_config=None, log=N...
The main task of the code is to copy a system default configuration file to a specified local configuration file. If the local file does not exist, it creates the necessary directory, copies the system config, and optionally merges it with a provided merge_config. If the local file already exists, it logs a message and...
def copy_config( local_config, merge_config=None, system_config=snake_base(os.path.join("config", "config.yaml")), log=None, ): if not os.path.isfile(local_config): if len(os.path.dirname(local_config)) > 0: os.makedirs(os.path.dirname(local_config), exist_ok=True) msg(f"...
def copy_config( local_config, merge_config=None, system_config=snake_base(os.path.join("config", "config.yaml")), log=None, ): if not os.path.isfile(local_config): if len(os.path.dirname(local_config)) > 0: os.makedirs(os.path.dirname(local_config), exist_ok=True) msg(f"...
This function executes a Snakemake workflow by constructing and running a CLI command with specified parameters such as Snakefile path, config files, thread count, conda environments, and custom arguments. It manages configuration merging, command-line option assembly, and error handling for workflow execution.
def run_snakemake( configfile=None, snakefile_path=None, merge_config=None, threads=1, use_conda=False, conda_prefix=None, snake_default=None, snake_args=[], log=None, ): """Run a Snakefile""" snake_command = ["snakemake", "-s", snakefile_path] # if using a configfile ...