dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def is_valid_point(self, x, y, z): if x < 0 or y < 0 or z < 0: return False if x >= self.maze.size or y >= self.maze.size or z >= self.maze.size: return False return not self.maze.is_obstacle(x, y, z) def is_in_close_set(self, position): return self.is_in_set(posi...
The code processes a 3D point (x,y,z) in a pathfinding algorithm. It validates the point, skips if already in the closed set or invalid, then initializes the position's parent and cost if not in the open set, appending it to the open set for further exploration.
def process_point(self, x, y, z, parent): if not self.is_valid_point(x, y, z): # Do nothing for invalid point return pos = Positions.Position(x, y, z) if self.is_in_close_set(pos): # Do nothing for visited point return # print("Process Poin...
def select_from_open_set(self): index = 0 selected_index = -1 min_cost = sys.maxsize for position in self.open_set: cost = self.total_cost(position) if cost < min_cost: min_cost = cost selected_index = index index += 1 ...
The code implements a 3D pathfinding algorithm (likely A* variant) to find a route from a starting point to a destination. It explores 28 neighboring positions in 3D space, maintaining open and closed sets to track unvisited and visited nodes. If the destination is reached, it reconstructs the path; otherwise, it retur...
def run_algorithm(self): start_time = time.time() start_point = Positions.Position(0, 0, 0) start_point.cost = 0 self.open_set.append(start_point) while True: index = self.select_from_open_set() # if no more points in the open list, return nothing ...
def parse_objects(objects): objects = objects.split(")") output = [] stops = [] for obj in objects: obj = re.split('[\[\]\'(), ]', obj) if len(obj) < 6: continue obj = [try_convert_int(val) for val in obj if val] obj = obj[:6] try: label = ...
The main task of the code is to perform real-time path planning for an autonomous vehicle by processing lane detection and object detection data from inter-process communication pipes. It interprets lane boundaries, detects obstacles, and issues control commands (e.g., braking, lane changes) to the motor and navigation...
def main(): saveVideo = True if (saveVideo): fourcc = cv2.VideoWriter_fourcc(*"XVID") out = cv2.VideoWriter("outputPP.avi", fourcc, 30.0, (320, 180)) #pipeMotor = os.open("/tmp/object_detection_to_motor", os.O_WRONLY) # Maybe we want this...? lanes_pipe = os.open("/tmp/lanes_to_pp", os....
def parse_args(): parser = argparse.ArgumentParser() parser.add_argument("--states", nargs='+', default=[], help="Run search terms over given list of states") parser.add_argument("--cities", nargs='+', default=[], help="Run search terms over given list of st...
The main task of the code is to continuously scrape and monitor changes in search results across specified cities using configurable settings. It reads input parameters, loads settings, logs details, retrieves city/state codes, executes searches with progress tracking, compares results over time, and notifies users of ...
def searcher(): oldresults= [] args = parse_args() # take in CLI arguments if args.settings == 'settings.yaml': # read in settings file settings = SettingsParser('etc/settings.yaml') print("\nUsing settings file: etc/settings.yaml") else: path = str('etc/' +...
def run_training(self, spike_train, t): halts = self.check_if_halts(t) while halts == False: self.forward_time_t(t) t = t + 1 halts = self.check_if_halts(t) return t def run_predicting_one_time(self, spike_train, load): self.initialize_all_groups(spike...
The function `run_network` determines whether to execute training or prediction based on the `train` parameter. If `train=True`, it triggers `run_training`. Otherwise, it checks the `privacy` input: if `None`, it runs standard prediction (`run_predicting_one_time`); if provided, it invokes privacy-aware prediction (`ru...
def run_network(self, spike_train=None, train=False, t=0, load=False, privacy=None): if train == True: return self.run_training(spike_train, t) else: if privacy is None: return self.run_predicting_one_time(spike_train, load) else: retur...
def FullModel(self, input_shape): X = Input(shape=input_shape) X_e = self.Encoder(input_shape)(X) X_p = self.Predictor(tf.keras.backend.int_shape(X_e)[1:])(X_e) I_d = tf.keras.layers.concatenate([X_e, X_p]) X_d = self.Discriminator(tf.keras.backend.int_shape(I_d)[1:])(I_d) ...
This code trains a deep learning model with an encoder, predictor, and discriminator using adversarial training. It iteratively optimizes each component in separate stages (encoder, predictor, discriminator), computes AUC metrics for validation, and saves the best model based on validation performance. The discriminato...
def Train(self, X_train, Y_train_p, Y_train_d, X_val, Y_val_p, Y_val_d, learning_rate, lambd, batch_size, num_epochs): # Initialization tf.keras.backend.clear_session() self.E = None self.P = None self.D = None self.FM = None self.iter_perfomance = [...
def print(self, *args, **kwargs): print('ugit:', *args, **kwargs) def normalize_path(self, path: str, is_dir: bool | None = None): if is_dir is None: is_dir = path.endswith('/') return self.join_path(self.split_path(path), is_dir) def list_device_files(self, path: str): for name, type, *_ in os.i...
This code synchronizes local device files with a Git repository by pulling updates, replacing or creating files when hashes differ, and removing local files no longer present in the repo. It respects ignore lists, skips dot files by default, and ensures only tracked files remain in the local directory.
def pull(self, git_root: str | None = None, ignore: list[str] | None = None, ignore_dot_files=True): self.print(f'Pulling repo: {self.raw_url}') git_root = self.normalize_path(git_root if git_root else '', is_dir=True) ignore = [ self.normalize_path(path) for path in ignore ] if ignore ...
def is_user_logged(username): for active_client in active_clients: if username in active_client: return True return False def create_message_dic(sender, receiver, message_type, content): return { "sender": sender, "receiver": receiver, "type": message_type, ...
This function handles client login by receiving and decoding a message, validating the username, encrypting and sending a key if the user isn't logged in, adding the user to active clients, broadcasting a login message, sending chat history, and starting a thread to listen for further messages. It ensures proper authen...
def client_handler(client): message = client.recv(16384).decode() login_dic = eval(message) username = login_dic["sender"] client_key = rsa.PublicKey.load_pkcs1(login_dic["content"]) if username != '': if is_user_logged(username): prompt_message = create_message_dic( ...
def decrypt(message: bytes, key): iv = message[:16] decrypt_data = message[16:] cipher = AES.new(key, AES.MODE_CBC, iv=iv) original = unpad(cipher.decrypt(decrypt_data), AES.block_size) return original def send_messages_to_all(message): save_message(message) for user in active_clients: ...
The function listens for incoming messages from a client, decrypts them, and routes messages to all users or specific recipients based on the 'receiver' field. It sends the message to the appropriate users and confirms delivery to the sender if the message is non-empty.
def listen_for_messages(client, username): while 1: message = decrypt(client.recv(16394), key).decode() if message != '': dic = eval(message) if dic["receiver"] == "all": send_messages_to_all(message) else: send_message_to_user(dic...
def process_history(history): start = history.index(b"STARTLOG~") + len(b"STARTLOG~") end = history.index(b"~ENDLOG", start) history = decrypt(history[start:end], aes_key).decode() logs = history.split('\n') for log in logs: if log != '': dic_received = eval(log) disp...
The function listens for server messages, collects log data until a specific end marker, decrypts and processes non-log messages, and displays errors or content based on message type.
def listen_for_messages_from_server(client): while 1: message = client.recv(16384) if message.startswith(b"STARTLOG~"): history_message = message while 1: if history_message.endswith(b"~ENDLOG"): process_history(history_message) ...
def turn_order(self) -> list[Character]: all_characters = [self.player] + self.enemies return sorted( all_characters, key=lambda x: x.attributes.speed, reverse=True) def print_roll(self, results: list[dice.Result]): for result in results: print(f"{...
This code manages a turn-based battle round by incrementing the round count, determining the action order, displaying creature statuses, executing each creature's action (including rolling, applying effects based on alliance, and handling confusion), and updating the battlefield state with delays between actions.
def step(self): self.round += 1 turns = self.turn_order() cur_statuses = ",\n".join( [x.char_hp() + f" (Speed: {x.attributes.speed})" for x in turns]) fp.Fancy_Print(f"\nRound {self.round}:\n\n" + f"{cur_statuses}.") for cur_turn_creature in turns...
def get_links(url): res = get_request(url) if res.status_code != 200: return None soup = BeautifulSoup(res.content, 'html.parser') results = soup.find_all('li') links = [] for li in results: try: li_class = li['class'] # li_bm = li['data-bm'] i...
The code searches for valid WordPress articles using a keyword, validates links against predefined criteria, extracts and paraphrases content via Selenium, saves the article and images, and sends a success notification if all steps complete successfully.
def get_article_from_keyword(keyword:str, keyword_result_report:KeywordsResultsReport): try: with open('spin.txt') as f: lines = f.readlines() if lines: lines = lines[0].split(',') # print(f"Lines: {lines}") except: lines = [] query = keyword.r...
def get_max_brightness(): """Return the maximum display brightness. :return: Maximum possible brightness value. :rtype: int """ return int(_get_value("max_brightness")) def get_actual_brightness(): """Return the actual display brightness. :return: Actual brightness value. :rtype: int ...
This function adjusts display brightness to a specified value, either instantly or with a smooth fade effect over a given duration. It validates input parameters, ensures the value is within allowable bounds, and applies gradual changes when smoothing is enabled.
def set_brightness(value, smooth=False, duration=1): """Set the display brightness. :param value: Brightness value between 11 and 255 :param smooth: Boolean if the brightness should be faded or not :param duration: Fading duration in seconds """ max_value = get_max_brightness() if not isins...
def crop_image(path, size): w, h = get_image_size(path) crop_size_x = w % size crop_size_y = h % size l1 = crop_size_x // 2 l2 = crop_size_y // 2 r1 = crop_size_x - l1 r2 = crop_size_y - l2 image = PIL.Image.open(path).crop((l1, l2, w-r1, h-r2)) image.save(path) def load_image(pat...
This function reduces an image's complexity by clustering colors into n centers, either via Rubik's cube-style processing (cropping, averaging colors) or standard methods. It loads an image, calculates color labels, and reconstructs the image using specified centers, smoothing, contour settings, and saves the result if...
def reduce(n, path, centers=None, rubik=False, size=-1, contour=True, smoothing=0, save_path=None): if rubik: crop_image(path, size) image = load_image(path) if rubik and (not fit(image.shape, size)): print('Bad params') return if rubik: image = get_avg_colors(image, ...
def compare_strings(string1,string2): """ Comparing two strings :param string1: first string, which will be compare :param string1: second string, which will be compare :returns: if the strings match """ strings1=string1.lower().split() #lower case divided into words ...
The function `footballers_mapper` extracts footballer data from a webpage's HTML based on a user's search input. It parses player names, matches them against the input, and retrieves associated club, season, and team information. Data is structured into a dictionary of players with their matches and a list of matches/t...
def footballers_mapper(tupple_page): """ Extracting all data about footballers from the page :param tupple_page: (searched input from user,webpage html) :returns: (dictionary of players and their matches, list of matches and teams) """ for_matches_team=[] # extracting teams ...
def DisplayMenu(self, events=None, start_menu=False): clear() message = self.main_menu_message if start_menu: clear() if self.difficulty == Difficulty.debug: print('DEBUGGING ACTIVE') print(message + '\n\n') print(f'1. Start game with random initial event.\n2. Choose initial ...
The code's main task is to handle user input for selecting initial events, changing difficulty, or ending the game. It validates input, updates event status, and displays menus accordingly. Options 1-3 trigger random/event selection, difficulty changes, and status updates, while option 4 terminates the program.
def Run(self): self.DisplayMenu(start_menu=True) user_input = input('Selection: ') while not user_input in ('1', '2', '3', '4'): self.DisplayMenu(start_menu=True) user_input = input('Input not recognized. Try again: ') if user_input == '1': #Set the initial event to be equal to a rando...
def create_grit(img,gridsize,color): global height global width for i in range(1,int(width/gridsize)+1): cv.line(img,(gridsize*i,0),(gridsize*i,height),color) for j in range(int(height/gridsize)): cv.line(img,(0,gridsize*j),(width,gridsize*j),color) return img def grid(self,areasi...
This code initializes and runs a snake game loop, handling user input, updating game state, rendering a grid with wave effects, and displaying the game canvas. It uses timers for game speed control, processes key events for movement/restart, and maintains gameplay until the escape key exits.
def play(self): canvas = np.zeros((height,width,3), dtype=np.uint8) canvas = create_grit(canvas,gridsize,(100,0,0)) self.grid(self.areasize,0) last_input = 255 gameTimer_start = time.time_ns()//1000000 gameSpeed = [10,500,5000] #ms gameTimeBookmark = [0,0,0] ...
def clearFrame(): for widget in frame.winfo_children(): widget.destroy() def offered_files_frame(): # Changes window title window.title('Peer Client: Offered Files') # Creates a text label above the downloads section tk.Label(frame, text='Download Section').pack() # Creates the dow...
The main task of the code is to create a GUI window for a peer-to-peer file sharing application. It sets up a window titled "Peer Client" with navigation buttons to switch between frames (e.g., viewing downloadable files, hosting files, and settings). The interface displays a dynamic welcome message depending on the se...
def root_window(connected): window.title('Peer Client') # Creates header frame for all directory buttons header = tk.Frame(window) header.pack(side="top", fill="x") # Creates buttons for changing frames, note that the frame must be cleared before the new frame is rendered tk.Button(header, ...
def __connect_to_server(self): if self.load_user_id() is None: self.__init__() try: # connects to server and recieves data self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.connect((self.server_ip, 12756)) # Sends messag...
The main task of the code is to establish a server connection, initialize a user object with loaded credentials and requested data, securely send a "close_connection" signal using RSA encryption, detach the socket, and return the connection status.
def first_connection(self): status = self.__connect_to_server() self.user = User(self.load_user_id(), self.__request_connection_data()) sendRsa("close_connection", self.get_server_RSA_pubkey(), self.sock) self.sock.detach() return status
def __connect_to_server(self): if self.load_user_id() is None: self.__init__() try: # connects to server and recieves data self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.connect((self.server_ip, 12756)) # Sends messag...
This function connects to a server, retrieves a list of downloadable files via RSA-encrypted communication, processes each filename into a dictionary with a checkbox status, and returns the structured list after handling connection closure and data validation.
def fetch_downloads_list(self): # Connects to server, if failure in connecting returns None if not self.__connect_to_server(): return None #Requests the downloads list sendRsa("down_list", self.get_server_RSA_pubkey(), self.sock) # Receives data on all avail...
def __connect_to_server(self): if self.load_user_id() is None: self.__init__() try: # connects to server and recieves data self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.connect((self.server_ip, 12756)) # Sends messag...
The function securely communicates with a server to retrieve users hosting requested files. It connects to the server, sends encrypted download requests using RSA, receives the list of hosting users, closes the connection, and returns the user data. If the connection fails, it returns None.
def get_download_users(self, download_request_list): status = self.__connect_to_server() # If the connection to the server fails, return None if not status: return None # send server list of files the client wants to download sendRsa("request_file_hosts", sel...
def extract_unique_time_slots(time_window): time_slots = set() for slot in time_window: start_time, end_time = slot time_slots.add(start_time) time_slots.add(end_time) unique_time_slots = sorted(time_slots) return unique_time_slots def find_next_node(fix_data, update_data): ...
The main task of the code is to generate optimized vehicle routes using time-window constraints, working hours, and break times. It processes each vehicle iteratively, selecting next nodes via `find_next_node`, managing route updates, and ensuring compliance with time limits. The function calculates start times, total ...
def AutoRouteAlgo(data): start_time_per_vehicles = [] vehicles_total_time = [] routes = [] vehicles_break_time_index_list = [] hour_list = data['hour_list'] num_vehicles = data['num_vehicles'] time_matrix= data['time_matrix'] time_window = data['time_windows'] depot = data['depot'] ...
def execute_command(cmd,no_check=False): print("cmd = ",cmd) p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) for line in p.stdout.readlines(): print("--->",line) strvalue = line.decode('utf-8').strip() print(strvalue) retval = p.wait() ...
The main task of the code is to retrieve FITS.gz files from an S3 input bucket, organize them by subdirectory, copy them locally, process each file to register exposure and L2 data in a database with metadata, and then clean up temporary local files. It uses AWS S3 for storage access, FITS headers for metadata extracti...
def register_files(): s3 = boto3.resource('s3') # Parse input files in input S3 bucket. my_bucket_input = s3.Bucket(bucket_name_input) files_input = {} for my_bucket_input_object in my_bucket_input.objects.all(): #print(my_bucket_input_object.key) gzfname_input = my_bucket_in...
def add_columns_powered(df,base_columns, upperbound, invert=False): for column in base_columns : for i in range(2, upperbound+1): df[column + '_power' + str(i)] = df[column] ** i if invert: df[column + '_root'+str(i)] = df[column].apply(root_column,args=(i,)) def add_...
The main task of the code is to enhance a dataset by generating polynomial features and interaction terms (n-uplets) from specified base columns, then compute correlations between these engineered features and a target variable. It returns the modified DataFrame with new features and a sorted correlation matrix, filter...
def main_brute(df,base_columns,target,thresh=0.2,upperbound=3,n_uplet=6,invert=True): df_copy=df.copy(deep=True) add_columns_powered(df_copy,base_columns,upperbound,invert) print("powers added") add_n_uplet(df_copy,base_columns,n_uplet) print("n_uplet added") corr=correlation_sort(df_copy,target...
def _gather_json_data(dirpath: str, filter: List[str] = None) -> List[dict]: """Gathers all JSON files from within a diven directory""" results = [] for filename in os.listdir(dirpath): if not filename.endswith(".json"): continue if filter and not filename in filter: ...
The main task of the code is to aggregate metadata from multiple dataset sources (local JSON files and STAC API), compile it into a structured JSON dictionary, and store the result in a cloud bucket for use with a datasets API endpoint. The handler function prepares data for queries like LIST and GET operations by gath...
def handler(): """ Returns: ------- (string): JSON-encoded dict with top level keys for each of the possible queries that can be run against the `/datasets` endpoint (key: _all_ contains result of the LIST operation, each of other keys contain the result of GET /datasets/{spotlig...
def display_details(filename, author, email): """Display the author's details.""" print(f'File : {filename}', f'Author : {author}', f'Email : {email}', sep='\n', end='\n\n') def input_name(): """Prompt for, read, and validate the player's name. Returns ---...
This code implements a Blackjack game where the user can play multiple rounds against a dealer. It tracks wins, losses, and ties, displays game outcomes, and handles error cases during score calculation. The game initializes hands, processes player and dealer moves, compares points, and updates statistics. After each r...
def play_game(): print("--------- Welcome to Blackjack ---------\n") # Display the author's details. display_details('main.py', 'Tan Duc Mai', 'krmzd@example.com') # Variable initialisation. valid_answers = ['y', 'n'] games = 0 dealer_hand = [] player_hand = [] won = 0 lost = 0...
def build_prompt(git_file_paths: List[str], template_file_path: str, notes_file_path: Optional[str] = None): git_files_contents: List[str] = [read_file_content(file_path) for file_path in git_file_paths] git_files_string = _prepare_git_files_to_prompt(git_files_contents) template_file_content: str = read_fi...
The function generates an explanation from code files using a template via GPT-3.5, then creates a filename and directory path based on the hierarchy string. It combines code and template into a prompt, sends it to OpenAI's API, extracts the generated explanation, and returns the explanation along with structured file-...
def generate_explanation_from_template(code_files_paths: List[str], template_file_path: str, notes_file_path: Optional[str], hierarchy_string): template, files_code = build_prompt(code_files_paths, t...
def find_nodes_on_shortest_path(graph, start: int, target: int): distances, predecessors = dijkstra_shortest_path(graph, start, target) path = reconstruct_path(predecessors, start, target) return path def find_landmark_path(sim_matrix, shortest_path): similarity = copy.deepcopy(sim_matrix) similarit...
The code optimizes a graph's nodes by adjusting their features to enhance similarity with specified landmarks along a shortest path from a start to target node. It increases similarity for key nodes using image-to-text attacks and reduces similarity for others via image-to-image attacks, tracking modified nodes and the...
def optimize_minimal_nodes(graph, start_node, landmarks, target_node, model, preprocess, img_to_img_args, img_to_txt_args, device): copy_graph = copy.deepcopy(graph) path = find_nodes_on_shortest_path(copy_graph, start_node, target_node) print(f'From starting node {start_node} to target node {target_node}...
def corrected_prediction_prob(config, domain=None): """ Reads predictions_probabilities for finetune and inference, and corrects the inference scores based on the f1-scores of the training data. The corrected scores are then returned as a pandas DataFrame. Args: config (dict): A dictionary cont...
The code ensembles predictions from NLP and Vision models by aligning their outputs via ID sorting and discrepancy handling. It combines corrected probability scores, maps predicted labels using a YAML file, and constructs a DataFrame containing original labels, individual model predictions, and ensemble predictions fo...
def ensemble(self, config): """ Ensemble predictions from NLP and Vision models Args: config (dict): configuration for the ensemble predictions Returns: df_results (pandas.DataFrame): a DataFrame containing the ensemble predictions and the labels """ ...
def grid(ds, right_edge, left_edge, dims): arb_grid = ds.arbitrary_grid(left_edge, right_edge, [dims,dims,dims]) #if yt.is_root(): ds_new = arb_grid.save_as_dataset(fields=[('deposit','PartType1_density')]) grid_ds = yt.load(ds_new) print ('-------- Arbitrary grid dataset created. --------') ret...
The code generates an animation from cosmological simulation data using yt and custom visualization tools. It loads a dataset, defines parameters for animation type (zoom/rotate/rotzoom), resolution, magnification, and centering, then creates frames by processing the data grid, adjusting the camera, and applying densit...
def main(): #------ Define parameters in CODE ------ #pathway to where program is saved program_path = "/Users/andy/Desktop/Summer Projects/Visualization/" #pathway to where data is saved data_path = "/Users/andy/Desktop/L100_N256/snapdir_015/snapshot_015.0.hdf5" #pathway to rockstar catalog & c...
def get_auth_client( subscription: Any, ) -> AuthClient: """Get an auth client for a given subscription. See https://docs.microsoft.com/en-us/python/api/azure-mgmt-authorization/azure.mgmt.authorization.authorizationmanagementclient?view=azure-python # noqa pylint: disable=C0301 Args: subscrip...
The function retrieves role assignment models for a given subscription by fetching role definitions and assignments, processing each assignment with the graph client, and returning a list of RoleAssignment objects. It handles CloudError exceptions, logging issues like GraphAPI permission errors, and returns an empty li...
def get_subscription_role_assignment_models( subscription: Any, graph_client: GraphRbacManagementClient, ) -> list[RoleAssignment]: """Get the role assignment models for each a subscription. Args: subscription: The subscription to get role assignments for. graph_client: The graph client...
def train_dataloader(self): transform = transforms.Compose([ transforms.Resize((self.args.frame_H, self.args.frame_W)), transforms.ToTensor() ]) dataset = Dataset_Dance(root=self.args.DR, transform=transform, mode='train', video_len=self.train_vi_len, \ ...
This code implements a training loop for a neural network model, iterating over epochs to train on a dataset. It accumulates loss, mean squared error (MSE), and Kullback-Leibler divergence (KLD) metrics, applies teacher forcing with a probabilistic ratio (self.tfr), updates learning rates via a scheduler, saves model c...
def training_stage(self): for i in range(self.args.num_epoch): epoch_loss = 0 epoch_mse = 0 epoch_kld = 0 train_loader = self.train_dataloader() # self.tfr = 0 adapt_TeacherForcing = True if random.random() < self.tfr else False ...
def _create_template_db(self, test_case: 'TestCaseWithDB'): with self._lock: if not self._created: self._create_db(True) db = self.init_db(self.dsn(database=self._template_name), test_case=test_case) db.close() self._created = True ...
This code creates a PostgreSQL database for a test case by first setting up a template database, then generating a new database name. It returns a Peewee database connection configured with the new database name and test case parameters, enabling database-specific testing and isolation.
def __call__(self, test_case: 'TestCaseWithDB') -> peewee.PostgresqlDatabase: self._create_template_db(test_case) db_name = self._create_db(False) return self.get_peewee_db(self.dsn(database=db_name), test_case)
def debug_comments(self,line): self.file.write(f"//{self.debug_line_number}\n") self.file.write(f"//{line}") self.debug_line_number += 1 def write_arithmetic(self,operation): #Arithmetic if operation == "add": self.__sp_dec() self.__d_eq_ptr() ...
This method processes commands by delegating to specific handlers based on the command type. If a debug line is provided, it logs the comment. For arithmetic commands, it calls `write_arithmetic`; otherwise, it handles push/pop operations via `write_push_pop` with parsed arguments.
def write_command(self,command_type,arg1,arg2,debug_line="null"): if debug_line != "null": self.debug_comments(debug_line) if command_type == self.C_ARITHMETIC: self.write_arithmetic(arg1) else: self.write_push_pop(command_type,arg1,int(arg2))
def debug_comments(self,line): self.file.write('//'+str( self.debug_line_number )+'\n') self.file.write('//'+line) self.debug_line_number += 1 def write_arithmetic(self,operation): #Arithmetic if operation == 'add': self.__sp_dec() self.__d_eq_ptr() ...
This function handles different VM command types by dispatching to corresponding methods like write_arithmetic, write_push, etc., based on the command_type parameter. It also optionally adds debug comments if debug_line is specified. The function processes arguments, converting them to integers where needed, and delega...
def write_command(self,command_type,arg1,arg2,debug_line='null'): if debug_line != Constants.NO_DEBUG: self.debug_comments(debug_line) if command_type == Constants.C_ARITHMETIC: self.write_arithmetic(arg1) elif command_type == Constants.C_PUSH: self.write_pu...
def cross_validation_split(dataset, n_folds): ''' Cross validation Arguments: dataset: ndarray n_folds: int, number of folds Returns: list of ndarray ''' dataset_split = [] dataset_copy = dataset.copy() fold_size = int(len(dataset) / n_folds) for i in range(n_...
The code performs cross-validation to evaluate a machine learning algorithm's performance on a dataset. It splits data into folds, trains the algorithm on each training fold, tests on the validation fold, and collects metrics like accuracy, precision, recall, AUPRC, and AUROC. It also stores trained models and generate...
def cv_evaluate_algorithm(dataset, algorithm, n_folds, path, *args): ''' Evaluate an algorithm using a cross validation split Returns: a list contains accuracy, precision, recall, auprc, auroc a list contains models from CV ''' folds = cross_validation_split(dataset, n_folds) sco...
def getTop5(category_list): # this list will store our top 5 articles top_results = [] general_article_set = [] print_first = True for ar in RetreiveNews('general'): # creating a set of general articles, ranked only by popularity, not category general_article_set.append(ar) # i...
The main task of the code is to fetch and filter top news articles based on specified categories, ensuring uniqueness by comparing titles with a fuzzy ratio, appending summaries and read times, and returning the processed results as JSON with CORS headers enabled.
def NewsHeadlines(request): print('Starting NewsHeadlines') # Get data from url categories = request.args.get('categories', default = '') cat_list = categories.split('-') top_results = getTop5(cat_list) # empty list which will # contain all trending news print('Filtering Results...
def getTop5(category_list): top_results = [] #this list will store our top 5 articles general_article_set = [] print_first = True for ar in RetreiveNews('general'): #TODO FIND OUT WHAT THE RESPONSE OBJECT RETURNS general_article_set.append(ar) #creating a set of general articles, ranked only by ...
The main task of the code is to retrieve and filter unique news articles from the 'health' category, ensuring diversity by checking title similarity. It gathers top results, removes duplicates, appends summaries and read times, then returns the curated list as JSON. The function prioritizes uniqueness, replaces non-uni...
def NewsHeadlines(): print('Starting NewsHeadlines') cat_list = ['health'] top_results = getTop5(cat_list) # empty list which will # contain all trending news print('Filtering Results') filtered_results = [] used_articles = [] article_num = 0 #iterate through top a...
def initialize_NN(self, layers): weights = [] biases = [] num_layers = len(layers) for l in range(0,num_layers-1): W = self.xavier_init(size=[layers[l], layers[l+1]]) b = tf.Variable(tf.zeros([1,layers[l+1]], dtype=tf.float32), dtype=tf.float32) ...
This code initializes a physics-informed neural network (PINN) for solving partial differential equations (PDEs). It sets up placeholders for initial/boundary conditions, collocation points, and parameters, constructs a neural network with specified layers, defines loss functions combining PDE residuals and condition e...
def __init__(self, U0, InitCond, UOrigin, OriginCond, Uf, Y_int, BinaryMat, Nf_u, Nf_t, layers, lb, ub, lambdaParam, rho, a): # Don't have boundary conditions # U0 are points along the spatial dimension at which we enforce the initial conditions # InitCond are the initial condition...
def initialize_NN(self, layers): weights = [] biases = [] num_layers = len(layers) for l in range(0,num_layers-1): W = self.xavier_init(size=[layers[l], layers[l+1]]) b = tf.Variable(tf.zeros([1,layers[l+1]], dtype=tf.float32), dtype=tf.float32) ...
This code initializes a neural network model to solve a partial differential equation (PDE) using physics-informed neural networks (PINNs). It sets up initial conditions, collocation points, and system parameters, constructs a neural network with specified layers, and defines a loss function combining initial condition...
def __init__(self, X0, InitCond, Xf, Nf_x, Nf_t, layers, lb, ub, dampRatio, nu, alfa, intensity): # Don't have boundary conditions # X0 are points along the spatial dimension at which we enforce the initial conditions # InitCond are the initial condition values # Xf are the collocation...
def target1(): global target1 target1 = tk.Button(boxroot, command=lambda: [no1(), sink1()], text="exit", bg="#FFB6C1") target1.place(x=0, y=0) def target2(): global target2 target2 = tk.Button(boxroot,command=lambda:[no2(), sink2()], text="exit", bg="#FFFF99") target2.place(x=50, y=50) def targ...
The code defines a function `useless()` that initializes a Tkinter GUI window with fixed size, non-resizable settings, and a blue background. It declares global variables for the window and four movable elements, then calls four target functions (`target1()` to `target4()`) to presumably add GUI components. Finally, it...
def useless(): global boxroot global movable1 global movable2 global movable3 global movable4 boxroot = tk.Tk() boxroot.geometry("1000x502") boxroot.resizable(False, False) boxroot.configure(bg='#3197e0') target1() target2() target3() target4() boxroot.mainloop()
def get_value(self, key): value = None with Absorbaroo._lock: if key in self._config.keys(): value = self._config[key] return value def _get_domainlist_id(self, edge_api, name): domainlists = edge_api.get_domainlists() for dl in domainlists: ...
The function updates a domain list on an edge API by authenticating with provided credentials, retrieving or generating a domain list ID, creating a CSV file from endpoints, and uploading it via the API. It returns True if all steps succeed, otherwise False.
def _update_domainlist(self, edge_api, endpoints): succeed = False if edge_api.login(self.get_value('edge_client_id'), self.get_value('edge_secret')): domainlist = self.get_value('edge_domainlist') if '' == domainlist['edge_id']: domainlist['edge_id'] = self._get_...
def get_value(self, key): value = None with Absorbaroo._lock: if key in self._config.keys(): value = self._config[key] return value def _get_endpoints(self, ep_api): endpoints = [] for ep in ep_api.get_endpoints(self.get_value('o365_instance')): ...
The main task of the code is to synchronize endpoints across Office 365, Edge, and Meraki systems by validating API credentials, checking version consistency, updating domain lists, and applying firewall rules, while logging status and updating timestamps if successful.
def synchronize_endpoints(self): if self._debug: print('Synchronize Endpoints is called....') ep_api = EndpointsAPI(self.get_value('o365_client_id'), debug=True) edge_api = EdgeAPI(self.get_value('edge_url'), debug=True) meraki_api = MerakiAPI(self.get_value('sdwan_key'), deb...
def get_value(self, key): value = None with Absorbaroo._lock: if key in self._config.keys(): value = self._config[key] return value def _get_endpoints(self, ep_api): endpoints = [] for ep in ep_api.get_endpoints(self.get_value('o365_instance')): ...
This function synchronizes endpoints across Office 365, DNS Edge CI, and Meraki SD-WAN by validating credentials, fetching endpoint data, updating domain lists, and configuring firewall rules. It returns True on successful synchronization or False if any validation step fails.
def force_synchronize_endpoints(self): ep_api = EndpointsAPI(self.get_value('o365_client_id'), debug=True) edge_api = EdgeAPI(self.get_value('edge_url'), debug=True) meraki_api = MerakiAPI(self.get_value('sdwan_key'), debug=True) # Checking Office 365 endpoints if not ep_api.val...
def get_value(self, key): value = None with Absorbaroo._lock: if key in self._config.keys(): value = self._config[key] return value def _update_domainlist(self, edge_api, endpoints): succeed = False if edge_api.login(self.get_value('edge_client_id'), s...
The main task of the code is to clear or update network endpoints by validating Edge and Meraki API configurations, updating domain lists and firewall rules, and resetting version/execution tracking values if successful. It returns a boolean indicating task completion status.
def clear_endpoints(self): edge_api = EdgeAPI(self.get_value('edge_url'), debug=True) meraki_api = MerakiAPI(self.get_value('sdwan_key'), debug=True) endpoints = [] # Checking DNS Edge CI if not edge_api.validate_edgeurl(): return False succeed = False ...
def __is_single_pair(self) -> bool: return self.__get_number_of_pairs() == 1 and self.__get_number_of_triplets() == 0 and not self.__is_four_of_a_kind() def __is_double_pair(self) -> bool: return self.__get_number_of_pairs() == 2 def __is_triplet(self) -> bool: return self.__get_number_of_triple...
The function determines a base score based on the type of hand detected. It checks for single pair, double pair, triplet, full house, four-of-a-kind, or five-of-a-kind in sequence, assigning scores 1 through 6 respectively. The first matching condition sets the score, which is returned.
def base_score(self): score: int = 0 if self.__is_single_pair(): score = 1 elif self.__is_double_pair(): score = 2 elif self.__is_triplet(): score = 3 elif self.__is_full_house(): score = 4 elif self.__is_four_of_a_kind(): ...
def check_for_b005(self, node): if node.func.attr not in B005.methods: return # method name doesn't match if len(node.args) != 1 or not isinstance(node.args[0], ast.Str): return # used arguments don't match the builtin strip call_path = ".".join(self.compose_call_path...
This code analyzes AST nodes for potential security issues by checking method calls. It specifically handles `Attribute`-based function calls, triggering checks for issues like B005, and other bugs (B004, B009, B010) for non-attribute calls. It constructs call paths to detect invalid patterns, appending errors when mat...
def visit_Call(self, node): if isinstance(node.func, ast.Attribute): self.check_for_b005(node) # for bug in (B312,): # if node.func.attr in bug.methods: # call_path = ".".join(self.compose_call_path(node.func.value)) # if call_path ...
def get_map(config_path, plex): plex_map = {} current_length = 0 current_count = 0 if TMDB.valid: tmdb = TMDb() tmdb.api_key = TMDB(config_path).apikey tmovie = TMDb_Movie() print("|") if plex.library_type == "movie": config_dir = os.path.dirname(config_path) ...
The main task of the code is to add media items (movies/shows) to a Plex collection using various methods (e.g., Plex search, IMDb, TVDb, Trakt) while applying filters. It retrieves items based on the specified method, checks filters for attributes like actors, genres, or ratings, and adds matching items to the collect...
def add_to_collection(config_path, plex, method, value, c, plex_map=None, map=None, filters=None): if plex_map is None and ("imdb" in method or "tvdb" in method or "tmdb" in method or "trakt" in method): plex_map = get_map(config_path, plex) if map is None: map = {} items = [] missing = ...
def getConfigPaths(path): configPaths = [] for filename in os.listdir(rootdir): if filename.startswith('config.') and filename.endswith('.json'): configPaths.append(join(path, filename)) return configPaths def getTopLevelTemplates(path): global version8 tmpFile = open(path, 'r') ...
The main task of the code is to audit custom fields across multiple configurations by collecting top-level Soy templates, building a template map, extracting custom fields from Soy files, and exporting them. It processes each config to avoid redundant hierarchies, ensuring unique templates and generating a structured o...
def main(path): #global variables defined as global global template2Path global soyFiles global jsonPaths global file2Cfs global version8 topSoyTemplates = [] #Using the rootdir we get the paths to all configs configPaths = getConfigPaths(path) #this loop allows for multiple c...
def get_bits(self,length): r = 0 for i in range(length,0,-1): r = (r << 1) | self.buf[self.index+i - 1] self.index += length return r def get_string(self,len): s = [] for i in range(0, len): s.append(self.get_1_byte()) return bytes(s).dec...
This function parses item data from a buffer by extracting bit flags, version, location, and other attributes, handling different item types (e.g., ear, compact, magic) and qualities (inferior, rare, set). It constructs an `Item` object with properties like durability, graphics, affixes, and socketed items, using bit m...
def get_item(self): item = Item() flags = self.buf[self.index:self.index + 32] item.IsIdentified = flags[4] item.IsSocketed = flags[11] item.IsNew = flags[13] item.IsEar = flags[16] item.IsStarteritem = flags[17] item.IsCompact = flags[21] item.Is...
def get_4_bytes(self): return self.get_bits(32) def get_2_bytes(self): return self.get_bits(16) def get_item(self): item = Item() flags = self.buf[self.index:self.index + 32] item.IsIdentified = flags[4] item.IsSocketed = flags[11] item.IsNew = flags[13] ...
The main task of the code is to parse binary data into a `Corpse` object by reading specific byte values (X, Y, item count) and a list of items. It constructs a `Corpse` instance, populates its attributes, and returns the item list after extracting data from a binary stream.
def get_corpse(self): c = Corpse() always0 = self.get_4_bytes() c.X = self.get_4_bytes() c.Y = self.get_4_bytes() jm_0x4d4a = self.get_2_bytes() item_count = self.get_2_bytes() c.ItemList = [] for j in range(0, item_count): c.ItemList.append(s...
def get_4_bytes(self): return self.get_bits(32) def get_string(self,len): s = [] for i in range(0, len): s.append(self.get_1_byte()) return bytes(s).decode().replace("\x00", "") def get_1_byte(self): return self.get_bits(8) def get_bits(self,length): r = 0 ...
This code parses a binary file format by reading and organizing data fields such as character attributes, skills, items, and status flags. It extracts values using bit manipulation, processes structured data (e.g., character progression, timestamps), and builds lists for skills, items, and corpses. The method handles e...
def parse(self): self.index = 0 self.Signature = self.get_4_bytes() self.Version = self.get_4_bytes() self.FileSize = self.get_4_bytes() self.CheckSum = self.get_4_bytes() self.ActiveWeapon = self.get_4_bytes() self.ChacterName = self.get_string(16) chact...
def get_likehood(strain_dict, nodes_vector_dict): strain_num = len(strain_dict.keys()) sample_num = len(list(nodes_vector_dict.values())[0]) def get_X_list(nodes_vecotr_dict): X_list = [] for key, val in nodes_vecotr_dict.items(): X_list.append(val) return X_list ...
The function `check_R_strain` iteratively optimizes a strain configuration dictionary by comparing BIC (Bayesian Information Criterion) values of different states. It removes nodes one-by-one, recalculates likelihoods, parameters, and BIC scores, and retains the configuration with the lowest BIC. The process continues ...
def check_R_strain(n1_nodes_strain_dict, n1_nodes_vector_dict, BIC_file): previous_strain_dict = deepcopy(n1_nodes_strain_dict) # for key in sorted(n1_nodes_strain_dict.keys(), key=lambda x: len(n1_nodes_strain_dict[x])): f1 = open(BIC_file, 'w') key_list = sorted(previous_strain_dict.keys(), key=lambda...
def filteritem(user_id): # -> array of array of any # mengembalikan data consumable milik user yang pernah diambil # KAMUS LOKAL # datas_all, inventory : array of array of any # item_id, stok, item_numambil, item_name, item_rarity : string # ALGORITMA datas_all = readCSV("consumable_history.csv")[1] inventory...
This function implements a gacha system where users can obtain consumable items pseudo-randomly based on their inventory. It increases chances by consuming inventory items, selects items by rarity tier, checks consumable stock, updates databases, and logs history. Admins are restricted, and empty inventories prevent pa...
def gacha(role, user_id): # memberikan barang tertentu ke user secara pseudo-random. # chance dapat ditingkatkan dengan menambahkan barang dari inventory # KAMUS LOKAL # rarity: array[1..3] of array[1..2] of any # inventory: array of array of any # prompt, rarity_result: character # result, bekal: array[1..2] ...
def acceleration_control(self, target_speed, current_speed): return self.Kp * (target_speed - current_speed) def search_target_index(self, state, waypoints): # Unpack state x = state.x y = state.y linear_velocity = state.linear_velocity yaw = state.yaw # Get look...
This function calculates vehicle acceleration and steering commands for path following. It uses SLAM data (position, velocity, orientation) and planner points to determine forward acceleration via a control law, find a look-ahead target point, and compute steering angle based on current state and target coordinates. Th...
def control(self, slam_data, planner_data): x = slam_data.state.x y = slam_data.state.y linear_velocity = slam_data.state.linear_velocity yaw = slam_data.state.yaw # Control law for forward acceleration acceleration = self.acceleration_control(self.target_speed, linear_v...
def _computeObs(self): pos = self._getCurrentState() offsetToClosestObstacle, _ = self._computeOffsetToClosestObstacle() closestObstaclePos = offsetToClosestObstacle + pos observation = np.concatenate([pos[:2], self.targetPos[:2], closestObstaclePos[:2]]) return observation def ...
The code processes an action to compute a velocity vector, applies it as a linear motion command to a drone, and returns observations, reward, termination status, and additional info for a reinforcement learning environment.
def step(self, action): vel = (action[:2] / np.linalg.norm(action[:2])) * np.abs(action[2]) * MocapAviary.MAX_SPEED self.motionCommander.start_linear_motion(vel[0], vel[1], 0, 0) return self._computeObs(), self._computeReward(), self._computeDone(), self._computeInfo()
def CreateMenu(self): menu_bar = tk.Menu(self.game_window) file_dd = tk.Menu(menu_bar, tearoff=0) file_dd.add_command(label='New Game', command=self.donothing) help_dd = tk.Menu(menu_bar,tearoff=0) menu_bar.add_cascade(label='File', menu=file_dd) menu_bar.add_cascade(labe...
The code initializes a game window and sets up its UI components by creating a menu, header, and minefield. It configures the game window, prepares the interface elements, and initializes the minefield for gameplay.
def __init__(self, game_window): self.game_window = game_window # self.game_window.geometry("400x400") self.CreateMenu() self.CreateHeader() self.CreateMinefield() ...
def DisplayLocatePhidgetsLink(): print("\n | In the following example, you will be asked to provide information that specifies which Phidget the program will use. " "\n | If you are unsure of any of these parameters, be sure to check www.phidgets.com/docs/Finding_The_Addressing_Information " "...
The main task of the code is to collect device parameters from the user through a series of input functions, including serial number, VINT properties, channel selection, and network setup, and return a configured `ChannelInfo` object for Phidgets device interaction.
def AskForDeviceParameters(ph): channelInfo = ChannelInfo() DisplayLocatePhidgetsLink() InputSerialNumber(channelInfo) InputVINTProperties(channelInfo, ph) InputChannel(channelInfo) SetupNetwork(channelInfo) return channelInfo
def find_holes(flow): ''' Find a mask of holes in a given flow matrix Determine it is a hole if a vector length is too long: >10^9, of it contains NAN, of INF :param flow: an dense optical flow matrix of shape [h,w,2], containing a vector [ux,uy] for each pixel :return: a mask annotated 0=hole, 1=no...
The main task of the code is to interpolate an intermediate frame at time $ t $ between two input frames (frame0 and frame1) using optical flow estimation, hole filling, occlusion mask generation, and inverse warping. It handles flow computation, fills gaps in the flow, blurs occlusion masks, and warps frames to genera...
def internp(frame0, frame1, t=0.5, flow0=None): ''' :param frame0: beggining frame :param frame1: ending frame :return frame_t: an interpolated frame at time t ''' print('==============================') print('===== interpolate an intermediate frame at t=',str(t)) print('===============...
def find_holes(flow): ''' Find a mask of holes in a given flow matrix Determine it is a hole if a vector length is too long: >10^9, of it contains NAN, of INF :param flow: an dense optical flow matrix of shape [h,w,2], containing a vector [ux,uy] for each pixel :return: a mask annotated 0=hole, 1=no...
The function `internp` interpolates a frame at time `t` between two input frames (`frame0` and `frame1`) using optical flow and occlusion handling. It calculates the optical flow, fills holes, estimates occlusion masks, blurs them, and warps the frames to generate the interpolated frame (`frame_t`). Key steps include f...
def internp(frame0, frame1, t=0.5, flow0=None): ''' :param frame0: beggining frame :param frame1: ending frame :return frame_t: an interpolated frame at time t ''' print('==============================') print('===== interpolate an intermediate frame at t=', str(t)) print('==============...
def extractformoptions(self): ''' extract form options and make constrains ''' if self.setoption('randomsport'): self.setoption('sport',random.randint(40000,65535)) elif not (1<= self.setoption('sport') <= 65535): return False,f'sport must be between 1 an...
The code's main task is to send crafted TCP packets with customizable options (e.g., fake TTL, corrupt flags) to a target IP, establishing a connection, generating segmented/payload-modified packets, and transmitting them with configurable delays and shuffling, while capturing and processing responses.
def sendpackets(self): ''' extract form options and send packets ''' res,errmsg=self.extractformoptions() if not res: return res,errmsg #define vars ipaddress=self.getoption('ipaddress') sport=self.getoption('sport') dport=self.getopti...
def getKnownNumbers(signal, numberDictionary): for j in signal: if len(j) == 2: numberDictionary["one"] = j elif len(j) == 3: numberDictionary["seven"] = j elif len(j) == 4: numberDictionary["four"] = j elif len(j) == 7: numberDictionar...
The main task of the code is to decode output numbers from input signal patterns by identifying segment mappings for digits (0-9), then converting output values to their corresponding numeric digits and summing them. It processes each input line, determines segment configurations, maps outputs to digits, and accumulate...
def PartTwo(inputs): """ User the input part to select the numbers. Should be able to follow a set logic to get the results. Want to get each line segment. Should be able to get each segment eventually. """ numberDictionary = {} segmentDictionary = {} grandTotal = 0 for i in inp...
def handle_streams( self, data ): channel_count = len( data ) if ( channel_count < 1 ): return self.create_stream( data ) def log_event(self, values): self.logfile.write( str(values) + '\n' ) def push_event(self,data,event_time): string_values = [] for inde...
The code processes an event by parsing JSON data, checking for changes in channel count to trigger stream handling, logging event values, and pushing the event data along with the event time. It handles JSON decoding errors and skips processing if no data is present.
def process_event(self, event,event_time): try: item = json.loads(event) data = item.get('data') if not data: return current_channel_count = len( data ) if ( self.previous_channel_count != current_channel_count ): self...
def process_event(self, event,event_time): try: item = json.loads(event) data = item.get('data') if not data: return current_channel_count = len( data ) if ( self.previous_channel_count != current_channel_count ): self...
The code continuously receives data from a client connection, checks for valid event markers ('live_event' and '$$$'), splits the data into individual events, and processes each valid event with a timestamp. It handles exceptions like keyboard interrupts and socket timeouts, closing the connection when interrupted.
def receive_data(self): while True: event_time = local_clock() try: received_data = self.client_connection.recv(4096).decode('utf-8') if 'live_event' not in received_data or '$$$' not in received_data: continue event...
def setup_socket(self): self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: self.server_socket.bind((self.host, self.port)) except socket.error as msg: print('Bind failed. Error code: ' + str(msg[0]) + ' Message ' + msg[1]) sys.exit() ...
The main task of the code is to initialize and run a network server by setting up a socket, opening a log file, listening for incoming connections, and receiving data. The `start` method orchestrates these steps to establish a server that can communicate over a network, log relevant information, and process received da...
def start(self): self.setup_socket() self.open_log_file() self.listen() self.receive_data()
def randomizeKettles(self): if not self.settings['kettles']: return time.sleep(1) self.status_update.emit('Randomizing kettles...') # restrict After Alterna to vanilla for now to avoid confusion self.levels['Msn_ExStage'] = 'Msn_ExStage' # C-1 needs...
The code's main task is to execute a sequence of operations: randomizing kettles, editing levels, and updating mission parameters. It handles exceptions by capturing errors and emitting an error signal, then always emits a completion signal regardless of success or failure.
def run(self): try: self.randomizeKettles() self.editLevels() self.updateMissionParameters() except Exception: er = traceback.format_exc() self.error.emit(er) finally: self.is_done.emit()
def make_fig_ax(): """Make polar figure and axes to plot on.""" fig, ax = plt.subplots(1, 1, figsize=set_size(fraction=0.5, aspect='equal'), subplot_kw=dict(projection='polar')) # Turn off radial grid ax.grid(False) # Remove radius marks ax....
The main task of the code is to generate and save two visualizations: one plotting arithmetic mean data and another plotting circular mean data. The `main()` function creates figure/axis objects, calls plotting functions to render the respective mean types, and saves the resulting graphs as image files named 'arith_mea...
def main(): """Plot and save desired graph.""" fig, ax = make_fig_ax() plot_arith_mean(fig, ax) savefig(fig, 'arith_mean', tight=None) fig, ax = make_fig_ax() plot_circ_mean(fig, ax) savefig(fig, 'circ_mean', tight=None)
def premiums_received(df, rounds, which_round): start_index = rounds[which_round] end_index = rounds[which_round +1] df_round = df.iloc[start_index:end_index] df_round2 = flips(df_round) premium_received = df_round2['totalCost'].sum() return premium_received def Options_at_Exp(df,...
The function `PNL_total` calculates and returns three key components of total profit/loss (PNL) for a specific trading round: premiums received, options' expiration value, and collateral PNL. It aggregates these values by calling specialized functions with input parameters like the dataframe, round identifier, and fina...
def PNL_total(df, round_starts, which_round, FINAL_SPOTS): prem = premiums_received(df, round_starts, which_round) opt_val = Options_at_Exp(df, round_starts, which_round, FINAL_SPOTS) collat_pnl = collateral_PNL(df, round_starts, which_round, FINAL_SPOTS) return prem, opt_val, collat_pnl
def date_to_week_day(date,month,year): ref_date = date_value(1,1,2006) input_date= date_value(date,month,year) diff= (input_date-ref_date) % 7 return diff def days_in_month(month , year=1990): if month==2: return 28+int(is_leap_year(year)) elif (month<8 and month%2!=0) or ...
The main task of the code is to print a calendar vertically, aligning dates under their corresponding weekday names. It calculates the starting weekday of the given month/year, determines the number of days in the month, and iterates through each weekday to print aligned dates in columns. The code adjusts date position...
def print_calendar_vertically(month, year): week_days = ["Sun","Mon", "Tue", "Wed", "Thu", "Fri", "Sat"] start_day_pos = date_to_week_day(1, month, year) days = days_in_month(month, year) for i in range(7): print(week_days[i], end='') print('\t', end = '') if(i < start_day...
def load_virus_model(model_path): model = load_model(model_path) return model def proc_fastq(infile, target_length): """ Parse a FASTQ file and extract reads. Rejects reads that: 1) Are an unexpected length 2) Contain > 1 N 3) Contain a character other than ACGTN :param infil...
The code extracts viral contigs from unmapped RNA-seq reads using a trained neural network model. It processes input FASTQ files, predicts viral sequences with a model, filters high-scoring reads (>0.46 threshold), and assembles contigs via a C function. Output is saved as a text file if not already present, avoiding r...
def extract_contigs(invars): ''' :param invars: input file, output file, read length, model path :return: ''' inpath = invars[0] outpath = invars[1] target_length = invars[2] model_path = invars[3] # output file name fn = outpath + inpath.split('/')[-1].replace('_unmapped', '_...
def randomObjects(numberOfObjects, minWeight, maxWeight, containersCapacity): objects = set(range(numberOfObjects)) weights = dict() totalWeight = 0 if containersCapacity < maxWeight: print("\nERROR") return "Change maxWeight or kilogramsCarriedByEachContainers" ...
The function `testOneSize` evaluates grouping algorithms (exhaustive or greedy) by generating random objects and testing how they are grouped into containers. The container capacity is set to the square root of the number of objects, and the chosen algorithm processes the random instance accordingly.
def testOneSize(numberOfObjects, algoType): containersCapacity = math.sqrt(numberOfObjects) randomInstance = randomObjects(numberOfObjects, 0, 1, containersCapacity) if algoType == 'E': exhaustiveAlgoGrouping(randomInstance, containersCapacity) else: g...
def charsQuantities(patternLength): # Input: # - patternLength : a number (integer) that represents the pattern length # Output: # - quantitiesList : a particular list of lists used to create combinations with # repeats (later), given a length called 'patternLength' # E...
This function generates all possible strings of a specified length using characters from a given alphabet, considering both combinations with repetition and their permutations. It returns a set of unique strings, ensuring every possible arrangement of characters is included.
def allPossiblePatterns(alphabet, patternLength): # Input: # - alphabet : a list of characters from which all the patterns are drawn up # - patternLength : a number (integer) that represents the pattern length # Output: # - allPossiblePatternsSet : a set of strings in which are present all possible ...
def load_waveform(self,fname): self.pd_new=loadPatientData(fname) def makeMonitorFigure(plot_mapping): plt.close('all') text_top={'wave_ecg':'ECG bpm', 'wave_pleth':r'SpO$_2$%', 'wave_nibp':'BP mmHg', 'wave_etco2':r'ETCO$_2$ kPa' } text_middle={'wave_ecg':'-', 'wave_pleth':'-', 'wave_nibp':'---/---'...
This code initializes a class to load physiological waveform data from a file, set up a plotting figure with predefined signal mappings, and prepare for real-time monitoring by copying processed data and initializing waveform plots.
def __init__(self,fname='pd_1.json',fps=30,numFrames=None): self.fps=fps self.numFrames=numFrames self.load_waveform(fname) self.pd=self.pd_new.copy() self.fname=fname self.plot_mapping={'wave_ecg':0, 'wave_pleth':1, 'wave_nibp':2, 'wave_etco2':3} self.fig,self.li...
def checkPatientStatus(): vitals_state = -1 try: response = http.request('GET', 'http://128.61.187.166:8080/var', timeout=2.0, retries=False) vitals_state = int(json.loads(response.data.decode('utf-8'))['vitals-state']) except (urllib3.exceptions.NewConnectionError, urllib3.exceptions.Conne...
This function updates waveform data and display when a new patient status is detected. If tc=0, it checks patient status, reloads waveforms if changed, synchronizes vital sign data between new/old structures, and updates text displays for ECG, PLETH, NIBP, and ETCO2. It then iterates through plot mappings to refresh al...
def updateWaveForms(self,tc): if tc==0: fname=checkPatientStatus() if self.fname!=fname: self.load_waveform(fname) self.fname=fname for cKey in ['vs_hr','vs_spo2','vs_sbp','vs_dbp','vs_etco2','vs_rr']: self.pd[cKey]=self...
def get_ami_by_uuid(self, uuid, region): if not self.session: self.connect(MAIN_ACCOUNT) ec2 = self.session.resource('ec2', region_name=region) self.logger.debug('Looking for image in region {} with uuid: {}'.format(region, uuid)) return list(ec2.images.filter( Ow...
This code promotes an AMI by updating its 'Approved_for' tag with the specified environment, ensuring the AMI is clean or using force. It checks if the tag exists, appends the environment value (or creates the tag if absent), and updates the tags. If the AMI is "dirty," it logs an error, advising the use of the -f flag...
def promote(self, arguments): uuid = arguments.uuid environment = arguments.environment ami = self.get_ami_by_uuid(uuid, MAIN_REGION) # Get tags from original AMI tags = ami.tags if arguments.force or self.ami_is_clean(tags): # get tag position pos...
def get_ami_by_uuid(self, uuid, region): if not self.session: self.connect(MAIN_ACCOUNT) ec2 = self.session.resource('ec2', region_name=region) self.logger.debug('Looking for image in region {} with uuid: {}'.format(region, uuid)) return list(ec2.images.filter( Ow...
This code removes a specified environment from the 'Approved_for' tag of an AMI. It retrieves the AMI by UUID, checks if the tag exists, updates its value by removing the environment, and reapplies the modified tags. If the tag is absent, it creates a new empty 'Approved_for' tag. The operation ensures proper formattin...
def demote(self, arguments): uuid = arguments.uuid environment = arguments.environment ami = self.get_ami_by_uuid(uuid, MAIN_REGION) # Get tags from original AMI tags = ami.tags # get tag position pos = self.get_tag_pos(tags, 'Approved_for') # if tag exist...
def initPlot(self): plt.ion() plt.show() def random_sample(self): random_x = random.uniform(self.min_x, self.max_x) # float random range random_y = random.uniform(self.min_y, self.max_y) # float random range return Node((random_x,random_y)) def extend(self, random_node, nodes, go...
This code implements a bidirectional RRT (Rapidly-exploring Random Tree) algorithm to find a path between a start and goal point. It alternates between expanding forward and backward trees, using random sampling with goal biasing to prioritize connections between trees. When both trees have nodes, it attempts to connec...
def plan(self): self.initPlot() # 1) Add start/initial node to node set. self.nodes_fwd.append(self.start) self.nodes_back.append(self.goal) # last_fwd_node = None last_backward_node = None # 2) Iterate... for i in rang...
def generateRevealedBoxesData(val): revealedBoxes=[]; for i in range(BOARDWIDTH): revealedBoxes.append([val] * BOARDHEIGHT); return revealedBoxes; def splitIntoGroupsOf(groupSize, theList): result=[]; for i in range(0, len(theList), groupSize): result.append(theList[i:i + groupSize])...
The function `startGameAnimation` initializes a game animation by generating a shuffled list of all box coordinates on the board, splitting them into groups of 8, and sequentially revealing then covering each group. This creates a dynamic visual effect as boxes are animated to appear and disappear, preparing the board ...
def startGameAnimation(board): coveredBoxes=generateRevealedBoxesData(False); boxes=[]; for x in range(BOARDWIDTH): for y in range(BOARDHEIGHT): boxes.append((x,y)); random.shuffle(boxes); boxGroups=splitIntoGroupsOf(8, boxes); drawBoard(board, coveredBoxes); for box...
def clear_routes_from_entries_exists_data(self, use_multiprocessing=False): """ Method goes through each route and looking for enters and exits from the rectangle area and remove it. :param use_multiprocessing: True / False """ paths = [os.path.join(self.split_js_path, fname) for...
This method updates existing split JSON files with new parameter values and regenerates results without re-splitting the input JSON. It writes a header to the result file, clears outdated route data if processing 'entries and exits' data, updates routes with new information, computes results, and marks the document as ...
def update_jsons_and_get_results(self, use_multiprocessing=False): """Method is used when we need to update all split json files without splitting input json again. Eg. User get the results for a given input json and some set of parameters. Then he/she wants to set new values of parameters and g...
def get_annotations_files_for_part(emo_dim, filename, part): folder = get_annotations_folder(emo_dim) annot_filenames = [] for file in os.listdir(folder): if fnmatch.fnmatch(file, get_partname(filename, part)+'_*.csv'): annot_filenames.append(file) return np.array(annot_filenames) de...
This function aggregates annotations from multiple files for a specified part of an audio file, applies a low-pass filter if required, and combines them into a single array. It retrieves annotation files, reads their data, processes timestamps, and stacks the annotations horizontally. The result is a consolidated array...
def read_all_labels_for_part(filename, part, emo_dim, num_annotations): annot_filenames = get_annotations_files_for_part(emo_dim, filename, part) annot_folder = get_annotations_folder(emo_dim) start_time, end_time = get_start_end_time(filename, part) part_annotations = None for file in annot_filena...
def read_all_labels_for_part(filename, part, emo_dim, num_annotations): annot_filenames = get_annotations_files_for_part(emo_dim, filename, part) annot_folder = get_annotations_folder(emo_dim) start_time, end_time = get_start_end_time(filename, part) part_annotations = None for file in annot_filena...
The function processes and aggregates arousal and valence labels for a specified dataset partition. It reads raw labels, computes their mean and standard deviation, structures the results, and returns all labels, their statistics, and timestamps. The task supports data analysis by summarizing emotional annotations (aro...
def get_part_labels(file, part): print("*"*75, " For AROUSAL ", "*"*75) part_aro_all, time = read_all_labels_for_part(file, part, Labels.arousal.value, default_num_annot) part_aro_mean, part_aro_std = read_mean_std_labels_for_part(part_aro_all) print("*"*75, " For VALENCE ", "*"*75) part_val_all, ti...
def get_files_for_partition(partition="Train"): files = np.loadtxt(partitions_file, delimiter=";", dtype='str') return files[files[:,1] == partition][:,0] def get_parts_for_file(filename): parts = np.loadtxt(parts_info_loc, delimiter=";", dtype='str') file_parts = parts[np.where(np.char.find(parts[:,0],...
The main task of the code is to read and concatenate audio data and corresponding labels (all, mean, std) from the MSP-Conversation dataset for a given partition. It processes each file/part, aligns durations, aggregates data arrays, and returns them as PyTorch tensors for machine learning tasks.
def read_mspconv(partition): files = get_files_for_partition(partition) # Init data holders audio_data = None all_lbl_data = None mean_lbl_data = None std_lbl_data = None time_data = None for file in files: # ["MSP-Conversation_0079"] parts = get_parts_for_file(file) for ...
def preprocessing_df(df, impute_zeros=False, pre_imputation='MixType', test_mode=False, result_path=None, date_time=None): """ Prepare df to use as data for XGBoost imputation. This will be done by checking each column, replacing 'object' data by numbers using label encoder, replacing a...
The code imputes missing values in a DataFrame using XGBoost, combining preprocessing, matrix factorization (cNMF/SVD), and iterative refinement. It handles data encoding, applies transformation methods based on data properties, trains XGBoost models, iteratively improves imputation, and saves results/visualizations if...
def fit(self, df): """ Impute using XGBoost Args: df: The df we get after using pre_df function Returns: Imputed df """ if not isinstance(df, pd.DataFrame): raise ValueError("Input must be a pandas DataFrame") result_path = N...
def generate_pow_assembly(n): fortran_src = F90_TEMPLATE.format(n=n) src_filename = "pow{n}.f90".format(n=n) obj_filename = "pow{n}.o".format(n=n) with tempfile.TemporaryDirectory() as dirname: src_path = os.path.join(dirname, src_filename) with open(src_path, "w") as file_obj: ...
The code tracks register usage during exponentiation assembly instructions, handling MOVAPD and MULSD operations, and verifies the final register state to analyze computation steps for exponentiation.
def track_exponentiation(n): instructions = generate_pow_assembly(n) input_register = get_input_register(instructions[0]) register_history = [({input_register: VAR_NAME}, instructions[0])] for instruction in instructions[1:-2]: if instruction.name == MOVAPD: handle_movapd(register_h...
def part1(): n, s, X = sympy.symbols("n, s, X") f = 1 + n * (n - 1) / 2 + n * (n - 1) * (n - 2) * (n - 3) / 24 g = 24 * f - 1 / X**4 gs = (g.subs({n: s / X}) * X**4).expand() print("g(s) =", gs) g2 = gs.diff(s, 2) g2 = (g2 - 19 * X**2).factor() + 19 * X**2 print("g''(s) =", g2) print...
The main task of the code is to configure a Python environment for LaTeX-rendered matplotlib plots by setting environment variables, enabling LaTeX text rendering with specific fonts, applying a seaborn theme, and executing multiple plot-generating functions (part1 to part8) to produce visualizations.
def main(): # $ brew install texlive # $ brew install --cask tex-live-utility # $ sudo tlmgr install cm-super os.environ["SOURCE_DATE_EPOCH"] = "0" matplotlib.rcParams["text.usetex"] = True matplotlib.rcParams["mathtext.rm"] = "serif" matplotlib.rcParams["mathtext.fontset"] = "cm" seabor...
def optimizeNN(maxIter, input_layer_size, hidden_layer_size, hidden_layer_count, num_labels, X, y, lambda_, initThetas): print(f"optimizing network") options = {'maxiter': maxIter} costFunction = lambda p: nnCostFunction(p, input_layer_size, ...
The code optimizes a neural network's hidden layer size, count, and regularization parameter (λ) to maximize validation accuracy. It iteratively trains models with varying configurations, evaluates performance, and retains the best parameters. Early stopping occurs if improvements fall below a threshold or accuracy dro...
def findGoodValues(input_layer_size, num_labels, XTrain, yTrain, XVal, yVal): maxiter = 100 bestTheta = [] bestSize = 0 bestCount = 0 bestPrediction = 0 print("estimated time: Very long") startTime = time.time() for hidden_layer_size in range(100, 2100, 100): for hidden_layer_co...
def next_state(row, col, p_id, var_id, padded_board, player_id, player_hands, n_players, position_square, count_pos_squares, position_attach, count_pos_attach, position_forbid, count_pos_forbid): """ :param row: [5 - 24] row of the piece origin in the playing board :param col: ...
The code simulates a game step based on an action, updating the game state by decoding the action, processing moves for all players' perspectives, handling invalid moves, updating valid action masks, and returning the next observation, reward, termination status, and additional info. It manages piece placement, rotatio...
def step(self, action): # computes a simulation step, given an action and returns observation and info, behaviour depends on action_mode if not self.dead[self.active_pl]: # decodes action if self.action_mode == 'discrete_masked': # action, must be a boolean vecto...
def get_class_and_count(dataset): ''' Get count of each class :param dataset: training samples :return dict_classes: dictionary of classes ''' dict_classes={} for i in range(len(dataset)): if(dataset[i][2] in dict_classes): count=dict_classes[dataset[i][2]] ...
The code builds a decision tree recursively by splitting the dataset based on the best attribute-value pair. If all samples in a subset belong to the same class, it creates a leaf node and records its depth. Otherwise, it recursively constructs left and right subtrees, updating leaf nodes' depth values. The function re...
def build_DT(dataset,list_leaves,count): ''' Builds the decision tree :param dataset: list of samples :param list_leaves: list of leaves :param count: depth value :return best_split_node, list_leaves: node of tree and list of leaf nodes with depth value ''' same_class=False class_va...
def read_csv(filename): ''' Reads csv file :param filename: Name of file :return dataset: list of data ''' with open(filename) as csvDataFile: csvReader = csv.reader(csvDataFile) dataset=[] for row in csvReader: dataset.append([float(row[0]),float(row[1]),int(...
The code builds a decision tree from a dataset, calculates tree metrics (depth, nodes, etc.) before pruning, applies Chi-Square pruning to reduce tree complexity, recalculates metrics post-pruning, and visualizes decision boundaries both before and after pruning. It outputs tree structures and metrics to CSV files for ...
def main(): ''' Main program to call the functions to build decision tree ''' file_name=input("enter filename :") dataset=read_csv(file_name) f = open('DecisionTree_withoutPruning.csv', 'w') print("------------------------BEFORE PRUNING---------------------------------") print() ...
def getStates(): df = pd.read_csv('data/04-13-2020.csv') states_list = df['Province_State'].values.tolist() return states_list def getConfirmedCases(path): df = pd.read_csv(path) return df[['Confirmed']] def getRowIndices(): rename_dict = {} # Create dictionary for renaming row indices f...
The code aggregates confirmed cases from multiple files into a pandas DataFrame. It initializes an empty DataFrame, iterates over input paths to append transposed case data, assigns state names as columns, renames rows using indices from `getRowIndices()`, and returns the structured DataFrame.
def getDataFrame(paths): frame = pd.DataFrame() states = getStates() for path in paths: cases = getConfirmedCases(path) frame = frame.append(cases.T, ignore_index=True) frame.columns = states frame.rename(index=getRowIndices(), inplace=True) return frame
def rebalance(self, current: AVLTreeNode) -> AVLTreeNode: """ Compute the balance of the current node. Do rebalancing of the sub-tree of this node if necessary. Rebalancing should be done either by: - one left rotate - one right rotate - a combination ...
This function inserts a key-value pair into an AVL tree, recursively handling insertion into left/right subtrees. After insertion, it updates node heights and subtree sizes, then rebalances the subtree via rotations if unbalanced. It returns the new root of the subtree, ensuring AVL balance is maintained. The method al...
def insert_aux(self, current: AVLTreeNode, key: K, item: I) -> AVLTreeNode: """ Attempts to insert an item into the tree, it uses the Key to insert it. After insertion, performs sub-tree rotation whenever it becomes unbalanced. returns the new root of the subtree....
def rebalance(self, current: AVLTreeNode) -> AVLTreeNode: """ Compute the balance of the current node. Do rebalancing of the sub-tree of this node if necessary. Rebalancing should be done either by: - one left rotate - one right rotate - a combination ...
This function deletes a node with the specified key from an AVL tree, recursively navigating to the target node, handling deletion cases (leaf, single child, or internal node), and rebalancing the tree via rotations to maintain AVL properties. It updates subtree heights, sizes, and ensures the root is rebalanced if nec...
def delete_aux(self, current: AVLTreeNode, key: K) -> AVLTreeNode: """ Attempts to delete an item from the tree, it uses the Key to determine the node to delete. After deletion, performs sub-tree rotation whenever it becomes unbalanced. returns the new root of the...
def create_repo(git_remote, username, password, repo): os.chdir(repo) os.system(f'git init') write(".gitignore", "**/*Cache*\n**/*cache*") # Format: https://username:password@myrepository.biz/file.git credential_url = f'{git_remote.split("//")[0]}//{username}:{password}@{git_remote.split("//")[1]}' ...
The main task of the code is to back up system configurations and data to a Git repository. It creates a repository, dumps dconf settings, captures APT packages, Flatpak apps, Snap packages, and application data, then pushes the backups to a remote Git server. The `step` variable tracks progress through the backup proc...
def backup(git_remote, username, password): global step step = 0 try: os.mkdir(repo_location) except: pass create_repo(git_remote, username, password, repo_location) step = 1 write_output('dconf-backup.txt', 'dconf dump /') get_apt_packages() write_output('flatpak.lis...
def forward_pass(X, parameters, activation, num_hidden): A = {} # To prevent broadcasting when a single input vector is given if X.ndim == 1: X = X[:, np.newaxis] H = {"h0":X} for l in range(1, num_hidden + 2): Wl = parameters["W" + str(l)] bl = parameters["b" + str(l)] ...
This function evaluates a neural network's performance on training and validation datasets by computing accuracy, error rates, and loss. It performs forward passes using given parameters, calculates accuracy (and error) for predictions, applies cross-entropy or squared loss based on input, and returns training/validati...
def measure_performance(X, Y, X_val, Y_val, params, activation_func, num_hidden, loss): Yhat, _, _ = forward_pass(X, params, activation_func, num_hidden) train_acc = find_accuracy(Yhat, Y) train_err = 100 - train_acc if loss == "ce": train_loss = (cross_entropy_loss(Yhat,Y)) elif loss == "sq...
def initialize_weights(sizes): parameters={} for i in range(len(sizes)-1): parameters["W" + str(i+1)]=glorot_initialization(sizes[i],sizes[i+1]) parameters["b" + str(i+1)]=np.zeros((sizes[i+1],1)) return parameters def creategrads(sizes): #this function initializes the gradient's matrix as z...
This function trains a neural network using batch gradient descent. It initializes weights, performs forward and backward passes for each data point, accumulates gradients over a batch, updates parameters using the learning rate, and tracks training error per batch and epoch. The process repeats for specified epochs, r...
def training_nn(train_data,train_label,sizes,batch_size,learning_rate,epoch_size,acti): epoch=0 updatepoint=0 batch_data = {} epoch_data = [] while(epoch<epoch_size): parameters=initialize_weights(sizes) gradient_matrix=creategrads(sizes) step=0 for j in range(0,1000...
def createnetwork(num_hidden, activation_func, sizes, inputsize = 784, outputsize = 10): sizes = [inputsize] + sizes sizes = sizes + [outputsize] np.random.seed(1234) parameters = {} if activation_func == "relu": for i in range(1, num_hidden+2): parameters["W" + str(i)] = 0.01*np...
The function implements Adam optimization for training a neural network on given data. It initializes parameters, computes gradients via forward/backward passes, updates weights using Adam's momentum and RMSProp-like terms with bias correction, and includes learning rate annealing. It tracks training/validation loss/er...
def adam(X, Y, X_val, Y_val, activation_func, loss_func, eta, num_epochs, num_hidden, sizes, batch_size, path_save_dir, inputsize = 784, outputsize = 10, beta1 = 0.9, beta2 = 0.999, eps = 1e-8, anneal = True, pretrain = False, state = 0): print("Adam") # data for information display and plots step_data = ...
def createnetwork(num_hidden, activation_func, sizes, inputsize = 784, outputsize = 10): sizes = [inputsize] + sizes sizes = sizes + [outputsize] np.random.seed(1234) parameters = {} if activation_func == "relu": for i in range(1, num_hidden+2): parameters["W" + str(i)] = 0.01*np...
This code implements momentum gradient descent for training a neural network. It initializes parameters (either from scratch or pretrained), performs mini-batch updates with momentum, tracks training/validation performance, adjusts learning rate via annealing, and saves model parameters. The function returns trained pa...
def mgd(X, Y, X_val, Y_val, activation_func, loss_func, eta, gamma, num_epochs, num_hidden, sizes, batch_size, path_save_dir, inputsize = 784, outputsize = 10, anneal = True, pretrain = False, state = 0): print("momentum gradient descent") # data for information display and plots step_data = {} epoch_...
def createnetwork(num_hidden, activation_func, sizes, inputsize = 784, outputsize = 10): sizes = [inputsize] + sizes sizes = sizes + [outputsize] np.random.seed(1234) parameters = {} if activation_func == "relu": for i in range(1, num_hidden+2): parameters["W" + str(i)] = 0.01*np...
The code implements mini-batch stochastic gradient descent (SGD) for training a neural network. It initializes parameters (either from scratch or pre-trained), processes data in batches, performs forward/backward passes, accumulates gradients, updates weights using learning rate `eta`, and evaluates training/validation...
def sgd(X, Y, X_val, Y_val, activation_func, loss_func, eta, num_epochs, num_hidden, sizes, batch_size, path_save_dir, inputsize = 784, outputsize = 10, anneal = True, pretrain = False, state = 0): print("minibatch") step_data = {} epoch_data = [] if pretrain == False: params = createnetwo...
def createnetwork(num_hidden, activation_func, sizes, inputsize = 784, outputsize = 10): sizes = [inputsize] + sizes sizes = sizes + [outputsize] np.random.seed(1234) parameters = {} if activation_func == "relu": for i in range(1, num_hidden+2): parameters["W" + str(i)] = 0.01*np...
The function `nag` trains a neural network using Nesterov Accelerated Gradient (NAG) optimization. It processes training data in batches, computes gradients via forward and backward passes, updates parameters with momentum (gamma) and learning rate (eta), and adjusts the learning rate via annealing if validation loss s...
def nag(X, Y, X_val, Y_val, activation_func, loss_func, eta, gamma, num_epochs, num_hidden, sizes, batch_size, path_save_dir, inputsize = 784, outputsize = 10, anneal = True, pretrain = False, state = 0): print("NAG") # data for information display and plots step_data = {} epoch_data = [] # initi...
def concat_surface_nodes(self, nodes: list[Surface]) -> Surface: """ Gets a list of surface nodes and returns a single surface node with their concatenation. """ rule = nodes[0] for n in nodes[1:]: rule = ConcatSurface(rule, n) return rule def wrap_con...
This function randomly modifies token constraints by iteratively applying actions like 'or', 'not', or 'and' to create new constraint combinations. It uses weighted choices to select operations, generates patterns from the corpus, and replaces constraints with OrConstraint or NotConstraint variants while preserving the...
def add_random_constraints(self, constraints: list[Constraint]) -> List[Constraint]: """ Gets a list of token constraints and a number of modifications to perform. Returns a new list of token constraints with the same length as the original. """ while True: cs = copy....