dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def read_lines(self, path: str) -> list[str]: with open(path, "r") as file: return file.readlines() def get_games(self, lines: list[str]) -> list[Game]: return [self.get_game(line) for line in lines] def get_multiplication(self, nums: list[int]): product = 1 for num in nums: ...
The code reads input lines from a file, parses them into game data, calculates a multiplication value for each game's color requirements, and returns the sum of all these values.
def run(self, path: str) -> int: lines = self.read_lines(path) games = self.get_games(lines) powers = [self.get_multiplication(game.get_needed_amount_of_colors()) for game in games] return sum(powers)
def separator(): """ Function to print separators to keep the different functions separated """ print(""" -.-*-.-*-.-*-.-*-.-*-.-*-.-*-.-*-.-*-.-*-.-*-.-*-.-*-.-*-.-*-.-*- """) def game(): """ Function for the actul game play a random word using single letters guesses with a spec...
The main task of the code is to prompt the user to play again or exit the game after completion. It handles user input validation, restarts the game if chosen, or terminates the game with closing messages, credits, and delays. It also manages game state transitions based on remaining lives and user decisions.
def game_end(): """ Function loop to choose to play again or stop """ global play if lives == 0: play = input(f""" That is to bad {name}! Want to try again? yes = y, no = n:\n""").strip(' ') else: play = input(f""" Yes {name}! Want to try again? yes = y, no = n:\n ...
def welcome_to(): """ Welcome to the game art """ print(r""" __ __ _ _ \ \ / /__| | ___ ___ _ __ ___ ___ | |_ ___ \ \ /\ / / _ \ |/ __/ _ \| '_ ` _ \ / _ \ | __/ _ \ \ V V / __/ | (__ (_) | | | | | | __/ | |_ (_) | \...
The main task of the code is to initialize and sequence a game's startup process by calling functions to display a welcome message, logo, player greeting, and launch the game, with timed pauses between each step to create a structured user experience.
def main(): """ Run all program functions """ welcome_to() time.sleep(0.6) logo() time.sleep(0.7) welcome_player() time.sleep(0.5) game()
def TT_mat(C_l): ell = np.arange(len(C_l)) TT = np.zeros_like(z) for l in ell[2:]: TT += (2*l+1)/(4*np.pi)*C_l[l]*P(l,z) return TT def TQ_mat(C_l): ell = np.arange(len(C_l)) TQ = np.zeros_like(z) for l in ell[2:]: TQ -= (2*l+1)/(4*np.pi)*F10(l,z)*C_l[l] return TQ def TU_m...
The code computes a covariance matrix for polarized intensity components (TT, TE, TB, EE, BB, EB) using rotation matrices and input power spectra. It constructs matrices from power spectra, applies rotation transformations, and combines them via nested loops to produce the final 3×768×3×768 covariance matrix, optionall...
def test_M(show=False): ell = np.arange(3*8.) C_l = np.zeros_like(ell) C_l[2:] = 1./ell[2:]**2 TT = TT_mat(C_l) # TT TQ = TQ_mat(C_l) # TE TU = TU_mat(C_l*0) # BT QQ = QQ_mat(C_l, C_l) # E, B UU = UU_mat(C_l, C_l) # E, B QU = QU_mat(C_l*0) # EB if show: plt.subplot(3,3,...
def build_poly_dataset(tX,degree): tX_expanded = build_poly(tX[:,0] , degree) for i in range (tX.shape[1]-1): tX_expanded = np.concatenate((tX_expanded , build_poly(tX[:,i+1] , degree)),axis=1) return tX_expanded def least_squares_GD(y, tX, initial_w,max_iters, gamma): """ Linear regression ...
The function performs k-fold cross-validation by splitting data into training and test subsets, applies specified regression or logistic models (e.g., least squares, ridge, logistic), computes training and test mean squared errors, and evaluates accuracy. It handles polynomial feature expansion if enabled and returns l...
def cross_validation(y, tx,k, k_indices, method,lambda_,degree): # get k'th subgroup in test, others in train te_indice = k_indices[k] tr_indice = k_indices[~(np.arange(k_indices.shape[0]) == k)] tr_indice = tr_indice.reshape(-1) y_te = y[te_indice] y_tr = y[tr_indice] x_te = tx[te_indice,:]...
def PCA(X , num_components): #mean of X X_mean = X - np.mean(X , axis = 0) #covariance matrix cov_mat = np.cov(X_mean , rowvar = False) #calculate eigenvalues,vectors eigen_values , eigen_vectors = np.linalg.eigh(cov_mat) #sort eigenvectors by eigenvalue sorted_in...
This code performs cross-validation to evaluate the accuracy of a least-squares model using PCA. It iterates over the number of principal components, applies PCA to the data, splits it into k-folds, and computes average accuracy across folds. The results are plotted to show how accuracy varies with the number of princi...
def cross_validation_demo_least_squares_PCA(y,x,k_fold,seed,method): iter_ = [] accuracy_=[] for i in range (x.shape[1]): iter_.append(i) tX = PCA(x,i) # split data in k fold k_indices = build_k_indices(y, k_fold, seed) # define lists to store the loss...
def preprocess_negative_entries(anchor_items): negative_items = np.array(anchor_items) shuffle(negative_items) def __clean_entry(entry): return [{**x, 'id': entry["id"]} for x in entry["images"]] assert len(anchor_items) == len(negative_items) negative_items = [__clean_entry(x) for x in ne...
The main task of the code is to generate triplets consisting of anchor, positive, and negative items from input entries. It preprocesses entries into positive and negative item lists, then pairs each positive item with a negative item that doesn't share the same anchor ID. The code ensures diversity in negative samples...
def build_triplets(entries): negative_items = preprocess_negative_entries(entries) positive_items = preprocess_positive_entries(entries) ##assert len(negative_items) == len(positive_items) # -> Some Articles have only 1 Images - therefore this Assertion doesnt work broadly across all brands data = [] ...
def millis(): return round(time.time() * 1000) def command(data): if (data == "g"): transmit_default_data() def store_remote_agent_data(data, received): global agent_list global node_list id, lon, lat, alt = parse_remote_agent_location(data) remote_agent_message = (id, data, received) ...
The function processes incoming XBee messages by extracting the sender's node ID and data. If the sender is "ham5" (ground control), it executes the `command` function with the data. For other remote agents, it logs the data and timestamp using `store_remote_agent_data`, enabling differentiated handling of ground contr...
def data_rcvd_callback(xbee_message): received = millis() address = xbee_message.remote_device.get_64bit_addr() node_id = xnet.get_device_by_64(address).get_node_id() data = xbee_message.data.decode("utf8") # ham5 was the ground control for all testing if (node_id == "ham5"): command(dat...
def render_frames( self, tdp: Path, source: Sequence[SConsFile], env: SConsEnvironment ) -> None: for i, (frame_stl_vals, frame_model_file) in enumerate( zip(self.stl_vals_list, cycle(source)) ): fn = tdp / f"image_{i:05d}.png" self.render_frame( ...
This function processes source files to generate target images by rendering frames into a temporary directory. If multiple frames are present and the target isn't a GIF, it creates a montage. Finally, it finalizes each target image with post-processing steps.
def __call__( self, target: Sequence[SConsFile], source: Sequence[SConsFile], env: SConsEnvironment, ) -> None: with tempfile.TemporaryDirectory() as td: tdp = Path(td) self.render_frames(tdp, source, env) if len(self.frames) > 1 and target...
def _decode(value, encoding="utf-8", errors="ignore"): # Helper method to only decode if bytes type if sys.version_info >= (3,0) and isinstance(value, bytes): return value.decode(encoding,errors) return value def get_os_version(): p = subprocess.Popen(["sw_vers","-productVersion"...
The main task of the code is to locate available Python installations on a system, check their Tk version compatibility, and return a list of paths with Python versions and Tk versions. It prioritizes newer Tk versions, skips incompatible ones (e.g., macOS 11.x+ with Tk 8.5), and optionally filters results based on a m...
def gather_python(show_all=False,path_list=None): # Let's find the available python installs, check their tk version # and try to pick the latest one supported - or throw an error if # we're on macOS 11.x+ and using Tk 8.5 or older. pypaths = (path_list if isinstance(path_list,(list,tuple)) else [path_l...
def gather_python(show_all=False,path_list=None): # Let's find the available python installs, check their tk version # and try to pick the latest one supported - or throw an error if # we're on macOS 11.x+ and using Tk 8.5 or older. pypaths = (path_list if isinstance(path_list,(list,tuple)) else [path_l...
The code builds a macOS application bundle (ProperTree.app) by locating a suitable Python version, removing any existing app, creating directory structures, copying scripts/resources, setting the shebang for the executable script, generating an Info.plist file, and preserving specific files during the process. It ensur...
def main(use_current=False,path_list=None): # Let's check for an existing app - remove it if it exists, # then create and format a new bundle os.chdir(os.path.abspath(os.path.dirname(__file__))) os.chdir("../") temp = None pt_current = None if os.path.exists("ProperTree.app/Contents/MacOS/Pr...
def __calc_cell(results, indexes, size, shots, ignore): """ Calculate the corresponding coefficient. :param results: Qiskit Result obj :param indexes: List of indexes :param size: Maximum index :param shots: Shots :param ignore: Indexes to ignore :return: Coefficient """ options...
The main task of the code is to construct a density matrix from quantum measurement results by randomly zeroing out specified counts, normalizing by total shots, and calculating probabilities across quantum states. It processes Qiskit Counts data, initializes a multi-dimensional array, iterates through states to popula...
def get_density_matrix(results, reduce): """ Driver Method :param results: Qiskit Counts obj :return: Density Matrix """ print(reduce) results_copy = copy.deepcopy(results) randomlist = random.sample(range(1, 728), reduce) for i in randomlist: for key in results_copy[i].keys(...
def splitIntoWords(string: str) -> [str]: words = [] map = {',': "_comma", ' ': "_space", '.': "_period"} stringBuilder = "" for char in string: if (char in map.keys()) and stringBuilder != "": words.append(stringBuilder.replace(" ", "")) stringBuilder = "" wo...
The function converts a text string into an MP3 file by splitting the input string into words, retrieving corresponding MP3 files from a source folder, concatenating them into a single audio file with a timestamped filename, and returning the file path.
def stringToMp3(sourceFolderName: str, string: str) -> str: words = splitIntoWords(string) paths = getMp3sFromWords(sourceFolderName, words) outputFileName = "data/output/{}.mp3".format(time.strftime("%Y%m%d-%H%M%S")) stitchMp3s(paths, outputFileName) return outputFileName
def reset_hash(self): self.hash = hashlib.sha256() def serialize_args(self, args): return "-".join(self.serialize_arg(arg) for arg in args) def serialize_kwargs(self, kwargs): return "-".join(k + ":" + self.serialize_arg(v) for k, v in kwargs.items()) def get_hash(self): ...
The main task of the code is to implement a caching mechanism for function results. It generates a unique cache key by serializing function arguments and a hash, then checks if the result exists in a file path. If cached, it loads and returns the result; otherwise, it computes the result, saves it to the cache, and ret...
def cached_f(*args, **kwargs): self.reset_hash() f_hash = ( self.serialize_args(args) + "#" + self.serialize_kwargs(kwargs) + "#" + str(self.get_hash()) ) p...
def __call__(self, inputs, labels=None, *args, **kwargs): given_training = self.model.training self._change_model_mode(given_training) if self._normalization_applied is True: inputs = self.inverse_normalize(inputs) self._set_normalization_applied(False) adv_...
The code's main task is to generate and save adversarial examples from a given data loader, along with associated metrics. It processes batches to create adversarial inputs, evaluates robust accuracy, computes L2 distances, and optionally saves predictions or clean inputs. The results are stored as PyTorch tensors in a...
def save(self, data_loader, save_path=None, verbose=True, return_verbose=False, save_predictions=False, save_clean_inputs=False, save_type='float'): r""" Save adversarial inputs as torch.tensor from given torch.utils.data.DataLoader. Arguments: save_path (str): save_path...
def __promotion(self): if self.end_pos not in self.__pawn(self.start_pos, self.col): return False offset = 0 if self.board[self.start_pos].col == 'W' else 56 return offset + 0 <= self.end_pos <= offset + 7 def __enpassant(self, pos, col, prev_pos): if not(24 <= pos <= 31 or...
This code validates a chess move by checking if it's a special case (promotion, enpassant, castling) based on piece type and position differences, returning the move type if complex; otherwise, it performs primary validation.
def validate(self, start_pos, end_pos, prev_pos): self.start_pos = start_pos self.end_pos = end_pos self.prev_pos = prev_pos self.col = self.board[start_pos].col self.name = self.board[start_pos].name dx = self.end_pos%8 - self.start_pos%8 complex_move =...
def __pawn(self, pos, col): moves = list() if col == 'W': if 0 <= pos - 8 <= 63: if self.board[pos - 8].col == 'N': moves.append(pos - 8) if 0 <= pos - 8*2 <= 63 and 48 <= pos <= 55: if self.board[pos - 8*2].co...
This function determines all possible moves for a chess piece at a given position. It identifies the piece type (pawn, rook, etc.), calls corresponding move-generation methods, and includes special rules like en passant for pawns and castling for kings. The result is a list of valid moves for the piece at the specified...
def getPossibleMoves(self, pos, prev_pos): name = self.board[pos].name col = self.board[pos].col if name == 'P': return self.__pawn(pos, col) + self.__enpassant(pos, col, prev_pos) elif name == 'R': return self.__rook(pos, col) elif name == 'N': return self.__knight(pos, col) ...
def commitMove(self, start_pos, end_pos, move): checkmove = CheckMove(self.__board) col = self.__board[start_pos].col move_type = checkmove.validate(start_pos, end_pos, self.__prev_end_pos) if move_type == "promotion": promo = input("Promote to: ").upper() if pro...
The code validates and executes a chess move, checking for legality (e.g., correct piece ownership, no self-capture, empty spaces). It commits the move, checks for check/checkmate/stalemate, reverts changes if invalid, and updates game state.
def makeMove(self, start_pos, end_pos, turn, move): board_backup = deepcopy(self.__board) move_history_backup = copy(self.__move_history) col = self.__board[start_pos].col opp_col = 'B' if col == 'W' else 'W' is_same_colour = self.__board[end_pos].col == col is_empty_sp...
def runStrip(binaryPath: str, verbose: int): stripbin = os.getenv("STRIP", "strip") if verbose >= 3: print("Using strip:") print(" stripped", binaryPath) subprocess.check_call([stripbin, "-x", binaryPath]) def getFrameworks(binaryPath: str, verbose: int) -> List[FrameworkInfo]: if verbos...
The function `deployPlugins` copies required Qt plugins from a source directory to an application bundle's plugin directory, filtering out unnecessary plugins based on deployment information. It skips specific plugin directories (e.g., "designer") and checks if corresponding Qt frameworks are used. It also excludes deb...
def deployPlugins(appBundleInfo: ApplicationBundleInfo, deploymentInfo: DeploymentInfo, strip: bool, verbose: int, sysLibDir: str, builtLibDir: str, ): # Lookup available plugins, exclude unneeded plugins = [] if deploymentInfo.pluginPath is None: return for dirpath, dirnames, ...
def get_wavfile(bucket, key): print('Downloading WAV file...') response = s3.get_object(Bucket=bucket, Key=key) print('WAV file successfully downloaded...') return io.BytesIO(response['Body'].read()) def get_ser_model(): model_bucket = os.environ['SAVED_MODEL_BUCKET'] json_filename = os.enviro...
The code processes an uploaded WAV file from an S3 bucket by retrieving the file, loading a SER (Speech Emotion Recognition) model, and generating a prediction result, which is then returned as the output.
def lambda_handler(event, context): bucket = event['Records'][0]['s3']['bucket']['name'] key = event['Records'][0]['s3']['object']['key'] wav_file = get_wavfile(bucket, key) model = get_ser_model() pred = make_prediction(model, wav_file) return pred
def convert_logo( path: str, output: str, server_id: str, server_name: str, sizes: list, lossless: bool = False, ): """ This function converts the server logo into different sizes and formats. The logo is kept in the original PNG format for environments that do not support WEBP. ...
The main task of the code is to parse command-line arguments for server media conversion, load server data, and convert logos, backgrounds, and banners into specified output directories. It supports dry runs, filters servers based on changed files, and reports conversion statistics, including successful conversions and...
def main(): """ Main function to parse arguments and convert server media. """ use_args = os.getenv("USE_ARGS") == "true" parser = argparse.ArgumentParser() # General Args parser.add_argument("--servers_dir", required=use_args, type=str) parser.add_argument("--inactive_file", required=u...
def poses_avg(poses): center = poses[:, :3, 3].mean(0) vec2 = normalize(poses[:, :3, 2].sum(0)) up = poses[:, :3, 1].sum(0) c2w = viewmatrix(vec2, up, center) return c2w def normalize(x): return x / np.linalg.norm(x, axis=-1, keepdims=True) def render_path_spiral(c2w, up, rads, focal, zdelta, z...
The function generates a spiral path of camera poses around a central point, using input camera poses (c2ws_all) and parameters like focus depth, radius scaling, and number of views. It calculates an average pose, determines a focal depth, computes radii based on camera positions, and constructs a spiral trajectory for...
def get_spiral(c2ws_all, near_far, rads_scale=0.5, N_views=120): # center pose c2w = poses_avg(c2ws_all) # Get average pose up = normalize(c2ws_all[:, :3, 1].sum(0)) # Find a reasonable "focus depth" for this dataset close_depth, inf_depth = near_far dt = .75 mean_dz = 1. / (((1. - dt)...
def define_transforms(self): self.transform = T.ToTensor() def read_meta(self): poses_bounds = np.load(os.path.join(self.root_dir, 'poses_bounds.npy')) # (N_images, 17) self.image_paths = sorted(glob.glob(os.path.join(self.root_dir, 'images/*'))) # load full resolution image then resize...
This code initializes a dataset processor for 3D reconstruction, handling image orientation (spheric/facing), transformations, and depth data. It sets up parameters for training/validation splits, applies coordinate system conversions, loads metadata, and optionally integrates COLMAP depth information for depth loss ca...
def __init__(self, args, split='train', spheric_poses=True, load_ref=False, depth_loss=True): """ spheric_poses: whether the images are taken in a spheric inward-facing manner default: False (forward-facing) val_num: number of val images (used for multigpu training, valida...
def _flatten_labels(y): import numpy as np return np.argmax(y, axis=1) def get_random_images(n=1, categories=None): from PIL import Image import cv2 import os import numpy as np root = os.path.join("fruits","Data") width = 100 height = 100 if not categories: target_folde...
The main task of the code is to evaluate a machine learning model's performance on test data by generating predictions, creating a confusion matrix, calculating precision, recall, and F1-score, and visualizing convolutional layer outputs for different model types (simple, residual, inception). It provides a comprehensi...
def final_report(model, X_test, y_test): y_preds = _flatten_labels(model.predict(X_test)) y_test_flat = _flatten_labels(y_test) data, labels = get_random_images() m = confusion(y_test_flat, y_preds) confusion_analysis(m) p, r, f = accuracy_breakdown(y_test_flat, y_preds) print(f"{model} has ...
def read_data(self): print("Reading data...") # Raw data from all sensors self.raw_data = pd.read_csv(self.data_path / SENSOR_TEMP_FILENAME, dtype="float64") # Make seperate sensor arrays for i in self.raw_data: if i != "time": self.se...
The code's main task is to conditionally process or load data based on the `self.save` flag. If `self.save` is True, it reads, cleans, predicts using machine learning, and saves data. If False, it directly loads data. Finally, it generates a graph using `graph_data()` regardless of the condition. The method ensures dat...
def start(self): # Only reload data if specified. Otherwise use pre-save data if self.save: self.read_data() self.clean_data() self.predict_ml() self.save_data() else: self.load_data() self.graph_dat...
def print_progress(self): percent_done = self.percent_finished_downloading() if percent_done%10 >= 5: percent_done += 10 - (percent_done%10) else: percent_done -= percent_done%10 num_arrow = percent_done num_period = 100 - num_arrow bar = "[" ...
This function marks the current download piece as complete in the bitfield, updates peer interest, checks if the download is finished, writes the completed piece to the file, and transitions the download state to COMPLETE if finished or READY_TO_REQUEST/WAITING_FOR_HOPE if ongoing.
def finished_cur_piece(self): self.bitfield[math.floor(self.cur_piece/8)] |= 0x80 >> (self.cur_piece % 8) self.print_progress() #now that our bitfield has changed, must recalculate interest in our peers for peer in self.tracker.peers: peer.check_interest(self.bitfield) ...
def has_piece(self,index): return self.bitfield[math.floor(index/8)]&(0x80 >> (index % 8)) > 0 def verify_piece(self, index): # Grab the correct piece from the torrent file torrent_piece = self.torrent.pieces[index*20:(index*20+20)] last_piece_bytes = (self.torrent.file_length - (self.nu...
The code monitors sockets for incoming connections/messages, handles peer handshakes, processes BitTorrent protocol messages (choke/unchoke, interested, have, bitfield, request, piece), updates peer states, and manages data transfer, while removing inactive peers.
def check_messages(self): socket_list = [self.tracker.listening_socket] for peer in self.tracker.peers: if peer.socket != None: socket_list.append(peer.socket) # print("awaiting new message:") ready_sockets, a, b = select.select(socket_list, [], ...
def connect_to_peers(self): threads = [] for P in self.tracker.peers: #try: my_thread = Thread( target=Peer.start_connection, args=[P, self.torrent.info_hash_bytes,self.torrent.peer_id.encode(), self.locals] ...
This code parses command-line arguments for a torrent client, initializes torrent and tracker modules with specified parameters, connects to peers, manages peer connections, sets up data buffers, and runs a loop to handle torrenting tasks like message checking, state updates, and periodic events.
def main(self, argv): torrent_path = '' compact = False try: opts, args = getopt(argv,"hcslt:",["tfile="]) except GetoptError: print('test.py -t <torrentfile> -c') exit(2) for opt, arg in opts: if opt == '-h': print(...
def get_params(trial: optuna.Trial) -> Iterator[str]: # noqa: C901 def lock_param(name: str, value: object): trial.set_system_attr( 'fixed_params', {**trial.system_attrs.get('fixed_params', {}), name: value}, ) def get_flag(name: str, lock: bool = None) -> str: ...
This function optimizes transcoding parameters using Optuna by selecting a binary tool, generating CLI parameters, and evaluating metrics like FPS and SSIM. It prunes trials with duplicate parameters, runs transcoding, captures results, and returns a score based on performance metrics to guide the optimization process.
def objective(trial: optuna.Trial) -> float: binary = HERE / str(trial.suggest_categorical('binary', BINARIES)) params_raw = [f'--{p}' for p in get_params(trial) if p] params = ' '.join(params_raw) trial.set_user_attr('cli', ' '.join(sorted(params_raw))) if trial.should_prune(): raise optu...
def prepare_api12_data(self, well_data): import datetime import pandas as pd self.output_data_api12_df = well_data.copy() self.add_gis_info_to_well_data() self.output_data_api12_df['O_PROD_STATUS'] = 0 self.output_data_api12_df['O_CUMMULATIVE_PROD_MMBBL'] = 0 sel...
This method retrieves and prepares well-related data for a specific API10 identifier by fetching information like well details, production metrics, directional surveys, and completion data from the BSEE database. It then processes and structures this data using preparation functions to ready it for downstream analysis ...
def get_bsee_data_and_prepare_data_for_api10(self, api10): well_data = self.bsee_data.get_well_data_by_api10(api10) production_data = self.bsee_data.get_production_data_by_api10(api10) WAR_summary = self.bsee_data.get_WAR_summary_by_api10(api10) directional_surveys = self.bsee_data.get_d...
def prepare_api_data(self): API10 = [] for df_row in range(0, len(self.dbe.input_data_well)): well_api = self.dbe.input_data_well.API12.iloc[df_row] api10_value = self.get_API10_from_well_API(well_api) API10.append(api10_value) self.dbe.input_data_well['API10'...
The main task of the code is to prepare and process well-related data for API 12 standards. It retrieves input data (well, production, directional surveys, etc.) from a database, then processes and structures them through methods like preparing casing, completion, and formation data, evaluating well distances, and hand...
def prepare_field_api12_data(self): self.prepare_api_data() well_data = self.dbe.input_data_well production_data = self.dbe.input_data_production WAR_summary = self.dbe.input_data_well_activity_summary directional_surveys = self.dbe.input_data_well_directional_surveys ST...
def read_from_xlsx(self, cfg_xlsx): from common.data import ReadData readdata = ReadData() result = readdata.from_xlsx(cfg_xlsx) return result def save_data(self, cfg, data): if cfg.__contains__('output'): if cfg['output']['target'] == 'db': db_propert...
This method retrieves data from specified input sources (e.g., ACCDB, Excel, CSV, ZIP, URL, DB) based on configuration settings, processes the data using source-specific logic, and saves the results. It initializes database connections for ACCDB, reads Excel files, processes CSV/ZIP/URL/DB sources through dedicated fun...
def get_data_and_save_to_target(self): result = {} if self.cfg.input_data['source'] == 'accdb': for set_index in range(0, len(self.cfg.input_data['sets'])): db_properties = {'server_type': 'accdb', 'database': self.cfg.input_data['sets'][0]['io']} from common...
def draw_board(self): self.window.fill(self.white_color) start = 1 for i in range(self.board.shape[0]): for j in range(start, self.board.shape[1], 2): # Form a grid shape self.draw_square(self.black_color, j, i) start = int(not start) #Alte...
This code renders a game interface by drawing the board, turn indicators, move highlights, captured pieces, and game-over messages, updating the display with all visual elements for real-time feedback during gameplay.
def draw(self): self.draw_board() text = self.header_font.render("Your Turn" if self.my_turn else "Opponents Turn", True, (255,0,0), self.white_color) self.window.blit(text, (self.right_sidebar + 20,0)) y = len(self.activity_texts) * 30 if y - self.window.get_size()[1] >= 30: ...
def on_message(self,ws, incMessage): if "Waiting for opponent" == incMessage: print("Waiting...") return if "You are team" in incMessage: # Means that both players are connected self.team = incMessage.split(": ")[-1] #Grab the team this client is on print(...
This code initializes a multiplayer chess game using Pygame and WebSockets. It sets up game state variables, connects to a server for real-time communication, handles piece movements, captures, and promotions, and manages UI elements like the board, sidebars, and main menu. The game processes WebSocket messages for opp...
def __init__(self): pygame.init() # Hold the captured pieces for both teams for display self.captured = { "White": { "Pawn": [], "Knight": [], "Bishop": [], "Rook": [], "Queen": [], }, ...
def combinations(df, cols_X_prot, cols_X_met, n_comb): # Define the parameter values no_samples = df.shape[0] prot_cols = cols_X_prot.stop - cols_X_prot.start met_cols = cols_X_met.stop - cols_X_met.start # Define the parameter values min_val = 50 max_val_prot = round(prot_cols * 0.35) ...
The function performs model optimization by sampling combinations of parameters (kprot, kmet, latent) to select proteomics/metabolomics features, train autoencoders, and evaluate clustering performance using Silhouette scores. It applies PCA, feature selection, and validation splits, recording initial/final Silhouette ...
def model_optimization(df, n_all_feat, n_comb, cols_X_prot, cols_X_met, cols_clin, cols_X_expr, y_label): # This function performs model optimization by randomly sampling possible combinations of parameters # and running feature selection, model training, and evaluation for each co...
def load_npz(npz_fn): npz = np.load(npz_fn) sls = np.array_split(npz['concatenated_searchlights'], npz['sections']) dists = np.array_split(npz['concatenated_distances'], npz['sections']) return sls, dists def load_searchlights(lr, radius, icoorder): basename = f'sls_fsaverage_{lr}h_{radius}mm_icoord...
The function retrieves or generates searchlight indices for cortical surfaces based on parameters like hemisphere, radius, and mask. It loads precomputed data if available, computes searchlights otherwise, and supports caching. Returns vertex indices (and distances if specified) for each searchlight, ensuring compatibi...
def get_searchlights( lr, radius, mask_space='fsaverage', icoorder=5, return_distances=False, cache=False): """Get searchlight indices based on precomputed files. Parameters ---------- lr : {'l', 'r'} Get the searchlights for the left ('l') or right ('r') hemisphere. radius ...
def LoadStreamData(): stream_data = pd.read_csv('data/raw/stream/nomis-20230320-0855-db.csv') stream_data = stream_data[['patch', 'date [DD.MM.YYYY]','lat_sp [DD]','lon_sp [DD]']] stream_data['Sample'] = stream_data['patch'].apply(lambda x: '_'.join(x.split('_')[0:2])) stream_data.pop('patch') strea...
The main task of the code is to load stream data using LoadStreamData(), gather and process it via GatherData(), and compile the final data structure with CompileData(), sequentially executing these steps to transform raw stream data into a compiled output.
def MainA(): stream_data = LoadStreamData() GatherData(stream_data) CompileData()
def get_all_borders(tile): borders = get_borders(tile) flip = get_flipped_borders(tile) return borders + flip def flip_ud(tile): tile = np.array([list(row) for row in tile]) tile = np.flipud(tile) return [''.join(list(row)) for row in tile] def rotate_left(tile): tile = np.array([list(row) f...
The main task of the code is to find a neighboring tile that can be transformed to match the right border of the given tile. It checks each neighbor's possible borders, applies rotations/flips to align the borders, and returns the first matching neighbor tile once a valid transformation is found.
def get_right(tile, tiles): to_match = ''.join([row[-1] for row in tiles[tile]]) for neigh in tiles: if neigh != tile: bords = get_all_borders(tiles[neigh]) if to_match in bords: idx = bords.index(to_match) if idx == 0: tiles[ne...
def get_all_borders(tile): borders = get_borders(tile) flip = get_flipped_borders(tile) return borders + flip def rotate_left(tile): tile = np.array([list(row) for row in tile]) tile = np.rot90(tile) return [''.join(list(row)) for row in tile] def flip_ud(tile): tile = np.array([list(row) fo...
The main task of the code is to find a neighboring tile that can be positioned below the given tile by aligning their borders through rotations and flips. It checks each neighbor's borders, applies transformations to match the target border, and returns the identifier of the properly oriented neighboring tile.
def get_below(tile, tiles): to_match = tiles[tile][-1] for neigh in tiles: if neigh != tile: bords = get_all_borders(tiles[neigh]) if to_match in bords: idx = bords.index(to_match) if idx == 0: tiles[neigh] = tiles[neigh] ...
def make_view(mystery_phrase: str) -> str: """Return a string that is based on mystery_phrase, with each alphabetic character replaced by the constants.MYSTERY_CHAR character. >>> make_view('apple cake is great! #csca08') '^^^^^ ^^^^ ^^ ^^^^^! #^^^^08' >>> make_view('a08@#$&') '^08@#$&' ...
This function plays a word-guessing game where players or a computer take turns guessing consonants/vowels in a mystery phrase. It tracks scores, updates the revealed letters, and determines the winner when the phrase is solved or the game ends. The game type (PVP/PVE) dictates turn logic, with the computer using selec...
def play_game(mystery_phrase: str, mystery_phrases: list[str], game_type: str) -> None: """Play the game!""" view = make_view(mystery_phrase) consonants, vowels = ALL_CONSONANTS, ALL_VOWELS player_one_score, player_two_score = 0, 0 current_player = PLAYER_ONE if game_type == PVE:...
def _authfile_token_expiry(self): return self._token_from_authfile().get('expiry', 0) def _authfile_is_valid(self): if datetime.now() < datetime.fromtimestamp(self._authfile_token_expiry()): return True return False def _token_from_authfile(self): try: filecontent...
The code's main task is to authenticate by checking if the current time is before the token's expiry. If not, it validates the auth file; if valid, it retrieves the access token, otherwise it renews the authentication.
def _authenticate(self): if datetime.now() < datetime.fromtimestamp(self._authfile_token_expiry()): return if self._authfile_is_valid(): self.access_token = self._token_from_authfile() else: self._renew_auth()
def moveToChest(arg_agent_host, chest_num): global agent_position if agent_position == chest_num: return if chest_num != -1: print(f"Moving to chest #{chest_num} ..") if agent_position - chest_num < 0: moveLeft(arg_agent_host, 2 * abs(agent_position - chest_num)) else: ...
The code performs a brute-force retrieval of items from multiple chests by distributing required quantities into chunks of 64, iterating through each chest to collect items, and swapping them into the agent's inventory. It processes inventory needs, tracks filled items, and halts once all requirements are met, using ti...
def bruteForceRetrieve(arg_agent, values: dict, size): # Reformatting the values into easily distributable sections (stacks of 64 presumed) inventoryNeeds = [] toFill = {} for i in values.keys(): if i not in toFill: toFill[i] = [] while values[i] > 64: inventoryNe...
def moveToChest(self, chest_num, force=False): if self.agent_position == chest_num: return 0 if self.agent_position - chest_num < 0: result = self.moveLeft(2 * abs(self.agent_position - chest_num), force) else: result = self.moveRight(2 * abs(self.agent_positi...
The main task of the code is to optimally retrieve specified quantities of items from chests, considering their positions and stochastic failure probabilities. It generates an action plan to collect items, calculates movement and operation costs, and returns the total retrieved items and score, prioritizing closest che...
def optimal_retrieve(self, inputRetrieve: dict): """ input: dict of objects to retrieve in format of {key: object_id, value: number to retrieve} Assumed that the self._itemPos is properly updated and kept done well """ action_plan = [] result = {} for item...
def moveToChest(self, chest_num, force=False): if self.agent_position == chest_num: return 0 if chest_num != -1 and self._print_logs: print(f"Moving to chest #{chest_num} ..") if self.agent_position - chest_num < 0: result = self.moveLeft(2 * abs(self.agent_p...
The main task of the code is to optimally retrieve specified quantities of items from chests, considering stochastic failure rates, by generating an action plan that minimizes movement. It calculates a score based on chest operations, item retrieval, and position adjustments, returning both the retrieval results and th...
def _optimal_retrieve(self, input: dict): """ input: dict of objects to retrieve in format of {key: object_id, value: number to retrieve} Assumed that the self._itemPos is properly updated and kept done well """ if self._print_logs: print(self._itemPos) ...
def fillRandomInput(inputs, distribution): input_stream = [] for x in range(inputs): appendValue = "" for item, prob in distribution: if random() < prob: appendValue += f"{item}:{randint(5) + 1}" break input_stream.append(appendValue) retur...
The code implements a brute-force method for item retrieval in a maze using the Malmo platform. It allows users to define maze size and item probability distributions, then simulates agent navigation to collect specified items. The function handles random, user-defined, and training modes, tracking steps taken and perf...
def bruteForce(): global agent_position # Create default Malmo objects: agent_host = MalmoPython.AgentHost() size = -1 itemDist = [] valDist = {} probTotal = 0 EPSILON = 0.0001 while size == -1 or itemDist == []: try: if size == -1: size = int(inp...
def moveToChest(self, chest_num, force=False): if self.agent_position == chest_num: return 0 if chest_num != -1 and self._print_logs: print(f"Moving to chest #{chest_num} ..") if self.agent_position - chest_num < 0: result = self.moveLeft(2 * abs(self.agent_p...
The code implements a reinforcement learning environment step function that processes an action, updates the agent's environment state by placing items in chests, calculates rewards based on successful placement or failure after a step limit, and returns the new observation, reward, termination status, and additional i...
def step(self, action): """ Take an action in the environment and return the results. Args action: <int> index of the action to take Returns observation: <np.array> flattened array of obseravtion reward: <int> reward from taking action do...
def setup_ships(self, size, player, count): """ Setup all the ships of a particular size for a certain player. Sets up all of the length-n size ships for a player. Count is not updated in-place. Parameters ---------- size : int Length of the ships. ...
The code initializes and runs a two-player ship battle game, handling setup (ship placement) and play phases. It manages human/CPU player interactions, randomizes CPU ship placement, and executes turn-based attacks until a winner is determined, returning the winning player's zero-indexed number.
def start_game(self): """ Start a new game. Starts a game with the settings provided in the constructor. All game code is contained here, with relevant helper methods also called here. Every game has two stages: Setup and Play. Returns ------- int ...
def prepare_descriptors(self, x): batched_inputs, images, raw_outputs, fpn_outputs = x x, img_size_dict, boxlists, inst_labels = self.get_init_descriptors(batched_inputs, images) nr_gt_per_img = torch.LongTensor([ts.size()[0] for ts in x]) return x, nr_gt_per_img, img_size_dict, boxlists...
The code processes input features through spatial transformation networks (STN) to generate descriptor and feature transformation matrices. It applies convolutional layers with batch normalization and ReLU, combines transformed features with hierarchically pooled global features, and averages outputs to produce a final...
def forward(self, x0): ''' Input: x0: input information: a tuple of (batched_inputs, images, r_features, features) Output: x: output tensor with shape (T, 256) trans_matrice_desc: (T*R, k, k) trans_matrice_feat: (T*R, 64, 64) boxlists: ...
def run_query(endpoint, query): runner = Runner() results = runner.run_cmd(endpoint=endpoint, query_file=query) return results def create_sparql(id: str, query: str, input: dict): for var_name, values in input.items(): values = list(map(lambda x: "<"+x+">", values)) query = query.replace(f"{var_na...
This function executes a series of tests against multiple endpoints using predefined queries, compares results with expected outcomes, and generates a markdown report. It iterates through each test case, runs SPARQL queries via specified endpoints, documents input terms and labels, and logs pass/fail statuses. The repo...
def run_tests(tests: dict, report: MdUtils): endpoints = tests["query_mechanism"].keys() for test in tests['tests']: for e in endpoints: query = tests['query_mechanism'][e]['query'] results = run_query(e, create_sparql(tests['id'], query, test['input'])) report.new_paragraph(text=test['test'],...
def GetLedgerLot(self, address): return_lot = None lot = Lot.objects.filter( address_full__icontains=address ) if lot.count() == 1: return_lot = lot elif lot.count() > 1: print('Multiple lots returned for address', address) elif lot.count() == 0: if '-' in address: ...
The main task of the code is to process a DataFrame by filling missing values in specific columns with 0.00, then iterate through each row to retrieve related ledger data (lot, plat, account), evaluate agreements and credits, and create new ledger entries for each agreement set. The function prepares and stores ledger ...
def AddNewLedgers(self, df): df['Roads'] = df['Roads'].fillna(0.00) df['SewerTransmission'] = df['SewerTransmission'].fillna(0.00) df['SewerCapacity'] = df['SewerCapacity'].fillna(0.00) df['Parks'] = df['Parks'].fillna(0.00) df['OpenSpace'] = df['OpenSpace'].fillna(0.00) df['Stormwater'] = df['S...
def insert_child(x: str, u: SuffixTreeNode, j: int, d: int) -> SuffixTreeNode: """ Takes a string, an internal node, a suffix index and distance to root. Inserts leaf node as child of internal node. Returns leaf node """ leaf = SuffixTreeNode((j + d, len(x)), parent=u, label=j) u.add_child(x...
The function constructs a Suffix Tree using McCreight's algorithm. It iterates over suffixes of the input string $x$, managing suffix links and inserting nodes. For each suffix, it identifies the appropriate parent node via suffix search, splits edges when necessary, and adds new leaf nodes. The process ensures linear-...
def mccreights_st_construction(x: str) -> SuffixTree: """ Iterate over suffixes x[i,n]$ for i in range(1,n). 1. Get parent v of last leaf i-1. 2. Suffix_search(v) returns node w. 3. Set suffix link of v to w. 4. From w, use naive_scan to find h(i). 5. Make internal node, ...
def dwi_config(config: dict, root: str, ID: str, env_path: str): ''' Convert the regex file pattern in config into specific files ''' cf = {} cf["T1"] = _add_ID([config["T1"]], root, ID)[0] # cf["FLAIR"] = _add_ID([config["FLAIR"]], root, ID)[0] if "exception" in config.keys(): cf["e...
This code processes diffusion-weighted imaging (DWI) data by iterating through subject IDs, selecting a subset based on parallel processing parameters (num, arrayID), configuring processing settings, and executing a pipeline for co-registration with T1 images, eddy correction, and other neuroimaging tasks. It skips exc...
def run(self, num=1, arrayID=0): all_IDs = sorted(os.listdir(self.opt["root"]+"/"+self.one_cf["ID"])) for index, i in enumerate(all_IDs): # only run at a specific cpu (arrayID) out of a total of (num) # this is specified in a slurm script if index % num == arrayID: ...
def build_anno(self, xml_node): anno_node = AnnoTreeNode() if "root" in xml_node.tag: anno_node.tag = "root" else: anno_node.tag = "topic" utt_keys = [] for entry in xml_node: if entry.tag=="topic": if entry: ...
The code loads and processes XML annotation files for each meeting by parsing the XML, building a normalized annotation tree structure, attaching meeting-specific notes, and finalizing the tree. It stores the processed trees and their indices in dictionaries for later use.
def load_anno_tree(self): anno_dir = self.anno_dir self.annos = {} self.leaves = {} self.anno_indices = {} for meeting in self.meetings: anno_xml_fnm = f"{anno_dir}/{meeting}.topic.xml" if not os.path.isfile(anno_xml_fnm): logger.error...
def load_all_words(self): self.words = {} for meeting in self.meetings: self.words[meeting] = self.load_meeting_words(meeting) def load_all_utterances(self): self.index = {} for meeting in self.meetings: self.index[meeting] = {} meeting_utteranc...
The main task of the code is to initialize a dataset by loading all words, building segments from utterances using those words, and loading an annotation tree structure to organize the data hierarchically. This prepares the dataset for further processing or analysis.
def load_dataset(self): # Loads all words self.load_all_words() # Loads seg files and uses words to build segments. self.load_all_utterances() # Loads annotation tree self.load_anno_tree()
def get_array(rule): if rule in ['0', 'False', 0, 'false']: return np.asarray([0]), [] elif rule in ['1', 'True', 1, 'true']: return np.asarray([1]), [] rule = rule.replace(' and ',' & ').replace(' or ',' | ').replace('not ','~').replace("E","__E__") tokens = get_tokens(rule) if len(tokens)==0: retu...
This function removes irrelevant regulators and their corresponding leaves from a rule array. It calculates the number of regulators based on the rule's length, identifies irrelevant regulators, and excludes their associated leaves. The output is a pruned rule array and a filtered list of regulators, effectively simpli...
def remove_irrelevant_regulators(rule, regulators=None): if type(rule)==str: rule, regulators = get_array(rule) if len(rule)==0: return rule, [] n_regulators = int(np.round(np.log2(len(rule)))) if regulators is None: regulators = list(range(n_regulators)) irrelevant = detect_irrelevant_regulato...
def camera_to_agent_position(self): self.reset_camera(**self.current_builder_position) def move_camera(self, x=0, y=0, z=0, yaw=0, pitch=0): self.camera.move(x=x, y=y, z=z, yaw=yaw, pitch=pitch) print(self.camera) self.camera.apply() def prev_dialog_step(self): return self.change...
This code handles real-time camera control in a Pygame application, processing continuous key inputs for movement (WASD/arrows) and discrete actions (brackets, 1/2, etc.) to switch camera views or toggle settings. It continuously checks for key presses, updates the camera position/angle, and redraws the display, mainta...
def run(self): while True: # CONTINUOUS ACTIONS shift_pressed = lambda: pygame.key.get_mods() & pygame.KMOD_SHIFT pressed_keys = pygame.key.get_pressed() if (pressed_keys[pygame.K_SPACE]): #reset self.camera_to_agent_position() if (pres...
def slide_left_and_merge(self, board): result=[] score = 0 for row in board: row = np.extract(row>0,row) score_, result_row = self.try_merge(row) score+= score_ row = np.pad(np.array(result_row), (0, self.width - len(result_row)), 'con...
This code handles a game step in a sliding tile game (e.g., 2048). It rotates the board based on the action, slides/merges tiles left, rotates back, adds a new tile, updates the score, and refreshes the UI. It returns the updated board, reward, game status, and empty info.
def step(self, action:int): rotated_obs = np.rot90(self.board, k=action) reward, updated_obs = self.slide_left_and_merge(rotated_obs) self.board = np.rot90(updated_obs, k=4 - action) self.place_random_tiles(self.board, cnt=1) done = self.is_done() self.score += r...
def slide_left_and_merge(self, board): result=[] score = 0 for row in board: row = np.extract(row>0, row) score_, result_row = self.try_merge(row) score += score_ row = np.pad(np.array(result_row), (0, self.width - len(result_row)), 'c...
The code implements a game step in a sliding tile puzzle (e.g., 2048). It rotates the board based on the action, slides and merges tiles, reverses the rotation, adds a new random tile, checks game completion, and returns the updated board, reward, done status, and empty info.
def step(self,action:int): rotated_obs = np.rot90(self.board, k=action) reward, updated_obs = self.slide_left_and_merge(rotated_obs) self.board = np.rot90(updated_obs, k=4 - action) self.place_random_tiles(self.board, cnt=1) done = self.is_done() return ...
def get_terminal_width() -> int: """ Returns the width of the terminal. Usage: get_terminal_width() """ try: return os.get_terminal_size().columns except OSError: return 80 def print_color(text: str, color: Optional[Union[str, List[str]]] = None) -> None: """ Prints text ...
The function prints text in the terminal with visible dark cyan borders made of '█' characters, ensuring readability. It handles both single strings and lists, splitting text into lines and wrapping each in dark cyan. The output is framed with '█' lines above and below, enhancing visibility.
def print_visible(text: Union[str, List[str]]) -> None: """ Prints text in the terminal so that it is visible. This is printed with a ton of newlines filled with █, all in dark cyan Usage: print_visible("Hello world!") """ width = get_terminal_width() - 1 print("") print_color("█" * widt...
def get_videotype(duration): if duration == "0": type = "LN" category = "Live" else: type = "CP" category = "Video" return type, category def get_mediaclassification(mediaduration): try: if int(mediaduration) == 0: mediaclassification = "Live" ...
The function extracts media metadata from a CMS data structure, constructs a structured payload with video details (ID, duration, title, URLs, classification), handles exceptions by defaulting to "NA", and combines it with a GFK object and platform-specific prefixes for video processing.
def get_videoobject(onecms, playeros, site, path, platform): try: mediaid = onecms[0]["mid"][0]["value"] except: raise Exception("Invalid ID") try: mediaduration = str(round(float(onecms[0]["field_duration"][0]["value"]))) except: mediaduration = "0" try: medi...
def get_useragent(resource_name, platform): """ Returns a custom user agent for lambda function Arguments: resource_name (str): Lambda function name platform (str): platform of the client Returns: (str): custom user agent ...
The main task of the code is to build a payload for media data processing by fetching details from an API or using predefined radio station data. It extracts parameters from the event, constructs an API request, handles OS detection, and returns either a pre-defined radio object or processed API data. Errors are logged...
def build_payload_seithi(event, resource_name): try: id = event["id"] platform = event["platform"] site = event["site"] path = event["path"] ##### Sitelang is harcoded because API was returning other language values according to the passed query string parameters RADI...
def compute_j_regularization(m, matrix_x, matrix_teta, matrix_y, r_factor): v = calculate_residual(matrix_x, matrix_teta, matrix_y) first_element_reg = np.array([0]) elements_reg = np.dot(matrix_teta[1:].transpose(), matrix_teta[1:]) regularization_matrix = np.append(first_element_reg, elements_reg...
This function performs gradient descent with regularization to optimize parameters (teta_vector) by iteratively updating them using gradient steps. It calculates the cost with regularization, monitors the change in cost, and stops when the change falls below a threshold (alpha). The process continues until convergence,...
def gradient_descent_regularization(teta_vector, m, matrix_x, y_vector, learning_rate, r_factor, alpha = 10**-14): cost = [] cost.append(compute_j_regularization(m, matrix_x, teta_vector, y_vector, r_factor)) next_teta_vector = gradient_step_regularization(m, teta_vector, matrix_x, y_vector, learning_rate, ...
def load_data(file = "ex1data.txt"): data = np.loadtxt(file, delimiter=",", unpack=False) return data def gradient_descent(teta_vector, m, matrix_x, y_vector, learning_rate, alpha = 10**-14 ): cost = [] cost.append(compute_j(m, matrix_x, teta_vector, y_vector)) next_teta_vector = gradient_step(m, te...
The code performs linear regression on a dataset, splitting it into training and test sets. It initializes parameters, applies gradient descent to minimize cost, and evaluates regularization effects by computing RMSE for both training and test data. Finally, it plots the original data and regression lines from both reg...
def main(): data = load_data("ex1data.txt") # /// Shuffle dataset #np.random.shuffle(data) # ///////////////////////////////////////////////////////////////////////////// # /// Exercicio 1 /// # ///////////////////////////////////////////////////////////////////////////// data_len = len(data) tra...
def set_model_from_file(self,filename): params = [] with open(filename,"r") as file: reader = csv.reader(file,delimiter=",") for row in reader: params.append(row) # iterate over each row starting with topology self.topology = [int(params[1][i]) for...
This code initializes a neural network model with customizable topology, optimizers, activation functions, and weight initializers. It validates input parameters, sets up layer-specific initializers and activations, configures the optimizer, and prepares the model structure. The code handles both default and user-defin...
def __init__(self, topology: list=[], optimizer='SGD', opt_params=[], activation=None, act_params=[], initializer=None, init_params=[], loss: str='mean_squared_error', filename=None, use_auc=False ): self.topology = topology ...
def rte2idx(rtein): # """ # RTE2IDX Convert route to shipment index vector. # Params: # rte = route vector # = m-element list of m route vectors # Returns: # idx = shipment index vector, such that idx = rte(isorigin(rte)) # = m-element list of m shipment index vectors ...
This function inserts route i into route j with minimal cost, considering shipment locations and avoiding duplicate insertions. It returns the combined route, its total cost, and original combined cost. If insertion increases total cost and doNaN is True, it returns NaN for the route.
def mincostinsert(rtei,rte,rteTC_h,sh,doNaN=False): # MINCOSTINSERT Min cost insertion of route i into route j. # [rte,TC,TCij] = mincostinsert(rtei,rte,rteTC_h,sh,doNaN) # rtei = route i vector # rtej = route j vector # rteTC_h = handle to route total cost function, rteTC_h(rte) # sh = structure array w...
def train(): global lr global vectorizer # Creating train set dict_train = { 'text': ['Search This Blog', 'nSearch This Blog', 'blog', 'posts', ' Posts ', 'Posts', 'Popular posts from this blog', 'Alexa Top Sites', 'commodities', 'goods', 'raw materials', 'oil', 'metal', 'ba...
The code fetches backlink data from Ahrefs API for a target domain, processes each link by saving it to the database with metadata, predicts categories, calculates domain metrics, traffic, and contact info, then updates the database with these derived values for analysis and storage.
def get_data(): all_links = {} Plus500.objects.all().delete() target_list=['ahrefs.com'] train() # the train of the category model for target in target_list: url = 'https://apiv2.ahrefs.com?from=backlinks&target=' + target + '&mode=subdomains&limit=50&order_by=domain_rating%3Adesc&select=url...
def SyncUpdate(particles): done = True rm_index = [] for i in range(len(particles)): if not(-400 <= particles[i]['pos'].xcor() < 400 and -400 < particles[i]['pos'].ycor() < 400) and i not in rm_index: rm_index.append(i) continue done = False Update(p...
The code simulates particle interactions and decay using a loop, updating a turtle graphics display periodically. It runs up to 10,000 iterations, breaking early if SyncUpdate signals completion. Each iteration handles particle interactions, applies decay with a chance decreasing over time, and updates the screen every...
def Draw(): for i in range(10000): turtle.tracer(0, 0) if SyncUpdate(particles): break if i%3==0: turtle.update() Interact(particles) Decay(particles, chance=500-int(i/10))
def forwardpropagation(self, a): self.A[0] = np.array([a]).T for L in range(self.numLayers-1): Z = np.dot(self.W[L], self.A[L]) + self.B[L] self.A[L+1] = self.sigmoid(Z) return self.A[-1] def backpropagation(self, x, y): #could optimise by simplifying transpositions (i ju...
The main task of the code is to visualize the cost function and its partial derivative with respect to a specific weight in a neural network. It iterates over a range of weight values, computes the associated cost for each by forward-propagating inputs and comparing outputs to targets, then plots the cost curve. It als...
def mapCost(self, x, y, position, value_range=4): if position[0][0]+1 != position[1][0]: print('Invalid weight'); return position = (position[0][0],position[1][1],position[0][1]) print('\nCost Graph:\n Loading...') detail = 1000 original = self.W[position[0]][posit...
def get_generation_scores(self): ''' Runs game for newly created generation, stopped when there is self.num_parents_mating players left ''' self.game.players = [Player(self.game, torchga.model_weights_as_dict(model=Model(), weights_vector=weights)) for weights in self.population] ...
This code runs a genetic algorithm for a specified number of generations. It evaluates each generation's performance, generates new populations, and progresses the game by removing obstacles. After completing all generations, it visualizes the score progression and saves the model's neural network state for future use.
def run(self): ''' Main loop creates new population and selects best instances for next one, self.num_generation times ''' for generation in range(self.num_generations): print(f'Generation: {generation + 1}') self.get_generation_scores() self.c...
def str_to_np(string_data): # Step 1: Remove unnecessary characters cleaned_data = re.sub(r'[()\[\]]', '', string_data) tuple_strings = cleaned_data.split(', ') float_arr = [float(x) for x in tuple_strings] tuple_array = ([(int(float_arr[i]), int(float_arr[i+1]), int(float_arr[i+2]), int(float_ar...
The main task of the code is to decode a hidden message embedded in an image using steganography, convert it into a numpy array, decompress the data to reconstruct an image, and save/display the resulting image. It also measures the decoding time and visualizes the iterative reconstruction process.
def decrypt(image_result, image_hide): secret_msg = Image.open(image_result) secret_msg = stepic.decode(secret_msg) # secret_msg = b64.b64decode(secret_msg) # print(secret_msg) # secret_msg = secret_msg.decode() transformations = str_to_np(secret_msg) # f = open('lmao2.txt', 'w') # f.wr...
def get_greyscale_image(img): B, G, R = img[:, :, 0], img[..., 1], img[..., 2] greyscale = 0.299 * R + 0.587 * G + 0.114 * B return greyscale def img_reduce(img, factor): new_img = np.zeros((img.shape[0] // factor, img.shape[1] // factor)) for i in range(new_img.shape[0]): for j in range(new...
The code compresses a grayscale image using specified parameters, saves transformation data to a file, decompresses it, and visualizes the iterative decomposition process.
def test_grayscale(image_hide): img = cv.imread(image_hide) img = get_greyscale_image(img) img = img_reduce(img, 4) plt.figure() plt.imshow(img, cmap='gray', interpolation='none') transformations = compress(img, 8, 4, 8) f = open('lmao.txt', 'w') f.write(str(transformations)) f.close...
def get_greyscale_image(img): B, G, R = img[:, :, 0], img[..., 1], img[..., 2] greyscale = 0.299 * R + 0.587 * G + 0.114 * B return greyscale def img_reduce(img, factor): new_img = np.zeros((img.shape[0] // factor, img.shape[1] // factor)) for i in range(new_img.shape[0]): for j in range(new...
The code performs steganography by embedding a processed hidden image into a cover image. It converts the hidden image to grayscale, resizes it, compresses its data, encodes it as a message, and embeds it into the cover image using the `stepic` library, saving the result as a new image.
def encrypt(image_hide, image_cover, image_result): img = cv.imread(image_hide) img = get_greyscale_image(img) img = img_reduce(img, 4) transformations = compress(img, 8, 4, 8) secret_msg = str(transformations) secret_msg = re.sub(r'[()\[\]]', '', secret_msg) secret_msg = secret_msg.encod...
def is_crash_id(crash_id: int) -> bool: """ Returns True if it is a valid integer :param int crash_id: The id to be tested :return bool: """ return str(crash_id).isdigit() def file_exists(crash_id: int) -> bool: """ Returns True if the file exists, False otherwise :param int crash_id...
The main task of the code is to retrieve metadata for a file associated with a given crash ID, including timestamp, file size, MIME type, and encoding. It checks if the file exists and if the crash ID is valid, returning an empty dictionary if invalid. If the file download failed, it defaults file size to 0 and sets MI...
def get_file_metadata(crash_id: int) -> dict: """ Returns a dictionary containing the metadata for a file. It assumes the file already exists in disk. :param int crash_id: :return dict: """ if not is_crash_id(crash_id) or not file_exists(crash_id): return {} timestamp = get_timesta...
def is_crash_id(crash_id: int) -> bool: """ Returns True if it is a valid integer :param int crash_id: The id to be tested :return bool: """ return str(crash_id).isdigit() def download_file(crash_id: int) -> bool: """ Downloads a CR3 PDF file into disk :param int crash_id: The crash ...
The function processes a crash record by validating the crash ID, downloading and verifying the associated file, generating metadata, updating it via GraphQL, and deleting the file. It returns True on success or False if any step fails, ensuring data integrity and cleanup.
def process_record(crash_id: int) -> bool: """ Controls the process for a single file """ if not is_crash_id(crash_id): print(f"Invalid crash_id: {crash_id}") return False # 1. Download file to disk if not download_file(crash_id): print(f"Could not find CR3 file for cras...
def get_subject_directories(simulation_directory): """Get primary subject directories (not including EMG subject directories) held within the simulation directory. Args: simulation_directory (str): path to directory containing simulation results. Returns: subject_directories (l...
The main task of the code is to extract, standardize, and consolidate biomechanical waveforms (e.g., ground reaction forces, kinematics, muscle forces) from multiple subjects' simulation results into a unified DataFrame. All waveforms are resampled to 100 timepoints for consistency, and subject-specific data is merged ...
def generate_summary_waveforms(simulation_directory, print_subjects=True): """extract and standardize waveforms (ground reaction forces, kinematics, kinetics, joint reaction forces, muscle forces, and joint powers) for all subjects with simulation results. All standardized waveforms are resampled to 100...
def except_error_if_file_exists(self): if self.check_if_file_exists(): raise FileExistsError("File already exists") def create_folder_if_not_exists(self): if not os.path.isdir(self.folder_path): os.mkdir(self.folder_path) def get_final_file_path(self) -> str: return self....
The main task of the code is to save a downloaded photo to a specified file path. It first checks if the file already exists, creates the necessary directory if missing, retrieves the final file path, downloads the photo, and writes it to the file if successfully retrieved.
def save_photo(self): self.except_error_if_file_exists() self.create_folder_if_not_exists() final_file_path = self.get_final_file_path() photo = self.download_photo() if not photo: return with open(final_file_path, "wb") as file: file.write(photo)
def create_driver(self): self.driver = webdriver.Chrome() def open_bing(self): self.driver.get("https://www.bing.com/") def switch_to_img(self): try: img_btn = WebDriverWait(self.driver, 10).until( EC.presence_of_element_located( ( ...
The code automates downloading photos from Bing using a web driver. It initializes the browser, navigates to Bing, switches to the image section, accepts cookies, searches for a term, applies a photography filter, and loads all resulting photos for further processing or download.
def start_download(self): self.create_driver() self.open_bing() self.switch_to_img() self.accept_cookies() self.search_term() self.choose_fotografy_filter() self.load_all_photos()
def askforbookquantity(): global qty #declaring a global variable qty a=input("Please enter the quantity: ") #taking input of quantity qty=int(a) #saving the quantity as qty #comparing the inserted quantity of user to check if it is less than or equal to zero if(qty <= 0): print("Quantity ca...
The main task of the code is to handle book borrowing requests by checking book availability in a list, collecting quantities, updating global variables (book ID, name, quantity), and triggering subsequent functions for borrowing, pricing, and file updates. It allows users to borrow multiple books via a loop and ensure...
def askforbook(): global qnty #declaring a global variable qnty qnty=[] #declaring an empty list to save the quantities of book val=False #declaring the boolean value of val as false to make the user to borrow another book global bookname #declaring a global variable bookname bookname=[] #declaring ...
def getData(): # with open("2022/Day_08/TestData.txt") as file: with open("2022/Day_08/Data.txt") as file: data = file.read().splitlines() # print(data) array = np.empty([len(data), len(data[0])]) for j, item in enumerate(data): for i, number in enumerate(item): n = int(n...
The main task of the code is to process tree data by calculating two metrics: the number of visible trees from the outside and the highest scoring tree's points. It retrieves data, computes visibility and scores, then prints the results for both parts.
def main(): data = getData() visibleTrees = getVisTrees(data) print("Part One: Visible amount of trees from the outside %s"%(visibleTrees)) treeScore = getTreeScore(data) print("Part Two: Best Scoring Tree has %s points" %(treeScore))
def ad_hoc_GETS(FF_summary, df_factors, df_stocks): df = pd.DataFrame(index = FF_summary.index, columns = FF_summary.columns) final_models = [] for i in df.index: if i == 'Mean': continue #Create an object to be compatible with the functio...
The function identifies structural break dates in stock return models using Chow tests, optimizes regression models by removing irrelevant factors for stocks without breaks, and segments data around detected breaks for stocks with breaks. It returns a dictionary storing optimized model results, including break dates an...
def break_dates_optimization(p_val_df_FF, FF_summary, df_stocks, df_factors): """ PROCEDURE TO FIND BREAK DATES """ """ First we create a dataframe that, for each stock, assign the min_pval of the Chow test and the corresponding date that corresponds to that mini...
def doUpdate(self): # grab the data from the external file cards = self.foreignCards() # grab data from db fields = self.col.db.all(""" select noteId, value from fields where fieldModelId = :id and value != ''""", id=self.updateKey[1]) # hash it ...
The main task of the code is to import foreign cards into a collection, potentially randomizing their order if specified, updating card tags, and marking the collection as modified. It first checks for an update key to trigger a doUpdate() method; if absent, it retrieves foreign cards, imports them, updates tags, and a...
def run(self): "Import." if self.updateKey is not None: return self.doUpdate() random = self.col.newCardOrder == NEW_CARDS_RANDOM num = 6 if random: num += 1 c = self.foreignCards() if self.importCards(c): self.col.updateCardTag...
def read_memory(self, address, offsets, readfunc, default=0): if address == 0: return default addr, last = self.offset_address(address, offsets) if addr == 0: return default return readfunc(addr + last) def offset_address(self, address, offsets): address ...
This code retrieves player data from a game's memory by reading specific offsets, parsing player information, and separating the local player from others. It reads memory addresses, iterates through player entries, and returns a list of players along with the local player object.
def get_all_players(self): allPlayersPtr = self.read_memory(self.base_addr, self.offsets['allPlayersPtr'], self.pm.read_ulonglong) & 0xffffffff allPlayers = self.read_memory(allPlayersPtr, self.offsets['allPlayers'], self.pm.read_ulonglong) playerCount = self.read_memory(allPlayersPtr, self.offs...
def get_all_players(self): allPlayersPtr = self.read_memory(self.base_addr, self.offsets['allPlayersPtr'], self.pm.read_ulonglong) & 0xffffffff allPlayers = self.read_memory(allPlayersPtr, self.offsets['allPlayers'], self.pm.read_ulonglong) playerCount = self.read_memory(allPlayersPtr, self.offs...
The main task of the code is to retrieve and return game-related data by reading player information, game state, and game code. It first checks if `self.pm` exists; if not, it returns `None`. Otherwise, it gathers all players and the local player, then constructs a `MemoryRead` object with these data along with the gam...
def read(self): if not self.pm: return None players, local_player = self.get_all_players() return MemoryRead(players=players, local_player=local_player, game_state=self.get_game_state(), game_code=se...
def ddothi(self): global chedo if chedo == 1: for i in range(0, len(dothi)): self.canvas.create_line(dothi[i][1], dothi[i][0], dothi[i][3], dothi[i][2], fill='yellow', width=1) if pt[0][0] != 0: for i in range(0, len(points)): i...
The code toggles a state variable `chedo` between 0 and 1. When `chedo` is 1, it executes `ddothi()` and conditionally `dtrace()` if `dh` is true. When `chedo` is 0, it runs `ve()` and similarly calls `dtrace()` if `dh` is true. The primary task is to switch between two operational modes (ddothi/ve) and conditionally e...
def chg(self): global chedo, dh chedo ^= 1 if chedo == 1: self.ddothi() if dh: self.dtrace() else: self.ve() if dh: self.dtrace()
def is_const(e): if len(e) != 1: return False t = str(e[0]) if 'a' <= t[0] <= 'z': return True return False def is_variable(e): if len(e) != 1: return False t = str(e[0]) if 'A' <= t[0] <= 'Z': return True return False def apply(subs, e): for s in su...
This code performs unification of two terms (e1 and e2) in a logic programming context. It recursively checks if terms can be made equal by substituting variables, returning a list of substitutions if successful or -1 if unification fails. It handles constants, variables, and nested structures, ensuring variables are n...
def unify(e1, e2): # e1, e2 is in list of string form # e.g. e1 = p(X, Y) -> e1 = ['p', 'X', 'Y'] if (is_const(e1) and is_const(e2)) \ or (len(e1) == 0 and len(e2) == 0): if e1 == e2: return [] else: return -1 if is_variable(e1): if e1[0] in e2...
def get_next_board(self, dir: MoveDirection): next_board = Board(self.width, self.height) points = 0 merges = 0 blocks_moved = 0 field, sorting_order = SORTING_CONFIG[dir] row_range = ( range(self.height - 1, -1, -1) if field == "row" and sorting...
This function handles a game move in the specified direction, updates the board state, increments the score, and optionally spawns a new tile. It returns the points earned, number of blocks moved, and merge events resulting from the move.
def move(self, dir: MoveDirection, spawn_after=True): if dir not in self.can_move: return 0 next_board, points, blocks_moved, merges = self.get_next_board(dir) self.score += points if spawn_after: self.spawn(next_board) self.board = next_board s...
def get_square(self, row: int, col: int): idx = self.coord2idx(row, col) if idx < 0: return None return self.squares[idx] def get_square_neighbor(self, row: int, col: int, dir: MoveDirection): if not self._is_valid_coords(row, col): return None if dir == M...
This function determines the farthest valid square a piece can move in a specified direction from a given position, checking each subsequent square in that direction until an invalid move is encountered or the edge of the board is reached.
def get_square_valid_movement(self, row: int, col: int, dir: MoveDirection): sqr = self.get_square(row, col) if sqr == None or sqr.value == 0 or sqr.is_wall: return None neighbor = self.get_square_neighbor(row, col, dir) selectedNeighbor = None while neighbor != Non...
def generate_basic_link(link: dict, context) -> str: """Generate html code for a simple link with a tag and href populated.""" if "link_type" in link and link["link_type"] == "external": return f""" <li class="nav-item"> <a class="nav-link" href="{link["url"]}" target="_blank"> {li...
The function generates HTML navbar links from a configuration in `context`, creating direct links for entries with "url", dropdown menus for entries with "children" (using sub-links), and section-based dropdowns for entries with "sections". It returns the combined HTML string of these links.
def generate_navbar_links() -> str: """ Generate different links for navbar_links configuration. """ links = context.get("theme_navbar_links") html_links = [] for link in links: # If "url" is present: direct link if "url" in link: html_links.append(generate_basic_link(link...
def get_contributors(github_project: str, github_repo: str, contributors_details: list = None): """Fetch list of contributors from github.""" page = 1 contributors = [] while (True): url = (f"{BASE_URL}repos/{github_project}/{github_repo}/" + f"contributors?p...
The main task of the code is to populate the Sphinx build context with GitHub-related team data. It retrieves contributor details, team statistics, and team member information from GitHub using configuration values like `github_project` and `github_repo`, then stores these in `html_context` for use during documentation...
def add_team_details( app: Sphinx ) -> None: """Add team deatils in the context""" # Fetching theme configurations theme_conf = app.config.html_theme_options # Registering functions for context to access while building context = app.config.html_context if "github_project" not in theme_conf...
def tokenizerPF(tokenList): s = Stack() k = 0 for item in tokenList: #print('current stack ') #s.printS() if isLetter(item) is True: #if operand tokensListPF.append(item) #important idea here is that the parens are taken into consideration for precedence but neve...
The main task of the code is to convert a user-input logical sentence into postfix notation, construct an expression tree from the postfix form, transform the tree into Conjunctive Normal Form (CNF), and output the resulting CNF expression. The process involves tokenization, postfix conversion, tree construction, CNF t...
def main(): tmp = input("enter your logical sentence\n") tokenList = tmp.split(" ") tokenizerPF(tokenList) # convert the tokens now to postfix order print('postfix str ', tokensListPF) #now create an expression tree from the postfix equation eT = constructExpTree() toCNF(eT) tList = pri...
def addNodeIfPossible(self, pos, items): if not items and not self.selectedEdges and not self.selectedNodes: self.addNode(pos) def selectionRoutineEnd(self, select=True): if self.nodePressed or self.lastMousePress is None: return selected = self.scene().items(self.selecti...
This method handles mouse release events by calling the parent class's implementation, mapping the event position to the scene, and checking the released button. For left-clicks, it adds a node if possible and ends a selection routine based on modifier keys. For right-clicks, it ends a drag operation. The logic involve...
def mouseReleaseEvent(self, event: QMouseEvent): super().mouseReleaseEvent(event) pos = self.mapToScene(event.pos()) items = self.scene().items(pos) if event.button() == Qt.LeftButton: self.addNodeIfPossible(pos, items) self.selectionRoutineEnd(event.modifiers()...
def _read_region_downsample( self, x_y: tuple[int, int], downsample: float, tile_size: tuple[int, int], downsample_base_res: bool, interpolation: Interpolation, ) -> np.ndarray: if downsample <= 0: raise ValueError("Downsample factor must be positi...
This function reads a specified region from a slide image at a given resolution, supporting level, downsample factor, or MPP units. It adjusts tile size, applies downsampling or level-based reading, and normalizes pixel values if requested. The result is returned as a NumPy array of pixel data.
def read_region( self, x_y: tuple[int, int], resolution: int | float, tile_size: tuple[int, int] | int, normalize: bool = False, downsample_base_res: bool = False, resolution_unit: Resolution = Resolution.LEVEL, interpolation: Interpolation = Interpolation...
def find_latest_training_file(self, bucket, folder, type): print('Finding latest training file...') last_training_file = None last_training_date = datetime.datetime(2000, 1, 1, 0, 0, tzinfo=tzutc()) files = s3.list_objects(Bucket = bucket, Prefix = folder) for file in files['Co...
The main task of the code is to process the latest training data file by identifying it from a specified bucket and prefix, reading its contents, and transforming the raw data using provided parameters. The function retrieves the most recent file, loads its data, and applies a transformation to prepare it for further p...
def transform_from_file(self, params): train_bucket = params['train_bucket'] train_set_prefix = params['train_set_prefix'] latest_training_file = self.find_latest_training_file(train_bucket, train_set_prefix, self.input_file_type) print("Latest training file is " + latest_training_file)...
def get_tiff_stack( index, path_to_tiff_folders="/Volumes/FreeAgent GoFlex Drive/DanforthXRAYData/" ): """ Get information about TIFF files in a specified directory. Args: index (int): The index of the desired tiff_stack. path_to_tiff_folders (str, optional): Path to the directory conta...
The function extracts a vertical slice from a 3D X-ray stack at a specified row, enhances it by normalizing pixel values using median background noise and container density values calculated from subsampled slices, and displays the result as a grayscale image with dynamic contrast adjustment. It returns the processed v...
def display_vertical_xray_slice(stack_index, target_row, figure_size = 7): """ Extract a vertical image slice from a 3D X-ray stack for a specified row. Parameters: stack_index (int): Index of the 3D X-ray stack. target_row (int): The row index for which the vertical slice is extracted. ...
def get_masks(path_to_tiff_stack, filename): """ Generate masks for different regions within an image based on circle parameters estimated from another image. Parameters: path_to_tiff_stack (str): Path to the directory containing TIFF images. filename (str): Name of the TIFF image file to u...
The function `get_stats` processes a TIFF image to compute statistical features for image analysis. It loads an image, applies optional denoising, extracts core/outer/container regions, calculates sliding window statistics (skewness, kurtosis, variance), detects edges, and normalizes values relative to outer/container ...
def get_stats( tiff_index, stack_index, window_size, skip, denoise, display_progress, tiff_files_sorted, path_to_tiff_stack, ): """ Calculate various statistics from an image. Args: tiff_index (int): Index of the TIFF image. stack_index (int): Index of the st...
def get_tiff_stack( index, path_to_tiff_folders="/Volumes/FreeAgent GoFlex Drive/DanforthXRAYData/" ): """ Get information about TIFF files in a specified directory. Args: index (int): The index of the desired tiff_stack. path_to_tiff_folders (str, optional): Path to the directory conta...
This function visualizes image statistics (skewness, kurtosis, variances, edges) of a specific TIFF image from a 3D X-ray stack using sliding windows. It loads the image, applies denoising if enabled, calculates statistical features, and displays them in subplots with appropriate visualizations and labels.
def visualize_sliding_window_statistics( tiff_index, stack_index, window_size, skip, denoise, show_progress ): """ Visualize various image statistics for a specific TIFF image in a 3D X-ray stack. This function processes a specific TIFF image from a 3D X-ray stack, calculates statistics such as ske...
def get_tiff_stack( index, path_to_tiff_folders="/Volumes/FreeAgent GoFlex Drive/DanforthXRAYData/" ): """ Get information about TIFF files in a specified directory. Args: index (int): The index of the desired tiff_stack. path_to_tiff_folders (str, optional): Path to the directory conta...
The code generates and displays heatmaps of logarithmic X-ray intensity histograms for three regions (core, container, outside) across depths in a TIFF stack. It processes images in skips, calculates histograms with a small epsilon to avoid division by zero, and visualizes results with depth (cm) on y-axis and intensit...
def intensity_histogram_by_depth(stack_index, tiff_skips, slice_thickness_cm=0.0039, max_intensity=17000): """ Generate and display heatmaps of logarithmic histogram counts of x-ray intensities for different depths. Parameters: stack_index (int): The index of the stack. tiff_skips (int): Th...
def get_tiff_stack( index, path_to_tiff_folders="/Volumes/FreeAgent GoFlex Drive/DanforthXRAYData/" ): """ Get information about TIFF files in a specified directory. Args: index (int): The index of the desired tiff_stack. path_to_tiff_folders (str, optional): Path to the directory conta...
This function calculates and plots intensity statistics (1st, 50th, 99th percentiles, mean, standard deviation) for three regions—soil core, plastic container, and outside—across depths in a 3D X-ray stack. It processes images at intervals defined by 'skip', converts indices to depth in cm, and visualizes statistical t...
def plot_intensity_stats_by_depth(stack_index, skip): """ Plot intensity statistics for different regions by depth in a 3D X-ray stack. Parameters: stack_index (int): Index of the 3D X-ray stack. skip (int): Number of slices to skip between calculations. Returns: (list, list, l...
def get_tiff_stack( index, path_to_tiff_folders="/Volumes/FreeAgent GoFlex Drive/DanforthXRAYData/" ): """ Get information about TIFF files in a specified directory. Args: index (int): The index of the desired tiff_stack. path_to_tiff_folders (str, optional): Path to the directory conta...
The function calculates and plots normalized soil density statistics (1st, 50th, 99th percentiles, mean, standard deviation) from a 3D X-ray stack at specified depth intervals. It processes TIFF images, computes statistics for soil core, container, and surrounding regions, normalizes values using container/outside aver...
def plot_soil_density_stats_by_depth(stack_index, skip): """ Plot soil density statistics by depth for a given X-ray stack. Parameters: stack_index (int): Index of the 3D X-ray stack. skip (int): Number of slices to skip between statistics calculations. Returns: Tuple: A tuple ...
def _selectNewGen(prevGen, isMaxFit = True): indices = range(len(prevGen)) #Get a list of all fitness values and convert to percents #Reverse fitness values if attempting to minimize fitness fitnessVals = _getFitnessValues(prevGen) if not isMaxFit: _minModFitness(fitnessVals) _percentFit...
The function `_generateNewGen` generates a new generation in a genetic algorithm by sequentially performing selection, crossover, and mutation on the previous generation (`prevGen`). It selects individuals based on fitness (`isMaxFitness`), applies crossover with specified points and probability (`pointCross`, `probC`)...
def _generateNewGen(prevGen, isMaxFitness = True, pointCross = 1, probC = .8, probM = .1, alpha = .01): _selectNewGen(prevGen, isMaxFitness) _crossNewGen(prevGen, pointCross, probC) _mutateNewGen(prevGen, probM, alpha)