dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def getusrf(usr): """ Get usrfile """ sipusr = uff.vsiper(usr) if len(usr) < 4 or not sipusr: return 4, "Error: (uf) Invalid userid." usrfile = os.path.join(cons('usrsdir'), sipusr) return 0, usrfile def verusr(usr, pwd): """ Verify usr & pwd """ # Verify usrid rc, usrfile = getu...
This function changes a user's password by validating the current password, checking the new password's validity, hashing it, updating the user file with the new hash, and verifying the change. It handles errors during verification, hashing, and file operations, returning appropriate status codes and messages.
def chgpwd(usr, pwd, npwd): """ Change pwd """ rc, usrfile = getusrf(usr) if rc: return rc, usrfile rc, msg = verusr(usr, pwd) if rc: return rc, msg rc, msg = valpwd(pwd, npwd) if rc: return rc, msg try: hash = sha.hash(npwd).replace(cons('orgsha'),cons('e...
def getusrf(usr): """ Get usrfile """ sipusr = uff.vsiper(usr) if len(usr) < 4 or not sipusr: return 4, "Error: (uf) Invalid userid." usrfile = os.path.join(cons('usrsdir'), sipusr) return 0, usrfile def verusr(usr, pwd): """ Verify usr & pwd """ # Verify usrid rc, usrfile = getu...
The main task of the code is to update user details (name, address, phone, email, password) after validating credentials, checking for changes, and writing updates to a file. It also handles account deletion, password hash generation, and returns status codes/messages for success or errors like invalid inputs, mismatch...
def upddtls(usr, pwd, nam='', adr='', phn='', eml='', npwd='', npwc='', rmv=False): """ Update user details """ rc, usrfile = getusrf(usr) if rc: return rc, usrfile rc, msg = verusr(usr, pwd) if rc: return rc, msg # Delete routine if type(rmv) == bool and rmv: os.remo...
def get_address(contract_name: str): return config.get("networks").get(network.show_active()).get(contract_name) def get_lending_pool(): lending_pool_address_provider = Contract.from_explorer( get_address("aave_pool_addresses_provider") ) lending_pool = lending_pool_address_provider.getLendingPo...
The main task of the code is to deposit a specified amount of WETH into a lending pool to borrow a requested amount of DAI, ensuring the user has sufficient WETH balance. It first checks and tops up the WETH balance if needed, initializes a lending pool connection, deposits WETH, calculates borrowable DAI, and executes...
def borrow_dai_for_weth(_weth_amount, _dai_amount, owner): _weth_token = interface.IWeth(get_address("weth")) _dai_token = Contract.from_explorer(get_address("dai")) lp = get_lending_pool() if Wei(_weth_amount) > _weth_token.balanceOf(owner.address): get_weth( _weth_token, ...
def evolv_bp(bp, uniform_rand, new_uniform_rand=None): """ Adding a new index to a given Baxter permutation Parameters ---------- bp: numpy.ndarray A Baxter permutation uniform_rand: numpy.ndarray A sequence of random variables, with the same size as "bp". new_uniform_rand: ...
The function `bpp_mcmc` performs MCMC sampling for the Baxter Permutation process to partition an input matrix into rectangular regions. It initializes parameters, masks data for testing, and iteratively updates the permutation, rectangle locations, and input ordering via Metropolis-Hastings steps. The process computes...
def bpp_mcmc(X, opt=None, verbose=True): """ MCMC sampler for Baxter Permutation process Parameters ---------- X: numpy.ndarray An input matrix (Currently, we accept matrices, namely 2-dimensional arrays.), expected to have dtype=int8 (8-bit signed int). opt: utils.Options ...
def forward(self, x): """ Forward function. Takes in one training gabor filter as argument and creates a prediction. """ # V1 simple cell filter # Unfold input gabor stimuli with stride 1 to perform locally connected weight multiplication – returns shap...
The code implements a training loop for a neural network, optimizing weights over multiple iterations using a provided optimizer. It tracks losses, training scores, weight changes, and generalization performance. For each batch, it computes loss, updates weights via backpropagation, and terminates early if loss exceeds...
def train(self, iterations, optimizer): """ Training loop. Takes in the number of iteractions and optimizer as arguments and trains the network over the number of iteractions. Calculates mean loss over batch size and optimizes over this loss. """ logger = logging.getLo...
def transfer_inputting(self, angle1, angle2, x_location, y_location, random_sf): """ Creates gabor filters at particular location to train network with. Takes in two angles that give the range of orientation of gabors and a Boolean random_sf to determine if spatial frequency of gabors ...
This code trains a neural network sequentially on two angles (angle1 and angle2) using a specified optimizer. It tracks weight changes, loss, and training accuracy during iterations, while evaluating generalization performance on a test range of angles. The network's tuning curves are generated post-training to analyze...
def double_train(self, iterations, optimizer, angle1, angle2, x_location, y_location): """ Training loop for sequential curriculum. Takes in the number of iteractions, optimizer, the first angle to be trained on (will be trained on -angle and angle), the second angle to be trained on af...
def parse_args(): ''' Defines commands and parses them. ''' parser = argparse.ArgumentParser() subparsers = parser.add_subparsers(help="commands", dest="command") add_parser = subparsers.add_parser("add", help="manually add entry/entries") upload_parser = subparsers.add_parser("uplo...
The main task of the code is to manage employee data through a command-line interface, allowing users to add, search, display (in text/HTML), upload, download, convert, or view information about records. It initializes a database, parses user commands, and executes corresponding functions to handle data operations.
def main(): print (Fore.CYAN + "\n***Welcome to Data Recorder!***\n\n" + Fore.RESET) print ("This tool will help you store records for Employees that include:" + Fore.CYAN + " %s" % SUPPORTED_RECORDS + Fore.RESET) print ("Curently, Data Recorder supports the following functions: " + Fore.MAGENTA + "%s\n" % ...
def search_init(self): self.master = Tk() self.master.title("Compare Excel docs") self.master["background"] = "#000099" self.master.iconbitmap( default=Window.resource_path("Tenaris_Logo.ico") ) self.l1 = Label( self.master, text="Cho...
The main task of the code is to prompt the user to select two Excel files using file dialogs, set the default directory path based on the first selected file, and initiate a comparison process by calling `get_ws_name()` and `compare()` methods after validating both files are selected. If either file is unselected, it t...
def get_files(self): global DEFAULT_PATH # self.path = str(self.e1.get()) # if self.path == "": # self.path = filedialog.askdirectory() # if self.path == "": # self.master.destroy() # return self.search_init() # Get 1st file self.file1 ...
def get_camera_mat(fov=49.13, invert=True): # fov = 2 * arctan( sensor / (2 * focal)) # focal = (sensor / 2) * 1 / (tan(0.5 * fov)) # in our case, sensor = 2 as pixels are in [-1, 1] focal = 1. / np.tan(0.5 * fov * np.pi/180.) focal = focal.astype(np.float32) mat = torch.tensor([ [focal...
The function generates 3D points along camera rays for a synthetic scene. It computes camera intrinsics/extrinsics, samples rays from a spherical camera position, and calculates points along those rays at varying depths. The output includes world-space pixel coordinates, camera origin, transformation matrices, and samp...
def giraffe(u = 1, v = 0.5, r=2.713, depth_range=[0.5, 6.], n_ray_samples=16, resolution_vol = 4, batch_size = 1 ): range_radius=[r, r] res = resolution_vol n_points = res * res # 1. get camera intrinsic camer...
def load_data(self): engine = create_engine(settings.psql_url) self.poll_data_df = pd.read_sql_query('select * from "poll_data_table"',con=engine).sort_values(by='timestamp_utc') self.store_timing_data_df = pd.read_sql_query('select * from "store_timing_data_table"',con=engine) self.tz_d...
The code generates a CSV file by aggregating store-specific reports. It initializes an empty DataFrame, loads data, processes store timing information, computes reports for each unique store, concatenates results, and exports the combined DataFrame to a CSV file without the index.
def generate_csv(self, filename): result_df = pd.DataFrame(columns=self.report_cols) self.load_data() store_timing_df = self.get_store_timing_df(self.store_timing_data_df, self.tz_data_df) for store_id in self.poll_data_df['store_id'].unique(): summary = self.compu...
def max_vertical_prod(matrix, n): return max_horizontal_prod(transpose(matrix), n) def max_horizontal_prod(matrix, n): max_val = 0 for lst in matrix: if lst_max_prod(lst, n) > max_val: max_val = lst_max_prod(lst, n) return max_val def max_diagonal_product(matrix, n): max_val = 0...
The code computes the maximum product of elements in a matrix by evaluating the highest values from vertical, horizontal, and diagonal directions, then returns the overall maximum among these three.
def matrix_max_prod(matrix, n): return max(max_vertical_prod(matrix, n), max_horizontal_prod(matrix, n), max_diagonal_product(matrix, n))
def SDF(pdbqt): # uses openbabel to convert pdbqt files to sdf format obConversion = ob.OBConversion() obConversion.SetInAndOutFormats("pdbqt", "sdf") mol = ob.OBMol() obConversion.ReadString(mol, pdbqt) # add all hydrogens to match atom types as this was done in the publication mol.AddHydroge...
The main task of the code is to calculate the ECIF (Electrostatic Interaction Fingerprints) by counting occurrences of each possible protein-ligand interaction pair within a specified distance cutoff. It processes input protein (PDB) and ligand (SDF) files, identifies interacting pairs using `GetPLPairs`, and returns a...
def GetECIF(protein, ligand, distance_cutoff): # Main function for the calculation of ECIF SDF_ligand = SDF(ligand) PDB_protein = PDB(protein) Pairs = GetPLPairs(PDB_protein, SDF_ligand, distance_cutoff=distance_cutoff) ECIF = [list(Pairs["ECIF_PAIR"]).count(x) for x in PossibleECIF] return ECIF
def parse_nbx_cell(cell): a = {'xbody': [], 'xarg': [] } a, _ = parse_src(a, cell['source']) return a['xarg'], a['xbody'] def parse_xarg(line): m = _re_xarg.match(line) name, val, sweep = map(strip, m.groups()) return name, val, sweep def get_items(*I): return lambda x: tuple([x[i] for i in ...
The code parses a notebook (nb) by filtering its cells, extracting arguments and body content, categorizing arguments into constant and sweep types, and returning a structured object (pnb) containing the notebook's name, function body, and categorized arguments.
def parse_nb(nb): nbx_cells = filter(is_nbx_cell, nb.cells) xargs = [] xbody = [] for cell in nbx_cells: xa, xb = parse_nbx_cell(cell) xargs += [parse_xarg(line) for line in xa] xbody += xb pnb = Bunch() pnb.name = nb.name pnb.func_body = xbody pnb.args = list(m...
def parse_nbx_cell_with_parse_dict(cell, parse_dict=PARSE_DICT): a = dict([(t,[]) for t in parse_dict.keys()]) a['none'] = [] a, _ = parse_src_with_parse_dict(a, cell['source'], parse_dict) return a def parse_xarg_expr(line): """Parses the line below an `xarg` tag, e.g. ('x', '0', '[1,2,3,4...
This function parses a notebook's cells using a specified dictionary, aggregates parsed data into structured lists, processes argument expressions, separates constant and sweep arguments, and returns a dictionary containing parsed results including function bodies, arguments, and the notebook name.
def parse_nb_with_parse_dict(nb, parse_dict=PARSE_DICT): nbx_cells = filter(is_nbx_cell, nb.cells) keys = parse_dict A = dict([(k,[]) for k in parse_dict.keys()]) A['func_body'] = [] for cell in nbx_cells: a = parse_nbx_cell_with_parse_dict(cell, parse_dict) for k in parse_dict.key...
def load_nb(fname): nbdict = json.load(open(fname,'r',encoding="utf-8")) nb = Bunch(nbdict) nb.name = fname return nb def parse_nb(nb): nbx_cells = filter(is_nbx_cell, nb.cells) xargs = [] xbody = [] for cell in nbx_cells: xa, xb = parse_nbx_cell(cell) xargs += [parse_xa...
(This code initializes an experiment setup by configuring parameters, loading and parsing a notebook, generating necessary scripts (experiment.py, wrapper.py, job.sh), and preparing job submission configurations. It creates directories, handles resource allocations, and sets up sweep parameters for parallel execution, ...
def __init__(self, nbname, mail_user, name=None, linting=True, time=[1,0], ntasks=10, step=5, simg="pytorch.simg", max_arr=900, mem_per_cpu=2000): ...
def load_nb(fname): nbdict = json.load(open(fname,'r',encoding="utf-8")) nb = Bunch(nbdict) nb.name = fname return nb def parse_nb_with_parse_dict(nb, parse_dict=PARSE_DICT): nbx_cells = filter(is_nbx_cell, nb.cells) keys = parse_dict A = dict([(k,[]) for k in parse_dict.keys()]) A['fun...
The code generates an experiment script from a notebook, creates necessary directories, applies parsing rules, validates the notebook, and returns metadata including the number of parameters to sweep. It handles Python-specific setup like __init__.py creation and module importing to determine parameter count.
def create_experiment_script(nbname, target_dir=".", lang="py", tpath=tpath): print("** Creating Experiment script and folder **") nb = load_nb(nbname) nb = parse_nb_with_parse_dict(nb, parse_dict=PARSE_DICT) check_nb(nb) path=Path(target_dir) if not os.path.exists(path): os.makedirs(p...
def preload_model(attributes=['cAGR', 'cCON', 'cEXT', 'cOPN', 'cNEU'], model_no=1): preloaded = [] for attrbute in attributes: model_path = f'./checkpoint/{attrbute}_model_{model_no}.tf' preloaded.append(load_model(model_path)) return preloaded def predict(model, text_no=None): # model_p...
The main task of the code is to evaluate the performance of five preloaded machine learning models (A, C, E, O, N) on a set of test cases. It predicts results for each model, compares them against expected outcomes, calculates accuracy scores, tracks prediction errors via vote counts, and logs aggregated results (accur...
def main(): # attributes = ['all_attributes'] attributes = ['cAGR', 'cCON', 'cEXT', 'cOPN', 'cNEU'] votes = [0, 0, 0, 0, 0] A, C, E, O, N = preload_model(attributes=attributes, model_no=2) # text_number = randint(0, 2468) all_res = [] no_testcases = 2468 no_testcases = 20 start = ran...
def _read_preheader(self): ph_bytes = self._read(PREHEADER_SIZE) return struct.unpack('>H', ph_bytes)[0] def _read_header(self, length): hdr_bytes = self._read(length) hdr_str = hdr_bytes.decode('utf-8') return json.loads(hdr_str) def _read_body(self, header): body_len = ...
The main task of the code is to read and parse a message from a chat server, returning a structured dictionary containing the message's header, processed body (as a dictionary), and raw body string. It achieves this by first reading the header length, then the header itself, followed by the body, which is split into pr...
def receive(self): """ Reads a message from the chat server, returning a dict with the header, the body processed as a dict, and the raw body string. """ header_len = self._read_preheader() header = self._read_header(header_len) body = self._read_body(header) ...
def _read_preheader(self, sock: socket.socket, data: dict) -> int: preheader_bytes = self._read(sock, data, PREHEADER_SIZE) return struct.unpack('>H', preheader_bytes)[0] def _read_header(self, sock: socket.socket, data: dict, length: int) -> dict: """ Receive header data by sock and the...
This code processes incoming data from a socket by reading headers/body, determining the action (e.g., login/logout/send_messages), executing corresponding handler methods, and handling errors like connection resets or malformed JSON. It returns True/False based on action type and error states, while managing user disc...
def process(self, sock, data: dict) -> bool: action = 'unknown' try: header_len = self._read_preheader(sock, data) header = self._read_header(sock, data, header_len) body = self._read_body(sock, data, header) action = body['action'] if action...
def _header(self, body_length): hdr = self.send_header hdr['Content-length'] = body_length hdr_str = json.dumps(hdr) return bytes(hdr_str.encode('utf-8')) def _preheader(self, length): if length > MAX_HEADER_SIZE: raise ValueError('Header size {length} is too big.') ...
The code sends a JSON-formatted message to a server by encoding it into bytes, constructing headers with length information, and concatenating them into a structured message. It transmits this via a socket and returns the server's response.
def send(self, msg): """ Send msg to the server. The message should be a json formatted string. Returns the processed response. """ body = bytes(msg.encode('utf-8')) header = self._header(len(body)) preheader = self._preheader(len(header)) message = preheader + he...
def _prepare_execute_args(self, operation): execute_args = dict(database=self._dbname, resourceArn=self._aurora_cluster_arn, secretArn=self._secret_arn, sql=operation) if self._transaction_id: execute_args["t...
This code executes a database query with error handling for pagination and large result sets, formats parameters, logs the operation, processes the response metadata, and initializes an iterator for result traversal.
def execute(self, operation, parameters=None): self._current_response, self._iterator, self._paging_state = None, None, None execute_statement_args = dict(self._prepare_execute_args(operation), includeResultMetadata=True) if parameters: execute_s...
def scroll(self, value, mode="relative"): if not self._paging_state: raise InterfaceError("Cursor scroll attempted but pagination is not active") scroll_stmt = "MOVE {mode} {value} FROM {pg_cursor_name}".format( mode=mode.upper(), value=value, **self._pagi...
This code implements an iterator for paginated database queries. It fetches records in batches using a cursor, adjusts page size on response size errors, and yields each record. If no pagination is active, it directly returns existing records. The method handles automatic pagination, error recovery, and metadata setup ...
def __iter__(self): if self._paging_state: next_page_args = self._paging_state["execute_statement_args"] while True: logger.debug("Fetching page of %d records for auto-paginated query", self._paging_state["records_per_page"]) n...
def write_arithmetic(self, operation): code_to_write = [] if operation == 'add': code_to_write = [ self.pop_stack_pointer_value_to_d, self.SP, 'A=M-1', 'M=M+D' ] elif operation == 'sub': code_to_write = [self.pop_stack_pointer_v...
This method processes VM commands by routing operations to corresponding handling functions, printing debug info, and executing arithmetic, logical, memory, control flow, function, and return operations through specialized methods.
def write_code_line(self, operation, arg1=None, arg2=None): print('OPERATION:', operation, 'arg', arg1, 'arg2', arg2) if operation in self.arithmetic_operations: self.write_arithmetic(operation) elif operation in self.logical_operations: self.write_logical_operations(oper...
def rnd_bwt(sig, n): bwt = [0]*n for i in range(0, n, sig): for j in range(sig): bwt[i+j] = j for i in range(0, n, sig): shuffle(bwt, i, i+sig) return bwt def bwt2cycle(bwt, sig, n, m): cycle = [0]*n i = 0 num_cycles = 1 while i < n: while cycle[i]==0: ...
This function generates a random de Bruijn sequence of order k over alphabet size Sig by constructing a Burrows-Wheeler Transform (BWT) array, identifying cycles in the transformed structure, and using union-find with random edge swaps to merge cycles into a single component. Once cycles are unified, it applies the inv...
def rnd_debruijn(Sig, k): sig = len(Sig) m = sig**(k-1) n = m*sig bwt = rnd_bwt(sig, n) [cycle, num_cycles] = bwt2cycle(bwt, sig, n, m) if num_cycles == 1: return inv_bwt(bwt, Sig, sig, m) edges = [] for i in range(0,n,sig): for j in range(i+1, i+sig): ...
def load_config(self): config = ReadConfig() self.speed = config["speed"] self.animation = bool(config["animation"]) self.align_center = bool(config["align_center"]) self.align_primary = bool(config["align_primary"]) self.align_secondary = bool(config["align_secondary"]) ...
This code initializes a taskbar management system by configuring alignment, styling, and threading. It loads settings, sets up loops for primary/secondary taskbar alignment (depending on OS and config), and starts styling processes. The `running` flag and threads suggest ongoing operations for taskbar positioning and a...
def __init__(self) -> None: TaskbarCenter.__init__(self) TaskbarStyler.__init__(self) self.load_config() self.interval= self.interval self.running = True self.threads = [None, None] if self.align_center: if OS_NAME == "Windows 11": ...
def Xcenter(self, control): x = self.icons_width(control) if x<0: return self.Xcenter(control) return (SCREEN[0]-x)//2 def AnimateMovement(self, handle, x, y, rect, icons_rect): deltaX = x-icons_rect[0] deltaY = y-icons_rect[1] if deltaX!=0 and y==0: ...
This function centers a tasklist window relative to the taskbar, adjusting for screen orientation (horizontal/vertical) and multi-monitor offsets. It calculates positional deltas, then either directly repositions the window or triggers an animation based on the 'animation' flag. Monitor adjustments account for secondar...
def center(self, taskbar:Window, tasklist:Window, control, MonitorAdjustment=False): taskrect = taskbar.rect icons_rect = tasklist.rect handle = tasklist.hwnd if MonitorAdjustment: PrimaryTaskbarRect = self.Shell_TrayWnd.rect SecondaryTaskbarRect = self.Shell_Se...
def mine_pattern(self, x, y): mines = 0 unopened = 2 ** 9 - 1 for dx, dy in full_deltas: if 0 <= x + dx < self.N and 0 <= y + dy < self.M: if self.map[x + dx][y + dy] == 'x': mines += 2 ** (8 - 3 * (dx + 1) - (dy + 1)) elif self.map...
This code deduces mine positions or safe paths along a given grid path by analyzing possible movements, checking mine patterns, and marking/opening cells based on conflicts. It returns whether any action (mine mark or cell open) was performed.
def deduce_path(self, path, ox, oy): zx, zy = path[1][0] - path[0][0], path[1][1] - path[0][1] if zx == 0: next_squares = next_r moving_coord = 1 M = self.M elif zy == 0: next_squares = next_b moving_coord = 0 M = self.N ...
def all_pos(size, mines): if mines == 0: return [[0 for _ in range(0, size)]] if size == 0: return [] res = [] for l in all_pos(size - 1, mines): res.append(l + [0]) for l in all_pos(size - 1, mines - 1): res.append(l + [1]) return res def open_cell(self, x, y)...
This code tests all remaining unopened cells in a Minesweeper-like scenario by brute-forcing possible mine configurations. It calculates constraints from known boundary cells, generates valid mine combinations, and marks cells as safe or mines based on consistency. The goal is to determine which unopened cells can be s...
def test_all_remaining(self): # Test all remaining possibilities (because I'm too lazy to improve the boundary path merge) unopened = set() boundary_state = dict() for x,y in self.todo_merge: real_mines = 0 ns = set() for dx, dy in deltas: ...
def explore_zeroes(self): while len(self.todo_zeroes) > 0: x, y = self.todo_zeroes.pop() self.fully_done.add((x, y)) for dx, dy in deltas: if 0 <= x + dx < self.N and 0 <= y + dy < self.M: if self.map[x + dx][y + dy] == '?': ...
The code solves a Minesweeper puzzle by deducing mine placements. It first handles a 1x1 edge case, then explores zero-cells to reveal safe spots. It iteratively applies deduction rules (simple and merged) to infer mine positions based on clues. If all mines are placed, it reveals remaining cells; otherwise, it returns...
def solve(self): if self.N == 1 and self.M == 1 and self.map[0][0] == '?': if self.remaining_mines == 0: return '0' else: return 'x' self.explore_zeroes() while True: before = len(self.opened) self.deduce_simple()...
def fetch_fiat_val_base_usd(fiat="INR"): if CURRENCY_API_KEY: try: url = "https://freecurrencyapi.net/api/v2/latest?apikey="+CURRENCY_API_KEY response= requests.get(url, headers= {**headers, **{ 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X...
The main task of the code is to initiate a monitoring process that fetches financial data (e.g., fiat values, cryptocurrency prices, mining wallet info, and farm data) using predefined environment variables. It checks for required credentials and keys, executes data retrieval tasks, handles exceptions, and schedules it...
def start_metrics(s): if not (HIVE_EMAIL and HIVE_PASSWORD and os.getenv('email') and os.getenv('password') and os.getenv("dd_key") and TTL): print("Please set all environment variables before starting.") exit(1) try: print("Monitoring start...") fetch_fiat_val_base...
def create_clusters(hash_paths, cluster_count): """ returns a list of (image_path, cluster_index) """ point_paths = convert_to_points(hash_paths) targets = choose_targets(point_paths, cluster_count) clusters = [] dist_sum = 0 for point_path in point_paths: point = point_path[0] ...
The code generates clusters from hash paths multiple times, evaluates their 'spread' (likely a measure of cluster quality), selects the best cluster configuration with minimal spread, and optionally copies the best cluster's images based on user input. It iterates up to 1000 times to optimize clustering, then prints st...
def generate(hash_paths, cluster_count): generated_clusters, spread_values = [], [] for _ in range(0, 1000): clusters, spread_value = create_clusters(hash_paths, cluster_count) generated_clusters.append(clusters) spread_values.append(spread_value) best_spread = min(spread_values) ...
def ProcessImage(self, obs): """ Input: obs: image of the track Output: gray_mask: Strip of binary image around the car position with black track an white background""" ## Cropping image strip_height = 20 middle_height = 65 top = int(...
The code calculates control actions using PD controllers for angular, distance, and velocity errors derived from image processing and current velocity. It combines these outputs into a final action tuple for navigation or motion control.
def calculateAction(self, rgb_image, velocity): # Get distance from processed image error_dist, error_ang = self.ProcessImage(rgb_image) # Calculate error for velocity control error_vel = self.TargetVelocity - velocity # Get control outputs from PD controllers co...
def parse_text_data_to_desired_initial_input_format(self, text_data): raw_data_list = text_data.split("\n") # print("c1", raw_data_list) list_data_by_meals = [] for i in raw_data_list: temporary = [] temporary.append(i) list_data_by_meals.append(temp...
This function processes raw user text data to calculate and consolidate nutritional information across meals and days, appending units and rounding values. It returns either consolidated daily data, raw meal-wise data, or both, based on parameters, while optionally printing meal-wise nutritional details for debugging.
def take_in_raw_user_text_data_serve_nutritional_data_split_into_meals_with_units_and_days_nutritional_data_with_units( self, raw_text_data, consolidated_data = True, raw_meal_wise_data = False, print_meal_wise_data_for_the_day = False): parsed_data = self.parse_text_data_to_desired_initial_input_f...
def char2int(self, x, y, z, rx, ry, rz): x = int(float(x) * 1000) y = int(float(y) * 1000) z = int(float(z) * 1000) rx = int(float(rx) * 10000) ry = int(float(ry) * 10000) rz = int(float(rz) * 10000) return x, y, z, rx, ry, rz def to_hex(self, z): if z < 0...
This function sends robot movement commands via UDP to set its XYZ coordinates and orientation. It converts input values to hexadecimal, constructs a data packet with predefined headers, and transmits it to a robot controller. The function waits until the robot reaches the target position, ensuring precise positioning ...
def Write_Robot_XYZ(self, x_d, y_d, z_d, angle = "0.0000"): # ID = 00 04 rx = "180.0000" ry = "0.0000" rz = angle data = bytes.fromhex( '59 45 52 43 20 00 68 00 03 01 00 04 00 00 00 00 39 39 39 39 39 39 39 39 ' '8A 00 01 00 01 02 00 00') x, y, z, rx, ry, r...
def front_finder(self): self.front = (filters.laplace(self.working_mask)>0).astype('uint8') def execution(self): # we will remove the target region height, width = self.working_mask.shape image = self.working_image*(color.gray2rgb((1-self.working_mask))) # fill the targe...
The code performs image inpainting by iteratively identifying the highest-priority pixel, sourcing a patch to fill it, updating the image, and repeating until completion. It tracks and prints the time taken for each step and the total process duration, returning the final inpainted image.
def inpainter(self): # to get the time algo took to finish each step initial_time = time.time() finish_check = True while finish_check: self.front_finder() self.execution() self.update_priority() target_pixel ...
def front_finder(self): self.front = (filters.laplace(self.working_mask)>0).astype('uint8') def saver(self): # we will remove the target region image = self.working_image*(color.gray2rgb((1-self.working_mask))) # fill the target region with white color white =...
This code performs iterative image inpainting by repeatedly identifying the highest priority pixel, obtaining a source patch for it, and updating the image until the task is complete. It updates the GUI, manages priorities, and applies patches to reconstruct the image, returning the final result.
def inpainter(self): # to get the time algo took to finish each step finish_check = True while finish_check: root.update() # updates the GUI self.front_finder() self.saver() self.update_priority() target_pixel = se...
def get_all_temporal_stats(): temporal_dict = {} global DATA_TYPE for dt in ['passing', 'rushing', 'receiving']: DATA_TYPE = dt for kvd in get_key_value_dict_list(): year_val = kvd['YEAR']['value'] if kvd['YEAR']['operation'] != '=': year_val = 'all' road_qb_games = get_road_games(kvd.copy(), DATA_T...
This function writes temporal statistics data into three CSV files categorized by 'passing', 'rushing', and 'receiving'. It retrieves all stats, creates CSV files with headers (stat_id, value, yearly data), and writes each stat's time-series data to the appropriate file based on its type. Errors occur for invalid data ...
def write_all_temporal_stats(): temporal_stats = get_all_temporal_stats() with open(get_temporal_filename('passing'), 'w') as f_pass: with open(get_temporal_filename('rushing'), 'w') as f_rush: with open(get_temporal_filename('receiving'), 'w') as f_rec: pass_writer = csv.writer(f_pass) rush_writer = csv...
def calculate_simple_dims(self) -> list: """ Calculates "simple" method dimensions. Loops through every dimension to check for valid slices. Slice side length has biggest effect on outcome ... Parameters: None """ image = cv2.imread(self.path, cv2.IMREAD_COLOR)...
The code calculates slice dimensions using a method specified by `self.method`, dispatching to either `calculate_simple_dims`, `calculate_precise_dims`, or `calculate_precise_grid_dims`. It measures and prints the computation time, then returns the computed dimensions.
def calculate_dims(self) -> list: """ Hub for different methods for calculating slice dimensions ... Parameters: None """ prev_time = time.time() if self.method == 'simple': dims = self.calculate_simple_dims() elif self.meth...
def generate_depth_image(self, frame) -> None: """ Generates depth image from supplied frame ... Parameters: ----------- frame : cv2 image object frame to be used in depth image generation """ create_depth_image_from_frame(frame) def calcula...
This code initializes a class for depth image generation using slicing methods. It sets parameters like thresholds, grid dimensions, and frame data. If `regen=True`, it generates a depth image and calculates slice dimensions; otherwise, it loads existing slice data. The class manages slicing grids and depth estimation ...
def __init__(self, method, init_frame, proportion_thresh, dist_thresh, slice_side_length=608, regen=True, square_size=100, grid_w=3, grid_h=4, refresh_rate=50): """ Sets attributes and generates depth image if regen=True ... Parameters: ----------- me...
def config_parser(): import configargparse parser = configargparse.ArgumentParser() parser.add_argument('--config', is_config_file=True, help='config file path') parser.add_argument("--expname", type=str, help='experiment name') parser.add_argument(...
The code trains a neural network (NeRF) to synthesize images from 3D scene data by optimizing parameters using ray batching and rendering. It loads dataset (e.g., Blender, LLFF), prepares training data, initializes models, and iteratively renders rays, computes loss (MSE), and updates weights via gradient descent. It i...
def train(): parser = config_parser() args = parser.parse_args() # Load data K = None if args.dataset_type == 'llff': images, poses, bds, render_poses, i_test = load_llff_data(args.datadir, args.factor, recenter=True, bd_fac...
def init_ndcg_matrix(): label_list = ['E', 'S', 'C', 'I'] ndcg_matrix = {'E':{}, 'S':{}, 'C':{}, 'I':{}} for label_t in label_list: for label_s in label_list: if label_t != label_s: ndcg_matrix[label_t][label_s] = [] else: ndcg_matrix[label_t][...
(The main task of the code is to evaluate a machine learning model's performance on a set of queries by calculating NDCG (Normalized Discounted Cumulative Gain) scores. It processes queries, computes ranking scores using a model, and aggregates NDCG metrics across regions (US, ES, JP) and label pairs (E, S, C, I). The ...
def evaluation(query_list=list, query2data=dict, pd2data=dict, auto_model=None, auto_trf=None, args=None, category='Train'): # init parameter use_mixed_model = args.model_cfg['use_mixed_model'] target_query_local...
def plot_durs(folder, window=0, ax=None, ytitle='', xlbl='', metrics={'inst_perf': [], 'inc_delays': [], 'days': [], 'durs': []}, fkwargs={'c': 'tab:blue'}, legend=True, conv=[0]): data = put_together_files(folder) data_flag = True # find stage3 data ...
This function plots multiple metrics (e.g., reward, performance) from simulation files across different thresholds and algorithms. It aggregates data from specified file patterns, applies stage-specific plotting logic, and generates a multi-subplot visualization saved as an SVG. Key tasks include file discovery, thresh...
def plot_results(folder, algorithm, w, durs=False, stage2=False, stage_change=False, keys=['reward', 'performance', 'curr_ph'], limit_ax=True): files = glob.glob(folder + '*_' + w + '_*_' + algorithm +'_*') print(folder + '*_' + w + '_*_' + algorithm) print(files) file...
def get_tag(tag, file): # process name f_name = ntpath.basename(file) assert f_name.find(tag) != -1, 'Tag '+tag+' not found in '+f_name val = f_name[f_name.find(tag)+len(tag)+1:] val = val[:val.find('_')] if '_' in val else val if val.find('-1') != -1: val = 'full' return val def dat...
This function processes training data to generate visualizations analyzing algorithm performance across different parameters (e.g., thresholds or protocols). It preprocesses raw data, extracts metrics, creates plots of mean values, performance histograms, and trial distributions. It computes statistics like trials/step...
def plot_results(folder, algorithm, setup='', setup_nm='', w_conv_perf=500, keys=['performance', 'curr_ph', 'num_stps', 'curr_perf'], limit_ax=True, final_ph=4, perf_th=0.7, ax_final=None, tag='th_stage', limit_tr=False, rerun=False, f_final_prop={'col...
def generate_rules(): """ Fucntion to generate the rules :return: dictionnary of rules """ dict_rules = dict() # Coordinated states for x_agent_1 in range(0, 10): for y_agent_1 in range(0, 10): if x_agent_1 != 0 or y_agent_1 != 0: for x_agent_2 in range(0...
The code implements Q-learning to determine the optimal action sequence for capturing a target, using rule-based state-action value updates. It runs for 500,000 episodes, updating rule values with a learning rate (α=0.3) and discount factor (γ=0.9). Epsilon-greedy exploration (ε=0.2 initially) selects actions, and vari...
def q_learning(rseed, startingstates): """ Function who running the algorithm of Q-learning :param rseed: :param startingstates: state from a random list :return: list countain the number of step for each episode """ # Let numpy initialize the seed from the machine random entropy source ...
def get_output(self): '''Returns the current network output.''' return self.terminals[-1] def unpool_as_conv(self, size, input_data, id, stride = 1, ReLU = False, BN = True): # Model upconvolutions (unpooling + convolution) as interleaving feature # maps of four convolutions (A,B,C,D). Building blo...
This function implements a residual upsampling layer (UpProjection) with two branches. It processes input data through interleaved convolutions, applies batch normalization if enabled, sums branch outputs, and applies ReLU. The first branch uses ReLU and BN during upprojection, while the second branch skips ReLU. The c...
def up_project(self, size, id, stride = 1, BN = True): # Create residual upsampling layer (UpProjection) input_data = self.get_output() # Branch 1 id_br1 = "%s_br1" % (id) # Interleaving Convs of 1st branch out = self.unpool_as_conv(size, input_data, id_br1, s...
def mostrarOpciones(self): print("MENU".center(30,"-")) print("[1] Insertar un elemento en una posicion determinada") print("[2] Agregar un aparato a la coleccion") print("[3] Dada la poscicion de la lista, mostrar el tipo de objeto que se encuentra en la posicion") print("[4] Mo...
The code presents a menu-driven interface where the user selects options to perform specific tasks. It continuously displays options, processes user input, executes corresponding methods (op1 to op6), and exits gracefully when option 7 is chosen, saving data before termination.
def opciones(self): continuar = True while continuar: self.mostrarOpciones() self.__op = int(input("Ingrese opcion deseada\n")) os.system("cls") if (self.__op == 1): self.op1() elif(self.__op == 2): self.op2() ...
def _debug(self, msg, *args): if self._print_debug: self._print_debug(msg % args) def _get_rules(self, keyword): """Get list of transformation rules for the given keyword""" keyword = keyword.upper() if "rules" not in self._script.get(keyword): logging.error("No r...
The code processes an input message to generate a chatbot response. It checks for a session start keyword or empty input, uses a welcome message if triggered. The message is normalized, keywords are extracted, and a response is generated using decomposition rules. If no rules apply, a fallback response is used. The fun...
def __call__(self, msg): """Return chatbot response for given input message.""" # handle start of a session if msg == KEYWORD_START or msg is None: self._debug("Empty input - use welcome message") keyword_rules = self._get_rules(KEYWORD_START) resp, _ = self....
def set_default_hsv_limits(self): """ Sets default HSV limits for masking red, yellow and green colors""" s_limits = [25, 255] #35 v_limits = [12, 255] #125 self.hsv_limits = { 'red': { 'lower': [ np.array([1, s_limits[0], v_limits[0]]), ...
The main task of the code is to initialize an image processing class that manages different image lists (original, standardized, masked, masks), sets default HSV masking limits and mask size sigmoid parameters, and classifies images when an original image list is provided. The code prepares the class for image classifi...
def __init__(self, original_image_list=None): self.image_lists = { 'original': None, 'standardized': None, 'masked': None, 'masks': None } # Set HSV limits for maksing. Can be modified publically to improve classification self.set_default_h...
def set_hsv_thresholds(self, hsv, color, limit, h_new, limit_index=0): """ Sets hue thresholds for all colors for HSV masking. Args: hsv (string): 'h', 's', or 'v' color (string): 'Red', 'yellow', or 'green' color. limit (string): 'upper' or 'lower' limit' ...
The function adjusts HSV thresholds for a specified traffic light color, classifies images using these thresholds, calculates classification accuracy, and returns 1 - accuracy as a loss value for optimization. It validates the color input, updates thresholds, performs image classification, and computes a loss metric to...
def change_and_evaluate_hsv_thresholds(self, new_threshold, hsv, color, limit, limit_index=0): """ Function for optimizer to changehsv thresholds then classify and return 1 - accuracy (optimiser minimizes this) """ colors = ['red', 'yellow', 'green'] if color not in colors: ...
def set_lower_sv_thesholds(self, s_lower, v_lower): """ Sets lower saturation and value thresholds for all colors for HSV masking. Args: s_lower (float): Lower saturation threshold. v_lower (float): Lower value threshold """ for color in self.hsv_limits.k...
The function evaluates the impact of varying HSV saturation and value lower thresholds on traffic light classifier accuracy using a 3D surface plot. It iterates through threshold combinations, classifies images via brightness method, records accuracy, and visualizes results with interactive surface plots to analyze thr...
def plot_effect_of_sv_thresholds_surf(self): """ Plots effect of lower saturation and value thresholds using brightness classification method. Ploted with surface to view interactions. """ # Get accuracy over range of SV lower limits n = 5 s_lowers = np.linspace(0, 254, n...
def set_lower_sv_thesholds(self, s_lower, v_lower): """ Sets lower saturation and value thresholds for all colors for HSV masking. Args: s_lower (float): Lower saturation threshold. v_lower (float): Lower value threshold """ for color in self.hsv_limits.k...
This code evaluates the impact of varying lower saturation and value thresholds on classifier accuracy for multiple methods. It iterates through threshold ranges, applies each threshold, classifies images, records accuracy, and plots results. The function returns a dictionary of results, visualizing how each threshold ...
def plot_effect_of_sv_thresholds(self, methods=[ ['brightness'], ['brightness', 'masksize'], ['maskpos'], ['brightness', 'maskpos'] ]): """ Plots effect of lower saturation and value thresholds using all classification methods. Values evaluated seperately without interaction. Returns: ...
def classify_images(self, methods=['brightness', 'maskpos']): """ Runs all necessary methods to classify images. Must be re-called if attributes are changed, e.g.hsv_limits. """ self.image_lists['standardized'] = self.standardize_image_list() masked, masks = self.mask_im...
This code evaluates and visualizes the impact of varying mask size sigmoid parameters ('mid' and 'scale') on classifier accuracy using 3D surface plots and scatter points, combining 'masksize' and 'brightness' classification methods to analyze their interactions.
def plot_effect_of_masksize_sigmoid(self): """ Plots effect of masksize sigmoid parameters with all (combined) classification methods. Ploted with surface to view interactions. """ n = 5 mid_range = np.linspace(0, 1.2, num=n) scale_range = np.linspace(-100, -25, num=n) ...
def get_hsv_range_for_optimisation(self, hsv): ranges = {} ranges['h'] = { 'red': { 'lower': [ [0, 2], [150, 180] ], 'upper': [ [3, 15], [170, 220] ] }, 'yellow': { 'lower': [ [5, 40] ], 'upper': [ [41, ...
This function evaluates and visualizes the impact of varying hue thresholds (lower/upper) on classifier accuracy for multiple traffic light classification methods. It systematically tests HSV hue ranges, records accuracy for each threshold value, and generates plots showing accuracy trends across methods and colors. Th...
def plot_effect_of_hue_thresholds(self, methods=[ ['brightness'], ['brightness', 'masksize'], ['maskpos'], ['brightness', 'maskpos'] ]): """ Plots effect of hue upper and lower thresholds for all classification methods. Values evaluated seperately without interaction. Returns: resul...
def rgb2hex(rgb): return ('%02x%02x%02x' % rgb).upper() def rgb_dist(rgb1, rgb2): return (int(rgb1[0])-int(rgb2[0]))**2+(int(rgb1[1])-int(rgb2[1]))**2+(int(rgb1[2])-int(rgb2[2]))**2 def get_nearest_rgb(rgb, palette): return get_nearest_hex(rgb2hex((rgb[0],rgb[1],rgb[2])), palette)
The function finds the nearest color in a given palette to the pixel at (i,j) in an image by checking the 8 neighboring pixels. It calculates distances between the target pixel and each neighbor, selects the closest neighbor, and returns the palette color closest to that neighbor's RGB value.
def get_color(img,i,j,palette): #gets hex value in palette of nearest color in 8 neighboring pixels h,w,d = img.shape c1 = img[i][j] c1hex = rgb2hex((c1[0],c1[1],c1[2])) if c1hex in palette: return c1hex colors = [] distances = [] for a in range(-1,2): for b in range(-1,...
def factor_graph(pattern): with open(histogram_file, 'rb') as hf: lightness_histogram = pickle.load(hf) saturation_histogram = pickle.load(hf) segment_lightness_histogram = pickle.load(hf) segment_saturation_histogram = pickle.load(hf) per_diff_histogram = pickle.load(hf) ...
The code implements a Metropolis-Hastings sampling algorithm to generate a new color palette by iteratively perturbing existing colors (via random RGB noise or swaps) and accepting/rejecting changes based on a probability ratio derived from model weights. It initializes a palette if none is provided, adjusts temperatur...
def sample(weights, pattern, num_iters, start=None): # metropolis hasitngs: # propose new state, accept with probability proportional to model score # different temperatures # - perturb randomly chosen color ~ N(0,sigma) in RGB # - swap colors num_colors = len(pattern.palette) palette = star...
def factor_graph(pattern): with open(histogram_file, 'rb') as hf: lightness_histogram = pickle.load(hf) saturation_histogram = pickle.load(hf) segment_lightness_histogram = pickle.load(hf) segment_saturation_histogram = pickle.load(hf) per_diff_histogram = pickle.load(hf) ...
The code implements a simulated annealing algorithm with MCMC to optimize a color palette for an image. It iteratively perturbs the palette, evaluates its probability using a factor graph, and accepts/rejects changes based on temperature schedules and Metropolis-Hastings criteria. The goal is to find the palette config...
def find_good_images(weights, pattern, num_iters, start_palette=None,fixed=None): get_prob = factor_graph(pattern) num_colors = len(pattern.palette) #initialize mcmc chain curr_palette = start_palette if curr_palette is None: curr_palette = [] for j in range(num_colors): ...
def factor_graph(pattern): with open(histogram_file, 'rb') as hf: lightness_histogram = pickle.load(hf) saturation_histogram = pickle.load(hf) segment_lightness_histogram = pickle.load(hf) segment_saturation_histogram = pickle.load(hf) per_diff_histogram = pickle.load(hf) ...
The code performs MCMC sampling to generate images by optimizing color palettes. It initializes a palette, iteratively perturbs it, evaluates probabilities using a factor graph, and accepts/rejects changes based on temperature schedules. The algorithm tracks high-probability palettes, appending them to 'good_images' pe...
def find_good_images_2(weights, pattern, num_iters, max_images, start_palette=None): get_prob = factor_graph(pattern) original_prob = get_prob(weights, pattern.palette) num_images = 0 num_colors = len(pattern.palette) good_images = [] #initialize mcmc chain curr_palette = start_palette ...
def initializa_map(self): mon_times = [] tue_times = [] wed_times = [] thu_times = [] fri_times = [] tmp_map = { "mon": mon_times, "tue": tue_times, "wed": wed_times, "thu": thu_times, "fri": fri_times, }...
The function parses course schedule information by extracting time data from a string based on the course type. If the course is LAB or SEM, it splits the string, processes each segment to map days/times, and formats the week data. For other types, it directly processes the full string, using helper methods to extract ...
def parse_schedule(self, info_type, course, formatted_list, course_type): tmp_string = course[info_type] if course_type in ("LAB", "SEM"): check_multiple = tmp_string.split(course_type) for string in check_multiple: tmp_map = self.initializa_map() ...
def create_secondary_skills() -> list[SecondarySkill]: data_first = {"name": "Attack", "level": 0, "description": "test_description"} data_second = {"name": "Defense", "level": 0, "description": "test_description"} return [ SecondarySkill.objects.create(**data_first), SecondarySkill.object...
The main task of the code is to create a Hero object by gathering attributes like name, class, specialty, two secondary skills, and a spell using helper functions, then saving it to the database via Hero.objects.create with the assembled data dictionary.
def create_hero(): skills = create_secondary_skills() data = { "name": "test_name", "hero_class": create_class(), "specialty": create_specialty(), "secondary_skill_first": skills[0], "secondary_skill_second": skills[1], "spell": create_spell(), } return He...
def design_field(state): print('-' * 9) for i in range(3): print('| ', ' '.join(state[i * 3:i * 3 + 3]), ' |', sep='') print('-' * 9) def choose_move(cur_state, who): state = cur_state.copy() opt_ai = ['easy', 'medium', 'hard'] if who == 'user': state = make_move(state) elif ...
This function simulates a two-player turn-based game. It alternates between player1 and player2, updating the game state after each move. The game loop continues until a winning condition is met, at which point the loop terminates and the winner is determined. The function uses helper functions to handle move selection...
def play_game(cur_state, player1, player2): state = cur_state.copy() loop_active = True design_field(initial_state) show = True while loop_active: state = choose_move(state, player1) design_field(state) loop_active, winner = who_wins(state, show) if not loop_active: ...
def createComponent(design: adsk.fusion.Design, name: str) -> adsk.fusion.Component: rootComp = design.rootComponent allOccs = rootComp.occurrences newOcc = allOccs.addNewComponent(adsk.core.Matrix3D.create()) comp = newOcc.component comp.name = name return comp def createBaseRectSketch(componen...
The main task of the code is to generate a 3D holster model based on user inputs. It processes input parameters, constructs the holster geometry through extrusions and cuts, applies fillets for rounding edges, and adds screw holes if specified. The code creates a component, defines its shape, and applies design feature...
def notify(self, args): try: eventArgs = adsk.core.CommandEventArgs.cast(args) unitsMgr = _app.activeProduct.unitsManager command = args.firingEvent.sender inputs = command.commandInputs global _holsterName global _remoteWidth...
def receiveMessage(s, msg): sendMessage(s, msg) return s.recv(4096).decode().strip() def sendMessage(s, msg): s.send(msg.encode()) def _isPrime(p): if p < 1: return False if (p.bit_length() <= 600) and (p.bit_length() > 1500): return False if not millerRabin(p, 300): retu...
The code receives an input 'p', converts it to an integer, and checks if it is both a prime (using _isPrime) and not a prime (using isPrime). If both conditions are met, it sends a flag; otherwise, it indicates the conditions are not satisfied. The task involves validating primality with two functions and triggering a ...
def main(s): p = receiveMessage(s, "Give p: ") try: p = int(p) except: sendMessage(s, "Error!") if _isPrime(p) and not isPrime(p): sendMessage(s, FLAG) else: sendMessage(s, "Conditions not satisfied!")
def frequency_dict(self, text): ''' Create Dictionary with Frequency of each character in the text :param text: text :return: dict = character > frequency ''' counter = Counter() for char in text: counter[char] += 1 return counter def min_heap_...
This code performs Huffman encoding on input text. It calculates character frequencies, constructs a min-heap of nodes, merges them into a binary tree, generates binary codes from the tree, and encodes the text using these codes. The function returns the encoded binary string and the resulting Huffman tree for decoding...
def encode(self, text): if text == str(): return str(), None # Get dictionary with frequency of characters frequency_dict = self.frequency_dict(text) # Min-Heap with Nodes(key, frequency) min_heap = self.min_heap_list(frequency_dict) merged_heap = self.merge_...
def HandleEventUI(self): self.screen.blit(self.backgroundInGame, (0, 0)) if self.state == GameState.INIT: # TODO: Draw panel game self.screen.blit(self.logo, (363, 40)) if Button(530, 355, self.playButton, 1).draw(self.screen): self.isOpenSetting = Fa...
This code initializes and runs a game loop for a "Tank War" game using Pygame. It sets up the game window, loads UI assets (buttons, backgrounds, icons), handles events, updates game objects (players, bullets), checks collisions, and renders the screen. The loop continues until the user quits, managing game states like...
def Play(self): # Initialize pygame.init() self.clock = pygame.time.Clock() # Set Resolution self.screen = pygame.display.set_mode((WIDTH_SCREEN, HEIGHT_SCREEN)) # Set name of the game pygame.display.set_caption("Tank War") # Set icon for the game ...
def menu(self): self.clean() self.parent.menu() def drawCurve(self, x, y, z): self.lineAhead.removeAllChildren() self.prev_line.moveTo(x[0], y[0], z[0]) self.prev_line.drawTo(x[1], y[1], z[1]) for i in range(len(x) - 1): self.line.drawTo(x[i + 1], y[i + 1], ...
This code adjusts a plane's curvature (kappa) and torsion (tau) based on user input, solves the Frenet-Serret equations to compute a 3D curve, updates the plane's position/orientation (T, N, B vectors), converts tangent vectors to heading/pitch/roll (hpr), and renders the curve. It handles real-time movement and visual...
def updateCurvTor(self, task): """ Movement bases on curvature and torsion """ if self.parent.keyMap["tor+"]: self.plane.tau += self.SCALE if self.parent.keyMap["tor-"]: self.plane.tau -= self.SCALE if self.parent.keyMap["curv+"]: self.plane.kappa += s...
def get_model(model_path : str) -> tf.Module: ''' Load model, turn off redundant gradients. ''' model = tf.keras.models.load_model(model_path) return model def decrypt_model(model : tf.Module, key : bytes) -> None: ''' Decrypts model using provided key Parameters ---------------- ...
The code's main task is to either encrypt or decrypt a machine learning model based on the decryption_mode flag. If decrypting, it loads a model and decryption key, decrypts the model, and saves the result. If encrypting, it encrypts the model with a provided key, saves the encrypted model, and stores the encryption ke...
def main(args : dict, decryption_mode : bool = False) -> None: # Set up model and secret key print("Fetching model and secret key") model = get_model(args.model) master_key = pickle.load( open(args.decryption_key, "rb")) if decryption_mode else None # Run decryption if decryption_m...
def getNodes(size): result = [] for i in range(-size, size + 1): for j in range(-size, size + 1): if abs(i + j) <= size: result.append(tuple([i, j, -(i+j)])) return tuple(result) def getEdges(nodes, size): result = list() for node in nodes: for neighbor in...
The main task of the code is to generate a maze by creating nodes and edges, shuffling the edges for randomness, and then printing the maze structure using the generated nodes and edges. The function orchestrates maze creation through node generation, edge list formation, randomization, and visualization.
def generate_maze(): nodes = getNodes(SIZE) edgeList = getEdges(nodes, SIZE) shuffle(edgeList, SEED) mazeEdges = generateMazeEdges(edgeList) return printMaze(nodes, mazeEdges, SIZE)
def init_params(self, data): # initialzie a set for each parameter, targeted for the updation step dat = np.split(data, self.k) w_ = np.array([]) mu_ = np.array([]) sigma_ = np.array([]) for i in range(self.k): w_ = np.append(w_, [1 / self.k]) ...
The code implements the Expectation-Maximization (EM) algorithm for a Gaussian Mixture Model (GMM). It iteratively performs E-step (computing responsibilities) and M-step (updating parameters: weights, means, and covariances) until convergence (when the change in log-likelihood falls below a threshold `eps`) or reaches...
def fit(self, data): """ Fit training data (the learning phase). Use init_params and then expectation and maximization function in order to find params for the distribution. Store the params in attributes of the EM object. Stop the function when the difference between ...
def arrange(data, cnt_dict, row): for i in range(len(data)): try: cnt_dict[i][data[i]]["idx"].append(row) except KeyError: tmp = {data[i] : { "idx": [row]}} try: cnt_dict[i].update(tmp) except KeyError: cnt_dict[i] = tmp...
The code processes an array by categorizing elements into a dictionary (`cnt_dict`) using the `arrange` function. It then iteratively applies version-specific comparison logic (`compare_low` or `compare`) to refine groupings until each category in `cnt_dict` contains at most one element. The main task is to organize an...
def parse(array, version): cnt_dict = {} row = 0 for data in array: arrange(data, cnt_dict, row) row += 1 while len(cnt_dict[0]['1']["idx"]) > 1: for idx in range(12): #print(cnt_dict) if len(cnt_dict[0]['1']["idx"]) <= 1 and len(cnt_dict[0]['0']...
def download_from_api(url: str) -> pd.DataFrame: """Download information from API""" token=read_api_data() headers = {'Authorization': token} response = requests.get(url, headers=headers) if response.status_code == 200: data = response.json() df = pd.DataFrame(data) return ...
The main task of the code is to perform an ETL process: extracting data from Mercadolibre APIs (trends, categories, best sellers, products), transforming it into structured formats, and loading it into local files, Google Cloud Storage (GCS), and BigQuery. It orchestrates data retrieval, storage, and cloud integration ...
def etl_parent_flow(): trends = download_from_api('https://api.mercadolibre.com/trends/MLA') categories = download_from_api('https://api.mercadolibre.com/sites/MLA/categories') best_sellers = best_sellers_api(categories) products, items = products_api(best_sellers) files = ['categories', 'b...
def get_sqs_entries(): sqs = boto3.client('sqs') m = sqs.receive_message(QueueUrl='https://sqs.us-east-1.amazonaws.com/146486855224/Dining.fifo') messageId = m['Messages'][0]['MessageId'] receiptHandle = m['Messages'][0]['ReceiptHandle'] x = json.loads(m['Messages'][0]['Body']) # print("messageId =>",messageId) ...
The main task of the code is to retrieve restaurant suggestions based on user-specified cuisine, group size, date, and time, then send the results via SMS using AWS SNS. It processes input parameters from an SQS queue, formats the response message, and delivers it to a phone number provided in the input.
def lambda_handler(event, context): # TODO implement slots = get_sqs_entries() # print(slots) rests = search_restaurants_for_cuisine(slots['Cuisine']) # print(json.dumps(rests)) message = "Hello! Here are the "+slots['Cuisine']+ " suggestions for "+slots['Size']+" people for "+slots['Date'] ...
def _train(self, X, y, verbose, silent): """ Private method to train the model. :param X: Training set :param y: Training labels :param verbose: Display details during expectation maximization :param silent: Hide the progress bar :return: Para...
The `grid_search` function performs hyperparameter tuning by evaluating multiple lambda values via grid search. It trains the model for each lambda using either cross-validation (if `k_fold > 1`) or a provided test set. For each lambda, it computes the RMSE (and its standard deviation for cross-validation). After ident...
def grid_search(self, lambdas, k_fold=1, X_test=None, y_test=None, verbose=False, silent=False): """ Train the model using grid search over lambda. :param lambdas: Ndarray of lambdas :param k_fold: If > 1, cross-validation is used for each combination using self.X and self.y. Otherwise...
def new_random_testcase(self): str_len = random.randint(0, 64) s = "" for i in range(str_len): # Choose a random character from the list of ASCII symbols s = s + random.choice(all_ascii_symbols) return TestCase([random.randint(-10000000, 10000000), random.randint(...
The `morlot` function implements an algorithm for generating and optimizing test cases to cover objectives. It balances exploration (random test case generation) and exploitation (improving existing test cases via action selection) using an epsilon-decay strategy. The loop continues until all objectives are covered or ...
def morlot(self): self.epsilon = 1 rewards = [] actions_taken = 0 stopping_condition = False while len(self.obj_list.uncovered_objective_list) != 0 and not stopping_condition: # epsilon decay if self.epsilon > 0.1: self.epsilon -...
def create_in_out_files(i_files_path, o_files_path, data_path): pairs = read_jsonl(data_path) c=0 for i in range(len(pairs)): sample_num = i in_file = os.path.join(i_files_path, str(sample_num)+".text.txt" ) ou_file = os.path.join(o_files_path, str(sample_num)+".summary.txt") fname_i = open(in_fil...
The code prepares training, validation, and test datasets by creating input/output directories, tokenizing text using a Stanford tokenizer, converting tokenized data into binary files, and chunking them into smaller segments for efficient model training and evaluation. It processes "tesum_data" JSONL files, organizes t...
def main(): ###Input directories: setnames = ['train', 'dev', 'test'] for set_name in setnames: data_path = "tesum_data/"+str(set_name)+".jsonl" in_path = "data/In_files/"+"zi_"+str(set_name)+"_dir/" if not os.path.exists(in_path) : os.makedirs(in_path) out_path = "data/Out_files/"+"zo_"+str(se...
def parse_arguments(args): """ Parse program arguments """ parser = argparse.ArgumentParser() parser.add_argument( '--lambda', type=float, dest='lam', default=0.1, help='penalty term') parser.add_argument( '--repeat', type=int, default=10, help='how many times to ...
The code runs multiple simulations of the RoMab algorithm with UCB1, evaluating fairness-aware bandit strategies. It initializes Bernoulli arms, configures fairness parameters, and iteratively executes simulations, logging metrics like total reward, pull counts, and fairness approximations. Results are timestamped and ...
def main(args): opt = parse_arguments(args) output_file = open( os.path.join(opt.output_dir, "raw", f"results_{datetime.now().isoformat()}.txt"), "w") arms_probs = opt.arms arms = [BernoulliArm(prob) for prob in arms_probs] K = len(arms) f1 = get_fairness_function(op...
def track_mouse(self): self.coords = [] for frame_index in range(self.num_frames): try: xy1, xy2 = self.detect_mouse(frame_index) cX, cY = (xy1[0] + xy2[0])//2 , (xy1[1] + xy2[1])//2 except ValueError as e: cX, cY = np.nan, np.nan ...
The code saves a video of tracked mouse regions of interest (ROIs) by capturing mouse coordinates, cropping each frame around these points, and writing the resulting frames into a video file at the specified FPS.
def save_rois(self, filepath, fps=30): coords = self.track_mouse() frame = self.frames[0] crop_dims = list(self.roi_dims) + [frame.shape[-1]] if len(frame.shape) == 3 else self.roi_dims writer = write_video(filepath, crop_dims, fps=fps) for index in range(len(coords)): # range(...
def act_on_login_choice(self, choice): """ :param choice: str - can be: -- l, r or q :return username (str / None): None / 'q' / 'username' """ username = 'John Doe' password = 'password' users_data = cu.get_users_data() users = users_data.keys() ...
The main task of the code is to handle a login/register loop, allowing users to log in, register, or quit. If logged in, users can choose to start a new game, continue a saved game, or return to the main menu. For new users, it guides them through game selection and opponent choice. The loop persists until the user qui...
def login_register_loop(self): while True: # Main menu - Login / Register / Quit: self.view.print_login_menu() login_register_choice_options = ['l', 'r', 'q'] login_choice = cu.make_choice(login_register_choice_options) username = self.act_on_login_ch...
def calculate_degree_distribution(graph): # Initialise the plot fig, ax = plt.subplots() # In-degree in_degrees = dict(graph.in_degree()) print_plot_degree_distributions(ax, in_degrees, graph, "In-degree") # Out-degree out_degrees = dict(graph.out_degree()) print_plot_degree_distributio...
The code calculates and prints key network metrics of a graph, including the number of vertices and edges, degree distribution, centrality measures, clustering coefficient, network diameter, density, and connected components.
def calculate_metrics(graph): # Calculate the number of vertices n_vertices = graph.number_of_nodes() print("Number of vertices: " + str(n_vertices)) # Calculate the number of edges n_edges = graph.number_of_edges() print("Number of edges: " + str(n_edges)) # Calculate the degree distributio...
def initializeGUI(self): layout = QtWidgets.QGridLayout() qbox = QtWidgets.QGroupBox("HV500 Client") sub_layout = QtWidgets.QGridLayout() qbox.setLayout(sub_layout) layout.addWidget(qbox, 0, 0) self._vmon_labels = [] self._vset_spinboxes = [] self._vset_...
The code connects to a LabRAD server (hv500_server) asynchronously, initializes a GUI, sets voltage limits (-300V to +300V), and links GUI widgets to server interactions. The GUI setup occurs after connection to ensure proper async execution order.
def connect(self): """ Connects to LabRAD and initializes the GUI. GUI init is placed in this function rather than __init__, because this function runs async, and GUI initialization should happen after connect. """ from labrad.wrappers import connectAsync self.c...
def parse_json_matrix(filename: str) -> dict: """Parse a JSON file into a key -> test_case dict""" with open(filename) as file: parsed = json.load(file) result = {} assert isinstance(parsed, list) for case in parsed: assert isinstance(case, dict) assert not keys.isdisjoint(ca...
The code compares benchmark results from two JSON files against a baseline, identifying outliers based on a deviation threshold. It outputs results in JSON, CSV, or markdown formats, highlighting significant deviations and providing detailed outlier reports when requested.
def compare_main(args: list): """Runs the comparison script""" parser = argparse.ArgumentParser(description="Compare to Ginkgo benchmark outputs") parser.add_argument( "--outliers", action="store_true", help="List outliers from the results" ) parser.add_argument( "--outlier-threshold...
def _format_target(self, target): if self.multi_class: target = torch.transpose(torch.nn.functional.one_hot(target, num_classes = self.n_classes),-1,-2) if is_classifier(self):#center classes target = (target - self.class_mean)*2 return target def _compute_loss(self, pred...
This function initializes close-form parameters for a model. It computes an intercept by evaluating the loss of a mean prediction against the target, then determines the close-form parameter either via a fixed value, grid search, or default. Finally, it updates the parameter by applying the natural logarithm of the com...
def _initialize_closeform(self, datas): if self.add_permut_term: with torch.no_grad(): target = datas["target"] formated_target = self._format_target(target) pred = formated_target.mean() * torch.ones(formated_target.shape, device = device) ...
def _forward_propagate(self, datas): activation, target = datas["input"], datas["target"] target = self._dither_target(target) activation = self._forward_pass(activation) if self.use_closeform: self.record["lambda"].append(np.exp(n2f(t2n(self.closeform_param)))) f...
The code performs one training iteration by computing forward propagation loss, checking for convergence termination, and if not converged, executing backpropagation. It returns whether the model has not yet converged, managing the training loop's continuation.
def run_one_iter(self, datas): loss = self._forward_propagate(datas) if self._check_termination(): self.has_converged = True else: self._backward_propagate(loss) del loss return not self.has_converged
def _initialize_state(self): self.init_time = time.time() self._random_state = check_random_state(self.random_state) self.torch_random_state = torch.Generator(device=device).manual_seed(int(self._random_state.uniform(0,2**31))) self.print_record = self.verbose not in [0, False] s...
The main task of the code is to initialize a machine learning model by setting up its internal state, preparing input/output data, splitting data for validation (if enabled), and configuring training parameters. It measures initialization time, preprocesses data, and optionally applies closed-form solutions. The functi...
def initialize_model(self, X, y): self.init_time = time.time() self._initialize_state() y = self._initialize_task(y) if self.validation: X, self.X_valid, y, self.y_valid = self._initialize_valid(X, y) self._initialize_training(len(y)) datas = self._initialize_data(X,y) ...
def run_one_iter(self, datas): loss = self._forward_propagate(datas) if self._check_termination(): self.has_converged = True else: self._backward_propagate(loss) del loss return not self.has_converged def _update_data(self, datas): if self.batch_le...
The code trains a model iteratively by repeatedly running one training iteration (`run_one_iter`) and updating data (`_update_data`) until termination. If early stopping is enabled, it loads saved weights and releases training memory to finalize the process.
def _train_model(self, datas): self.current_time = time.time() #run until termination while self.run_one_iter(datas): datas = self._update_data(datas) #end training if self.early_stopping: self._load_weights() self._release_train_memory()
def _initialize_data(self, X, y): if self.batch_learning: self._initialize_batch(len(y)) if not self.multi_class: y = y.reshape((X.shape[0],-1)).T if self.rescale_target: y = y / self.target_std if self.center_target and not is_classifier(self): ...
The code fits a model by initializing data either incrementally or from scratch, then trains the model using the initialized data, and returns the trained model instance.
def _fit(self, X, y, incremental=False): if incremental: datas = self._initialize_data(X,y) else: datas = self.initialize_model(X,y) self._train_model(datas) return self
def _initialize_parameters(self, X, random_state): n_samples, n_features = X.shape self.weight_concentration_prior = 1./self.n_components self.select_prior = 1 self.gamma = np.ones((self.n_components, n_features)) self.delta = np.ones((self.n_component...
The code performs multiple initializations of a probabilistic clustering model, iteratively executing E-step (computing log probabilities and responsibilities) and M-step (updating parameters) to maximize the lower bound. It tracks cluster assignments and selection probabilities at each iteration across all initializat...
def fit_predict(self, X): n_init = self.n_init max_lower_bound = -np.infty random_state = check_random_state(self.random_state) n_samples, n_features = X.shape clus_update = {} sel_update = {} for init in range(n_init): ...
def work_data(lines): stacks = format_stacks(lines) instructions = format_instructions(lines) return (stacks, instructions) def perform_instructions(stacks, instructions): new_stacks = stacks for num, start, des in instructions: num = int(num) start = int(start) - 1 des = int...
The code processes a series of stack operations defined in instructions, applies them to initial stack configurations, and returns the top elements of the modified stacks as a string.
def process(): lines = get_lines() stacks, instructions = work_data(lines) new_stack = perform_instructions(stacks, instructions) top_string = read_top(new_stack) return top_string
def get_spline(ages,new_len,mortality,deg=3): #Use scipy's spline interpolation to preserve initial points as knots spl = UnivariateSpline(ages,mortality,k = deg, s=len(ages)) data = np.linspace(0,int(max(ages)),new_len) curve = spl(data) curve = curve.clip(max=100) curve = curve.clip(min=0) return [curve,spl] d...
This function processes mortality data to generate a life table, including population distribution, life expectancy, and demographic statistics. It interpolates and smooths mortality rates over age, expands them to a standardized cohort length, calculates steady-state populations, and derives key metrics like birth/dea...
def pre_sim_process(ages,mortality,lifetime,fertility_start,fertility_end,TF_guess=3,curve_degree=3,cohort_len=1,flat_fertility_pdf=0,customfactor=1,verbose=0): #Constants: human_astar_life_ratio = 100/1000 human_waith_life_ratio = 100/25000 #mortality values need to be evaluated at normalized age...
def get_curve(ages,new_ages_len,mortality,deg=12): #fit a polynomial of degree 'deg' to the non-normalized-spacing ages and mortality. #With a functional version we can discretize it however we want later. z = np.polyfit(ages,mortality,deg) poly = np.poly1d(z) #create the new ages array with t...
The code processes demographic data to compute life tables, population distributions, and related statistics. It interpolates mortality rates, estimates steady-state populations, calculates life expectancy, and generates a structured output including age-specific mortality, cohort sizes, and demographic metrics for fur...
def pre_sim_process(ages,mortality,lifetime,fertility_start,fertility_end,TF_guess=3,curve_degree=12,cohort_len=1,flat_fertility_pdf=0,verbose=0,): #Constants: human_astar_life_ratio = 100/1000 human_waith_life_ratio = 100/25000 #mortality values need to be evaluated at normalized age spaces #...
def guess_distance(point1, point2): x1, y1 = point1 x2, y2 = point2 return abs(x1 - x2) + abs(y1 - y2) def reconstruct_path(came_from, current, grid): while current in came_from: current = came_from[current] if current != start: current.make_path() draw(grid) def draw...
This code implements the A* pathfinding algorithm on a grid. It uses a priority queue to explore nodes, calculates tentative scores for neighbors, and updates paths if a shorter route is found. The algorithm visualizes the search process via Pygame, marking nodes as open/closed and reconstructing the path when the end ...
def a_star_algorithm(grid): count = 0 open_set = PriorityQueue() open_set.put((0, count, start)) came_from = {} g_score = {node: float("inf") for row in grid for node in row} g_score[start] = 0 f_score = {node: float("inf") for row in grid for node in row} f_score[start] = guess_distance...
def tf_ms_ssim(img1, img2, mean_metric=True, level=5): weight = tf.constant([0.0448, 0.2856, 0.3001, 0.2363, 0.1333], dtype=tf.float32) mssim = [] mcs = [] for l in range(level): ssim_map, cs_map = tf_ssim(img1, img2, cs_map=True, mean_metric=False) mssim.append(tf.reduce_mean(ssim_map))...
The code computes a composite structural loss combining multiple image quality metrics: MS-SSIM (with 1-SSIM), MSE, multiresolution patchwise MSE, chi-squared distance, and JS divergence. These are weighted and summed to guide image generation by balancing structural similarity, pixel accuracy, and statistical distribu...
def structural_loss(y_true, y_pred): img1 = tf.image.rgb_to_grayscale(y_true) img2 = tf.image.rgb_to_grayscale(y_pred) ms_ssim_loss = 1 - tf_ms_ssim(img1, img2) # heuristics, gives better generation result mse_loss = keras.losses.mse(y_true, y_pred) mr_pmse_loss = multires_patchwise_mse(y_true, y_pr...
def light_on(self, number): assert number >= 0 and number < self.n_buttons on = self._get_lights_register() self._put_lights_register(on | self.masks[number]) def get_buttons(self): inp = ~self._get_debounced_switches_register() return [n for n, m in enumerate(self.masks) if inp ...
The main task of the code is to light up a specific button on a board, wait until only that button remains active, then clear the board. It validates the input button index, activates the button, loops until no other buttons are active, and finally resets the board state.
def whack(self, number): assert number >= 0 and number < self.n_buttons self.light_on(number) while self.get_buttons() != [number]: pass self.board_clear()
def get_buttons(self): inp = ~self._get_debounced_switches_register() return [n for n, m in enumerate(self.masks) if inp & m] def light_on(self, number): assert number >= 0 and number < self.n_buttons on = self._get_lights_register() self._put_lights_register(on | self.masks[numb...
The function waits for a specific button (number) to be pressed, validates it against expected inputs, and if correct, lights it up, waits for release, clears the board, then returns True. If an incorrect button is pressed, it immediately returns False.
def press_release(self, number): assert number >= 0 and number < self.n_buttons while True: buttons = self.get_buttons() if buttons: if buttons == [number]: break # Hit the wrong button return False self....
def load_upsert(self, data: pd.DataFrame ) -> bool: """ Database upsert function for loading Domain API results. Arguments: data: Pandas dataframe containing the desired data to load after extract from Domain API Returns: True if successful (nothing ...
The code's main task is to perform data loading into a database table using different strategies based on the `self.mode` parameter. It selects between conventional upsert, chunked upsert, incremental load, or complete overwrite, logs the chosen method, executes the corresponding loading function (`load_upsert`, `load_...
def load(self, data: pd.DataFrame ) -> bool: if (self.mode == "upsert"): logging.info(f"Performing conventional upsert into table {self.target_table}") success = self.load_upsert(data) elif (self.mode == "upsert_chunks"): logging.info(f"Performin...
def allSameClass(self, data): for row in data: if row[-1] != data[0][-1]: return False return data[0][-1] def getMajClass(self, curData): freq = [0]*len(self.classes) for row in curData: index = self.classes.index(row[-1]) freq[index] +...
The main task of the code is to recursively generate a decision tree node by evaluating stopping conditions (e.g., uniform class, empty data, no attributes), splitting data using the best attribute, and creating child nodes for each subset. It constructs a tree structure where internal nodes represent attribute splits ...
def recursiveGenerateTree(self, curData, curAttributes): allSame = self.allSameClass(curData) if len(curData) == 0: # Fail return Node(True, "Fail", None) elif allSame is not False: # return a node with that class return Node(True, allSame, None) ...
def read_and_parse_job(self): print("=========== Start parsing job information ===========") if not self.raw_job and not self.parsed_job: logger.warning( "Job_text and Parsed_job are empty, please call set_job_text() first." ) return None star...
The main task of the code is to automate resume creation and optimization by parsing job postings, rephrasing resume content (experiences, projects, skills), generating a structured YAML resume, identifying improvements, and exporting the final resume as PDF and JSON. It systematically processes input data, refines con...
def main(self): # Step 1 - Read and parse job posting self.read_and_parse_job() # Step 2 - read raw resume and create Resume builder object self.read_resume() # Step 3 - Rephrase unedited experiences. Try re-running cells in case of missing answers or hallucinations. se...
def events(self): # Game loop - Event for event in pg.event.get(): if event.type == pg.QUIT: self.playing = False self.running = False if event.type == pg.KEYDOWN: jump_button = event.key == pg.K_SPACE if jump_butto...
The main task of the code is to execute a game loop that runs while `self.playing` is True. It maintains a fixed frame rate using `self.clock.tick(FPS)`, processes events, updates game state, and renders visuals. The loop continues until `self.playing` is set to False, ensuring continuous game operation until terminati...
def runGame(self): # Game loop self.playing = True while self.playing == True: self.clock.tick(FPS) self.events() self.update() self.draw() self.all_sprites.update()
def draw(self): # Game loop - Draw #self.gameDisplay.fill(BG_COLOUR) ## pg.draw.rect(self.gameDisplay, RED, self.player.rect, 2)### ## for plat in self.platforms: ## pg.draw.rect(self.gameDisplay, RED, plat.rect, 2) ## for enemy in self.enemies: ## pg.draw.rect...
This function displays the game over screen by rendering the "GAME OVER" message, the player's score, a restart instruction, and the leaderboard. It updates the display and waits for a key press to proceed.
def showGameOverScreen(self): #if self.running == True and self.playing == False: self.draw() self.drawText("GAME OVER", TITLE_FONT_SIZE, GAME_OVER_COLOUR, (SCREEN_WIDTH / 2), (SCREEN_HEIGHT * 1/5), 1, True, GREY2) self.drawText("Your Score: " + str(self.score), 32, TEXT_COLOUR, (SCREEN_...
def node_count(self): """ Returns the number of nodes in G """ return len(self.node_list) def edge_count(self): """ Returns the number of edges in G """ return len(self.edge_list) def is_directed(self): """ Returns True if G is directed, False otherwise """ # saves the re...
This function calculates the density of a graph by determining the ratio of its actual edge count to the maximum possible edges in an undirected graph, adjusted by dividing by 2 if the graph is directed.
def density(self): """ Returns the density of G according to https://en.wikipedia.org/wiki/Dense_graph """ n = self.node_count() den = n * (n - 1) / 2 ratio = self.edge_count() / den if self.is_directed(): return ratio / 2 return ratio
def move_motors(film_motor, takeup_motor, dir, mode): if mode == 0: film_motor.TurnFrames(dir, 15) elif mode == 1: film_motor.TurnFrames(dir, 1) elif mode == 2: film_motor.TurnStep(dir, 1) def new_index(settings): settings['image'] = f'{settings["mo...
The code provides a user interface for controlling a camera and motors (film and takeup) to capture and process film frames. It initializes the PiCamera, listens for keyboard inputs (e.g., 'w', 's', 'c') to move motors or take pictures, updates frame indices, and manages automatic picture-taking until a specified numbe...
def user_interface(film_motor, takeup_motor, settings): #Starting Camera mode = 0 camera = PiCamera() camera.resolution = (4056, 3040) camera.start_preview() camera.rotation = 180 # camera.zoom = (0.4, 0.3, 0.7, 0.7) # settings['index'] = -1 # if 'latest_pic' in settings: ...