dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def get_cell_height(self): """ Get height of the cell, that is equal for all cells """ return self.get_board_height() / ROW_SIZE def get_cell_width(self): """ Get width of the cell, that is equal for all cells """ return self.get_board_width() / COLUMN_SIZE def get_board_height(self): ...
The main task of the code is to create a game board by drawing horizontal and vertical lines to form a grid of cells, then placing initial disks. It calculates cell dimensions, iterates to draw grid lines, and calls a method to render four starting disks, likely for a game like Reversi/Othello.
def create_game_board(self): """ Draw vertical and horizontal lines to have cells, then put the initial disks """ # self.root.delete() self.root.update() cell_height = self.get_cell_height() cell_width = self.get_cell_width() # Draw the horizontal lines of game board ...
def is_valid_url(url): match = re.match(r'(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?', url) return match is not None def update_values(service, spreadsheet_id, range, values): body = { 'values':[values] } service.spreadsheets().values().update(spreadsh...
The code processes URLs in a Google Sheets document by authenticating via OAuth2, retrieving sheet data, validating URLs, checking their availability, capturing content, and updating the spreadsheet with results like error messages, availability status, and captured URLs while tracking errors.
def process_doc(spreadsheet_id, auth_code, headers): flow = client.OAuth2WebServerFlow(client_id=CLIENT_ID, client_secret=CLIENT_SECRET, scope=SCOPES, redirect_uri=REDIRECT_URI_PROD, ...
def totalSens(self, count): self.total = count def split(self): print("_*__*__*__*__*__*__*__*__*__*__*_") def convrtToDict(self, sen, neighbour): m = (neighbour.id, int(input("Enter the distance to " + sen.id + ": "))) if sen.id not in self.senDictionary: self.senDictionary[sen.id] ...
The main task of the code is to create and configure multiple wireless sensors by collecting validated user inputs for sensor IDs, neighbor connections, oxygen levels, and temperature measurements. It ensures numerical and alphanumeric constraints through error-checking loops, stores sensor data in a list, and utilizes...
def createSensors(self): while True: #checks to see if the input that the user has put in is a number and nothing else try: numberOfSensors = int(input("Enter the number of sensors: ")) break #breaks the loop after it sees the input is an int #if it is not a num...
def is_struct(line): return "struct" in line and is_valid_curlybrace(line)[0] def get_struct_name(stringrep, i): lines = stringrep[i:] if len(lines) == 0: return line = lines[0].strip() if not line.startswith("typedef"): return line[line.find("struct") + 6:line.find("{")].strip() ...
This function processes input (file or string) to extract C structures, tracking their content via curly braces. It stores structures in a dictionary, ensures uniqueness, and generates Python code with ctypes. It updates a data structure with found structures, writes imports if missing, and builds each structure in "Cu...
def process_struct(filepath=None, stringrep=None): if filepath is not None: with open(filepath, "r") as f: lines = f.readlines() elif stringrep is not None: lines = stringrep.split("\n") else: return currstruct = "" oc = {"{": 0, "}": 0} for i, line in enumera...
def create_chunked_data(start_date, end_date, max_res_ratio, chunk_size, overlap_ratio, max_frequency): etf_table = get_price_data(tickers=ETF_TICKERS, start_date=start_date, end_date=end_date, table='SFP') etf_table = smooth_target_col(etf_table, max_res_ratio=max_res_ratio, target_col='low', name='smooth_pric...
The code segments a time series into chunks, clusters them using spectral clustering based on frequency distributions, and returns representative date ranges from each cluster. It first partitions data into overlapping chunks, computes a distance matrix, applies clustering to group similar chunks, then samples a specif...
def create_chunks(self): date_ranges, res = create_chunked_data(self.start_date, self.end_date, self.max_res_ratio, self.chunk_size, self.overlap_ratio, self.max_frequency) chunked = chunk_frequency_data(res) unique_dist, dist_matrix = construct_distance_matrix(chunked) spec_cluster = Sp...
def fSet_axismask(self, axismask, task, motionmode, update=False): if update: self.axismask = axismask self.addlog('Axis mask changed to ' + str(self.axismask)) else: kwargs = {'axismask': axismask, 'task': task, 'motionmode': motionmode, 'update': True} s...
This function configures motion parameters for a task, using default values when parameters are omitted. It directly assigns task/motion mode settings and calls methods to set axis mask, relative/absolute mode, units, ramping, acceleration, and lookahead. Returns a log of the operation.
def Set_Motion(self, dtask='', axismask='', length_units='', RelAbs='', MotionRamp='', MaxAccel='', LookAhead='', dmotionmode='', dmotiontype='', motionmode='', task=''): # These direct assignments are somewhat queue jumping at the moment if dtask != '': self.defaulttask = dtask if ...
def initialize_centroids(self): random_points = np.random.choice(self.rows, self.k, replace=False) centroids = [self.data[index] for index in random_points] return centroids def _create_clusters(self): clusters = [[] for i in range(self.k)] for index, row in enumerate(self.data):...
This code implements the K-means clustering algorithm by initializing centroids, iteratively assigning data points to clusters, updating centroids based on cluster means, and stopping when centroids converge. It returns the final cluster assignments after convergence or maximum iterations.
def kmeans(self): self.centroids = self.initialize_centroids() for i in range(self.iterations): self.clusters = self._create_clusters() past_centroids = self.centroids self.centroids = self._update_centroids() if self._is_converged(past_centroids): ...
def set_seed(seed): """ Function for setting the seed for reproducibility. """ np.random.seed(seed) torch.manual_seed(seed) if torch.cuda.is_available(): torch.cuda.manual_seed(seed) torch.cuda.manual_seed_all(seed) torch.backends.cudnn.determinstic = True torch.backends....
The code trains and evaluates a specified neural network model on the CIFAR10 dataset, handling model loading, training (with checkpoint support), testing under corruptions, and result saving. It sets a seed for reproducibility, uses GPU if available, and returns test accuracies across corruption types and the standard...
def main(model_name, lr, batch_size, epochs, data_dir, seed): """ Function that summarizes the training and testing of a model. Args: model: Model architecture to test. batch_size: Batch size to use in the test. data_dir: Directory where the CIFAR10 dataset should be loaded from or ...
def visualize_time_domain_complex(self, save_dir, idcs=None, fix_scale=False, include_axis=False): """ Plot the time domain filters of the filterbank. Parameters ---------- save_dir : string Directory under which to save images for each plot idcs : list, ndarra...
The main task of the code is to generate and save visualizations of filters in both time and frequency domains. It creates structured directories for time-domain and frequency-domain plots, extracts relevant keyword arguments for each visualization type, and calls specialized methods to render time-domain complex signa...
def visualize(self, save_dir, **kwargs): """ Visualization function which extracts relevant keyword arguments and runs all visualization functions. Parameters ---------- save_dir : string Top-level directory to hold images of all plots **kwargs : N/A ...
def ask_version(self): method = '_find_version_{}'.format(self.config['language']) self.current_version = getattr(self, method)() self.new_version = '0.0' msg = 'Current version is ' + click.style(self.current_version, fg='yellow') + ', enter new' while parse_version(self.new_ver...
This function automates a release process by bumping the version, committing changes, pushing to repositories, running unit tests (if enabled), handling CI workflows, creating version tags, and updating packages. It uses configuration settings and flags to determine specific actions like language-specific setup verific...
def go_ahead(self, force: bool, run_tests: bool): self.force = force getattr(self, 'verify_setup_{}'.format(self.config['language']))() self.ask_version() self.commit('Bump version {}'.format(self.new_version)) self.push() if run_tests is True: getattr(self...
def create_players( self ): self.players.append( Player( True ) ) for player in range( self.number_of_players - 1 ): self.players.append( Player() ) for index in range( len(self.players) ) : self.players[index].name = "Player " + str(index + 1) print( self.pla...
The code initializes a game with a specified number of players by creating a deck, shuffling it, dealing two cards to each player, and entering a loop where players take turns until all are standing (finished or out of the game).
def __init__( self, number_of_players ): self.number_of_players = number_of_players self.deck = Deck() random.shuffle( self.deck.cards ) self.players = [] self.create_players() for player in self.players: for i in range( 2 ): self.deal_ca...
def _init_perm(self): self.perm_long = range(256) self.perm_short = range(64) def _add_hdist(self): hdist = { "lang": "painless", "source": '64-Long.bitCount(params.subcode^doc[params.field].value)'} self.es.put_script(id=self.script_name, script=hdist) def _creat...
This code initializes an Elasticsearch extension for efficient similarity search using binary codes. It sets up index configurations, creates indices if they don't exist, and prepares parameters like binary code lengths, subcode radius, and shard/replica settings. The class extends Elasticsearch to support hash-based r...
def __init__(self, es: Elasticsearch, additional_fields: List[str] = ["image_path"], index_prefix: str = 'eh', shards=1, replicas=1, radius=2): """ Extend Elasticsearch for efficient similarity search based on binary codes. :param es: instance of a :class:`elasticsearch.Elastic...
def _remove_blocks(self, index_name): self.es.indices.put_settings( index=index_name, body={"index": {"blocks.write": None}}) def _add_hdist(self): hdist = { "lang": "painless", "source": '64-Long.bitCount(params.subcode^doc[params.field].value)'} ...
This code resets an Elasticsearch index by deleting existing indices, removing blocks, and recreating them with new configurations, ensuring data is cleared and write blocks are applied for the nbs index.
def reset(self): """ Delete and recreate all indices. This will also delete all documents in the retrieval index. """ if self.es.indices.exists(index=self.index_name): self._remove_blocks(self.index_name) self.es.indices.delete(index=[self.index_name]) if ...
def _save_codes(self, file: tempfile.NamedTemporaryFile): self.es.indices.refresh(index=self.index_name) num_docs = self._size() max_docs = min(self.num_decorrelate, num_docs) size = 1000 lines = [] batches = scan( size=size, client=self.es, ...
The main task of the code is to optimize the bit permutation of codes in an index by computing a correlation matrix, rearranging bit positions to reduce correlation, and applying the new permutation to improve search performance. It uses a temporary copy of the index, computes bit distributions and correlation plots if...
def decorrelate(self, plot_dir: str = None, num_samples: int = None): """ After adding about 10,000 codes in the index the decorrelate method should be called. After rearranging the bit positions search may be significantly faster. The bit distribution and correlation matrix are plotted if a ...
def pass_time(self, rabbits, rabbit_lock): if self.time_to_live <= 0: with rabbit_lock: rabbits.done = True return else: self.time_to_live -= 1 * self.life_speed_up if self.reproductive_timer > 0: self.reproductive_timer -= 1 * sel...
The code defines an `action` method for an agent, handling its behavior based on environmental interactions. It updates time, checks proximity to grass, foxes, and rabbits, and executes actions: fleeing from nearby foxes, hunting grass if time permits, seeking a partner for reproduction, or moving randomly. It also han...
def action(self, grass, foxes, rabbits, rabbit_lock, grass_lock, clock_speed): self.pass_time(rabbits, rabbit_lock) nearest_grass, nearest_g_distance = self.get_grass_info(grass) nearest_fox, nearest_f_distance = self.get_fox_info(foxes) best_rabbit, best_r_distance = self.get_rabbit_in...
def times(x, y): # calculate the coefficient newCoefficient = x.coefficient * y.coefficient # merge the two dictionaries newVariables = multiplyMonoVariables(x.variables, y.variables) # create new mono object and return return [mono(newCoefficient, newVariables).pemdasCleanUp()] def dividedBy...
The function simplifies an equation by evaluating multiplication and division operations first, then addition and subtraction, modifying the equation list in-place by replacing operands and operators with their computed results. It iterates through the equation, processes each operator sequentially, and restarts the lo...
def simplifyNoBracketEquation(equation): # determines whether or not to start a new for loop newForLoop = True # when we want another for loop while newForLoop: # if we don't find any operators in the equation we will stop newForLoop = False # set index for the while loop ...
def findMonomialsInEquation(equation): # a list of all monomials inside equation allMonomials = [] # iterate through equation's items for item in equation: # item is a monomial if isinstance(item, mono): # add item to our list of monomials allMonomials.append(...
The function `factorPolynomial` factors a polynomial by extracting the greatest common factor (GCF). It identifies all monomials in the input polynomial, computes their common factor, and if it is not 1, divides each term by this factor. The GCF is then placed outside the polynomial as a factor. The result is a factore...
def factorPolynomial(poly): # TODO: factor by difference of squares, factor by grouping, factor out # get all monomials inside poly monomialsInsidePoly = findMonomialsInEquation(poly) # find the commonFactor of the monomials commonFactor = findCommonMono(monomialsInsidePoly) # common factor ...
def dividedBy(x, y): # divide both x.co, y.co by this number to get the new x, and y coefficients divideBothBy = findCommonMono([x, y]).coefficient # calculate new coefficients from 4/8 ---> 1/2 changedXCoefficient = x.coefficient / divideBothBy changedYCoefficient = y.coefficient / divideBothBy ...
The function performs polynomial long division, returning the quotient terms and remainder. It iteratively divides the leading term of the dividend by the divisor's leading term, appends the result to the quotient, subtracts the product from the dividend, and repeats until the dividend's degree is lower than the diviso...
def polyLongDivision(dividend, divisor): # the result of dividend / divisor endResult = [] # the term at the front of divisor divisorFrontTerm = divisor[0] # the variable name variableName = list(dividend[0].variables.keys())[0] # stop when the front number in the dividend has an exponen...
def define_parser(): parser = argparse.ArgumentParser( 'vep-annotation-reporter', description = "A tool to create a tab-delimited (TSV) file of variants in a VCF and their " + "VEP annotations." ) parser.add_argument( "input_vcf", help="The VCF file with...
The code processes input VCF or TSV files, extracts VEP (Variant Effect Predictor) fields, and generates an output TSV file containing variant data (CHROM, POS, REF, ALT) augmented with specified VEP annotations. It handles input formats via command-line arguments, merges data, and writes results in TSV format with cus...
def main(args_input = sys.argv[1:]): parser = define_parser() args = parser.parse_args(args_input) vep = extract_vep_fields(args) if args.output_tsv: output_file = args.output_tsv else: (head, sep, tail) = args.input_vcf.rpartition('.vcf') output_file = "{}.tsv".format(head...
def user_choice(): return input("> ").lower().replace(' ', '') def add_webhook_via_twitter_ids(self): self.webhook_count() print('\nYou can post the same content in multiple text channels by separating the webhook URLs with a comma ,') print('Get the twitter IDs from here: http://gettwitteri...
The code presents a menu to let users choose between setting up a webhook using Twitter IDs or a Twitter List URL, invoking respective methods based on input, with an option to return to the previous menu.
def add_webhook(self): while True: print('Do you want to setup your Webhook via Twitter IDs or a Twitter List URL?') print("1. Twitter IDs") print("2. Twitter List URL") print("\n0. Go back") choice = user_choice() if choice == "1": ...
def unpack(self): """Get dots coordinates of a move.""" # Get dots d1, d2 = self.get() # Get dots coordinates x1, y1 = d1 x2, y2 = d2 return x1, y1, x2, y2 def done(self, state): """Check if a move was already done.""" return self.dots in [m.dots...
This code validates and executes a move in a game by checking its legality (adjacent coordinates), ensuring it hasn't been made before, updating the game state (plotting the move, removing it from available moves), and checking if a box is completed. It returns 1 for a successful move or 0 if invalid/already done.
def make(self, state): """Make a move, if legal.""" # Unpack move x1, y1, x2, y2 = self.unpack() # Check if move is legal delta_x = abs(x1 - x2) delta_y = abs(y1 - y2) delta = delta_x + delta_y if delta != 1: return 0 # Check if move...
def _get_profile_path(self, profile_id: str) -> str: if profile_id is not None: return os.path.join(AdvancedProfileHelper.ADVANCED_PROFILES_PATH, profile_id) else: return os.path.join(AdvancedProfileHelper.DEFAULT_PROFILE_PATH) def get_profile_mod_paths(self, profile_id: str) -> List[str]: mods_...
This function initializes a Minecraft profile by transferring mods between the specified profile and default profile folders, updating resource packs in the options.txt file, and modifying the profile configuration. It moves .jar mods from the profile's mods folder to the default profile's folder and vice versa, ensuri...
def initialize_profile(self, mc_path: str, profile_id: str): if profile_id is None: return profile_path = self._get_profile_path(profile_id) if not os.path.exists(profile_path): return mc_mod_folder = os.path.join(mc_path, "mods") default_profile_mods_path = os.path.join(Advanc...
def get_profile_mod_paths(self, profile_id: str) -> List[str]: mods_path = os.path.join(self._get_profile_path(profile_id), "mods") if not os.path.exists(mods_path): return [] else: return [os.path.join(mods_path, mod_path) for mod_path in os.listdir(mods_path) if mod_path.endswith(".jar")] def...
This function restores the default mod profile by removing all existing .jar mod files from the specified Minecraft mods directory, then moving default profile .jar mods into this directory, and finally updating resource pack settings with the default profile configuration.
def restore_default_profile(self, mc_path: str): mc_mod_folder = os.path.join(mc_path, "mods") for relative_mod_path in os.listdir(mc_mod_folder): if not relative_mod_path.endswith(".jar"): continue os.remove(os.path.join(mc_mod_folder, relative_mod_path)) default_profil...
def Eval__max__lens(): for table, attrs in AttrsDI.items(): LOL = ValuesDI[table] Array = numpy.array(LOL) print('\n\n========') print(table) max_lens = [] for column_index in range(len(attrs)): curr_column = Array[:, column...
The code's main task is to prepare SQL creation statements, connect to a Microsoft SQL database, insert data values, and log errors. It disables table creation/cleaning steps via comments, focusing on data insertion after establishing the database connection and preparing required SQL statements.
def Start(): Eval__max__lens() PrepareCreateStatements() # PrintoutSQL_stqtements() Connect_mssql() # CreateTables() # Clean__all__tables() InsertValues() WriteErrorsLog()
def Read__source(): curr_fname = CurrDI['source'] ##fname = 'StudiesWithResults\\NCT00014495.xml' fname = 'StudiesWithResults/'+ curr_fname fi = open(fname, 'r') line = fi.read() fi.close() OrDI = xmltodict.parse(line)##fd.read()) CurrDI['OrDI'] = OrDI CurrDI['outcome'] = 0 Cu...
The main task of the code is to gather and process study-related data by reading sources, identifying study IDs, evaluating drugs and diseases, retrieving participant flow and baseline information, and compiling study results. It orchestrates multiple data extraction and analysis steps to compile comprehensive research...
def Get_DATA(): Read__source() Study__id() Eval__study__drugs() Eval__disease() Get__participant_flow() Get__baseline() Study_results()
def transform_resource( fc: FHIRClient, capability_statement: CapabilityStatement, resource_type: str, chunk_size: int, limit: Union[None, int], novalidation: bool, parallel_processing: bool, database_deleted: bool, neo4j_driver: neo4j.Driver, ...
The main task of the code is to connect to a FHIR server and Neo4j database, validate the Neo4j APOC library, and execute operations like deleting data, transforming FHIR resources into Neo4j nodes/relationships, and resolving unresolved references. It processes command-line arguments to determine actions, handles conn...
def main(args: argparse.Namespace) -> int: """Main function. Args: args (argparse.Namespace): the command-line arguments as processed by argparse Returns: int: status code: 1 if an error occurred, 0 otherwise """ # set log level; only set log level of fhir2neo4j logger here, globa...
def getElementaryIntervals(self, data, si, ei): '''generates a sorted list of elementary intervals''' coords = [] [coords.extend([x[si],x[ei]]) for x in data] coords = list(set(coords)) coords.sort() return coords def recursiveBuildTree(self, elIntervals): ''' ...
This code initializes an interval tree structure to efficiently query and manage genomic or similar interval-based data. It processes input data with start/end coordinates, constructs elementary intervals, recursively builds a tree, inserts data into the tree, and trims it to the specified range. The tree enables fast ...
def __init__(self, data, si, ei, start, end): ''' data: an array of elements where each element contains start coodinate, end coordinate, and element id. si: index or key of the start coodinate in each element ei: index or key of the end coordinate in each element start: position...
def get_current_value_from_currency(currency): if "-EUR" not in currency: currency = currency+"-EUR" for order in pricesLatest24h: if order['market'] == currency: return order['last'] def average_price_per_currency(apiKey,apiSecretKey,currency): if "-EUR" not in currency: ...
The function gathers financial metrics for a specified currency, including current price, average price, VWAP, total invested amount, and profitability status (average vs. VWAP). It formats these into a structured dictionary, rounding values to three decimal places, and ensures the currency code ends with "-EUR" for co...
def overview(apiKey,apiSecretKey,currency): if "-EUR" not in currency: currency = currency+"-EUR" current_price = get_current_value_from_currency(currency) average_price = average_price_per_currency(apiKey,apiSecretKey,currency) vwap = get_vwap_of_currency(currency) total_invested = get_tota...
def _resume_prune_status(self, ckpt_path): state = torch.load(ckpt_path) self.model = state['model'].cuda() self.model.load_state_dict(state['state_dict']) self.optimizer = optim.SGD(self.model.parameters(), lr=self.args.lr_pick if self.args.__dict__.get(...
This function performs iterative model pruning with regularization during training. It initializes an optimizer, resumes from a checkpoint if specified, and enters a training loop that updates weights, applies regularization, and prunes filters. The process alternates between "update_reg" (adjusting regularization) and...
def mini_prune(self, cycle): # prune --> mini_prune self.model = self.model.train() self.optimizer = optim.SGD(self.model.parameters(), lr=self.args.lr_pick if self.args.__dict__.get('AdaReg_only_picking') else self.args.lr_prune, momentum...
def _update_pr(self, cycle): '''update layer pruning ratio in iterative pruning ''' for layer, pr in self.pr_backup.items(): pr_each_time_to_current = 1 - (1 - pr) ** (1. / self.args.num_cycles) pr_each_time = pr_each_time_to_current * ( (1-pr_each_time_to_current) ** (cy...
The code performs iterative pruning of a neural network model by updating weight sparsity over multiple cycles. It clears existing pruning values, computes layer-wise sparsity, applies masks to zero-out pruned weights, and optionally finetunes the model between cycles. The process logs sparsity metrics and returns the ...
def prune(self): # clear existing pr for layer in self.pr: self.pr[layer] = 0 for cycle in range(1, self.args.num_cycles + 1): self.logprint(f'==> Start sub-Reg #{cycle}') self._update_pr(cycle) # get pr self._get_kept_wg_L1() # from pr, update se...
def append_byte(self, value: int) -> None: self.__data.append(struct.pack('b', value)) def append_int(self, value: int) -> None: self.__data.append(struct.pack('i', value)) def __append_numpy_array_as_list_to_buffer(self, data: List, fmt: str) -> None: first_element = data[0] if isinsta...
This function serializes a NumPy array into a buffer by first checking if the input is None (appending 0) or not (appending 1). It then records the array's shape, validates its data type against a mapper, appends the element type, dimensions, and converts the array to a list for further buffer processing.
def append_numpy_array(self, value: np.ndarray) -> None: if value is None: self.append_byte(0) else: self.append_byte(1) shape = value.shape self.append_int(len(shape)) if value.dtype.name not in self.__numpy_type_mapper: raise...
def append_byte(self, value: int) -> None: self.__data.append(struct.pack('b', value)) def append_int(self, value: int) -> None: self.__data.append(struct.pack('i', value)) def append_string(self, value: str) -> None: if value is None: self.append_byte(0) else: se...
This method serializes a dictionary into a byte stream by first indicating if the dictionary is null, then writing its length and key-value pairs. It converts non-primitive values (sets/tuples) to lists, handles string arrays, and appends primitive values. Unsupported types raise an error, ensuring only string keys and...
def append_dictionary(self, value: Dict[str, Any]) -> None: if value is None: self.append_byte(0) else: self.append_byte(1) self.append_int(len(value)) for key in value.keys(): self.append_string(str(key)) element = value[k...
def append_numpy_array(self, value: np.ndarray) -> None: if value is None: self.append_byte(0) else: self.append_byte(1) shape = value.shape self.append_int(len(shape)) if value.dtype.name not in self.__numpy_type_mapper: raise...
This function appends input data to a structure by identifying its type (numpy array, string array, list, tuple, float, int, string, dict) and calling the corresponding append method. If the type is unsupported, it raises an exception. The core task is type-checking and routing data to the appropriate handling method f...
def append_data(self, value): if isinstance(value, np.ndarray): self.append_numpy_array(value) elif self.__is_string_array(value): self.append_array_of_string(value) elif isinstance(value, list): self.append_list(value) elif isinstance(value, tuple): ...
def write(input): global NewLine output = "" for char in input: if NewLine: output += Indent * ' ' NewLine = False output += char if char == '\n': NewLine = True sys.stdout.write (output) def indent(): global Indent Indent += 1 def print_binary_data(size): value = "" while size > 0...
The function processes a data blob by reading a specified length of data, converting it to binary representation, and returning the result while handling indentation for formatted output.
def handle_blob(entry): length = entry [1] write ("\n") indent () value = print_binary_data (read_value (length)) dedent () return value
def read_value(expr): input = iter (expr.split ()) def eval(): token = input.next () if expr == 'cstr': return read_cstr () if expr == 'true': return True if expr == 'false': return False if len (token) > 1 and token [0] in ('=', '@', '<', '!', '>'): val = read(expr) assert (len (...
The code processes an enumeration entry by reading a value from the input format, selecting the appropriate definition (handling nested tuples if present), and formatting the output with the corresponding description and value. It returns the processed value after writing the formatted result.
def handle_enum(entry): iformat = entry [1] oformat = entry [2] definitions = entry [3] value = read_value (iformat) if type (definitions) is types.TupleType: selector = read_value (definitions [0]) definitions = definitions [1] [selector] if value in definitions: description = definitions[value] els...
def read_value(expr): input = iter (expr.split ()) def eval(): token = input.next () if expr == 'cstr': return read_cstr () if expr == 'true': return True if expr == 'false': return False if len (token) > 1 and token [0] in ('=', '@', '<', '!', '>'): val = read(expr) assert (len (...
The code processes input flags by reading a value using the specified input format, writing it with the output format, and then iterating through definitions. For each definition, it checks if the value matches a mask. If a match is found, it maps the selection to a name or writes the name with the selection value. The...
def handle_flags(entry): iformat = entry [1] oformat = entry [2] definitions = entry [3] value = read_value (iformat) write_value (oformat, value) indent () for entry in definitions: mask = entry [0] name = entry [1] if len (entry) == 3: map = entry [2] selection = value & mask if selection ...
def neg_log_likelihood(data, theta, beta, alpha): """ Compute the negative log-likelihood. You may optionally replace the function arguments to receive a matrix. :param data: A dictionary {user_id: list, question_id: list, is_correct: list} :param theta: Vector :param beta: Vector :return:...
The code trains an Item Response Theory (IRT) model by optimizing parameters (theta for users, beta for items, and alpha for item discrimination) using gradient descent. It iteratively computes the negative log-likelihood, evaluates accuracy on training and validation data, updates parameters, and records performance m...
def irt(data, val_data, lr, iterations): """ Train IRT model. You may optionally replace the function arguments to receive a matrix. :param data: A dictionary {user_id: list, question_id: list, is_correct: list} :param val_data: A dictionary {user_id: list, question_id: list, is_correct: list}...
def get_rarity(_nft_index): rarity = 'Unknown' for rarity_weight in rarity_weights: if _nft_index >= rarity_weight['from'] and _nft_index <= rarity_weight['to']: rarity = rarity_weight['value'] return rarity def create_dna(_variations, _rarity): rand_nums = [] for variation in _variations: ran...
This code generates a series of unique NFTs by creating DNA sequences with specific rarity levels, verifying their uniqueness, and compiling metadata. It iterates through an edition size, assigns rarity, generates DNA, checks for duplicates, and builds NFT metadata if unique. Each NFT is signed and saved, with all meta...
def generate_nfts(): dna_list = [] nfts_meta = [] for nft_index in range(edition_size): nft_no = str(nft_index + 1) print('-----------------') print('creating NFT ' + nft_no + ' of ' + str(edition_size)) rarity = get_rarity(nft_index + 1) print('- rarity: ' + rarity) new_dna = create_d...
def __exit__(self, exc_type=None, exc_val=None, exc_tb=None, soft=True): if self.acting_process.is_running: self.acting_process.exit() if soft: self.reset(start_battle_flag=False) def _init_control_process(self): """ Creates an instance of ActingProcess, ...
This code processes an action in a reinforcement learning environment, updates the agent's state, captures the resulting screen observation, calculates rewards and termination status, and returns these values for training. The function handles both dictionary and token-based actions, checks for exit signals, initialize...
def step(self, action: Union[dict, Any]): """ Update the action params valid until the next step call. Return the screen observed at the same time :param action: optional kwargs of form {direction': (x,y), norm != 0, 'make_move': int bool like, 'make_shot': int bool like...
def execute_control_flow_instruction(self, opcode, addr): if opcode is Opcode.HLT: raise StopIteration() if opcode is Opcode.JMP: self.data_path.latch_instr_ptr(IpSelSignal.CU, addr) self.tick() elif opcode is Opcode.JZ: if self.data_path.zero():...
This function decodes a fetched instruction by extracting opcode, address type, and argument. It executes control flow instructions (JMP, JZ, etc.) or ALU operations (ADD, SUB, etc.), updates the accumulator, handles memory/load/store operations, manages stack operations (PUSH/POP), and increments the instruction point...
def decode_and_execute_instruction(self): instr = self.data_path.memory[self.data_path.ip] opcode, addr_type, arg = command_from_hex(instr) if opcode in {Opcode.JMP, Opcode.JZ, Opcode.CALL, Opcode.RETURN, Opcode.HLT}: self.execute_control_flow_instruction(opcode, arg) re...
def majorityOutput(examples): """ Gets the majority classification from a list of examples. :param examples: list of examples. :return: majority classification """ value = None max_weight = -1 count = count_goals(examples) for ex in examples: if count[ex.goal] > max_weig...
The code recursively builds a decision tree by selecting the feature with maximum information gain, splitting examples into subsets, and creating child nodes for each feature value. Base cases handle empty examples, no remaining features, or uniform goals. Depth limits recursion, and majority voting determines leaf nod...
def dTree(examples, features, parent_examples, depth): """ decision tree builder method (recursive) :param examples: current examples :param features: set of features :param parent_examples: parent's examples :param depth: maximum depth :return: decision tree Root """ if not examples...
def get_arguments(): """Parse all the arguments provided from the CLI. Returns: A list of parsed arguments. """ parser = argparse.ArgumentParser(description="Dynamic Video Segmentation Network") parser.add_argument("--video_file", type=str, default=VIDEO_FILE, help="Pa...
This code processes a video using a neural network model combining segmentation and optical flow. It initializes TensorFlow placeholders, loads pre-trained models, and processes each frame through either a segmentation or spatial warping path based on predicted scores. The output is saved as a segmented video, with dec...
def main(): args = get_arguments() print(args) key_image_raw_contents = tf.placeholder(tf.float32, [original_height, original_width, 3]) current_image_raw_contents = key_image_raw_contents image_s, image_f, resized_image = scale_and_mask(key_image_raw_contents, current_image_raw_contents, input_siz...
def create_event(eventbrite_api_token, organization_id ,event_details): summary_length = len(event_details['event'].get('summary', '')) assert summary_length <= 140, f'Summary is limited to 140 characters. Got {summary_length}' url = f"{EVENTBRITE_API_BASE_URL}organizations/{organization_id}/events/" h...
The function creates an Eventbrite event with specified details, converts local time to UTC, constructs event/ticket JSON, and uses the API to create the event and ticket class. It handles timezone conversion, event data formatting, and optional publishing.
def quick_create_event(now, eventbrite_api_token, organization_id, title, summary, description, date_start, duration_hours, event_timezone='Australia/Perth', cost_cents=None, publish=False): # Create a timezone object for the specified timezone new_timezone = pytz.timezone(event_timezone) date_start = new_...
def init_first_stage_from_ckpt(self, config, ckpt_path): model = instantiate_from_config(config) if ckpt_path is not None: state_dict = torch.load(ckpt_path, map_location="cpu") sd = state_dict['state_dict'] new_state_dict = OrderedDict() only_use_vqgan = ...
The code initializes a model combining a VQVAE (first stage) for image encoding, a permuter (defaulting to identity), and a transformer. It loads pre-trained weights or checkpoints if provided, handling configurations for image-label-bbox data. The model processes images via tokenization, uses layout permutations, and ...
def __init__(self, transformer_config, first_stage_config, permuter_config=None, pretrain_path=None, ckpt_path=None, ignore_keys=[], first_stage_key="image", label_key='label', bbox_key='bbox', vqvae_c...
def extract_features(raw): data = [] for r in raw: point = {} point["label"] = (r['AD'] == '1') features = [] features.append(1.) features.append(float(r['C'])) point['features'] = features data.append(point) return data def load_csv(filename): li...
The code evaluates a machine learning model's performance by loading training and test data, extracting features, training a model, and calculating accuracy on both training and validation sets to assess its effectiveness.
def test_submission(): train_data = extract_features(load_csv("training.csv")) valid_data = extract_features(load_csv("test.csv")) model = submission(train_data) predictions = [predict(model, p) for p in train_data] print("Training Accuracy:", accuracy(train_data, predictions)) predictions = [pr...
def get_bestbuy_citylist(state_href): state_response = requests.get(BESTBUY_URL + state_href) state_soup = BeautifulSoup(state_response.text, 'html.parser') citya_list = state_soup.find_all('a', attrs={'class':'c-directory-list-content-item-link'}) store_list = [] for city_a in citya_list: ...
The main task of the code is to scrape BestBuy's website by parsing HTML content, extracting links based on URL depth levels (state, city, store), and aggregating store information into a list using recursive helper functions. It uses BeautifulSoup for parsing and requests for HTTP requests, dynamically determining whi...
def get_bestbuy(): bestbuy_response = requests.get(BESTBUY_URL) bestbuy_soup = BeautifulSoup(bestbuy_response.text, 'html.parser') statea_list = bestbuy_soup.find_all('a', attrs={'class':'c-directory-list-content-item-link'}) store_list = [] for state_a in statea_list: state_href = state_a[...
def get_PDFs(folder): PDFs = glob.glob(folder + "/*.pdf") return PDFs def process_regex(naming_regex): naming_regex = naming_regex.lower() regex = naming_regex.replace('s', '\\D+') # 's' for strings regex = regex.replace('d', '\\d+(?:\\.\\d+)?') # 'd' for numbers regex = regex.replace('x'...
The main task of the code is to process gas chromatography (GC) data from PDF files using a GUI interface. It allows users to input a folder path, naming regex, columns, and standards, then extracts and processes data from MARIA.isr reports. The tool handles PDFs, applies regex for sample naming, calculates flux if ena...
def GC(): sample_rows = {} samples = {} standards = {} # GC form layout layout = [[sg.Text('GC Data Processing Tool', font='Any 36', background_color='#0680BF')], [sg.Text("", background_color='#0680BF')], [sg.Text('PDF files folder:', size=(15, 1), background_color='#0680BF'), sg.I...
def __update_host_failed(host_bean, host_dao, msg=None): """ Update host status to request_failed and is_delete to true :param host_bean: :param host_dao: :return: """ if msg: notify.notify_admin(msg) host_bean.status = host.HOST_STATUS_REQUEST_FAILED host_bean.is_deleted = ...
The main task of the code is to create a cloud instance based on provided parameters (host_class, is_spot, host_id, host_name), update the host status in the database, handle spot/demand instance logic, retrieve configuration details from a worker profile, attempt instance creation using default or alternative VSwitche...
def add(host_class=None, is_spot=None, host_id=None, host_name=None): """ Add instance. :param host_class: :param is_spot: :param host_id: :param host_name: :return: """ logger.debug('**** Start update host status.') try: host_dao = HostDao() host_bean = host_dao...
def get_edge_trees(data: utils.Data) -> int: return 2 * data.count() + 2 * (data.first().count() - 2) def part_one(data: utils.Data) -> int: trees_on_edge = get_edge_trees(data) interior_visible_trees = get_interior_visible_trees(data) return trees_on_edge + interior_visible_trees def part_two(data: uti...
The code tests a data processing pipeline by initializing a `Data` object with a sample, then verifying that `get_edge_trees(data)` returns 16, `part_one(data)` returns 21, and `part_two(data)` returns 8. It asserts these expected outcomes to validate correctness, with the final result of `part_two` printed for confirm...
def test(sample): data = utils.Data(sample, level2_separator="") assert get_edge_trees(data) == 16 assert part_one(data) == 21 print(part_two(data)) assert part_two(data) == 8
def reset_file_system() -> None: root = Node(name="/", filename="/", file_type=FileType.DIR, parent_directory=None) file_system = {"/": root} def read_input(input: str) -> None: current_path = "/" lines = input.split("\n") for line in lines: if line == "$ ls": # Go to the next li...
The code processes a file system input to calculate the total size of all directories with a size less than or equal to 100,000. It resets the file system, reads the input, computes directory sizes, and sums eligible directories' sizes for the result.
def part_one(input: str) -> int: reset_file_system() read_input(input) calculate_dir_size() result = 0 for node in file_system.values(): if node.file_type == FileType.DIR: if node.size <= 100000: result = result + node.size return result
def getJataka(d): pb = "BENGALURU" dt = d.strftime("%d.%m.%Y") tm = d.strftime("%H:%M") la = "12.97" lo = "77.63" return Astro(pb,dt,tm,la,lo,"") def addDays(d,i): return (d + timedelta(days=i)) def gen_table(dt,ark,mas,paksh,tit,type): date_list = [] ti_pos = tithi_name.index(tit) ...
This code generates a panchanga (Hindu calendar) table for a given date/time, retrieves astronomical data (arka, paksha, tithi) and database entries (masa, paksha), adjusts dates if needed, formats output with headers, and creates a filename. It uses SQLite queries, date calculations, and specific formatting rules for ...
def __init__(self, d, t, c): dt = datetime.strptime(d+" "+t,"%Y-%m-%d %H:%M") jat = getJataka(dt) arka = jat.arka paksha = jat.paksha tithi = jat.tithi masa = '' date = dt for z in range(0,2): conn = sqlite3.connect(db) panch = conn...
def get_dataset_ref(): dataset_ref = None if len(sys.argv) < 2: print('usage: python common.py dataset_ref') else: try: dataset_ref = int(sys.argv[1]) except: dataset_ref = str(sys.argv[1]) return dataset_ref def load_openml(seed): dataset = fetch_open...
The function `load_data_delegate` loads dataset based on the type of `get_dataset_ref()`: OpenML data if it's an integer, local CSV if a string, else raises an error.
def load_data_delegate(seed): if isinstance(get_dataset_ref(), int): return load_openml(seed) elif isinstance(get_dataset_ref(), str): return load_csv() else: raise Exception('dataset_ref must be int (OpenML) or str (local CSV)')
def get_playlist_details(_youtube, **kwargs): return youtube.playlists().list( part="snippet,contentDetails", **kwargs, maxResults=10 ).execute() def get_playlistitems_details(_youtube, pl_id): return youtube.playlistItems().list( part="snippet,contentDetails", m...
The function retrieves YouTube playlist and item details for a given channel, structures the data into MongoDB-compatible documents, and inserts them into a MongoDB collection. It fetches playlist metadata, iterates through items to gather video details, and stores both playlist and item information in the database, re...
def playlist_details_to_mongo_db(channel_id): pl_of_ch_id = get_playlist_details(youtube, channelId =channel_id) pl_det = [] for i in pl_of_ch_id['items']: pl_id= i['id'] pl_item_det=get_playlistitems_details(youtube, pl_id) # playlistitem_details_to_mongo_db(pl_id) ...
def outcomes_for_selection(selection:int) ->list[Outcome]: IDX_FOR_SELECTION = [0,1,2,3,4,7,6,16,8,9,10,17,11,13,19,26,5,12,18,20,14,21,22,23,15,25,24,27,28,29,30,31] idx = IDX_FOR_SELECTION[selection] range = SELECTION_RANGES[idx] return OUTCOMES[range] def relevant_upper_totals(slots:Slots)->list[int...
This code builds a cache of expected values (ev_cache) for Yahtzee game states by evaluating optimal slot and dice choices under varying conditions. It iterates through all possible slot combinations, upper totals, and rolls-remaining scenarios, calculating the best decisions (ChoiceEV) for each state. Special cases li...
def build_cache(self) : all_die_combos = outcomes_for_selection(0b11111) placeholder_outcome:Outcome = Outcome((0,0,0,0,0),(0b111,0b111,0b111,0b111,0b111),0) # leaf_cache = {} # first handle special case of the most leafy leaf calcs -- where there's one slot left and no rolls remaining...
def open_h5_file(fpath: pathlib.Path) -> h5py.Group: """ Opens an HDF5 file. """ h5_file = h5py.File(fpath, "r") return h5_file def get_reconstruction_group(h5_file: h5py.File) -> h5py.Group: """ Retrieves the Reconstruction group within an HDF5 file. """ h5_group = h5_file["Reconst...
The main task of the code is to visualize data from an HDF5 file using 3D plots. It opens the file, creates a 3D matplotlib figure, plots a voxel grid from the "reconstruction" group, adds policy-related views from the "policy" group, and displays the combined visualization. The function processes command-line argument...
def main(parsed_args: argparse.Namespace) -> None: """ Program entry point. """ h5_file = open_h5_file(parsed_args.file) fig = plt.figure() ax: plt.Axes = fig.add_subplot(111, projection='3d') ax.set_title("Reconstruction Views") reconstruction_group = get_reconstruction_group(h5_file)...
def active_tasks(): active_tasks = Task.objects.all().filter(is_active = True) return active_tasks def like_group_last_n_posts(task): print('*'*20) print('Start like last n posts task') print('*'*20) time.sleep(1) # task need to be make bots_to_use = get_bots_to_use() bots_to_use = bots_to_use[:task.bots_use_c...
The main task of the code is to process active tasks by checking if they are due, executing their specific actions (liking posts or autoposting), updating their last action time, saving changes, and introducing a delay between tasks.
def make_tasks(): print('start to make tasks') for task in active_tasks(): if not task.time_to_make(): return None if task.t_type == 'like_group_last_n_posts': like_group_last_n_posts(task) if task.t_type == 'autopost_group_thief': autopost_group_thief(task) # set last action time for each task tas...
def set_log_level(log_level): if log_level is not None: numeric_log_level = getattr(logging, log_level.upper(), None) if not isinstance(numeric_log_level, int): raise ValueError('Invalid log level: %s' % log_level) logger.setLevel(numeric_log_level) def _get_plugins(names): _load_plugins() available_plugins...
The code scans Git commits for secrets using configured plugins. It loads a YAML config, parses command-line arguments, identifies common ancestor commits, and iterates through the commit history. For each commit, it checks for secret leaks using specified plugins, counts findings, and returns an exit code based on res...
def main(): logger.debug("Hello") with open(".ci_secrets.yml", 'r') as ymlfile: cfg = yaml.load(ymlfile) if 'log_level' in cfg.keys(): set_log_level(cfg['log_level']) plugin_types = _get_plugins(cfg['plugins'].keys()) plugins = [] for plugin in plugin_types: logger.debug("Configuring: {name}({param})".form...
def Calculate_w(n, c, x, v, m, w, wt, d): t = 2 / (m - 1) dists = np.zeros(c) for i in range(n): for j in range(c): wt[j][i] = 0 w[i][j] = 0 f = False for j in range(c): # dists[j] = pow(np.linalg.norm(x[i] - v[j]), t) dists[j] = pow(Eu...
This function performs iterative updates to compute fuzzy cluster centers (v) and membership weights (w, wt) using a convergence criterion based on error (E). It repeatedly calculates new weights, updates cluster centers, checks for convergence, and returns the final centers, weights, objective value, and elapsed time ...
def f_cmeans(E, tt1, tt, n, c, x, v, w, wt, m, d, tempv, it, obj): iter_ = 0 st = time.time() while True: iter_ += 1 w, wt = Calculate_w(n, c, x, v, m, w, wt, d) tempv = Calculate_Newv(c, n, d, x, wt, tempv) error_ = Errorv(c, v, tempv, d) v = copy.deepcopy(tempv) ...
def f_cmeans(E, tt1, tt, n, c, x, v, w, wt, m, d, tempv, it, obj): iter_ = 0 st = time.time() while True: iter_ += 1 w, wt = Calculate_w(n, c, x, v, m, w, wt, d) tempv = Calculate_Newv(c, n, d, x, wt, tempv) error_ = Errorv(c, v, tempv, d) v = copy.deepcopy(tempv) ...
This function performs an iterative optimization algorithm for fuzzy clustering. It adjusts cluster centers using deletion/insertion heuristics, evaluates objective functions via f_cmeans, and updates parameters to minimize the objective. The process iterates up to max_iter times, refining cluster assignments and weigh...
def fj_means(n, c, d, max_iter, E, x, v, w, wt, tempv, m, obj): it = 0 objtmp = 0 sc = np.zeros(50000) ind = np.zeros(n) tempv1 = np.zeros((c, d)) it1 = 10000 obj = 0 t1 = 0 iter_ = 0 v, w, wt, tempv, obj, tt2 = f_cmeans(E, it, t1, n, c, x, v, w, wt, m, d, tempv, it, objtmp) ...
def f_cmeans(E, tt1, tt, n, c, x, v, w, wt, m, d, tempv, it, obj): iter_ = 0 st = time.time() while True: iter_ += 1 w, wt = Calculate_w(n, c, x, v, m, w, wt, d) tempv = Calculate_Newv(c, n, d, x, wt, tempv) error_ = Errorv(c, v, tempv, d) v = copy.deepcopy(tempv) ...
The code implements a **Variable Neighborhood Search (VNS)** algorithm for optimizing fuzzy clustering. It iteratively refines cluster centers (`v`) by generating random swaps between clusters and data points, using a fuzzy c-means (`f_cmeans`) sub-routine to update cluster memberships and objective values. The algorit...
def vns1(n, d, x, v, w, wt, tempv): it1, obj, t = 0, 0, 0 c = NUM_OF_CLUSTER t0 = MAX_CPU_TIME E = TERMINATION_THRESHOLD m = FUZZY_FACTOR kmax, nbiter, tt, objtmp, tt1 = 0, 0, 0, 0, 0 it = 1000 sc = np.zeros(50000) ind = np.zeros(n) tempv1 = np.zeros((c, d)) kmax = min(c, 10)...
def load_use_case_resources(current_file_dir: Path) -> typing.List[UseCase]: """ Load use case metadata resources Parameters ---------- current_file_dir: Directory of the current script Returns ------- The use cases resources object parsed to a dict """ resources_path = curr...
This function sets up resources by downloading models, configuring a Python virtual environment, and optionally applying Vela optimizations. It checks system requirements, manages cache settings, handles additional NPU configurations, and updates metadata. The output is the virtual environment path, ensuring all resour...
def set_up_resources( run_vela_on_models: bool = False, additional_npu_config_names: tuple = (), arena_cache_size: int = 0, check_clean_folder: bool = False, additional_requirements_file: Path = "" ) -> Path: """ Helpers function that retrieve the output from a command. ...
def add_emission(self, step): """ For every step and for every agent, the current emissions amount and allowance credits are recorded. whenever the "end of the month" is reached, the agents are given a fixed amount of credits. Amount of emissions are increased for every time step based o...
The code simulates a transaction process over time steps by adding emissions and credits, selecting buyers/sellers (sorted by price), and executing trades based on highest buyer/lowest seller prices. It uses different methods for agent selection and emission reduction, returns statistical results.
def do_magic(self, random_sel = False, em_red = True, plots = True): """ • add emission and potentially credits each step • select buyers and sellers • Buyers list sorted by max price • Sellers list sorted by ...
def _read(self, adr): if adr in self.memory.keys(): return self.memory[adr] return 0 def _parse_mode(self, opcode): return opcode % 1000 // 100, opcode % 10000 // 1000, opcode // 10000 def _op_add(self, modes): params = self._read_vals(self.ip + 1, 3) result = self._t...
The code executes an Intcode program by processing opcodes from memory. It reads the current instruction, parses the opcode and parameter modes, and performs corresponding operations (addition, multiplication, input/output, conditional jumps, comparisons, etc.). The loop continues until termination (opcode 99), invalid...
def run(self): while self.ip < len(self.memory): full_opcode = self._read(self.ip) opcode, modes = full_opcode % 100, self._parse_mode(full_opcode) if opcode == 1: self._op_add(modes) elif opcode == 2: self._op_mul(modes) ...
def sort_by_position(self): """ Sorts the list of players by their position. """ self.players.sort(key = lambda player: player.position) def betting_round(self, preflop = False, **kwargs): """ Starts a new betting round. If preflop is True, the players in the b...
This method initializes a new poker hand by rebuilding and shuffling the deck, dealing cards to each player, and conducting betting rounds. It starts with preflop betting, then progresses through community card reveals (flop, turn, river) with additional betting rounds, updating the game state until a winner is determi...
def new_hand(self, cards_per_player = 2, **kwargs): """ This method should be called at the start of every hand. It rebuilds the deck and shuffles it, then gives every player as many cards as given by the parameter "cards_per_player" (default is 2). The hole cards of each player...
def flush_check(card_list): """ Inputs: A reverse-sorted list of cards. Outputs: All cards of the flush suit if there is a flush \ (meaning there are at least 5 such cards) or an empty list otherwise. Note: The fact that more than just the 5 highest cards are returned is \ important fo...
The function `evaluate_holdem` determines the best 5-card poker hand from a 7-card list in Texas Hold'em. It checks for combinations like straight flush, flush, four of a kind, full house, and straight, prioritizing higher-ranking hands. It returns the name of the best hand and the corresponding 5 cards, leveraging Hol...
def evaluate_holdem(card_list): """ Inputs: A list of cards. Outputs: The name of the best 5-card hand one can make, as well as a list \ with the 5 cards. Note: This function only works for Hold'em as it makes a key assumptions \ which is true for 7 cards but not necessarily for 9: If ...
def load_training_images(output_size=None): suffix = '' if output_size is None else '_%d' % output_size images_npy_filename = os.path.join(train_img_dir, '%s%s.npy' % (train_image_npy_prefix, suffix)) if os.path.exists(images_npy_filename): images = np.load(images_npy_filename) else: im...
This function loads training images and their corresponding masks, then partitions the data into specified segments (num_partitions) for distributed training. It returns the designated partition (idx_partition) with an optional test split, enabling efficient data handling in machine learning workflows.
def load_training_data(output_size=None, num_partitions=5, idx_partition=0, test_split=0.): x = load_training_images(output_size=output_size) y = load_training_masks(output_size=output_size) return partition_data(x=x, y=y, k=num_partitions...
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 sample def build_tree(train, max_depth, min_size, n_features): #Building the tree involves creating...
The code implements a random forest algorithm by training multiple decision trees on bootstrapped samples of the training data. Each tree is built with specified parameters (max depth, min size, feature count), and predictions are aggregated via bagging. The function returns the ensemble predictions for the test set.
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, ro...
def sv_is_glonass(sv): return sv[0] == 'R' def sv_is_sbas(sv): return sv[0] == 'S' def sv_to_constell(sv): if sv[0] == 'G': return "GPS" elif sv[0] == 'E': return "GAL" elif sv[0] == 'C': return "BDT" elif sv[0] == 'J': return "QZSS" else: return None ...
The code processes navigation data from specified directories, extracts Keplerian orbital parameters for supported satellites, converts them to Earth-Centered Earth-Fixed (ECEF) coordinates, calculates elevation/azimuth angles relative to a reference point, and writes results to text files, excluding unsupported GNSS s...
def main(argv): if len(argv) == 0: print("[test_pool_dir]") return 0 base_dir = argv[0] debug = len(argv) > 1 supported_rev = ["V2", "V3"] for rev in os.listdir(base_dir + "/NAV"): if not(rev in supported_rev): continue for fp in os.listdir...
def get_vectorizer(model_name): """Get the vectorizer based on the model name Parameters: model_name (str): name of the embedding model Returns: vectorizer (function): function to vectorize the data """ if model_name in list_model_spacy: vectorizer = lambda word: nlp(word)....
The main task of the code is to generate 2D projections of word embeddings using various manifold learning techniques (e.g., t-SNE, UMAP) and visualize them. It loads or processes input data, applies dimensionality reduction models, creates multi-subplot visualizations with clustering information, and saves the resulti...
def manifold_plotting(active_savepath, embedding_model_name, pickle_data): """Plot the manifold Parameters: active_savepath (object): active savepath embedding_model_name (str): name of the model pickle_data (dict): data to process and plot """ CATEGORY_TO_NAME = CONFIG["MANIFO...
def prepare(self): self._validate_constructor() self.load() self.preprocess() def compress(self): self.approximation = approximate_dataset( self.adata, self.celltype_column, self.additional_groupby_columns, ) def store(self): config = s...
The main task of the code is to execute a sequence of operations when the object is called. It first prepares necessary data or resources via `self.prepare()`, then compresses the data or processes it through `self.compress()`, and finally stores the result or processed data using `self.store()`. This structure enables...
def __call__(self): self.prepare() self.compress() self.store()
def LoadBackImage(absPath): print('[INFO] Loading BackImage') liste = glob.glob(absPath + "/res/backimage.*") for files in liste: extension = files.split('backimage.')[1] if(extension == 'png'): print('[INFO] Extension : png') elif(extension == 'jpg'): print('[INFO] Extension : jpg\nConversion en png') d...
The main task of the code is to generate and process an image based on text content, using a background image and sound file. It creates an image, applies color focusing and processing, integrates sound effects, and saves the final output. The program allows user choices to display the image and enable verbose logging ...
def main(): ##### Initiation de l'environnement de travail absPath = os.path.abspath('.') try: os.mkdir(absPath + '/img') print('[INFO] Dossier img cree') except: print('[INFO] Dossier img existant') ##### Mise en memoire des variables print('[INFO] Programme Lance') text = open('res/textAPeindre.txt').r...
def LoadBackImage(absPath): print('[INFO] Loading BackImage') liste = glob.glob(absPath + "/res/backimage.*") for files in liste: extension = files.split('backimage.')[1] if(extension == 'png'): print('[INFO] Extension : png') elif(extension == 'jpg'): print('[INFO] Extension : jpg\nConversion en png') d...
The main task of the code is to process text, image, and audio data into a final visual output. It destroys UI elements, creates a directory, loads resources, and sequentially applies text generation, image processing, and sound integration functions. Progress bars track each step, and the result is stored in 'tableauF...
def Conversion(): ##### Destruction des pack fenetreParametresText.pack_forget() fenetreParametresImage.pack_forget() fenetreParametresSon.pack_forget() boutonConversion.pack_forget() ##### Initiation de l'environnement de travail absPath = os.path.abspath('.') try: os.mkdir(absPath + '/img') print('[INFO...
def proccess_data(data=[]): try: res = [] for d in data: message = d.get('text', '').lower().lstrip().rstrip() message = ' '.join(message.split()) if message: res.append({ 'text': d.get('text', ''), 'id': d.g...
The main task of the code is to parse input text, check a cache database for existing results, and if not found, use Rasa to generate an answer. It processes input data, checks for cached entries via a hash, and either returns cached results or queries Rasa, storing new responses in the database. Error handling and log...
def parse(): try: endpoint = '/parse' res = {} messages_ = proccess_data([ { 'text': request.get_json().get('text', ''), 'id': request.get_json().get('id', ''), } ]) messages_hash = messages_[0].get('hash', '') ...
def proccess_data(data=[]): try: res = [] for d in data: message = d.get('text', '').lower().lstrip().rstrip() message = ' '.join(message.split()) if message: res.append({ 'text': d.get('text', ''), 'id': d.g...
The function processes incoming messages by querying a Rasa AI model for responses, merges the results with original data, saves them to a cache, and returns a structured success response containing the processed messages. It handles JSON requests, logs data, and manages errors by returning appropriate error messages i...
def handle_messages(): try: endpoint = '/handle_messages' logging.info(request.get_json()) messages = request.get_json().get('messages', []) messages_ = proccess_data(messages) res_finall = [] for data in messages_: question = data.get('message', '') ...
def parse_url(url: Union[str, int]) -> str: """Takes something that may resemble a Schoo URL and turns it into the likely video id""" video_id = None if isinstance(url, int): video_id = str(url) log(f"Given number for extracting video id. Video id is {video_id}") elif isinstance(url, str...
The main task of the code is to download Schoo audio content as an MP4 file using ffmpeg, either via a provided URL or video ID. It parses command-line arguments, extracts a video ID from the URL, and either retrieves the course title (if specified) or downloads the video using an m3u8 link. The script returns 0 for su...
def main() -> int: parser = argparse.ArgumentParser( prog=PROG, description="Downloads Schoo audio into an mp4 file using ffmpeg, taking either a url, or a video id", ) parser.add_argument("url") parser.add_argument( "-t", "--title", action="store_true", h...
def log(msg: str, end="\n") -> None: utils.log(msg, end=end, prog=PROG) def _send_openai_request( prompt_request: str, model: str = MODEL, temperature: float = TEMPERATURE, max_tokens: int = MAX_TOKENS, top_p: float = TOP_P, frequency_penalty: float = FREQUENCY_PENALTY, presence_penalty:...
The function `recurse_summary` generates a summary using OpenAI's API based on the input prompt, saves the result to a file with a dynamically generated name, and handles rate-limit errors by recursively retrying the request. It validates the prompt, logs errors for empty inputs, and ensures output is stored in the spe...
def recurse_summary( prompt: str, chunk_idx: int, course_title: str, filename: str, output_path: str = "./", ) -> str: prompt = prompt.strip() if len(prompt) == 0: log( "Prompt was empty, which is an error. Returning nothing and not sending anything out to OpenAI" ...
def _stitch_summaries(summaries: list[str]) -> str: return "\n".join(summaries) def log(msg: str, end="\n") -> None: utils.log(msg, end=end, prog=PROG) def _send_openai_request( prompt_request: str, model: str = MODEL, temperature: float = TEMPERATURE, max_tokens: int = MAX_TOKENS, top_p: fl...
The function aggregates multiple course summaries into a meta-summary, uses OpenAI to generate a condensed version with 10-20 bullet points, saves the result to a file, and returns its path. It handles empty inputs and rate-limit errors by retrying after delays.
def summary_of_summaries(filename: str, summaries: list[str], course_title: str) -> str: """Stitches each of the summaries together into one meta-summary and requests OpenAI summarize that instead returns the path to the written output summary """ stitched = _stitch_summaries(summaries).strip() if l...
def _get_summarized_filename(filename: str, chunk_number: int) -> str: base = utils.get_basename_no_ext(filename) return f"{base}_{chunk_number}_summary.txt" def log(msg: str, end="\n") -> None: utils.log(msg, end=end, prog=PROG) def recurse_summary( prompt: str, chunk_idx: int, course_title: st...
The function processes token chunks of a Japanese course transcript, generating summaries via OpenAI. It saves summaries to a folder, skipping existing files if `overwrite` is false. Each summary is formatted with the chunk index, total chunks, and course title. The function returns a list of generated summaries.
def send_summary_prompts( chunks: list[list[int]], course_title: str, filename: str, overwrite: bool = True, output_path: str = "./", ) -> list[str]: """Given a list chunked tokens, submits each list to OpenAI individually and returns a summary of the contents Writes these summaries out to ...
def write_chunks_to_files( filename: str, overwrite: bool = True, output_path: str = "./" ) -> list[list[int]]: """Given a filename containing some tokens, split the file into individual lists of tokens that GPT-3 can access in a single request. Writes these lists back out to disk in numbered order. Ret...
This function processes a file by splitting it into chunks, generating summaries for each chunk, and combining them into an overall summary. It writes chunks to disk, handles single/multiple chunk scenarios, and optionally cleans up temporary files. The output is a consolidated summary of the input content, tailored to...
def summarizer_file( filename: str, course_title: str, overwrite: bool = False, cleanup: bool = False ) -> str: base_dir = utils.get_output_directory_path(filename) chunk_path = os.path.join(base_dir, "chunks") summary_path = os.path.join(base_dir, "summaries") chunks = write_chunks_to_files( ...
def aprint(self,msg,color="white"): cprint(msg, color=color, attrs=['bold']) def helper_checkEndSensors(self): self.aprint("--> Checking End Sensors..","yellow") if self.helper_checkModules(): cprint("Check the IO modules","red") return False for drive in CONFIG.D...
The main task of the code is to perform a functional test by verifying the proper operation of end sensors and brakes. It checks if both components work correctly using helper methods, prints error messages in red if they fail, and asserts their functionality with descriptive failure messages. The test ensures system c...
def test_functional(self): self.aprint("--> Starting the Functional Test..","yellow") res_EndSensor = self.helper_checkEndSensors() if not res_EndSensor: self.aprint("End Sensors are not working!!", "red") self.assertTrue(res_EndSensor, msg="End Sensors are not working!!") ...
def get_series_data(single_csv_path, all_RGBs_path): series_num, TE = read_TE_and_series_from_ps(single_csv_path) # series = STRING, TE = STRING # first get the TE ans series number corresponding to this csv # these values can be found in the ps file series_description = 'current series: TE =' + '...
The function `add_data_to_each_series` processes each CSV file from `all_csvs_path`, merges patient information, series data (TE, location), and MRS results from corresponding files, and saves this combined data into a new CSV file named with patient ID, series number, and TE. It updates the `exam_dict` with series-spe...
def add_data_to_each_series(all_csvs_path, all_RGBs_path, exam_dict, patient_info_values): #is_fetal = patient_info_values[-1] is_fetal = exam_dict[Strings.PATIENT_INFO][Strings.IS_FETAL] for single_csv_path in all_csvs_path: # go through all the CSVS (one csv for each series) and add the data for the...
def sharpen_image(self, image): image = cv2.cvtColor(image, cv2.COLOR_BGR2BGRA) hpf = image - cv2.GaussianBlur(image, (21, 21), 3) + 127 # Normalize images to the range [0, 1] image_norm = image.astype(float) / 255.0 hpf_norm = hpf.astype(float) / 255.0 ...
The code processes an image by sequentially applying sharpening, noise switching, frame processing, wave effects, blurring, and additional sharpening to enhance clarity, reduce noise, and add visual stylization.
def processAll(self,image): image = self.sharpen_image(image) image = self.switchNoise(image) image = self.processFrame(image) image = self.waves(image) image = self.waves2(image) image = self.blur(image) image = self.sharpen2(image) return image
def getCurrentOp(self, wire): if wire >= len(self.wires): raise Exception("Not a valid qbit") while len(self.wires[wire]) <= 0: if not self.increment(): break if len(self.wires[wire]) > 0: return self.wires[wire][0] return None def op_e...
The code validates and processes operations during elimination by checking if each operation in the list matches the expected operation and index, raising exceptions for invalid cases, then proceeding to the next operation.
def eliminateOp(self, op): for i,q in enumerate(op[1]): wireop,index = self.getCurrentOp(q) if not op_eq(wireop, op): raise Exception("Operation elimiation not valid") if index != i: raise Exception("Operation elimiation not valid") ...
def get_game_size(): """ () -> int Return the valid tic-tac-toe game board size entered by game player. (No docstring example given since the function depends on user input.) """ prompt_message = ('\nEnter desired game board size (an int between 1 and ' + str(MAX_BOARD_SIZE)...
The main task of the code is to enable a user to play a tic-tac-toe game against a computer program. It alternates turns between the human player and the computer, updates the game board with each move, checks for a win or draw, and displays the result. The game continues until a player wins or the board is full, with ...
def play_tictactoe(): """ () -> None Play a single game of tic-tac-toe, with one player being the program user and the other player being this computer program. (No docstring example given since the function indirectly depends on either user input or randomly generated numbers.) """ # Ini...
def load_rating(args): print('reading rating file ...') # reading rating file train_file = '../data/' + args.dataset + '/train_data' eval_file = '../data/' + args.dataset + '/eval_data' test_file = '../data/' + args.dataset + '/test_data' if os.path.exists(train_file + '.npy') and os.path.exist...
The main task of the code is to load and preprocess training, evaluation, and test datasets, along with knowledge graph (KG) information and user interaction history. It retrieves user-item ratings, constructs KG elements (entities, relations, adjacency matrices), adjusts user history, and returns all components for do...
def load_data(args): train_data, eval_data, test_data, user_history_dict, n_user, n_item = load_rating( args) n_entity, n_relation, kg, adj_enlc, adj_relc, adj_engb = load_kg( args, n_item) user_history_dict = fix_userhist(args, user_history_dict) print('Loaded data') return train_da...
def entity_agg(self, entity_his, relation_his, user_global_em): batch = entity_his[0].shape[0] # (batch * n_memories, 1), (batch * n_memories, neighbor) entity_his = [i.reshape([-1, i.shape[-1]]) for i in entity_his] if relation_his is not None: relation_his = relation_his.re...
This code implements a recommendation model that combines user and item embeddings using a gating mechanism to integrate local and global item representations. It computes scores for positive and negative items via attention mechanisms, calculates recommendation loss, and incorporates knowledge graph regularization los...
def forward(self, user_indices, entity_lc, relation_lc, entity_gb, kg): # set_trace() user_global_em = self.user_embedding( user_indices) # (batch, embeddings) user global embedding entity_hislc_em = self.entity_agg( entity_lc[0], relation_lc[0], user_global_em) # loca...
def hard(top,arr): x = random.randrange(1,6) if(x==1): arr = [[0,3,0,0,0,1,5,0,0], [0,0,0,5,0,0,0,8,4], [0,0,5,0,0,7,0,6,0], [0,0,0,0,0,0,0,0,0], [0,8,0,2,0,0,0,7,0], [0,0,0,8,5,0,0,0,9], [0,0,3,0,9,4,0,0,7], [0,0,4,0,0,0,0,0,8], [5,0,6,0,...
This function creates and positions buttons on a GUI window for interacting with a maze application. It generates buttons labeled "Acak" (Hard), "Selesaikan" (Solve), and "Manual" to control maze generation, solving, and manual input. Buttons are placed at specific coordinates with defined sizes, linking to functions l...
def createButtons(top,maze): # button_easy = Button(top, text="Easy", justify='left', default='active',bg="#ffaaa7", command = lambda: easy(top,maze),font=("Cambria",12,BOLD)) # button_medium = Button(top, text="Medium", justify='left', default='active',bg="#fed049", command = lambda: medium(top,maze),font=("Ca...
def createRow(canvas): i,j=38,79 p=38 q=299 for m in range(10): if m % 3 == 0 : canvas.create_line(i,j,p,q,width=3.5) else: canvas.create_line(i,j,p,q,width=1) i+=30 p+=30 def createCol(canvas): i,j=38,79 p,q=308,79 for m in range(10): ...
This code creates a Sudoku solver GUI using Tkinter. It sets up a window with a canvas for grid lines, input fields for numbers, buttons (including a quit button), and displays instructions. The maze parameter is passed to the createButtons function, suggesting integration with a maze-solving algorithm, though the GUI ...
def createGUI(maze): top = Tk() top.title("Sudoku Solver") canvas = Canvas(top,height=400, width =450, bg="#91091e") canvas.create_text(160,40, text="Masukkan angka yang kamu inginkan", fill="white", font=("Cambria",13,BOLD)) canvas.create_text(160,60, text="atau pilih masukan acak!", fill="white", ...
def extract_peaks(which_cam, image, ntraps): """ Finds the value & location of each Gaussian Peak. Given a matrix of pixel values, locates each trap peak and records its position along x-axis and pixel value. Parameters ---------- which_cam : bool *True* or *False* selects Pre- or Post...
(The function fits 1D Gaussian curves to the x-axis of an image to determine peak values, averaging results over multiple iterations. It uses camera data, extracts peaks, performs curve fitting, and returns the averaged peak values as an array. It handles errors by returning an array of ones if fitting fails.)
def analyze_image(which_cam, cam, ntraps, step_num=0, iterations=20): """ Fits 1d Gaussians across image x-axis & returns the peak values. Parameters ---------- which_cam : bool `True` or `False` selects Pre- or Post- chamber cameras respectively. cam : :obj:`instrumental.drivers.cameras.uc...
def _run_cam(self, which_cam=None): """ Fires up the camera stream (ThorLabs UC480) Parameters ---------- which_cam : bool Chooses between displaying the Pre- or Post- chamber ThorCams. Passing nothing returns a camera object for silent use (not displaying). ...
(The code stabilizes laser trap intensities by iteratively adjusting waveform magnitudes to achieve uniform power distribution across traps. It uses camera feedback to analyze trap powers, calculates correction rates based on power variance, and updates magnitudes until intensities converge to homogeneity. The function...
def stabilize_intensity(self, wav, cam=None, which_cam=None): """ Balances power across traps. Applies an iterative update to the magnitude vector (corresponding to the trap array) upon image analysis. Converges to homogeneous intensity profile across traps. Example ---...
def any_cert_to_x509_pem_chain(cert: bytes) -> bytes: """Convert any certificate to a concatenated list containing one or more x509 PEM certificates.""" if cert.find(b"-----BEGIN CERTIFICATE") != -1: # PEM encoded X509 Format return cert if cert.find(b"-----BEGIN PKCS7") != -1: ...
The main task of the code is to retrieve and yield each certificate in a chain, starting from the provided certificate, then recursively obtaining its issuer's certificate via URI until reaching the root certificate with no further issuers. It processes certificates in PEM format, splitting chains into individual certi...
def get_certificate_chain(certificate: bytes) -> Iterator[bytes]: while True: # Make sure the certificate is in x509 PEM format. Possibly with # multiple certs pem_chain = any_cert_to_x509_pem_chain(certificate) # Iterate over the pem_chain. for certificate in x509_chain_to_i...
def Darknet(name=None): x = inputs = Input([None, None, 3]) x = DarknetConv(x, 32, 3) x = DarknetBlock(x, 64, 1) x = DarknetBlock(x, 128, 2) # skip connection x = DarknetBlock(x, 256, 8) # skip connection x = DarknetBlock(x, 512, 8) x = DarknetBlock(x, 1024, 4) return tf.keras.Model(i...
This code defines a YOLOv3 object detection model using Keras. It creates a neural network with an input layer, Darknet backbone, convolutional layers, and a YOLO output head. The model processes input images of specified size and channels, outputs detection results for 80 classes, and returns a Keras Model instance na...
def YoloV3(size=None, channels=3, classes=80, training=False): x = inputs = Input([size, size, channels], name='input') x = Darknet(name='yolo_darknet')(x) x = YoloConv(512, name='yolo_conv_0')(x) output = YoloOutput(512, classes, name='yolo_output')(x) return Model(inputs, output, name='yo...
def call_img(img_path): #select_image() img = cv2.imread(img_path) img10=cv2.imread(img_path) gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Convert to RGB bfilter = cv2.bilateralFilter(img, 50, 100,50) edged = cv2.Canny(bfilter, 30, 200) img=cv2.cvtColor(edged, cv2.COLOR_BGR2RGB) ...
The main task of the code is to open an image file, update a counter and data storage with the new image, copy the image to a designated directory, and trigger image processing functions. It uses global variables to track the image path and counter, loads/saves data via pickle, and handles file operations for image man...
def open_file(): global img_path filetypes = ( ('text files', '*.png;*.jpg;*.jpeg' ''), ('All files', '*.*') ) img_path = fd.askopenfilename( title='Open a file', initialdir='/', filetypes=filetypes) print("path :=====> ",img_path) ...
def call_img(img_path): #select_image() img = cv2.imread(img_path) img10=cv2.imread(img_path) gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Convert to RGB bfilter = cv2.bilateralFilter(img, 50, 100,50) edged = cv2.Canny(bfilter, 30, 200) img=cv2.cvtColor(edged, cv2.COLOR_BGR2RGB) ...
The function processes user clicks on historical images by setting the image path, invoking image processing (`call_img`), and recognizing handwritten text. It temporarily stores the path globally and includes conditional logic for directory checks (inactive due to `if False`). Primary tasks: image path management, ima...
def Image_history_click(event, path): """ Function which run when user click on any history related image """ global Open_image_path # Set Image path Open_image_path = path print("path is: ",path) # Hide Option window # Window.withdraw() #infer(model,pt+nm+".png") call_img(path) ...
def pushIntoVisitedWays(way, parentWay = ""): # Appends a new VisitedWay to the visitedWay Array global visitedWays # "new" visited way should not already exists in array (no duplicates) if not any(way in visitedWay for visitedWay in visitedWays): if parentWay != "": # check if parent is given ...
This function searches for a route from a starting way to an ending way using a graph traversal algorithm. It utilizes a SQL database to retrieve adjacent ways, tracks visited nodes, and iteratively explores connections until the end way is found. Once the end way is located, it constructs and returns the route.
def searchRoute(startWay, endWay): # Main global sql global visitedWays global endFound sql = SqlHandler(dbPath, osmPath) visitedWays = [] endFound = False counter = 0 sideWays = sql.getSideWaysOfWay(startWay) pushIntoVisitedWays(startWay) checkSideWaysOfWay(startWay, ...
def createDatabase(path): print("Generate database structure") conn = sqlite3.connect(path) cur = conn.cursor() cur.execute('''CREATE TABLE "nodes" ( "id" INTEGER NOT NULL UNIQUE, "lon" TEXT NOT NULL, "lat" TEXT NOT NULL, PRIMARY KEY("id") );''') cur.execute('''CREATE TABLE "ways" ( "...
The code initializes a database by creating a connection, importing OSM data into SQL tables, processing way-side and junction relationships, and finalizing the setup. It handles geospatial data transformation and database schema population for further analysis or querying.
def initSql(path, osmPath): print("Initializing database. This may take a while.") conn = createDatabase(path) parse_osm_to_sql(conn, osmPath) parse_way_sideWay_junction(conn) print("Done: Initializing database")
def _absolute_path(self, dirname, filename, extension=''): return '{}/{}{}'.format(self._paths(dirname), filename, extension) def _rename_input_files(self): prefix = 'original' for filename in os.listdir(self._paths('in')): old_path = self._absolute_path('in', filename) n...
The main task of the code is to perform color transfer between source and target images using the ColorTransfer class, save results, rename input files, generate a consensus file, and handle errors during execution. It processes configurations from self._input_config, applies color transfer with optional parameters (cl...
def main(self): color_transfer = ColorTransfer() for entry in self._input_config: print(Flag().task_started.format(entry['source'] + ' - ' + entry['target'])) source = self._absolute_path('in', entry['source']) target = self._absolute_path('in', entry['target']) ...
def _paths(self, key): return { 'datadir': '{}', 'in': '{}/in', 'conf': '{}/input-config.yml', 'out': '{}/out', 'json': '{}/out/output.json' }[key].format(self._datadir) def _is_supported_file(self, filename): return ( os.path.isfile(se...
The main task of the code is to prepare a data directory by creating 'in' and 'out' subdirectories, identifying supported files in the original data directory, and moving those files to the 'in' directory using system commands. This sets up a structured file organization for subsequent processing tasks.
def _prepare_datadir(self): datadir_content = os.listdir(self._paths('datadir')) os.mkdir(self._paths('in')) os.mkdir(self._paths('out')) for filename in [ f for f in datadir_content if self._is_supported_file(f) ]: subprocess.call([ 'mv', self._absolute_path('datadir', filen...
def contribute_data(f, cli_tok, osc_url, json_des_path=""): json_data, tok = get_json_data(f, cli_tok, "contribute") res = validate_fields("contribute", json_data) if res == -1: print("Please correct the errors and resubmit") return -1 out = json.dumps(json_data) url = osc_url + DA...
The code processes command-line arguments for dataset operations (contribute, query, update) on an Open Science Chain (OSC) portal. It validates required parameters like template files, authentication tokens, and user identifiers (oscid/email). The script directs operations to respective functions, switches between dev...
def main(): parser = argparse.ArgumentParser(formatter_class=RawTextHelpFormatter) parser.add_argument( "operation", help="""'contribute', 'query' or 'update'.\n For update, first perform a query and then modify the saved yaml file.""", ) parser.add_argument( "--template"...
def runModel(path,batch_size,epochs): history = 0 animalCheck = os.path.isfile("data.npy") labelCheck = os.path.isfile("labels.npy") if not animalCheck or not labelCheck: train_image_names = filesall(path) data, labels = readimages(train_image_names) data, labels, le, res = norma...
The main task of the code is to train a machine learning model using the provided dataset, evaluate its performance on test data via a classification report, generate a confusion matrix with normalization, and visualize training history and model accuracy through graphs. It processes predictions, compares them against ...
def startTrain(): global historyGlobal,y_testGlobal,x_testGlobal,leClasses #makeNPYFiles("Dataset") model = runModel(dataset,batch,epochs) predictions = model.predict(x_testGlobal, batch_size=1) print(classification_report(y_testGlobal.argmax(axis=1), predictions.argmax(axis=1), target_names=list(le...