dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def opening_style(): col1, col2 = st.columns(2) col1.title(' Welcome to DTS2CSV!') col1.write('Hackathon Version, October 2021, Ver. 3.2 (1.0)') col2.image('https://raw.githubusercontent.com/AudricWannaz/DTS2CSV/main/dts2csv/logo.png') st.header('convert any DTS data in a CSV within seconds') def in...
The main task of the code is to structure a web application by initializing UI components, session state, and interactive elements. It sequentially calls functions to set up the opening style, manage session data, display a sidebar, handle user mode interactions, and finalize styling, creating a cohesive application fr...
def main(): opening_style() init_session_state() sidebar() mode_director() closing_style()
def pick_dval(name, base, override): if name in override: retval = override[name] return retval if retval else '' if name in base: retval = base[name] return retval if retval else '' return '' def build_zip_params(params): retval = '' if 'compression' in params: ...
The function determines the archive type from the job and arc parameters, defaults to '7z' if unspecified, and returns the corresponding command-line parameters by calling either build_zip_params or build_7z_params based on the archive type. If the type is invalid or missing, it returns an empty string or raises an err...
def build_cmd_format_params(arc, job): arc_type = pick_dval('type', arc, job) if not arc_type: arc_type = '7z' if not arc_type in job: return '' if arc_type == 'zip': return build_zip_params(job['zip']) elif arc_type == '7z': return build_7z_params(job['7z']) else...
def build_cmd_archive(arc, override): arc_name = pick_dval('out_dir', arc, override) if arc_name and not arc_name.endswith('/'): arc_name = arc_name + '/' arc_name = arc_name + arc['name'] if 'name' in override: arc_name = arc_name + '.' + override['name'] extension = pick_dval('...
This function constructs a command string for an application based on provided schema and job parameters, incorporating archive handling, strategy type (update, shadow, differential), threading options, and additional formatting parameters. It returns the final command and a patch name if applicable.
def build_cmd_app_idx(schema, jobs, index): cur_job = next((sub for sub in jobs.values() if sub['id'] == index), {}) app_path = '"{}"'.format(schema['app_path']) strategy = 'u' archive = schema['archive'] arc_name, patch_name = build_cmd_archive(archive, cur_job) strategy_type = 'update' if...
def collect_includes(schema): retval = [] jobs = schema['jobs'] for i in range(len(jobs)): cur_job = next((sub for sub in jobs.values() if sub['id'] == i), {}) if 'include' in cur_job: inc = cur_job['include'] if type(inc) != list: retval.append(inc) ...
Your return The function `build_cmd_app` processes a schema to generate commands (`retval`) and patches (`patches`) based on specified jobs. It checks for job existence, collects dependencies, and either executes a specific job (via `args.job`) or all jobs iteratively. Each job invokes `build_cmd_app_idx` to construc...
def build_cmd_app(schema): jobs = schema['jobs'] if 'jobs' in schema else {} retval = [] patches = [] if jobs: includes = collect_includes(schema) check_inc_collisions(includes) schema['all_includes'] = includes if args.job: cur_job = next((sub for sub in job...
def import_data(self, raw_path): """Importing csv as pandas DataFrame Parameters ---------- raw_path : str | Path Path to the csv file Returns ------- pd.DataFrame Contains data plus a Churn column """ path = Path(raw_path...
This method executes a machine learning pipeline by importing data, performing exploratory data analysis (EDA), encoding categorical features, conducting feature engineering, training models, and generating reports. It relies on configuration parameters stored in `self.conf` and model-specific settings in `self.model_p...
def run_pipeline(self): """Runs the whole pipeline Expects self.conf, and self.model_params to be set and complete """ self.import_data( self.conf["bank_data_path"] ) self.perform_eda(self.conf["images_eda_path"]) self.encoder_helper( sel...
def load_csv_regs(filename): regs = [] with open(filename) as csvfile: reader = csv.DictReader(csvfile) for row in reader: reg = {} reg['address'] = int(row['address']) reg['name'] = row['name'] reg['read'] = [row['read{}'.format(i)] for i in ran...
The code initializes an A7106 radio module by configuring GPIO pins for communication, loading register settings from a CSV file, and setting up parameters like channel ID, packet length, and hardware-specific pins. It prepares the hardware interface, disables GPIO warnings during setup, and applies initial configurati...
def __init__(self, id=0x930B51DE, channel=0, packet_len=64, pins={}): """ Initialize the A7106 radio """ if pins != {}: self.pins = pins GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) GPIO.setup(self.pins['cs'], GPIO.OUT, initial = GPIO.HIGH) GPIO.s...
def computeReward(self, currentUserId, currentSeqIndex, predictAction): # @param currentUserId, currentSeqIndex to get the real ActionsVector # use cos similarity to compute reward1 # use order to sompute reward2 # assume all input is a array in 2D realAction = self.generateRealA...
This function updates the environment state based on a user's predicted action. It calculates a reward, checks if the current state is terminal, and returns a tuple containing termination status, the next sequence index, the generated input vector for the next state, and the computed reward. The method advances the seq...
def update(self, currentUserId, currentSeqIndex, predictAction): ifTerminal = False reward = self.computeReward(currentUserId, currentSeqIndex, predictAction) if self.checkIfTerminal(currentUserId, currentSeqIndex): ifTerminal = True return (ifTerminal, currentSeqIndex + 1, s...
def demux_fastq(fastq, output_dir, barcodes=my_barcodes, barcode_assignments=my_barcode_assignments): barcode_counter = {'other':0, 'ACAAGT':0, 'AAGCAA':0, 'GGCTTG':0, 'TGGTCC':0, 'ATGACC':0, 'CAGCTT':0, 'GGATAC':0, 'TCCTGT':0} """ :param fastq: :param barcodes: :param barcode_...
The main task of the code is to process multiple FASTQ files by demultiplexing reads using specified barcodes, generating and saving barcode-specific read counts in the output directory, and summarizing overall metrics for analysis.
def master(fastq_files, output_dir, barcodes=my_barcodes): for fastq in fastq_files: counter_new = demux_fastq(fastq, output_dir, barcodes) format_and_save_barcode_counter(counter_new, output_dir, fastq) summarize_metrics(output_dir)
def parse_args(): parser = argparse.ArgumentParser(description='Infer the number of generations since admixture') parser.add_argument('file', metavar='data_file.hdf5') parser.add_argument('--profile', action='store_true') parser.add_argument('-m', '--min-bin-size', type=float, default=0.09, metavar='cen...
The main task of the code is to estimate the number of generations and genetic parameters (standard deviation, covariance) from genetic data stored in an HDF5 file. It processes input datasets (X, P, POS), validates the minimum bin size in centimorgans, and either profiles the computation using `cProfile` or calculates...
def main(): # Parse arguments args = parse_args() with h5py.File(args.file, 'r') as file: X, P, POS = map(hdf5_to_numpy, [file['X'], file['P'], file['POS']]) # Convert min_bin_size to morgans min_bin_size = args.min_bin_size / 100 if min_bin_size < 5e-4: raise Val...
def create_parser(): parser = argparse.ArgumentParser(description='Pipeline to run SR training ... ') parser.add_argument('--uid', type=str, help="sequence id for the experiment") parser.add_argument('--d', type=str, help="#id GPU device") parser.add_argument('--verbose', action=...
The code initializes and configures a machine learning model for training. It sets up arguments, random seeds, GPU resources, creates a model, prepares directories, executes training with specified parameters, and cleans up sessions. The main task involves model initialization, training execution, and environment setup...
def run(): # set args logging.info("initialize parser.") args = create_parser().parse_args() # set up the random seed logging.info("set up the random seed and verbose") set_up_random_seed(RANDOM_SEED, args.verbose) # set up gpu logging.info("set up GPU") set_up_gpu(args.d, args.ver...
def loadTable(self): input = crud.read(2, self.username, self.password) if input == False: return 0 entries = input.split(",") rowCount = int(len(entries)/3) row = 0 self.tableWidget.setRowCount(rowCount) index = 0 #print(input) #print...
The code initializes a main screen GUI for a password manager application, loading UI elements and connecting buttons to functions for adding entries, viewing/editing/deleting entries, changing passwords, and logging out. It sets up a stacked sidebar for different views, initializes user credentials, and prepares the i...
def __init__(self, username : str = "default", password : str = "default"): # Attempt for arguments in Main Screen super(MainScreen, self).__init__() uic.loadUi("ui/MainScreen.ui", self) self.username = username self.password = password self.tableLoaded = False # Legacy Variable ...
def isStick(self,node): neilst = [nei for nei in self.BipartiteG[node]] if len(neilst) == 1: if len([nei for nei in self.BipartiteG[neilst[0]]]) == 1: return True else: return False def redo_tree_weight(self,aG,nodeinTree=None,a=None,b=None): ''' ...
This code identifies a violating edge in a bipartite graph by checking if C[i,j] < f[i] + g[j] and neither node is "sticked." If found, it adds the edge to the graph. If the graph remains a forest, it adjusts weights and updates the complement; otherwise, it handles cycles via nudgeCycle. The goal is to iteratively opt...
def Update(self): # find a volating corrdinate violating = None for i in range(self.n): for j in range(self.m): if(self.P[i,j] > 0): continue else: if(self.C[i,j] < self.f[i] + self.g[j]): ...
def parse_config(self, config: dict): # get model config model_config = config["model"] # Parse model config self.model_config = model_config self.name = model_config.get("name") self.amp_config = model_config.get('vel_to_amp', {}) self.vel_config = model_config....
The code initializes an FWIModel by parsing configuration, constructing generators and discriminators (likely for GANs), setting up training/evaluation metrics, and performing a safety check. It disables automatic optimization, requiring manual optimization handling.
def __init__(self, config: dict): super(FWIModel, self).__init__() self.automatic_optimization = False self.parse_config(config) self.build_generators() self.build_discriminators() self.build_train_metrics() self.build_eval_metrics() self.safety_check()
def _normalize_indexes(self, indexes, is_group=False): """ To allow for the case where there are multiple inlines defined on a given ModelAdmin or InlineModelAdmin, we need indexes to be a list of lists (or at any rate an iterable of iterables, but lets call the outermost iterabl...
The function retrieves a specific element by normalizing input indexes, reordering them to prioritize the model name, fetching the corresponding group, and locating the element using an XPath constructed from the model name and adjusted item index.
def get_item(self, indexes): indexes = self._normalize_indexes(indexes) model_name, item_index = indexes.pop() indexes.append(model_name) group = self.get_group(indexes=indexes) return group.find_element_by_xpath(".//*[%s][%d]" % (xpath_item(model_name), item_index + 1))
def _normalize_indexes(self, indexes, is_group=False): """ To allow for the case where there are multiple inlines defined on a given ModelAdmin or InlineModelAdmin, we need indexes to be a list of lists (or at any rate an iterable of iterables, but lets call the outermost iterabl...
This code removes an inline item by normalizing input indexes, extracting the model name from the last index, constructing a CSS selector for a removal handler, and clicking the identified element to trigger removal.
def remove_inline(self, indexes): indexes = self._normalize_indexes(indexes) model_name = indexes[-1][0] remove_selector = "#%s .djn-remove-handler.djn-model-%s" % ( self.get_item(indexes).get_attribute('id'), model_name) with self.clickable_selector(remove_selector) as el: ...
def _normalize_indexes(self, indexes, is_group=False): """ To allow for the case where there are multiple inlines defined on a given ModelAdmin or InlineModelAdmin, we need indexes to be a list of lists (or at any rate an iterable of iterables, but lets call the outermost iterabl...
This code deletes an inline item in a Django admin interface by normalizing indexes, locating the appropriate delete element via CSS selectors, clicking it, and handling Grappelli-specific confirmation steps if enabled. It retrieves the model name and item ID, constructs dynamic selectors, and ensures clickable element...
def delete_inline(self, indexes): indexes = self._normalize_indexes(indexes) model_name = indexes[-1][0] item_id = self.get_item(indexes).get_attribute('id') delete_selector = "#%s .djn-delete-handler.djn-model-%s" % ( item_id, model_name) with self.clickable_selector...
def _normalize_indexes(self, indexes, is_group=False): """ To allow for the case where there are multiple inlines defined on a given ModelAdmin or InlineModelAdmin, we need indexes to be a list of lists (or at any rate an iterable of iterables, but lets call the outermost iterabl...
This code undeletes an inline item in a Django admin interface by locating and clicking a specific element identified by a CSS selector derived from the item's ID and model name. If using the Grappelli theme, it also waits for a corresponding delete handler element to become clickable, ensuring proper interaction with ...
def undelete_inline(self, indexes): indexes = self._normalize_indexes(indexes) model_name = indexes[-1][0] item_id = self.get_item(indexes).get_attribute('id') undelete_selector = "#%s .djn-delete-handler.djn-model-%s" % (item_id, model_name) with self.clickable_selector(undelete...
def admin_login(self, username, password, login_url='/admin/'): """ Helper function to log into the admin. """ self.selenium.get('%s%s' % (self.live_server_url, login_url)) username_input = self.selenium.find_element_by_name('username') username_input.send_keys(username) ...
This method navigates to a Django admin page for a model, logging in if necessary. It constructs a URL for adding or editing an object, ensures the user is authenticated, sets browser dimensions, loads the page, and initializes jQuery for DOM manipulation. The final step adjusts header/footer positioning for testing.
def load_admin(self, obj=None): info = (self.root_model._meta.app_label, self.root_model._meta.object_name.lower()) if obj: url = reverse('admin:%s_%s_change' % info, args=[obj.pk]) else: url = reverse('admin:%s_%s_add' % info) if not self.logged_in: s...
def _normalize_indexes(self, indexes, is_group=False): """ To allow for the case where there are multiple inlines defined on a given ModelAdmin or InlineModelAdmin, we need indexes to be a list of lists (or at any rate an iterable of iterables, but lets call the outermost iterabl...
This method sets a form field's value by normalizing indexes, locating the field via a selector, clearing its content, and inputting the provided value.
def set_field(self, attname, value, indexes=None): indexes = self._normalize_indexes(indexes) field_selector = self.get_form_field_selector(attname, indexes=indexes) with self.clickable_selector(field_selector) as el: el.clear() el.send_keys(value)
def _normalize_indexes(self, indexes, is_group=False): """ To allow for the case where there are multiple inlines defined on a given ModelAdmin or InlineModelAdmin, we need indexes to be a list of lists (or at any rate an iterable of iterables, but lets call the outermost iterabl...
This code adds a new inline form field to a Django admin interface by clicking an "Add" button, updates the index to reflect the new item, and sets optional name and slug attributes for the newly added inline item.
def add_inline(self, indexes=None, name=None, slug=None): indexes = self._normalize_indexes(indexes, is_group=True) new_index = self.get_num_inlines(indexes) model_name = indexes[-1] add_selector = "#%s .djn-add-item a.djn-add-handler.djn-model-%s" % ( self.get_group(indexes)...
def _analyze(self): self._analyze_nodes() self._analyze_edges() def parents(self, node): if self._is_a is None: self._analyze() id_ = node['id'] return [self.get_node(p) for p in self._is_a[id_]]
This function calculates the minimum depth of a given node relative to the root in a tree or graph structure. It uses memoization to store computed depths, recursively determining the shortest path by checking the minimum depth of the node's parents and adding 1, with roots having a depth of 0.
def min_depth(self, node): """Return length of shortest path from node to root.""" if self._is_a is None: self._analyze() id_ = node['id'] if id_ not in self._min_depth: parents = self.parents(node) if not parents: self._min_depth[id_] ...
def get_meta(node): metas = assure_list(node['meta']) if len(metas) != 1: raise FormatError('expected one meta, got {}'.format(len(metas))) return metas[0] def get_xrefs(meta): if 'xrefs' not in meta: return [] xrefs, vals = assure_list(meta['xrefs']), [] for xref in xrefs: ...
The function processes a node by extracting UniProt IDs from its metadata, warns if multiple IDs exist, generalizes the node to a family or gene based on options, and prints each UniProt ID mapped to the node's ID.
def process_node(node, graph, options): meta = get_meta(node) xrefs = get_xrefs(meta) uids = uniprot_ids(xrefs) if len(uids) > 1: warn('multiple UniProt IDs for {}: {}'.format(node['id'], uids)) orig, generalized = node, False if options.family: node = generalize_to_family(node, ...
def makeleapgen(a, b): # sets up move destinations, accounting for possible extension by riders def p1(board, src): # get all offsets (8 total, not necessarily unique, not necessarily in bounds) offsets = leapoffs(a,b) # turn into list of Moves moves = [Move(src, addlocs(src, o)...
The code generates a rider movement pathfinder by combining a leap generator with modifiers for boundary constraints, movement restrictions (no hopping), replacement capture rules, and friendly fire prevention, returning the final modified pathfinder.
def makerider( leap, range=-1, pf=pathfinders.idem, # extmods=[nowrap, noretrace], extmods=boundkeepers, aftmods=[nohop, replace, nofriendly] ): p1 = makeleapgen(*leap) # leap generator for riders as well # extmods = boundkeepers # idem = lambda l: [l]...
def makeleapgen(a, b): # sets up move destinations, accounting for possible extension by riders def p1(board, src): # get all offsets (8 total, not necessarily unique, not necessarily in bounds) offsets = leapoffs(a,b) # turn into list of Moves moves = [Move(src, addlocs(src, o)...
The function `makeleaper` generates valid leap moves for a chess piece between positions `a` and `b`, applying modifications to restrict out-of-bound moves, enable replacement of enemy pieces, and prevent friendly fire. It returns a list of modified move configurations after sequentially applying boundary checks, repla...
def makeleaper(a, b): p1 = makeleapgen(a,b) # # p2 = modify(p1, nowrap) # extmods = boundkeepers # no going out of bounds # # extendmod = lambda a, b: extend(a, b, extmods, 1, None) # # do not conflate extmods with extendmod # p2 = modify(p1, extend(extmods, 1, None)) # # print(p2) ...
def start_daemon(host, port, user): if read_pid_file(): print("Daemon is already running.") return command = ['python', DAEMON_SCRIPT, user, '--host', host, '--port', str(port)] with open(LOG_FILE, 'a') as log_file: process = subprocess.Popen(command, stdout=log_file, stderr=sub...
This code creates a command-line interface (CLI) tool for managing a remote daemon process. It supports commands to connect to a server (with user, host, and port parameters), stop, restart, check the status of, or view logs from the daemon. The `connect` command is the primary function, initiating the daemon with spec...
def main(): # Create the parser parser = argparse.ArgumentParser(description="Client for executing remote code.") subparsers = parser.add_subparsers(dest='command') connect_parser = subparsers.add_parser('connect', help='Connect to the server and start the daemon process') subparsers.add_parser('st...
def read_string(self): return self.read().decode('hex') def read_bool(self): return str(bool(self.read_string())) def read_int(self, size=2): return int(self.read(size), 16) def read(self, size=None, eat_null=True): if not size: size = self.data.find("00", self.index) - self.index if size % 2: size += 1 #...
The code reads a structured data entry from a binary stream, parsing fields like IP, name, status, type, map, player counts, and an unknown 4-byte value into a dictionary, using predefined methods for different data types.
def read_entry(self): entry = {} entry["ip"] = self.read_string() entry["name"] = self.read_string() entry["locked"] = self.read_bool() entry["type"] = types.get(str(self.read_int(2)), 'Unknown') entry["map"] = self.read_string() entry["players"] = self.read_int() entry["max"] = self.read_int() entry[...
def intro(noisy, sound, display, tune = False): """ Checking sound (song & text to speach convertor) and display (clear & . """ show_image(display, 'EV3') if (noisy): host_letter = socket.gethostname()[4] sound.speak('Hello, I am E V 3 ' + host_letter + '!') show_image(display, 'Neut...
This code creates an interactive menu system using buttons to navigate through sensor/motor options, displaying corresponding images and LED colors. It cycles through choices (0-5) via directional buttons, exits on Backspace, and triggers a sensor check on Enter. The 'noisy' parameter controls sound feedback, with LED ...
def main(noisy = True): """Select which test to start using the box buttons.""" sound = Sound() display = Display() looping = True choice = 0 button = Button() leds = Leds() colors = ['GREEN', 'YELLOW', 'AMBER', 'ORANGE', 'RED', 'BLACK'] img_nms = [ 'Large motor', 'Medium mot...
def sorted_slots(timeslots): return sorted(list(map(make_time, timeslots))) def dt_to_utc(d, t, fromtz): return ts(to_utc(fromtz, datetime.combine(d, t))) def next_timeslot(timeslots, tz): '''Check if job can be run today, depending on timeslots (if its too late to run a job), timeslots => ['1...
This function determines the next scheduled execution time based on provided 'exec_info', which includes date, days, and timeslots. It prioritizes a specified date with the earliest timeslot, checks if the job can run today (if 'days' match the current weekday), and returns the earliest valid timeslot. If not applicabl...
def get_scheduled_at(exec_info): """TO-REMEMBER- incase of date, it picks the first slot, need a check to ensure, user doesnt schedule for time, less than. """ tz = pytz.timezone(exec_info.get('timezone')) date = exec_info.get('date') timeslots = exec_info.get('timeslots') today = dateti...
def get_hour_offset(job): hour_count = job.every_hour latency = job.ran_at - job.scheduled_at if latency > job_latency_threshold: diff = int(latency / hour) hour_count += diff return hour_count * hour def next_timeslot(timeslots, tz): '''Check if job can be run today, depending on...
The function `get_next_ts` determines the next scheduled time for a job based on its configuration. If the job runs hourly, it calculates an offset to adjust for potential downtime and adds it to the scheduled time. Otherwise, it identifies the next valid timeslot using the job's timezone and timeslot definitions. If n...
def get_next_ts(job): scheduled_at = job.scheduled_at if job.every_hour: # if job runs on every hour basis, # get_hour_offset returns number of hours, # (to offset, in case worker was down) offset = get_hour_offset(job) return scheduled_at + offset tz = pytz.ti...
def add_death(character): new_index = death_df.shape[0] # add new row death_df.loc[new_index] = (character, pd.Timestamp('now')) # save file death_df.to_csv(death_file, encoding='utf8') # update death count file write_death_count(character) def create_inspiration_message(): # create cand...
The function `process_death` records a character's death by incrementing their death count, generates an inspirational message, and prints the death number along with a formatted score percentage. It then displays the inspirational message, providing feedback after each death event.
def process_death(character, score): add_death(character) inspiration_message = create_inspiration_message() print(f'Death # {get_death_count(character)} ({score*100:03.2f}%)', end='\t') #print(f'But, someone else in your shoes has said something like:\n') print(f'{inspiration_message}\n')
def get_gtdbtk_classifications(self, ar53_metadata_file, bac120_metadata_file, gtdbtk_output_dir, gtdbtk_prefix): """Get GTDB-Tk classification files.""" gtdbtk_ar...
This code translates GTDB-Tk classifications to NCBI taxonomy using majority voting. It parses GTDB-Tk assignments, constructs classification trees, extracts NCBI taxonomy data, and maps GTDB species clusters to NCBI ranks. The final step assigns NCBI classifications to genomes via majority vote within species clusters...
def run(self, gtdbtk_output_dir, ar53_metadata_file, bac120_metadata_file, gtdbtk_prefix, output_file): """Translate GTDB to NCBI classification via majority vote.""" # create output file directory if required output_dir = os.path.dirn...
def random_fancy_business(fancy_city): starting_point = random_page_num(fancy_city) * 10 # pages are 10 businesses apart random_page_url = '{0}/search?find_desc=&find_loc={1}&ns=1#start={2}&attrs=RestaurantsPriceRange2.4'.format( BASE_URL, fancy_city, starting_point ) random_page = parsed_response(random_pa...
The function `find_angry_review` recursively searches for a one-star or two-star review of a randomly selected business in a "fancy" city. It prioritizes one-star reviews, falling back to two-star if unavailable, and restarts the process if neither is found, ensuring a negative review is eventually returned.
def find_angry_review(): fancy_city = random.choice(fancy_cities) random_business = random_fancy_business(fancy_city) one_star_review = random_review(random_business, 1) if one_star_review: return one_star_review else: two_star_review = random_review(random_business, 2) if two_star_review: r...
def init_dungeon(d_width, d_height): """ This function sets every square in the dungeon to wall dungeon size generated by the dungeon size function. Function creates a paired dictonary with an x,y coordinate: and True This will create a rectangle with all squares set to wall. """ dungeon_ma...
This function determines a dungeon's size, generates its map with rooms, player, boss, and monsters, and saves it to Google Sheets. If a map exists for the character, it loads it; otherwise, it prompts the user to choose a size (S/M/L), creates the dungeon, and uploads the generated map.
def dungeon_size(stdscr, character): """ This function decides the size of the map and runs all the individual dungeon generation functions if a map already exists for the character it will load that instead """ # Fetch data from google sheets existing_map = str(SHEET.worksheets()) cha...
def player_select(stdscr): """ This function reads the google sheet for characters with the status = "alive", and allows the players to select an alive character or choose a new one """ players = SHEET.worksheet("players") player_data = players.get_all_values() alive_characters = [] ...
The main task of the code is to initialize and orchestrate a game by first allowing the player to select a character, then determining the dungeon size based on the character, and finally setting up the game screen with the chosen character and dungeon parameters. The `main` function serves as the entry point to sequen...
def main(stdscr): """ main function to call other functions """ character = player_select(stdscr) dungeon_size(stdscr, character) gamescreen(stdscr, character)
def calc_threshold(self, data): """Calculate the recommended threshold for spike detection based on the variance of a set of data INPUTS: data: data which is to undergo peak detection OUTPUTS: recommended threshold""" return self.params['thK'] * np.median...
The code performs cross-validation for a spike sorter by applying spike sorting with predefined parameters, generating a confusion matrix to evaluate classification accuracy, and optionally plotting results. It calculates metrics like false positives, false negatives, and accuracy, returning a dictionary of performance...
def cross_validate(self, plot=True, plotFalseNegs=False): """Perform cross-validation using the training data INPUTS: plot: bool, if True, plot the confusion matrix plotFalseNegs: bool, if True, plot false negative waveforms OUTPUTS: results: dict with keys: ...
def filter(self, data, fs): """Function to filter as signal using wavelet denoising and finds the peak detection threshold based on the variance of the filtered signal INPUTS: data: data to be filtered fs: sampling frequency of the data OUTPUTS: filtd:...
This class performs spike sorting using wavelet decomposition and SVM classification. It initializes parameters for data filtering, wavelet denoising, spike detection, and SVM training. Key steps include filtering training data, extracting labeled spike clips, generating training/test sets, detecting false positives, a...
def __init__(self, data, sub_data, hpFreq, Fs, denoisingWavelet, denoisingLevel, \ denoising_thresh_coeff, thK, labels, training_data_ratio, \ clipSize, clipDistDef, dwtWavelet, svmKernel, evalTol, fp_rejection): """Spike Sorter Class based on wavelet decomposition and SVM classification INP...
def _get_content_loss(self, generated_features, content_features): return F.mse_loss(generated_features[self.content_idx], content_features[self.content_idx]) def _get_style_loss(self, generated): generated_gramms = self._get_gramms(generated) # to numpy loss = 0 for x_gramm, y_...
This code computes a mixed loss combining content, style, and edge (Sobel) losses for image generation tasks. It extracts features from generated and content images, calculates individual losses using predefined methods, and weights them to produce a total loss for optimization.
def forward(self, generated, content): generated_features = self.extractor(generated) content_features = self.extractor(content) content_loss = self._get_content_loss( generated_features, content_features) style_loss = self._get_style_loss(generated_features) sobel_l...
def get_most_recent_entry(csv_file: str) -> str: with open(csv_file, "rb") as file: try: file.seek(-2, os.SEEK_END) while file.read(1) != b'\n': file.seek(-2, os.SEEK_CUR) except OSError: file.seek(0) last_line = file.readline().decode() ...
The code retrieves historical web snapshots from the Wayback Machine for a specified website, processes each snapshot's HTML content to extract structured data (IDs and PP values) from a table, and appends this data to a CSV file. It avoids duplicating entries by skipping timestamps already present in the CSV and uses ...
def get_snapshots(csv_file: str) -> None: start_day = get_most_recent_entry(csv_file) start_d = date(2007,10,11) + timedelta(days=int(start_day)) start_timestamp = date_to_timestamp(start_d) with request.urlopen("http://web.archive.org/cdx/search/cdx?url=" + websites[cur_website] + "&output=json&from=...
def num_ranks_in_line(line: list[str]) -> int: return (len(line) - 1) // 2 def player_pp_on_day(id: str, day: int, csv_data: List[str], start_line_num: int, end_line_num: int) -> int: ''' day must be within the range of days spanned by start_line_num and end_line_num ''' print(start_line_num, " ", e...
The code processes a CSV file to generate a new file by grouping consecutive lines into blocks where each block contains at least 50 ranks. It extracts unique player IDs, calculates their performance points for each day, sorts them, and writes the top 50 entries per day to the new file. The process iterates through the...
def make_continuous(csv_file: str, new_file: str) -> None: with open(csv_file, "r") as f_csv: csv_data = f_csv.readlines() with open(new_file, "w") as f_new: i = 0 while i < len(csv_data) - 1: print(i) start_line_num = i end_line_num = i+1 ...
def file_len(fname): ''' This function returns the height and width of the maze :param fname: File name :return: height, width of the maze ''' with open(fname) as f: for i, l in enumerate(f): pass width = len(l.replace(" ", "")) if (width % 2 != 0): ...
The main task of the code is to solve a maze by determining the shortest exit path from the start node (0,0) to the exit node (height-1, width-1) using multiple algorithms. It employs A* search with four distinct heuristic functions (Manhattan, Euclidean, Diagonal, and Random) and Iterative Deepening DFS (IDS). The cod...
def main(): ''' The main function reads the graph file and prints out how quickly you can exit from each node and whether an exit is possible or not ''' if(len(sys.argv)<2): filename="maze.txt" else: filename=sys.argv[1] height, width = file_len(filename) exit =...
def __process_arguments(args: list) -> Tuple[list, bool]: parser = ArgumentParser( description="Builds the benchmarks.", allow_abbrev=False) parser.add_argument( '-v', '--verbose', required=False, default=False, action='store_true', help='Turns on verbosi...
The main task of the code is to build and run a .NET project using specified configurations and frameworks, processing command-line arguments, setting up logging, validating the runtime, executing `dotnet build`, and running benchmarks for each target framework. It handles errors like process failures, I/O issues, and ...
def __main(args: list) -> int: try: validate_supported_runtime() args = __process_arguments(args) configuration = args.configuration frameworks = args.frameworks incremental = args.incremental verbose = args.verbose target_framework_monikers = FrameworkAction...
def _is_surrounded(self, point, color): """ check whether empty point is surrounded by stones of color. """ for nb in self._neighbors(point): nb_color = self.board[nb] if nb_color != BORDER and nb_color != color: return False return True de...
This function plays a move of the specified color on the given point in a Go game, checking legality by validating if the point is empty, not a ko recapture, and ensuring the move doesn't result in suicide. It handles captures, updates the board, and manages ko rules, returning True if the move is legal and updating th...
def play_move(self, point, color): """ Play a move of color on point Returns boolean: whether move was legal """ assert is_black_white(color) # Special cases if point == PASS: self.ko_recapture = None self.current_player = GoBoardUtil.oppon...
def info(args, message): if args.shout: print(f"✨ {message}") def align_css_file(args): with open(args.filepath, 'r', encoding = 'utf-8') as f: new_filename = f"{uuid.uuid4().hex}.css" with open(new_filename, 'w', encoding = 'utf-8') as new_f: ...
The main task of the code is to align CSS parameter-value pairs in a file by parsing command-line arguments for indentation, left/right spacing, and file path. It processes the specified CSS file, adjusts formatting according to user-defined settings, and outputs a confirmation upon successful alignment.
def main(): parser = argparse.ArgumentParser(description = "Aligner of css param-value splitter") parser.add_argument("filepath", type = pathlib.Path, help = "Set path of the file which you want to align") #? Aligning settings #? _ = space character #? div { #? ____border____:____1px...
def schedule_qty(shift,position): selection = 1 finalize = 1 v = 0 db, cur = db_set(request) JCsql = "SELECT count(*) from tkb_schedule where Shift='%s' and Position='%s' and Selection='%s' and Finalize !='%s'" % (shift,position,selection,finalize) cur.execute(JCsql) tmp = cur.fetchall() tmp2 = tmp[0] tmp_J_...
The main task of the code is to handle scheduling form requests by processing POST data to add/delete jobs, validating existing schedules, updating session variables, and redirecting users or rendering templates based on input. It checks for position/shift changes, ensures no duplicate schedules, and passes data to sub...
def schedule_set4(request,list): shift = request.session["matrix_shift"] try: position = request.session["position"] except: position = 'CNC' qty_jobs, qty_employee, tmp_count = schedule_qty(shift,position) A='Jobs' B='Employee' #return render(request, "testA.html", {'A':A,'a':qty_jobs,'B':B,'b':qty_employe...
def fetch_data(ticker, time_interval): end_date = datetime.today().date() start_date = end_date - timedelta(days=59) data = yf.download(ticker, start=start_date, end=end_date, interval=time_interval) return data def calculate_candlestick_characteristics(data): data['Open'] = pd.to_numeric(data['Ope...
The main task of the code is to backtest a trading strategy by analyzing historical market data. It fetches data, calculates candlestick characteristics, detects patterns, simulates trades based on these patterns, and evaluates performance metrics like profit, win/loss ratios, and trade dates. The process includes gene...
def backtest(): data = fetch_data(ticker, time_interval) data_with_characteristics = calculate_candlestick_characteristics(data) pattern_results, data_with_pattern = detect_patterns(data_with_characteristics) first_trade_date, last_trade_date = pattern_table(pattern_results) data = data_with_pattern...
def _call_lie(self): # Stop the betting in the bet machine loop and see if the previos player was lying self.bet_stopper = True all_dice_count = 0 bet_loser = 'player0' print(f"{self.current_player_pointer.capitalize()} calls a lie on {self.previous_player_pointer.capitalize()}.....") print(f"Th...
The main task of the code is to handle a human player's betting decision in a turn-based game. If the current player is 'player1', it prompts them to either call a lie ('c') or raise ('r'), updating the game state accordingly. If the current player is a bot, it triggers the bot's turn logic. The function ensures valid ...
def _player_bet(self): # If the human player is on turn, show a menu with options if self.current_player_pointer == 'player1': bet = '' print(f"Current bet is {self.current_bet[0]} of {self.current_bet[1]}") while bet != 'c' and bet != 'r': bet = input("Do you want to raise [r] or ca...
def _check_for_end(self) -> bool: return (self._number_of_players() < 2 or 'player1' not in self.players) def _display_player_row(self): self.players['player1'].get_hand() def _bet_machine(self): # the first player makes a bet # But the first player can be a bot too self._raise() while not sel...
The main task of the code is to manage a game loop that repeatedly checks for winning conditions, rolls dice for players and bots, displays results, processes betting, and increments the round counter until a win/loss condition is met. It concludes by printing a victory or defeat message based on whether 'player1' rema...
def main_loop(self) -> None: while True: # Check for winning conditions if self._check_for_end(): break # Row dices of player and bots for i in self.players.values(): i.row_dice() self._display_player_row() # Start the betting self._bet_machi...
def get_level_from_screen(): screen = ACTIVE_SCREEN return int(screen.split('_')[1]) def place_common_elements(): global CURRENT_LEVEL_NUMBER SCREEN.blit(IMAGES['gate-zone'], (150, 10)) current_output_image_name = 'assets/level/outputs/level_' + str(CURRENT_LEVEL_NUMBER) + '.png' output_image ...
This function draws the current level by clearing existing sprites and free spaces, retrieving the level data, placing common elements and gates, calculating vertical positions for cats based on their count, and rendering each cat row at a centered Y-coordinate while managing sprite groups and free space tracking.
def draw_level(): global LEVELS, CURRENT_LEVEL_NUMBER, MOVING_SPRITES, FREE_SPACES_GROUP, FREE_SPACES_LIST MOVING_SPRITES.empty() FREE_SPACES_GROUP.empty() FREE_SPACES_LIST.clear() CURRENT_LEVEL_NUMBER = get_level_from_screen() current_level = PLAYABLE_LEVELS.get_levels()[CURRENT_LEVEL_NUMBER]...
def init(self): if self._initialized: raise ValueError('Already initialized - call reset method to start over') self.solutions = self.init_fn(self.population_size) shape = self.solutions.shape num_solutions = shape[0] self.dimension = shape[1] if num_soluti...
The code performs a search using a swarm-based optimization algorithm (e.g., Artificial Bee Colony). It iterates up to `max_generations`, executing foraging steps (employed bees, onlooker bees, scout bees) to explore solutions. Termination is checked each iteration, and user-defined callbacks are invoked at each genera...
def search(self, max_generations): if not self._initialized: self.init() # Call user defined function at generation 0 if self.callback_fn is not None: self.callback_fn(self, logger) for _ in range(max_generations): self.generation += 1 se...
def _check_fleet_edges(self): """check if the alien hits edge""" for alien in self.aliens_group.sprites(): if alien.check_edges(): self._change_fleet_direction() break def _check_bullet_alien_collision(self): """ checks for collision of bullets...
The main task of the code is to manage alien behavior in a game, including checking collisions between bullets and aliens, aliens and the ship, aliens reaching the bottom, and updating alien movement. It also triggers direction changes when aliens hit edges, ensuring proper game mechanics and interactions.
def _update_aliens(self): """manage movement of aliens""" # checks if alien fleet hits edges. # it inherently calls fleet's direction changing method self._check_fleet_edges() # method to check if bullet hit alien self._check_bullet_alien_collision() # #...
def _key_down_events(self, event): # until the key remains pressed down, ship.moving.right flag remains true # hence the ship.update() will keep moving # ship's position (ship.rect.x) to right(i.e. adding ship_speed value to x attribute of ship's rect (ship.rect.x)) # move ship right ...
The main task of the code is to handle user input events in a Pygame application. It processes keyboard presses/releases, mouse clicks, and checks for a quit event to exit the game. Specifically, it triggers methods for key actions and verifies if the play button is clicked by capturing mouse positions.
def _check_events(self) : # watch keyboard and mouse events for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.KEYDOWN: self._key_down_events(event) elif event.type == pygame.KEYUP: ...
def _check_events(self) : # watch keyboard and mouse events for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.KEYDOWN: self._key_down_events(event) elif event.type == pygame.KEYUP: ...
The code defines the main game loop that runs indefinitely until a QUIT event is triggered. It checks for events, updates the ship, bullets, and aliens' positions if the game is active, and continuously renders the screen to reflect gameplay changes.
def run_game(self): """ Main game loop """ # running game window infinitely until QUIT event is triggered while True: # helper method to check for events self._check_events() if self.stats.game_running: # update ships position...
def load_instructions(): instructions = file_get_contents( os.path.join(os.environ['LIBOQS_DIR'], 'scripts', 'copy_from_upstream', 'copy_from_upstream.yml'), encoding='utf-8') instructions = yaml.safe_load(instructions) upstreams = {} for upstream in instructions['upstreams']: up...
This function synchronizes LIBOQS test data and configurations by loading KATs (Known Answer Tests) from upstream JSON files, updating code and config files with replacement instructions, rewriting KATs back to files, and triggering documentation and CBOM updates. It also conditionally removes the 'repos' directory.
def copy_from_upstream(): for t in ["kem", "sig"]: with open(os.path.join(os.environ['LIBOQS_DIR'], 'tests', 'KATs', t, 'kats.json'), 'r') as fp: kats[t] = json.load(fp) instructions = load_instructions() process_families(instructions, os.environ['LIBOQS_DIR'], True, True) replacer(...
def get_waveform( path_or_fp: Union[str, BinaryIO], normalization=True, mono=True, frames=-1, start=0, always_2d=True ) -> Tuple[np.ndarray, int]: """Get the waveform and sample rate of a 16-bit WAV/FLAC/OGG Vorbis audio. Args: path_or_fp (str or BinaryIO): the path or file-like object ...
The main task of the code is to extract mel-filter bank features from an audio waveform using PyKaldi (preferred for speed) or TorchAudio, returning a numpy array. It ensures input waveforms are 16-bit unsigned integers without normalization, prioritizing PyKaldi, and raises an error if neither library is installed.
def get_fbank(path_or_fp: Union[str, BinaryIO], n_bins=80) -> np.ndarray: """Get mel-filter bank features via PyKaldi or TorchAudio. Prefer PyKaldi (faster CPP implementation) to TorchAudio (Python implementation). Note that Kaldi/TorchAudio requires 16-bit signed integers as inputs and hence the wavefo...
def discretise(self, observation): b0 = self.get_discretised_bucket(0,observation[0]) b1 = self.get_discretised_bucket(1,observation[1]) b2 = self.get_discretised_bucket(2,observation[2]) b3 = self.get_discretised_bucket(3,observation[3]) discretised = b0, b1, b2, b3 ret...
The code simulates an episode in a reinforcement learning agent, interacting with an environment by selecting actions, receiving rewards, and updating internal knowledge. It discretizes observations, accumulates total reward, applies a penalty if the episode ends, and returns the reward sum. The loop continues until th...
def attempt(self): observation = self.discretise(self.environment.reset()) done = False reward_sum = 0.0 while not done: if self.render: self.environment.render() action = self.pick_action(observation) new_observation, reward, done, inf...
def _exec_run(self, command, **kwargs): # Set pyenv dir, otherwise it will detect the original pyenv which is inaccessible command = 'PYENV_DIR={} {}'.format(self.path, command) # Wrap with firejail if settings.VirtualEnv.USE_FIREJAIL: network = '' if self.network else ' --ne...
This code initializes a Python virtual environment by creating a working directory, installing pyenv (if configured), setting up a virtualenv with a specified Python image, upgrading pip, and symlinking or copying volume directories based on firejail configuration.
def start(self): # Create working folder and cd os.makedirs(self.path, exist_ok=True) os.chdir(self.path) # Provide pyenv for firejail if settings.VirtualEnv.USE_FIREJAIL: self._exec_run('curl https://pyenv.run | bash') self._exec_run('pyenv install {}'.fo...
def log(self, message, log_type='info'): getattr(logger, log_type)("[TS={}, A={}, R={}, M={}] {}".format(self.ts_id, self.agent_id, self.runner_type, self.metadata, message)) def pull_image(self): self.log('Pulling image: {}'.format(self.image)) client.images.pull(self.image) def run_container(self): self.log('...
This code runs a containerized task with time limits, installs dependencies, executes a runner script, validates JSON output, saves results, handles errors, and cleans up resources. It logs progress, enforces size limits, and supports interactive mode.
def run(self, interactive=False): self.log('Running container: TS.{}, A.{}, RT.{}, RTL.{}'.format(self.ts_id, self.agent_id, self.runner_type, self.run_time_limit)) output = (None, None) # (error, data) try: with utils.time_limit(self.pull_time_limit, 'Image pull time limit exceeded'): self.pull_image() ...
def _compute_meta_dataframe(links): """Convert links to a pandas DataFrame object """ import pandas as pd from wiki import get_wiki_json links = list(set(links)) meta = dict(link=[], title=[], doc=[], num_sections=[], num_images=[], num_ilinks=[], num_elinks=[], ...
This code initializes a text analysis model by processing input links to compute metadata, build a TF-IDF model, generate LDA topics, and cluster documents using spectral clustering based on similarity matrices. It handles stopword filtering, sets default parameters, and integrates gensim tools for topic modeling and s...
def __init__(self, links, stopwords=True, num_topics=40, num_clusters=40, **kwargs): from gensim.models import TfidfModel from gensim.similarities.docsim import MatrixSimilarity if 'n_below' not in kwargs: kwargs['n_below'] = 5 if 'n_above' not in kwargs: ...
def _make_custom_css(output_dir): """Output custom CSS file for """ import os ctext = "html{min-height:100%;position:relative}body{margin-top:50px;z-" \ "index:0}@media (min-width: 992px){body{margin-bottom:113px}}.s" \ "ection{}.hidden{display:none}a{text-decoration:none;color:...
The main task of the code is to generate a visualization webpage for exploring text data, creating multiple HTML files (docs, index, clusters, topics, viz) in a specified directory. It uses cluster/topic metadata from an input JSON or a corpus to structure the pages, leveraging XML parsing and custom CSS for formatting...
def wiki_text_explorer(wcorp, input_file=None, output_dir="text-explore"): """Produce visualization webpage. Args: input_file: Optional path to a json file that describes cluster and topic names. output_dir: Directory name of where to build the explorer. """ from xml...
def forward(self, inputs): """ This function performs a simple foward pass through the model for the given minibatch. Parameters: inputs : A tensor of size=(batch_size, 784) containing the flattened inputs for each image in the dataset. Returns: self.out2 : A numpy arra...
The code trains a neural network using stochastic gradient descent (SGD) over multiple epochs. It processes training data in minibatches, flattens 28x28 images, performs forward passes, computes gradients via backpropagation, and updates weights. After each epoch, it evaluates model performance on a validation set, log...
def train(self, train_loader, val_loader): """ This function trains the neural model over the epochs defined, updating its weights after each minibatch and also computing the test error after each epoch. Parameters: train_loader : The torch dataloader for the training set. val_l...
def scatter_3d(data, labels, i): fig = plt.figure() ax = plt.axes(projection="3d") ax.scatter3D(data[0], data[1], data[2]) ax.set_xlabel(labels[0]) ax.set_ylabel(labels[1]) ax.set_zlabel(labels[2]) fig.savefig(f'results/charts/3d_{i}.png') def scatter_2d(data, labels, i): fig = plt.figur...
The code generates 2D and 3D scatter plots to visualize trade-offs among four metrics (proportion, compatibility, compactness, difficulty of change) for solutions in P, creates line plots tracking metric evolution over iterations from H, identifies optimal solutions, and produces a table comparing initial vs. best solu...
def report(P, H): try: os.mkdir('results/charts') except: pass fit = np.array([np.array([proportion(p), compatibility(p), compactness(p), -difficulty_of_change(p)]) for p in P]) labels = ['proportion', 'compatibility', 'compactness', 'difficulty of change'] scatter_3d([fit[:, 0], fit...
def mutation(C): return np.array(list(map(path_based_mutation, C))) def edge_crossover(P): n = P.shape[0] parents1 = np.random.randint(0, n, size=n // 2) parents2 = np.random.randint(0, n, size=n // 2) edges = np.array(list(map(edge_cells, P))) children = np.concatenate([P[parents1, :], P[parent...
The main task of the code is to perform a crossover operation on a parent solution P by first applying an edge-based crossover, then applying multiple constraint-driven edge mutations to the resulting candidate solution, ensuring it adheres to problem constraints through iterative refinements.
def crossover(P): C = mutation(edge_crossover(P)) for i in range(properties['edge_mutation_size']): constraint_edge_mutation(C) return C
def mutation(C): return np.array(list(map(path_based_mutation, C))) def box_crossover(P): n = P.shape[0] h = P.shape[1] w = P.shape[2] parents1 = np.random.randint(0, n, size=n // 2) parents2 = np.random.randint(0, n, size=n // 2) H1 = np.random.randint(0, h, size=n // 2) H2 = np.random....
The main task of the code is to perform a genetic algorithm operation by first applying a box crossover to input P, then mutating the result, followed by multiple edge-specific mutations constrained by the 'edge_mutation_size' property to refine the output configuration.
def crossover2(P): C = mutation(box_crossover(P)) for i in range(properties['edge_mutation_size']): constraint_edge_mutation(C) return C
def _get_app_kwarg_dict(appInstance=None): ''' Returns the dictionary of CORS specific app configurations. ''' app = (appInstance or current_app) return dict( (k.lower().replace('cors_', ''), app.config.get(k)) for k in CONFIG_OPTIONS if app.config.get(k) is not None ...
The main task of the code is to handle Cross-Origin Resource Sharing (CORS) for a Flask route by configuring CORS options, generating an appropriate response (including automatic OPTIONS handling), applying CORS headers to the response, and marking the response as evaluated for Flask-CORS tracking.
def wrapped_function(*args, **kwargs): # Handle setting of Flask-Cors parameters options = {} options.update(_defaults_dict) options.update(_get_app_kwarg_dict()) options.update(_options) _serialize_options(options) logger.debug("Reque...
def _try_match(pattern, request_origin): ''' Safely attempts to match a pattern or string to a request origin. If a pattern is an illegal regular expression ''' try: return re.match(pattern, request_origin) except: return request_origin == pattern def _serialize_options(...
This function handles CORS (Cross-Origin Resource Sharing) by adding appropriate headers to HTTP responses. It checks if CORS headers are already present; if not, it matches the request path against predefined regex patterns. If a match is found, it applies associated CORS options, logs the match, and sets the headers ...
def cors_after_request(resp): ''' The actual after-request handler, retains references to the the options, and definitions of resources through a closure. ''' # If CORS headers are set in a view decorator, pass if resp.headers.get(ACL_ORIGI...
def get_user_input(): print("1. Add to playlist") print("2. Print") print("3. Both") print("q. (Q)uit") ustring = input("Please enter input: ") if ustring.lower() == "q": quit() else: return ustring def get_music(plex, dt): albums = [] music = plex.library.section(f...
This function retrieves music albums for each day of the current week, processes them based on user input (add to playlist, print/export, or both), and iterates through seven days. It uses the Plex library to interact with media, checks the current date, and performs actions like playlist creation or data output depend...
def get_albums_released_for_week(plex): ustring = get_user_input() dt = datetime.datetime.today() for x in range(7): day_of_week = dt.weekday() week_name = dt.strftime('%A') albums = get_music(plex, dt) if ustring == "1": add_to_playlist(plex, f"{day_of_week} ...
def get_user_input(): print("1. Add to playlist") print("2. Print") print("3. Both") print("q. (Q)uit") ustring = input("Please enter input: ") if ustring.lower() == "q": quit() else: return ustring def get_music(plex, dt): albums = [] music = plex.library.section(f...
The code retrieves music albums released today from a Plex server, then handles them based on user input: option 1 or 3 adds them to a "Released Today" playlist, option 2 or 3 also prints/writes album details sorted by date with age-based formatting. The main task is fetching and managing newly released music data acco...
def get_albums_released_today(plex): ustring = get_user_input() dt = datetime.datetime.today() albums = get_music(plex, dt) playlist = "Released Today" if ustring == "1": add_to_playlist(plex, playlist, albums) elif ustring == "2": print_and_write(albums, playlist, SortType.da...
def get_plex_server(config): plex_config = config['PLEX'] baseurl = plex_config.get('URL') token = plex_config.get('TOKEN') return PlexServer(baseurl, token) def get_albums_released_today(plex): ustring = get_user_input() dt = datetime.datetime.today() albums = get_music(plex, dt) play...
The code presents a menu-driven interface to query a Plex server for album data. It allows users to retrieve albums released today, all albums' release dates, play counts, or weekly releases. The program reads configuration settings, connects to the Plex server, and executes the selected task based on user input, exiti...
def main(): print("1. Get Albums Released Today") print("2. Get All Albums Released Dates") print("3. Get Albums Play Count") print("4. Get Albums Released For The Week") print("q. (Q)uit") ustring = input("Please enter input: ") if ustring.lower() == "q": quit() config = Conf...
def global_mean_calculation(): """ calculate the global mean if the data of all clients arrived """ current_app.logger.info('[API] run global_mean_calculation') global_norm = redis_get('global_norm') nr_clients = redis_get('nr_clients') np.set_printoptions(precision=30) if len(global_nor...
The code handles GET/POST requests for data exchange between a master and slaves in a distributed computing setup. It manages Redis-stored data for steps like covariate intersection, normalization, model initialization, and convergence. POST requests aggregate slave data (e.g., covariates, means, stats), while GET requ...
def data(): """ GET request to /data sends data POST request to /data pulls data :return: GET request: JSON with key 'data' and value data POST request: JSON True """ master = redis_get('master') master_step = redis_get('master_step') slave_step = redis_get('slave_step') ...
def local_variance_calculation(): """ calculate variance of the local dataframe and send to the master """ # calculate local variance using the global mean global_mean = redis_get("global_mean") X = redis_get("X") variance = np.mean((X - global_mean) ** 2, axis=0) if redis_get...
The code handles a GET request to `/status`, checks Redis for the current processing step, logs system state, and triggers specific tasks (e.g., calculations, time tracking) based on the step. It returns a JSON indicating system availability (`True`/`False`) or signals completion if the process is finished, updating Re...
def status(): """ GET request to /status, if True is returned a GET data request will be send :return: JSON with key 'available' and value True (/data GET request) or False (/data POST request) """ current_app.logger.info('[API] /status GET request') cur_step = redis_get('step') available =...
def move_reward(state,new_pos,pos,visited_positions,reward_ctr): """ Reward movement related events. """ if new_pos in visited_positions: reward_ctr -= 4 else: reward_ctr += 2 return reward_ctr def get_closest_object(objects,pos): close_object = (0,0) old_distance = 100...
This function calculates a reward value for an agent's actions in a game, integrating environmental elements (crates, coins, enemies) and events. It evaluates movement, proximity to objects, bomb handling, and event outcomes using radar checks and predefined reward values, summing them to determine the total reward for...
def n_sarsa_reward(self,crates,events,i,game_state): crates = self.target_crates_history[i][:] coins = self.target_coins_history[i][:] bombs = self.bomb_history[i][:] enemies = self.target_enemy_history[i][:] state = self.state_history[i] pos = self.visited_positions[i] visited_positions =...
def n_sarsa_reward(self,crates,events,i,game_state): crates = self.target_crates_history[i][:] coins = self.target_coins_history[i][:] bombs = self.bomb_history[i][:] enemies = self.target_enemy_history[i][:] state = self.state_history[i] pos = self.visited_positions[i] visited_positions =...
The main task of the code is to update the value function and policy using an n-step SARSA algorithm with an epsilon-greedy strategy. It calculates rewards for past events, computes discounted returns, adjusts the value function with a learning rate, and updates the policy to prioritize high-value actions while maintai...
def n_sarsa(self,game_state,crates): i = 0 for event in self.event_history: self.reward_history.append(n_sarsa_reward(self,crates,event,i,game_state)) i+=1 if game_state['round'] < 5000: epsilon = 0.4 elif game_state['round'] >= 5000 and game_state['round'] < 10000: ep...
def get_calls_in_car_duplicated(current_sol, veh, n_veh, index_changing_car, chosen_veh): ''' return calls_in_car (the calls that are inserted in the chosen_veh, exactly how they are in the solution) ''' if(chosen_veh < n_veh -1): calls_in_car = current_sol[index_...
This function checks if inserting a specific call into a chosen vehicle would exceed its capacity. It duplicates the current solution, verifies if the call is already in the vehicle, inserts the call if not present, and then checks the vehicle's capacity against the problem constraints. If the vehicle is not the last o...
def is_car_full_with_call(prob, copy_current_sol, chosen_call, chosen_veh, veh, n_veh, index_changing_car): ''' return True/False (check if you are over the capacity of chosen_veh after inserting chosen_Call) ''' if(chosen_veh < n_veh - 1): sol = copy_current_sol[...
def obtain_cost_call_in_car(prob, chosen_call, chosen_veh): ''' return cost_car (cost of chosen_veh transporting chosen_Call) ''' if(chosen_veh == prob.get('n_vehicles')): return prob['Cargo'][chosen_call-1][3] else: return prob['PortCost']...
This function identifies the optimal vehicle and insertion position for a call in a routing problem by evaluating cost and capacity constraints. It filters valid vehicles, normalizes costs using a heuristic, selects the best candidate, and determines the best insertion positions. If no valid option exists, it defaults ...
def get_best_car_best_position(prob, chosen_call, current_sol, veh, n_veh, index_changing_car): ''' return best_car, pos1, pos2, cost ''' costs_car = [] cars = [] best_cars = [] for i in range(n_veh): cost_car = obtain_cost_call_in...
def round(val): return '%.2f' % val def safe_division(a, b): return a / b if b else 0 def get_lexical_complexity_score(self, sentence): words = tokenize(remove_stopwords(remove_punctuation(sentence))) words = [word for word in words if word in get_word2rank()] if len(words) == 0: ...
This function calculates the ratio of lexical complexity scores between a simple and complex sentence, ensuring the result does not exceed 2, then rounds it to two decimal places.
def get_word_rank_ratio(self, complex_sentence, simple_sentence): return round(min(safe_division(self.get_lexical_complexity_score(simple_sentence), self.get_lexical_complexity_score(complex_sentence)), 2))
def handle_custom_resource_status_message(event: dict, context: dict): custom_resource_request_type = event.get('RequestType') try: yield custom_resource_request_type # when custom_resource_request_type is None, this lambda is being # triggered by Amazon's SNS topic because IP prefixes ...
This Lambda function manages S3 bucket policies by adding, updating, or removing IP restrictions based on region-specific prefixes. It is triggered via CloudFormation Custom Resources or SNS events, retrieves the current bucket policy, modifies it according to the request type, and applies the updated policy to the spe...
def handler(event: dict, context: dict): """ This lambda will either be triggered by a CloudFormation Custom Resource creation or by a recurring SNS topic """ # context manager for the case when this lambda is triggered by aws custom resource with handle_custom_resource_status_message(event, con...
def get_clusters_size(n_samples, n_clusters): """Gets the number of members per cluster for equal groups kmeans""" return (n_samples + n_clusters - 1) // n_clusters def initial_assignment(labels, mindist, n_samples, all_distances, max_cluster_size): """Initial assignment of labels and mindist""" all_poi...
(This function computes cluster labels and inertia for given data points and cluster centers using precomputed distances. It initializes cluster assignments, refines them by swapping points between clusters to minimize distances, and returns the optimal labels and total inertia as the sum of squared distances to cluste...
def _labels_inertia_precompute_dense(X, x_squared_norms, centers, distances): """Compute labels and inertia using a full distance matrix. This will overwrite the 'distances' array in-place. Parameters ---------- X : numpy array, shape (n_sample, n_features) Input data. x_squared_norms : ...
def _tolerance(X, tol): """Return a tolerance which is independent of the dataset""" if sp.issparse(X): variances = mean_variance_axis(X, axis=0)[1] else: variances = np.var(X, axis=0) return np.mean(variances) * tol def _validate_center_shape(X, n_centers, centers): """Check if cent...
The code implements the K-means clustering algorithm to group input data into a specified number of clusters. It runs multiple initializations (n_init) to avoid local optima, using methods like 'k-means++' or random centroid placement. The function returns cluster centroids, sample labels, and inertia (sum of squared d...
def k_means(X, n_clusters, init='k-means++', precompute_distances='auto', n_init=10, max_iter=300, verbose=False, tol=1e-4, random_state=None, copy_x=True, n_jobs=1, return_n_iter=False, sample_weight=None): """K-means clustering algorithm. Read more in the :ref:`User Guide <...
def generate_ed_arrivals(self): # Keep generating indefinitely whilst the simulation is running while True: # Increment patient counter by 1 self.patient_counter += 1 # Create a new patient p = ED_Patient(self.patient_counter, g.prob_acu) ...
The code's main task is to execute a simulation by initializing entity generators, running the simulation for a duration combining `sim_duration` and `warm_up_duration`, calculating average queue times, and saving results to a file. It orchestrates the simulation workflow, processes entity arrivals, computes performanc...
def run(self): # Start entity generators self.env.process(self.generate_ed_arrivals()) # Run simulation self.env.run(until=(g.sim_duration + g.warm_up_duration)) # Calculate run results self.calculate_mean_q_times() # Write run results t...
def _extract_data(latlon, raster, distance, ellipsoid): lat, lon = latlon lat_resolution, lon_resolution = _resolution(raster.transform) row, col = raster.index(lon, lat) if not 0 <= row < raster.height or not 0 <= col < raster.width: # TODO specific exception raise Exception("LatLon n...
The code calculates the horizon angles (elevation and azimuth) from a given observer point on a geographic raster, considering terrain elevation and precision. It extracts relevant raster data, computes angles to pixel corners, adjusts for observer height, generates a sun mask, and returns elevation, zenith, and azimut...
def horizon(latlon, raster, distance=25 * KM, precision=1, height=0): if raster.crs.is_projected: raise Exception("Only geographic CRS are supported") crs = CRS.from_wkt(raster.crs.to_wkt()) ellipsoid = crs.ellipsoid logger.debug("Extracting data...") study_area, study_transform = _extract...
def get_num_parameters_and_constraint_for_hidden(self): #! calculate the current parsity num_parameters = 0 # 12 * 1 * 1 # 12 * 12 * 1 all_head_score, head_score = self.transform_scores_for_head() hidden_score = 1 - self.cdf_qz(0, self.hidden_loga) # 768 if all_h...
This function computes Lagrangian regularization loss to control model sparsity during pruning. It calculates expected sparsity based on pruned parameter counts, adjusts target sparsity during warmup, and combines linear and quadratic terms (via λ₁ and λ₂) to penalize deviations between expected and target sparsity. Th...
def lagrangian_regularization(self, pruned_steps): target_sparsity = self.target_sparsity if "hidden" in self.types: expected_size = self.get_num_parameters_and_constraint_for_hidden() #! calculate \bar s else: expected_size = self.get_num_parameters_and_constraint() #! c...
def create_edge_dict(edgelist): """ Creates an edge dictionary with the edge `(p, q)` as the key, and weight `w` as the value. :param edgelist: list with elements of form `(p, q, w)` :type edgelist: list :return: A dictionary with key `(p, q)` and value `w`. :rtype: dict """ edgedict = {...
The code predicts and ranks potential links in a graph using node embeddings. It computes a "glide score" combining local similarity (via metrics like L3 or CW) and distance-based terms, then thresholds results to identify high-probability links. The function returns a matrix of ranked edge scores, with optional binari...
def glide_predict_links(edgelist, X, params={}, thres_p=0.9): """Predicts the most likely links in a graph given an embedding X of a graph. Returns a ranked list of (edges, distances) sorted from closest to furthest. :param edgelist: A list with elements of type `(p, q, wt)` :param X: A nxk embe...
def dist_obj_in_dist_boxes(n_objects, j_items_per_box, k_boxes): # distinguishable objects --> distinguishable boxes prod = 1 # dummy variable for returning for i in range(0, k_boxes): # loop through boxes prod = prod*C(n_objects-j_items_per_box*i, j_items_per_box) # multiply combinations along the wa...
The main task of the code is to calculate the number of ways to distribute items into boxes, considering four scenarios: distinguishable/indistinguishable items and boxes. It iterates through four cases, prints combinatorial questions, and computes results using functions like dist_obj_in_dist_boxes, ind_obj_in_dis_box...
def main(): # main function that actually deals with the output for i in range(0,4): print(f"{i+1})") if i == 0: # distinguishable items into distinguishable boxes print("a)") print("How many ways are there to deal 5-card poker hands from a 52-card deck to each of 4 players?"...
def get_random_action(self, state: GameState) -> GameAction: if random.random() < 0.5: return self.get_random_row_action(state) else: return self.get_random_col_action(state) def get_random_col_action(self, state: GameState) -> GameAction: position = self.get_random_posit...
The main task of the code is to determine the appropriate action for a game agent based on the current game state. It checks if all rows or columns are marked (status == 1). If neither is fully marked, it selects a random action. If all rows are marked, it chooses a random column action; otherwise, it selects a random ...
def get_action(self, state: GameState) -> GameAction: all_row_marked = np.all(state.row_status == 1) all_col_marked = np.all(state.col_status == 1) if not (all_row_marked or all_col_marked): return self.get_random_action(state) elif all_row_marked: return self.ge...
def convert_grid_to_logical_position(self, grid_position): grid_position = np.array(grid_position) position = (grid_position - distance_between_dots / 4) // ( distance_between_dots / 2 ) type = False logical_position = [] if position[1] % 2 == 0 and (position...
The code handles mouse click events on a game board. If the board isn't reset, it converts the click coordinates to a logical grid position and updates the game state. If the board is reset (e.g., after a game over), it clears the canvas, triggers a "play again" function, and resets the board state for a new game.
def click(self, event): if not self.reset_board: grid_position = [event.x, event.y] logical_position, valid_input = self.convert_grid_to_logical_position( grid_position ) self.update(valid_input, logical_position) else: self.can...
def terminal_test(self, state: GameState) -> bool: return np.all(state.row_status == 1) and np.all(state.col_status == 1) def get_utility(self, state: GameState) -> float: [ny, nx] = state.board_status.shape utility = 0 # == Count boxes box_won = 0 box_lost = 0 f...
This function implements the Minimax algorithm with alpha-beta pruning to determine the optimal game value for a given state. It alternates between maximizing (player1) and minimizing (opponent) values recursively, exploring game states up to a specified depth. Alpha-beta pruning optimizes search efficiency by cutting ...
def get_minimax_value( self, state: GameState, depth: int = 0, max_depth: int = 0, alpha: float = -np.inf, beta: float = np.inf, ) -> float: if time() >= self.global_time: raise TimeoutError() if self.terminal_test(state) or depth == max_d...
def generate_actions(self, state: GameState) -> List[GameAction]: row_positions = self.generate_positions(state.row_status) col_positions = self.generate_positions(state.col_status) actions: List[GameAction] = [] # TODO: Menambahkan heuristik move ordering for position in row_po...
The code implements a minimax algorithm with alpha-beta pruning to select the optimal game action. It evaluates all possible moves from the current game state, calculates their minimax values with increasing search depth, and chooses the action with the highest utility. The algorithm respects a time limit to avoid exce...
def get_action(self, state: GameState) -> GameAction: self.is_player1 = state.player1_turn selected_action: GameAction = None self.global_time = time() + TIMEOUT row_not_filled = np.count_nonzero(state.row_status == 0) column_not_filled = np.count_nonzero(state.col_status == 0)...
def parse_args(args, conf): keys = ["-h", "-d", "-t", "-s", "-i"] help = "" help += "-h - help\n" help += "-d \"db_path.db\" - path to database (required)\n" help += "-t \"tabel_name\" - tabel name (required)\n" help += "-s <period> - show notes\n" help += "\t<period> - period of note showin...
The main task of the code is to manage a note-taking system via command-line arguments. It parses configurations, interacts with a database through a Repository, and executes actions based on the specified mode: adding daily notes, displaying all notes, or entering an interactive interface for note management.
def main(): from datetime import date import sys conf = Config() parse_args(sys.argv, conf) repository = Repository(conf.db_path, conf.table_name) if conf.mode == "note": message = input_message() repository.append_note(Note(message)) show_notes(repository.select_notes...
def get_sample(self) -> SampleData: # Determine how long until the next sample needs to be taken now = datetime.now() time_to_next = self.interval - (now.timestamp() % self.interval) # wait! time.sleep(time_to_next) data = envoy.get_power_data(self.cfg.envoy_url, self.s...
The code continuously retrieves data from an Envoy system, handling potential timeouts by retrying up to 10 times. If successful, it writes the retrieved data and inverter data to InfluxDB, resetting the timeout counter. If timeouts exceed 10, it raises an error to halt execution. The loop ensures persistent data colle...
def run(self): timeout_count = 0 while True: try: data = self.get_sample() inverter_data = self.get_inverter_data() except (ReadTimeout, ConnectTimeout) as e: # Envoy gets REALLY MAD if you block it's access to enphaseenergy.com ...
def __get_landmark_pts(self, img): detected_face = self.detector.predict(img) landmarks = self.predictor.predict(detected_face, img) return landmarks def __align_src(self, src, src_landmarks, tgt_landmarks): scaling_factor = self.__get_scaling_factor(src_landmarks, tgt_landmarks) ...
The function `__src_warp_swap` performs face swapping by aligning the source image (`src`) to the target image (`tgt`) using facial landmarks. It extracts landmarks from both images, aligns the source image based on these landmarks, generates a new face by warping the aligned source to match the target's structure, and...
def __src_warp_swap(self, src, tgt): tgt_landmarks = self.__get_landmark_pts(tgt) src_landmarks = self.__get_landmark_pts(src) src = self.__align_src(src, src_landmarks, tgt_landmarks) src_landmarks = self.__get_landmark_pts(src) new_face = self.__get_new_face(src, tgt, src_lan...
def __get_landmark_pts(self, img): detected_face = self.detector.predict(img) landmarks = self.predictor.predict(detected_face, img) return landmarks def __align_src(self, src, src_landmarks, tgt_landmarks): scaling_factor = self.__get_scaling_factor(src_landmarks, tgt_landmarks) ...
This code performs facial feature-based image warping by aligning source and target landmarks, applying triangular mesh deformation to warp the target image's face region to match the source's structure, and returning the transformed image along with a source face cutout for composite operations.
def __target_warp_swap(self, src, tgt): tgt_landmarks = self.__get_landmark_pts(tgt) src_landmarks = self.__get_landmark_pts(src) src = self.__align_src(src, src_landmarks, tgt_landmarks) src_landmarks = self.__get_landmark_pts(src) src_center = self.__get_center(src_landmarks) tgt...
def vertex_degree(g, g_type, degree_type="total"): # Initialize degree of all vertices as 0 q = {v:0 for v in g["vertices"]} # Increment degree of edge endpoints accordingly for e in g["e_list"]: if g_type == "undirected" or degree_type == "total": q[e[0]] += e[2] q[e[1]]...
The main task of the code is to compute vertex quality scores for a graph using various centrality measures. It acts as a dispatcher function that selects between methods like in/out/total degree, normalized degree, PageRank, or a PageRank-degree hybrid based on the input parameter. The function returns the computed ve...
def compute_vertex_quality(g, g_type, method="pagerank_degree_hybrid"): if method == "in_degree": return vertex_degree(g, g_type, "in") if method == "out_degree": return vertex_degree(g, g_type, "out") if method == "degree": return vertex_degree(g, g_type, "total") if method == "...
def observe(self,opponent): available_members = [] for ids in opponent.layers[:-1]: available_members+=ids if not len(available_members): return None observed_id = np.random.choice(available_members) return observed_id def form_squad(gang,leader): if leader == None: return [] squ...
The code's main task is to orchestrate an attack strategy by observing the opponent, forming enemy squads, recruiting a leader, assembling a squad, and attacking if the squad is non-empty. It involves analyzing the opponent's structure, recruiting a leader from enemies, forming a squad for self, and initiating an attac...
def move(self,opponent): oppo_leader = self.observe(opponent) enemies = form_squad(opponent,oppo_leader) leader = self.recruit(enemies) squad = form_squad(self,leader) # print (oppo_leader,enemies,leader, squad) if len(squad) > 0: self.attack(leader, squad, enemies,opponent)
def m_wt_matrix(Points,Img): n = len(Points) #W = np.zeros([n,n]) p2indx,indx2p = create_map_dict(Points) rows = [] cols = [] data = [] for point in Points: cords = p2c(point,w,h) neighbours = get_neighbours_m(cords,Points) #print(cords, neighbours) for n...
This function performs normalized cut clustering on point data by computing graph Laplacian eigenvectors, partitioning points into clusters based on eigenvector values, and recursively splitting large clusters. It uses weight matrices, eigen-decomposition, and thresholding to hierarchically segment point sets while tra...
def norm_cut(Points, p2indx,indx2p,parent,flag): global mask_img, mask_img_updates W, p2indx, indx2p = m_wt_matrix(Points,image) D = D_matrix(W) #A = D_half.dot(W) #A = A.dot(D_half) eig_vals , eig_vec = eigs(D - W,M = D,k = 2, which = 'SM') #eig_vals , eig_vec = eig(...
def render(self): if self.render_mode is None: assert self.spec is not None gym.logger.warn( "You are calling render method without specifying any render mode. " "You can specify the render_mode at initialization, " f'e.g. gym.make("{self.s...
This code simulates a single step in a reinforcement learning environment by selecting a probabilistic transition from the current state and action. It updates the environment's state, renders if enabled, and returns the next state (with noise), reward, termination flag, and metadata including transition probability an...
def step(self, a): transitions = self.P[self.s][a] i = categorical_sample([t[0] for t in transitions], self.np_random) p, s, r, t = transitions[i] self.s = s self.lastaction = a if self.render_mode == "human": self.render() return (int(self._add_noise...
def add_ice(self): self.ice_locs = [] for row in range(self.max_row + 1): for col in range(self.max_col + 1): if (row, col) not in self.locs and self.np_random.random() < self.ICE_PROPORTION: self.ice_locs.append((row, col)) def setup_transitions(self): ...
The code resets the environment by initializing the state distribution, handling model uncertainty with ICE addition, setting up transitions, sampling the initial state, and returning the state with noise and action masks for reinforcement learning. It also initializes variables like lastaction and taxi_orientation, an...
def reset( self, *, seed: Optional[int] = None, options: Optional[dict] = None, ): super().reset(seed=seed) if self.model_uncertainty: self.add_ice() self.setup_transitions() self.s = categorical_sample(self.initial_state_distrib, self.np_r...
def get_ac_version(): import pkg_resources try: ac_version = pkg_resources.get_distribution('astronomer-certified').version except pkg_resources.DistributionNotFound: # Try to work out ac_version from airflow version ac_version = AIRFLOW_VERSION.replace('+astro.', '-') return ac_...
The code periodically checks for new versions of Astronomer Certified Airflow, updates the AstronomerAvailableVersions table, and manages update intervals. It disables checks if the interval is zero, retrieves the current version, hides outdated entries, introduces a startup delay, and enters a loop to check for update...
def run(self): """ Periodically check for new versions of Astronomer Certified Airflow, and update the AstronomerAvailableVersions table """ if self.check_interval == 0: self.log.info("Update checks disabled") return self.ac_version = get_ac_versi...
def calculate_gain_ratio__(self, dataset, labels, attribute): """ :param dataset: array of data instances with which a gain ratio is going to be calculated :param labels: array of labels of those instances :param attribute: for which attribute the gain ratio score is going to be calculat...
This code implements the ID3 algorithm recursively to build a decision tree. It selects the best attribute for splitting using information gain or gain ratio, creates a tree node, partitions data based on attribute values, and recursively constructs subtrees for each partition. Leaf nodes are created when all instances...
def ID3__(self, dataset, labels, used_attributes): """ Recursive function for ID3 algorithm :param dataset: data instances falling under the current tree node :param labels: labels of those instances :param used_attributes: while recursively constructing the tree, already used l...
def reply11(msg): reply(msg, type='error', code=11, text='Not a leader') def becomeFollower(msg=None): global state with lock: state = FOLLOWER if msg: handler_follower(msg) threading.Thread(target=waitForFollowerTimeout).start() def majority(): return len(node_ids) // 2 ...
This code handles Raft consensus protocol messages as a candidate node. It processes incoming messages like AppendEntries, RequestVote, and RequestVoteReply, updates vote counts, and transitions between follower/leader states based on term comparisons and majority vote thresholds to manage distributed consensus and ele...
def handler_candidate(msg): global votes type = msg.body.type with lock: if type in ['read','write','cas']: reply11(msg) elif type == 'AppendEntries': becomeFollower(msg) if msg.body.term >= currentTerm else reply(msg, type='AppendEntriesReply', term=currentTerm, succ...
def viewScreen(): global emp_data empL=resize(emp_data) mylist.delete(0,END) for line in range(len(empL)): row="|".join(empL[line]) mylist.insert(END,row) if(line==0): mylist.insert(END,"========================================================================") def S...
The code handles form submission for employee data management, either adding/updating entries or deleting existing ones. It collects input from fields, modifies the global emp_data list, disables input fields, updates the UI, and adjusts button states based on the operation (add/edit/delete) and data count.
def submit(entry): if(sbmitbtn["state"]=="normal"): global emp_data global rowID global fkey global mode sbmitbtn["state"]="disabled" if(fkey=="Delete"): emp_data.pop(rowID) e1.delete(0,END) viewScreen() Save() ...