dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def cosine_similarity(x, y): return np.dot(x, y) / (np.linalg.norm(x) * np.linalg.norm(y)) def intra_cluster_distance(sample, cluster): distances = [cosine_similarity(sample, other) for other in cluster] return sum(distances) / len(distances) def nearest_cluster_distance(sample, clusters): distances = [...
This code performs KMeans clustering on input data using cosine similarity to assign data points to clusters. It initializes cluster centers randomly, iteratively updates them by averaging points in each cluster, and assigns labels post-clustering. The algorithm computes the Silhouette coefficient to evaluate cluster q...
def kmeans_clustering(data, k=3, num_iterations=20): # Initialize the cluster means as k distinct data points cluster_means = data[np.random.choice(len(data), size=k, replace=False)] # Perform the iterations for i in range(num_iterations): # Assign each data point to the nearest cluster ...
def intersect(self, arc, point): if(arc is None or point is None): return None # If the y values are the same, they do not intersect if(arc.point.y is point.y): return None right = None left = None # See if we can intersect between the left and r...
The function handles a "site event" in a computational geometry algorithm, navigating left or right through a structure of arcs based on the point's x-coordinate relative to the arc's key. It checks for intersections between the point and arcs, recursively traversing left or right until it either inserts the point at a...
def site_event(self, arc, point): # We go left as far as we can first if(point.x < arc.key): # Is the left open? if(arc.left is None): # Check if we intersect inter_point = self.intersect(arc, point) # Do we intersect here? ...
def process_site_event(self, event): # If there are no arcs, add this on top if(self.arcs is None): self.arcs = Arc(event.point, event.point.x) # Else, loop through and see where this goes else: done = self.site_event(self.arcs, event.point) # Check i...
The code processes a set of 2D points by inserting them into an event queue as "site events," then iteratively handles each event (either site or circle events) to construct a Voronoi diagram or Delaunay triangulation. It cleans up after processing.
def process(self, points): # First insert points into the event queue as site events for point in points: # Points are np arrays new_point = Point(point[0], point[1]) self.events.push(Event(Event.SITE_EVENT,point=new_point)) # Now process events ...
def read_body(handle: IO) -> list: return [line.replace("\r", "").replace("\n", "") for line in handle.readlines()] def should_skip_class(body: list) -> bool: for line in body: if line.find("Not decompiled") != -1: return True if line.find("createInstance(param1:int) : IModule") != -...
The function serializes a packet configuration from a class definition in a file. It reads the file's body, skips processing if specified, parses module details (name, base, constants, constructor, fields, ID), and returns a structured dictionary for later deobfuscation. The output includes parsed data like module meta...
def serialize_packet_config(handle: IO): body = read_body(handle) # mothafucka # nobody likes this warning x = 9 if should_skip_class(body): # This is probably the module registry print(f"Skipping file {handle.name}") return None module_name, module_base = parse_class_defini...
def spawn(self, threads: int = 100): """ Spawns worker threads. :param threads: number of threads to spawn 1-10000 :return: """ if not 1 < threads < 10000: raise ValueError("Thread number outside supported range [1:10'000]") self.workers = [] ...
The main task of the code is to orchestrate parallel job execution by initializing worker threads, enqueuing/dequeuing tasks, monitoring worker status, committing database transactions, and performing cleanup operations. It manages concurrency control, ensures data persistence, and terminates processes gracefully while...
def initiator(self, workers: int = 100): """ Runs the entire job basically. Starts all threads, retrieves all values, stores the database and does the clenaup. :param workers: number of workers in parallel. :return: """ self.spawn(workers) self.enqueue_jo...
def get_book_id() -> int: """Get book id from user input and check it is in valid format. Returns: book id """ while True: book_id = input( """Please enter a book ID 0. Exit -1. Back : """).strip().lower() try: book_id = int(book_id) match bo...
The function allows a user to select a book by ID, retrieves and displays its details from the database, and then presents an update menu. If the book isn't found, it shows an error. The loop continues until the user cancels or successfully updates the book.
def update_book(conn: Connection): """Ask user to select a book to update and then update it. Arguments: conn -- bookstore db connection """ while True: book_id = get_book_id() if book_id: book = get_book_by_id(conn, book_id) headers = get_headers(book) ...
def search_by_id(conn: Connection): """Allow user to search by id and print results. Arguments: conn -- bookstore db connection """ while True: id = get_book_id() if id: results = get_book_by_id(conn, id) print_results(results) else: r...
The function `search_books_menu` presents a menu for users to search books in a database by ID, author, title, or quantity, or exit. It loops until the user chooses to exit or return. Based on input, it calls specific search functions or uses `search_all` for general terms, handling invalid inputs with error messages.
def search_books_menu(conn): """Print menu allowing user to perfrom a general or more specific search. Arguments: conn -- bookstore db connection """ while True: option = input( """ Please enter your search term to search by ID, Author or Title or choose from the following o...
def get_image(image_path, image_size, is_crop=True, resize_w=64): global index img = cv2.cvtColor(cv2.imread(image_path) ,cv2.COLOR_BGR2RGB) out = transform(img, image_size, is_crop, resize_w) return out def colorize(img): # convert grayscale to rgb by concatenation if img.ndim == 2: img...
This code processes image datasets (ImageNet or LSUN) into TFRecord files for machine learning. It collects image paths, resizes/colorizes images, assigns labels, and stores metadata. For ImageNet, it handles class-specific directories, while LSUN is treated as a single class. The output includes labeled TFRecords with...
def main(args): metadata = {'img_size': args.img_size} files = [] if args.dataset == "imagenet": dirs = glob(os.path.join(args.path,"train/n*")) assert len(dirs) == 1000, len(dirs) shuffle(dirs) dirname = dirs[:] if args.n_class == -1 else dirs[:args.n_class] for d i...
def get_image(image_path, image_size, is_crop=True, resize_w=64): global index out = transform(cv2.imread(image_path), image_size, is_crop, resize_w) return out def colorize(img): if img.ndim == 2: img = img.reshape(img.shape[0], img.shape[1], 1) img = np.concatenate([img, img, img], axi...
The code processes a dataset of images by converting them into TensorFlow TFRecord format, which is optimized for machine learning training. It shuffles image files, maps directories to class labels, saves metadata (number of records and classes) in a pickle file, and serializes each image with its label into a TFRecor...
def main(args): pattern = os.path.join(args.path,"train/n*/*JPEG") files = glob(pattern) assert len(files) > 0 # assert len(files) > 1000000, len(files) #small: 19439 shuffle(files) dirs = glob(os.path.join(args.path,"train/n*")) # assert len(dirs) == 1000, len(dirs) # small: 774 dirs ...
def generate_all_responses_and_embs( gt_prompts, gt_responses, ft_id, emb_model, stop_tokens, embedding_batch_size, max_threads=10, save_to_file=None ): # Get fine-tune model info job_info = together.Finetune.retrieve(fine_tune_id=ft_id) model_name = job_info["model_output_name"] base_model = job_i...
(The main task of the code is to evaluate and compare embeddings from a base model, fine-tuned model, and ground truth data. It calculates Euclidean distances, cosine similarities, and trains classifiers to distinguish embedding groups. Results are visualized using PCA or other decomposition methods, with metrics like ...
def main( examples, emb_model, image_file, ft_id=None, load_file=None, instruction_split=False, max_threads=1, save_file=None, vis_method="pca", classifier="SVC", stop_tokens=[], embedding_batch_size=-1, ): assert ( ft_id is not None or load_file is not None ...
def makeEdgeImage(self, imgBgr:np.ndarray) -> np.ndarray: # Convert to gray scale. imgGray = cv2.cvtColor(imgBgr, cv2.COLOR_BGR2GRAY) # Blur the image to remove noise. imgBlur = cv2.GaussianBlur(imgGray, (self.BLUR_KERNEL_SIZE, self.BLUR_KERNEL_SIZE), self.GAUSS_SIGMA) # Find e...
The code detects corners in an input image by first generating an edge map, identifying corner points, ordering them if exactly four are found, updating a running average for stability, and returning the refined corner coordinates.
def findCorners(self, imgBgr:np.ndarray): imgEdges = self.makeEdgeImage(imgBgr) cornerPoints = self.getCorners(imgEdges) if (cornerPoints is not None and cornerPoints.shape[0] == 4): cornerPoints = self.orderPoints(cornerPoints) self.cornerRunningavg(cornerPoints) r...
def _normalizeText(self, messageText): translator = str.maketrans(' ', ' ', string.punctuation) messageText = messageText.translate(translator).lower() space = " " for key in ['\n', '\t']: messageText = messageText.replace(key, space) return " ".join(filter(None, mes...
The code processes a message by normalizing its text, classifying its intent, and generating a response based on the intent, user context, and channel type. It handles user input to provide appropriate answers in chat or private channels.
def handle(self, message, user, mention, privateChannel=False): message = self._normalizeText(message) intent = self.classifyIntent(message) return self.answerFromIntent( intent, user, mention, privateChannel, message)
def load_yaml(path, default_path=None): with open(path, "r") as f: cfg_special = yaml.full_load(f) inherit_from = cfg_special.get("inherit_from") # if yes, load this config first as default # if no, use the default_path if inherit_from is not None: cfg = load_yaml(inherit_from, defa...
This code parses and merges configuration parameters from a YAML file and command-line arguments, overriding defaults with specified options. It sets up parameters for data, camera settings, datasets, neural rendering (NeRF), and other components, then stores the final configuration as an editable dictionary in `self.a...
def __init__(self, args=None, verbose=True) -> None: config_file_parser = argparse.ArgumentParser() config_file_parser.add_argument("config", type=str, help="the configure file") config_file_args, remaining_args = config_file_parser.parse_known_args( args=args ) de...
def check_input(u, uTrue, z, zTrue): #check u if type(u)==list: u=np.matrix(u).T elif len(z.shape)==1: u=np.matrix(u.tolist()).T elif len(z.shape)==2 and u.shape[0] == 1 and u.shape[1] == 2: u = u.T #check uTrue if type(uTrue)==list: uTrue=np.matrix(...
This function simulates a system's motion by applying input/measurement noise (if enabled), updating the true state via a motion model, estimating the state using sensor data, and returning the estimated position coordinates. It handles noise injection, dead reckoning simulation, state estimation, and data logging in a...
def move_forward(self,u,uTrue,z,zTrue,generate_input_noise = False,generate_measurement_noise = False): #main function u, uTrue, z, zTrue = check_input(u, uTrue, z, zTrue) if generate_input_noise: u = simulate_input_noise(uTrue) # maybe add input_noise if generate_measurement_noise: z = ...
def setup_model(): device = "cuda" if torch.cuda.is_available() else "cpu" model = YOLO(YOLO_MODEL) return model, device def setup_video_source(webcam): video_source = 0 if webcam else VIDEO_SOURCE capture = cv2.VideoCapture(video_source) assert capture.isOpened(), "Error reading video file" ...
The main task of the code is to perform real-time object detection and tracking on video input (from webcam or file), with customizable parameters like processing speed, region-based counting, frame display/saving, and model configuration. It processes each frame using a preloaded model, updates tracking data, optional...
def main( speed=None, webcam=False, resize=False, classes=[0], view_img=False, save_img=False, exist_ok=False, thickness=2, ): count = 0 model, device = setup_model() window_name = WINDOW_NAME cv2.namedWindow(window_name, cv2.WINDOW_NORMAL) capture, source = setup_vid...
def _init_fit_params(self, X_sample: np.ndarray) -> None: """Initialize model attributes defined during predict""" self.X_orig = X_sample n_features = X_sample.shape[1] self.retained_features_ = list(np.arange(n_features)) self.feature_importances_ = np.zeros(n_features) ...
The code identifies consistently useful features by iteratively training models on subsets of features, evaluating their performance, and updating a mask to retain features that meet a performance threshold. It handles parallel processing, tracks successes/failures, and may drop underperforming features based on specif...
def fit(self, X: np.ndarray, y: np.ndarray) -> None: """Find consistently useful features Parameters ---------- X : array-like of shape = [n_samples, n_features] Input samples y : array-like of shape [n_samples,] Target labels Returns --...
def pageloader(): WebDriverWait(self.driver, 3600).until(EC.invisibility_of_element_located((By.XPATH, '//*[contains(@id,"progressbar_disc")]'))) self.wait() WebDriverWait(self.driver, 3600).until(EC.invisibility_of_element_located((By.XPATH, '//*[contains(@id,"pageloader")]'))) def...
The code automates logging into a web application using provided credentials, navigates through pages, performs a search for a specific quote ID ("05985096"), and interacts with elements to select and process the quote. It uses Selenium for element interaction, JavaScript execution, and waits for dynamic content loadin...
def test_001_login(self): self.driver.find_element(By.ID,"ctl00_MainContentPlaceHolder_txtUsername").send_keys(self.username) self.driver.find_element(By.ID,"ctl00_MainContentPlaceHolder_txtPassword").send_keys(self.password) self.driver.find_element(By.ID,"ctl00_MainContentPlaceHolder_txtDomain...
def convert_tonums(h, nums={'T': 10, 'J': 11, 'Q': 12, 'K': 13, "A": 14}): for x in range(len(h)): if (h[x][0]) in nums.keys(): h[x] = str(nums[h[x][0]]) + h[x][1] return h def is_seq(h): if len(h) >= 5: return is_seq_not5(h) def is_flush(h): if len(h) >= 5: suits = [...
The code checks if a given hand `h` represents a royal flush. It verifies the hand has at least 5 cards, converts them to numerical values, checks for a sequence and flush, then confirms the lowest card is 10 (indicating 10, J, Q, K, A). If all conditions are met, it returns `True`; otherwise, `False`.)>
def is_royal(h): if len(h) >= 5: nh = convert_tonums(h) if is_seq(h): if is_flush(h): nn = [int(x[:-1]) for x in nh] if min(nn) == 10: return True else: return False
def is_royal(h): if len(h) >= 5: nh = convert_tonums(h) if is_seq(h): if is_flush(h): nn = [int(x[:-1]) for x in nh] if min(nn) == 10: return True else: return False def is_seq(h): if len(h) >= 5: return...
The main task of the code is to evaluate a poker hand's rank by checking hierarchical conditions (e.g., Royal Flush, Straight Flush, Four of a Kind) and returning the hand's name, relevant card data, and a score value. It prioritizes higher-ranking hands first, using helper functions to validate each condition, and def...
def evaluate_hand(h): if is_royal(h): return "ROYAL FLUSH", h, 370 elif is_seq(h) and is_flush(h): return "STRAIGHT FLUSH", h, 330 elif is_fourofakind(h): _, fourofakind = is_fourofakind(h) return "FOUR OF A KIND", fourofakind, 290 elif is_fullhouse(h): return "FU...
def evaluate_hand(h): if is_royal(h): return "ROYAL FLUSH", h, 370 elif is_seq(h) and is_flush(h): return "STRAIGHT FLUSH", h, 330 elif is_fourofakind(h): _, fourofakind = is_fourofakind(h) return "FOUR OF A KIND", fourofakind, 290 elif is_fullhouse(h): return "FU...
The code compares two poker hands (`h1` and `h2`) to determine which is stronger. It evaluates each hand's rank and specific card values, handling special cases like straight flushes, two pairs, pairs, full houses, and high cards. For tied ranks, it compares key card values (e.g., highest pairs, kickers) to decide the ...
def compare_hands(h1, h2): one, two = evaluate_hand(h1), evaluate_hand(h2) if one[0] == two[0]: if one[0] == "STRAIGHT FLUSH": sett1, sett2 = convert_tonums(h1), convert_tonums(h2) sett1, sett2 = [int(x[:-1]) for x in sett1], [int(x[:-1]) for x in sett2] com = compare...
def is_train_test_file_exists(self) -> bool: logging.info("Checking if train and test file exists") is_train_file_exists = False is_test_file_exists = False train_file_path = self.data_ingestion_artifact.train_file_path test_file_path = self.data_ingestion_artifact.test_file_pat...
This function validates data by checking if training/test files exist, detecting data drift, and verifying schema compliance. It sets validation status based on these checks, logs results, and returns a DataValidationArtifact with validation outcomes, schema paths, and status.
def initiate_data_validation(self) -> DataValidationArtifact: is_train_test_file_exists = self.is_train_test_file_exists() is_data_drift_found = self.is_data_drift_found() is_validated = self.validate_dataset_schema() if is_train_test_file_exists is True and is_data_drift_found is False:...
def get_initialized_model_list(self) -> list[InitializedModelDetail]: initialized_model_list = [] for serial_number, model_config in self.models_config.items(): model_class = self._get_class(model_config["module"], model_config["class"]) model = model_class() if "par...
The main task of the code is to identify the best-performing model from a list of initialized models by conducting a grid search on input data (X, y) and selecting the model that meets or exceeds a specified base accuracy threshold (0.45). It first initializes models, performs hyperparameter tuning via grid search, the...
def get_best_model(self, X, y, base_accuracy=0.45) -> GridSearchedBestModel: initialized_model_list = self.get_initialized_model_list() grid_searched_best_model_list = self.initiate_best_parameter_search_for_initialized_models( initialized_model_list=initialized_model_list, input_feature=X, ...
def __init_props( self, scene: Scene, arr: list, label: str, index_offset: int, index_start: int, index_hex_display: bool, hide_index: bool, arr_dir: MArrayDirection, switch_index_pos: bool, arr_label_pos: MArrayDirection, a...
This code initializes a visual array representation in a Manim scene, configuring display properties like index formatting, label positioning, element appearance, and array direction. It sets up Mobjects for array elements, labels, and indices, applying user-defined styling parameters and arranging components according...
def __init__( self, scene: Scene, arr: list = [], label: str = "", index_offset: int = 1, index_start: int = 0, index_hex_display: bool = False, hide_index: bool = False, arr_dir: MArrayDirection = MArrayDirection.RIGHT, switch_index_pos: b...
def __init_props( self, scene: Scene, arr: MArray, index: int, size: int, label: str, label_gap: float, label_pos: MArrayDirection, ) -> None: """Initializes the attributes for the class. Parameters ---------- scene ...
This code initializes a sliding window object in a Manim scene, attaching it to an array with specified index, size, label, and visual properties. It sets up the window's position, label placement, and rendering parameters, creates the visual components (rectangle and text), and adds an updater for dynamic behavior dur...
def __init__( self, scene: Scene, arr: MArray, index: int = 0, size: int = 1, label: str = "", label_gap: float = 0.5, label_pos: MArrayDirection = MArrayDirection.DOWN, mob_window_args: dict = {}, mob_label_args: dict = {}, **kwarg...
def p_choose(self, query, key, key_padding_mask): return self.p_choose_from_qk(self, query, key, key_padding_mask) def _get_monotonic_buffer( self, incremental_state: Optional[Dict[str, Dict[str, Optional[Tensor]]]] ): maybe_incremental_state = self.get_incremental_state( increme...
The function computes monotonic attention weights (alpha, beta) during inference for simultaneous translation, determining how many source tokens to attend at each decoding step. It calculates stepwise probabilities, updates attention states incrementally, and handles both soft/hard attention modes, crucial for real-ti...
def monotonic_attention_process_infer( self, query: Optional[Tensor], key: Optional[Tensor], incremental_state: Optional[Dict[str, Dict[str, Optional[Tensor]]]], ): """ Monotonic attention at inference time Notice that this function is designed for simuleval n...
def monotonic_attention_process_test( self, query: Optional[Tensor], key: Optional[Tensor], key_padding_mask: Optional[Tensor] = None, ): """ Calculating monotonic attention process for training Including: stepwise probability: p_choose ...
This code implements a monotonic attention mechanism in a neural network, computing attention weights (alpha, beta) and output (attn) using query, key, and value tensors. It handles training, inference, and incremental decoding modes, applying projections, masking, and tensor reshaping to generate context-aware outputs...
def forward( self, query: Optional[Tensor], key: Optional[Tensor], value: Optional[Tensor], key_padding_mask: Optional[Tensor] = None, attn_mask: Optional[Tensor] = None, incremental_state: Optional[Dict[str, Dict[str, Optional[Tensor]]]] = None, need_weig...
def find_user(self, user_name) -> str: """find_user [checks whether the user is in the logfile if exist returns unname already exist or returns error message ] Arguments: user_name {[str]} -- [Getting user_name for checking the user exist or not] Returns: [str] --...
This method handles user registration by extracting username and password from input, checking if the user exists, registering them if not, and then attempting to log them in, returning the login response.
def user_register(self) -> str: """user_register [This method initiates the registration process for the user.] Returns: str -- [returns the response from the login method] """ message = self.message.split(' ' ,3) user_name = message[1] pwd = message[2] ...
def drawSquare(game, x, y, selected, highlighted, isPossibleMove): i,j = x,y if game.flipped: x = 7-x y = 7-y colour = (0,0,0) if game.colourTable[i%2][j%2] == 'w': if selected: colour = game.selected_white elif highlighted: colour = gam...
This function updates a chess game state after a move, handling special rules like pawn promotion, en passant, castling, and 50-move draw. It adjusts the board, plays appropriate sounds (move, capture, castle, check), resets the 50-move counter when pawns move, and checks for king safety. It also updates castling right...
def updateSpecial(game, selected, position): game.fiftyMove += 1 if (game.board[selected[0]][selected[1]] == 'P' or game.board[selected[0]][selected[1]] == 'p'): game.fiftyMove = 0 sound = pygame.mixer.Sound('sounds/move.wav') if game.board[selected[0]][selected[1]].islower(): sound = p...
def updateSpecial(game, selected, position): game.fiftyMove += 1 if (game.board[selected[0]][selected[1]] == 'P' or game.board[selected[0]][selected[1]] == 'p'): game.fiftyMove = 0 sound = pygame.mixer.Sound('sounds/move.wav') if game.board[selected[0]][selected[1]].islower(): sound = p...
The main task of the code is to handle a chess move by updating game state (special moves, en passant, points), checking end-game conditions (checkmate, stalemate, 50-move rule), and rendering the board. It returns True if the move is valid and triggers game-ending logic, or False if the move is invalid, redrawing the ...
def moveSelected(game, selected, position): if position in game.moves: updateSpecial(game, selected, position) drawSquare(game, selected[0], selected[1], True, False, False) drawSquare(game, position[0], position[1], True, False, False) updateEnPassant(game, selected, position) ...
def calculateBoard(game): if isWKingChecked(game, 0): return -100000 if isBKingChecked(game, 0): return 100000 sum = 0 for i in range (8): for j in range (8): if game.board[i][j] == 'P': if game.whiteScore < 14 and game.blackScore < 14: ...
This function implements the minimax algorithm with alpha-beta pruning to determine the optimal move in a chess-like game. It evaluates all possible moves for the current player (maximizing or minimizing), recursively computes their outcomes, and tracks the best move (game.bestMove) by comparing scores. It handles pawn...
def computeMove(game, depth, isMaximizingPlayer, alpha, beta): if depth == 0: return calculateBoard(game) if isMaximizingPlayer: bestVal = -1000000 for i in range (8): for j in range (8): if not game.board[i][j] == '0' and not game.board[i][j].islower(): ...
def _keyschedule(self): permutatedKeys = [] permutatedKey = self._applyPermutation(self.__key, self._PC_1) #splitting the keys to get the right and the left halves keys = self._splitKeys(permutatedKey) #applying and getting the sixteen rounds of keys sixteenRoundKeys ...
The main task of the code is to encrypt a 64-bit message block using a Feistel network with 16 rounds of substitution and permutation, employing a key schedule to generate subkeys, ensuring proper initialization and state checks before performing encryption.
def __encryptBlock(self, inMessage): #if all the appropriate information hasn't being loaded into the object #we can't start decrypting the message if inMessage == None: raise EncryptionError("ERROR: message hasn't been set") if self.__key == None: raise Encrypt...
def _keyschedule(self): permutatedKeys = [] permutatedKey = self._applyPermutation(self.__key, self._PC_1) #splitting the keys to get the right and the left halves keys = self._splitKeys(permutatedKey) #applying and getting the sixteen rounds of keys sixteenRoundKeys ...
This code decrypts a cipher block using a Feistel network. It validates inputs, reverses precomputed subkeys, applies initial permutation, splits data into left/right halves, processes 16 rounds with reversed keys, recombines halves, applies inverse permutation, and returns decrypted data.
def __decryptBlock(self, inCipher): if inCipher == None: raise DecryptionError("ERROR: message hasn't being set") if self.__key == None: raise DecryptionError("ERROR: key hasn't being set") if (self.__encryption == encryptionStatus.decrypted): raise Decrypti...
def _padBinaryNum(self, inBinary, requiredLen): #I am just trying out this implementation as it gives you the actual required bits #TODO: the line below this, this idea doesn't work at all #remainder = abs(len(inBinary) - requiredLen) #TODO: come back and delete this line of cod...
The code encrypts a message by padding it to 64-bit blocks, splitting it into blocks, encrypting each block individually, and concatenating the results into a single encrypted string, updating the message and encryption status accordingly.
def encrypt(self): #all the preprocessing of the message will occur here, hence dividing #the message into the appropriate 64 bit block sizes #checking on how much we will need to pad the message by for each block #to be represented by a 64 block stream #how many bits will need...
def read_data_to_dataframes(self, file_path, read_n_files=None, columns_to_keep=["date", "day", "month", "year", "author", "addedloc", "deletedloc"]): """ Reads JSON/PARQUET files and returns a list of pandas dataframes. Optionally filters specified columns from the dataframes. Paramete...
The code processes data from a specified path by reading, filtering, and splitting dataframes into time intervals. It filters out dataframes with invalid date ranges, computes lines per author on a weekly basis, splits the data into intervals, and combines split dataframes for further analysis or modeling.
def __init__(self, path, splits=2): self.data_dir = path self.data = self.read_data_to_dataframes(self.data_dir) self.filtered_data = [self.filter_dataframe(d) for d in self.data if (self.filter_dataframe(d).date.max()-self.filter_dataframe(d).date.min()).days != 0] self.lpa_data = [self...
def prepare_for_walk(all_dfs): lpa_probs_dfs = calc_probs(all_dfs) lpa_probs_combined = combine_probs_dfs(lpa_probs_dfs) merged_dfs = merge_dataframes(all_dfs) merged_probs_dfs = pd.DataFrame({"week":merged_dfs.index, "lpa":merged_dfs.model, "lpa_diff":merged_dfs.model.diff().abs(), "updown":lpa_probs_c...
This function evaluates multiple training sets by iteratively splitting data, training a random walk model, predicting outcomes, and calculating errors. It returns the trained models, their corresponding errors, and the training datasets used for N iterations.
def best_train_set(dfs, N): models = [] errors = [] trains_arr = [] hashes = [] for _ in range(N): train, test = train_test_split(dfs, test_size=0.2) trains_arr.extend((train,)) total_df = prepare_for_walk(train) model = random_walk(total_df, total_df.lpa[...
def conv(x, output_c, k=1,s=1, p='same'): #if s == 1: # padding = 'same' #else: #if s==2: # x = layers.ZeroPadding2D(((0, 1), (0, 1)))(x) # padding = 'valid' x=Conv2D(output_c,k,s,padding=p,kernel_regularizer=l2)(x) x=keras.layers.BatchNormalization(epsilon=0.001)(x) #x=keras.activations.s...
The code builds a neural network model for object detection, using a U-shaped architecture with convolutional layers, CSP bottlenecks, and spatial pyramid pooling. It generates three output heads for multi-scale detection, each producing bounding box predictions with dimensions based on input parameters (width, depth, ...
def build_model(input_size,width,depth,nc): #input=keras.Input(shape=(416,416,3)) input=keras.Input(shape=(input_size,input_size,3)) x=input x=conv(x,int(round(64*width)),k=6,s=2) x=conv(x,int(round(128*width)),3,2) x=cspBottleneck(x,int(round(128*width)),int(round(128*width)),int(round(3*depth))) x=con...
def extend_targets(target,anchors,na,nl,grids,img_size): nt=target.shape[0] ne=target.shape[1] grid_scale=(grids/img_size) grid_scale=np.reshape(grid_scale,(nl,1) ) scaled_anchors=np.multiply(anchors,grid_scale[:,None]) target1=np.reshape(np.repeat(target,3,axis=0), (nt,3,ne) ) scale=np.ti...
The function `compute_loss2` computes a multi-task loss for object detection, combining box, objectness, and classification losses. It processes predicted outputs (`y_pred`) against ground-truth targets (`y`), using anchors and grid information. Box loss is calculated via IoU, objectness loss uses sigmoid cross-entropy...
def compute_loss2(y_pred,y,anchors,bs,bs_,grids,img_size,hyp): lbox=tf.zeros(1) lobj=tf.zeros(1) lcls=tf.zeros(1) nc=y_pred[0].shape[4]-5 #tcls,tbox,indices,anch=extract_indices(extend_targets(y,aanchors,3,3,np.array([52,26,13])),anchors) etargets,scaled_anchors=extend_targets(y,anchors,na,nl,grids,im...
def vary_annuity(self, payment_mode= None): """ The amount paid per installment is either increasing(+ve vary_amt) or decreasing(-ve vary_amt). """ payment_mode = payment_mode if(payment_mode)else(self.payment_mode) factor= None if payment_mode=="arrear": factor = self.rate...
This method converts an initialized annuity into an arrear annuity, handling varying amounts, infinite periods, or perpetual payments. It selects the appropriate calculation method (arrear, advance, or continuous) based on the annuity's payment mode and time span, returning the computed annuity value.
def annuity(self, n= None ): """ Convets the initialized annuity to an arrear annuity convetible annually(once per unit time). """ annuity = None n = n if(n)else(self.time_span) if self.vary_amt: """ A vary ammount implies that the annuity is a varying annuity. ""...
def annuity(self, n= None ): """ Convets the initialized annuity to an arrear annuity convetible annually(once per unit time). """ annuity = None n = n if(n)else(self.time_span) if self.vary_amt: """ A vary ammount implies that the annuity is a varying annuity. ""...
The function calculates the present or future value of an annuity, considering varying payment amounts and payment modes (advance, arrear, continuous). It adjusts for differing time periods and rates, using the annuity amount and time value factors to compute results. If 'future' is True, it returns the future value; o...
def time_value(self, value= None, n=None, differ=0, differ_rate=0, future= False ): """ Returns the time value of the annuity. """ n = n if(n)else(self.time_span) # how long the payments were made. differ = differ if(differ)else(self.differ) # differ time differ_rate = differ_rate i...
def split(data, node): fea, threshold = node.fea, node.threshold d1 = data[data[:,fea-1] <= threshold] d2 = data[data[:, fea-1] > threshold] return (d1,d2) def find_best_split(data): c = len(data) c0 = sum(b[-1] == 2 for b in data) # # of 2s in training set if c0 == c: return (2, None) i...
The code constructs a decision tree with a maximum depth of 4. It recursively splits data into left and right child nodes, using best splits for internal nodes (depth < 4) and setting leaf nodes to class labels (2 or 4) based on majority count at depth 4. The function returns the tree's maximum depth after building.
def create_tree(data, node, depth): if depth < 4: depth += 1 depth_left = depth depth_right = depth d1,d2 = split(data, node) f1, t1 = find_best_split(d1) f2, t2 = find_best_split(d2) if t1 == None: node.left = f1 else: node.left = Node(f1,...
def reset (model): #reset model after each run/trial model.empty = start() model.game_running = True model.arr = generatearr() model.running = True def rand(): #generates random tile init chance = random.randrange(0, 100) if chance < 90: a = 2 else: a = 4 return a def maxnum (...
This code animates a puzzle-solving process using Pygame, initializing a game board, handling user events, making moves, and rendering updates. It returns the maximum number on the board once the state stabilizes, with a 1000 FPS loop for animation.
def run_your_solveranimate(): #animated runner pygame.init() model = Model() reset(model) clock = pygame.time.Clock() for i in range(0, 2): (x, y) = model.empty.pop() model.arr[x][y] = rand() screen = pygame.display.set_mode(((rows * WIDTH) + 15, (cols * HEIGHT) + 10)) whil...
def reset (model): #reset model after each run/trial model.empty = start() model.game_running = True model.arr = generatearr() model.running = True def rand(): #generates random tile init chance = random.randrange(0, 100) if chance < 90: a = 2 else: a = 4 return a def maxnum (...
The code simulates a game where a model's board is initialized with random values, updates via a move decision loop, and returns the maximum number on the board when no further changes occur. It uses Pygame for timing and event handling, checking for quit events and stabilizing the board state to determine the result.
def run_your_solver(): #non animated runner model = Model() reset(model) clock = pygame.time.Clock() for i in range(0, 2): (x, y) = model.empty.pop() model.arr[x][y] = rand() while model.game_running: copyboard = copy.deepcopy(model.arr) if pygame.event.EventType ==...
def is_forge_installer_downloaded(self): return self.get_forge_installer_path() is not None def get_forge_installer_path(self) -> Union[str, None]: results = glob.glob(os.path.join(self.server_path, "forge-*-installer.jar")) if len(results) == 0: return None if len(results)...
The code defines a `__str__` method to generate a human-readable string representation of a Minecraft server's configuration, including server name, path, Forge installer status, Forge server path, and Java memory flags. Boolean values are converted to 'x' (True) or ' ' (False) for display. The formatted string provide...
def __str__(self): booltochar = {True: "x", False: ' '} return """ Minecraft Server '{mcservername}': PATH: '{path}' [{does_forge_installer_exist}] Forge installer downloaded: '{forge_installer_path}' [{is_forge_installed}] Forge jar installation: ...
def generate_clean_temp_dir(self) -> str: """Make a new temporary directory and make sure it's empty.""" tempdir = os.path.join(self.get_base_temp_dir()) if os.path.exists(tempdir): shutil.rmtree(tempdir) os.makedirs(tempdir) return tempdir def folders_in_path(pat...
The function downloads a modpack ZIP from a given URL, extracts it to a temporary directory, and installs it by copying its contents if the ZIP contains exactly one folder and no files. If the structure differs, it raises an error stating the feature is unimplemented. It also checks for Forge server installation, promp...
def install_modpack_zip_from_url(self, url): modpack_response = DownloadLib.get_results_from_url(url) tempdir = self.generate_clean_temp_dir() modpack_zip_temp_filepath = os.path.join(tempdir, DownloadLib.response_filename(modpack_response)) modpack_unzipped_path = os.path.join(tempd...
def spawn_graphical_terminal(command: List[str], working_dir) -> subprocess.Popen: """ Spawn a graphical terminal and run a command in it. This will search for various tools like 'cmd' and 'gnome-terminal' and try to use ones that exist. """ ensure_java_exists() if is_ci(): raise Excep...
This method launches a Forge server in a graphical terminal environment by spawning a new terminal window with the server's command and working directory, then storing the process object for management.
def run_forge_server_graphical(self): """Run the forge server in a new terminal window in a graphical environment.""" ps = spawn_graphical_terminal(self.get_forge_server_command(), working_dir=self.server_path) self.set_server_process(ps)
def configure_common_widget(self): common_widget = QtWidgets.QWidget() self.grid_layout.addWidget(common_widget, 0, 0, 1, 1) inside_grid = QtWidgets.QGridLayout() common_widget.setLayout(inside_grid) self.fill_herd_owner(name='common herd', widget=inside_grid) animals = s...
The code initializes a game window by setting its title, configuring UI components (common, player, and info widgets), updating the view, establishing game callbacks, and displaying the initial game start message with the first player's name.
def setup_window(self): self.window.setWindowTitle('Farmer Game') self.configure_common_widget() self.configure_player_widget() self.configure_info_widget() self.update_view() self.set_game_callbacks() self.update_info("{} starts the game".format(self.players_name...
def Xy_split(self, y_column_number: int) -> Union[list[list], list]: Xs = [] ys = [] for lst in self.dataset: y = lst.pop(y_column_number - 1) Xs.append(lst) ys.append(y) return Xs, ys def get_gini_impurity(self, node: Node) -> float: length_of...
This code initializes a decision tree by splitting the input dataset into features (X) and target (y), creating a root node, calculating initial Gini impurity, building the tree recursively, and optionally printing the tree structure if specified.
def __init__(self, dataset: list[list], col_names: list[str], y_column_number: int, print_tree=False) -> None: self.dataset = dataset self.col_names = col_names X, y = self.Xy_split(y_column_number) self.root = Node(X, y) gini = self.get_gini_impurity(self.root) self.root...
def delete_news_articles(delete_news:str): """deletes news articles that the user has interacted with to deleted""" global news_articles global deleted_news for i in range(len(news_articles)-1): if news_articles[i]['title'] == delete_news: deleted_news.append(news_articles[i]) ...
The main task of the code is to handle a Flask web application that processes URL parameters to manage news updates, schedule data updates, cancel scheduled jobs, and render a dashboard with real-time COVID-19 data and news articles. It uses global variables to track data, checks request arguments for user actions, log...
def main(): """the main flask module that renders the website""" covid_news_handling.s.run(blocking=False) global news_articles global covid_data global deleted_news delete_news = request.args.get('notif') news_articles = covid_news_handling.news_articles covid_data = covid_data_handler...
def goalCondition(self): return self.goalPoint.euclideanDistance(self.currentPosition) < self.step_size def findClosestObstacle(self): self.closestDistance = float('inf') for obstacle in self.obstaclesList: polygon = Polygon2D(len(obstacle), obstacle) distance, _, _ = polygon.computeDistancePointToPolyg...
This code implements a navigation algorithm that repeatedly checks for obstacles, moves toward a goal if no obstacles are near, and stores data upon reaching the goal. If an obstacle is detected, it returns a failure outcome; otherwise, it returns success after completing the task.
def bugBaseAlgorithm(self): while not self.goalCondition(): self.findClosestObstacle() if self.isNearObstacle(): return self.getAlgoOutcome(fail = True) self.moveTowardsGoal() self.storeData() return self.getAlgoOutcome(fail = False)
def goalCondition(self): # return abs(self.gradient.euclideanDistance(None)) < 0.1 return self.currentPosition.euclideanDistance(self.goalPoint) < 0.1 def moveAndUpdatePath(self, shoot = False): if not shoot: self.computeGradient() self.localGoal.pose_dest.x = self.currentPosition._x + self.step_size*se...
The code's main task is to navigate toward a goal by continuously updating the path in a loop until the goal condition is met. It checks proximity to path points, triggering a shooting action toward the goal when within 0.04 units. Finally, it returns "Success" along with the path and plan.
def planner(self): while not self.goalCondition(): self.moveAndUpdatePath() # self.moveAndUpdatePathPython() if len(self.path)>3: for i in range(3): if self.currentPosition.euclideanDistance(Point2D(self.path[-2-i][0], self.path[-2-i][1])) < 0.04: self.shootTowardsGoal() return "Succe...
def computeDistanceTwoPoints(p1, p2): # tested x1, y1 = p1[0], p1[1] x2, y2 = p2[0], p2[1] return sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2) def computeDistancePointToPolygon(P, q): # tested n = len(P) dist = np.zeros(n) for i in range(n - 1): dist[i] = computeDistancePointToSegment(q, P...
The function `gradU` computes a combined gradient vector for navigation, incorporating an attractive force toward a goal point and repulsive forces from obstacles. The attractive gradient scales based on distance to the goal, while the repulsive gradient sums contributions from each obstacle, using perpendicular projec...
def gradU(q, q_goal, d_star, x, eta, q_i_star, obstaclesList): if computeDistanceTwoPoints(q, q_goal) > d_star: gradientAttractive = d_star * x * (np.array(q_goal) - np.array(q)) / computeDistanceTwoPoints(q, q_goal) else: gradientAttractive = x * (np.array(q_goal)-np.array(q)) n = len(obs...
def reachedGoal(self): return self.dist(self.goalPoint, self.myPose[:2]) < self.eps def generateFeasibleSamples(self): # origin = self.myVel theta = self.myPose[2] self.samples = [] for vel in np.linspace(0, self.VEL_MAX, self.VEL_DISCRETE): for ...
The main task of the code is to navigate towards a goal while avoiding obstacles. It repeatedly generates feasible movement samples, filters them to remove invalid paths, selects the optimal next step, and executes the movement until the goal is reached.
def avoidObstacles(self): while not self.reachedGoal(): self.generateFeasibleSamples() # done self.filterPoints() # done self.findOptimumPoint() # done self.takeStep()
def gradU(q, q_goal, d_star, x, eta, q_i_star, obstaclesList): if computeDistanceTwoPoints(q, q_goal) > d_star: gradientAttractive = d_star * x * (np.array(q_goal) - np.array(q)) / computeDistanceTwoPoints(q, q_goal) else: gradientAttractive = x * (np.array(q_goal)-np.array(q)) n = len(obs...
The function computes a path from a start to a goal position using a potential field gradient descent approach, avoiding obstacles. It iteratively adjusts the current position based on the gradient of a potential function, updating the path and desired trajectory until the gradient magnitude falls below a threshold or ...
def computePotFunc(start, goal, obstaclesList, step_size, client, d_star, x, eta, q_i_star): # algorithm implementation current_position = start path = [] desired_path = [] epsilon = 0.2894 path.append(start[:]) desired_path.append(start[:]) print("Start PotFunc") grad = gradU(cu...
def cleanup(directory): if path.exists(directory): shutil.rmtree(directory) os.mkdir(directory) def read_idiff_file(file): new_files.clear() deleted_files.clear() renamed_files.clear() modified_files.clear() with open(file) as fp: for next_section in [NEW_FILES, DELETED_FILE...
The main task of the code is to convert `.idiff` files from the `GE_DIR` directory into `.pe` files in the `PE_DIR` directory. It cleans the output directory, processes each `.idiff` file by reading its contents, generating corresponding `.pe` files, and tracking the number of new, deleted, renamed, and modified files ...
def main(): cleanup(PE_DIR) files = sorted(glob.glob(f"{GE_DIR}/*.idiff")) for in_file in files: out_file = in_file.replace(GE_DIR, PE_DIR).replace(".idiff", ".pe") print(f"Processing {in_file} -> {out_file}") read_idiff_file(in_file) write_pe_file(out_file) print...
def _read_filetimes(self): # Read the current bookkeeping data. try: with open(self.bkfile, "r") as fh: return json.load(fh)['filetimes'] except KeyError: return {} def bookkeep(self): """Checks if all files on disk have been analysed. """ ...
This code initializes a class by setting up parameters, creating a bookkeeping file if it doesn't exist, logging errors, and organizing data for analysis tracking. It reads file timestamps, prepares a summary structure, and updates the bookkeeping file to track analysis progress and session details.
def __init__(self, datadir: str, dataparams: AttrDict, analysisparams: AttrDict) -> None: self.datadir = datadir self.dataparams = dataparams self.analysisparams = analysisparams self._currsess = dt.now().strftime("%D %T") # Check if the bookkeeping file exists ...
def produce_tokens(text): processed_text = [] processed_text_as_list = [] # text = text.encode().decode("unicode-escape") # text = html.unescape(text) # text = " ".join(re.findall(r"[\w%\-.']+", text)) sentences = nltk.sent_tokenize(text) for s in sentences: tokens = nltk.word_toke...
The code processes text data by applying either or both Standard and Stanza annotation pipelines to tokenize text and assign entity labels. It constructs a structured dictionary with token positions and user annotations, grouping labeled tokens into annotation entries with specific formatting, colors, and user identifi...
def process_annotation_data(file_key, pipeline_key): path = "data//" file_path = path + file_key with open(file_path) as f: # text = json.load(f) text = str(f.read()) tokens, tokens_as_list = produce_tokens(text) if pipeline_key == "Standard" or pipeline_key == "Both": ...
def load(number= n,filename=filename,parlist=parlist): namelist=[] for i,par in enumerate(parlist): namelist.append(parlist[i]['name']) path = filename+'/smc/pars_' + number + '.out' dist_path = filename+'/smc/distances_' + number + '.out' raw_output= np.loadtxt(path) dist_outp...
The function `runBifurcation` performs bifurcation analysis on a dynamical system by iterating over parameter sets, computing stability and bifurcation metrics (e.g., max stability, bifurcation counts, transitions), and generating visualizations of system states (unstable, stable, oscillatory, etc.). It saves results a...
def runBifurcation(ARA,filename,n,i): p, pdf= load(n,filename,meq.parlist) pars = p[(1000*i):(1000+1000*i)] sizex = round(np.sqrt(len(pars))) sizey = round(np.sqrt(len(pars))+0.5) max_stability=[] count_bifurcation=[] bifurcation_transition=[] index = i*1000 for pi,p in...
def total_stopping_sets(v, dv, dc, t): # value = g(dc,t)[x**(v*dv)] * math.factorial(v*dv) value = g(dc,t).coeff(x, v*dv) * math.factorial(v*dv) return value def f(dc,sigma,dt,coef): # if (sigma,dt) in f_dict: # return f_dict[(sigma,dt)][x**coef] a = sympy.expand( ((1+x)**(dc-1)-1)**(sigma) ...
The function A recursively computes a combinatorial sum involving stopping sets in coding theory. It calculates values based on parameters v, t, s, dv, dc, N, and X, using nested loops over variables ds, sigma, dt, tau. The result combines combinatorial terms (math.comb), factorials, exponents, and recursive calls to i...
def A(v,t,dv,dc,N,s,X): # First check if value has already been calculated, if so return that # if (v,t,s) in A_dict: # return A_dict[(v,t,s)] if v==0: return 0 if s==0: value = total_stopping_sets(v,dv,dc,t) *(v/N)**X / (math.factorial(v)*math.factorial(dv)**v) # A_dict[...
def get_features(nw, layers, comms, node_labels, num_labels): comms_features = [] for comm in comms: total_vector = [] for i in range(layers): feature_vector = get_features_helper(nw, comm, i, node_labels, num_labels) total_vector.extend(feature_vector) comms_feat...
The function trains a KMeans model on graph-derived node features, clusters nodes into groups, and computes group statistics. If Simple is True, it returns the model and group size distribution; otherwise, it also calculates layer-specific seed information and biases for each cluster group across multiple graph layers.
def train(nw, layers, gts, node_labels, nclus, Simple=False): num_labels = len(set(node_labels.values())) gt_features = get_features(nw, layers, gts, node_labels, num_labels) KM_obj = KMeans(nclus) gt_labels = KM_obj.fit_predict(gt_features) size_dist_per_group, grouped_features = make_groups(gt_lab...
def get_ticker(self): """Get user's input of ticker. Must be available on Yahoo Finance.""" ticker = None while ticker is None: ticker = input("Please input ticker: ").upper() try: pdr.get_data_yahoo(ticker, start = dt.datetime(2021,11,23), end = dt.datet...
This function validates date ranges for stock data retrieval by converting dates to datetime, checking validity, and fetching data. It handles cases where the market is closed by retrying until valid data is obtained, returning the fetched data upon success.
def check_data(self): """Add another validity check for situations like the stock market is closed between start date and end date.""" self.df["Date"] = pd.to_datetime(self.df["Date"]) ticker = self.get_ticker() signal = True while signal: start_da...
def get_user_manual(self): """Print the user manual.""" with open(self.manual_filename, encoding = 'UTF-8') as f: print(f.read()) def check_data(self): """Add another validity check for situations like the stock market is closed between start date and end date.""" ...
The code processes user choices to navigate sub-menus: option 1 provides a manual, 2 initiates stock analysis with user-specified data, 3 triggers stock prediction training, and 4 exits. It loops until the user selects "4", validating inputs and executing corresponding functions for each choice.
def process_options(self, choice): """When users make choices, lead them to the corresponding sub-menu.""" while choice != "4": if choice == "1": self.get_user_manual() elif choice == "2": print("Stock Analysis: Plea...
def welcome(self): print("Welcome to stock analyzer!") def show_options(self): print("There are four options: 1, User Manual; 2, Stock Analysis; 3, Stock Predictor; 4, Quit") def get_option(self): """Get user's input of choice.""" return input("Please select your options (enter 1, 2, 3 o...
The main task of the code is to execute a menu-driven interaction by welcoming the user, displaying available options, capturing their choice, and processing the selected action. It orchestrates user input handling and workflow execution in a structured manner.
def main(self): self.welcome() self.show_options() choice = self.get_option() self.process_options(choice)
def create_train_val_dataset(mode, data, precs, atom_feature, edge_feature, ms_transformation, max_mz, resolution,instrument_on_node, self_loop, num_virtual_nodes, element_list, fp_size, noise): mol_dict, pos_train, neg_train = data pos_prec, neg_prec = precs if mode == 'positive': prec_types = pos_...
This function loads training, validation, and test datasets from CSV files and a molecule dictionary, processes them into graph structures using specified hyperparameters, generates dataset indices, saves these indices, and combines all data into a unified graph dataset converted for PyTorch Geometric compatibility.
def load_trvate(hp): print('Loading Data...') pos_train = pd.read_csv(os.path.join(data_dir_prefix+'data', hp['data_dir'], "pos_train.csv")) neg_train = pd.read_csv(os.path.join(data_dir_prefix+'data', hp['data_dir'], "neg_train.csv")) with open(os.path.join(data_dir_prefix+'data', hp['data_dir'], "mol_...
def update_mini_batch(self, mini_batch, eta, lmbda, n): nabla_b = [np.zeros(b.shape) for b in self.biases] nabla_w = [np.zeros(w.shape) for w in self.weights] for x,y in mini_batch: delta_nabla_b, delta_nabla_w = self.backprop(x,y) nabla_b = [nb+dnb for nb,dnb in zip(nabla_b, delta_nabla_b)] ...
The code implements Stochastic Gradient Descent (SGD) for training a neural network. It processes training data in mini-batches over multiple epochs, updating the model's parameters using gradient descent with a specified learning rate. The function optionally evaluates model performance on separate evaluation data, tr...
def SGD(self, training_data, epochs, mini_batch_size, eta, lmbda = 0.0, evaluation_data=None, monitor_evaluation_cost=False, monitor_evaluation_accuracy=False, monitor_training_cost=False, monitor_training_accuracy=False): """ Eta is step-size of gradient, or learning rate Training_data is tuples conta...
def getvar(): global nm global lm global mob global email global x7 global x8 nm=e1.get() lm=e2.get() email=e3.get() mob=e4.get() x7=sp.get() x8=cb.get() def msg(): #echeck ="@gmail.com" EMAIL_REGEX = re.compile(r"^([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z...
The code appends user data, including first name, last name, mobile number, email, age, and gender, to a text file named 'records.txt' if it exists. It retrieves variables via getvar(), processes data with msg() and csv(), then writes formatted entries into the file. If the file doesn't exist, it calls an undefined 'fi...
def appen(): getvar() msg() csv() if os.path.exists("records.txt"): f=open("records.txt","a") f.write("First Name:\t") f.write(nm) f.write("\n") f.write("Last Name:\t") f.write(lm) f.write("\n") f.write("mobile.no:\t") f.writ...
def setBricks(self): bricks = [] random.seed(Constants.SEED) for j in range(Constants.NUM_VERT): bricks.append([]) for i in range(Constants.NUM_HORIZ): pos = [Constants.BRICK_SIZE[0]*i, Constants.BRICK_SIZE[1]*j] if i > 0 and j > 1 and i <...
This code defines a game loop for a Pygame-based game, handling player movement, ball physics, collision detection with bricks, win/loss checks, and rendering. It initializes game objects (player, ball, bricks), updates their states, checks for victory conditions, and maintains frame rate control using a clock. The loo...
def gameLoop(self): self.won = None self.restart = False self.running = True pressed_left = False pressed_right = False clock = pygame.time.Clock() score = 0 Player = Objects.Player([int(Constants.SCREEN_SIZE[0]/2) - Constants.PLAYER_SIZE[0]/2, int(9*Cons...
def _findAnimal(self): # find spot where 'S' is in grid, thats where the animal is for i in range(self.height): for j in range(self.width): if (self.grid[i][j] == 'S'): return (i, j) return (0, 0) def _getCoordsInLoop(self): # start at anim...
This code initializes a grid-based structure by reading a file, parsing its contents into a 2D grid, determining grid dimensions, locating an animal's position, identifying reachable coordinates, building an adjacency list, and computing distances for pathfinding or analysis.
def __init__(self, file): self.grid = [] with open(file) as f: lines = f.readlines() for line in lines: r = [c for c in line[:-1]] self.grid.append(r) self.height = len(self.grid) self.width = len(self.grid[0]) if self.height > 0 el...
def check_number(number: str) -> bool: return "+" in number or "_" in number def clickTextBox() -> None: location = pyautogui.locateOnScreen(f"./smile1.png") try: try: pyautogui.moveTo(location[0] + 150, location[1] + 5) except Exception as e: if str(e) == "NoneType' ...
This function schedules and sends a WhatsApp message to a specified phone number at a given time, with validation checks for phone number format, time parameters, and wait duration. It uses pyautogui for automation, handles tab closure post-message, and ensures sufficient wait time for WhatsApp Web to load.
def sendwhatmsg( phone_no: str, message: str, time_hour: int = None, time_min: int = None, time_sec: int = 0, wait_time: int = 15, tab_close: bool = False, close_time: int = 3, ) -> None: if not check_number(number=phone_no): raise exceptions.C...
def set_rowcount(self): counter = 0 for row in self.data: counter += 1 self.number_of_audits_detected = counter def set_title_string(self): if self.number_of_audits_detected == 1: title_string = "a new audit" if self.number_of_audits_detected > 1: ...
The code initializes a class instance with provided data, sets the row count, generates a title string, and configures a message. The main task is to set up the object's initial state and attributes for further processing or display.
def __init__(self, data): self.data = data self.set_rowcount() self.title_string = self.set_title_string() self.configure_message()
def gen_observation(self,state,action): obs=np.ones(2) p_test=np.random.binomial(action,state[0]) n_arrival=np.random.poisson(3) obs[0]=int(p_test) obs[1]=int(n_arrival) return obs def next_state(self,si,action,obs): Ii=si[0] betai,gammai=si[1] ...
The function `simulate_action` simulates the outcome of taking action `ai` from state `si`, returning the next state, observation, reward, and cost. It generates the observation, computes the new state, updates the belief based on the action and observation, calculates reward using the updated belief, and derives cost ...
def simulate_action(self,c_states,c_belief, si, ai, debug=False): """ Query the resultant new state, observation and rewards, if action ai is taken from state si si: current state ai: action taken at the current state return: next state, observation and reward """ ...
def compare(sym1: Symbol, sym2: Symbol) -> int: if sym1.stage < sym2.stage: return -1 if sym2.stage < sym1.stage: return 1 return -1 if sym1.iden < sym2.iden else (1 if sym2.iden < sym1.iden else 0) def __splay(self, x: Node): while x.parent is not None: if x.parent....
This function deletes a node with a specified symbol from a splay tree. It searches for the node, splays it to the root, splits the tree into left and right subtrees, and recombines them to maintain the splay tree structure.
def __delete_helper(self, root: Node, sym: Symbol): x, temp = None, root while temp is not None: if compare(temp.sym, sym) == 0: x = temp break if compare(temp.sym, sym) == -1: temp = temp.right else: tem...
def parser_arguments(): parser = argparse.ArgumentParser() parser.add_argument( '--thumbnail-size', metavar='WIDTHxHEIGHT', help='Thumbnail size "WIDTHxHEIGHT". Default {}x{}'.format( *DEFAULT_THUMBNAIL_SIZE ), type=check_thumbnail_size, required=Fals...
The code processes a Blogger XML file by parsing it, creating required directories, extracting post entries, and processing each post using specified options. It handles parsing errors and ensures valid XML input before proceeding with data extraction and post processing.
def main(): options = parser_arguments() create_required_directories(options.output_folder) try: xml_tree = ET.parse(options.blogger_file) except ET.ParseError: logger.error( 'Can not parse "%s". Check if it is actually ' 'exported blogger\'s xml file', options....
def get_fixture(away_team_name, home_team_name, competition): """ Gets Fixture objects and returns it :param date: string - date of fixture :param away_team_name: string :param home_team_name: string :param matchday: int :param competition: Competition object :return: Fixture object ...
The main task of the code is to synchronize local fixture data with an API server by updating completed matches' details (date, goals, matchday) in the database for a specific competition. It retrieves competition and fixture data from the API, identifies unfinished fixtures, and updates their status, scores, and assoc...
def update_fixtures(api_id, matchday=""): """ Updates fixtures with data from api server. Fixtures are updated according to matchday. :param api_id: int - id of competition in api server :param matchday: int - number of matchday :return: None """ # gets data from api serer data = ge...
def in_hull(points, hull_or_vertices, tol=1e-10): if isinstance(hull_or_vertices, ConvexHull): hull = hull_or_vertices else: hull = ConvexHull(hull_or_vertices) points = np.atleast_2d(points) return np.all(np.add(np.dot(points, hull.equations[:,:-1].T), hull.equations[:,-1]) <...
The function `intersection_of` computes the intersection of two convex hulls defined by their vertices (`vertices1` and `vertices2`). It checks if either hull contains points from the other, constructs inequality constraints (`A`, `b`) from the vertices, and solves for the overlapping region. If valid, it returns the i...
def intersection_of(vertices1=None, vertices2=None, tol=1e-10): if any(in_hull(vertices1, vertices2, tol=tol)) or any(in_hull(vertices2, vertices1, tol=tol)): A1, b1, Aeqn_1, beqn_1 = V2Ab(vertices1, tol=tol) A2, b2, Aeqn_2, beqn_2 = V2Ab(vertices2, tol=tol) Ab1 = np.concatenate((A1,b1), a...
def in_hull(points, hull_or_vertices, tol=1e-10): if isinstance(hull_or_vertices, ConvexHull): hull = hull_or_vertices else: hull = ConvexHull(hull_or_vertices) points = np.atleast_2d(points) return np.all(np.add(np.dot(points, hull.equations[:,:-1].T), hull.equations[:,-1]) <...
This function computes Voronoi cells for given points constrained within a boundary polygon. It checks if points lie inside the boundary, constructs Delaunay triangulation, generates bisector constraints between neighboring points, combines them with boundary constraints, and calculates Voronoi vertices. It creates Con...
def bounded_voronoi(points=None, boundary_vertices=None, tol=1e-10): if False in in_hull(points, boundary_vertices, tol=tol): print("some points are outside the boundary") print("you should use function soft_bounded_voronoi instead of bounded_voronoi") print(in_hull(points, boundary_vertice...
def buffer_hull(vertices, r=None, num_pts=10): if r is None: center = np.mean(vertices, axis=0) r = np.amax(np.linalg.norm(vertices-center, axis=1)) #print("r=" + str(r) + " is set for the buffer hull") buffer_points = [] for vertice in vertices: buffer_points.append(circum...
The function `soft_bounded_voronoi` computes Voronoi cells for input points constrained within a convex boundary, adjusting for numerical errors. It filters points inside the boundary, generates bounded Voronoi regions, and ensures their combined area matches the boundary's volume. If discrepancies arise (due to numeri...
def soft_bounded_voronoi(points=None, boundary_vertices=None, r=None, tol=1e-10): buffer = buffer_hull(boundary_vertices, r, num_pts=10) points = points[in_hull(points, buffer, tol=tol)] if all(in_hull(points, boundary_vertices, tol=tol)) == True: voronoi_cells = bounded_voronoi(points, boundary_v...
def get_image(self, idx): ann = self.anns[idx] img_file = os.path.join(self.img_root[ann['source']], ann['filename']) return Image.open(img_file).convert('RGB') def get_ref_bboxes(self, idx): return np.array(self.anns[idx]['ann']['ref_bboxes']) def _draw_bboxes(self, image, bboxes): ...
The main task of the code is to save an annotated image and corresponding dialogues for a given index into a specified directory. It creates the directory if needed, retrieves the image and bounding boxes, draws annotations on the image, and saves both the annotated image (as JPG) and dialogues (as JSON) with filenames...
def save(self, idx, save_path): """ save_path: a directory you want to save and visualize the annotation. """ os.makedirs(save_path, exist_ok=True) image = self.get_image(idx) ref_bboxes = self.get_ref_bboxes(idx) image_show = self._draw_bboxes(image, ...
def welcome(): """Adds a welcome message""" print('=' * 75) print(' Starting DecisionTree.py Version %s' % VERSION) print('-' * 75) print(' Code Parameters:\n') print(' Input File :', INFILE.split('\\')[-1]) print(' Target Column :', TARGET) print(' Omitting Columns :', OMIT) ...
The main task of the code is to execute a machine learning workflow: it starts by displaying a welcome message, imports dataset features (X), labels (Y), and column names (cols), trains two tree models (node_one, node_two) using `run_trees`, evaluates their accuracies (accs), and visualizes the results via `plot_result...
def main(): """Main Execution of Script""" welcome() X, Y, cols = import_data(infile=INFILE) node_one, node_two, accs = run_trees(X, Y, cols) plot_results(node_one, node_two, accs)
def synonym_replacement(words, n, synonym_dictionary, stop_words): new_words = words.copy() random_word_list = list(set([word for word in words if word not in stop_words])) random.shuffle(random_word_list) num_replaced = 0 for random_word in random_word_list: synonyms = get_synonyms(random_word, synonym_dictiona...
This code performs data augmentation on a given sentence using four techniques: synonym replacement, random insertion, random swap, and random deletion. It generates multiple variations of the input sentence by applying these transformations with controllable probabilities, then shuffles and trims the results to produc...
def eda(sentence, synonym_dictionary, stop_words, alpha_sr=0.1, alpha_ri=0.1, alpha_rs=0.1, p_rd=0.1, num_aug=9): words = sentence.split(' ') words = [word for word in words if word != ''] num_words = len(words) augmented_sentences = [] num_new_per_technique = int(num_aug/4) + 1 #sr if (alpha_sr > 0): n_sr ...
def gen_func_def(m,k,n,sched): return ''' arm_status outer_fp32_%dx%dx%d_%s_first( const arm_matrix_instance_f32 * pSrcA, const arm_matrix_instance_f32 * pSrcB, arm_matrix_instance_f32 * pDst) { ''' % (m,k,n,sched) def gen_var_decls(): return ''' float32_t *A = pSrcA->pData; float32_t *B = pSr...
This function generates C code for optimized matrix multiplication, handling block processing and leftover elements. It creates variable declarations, loop structures, and memory access patterns for multiplying matrices A and B, storing results in C. The code includes bounds calculation, outer loops for block iteration...
def gen_k_first(M,K,N,m,k,n,sched): # func_def = gen_func_def(m,k,n,sched) var_decls = gen_var_decls() end = gen_end() var_decls += ''' uint32_t C_ind = 0U; float32_t *A_ptr = pSrcA->pData; /* Input data matrix pointer A */ float32_t *B_ptr, *C_curr; ''' # C_decls = ','.join(["C%d%d...
def _get_all_together_results(self) -> dict: existing = self._load_from_file_if_exists(PathHelper.get_file_name(FileName.ORG_REPO_LANGS)) if existing: return existing else: org_repos = self._load_orgs_for_batch() total_repos = self._get_total_repos(org_repos)...
The code's main task is to process and batch supported results by first retrieving all combined data, filtering out unsupported items, and then organizing the remaining supported results into batches for further handling.
def run(self): all_together = self._get_all_together_results() all_supported = self._filter_out_unsupported(all_together) self._batch_results(all_supported)
def square_Under_Attack(self, r, c): self.white_Turn = not self.white_Turn opp_Moves = self.get_All_Possible_Moves() self.white_Turn = not self.white_Turn #Switch back turn for move in opp_Moves: if move.end_Row == r and move.end_Col == c: #Square is und...
The function checks if the king's square is under attack, returning early if so. It then generates king-side and queen-side castling moves based on current castling rights and the player's turn, appending valid moves to the provided list.
def get_Castle_Moves(self, r, c, moves): if self.square_Under_Attack(r, c): return if (self.white_Turn and self.current_Castling_Right.wks) or (not self.white_Turn and self.current_Castling_Right.bks): self.get_King_Side_Castle_Moves(r, c, moves) if (self.white_T...
def get_All_Possible_Moves(self): moves = [] for r in range(len(self.board)): for c in range(len(self.board[r])): turn = self.board[r][c][0] if (turn == 'W' and self.white_Turn) or (turn == 'B' and not self.white_Turn): piece = self.board[...
The main task of the code is to generate all valid moves for the current player by filtering out moves that leave the king in check. It temporarily stores en passant and castling rights, iterates through all possible moves, simulates each move to check for check conditions, removes invalid moves, and handles checkmate/...
def get_Valid_Moves(self): temp_Enpassant_Possible = self.enpassant_Possible temp_Castle_Rights = CastleRight(self.current_Castling_Right.wks, self.current_Castling_Right.bks, self.current_Castling_Right.wqs, self.current_Castling_Right.bqs) moves = sel...
def check_for_pins_and_checks(self) : pins = [] # squares where the allied pinned piece is and direction pinned from checks = [] # squares where enemy is applying a check in_check = False if self.white_to_move : enemy_color = "b" ally_color = "w" star...
This function generates valid moves for a chess engine by checking for checks, handling en passant and castling rights, and ensuring the king isn't left in check. It filters moves to block checks, captures attackers, or move the king, adds castling moves, restores original game state, and detects checkmate/stalemate if...
def get_valid_moves(self) : temp_enpassant_possible = self.enpassant_possible # copy the current castling rights temp_castling_rights = CastleRights(self.current_castling_rights.wks, self.current_castling_rights.bks, self.current_castling_rights.wqs, s...
def menu(): global ENUM while True: print("====EskPLOITATION====") print("1. Scan Port") print("2. Access Backdoor Shell") print("3. Get Enumerate") choose = int(input("> ")) if(choose == 1): Port_Finder(0,3600,True) elif(choose ==...
The main task of the code is to parse command-line arguments for a network tool, set global variables (URL, PORT, INTERFACE, LISTEN), and route execution to either a menu interface, receive enumeration, or send enumeration functions based on the provided flags (-I, -L, or default behavior). It handles user input valida...
def main(): global URL,PORT,INTERFACE,LISTEN system("clear") if len(sys.argv) == 1: print("Wrong Command Please Use option -H or --host <Host> -P or --port <Port> [-I or --interface] [-L or --listen]") return options, args = getopt.getopt(sys.argv[1:], "H:P:IL", ["host=", "port=", "inter...
def wait_for_all_classifications(article_id, retry): # Configuration for database dynamodb = boto3.resource('dynamodb') table = dynamodb.Table('technology_article_results') pk_key = 'article_id' # Get row response = table.get_item(Key={pk_key: int(article_id)}) article = response['Item'] ...
The main task of the code is to process DynamoDB stream events for new articles, extract their IDs, wait for classification data, and update time-based (hour/day/week/month) statistics for each article. It handles events by checking for 'NewImage' in records, retrieves article IDs, and triggers updates to time-aggregat...
def lambda_handler(event, context): for record in event['Records']: if 'NewImage' in record['dynamodb']: article_id = record['dynamodb']['NewImage']['article_id']['N'] else: print('Not a new event.') return; article = wait_for_all_classifications(article_id, 0...
def _evaluate_classification( self, examples: list[ClassificationExample], task_type: TaskType, ) -> dict[str, Union[Sequence[float], Sequence[int]]]: prompts = [ example.prompt + class_seq for example in examples for class_seq in example.classes ...
This method evaluates input examples based on the specified task type by routing them to corresponding evaluation functions, returning results as dictionaries with sequences of floats/integers. It restricts batch size to 1, handles classification, numeric, sequence probability, and log-odds tasks, casting examples to a...
def __call__( self, examples: list[Example], task_type: TaskType ) -> dict[str, Union[Sequence[float], Sequence[int]]]: # TODO: remove this restriction if len(examples) > 1: raise ValueError( f"Batch size of {len(examples)} not currently supported for HF models: p...
def rgbtohex(r,g,b): return f'#{r:02x}{g:02x}{b:02x}' def canvasClick( self, event ): x = event.x // self.rect_width # Matrix col index y = event.y // self.rect_height # Matrix row index if x < 0 or x >= self.width or y < 0 or y >= self.height: return if self.mode == MNIST_MODE or self.mo...
This code initializes a graphical user interface (GUI) for an image classification application. It sets up a Tkinter window with a grid-based canvas for user drawing, sliders to adjust parameters, a classification button, and a menu to select datasets (e.g., MNIST, MNIST Fashion). It loads pre-trained neural network mo...
def __init__( self, width = 28, height = 28, path_dir = "./models_data/"): self.style = """ Tk{ background: "#565657"; /*background color of the root widget*/ } Label{ foreground: "#ebebeb"; background: "#565657"; } Button{ f...
def Read_Configuration(self, AlertParam, **Kwargs): ''' Helper function to read configuration from database for requested alert. eg: Read_Configuration ( 'Gain Alert' ) ''' Server = str(self.C.config_dict['ClientDetails']['Alert_Config_det...
The main task of the code is to generate a complete HTML alert containing one or more Simple/Custom HTML tables based on the provided alert configuration. It reads query results, applies custom formatting where specified, constructs the HTML structure, and sends the alert via email as an attachment or directly, handlin...
def Complete_Alert (self,AlartParam ,**Kwarg): ''' Helper function to generate the complete HTML alert containing one or more ( Simple/Custom ) HTML tables depending upon the given configuration of passed alert name. eg: Complete_Alert( Alert Name) ...
def divide_to_i_j(self, city): return int(city/self.vm_num), city % self.vm_num def get_allow_city(self, passed_ct, left_sv, left_vm): not_allow = [] for i in range(len(left_sv)): if left_sv[i] == 0: for j in range(self.vm_num): not_allow.append(se...
This code implements an Ant Colony Optimization (ACO) algorithm for path finding. It iterates multiple times, initializing ants at random positions. Each ant constructs a path by selecting allowed cities based on pheromone trails and heuristic information, updating paths with probabilities. Pheromones are reinforced ba...
def run(self): for i in range(self.iter_times): passed_city = [[city] for city in self.ant_init_position] left_service = [] left_vm = [] for city in self.ant_init_position: sev, vm_j = self.divide_to_i_j(city) service = self.servic...
def gene_mat(self, sum, row, column, rand_size=1.5): z = 0 mat = np.zeros((row, column), dtype=np.int) for k in range(row): mat[k] = self.rand_sum(sum[k], column, rand_size) if self.if_false(mat): return self.gene_mat(sum, row, column) return mat def crowd...
The code performs a genetic algorithm to optimize a solution by iteratively evolving a population over multiple generations. It initializes a population, selects parents via crowding and ranking, applies genetic operators to generate new solutions, and returns the best individual from the final population after the spe...
def run(self): last_pop = [self.gene_mat(self.service_list, len( self.service_list), self.vm_num) for i in range(self.pop_size)] for gen_i in range(self.gen_count): cr_pool = self.crowd_and_rank(last_pop) parent_selected = self.select(cr_pool) last_pop ...
def Update_archive(self, archive_list): par_list=copy.deepcopy(self.partices) par_list = self.update_compare_set(par_list) par_list = np.concatenate((archive_list, par_list), axis=0) curr_archive_list = self.update_compare_set(par_list) return curr_archive_list def UpdateVelocity...
The code implements a swarm optimization algorithm by iterating through a maximum number of steps, updating an archive of optimal solutions, and adjusting each particle's velocity and position to optimize a target function.
def RunSwarm(self): size = len(self.partices) for curr_iter in range(self.max_iter): self.archieve = self.Update_archive(self.archieve) self.curr_iter = curr_iter for par_index in range(size): self.UpdateVelocityAndPosition(par_index) ...
def _get_audio_files( data_path: pathlib.Path, ) -> List[pathlib.Path]: # Check if the path is of a directory or a file: if data_path.is_dir(): # Get all files inside the directory: audio_files = list(data_path.glob("*.*")) elif data_path.is_file(): audio_files = [data_path] ...
The function transcribes audio files into text using a Whisper model, saving transcriptions to an output directory. It returns a dataframe with metadata (audio file, transcription file, detected language, duration) and a dictionary of errors. Key features include language detection, translation to English, speech diari...
def transcribe( data_path: Union[str, List[str]], output_directory: str, model_name: str = "base", device: Literal["cuda", "cpu", "auto"] = "auto", compute_type: str = "default", language: str = None, translate_to_english: bool = False, speech_diarization: Dict[str, List[Tuple[float, flo...
def _get_analyzer_engine( model: str = None, entities: List[str] = None ) -> pa.AnalyzerEngine: """ Return pa.AnalyzerEngine. :param model: The model to use. Can be "spacy", "flair", "pattern" or "whole". :param entities: The list of entities to use. :returns: pa.AnalyzerEngine """ # r...
The function `recognize_pii` processes text files to identify and anonymize personal identifiable information (PII) using specified models (e.g., spaCy, Flair). It walks through input files, detects entities, applies anonymization rules, and generates outputs like anonymized text, HTML visualizations, and JSON reports....
def recognize_pii( context: mlrun.MLClientCtx, input_path: Union[str, pathlib.Path], output_directory: str, html_key: str, score_threshold: float, entities: List[ str ] = None, # List of entities to recognize, default is recognizing all entity_operator_map: dict = None, mode...
def evaluate(grid): lines = [ [0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8], [0, 4, 8], [2, 4, 6], ] for row in lines: [a, b, c] = row if (grid[a] and grid[a] == grid[b] and grid[b] == grid[c]): re...
The function processes a game state by evaluating the board, determining the next optimal move for the AI ('X'), updating the game grid, and returning a structured response with the updated state, game status, and move details. It checks for win/tie conditions, handles turn transitions, and ensures proper game flow bet...
def getnextmove(): data = bytes(request.data).decode('UTF_8') data_json = json.loads(data) grid = data_json['state']['current'] grid_copy = copy.deepcopy(grid) gird_2d = np.reshape(grid_copy, (3, 3)) status, moves = evaluate(grid) if (isBoardFull(grid_copy)): response_value = { ...
def birkhoff_weights_context(n, _context): weights = _context.nplike_array_type([n]) if isinstance(weights, np.ndarray): return birkhoff_weights(n) elif isinstance(weights, cp.ndarray): return birkhoff_weights_cupy(n) else: raise ValueError("Unknown type of weights") def get_part...
This function tracks particles and their displaced counterparts over multiple turns in a particle accelerator, calculating and logging their displacement using Birkhoff weights. It writes normalized coordinates, log displacement values, and direction data to an HDF5 file for analysis, handling both CPU and GPU contexts...
def track_log_displacement_singles_birkhoff( line: xt.Line, twiss: xtw.TwissTable, nemitt: Tuple[float, float], part: xp.Particles, d_part_list: List[xp.Particles], d_part_names: List[str], initial_displacement: float, samples: List[int], _context, outfile: H5pyWriter, ): """...
def try_display_public(ips: List[Tuple[str, str]], port: int, args: Args): public_ip = get_my_ip() if public_ip is not None: remove_ip_from_list(ips, public_ip) display_url_via_ip(public_ip, port, "🚀", f"via public ip ({public_ip})", args) def try_display_vpn(ips: List[Tuple[str, str]], port: i...
The function `display_possible_urls` generates and displays potential URLs using local IP addresses and network configurations. It retrieves local IPs, attempts to show public and VPN URLs, then lists additional variants by iterating through IPs to construct URLs with specified formatting and parameters.
def display_possible_urls(port: int, args: Args): ips = get_local_ips() try_display_public(ips, port, args) try_display_vpn(ips, port, args) if len(ips) > 0: print("Other variants:") for ip in ips: display_url_via_ip(ip[1], port, "➤", f"via {ip[1]}", args)
def check_file_exists(path: Path): if not path.exists(): print(f"Cannot find {path}") exit(1) def display_hyperlinks_warning(): print("If you don't see links, add '--no-hyperlinks' flag") def display_possible_urls(port: int, args: Args): ips = get_local_ips() try_display_public(ips, port...
The main task of the code is to execute a performance script, launch an HTTP server with specified parameters, display warnings and URLs for server access, and maintain an infinite loop to keep the server running. It parses command-line arguments, validates file existence, generates server URLs, and handles hyperlink w...
def main(): args = parse_args() check_file_exists(args.path) perf_script_output = run_perf_script(args.path) http_server = start_server(Path(perf_script_output.name), args.address, args.port) if args.hyperlinks_enabled: display_hyperlinks_warning() print() display_possible_urls(h...
def q1_reflexive(): ''' Inputs: None Output: Prints relations 1 and 2 as well as the result of the is_reflexive function and the reflexive closure function Function: Determines if the relations are reflexive and finds the reflexive closure of the relations ''' #Relation 1 and 2 as well as t...
The main task of the code is to sequentially execute and invoke multiple functions related to relation properties (reflexive, symmetric, transitive, equivalence, poset) with newline separators between each call. The `main()` function acts as a controller, orchestrating the execution of these functions without accepting...
def main(): ''' Inputs: None Outputs: None Function: Calls all the functions ''' #Calls all the functions with \n between each one q1_reflexive() print("\n") q2_symmetric() print("\n") q3_transitive() print("\n") q4_equiv() print("\n") q5_poset()
def q1(): ''' Inputs: None Output: None Function: Tests if the functions given in the problem are injective, surjective and bijective ''' #List of test inputs (they are also numbered) test_inputs = [ ({"a","b","c","d"}, {"v","w","x","y","z"}, {("a","z"),("b","y"),("c","x"),("d","w")...
The main task of the code is to sequentially execute and display results for four distinct questions by calling functions q1() to q4(), each prefixed with its question number and separated by newlines. The main() function acts as a controller to orchestrate the execution of these question-specific functions in order, e...
def main(): ''' Inputs: None Output: None Function: Calls the functions for each question ''' #Call each function with a new line in between print("Question 1:") q1() print() print("\nQuestion 2:") q2() print("\nQuestion 3:") q3() print("\nQuestion 4:") q4()