dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def tidy_life_expectancy(life_expectancy_df): life_expectancy_df.columns = life_expectancy_df.columns.str.lstrip() life_expectancy_df.columns = life_expectancy_df.columns.str.rstrip() life_expectancy_df.rename(columns = {'HIV/AIDS':'HIV/AIDS Deaths'}, inplace = True) life_expectancy_df.rename(columns =...
The code cleans a life expectancy dataset by reading the data, tidying it, converting inaccuracies to NaN, melting the data, making a deep copy, further cleaning, detecting outliers, and saving the cleaned data to a new CSV file. The main task is to preprocess and clean the dataset for analysis by handling missing/inac...
def clean_data(**kwargs): life_expectancy_df = pd.read_csv('c/Users/ahmed/data/Life Expectancy Data.csv') tidy_life_expectancy_df = tidy_life_expectancy(life_expectancy_df) corrected_life_expectancy_df = turn_inaccurate_to_nan(tidy_life_expectancy_df) life_expectancy_df_melted = correct_data(corrected_l...
def log_info(string: str) -> None: """Prints STR to STDERR if the DEBUG environment variable is set.""" if "DEBUG" in os.environ: print(f"[+] {string}", file=sys.stderr) def get_ld_paths() -> List[str]: """ Vendored from https://github.com/albertz/system-tools/blob/master/bin/find-lib-in-pat...
The function prepares an environment to run OpenGL/CUDA programs on Nvidia GPUs by isolating necessary dynamic shared objects (DSOs) into a cache, generating configuration files, patching runpaths, and setting environment variables like LD_LIBRARY_PATH, __GLX_VENDOR_LIBRARY_NAME, and __EGL_VENDOR_LIBRARY_DIRS. It ensur...
def nvidia_main( cache_dir: str, dso_vendor_paths: List[str], print_ld_library_path: bool = False ) -> Dict: """Prepares the environment necessary to run a opengl/cuda program on a Nvidia graphics card. It is by definition really stateful. Roughly, we're going to: 1. Setup the nvidia cache directo...
def log_info(string: str) -> None: """Prints STR to STDERR if the DEBUG environment variable is set.""" if "DEBUG" in os.environ: print(f"[+] {string}", file=sys.stderr) def get_ld_paths() -> List[str]: """ Vendored from https://github.com/albertz/system-tools/blob/master/bin/find-lib-in-pat...
The main task of the code is to configure a cache directory, retrieve shared libraries (DSOs) from a specified path or system load paths, process them with `nvidia_main`, log execution time, and optionally execute a NIX binary with updated environment variables.
def main(args): start_time = time.time() home = os.path.expanduser("~") xdg_cache_home = os.environ.get("XDG_CACHE_HOME", os.path.join(home, ".cache")) cache_dir = os.path.join(xdg_cache_home, "nix-gl-host") os.makedirs(cache_dir, exist_ok=True) log_info(f'Using "{cache_dir}" as cache dir.') ...
def get_records_transciptions_summarizes() -> tuple[list[Path], ...]: records = find_all_files_in_folder(RECORDS_FOLDER_PATH) transcriptions = find_all_files_in_folder(TRANSCRIPTIOS_FOLDER_PATH) summarizes = find_all_files_in_folder(SUMMARIZES_FOLDER_PATH) return records, transcriptions, summarizes def...
The main task of the code is to ensure all records have corresponding transcriptions and summarizes. It first checks if transcriptions exist for each record, generating them if missing. Then, it verifies if summarizes exist for each transcription, creating them if absent. This process guarantees complete transcription ...
def summarize_all_records(): records, transcriptions, summarizes = get_records_transciptions_summarizes() records_names, transcriptions_names, summarize_names = ( get_names_of_records_transciptions_summarizes( records, transcriptions, summarizes ) ) # make trascripts from all...
def consensus(self): """ when this node find a node that have a longer and safe chain, replace that with local chain :returns: boolean if a longer-chain node exist :rtype: boolean """ nodes = self.nodes new_chain = None max_length = len(self.c...
The function creates a new block in a blockchain by validating the provided proof against the previous block's proof and hash. If valid, it generates a Merkle root from transactions, constructs the block with metadata, adds it to the chain, and resets transaction memory. Returns False if consensus fails or validation f...
def new_block(self, proof): """ add new block to chain with validation layers :param proof : a random nunce founded in proof_of_work function :type proof : int :returns : False if can not create block :rtype: boolean """ if self.consens...
def update_init(): url = "https://github.com/H4CKY54CK/flair-selector/archive/master.zip" wgetit(url, 'flairstuffs.zip') unarchit('flairstuffs.zip') images = r"flairstuffs\flair-selector-master\images" if os.path.exists('images'): shutil.rmtree('images') shutil.move(images, 'images') ...
The main task of the code is to automate an update process for a project, including installing dependencies, locating and decrypting image files, merging directories, generating sprites, and uploading updated assets to a Reddit subreddit stylesheet. It ensures required tools and files are present, handles directory sea...
def update(args=None): if miscversion != '2.0.1': subprocess.run('pip install https://github.com/h4cky54ck/misctools/archive/master.zip') if subprocess.getoutput('spriteit -V') != 'v2.0.1': print("The automatic install feature has failed. Please upgrade your `misctools` package via `pip ...
def infer_spatial_distribution( data, data_covariance, prior, spatial_dimensions, input_dyad, verbose ): data_precision = invert_covariance(data_covariance, input_dyad) # shift residuals to weighted mean: demean if verbose: print("...demean residuals") data_demean = _demean_data(data, data_...
The function characterizes the spatial distribution of input data by estimating statistical parameters (likelihood, posterior) and deriving key properties like maximum likelihood (ML) and maximum a posteriori (MAP) locations, covariance structures, and moments (mean, integral covariance). It combines Bayesian inference...
def characterize_spatial_distribution( data, data_covariance, prior=xr.DataArray(1), # can be an xarray structure spatial_dimensions=["x", "y", "z"], input_dyad=["data", "data_T"], # specifies input axes for covariance output_dyad=["space", "space_T"], # specifies output axes for covariance ...
def get_ml(): # ml = main_link home = get_page(base_url) ml_tag = home.find("a", class_="EditorialPlacement__Link-sc-1kp33kw-2 eCAFYK") return ml_tag["href"] def get_mt(): # mt = main_title home = get_page(base_url) mt_div = home.find("div", class_="EditorialPlacement__Title-sc-1kp33kw-1 bMPUfx"...
The main task of the code is to retrieve and return three pieces of information: a link, a title, and an article. The function `get_main()` calls three separate functions (`get_ml()`, `get_mt()`, and `get_ma()`) to fetch these elements and combines them into a tuple for output. This structure allows for modular data co...
def get_main(): link = get_ml() title = get_mt() article = get_ma() return link, title, article
def get_ol(): # ol = other_links home = get_page(base_url) ol_par = home.find_all('a', class_="EditorialPlacement__Link-sc-1kp33kw-2 kzXgsm") ol = [link["href"] for link in ol_par] return ol def get_ot(): # ot = other_titles home = get_page(base_url) ot_divs = home.find_all('div', class_="Ed...
The function `get_others` retrieves three sets of data by calling `get_ol` (links), `get_ot` (titles), and `get_oa` (articles), then returns them as a tuple. Its main task is to collect and combine these data elements for further processing or output.
def get_others(): links = get_ol() titles = get_ot() articles = get_oa() return links, titles, articles
def _get_cordinates(self): idx = np.random.choice(np.prod(self.dims),(self.npredator + self.nprey), replace=False) return np.vstack(np.unravel_index(idx, self.dims)).T def _set_grid(self): self.grid = np.arange(self.BASE).reshape(self.dims) # Mark agents in grid # self.grid[self....
The main task of the code is to reset the environment's state by initializing variables, repositioning predators and prey, updating the grid, and returning the initial observation for the episode. It prepares the environment for a new simulation cycle by clearing previous data, setting new coordinates, and generating t...
def reset(self): """ Reset the state of the environment and returns an initial observation. Returns ------- observation (object): the initial observation of the space. """ self.episode_over = False self.reached_prey = np.zeros(self.npredator) # L...
def _get_document_for_url(self, url): content = self._get_content_for_url(url) return lxml.html.document_fromstring(content) def _get_auth_data(self): result = self._get_request_for_url( parse.urljoin( self.BASE_URL_SECURE, '/user/auth_token' ...
This code handles user login by scraping a login page to extract security tokens, submitting credentials via POST with those tokens, verifying the response for errors, and storing authentication data and user metadata if successful.
def _login(self): login_url = parse.urljoin(self.BASE_URL_SECURE, self.LOGIN_PATH) document = self._get_document_for_url(login_url) authenticity_token = document.xpath( "(//input[@name='authenticity_token']/@value)[1]" )[0] utf8_field = document.xpath( "(/...
def _get_document_for_url(self, url): content = self._get_content_for_url(url) return lxml.html.document_fromstring(content) def _get_url_for_exercise(self, date, username): return parse.urljoin( self.BASE_URL, 'exercise/diary/' + username ) + '?date=%s' % ( ...
This function retrieves exercise data for a specified date. It accepts either a datetime/date object or three integers (year, month, day) to construct a date. It then fetches the corresponding exercise URL, retrieves the document, extracts exercise goals, and returns the processed exercise data.
def _get_exercises(self, *args, **kwargs): if len(args) == 3: date = datetime.date( int(args[0]), int(args[1]), int(args[2]), ) elif len(args) == 1 and isinstance(args[0], datetime.date): date = args[0] else: ...
def _get_document_for_url(self, url): content = self._get_content_for_url(url) return lxml.html.document_fromstring(content) def _get_url_for_measurements(self, page=1, measurement_id=1): return parse.urljoin( self.BASE_URL, 'measurements/edit' ) + '?page=%d&type...
The function retrieves measurements of a specified type (e.g., 'Weight') between given date bounds. It fetches data from a URL, filters entries by the specified date range, and returns an ordered dictionary of measurements. If no bounds are provided, it defaults to the last 30 days. It handles date order reversal for u...
def get_measurements( self, measurement='Weight', lower_bound=None, upper_bound=None ): """ Returns measurements of a given name between two dates.""" if upper_bound is None: upper_bound = datetime.date.today() if lower_bound is None: lower_bound = upper_bound...
def _get_document_for_url(self, url): content = self._get_content_for_url(url) return lxml.html.document_fromstring(content) def _get_url_for_measurements(self, page=1, measurement_id=1): return parse.urljoin( self.BASE_URL, 'measurements/edit' ) + '?page=%d&type...
The main task of the code is to update a user's measurement (e.g., weight) on MyFitnessPal by parsing measurement IDs from a webpage, constructing a POST request with the correct data structure, and submitting it to the server. It validates input, maps measurements to their IDs, and ensures only the specified measureme...
def set_measurements( self, measurement='Weight', value=None ): """ Sets measurement for today's date.""" if value is None: raise ValueError( "Cannot update blank value." ) # get the URL for the main check in page # this is left in bec...
def _get_document_for_url(self, url): content = self._get_content_for_url(url) return lxml.html.document_fromstring(content) def _get_url_for_measurements(self, page=1, measurement_id=1): return parse.urljoin( self.BASE_URL, 'measurements/edit' ) + '?page=%d&type...
The function retrieves a list of measurement IDs by fetching a document from a specific URL, extracting the IDs from the document, and returning them as options.
def get_measurement_id_options(self): """ Returns list of measurement choices.""" # get the URL for the main check in page document = self._get_document_for_url( self._get_url_for_measurements() ) # gather the IDs for all measurement types measurement_ids = s...
def _get_document_for_url(self, url): content = self._get_content_for_url(url) return lxml.html.document_fromstring(content) def _get_url_for_date(self, date, username): return parse.urljoin( self.BASE_URL, 'food/diary/' + username ) + '?date=%s' % ( ...
The main task of the code is to generate a `Day` object containing meal, goal, and completion data for a specified date. It accepts either three integers (year, month, day) or a `datetime.date` instance, fetches associated data from a document, and lazily loads additional details like notes, water intake, and exercises...
def get_date(self, *args, **kwargs): if len(args) == 3: date = datetime.date( int(args[0]), int(args[1]), int(args[2]), ) elif len(args) == 1 and isinstance(args[0], datetime.date): date = args[0] else: ...
def getCuisineAmounts(recipes): cuisineCounts = dict() for recipe in recipes: cuisine = recipe.get("cuisine") if cuisine in cuisineCounts: cuisineCounts[cuisine] += 1 else: cuisineCounts[cuisine] = 1 return cuisineCounts def getUniqueIngredients(recipes): ...
The function constructs a decision tree node by selecting the ingredient with the highest information gain to split recipes, recursively building branches for subsets of recipes, and creating leaf nodes when only one cuisine remains or no further splits are possible. It introduces feature randomness if part of a forest...
def makeDecisionTree(self, recipes): cuisineCounts = getCuisineAmounts(recipes) uniqueIngredients = getUniqueIngredients(recipes) # introduce feature randomness if this is a forest decision tree if self.inForest: uniqueIngredients = cuisineCountsWithFeatureRandomness(uniqueI...
def _process_data(self, data): inputs = data["input_tensors"].to(self.device) masks = data["mask_tensors"].to(self.device) targets = data["gt_tensors"].to(self.device) # guidances = self._get_edge_guidances(targets).to(self.device) if 'edge' in data['guidance'] else None guidance...
The main task of the code is to train a model for one epoch by iterating through batches, computing combined losses (non-GAN, GAN spatial/temporal), updating generator and discriminator parameters, tracking metrics, and logging results. It also handles validation/testing and adjusts the learning rate.
def _train_epoch(self, epoch): """ Training logic for an epoch :param epoch: Current training epoch. :return: A log that contains all information you want to save. Note: If you have additional information to record, for example: > additional_log = {"...
def info(self): self._info_general() if self.username != "root": if self.juju_manager.is_installed(): self.login() print() self._info_juju() def interview(self): # interview print("run interview ...") if os.path.exists(self.interview_...
The code's main task is to orchestrate a preparation process by sequentially gathering information, conducting interviews, generating content, and building the final output. Each method call (info, interview, generate, build) likely handles distinct stages of data collection, processing, and construction, culminating i...
def prepare(self): self.info() self.interview() self.generate() self.build()
def delete_booking(): #This one is self explanatory, it deletes the booking from the database # Delete the selected booking from the database conn = dbfunc.getConnection() if conn != None: try: # Retrieve the user ID and booking details from the form data user_id = int(r...
The main task of the code is to handle user requests for viewing, editing, or deleting bookings. It retrieves booking data from a database, processes form submissions for edits/deletions, and renders the appropriate HTML templates (bookingView.html or editBooking.html) with dynamic data like bookings, user IDs, and ale...
def bookingView(): # Check if message and alert_type query parameters are set message = request.args.get('message') alert_type = request.args.get('alert_type') #This lets the user view their bookings if request.method == 'POST': print('POST') user_id = int(request.form.get('user_i...
def _place_char(self, pos: tuple[int, int], char: str) -> None: self.map[pos[0], pos[1]] = char def get_illuminated(self, bulb: tuple[int, int]) -> list[tuple[int, int]]: dirs = [[bulb]] + [self._get_line(bulb, d) for d in DIFFS] return list(itertools.chain.from_iterable(dirs)) def _is_bulb(self...
The main task of the code is to place a bulb at the specified position and optionally illuminate adjacent cells if `show_rays` is True. It first places a bulb character, then iterates over illuminated cells, placing an illumination marker on non-bulb cells to visually represent light spread.
def place_bulb(self, bulb: tuple[int, int], show_rays: bool = False) -> None: self._place_char(bulb, BULB) if show_rays: for illuminated in self.get_illuminated(bulb): if not self._is_bulb(illuminated): self._place_char(illuminated, ILLUMINATED)
def proc_update(self): """Checks current processing state. """ status_lists, total = self.u.pooled_status(self.r, 'Automator:proc_status') # For now, wait for ALL nodes to complete if 'idling' not in status_lists: # Need this temporarily since all states not known ye...
The code initializes an automator that listens to Redis channels for VLASS tracking, processing, and recording updates. It subscribes to a channel, checks initial system states (processing/recording/VLASS tracking), and reacts to incoming messages like 'vlass-track', 'rec_update', and 'proc_update' to update states dyn...
def start(self): """Start the automator. Actions to be taken depend on the incoming observational stage messages on the appropriate Redis channel. """ self.u.alert('Starting up...') self.ps = self.r.pubsub(ignore_subscribe_messages=True) self.u.alert('Listen...
def forward_propagation(self, X) -> (np.ndarray, list): """ Does forward propagation. :param X: input data :type X: numpy array (k,m) :return: network's output and cached intermediate results """ cache_results = [] layers_amount = len(self.weights) ...
The code trains a deep neural network for 20,000 generations using forward and backward propagation, updating weights iteratively. It records training loss, calculates train/test accuracy, and logs metrics like time and dataset sizes. Results are saved in a report, and loss curves and decision boundaries are plotted fo...
def train(self): """ Trains deep neural network. Saves the results and plots them. """ generations = 20000 losses = [] tic = time.time() for gen in range(generations): # Forward prop, backward prop and weights correction. A, cache_results ...
def generate_population(self, size): """ Method to generate and initialise the population """ population = [] for _ in range(size): genes = [0, 1] chromosome = [] for _ in range(len(self.items)): chromosome.append(random.choice(...
This function implements a genetic algorithm to evolve a population of chromosomes over multiple generations. It selects parent chromosomes, performs crossover to generate offspring, applies mutation with a 20% probability, and replaces the population with new offspring. After 100 generations, it identifies the best ch...
def geneticAlgo(self) -> list: population_size = 10 mutation_probability = 0.2 generations = 100 # generate a random population population = self.generate_population(population_size) parent1 = '' parent2 = '' # evolve the population for specified number o...
def Authentication(): print('You are attempting to log in as %s.'%(getpass.getuser())) Tries = 0 while Tries != 3: #checks password by refering to credential functions check. if Credentials.Check(getpass.getpass(prompt='Password Please: ', stream=None)) == True: audio.Audio_Func...
The code prompts the user to choose between 'access' (calling Authentication()) or 'create' (calling VoteNames() and recursively restarting the function). It validates input, handles 'exit', and loops until a valid choice is made. The main task is to direct user actions for list access or creation with input validation...
def UserOp(): WhereToGo = '' while WhereToGo.lower() != 'access' or WhereToGo.lower() != 'create': WhereToGo = input('Would you like to access the list or create(append) to an existing list?\nType Create or access. or exit ') if WhereToGo.lower() == 'access': Authentication() ...
def train_epoch( self, dataloader: DataLoader, epoch=0, log_every=-1, from_precomputed_set=False ): self.train() epoch_loss = 0 running_loss = 0 for i, (x, y_hat) in tqdm(enumerate(iter(dataloader)), total=len(dataloader)): # zero the parameter gradients ...
This function trains a machine learning model using specified datasets, with options for validation, early stopping, checkpoint saving, and data preprocessing. It iterates over epochs, computes training/validation losses, and terminates if validation performance stagnates. The trained model and loss history are saved a...
def train_model( self, n_epochs=-1, val_stop=5, save_path=".", save_every=-1, data_shuffle=True, data_num_workers=0, batch_size=16, from_precomputed_set=False, validate=False, data_set=None ): if data_set is None: ...
def draw_randomized_grid(self): angle = random.randrange(0, 90) lines = random.randrange(3, 10) offset_x, offset_y = random.randrange(0, 100), random.randrange(0, 100) fill_color = getRandomColor() width = random.randrange(1, 10) self.draw_grid(angle, lines, offset_x, off...
The main task of the code is to generate a randomized visual composition by sequentially drawing a randomized grid, adding random lines, inserting shapes, and placing random text. Each method contributes to creating a dynamic, varied visual layout, combining structured elements with unpredictable patterns and textual c...
def add_default(self): self.draw_randomized_grid() self.draw_random_lines() self.add_shapes() self.add_random_text()
def get_exp_val(self, input, part): self.qr = QuantumRegister(self.bn) # for Hadamard test qr_had = QuantumRegister(1) self.cr = ClassicalRegister(1) self.qc = QuantumCircuit(self.qr, qr_had, self.cr) # encode input self.encode_input(input) # get output st...
This function computes output values based on the input, using Qiskit's methods to calculate real and imaginary parts if enabled, combining them into a complex number scaled by gamma. Otherwise, it encodes the input and returns a gamma-scaled output. The core task is to generate a processed output value, either via Qis...
def outputs(self, input): if self.use_qiskit: real_part = self.get_exp_val(input, 'real') imag_part = self.get_exp_val(input, 'imag') return [[(real_part + 1j * imag_part) * self.gamma]] else: input_state = self.encode_input(input) return self....
def _tel_req(self, frame_words): self._log.debug('_tel_req') for f in self.queued_frames: frame_out = bytes(f, 'ascii') self._socket.send(frame_out) self._log.debug('SENT:\n\t{}'.format(frame_out)) # send EOT (end-of-transmission) ascii char (0x04) fr...
The function sends a heartbeat frame over a socket, receives and parses a server response, executes command-specific handlers based on the received command (e.g., $TEL, $RCF), and recursively resends the heartbeat if the 'keep_alive' flag is set. It logs sent/received data and handles exceptions, ensuring continuous co...
def _send_heartbeat_and_handle_server_request(self, heartbeat_frame): frame_out = bytes(heartbeat_frame, 'ascii') try: self._socket.send(frame_out) self._log.debug('SENT:\n\t{}'.format(frame_out)) frame_in = b'' buffer = self._socket.recv(4096) ...
def _read_queued_frames_from_file(self): self._log.debug('_read_queued_frames_from_file') queued_frames = [] try: file_path = '/sd/{}'.format(self.QUEUED_FRAMES_FILE) if 'sd' in os.listdir('/') and self.QUEUED_FRAMES_FILE in os.listdir('/sd'): with open(fi...
The code initializes communication with a server by reading queued frames from a file, creating a heartbeat frame, establishing a socket connection (with optional SSL), sending the heartbeat, handling server requests, and closing the connection. It returns True on success or False on exceptions, logging errors along th...
def init(self): """Init communication with the server""" self.queued_frames = self._read_queued_frames_from_file() num_frames = len(self.queued_frames) self._log.debug('Queued frames: {}'.format(num_frames)) heartbeat_frame = self.create_heartbeat_frame(num_frames) try...
def split(list): middleIndex = len(list) // 2 left = list[:middleIndex] right = list[middleIndex:] return left, right def merge(list1, list2): #iterate through each index in the shorter list # print('list1 = {0}'.format(list1)) # print('list2 = {0}'.format(list2)) #figuring out which list is longer and...
The code implements merge sort to sort a list in ascending order using a divide-and-conquer approach. It recursively splits the list into halves, sorts them, and merges the sorted sublists. The algorithm runs in O(n log n) time, with splitting taking O(log n) and merging O(n) time.
def merge_sort(list): ''' sorts a list in ascending order returns a new sorted list Divide: first find the midpoint of the list and divide into sublists Conquer: recursively sort the sublists created in previous steps Combine: Merge the sorted sublists created in previous step runs in O(n log n) time ...
def split(list): middleIndex = len(list) // 2 left = list[:middleIndex] right = list[middleIndex:] return left, right def merge_sort(list): ''' sorts a list in ascending order returns a new sorted list Divide: first find the midpoint of the list and divide into sublists Conquer: recursively sort th...
This code implements a merge sort algorithm to sort a list. It recursively splits the list into halves, sorts each half, and merges them back together using a merge function. The base case returns the list if it has one or zero elements. The `split` function divides the list, while `merge_video_example` combines sorted...
def merge_sort_example(list): ''' copied from video example ''' if len(list) <= 1: return list left, right = split(list) left_result = merge_sort(left) right_result = merge_sort(right) return merge_video_example(left_result, right_result)
def get_next_location(self): for cell in self.cells: if self.board[cell.row][cell.col] == '0': domain = self.domains[(cell.row, cell.col)] return (cell.row, cell.col, domain) return (-1, -1) def printB(self): # print("Rows:") # for i in ran...
This function solves a Sudoku puzzle using backtracking with forward checking. It recursively fills empty cells with valid numbers, checks constraints, and backtracks when conflicts arise. It tracks expanded nodes and backtracks to manage performance, returning True if solved or False if exceeding limits.
def solve_simple_backtracking(self): if self.expandedNodes >= 1000: print("could not solve") print("Searches: ", self.expandedNodes) print("Number of backtracks: ", self.num_backtracks) return False location = self.get_next_location() if location[...
def get_next_location_MRV(self): # update the domain lengths first new_q = PriorityQueue() while not self.queue.is_empty(): entry = self.queue.pop() entry.domain_length = count_set_bits(self.domains[(entry.cell.row, entry.cell.col)]) new_q.push(entry) ...
This function solves a constraint satisfaction problem using backtracking with the Minimum Remaining Values (MRV) heuristic. It selects the most constrained cell, attempts valid values, applies forward checking to prune domains, and backtracks if no solution is found. It tracks expanded nodes and backtracks, returning ...
def solve_most_constraint_backtracking(self): if self.expandedNodes >= 1000: print("could not solve") print("Searches: ", self.expandedNodes) print("Number of backtracks: ", self.num_backtracks) return False location = self.get_next_location_MRV() ...
def print_numbered_list(input): print("0. Cancel") for i, option in enumerate(input, start = 1): print(f"{i}. {option}") def user_input(options): while True: try: user_choice = int(input("Enter the number of your choice: ")) if user_choice == 0: sys.ex...
This function allows users to modify specific pipeline parameters (medical field, device, or search terms) by selecting options from a list. It warns of potential costs due to re-runs and directs to corresponding modification handlers based on user input.
def change_pipeline_values(): print("\nCAUTION!!! Changing values will force re-runs of summaries, which will cost money.") print("What values would you like to change? If you would like to not change any values, input 0. Please choose an option:") print_numbered_list(second_options) chosen_index = user...
def summarize_folder(input_folder): def has_number(s): for char in s: if char.isdigit(): return True return False folder_files = os.listdir('' + input_folder) #folder_files = os.listdir(input_folder) output_folder = f'{input_folder[:15]}devices_gpt_output/' ...
The main task of the code is to process text files in a specified folder by extracting topics and associated numbers, grouping them, generating summaries using OpenAI's API, and cleaning up old files. It reads configuration settings, processes filenames with regex, organizes data into a dictionary, creates a summary ou...
def main(): if len(sys.argv) < 2: print('Usage: python Gpt.py <folder1>') return input_folder = sys.argv[1] config = read_config() openai.api_key = config.get('OpenAIAPI', 'key') openai_model = config.get('OpenAIAPI', 'model') repeat_topics = summarize_folder(input_folder)...
def rotateLeft(): print("Rotating counter-clockwise (aka left when viewed from top)") GPIO.output(DIR, CCW) for x in range(int(SPR/4)): GPIO.output(STEP, GPIO.HIGH) sleep(DELAY) GPIO.output(STEP, GPIO.LOW) sleep(DELAY) # Check if red light is on, if so we're done whi...
The main task of the code is to provide a command-line interface for controlling a device or robot through user input. It processes commands like rotating left/right, calibrating, opening/closing a lid, checking a bumper, or quitting, executing corresponding functions based on user input until the 'q' command is entere...
def main(): while True: user = input("Enter one of R,L,O,C to continue, q to quit: ") if user == "L": rotateLeft(); elif user == "R": rotateRight(); elif user == "T": # Tune/calibrate for red light calibrate(); elif user == "O": openLid(); elif user == "C": closeLid(); elif user == "B": ...
def prepare_data(self): updated = False # create genome object # if not self.genome_ref: # connect to client try: gfuClient = GenomeFileUtil(self.callback_url, token=self.getContext()['token']) except Exception as e: ...
This test method executes the StrainFinder_v1 tool to analyze genomic data by processing a genome reference and paired-end reads library. It configures parameters like mapping quality thresholds (30), depth ranges (3-10000), and outputs results to a workspace. The test prepares sample data, runs the analysis, and print...
def test_run_StrainFinder_v1_01(self): method = 'test_run_StrainFinder_v1_01' print ("\n\nRUNNING "+method+"()") print ("===========================================\n\n") self.prepare_data() # run method output_name = meth...
def prepare_data(self): updated = False # create genome object # if not self.genome_ref: # connect to client try: gfuClient = GenomeFileUtil(self.callback_url, token=self.getContext()['token']) except Exception as e: ...
This test method executes the StrainFinder_v1 tool to analyze genomic data, using specified parameters like genome references, read libraries, and quality thresholds. It prepares test data, runs the method with defined inputs, and prints the results for validation.
def test_run_StrainFinder_v1_02(self): method = 'test_run_StrainFinder_v1_02' print ("\n\nRUNNING "+method+"()") print ("===========================================\n\n") self.prepare_data() # run method output_name = meth...
def prepare_data(self): updated = False # create genome object # if not self.genome_ref: # connect to client try: gfuClient = GenomeFileUtil(self.callback_url, token=self.getContext()['token']) except Exception as e: ...
This test method executes the StrainFinder_v1 tool by preparing input data, constructing a ReadsSet object, and invoking the method with parameters including a genome reference, reads library references, and output settings. It validates the tool's functionality by running the analysis and printing results, ensuring co...
def test_run_StrainFinder_v1_03(self): method = 'test_run_StrainFinder_v1_03' print ("\n\nRUNNING "+method+"()") print ("===========================================\n\n") [OBJID_I, NAME_I, TYPE_I, SAVE_DATE_I, VERSION_I, SAVED_BY_I, WSID_I, WORKSPACE_I, CHSUM_I, SIZE_I...
def select(node): uctList = [] nodeList = [] traverse(node, uctList, nodeList) maxIndex = np.argmax(uctList) return nodeList[maxIndex] def expand(node): return node.addChild() def simulate(node): # return win or lose of the game notSimEnded = not node.game.isTerminal() duplicateGame ...
The code implements the Monte Carlo Tree Search (MCTS) algorithm to determine the optimal move in a game. It repeatedly selects nodes, expands the tree, simulates outcomes, and backpropagates results within a time limit. The process prioritizes exploring promising paths to identify the best child node, returning its as...
def MCTS(startNode): timeLeft = MOVETIMER while timeLeft > 0: startTime = time.time() selectedChild = select(startNode) if not selectedChild.game.isTerminal(): newLeaf = expand(selectedChild) simulationResult = simulate(newLeaf) else: simulatio...
def _should_be_turned_on_now(self): # Return true if now is in the range of light time today = datetime.today() start_date = today.replace(hour=self._light_start_hour, minute=self._light_start_minute) if self._light_start_hour > self._light_end_hour: tomorrow = today + timed...
The code's main task is to determine whether to turn a light on or off based on a condition checked by the `_should_be_turned_on_now()` method. If the condition is met, it activates the light using `turn_light_on()`; otherwise, it deactivates it via `turn_light_off()`. This logic likely automates lighting control based...
def run(self): if self._should_be_turned_on_now(): self.turn_light_on() else: self.turn_light_off()
def create_display_frame(self): frame = tk.Frame(self.window,height=221,bg=Light_gray) frame.pack(expand=True, fill="both") return frame def create_display_label(self): total_label=tk.Label(self.display_frame,text=self.total_expressiom, anchor=tk.E,bg=Light_gray,fg=LAbel_col...
This code initializes a Tkinter-based calculator GUI. It sets up the window, display area for expressions, digit/operator buttons, and binds keyboard inputs. The class creates a 4x3 button grid with digits, operators, and special functions (clear, square, sqrt), configuring layout and positioning elements for a functio...
def __init__(self): self.window=tk.Tk() self.window.geometry("375x667") self.window.resizable(0, 0) self.window.title("Calculator") self.total_expressiom="" self.current_expression="" self.display_frame=self.create_display_frame() self.total_label, self....
def input_fn(batch_size_,datasettype): #make the dataset usable buffer_size_ = 100 dataset = tf.data.Dataset.from_generator(lambda: gen(datasettype),(tf.string,tf.string)) dataset = dataset.shuffle(buffer_size=buffer_size_,reshuffle_each_iteration=True).repeat(count=None) #Shuffle to mix up the order of data t...
This code evaluates a trained model's performance on a dataset by computing Intersection over Union (IoU) metrics for each class and the overall mean IoU. It loads a pre-trained model, predicts outputs, compares them with ground-truth labels, calculates IoU values, and prints class-wise and average IoU results. It also...
def test_model(batch_size_,restore): #test if the output is what is expected; prints model generated images of the last batch dataset=input_fn(batch_size_,datasettype = 'train') #datasetval = input_fn(batch_size_,datasettype = 'validation') model=TheModel(batch_size_,restore) model.load_weights('best_model.h5...
def generateFragmentDB(dirpath): # initialize Lists for all found fragments and the corresponding Codons. Same fragment can occur multiple times fragCodonCollection_5 = [] # windowsize = 5 fragCodonCollection_7 = [] # windowsize = 7 sequences = [] for pat...
The code's main task is to process biological sequence data by generating or loading codon usage statistics (CUV, RSCU, GC content) from genome databases, aligning protein sequences, creating input dataframes for machine learning, and training a model using these features. It includes hard-coded paths, substitution mat...
def main(): # Hard coded section that needs to be exchanged via arguments from the command line parser. # names have to remain the same #------------------------------------------------------------ dirpath = "/Users/friedi/Documents/Cupriavidus necator/Databank" modelinput = "/Users/friedi/Documen...
def update_play(self): response = requests.get(self.game_url) data = response.json() updated_play = data["liveData"]["plays"]["currentPlay"] if (updated_play != self.current_play): self.set_last_play(updated_play) return True else: return Fal...
The code's main task is to update the game state by checking if a new play has occurred. If updated, it visualizes the rink using the play's coordinates and checks if the game should end based on the play's result. If the game ends, it halts the game session by setting `game_is_live` to False and triggering the `end_ga...
def update(self): play_has_updated = self.update_play() if play_has_updated: self.print_rink_using_coordinates(self.current_play["coordinates"]) if self.current_play["result"]["description"] == "Game End" or self.current_play["result"]["description"] == "Game Offici...
def pre_req(self): self.requests += 1 if self.requests > self.requestsHold: self.perform_refresh() self.requests = 0 def get_endpoint(self, endpoint): if self.base_endpoint not in str(endpoint): endpoint = f"{self.base_endpoint}/{endpoint}" return endp...
This code sends a GET request to a specified API endpoint, handles authentication/preliminary tasks via `pre_req()`, validates the response status, and returns parsed JSON data if successful.
def get(self, endpoint): self.pre_req() r = requests.get(self.get_endpoint(endpoint), headers=self.get_headers()) if r.status_code != 200: raise Exception(f"Request not complete {r.text}") data = r.json() return data
def pre_req(self): self.requests += 1 if self.requests > self.requestsHold: self.perform_refresh() self.requests = 0 def get_endpoint(self, endpoint): if self.base_endpoint not in str(endpoint): endpoint = f"{self.base_endpoint}/{endpoint}" return endp...
This method sends a POST request to a specified endpoint with provided data, using headers and JSON formatting. It checks for a successful response (status code 200), raises an exception if failed, and returns the parsed JSON response data.
def post(self, endpoint, data): self.pre_req() r = requests.post(self.get_endpoint(endpoint), headers=self.get_headers(), json=data) if r.status_code != 200: raise Exception(f"Request not complete {r.text}") data = r.json() return data
def pre_req(self): self.requests += 1 if self.requests > self.requestsHold: self.perform_refresh() self.requests = 0 def get_endpoint(self, endpoint): if self.base_endpoint not in str(endpoint): endpoint = f"{self.base_endpoint}/{endpoint}" return endp...
This code sends a POST request to a specified endpoint with provided data, handles authentication headers, checks for a successful response (200 status code), and returns the JSON response or raises an exception if the request fails.
def put(self, endpoint, data): self.pre_req() r = requests.post(self.get_endpoint(endpoint), headers=self.get_headers(), json=data) if r.status_code != 200: raise Exception(f"Request not complete {r.text}") data = r.json() return data
def read_metadata(self, path_json): with open(path_json) as json_file: data = json.load(json_file) train_list = pd.DataFrame.from_dict(data, orient='index') train_list.reset_index(level=0, inplace=True) return train_list def read_existed_files(self, out_dirname): ...
The main task of the code is to initialize a face detection system using the MTCNN model, load metadata from provided JSON files, check for existing output files in the specified directory, and initiate the extraction process for face detection tasks. It sets up parameters, prepares input data, and triggers the extract...
def __init__(self, jsons, dirs, dir_out): self.detector = MTCNN(margin=20, keep_all=True, post_process=False, device='cuda:0') self.margin = 0 self.save_interval = 60 self.json_lists = jsons self.dir_lists = dirs self.dir_out = dir_out self.train_list = self.read...
def generify(points, epsilon=0): return_points = set() for point in points: delta_x = random.uniform(-epsilon,epsilon) delta_y = random.uniform(-epsilon,epsilon) point_x = point[0]+delta_x point_y = point[1]+delta_y return_points.add((point_x,point_y)) return return_p...
The main task of the code is to generate and optimize a Delaunay triangulation from a set of 2D points. It first generalizes input points, creates an initial vertical triangulation, visualizes it, then applies optimization to refine the triangulation, finally drawing the optimized Delaunay triangulation.
def main(points): points = generify(points,epsilon=0.0001) triangles, lines = triangulate(points, vertical = True) draw_triangulation(triangles,"initial_triangulation_2") new_triang = optimize(list(triangles)) draw_triangulation(new_triang, "delaunay_2")
def read_file(filename): with open(filename, "r") as file: lines = file.readlines() return lines def decryptString(encryptedText, key): decryptedData = vigenereDecrypt(encryptedText, key) return decryptedData def display_menu(): print("1. Add a new line") print("2. Read all lines") p...
The main task of the code is to manage a text file with encryption capabilities, allowing users to add, display, update, or delete lines. It decrypts data if the file is encrypted, processes user choices through a menu, and exports the file (with optional re-encryption) after operations.
def main(): filename = input("Enter the file name: ") is_encrypted = input("Is the file encrypted? (y/n): ") if is_encrypted.lower() == "y": encryptionKey = input("Enter the decryption key: ") encryptedLines = read_file(filename) decryptedLines = [decryptString(line.strip(), encrypt...
def return_runtime(self,app_name): return app_name+": "+self.obtain_absolute_runtime(self.output_path+"/profile-data/"+app_name+".runtime.out") def generate_hotspots_lists(self,data): df1=self.obtain_identified_hotspots(self.config_data["application"]["application1"]) df2=self.obtain_identified_...
The main task of the code is to generate a structured report file containing runtime information for two applications, a list of hotspots, and instruction characterization analyses for both combined and individual applications. It writes data such as runtime results, hotspot lists, and instruction patterns into the pro...
def output_file(self,data): print("Runtime",file=data) print("="*100,file=data) print(self.return_runtime(self.config_data["application"]["application1"]),file=data) print(self.return_runtime(self.config_data["application"]["application2"]),file=data) print("\nHotspots List",file...
def mkdir_outputs(self): if (os.path.exists(self.out_folder))==False: os.system("mkdir "+self.out_folder) if (os.path.exists(self.output_path))==False: os.system("mkdir "+self.output_path) print("Output path:"+self.output_path) def instrument_logical_address(s...
The main task of the code is to execute instrumentation and analysis workflows based on configuration flags. It creates an output directory, checks if logical address or function name modes are enabled, and performs corresponding operations like performance analysis, hotspot identification, instrumentation, and reporti...
def main(self,print_command): self.mkdir_outputs() if self.config_data["runmode"]["logical_address"]=="true": self.instrument_logical_address(print_command) if self.config_data["runmode"]["function_name"]=="true": self.run_perf(print_command) self.identified_h...
def greeting(): hour = dt.datetime.now().hour if 0 <= hour < 12: eithne_talk('Good Morning') elif 12 <= hour < 18: eithne_talk('Good Afternoon') else: eithne_talk('Good Evening') def eithne_talk(audio_string): # Set up Eithne's vocals. talk = gTTS(text=audio_string, lang=...
The main task of the code is to initialize a voice assistant named Eithne by displaying a welcome message, selecting a random greeting, and entering an infinite loop to continuously capture user audio input and generate responses using the `respond()` function, enabling interactive voice-based assistance.
def main(): print('====== Eithne, Voice Assistant ======') greeting() h = ['How can I help?', 'What would you like to do today?', 'What service do you require?', "I'm listening", "What can I do for you?", "Thanks for waking me up!"] message = h[random.randint(0, len(h) - 1)] eithne_talk(mes...
def q_sample(self, y_start, p, t): """ Diffuse the data for a given number of diffusion steps. In other words, sample from q(y_t | y_start, f(x)). :param y_start: the initial data batch. :param t: the number of diffusion steps (minus 1). Here, 0 means one step. :return: ...
This function computes training losses for a diffusion model at a single timestep, handling various loss types (KL, rescaled KL, MIX, BCE). It generates noisy inputs (y_t), calculates loss terms based on the specified loss type, and returns a dictionary containing the loss tensor and optionally additional keys like 'fo...
def training_losses(self, model, y_start, t, model_kwargs=None, lambda_focal=1): """ Compute training losses for a single timestep. :param model: the model to evaluate loss on. :param y_start: the [N x C x ...] tensor of inputs. :param t: a batch of timestep indices. :pa...
def query_delta_gamma_data(session, iv, symbols, eod, strike_threshold=1, lower_abs_delta_threshold=0.4, upper_abs_delta_threshold=0.6, include_delta_region=True): # pull and aggregate everything within strik...
The main task of the code is to generate trading signals (sig) and process options data (df_options) from a database by iterating through parameter sets. It queries delta/gamma data, prepares it for specific markets, calculates volatility-based signals using defined indicators, and structures results with multi-index c...
def generate_thor_signal(param_set): engine = create_engine(os.getenv('DATABASE_CONNECTION')) session_factory = sessionmaker(bind=engine) metadata = MetaData() metadata.reflect(bind=engine) iv = Table('ivolatility', metadata, autoload=True, autoload_with=engine) ep = Table('equity_price', metad...
def query_spot_data(symbol): engine = create_engine(os.getenv('DATABASE_CONNECTION')) session_factory = sessionmaker(bind=engine) metadata = MetaData() metadata.reflect(bind=engine) ep = Table('equity_price', metadata, autoload=True, autoload_with=engine) session = scoped_session(session_factor...
The function generates financial signals from options data by processing parameter sets, querying cached or database-stored market and signal data, filtering by delta ranges, and computing volatility signals. It optionally calculates correlations with underlying assets, kurtosis, and performance metrics, returning sign...
def generate_odin_signal(all_parameters, calcCorr = False, start_date='2008-01-01', useORATS=False): sig_set = [] trade_market = [] df_sig_cache = {} df_spot_cache = {} param_features = [] for param_set in all_parameters['key']: param_v = eval(param_set) signal_markets = param_...
def find_rail_sides(img, edges_dict): left_border = [] right_border = [] for y,xs in edges_dict.items(): rails = find_rails(img, [y], values=[9,10], min_width=5) left_border_actual = [min(xs)[0],y] right_border_actual = [max(xs)[1],y] ...
The main task of the code is to identify and extrapolate the left and right zone borders in an image based on edge detection and distance mapping. It processes input data to interpolate endpoints, adjust borders using real-world measurements, and returns the final borders alongside corresponding regions. This is likely...
def find_zone_border(id_map, image, edges, irl_width_mm=1435, irl_target_mm=1000, lowest_y = 0): left_border, right_border, flags_l, flags_r = find_rail_sides(id_map, edges) dist_marked_id_map, end_points_left, end_points_right, left_region, right_region = find_dist_from_edges(id_map, ...
def files_in_subdirs(start_dir, pattern = ["*.png","*.jpg","*.jpeg"]): files = [] for p in pattern: for dir,_,_ in os.walk(start_dir): files.extend(glob.glob(os.path.join(dir,p))) return files def config_to_rgb(inp_path_config_json, default_col = [255,255,255]): lut = [] inp_json...
The code visualizes annotations from JSON files by displaying corresponding images with labels, using OpenCV. It loads JSON files, converts color configurations to BGR format, and cycles through images with 'a'/'d' keys, wrapping around. Each frame shows the filename and annotation, allowing interactive navigation and ...
def vis_all_json(json_folder, jpg_folder, uint8_folder, inp_path_config_json): all_json = files_in_subdirs(json_folder, pattern = ["*.json"]) lut_bgr = config_to_rgb(inp_path_config_json, default_col = [255,255,255])[::-1] #we need to swap color channels as opencv uses BGR curr_idx, retKey = 0, ord('a') ...
def segment(model_seg, image_size, filename, PATH_jpgs, dataset_type, model_type, item=None): image_norm, _, image, mask, _ = load(filename, PATH_jpgs, image_size, dataset_type=dataset_type, item=item) id_map = process(model_seg, image_norm, mask, model_type) id_map = cv2.resize(id_map, [1920,10...
The code processes an image using segmentation and detection models to classify objects into moving/stationary categories, then visualizes results with borders, regions, and labeled detections, leveraging segmentation masks and edge detection for context.
def run(model_seg, model_det, image_size, filepath_img, PATH_jpgs, dataset_type, model_type, target_distances, file_index, vis, item=None, num_ys = 15): segmentation_mask, image = segment(model_seg, image_size, filepath_img, PATH_jpgs, dataset_type, model_type, item) print('File: {}'.format(filepath_im...
def open_file(file_path): """ Open a file and return its second column as a list of floats """ with open(file_path, "r") as file: return [float(line.split(",")[1]) for line in file.readlines()] def calculate_mean(data): """ Calculate the mean of a list of numbers :param data: (list)...
The code performs multiple statistical tests (z-test, t-test, F-test, chi-squared, ANOVA, MANOVA, regression) to compare reward data from different games, primarily assessing whether the "test game" significantly differs from "Space Invaders" in mean rewards, variance, and other metrics, using critical values for signi...
def main(): space_invaders_rewards = open_file("test2.csv") air_raid = open_file("test.csv") carnival = open_file("test3.csv") demonattack = open_file("test4.csv") mean_space_invaders = calculate_mean(space_invaders_rewards) mean_test_game = calculate_mean(test_game_rewards) standard_deviat...
def clean_standard_data(standard_record): "Sanitize data already in an interoperable format." def sanitize_sex(sex): sex = sex.lower() if "f" in sex or "w" in sex: return "F" else: return "M" def sanitize_age(age): for possible_age in age.split(" "): ...
The main task of this code is to process and save candidate medical records along with their associated images. It iterates through input records, cleans the data, downloads images from URLs using a cache, stores them in a directory, and appends metadata to a DataFrame. The results are saved as a CSV file, while interm...
def output_candidate_entries(standard, columns, out_name, img_dir, resource_cache, retry=False): "Save the candidate entries to a file." pickle_name = out_name + "_pickled_data" out_df = pd.DataFrame(columns=columns) if not os.path.exists(img_dir): os.mkdir(img_dir) all_records = [] for ...
def user_yes_no_query(question): sys.stdout.write('%s [Y/n]\n' % question) no_answer = True while no_answer: _input = input() if _input == "" or _input == "y": return True elif _input == "n": return False else: ...
The function `add_chips` adds chips to Python files in a specified path or project directory, handling exclusions via `.chipsignore`. It processes files, updates tracking data, and returns results (success/failure/skipped files) based on `result_type` parameters, with options for automatic result generation and output ...
def add_chips(self, path: str = None, auto: str = "on", result_type: str = "list", _silent: bool = False, ) -> (str, list, list): """ Add chips to current project or path :param auto: Determines whether to...
def spawn_scene(self, target_id): self.pub_start_spawn.publish(Tag_Spawn(target_id=target_id, phase=phase_place)) rospy.sleep(0.1) def lift_torso(self): self.client_torso.wait_for_server() rospy.loginfo("[PlS] Moving torso up") trajectory = JointTrajectory() trajectory.jo...
The code places an object by first spawning the scene, lifting the torso, calculating target positions based on object and cylinder dimensions, moving the arm to the adjusted pose, approaching with a safety distance, opening the gripper, detaching the object, and returning to a safe position while clearing the scene.
def place(self, target_id): self.spawn_scene(target_id) self.lift_torso() dz = 0.15 obj_ret = self.scene.get_attached_objects([links_tag[target_id]]) obj_obj = obj_ret[links_tag[target_id]] obj_pose = obj_obj.object.primitive_poses[0] obj_shape = obj_obj.object.pr...
def initialize(self): self.added_list = list() rospy.sleep(0.1) def add_table(self): # if already present updates the box name = "table" object_pose = geometry_msgs.msg.PoseStamped() object_pose.pose.position.x = table_x object_pose.pose.position.y = table_y ...
This callback handles collision object spawning based on target ID and phase from a message. It initializes and spawns tables/cylinders for 'pick'/'place' phases, validates target IDs (blue/green/red), and logs errors for unsupported targets/phases.
def spaw_collision_objects_callback(self, message): if message.target_id not in [target_blue, target_green, target_red]: rospy.logerr("[TN] Received target {"+str(message.target_id)+"} is not implemented") return if message.phase == phase_pick: self.initialize() ...
def add_cylinder(self, tag): identifier = tag.id[0] name = "tag_"+str(identifier) object_pose = geometry_msgs.msg.PoseStamped() object_pose.pose = tag.pose.pose.pose object_pose.header.frame_id = tag.pose.header.frame_id if identifier == 1: object_pose = self....
This function processes detected tags to add corresponding 3D objects. If adding is enabled, it checks each tag's ID against a list of added IDs. New tags trigger object creation: cylinders for IDs in prism_list, boxes for target_red, and triangles for target_green. It ensures each tag is only processed once by trackin...
def april_callback(self, tag_array): if self.adding_is_on: for tag in tag_array.detections: if tag.id not in self.added_list: self.added_list.append(tag.id) if tag.id[0] in prism_list: self.add_cylinder(tag) ...
def reset_head(self): return self.move_head(0, -0.3) def abort(self, message): rospy.logerr(message) self._as.set_aborted(MoveResult(r=message)) def feedback(self, message): rospy.loginfo(message) self._as.publish_feedback(MoveFeedback(f=message)) def reach_position(self, pose): ...
The code executes a robotic motion sequence for object picking: it resets the head to a standard position, moves to an intermediate pose, navigates to a target-specific final position, adjusts the head to a task-specific pose, and confirms success. Each step checks for successful execution, aborting on failure with err...
def move_to_pick(self, target_id): # head standard position result, status = self.reset_head() if not status == actionlib.GoalStatus.SUCCEEDED: self.abort("[MS] Error reaching standard head pose on pick phase") return self.feedback("[MS] Standard head pose on pick...
def reset_head(self): return self.move_head(0, -0.3) def abort(self, message): rospy.logerr(message) self._as.set_aborted(MoveResult(r=message)) def feedback(self, message): rospy.loginfo(message) self._as.publish_feedback(MoveFeedback(f=message)) def reach_position(self, pose): ...
The code executes a sequence of movements to position a robotic arm at a specified target location. It first resets the head to a standard pose, moves to an intermediate position, then navigates to the final target position using the provided target ID. After confirming the final position, it adjusts the head to its fi...
def move_to_place(self, target_id): # head standard position result, status = self.reset_head() if not status == actionlib.GoalStatus.SUCCEEDED: self.abort("[MS] Error reaching standard head pose on place phase") return self.feedback("[MS] Standard head pose on pl...
def abort(self, message): rospy.logerr(message) self._as.set_aborted(MoveResult(r=message)) def move_to_pick(self, target_id): # head standard position result, status = self.reset_head() if not status == actionlib.GoalStatus.SUCCEEDED: self.abort("[MS] Error reaching ...
The code handles a goal by validating its target ID and phase. If the target is unimplemented, it aborts. Depending on the phase (pick/place), it calls corresponding movement functions. If the phase is invalid, it aborts. The main task is executing navigation actions based on goal parameters while enforcing valid input...
def execute_cb(self, goal): goal_id = goal.target_id goal_phase = goal.phase if goal_id not in [target_blue, target_green, target_red]: self.abort("Target {"+str(goal_id)+"} not implemented") return if goal_phase == phase_pick: self.move_to_pick(goal_...
def get_user_ratings(self, user_id): if user_id in self._user_ratings: return self._user_ratings[user_id] return None def get_dictionary(self,restaurant_idx): return self._restaurant_dicts[restaurant_idx] def similarity(self, restaurant1, restaurant2, coords = None): ''' ...
The main task of the code is to recommend up to `k` restaurants to a user based on their past ratings, using item-based collaborative filtering. It calculates predicted ratings by comparing similarity between restaurants, filters by price, distance, and unvisited status, and returns the top `k` recommendations with pre...
def recommend_item_to_item(self, user_name, k, put_visited_too = False, coords = None, max_dist = 5, max_price = 4): ''' Returns a list of at most k pairs (restaurant,predicted_rating) adequate for a user whose name is user_name ''' # Get the user index, user_idx = self....
def cannon_moves(self, piece): """ method specifically for cannon movement since it is unique :param piece: the Cannon object :return: a list of spaces in algebraic notation that the cannon can go """ # get location and movement information piece_x, piece_y = pie...
This function calculates all possible moves for a given chess piece, considering movement rules, blocking pieces, and palace constraints. It handles unique cannon movement, checks for valid directions, and ensures moves stay within the palace for confined pieces. It returns algebraic notation of valid spaces, excluding...
def find_possible_moves(self, piece): """ find the possible moves of a given piece based on positions of other pieces - does not take into account putting own king into check :param piece: the Piece object for movement :return: list containing spaces of possible movement in algeb...
def get_pieces(self, player): """gets the pieces of a given player using the Board method""" return self._board.get_player_pieces(player) def get_general(self, player): """gets the general of a given player using the Board method""" return self._board.get_player_general(player) def space...
The function determines if a player is in check by checking if their general's position is within the attack range of the opponent's pieces. It identifies the player's color, retrieves the opponent's pieces and the player's general, calculates the opponent's attackable spaces, and returns True if the general's position...
def is_in_check(self, player_color): """ determines if the specified player is in check :param player_color: a string containing the player color :return: True if the player is in check, false otherwise """ if player_color.lower() == 'blue': player = True ...
def get_general(self, player): """gets the general of a given player using the Board method""" return self._board.get_player_general(player) def find_possible_moves(self, piece): """ find the possible moves of a given piece based on positions of other pieces - does not take into ...
This function checks if a player's general can escape check by moving to a safe position. It retrieves the general's possible moves and compares them against squares under attack by the opponent. If any move is not under attack, it returns True, indicating the general can avoid check; otherwise, it returns False.
def check_for_mate_avoid(self, player): """ determines if the general can be moved to avoid being in check :param player: True for blue, False for red :return: True if the player can move the general to get it out of check """ # get the player general and a list of its m...
def player(player): """returns 'blue' for True, 'red' for False""" if player: return 'blue' return 'red' def get_pieces(self, player): """gets the pieces of a given player using the Board method""" return self._board.get_player_pieces(player) def find_possible_moves(s...
This function checks if a player can escape check by moving a friendly piece. It iterates through all friendly pieces' possible moves, temporarily applies each move, and checks if the king is no longer in check. If any move achieves this, it returns True; otherwise, returns False after reverting the board state.
def check_for_mate_defense(self, player): """ determines if a friendly piece can be moved to block the king from check or take the attacking piece :param player: True for blue, False for red :return: True if the player can uncheck their king by moving a different piece ""...
def parse_input(): height_map = [] with open("resources/day09.txt") as file: while row := file.readline().rstrip(): height_map.append(list(map(Spot, row))) return height_map def get_low_points(height_map): low_points = [] for y in range(0, len(height_map)): for x in rang...
The code calculates the product of the three largest basin sizes in a height map. It parses input, identifies low points, computes basin sizes around each, selects the top three, and returns their product.
def solution2(): height_map = parse_input() low_points = get_low_points(height_map) basin_sizes = [] for c in low_points: basin_sizes.append(calc_basin_size(height_map, c[0], c[1])) top_3 = sorted(basin_sizes, reverse=True)[:3] return reduce((lambda x, y: x * y), top_3)
def sunPosition(self, jd): D = jd - 2451545.0 g = self.fixangle(357.529 + 0.98560028 * D) q = self.fixangle(280.459 + 0.98564736 * D) L = self.fixangle(q + 1.915 * self.sin(g) + 0.020 * self.sin(2 * g)) R = 1.00014 - 0.01671 * self.cos(g) - 0.00014 * self.cos(2 * g) e = ...
This function calculates the solar time when the sun reaches a specified angle above the horizon, considering both the sun's declination and the observer's latitude. It computes the hour angle using inverse cosine, adjusts it based on the direction (clockwise or counterclockwise), and returns the adjusted time relative...
def sunAngleTime(self, angle, time, direction=None): try: decl = self.sunPosition(self.jDate + time)[0] noon = self.midDay(time) t = 1 / 15.0 * self.arccos((-self.sin(angle) - self.sin(decl) * self.sin(self.lat)) / (self.cos(decl) * self...
def timeDiff(self, time1, time2): return self.fixhour(time2 - time1) def adjustHLTime(self, time, base, angle, night, direction=None): portion = self.nightPortion(angle, night) diff = self.timeDiff(time, base) if direction == 'ccw' else self.timeDiff(base, time) if math.isnan(time) or di...
The code adjusts prayer times for high latitude regions by modifying imsak, fajr, isha, and maghrib times using sunset-sunrise duration and predefined settings. It ensures accurate timings when standard solar calculations fail, applying counter-clockwise adjustments for dawn/prayer times and handling nighttime duration...
def adjustHighLats(self, times): params = self.settings nightTime = self.timeDiff(times['sunset'], times['sunrise']) # sunset to sunrise times['imsak'] = self.adjustHLTime(times['imsak'], times['sunrise'], self.eval(params['imsak']), nightTime, 'ccw') ...
def sunPosition(self, jd): D = jd - 2451545.0 g = self.fixangle(357.529 + 0.98560028 * D) q = self.fixangle(280.459 + 0.98564736 * D) L = self.fixangle(q + 1.915 * self.sin(g) + 0.020 * self.sin(2 * g)) R = 1.00014 - 0.01671 * self.cos(g) - 0.00014 * self.cos(2 * g) e = ...
This code calculates the Asr prayer time by determining the sun's declination, computing an angular value based on latitude and declination, then using this angle to derive the specific time for Asr prayer.
def asrTime(self, factor, time): decl = self.sunPosition(self.jDate + time)[0] angle = -self.arccot(factor + self.tan(abs(self.lat - decl))) return self.sunAngleTime(angle, time)
def adjustHighLats(self, times): params = self.settings nightTime = self.timeDiff(times['sunset'], times['sunrise']) # sunset to sunrise times['imsak'] = self.adjustHLTime(times['imsak'], times['sunrise'], self.eval(params['imsak']), nightTime, 'ccw') ...
This function adjusts prayer times by applying timezone corrections, high latitude adjustments, and minute-based offsets for specific prayers (imsak, maghrib, isha, dhuhr) based on user-defined settings.
def adjustTimes(self, times): params = self.settings tzAdjust = self.timeZone - self.lng / 15.0 for t, v in times.items(): times[t] += tzAdjust if params['highLats'] != 'None': times = self.adjustHighLats(times) if self.isMin(params['imsak']): ...
def dayPortion(self, times): for i in times: times[i] /= 24.0 return times def sunAngleTime(self, angle, time, direction=None): try: decl = self.sunPosition(self.jDate + time)[0] noon = self.midDay(time) t = 1 / 15.0 * self.arccos((-self.sin(angle)...
The code computes Islamic prayer times (imsak, fajr, sunrise, etc.) using astronomical calculations and user-defined parameters. It processes input time data, applies sun angle adjustments, midday calculations, and Asr factor logic to determine each prayer's timing, returning a structured dictionary of results.
def computePrayerTimes(self, times): times = self.dayPortion(times) params = self.settings imsak = self.sunAngleTime(self.eval(params['imsak']), times['imsak'], 'ccw') fajr = self.sunAngleTime(self.eval(params['fajr']), times['fajr'], 'ccw') sunrise = self.sunAngleTime(self.rise...
def shadow_replace_font_detector(document): warnings = 0 file = open(document, 'rb') content_encoded = file.read() file.close() content = content_encoded.decode("iso-8859-1") content_str = str(content) content_str_lower = content_str.lower() #Get byte value of first signature tmp = ...
This code detects shadow attacks in a document by running multiple detection functions, prepares a modified version of the document for rechecking, and returns the total count of detected attacks. It prints a warning if any attacks are found, otherwise confirms no active attacks.
def detector(document): print("Start Detection-Mode.") warnings_detection_all = 0 warnings_dec_hide_form = 0 warnings_dec_replace_form = 0 #Call detector warnings_dec = shadow_replace_font_detector(document) if (warnings_dec == 0): warnings_dec = shadow_hide_and_hide_replace_detecto...
def check_sig_state(document): sig_state = 0 file = open(document, 'rb') content = file.read() file.close() content = content.decode("iso-8859-1") content_str = str(content) #Check if the pdf contains signatures sig_state = content_str.count("/Type/Sig") if (sig_state <= 0): ...
This code detects and prevents shadow attacks in PDF documents. It checks for existing signatures; if found, it runs a detector to identify active attacks. If none are found, it removes signatures, updates the document, and runs a preventor for inactive attacks. If no signatures exist, it directly applies the preventor...
def start_preventor_detector(document): #show_elements(document) warnings = 0 if(check_sig_state(document) > 0): #Detector print("PDF File contains signatures.") try: warnings = detector(document) except: print("Error in Detection process!") ...
def get_user_settings(user_id): """Get settings from our database by given user_id""" settings = connect_db() result = settings.settings.find_one({'_id': {'$eq': user_id}}) return result def get_calendar_sevice(user_id, credentials=None): """Return calendar service; Input: user_id - a...
The main task of the code is to create a new Google Calendar for a user, using their credentials and settings. It retrieves user-specific time zone information, constructs a calendar with the provided name and time zone, and inserts it via the Google Calendar API. The function returns True if successful (calendar creat...
def create_calendar(user_id, calendar_name, service=None): """Create new calendar in authorized Google Calendars account. Inherit time_zone from saved settings or from the primary calendar Input: user_id - user id as it is in the database; calendar_name - a name for the new calendar; ...
def get_calendar_id(user_id, calendar_name): """Get a list of all calendar ids from the user account, and looking for id with a particular name; Input: user_id - user id as it is in the database; calendar_name - not case-sensitive - it compares everything in lowercase; Output: calend...
The function fetches an existing calendar for a user by name, retrieves its time zone, saves the calendar ID and time zone to user settings, and returns True if successful (calendar exists), otherwise False. It emphasizes precise calendar name input to avoid duplicates.
def fetch_calendar(user_id, calendar_name): """Try to fetch calendar by the given name - in case user wants to bind existed calendar. Plus save it to user settings; Input: user_id - user id as it is in the database; calendar_name - space-sensitive... overall very sensitive - make sure you ty...
def get_user_settings(user_id): """Get settings from our database by given user_id""" settings = connect_db() result = settings.settings.find_one({'_id': {'$eq': user_id}}) return result def set_calendar_to_primary(user_id): """Set calendar id to primary value + restore time zone; Input: ...
The function `add_event` adds a user-specified event to their Google Calendar. It uses parameters like `user_id`, `description`, `start`, `end`, and optional fields (service, attendees, location) to create an event. It retrieves user settings (credentials, time zone, calendar ID), formats event times, constructs the ev...
def add_event(user_id, description, start, end, service=None, attendees=None, location=None): """Try to add event; Input: user_id - as it is in our database; description - string - main message for the event; first 50 symbols will be set as a title; start, end - datetime.datetime/ dateti...
def gradient_descent( init_x: float, init_y: float, beta: float, epsilon: float, epochs: int, plot: bool = False, debug: bool = False, ) -> Result: (previous_x, previous_y) = (init_x, init_y) x_values = [init_x] y_values = [init_y] for e in range(epochs): (x, y) = gr...
The main task of the code is to execute either gradient descent or Newton's method for minimizing the Rosenbrock function, using user-defined parameters like initial values, beta, and stopping conditions. It measures the average execution time over 10 runs, outputs optimization results, and optionally visualizes the al...
def main(): parser = argparse.ArgumentParser() parser.add_argument( "-x", "--init-x", type=float, help="x value algorithm starts with" ) parser.add_argument( "-y", "--init-y", type=float, help="y value algorithm starts with" ) parser.add_argument( "-b", "--beta", type=flo...
def load_data_from_file(filename: str) -> DataFrame: df = pd.read_csv( filename, sep=",", names=[X1, X2, X3, X4, CLASS], ) return df def prepare_train_and_test_set( dataset: DataFrame, train_size: float, is_train_set_sorted: bool = False ): train_set, test_set = train_test_s...
The code performs a classification evaluation using a dataset split into train and test sets. It calculates statistical metrics (mean, std, prior probabilities) from the training set to classify the test set, generating confusion matrices. It runs 10 iterations, aggregating accuracy, precision, and recall statistics ac...
def main(): parser = argparse.ArgumentParser() parser.add_argument( "-f", "--filename", type=str, help="Path to file with data", ) parser.add_argument( "-ts", "--train-size", type=float, help="Percentage of dataset used in the train set.",...
def load_data_from_file(filename: str) -> DataFrame: df = pd.read_csv( filename, sep=",", names=[X1, X2, X3, X4, X5, X6, CLASS], ) return df def plot_features_histograms(dataset: DataFrame): groups = dataset.groupby(CLASS) feature_values_occurrences_by_class = {} for na...
The main task of the code is to evaluate a random forest classifier's performance using cross-validation and a validation set. It loads data from a file, splits it into training/validation sets, trains the classifier with specified parameters (trees, depth, folds), computes accuracy, precision, and recall metrics for e...
def main(): parser = argparse.ArgumentParser() parser.add_argument( "-f", "--filename", type=str, help="Path to file with data", ) parser.add_argument( "-ts", "--train-size", type=float, help="Percentage of dataset used in the train set.",...
def is_land(self, r, c): if ( 0 <= r < self.size and 0 <= c < self.size and (self.history[-1][r][c] > 0 or self.history[-1][r][c] == -1) ): return True return False def return_connected(self, r, c): connected = [(r, c)] queue = [(r,...
The function identifies islands that can be connected to the cell (r, c) without exceeding area constraints. It iterates through remaining islands, uses BFS to explore connections, and checks if valid paths exist. If a path reaches (r, c) or remaining area is exhausted, islands are added to the result list. The task in...
def close_islands(self, r, c): close_islands = [] for ir, ic in self.remaining_islands: # if rc is island and area of this and ir,ic exceeds that nubmer, skip if self.is_land(r, c): sizes = self.land_DSU.get_size((r, c)) + self.land_DSU.get_size( ...
def initialize(): dealer_cards.clear() dealer_score == 0 user_cards.clear() user_score == 0 def calculate_sum(list): if list.count(11) and sum(list) > 21: list = replace_values(list, 11, 1) return sum(list) return(sum(list)) def result(): dealer_score = calculate_sum(dealer_c...
This code simulates a Blackjack game where the user and dealer receive cards, the user decides to draw more cards or pass, the game calculates scores, determines the result, and allows replaying. It initializes game state, handles user input, and recursively restarts the game if the player chooses.
def play(): initialize() dealer_cards.append(random.choice(cards)) dealer_score = calculate_sum(dealer_cards) user_cards.append(random.choice(cards)) user_cards.append(random.choice(cards)) user_score = calculate_sum(user_cards) print(f"{logo}\n\n") print(f"Your cards: {user_cards}, cu...
def print(*args, **kwargs): """Custom print""" if 'color' in kwargs: _color = kwargs['color'] del kwargs['color'] if is_color_term() and _color: new_args = [] for arg in args: new_args.append('{}{}{}'.format(color(_color), args[0], color('default')...
The code creates an AWS CloudFormation stack using the provided stack name and template file. It checks if the stack already exists, exits if it does, and uses subprocess to execute the AWS CLI command. Error handling is included for failed stack creation, with colored terminal output for user feedback on status and er...
def create_stack(self, **kwargs): """ Creates Cloudformation stack using the details provided. """ stack_name = kwargs.get('stack_name') template_file = kwargs.get('template_file') if not self.quiet: print('Creating stack: ', end='') print('{}'.for...
def getIsWeekday() -> bool: now = getTokyoTime().weekday() return now < 5 def createActivityList(isWeekday: bool) -> list: if isWeekday: # !WARNING Bug, it needs to be in units of one hour sleepMorning = random.randint(6, 8) sleepNight = random.randint(1, 2) otherStudy1 = ran...
The main task of the code is to automate study record posting by checking if it's a weekday, creating an activity list, logging in to obtain credentials, retrieving time slots based on weekday status, and iterating through these slots to post study records with specific parameters like type ID, start, and end times.
def main(): isWeekday = getIsWeekday() activityList = createActivityList(isWeekday) loginPostCookies, requestToken, studentId = postLogin() if not isWeekday: timeList = getTimeListByActivityList(activityList) else: classTimeList = getClassTimeList(loginPostCookies=loginPostCookies,...
def apply_kernel(self, x0, x1): if isinstance(self.kernel, str): return pairwise_kernels(x0, x1, metric=self.kernel) else: return self.kernel(x0, x1) def compute_derivative_hinge_by_multipliers(self, x): condition = ((1 - self.y_ * self.compute_h(x)) > 0.0).astype(int) #...
This code implements a binary SVM classifier using gradient descent on the hinge loss. It initializes parameters, converts labels to {-1, 1}, and iteratively updates Lagrange multipliers and bias. The algorithm enforces non-negative multipliers, tracks support vectors, and terminates when loss falls below a tolerance t...
def fit(self, X, y): X, y = check_X_y(X, y) self.classes_ = unique_labels(y) if len(self.classes_) != 2: raise NotImplementedError("Only binary classification is supported") self.X_ = deepcopy(X) self.y_ = deepcopy(y) # make sure that y is in {-1, 1} s...
def get_hyperplane(self): check_is_fitted(self) w = np.dot(self.dual_coef_, self.support_vectors_) b = self.bias return w, b def predict(self, x): check_is_fitted(self) x = check_array(x) y_hat = np.sign(self.compute_h(x)).astype(int) y_hat[y_hat == -1] = ...
The code visualizes an SVM model's decision boundary, margins, and support vectors on 2D data using matplotlib. It validates input dimensions, generates a mesh grid, plots classification regions with contourf, overlays data points, decision boundaries, and dashed margins, then displays the result with labeled axes and ...
def visualize(self, x, y, **kwargs): import matplotlib.pyplot as plt check_is_fitted(self) x, y = check_X_y(x, y) if x.shape[-1] != 2: raise ValueError(f"x.shape[-1] = {x.shape[-1]} != 2. Only 2D data is supported.") if y.ndim != 1: raise ValueError(f"y.n...
def get_reduced_data_indices(): data_path = os.path.join(ORIGINAL_DIR, 'rxn_indices_by_len_quantiles.json') rxns_indices_by_len_quantiles = json.loads(json.load(open(data_path, 'r'))) taken_rxn_indices = [] for indices in rxns_indices_by_len_quantiles: n_taken_rxns = int(len(indices) * DATA_REDU...
The code processes chemical reaction data (SMILES strings) for different splits (train/test/valid), applying data reduction and augmentation for training. It reads source/target pairs, parses reactions, generates new samples based on the task, applies fold-specific augmentation (disabled for test/valid), and writes pro...
def write_smiles_files(out_dir, task, fold, split): if split != 'train': fold = 1 # no augmentation for test and valid data with open(os.path.join(ORIGINAL_DIR, 'src-%s.txt' % split), 'r') as src_in,\ open(os.path.join(ORIGINAL_DIR, 'tgt-%s.txt' % split), 'r') as tgt_in,\ open(os.path...
def check_if_roundtrip_should_be_run(folder): if not any([s + os.path.sep in folder for s in ROUNDTRIP_TASKS]): return False if not all([s in folder for s in ROUNDTRIP_SPECS]): return False return True def check_if_50k_should_be_run(folder): if not any([s + os.path.sep in folder for s in...
This function generates a configuration file by replacing placeholders with specified paths and settings. It checks if 'roundtrip' or '50k' modes require execution, identifies necessary paths, sets n_best to '1' for 'roundtrip' or '10' otherwise, and writes the modified config file with dynamic path substitutions.
def write_config_file(ckpt_folder, logs_folder, mode): if 'roundtrip' in mode: if not check_if_roundtrip_should_be_run(ckpt_folder): return if '50k' in mode: if not check_if_50k_should_be_run(ckpt_folder): return config_path, ckpt_path, data_path, logs_path, output_path =\ identify_p...
def load_reagents(path: str, fold: int, num_pred_per_instance: int = 1, standardize: bool = True) -> List[List[str]]: """ Load reagent strings from a file and chunk them into a list of lists of equal size. Parameters: path (str): The path to...
The code generates accuracy plots (Figure 4) for each fold by loading or computing clusters of predictions vs true reagents, calculating top-k accuracy matrices, and visualizing results. It handles data loading, clustering, and plotting for multiple folds, saving outputs in specified directories.
def do_plot(): for fold in FOLDS: data_path = os.path.join(FILE_DIR, 'fig45-x%s_data.pickle' % fold) # Load predictions and true labels and cluster by number of true reagents if LOAD_DATA: with open(data_path, 'rb') as f: clusters = pickle.load(f) ...
def filter_data_folders(additional_filters=[]): return [(folder, files) for folder, _, files in os.walk(DATA_DIR) if 'x1' in folder and 'x10' not in folder # and '-single' not in folder and '-noreag' not in folder and all([f in folder for f in additional_filters])] def filter_data...
The main task of the code is to generate SELFIES (Self-Referential Embedded String Representation) datasets by converting SMILES (Simplified Molecular Input Line Entry System) files from specified folders. It filters data folders and files, processes each SMILES file, and writes corresponding SELFIES files using a conv...
def create_selfies_datasets(): print('\nStarted generating selfies datasets from smiles datasets') for folder, files in filter_data_folders(additional_filters=['smiles', 'atom']): for smiles_file in filter_data_files(files): sm...
def create_smiles_datasets(): print('\nStarted generating smiles datasets') for task in TASKS: print('-- Task: %s' % task) for fold in FOLDS: print('---- Fold: %s' % fold) generate_augmented_dataset(task, fold) def create_selfies_datasets(): print('\nStarted generatin...
The main task of the code is to generate and prepare molecular data for machine learning tasks by creating SMILES, SELFIES, and SPE datasets, along with Word2Vec embeddings, ensuring reproducibility through a fixed random seed.
def main(): random.seed(1234) # this is enough for replicable augmentation create_smiles_datasets() # original data -> all tasks & data augmentations create_selfies_datasets() # smiles data -> selfies data create_spe_datasets() # smiles and selfies atom data -> spe data create_w2v_embeddings()