dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def _get_course_data(self, department: str) -> [dict]: """retrieves course data and sanitizes it for database usage""" query_params = {'YearTerm': self._term, 'Dept': department} while True: try: course_data = soc.get_course_data(query_params) for cour...
(The function updates a database with current WebSOC course data for specified departments. It iterates through each department, retrieves course information, updates static and live entries, tracks the number of updates and courses processed, logs progress, cleans up removed entries, and introduces delays between requ...
def update_data(self, departments: set=soc.S_DEPARTMENTS) -> None: """updates database with current WebSOC entries of given departments""" n_updates = 0 n_courses = 0 for department in departments: course_data = self._get_course_data(department) n_update = 0 ...
def _advance(self): self.current += 1 return self.source[ self.current - 1 ] def _add_token(self, token_type, literal=None): text = self.source[self.start : self.current] self.tokens.append(Token(token_type, text, literal, self.line)) def _match(self, expected): ...
The `_scan_token` method identifies and classifies individual tokens from input characters. It handles single-character tokens (e.g., parentheses, operators), two-character operators (e.g., `!=`, `<=`), comments, whitespace, string literals, numbers, identifiers, and keywords. It uses conditional checks to determine to...
def _scan_token(self): c = self._advance() # Single tokens if c == "(": self._add_token(tt.LEFT_PAREN) elif c == ")": self._add_token(tt.RIGHT_PAREN) elif c == "{": self._add_token(tt.LEFT_BRACE) elif c == "}": self._add_to...
def _generate_endpoint(self, path, **params): if self._is_access_token_valid(): self._auth() return '%s%s%s' % (self.access_token.api_server, self.api_version, path % params) def _make_request(self, endpoint, **params): if self._is_access_token_valid(): self._auth() ...
This method fetches account data from an API by generating an endpoint, making a request, parsing the response, and returning the extracted accounts.
def accounts(self): logging.info('API Request - Accounts') endpoint = self._generate_endpoint('/accounts') content = self._make_request(endpoint) return self._simple_parse(content, 'Account').accounts
def _generate_endpoint(self, path, **params): if self._is_access_token_valid(): self._auth() return '%s%s%s' % (self.access_token.api_server, self.api_version, path % params) def _make_request(self, endpoint, **params): if self._is_access_token_valid(): self._auth() ...
This function retrieves account balance information from an API by generating an endpoint with the provided account number, making a request, and parsing the response to return combined balances in CAD currency.
def accounts_balances(self, account, type='combinedBalances', currency='CAD'): logging.info('API Request - Account Balance') endpoint = self._generate_endpoint('/accounts/%(account_id)s/balances', account_id=account.number) content = self._make_request(endpoint) return self._simple_parse...
def _generate_endpoint(self, path, **params): if self._is_access_token_valid(): self._auth() return '%s%s%s' % (self.access_token.api_server, self.api_version, path % params) def _make_request(self, endpoint, **params): if self._is_access_token_valid(): self._auth() ...
The main task of the code is to retrieve and parse account positions data from an API. It logs the request, constructs an endpoint using the account number, fetches content via a request, and returns parsed position information by extracting the 'Position' key from the response.
def accounts_positions(self, account): logging.info('API Request - Account Positions') endpoint = self._generate_endpoint('/accounts/%(account_id)s/positions', account_id=account.number) content = self._make_request(endpoint) return self._simple_parse(content, 'Position').positions
def _generate_endpoint(self, path, **params): if self._is_access_token_valid(): self._auth() return '%s%s%s' % (self.access_token.api_server, self.api_version, path % params) def _make_request(self, endpoint, **params): if self._is_access_token_valid(): self._auth() ...
This method fetches symbol data from an API by generating an endpoint, making a request with provided symbols, and parsing the response to extract symbol information.
def symbols(self, symbols): logging.info('API Request - Symbols') endpoint = self._generate_endpoint('/symbols') content = self._make_request(endpoint, names=','.join(symbols)) return self._simple_parse(content, 'Symbol').symbols
def _generate_endpoint(self, path, **params): if self._is_access_token_valid(): self._auth() return '%s%s%s' % (self.access_token.api_server, self.api_version, path % params) def _make_request(self, endpoint, **params): if self._is_access_token_valid(): self._auth() ...
The code fetches market quotes for specified symbols by constructing an API request with filtered symbol IDs, executing the request, and returning parsed quote data.
def markets_quotes(self, symbols): logging.info('API Request - Market Quotes') endpoint = self._generate_endpoint('/markets/quotes') params = { 'ids': ','.join([str(symbol.symbolId) for symbol in symbols if symbol.isQuotable]) } content = self._make_request(endpoint, ...
def validate(size, cliques): """ Validate the integrity of the input as a kenken board * For each of the cliques: * Remove duplicate members of the clique at hand * Check whether the specified operator is acceptable or not * Check if any of the members of the clique are out of boun...
This code initializes a Constraint Satisfaction Problem (CSP) where each clique's members must satisfy a mathematical operation (addition, subtraction, etc.) to reach a target value. It extracts variables, domains, and neighbors from cliques, validates inputs, and sets up the CSP framework with a constraint function to...
def __init__(self, size, cliques): """ In my implementation, I consider the cliques themselves as variables. A clique is of the format (((X1, Y1), ..., (XN, YN)), <operation>, <target>) where * (X1, Y1), ..., (XN, YN) are the members of the clique * <operation> is...
def multi_file_upload_handler(self, request): """ called when the user uploads multiple file (by selection). Like the zip file handler, this saves a new Job object for each file. We create a new 'fake' form for each file so we can run validation on each file separately by calling form.is...
This code handles file uploads for SBML files, determining whether to process multiple files, ZIP archives, or single files. It checks for validation skips, processes forms, and redirects accordingly, or delegates to parent class handling if validation is required.
def post(self, request, *args, **kwargs): file = request.FILES['sbml_file'] self.progress_id = file.progress_id if len(request.FILES.getlist('sbml_file')) > 1: # did the user upload multiple files? cache.set('current_upload', len(request.FILES.getlist('sbml_file')), timeout=180) ...
def score_cands(tokenizer, model, source): scores1 = _score_cands(tokenizer, model, source, NUMERSENSE_ANSWERS) scores2 = _score_cands(tokenizer, model, source, [cand.capitalize() for cand in NUMERSENSE_ANSWERS]) scores = (scores1 + scores2) / 2 probs = F.softmax(scores, dim=0) return scores, probs ...
The code processes a numersense dataset using a T5 model to score and predict answers, supporting aggregation methods (poe/moe/bestprob) and interactive testing. It evaluates queries against knowledge sources, computes accuracy, and outputs results as JSON or submission files, with options for model size, input path, a...
def main(): parser = argparse.ArgumentParser() parser.add_argument('--model-type', type=str, default='t5-11b', choices=['t5-small', 't5-base', 't5-large', 't5-3b', 't5-11b']) parser.add_argument('--input-path', type=str, required=True) parser.add_argument('--submit', action='store_true') parser.add_...
def get_all_image_names(search_path): """Returns list of image names meeting the folder search term. Parameters ---------- search_path : string defines folder containing images Returns ---------- image_names : list string showing filenames """ paths = glob.glob(sear...
The code's main task is to test and demonstrate the analysis of photon event data from images (real or simulated). It loads image data, fits curvature and resolution parameters, and visualizes results via two plots: one showing the image and curvature, the other displaying spectral resolution. The function handles both...
def run_test(search_path='test_images/*.h5'): """Run at test of the code. This can also be used as a reference for command-line analysis. Parameters ------------- search_path : string string to fine images passed to get_all_image_names Returns ------------- ax1 : matplotlib axi...
def is_train_test_file_exists(self)->bool: try: logging.info("Checking if training and test file is available") is_train_file_exist = False is_test_file_exist = False train_file_path = self.data_ingestion_artifact.train_file_path test_file_path = sel...
The main task of the code is to perform data validation by checking the existence of train/test files, validating the dataset schema, and detecting data drift. If all checks pass, it creates a `DataValidationArtifact` with success status and file paths. If any step fails, it raises an exception. The artifact confirms v...
def initiate_data_validation(self)->DataValidationArtifact : try: self.is_train_test_file_exists() self.validate_dataset_schema() self.is_data_drift_found() data_validation_artifact = DataValidationArtifact( schema_file_path=self.data_validation_c...
def get_pr_data_loc(data, samples): result = [] for s_point in samples: # get k nearest points visual_angle = 2 * math.tan((CONE_DIAMETER / 2) / (s_point[1] + EPSILON)) * 180 / math.pi num_ideal_points = max(int(visual_angle * POINTS_PER_DEGREE), 1) s_point = toxy(s_point) ...
The function performs template matching on lidar data to estimate a new location (new_LocX, new_LocY) and update the sigma parameter (representing uncertainty/spread) by evaluating probability distributions over a sampled grid. It generates sample points around an initial center, computes their probabilities, selects t...
def template_matching(LocX, LocY, sigma, lidar_data, label=None, plot=False): # data_points = extract_data_points() data_points = lidar_data data_points_xy = toxy(data_points) sample_range = 3 * sigma sample_gap = 0.05 # how far each sample is from each other center_point_xy = [LocX, LocY] ...
def update_alltime_stats(): if history_var.get() == 1: alltime_gaard_tokens["text"] = str(int(alltime_gaard_tokens["text"]) + int(gaardbutton["text"])) alltime_yasmine_tokens["text"] = str(int(alltime_yasmine_tokens["text"]) + int(yasminebutton["text"])) alltime_orpheus_tokens["text"] = str(...
The code handles submission of button values to update session statistics, increments counters for events and battles based on selected options (mythic mimic, mimic, no reward), resets button states, saves session data, and triggers percentage calculations. It ensures proper tracking of tokens, events, and rewards whil...
def submit(): if int(gaardbutton["text"]) == 0 and int(yasminebutton["text"]) == 0 and int(orpheusbutton["text"]) == 0 and int(araneabutton["text"]) == 0 and int(anubutton["text"]) == 0 and int(nyshabutton["text"]) == 0 and no_reward_pressed and not first: return update_alltime_stats() if mythmim_...
def find_medal_rewards(string): medals = {"Gaard": 0, "Yasmine": 0, "Orpheus": 0, "Aranaea": 0, "Anu": 0, "Nysha": 0} temp = string.splitlines() num = "" for medal in medals: for item in temp: if item.find(medal) != -1: for char in item: if char.i...
The main task of the code is to automatically detect in-game rewards from a screenshot of the "GemsofWar" window, calculate their value using predefined multipliers, update corresponding UI buttons with the detected rewards, log results, and trigger actions like mimic toggling or submission based on reward totals and t...
def auto_detect_rewards(): # TAKE TIME FOR HOW LONG FUNCTION TAKES TO COMPLETE # start = time() sleep(0.4) # GET WINDOW COORDINATES # window_handle = FindWindow(None, "GemsofWar") window_rect = GetWindowRect(window_handle) # GET WINDOW AND RESIZE IT # win = pygetwindow.getWindowsWithTit...
def decrypt(cipher, key): return crypt(cipher, key, -1) def dist(freq, letter_freq): sqe = 0. for key, value in freq.items(): sqe = sqe + (value - letter_freq[key]) ** 2 return sqe / len(freq) def frequency(text): text_dictionary = {} for i in text: text_dictionary[i]= text_dictionary.ge...
This code generates a decryption key by performing frequency analysis on segments of ciphertext. For each key position, it tests possible letters, decrypts the corresponding ciphertext segment, compares letter frequencies to a standard distribution, and selects the letter with the closest match. The process iterates ov...
def generateKey(ciphertext, keylen): key = "" for i in range(keylen): sqe = 100 ** 9 spilt_mesg = ciphertext[i::keylen] k = 0 for b in range(0,26): t = decrypt(spilt_mesg , alphabet[b]) d = dist(frequency(t), letterFrequency) if d < sqe: ...
def get_pkg_version(package_name): pkg_description = cmd.run_cli('package describe {}'.format(package_name)) regex = r'"version": "(\S+)"' match = re.search(regex, pkg_description) return match.group(1) def add_repo(repo_name, repo_url, prev_version, index, package_name): assert shakedown.add_packag...
The code performs package version upgrades and downgrades by manipulating repository priorities. It uninstalls a package, identifies test and Universe versions, adjusts the Universe repository's position (top/bottom), and executes install/upgrade steps to test version transitions. The process verifies upgrade/downgrade...
def upgrade_downgrade(package_name, running_task_count): install.uninstall(package_name) test_version = get_pkg_version(package_name) print('Found test version: {}'.format(test_version)) repositories = json.loads(cmd.run_cli('package repo list --json'))['repositories'] print("Repositories: " + str...
def searchPos(namaTempat) : found = False for i in range (len(simpul)) : if (simpul[i][2] == namaTempat) : return i if(not found) : return -1 def evalFunc (dFromStart, currNode, exploreNode, goal) : fn = gn (dFromStart, currNode, exploreNode) + hn(exploreNode, goal) r...
The code implements the A* algorithm to find the shortest path from a start node to a goal node in a graph. It uses a stack to track the current path, evaluates nodes using a heuristic function, and backtracks when no unvisited neighbors are available. The algorithm prioritizes nodes with the minimal evaluation functio...
def aStar(start, goal) : # Inisiasi stack = [] # Stack yang menyimpan jalur yang dilalui (jalur terpendek disimpan disini) visitedNodes = [] # Array boolean, menyimpan nodes yang sudah dilewati currNode = start # Node saat ini stack.append(start) dFromStart = 0 # Jarak dari simpul asal ...
def is_dir(self, ftp_instance, path): # remember current directory original_cwd = ftp_instance.pwd() # change directory to item_name try: ftp_instance.cwd(path) # go back ftp_instance.cwd(original_cwd) return True # change failed, n...
The function recursively explores directories on either a production or development site, building relative paths for files and comparing them. It processes each entry, handling subdirectories by recursion and non-directories by generating relative paths for comparison via `compare_add_row`, using a prefix to track the...
def explore_directory(self, dir_path, prefix="", site2=False): if not site2: for entry in self.prod_site.nlst(dir_path): full_path = dir_path + '/' + entry # add prefix and entry recursively call, or process them if self.is_dir(self.prod_site, full_pa...
def WrongLanguageError(): print(style.RED + "Error : No such language found\n" + style.RESET) def print(s): lock.acquire() stdout.write(str(s)) lock.release() def show_languages(command,printable = True): languages_path = f"{getcwd()}/{'/'.join(path)}" all_languages = listdir(languages_path) ...
This function handles invalid commands by checking if the path ends with 'languages'. If true, it triggers a language error, displays available languages using 'show_languages', and prints 'None' if no languages are found. Otherwise, it prints an 'Invalid command' error message in red.
def WrongCommandError(): if path[-1] == "languages": WrongLanguageError() print("Available languages -> ") if not show_languages({"command": "*", "parameters": {}}, printable = False): print(style.RED + "None\n") else: show_languages({"command": "*", "paramete...
def __checkInput(self, rx, rxType): # check the lockout, bail if locked if self.__checkLockout() == "locked": self.__logger.log("INFO", "ACCESS DENIED BY LOCKOUT", {"token": rx}) return # check the token, true if approved, false if denied tokenCheckOutput = self....
This code handles numeric keypad input with a delimiter, managing state transitions between "ready" and "reading" modes. It processes incoming characters, enforces timeout limits, resets on timeout, triggers validation on delimiter receipt, and implements overspeed lockout to ignore invalid inputs. The input buffer is ...
def __newNumpadInput(self, rx): # make __logger available # global l # set time timeNow = time.time() # if not reading and rx is not the start/stop delimiter, do nothin if self.__numpadState == "ready" and rx != self.__params["delimiter"]: self.__logger.log(...
def __wiegandToHex(self, bits, code): if bits == 34: binaryFormatter = "#036b" trimChar = 2 elif bits == 26: binaryFormatter = "#028b" trimChar = 4 else: self.__logger.log("ERRR", "__wiegandToHex called with unexpected amount of bits", ...
The main task of the code is to process Wiegand card token or keypad inputs. For 34/26-bit codes, it converts the token to hex, logs it, and checks against a list. For 4-bit codes, it interprets keypad inputs (e.g., *, #) and triggers a numpad function. It logs debug/warning messages for validation, connection checks, ...
def __wiegandCallback(self, bits, code): # if bits == 34 or 26, it's a card token # convert to binary string # trim "0b", start parity bit, end parity bit # re order bytes # convert to hex # compare against list # # if bits == 4 # intrept key...
def get_ds(config): # This fn gets the raw dataset and convert it into trainable format. # First load dataset using HuggingFace's "load_dataset" fn. # https://huggingface.co/datasets/cfilt/iitb-english-hindi need this: ds_raw = load_dataset(f"{config['datasource']}", split='train'). # https://huggingfa...
The main task of the code is to train a transformer model for sequence-to-sequence tasks (e.g., machine translation) using a specified configuration. It initializes the model, loads training/validation data, handles preloading of saved weights, performs training with backpropagation, validates after each epoch, logs me...
def train_model(config): # This fn defines process to train the transformer model. # Define the device to use out of cuda or cpu device = "cuda" if torch.cuda.is_available() else "mps" if torch.has_mps or torch.backends.mps.is_available() else "cpu" device = torch.device(device) print("Using device...
def get_headword(self, node): headword_nodes = node.getElementsByTagName("headword") assert len(headword_nodes) == 1 headword_node0 = headword_nodes[0] headword = self.get_text(headword_node0) return headword def get_pos(self, node): pos_nodes = node.getElementsByTagName(...
The code initializes an object by extracting linguistic data from an XML/HTML node, setting attributes like language, headword, part-of-speech, translation, examples, classifiers, definitions, and synonyms/antonyms. It uses helper methods to parse specific node elements, organizing structured lexical information for fu...
def __init__(self, node, entry_id): self.entry_id = entry_id self.lang = node.getAttribute("lang")[0:2] self.headword = self.get_headword(node) self.pos = self.get_pos(node).lower() self.translation = self.get_translation(node) self.examples = self.get_examples(node) ...
def _fetch_index(self, uri, ud, d): """ Run fetch checkstatus to get directory information """ f = tempfile.NamedTemporaryFile() agent = "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.2.12) Gecko/20101027 Ubuntu/9.10 (karmic) Firefox/3.6.12" fetchcmd = self.basecmd ...
This function scans directories to determine the latest upstream version of a package by parsing directory names with regex, comparing versions, and recursively checking each directory to find the highest version available. It constructs URLs, fetches index pages, and uses BeautifulSoup to parse links, updating the ver...
def _check_latest_version_by_dir(self, dirver, package, package_regex, current_version, ud, d): """ Scan every directory in order to get upstream version. """ version_dir = ['', '', ''] version = ['', '', ''] dirver_regex = re.compile("(\D*)((\d+[\.-_])+(...
def _init_regexes(self, package, ud, d): """ Match as many patterns as possible such as: gnome-common-2.20.0.tar.gz (most common format) gtk+-2.90.1.tar.gz xf86-input-synaptics-12.6.9.tar.gz dri2proto-2.3.tar.gz blktool_4.or...
The function determines the latest package version by parsing URLs, extracting version strings from filenames or directory paths using regex, and formatting them. It checks for version presence in the package name, constructs URIs, and delegates to helper methods for version validation and retrieval, returning the proc...
def latest_versionstring(self, ud, d): """ Manipulate the URL and try to obtain the latest package version sanity check to ensure same name and type. """ package = ud.path.split("/")[-1] current_version = ['', d.getVar('PV', True), ''] """possible to have no ver...
def snake_up(): global pending_action, status if snake_list: new_head = snake_list[0] - 20 if new_head <= 0: status = Status.DIED return snake_list.insert(0, new_head) update_reward_for_new_head(new_head) draw_snake() pending_action = False...
The code updates the snake's movement direction based on its current status (UP, RIGHT, DOWN, LEFT) by calling corresponding functions. If the snake's status is not "DIED," it schedules the `update` function to repeat periodically using `root.after`, maintaining the game loop.
def update(): if status == Status.UP: snake_up() elif status == Status.RIGHT: snake_right() elif status == Status.DOWN: snake_down() elif status == Status.LEFT: snake_left() if status != Status.DIED: root.after(UPDATE_INT, update)
def ntt(x, W, q): n = len(x) x = bitreverse(x) for stage in range(int(math.log2(n))): k = 0 for i in range(n): if (1<<stage) & i == 0: w = W[k] old_x_i = x[i] old_x_i_corr = x[i ^ (1 << stage)] x[i] = barret_reduction(old_x_i + barret_reduction(w*old_x_i_corr,q),q) ...
The code performs a Number Theoretic Transform (NTT) on a list `x` using a modulus `q=673` and roots of unity `W`, then applies the inverse NTT to verify the transformation. It demonstrates NTT and its inverse using modular arithmetic, testing correctness by transforming and reconstructing the original data.
def main(): x = [672,671,0,1,2,3,4,672] q = 673 W = [(326**i)%q for i in range(8)] #print("W:", W) print(x) print(ntt(x, W, q)) iW = [mod_inverse(w, q) for w in W] print(intt(ntt(x, W, q), iW, q))
def check_int(n): if not isinstance(n, numbers.Integral): raise TypeError() def find_modulus(veclen, minimum): check_int(veclen) check_int(minimum) if veclen < 1 or minimum < 1: raise ValueError() start = (minimum - 1 + veclen - 1) // veclen for i in itertools.count(max(start, 1)): n = i * vecle...
The code computes a transformed version of the input vector `invec` using a primitive root and modulus. It first validates `minmod`, determines the modulus based on the vector's length and `minmod`, finds a primitive root modulo the computed value, then applies a transformation using this root and modulus. The function...
def find_params_and_transform(invec, minmod): check_int(minmod) mod = find_modulus(len(invec), minmod) root = find_primitive_root(len(invec), mod - 1, mod) return (transform(invec, root, mod), root, mod)
def load_product_class(item: dict): """Loads the product class object from the dict. Args: item: The dict representing the model Returns: The object that was added. """ ProductClass = get_model('catalogue', 'ProductClass') product_class, __ = ProductClass.objects.get_or_create(...
The code's main task is to load fixture data into a database by iterating through dictionaries within the input fixture. It processes product classes, partners, categories, and stock records, calling respective loading functions for each item. This ensures structured data insertion into the database, maintaining relati...
def load_fixture(fixture: dict) -> None: """Loads the fixture into the database. Args: item: The dict representing the fixture. Returns: None """ for product_class in fixture["product_classes"]: load_product_class(product_class) for partner in fixture["partners"]: ...
def _get_image_files(self, image_dir: str) -> list[str]: """Retrieves all filenames of the images present in the directory Only files having extensions in allowed_extensions is considered. Args: image_dir (str): The directory where the image files are present. Returns: ...
(The code populates a database with image fixture data from a specified directory, associating images with products via filename-based lookup. It handles errors like duplicate products, missing entries, identical images, and invalid files, logging warnings for recoverable issues and raising exceptions for critical erro...
def handle(self, dirname: str) -> None: """Populates database with the image fixture data. Error checking is performed. All errors are logged. Args: dirname (str): The directory where the image files are located. Returns: None """ Product = get_...
def _init_dask_client(self): """ initialize dask.distributed Client :return: (Client) dask client """ def _create_run_skeleton(self): """ create the run artifacts skeleton /artifacts dir /{run_id} /final_model /experiment_1 ...
The method `run_experiments` executes user-defined experiments using a provided function, manages a Dask client for parallel processing, generates and saves experiment reports, metadata, and artifacts, and ensures proper cleanup by shutting down the Dask client. It also logs status updates throughout the process.
def run_experiments(self, experiment_func, experiment_callback=None): """ Run experimenter experiments. When the experimenter tune is done, save the run report, metadata and shutdown dask client. :param experiment_func: (callable) The user [Experiment Design]. :param experiment_c...
def join(rows_u): d = [] for i in rows_u: d.extend(i) return d def separator(crit,p): print(f"Path for separator: {p}") if not os.path.isdir(f"{p}\\{crit}"): with open(f"{p}\\{crit}","w") as f: f.write(" ") def solve_other(driver): answer = 0 time.sleep(3) try...
This function automates downloading financial documents (PDFs) from a web table using Selenium. It iterates through table rows, clicks to open PDFs, handles CAPTCHA, and verifies downloads. If downloads fail, it retries after refreshing the page. The function supports both audited and non-audited documents, uses recurs...
def download(driver,p,count = 0,fails = 0,audit = True, crit = "AUD"): a = audit print(p) print(f"Audit = {a}") wait = WebDriverWait(driver,10) try: #Fake rows element to start while loop rows = range(100) #Set an action object to execute clicks on the webpage at will. ...
def vPrint(self,x): self.verbose if self.verbose == True: print(x) def fileRead(self): self.fileString self.file with open(self.file, "rb") as f: self.content = f.read() self.fileString = binascii.hexlify(self.content) #print("1") ...
The code parses a file by reading its content, validating its IP address, size, and protocol, then generating and combining a signature for verification or processing.
def fileParse(self,toDo): self.fileString self.fileExtension self.file self.file = toDo self.vPrint("File to be read " + self.file) self.vPrint("File extension: " + self.fileExtension) self.fileRead() #test if self.file is being read in properly ...
def argRead(self): self.file self.source self.destination self.protocol self.size self.fileExtension self.verbose self.directory self.rand def fileParse(self,toDo): self.fileString self.fileExtension self.file ...
The main task of the code is to parse either a specified file or directory based on input arguments, ensuring exclusivity between the two options. It checks validity, executes the corresponding parsing method (fileParse/dirParse), and returns the signature.
def execute(self): # global self.file # global self.directory self.argRead() #Determine if a self.file or a self.directory needs to be parsed if self.file == "" and self.directory == "": print("Either a self.directory or a self.file must be specified.") ...
def makeUI(self): """[INTERNAL] Builds jupyter UI for the chess game using ipywidgets. :returns: None """ Layout = widgets.Layout loggerInfo = self.loggerInfo.copy() marginInfo = self.marginInfo.copy() self.vizBoard = self.renderBoard(self.board) ...
This function facilitates a chess game between two agents (white and black), handling game termination conditions, move limits, and visualization. It alternates turns, executes moves via the agents, updates the board state, and returns the game outcome. Exceptions are logged, and the game stops gracefully on user inter...
def playGame(self, whiteAgent, blackAgent, gameTime=0, nMoves=0, visualise=False): """Runs a game between two agents. It handles `KeyboardInterrupt` exception to stop the drawing thread before raising the exception. Other exceptions are captured and er...
def _read_report(self, file: str): if self.memory: pages = fitz.open( None, stream=file, ) else: pages = fitz.open( file, filetype="pdf" ) return pages def _view_report(self, page_no: ...
The main task of the code is to identify and extract the correct financial statement (SOFP, SOPL, or SOCF) from an annual report by matching keywords across pages. It locates the page(s) with the highest keyword matches, combines data from consecutive pages if needed, and returns a cleaned pandas DataFrame containing t...
def report(self, type: str) -> pd.DataFrame: """ This function reads the annual report and outputs the requested financial statement type: str variable 'SOFP', statement of financial position 'SOPL', statement of profit or loss 'SOCF', statement of cash flow """ ...
def load_config(config_file): with open(config_file, 'r') as myfile: data = myfile.read().replace('\n', '') return ast.literal_eval(data) def load_csv_to_header_data(filename): fpath = os.path.join(os.getcwd(), filename) fs = csv.reader(open(fpath, newline='\n')) all_row = [] for r in f...
The code's main task is to construct a decision tree using the ID3 algorithm from a dataset specified in a configuration file. It loads data, processes attributes, identifies unique values, builds the tree recursively, and prints the resulting structure in a human-readable format.
def main(): argv = sys.argv print("Command line args are {}: ".format(argv)) config = load_config(argv[1]) data = load_csv_to_header_data(config['data_file']) data = project_columns(data, config['data_project_columns']) target_attribute = config['target_attribute'] remaining_attributes = ...
def greeting(intent_request): # Order the flowers, and rely on the goodbye message of the bot to define the message to the end user. # In a real bot, this would likely involve a call to a backend service. return close(intent_request['sessionAttributes'], 'Fulfilled', {'...
The code routes incoming user intents to specific handler functions based on the intent name, logging the interaction and invoking functions like `greeting`, `dining_suggestion`, or `thankyou`. If the intent is unsupported, it raises an exception.
def dispatch(intent_request): """ Called when the user specifies an intent for this bot. """ logger.debug('dispatch userId={}, intentName={}'.format(intent_request['userId'], intent_request['currentIntent']['name'])) intent_name = intent_request['currentIntent']['name'] # Dispatch to your bot...
def checkZone(self, aggressor: int) -> frozenset: checkZone = frozenset() for checkRow in self.grid: for checkSquare in checkRow: if checkSquare.piece is not None: if checkSquare.piece.player == aggressor: # Again, pawns are unique ...
This function determines valid castling moves for a king in chess. It checks if the king hasn't moved, if the target squares are unoccupied and not in the opponent's attack zone, and if the rook is in its original position. It returns a frozenset of valid castling moves (king moves two squares toward the rook) for the ...
def getKingMoves(self, player: int) -> frozenset: moves = frozenset() checkZone = self.checkZone(opponent(player)) # Saves some processing to grab this king = self.getKing(player) if king.moved: return moves if king.location in checkZone: return moves ...
def getKing(self, player) -> King: if player == 1: return self.king1 elif player == 2: return self.king2 else: raise ValueError("Player can be either 1 or 2") def checkZone(self, aggressor: int) -> frozenset: checkZone = frozenset() for checkRo...
The function checks if the specified player's king is located within the opponent's check zone, returning True if the king is under attack.
def check(self, player: int) -> bool: return self.getKing(player).location in self.checkZone(opponent(player))
def getMoves(self, start: Square) -> frozenset: if start is None: return frozenset() else: if start.piece is None: return frozenset() else: if start.piece.moves is None: return frozenset() else: ...
This function checks if a player is in stalemate by aggregating all possible moves for their pieces (Kings, Pawns, and others) on the board. If no valid moves exist for the player, it returns True, indicating a stalemate; otherwise, it returns False.
def stalemate(self, player: int) -> bool: stalemate = False moves = frozenset() for row in self.grid: for square in row: if square is not None: if square.piece is not None: if square.piece.player == player: ...
def getPawnMoves(self, square: Square) -> frozenset: moves = frozenset() if square.piece is None: return moves if isinstance(square.piece, Pawn): row = square.row column = square.column player = square.piece.player square.piece.enPassan...
This code checks if a player is in checkmate by simulating all possible moves for their pieces. It temporarily moves each piece, checks if the player is still in check, and reverts the move. If any move allows the player to escape check, checkmate is False. The function returns True only if no valid escape exists, conf...
def checkmate(self, forPlayer: int) -> bool: checkmated = True for row in self.grid: for square in row: if square.piece is not None and square.piece.player == forPlayer: if isinstance(square.piece, Pawn): testMoves = self.getPawnMov...
def get_sub_clips(self): len_subclip = int(len(self.raw)/40) sc = np.zeros((40, len_subclip)) for i in range(40): sc[i][:] = self.raw[i*len_subclip:(i+1)*len_subclip] return sc def get_energy(self, subclips): energies = np.zeros(len(subclips)) count = 0 ...
This code extracts audio features from subclips by aggregating results from multiple methods including energy, zero-crossing rate, Mel-frequency cepstral coefficients, spectral centroid, flux, bandwidth, and harmonic ratio. It compiles these features into a list and returns them, excluding the commented-out LPC coeffic...
def extract(self): subclips = self.get_sub_clips() features = [] features.extend(self.get_energy(subclips)) features.extend(self.get_zero_crossing(subclips)) features.extend(self.get_mel_freq_cepstral_coeffs(subclips)) features.extend(self.get_spectral_centroid(subclips))...
def parse_args(args): """ Command-line argument parsing Parameters ---------- args : Returns ------- XY : cleaned and formatted training database """ parser = argparse.ArgumentParser(description='Performs maximum likelihood calculations for reactor parameter prediction.') ...
The code calculates the maximum log-likelihood of test samples against a training database for spent fuel prediction, computes prediction errors, and saves results as a CSV. It processes training/test data, aligns features, applies ratio transformations if specified, and uses the `mll_testset` function for predictions.
def main(): """ Given a database of spent fuel entries (containing nuclide measurements and labels of reactor operation parameters of interest for prediction) and a testing database containing spent fuel entries formatted in the same way, this script calculates the maximum log-likelihood of each tes...
def parse_args(args): """ Command-line argument parsing Parameters ---------- args : Returns ------- XY : cleaned and formatted training database """ parser = argparse.ArgumentParser(description='Performs maximum likelihood calculations for reactor parameter prediction.') ...
The code calculates the maximum log-likelihood of test samples against a training database to predict reactor operation parameters (e.g., type, cooling time, burnup). It processes training and test data, aligns units, computes prediction errors with uncertainty, and saves results as a CSV. The task involves statistical...
def main(): """ Given a database of spent fuel entries (containing nuclide measurements and labels of reactor operation parameters of interest for prediction) and a testing database containing spent fuel entries formatted in the same way, this script calculates the maximum log-likelihood of each tes...
def get_agenda(): # for this to work with icalBuddy (as of 1/31/21) a special version of the # binary is needed (see this thread https://forum.keyboardmaestro.com/t/icalbuddy-doesnt-work-within-keyboard-maestro-mojave-calendar-permissions/15446/5) # I replaced the exsting version in /opt/homebrew/cellar/bin...
The main task of the code is to generate a structured daily note file by writing navigation links, agenda items, open to-do tasks, and sections for reading and notes. It retrieves calendar data, filters active tasks, and formats them into a markdown-like structure with checkboxes and dates, while including weather info...
def generate_file(fh): tasks = {} agenda = get_agenda().split("\n") # Make note navigation nav_bar = get_link_for_file(get_daily_notes_filename(offset=-1)) nav_bar += " | " + get_link_for_file(get_daily_notes_filename(offset=1)) nav_bar += " | " + get_weather() fh.write(nav_bar + "\n") ...
def make_note(self, note: Note): rendered = self.render_template("note.j2", note=note) dest_dir = f"{self.dist}/n/{note.id}" mkdir_p(dest_dir) with open(f"{dest_dir}/index.html", "w") as output_fd: output_fd.write(rendered) def make_toc(self): index = [] note...
The code's main task is to prepare a distribution directory by creating subdirectories 'n' and 't', process each note in `self.notes` using `make_note`, and generate a table of contents (`make_toc`) and tags (`make_tags`). This likely builds a structured output, such as documentation or a website, by organizing content...
def publish(self): mkdir_p(f"{self.dist}/n") mkdir_p(f"{self.dist}/t") for note in self.notes: self.make_note(note) self.make_toc() self.make_tags()
def get_events(self): # Fetch all the events happening for x in pygame.event.get(): # If the event is closing the window if x.type == pygame.QUIT: # Close the window self.runningState = False self.isPlaying = False # If ...
The main task of the code is to manage the game's main loop, handling events, rendering the menu screen with title text and buttons (Start Game, Credits, Quit), and updating the display until the START flag triggers loop termination. It processes user inputs, blits the background, draws UI elements, and calls game logi...
def main_loop(self): # Start the mainloop while self.isPlaying: # Check for all the events happening self.get_events() # If the user prompts for the game to be started if self.START: # Change start to False self.isPlaying = ...
def initcent(data,k): #output pure number data row=len(data) col=len(data[0]) rang=[i for i in range(1,row)] lists=random.sample(rang,k) centroids=[] for i in range(k): centroids.append(data[lists[i]][1:]) return centroids def dist(vecA,vecB): #input pure data,no name c=[] for i in range(len(vecA)): a=...
The code performs K-means clustering on input data with 'k' clusters, iterating 100*k times to find the optimal clustering. It initializes centroids, assigns data points to nearest clusters, recalculates centroids, and computes Within-Cluster Sum of Squares (WCSS). The function returns the cluster configuration with th...
def kmean(data,k): row=len(data) col=len(data[0]) Cluster=[] Wcss=[] for i in range(100*k): #using dynamic iterTime centroids=initcent(data,k)#giving initial centroids change=True while change: # running unitl the centroids do not change change=False cluster=[[] for i in range(k)] optcluster=[[...
def getMin(L): m=L[0] for i in L: if i <= m: m=i return L.index(m),m def kmean(data,k): row=len(data) col=len(data[0]) Cluster=[] Wcss=[] for i in range(100*k): #using dynamic iterTime centroids=initcent(data,k)#giving initial centroids change=True while change: # running unitl the centroids do ...
The code performs two-step clustering on combined data from two datasets. It first clusters data points based on minimum values, then sub-clusters each group using maximum and minimum values to identify dominant clusters, returning the largest sub-clusters from each group.
def two_step_clustering_verify(data1,data2,k,A,B): #inital phase final_data1 = data1[:,A:B] # remove first 10h unstable data final_data2 = data2[:,A:B] final_data = np.vstack((final_data1,final_data2)) #plot_show(final_data) ##### cluster first time d= [] for i in range(len(final_data1)): a,m = getMin(list(fi...
def data_processing_verify(data,window_size): sample_size = 500 a = random.sample(data,sample_size) b = np.array(a,dtype=float) smooth_data = np.zeros((len(a),len(a[0]))) for i in range(len(b)): smooth_data[i,:] = moving_average(b[i,:],window_size) return smooth_data def two_step_clustering_verify(data1,data2,...
The function verifies clustering accuracy by processing two datasets (P0 and P1) with parameter w, performing two-step clustering using parameters k, A, and B, and calculating the accuracy between resulting clusters. It returns the accuracy metric as the verification result.
def verify(P0,P1,k,A,B,w): data1 = data_processing_verify(P0,w) data2 = data_processing_verify(P1,w) cluster1,cluster2 = two_step_clustering_verify(data1,data2,k,A,B) acc = accuracy(cluster1,cluster2,data1,data2) return acc
def get_sum_subtrees(G, node_to_value): roots = get_roots(G) node_to_sum = {} for r in roots: get_sum_subtree(G, r, node_to_value, node_to_sum) return node_to_sum def get_sum_up_routes(G, node_to_value): leaves = get_leaves(G) node_to_sum = {} for l in leaves: ...
The code identifies the optimal reattachment point for a cluster in a tree structure by evaluating three scenarios: attaching to a node with the highest combined in/out weights, attaching as a child to a node with high child scores, or attaching to roots. It updates the reduced tree by extending clusters or adding new ...
def find_best_reattachment_for_cluster(self, reduced_tree, c_kp_list): # G: graph of clusters (nodes) G = nx.DiGraph() clusters_ids = list(range(len(reduced_tree["clusters"]))) edges = [[e[1], e[0]] for e in reduced_tree["relations"]] G.add_nodes_from(clusters_ids) G.add_...
def get_sum_subtrees(G, node_to_value): roots = get_roots(G) node_to_sum = {} for r in roots: get_sum_subtree(G, r, node_to_value, node_to_sum) return node_to_sum def get_sum_up_routes(G, node_to_value): leaves = get_leaves(G) node_to_sum = {} for l in leaves: ...
The main task of the code is to determine the optimal cluster or position in a graph of clusters to reattach a given node (v_node_id) based on calculated weights. It evaluates three cases: attaching to a cluster with maximum combined in/out weights, attaching to a cluster's child with highest score, or attaching to roo...
def find_best_reattachment(self, reduced_tree, v_node_id): # G: graph of clusters (nodes) G = nx.DiGraph() clusters_ids = list(range(len(reduced_tree["clusters"]))) edges = [[e[1],e[0]] for e in reduced_tree["relations"]] G.add_nodes_from(clusters_ids) G.add_edges_from(ed...
def get_kph(self, clusters, relations): return KPH(clusters, relations, n_kps=self.n_kps, topic=self.topic, domain=self.domain) def reduced_tree_to_graph(self, reduced_tree): return tree_to_full_graph(reduced_tree['clusters'], reduced_tree['relations'], self.pair_to_weight) def get_graph_score(self, G):...
The main task of the code is to iteratively refine a hierarchical structure (clusters and relations) by optimizing a graph score through node reattachment. It processes a reduced tree, removes nodes/clusters, finds optimal reattachment positions, and updates the hierarchy until convergence or max iterations. The result...
def get_hierarchy(self, max_iterations = 8): if self.n_kps == 1: return self.get_kph(clusters = [0], relations = []) G = self.reduced_tree_to_graph(self.reduced_tree) for i in range(max_iterations): start_iter_graph_score = self.get_graph_score(G) for v in r...
def load_pairwise_scores(scores_path, domains = None, topics = None): scores_df = pd.read_csv(scores_path) scores_df = scores_df.rename(columns={"specific_idx": "i", "general_idx": "j"}) if domains: scores_df = scores_df[scores_df["domain"].isin(domains)] if topics: scores_df = scores_df...
The code evaluates pairwise scores across domains and methods, computes metrics like AUC and F1, plots PR curves, and outputs aggregated results in a table and CSV. It processes scores, filters by recall threshold, and averages performance per method for comparison.
def eval_pairwise_scores(scores_path, methods, out_path, domains=None, min_recall = 0.1): logging.info(f"Evaluating pairwise scores for scores in :{scores_path}\n\t\t\tmethods:{methods}\n\t\t\toutput_path:{out_path}") scores_df = load_pairwise_scores(scores_path, domains) domain_to_method_to_results_df = de...
def min_time(timeList): minTime = min(timeList) decimal = parse_time(minTime) % 1 result = 0 if decimal == 0: result = parse_time(minTime) - 1 else: result = int(parse_time(minTime)) return result def max_time(startTimes, endTimes): maxTime = 0 for i in range(len(endTime...
This method processes shift data to prepare it for plotting by extracting start/end times, calculating durations (handling overnight shifts), generating x-axis ticks, and organizing data into arrays for visual representation like a bar chart.
def _procData(self): """ Process data to have all values needed for plotting """ # parameters for bars self.nShifts = len(self.names) self.start = [None] * self.nShifts self.end = [None] * self.nShifts for pkg in self.shifts: idx = self.names.index(pk...
def move(self): if self.bearing == Bearing.NORTH and self.check_front(): self.y -= 1 elif self.bearing == Bearing.EAST and self.check_front(): self.x += 1 elif self.bearing == Bearing.SOUTH and self.check_front(): self.y += 1 elif self.bearing == Beari...
This function processes a sequence of robot movements by dequeuing commands, executing corresponding actions (move, turn, reverse, or mark goals), updating the map, and scheduling itself to repeat every 0.5 seconds using Tkinter's after method.
def displayMovement(self): if not self.simulator.robot_movement: return movement = self.simulator.robot_movement.pop(0) if movement == 'w': self.move() elif movement == 'a': self.left() elif movement == 'd': self.right() eli...
def hamiltonian_path(self): self.robot.hamiltonian_path_search(map_sim, self.goal_pairs) def findFP(self): self.robot.fastestPath(map_sim) def reset(self): if self.job: self.root.after_cancel(self.job) self.robot_movement = [] self.goal_pairs = [] self.temp_pa...
This method processes messages from a queue, triggering specific actions based on message prefixes: initiating exploration, finding the fastest path, or resetting the system. It repeatedly checks the queue, executes corresponding methods, and reschedules itself to run again after 200ms using `self.root.after` for conti...
def event_loop(self): while not general_queue.empty(): msg = general_queue.get() print(msg[:3]) if msg[:3] == START_EXPLORATION: logging.debug('Starting exploration') self.hamiltonian_path() elif msg[:3] == START_FASTEST_PATH: ...
def validate_user_input(self, text_element_key): """Limit user input to this field to 5 characters and remove any invalid characters on the fly. """ element = self.window[text_element_key] val = element.get() if not val: return if not val[-1].isalpha()...
The code runs a Wordle UI, initializing a game with a solver. It processes user events like resetting the game, validating input, submitting guesses, clearing entries, suggesting words, and solving the puzzle. When solving, it clears the log and displays each suggested word. The loop handles interactions, updates the i...
def run(self): """Start the Wordle UI.""" wordle = WordleGame(enable_solver=True) self.window["-ML-"].update("") while True: event, values = self.window.read() if event is None: break if event == "Reset": wordle = Wordle...
def game_is_over(self): """Return True if user has used all 6 guesses or the game was previously determined to be over, else return False. """ if len(self.guesses_made) >= 6 or self.game_over: return True return False def evaluate_guess(self, guess): """Return...
The main task of the code is to solve a word game by iteratively guessing words using a specified scoring method. It employs an optional pre-selected first guess (e.g., "later") to optimize performance, significantly reducing solving time. The function evaluates each guess, updates the game state, and returns the list ...
def solve(self, method=word_level_score, first_guess="later"): """Solve the game using the provided method. Returns the guess list and scores, and whether or not the puzzle was solved. Providing a pre-computed first guess that partitions the solution space well can greatly speed up solv...
def parseGenome(genome): """ Indexes the sequences in the assembly for quick lookup. Paramters: genome (array): An array of SeqRecords """ for rec in genome: SeqRecords[rec.id] = rec def processGenes(args, genes): """ Processes and renames the genes in the provided GFF3 file...
The main task of the code is to process gene and repeat annotations from input files, generate standardized GFF3 and FASTA outputs, and rename features using specified metadata. It parses GFF, RepeatMasker, and FASTA files, extracts sequences, and writes gene/transcript/CDS/protein FASTA files with a consistent naming ...
def main(): """ The main function """ # Specify the arguments that are allowed by this script parser = argparse.ArgumentParser( description='Process some integers.') parser.add_argument('--genes', dest='genes', action='store', required=True, help='...
def move(coords, sleeptime): steps = get_steps() final = [ round(distance([0, 0], coords)/mm_per_step_0), round(distance([0, height], coords)/mm_per_step_1), round(distance([width, height], coords)/mm_per_step_2), round(distance([width, 0], coords)/mm_per_step_3), ] y0 = ((steps[0]*mm_p...
The code reads calibration data from "calibration.txt", processes six numerical values, adjusts robotic arm positions using manual commands, and saves recalibrated radii values based on the final position derived from the calibration data.
def calibrate(): file = open("calibration.txt", "r") steps = ["", "", "", "", "", ""] index = 0 for s in file.read(): if s == "\n": index += 1 else: steps[index] = steps[index] + s file.close() for i in range(6): steps[i] = int(steps[i]) final...
def _create_tool_box(self): self._button_group = QButtonGroup(self) self._button_group.setExclusive(False) self._button_group.buttonClicked.connect(self._button_group_clicked) self._shapes_id: dict[int, Type[model.Shape]] = {} self._last_btn_id = -1 layout = QGridLayout(...
The code initializes a GUI application with a drawing area and tools. It sets up a tool box, actions, and toolbars, then creates a `PaintingArea` for drawing. The layout arranges the tool box and painting area horizontally, sets window properties, and configures focus handling. The main task is to create a graphical in...
def __init__(self): super().__init__() self._create_tool_box() self._create_actions() self._create_toolbars() self._area = PaintingArea() self._area.line_color = self._line_color self._area.fill_color = self._fill_color layout = QHBoxLayout() la...
def run_menu(self): ''' ** Main ** Puts functionality to the main menu page ''' pygame.display.update() #Update screen self.design_menu() #Creates the menu's design #Consider all events that occur in the menu page for event in pygame.event.get(): ...
This code manages a GUI application's state transitions. It runs a loop that executes different functions based on the current status (e.g., main menu, grid window, drawing, algorithm visualization). The loop continues until the GUI stops, then quits Pygame and exits the program. It handles user interactions, state cha...
def run(self): #As long as the GUI is running while self.ACTIVE: #If the current page is the main menu if self.CURR_STATUS == 'main menu': self.run_menu() #If the current page is the grid window if self.CURR_STATUS == 'grid window': ...
def format_conditions(self, triggers): text = "" for trig in triggers: if type(triggers[trig]) is str and triggers[trig] in country_tags: triggers[trig] = country_tags[triggers[trig]] if trig in trigger_dict: if type(triggers[trig]) is dict: ...
The main task of this code is to generate a formatted text description of outcomes in a random list, including conditions, modifiers, and effects. It iterates through each outcome, appending structured text with outcome numbering, conditional triggers, weight calculations based on modifiers, and formatted effect lists....
def format_random_list(self, rand_list): list_text = "" has_ids = False i = 1 for rand_item in rand_list: list_text += "Outcome " + str(i) + ":\n\n" i += 1 outcome = rand_list[rand_item] if "trigger" in outcome: list_text +=...
def shuffleData(dataset): """ Shuffle dataset and separate data inputs and labels Outputs: X_train: data inputs y_train: data labels """ np.random.shuffle(dataset) X_inputs = dataset[:,2:5] X_train = [] for i in range(len(X_inputs)): x = np.hstack((X_...
This function performs mini-batch stochastic gradient descent to train a model by iteratively updating weights using gradient descent. It initializes weights, computes loss and gradients over shuffled data batches, updates weights with learning rate, and stops when gradient magnitude falls below tolerance or max iterat...
def grad_descent(data, step_size, max_iter, lr, tol): """ Mini batch stochastic gradient descent Inputs: data: training dataset step_size: batch size max_iter: max iterations lr: learning rate tol: tolerance Outputs: new_dataFrame...
def checkif_in_trading_window(self, candle="1D"): assert self.connection_preparation_window + self.trading_window < self.axon_maximum_connection_duration self.now = datetime.datetime.utcnow() self.tsnow = int(time.time()) if candle == "1D": if self.now.hour <= 1: ...
The main task of the code is to execute a daily trading strategy by continuously checking if the system is within a trading window, waiting for a forecast from Axon's websocket, connecting to the trading platform, and executing trades when the latest forecast is received. It handles retries on exceptions and sleeps unt...
def run_daily_trading_strategy(self): while True: self.checkif_in_trading_window() if self.is_in_trading_window and not self.new_forecast_executed: assert self.connect() # self.get_latest_forecast() forecast_candle = self.forecast['forecas...
def partition_function(self, operation=None): """ Set the bath qubits according to a partition function """ assert self.prob_ground <= 1, f"prob_ground must be <1 (it's a probability), not {self.prob_ground}" _rand_ = random.random() # random number to determine if qubit will be flipped if operation == 'App...
The code constructs a quantum circuit for quantum phase estimation (QPE). It initializes qubits, applies Hadamard gates for superposition, controlled operations using an unknown gate, inverse QFT for phase retrieval, and measures computation qubits. Additional methods handle thermalization, Markovian dynamics, and bath...
def make_qpe_circuit(self): # define empty circuit self.c = cirq.Circuit() # Thermally initialize bath qubits according to the partition function self.partition_function(operation='Append') # Apply Walsh-Hadamard transform to put Qubits in superposition self.c.append(cirq.H.on_each(*self.computat...
def gate(self,phi): """A unitary 1-qubit gate U with an eigen vector |0> and an eigen value exp(2*Pi*i*phi)""" gate = cirq.SingleQubitMatrixGate(matrix=np.array([[np.exp(2*np.pi*1.0j*phi), 0], [0, 1]])) return gate def set_io_qubits(self): """ Adds n=n_computation_qubits number of input qubits, one output qubit...
The code executes Quantum Phase Estimation (QPE) to determine the phase of an unknown quantum gate. It runs multiple simulations, constructs QPE circuits dynamically, and aggregates results to compute the most probable phase estimate. The output includes the true phase, estimated phase, their difference, and the domina...
def main(self, n_computation_qubits=10, n_bath_qubits=0, n_simulations=100, print_circuit=False, bath_type='Markovian', unknown_gate_phase=.8*np.pi, prob_ground=0.821662): """ Runs QPE on (n_computation_qubits)-qubits """ self.prob_ground = prob_ground self.n_computation_qubits = n_computation_qubi...
def next_token(self): self.current_token += 1 if self.current_token > len(self.tokens): self.error_end_input() self.token = self.tokens[self.current_token-1]['token'] self.current_token_line = self.tokens[self.current_token-1]['line'] def id(self): if re.match(r'[a-z]...
This code parses a SQL TRUNCATE TABLE statement by verifying the correct token sequence: 'truncate' followed by 'table' and an identifier, then checking for a semicolon. It handles syntax errors by raising exceptions for unexpected tokens, ensuring valid SQL syntax compliance.
def truncate(self): if self.token == 'truncate': self.next_token() if self.token == 'table': self.next_token() self.id() else: self.error_not_expected_token('table') self.verify_semicolon()
def id(self): if re.match(r'[a-z]+', self.token): if self.token not in self.reserved_words: self.next_token() else: self.error_reserved_word() else: self.error_not_expected_token("<id>") def next_token(self): self.current_token ...
The main task of the code is to parse a comma-separated list of identifiers. It first processes a single identifier via `self.id()`, then checks for a comma token. If found, it advances the token stream and recursively calls `self.ids()` to continue parsing subsequent identifiers, effectively handling multiple identifi...
def ids(self): self.id() if self.token == ',': self.next_token() self.ids()
def next_token(self): self.current_token += 1 if self.current_token > len(self.tokens): self.error_end_input() self.token = self.tokens[self.current_token-1]['token'] self.current_token_line = self.tokens[self.current_token-1]['line'] def id(self): if re.match(r'[a-z]...
This code processes a 'use' statement in a parser. It checks if the current token is 'use', advances to the next token, parses an identifier, and verifies a semicolon follows, ensuring syntactic correctness for the 'use' directive.
def use(self): if self.token == 'use': self.next_token() self.id() self.verify_semicolon()
def next_token(self): self.current_token += 1 if self.current_token > len(self.tokens): self.error_end_input() self.token = self.tokens[self.current_token-1]['token'] self.current_token_line = self.tokens[self.current_token-1]['line'] def id(self): if re.match(r'[a-z]...
This method parses a 'where' clause by checking for the 'where' token, followed by an identifier, an equals sign, and a value. It advances tokens sequentially, validating syntax and raising an error if the '=' token is missing after the identifier.
def where(self): if self.token == 'where': self.next_token() self.id() if self.token == '=': self.next_token() self.value() else: self.error_not_expected_token('=')
def value(self): if re.fullmatch(r'[0-9]+', self.token) or re.fullmatch(r'\'[a-z0-9\-]*\'+', self.token): if self.token not in self.reserved_words: self.next_token() else: self.error_reserved_word() else: self.error_not_expected_token("...
This method recursively parses a comma-separated list of values. It first processes a single value via self.value(), then checks for a comma token. If found, it advances to the next token and recursively calls itself to parse subsequent values, effectively handling multiple values separated by commas in a list-like str...
def values(self): self.value() if self.token == ',': self.next_token() self.values()
def field(self): self.id() self.id() def next_token(self): self.current_token += 1 if self.current_token > len(self.tokens): self.error_end_input() self.token = self.tokens[self.current_token-1]['token'] self.current_token_line = self.tokens[self.current_token...
This code recursively parses a list of fields separated by commas. It processes a single field via `field()`, checks for a comma token, advances the parser if found, and recursively processes subsequent fields. The method handles comma-separated field sequences in a parser or tokenizer, likely for structured data forma...
def fields(self): self.field() if self.token == ',': self.next_token() self.fields()
def next_token(self): self.current_token += 1 if self.current_token > len(self.tokens): self.error_end_input() self.token = self.tokens[self.current_token-1]['token'] self.current_token_line = self.tokens[self.current_token-1]['line'] def id(self): if re.match(r'[a-z]...
This code parses a DELETE SQL statement by checking for the 'delete' keyword, followed by 'from', an identifier (id), and a 'where' clause. It validates tokens sequentially, advances through them using next_token(), and raises errors for unexpected tokens. Finally, it verifies a semicolon to ensure proper syntax.
def delete(self): if self.token == 'delete': self.next_token() if self.token == 'from': self.next_token() self.id() self.where() else: self.error_not_expected_token('from') self.verify_semico...
def next_token(self): self.current_token += 1 if self.current_token > len(self.tokens): self.error_end_input() self.token = self.tokens[self.current_token-1]['token'] self.current_token_line = self.tokens[self.current_token-1]['line'] def id(self): if re.match(r'[a-z]...
This code parses an UPDATE statement by checking tokens like 'set', '=', and 'where', validating syntax, and handling errors for unexpected tokens, ensuring correct structure with error reporting and semicolon verification.
def update(self): if self.token == 'update': self.next_token() self.id() if self.token == 'set': self.next_token() self.id() if self.token == '=': self.next_token() self.value() ...
def next_token(self): self.current_token += 1 if self.current_token > len(self.tokens): self.error_end_input() self.token = self.tokens[self.current_token-1]['token'] self.current_token_line = self.tokens[self.current_token-1]['line'] def id(self): if re.match(r'[a-z]...
The code parses an 'ORDER BY' command by checking tokens. If 'order' is detected, it expects 'by' followed by an identifier (self.id()), otherwise it raises an error. If 'order' isn't found, it delegates to self.where(). The main task is validating and processing SQL-like ordering syntax.
def cmd3(self): if self.token == 'order': self.next_token() if self.token == 'by': self.next_token() self.id() else: self.error_not_expected_token("by") else: self.where()
def next_token(self): self.current_token += 1 if self.current_token > len(self.tokens): self.error_end_input() self.token = self.tokens[self.current_token-1]['token'] self.current_token_line = self.tokens[self.current_token-1]['line'] def id(self): if re.match(r'[a-z]...
This code parses an INSERT SQL statement by validating the syntax structure, checking for required keywords like 'insert', 'into', 'values', and ensuring proper use of parentheses and semicolons, while handling errors for unexpected tokens or missing components.
def insert(self): if "insert" == self.token: self.next_token() if "into" == self.token: self.next_token() self.id() if self.token == '(': self.next_token() self.ids() if self.token...
def next_token(self): self.current_token += 1 if self.current_token > len(self.tokens): self.error_end_input() self.token = self.tokens[self.current_token-1]['token'] self.current_token_line = self.tokens[self.current_token-1]['line'] def id(self): if re.match(r'[a-z]...
The main task of the code is to parse and validate SQL-like syntax for creating databases or tables. It checks tokens sequentially, processes identifiers, verifies parentheses, and handles field definitions. If syntax errors occur (e.g., missing parentheses), it raises appropriate errors. The method returns successfull...
def cmd1(self): if self.token == "database": self.next_token() self.id() elif self.token == "table": self.next_token() self.id() if self.token == "(": self.next_token() self.fields() if self.token...
def next_token(self): self.current_token += 1 if self.current_token > len(self.tokens): self.error_end_input() self.token = self.tokens[self.current_token-1]['token'] self.current_token_line = self.tokens[self.current_token-1]['line'] def cmd2(self): if self.token == ...
The code parses a SQL SELECT statement by checking for the 'select' keyword, processing subsequent tokens like 'from', identifiers, and ensuring proper syntax with a semicolon, validating the structure step-by-step.
def select(self): if self.token == "select": self.next_token() self.cmd2() if self.token == 'from': self.next_token() self.id() self.cmd3() self.verify_semicolon()
def next_token(self): self.current_token += 1 if self.current_token > len(self.tokens): self.error_end_input() self.token = self.tokens[self.current_token-1]['token'] self.current_token_line = self.tokens[self.current_token-1]['line'] def cmd1(self): if self.token == ...
This code parses and executes a "create" command by checking the token, advancing to the next token, invoking a command method (cmd1), and verifying a semicolon for syntax validation.
def create(self): if "create" == self.token: self.next_token() self.cmd1() self.verify_semicolon()
def serialize( value, ref=None ): if callable( value ): if not ref: ref = bindReturn( value ) return { 'type':"function", 'ref':ref } if not(isJsonSerializable( value )): if not ref: ref = bindReturn( value ) return { ...
This function handles incoming messages by performing operations based on the 'op' field (e.g., GET/SET/CALL). It processes requests, interacts with referenced objects, executes Python code, manages bindings between languages, and sends serialized responses or errors through a connection. It maintains a loop to continu...
def runMessageHandler(): if not connection: raise Exception("Not connected") print("receiving messages") _running = True while _running: msg = connection.receive() try: print("Py <- "+str(msg)) op = msg["op"] rsp = {} if op == "GET...
def CalcRes(self): n1 = self.n1 n2 = self.n2 N = self.N M = self.M x = self.x y = self.y f = self.f B1 = self.B1 B2 = self.B2 reslist=[] # first ne residuals at k=0 for i in range(n1): E = y[i][0] - sel...
This code iteratively solves a system of equations using residual calculations, matrix inversion, and error checks. It performs iterations to minimize error until convergence (error < tolerance) or max iterations are reached. If unresolved, it marks the process as unsuccessful. The loop updates variables, scales correc...
def start(self): errList = [] itList = [] for it in range(self.iteration): resList=self.CalcRes() s = self.CalcS() with warnings.catch_warnings(): warnings.simplefilter("ignore") deltayList = spsolve(s, -resList) er...
def secho(s: str, fg=None) -> None: """Write text in tqdm with :func:`click.style`.""" tqdm.write(click.style(s, fg=fg)) def analyze_by_path(path: Union[str, Path], *, iri_filter: Optional[str] = None) -> AnalysisResults: """Analyze an ontology at a given IRI.""" path = Path(path).resolve() parse_re...
The function `analyze` processes an ontology by accepting one input source (IRI, prefix, or file path) and validating its existence. It performs analysis using `analyze_by_path`, `analyze_by_iri`, or `analyze_by_prefix`, depending on the input. Results are formatted as markdown, saved to a file if a prefix is provided,...
def analyze( iri: Optional[str], prefix: Optional[str], path: Optional[Path], cache: bool, iri_filter: Optional[str], obo_filter: bool, ): """Analyze a given ontology.""" analysis_results: AnalysisResults if 1 != sum(arg is not None for arg in (iri, prefix, path)): secho("Ca...
def cell_is_in_line(self, cell): moves = CoordinatesMoves horizontal_moves = [moves.LEFT, moves.RIGHT] vertical_moves = [moves.UP, moves.DOWN] diagonal1_moves = [moves.UP_LEFT, moves.DOWN_RIGHT] diagonal2_moves = [moves.UP_RIGHT, moves.DOWN_LEFT] directions = [horizontal...
This function moves an item along a specified path on a grid, updating positions step-by-step with a timer. It transfers the item from the current cell to the next cell in the path, clears the current cell, and triggers a signal. When reaching the final step, it deactivates the item, checks for completed lines, and eit...
def move_item(self, path: list, step: int = 0): current_cell_point = path[step] current_cell = self.items[current_cell_point.x(), current_cell_point.y()] if step < len(path) - 1: next_cell_point = path[step + 1] next_cell = self.items[next_cell_point.x(), next_cell_poin...
def terrain_gen(npeaks=1, smoothness=1.7): def terrain(x): return cos(npeaks*pi*x) / smoothness return terrain def loop(terrain, controller,limit=1000): result = {'x': [], 'v': [], 'c': [], 'nstep':0, 'failed': False} car = Car() while car.x<Consts.goal: if result['nstep']...
The code evaluates a controller's performance on diverse terrains by iterating over ranges of `npeaks` and `smoothness` parameters. For each terrain configuration, it generates a terrain, runs the controller, checks for failure, and collects errors. It returns the count of failed tests and a list of error values, with ...
def evaluate(controller, silent=True, r=range(2,10), s=range(10,15,1)): nfailed = 0 errors = [] t = 0 for npeaks in r: for smoothness in s: t+=1 terrain = terrain_gen(npeaks=npeaks, smoothness=smoothness) result = loop(terrain, controller) if resu...
def check_turn(self): xpos, ypos = self.get_center() if xpos == ROAD_WIDTH/4 and ypos >= ROAD_WIDTH/4 and ypos+self.y_vel < ROAD_WIDTH/4: self.correct_y() self.x_vel = abs(self.y_vel) self.y_vel = 0 elif ypos == 3*ROAD_WIDTH/4 and xpos >= 3*ROAD_WIDTH/4 and xp...
This function updates the position of an object by handling directional turns and forward movement. It checks if a turn is required, calculates the distance to the turn intersection, and adjusts velocity vectors (x_vel, y_vel) to execute the turn (U/L/D/R). If the turn is incomplete, it accumulates distance and continu...
def update_pos(self): self.check_turn() stop = self.check_signal_cross() if self.turn_inbound == True: if self.start_dist == True: self.turn_dist = 0 self.start_dist = False dir = self.turn_direction intersect_dist = self.turn_d...
def setup_status(pixels, status, message, end=None): if end is None: print("setup_status: %s -- %s"%(status, message)) else: print(message, end=end) if not pixels: return if not isinstance(pixels, list): pixels = [pixels] color = {STATUS.ready: 'WHITE', ...
The main task of the code is to initialize a NeoPixel LED strip connected to pin 5 with 50 pixels, sequentially setting status indicators for device setup stages: initializing a microchip, connecting to a network, requesting RTC time, and marking setup completion. It uses the SeabornNeoPixel library to control LEDs, up...
def main(): from seaborn_neopixel import SeabornNeoPixel np = SeabornNeoPixel(pin=5, count=50) setup_status(np.pixels[0:1], STATUS.ready, 'setup microchip: %s'%NAME) connect_to_network(pixels=np.pixels[1:2]) request_rtc(pixels=np.pixels[2:3]) setup_status(np.pixels[0:1], STATUS.go, 'setup compl...
def static_forward(self, x: torch.Tensor) -> torch.Tensor: # B, n, d = x.size() ### Wrap for cpu offloading ### ############################### source_device = x.device if self.matrix_op_device is not None and source_device != self.matrix_op_device: x = x.to(self.mat...
This function processes input tensor `x` using different forward methods based on `batch_sizes`. If `batch_sizes` is provided and `self.db` is True, it uses `static_forward` for uniform batch sizes or `dynamic_static_forward` for varied ones. If `self.db` is False, `dynamic_forward` is used. Without `batch_sizes`, `sta...
def forward( self, x: torch.Tensor, batch_sizes: np.ndarray | List[int] | None = None ) -> torch.Tensor: if batch_sizes is not None: if self.db: ub = np.unique(batch_sizes) if len(ub) == 1: x = self.static_forward(x.view(-1, ub[0], x.si...
def initializeParameterNode(self): """ Ensure parameter node exists and observed. """ # Parameter node stores all user choices in parameter values, node selections, etc. # so that when the scene is saved and reloaded, these settings are restored. self.setParameterNode(self.logic.getParameterNode...
The code initializes a Slicer module by loading a UI from a .ui file, setting up the MRML scene, creating a logic class for computations, and connecting GUI elements to handle user interactions like button clicks, node selections, and data collection parameters. It also sets up event observers for scene changes and ini...
def setup(self): ScriptedLoadableModuleWidget.setup(self) # Load widget from .ui file (created by Qt Designer). uiWidget = slicer.util.loadUI(self.resourcePath('UI/BroadbandSpecModule.ui')) self.layout.addWidget(uiWidget) self.ui = slicer.util.childWidgetVariables(uiWidget) # Set scene in MRML...
def updateOutputTable(self): '''Handles formating the input spectum for display in the output table''' # Get the table created by the selector parameterNode = self.getParameterNode() spectrumImageNode = parameterNode.GetNodeReference(self.INPUT_VOLUME) tableNode = parameterNode.GetNodeReference(self...
This function handles real-time processing and plotting when the spectrum image is modified. It updates the output table, classifies spectra if enabled, updates charts, and manages control points during scanning by checking distances between the probe tip and last control points. If thresholds are exceeded, new control...
def onSpectrumImageNodeModified(self, observer, eventid): ''' This function is called whenever the spectrum image is modified. It handles much of the real-time processing and plotting. ''' parameterNode = self.getParameterNode() spectrumImageNode = parameterNode.GetNodeReference(self.INPUT_VOL...
def removeObservers(self): ''' Removes observers from the scene ''' for nodeTagPair in self.observerTags: nodeTagPair[0].RemoveObserver(nodeTagPair[1]) def addObservers(self): ''' Adds observers to the scene ''' parameterNode = self.getParameterNode() spectrumImageNode = parameterNode.GetNodeR...
The main task of the code is to initialize spectrum data plotting in a medical imaging viewer. It changes the layout to a conventional plot view, removes existing observers to prevent duplicates, adds new observers for updates, and triggers the initial spectrum data update with (0,0) parameters. This sets up the visual...
def startPlotting(self): ''' Starts plotting the spectrum data in the spectrum viewer''' print("Start plotting") # Change the layout to one that has a chart. ln = slicer.util.getNode(pattern='vtkMRMLLayoutNode*') ln.SetViewArrangement(slicer.vtkMRMLLayoutNode.SlicerLayoutConventionalPlotVi...
def get_mode_and_filename_from_terminal_params(): #DEFAULT PARAMETRES prog_mode = 1 file_name = "moonlanding.png" #PARAMETRE PARSING #sys.argv returns a list of all argument. arg 0 is always the name of the program. args_valid = True most_recent_arg = "" for i in range(1, len(sys.argv)...
The code processes images based on user-selected modes: (1) FFT visualization, (2) denoising via frequency filtering, (3) compression with Fourier coefficient zeroing and CSV saving, or (4) runtime comparison of DFT/FFT algorithms. It handles input validation, image scaling, Fourier transforms, and visualization, with ...
def main(): # Obtain user-defined program parametres mode, filename = get_mode_and_filename_from_terminal_params() # Stop for user errors if mode is None or filename is None: return # Attempt to retrieve image data img = get_image_from_filename(filename) # Stop for io errors if i...
def measure(self, reset=False): circuit = self.circuit_grid_model.compute_circuit() backend_sv_sim = BasicAer.get_backend('qasm_simulator') cr = ClassicalRegister(self.qbit_qty) measure_circuit = deepcopy(circuit) # make a copy of circuit measure_circuit.add_register(cr) # add...
The code generates a visual representation of quantum circuit data by creating lines with padding, measuring probabilities, and combining circuit structure with probability values. It initializes empty lines, adds padding spaces, processes measured data into probabilities, constructs circuit diagrams, and appends proba...
def render(self, last_measured={}): lines = [] for i in range(self.y_padding): lines.append(" " * self.width) measured = self.measure() probas = [0] * self.bar.tracks_qty for key, value in measured.items(): probas[int(key, 2)] = int(value) line...
def __getConnAndCursor(self): """ returns a dict with a connection object and a cursor with results as dicts """ conn = getConnection(self.credentials) cursor = conn.cursor(dictionary=True) return { "conn": conn, "cursor": cursor } def...
The main task of the code is to retrieve completed interviews created by a specific user from a database, fetch associated interviewee data and profile files, and return structured JSON responses containing interview results, names, and profiles. It handles database queries, file I/O operations, error logging, and form...
def getInterviewsByUserId(self, user_id): """ Spected reasponse format: {Interviews:{ "interview_key_1":{"results":{"contento of the results files"}, "name":"name of the interviewee"} . . . ...
def __getIntervieweeNameNdTests(self, interview_id): """ gets interview all the interview's tests short names and the name of the interviewee that took them """ mysql = self.__getConnAndCursor() try: sql = f"SELECT interviewees.name AS interviewee, tests.short_nam...
This function retrieves and constructs test information based on a given test token and user ID. It logs the process, fetches interviewee and test details, builds a response dictionary, and checks for cached results in a JSON file. If the file exists, it loads the cached data into the response; otherwise, it initialize...
def getTestTokenInfo(self, test_token, user_id): #the test_token == interview_id self.logger.log(f"Getting test_token info({test_token})...") tests_short_names = self.__getIntervieweeNameNdTests(test_token) response = { 'interview': test_token, 'interviewer': f"te...
def __getConnAndCursor(self): """ returns a dict with a connection object and a cursor with results as dicts """ conn = getConnection(self.credentials) cursor = conn.cursor(dictionary=True) return { "conn": conn, "cursor": cursor } def...
The main task of the code is to delete an interviewee by their ID from the database and associated file system data. It checks if the interviewee exists, deletes related interviews, removes the interviewee's directory, and deletes the interviewee record from the database. If any step fails, it returns an error response...
def deleteIntervieweeById(self, interviewee): """ Spected reasponse format: {response:"standar response"} """ self.logger.log(f"Deleting interviewee '{interviewee}'...") if re.match(r"^[a-z\d]{40}",interviewee): mysql = self.__getConnAndCursor() ...
def doManualBackUp(self, json_data, backup_name): """ does a manual backup of any and all results or ungoing tests, the only way any of this get deleted is by manual deletion. no info of this backups is stored and they are not used anywhere else in the system. """ ...
The main task of the code is to update an interview's status in the database as completed and save its results as a JSON file. It logs the process, performs a backup, retrieves the interview data, marks it as finished, creates a directory structure based on user data, writes the results to a JSON file, and handles erro...
def updateResults(self, interview_id, results): """ gets the results of an interview once is completele finished and updates its status on de DB Spected reasponse format: {response:"standar response"} """ self.logger.log(f"Updateing results for {i...