dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def checkBattery(): battery = psutil.sensors_battery() percentage = battery.percent return percentage def speak(audio): engine.say(audio) print(audio) engine.runAndWait() def selectGender(): gender = take_command() #print(gender) if gender=="arva" or gender=="arwa" or gender=="Arwa" ...
The code's main task is to check the system's battery level, issue reminders to charge if low, and exit if critically low. It then greets the user based on the time of day and prompts them to choose between two voices (Arva or Vishti) for interaction.
def wish(): hour = int(dt.datetime.now().hour) battery = checkBattery() if battery>15 and battery<35: speak("REMINDER... Battery low, connect the charger") elif battery<=15 and battery>2: speak("Less than 15 percent battery remaining, connect the charger or the system will shut down") ...
def SnakeAndLadderCreation(boardsize): y = math.ceil(boardsize/10) choice = [i for i in range(3, boardsize-1)] snake = [0 for i in range(2*y)] ladder = [0 for i in range(2*y)] gistsnake = "" gistladder = "" for i in range(0, 2*y, 2): snake[i] = random.choice(choice) choice.re...
The function initializes a snake and ladder game by setting up player positions, generating the board with snakes and ladders, displaying game details, and looping through players' turns. It uses color-coded visuals and updates positions via the `MakingTheMove` function, terminating when a player reaches position -1.
def Initiasation(players, boardrow, boardcol): print(Fore.WHITE+"-------------------------------------") positions = [0 for i in range(players)] snakeandladder = SnakeAndLadderCreation(boardrow*boardcol) print("Total Players:", players) print("Initial position of all the players:", 0) print(Fore...
def getResults(): results = [] competitionIds = [ # world champs 7138987, # diamond league 7172922, 7172925, 7172926, 7155407, 7154228, 7155467, 7172927, 7147656, 7154214, 7172928, 7154215, ...
The main task of the code is to update athletes' Elo ratings based on race results. It gathers results and athlete data, calculates Elo changes for each athlete in each race, updates their ratings, enforces a minimum starting Elo, and prints detailed results. Finally, it summarizes all athletes' final Elo scores in des...
def main(): # gather results results = getResults() athletes = getAthletes(results) # check each result for result in results: delo = {} for name in result.names: delo[name] = calculate(athletes[name], athletes, result) print(f"{result.date} {result.racename} re...
def formula_search (doc, svar): return doc.findall('.//function[@name="' + svar + '"]...') def list_variables (fnode, svar): list_var = {} for child in fnode.iter('var'): if (child.attrib.get("name") != svar): list_var[str(child.attrib.get("name"))] = 0 return(list_var) def get_unit ...
The code selects a mathematical equation based on user input, collects required variables, and creates input fields for users to enter values. It then evaluates the equation using the entered values, handles scientific notation and units, and displays the computed result or error messages.
def selectEquation(btnText, argVar): searched_variable = txtToName[argVar] items = formula_search(root, searched_variable) selected_equation = btnText[0] formula_node = items[int(selected_equation) - 1] lvar = list_variables(formula_node, searched_variable) svar_unit = get_unit(formula_node, se...
def reset_error_msg(): all_widgets = main.grid_slaves() for widget in all_widgets: if(widget.config("text")[-1] == "Please enter a number" or "has a value of" in (widget.config("text")[-1]) or widget.config("text")[-1] == "There is no possible value"): widget.destroy() def createHistoryButto...
The code processes user input to solve for a variable using a selected formula. It destroys existing widgets, displays input fields for required variables, evaluates the formula upon submission, handles scientific notation, and shows results with error handling. If multiple formulas exist, it lets the user choose one b...
def get_formula(argVar): reset_error_msg() all_widgets = main.grid_slaves() for widget in all_widgets: widget.destroy() createHistoryButton() searched_variable = txtToName[argVar] items = formula_search(root, searched_variable) if(len(items) == 1): formula_node = items...
def emptyGuide(): all_widgets = guide.grid_slaves() for widget in all_widgets: widget.destroy() doNotCloseGuide() def createHistoryButton(): global lastVariables if(len(lastVariables) != 0): history = Button(main, text="Previous answers", command=showHistory, font="Consolas 10", bord...
This function displays variables from an XML tree as interactive buttons, allowing user selection. It parses the provided XML file, extracts variable names and associated formulas, and dynamically creates buttons for each. The UI is updated by clearing existing widgets, generating new buttons in a grid layout, and stor...
def showVarList(treeToUse): emptyGuide() Label(guide, text = "To continue, choose the variable you want to find.", font="Consolas 10", bg="#c2d1e8").grid(row=2, column=22) createHistoryButton() all_widgets = main.grid_slaves() for widget in all_widgets: widget.destroy() createHistoryButt...
def _generate_a(self, number: int) -> None: self.a = random.randint(1000, 2000000000) def _generate_p(self, number: int) -> None: while True: prime_candidate = self.get_low_level_prime(number) if not self.is_miller_rabin_passed(prime_candidate): continue ...
The main task of the code is to initialize or generate multiple parameters by calling private methods. It invokes `_generate_a(50)`, `_generate_p(35)`, `_generate_g()`, and `_generate_residue_division()` to set up parameters like 'a', 'p', 'g', and residue divisions, likely for cryptographic or mathematical computation...
def generate_parameters_client(self) -> None: self._generate_a(50) self._generate_p(35) self._generate_g() self._generate_residue_division()
def collapse_reads(df, meta, collapse_var='', use_rpm=True): ''''Average read counts using geometric mean''' if use_rpm: df = normalize_rpm(df, meta, collapse_var) elif collapse_var: df = df.transpose() df = np.log10(df.fillna(0.0) + 1) df = df.join(meta[collapse_var]) df = df.groupby(collapse_var).mean()...
The main task of the code is to normalize biological data (e.g., metagenomic reads) across sample types ('tissue'/'blood'), collapsing data to sample-, patient-, and file-level metadata. It applies three normalization methods (read average, relative abundance, and CLR) to processed data, saving results as tab-separated...
def main(): # Normalize within sample types for sample_type in ['tissue','blood']: if sample_type == 'blood': ix_tissue = META.index[META['sample.Sample']=='BDN'] elif sample_type == 'tissue': ix_tissue = META.index[META['sample.Sample'].isin(['PT','STN'])] samples = np.intersect1d(DATA.columns, ix_tis...
def add_port(name, port): cmd = ["add-port", name, port] return _vsctl_cmd(cmd) def set_type_port(port, type): cmd = ["set", "interface", port, "type={}".format(type)] return _vsctl_cmd(cmd) def set_peer_port(port, peer): cmd = ["set", "interface", port, "options:peer={}".format(peer)] return _v...
The function `add_port_patch` adds a port with specified configurations, setting its type to "patch", assigning a port number, and optionally specifying a peer port. It wraps exceptions in a `RuntimeError` to handle failures during port configuration.
def add_port_patch(name, port, num_port, peer=None): try: add_port(name, port) set_type_port(port, "patch") set_peer_port(port, peer) set_port_num(port, num_port) except Exception as ex: raise RuntimeError(ex.__str__())
def get_ports(br): cmd = ["list-ports", br] p = _vsctl_cmd(cmd) return p.split() def is_trunk(port): cmd = ["get", "port", port, "trunk"] ret = _vsctl_cmd(cmd) r = ret.replace("\n", "") if r == "[]": return False return True def get_tag_port(port): cmd = ["get", "port", port,...
The function `get_tags_br` extracts non-trunk port tags from a network device (via `br`), cleans them by removing newline characters, and returns a list of these tags. If no non-trunk tagged ports exist, it raises a `RuntimeWarning`.
def get_tags_br(br): ports = get_ports(br) tags = [] for port in ports: if not is_trunk(port): tag = get_tag_port(port) tags.append(tag.replace("\n", "")) if len(tags) == 0: raise RuntimeWarning("there are is not tagged ports") return tags
def get_trunk_ports(br): ports = get_ports(br) for i in ports: if is_trunk(i): return i raise RuntimeWarning("there are not trunk ports") def get_tags_br(br): ports = get_ports(br) tags = [] for port in ports: if not is_trunk(port): tag = get_tag_port(port...
The code updates trunk ports on a bridge by retrieving the trunk ports and associated tags, then applying those tags to configure the trunk ports properly.
def update_trunk_port(br): trunk = get_trunk_ports(br) tags = get_tags_br(br) set_trunk_port(trunk, tags)
def predict_GLM(data, lags = 5): """ Parameters --------------------- data: A list of 0s and 1s lags: the number of symbols the observer looks back. Must be a positive integer. Outputs ------------------------ A set of probabilities for the next symbol being a 1 """ # Create a d...
The function evaluates the likelihood of prediction strategies (GLM, L4) by either using provided predictions or simulating them via specified methods (GLM, L2, L4). It calculates and returns likelihoods for each strategy using statistical models, comparing observed predictions against true observer parameters (alpha, ...
def predFunc_guess(data, preds, lags = 5, simulate = "", alphaTrue = 3, betaTrue = 1, gammaTrue = 1, numObs = 1): """ Takes a string of model output and predictions, returns the likelihood of each prediction strategy Parameters ----------------- data: Time series of symbols to be analyzed preds:...
def _get_session_index(self): self.currentSessionIndex += 1 if self.currentSessionIndex == self.nbSessions : self.currentSessionIndex = 0 return self.currentSessionIndex def _get_page(self,index, url, params=None, check=True): response = self.webSessions[index].get(url, allow...
The main task of the code is to fetch a webpage content via a GET request. If the session is logged out, it automatically refreshes the session and retries. If re-login fails, it raises a LoggedOutError. The function returns the page content after handling potential session issues, with logging for debugging and error ...
def get_page(self, url): """ Try to load a page (GET), if the account is disconnected, it automaticly refresh the session and log back in if the session is still not logged in : LoggedOutError will be raised """ index = self._get_session_index() try: ...
def get_nb_pending_job(self): """ Return number of pending job """ return len(self.jobList[PENDING]) def get_nb_current_job(self): """ Return number of pending job """ return len(self.jobList[CURRENT]) def _pop_job(self): """ Pop first pen...
The code processes jobs in parallel using a thread pool. It continuously submits pending jobs to the executor and sleeps based on the current job count to manage execution rate, ensuring all jobs are handled while dynamically adapting to new tasks.
def run(self): with ThreadPoolExecutor(max_workers=self.threadNb) as executor: while self.get_nb_pending_job() > 0 or self.dynamicQueue and self.get_nb_current_job() > 0: while self.get_nb_pending_job(): jobId, jobArg = self._pop_job() executo...
def check_for_errors(self): """ Checks if the code has the errors or not specified data """ if ( DRIVER_PATH == '' ): raise Exception('You must specify the path to the Webdriver') def greeting_message(self): """ Output the Greeting message """ self.clear_screen() print('Welcome to Steam Bulk Buye...
The main task of the code is to orchestrate a user-guided purchase process by sequentially checking for errors, displaying a greeting, collecting user items, outputting retrieved items, pausing for confirmation, issuing a warning, processing the purchase, and displaying a success message. It ensures structured interact...
def main(self): self.check_for_errors() self.greeting_message() self.get_items_from_user() self.output_retrieved_items() input('Press ENTER to Proceed...\n') self.warning_message() self.purchase_items() self.success_message()
def update_data_list(self) -> List[float | Any]: open_column = self.df["open"] high_column = self.df["high"] low_column = self.df["low"] close_column = self.df["close"] all_values = list(zip(open_column, high_column, low_column, close_column)) cleared_list = list(chain(*...
The main task of the code is to generate successful buy and sell orders using historical data. It updates data, determines sections based on input percentages, executes buy orders, identifies the earliest allowable sell index, and then executes sell orders. The function returns two dictionaries containing buy and sell ...
def make_transactions( self, ) -> Tuple[Dict[float, Dict[str, float]], Dict[float, Dict[str, float]]]: history_data = self.update_data_list() section_number = len(self.input_percents) successful_buy_orders = self.try_to_buy(history_data, section_number) min_sell_history_index...
def get_data(): dirname = os.getcwd() + '/data' remove_old(dirname) print('Cloning into %s' % dirname) git.Repo.clone_from('https://github.com/CSSEGISandData/COVID-19.git', dirname, progress = Progress()) mypath = dirname + '/csse_covid_19_data/csse_covid_19_daily_reports/' os.remove(mypath + '/...
The code processes command-line arguments to either display help, trigger a one-time data update, or run a scheduled task loop. If no flags are provided, it configures settings and enters a loop executing pending scheduled tasks every second, handling keyboard interrupts and errors gracefully.
def main(args): if '-h' in args: print('USAGE') print('\t%s [-update | -h]' % sys.argv[0]) print('') print('DESCRIPTION') print('\t-update\tget data only once and immediatly') print('\t-h\tdisplay help') return if '-update' in args: get_data() ...
def get_dates_for_whole_period(): today = datetime.date.today() dates = [] for i in range(WEEKS_TO_EXAMINE): dates.extend(examine_one_week(today + datetime.timedelta(days=i * 7))) return get_hours_for_dates(dates) def list_subs(subtrahend, minuend): return sorted([item for item in subtrahend...
The function identifies new available date slots by comparing current dates with cached ones, logs the findings, updates the cache, and sends notifications if new dates are detected.
def get_new_dates_for_whole_period(): cached = cache.read() available_dates = get_dates_for_whole_period() script_log(str(len(available_dates)) + " slots found " + ', '.join(available_dates)) new_dates = list_subs(available_dates, cached) cache.write(available_dates) if len(new_dates): s...
def validate_dates(): """Function that compares the system date with the actual date. When different the user is asked for input, to either proceed with the current settings, or reset the date. """ if read_config()['enable_date_alert']: today = string_to_date(get_today()) system_date =...
The main task of the code is to add a product to a 'bought.csv' file multiple times based on the 'amount' parameter. It validates the product name, generates unique buy IDs, creates data entries with product details, and writes them to the CSV. After processing, it prints a table showing the last added row's details, c...
def buy_product(product_name:str, price:float, expiration_date, amount:int=1): """Adds a product (in lowercase) to the bought.csv file the amount of times passed via the amount argument by: - validating the product name - generating a buy id - putting all values in a list After writing to the csv fi...
def validate_dates(): """Function that compares the system date with the actual date. When different the user is asked for input, to either proceed with the current settings, or reset the date. """ if read_config()['enable_date_alert']: today = string_to_date(get_today()) system_date =...
The main task of the code is to record a sold item by generating a unique ID, validating the system date, and writing the item's details—包括 sold ID, bought ID, product name, system date, and sell price—to the 'sold.csv' file in a structured format.
def store_sold_item(bought_id:int, product_name:str, sell_price:float): """Writes the sold item to the sold.csv file after: - checking and validating the system date - generating an id - putting all row items in a list """ validate_dates() sell_id = generate_id(SOLD_CSV) data = [sell_id,...
def check_product_names(word:str): """Validator function that checks the given string and compares it with existing strings in groceries.csv and bought.csv. The list of strings is collected via get_grocery_list(). The process module from thefuzz compares the given string with those in the list from get_grocery_...
The main task of the code is to validate a product's name and availability, record its sale by updating a CSV file, and display a confirmation table with the latest sale data. It checks product validity, ensures availability, processes the sale via the store function, and prints a table showing the last recorded sale e...
def sell_product(name:str, price:float, amount:int=1): """Function for checking if a product name is valid and the product is available for sale. Calls the store function when the item is available. After updating the csv file a table containing data from the last row from that file will be printed. """ ...
def Recept_Skill_Anpassung(skill_data, data, gesucht): # Adjusts recipe quantities based on skill data crafting_recept = [] surplus = [] # Modify input recipe quantities for i, was in enumerate(data[gesucht[0]][9].items()): crafting_recept.append(list(was)) crafting_recept[i][1] *= ...
The function recursively breaks down crafting items into their component ores by decomposing non-ore items until only required ore quantities remain, then consolidates and returns the summarized list of ores. It processes each item in the crafting list, recursively decomposing non-ore items using `Recept_Skill_Anpassun...
def Cordinator(data, skill_data, crafting_list): # Breaks down items into their components until only the required ore quantity remains Ore_list_complete = [] for i, was in enumerate(crafting_list): if data[was[0]][1] != "Ore" and data[was[0]][9] != {}: Ore_list = Cordinator(data, skill...
def is_exists(self, name, attrs: dict) -> tuple[bool, str]: key = str(attrs) if key in self.dicts: return True, self.dicts[key] name = self.format_name(name) self.dicts[key] = name return False, name def is_invalid_name(self, name: str) -> bool: if keyword.isk...
This function converts Python objects into their corresponding type hint strings for type annotations, handling nested structures like dictionaries and lists. It recursively identifies types, generates `TypedDict` classes for dictionaries, and constructs `List`/`Union`/`Optional` type strings for lists, while appending...
def _typerify(self, key: str, v: Any) -> str: if v is None: return "None" elif isinstance(v, str): return "str" elif isinstance(v, bool): return "bool" elif isinstance(v, int): return "int" elif isinstance(v, float): ret...
def find_adj(m): adj = [] if len(m) == 1: if m[0][0] == 0: return 0 return 1 else: for i in range(len(m)): row_adj = [] for j in range(len(m[i])): minor = [] for k in range...
The code computes the inverse of a matrix `q` using the adjugate matrix method. It constructs a modified matrix `pre_f` where diagonal elements are `1 - q[i][j]` and off-diagonal elements are `-q[i][j]`, then calculates the adjugate matrix, determinant, and divides them to obtain the inverse matrix `f_mat`
def find_f(q): pre_f = [] for i in range(len(q)): row_pre_f = [] for j in range(len(q[0])): if i == j: row_pre_f.append(Fraction(1, 1) - q[i][j]) else: row_pre_f.append(Fraction(0, 1) - q[i][j]) p...
def getCats(self, *ids): return self.__get(cweutil.toList(ids, True), "cat") def getKey(self, keyId): try: return self.db[keyId]["key"] except: return None def normalizeDb(self): for _id in self.db.keys(): for x in ["hasMem", "memOf"]: ...
This method updates a database by iterating through categories, linking each category's ID to its status and relationships. It processes "Has_Member" entries, normalizing CWE and View_ID relationships bidirectionally in the database. Errors are silently ignored, and the database is normalized afterward.
def __createDbCat(self): for cat in self.getCats(): try: catId = cat["ID"] self.db[catId]["status"] = cat["Status"] nodes = cat["Relationships"]["Has_Member"] if isinstance(nodes, dict): nodes = [nodes] ...
def getViews(self, *ids): return self.__get(cweutil.toList(ids, True), "view") def getKey(self, keyId): try: return self.db[keyId]["key"] except: return None def normalizeDb(self): for _id in self.db.keys(): for x in ["hasMem", "memOf"]: ...
This function constructs bidirectional relationships in a database between view IDs and their member CWE_IDs. It iterates through views, maps each member's CWE_ID to its view ID in `self.db`, and updates both `hasMem` (view → CWE_IDs) and `memOf` (CWE_ID → view IDs) entries. Exceptions are silently ignored, and the dat...
def __createDbView(self): for view in self.getViews(): try: viewId = view["ID"] nodes = view["Members"]["Has_Member"] if isinstance(nodes, dict): nodes = [nodes] for node in nodes: key = self.getK...
def loadJson(self): return cweutil.read(self.jsonPath) def __createDbKey(self, data, key): def cleanDbKeys(data): _data = json.dumps(data) for t in re.findall(r'"@\w+":', _data): _data = re.sub(t, t.replace("@", ""), _data) return json.loads(_data) ...
The main task of the code is to create a structured database from a JSON file by initializing an empty dictionary, removing an existing database file, loading JSON data, parsing specific sections (Views, Categories, Weaknesses), populating the dictionary with categorized entries, and writing the structured database to ...
def createDb(self): self.db = {} cweutil.rm(self.dbPath) results = self.loadJson() self.__createDbKey(results["Weakness_Catalog"]["Views"]["View"], "view") self.__createDbKey(results["Weakness_Catalog"]["Categories"]["Category"], "cat") self.__createDbKey(results["Weaknes...
def deleteDb(self): for key in ["view", "cat", "cwe"]: [cweutil.rm(path) for path in glob.glob(f"{self.dataDir}{os.sep}{key}{os.sep}*.json")] for key in ["json", "xml"]: [cweutil.rm(path) for path in glob.glob(f"{self.dataDir}{os.sep}*.{key}")] def download(self): tmpZipP...
The code's main task is to update the database by first deleting existing data, then downloading new data, and finally creating a new database structure. This sequence ensures the database is refreshed with the latest information, removing outdated entries and re-establishing the data structure.
def update(self): self.deleteDb() self.download() self.createDb()
def generate_data(): """Data extraction and transformation.""" output_file = config.get("PATH_TO", "test_path_to") download_data( aws_key=config.get("AWS_KEY", "test_key"), aws_secret=config.get("AWS_SECRET", "test_secret"), bucket=config.get("BUCKET", "test_bucket"), prefi...
This code defines a machine learning training pipeline using MLflow for tracking. It sets up an experiment, logs model parameters, trains a model on generated data, evaluates performance (ROC AUC), saves the model, registers it, and generates quality/performance reports. Key steps include MLflow integration, model trai...
def main_flow_training(): """The main training pipeline""" mlflow.set_tracking_uri(f"http://{TRACKING_SERVER_HOST}:5000") mlflow.set_experiment(EXPERIMENT_NAME) run_description = "Laundering model experiment description." tags = { "owner_team": "credits", "deployer": "mjaramillo", ...
def generate_12hr_dataset(self): window = self.day_seconds / 2 points = self.extract_data_window(window) hticks = self.generate_hticks(points, window) vticks = self.generate_vticks(points) self.write_window_data(self.plot_12 + '.json', points, hticks, vticks) def generate_24hr_da...
The main task of the code is to generate multiple time-based datasets by sequentially calling methods that create 12-hour, 24-hour, 2-day, 5-day, and 10-day datasets. This function orchestrates the creation of these datasets, likely for data analysis, modeling, or storage purposes, ensuring all specified time intervals...
def write_all_datasets(self): self.generate_12hr_dataset() self.generate_24hr_dataset() self.generate_2d_dataset() self.generate_5d_dataset() self.generate_10d_dataset()
def report_failed_and_exit(message=None): if not message: message = 'Data collection terminated by error.' logging.error('FAILED: %s' % message) sys.exit(1) def get_property(keyname, section): cp = ConfigParser.ConfigParser() cp.read(CONFIG_FILENAME) try: return cp.get(section, k...
The main task of the code is to verify the existence of a configuration file and a report directory. If the configuration file is missing, it exits with an error. If the report directory doesn't exist, it attempts to create it; if creation fails, it logs an error and exits. The function ensures prerequisites are met be...
def check_files(): if not os.path.exists(CONFIG_FILENAME): report_failed_and_exit('config file %s not found.' % CONFIG_FILENAME) data_dir = get_property('REPORT_DIR', 'CONFIG') if not report_dir_exists(): try: os.makedirs(data_dir) except OSError: logging.err...
def log_dir_exists(): return os.path.exists(get_property('LOG_DIR', 'LOGS')) def get_property(keyname, section): cp = ConfigParser.ConfigParser() cp.read(CONFIG_FILENAME) try: return cp.get(section, keyname) except ConfigParser.NoOptionError: logging.error("Option %s not found in con...
The main task of the code is to ensure the log directory exists by creating it if necessary. It checks for the directory's existence, attempts to create it using `os.makedirs`, and handles potential errors like permission issues or invalid paths by logging an error and exiting the program.
def create_log_dir(): if not log_dir_exists(): try: os.makedirs(get_property('LOG_DIR', 'LOGS')) except OSError: logging.error('Unable to create log directory. Check location of LOG_DIR') report_failed_and_exit('Unable to create log directory')
def datasets_dir_exists(): return os.path.exists(get_property('PLOT_DATA_DIR', 'PLOTS')) def get_property(keyname, section): cp = ConfigParser.ConfigParser() cp.read(CONFIG_FILENAME) try: return cp.get(section, keyname) except ConfigParser.NoOptionError: logging.error("Option %s not ...
The main task of the code is to create a directory for storing datasets if it does not already exist. It checks for the directory's existence, attempts to create it using the path specified by the 'PLOT_DATA_DIR' property, and logs an error with an exit if the creation fails due to an OSError.
def create_datasets_dir(): if not datasets_dir_exists(): try: os.makedirs(get_property('PLOT_DATA_DIR', 'PLOTS')) except OSError: logging.error('Unable to create datasets directory. Check location of PLOT_DATA_DIR') report_failed_and_exit('Unable to create dataset...
def get_model(ctable: transform.CharacterTable, *, teacher_force: bool = False) -> models.Seq2seq: return models.Seq2seq(teacher_force=teacher_force, hidden_size=config.TrainConfig.hidden_size, eos_id=ctable.eos_id, vocab_size=ctable.vocab_size) def get_train_stat...
The code trains a model for a fixed number of steps using a character table, logs metrics during training, decodes periodically to evaluate performance, and saves the final trained model to the specified directory. It initializes the model, training state, and processes batches iteratively, updating parameters and reco...
def train_and_evaluate(serving_model_dir: str, logs_dir: str) -> train_state.TrainState: """Trains for a fixed number of steps and decode during training.""" # logs_dir = os.path.join(workdir, "logs") # serving_dir = os.path.join(workdir, "models") # TODO(marcvanzee): Integrate ctable with train_state....
def initialise_val_grid(): val_grid = np.zeros((50, 25)) for x in range(50): for y in range(25): val_grid[x][y] = np.random.random() + 0.0000001 return val_grid def is_wall(x, y): if x == 0 or x == 49: return True if y == 0 or y == 24: return True if x == 25 o...
The code implements value iteration for a grid world MDP. It iteratively updates state values and optimal actions using a discount factor, stopping early if changes fall below a threshold. Walls are handled by setting actions to -1 and values to 0. The function returns the optimal value grid and action grid after up to...
def value_iteration(discount_factor, threshold, iterations): val_grid = initialise_val_grid() action_grid = np.zeros((50, 25)) for itr in range(iterations): delta = 0 for x in range(50): for y in range(25): if is_wall(x, y): action_grid[x][y] =...
def initialise_val_grid(): val_grid = np.zeros((50, 25)) for x in range(50): for y in range(25): val_grid[x][y] = np.random.random() + 0.0000001 return val_grid def is_wall(x, y): if x == 0 or x == 49: return True if y == 0 or y == 24: return True if x == 25 o...
The code implements **value iteration** for a grid-world environment to find optimal policies under a max-norm convergence criterion. It iteratively updates state values (`val_grid`) and corresponding actions (`action_grid`), tracking changes (`delta`). Convergence is checked against a threshold, with policy changes lo...
def value_iteration_for_maxnorm_nine(discount_factor, threshold): val_grid = initialise_val_grid() action_grid = np.zeros((50, 25)) action_grid_prev = np.zeros((50, 25)) i = 1 k = 0 r = np.random.randint(1, 51, 10) + 50*np.arange(10) delta_list = [] while True: delta = 0 ...
def initialise_val_grid(): val_grid = np.zeros((50, 25)) for x in range(50): for y in range(25): val_grid[x][y] = np.random.random() + 0.0000001 return val_grid def is_wall(x, y): if x == 0 or x == 49: return True if y == 0 or y == 24: return True if x == 25 o...
This code performs value iteration for a grid-world MDP, updating value and action grids until convergence or max iterations. It tracks value changes (delta), prints policy updates at specific intervals, and returns final value grid, action grid, and delta history.
def value_iteration_for_maxnorm_one(discount_factor, threshold, iterations): val_grid = initialise_val_grid() action_grid = np.zeros((50, 25)) action_grid_prev = np.zeros((50, 25)) i = 1 m = 0 k = np.random.randint(1, 4) delta_list = [] while True: delta = 0 action_grid_p...
def value_iteration(discount_factor, threshold, iterations): val_grid = initialise_val_grid() action_grid = np.zeros((50, 25)) for itr in range(iterations): delta = 0 for x in range(50): for y in range(25): if is_wall(x, y): action_grid[x][y] =...
The code performs value iteration for a reinforcement learning problem, visualizes the resulting value grid and action grid via heatmaps, highlights an action at coordinate (20,15), and prints the transposed action grid. The random seed ensures reproducibility.
def part_a_simple(): np.random.seed(0) val_grid, action_grid = value_iteration(0.1, 0.1, 100) show_heatmap(val_grid, False) show_heatmap(action_grid, False) action_indicator_diag(action_grid, (20, 15)) print(action_grid.T)
def unique(rows, col): return set([row[col] for row in rows]) def partition(check, data): true_set = [] false_set = [] for row in data: if check.check(row): true_set.append(row) else: false_set.append(row) return true_set, false_set def gini_split(left, right)...
The function identifies the optimal split for a decision tree by calculating Gini impurity for each unique value in columns 0-12. It iterates through all possible splits, partitions data into true/false subsets, skips empty partitions, and updates the best split (lowest Gini) and corresponding condition. Returns the mi...
def find_best_gini(data): best_split = 1 best_check = None for col in range(13): unique_values = unique(data, col) for values in unique_values: c = check(col, values) t, f = partition(c, data) if len(t) == 0 or len(f) == 0: continue ...
def find_best_gini(data): best_split = 1 best_check = None for col in range(13): unique_values = unique(data, col) for values in unique_values: c = check(col, values) t, f = partition(c, data) if len(t) == 0 or len(f) == 0: continue ...
The code constructs a decision tree using the Gini index. It recursively splits data by finding the best feature to minimize Gini impurity, partitions the dataset, and builds left/right branches. If further splits yield no improvement (Gini = 1), it creates a leaf node. The tree combines internal nodes with features an...
def build_tree(data): gini_split, c = find_best_gini(data) if gini_split == 1: return leaf_node(data) t_set, f_set = partition(c, data) left_branch = build_tree(t_set) right_branch = build_tree(f_set) return internal_node(c, left_branch, right_branch)
def get_alg_name(alg): if type(alg) is dict: if "name" in alg: if alg["name"] is not None: return alg["name"] else: return f"{alg['atype']}" if isinstance(alg, str): return alg def get_cspace_name(colour_space): ...
This function processes a specific algorithm-color-space-dataset combination by calculating performance scores across folds if not already computed, then logging results and updating the score record. It checks existing scores, computes new ones using calculate_scores_folds, rounds values, stores them, and updates the ...
def process_algorithm_colour_space_dataset(self, index_algorithm, index_colour_space, index_dataset): algorithm = self.algorithms[index_algorithm] colour_space = self.colour_spaces[index_colour_space] dataset = self.datasets[index_dataset] print("Start", f"{dataset} - {self.get_alg_name...
def check_allergy(allergy): result = df[~df["ingredients"].str.contains(allergy)] return result def fill_meal(meal, protein, carbon, fat): df = auto_gen_meal(meal, dishtypes, True) loss = 15 iter = 0 a, b, c = 0, 0, 0 while not ( (fat - 20 < c < fat + 15) and (protein - loss ...
The code implements a hill-climbing algorithm to optimize meal planning. It aims to find the best meal configuration (optimal) that meets specified nutritional targets (protein, carbon, fat) while adhering to allergy constraints. The algorithm iterates 20 times, generating random meal options and selecting the one with...
def hill_climbing(N, protein, carbon, fat, allergy): check_allergy(allergy) optimal = fill_meal(N, protein, carbon, fat) print(optimal) iter = 0 for i in range(0, 20): df1 = fill_meal(N, protein, carbon, fat) if meal_eval(df1, protein, carbon, fat) <= meal_eval( optimal, ...
def dfs_split(adj): # Assume adj is of shape [nb_nodes, nb_nodes] nb_nodes = adj.shape[0] ret = np.full(nb_nodes, -1, dtype=np.int32) graph_id = 0 for i in range(nb_nodes): if ret[i] == -1: run_dfs(adj, ret, i, graph_id, nb_nodes) graph_id += 1 return ret def f...
The main task of the code is to load and preprocess a protein-protein interaction (PPI) graph dataset. It constructs the adjacency matrix, standardizes node features, splits the graph into subgraphs, assigns train/val/test splits, and prepares tensors for machine learning. The output includes processed adjacency matric...
def load_ppi(data_path): print ('Loading G...') with open(data_path + 'ppi-G.json') as jsonfile: g_data = json.load(jsonfile) # print (len(g_data)) G = json_graph.node_link_graph(g_data) #Extracting adjacency matrix adj=nx.adjacency_matrix(G) prev_key='' for key, value in g_da...
def load_data_nc(dataset, use_feats, data_path, split_seed): if dataset in ['cora', 'pubmed', 'citeseer']: adj, features, labels, idx_train, idx_val, idx_test = load_citation_data( dataset, use_feats, data_path, split_seed ) else: if dataset == 'disease_nc': adj, ...
The code loads and preprocesses graph data by normalizing the adjacency matrix, converting both the adjacency matrix and features into sparse tensors, and returning the processed data for use in graph-based machine learning tasks.
def load_data(args, datapath): data = load_data_nc(args.dataset, args.use_feats, datapath, args.split_seed) adj_n = aug_normalized_adjacency(data['adj_train']) data['adj_train'] = sparse_mx_to_torch_sparse_tensor(adj_n) data['features'] = sparse_mx_to_torch_sparse_tensor(data['features']) return dat...
def mag_component(self,gain,data1,data2): return self.get_Magnitude(gain,data1)+self.get_Magnitude((1-gain),data2) def phase_component(self,gain,data1,data2): return self.get_phase(gain,data2)+self.get_phase((1-gain),data1) def combine(self,data1,data2,operation): if operation==0: da...
The function `get_mag_phase` calculates the magnitude and phase components of input data using `mag_component` and `phase_component` methods, then combines them using a `combine` method with an additional parameter `0` to produce a combined result.
def get_mag_phase(self,gain1,gain2,data1,data2): data_magnitude=self.mag_component(gain1,data1,data2) data_phase=self.phase_component(gain2,data1,data2) return self.combine(data_magnitude,data_phase,0)
def get_real(self,gain,data): data=np.real(data)*gain return data def get_imag(self,gain,data): data=np.imag(data)*gain*1j return data def combine(self,data1,data2,operation): if operation==0: data_combined = np.multiply(data1, np.exp(1j*data2)) if operation==...
The function computes real and imaginary components by combining two data sets with weighted gains. It calculates `data_real` as the sum of `gain1`-weighted `data1` and `(1-gain1)`-weighted `data2`, and `data_imag` as the sum of `gain2`-weighted `data2` and `(1-gain2)`-weighted `data1`. These are then merged into a sin...
def get_Real_imag(self,gain1,gain2,data1,data2): data_real=self.get_real(gain1,data1)+self.get_real((1-gain1),data2) data_imag=self.get_imag(gain2,data2)+self.get_imag((1-gain2),data1) return self.combine(data_real,data_imag,1)
def get_mag_phase(self,gain1,gain2,data1,data2): data_magnitude=self.mag_component(gain1,data1,data2) data_phase=self.phase_component(gain2,data1,data2) return self.combine(data_magnitude,data_phase,0) def get_Real_imag(self,gain1,gain2,data1,data2): data_real=self.get_real(gain1,data1)+...
This function combines audio data components (magnitude, phase, real, imaginary) based on user selections. It uses conditional checks to route inputs to appropriate processing methods like get_mag_phase, get_Real_imag, and combine. The task is to mix selected data types, applying gain adjustments and combining results ...
def mix_panel(self,gain1,gain2,chooesed1,choosed2,data1,data2): if chooesed1=="Mag" and choosed2=="Phase": return self.get_mag_phase(gain1,gain2,data1,data2) if chooesed1=="Phase" and choosed2=="Mag": return self.get_mag_phase(gain2,gain1,data2,data1) if chooesed1=="Real"...
def get_tag_id(self, tag, self_call = False): tag_response = requests.get(f'{self._BASE_API_PATH}/{self._site}/tags?search={tag}', headers=self.auth_header) if tag_response.status_code == 401 and not self_call: self._refresh_token() se...
This function retrieves an existing tag ID or creates a new tag if it doesn't exist. It first checks if the tag exists using get_tag_id(). If not, it sends a POST request to create the tag. If authentication fails (401), it refreshes the token and retries. On success, it returns the tag ID from the response JSON; on er...
def retrieve_or_create_tag_id(self, tag, self_call = False): tag_id = self.get_tag_id(tag) if tag_id is not None: return tag_id # New tag, so create it. tag_response = requests.post(f'{self._BASE_API_PATH}/{self._site}/tags', headers=self....
def run_worflow(my_image, my_model): # mean-std normalize the input image (batch-size: 1) img = transform(my_image).unsqueeze(0) # propagate through the model outputs = my_model(img) return outputs def filter_bboxes_from_outputs(outputs,im, threshold=0.8): # keep only pred...
The code's main task is to predict and visualize object detection results on an image. It loads an image, processes it with a model workflow, filters bounding box predictions, and plots the detected objects with their probabilities on the original image.
def predict(): img_name = './milk535.png' im = Image.open(img_name) outputs = run_worflow(im, model) prob, boxes = filter_bboxes_from_outputs(outputs, im=im) return plot_finetuned_results(im, prob, boxes)
def run_worflow(my_image, my_model): # mean-std normalize the input image (batch-size: 1) img = transform(my_image).unsqueeze(0) # propagate through the model outputs = my_model(img) return outputs def filter_bboxes_from_outputs(outputs,im, threshold=0.8): # keep only pred...
The code handles image uploads, processes them using a model to detect objects, filters bounding boxes from outputs, and returns the annotated image with results.
def uploader(): if request.method == 'POST': file = request.files['file'] # Extracting uploaded data file name img_filename = secure_filename(file.filename) # Upload file to database (defined uploaded folder in static path) file.save(os.path.join(app.config['UPLOAD_FOLDER'], i...
def run_worflow(my_image, my_model): # mean-std normalize the input image (batch-size: 1) img = transform(my_image).unsqueeze(0) # propagate through the model outputs = my_model(img) return outputs def filter_bboxes_from_outputs(outputs,im, threshold=0.8): # keep only pred...
This code defines a Flask route handling image uploads. It processes uploaded images using a model to detect objects, filters bounding boxes from predictions, and returns annotated results. If no file is uploaded, it displays a form for users to submit images.
def test(): if request.method == 'POST': # check if the post request has the file part if 'file' not in request.files: flash('No file part') return redirect(request.url) file = request.files['file'] im = Image.open(file) outputs = ...
def get_evidence_by_page(evidence): evidence_by_page = {} for ele in evidence: page = ele.split("_")[0] if page in evidence_by_page: evidence_by_page[page].append(ele) else: evidence_by_page[page] = [ele] return [list(values) for key, values in evidence_by_pag...
The function prepares an input sequence by combining a claim with evidence from Wikipedia pages, either using gold-standard or predicted evidence. It processes sentences and tables, appending context and evidence text, then joins elements with ' </s> ' for model input formatting.
def prepare_input_schlichtkrull(annotation, gold): sequence = [annotation.claim] if gold: evidence_by_page = get_evidence_by_page(annotation.flat_evidence) else: evidence_by_page = get_evidence_by_page(annotation.predicted_evidence) for ele in evidence_by_page: for evid in ele: ...
def find_job_titles(self, resume_segment): labels = ["company", "institution", "job title", "details"] idx_line = [] for idx, line in enumerate(resume_segment): splitter = re.compile(r'[\s{}]+'.format(re.escape(punctuation))) answer_splitted = splitter.split(line) ...
This function parses job history information from a resume segment by identifying job titles, extracting associated company names, and determining start/end dates for each job. It constructs a list of job entries with titles, companies, and dates, storing them in the parsed_cv dictionary under "Job History". The parsin...
def new_parse_job_history(self, resume_segment): idx_job_title = self.find_job_titles(resume_segment) current_and_below = False if not len(idx_job_title): self.parsed_cv["Job History"] = [] return if idx_job_title[0][0] == 0: current_and_below = True job...
def get_job_titles(self, resume_segment): classes = ["organization", "institution", "company", "job title", "work details"] idx_line = [] for idx, line in enumerate(resume_segment): has_verb = False line_modifed = ''.join(i for i in line if not i.isdigit()) se...
This code parses job history from a resume segment by extracting job titles, companies, and dates. It identifies job positions, determines associated companies based on text lines, and calculates start/end dates using index spans. Results are structured into a list of dictionaries under "Job History" in the parsed CV, ...
def parse_job_history(self, resume_segment): idx_job_title = self.get_job_titles(resume_segment) current_and_below = False if not len(idx_job_title): self.parsed_cv["Job History"] = [] return if idx_job_title[0][0] == 0: current_and_below = True job_hist...
def new_parse_contact_info(self, contact_info): contact_info_dict = {} name = self.new_find_person_name(contact_info) email = self.find_contact_email(contact_info) phone1, phone2 = self.find_phone_numbers(contact_info) address = self.find_address(contact_info) contact_in...
The code processes resume segments by calling specific parsing methods for each section (contact info, job history, education, skills) and compiles the parsed data into `self.parsed_cv`, returning it after processing all segments.
def parse(self, resume_segments): for segment_name in resume_segments: resume_segment = resume_segments[segment_name] if segment_name == "contact_info": self.new_parse_contact_info(resume_segment) elif segment_name == "work_and_employment": sel...
def event_loop(self): global dest_pos, start_pos for event in pygame.event.get(): if (self.ready): self.keys = pygame.key.get_pressed() if event.type == pygame.QUIT or self.keys[pygame.K_ESCAPE]: self.done = True if self.key...
The main task of the code is to run a game loop that processes events, updates game state with time delta (dt), renders frames, maintains target FPS, and displays the current frame rate. It continuously runs until `self.done` is set to True, ensuring smooth game execution and performance monitoring.
def main_loop(self): while not self.done: dt = self.clock.get_time() / 1000 self.event_loop() self.update(dt) pygame.display.update() self.clock.tick(self.fps) self.display_fps()
def auto_drive_loop(self): global dest_pos, start_pos, path, path_current_index, expected_pos_before_turn, expected_pos_after_turn, repos_before, repos_after, keep_turning, index_before, index_after, awareness, light_aware_pos, distance_to_pave if (self.ready): if (path[path_current_index] i...
The code implements an autonomous driving simulation loop. It continuously updates the game state by calculating delta time (dt), executing the auto_drive_loop for logic updates, rendering visuals with pygame, maintaining frame rate via clock.tick(), and displaying real-time FPS. The loop runs indefinitely, ensuring sm...
def auto_drive(self): global seconds while True: seconds = int(time.time()) dt = self.clock.get_time() / 1000 self.auto_drive_loop() self.update(dt) pygame.display.update() self.clock.tick(self.fps) self.display_fps()
def initRequest(self): """ init request and get news from news card """ result = [] if isinstance(self.base_url, list): for base_url in self.base_url: soup = self.getSoup(base_url) if not soup: return None ...
The main task of the code is to fetch and process articles from a source by initializing requests, parsing HTML content to extract titles, content, and dates, validating data integrity, cleaning text, converting dates, and compiling results into a structured list. If any required data is missing, it logs the issue. The...
def main(self): articles = self.initRequest() print(f'added url from ({self.source}): {len(articles)}') result = [] if articles: for article in articles: soup = self.getSoup(article) if not soup: return False ...
def set_height(self, node): if not node: return 0 return 1 + max(self.get_height(node.left), self.get_height(node.right)) def get_balance(self, node): if not node: return 0 return self.get_height(node.left) - self.get_height(node.right) def rotate_right(self, node): new_node = node.left node.left = ne...
This function inserts a value into an AVL tree, recursively placing it in the correct position, then rebalancing the tree via rotations (right or left) based on the node's balance factor. It updates node heights, checks balance, and applies rotations to maintain AVL properties, ensuring logarithmic height for efficient...
def insert(self, root, value): if not root: return Node(value) elif value < root.value: root.left = self.insert(root.left, value) else: root.right = self.insert(root.right, value) root.height = self.set_height(root) balance = self.get_balance(root) if balance > 1 and value < root.left.value: ret...
def set_height(self, node): if not node: return 0 return 1 + max(self.get_height(node.left), self.get_height(node.right)) def get_balance(self, node): if not node: return 0 return self.get_height(node.left) - self.get_height(node.right) def right_rotate(self, no...
Your returnThis code inserts a value into an AVL tree, maintaining balance through rotations. It recursively places the value in the correct position, updates node heights, and checks balance factors. If imbalance occurs (e.g., left-left, left-right, right-right, right-left cases), it performs rotations (left or right)...
def insert(self, root, value): if not root: return TreeNode(value) elif value < root.value: root.left = self.insert(root.left, value) else: root.right = self.insert(root.right, value) root.height = self.set_height(root) balance = self.get_bala...
def _check_events(self): """reaction for even from mouse or keyboard""" for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.KEYDOWN: self._check_keydown_events(event) elif event.type == py...
The main task of the code is to execute the game loop by continuously checking for user input, updating the ship's position, managing bullets (including removing those out-of-screen), and rendering the game screen. The loop ensures real-time interaction and visual updates, with a note on safely deleting bullets using a...
def run_game(self): """Start main game loop""" while True: """waiting for press key or mouse click""" self._check_events() self.ship.update() self._update_bullets() self._update_screen() """ delete bullets beyond screen, use self....
def forward_encoder(self, x, mask_ratio, annotations=None): # embed patches x = self.patch_embed(x) # add pos embed w/o cls token x = x + self.pos_embed[:, 1:, :] # Apply either random or semantic masking based on mask_type if self.mask_type == 'semantic' and an...
This code defines a forward pass in a neural network model. It processes input images through an encoder to generate latent representations and a mask, then uses a decoder to reconstruct masked regions. The loss is computed between original images and predictions, with the mask determining which regions are ignored. Th...
def forward(self, imgs, mask_ratio=0.75): latent, mask, ids_restore = self.forward_encoder(imgs, mask_ratio) pred = self.forward_decoder(latent, ids_restore) # [N, L, p*p*3] loss = self.forward_loss(imgs, pred, mask) return loss, pred, mask
def find_first_way(self, ways, first_stop): for w in ways: nodes = self.way_nodes(w) for i, n in enumerate(nodes): if self.ref(n) == first_stop: return w, i def way_nodes(self, way): ref = self.ref(way) return self.way_index.get(ref).se...
This function sorts and concatenates way nodes into a continuous path starting from a specified stop, connecting ways end-to-end. It reverses the initial way if required, iteratively adds connected ways by matching end nodes, and retries with reversed direction if the initial attempt fails to form a valid sequence.
def sort_way_nodes(self, ways: List, first_stop, reverse_first: bool = False): sorted_way_nodes = [] ways_copy = ways.copy() first_way, index = self.find_first_way(ways, first_stop) first_way_nodes = self.way_nodes(first_way) if reverse_first: first_way_nodes.reverse(...
def longest_route(self, routes): stop_counts = [len(self.rel_stops(r)) for r in routes] idx = stop_counts.index(max(stop_counts)) return routes[idx] def rel_ways(r): return r.select('member[type="way"][role=""]') def rel_stops(r): return r.select('member[type="node"][role="stop"]...
The main task of the code is to parse OSM route data into structured TransitRoute objects. It processes each route by extracting the longest path, validating ways/stops, adjusting coordinates, and creating a TransitRoute with start/end stops and node coordinates, ensuring only valid routes with ≥2 stops are included.
def parse_routes(self) -> List[TransitRoute]: route_names = self.rel_index.keys() routes = [] routes_processed = [] for name in route_names: if name in routes_processed: continue name_routes = self.rel_index[name] r = self.longest_rou...
def display_board(): #to display board print(board[0] + " | " + board[1] + " | " + board[2]) print(board[3] + " | " + board[4] + " | " + board[5]) print(board[6] + " | " + board[7] + " | " + board[8]) def handle_turn(player): #handles a turn print(player + "'s turn.") position = input("Choos...
This code defines a function to manage a turn-based game loop, handling player turns, checking game-over conditions, and announcing the winner or a tie. It displays the game board, alternates between players, and ends when a player wins or the game ties, then outputs the result.
def play_game(): #main function display_board() while game_still_going: handle_turn(current_player) check_if_game_over() flip_player() if winner == "X" or winner == "O": print(winner + " won!") elif winner == None: print("Its a tie!")
def _delete_change_sets(cloudformation_client: boto3.client, stack_name: str) -> None: kwargs = {"StackName": stack_name} response = cloudformation_client.list_change_sets(**kwargs) change_sets = response["Summaries"] for change_set in change_sets: change_set_name = change_set["ChangeSetName"] ...
This function updates an AWS CloudFormation stack by first deleting existing change sets, then creating a new change set using a specified template and parameters, and finally executing the new change set to apply updates to the stack.
def _update_stack( cloudformation_client: boto3.client, stack_name: str, template_file_path: str, formatted_parameters: List[Dict[str, Union[str, bool]]], ) -> None: print(f"Creating Change Sets [{stack_name}]") _delete_change_sets(cloudformation_client, stack_name) template = _fetch_templ...
def deploy_cloudformation_template( stack_name: str, template_file_path: str, pair_name: str, now_ms: int, ) -> None: cloudformation_client = boto3.client("cloudformation", region_name=AWS_REGION) print(f"Deploying template [{stack_name}]") should_create = False try: cloudformat...
This script deploys AWS resources for a Pitkiot app backend using CloudFormation, creates an S3 bucket, uploads code packages, and retrieves Lambda function URLs. It requires a pair name argument, deploys infrastructure templates, and outputs endpoint URLs for game management and word handling functions. The process en...
def main() -> None: # tell this script how to handle arguments description = "Script for deploying Pitkiot app backend resources" parser = argparse.ArgumentParser(description=description) parser.add_argument( "--pair-name", required=True, help="The name of the pair submitting the...
def is_collision_free(grid, edge): rasterized_line = bresenham_line(edge) for point in rasterized_line: if (grid[point[0]][point[1]].color == GREEN or grid[point[0]][point[1]].color == RED or grid[point[0]][point[1]].color == BLACK): return False return True def calc_dist(u, v): dist...
The code implements a Probabilistic Roadmap (PRM) algorithm to find a collision-free path from a start to a goal position in a grid-based environment. It generates random vertices, constructs a roadmap with nearest-neighbor connections, adds start/goal nodes, and uses Dijkstra's algorithm to search for the shortest pat...
def PRM(world, robot, start, goal): n = 100 while(len(world.VERTICES) < n): i = random.randint(0, world.ROWS - 1) j = random.randint(0, world.ROWS - 1) while (world.CONFIGURATION_SPACE[i][j] == False): i = random.randint(0, world.ROWS - 1) j = random.randint(0, wo...
def cleanup_jobs(api): currently_backing_up = {} batchv1 = k8s_client.BatchV1Api(api) with tracer.start_as_current_span('list_namespaced_job'): jobs = batchv1.list_namespaced_job( NAMESPACE, label_selector=METADATA_PREFIX + 'volume-type=rbd', ).items for job in j...
The main task of the code is to manage Kubernetes volume backups using Ceph RBD. It cleans up existing backup jobs, identifies volumes to back up, skips duplicates, annotates PVs with timestamps, and executes filesystem or block backups based on volume mode, while logging progress and utilizing OpenTelemetry tracing fo...
def backup_main(now, ceph, cleanup_only, max_backup_duration): api = k8s_client.ApiClient() corev1 = k8s_client.CoreV1Api(api) # Clean old jobs currently_backing_up = cleanup_jobs(api) if cleanup_only: return # Back up volumes to_backup = build_list_to_backup(api, now) for vol...
def randomSpawnAgent(self): random_agent = gym.spaces.Box( -min(self.cfg.env_dim[0]/2, self.cfg.env_dim[1]/2), min(self.cfg.env_dim[0]/2, self.cfg.env_dim[1]/2), shape=((self.cfg.usv_agent_num + self.cfg.uav_agent_num), 2), dtype=float ) random_g...
The main task of the code is to randomly assign agent and goal positions while ensuring no collisions occur. It repeatedly generates new positions until all agents are collision-free, then updates each agent's perception data, and finally returns the observation space for the environment.
def reset(self): # radom assign agent & goal position, return observation space collision_check = True while collision_check == True: self.randomSpawnAgent() collision_check = False for agent in range(self.cfg.usv_agent_num + self.cfg.uav_agent_num): i...
def goalUpdate(self): state = False idx = 0 for goal in self.observatiopn_space["goal"]: for agent in self.observatiopn_space["pos"]: if self.distanceP2P(goal, agent) <= self.cfg.goal_margin and self.observatiopn_space["goal_status"][idx] == 0: se...
This code processes an agent's action by clamping velocity to predefined limits, updating the agent's position, checking goal achievement (reward +100 or +300), detecting collisions (reward -50), and returning the updated state, reward, and completion status.
def step(self, agent_index, action): finished = False reward = 0 if abs(action[0]) > self.observatiopn_space["vel"][agent_index]: if action[0] > 0: action[0] = self.observatiopn_space["vel"][agent_index] else: action[0] = self.observatiop...
def goalUpdate(self): state = False idx = 0 for goal in self.observatiopn_space["goal"]: for agent in self.observatiopn_space["pos"]: if self.distanceP2P(goal, agent) <= self.cfg.goal_margin and self.observatiopn_space["goal_status"][idx] == 0: se...
The code creates a Pygame-based GUI to visualize a multi-agent simulation environment. It renders the environment map, agent positions (USV/UAV), goals, and local sensor views, allowing users to switch monitored agents via the spacebar and adjust agent inputs with arrow keys. The loop updates agent states, checks colli...
def manualDisplay(self): pygame.init() screen = pygame.display.set_mode([self.cfg.env_px + self.cfg.debug_view_px, self.cfg.env_px]) monitor_agent = 0 while True: # event & input for event in pygame.event.get(): if event.type == pygame.QUIT: ...
def group(self, smooth=True): if smooth: return self._group_smooth() return self._group_non_smooth() def get_segment_name(self, start_s, end_s, idx): basename = os.path.basename(self.audio_file.strip()) basename = f"target-{int(start_s * 1000)}ms-{int(end_s * 1000)}ms_{idx}_{...
The main task of the code is to segment an audio file into time-based segments using grouped events, save each segment as a separate audio file, and optionally generate spectrogram images for visualization. It reads the input audio, creates output directories, slices audio based on event timestamps, assigns segment nam...
def segment(self, audio_output, img_output=None, smooth_predictions=True): grouped_events = self.group(smooth_predictions) source_audio, sr = sf.read(self.audio_file.strip()) os.makedirs(audio_output, exist_ok=True) if img_output is not None: os.makedirs(img_output, exist_ok=...
def get_next_node(self, current_route): last_node = current_route[-1] next_node = [] edges = self.matrix[last_node-1] for i in range(len(edges)): if edges[i] != 0 and not check_node_in_route(current_route, i + 1): next_node.append(i+1) ...
This code implements a breadth-first search (BFS) algorithm to find a path from a source node to a destination node in a graph. It uses a queue to explore routes, appending new paths to the queue until a valid route from source to destination is found. The solution path and its total weight are returned.
def search(self, source, destination): self.queue.append([source]) solution = [] while len(self.queue) > 0: route_now = self.queue.pop(0) if route_now[0] == source and route_now[-1] == destination: solution = route_now break ...
def FF(self, layer1, layer2, weights, theta, useAF): # List of strength S = [] # Calculate strength for j in range(len(layer2)): S.append(0) for i in range(len(layer1)): S[j] += layer1[i] * weights[i][j] S[j] -= theta[j] #...
The code trains a neural network by iterating over epochs, performing feedforward propagation to compute outputs, calculating error using labels, and applying backpropagation to update weights. It tracks average accuracy and loss per epoch, adjusts the learning rate if it exceeds 0.5, and uses loading bars for progress...
def train(self, inputs, labels, epoch, learning_rate): print("\nTRAINING:") # Set the learning rate self.lr = learning_rate # Iterate for the number of epoch | start_load is to start the loading bar for i in range(start_load(epoch)): avg_acc = 0 avg_loss ...
def make_output_folder(session_id, stat, isEst, isNull, isResults, isGraphing=False): """ Creates output file to store all of the csv's specific to the stat """ dir_name = stat.name tags = "" if isNull: tags += "_null" if isEst: tags += "_estimate" else: ...
The function `read_stats` retrieves and processes statistical data from CSV files in a session-specific directory. It filters files based on parameters like `eps`, `epsilon_num_alloc`, `group_sizes_db`, and `means_db`, then reads matching files using `_read_stats`, returning a list of processed results.
def read_stats(eps, epsilon_num_alloc, group_sizes_db, means_db, session_id, stand_dev, stat,isEst=False, isNull=False, isResults=False): """ This function reads in the results from output files and results files and returns them as a list """ dir_name = session_id + "_Data/" + mak...
def make_output_folder(session_id, stat, isEst, isNull, isResults, isGraphing=False): """ Creates output file to store all of the csv's specific to the stat """ dir_name = stat.name tags = "" if isNull: tags += "_null" if isEst: tags += "_estimate" else: ...
This function reads coordinate data from CSV files in a session-specific directory, filtering files based on parameters like epsilon, group sizes, means, and standard deviation. It collects matching files, reads their coordinates using a helper function, and returns the list of coordinate data.
def read_coordinates(alpha, eps, epsilon_num_alloc, group_sizes_db, means_db, session_id, stand_dev, stat, isEst): """ This function reads in the coordinates according to the database parameters. We had to write a separate function from read_stats() because the coordinates files also contain all of the data...
def find_threshold(self, th1,effref): nbins = th1.GetNbinsX() fullArea = th1.Integral(0,nbins+1) if fullArea == 0: return 0,1 notDetected = 0.0; i = 0 while (1. - notDetected > effref): cutArea = th1.Integral(0,i) i+=1 prevNotDetect...
This function iteratively adjusts a linear correction to minimize false alarms in signal detection. It calculates thresholds, efficiencies, and applies linear adjustments (slope/offset) to hist_signal and hist_background. If the false alarm rate exceeds the limit, it reduces the reference value (pd_ref) and repeats unt...
def calculate( self, hist_signal, hist_background, pd_ref, false_alarm_limit = 0.5): d = {'x_dots' : [], 'y_dots':[], 'errors':[]} false_alarm = 1.0 while false_alarm > false_alarm_limit: # Get the threshold when we not apply any linear correction threshold, _ = self.f...
def create_app_heading_frame(self): """ Creates heading frame for the application. :return: the frame """ frame = Frame(self, height = 50, bg = "#2b2e30") frame.pack(fill = X) return frame def create_heading_label(self): """ Creates the heading lab...
This code initializes a password generator GUI application by centering the window on the screen, setting its title and size, and creating UI components such as input fields for password length, strength options, and a generate button.
def __init__(self): super().__init__() # Centering the window when opened. screen_width = self.winfo_screenwidth() screen_height = self.winfo_screenheight() app_width = 500 app_height = 280 set_x = int((screen_width / 2) - (app_width / 2)) set_y = int((scr...
def _supports_interface( self, w3: Web3, contract_address: str, interface: str ): try: erc165_contract = w3.eth.contract( address=contract_address, abi=ERC165_ABI ) return erc165_contract.functions.supportsInterface(interface).call() except...
This code processes blockchain logs to handle ERC721 and ERC1155 token transfers. It checks the log's event signature and contract interface support, then delegates to specialized methods for processing single or batch transfers, ensuring compatibility with respective token standards.
def process(self, dispatcher: Dispatcher, w3: Web3, task: ProcessLogTask): logger.info( "Fetching log", block_number=task.block_number, log_index=task.log_index, ) log = task.log log_index = task.log_index timestamp = task.timestamp t...
def spoints_facets(frequency): [v, f, e] = topology(frequency) [vp, lp] = vlabels(v, f, e, frequency) vc = vcoords(vp, lp, frequency) fidx = face_factor(v, f, frequency, lp) return [vc, fidx] def icosa_sphere(facenum, points): RAD_TO_DEG = 57.2957795130824 sphere_pnt = points.copy() * 0.0 ...
The code generates an icosphere by creating spherical points for multiple facets, converting them to Cartesian coordinates, scaling by radius R, and concatenating all points into a single array. It uses recursive subdivision (maxlevel) to refine the sphere's geometry, then combines 20 sets of transformed points into a ...
def icosphere(maxlevel, R): [spoints, sfacets] = spoints_facets(maxlevel) sfacets = sfacets - 1 pp = [] for fnum in range(0, 20): points = icosa_sphere(fnum, spoints) sphere2cart(points) points = points * R pp.append(points) return np.hstack(pp)
def plot_curve_single(self, index, raw=False): """ Plots a single curve, either smoothed or raw """ # Close any opened plots if plt.get_fignums(): plt.close() # Plot a single curve to show user before deleting ax = plt.axes(projection='3d') plt.ion() ...
This function loads a demonstration from an h5 file, processes pose data by adjusting coordinates and orientations, temporarily stores it, visualizes the demonstration, and determines whether to retain or discard it based on user input.
def load_demonstration_from_file(self): """Loads a demonstration from an h5 file based on user input Returns T/F based on whether the demonstration is one to keep""" # Open file that contains pose data filename = raw_input('Enter the filename (including file path) of the .h5 demo: ') ...
def get_y_n(prompt): """Gets a yes or no response from the user""" answer = raw_input(prompt) while len(answer) == 0 or answer[0] not in ["Y", "y", "N", "n"]: answer = raw_input("\nPlease enter a valid (Y/N) response: ") if answer[0] == "Y" or answer[0] == "y": return True else: ...
The code records a robot's Cartesian trajectory demonstration by collecting poses at 200Hz over 5 seconds, storing them in class variables, and optionally saving or discarding the data based on user input. It includes user prompts for starting/aborting, a countdown, and returning to the initial joint configuration if r...
def record_a_demonstration(self): """Records a demonstration from the simulated robot based on movegroup data Returns T/F based on whether the demonstration is one to keep""" # Set rate of collecting poses rt = rospy.Rate(200) # Give user the option to have the robot ...
def plot_curves(self, raw=False): """ Plot all of the current processed demonstrations """ # Close any opened windows if plt.get_fignums(): plt.close() # Plot curves according to self.plot_line_colors and the order they were recorded patches = [] ax = plt.axe...
This function allows users to delete a prerecorded demonstration from a list, ensuring at least two remain. It displays all demonstrations, validates user input for the demonstration number, confirms deletion, and removes the selected demonstration if confirmed. The process includes plotting curves for visualization an...
def delete_a_demonstration(self): """Allows user to delete a prerecorded demonstration""" # Dont let user delete if there are only 2 demonstrations if len(self.smooth_demonstrations) <= 2: print("You must have at least two demonstrations for the canal surface.\n") return ...
def plot_curves(self, raw=False): """ Plot all of the current processed demonstrations """ # Close any opened windows if plt.get_fignums(): plt.close() # Plot curves according to self.plot_line_colors and the order they were recorded patches = [] ax = plt.axe...
This function allows users to interactively add or delete demonstrations after initial data collection. It loops until the user chooses to proceed to canal surface calculation, offering options to delete a demonstration, add a new one (via file or recording), and processes updates to the demonstration data and origin d...
def prompt_insertion_and_deletion(self): """ Driver that prompts user for insertion and deletion after an inital set of demonstrations has been collected""" # While the user does not want to proceed to canal surface calculation (wants to add/remove demonstrations) action = " " ...
def prepend_feed_ops(inference_program, feed_target_names, feed_holder_name='feed'): if len(feed_target_names) == 0: return global_block = inference_program.global_block() feed_var = global_block.create_var( name=feed_holder_name, type=core....
This function builds and saves an inference model by pruning the main program, removing unnecessary operations, optimizing for inference, and serializing the optimized program and parameters into files in the specified directory.
def save_inference_model(dirname, feeded_var_names, target_vars, executor, main_program=None, model_filename=None, params_filename=None): """ Build a model especi...
def compute_class_specific_qhats(cal_class_scores, cal_true_labels, num_classes, alpha, default_qhat=np.inf, null_qhat='standard', regularize=False): ''' Computes class-specific quantiles (one for each class) that will result in marginal coverage of (1-alpha) Inputs: ...
The main task of the code is to perform class-wise conformal prediction by computing class-specific quantiles (qhats) from calibration data, generating prediction sets for validation data, and evaluating coverage and set size metrics. It processes scores/labels for calibration and validation, calculates uncertainty-awa...
def classwise_conformal_pipeline(totalcal_scores_all, totalcal_labels, val_scores_all, val_labels, alpha, num_classes, default_qhat=np.inf, regularize=False): ''' See compute_class_specific_qhats() for doc-string ''' classwise_q...
def compute_qhat(class_scores, true_labels, alpha, plot_scores=False): ''' Compute quantile q_hat that will result in marginal coverage of (1-alpha) Inputs: class_scores: num_instances x num_classes array of scores, or num_instances-length array of conformal scores for true class. A hi...
The function computes cluster-specific quantiles for each class to achieve marginal coverage of (1 - α). It maps classes to clusters, calculates quantiles based on calibration data, and handles rare classes using a default method. If all clusters are unassigned, it returns standard quantiles. The output is an array of ...
def compute_cluster_specific_qhats(cluster_assignments, cal_class_scores, cal_true_labels, alpha, null_qhat='standard', exact_coverage=False): ''' Computes cluster-specific quantiles (one for each class) that will result in marginal coverage of (1-alpha) Inputs: ...
def load_data_arff(file_path): """ load .arff file type and encode text columns """ raw_data = loadarff(file_path) df = pd.DataFrame(raw_data[0]) str_df = df.select_dtypes([np.object]) str_df = str_df.stack().str.decode('utf-8').unstack() df[str_df.columns] = str_df return df def run_rf(ds_name,df, ...
The code trains Random Forest models on two datasets ('diabetes', 'german'), preprocesses data, and uses these models to initialize TwistGANs. It trains the GANs on concatenated training/test data and evaluates them by generating 100 fake samples, comparing real/fake predictions.
def main(): db_names = ['diabetes','german'] path = [DIABETES_PATH,GERMAN_PATH] models = [DIABETES_RF_MODEL_PATH,GERMAN_RF_MODEL_PATH] for i in range(len(path)) : print(path[i]) df = load_data_arff(path[i]) run_rf(db_names[i],df,SAVE_MODEL) #train random forest on data and save model (opt) mode...
def _get_keyboard_input(self) -> Sequence[bool]: return pygame.key.get_pressed() def _check_collisions(self) -> None: for p in self._gamestate.projectiles: if p.direction == 1: for o in self._gamestate.obstacles: if ( p.y + p.height...
The code updates the game state by processing keyboard input, checking collisions, advancing levels upon defeating enemies, and updating game objects. It handles game over logic, pauses, and main menu transitions, while delegating actions to controllers for actors and projectiles.
def _update(self, delta_time: int) -> None: keyboard_input = self._get_keyboard_input() if self._gamestate and self._gamestate.game_over: self._main_menu = True self._gamestate.game_over = False elif not self._pause and not self._main_menu: self._check_collisi...
def help1(): print(''' -------------------------------------------- Option [1] Brute force the ssh using hydra | -------------------------------------------- Option [2] get the system info =coming soon| -------------------------------------------- Option [3] Scan the network again ...
This function presents a menu-driven interface, executing commands like running scripts (chmod +x ./brute.sh), scanning (scan1(), pscan()), restarting the program, or returning to the main menu. It handles user input to trigger specific actions, with error handling for invalid commands.
def extra(): help1() extra1 = str(input(" Options ===> ")) if '1' in extra1: cls() print(banner) os.system(' chmod +x ./brute.sh && ./brute.sh ') extra() elif '3' in extra1: cls() print(banner) scan1() extra() elif '4' == ...
def _check_fleet_edges(self): #Action after any alien reached an edge. for alien in self.aliens.sprites(): if alien.check_edges(): self._change_fleet_direction() break def _ship_hit(self): """when ship and aliens contact""" if self.stats.ship...
This method updates alien positions by checking fleet edges and calling their update method. It detects collisions between the ship and aliens using spritecollideany, triggering _ship_hit() if collided. Finally, it checks if any aliens have reached the bottom of the screen.
def _update_aliens(self): ''' We use this to call alien's update. ''' #Checking if the fleet is at the edge, then update the positions of all aliens in fleet. self._check_fleet_edges() self.aliens.update() #alien and collilsions """The spritecollideany()...
def _check_events(self): #Respond to keypresses and mouse events. for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() # exiting the game elif event.type == pygame.KEYDOWN: self._check_keydown_events(ev...
The code defines a game loop that continuously checks for user input, updates the game state by moving the player's ship, bullets, and aliens, and redraws the screen to reflect changes, maintaining real-time interaction and gameplay dynamics.
def run_game(self): # this is the game controller loop which updates after every input from the user. '''Start the main loop for the game.''' while True: self._check_events() if self.stats.game_active: self.ship.update() ...
def id3(x, y, attribute_value_pairs=None, depth=0, max_depth=5): val, cnt = np.unique(y, return_counts=True) val, cnt = np.unique(y, return_counts=True) if len(val) == 1: return val[0] if depth==max_depth or x.shape[1] == 0: return np.argmax(cnt) if attribute_value_pairs is None...
The code generates a learning curve to evaluate how training and test errors of a decision tree vary with its depth. It splits the training data into training and validation sets, trains trees with depths 1–10, computes validation and test errors for each, and plots them against tree depth. The plot visualizes overfitt...
def learning_curve(Xtrn, ytrn, Xtst, ytst, title): train_er={} test_er={} val_frac = 0.1 Xtrn, Xval, ytrn, yval = train_test_split(Xtrn, ytrn, test_size=val_frac, random_state=42) for i in range(1,11): decision_tree = id3(Xtrn, ytrn, max_depth=i) y_pred_trn = [predict_example(x, dec...
def parse_config(self, line: str): self._in(LogLineType.CONFIG, line) config = StateMgr.get('config') if line != 'config|ready': cmd, key, value = line.split('|', 2) config[key] = f'{config[key]}|{value}' if key in value else value else: self._register...
This code processes a line by stripping whitespace and routing it to specific parsing methods based on its prefix: 'config|', 'report|', or 'filter|'. It delegates the line to `parse_config`, `parse_report`, or `parse_filter` respectively, enabling categorized handling of different data types.
def read(self, line): line = line.strip() if line.startswith('config|'): self.parse_config(line) if line.startswith('report|'): self.parse_report(line) if line.startswith('filter|'): self.parse_filter(line)
def crossover(cutpoint_start, cutpoint_end, parent): xs = [] result = [] result.extend(parent) xs_left = result[:cutpoint_start] xs_right = result[cutpoint_end-len(result):] xs.extend(xs_left) xs.extend(xs_right) xs = mutate(xs, 0.1) m_i = 0 for i in range(len(result)): if (i < cut...
The code implements an evolutionary algorithm (EA) for solving the Traveling Salesman Problem (TSP). It iteratively generates offspring through crossover and mutation, then selects the best solution using (1+1)-ES. The main task is to optimize a path through given coordinates by evolving potential solutions over specif...
def tsp_ea(coords, iterations): # cutpoint_start = 1, cutpoint_end = 2 # [(a,b), (c,d), (e,f), (g,h)] # ^^^^^ ^^^^^ ^^^^^ ^^^^^ # 0 1 2 3 # ^^^^^^^^^^^^ # permutate on [(a,b), (g,h)] # crossover() can return both # [(g,h), (c,d), (e,f), (a,b)] # [(a,b), (c...
def tsp_ea(coords, iterations): # cutpoint_start = 1, cutpoint_end = 2 # [(a,b), (c,d), (e,f), (g,h)] # ^^^^^ ^^^^^ ^^^^^ ^^^^^ # 0 1 2 3 # ^^^^^^^^^^^^ # permutate on [(a,b), (g,h)] # crossover() can return both # [(g,h), (c,d), (e,f), (a,b)] # [(a,b), (c...
The code's main task is to verify the correctness of two Traveling Salesman Problem (TSP) solvers (EA and MA) by checking if they compute the optimal path distance of 160 for a predefined set of coordinates, rather than a suboptimal 200. It uses assertions to ensure both algorithms return the expected minimal total dis...
def sanity_check(): coords = [[0,0], [10,10], [40,40], [20,20], [30,30]] # sanity check should result 160 instead of 200 result_ea, _ = tsp_ea(coords,1500) result_ma, _ = tsp_ma(coords,1500) assert(total_distance(result_ea) == 160) assert(total_distance(result_ma) == 160) assert(total_distance(c...
def sanity_check(): coords = [[0,0], [10,10], [40,40], [20,20], [30,30]] # sanity check should result 160 instead of 200 result_ea, _ = tsp_ea(coords,1500) result_ma, _ = tsp_ma(coords,1500) assert(total_distance(result_ea) == 160) assert(total_distance(result_ma) == 160) assert(total_distance(c...
The main task of the code is to compare the performance of two algorithms (Evolutionary Algorithm and Memetic Algorithm) for solving the Traveling Salesman Problem (TSP) on the 'burma14.txt' dataset. It runs each algorithm 10 times with 1500 iterations, randomizing initial city orderings, and plots the total distance r...
def main(): sanity_check() # coords = load_file('file-tsp.txt') coords = load_file('burma14.txt') runs = 10 iterations = 1500 _fig, ax = plt.subplots() for run in range(runs): coords = mutate(coords,1) # randomize inital ordering of positions of city result_ea, intermediate_r...
def create_grid(self, npts, gmin=0, gmax=2*np.pi, bmin=0, bmax=np.pi): grange = np.linspace(gmin, gmax, npts) brange = np.linspace(bmin, bmax, npts) gmesh, bmesh = np.meshgrid(grange, brange) gg = gmesh.reshape((-1,)) bb = bmesh.reshape((-1,)) exp_arr = np.array(list(map...
This code iterates through p values from 1 to p_end, generating grids, finding optimal parameters (angles) for each p using a cutoff threshold, and storing the best ansatz configurations, maximum exponent values, and parameter pairs. It builds a record of optimized quantum circuit parameters (best_params) and correspon...
def run(self, p_end, npts=50, cutoff=1.0): for i in range(1, p_end + 1): print(f'Creating grid for p={i}') self.create_grid(npts) max_exp = np.max(self.exp_arr[:, :, i-1]) best_params = self.find_args(i, cutoff * max_exp)[0] # take only one pair of angles ...
def _mplus(self): ans = plus for q in range(1, self.num_qubits): ans = np.kron(ans, plus) return ans def _hmt(self): N = 2 ** self.num_qubits ans = np.zeros((N, N)) for u, v in self.edge_list: ans += np.eye(N) - self.tensor(Z, [u, v]) retur...
The code computes the expectation value of a Hamiltonian using a quantum ansatz. It splits input parameters into gamma and beta vectors, constructs the ansatz state, and calculates the expectation via matrix multiplication. The result is returned as a real number if close to its absolute value, otherwise as a complex n...
def expectation(self, params): if self.plusxn is None or self.hamiltonian is None: self.plusxn = self._mplus() self.hamiltonian = self._hmt() depth = len(params)//2 gamma_vec = params[:depth] beta_vec = params[depth:] ansatz = self.ansatz(gamma_vec, beta_v...