dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def Dz0(self, XCr, params): d_i = params return np.exp(1j * XCr.Z / 2.0 / XCr.cosa * self.epsxh0x(XCr) * d_i) def ksih0_select(self, XCr, params): d_i = params jv0_pp = jv(0, 2.0 * XCr.ele_susceptH * XCr.Z / 2.0 / XCr.cosa * d_i) * np.exp((XCr.ele_susceptH * XCr.Z * d_...
The function `operator_B` transforms input parameters `U1prop` and `U2prop` by scaling them with stored values `dz_store` and `ksh_store`, then computes complex-valued outputs `U1R` and `U2R` using exponential terms involving wave numbers and phase factors. These operations likely model wave propagation or signal proce...
def operator_B(self, U1prop, U2prop, params): XCr, k, d_i = params dz_store = self.Dz0(XCr,d_i) # stored for later use ksh_store = self.ksih0_select(XCr,d_i) # stored for later use U1prop *= dz_store U2prop *= dz_store U1R = U1prop * ...
def technicalContribution(data): testIncluded = 0 if data['payload']['pull_request']['body'] == None: PRBodySize = 0 else: PRBodySize = len(data['payload']['pull_request']['body']) CommitSize = data['payload']['pull_request']['additions'] + data['payload']['pull_request']['deletions'] ...
The main task of the code is to extract and compile multiple features related to a pull request, including technical contributions, social interactions, repository metadata, and submitter attributes, into a structured list for analysis or prediction. It aggregates data from API calls and internal calculations to genera...
def create_record(data): # technicalContribution(record) take a total 2 API calls testIncluded, PRBodySize, CommitSize, No_of_Files_Changed = technicalContribution(data) # socialConnection take a total of 2 API calls socialDistance, priorInteraction = socialConnection(data) # pullrequestFeatures ta...
def string_dates(x): if x < 10: return '0' + str(x) else: return str(x) def create_record(data): # technicalContribution(record) take a total 2 API calls testIncluded, PRBodySize, CommitSize, No_of_Files_Changed = technicalContribution(data) # socialConnection take a total of 2 API ...
The code generates a dataset of closed GitHub pull requests over a specified time period, filtering entries based on a repository list and excluding cases where users close their own PRs or forked repositories. It processes JSON event files, checks conditions, and saves valid records while monitoring rate limits.
def generatePRDataset(datetime_date, number_of_days, repo_list_filepath): x = datetime_date fp_repo = open(repo_list_filepath, 'r') repo_dict = json.loads(fp_repo.read()) # print(len(repo_dict)) # print(str(sum(repo_dict.values()))) # exit(42) records = [] for a in range(number_of_days):...
def print_console(*argv): if verbose_mode: uniq = "" for arg in argv: uniq += str(arg) + " " uniq = uniq[:-1] print(uniq) def get_ip_address(ifname): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) return socket.inet_ntoa(fcntl.ioctl( s.fileno(), ...
The code registers a user by establishing an SSL connection to a server, sending a "REG" message with the user's credentials, and awaiting a response. It validates the server's reply, ensuring correct formatting and success status ("REA") before marking the user as registered. If errors occur, it exits with appropriate...
def registerUser(user,passw): client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) client = ssl.wrap_socket(client, keyfile=user.key, certfile=user.cert) msg = "REG:" + user.name + ":" + passw + ":\n" print_console("--Send message...
def treat_loc(client_address,lat,lon,user): if client_address[0] not in user.others_ips: user.appendIP(client_address[0]) latitude = user.latitude longitude = user.longitude curr_token = user.actualToken dist = calc_distance(latitude,longitude,lat,lon) if dist <= 5: # send TOK ...
The function `treat_message` parses incoming messages by splitting them into components, validates their format, and delegates processing to specific handlers based on the message type (e.g., LOC, TOK, RTOK, COD, CON). It extracts coordinates, tokens, codes, or token lists, performs type checks, and calls corresponding...
def treat_message(msg, client_address, user): # parse message msg_args = msg.split(':') if(msg_args[-1] != '\n'): # wrong formatting - ignore return if(msg_args[0] == 'LOC'): # LOC:<lat>:<lon>:\n o_lat, o_lon = 0, 0 try: assert(len(msg_args) == 4) o_lat ...
def load_censor_coordinates(censorfile): # not great practice, but easy enough to use here global CENSOR_COORDINATES with open(censorfile,'r') as f: reader = csv.reader(f) header = next(reader) lat_index = header.index('latitude') lon_index = header.index('longitude') ...
The main task of the code is to process CSV and GPX files from specified directories by applying censorship (via coordinate filtering) and transferring them to a target directory. It also archives results by copying files to an output directory and zipping them, contingent on user-specified options. The function handle...
def main( censor_search_directories, censor_target_dir, censorfile, censor_string, options, # pretty much everything else... ): #os.chdir(ROOT_DIRECTORY) if censorfile != '': load_censor_coordinates(censorfile) # quick h4ck global CENSOR_STRING CENSOR...
def expand(self, node): if not self.game.checkTerminalState(node.state, node.player)[0]: legal_moves = self.game.validMoves(node.state) for move in legal_moves: new_board = copy.deepcopy(node.state) self.game.playMoveWithCopy(new_board, move, node.player) ...
The code implements a Monte Carlo Tree Search (MCTS) algorithm to determine the best move for a player in a game. It constructs a tree from the given state, expands nodes iteratively, performs playouts to evaluate moves, and selects the most promising action based on the search results. The function returns the best va...
def bestMove(self, state, player): self.root = Node(state, None, None, player) node = self.root if(self.game.checkTerminalState(self.root.state, self.root.player)[0]): return 42 for i in range(5): self.expand(node) if self.game.checkTerminalState(node....
def signup(flag): email = input("Enter email address: ") pwd = input("Enter password: ") confirm_pwd = input("Confirm password: ") if confirm_pwd == pwd: enc = confirm_pwd.encode() hash1 = hashlib.md5(enc).hexdigest() with open("credentials.txt", "w...
The code implements a train company data management system with a terminal menu for entering/viewing/updating/deleting employee, train, passenger, service, and delay data. It includes user authentication via signup/login, a loop for persistent menu access, and table-specific operations based on user selections, exiting...
def main(): options = ["Enter Employee Data", "Enter Train Data", "Enter Passenger Data", "Enter Service Data", "Enter Delay Data", "View Table Data", "Update Data", "Delete Data", "Exit"] terminal_menu = TerminalMenu(options) flag = 0 while 1: print("------------Train Company System--------...
def load_api_key(path): with open(path, "r") as key_file: return key_file.read().strip() def load_data(path): """Load data from a csv file.""" return pd.read_csv(path) def process_responses(df, engine, prompt_dict): """Get responses from GPT model for each row in the DataFrame.""" for prompt...
The main task of the code is to process resume data using GPT-3.5-turbo by loading an API key, sampling labeled resumes (passed/failed), generating responses via specified prompts, and saving the processed data to a CSV file.
def main(input_file, output_file, prompt_dict, n=None): # Load API key openai.api_key = load_api_key("../../key/key.txt") # Load and process data df = load_data(f"../data/{input_file}.csv") if n: passed_resumes = df[df['Label'] == 1].sample(n) failed_resumes = df[df['Label'] == 0].sa...
def conv2d(x, num_filters, stride=1, filter_size=3, pad='SAME', nonlinearity=_actv_func, init_scale=1., init=init_pass, use_weight_normalization=True, use_batch_normalization=False, mean_only_norm=False, deterministic=False, slope=0.01): filter_size = [filter_size,...
This code implements a neural network with convolutional and deconvolutional layers for feature processing. It combines input and optional mask, applies a 1x1 convolution, then uses stacked convolutions/deconvolutions with residual connections (if enabled) and Xception blocks. The network upscales features through deco...
def network_in_network(input, nin_features_out, mask=None): if use_mask: concatenation = tf.concat(values=[input, mask], axis=concat_axis) else: concatenation = input with tf.variable_scope("Inner"): nin = conv2d(concatenation, 64, 1...
def xception_encoding_block_diff(input, features_start, features_end): cnn = conv_block( input=input, filters=features_start) cnn = conv_block( input=cnn, filters=features_start) cnn = strided_conv_block( ...
The code processes an input through a series of Xception-style encoding and middle blocks, appending intermediate outputs to a list. It first applies two encoding blocks with feature maps, then an encoding block, followed by four middle blocks. The final output and all intermediate layers are returned, likely for featu...
def shared_flow(input, layers): shared = xception_encoding_block_diff(input, features2, features3) layers.append(shared) shared = xception_encoding_block_diff(shared, features3, features4) layers.append(shared) shared = xception_encoding_block(shared...
def reset_tree(self): self.N_belief_updates = 1 self.adversarial_belief = np.array(self.orig_belief) self.adv_mixed_strategy = np.array(self.orig_belief) self.Wh = {} self.Wha = {} self.Qha = {} self.model_values = np.zeros(self.n_mdps) self.model_counts ...
This code implements a Monte Carlo Tree Search (MCTS) algorithm for a multi-agent or multi-Environment setting. It simulates game outcomes across multiple Markov Decision Processes (MDPs), updates value estimates using running averages, and tracks adversarial beliefs and agent strategies. The main task is to iterativel...
def MCTS(self, s): # reset tree from previous computation? self.adv_dists = [] self.adv_brs = [] self.adv_avg = [] self.agent_est_value = [] self.agent_Q_vals = [] self.adv_est_value = [] self.model_value_history = [] self.reset_tree() fo...
def process_action(self,player_index, action): if action == 0: # Advance self.advance(player_index) elif action == 1: #Retreat self.retreat(player_index) elif action == 2: #Rush self.rush(player_index) elif action == 3: #Boom...
The code's main task is to execute a given action in a game environment, update the game state, check for win/loss conditions, calculate rewards based on power changes and win status, and return observations, rewards, termination status, and additional info. It processes the action, simulates the opponent's move, evalu...
def step(self, action): # This game will not be truncated so it is always False # Return value: observation, reward, terminated, truncated, info. The last item "info" can be a dictionary containing additional information from the environment, such as debugging data or specific metrics. print(f"{...
def animate(m, duration = .05): #print(chr(27) + "[2J") os.system('cls' if os.name == 'nt' else 'clear') m.printGui() time.sleep(duration) def obviousFlags(board): flags = [] for y in range(m.height): for x in range(m.width): if board[y][x] != Minesweeper.ground_symbol \ ...
The code solves a Minesweeper game by iteratively uncovering cells and flagging obvious mines using board state analysis. It alternates between uncovering safe cells, marking obvious mines, and applying logic-based uncovering when no obvious moves remain, with optional animation for visualization.
def solve(m = Minesweeper(10,10,10), anim = False): uncoverNext = [[0,0]] while (len(uncoverNext) > 0 and not m.won and not m.lost): for coord in uncoverNext: if (anim): animate(m) m.uncover(coord[0], coord[1]) cop = m.getBoardState() ...
def irt(data, val_data, lr, iterations): """ Train IRT model. You may optionally replace the function arguments to receive a matrix. :param data: A dictionary {user_id: list, question_id: list, is_correct: list} :param val_data: A dictionary {user_id: list, question_id: list, is_correct: list} ...
The code implements an Item Response Theory (IRT) model, tuning hyperparameters (learning rate and iterations) to optimize model performance. It evaluates the model's accuracy on validation and test datasets, plots training/validation likelihoods across iterations, and visualizes probability curves for specific questio...
def main(): train_data = load_train_csv("../data") # You may optionally use the sparse matrix. sparse_matrix = load_train_sparse("../data") val_data = load_valid_csv("../data") test_data = load_public_test_csv("../data") ##################################################################### ...
def resize(self, width=0, height=0): width = width if width > self.min_w else self.min_w height = height if height > self.min_h else self.min_h self.u.resize(width, height) def num_to_macos(self,macos_num,for_url=True): if for_url: # Resolve 8-5 to their names and show Big Sur as 10.16 ...
The main task of the code is to display the current catalog, maximum macOS version, and a generated URL, then prompt the user to press [enter] to return. It resizes the interface, prints formatted information, constructs a URL, and waits for user input before exiting.
def show_catalog_url(self): self.resize() self.u.head() print("") print("Current Catalog: {}".format(self.current_catalog)) print("Max macOS Version: {}".format(self.num_to_macos(self.current_macos,for_url=False))) print("") print("{}".format(self.build_url())) ...
def resize(self, width=0, height=0): width = width if width > self.min_w else self.min_w height = height if height > self.min_h else self.min_h self.u.resize(width, height) def get_catalog_data(self, local = False): # Gets the data based on our current_catalog url = self.build_ur...
This method resizes the interface, checks for catalog data availability, handles errors if the catalog is unreachable or files are missing, prompts user action for errors, then parses product data from installers into a dictionary. It ensures proper error handling and user feedback during catalog processing.
def set_prods(self): self.resize() if not self.get_catalog_data(self.save_local): self.u.head("Catalog Data Error") print("") print("The currently selected catalog ({}) was not reachable".format(self.current_catalog)) if self.save_local: pr...
def resize(self, width=0, height=0): width = width if width > self.min_w else self.min_w height = height if height > self.min_h else self.min_h self.u.resize(width, height) def save_settings(self): # Ensure we're using the latest values for setting in self.settings_to_save: ...
The main task of the code is to present a menu allowing users to select a catalog from a list, handle navigation back to the main menu or quitting, validate user input, and load the selected catalog data. It ensures proper input handling by recursively prompting until a valid choice is made, then updates the current ca...
def pick_catalog(self): self.resize() self.u.head("Select SU Catalog") print("") count = 0 for x in self.catalog_suffix: count += 1 print("{}. {}".format(count, x)) print("") print("M. Main Menu") print("Q. Quit") print("") ...
def resize(self, width=0, height=0): width = width if width > self.min_w else self.min_w height = height if height > self.min_h else self.min_h self.u.resize(width, height) def num_to_macos(self,macos_num,for_url=True): if for_url: # Resolve 8-5 to their names and show Big Sur as 10.16 ...
The main task of the code is to allow users to select a maximum macOS version for a catalog URL. It displays the current version, provides menu options (Main Menu/Quit), validates user input, converts the input to a numerical format, updates the current macOS version setting, saves the configuration, and retrieves cata...
def pick_macos(self): self.resize() self.u.head("Select Max macOS Version") print("") print("Currently set to {}".format(self.num_to_macos(self.current_macos,for_url=False))) print("") print("M. Main Menu") print("Q. Quit") print("") print("Please ...
def num_to_macos(self,macos_num,for_url=True): if for_url: # Resolve 8-5 to their names and show Big Sur as 10.16 return self.mac_os_names_url.get(str(macos_num),"10.{}".format(macos_num)) if macos_num <= 16 else str(macos_num-5) # Return 10.xx for anything Catalina and lower, otherwise 11+ ...
This code displays a menu of available macOS installers, formats product details, and handles user selections for managing downloads, settings, and system updates. It presents options to change macOS versions, catalogs, toggle features, and execute commands like clearing or setting SoftwareUpdate catalogs. User input t...
def main(self, dmg = False): lines = [""] lines.append("Available Products:") lines.append(" ") if not len(self.mac_prods): lines.append("No installers in catalog!") lines.append(" ") for num,p in enumerate(self.mac_prods,start=1): var1 = "{}. ...
def check_dd(self): # Checks if ddrelease64.exe exists in our Scripts dir # and if not - downloads it # # Returns True if exists/downloaded successfully # or False if issues. # Check for dd.exe in the current dir if os.path.exists(os.path.join(self.s_path, self.dd...
The main task of this code is to check system requirements, list removable disks with details, and allow user interaction to select a disk for operations like formatting, partition flag adjustments, or installing boot managers (OpenCore/Clover) based on specified options. It ensures proper tool installation, warns abou...
def main(self): # Start out with our cd in the right spot. os.chdir(os.path.dirname(os.path.realpath(__file__))) # Let's make sure we have the required files needed self.u.head("Checking Required Tools") print("") if not self.check_dd(): print("Couldn't find o...
def good_moves(tubes): for s, st in enumerate(tubes): if not good_source(st): continue for t, tt in enumerate(tubes): if t == s: continue if good_move(st, tt): yield (s,top_chunk(st),t) def make_move(tubes, s, chunk, t): c,out = chunk while out > 0: tubes[t].append(tubes[s]...
This function uses recursive backtracking to solve a puzzle by iterating through valid moves, applying each move, and checking if the puzzle is solved. If not, it recursively attempts further moves. If a solution path is found, it returns True; otherwise, it undoes the move and continues searching. The process tracks a...
def help_solve(tubes, moves): for move in good_moves(tubes): make_move(tubes, *move) moves.append((move, copy_tubes(tubes))) if is_solved(tubes): return True elif help_solve(tubes, moves): return True else: moves.pop() undo_move(tubes, *move) return False
def is_solved(tubes): for tube in tubes: if len(tube) > 0: if len(tube) < COLOUR_VOLUME: return False c = tube[0] for oc in tube: if oc != c: return False return True def help_solve(tubes, moves): for move in good_moves(tubes): make_move(tubes, *move) mov...
The code's main task is to determine the sequence of moves required to solve a puzzle involving tubes (likely a variant of the Tower of Hanoi). It checks if the tubes are already solved; if not, it uses `help_solve` to generate moves. The function returns a tuple containing the list of moves and a boolean indicating su...
def solve(tubes): moves = [] success = True if not is_solved(tubes): success = help_solve(copy_tubes(tubes),moves) return (moves, success)
def read_csv(filename: str) -> DataFrame: """Reads the csv file into a pandas DataFrame :param filename: str. :return: a pandas DataFrame. """ df = pd.read_csv(filename) return df def clean_data(df: DataFrame) -> DataFrame: """Cleans the raw data and turn all columns into numerical values. ...
The code trains a neural network on heart disease prediction using normalized data, splits into train/test sets, performs training with Adam optimizer and BCE loss, evaluates accuracy, and plots training/test loss curves. It handles data preprocessing, model training, validation, and result visualization for a given ne...
def main(network: nn.Module, index: int): train_df = read_csv('data/heart_disease_data/heart_train_718.csv') test_df = read_csv('data/heart_disease_data/heart_test_200.csv') print(train_df.shape, test_df.shape) # combine the training and test set to prepare for data normalization combined_df = pd.c...
def match_density_to_bathymetry(density_src, bathy, bathy_xj, bathy_yi): """ Match the density field shape to the bathymetry field shape. Useful for when the density array is of lower resolution and needs to be interpolated to match the shape of the bathymetry value matrix. :param density_src...
This function calculates a gravity anomaly from bathymetry and density data, using specified interpolation depth, window size, and resolution. It reads input files, processes spatial data, computes anomaly values via a local sweep method, and outputs the result as a raster file. Parameters are optionally recorded for r...
def derive_anomaly_field(bathymetry_file_path, anomaly_file_path, density_file_path, interpolation_depth, target_window_size, target_resolution, record_parameters=True): """ Derive the gravity anomaly file directly from and to files in the filesystem. For more details on how the gravity anomaly is calculate...
def seperate_receptor_and_ligand(pdb): target_name = pdb[0] pdb_name = pdb[1] mol = pdb[2] receptor = [] ligand = [] connect = [] for i in range(3,len(pdb)): if pdb[i][0] == 'ATOM': receptor.append(pdb[i]) if pdb[i][0] == 'HETATM': ligand.append(pdb[i]...
The code processes a list of PDB files to identify and split ligand molecules into scaffold-decoration fragment pairs based on their binding proximity to a predefined hinge region centroid. It checks receptor-ligand atom distances, fragments ligands meeting geometric criteria, and logs errors. The main task is to gener...
def split_ligand_in_hinge_binding_loc(pdbs): with open('error_hinge.txt', 'w') as out_file: centroid = [-3.134,21.976,47.086] scaffold_decoration_pairs = [] num = len(pdbs) pc = 1 for pdb in pdbs: ac = [] pairs = [] state = False ...
def seperate_receptor_and_ligand(pdb): target_name = pdb[0] pdb_name = pdb[1] mol = pdb[2] receptor = [] ligand = [] connect = [] for i in range(3,len(pdb)): if pdb[i][0] == 'ATOM': receptor.append(pdb[i]) if pdb[i][0] == 'HETATM': ligand.append(pdb[i]...
The code processes a list of PDB files to identify and fragment interactions between ligand and receptor atoms within 3.5 Å. It separates ligand fragments, converts them to SMILES, and pairs them with receptor amino acids, filtering valid interactions. Errors are logged, and duplicates are removed. The main task is to ...
def merge_fragment_amino_acid_pairs_hd(pdbs): with open('error_hd.txt', 'w') as out_file: fragment_amino_acid_pairs = [] num = len(pdbs) i = 1 for pdb in pdbs: state = False pairs = [] target_name,pdb_name,receptor,ligand,connect,mol = seperate_re...
def check_bn(model): flag = [False] model.apply(lambda module: _check_bn(module, flag)) return flag[0] def _get_momenta(module, momenta): if isbatchnorm(module): momenta[module] = module.momentum def _set_momenta(module, momenta): if isbatchnorm(module): module.momentum = momenta[mod...
This function updates Batch Normalization (BN) layers' momentum parameters in a neural network model using data from a loader. It calculates adaptive momentum values based on batch sizes, adjusts BN layers' momentum accordingly, and re-applies these values post-training to ensure accurate normalization during subsequen...
def update_bn(loader, model, **kwargs): if not check_bn(model): return model.train() momenta = {} model.apply(reset_bn) model.apply(lambda module: _get_momenta(module, momenta)) num_samples = 0 for input, _ in loader: input = input.cuda(device=None, non_blocking=False) ...
def item_example_emb(row, category_name): title = row.title description = row.description brand = row.brand price = row.price rank = row.rank_scaled url_high_res = row.image_url_high_res image_count = row.image_count image_shape = 0 if image_count != 0: image_path_high_res ...
The code processes a pandas DataFrame by generating TF Example features based on the specified model type (emb/bert/conv/union). It normalizes key fields like price, image shape, and count, then converts each example's attributes into appropriate TensorFlow features (int64/float) for machine learning input.
def process_df(df, tokenizer, category_name, model=model): """ Takes pandas dataframe and returns list of Examples """ examples = [] for i in range(df.shape[0]): row = df.iloc[i] if model == "emb": examples.append(item_example_emb(row, category_name)) if model ==...
def get_arguments(): parser=argparse.ArgumentParser(HELP_MSG) parser.add_argument('-t', required=True, default=None,dest='http_template',help='<URLTEMPLATE>') parser.add_argument('-l', required=False, default=None,dest='http_length',help='<MAXURLLENGTH>') parser.add_argument('-a', required=False, defaul...
The code's main task is to generate and test numerous HTTP URL variations based on templates, using a dictionary of words and character sets. It employs multiprocessing to concurrently scan directories and test permutations of placeholders (e.g., `$`, `?`, `[a-z]`) in URLs. The script processes command-line arguments, ...
def main(dirCounter): global DEBUGFLAG HEADERS= {'User-Agent':'Mozilla/5.0 (X11; U; Linux i686) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.140 Safari/537.36'} queue=Queue() chrStr="5wgh47vkzsy5dfvcw2y9qkzo46acpnbl" masks_list=[] wildcharlist=[] stringlist=[] all_http_results=[] supercharlist=[] h...
def get_game_state(self): """ Returns th game state. ('UNFINISHED', 'RED_WON', or 'BLUE_WON'). """ return self._game_state def move(self, pos): """ Moves selected piece to desired location if it passes all game rules/logic and is valid. """ if self._select...
The code determines if a game piece can be selected based on the current game state, allowing reselection of a different piece if already selected. It checks if the piece is valid (correct team, not empty), selects it if valid, and updates valid moves. Returns True on successful selection, False otherwise.
def select(self, pos): """ Return True or False depending on if a piece is currently selected. """ # is game already over? if self.get_game_state() != 'UNFINISHED': return False # if a piece is currenlt selected, allows the option to select a different piece...
def get_general_obj_and_pos(self, player): """ Returns a tuple containing the General GamePiece Object for the given player ('red' or 'blue') and the General GamePiece's current position. """ if player == 'red': team = 0 else: team = 1 bo...
Your return The code identifies valid moves for a player to escape check by either moving their general to a safe position, capturing attacking opponent pieces, or blocking their paths. It filters general moves, checks for future threats, and handles specific blocking logic for pieces like Horse, Elephant, Chariot, a...
def get_valid_moves_to_uncheck_self(self, player, opponent): """ If in check, returns a dictionary of moves that are valid to uncheck (if any). """ valid_moves_to_uncheck_self = {} player_gen_obj, player_gen_pos = self.get_general_obj_and_pos(player) # can the pl...
def get_space_contents(self, pos): """ Returns the GamePiece object or '---' string (indicating empty position) present at the specified position. """ col, row = pos return self._board[row][col] def is_in_check(self, player): """ Returns True if the player passed ...
The function `make_move` validates and executes a player's piece movement, checking if the move is legal (e.g., correct team, no invalid positions, not exposing the general to check). It handles piece capture, updates the board, and checks for checkmate. Returns `True` on valid moves; `False` otherwise. It ensures the ...
def make_move(self, move_from, move_to): """ Moves a player piece from 'move_from' to 'move_to'. If move is invalid (square being moved from doesn't contain a piece belonging to the player whose turn it is, or if the indicated move is not legal, or if the game has already been won) it returns F...
def is_in_check(self, player): """ Returns True if the player passed as argument is in check. Returns False otherwise. """ if player == 'red': opponent = 'blue' else: opponent = 'red' gen_obj, gen_pos = self.get_general_obj_and_pos(pla...
This function determines valid moves for a game piece, ensuring they don't expose the player's general to check. If the player is in check, it filters moves that resolve the check. Otherwise, it validates moves by checking if they would leave the general vulnerable, returning only safe moves for rendering on the game i...
def get_valid_moves(self, game_piece): """ Returns a list of valid moves for the given game piece (Used for rendering valid moves on screen) """ valid_moves = [] if game_piece.get_team() == 'r': player = 'red' opponent = 'blue' else: p...
def settings_read(config_path): """ Read application settings from INI file """ num_params = ["job_exec_time"] app_settings = config_read(config_path, num_params=num_params) app_settings = app_settings[0] return app_settings def splash_screen(): """ Show splash screen along with a ...
The main task of the code is to process Twitter data configurations via a command-line interface, either in single-file or batch mode. It reads settings, validates configurations, executes data retrieval using `tweet_manager_core`, manages progress tracking, and merges output JSON files. The script handles user input, ...
def main(): """Main program""" settings_path = "settings.ini" OUTPUT_PATH = "outputs" OUTPUT_FILENAME = f"{datetime.datetime.now().strftime('%m-%d-%Y')}-merged.json" app_settings = settings_read(settings_path) splash_screen() # Get config path from arguments all_args = sys.argv[1:] ...
def __roster_menu(self) -> str: """ __roster_menu uses the Inquirer library to create an interactive menu. Returns: str: indicates the player's menu selection. """ title = "Select a profile. Press ENTER to confirm" if self.__selected_player: name ...
The main task of the code is to display a roster menu for managing player profiles, allowing users to create/delete profiles, select a profile for gameplay, or exit. It returns the name of the selected player profile after processing user input through a loop that updates the interface and handles selections accordingl...
def show_roster_menu(self) -> str: """ show_roster_menu displays the roster menu to the terminal Based on user selection, this method can create/delete player profiles, select a profile for gameplay, and/or exit the roster menu. Returns: str: Name of selected player...
def percentage_of_complex_words_fun(self): if(self.complex_count == None): self.complex_count_fun() return self.percentage_of_complex_words_fun() elif(self.tokens == None): self.calculate_polarity_score(self.text_path) return self.percentage_of_complex_wor...
The code calculates the Fog Index, a readability metric, by combining the percentage of complex words and average sentence length. It ensures both values are computed before applying the formula: 0.4 × (percentage_of_complex_words + average_sentence_length).
def fog_index(self): if (self.percentage_of_complex_words == None): self.percentage_of_complex_words_fun() return self.fog_index() elif(self.average_sentence_length==None): self.average_sentence_length_fun() return self.fog_index() else: ...
def parse_xml_index_partial_harmonyV6(xml): # navigate to the part which has image size and resolution of each pixel, take the values from the first channel tag_Maps = xml.find('Maps')[2][0] x_resol = round(float(tag_Maps.find('ImageResolutionX').text), 23) y_resol = round(float(tag_Maps.find('ImageReso...
The code parses an XML file containing microscopy data, handling version-specific formats (V5/V6) to extract and process metadata. It cleans the XML, extracts structured data, renames columns, sorts entries, generates image identifiers, computes well IDs, and reorganizes the DataFrame for analysis, returning the proces...
def parse_xml_index(xml_path, opera_harmony_version="V5"): with open(xml_path, 'r', encoding='utf-8') as f: xml_file = f.read() f.close() xml_file = re.sub(r'xmlns="http://www.perkinelmer.com/PEHH/HarmonyV\d"', '', xml_file) xml = ET.fromstring(xml_file) if opera_harmony_version ==...
def _find_account_uri(self, username=None, acct_id=None): """ Get specified user information :param username: user name :param acct_id: user id :return: dict """ # Need to specify username or user id if not any((username, acct_id)): return {'re...
The code adds a user to a system by validating the provided username, checking if it already exists, preparing a payload with user details, and making API requests to create the user if the username is unique. It returns a status indicating success, failure, or if no changes were needed.
def add_user(self, user): """ Add user :param user: new user profile :return: dict """ if not user.get('account_username'): return {'ret': False, 'msg': 'Must provide account_username for AddUser command'} response = self._find_acc...
def _find_account_uri(self, username=None, acct_id=None): """ Get specified user information :param username: user name :param acct_id: user id :return: dict """ # Need to specify username or user id if not any((username, acct_id)): return {'re...
The main task of the code is to enable a user account by checking if it's already enabled, and if not, sending a PATCH request to update its status to enabled using the provided user information. It returns a response indicating success or failure, along with whether the account was modified.
def enable_user(self, user): """ Enable user :param user: user Info :return: dict """ response = self._find_account_uri( username=user.get('account_username'), acct_id=user.get('account_id')) if not response['ret']: return respo...
def _find_account_uri(self, username=None, acct_id=None): """ Get specified user information :param username: user name :param acct_id: user id :return: dict """ # Need to specify username or user id if not any((username, acct_id)): return {'re...
The main task of the code is to disable a user's account by locating their account URI, checking if they are already disabled, and if not, sending a PATCH request to set their status to "False". It returns success/failure responses and avoids redundant changes if the account is already disabled.
def disable_user(self, user): """ Disable user :param user: user Info :return: dict """ response = self._find_account_uri( username=user.get('account_username'), acct_id=user.get('account_id')) if not response['ret']: return res...
def _find_account_uri(self, username=None, acct_id=None): """ Get specified user information :param username: user name :param acct_id: user id :return: dict """ # Need to specify username or user id if not any((username, acct_id)): return {'re...
The code updates a user's role in an account by checking if a new role ID differs from the current one, constructing a PATCH request payload, and sending it to the appropriate URI if changes are needed. It returns success/failure status and whether changes were made.
def update_user_role(self, user): """ Modify user role groups :param user: user Info :return: dict """ if not user.get('account_roleid'): return {'ret': False, 'msg': 'Must provide account_roleid for UpdateUserRole command'} respon...
def _find_account_uri(self, username=None, acct_id=None): """ Get specified user information :param username: user name :param acct_id: user id :return: dict """ # Need to specify username or user id if not any((username, acct_id)): return {'re...
The main task of the code is to update a user's password by retrieving the account URI, constructing a request payload with the new password, and sending a PATCH request. It returns a success response if the update is successful or an error response if any step fails.
def update_user_password(self, user): """ Modify user password :param user: user Info :return: dict """ response = self._find_account_uri( username=user.get('account_username'), acct_id=user.get('account_id')) if not response['ret']: ...
def _find_account_uri(self, username=None, acct_id=None): """ Get specified user information :param username: user name :param acct_id: user id :return: dict """ # Need to specify username or user id if not any((username, acct_id)): return {'re...
This function updates a user's name by sending a PATCH request to the appropriate URI after validating input parameters. It checks if the new name differs from the existing one, constructs the payload, removes the password, and returns a success/failure response.
def update_user_name(self, user): """ Modify user name :param user: user Info :return: dict """ if not user.get('account_updatename'): return { 'ret': False, 'msg': 'Must provide account_updatename ' 'for ...
def get_manager_ethernet_uri(self): """ Get EthernetInterfaces uri :return: dict """ response = self.get_request(self.root_uri + self.manager_uri) if not response['ret']: return response data = response['data'] if 'EthernetInterfaces' not in da...
The code configures IPv4 settings for a network interface by validating input parameters, retrieving Ethernet interface details, comparing existing and new IPv4 configurations, and applying changes via a PATCH request if differences are detected. It ensures proper net_id validation, handles DHCP/static configurations, ...
def set_ipv4(self, info): """ Set IPv4 :param info: ipv4 config info :return: dict """ if not info.get('net_id'): return {'ret': False, 'msg': 'Must provide net_id for SetIPv4 command'} ethernet_resp = self.get_manager_ethernet_uri(...
def get_manager_ethernet_uri(self): """ Get EthernetInterfaces uri :return: dict """ response = self.get_request(self.root_uri + self.manager_uri) if not response['ret']: return response data = response['data'] if 'EthernetInterfaces' not in da...
The main task of the code is to configure IPv6 settings on a network interface by validating input parameters, constructing appropriate API payloads, and sending a PATCH request to an Ethernet management URI. It supports both DHCPv6 and static IPv6 configurations, ensuring required fields like `net_id` are provided, an...
def set_ipv6(self, info): """ Set IPv6 :param info: ipv6 config info :return: dict """ if not info.get('net_id'): return {'ret': False, 'msg': 'Must provide net_id for SetIPv6 command'} ethernet_resp = self.get_manager_ethernet_uri(...
def get_health_resource(self, subsystem, uri, health, expanded): """ Get health resource information :param subsystem: Subsystem :param uri: uri :param health: health report :param expanded: expaned info :return: """ status = 'Status' if e...
The main task of the code is to recursively gather and compile health information for a specified subsystem by processing data structures (lists/dicts) containing '@odata.id' references. It expands resources, navigates member collections, and aggregates health details into a report through recursive calls to `get_healt...
def get_health_subsystem(self, subsystem, data, health): """ Get Subsystem Health Report :param subsystem: Subsystem :param data: resp :param health: health report :return: dict """ if subsystem in data: sub = data.get(subsystem) if...
def calc_rings(Configuration,size_in_beams = 0., ring_size = 0.,debug=False): if ring_size == 0.: ring_size = Configuration['RING_SIZE'] if size_in_beams == 0.: size_in_beams = Configuration['SIZE_IN_BEAMS'] if debug: print_log(f'''CALC_RINGS: Calculating the number of rings in the ...
The function `set_ring_size` adjusts the ring size and beam size in a configuration to ensure a sufficient number of rings for a reliable fit. It reduces the ring size iteratively if the initial number of rings is below the minimum threshold, then increases the beam size if needed. It updates the configuration paramete...
def set_ring_size(Configuration, debug = False, size_in_beams = 0., check_set_rings = True): if size_in_beams == 0.: check_set_rings = False size_in_beams = Configuration['SIZE_IN_BEAMS'] ring_size = Configuration['RING_SIZE'] no_rings = calc_rings(Configuration,ring_size=ring_size,size_in...
def print_log(log_statement,log, screen = False,debug = False): log_statement = f"{linenumber(debug=debug)}{log_statement}" if screen or not log: print(log_statement) if log: with open(log,'a') as log_file: log_file.write(log_statement) def columndensity(levels,systemic = 100.,be...
The function calculates the number of inner rings to fix by analyzing column density thresholds from SBR data, adjusts indices based on density values, and returns a range of ring limits using configuration parameters. It uses debug logging, computes averaged SBR values, filters column densities, and determines ring bo...
def get_inner_fix(Configuration,Tirific_Template, debug =False): if debug: print_log(f'''GET_INNER_FIX: Attempting to get the inner rings to be fixed. ''',Configuration['OUTPUTLOG'], debug = debug, screen = True) sbr_av = np.array([(float(x)+float(y))/2. for x,y in zip(Tirific_Template['SBR'].split(),T...
def set_rings(Configuration,ring_size = 0.,size_in_beams = 0. , debug = False): if ring_size == 0.: ring_size = Configuration['RING_SIZE'] if size_in_beams == 0.: size_in_beams = Configuration['SIZE_IN_BEAMS'] if debug: print_log(f'''SET_RINGS: Starting with the following parameters....
The function computes signal-to-background ratio (SBR) limits for ring areas using input parameters like noise levels, beam size, and modifiers. It calculates ring areas, applies a formula involving beam solid angle and noise, adjusts with configuration modifiers, and returns radii and SBR limits for each ring.
def sbr_limits(Configuration,hdr, systemic= 100. , debug = False): radii = set_rings(Configuration,debug=debug) if debug: print_log(f'''SBR_LIMITS: Got {len(radii)} radii ''',Configuration['OUTPUTLOG'], debug=debug,screen =True) level = hdr['FATNOISE']*1000 bm = [hdr['BMAJ']*3600.,hdr['BMIN']*36...
def residue1(x, ie,dettf,caa,icaa,cbb,icbb,f,co,ico): upm = mp.matrix(4,4) upm[0,0] = dettf[0,0,ie] upm[1,0] = dettf[1,0,ie] upm[2,0] = dettf[2,0,ie] upm[3,0] = dettf[3,0,ie] upm[0,1] = dettf[0,1,ie] upm[1,1] = dettf[1,1,ie] upm[2,1] = dettf[2,1,ie] upm[3,1] = dettf[3,1,ie] upm[...
The code computes eigenfunctions by iterating over a matrix and assigning values based on the parameter `n`, which determines the specific residue calculation method (residue1–residue4) applied to each element. It constructs a matrix `eigenf` of size `(ico-1)x1` using input parameters and returns the computed values.
def eigenfunctions(xx,ico,n,dettf,caa,icaa,cbb,icbb,f,co): eigenf = mp.matrix(int(ico-1),1) if n == 1: for i in range(ico-1): eigenf[i] = residue1(xx[i], i,dettf,caa,icaa,cbb,icbb,f,co,ico) elif n == 2: for i in range(ico-1): eigenf[i] = residue2(xx[i], i,dettf,caa,i...
def get_match_detail(match_id, region): match_detail = None try: logger.info(f"[RIOT API] Getting match detail for {match_id}") match_detail = watcher.match.by_id(region, match_id) except ApiError as e: print(f"[ApiError] {e}") pass return match_detail def get_match_met...
The code retrieves a League of Legends summoner's match history from the 2023 season using the Riot API, paginating through up to 100 matches per request. It processes each match to extract metadata and details, creates corresponding database records, and links them to the summoner's match history.
def get_summoner_matches(summoner, region): all_matches = [] summoner = Summoner.objects.get(puuid=summoner["puuid"]) season_2023 = int(datetime.datetime(2023, 1, 10).timestamp()) logger.info(f"[RIOT API] Getting match history for {summoner.name}") matches = watcher.match.matchlist_by_puuid( ...
def update_brightness_slider(value): global brightness_slider brightness_slider.blockSignals(True) brightness_slider.setValue(int(value * 100)) brightness_slider.blockSignals(False) def update_contrast_slider(value): global contrast_slider contrast_slider.blockSignals(True) contrast_slider.s...
The main task of the code is to allow users to select a new image file via a dialog, update the application's image path, load the selected image, reset brightness/contrast parameters to default values (1.0), enable initial state buttons, and refresh the UI with the new image and default adjustments.
def change_image_path(): global path, original_image, modified_image, backup_image, initial_brightness_factor, initial_contrast_factor file_dialog = QFileDialog() new_path, _ = file_dialog.getOpenFileName(None, "Open Image", "", "Image Files (*.png *.jpg *.jpeg *.bmp *.gif)") if new_path: path =...
def update_brightness(value): global brightness_factor brightness_factor = max(value, 0.01) apply_brightness_contrast() def update_contrast(value): global contrast_factor contrast_factor = value apply_brightness_contrast() def update_image_label(): img = modified_image.copy() if modified_ima...
The code defines a main function for a photo editor GUI application using PyQt. It initializes a window with buttons for image rotation, grayscale conversion, undo, upload, and export, along with sliders for brightness and contrast adjustments. The interface displays the edited image in a label, linking user interactio...
def main(): global image_label, original_image, modified_image, backup_image, \ initial_state_button, brightness_slider, contrast_slider app = QApplication(sys.argv) window = QMainWindow() window.setWindowTitle("Photo Editor") window.setGeometry(100, 100, 400, 500) # Create buttons ...
def log_post(msg): """ Post a message to the CASA logger and logfile. """ casalog.post(msg, 'INFO', 'bsvoboda') def test_clean_line_mosaic(spw, ext=None, startmodel=None): """ Clean-line function for the G285 field, which overlaps at the half-power radius, so particular parameters are select...
This function processes spectral line cleaning for multiple targets and spectral windows. If `just_ammonia` is True, it limits processing to ammonia-specific lines (SPWS 'nh3_11' and 'nh3_22'). For each target and selected SPW, it logs progress and executes cleaning routines: `test_clean_line_mosaic` for the 'G285_mosa...
def clean_all_lines(just_ammonia=False): if just_ammonia: spws = [SPWS['nh3_11'], SPWS['nh3_22']] else: spws = SPWS.values() for ii, targ in enumerate(TARGETS.values()): for jj, spw in enumerate(spws): log_post(':: {0} -- {1}'.format(targ.name, spw.name)) log_...
def init_cube_imager(params): """ Initialize the Imager module and create a dirty map to use as the first residual. Parameters ---------- params : imagerhelpers.input_parameters.ImagerParameters Returns ------- imager : imagerhelpers.imager_base.PySynthesisImager """ log_po...
This function performs joint image reconstruction by combining single-dish (SD) and interferometric data using specified methods ('iterf' or 'stanim'). It initializes an imager, aligns PSFs, iteratively merges SD data with interferometric residuals, updates masks, and converges to a final image. The process restores an...
def do_reconstruct(params, sdimage=SD_IMG, method='iterf'): """ Do joint image reconstruction with single-dish and interferometric data. This function uses the PySynthesisImager refactored tclean API and takes a ImagerParameters instance. Two methods are implemented for methods of "combine during de...
def sphere_init_config(fovea_radius = 0.3,lens_depth = 0.3,num_pts = 100,inner_rad = 0.8,outer_rad = 1.2,prune_into_eye = True,bounding_box = None): sample = [] while(len(sample) < num_pts): pt = np.random.normal(size = 3) pt /= np.linalg.norm(pt) pt_rad = np.random.rand()*(outer_rad-in...
This function simulates vascular network growth by iteratively extending from initial points toward auxin nodes, guided by proximity and geometric constraints. It initializes or uses provided vascular structures, samples auxin points, computes nearest neighbors, and grows new vascular points while pruning auxin nodes o...
def vascular_growth_sim(fovea_radius = 0.2,lens_depth = 0.5,max_iter = 1000,init_num_pts = 200,inner_rad = 0.7,outer_rad = 1.2,D_step = 0.9,death_dist = None,init_vasc = None,bounding_box=None): """ if init_vasc is None, then initialize pt_list and vascular structure otherwise, init_vasc = (pt_list ) ""...
def printFunc(*args, **kwargs): pickle.dump("\n", filehandler) pickle.dump(" ".join(map(str, args)), filehandler) print(" ".join(map(str, args))) def find_top_5_friends(twitter_api, user_id): top_friends = [] list_of_tuples = [] followers_nums = [] try: following, followers = get_fri...
The main task of the code is to recursively build a social network graph by adding the top 5 friends of a given Twitter user (parent node) up to a specified depth. It uses the Twitter API to retrieve friends, adds them to the graph, and repeats the process for each new friend, decrementing depth at each level. The func...
def get_recip_friends(twitter_api, parent, depth, graph): if depth > 0: printFunc("Number of Nodes so far:", graph.number_of_nodes()) printFunc("Parent:") printFunc(parent) #find the top 5 friends and assign them to top5 using the parent node's user_id top5 = find_top_5_frie...
def _convert_graph_def(message_dict): """ Convert JSON to TF GraphDef message Args: message_dict: deserialised JSON message Returns: TF GraphDef message """ message_dict = _convert_attr_values(message_dict) return ParseDict(message_dict, tf.compat.v1.GraphDef()) def _convert...
The function converts a TensorFlowJS JSON model into a TensorFlow Graph for inference or saving. It validates the presence of required keys in the model JSON, extracts the model topology and weights manifest, reads weight data from the specified base path, converts the topology to a graph definition, transforms weights...
def _convert_graph_model_to_graph(model_json, base_path): """ Convert TFJS JSON model to TF Graph Args: model_json: JSON dict from TFJS model file base_path: Path to the model file (where to find the model weights) Returns: TF Graph for inference or saving """ if not tfj...
def get_init_for_document(self, document): result, target = self.get_init_for_folder(document.folder) target['children'] = self.build_children(document.folder, activate_slug=None) + [{ 'id': 'doc-' + str(document.id), 'text': unicode(document.name) + ' ' + _('(current)'), ...
This method handles GET requests by checking parameters to fetch document or folder data. If 'init_for_document' is provided, it retrieves a document and returns initialization data. For 'init_for_folder', it fetches a folder and returns folder-specific initialization data. If 'document_slug' is given, it gets folder d...
def get(self, request, *args, **kwargs): if 'init_for_document' in request.GET: document = get_object_or_404(Document.objects.filter(account=get_current_account(self.request)), pk=int(request.GET['init_for_document'])) result, _ = self.get_init_for_document(document) return s...
def __insert(self, node : Node, parent : Node): # Empty tree if self.root.isNIL: self.root = node self.root.isRed = False return # Add node to left if node.value < parent.value: parent.setLeft(node) self.__fixColor(node...
The code's main task is to insert a new node into a tree structure by creating a node with the given value and determining its parent node via a search, then passing both to an internal insertion method to establish the node's position within the tree.
def insert(self, value): self.__insert(self.__node(value), self.__searchParent(value))
def search_element(node, tag, attrib=None, attrib_value=None): """ Find a tag under a specified node and return the value @param node: specify the current node for this search @param tag @param attrib @param attrib_value @return qualified node """ good_node = None # Note that elemen...
The main task of the code is to search for specific XML elements by tag, attribute, and XPath within a given XML tree. It checks for a 'neighbor' element with 'name' attribute 'Malaysia' under the root and its children, logs debug information when found, and retrieves the 'hostility' value. It also uses an XPath to loc...
def search_function_exercise(root): """ Exercises implemented functions on test xml file @param root: root element of the input xml file """ # traverse_tree(root, 0) # Traverse the first level nodes for the target search_tag = 'neighbor' search_attrib = 'name' attrib_value = 'Malay...
def _check_output_dir(self) -> None: if self.output_dir: Path(self.output_dir).mkdir(exist_ok=True) else: self.output_dir = '.' def get_channel_data(channel_url: str) -> tuple: yt_opts = { 'skip_download': True, 'extract_flat': True, 'q...
This function downloads subtitles from a YouTube channel by processing each video entry, either sequentially or via multithreading, saving metadata to a JSON file and logging failed downloads. It handles signal interruption, creates an output directory, and stores results with progress tracking.
def download_channel_subtitles(self, channel_url: str, multithreading: bool = False, **kwargs): signal.signal(signal.SIGINT, self._keyboard_interrupt_handler) self.logger.info(f'Processing channel:...
def save_ckpt(model, epoch, optimizer, save_name): """Save checkpoint""" if isinstance(model, torch.nn.DataParallel): model = model.module torch.save({ 'epoch': epoch, 'optim_state_dict': optimizer.state_dict(), 'model_state_dict': model.state_dict()}, save_name) def tr...
The code trains a facial recognition model (LResNet50E_IR_Sia) with a configurable classifier (MCP/AL/L), using pre-trained weights and fine-tuning specific layers. It loads grayscale or RGB data, sets up data loaders, freezes early layers, defines optimizers with differential learning rates, and performs training/vali...
def main(): # --------------------------------------model---------------------------------------- model = net_sia.LResNet50E_IR_Sia(is_gray=args.is_gray) model_eval = net_sia.LResNet50E_IR_Sia(is_gray=args.is_gray) os.environ['CUDA_VISIBLE_DEVICES'] = args.gpus # 512 is dimension of feature clas...
def walk(self, basedir): """Walk all the directories of basedir except hidden directories :param basedir: string, the directory to walk :returns: generator, same as os.walk """ system_d = SitePackagesDir() filter_system_d = system_d and os.path.commonprefix([system_d, ba...
This function searches for a module file matching 'modname' within the 'basedir' directory. It checks for exact matches, partial name overlaps, and specific prefixes/suffixes defined in 'module_postfixes' and 'module_prefixes'. If found, it returns the full file path; otherwise, it raises an IOError after exhausting al...
def _find_module_path(self, basedir, modname): """find a module matching modname in basedir and return the path to that module :param basedir: string, the base directory to look for the module in :param modname: string, the module name :returns: string, the full path to the found module...
def _find_prefix_path(self, basedir, prefix): """Similar to _find_prefix_paths() but only returns the first match""" ret = "" for ret in self._find_prefix_paths(basedir, prefix): break if not ret: raise IOError("Could not find prefix {} in path {}".format(prefix,...
This function searches for a module file in the specified base directory that matches the given module name. It checks for exact matches, filename prefixes/suffixes, and module-specific naming conventions. If found, it returns the full path; otherwise, it raises an IOError indicating the module was not located.
def DISABLED_find_module_path(self, basedir, modname): """find a module matching modname in basedir and return the path to that module :param basedir: string, the base directory to look for the module in :param modname: string, the module name :returns: string, the full path to the foun...
def _find_prefix_paths(self, basedir, prefix): """the prefix is what comes before the module name (prefix.module_name) so this will only find prefixes, not modules""" ret = basedir modnames = re.split(r"[\.\/]", prefix) seen_paths = set() for root, dirs, files in self.wa...
The main task of the code is to recursively find and yield paths to test modules within a specified base directory. It handles both explicit file paths and searches based on module names, prefixes, and suffixes. The function checks for files matching test conventions (e.g., __init__.py, postfixes, prefixes) and avoids ...
def paths(self): ''' given a basedir, yield all test modules paths recursively found in basedir that are test modules return -- generator ''' module_name = getattr(self, 'module_name', '') module_prefix = getattr(self, 'prefix', '') filepath = getattr(sel...
def delete_relevant_answers(cursor, question_id): for row in get_answers_by_question_id(question_id): delete_answer(row['id']) def get_related_comments(cursor, id_type, id_number): query = sql.SQL('''SELECT * FROM comment WHERE {id_type}={id_number};''') curso...
This function deletes a question from the database by first removing its related answers, then deleting all associated comments, and finally executing a SQL DELETE query to remove the question itself using the provided question_id and database cursor.
def delete_question(cursor, question_id): delete_relevant_answers(question_id) for row in get_related_comments("question_id", question_id): delete_comment_by_id(row['id']) query = ''' DELETE FROM question WHERE id = %s;''' cursor.execute(query, (question_id, ))
def _get_path(self, file_basename: str): """ Produce the file path for a given target file (file_basename expected to be without file extension e.g. "Outcomes" not "Outcomes.csv" Parameters ---------- file_basename: str Returns ------- ...
This function populates the Microbiology table by processing various test results (AsperELISA, AsperPCR, Blood Culture, Beta-Glucan, Respiratory Virus, and Covid19). It uses regex patterns to extract sample types and results from CSV files, applies data transformations, and inserts processed data into the database. Eac...
def _microbiology(self): """ Populate the Microbiology table Returns ------- None """ self.vprint("---- Populating Microbiology Table ----") # AsperELISA ---------------------------- self.vprint("...processing Aspergillus ELISA results") ...
def _patients(self): """ Populate Patients table Returns ------- None """ self.vprint("---- Populating Patients Table ----") self.vprint("...create basic table") df = safe_read(self._get_path("People")) df = df[df.TEST_PATIENT == "N"] ...
The main task of the code is to populate a database by sequentially inserting data into multiple tables (patients, comorbidities, events, pathology, etc.) using private methods. It logs progress with `vprint()` statements and confirms completion. The method orchestrates data population for a structured database, ensuri...
def populate(self): """ Populate all tables. Returns ------- None """ self.vprint("=============== Populating database ===============") self.vprint("\n") self._patients() self._comorbid() self._events() self._pathology() ...
def get_json(info_url, status_url): station_map = {} station_arr = [] r_info = requests.get(info_url).json()['data']['stations'] r_status = requests.get(status_url).json()['data']['stations'] for station in r_info: station_map[station['station_id']] = station for station in r_status: ...
The main task of the code is to generate a record by integrating station information, weather data, and the current timestamp. It retrieves station data from JSON files, generates weather data, populates the record's stations and weather fields, and sets the record's date to the current time in seconds since the epoch.
def gen_record(record): import time stations_data = get_json(STATION_INFORMATION,STATION_STATUS) weather_data = gen_weather_data() gen_stations(record.stations,stations_data) gen_station(record.weather,weather_data) record.date.FromSeconds(int(time.mktime(datetime.now().timetuple())))
def find_start_page(): if os.path.exists(FILE_SETTINGS): try: with open(FILE_SETTINGS) as f: settings_dict = json.loads(f.read()) last_page = settings_dict['last_page'] except: last_page = False else: try: last_page = fi...
The function `datapull()` retrieves data starting from a specified page, saves it to a file, logs execution details (start/end time, duration, file size), and returns a completion summary including timestamp, processing time, filename, and formatted file size in GB.
def datapull(): start_time = datetime.now() start_page = find_start_page() records, filename, current_page = add_record(start_page) save_records(records, filename) end_time = datetime.now() run_data = log_run(start_time, end_time, filename, current_page) filesize_gb = '{:.2f}'.format(run_dat...
def standard_cnf_sentence(self, cnf_sentence: list): std_cnf_sentence = [] for clause in cnf_sentence: std_clause = self.standard_clause(clause) if not self.is_valid_clause(std_clause) and std_clause not in std_cnf_sentence: std_cnf_sentence.append(std_clause) ...
This function performs propositional logic resolution to determine if a knowledge base entails a given sentence. It converts the negated target sentence to CNF, adds it to the KB, then iteratively resolves clauses. If a contradiction (empty clause) is derived, it returns True (entailment holds). If no new clauses can b...
def pl_resolution(self): cnf_clause_list = deepcopy(self.KB) neg_alpha = self.standard_cnf_sentence(self.negation_of_cnf_sentence(self.alpha)) for clause in neg_alpha: if clause not in cnf_clause_list: cnf_clause_list.append(clause) while True: se...
def get_parents(self): ''' The function returns an array where each index stands for a node and the value for that index is the index of its parent ''' m, n = self.m, self.n parents = np.zeros(m+n, dtype=np.int32) Z = self.Z for i, z in enumerate(Z): ...
This code initializes a hierarchical clustering structure by processing input data `X` and a hierarchy `Z`. It sets attributes like cluster count (`self.m`), data points (`self.n`), and derives node relationships (parents, siblings, item nodes, node sizes) from `Z` to represent hierarchical cluster organization.
def __init__(self, X, Z, *args, **kwargs): ''' X: the original data of order mxn Z: the hierarchy 2D list ''' self.X = X self.Z = Z self.m = len(Z) # number of clusters self.n = X.shape[0] # number of data points # self.D = self.distanc...
def send_str_utf8(s: socket.socket, st: str): st_data = st.encode("utf-8") send_data(s, st_data) def send_int_str_utf8(s: socket.socket, i: int): send_str_utf8(s, str(i)) def send_data(s: socket.socket, data: bytes): lendata = len(data).to_bytes(8, "big") s.send(lendata) s.send(data)
This function sends commands and associated data over a socket. It transmits the command string, then handles specific commands by sending additional parameters: "mkdir" sends a directory name, "file_transfer_begin" sends a filename and two integers (likely size/checksum), "file_data" sends binary data, while other com...
def send_command(s: socket.socket, command: str, *args): send_str_utf8(s, command) match command: case "mkdir": send_str_utf8(s, args[0]) case "file_transfer_begin": send_str_utf8(s, args[0]) send_int_str_utf8(s, args[1]) send_int_str_utf8(s, args[...
def recv_str_utf8(s: socket.socket) -> str: return recv_data(s).decode("utf-8") def recv_int_str_utf8(s: socket.socket) -> int: return int(recv_str_utf8(s)) def recv_data(s: socket.socket, len: int = 0) -> bytes: lendata = s.recv(8) if len > 0: return __recv_data(s, len) else: my_len...
Your returnThe function `recv_command` receives a command from a socket and processes it along with its arguments. Depending on the command type (e.g., "mkdir", "file_transfer_begin", "file_data"), it retrieves corresponding parameters such as directory names, file details, or data chunks. It returns a tuple containing...
def recv_command(s: socket.socket, file_data_recv_bytes_per_time: int = 0) -> tuple: command = recv_str_utf8(s) args = [] match command: case "mkdir": args.append(recv_str_utf8(s)) case "file_transfer_begin": args.append(recv_str_utf8(s)) args.append(recv_...
def worldToMap(self, pos): return np.floor(pos / self._resolution).astype(int) def mapToWorld(self, pos): return (self._resolution / 2) + self._resolution * pos def in_bounds(self, pos, world_coords=True): if world_coords: pos = self.worldToMap(pos).astype(int) else: ...
This function traces a line from a starting position to an end point in a grid using a modified Bresenham/DDA algorithm, checking each cell for availability (obstacle-free). It returns the world coordinates of the first valid cell encountered along the path, or None if out of bounds. The 'invert' flag determines whethe...
def find_available(self, pos, end, invert=False): # Rasterize the line using Bresenham's algorithm # Use DDA to cover all cells that the ray passes through (modified Bresenham) cur_cell = self.worldToMap(pos) pos = self.mapToWorld(cur_cell) end_cell = self.worldToMap(end) ...
def get_width(self): return self._width * self._resolution def get_height(self): return self._height * self._resolution def find_available(self, pos, end, invert=False): # Rasterize the line using Bresenham's algorithm # Use DDA to cover all cells that the ray passes through (modified Br...
This function identifies obstacles within a circular radius around a given position by scanning angular directions, returning their positions and distances. It checks each radial direction for obstacles using `find_available`, collects valid obstacles, and computes their distances from the center position, with an opti...
def get_available_cells_in_radius(self, pos, radius, invert=False): obstacles = [] distances = [] if not self.get_width() >= pos[0] >= 0 or \ not self.get_height() >= pos[1] >= 0: return obstacles, distances angles = np.arange(0, 2*np.pi + self._d_theta, self._d_t...
def init_params(self): method = self.init layers = self.layers # parameters = {} L = len(layers) if method == None or method == 'random': for l in range(1, L): self.parameters['W'+str(l)] = np.random.randn(layers[l], ...
The code trains a neural network using mini-batch gradient descent, iterating over epochs and batches to update parameters via forward and backward propagation. It monitors cost, checks for convergence/divergence, and optionally plots the cost curve. Hyperparameters like learning rate, batch size, and epochs are config...
def train(self, X, Y, learning_rate=0.01, n_epochs=100, batch_size=64, conv_cost=0.01, printcost=True, plot=False, report_freq=500): cost = [] div_warn = 0 # divergence warning c = 1 t1 = time.time() # create mini-batch parameters and randomize batchnum = ...
def _add_or_remove_neighbours(self, source_row, source_col, target_row, target_col, add): """ Removes mutual neighbours (source, target) in neighbours and physical neighbours """ source_square = self.get_square_or_none(source_row, source_col) target_square = self.get_square_or_no...
This function places or removes horizontal/vertical fences at specified grid positions, updating adjacent square connections. It adjusts neighbor relationships by adding/removing links, handling both direct and distant (pawn-blocked) connections. When placing fences, it modifies grid states and removes diagonal/straigh...
def _place_or_remove_fence(self, row, col, orientation, place=True): """ Places or removes a fence and updates the square neighbourhoods accordingly. """ # Assumes valid fence if orientation == 'h': self._add_or_remove_neighbours(row, col, row + 1, col, add=not place)...
def check_winner(self): for player, pawn in self.pawns.items(): if pawn.square.winning_square(player): raise GameOver(player, last_move=False, message=f'Player {player} wins the game') def fence_exists(self, row, col, orientation): if orientation == 'v': return se...
This function places a fence on a board if valid, checking for out-of-bounds, overlaps, and ensuring all pawns retain valid paths. It temporarily places the fence, runs BFS to verify pawn mobility, and reverts the placement if any path is blocked, raising an InvalidFence exception with details if invalid.
def place_fence(self, row, col, orientation, check_winner=True, run_BFS=True): """ Places a fence or raises InvalidFence exception if the fence is invalid. """ if check_winner: self.check_winner() # Check if neighbouring squares are valid try: squ...
def expect(self, token): if self.current_token != token: raise Exception('expect token:%s' % token.type) self.next() def expression(self): return self.binary(self.and_, OR) def next(self): try: self.current_token = next(self.next_token) except: ...
This code parses a list of expressions enclosed in brackets. It collects evaluated expressions into a list, handles commas between elements, and returns a List object containing the parsed values.
def list_(self): self.expect(LBRACKET) values = [] while self.current_token != RBRACKET and self.current_token != EOF: value = self.expression() values.append(value) if self.current_token == COMMA: self.next() self.expect(RBRACKET) ...
def expect(self, token): if self.current_token != token: raise Exception('expect token:%s' % token.type) self.next() def expression(self): return self.binary(self.and_, OR) def next(self): try: self.current_token = next(self.next_token) except: ...
This code parses a map/dictionary structure from a token stream by reading key-value pairs separated by colons, collecting them into a list of MapItems, and returning a Map object containing these items. It expects opening and closing braces, handles commas between pairs, and validates syntax through token checks.
def map_(self): self.expect(LBRACE) items = [] while self.current_token != RBRACE and self.current_token != EOF: key = self.expression() self.expect(COLON) value = self.expression() items.append(MapItem(key, value)) if self.current_toke...
def next(self): try: self.current_token = next(self.next_token) except: self.current_token = EOF def equality(self): return self.binary(self.comparison, EQUAL, NOTEQUAL)
The code parses a NOT expression by checking if the current token is 'NOT'. If true, it consumes the token, recursively parses the operand using `not_`, and returns a unary expression with 'NOT' and the operand. If not, it delegates to `equality()` to parse other expressions, ensuring proper handling of logical negatio...
def not_(self): if self.current_token == NOT: self.next() operand = self.not_() return Unary(NOT, operand) return self.equality()
def next(self): try: self.current_token = next(self.next_token) except: self.current_token = EOF def list_(self): self.expect(LBRACKET) values = [] while self.current_token != RBRACKET and self.current_token != EOF: value = self.expression() ...
This code parses the current token into appropriate AST nodes: variables, literals, or complex structures like lists, maps, and expressions enclosed in parentheses. It identifies token types (name, integer, float, string) and constructs corresponding objects, or delegates to helper methods for compound structures.
def primary(self): tok, value = self.current_token, self.current_token.value if tok == NAME: self.next() return Variable(value) if tok == INT: self.next() return Literal(int(value)) if tok == DOUBLE: self.next() retu...
def primary(self): tok, value = self.current_token, self.current_token.value if tok == NAME: self.next() return Variable(value) if tok == INT: self.next() return Literal(int(value)) if tok == DOUBLE: self.next() retu...
This code parses expressions with function calls, subscripts, and attribute access, building an abstract syntax tree (AST). It processes tokens like parentheses (for function calls), brackets (for subscripts), and dots (for attributes), recursively constructing nodes like Call and Subscript to represent the parsed stru...
def call(self): expr = self.primary() while self.match(LPAREN, LBRACKET, DOT): if self.current_token == LPAREN: self.next() args = [] while self.current_token != RPAREN and self.current_token != EOF: arg = self.expression() ...
def next(self): try: self.current_token = next(self.next_token) except: self.current_token = EOF def call(self): expr = self.primary() while self.match(LPAREN, LBRACKET, DOT): if self.current_token == LPAREN: self.next() ...
This code parses a unary minus expression. If the current token is a minus sign, it recursively processes the operand and returns a Unary node representing the negation. Otherwise, it delegates to the 'call' method for other expressions. The function handles nested negatives and constructs an abstract syntax tree for u...
def negative(self): if self.current_token == MINUS: self.next() operand = self.negative() return Unary(MINUS, operand) return self.call()
def _handle_event(self): for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.KEYDOWN: self._handle_key_down(event) elif event.type == pygame.KEYUP: self._handle_key_up(event) def _update(self): self.ship.update() for b...
The code runs a game loop that continuously handles events (like keyboard/mouse input), updates game state, renders the screen, and maintains a 60 FPS frame rate using a clock. This loop sustains real-time interaction and visual updates for the game.
def run_game(self): # Start main loop for the game. while True: self._handle_event() # Watch for keyboard and mouse events. self._update() self._update_screen() self.clock.tick(60)
def getProbs(self,candidates,choice='traditional'): start=time.time() candidates.sort(key=lambda x: self.compute_length(x)) SPProbs=[] first_prob=1 for i in range(1,len(candidates[0])): first_prob=first_prob*self.G[candidates[0][i-1]][candidates[0][i]]['prob'] if (choice=="traditional"): self.probD...
The code validates models by processing a dataset, comparing traditional and learning-based methods. It accumulates and averages probability and index results for specified k-values, returning these metrics for evaluation.
def validation(self): self.candidate_size=20 self.kvalues=[1,5,10] tra_time=learn1_time=0 self.N_val=1000 self.kcounters={} for value in self.kvalues: self.kcounters[value]=self.counter prob_tra=[0 for _ in range(len(self.kvalues))] prob_learn1=[0 for _ in range(len(self.kvalues))] index_tr...
def getProbs(self,candidates,choice='traditional'): start=time.time() candidates.sort(key=lambda x: self.length(x)) SPProbs=[] first_prob=1 for i in range(1,len(candidates[0])): first_prob=first_prob*self.G[candidates[0][i-1]][candidates[0][i]]['prob'] if (choice=="traditional"): self.probDict={} ...
The code computes and compares performance metrics (probabilities, rank sums, time) of different algorithms (traditional, learning, random) on graph data by processing input files, accumulating statistics, and outputting averages/quartiles for evaluation.
def computeProbs(self): tra_time=learn1_time=learn2_time=random_time=0 prob_worse=[[] for _ in range(len(self.kvalues))] prob_tra=[[] for _ in range(len(self.kvalues))] prob_random=[[] for _ in range(len(self.kvalues))] prob_learn1=[[] for _ in range(len(self.kvalues))] index_tra=[[] for _ in range...
def squareUnderAttack(self, row, col): self.isWhiteMove = not self.isWhiteMove opponentsMoves = self.getPossibleMoves() self.isWhiteMove = not self.isWhiteMove for move in opponentsMoves: if move.endRow == row and move.endCol == col: return True retur...
The main task of the code is to generate valid castling moves for a chess engine based on the current player's castling rights and whether the king is under attack. It checks for king-side and queen-side castling eligibility, then adds corresponding moves to the provided list if conditions are met.
def getCastlingMoves(self, row, col, moves): if self.squareUnderAttack(row, col): return if (self.isWhiteMove and self.castlingRights.wks) or (not self.isWhiteMove and self.castlingRights.bks): self.kingSideCastlingMoves(row, col, moves) if (self.isWhiteMove and self.cast...
def searchPinsAndChecks(self): pins = [] checks = [] isCheck = False if self.isWhiteMove: enemyColor = "b" allyColor = "w" startRow = self.whiteKingLocation[0] startCol = self.whiteKingLocation[1] else: enemyColor = "w" ...
This function generates valid moves for the current player in a chess game, considering checks, pins, and castling rights. It checks if the king is in check, filters moves to escape check, handles multiple checks by allowing king moves, and adds castling moves when applicable. It also determines checkmate or stalemate ...
def validMoves(self): #check logic of this function! tempCastlingRights = CastlingRights(self.castlingRights.wks, self.castlingRights.bks, self.castlingRights.wqs, self.castlingRights.bqs) moves = [] self.isCheck, self.pins, self.checks = self...
def return_list_files(self): self.get_folder() for file in os.listdir(): if 'xls' in file: self.list_files.append(file) def formats(print_title=None, print_sub_header=None, print_hashes=False, print_dashes=False, clear_window=True): """ Prints things for good ...
The main task of the code is to select specific sheets from multiple Excel workbooks based on user input. It lists found workbooks, loads each file, checks available sheets, and prompts the user to choose which sheets to retain (via numbers or 'all'). Input validation ensures correct formatting, and selections are stor...
def select_sheets_to_keep(self): # create the list of file self.return_list_files() # show the user what filenames were found # make clear space for visual purposes self.formats(print_title="LIST OF WORKBOOKS") print("Found the following workbooks.\n" "The s...
def return_list_files(self): self.get_folder() for file in os.listdir(): if 'xls' in file: self.list_files.append(file) def formats(print_title=None, print_sub_header=None, print_hashes=False, print_dashes=False, clear_window=True): """ Prints things for good ...
This function processes multiple Excel workbooks by listing all found files, loading each workbook, identifying its sheets, and prompting the user to select which sheets to retain. It stores the selected sheets in a dictionary for later use in pandas, while automatically iterating through all files without requiring ma...
def select_sheets_to_keep_fast(self): # create the list of file self.return_list_files() # show the user what filenames were found # make clear space for visual purposes self.formats(print_title="LIST OF WORKBOOKS") print("Found the following workbooks.\n" "...
def select_sheets_to_keep(self): # create the list of file self.return_list_files() # show the user what filenames were found # make clear space for visual purposes self.formats(print_title="LIST OF WORKBOOKS") print("Found the following workbooks.\n" "The s...
The main task of the code is to load Excel workbooks and sheets into pandas DataFrames, allow users to select and validate columns, choose an index column, and export the filtered data to text files with structured formatting. It processes multiple files, interacts with the user for column/index selections, validates i...
def create_dataframes(self): # load in files and create data dict of workbook names and their respective sheets self.select_sheets_to_keep() # iterate over all keys (filenames) and load each respective worksheet as a dataframe for wb in self.data_dict.keys(): for ws in self....
def homepage(new_html,width=1000,height=1850): calc_file=codecs.open(new_html,'r') page=calc_file.read() stc.html(page,width=width,height=height,scrolling=False ) def weather(zip_code, country_code): try: api_key = "f10eff398a3485f33ff8ab51ef3bab2f" base_url = "https://api.openweathermap...
The code creates a Streamlit web app with a sidebar menu for navigation. It handles five main tasks: displaying a homepage, fetching and showing weather data based on zip code, predicting fire vulnerability using weather data and a model, allowing users to upload fire-related images with contact details, and rendering ...
def navigation(st): Menu=['Home','Weather','Fire vulnerability','Upload a Fire','Prevention Techniques'] choice=st.sidebar.selectbox('Main Menu',Menu) if choice=='Home': homepage('new.html') elif choice=='Weather': st.title('Weather Finder') if __name__ == '__main_...
def is_installed(self, package_name: str) -> bool|None: """ The function checks if the specified package is installed or not. Args: package_name (str): The name of the package, for example 'com.google.chrome' Returns: Boolean indicates if app is ...
This function starts an Android app using ADB commands, specifying the package and activity. It optionally waits for launch completion and forces a stop before starting. It checks app installation, sends HOME key event, executes 'am start' with parameters, logs results, and returns success status or None if no device i...
def start_app(self, package: str, activity: str, wait: bool=True, stop: bool=True) -> bool|None: """ The function starts an Android app with the specified package and activity, optionally waiting for the launch to complete and stopping the app before starting the activity. Args:...
def caclulateSpeed(self, ball, degree, axis): speed = 0 if axis == 'X': speed = ball.speedX elif axis == 'Y': speed = ball.speedY else: return speed direction = 1 if degree < 0: direction = -1 if degree != 0: mg = ba...
The code calculates physics for a group of balls in a multi-threaded environment. It computes speed components (X/Y) for each ball, handles ball-wall collisions, and optionally ball-ball collisions. The first thread (indexThread=0) waits for others using a flag, ensuring synchronized updates.
def calculatePhysics(self, indexThread): for i in range(self.groupSize * indexThread, self.groupSize * (indexThread + 1)): if i < len(self.ballsList): self.ballsList[i].speedX = self.caclulateSpeed(self.ballsList[i], self.degreeX, 'X') self.ball...
def showData(self): for i in range(len(self.entries)): self.entries.get(self.configNameValues[i]).delete(0, END) self.config = self.loadConfig() self.entries.get(self.configNameValues[0]).insert(0, self.config.physics.NUMBER_BALLS) self.entries.get(self.configNameValues[1]).i...
The main task of the code is to execute the application by displaying data, updating the interface, checking for closure conditions, and initiating the main event loop to keep the GUI running.
def appRun(self): self.showData() self.update() self.checkClose() self.root.mainloop()
def initialize_with_zeros(dim): w = np.zeros((dim,1)) b = 0 return w,b def optimize(w, b, X, Y, n_iterations, learning_rate, print_cost=False): """ This function optimizes w and b by running a gradient descent algorithm Arguments: w -- weights, a numpy array of size (num_px * num_px * 3...
The code trains a logistic regression model using gradient descent on training data, evaluates it on test data, calculates train/test accuracies, and returns parameters, costs, and performance metrics in a dictionary.
def model(X_train, Y_train, X_test, Y_test, num_iterations = 2000, learning_rate = 0.5, print_cost = False): # initialize parameters with zeros (≈ 1 line of code) w,b = initialize_with_zeros(X_train.shape[0]) # Gradient descent parameters, grads, costs = optimize(w,b,X_train, Y_train, num_iterations,l...