dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def confirm_sent(self, bytes, packet): return bytes == len(packet) def receive_packet(self): # Receive a packet and extract its fields, then return them type, seq, address, data = deconstruct_packet(self.sock.recvfrom(CHUNK)).values() return type, seq, address, data def close_connection(...
This function sends a file size information packet containing the number of packets to transmit, increments the sequence number, and waits for an acknowledgment. If confirmed, it marks the file info as sent; otherwise, it closes the connection with an error after retrying up to 10 times.
def send_packet_count(self): seq = self.outgoing_seq # Increment the outgoing sequence number to use for the file size info packet self.increment_seq() # Pack the number of packets to send into a file size info packet packet_count = len(self.packets_to_send) file_size_inf...
def cubic_algo(self, T): """ Implementation of the Cubic Congestion Control algorithm. :param T: Time elapsed since last window reduction :return: New congestion window size """ # Calculate the scaling factor K based on the current window size and elapsed time since the l...
This function implements congestion control for data transmission, dynamically adjusting the congestion window (cwnd) using slow start and cubic algorithms. It sends packets in batches based on cwnd, handles acknowledgments to update the window, and manages transitions between congestion avoidance states. The goal is e...
def send_data(self): all_packets_sent = False while self.packets_to_send and not all_packets_sent: # CC algo: # slow start if not self.congestion_avoidance: if self.cwnd >= self.slow_start_threshold: self.congestion_avoidance = True...
def ParentMass(spectrum): return (sorted(spectrum, reverse=True)[0]) def Expand(Board): #Here L means I/L, K means K/Q #aminoAcids = ['G', 'A', 'S', 'L', 'P', 'K'] #aminoAcids = ['G', 'A', 'S', 'P', 'L', 'K', 'V', 'T'] aminoAcids = ['G', 'A', 'S', 'P', 'V', 'T', 'C', 'L', 'N', 'D', 'K', 'E'...
The main task of the code is to identify the highest-scoring cyclic peptide sequence from a given spectrum using a leaderboard-based approach. It iteratively expands potential peptides, trims the leaderboard to retain top candidates, and tracks the best peptide (LeaderPeptide) and its score. The algorithm compares each...
def LeaderBoardCycloPeptideSequencing(Spectrum, N): leaderboard = set('empty_peptide') LeaderPeptide = '' mostFreq = [] parentMass = ParentMass(Spectrum) while len(leaderboard) != 0: leaderboard = Expand(leaderboard) leaderboard_copy = list(leaderboard) for elemen...
def listen(): try: with sr.Microphone() as source: listener.adjust_for_ambient_noise(source, duration=0.5) print("listening") voice = listener.listen(source) # show_all : for full response command = listener.recognize_google(voice) except sr.Re...
The main task of the code is to process voice commands by checking if keywords from the list 'whats' are present in the input. If a match is found, it sends the command via `msgTo()`; otherwise, it queries the command. The commented section suggests handling specific commands like "take a selfie" or "draw" with tailore...
def processCommand(): command = listen().lower() print(command) for i in whats: if i in command: msgTo(command) return else: query(command) return '''if ("take a selfie") in command: hand.selfie() elif ("draw") in command: for i in...
def find(self, fuzzyTerm): print("Trying to find package for: " + fuzzyTerm) searchTermHierarchy = createSearchHierarchy(fuzzyTerm) #scoreBoards = [] fullScoreBoard = [] for pkgManager in self.packageManagers: scoreBoard = createPkgScoreBoard(searchTermHi...
The main task of the code is to search for packages using a fuzzy term, display the top 8 results to the user for selection, and install the chosen package if confirmed. If no selection is made, it returns False.
def findinstall(self,fuzzyTerm): fullScoreBoard = self.find(fuzzyTerm) maxShowCnt = 8 packageToInstall = self.promptInstall(fullScoreBoard, maxShowCnt) if(packageToInstall is not None): #return self.installPkgDef({"name":packageToInstall[1],"mgr":packageToInstall[2]}) ...
def create_options_list(self, argv: List) -> List: string = ' '.join(argv) pattern = r'-[efn]' match_obj = re.findall(pattern, string) print("create_options_list: ", match_obj) return match_obj def find_script_in_string(self, argv: List) -> str: suggestions = [i for i in ...
The code processes command-line arguments by creating an options list, extracting a script, determining a file path, splitting the script into parts, and executing it. The main task is to parse and run a script based on input arguments, handling file paths and command separation for execution.
def calculate(self): self.options = self.create_options_list(self.argv) self.script = self.find_script_in_string(self.argv) self.file_path = self.find_file_path(self.argv) self.separated_script = self.split_script(self.script) self.run_script(self.separated_script, self.file_path...
def round_it(x): x=(round(x, 2)*100//5*5)/100 return x def Exit_program(): global CE_ATM , PE_ATM , CE_OTM , PE_OTM , ORDER_IDS , qty , SL_LOT , MAIN_ORDER_PLACED , exit_triggered if MAIN_ORDER_PLACED : # Exit all ATM positions PlaceBuyOrder(CE_ATM,qty*SL_LOT,"MKT","EXIT") ...
This code processes real-time market ticks to execute trading strategies. It updates last price data, monitors BANKNIFTY_TOKEN conditions, calculates ATM/OTM options, places orders when thresholds are met, and checks stoploss/profit conditions. It also triggers exit at 13:56. The core tasks involve dynamic order manage...
def on_ticks(ws, ticks): # Callback to receive ticks. for tick in ticks: instrument=tick["instrument_token"] # For any other timeframe. Simply change ltt_min_1 variable defination. # e.g. # ltt_min_15=datetime.datetime(ltt.year, ltt.month, ltt.day, ltt.hour,ltt.minute//15...
def get_2d(a): """ Reshape a 1- or 2-d numpy-array to be 2-dimensional """ if len(a.shape) <= 1: a = a.reshape(-1, 1) return a def posinv(A): cholesky, info = slg.lapack.dpotrf(A) if info != 0: raise np.linalg.LinAlgError('Singular or non-pd Matrix.') inv, info = slg.lapa...
The function `civ` estimates the causal effect of regressor $ X $ on response $ Y $ using instrument $ I $ and conditioning set $ B $. It adjusts for confounding by subtracting prediction residuals from $ X $, $ Y $, and $ I $ when $ B $ is provided, then applies instrumental variables (IV) regression on residuals. If ...
def civ(X, Y, I, B=None, N=None, W=None, predict = lambda x,b: sm.OLS(x, b).fit().predict()): """ Compute the causal effect of X on Y using instrument I and conditioning set B. Inputs: - X: Regressor. numpy array [shape (n_obs,) OR (n_obs, dims_X)]...
def denoise_text(self,text): text = self.strip_html(text) text = self.remove_between_square_brackets(text) return text def replace_contractions(self,text): """Replace contractions in string of text.""" return contractions.fix(text) def get_tokenized_list(self,doc_text): t...
The function preprocesses text by denoising HTML content, replacing contractions, tokenizing the text, and normalizing tokens based on specified type and language, returning the processed word list.
def preprocess_text(self,text, normalization_type, text_type, language): pt = text if text_type == 'html': pt = self.denoise_text(text) pt = self.replace_contractions(pt) words = self.get_tokenized_list(pt) words = self.normalize(words, normalization_type, language) ...
def make_X11_color_map(): """ Convert hex code to nice name, if one exists """ from matplotlib.colors import cnames colormap = {cnames[k].lower(): k for k in cnames} return colormap def render_ui(self): window = Tk() s = Style(window) s.theme_use("...
The code initializes a GUI based on a TABLECrate, setting up components like a color map, rendering the interface, and enabling an "Open" menu option if an open_func is provided. It populates UI data from a given tab and configures menu states dynamically.
def __init__(self, tab=None, open_func=None): 'Create GUI based on a TABLECrate' self.open_func = open_func self.color_map = self.make_X11_color_map() self.render_ui() if tab is not None: self.populate_from_crate(tab) if open_func is not None: se...
def get_create_summoner_info(summoner_name: str, base_url=summoner_by_name_url, token=auth_token): response = requests.get(f'{base_url}{summoner_name}?{token}') if response.status_code == 200: summoner_info = response.json() summoner_stats = get_summoner_stats(summoner_info['id']) if sum...
The code processes a request to generate player suggestions based on a summoner's match history. It retrieves the summoner's data, fetches their match history, identifies eligible participants, and renders the results in a template. The function measures execution time for performance tracking and returns an HTTP respo...
def resp(request: HttpRequest, summoner_name: str, base_url=summoner_by_name_url, token=auth_token) -> HttpResponse: start = timer() player_return_dict = {} # Create Summoner that made request on site get_create_summoner_info(summoner_name) matches = get_summoner_match_history(summoner_n...
def addRow(table,cur,con,root,mainframe): #creates a form the user can utilize to add new info into the app try: newWindow = tk.Toplevel(root) columns = globals()["columns"] listColumns = columns[1:] #pulls all columns except for id listInfo = {} row = 2 for ...
The code creates a menu bar for a GUI application, adding File, Edit, and View menus with commands like "New Row," "Delete Rows," "New Column," and "Edit Row." It dynamically populates a "Sort By..." submenu with column names, linking each to a sorting function. The menu bar is configured to the main window, enabling u...
def menuBar(self): #adds a menubar to the mainFrame root = self.root menubar = tk.Menu(root) filemenu = tk.Menu(menubar, tearoff = 0) editmenu = tk.Menu(menubar, tearoff = 0) viewmenu = tk.Menu(menubar,tearoff= 0) sortmenu = tk.Menu(viewmenu,tearoff= 0) menubar.ad...
def evaluate_board(board, player, selectedStone = None, destination = None): score = 0 opponent = 'human' if player == 'computer' else 'computer' # Broj figura na tabli player_pieces = len(board['currentState'][f'{player}Stones']) opponent_pieces = len(board['currentState'][f'{opponent}Stones']) ...
This function implements the Minimax algorithm with alpha-beta pruning for a board game, evaluating optimal moves for a player ('computer' or 'human') by recursively exploring possible moves, considering both placing new stones and moving existing ones. It calculates scores based on board states, prioritizes maximizing...
def minimax2(board, depth, player, mills, alpha, beta, stone=None, destination=None): if game_over(board) or depth == 0: score = evaluate_board(board, player, stone, destination) return score, None if player == 'computer': best_value = float("-inf") best_move = None sto...
def minimax2(board, depth, player, mills, alpha, beta, stone=None, destination=None): if game_over(board) or depth == 0: score = evaluate_board(board, player, stone, destination) return score, None if player == 'computer': best_value = float("-inf") best_move = None sto...
The code determines the best move in a board game using the minimax algorithm with alpha-beta pruning, adjusting search depth based on the player's stone count and pending moves. It evaluates moves, executes the optimal one, updates the board, and falls back to random placement if no valid move is found.
def make_best_move(board, player, mills): # print("Player",player) depth = 2 if len(board['currentState'][f'{player}Stones']) == 3: depth -= 1 elif board['pending'][player] == 0: depth += 1 # elif board['level'] == 0: # depth = 3 else: depth = 2 print...
def is_board_full(board): """ Checks if the main board has any available moves @:param: The board against which moves are being checked :return: True if the board has no more moves, False otherwise """ for i in range(1, 10): if board[i] == blank: return False return True ...
The main task of the code is to run a round of tic-tac-toe, alternating between the player's and computer's moves. It checks for a win or tie after each move, updates the board, and announces the result. The loop continues until the board is full or a player/computer wins, ensuring proper game flow and outcome determin...
def run_round(board): """ Runs a round of tic tac toe """ while not is_board_full(board): print() player_position = player_move(board) insert_token_to_board(x, player_position, board) print_board(board) # check if player won, then break out of while loop i...
def get_text_input(): return input() def user_says_bye(user_input): return get_user_intent(user_input) == Goodbye def get_user_intent(user_input): intent_to_top_score = {} for intent, samples in training_samples.items(): max_score = get_max_similarity(samples, user_input) intent_to_top_s...
This code defines a chatbot that interacts with users by recognizing their intent and responding accordingly. It starts with a greeting, processes user input in a loop, executes specific functions for different intents (e.g., playing games, answering personal questions), and continues until the user says goodbye.
def run_bot(): print("Hi there!") user_input = get_text_input() while not user_says_bye(user_input): intent = get_user_intent(user_input) if intent == WhatName: print(get_name_response()) elif intent == WhatGame: print(get_game_response()) elif intent ...
def starting_message(): print("Get ready to play tic-tac-toe! The way this will work is simple.\n" "We will show you the board, and in order to put down an 'X', you will need to specify the position." "The top left position is 1 and so on, just like below") example_board = [blank] * 10 f...
The code defines a game loop that repeatedly generates a game board, displays it, runs a round of gameplay, and asks the player if they want to play again. It starts with an introductory message and ends with a thank-you message when the player quits. The loop continues until the player chooses to stop playing.
def play_game(): starting_message() play_again = True while play_again: board = generate_board() print_board(board) run_round(board) play_again = does_player_want_to_play_again() print("Thanks for playing!")
def prepare_cache_files(cache_folder, cache_prefix, ignore_cache): required_cache_suffix = ['.node-lengths.cache.pck', '.edge-lengths.cache.pck'] required_cache_names = ['node-lengths', 'edge-lengths'] graph_cache = check_required_cache_files(cache_folder, cache_prefix, required_cache_suffix, required_cach...
The function processes a GAF input file by preparing/cache files, loads graph data if cache is incomplete or forced, processes alignment, generates statistics/issue records, and caches results. If cache is complete and "ignore cache" is off, it exits early.
def run_process_gaf(args): logger.debug(f'Processing GAF input file {args.align}') logger.debug(f'Preparing cache files in folder {args.cache_folder}') cache_files, cache_incomplete, graph_cache = prepare_cache_files( args.cache_folder, args.cache_prefix, args.ignore_cache ) ...
def build_any_graph(graph_node_cache, graph_edge_cache, add_inverted_edges, omit_nodes, directed): if omit_nodes is not None and len(omit_nodes) == 1 and ',' in omit_nodes[0]: logger.debug("Found comma in 'omit_nodes' list; I assume the list of nodes is comma-separated, " "and not whit...
The function constructs a graph from cached node/edge data, traverses specified paths to extract sequence data, handles orientation variations for unoriented start nodes, and compiles results into FASTA and table buffers for output. It prioritizes valid paths, manages exceptions for missing routes, and stores sequence ...
def extract_path_sequences(cache_files, path_spec_iter, path_spec, seq_cache_file, undirected_graph, add_inverted_edges, omit_nodes, fix_path_dir, skip_steps): logger.debug("Building graph from cache...") if undirected_graph: graph = build_any_graph(cache_files['nodes-graph'], cache_files['edges-graph'...
def check_required_cache_files(cache_folder, cache_prefix, required_suffix, required_names): if not cache_folder.is_dir(): logger.error(f'Cache folder does not exist: {cache_folder}') err_msg = '' required_caches = dict() for suffix, name in zip(required_suffix, required_names): if nam...
The main task of the code is to extract sequences from graph-based cache files using specified path information, generate FASTA format output, and create a path table. It checks required cache files, processes path specifications, handles graph direction settings, and writes results to files. The function also ensures ...
def run_extract_seq(args): logger.debug("Checking if graph cache seems to be complete") # we need edge and sequence information required_suffixes = [ '.edges-graph.cache.pck', '.nodes-graph.cache.pck', '.sequences.cache' ] required_names = ['edges-graph', 'nodes-graph', 'seq...
def filteredListOfFiles(dirName, filter): fullFileList = getListOfFiles(dirName) resultingList = [] for file in fullFileList: if file.endswith(filter): resultingList.append(file) return resultingList def ReadConfigFile(filePath): print("Opening camera configuration file in:",file...
The code geolocates bounding boxes in video frames by converting pixel coordinates to geographic (latitude/longitude) coordinates using camera parameters. It processes JSON data from multiple videos, calculates 3D positions, and saves results as JSON and CSV files in the specified output folder.
def GeoLocaliseBoxes(): framesFolder, camParams, outputFolder = \ args.framesFolder, args.camParams, args.outputFolder print("Loading frames data") jsonFiles = filteredListOfFiles(framesFolder, ".json") videosList = {} for jsonFile in jsonFiles: videoName = os.path.splitext(os.pa...
def filteredListOfFiles(dirName, filter): fullFileList = getListOfFiles(dirName) resultingList = [] for file in fullFileList: if file.endswith(filter): resultingList.append(file) return resultingList def GetRasterCorners(ds): ext=GetExtent(ds) src_srs=osr.SpatialReference() ...
The main task of the code is to geolocate drone sensor data by matching GPS coordinates from JSON files with elevation data from GeoTIFF files. It processes frames, extracts relevant TIF files, calculates altitudes using GDAL, and exports enriched data into JSON and CSV formats for each video, including frame metadata,...
def GeoLocaliseDrone(): framesFolder, demFolder, outputFolder = \ args.framesFolder, args.demFolder, args.outputFolder print("Loading frames data") jsonFiles = filteredListOfFiles(framesFolder, ".json") videosList = {} for jsonFile in jsonFiles: videoName = os.path.splitext(os.pa...
def printArgs(sourceFolder, predictionFolder, outputFolder, weightsPath, imageSize, confidenceScore, modelPath): print("sourceFolder: ", sourceFolder) print("predictionFolder: ", predictionFolder) print("outputFolder: ", outputFolder) print("weightsPath: ", weightsPath) print("imageSize: ", str(imag...
This code consolidates video prediction data with subtitle and sensor information by processing source videos, aligning frame-level predictions with timestamps from subtitles, and exporting results to JSON/CSV files. It reads model outputs, matches frames to subtitle segments, extracts sensor data, and structures outpu...
def Consolidate(): print("Consolidating!") sourceFolder, predictionFolder, outputFolder, weightsPath, imageSize, confidenceScore, inferencePath = \ args.sourceFolder, args.predictionFolder, args.outputFolder, args.weightsPath, args.imageSize, args.confidenceScore, args.inferencePath printArgs(source...
def locate(means, delta): """ Output: no of calls to oracle AND two intervals i1, i2 i1: highest mean lies in this interval i2: second highest mean in this interval min i1 - max i2 >= 2|i1| """ i1 = (0, 1) i2 = (0, 1) delta = delta/8 total_calls = 0 num_calls_to_shrink = 0 while i1[0] - i2[1] < 2*(i1[...
The function `BestArm` identifies the arm with the highest mean from a list, ensuring a success probability of at least $1 - \delta$. It employs a two-phase strategy: first, the `locate` function narrows down candidate arms using a probabilistic guarantee, counting oracle calls. Then, `amplify_probs` refines the select...
def BestArm(means, delta): """ Input: means: list of means of arms Output: total number of calls to oracle index of arm with highest mean with probability >= 1-delta is printed """ delta = delta/2 calls_for_locate, i1, i2 = locate(means, delta) print("total calls made for locate=", "{:e}".format(calls_for_lo...
def extract_features(mshwks): ''' takes in a list of skeleton meshworks and extracts the features for each segmentinto a df Parameters ---------- skels : list of meshparty.meshwork.meshwork.Meshworks meshwork of the bodies to have their features extracted Returns -------...
This function processes multiple neuron skeletons by removing axon segments using machine learning models. It loads skeleton data, extracts features, applies two random forest classifiers to identify axon/dendrite segments, and masks the skeletons to retain only dendrite segments. The resulting skeletons are saved to a...
def remove_axons_multiple_bodies(mws_cf_source_path, skels_cf_destination_path, m1, m2, verbose = True): ''' Takes in a skeleton object, returns a skeleton object without the identified axons. Parameters ---------- mshwks : list of meshparty.skeleton.Skeleton objects skeleton objects ...
def fetch() -> pd.DataFrame: # if randint(0, 1) > 0: # raise Exception playlists_df, tracks_df = get_playlist_and_track_dfs() return playlists_df, tracks_df def clean(df = pd.DataFrame) -> pd.DataFrame: # clean up years without month and date by adding placeholder month/day df['release_date'...
The main task of the code is to perform an ETL process: extract data from the web, clean the tracks dataset, save both cleaned tracks and original playlists to local files, and then upload these files to Google Cloud Storage (GCS). The function handles data fetching, transformation, local storage, and cloud upload in a...
def etl_web_to_gcs(playlist_file, track_file) -> None: playlists_df, tracks_df = fetch() tracks_df_clean = clean(tracks_df) playlist_path = write_local(playlists_df, playlist_file) track_path = write_local(tracks_df_clean, track_file) write_gcs(playlist_path) write_gcs(track_path)
def find_paired_fastqs(input_directory): for dirpath, _, filenames in os.walk(input_directory, followlinks=True): filenames = [ fn for fn in filenames if fn[-6:].lower() == '.fastq' or fn[-9:].lower() == '.fastq.gz' ] yield from ( (dirpath, fnp...
The main task of the code is to iteratively refine a reference sequence by aligning paired FASTQ files, generating consensus sequences, and updating the reference until convergence. It processes input data through alignment, consensus building, and iterative refinement, saving intermediate results and final consensus s...
def main( input_directory, output_directory, program, reference, iterative, max_iterative_circles ): refinit = get_refinit(program) align = get_align(program) if not iterative: max_iterative_circles = 1 for dirpath, fnpair, pattern in find_paired_fastqs(input_directory): samf...
def Seq(f, s, *args): if isinstance(f, EmptyC) or isinstance(s, EmptyC): return EmptyC() if isinstance(f, EpsC): return Seq(s, args[0], *args[1:]) if len(args) else s if isinstance(s, EpsC): return Seq(f, args[0], *args[1:]) if len(args) else f if isinstance(f, StarC) and f == s:...
This code computes the derivative of a regular expression with respect to a character `c`, handling various regex constructs (Char, Star, Alt, Seq) by recursively applying derivative rules. It returns a new regex representing the set of strings that match the original regex after removing the first occurrence of `c`. T...
def derivative(self, c, o=None): if o is None: o = self if isinstance(o, EmptyC): return EmptyC() if isinstance(o, EpsC): return EmptyC() if isinstance(o, CharC): if o.first == c: return EpsC() return EmptyC()...
def insert(msg): textArea.insert(tk.INSERT, "> " + msg + '\n') def send(msg): try: socket.send(msg, socket.socket) except (ConnectionRefusedError, ConnectionResetError) as e: insert(e.strerror) return False return True def receive(): while True: try: serve...
This function sends a specified file to a server, checks if the file exists, reads its content, and sends it. If successful, it continuously receives server responses, inserts unique messages into a log, and writes them to a new file with a `.converted` extension, avoiding duplicates by checking against existing socket...
def sendFile(): global fileName if not fileName or not os.path.isfile(fileName): insert("filename is blank or filePath doesn't exist") return file = open(fileName, 'r').read() if send(file): while True: flag, serverMsg = receive() if not flag and serverM...
def insert(msg): textArea.insert(tk.INSERT, "> " + msg + '\n') def receive(): while True: try: serverMsg = socket.receive(socket.socket) except ConnectionResetError as e: insert(e.strerror) return False, '' if serverMsg in (socket.WELCOME, socket.USER_...
The code handles a client-side connection to a server by retrieving address and port from GUI inputs, establishing a socket connection, and processing server responses. It manages connection errors, checks for a username confirmation message (USERNAME), and updates GUI states (submit button and connection button) if su...
def connectionHandler(): global socket, address, port address = E1.get() port = E2.get() try: socket = SocketClass(address, int(port)) except (ConnectionRefusedError, ConnectionResetError) as e: insert(e.strerror) return flag, serverMsg = receive() if flag: if...
def insert(msg): textArea.insert(tk.INSERT, "> " + msg + '\n') def send(msg): try: socket.send(msg, socket.socket) except (ConnectionRefusedError, ConnectionResetError) as e: insert(e.strerror) return False return True def receive(): while True: try: serve...
The main task of the code is to handle user submission of a username, send it via a socket, process server responses, and update UI states. It retrieves the username from an entry widget, validates it, sends it to the server, checks the response (e.g., file transfer or error), and transitions between states (submit, op...
def submitHandler(): global username username = E31.get() insert(username) if username.strip(): if send(username): flag, serverMsg = receive() if flag: if serverMsg == socket.FILE: changeState(submit) changeState(ope...
def allowed_file(filename): return "." in filename and filename.rsplit(".", 1)[1].lower() in ALLOWED_EXTENSIONS def preprocess_data(filename, exclude_index=0): # Determine the file type and read accordingly if filename.endswith(".xlsx"): df = pd.read_excel(filename) elif filename.endswith(".csv"...
The code generates a heatmap from uploaded Excel data by processing zip codes, merging with geographic data, and creating an interactive map with Folium. It validates input files, preprocesses data, merges with US zip code info, filters geographic regions, and outputs a heatmap HTML file and KML data, returning URLs fo...
def generate_heatmap(): if "excel_file" not in request.files: return jsonify({"error": "No file provided"}), 400 file = request.files["excel_file"] # Check if user did not select file if file.filename == "": return jsonify({"error": "No file selected"}), 400 # Check if file is allo...
def predict_image(self, data, y_true=None, kind='single', limit=0, show=True, max_no_of_plots=28): return self.__predict_cnn(data, y_true=y_true, kind=kind, limit=limit, show=show, max_no_of_plots=max_no_of_plots) def predict_text_post(self, text_post): return self.__predict_text_post(textPost=text_post...
This function performs hybrid prediction by processing text and image inputs (from DataFrame, list, or direct inputs) to generate predictions. It handles different data formats, combines text/image predictions, and evaluates accuracy against true labels if provided. Returns text and image predictions, with optional eva...
def predict_hybrid(self, data=None, text_col_name=None, image_col_name=None, img_path=None, post=None, mode='single', y_true=None, kind='single', limit=0, show=True, max_no_of_plots=28): """ mode: {'single', 'multiple', 'dataframe'} text_col_name, image_col_name: should only be set if 'data'...
def restrict_factor(f, var, value): '''f is a factor, var is a Variable, and value is a value from var.domain. Return a new factor that is the restriction of f by this var = value. Don't change f! If f has only one variable its restriction yields a constant factor''' new_var_l = [] all_vars = f....
The code implements **Variable Elimination (VE)** to compute the **posterior probability distribution** of a **query variable** (QueryVar) given **evidence variables** (EvidenceVars) in a Bayesian Network (BN). It processes BN factors by restricting them to evidence values, eliminates variables via multiplication and s...
def VE(Net, QueryVar, EvidenceVars): ''' Input: Net---a BN object (a Bayes Net) QueryVar---a Variable object (the variable whose distribution we want to compute) EvidenceVars---a LIST of Variable objects. Each of these variables has had its e...
def test_simple_FC(stu_propagators): did_fail = False score = 0 try: queens = nQueens(8) curr_vars = queens.get_all_vars() curr_vars[0].assign(1) stu_propagators.prop_FC(queens,newVar=curr_vars[0]) answer = [[1],[3, 4, 5, 6, 7, 8],[2, 4, 5, 6, 7, 8],[2, 3, 5, 6, 7, 8]...
The main task of the code is to execute multiple tests evaluating constraint propagation algorithms (FC/GAC) on simple and three-queen problems using a provided propagators module. It accumulates scores from each test, prints detailed results, and outputs a total score out of 4. The function dynamically imports the pro...
def main(stu_propagators=None): total = 0 if stu_propagators == None: import propagators as stu_propagators print("---starting test_simple_FC---") score,details = test_simple_FC(stu_propagators) total += score print(details) print("---finished test_simple_FC---\n") print("---...
def apply_pyramid(img): base = img layer_1 = average_pooling(base, (2, 2), (2, 2)) layer_1 = average_pooling(layer_1, (2, 2), (2, 2)) layer_2 = average_pooling(layer_1, (2, 2), (2, 2)) layer_3 = average_pooling(layer_2, (2, 2), (2, 2)) pyramid = [layer_1, layer_2, layer_3] # Run Gabor Ker...
The main task of the code is to detect and return connected components (CCs) in a multi-scale image pyramid. It first blurs the input grayscale image, generates a pyramid of scaled images, thresholds each level to create binary images, and then identifies CCs in all thresholded images across all pyramid levels. The fun...
def get_lines(gray_img): gray_img = cv2.blur(gray_img, (10, 10)) out = apply_pyramid(gray_img) thresholded_imgs = [[threshold(im) for im in level] for level in out] ccs = [] for level in thresholded_imgs: for im in level: ccs.extend(connected_components(im)) return ccs
def create_point_set(blob, threshold, area, gray_img): # getting all points that are white, make tuples y, x = np.where(blob == 255) all_pairs = [(x[i], y[i]) for i in range(len(x))] random.shuffle(all_pairs) error_image = np.zeros(blob.shape) # where lines are drawn num_shaded_pixels = 0 ...
The code processes blobs in a grayscale image to generate lines. For each blob, it creates points, generates strokes, and constructs splines. These splines are added to an image and an array. The array is then sorted by the number of non-zero elements in descending order, and the function returns the final image and so...
def create_lines(gray_img, blobs, thresholds, areas): shape = gray_img.shape lines_array = [] lines_img = np.uint8(np.zeros(shape)) # for each blob create a new point gets for i, blob in enumerate(blobs): pts = create_point_set(blob, thresholds[i], areas[i], gray_img) for j in rang...
def threshold_imgs(img): thresholds = get_thesholds(img) imgs = [] thresholds_as_fractions = [0] for i in range(len(thresholds)): curr_thresh = thresholds[i] prev_thresh = int(thresholds_as_fractions[i] * 255.) thresh_img = cv2.inRange(img, prev_thresh, curr_thresh) i...
The main task of the code is to process a grayscale image by blurring, thresholding, identifying connected components, and extracting line structures, returning both the line-enhanced image and an array of detected lines for further analysis or visualization.
def shade(gray_img): thresh_imgs, thresholds = threshold_imgs(cv2.blur(gray_img, (10, 10))) ccs, thresholds, areas = get_ccs(thresh_imgs, thresholds) lines_img, lines_array = create_lines(gray_img, ccs, thresholds, areas) return lines_img, lines_array
def _filter_empty_sentences(sentences: List[Sentence]) -> List[Sentence]: filtered_sentences = [sentence for sentence in sentences if sentence.tokens] if len(sentences) != len(filtered_sentences): log.warning( f"Ignore {len(sentences) - len(filtered_sentences)} sentence(s) wi...
The main task of the code is to predict sequence tags for Named Entity Recognition (NER) tasks by processing input sentences in batches. It computes token-level tags using a model, optionally returns tag probabilities, handles sequence context, and supports CRF-based tagging. The function adds predicted labels to token...
def predict( self, sentences: Union[List[Sentence], Sentence], mini_batch_size=32, all_tag_prob: bool = False, verbose: bool = False, label_name: Optional[str] = None, return_loss=False, embedding_storage_mode="none", ):...
def _requires_span_F1_evaluation(self) -> bool: span_F1 = False for item in self.tag_dictionary.get_items(): if item.startswith('B-'): span_F1 = True if item == 'O': span_F1 = True if item == '': span_F1 = True r...
The `evaluate` method assesses a model's performance on a dataset of sentences by computing F1 scores, either standard or span-based, depending on the model's requirements. It converts input sentences into a dataset, loads them in batches, and uses appropriate evaluation logic. Results are returned along with a score, ...
def evaluate( self, sentences: Union[List[Sentence], Dataset], out_path: Union[str, Path] = None, embedding_storage_mode: str = "none", mini_batch_size: int = 32, num_workers: int = 8, wsd_evaluation: bool = False, **kwargs ...
def log(message, prefix_newline=False): """Logging function, provides a hook to suppress or redirect log messages.""" print(('\n' if prefix_newline else '') + '{0:.2f}'.format(time.time()) + ': ' + str(message)) def _validate_run_eukrep_params(self, task_params): """ _validate_run_eukrep_params:...
The `run_eukrep` function processes a metagenome assembly to classify contigs into eukaryotic and non-eukaryotic sequences using the EUKREP tool. It validates inputs, retrieves and cleans the assembly file, executes EUKREP to split contigs, saves results as new assembly objects in the specified workspace, and generates...
def run_eukrep(self, task_params): """ run_eukrep: eukrep app required params: assembly_ref: Metagenome assembly object reference binned_contig_name: BinnedContig object name and output file header workspace_name: the name of the workspace it gets saved to. ...
def get_since_id(self): ''' This function returns the Tweet ID of the newest Tweet stored in the database. This Tweet ID will be used as the since ID, if necessary. ''' # Import most recent Tweet ID from MySQL database mysql_query = ''' SELECT tweet_id FRO...
This function repeatedly queries Twitter's API to collect and aggregate tweets based on specified search terms, adhering to request limits. It uses pagination via `since_id` and `until_id` to retrieve older tweets iteratively. Results are stored in DataFrames, including tweet metadata and sentiment analysis. Referenced...
def aggregate_query_results(self, query_terms, requests_limit): ''' This function repeats the query to Twitter and aggregates the results. The Twitter API endpoint used has a requests limit of 450 per 15 minutes. Required input: - query_terms: the term(s) to be searched using...
def get_start_end(graph): # get the start and end nodes for node in graph.nodes: #print(graph.nodes[node]['score']) if graph.nodes[node]['score'] == "S": start = node elif graph.nodes[node]['score'] == "E": end = node elif graph.nodes[node]['score'] == "B"...
The code implements a genetic algorithm to optimize vehicle routing on a graph. It generates an initial population of agents, selects the top performers, applies mutation and crossover to create new generations, and iterates over specified generations to evolve solutions. The goal is to find the agent with the best fit...
def genetic_algorithm(graph, nb_vehicule, max_distance, nb_agent = 30, nb_generation = 100): start, end = get_start_end(graph) # generate the first generation generation = generate_first_generation(graph, start, end, nb_vehicule, max_distance, nb_agent) for i in range(nb_generation): # select ...
def _request_hotel(hotel_id=None, destination=None): loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) loop = asyncio.get_event_loop() result = None if hotel_id: result = loop.run_until_complete( _fetch_from_suppliers_single_hotel(hotel_id)) # remove any None v...
The function retrieves hotel data using the provided ID, validates it, merges the information, saves the result to a database, and returns the processed hotel details.
def update_db_new_hotel(hotel_id): data = _request_hotel(hotel_id=hotel_id) if len(data) == 0: raise Exception hotel_details = _merge_hotel_info(data) save_hotel_to_db(hotel_details) return hotel_details
def _request_hotel(hotel_id=None, destination=None): loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) loop = asyncio.get_event_loop() result = None if hotel_id: result = loop.run_until_complete( _fetch_from_suppliers_single_hotel(hotel_id)) # remove any None v...
The code fetches hotel data for a given destination, processes each hotel's information, saves it to a database, updates a destination record with a timestamp, and returns the processed hotel details as a JSON response.
def update_db_hotels_by_destination(dest): data = _request_hotel(destination=dest) combined_details = [] for _, hotel in data.items(): detail = _merge_hotel_info(hotel) save_hotel_to_db(detail) combined_details.append(detail) db.ascenda.dest_update.update_one( {DOCUMENT_...
def printList(self): curr = self.head finalString = "" while curr: tempString = curr.data.name + " " + str(type(curr.data))[24:-2] # tempString += f"{vars(curr.data)}\n{vars(curr.massFlow)}\n\n" finalString += str(tempString) curr = cu...
The code's main task is to generate a formatted summary string displaying key system metrics: layout details, energy/power values, ethanol production data, costs, and waste. It aggregates outputs from multiple methods to provide a comprehensive overview of the system's performance, including derived values like energy ...
def fullPrint(self) -> str: return f"LAYOUT: {self.printList()}\n\ POWER: {self.layoutPower():.3f} / kJ day\n\ HEAD: {self.layoutEffectiveHead():.3f} m\n\ STATIC COST: ${self.layoutStaticCost():.2f}\n\ ETHANOL CONCENTRATION: {self.ethanolConcentration()*100:.3f}%\n\ PURE ETHANOL AMOUNT: {self.ethanolAmount():.3...
def ethanolConcentration(self): last = self.getLastNode() return last.massFlow.ethanolConcentration() def layoutPower(self): curr = self.head power = 0 while curr: power += curr.data.calculatePower(self.layoutEffectiveHead(), curr.massFlow, curr.massFlow.dens...
The function calculates a composite score for a layout based on normalized power, static cost, ROI, and ethanol purity metrics, each weighted differently. It sets the score to zero if ethanol concentration is below 0.98. Otherwise, it computes normalized values, applies weights (power×3, staticCost×7, ROI×10, purity×3)...
def layoutScore(self, minPow, maxPow, minStatCost, maxStatCost): # print(f"calculating score") if self.ethanolConcentration() < 0.98: self.score = 0 return self.score power = (self.layoutPower() - minPow) / (maxPow - minPow) staticCost = (self.la...
def conj_grad(kernel, f, mu, dx, bx, dy, by, tol_cg, max_cg): x = f r = convolution_T(f, kernel)+mu*Wx_T(dx-bx)+mu*Wy_T(dy-by)-operator(x,kernel,mu) rsold = np.sum(r*r) p = r k = 0 while k<max_cg: Ap = operator(p,kernel,mu) alpha = np.sum(r*r)/np.sum(p*Ap) x = x + alpha*p...
The code implements the Alternating Direction Method of Multipliers (ADMM) to solve an inverse problem, likely image restoration (e.g., deblurring/denoising). It iteratively updates the image estimate `u` using conjugate gradient (CG) steps, soft-thresholding for regularization, and dual variable updates. The algorithm...
def ADMM(image_true, kernel, f, mu, lam, delta, tol_cg, tol_iter, max_cg, max_iter): d = len(f) # initial u = f dx = np.zeros((d, d)) bx = np.zeros((d, d)) dy = np.zeros((d, d)) by = np.zeros((d, d)) k = 0 # iteration times while k<max_iter: u = conj_grad(kernel, u, mu, dx,...
def entryExists(connection, hdid, fname, dirName): query = query_file_on_drive.format(**{'hdid': hdid, 'path': dirName, 'quotepath': extractQuote(dirName), 'name' : fname, 'quotename': extractQuote(fname)}) #print(query) results=execute_read_query(connection, query) #print("entryExists returns ", len(re...
The function scans files in a directory tree, checking if they exist in a database. For each file, it computes MD5 hashes, sizes, and timestamps. If the entry is missing, it adds a record to the database (or prints details in dry-run mode). It handles errors like file not found or permission issues, tracking added, ski...
def scanFiles(connection,rootDir, hdid, bufsize = 4096, dryRun = False): added = 0 skipped = 0 errors = 0 recalculateEntry = False for dirName, subdirList, fileList in os.walk(rootDir, topdown=False): #print('Found directory: %s' % dirName) for fname in fileList: # if (Tr...
def clean_data(self, data, required_columns): """ Removes entries that don't have data in `required_columns`, converts currencies to USD and calculates CAPEX per kW. Parameters ---------- data : pd.DataFrame required_columns : list """ data = dat...
The main task of the code is to initialize a regression model by preparing and processing project data. It filters, cleans, and structures input data based on parameters like target variable (y_var), regression variables, filters, and country aggregations, then executes a multi-linear regression analysis using the proc...
def __init__( self, projects, y_var, filters={}, regression_variables=[], status=["Fully Commissioned"], drop_countries=[], drop_categorical=[], aggregate_countries={}, log_vars=[], add_vars={}, **kwargs, ): """ ...
def __clean_query(self, raw_sql): statements = sqlparse.split(raw_sql) statement = statements[0] sql_parsed = sqlparse.format(statement, reindent=True, keyword_case='upper') sql_parsed_split = sql_parsed.splitlines() cleaned_query = '' for item in sql_parsed_split: ...
The code parses a SQL query by cleaning it, splitting into tokens, extracting tables and selectable columns, and splitting the query further for analysis or processing.
def __init__(self, query): self.query = self.__clean_query(query) self.tokens = sqlparse.parse(self.query)[0].tokens self.tables = self.__extract_tables() self.selectable_columns = self.__get_selectable_columns() self.splitted_query = self.__splitted()
def IsSheetNoteFamilyType(family_type): for p in family_type.Parameters: if 'SERIES' in p.Definition.Name: return True else: continue return False def GetSheetNoteFamilies(): GenericAnnontationFamilyTypes = DB.FilteredElementCollector(doc ).OfCategory(DB.BuiltInCategory.OST_GenericAnnotation ).W...
This function merges multiple sheet note family types into a single target family. It first validates the selected family type and checks for a 'SERIES' parameter. Then, it iterates through all other sheet note families, merging each into the target family using the MergeSheetNoteFamilyTypes method, and returns the con...
def MergeAllSheetNoteFamilyTypes(): try: assert selection[0].GetType() == DB.AnnotationSymbolType except AssertionError: print("ERROR: No Generic Annotation type selected. Select (in the Project Browser) any type of the family you want to merge the other families into, the try again.") return None try: ass...
def val_num(x, minVal=None, maxVal=None, errMsg=None): if (minVal is not None): if x < minVal: if errMsg is None: raise Exception('The value ' + str(x) + ' should be bigger then ' + str(minVal)) raise Exception(errMsg + ' Actual val: ' + str(x)) if not (maxVal is...
The code trains a neural network model using batched data, alternating between whitening and reconstruction phases, with optional mutual training and decoder-only training. It evaluates model performance on training and validation data, monitors losses, handles early stopping based on validation improvements, and saves...
def train(self, data_train, amount_epochs, lr=0.1, batch_size=None, data_val=None, evaluate_every=None, verbose=False, train_only_decoder=False, save_best=True, tol=None, mutual_train=False, initial_training=False, whlr_reclr_ratio=1): N_train = data_train.shape[0] N_val = 0...
def is_monospace_formatted(text_format): return text_format.font().styleHint() == QFont.Monospace def build_literal_block(self, block): self.append_node(nodes.literal_block()) self._indentation_stack.append(block.blockFormat().indent()) def build_block_quote(self, block): block_indent = bloc...
This code converts a Qt document into a structured doctree by processing each block, handling headers, indentation, block quotes, and literal blocks. It maintains section stacks and indentation levels to build the document's hierarchy, appending nodes like paragraphs, headers, or literal blocks based on formatting and ...
def convert(self, qt_document): doctree = utils.new_document("", frontend.get_default_settings()) self._section_stack = [doctree] self._section_level_stack = [0] block = qt_document.firstBlock() while block.isValid(): block_format = block.blockFormat() l...
def Flabel(Valor): contenido = """//---------------------------------------------------------------- //[L1.0 LABEL ] contenidoform += '<label class="mb-3">"""+ str(Valor) +"""</label>'""" contenido +=""" """ return contenido def Finputtext(Valor, Fondo): #Quitar Espacios variableV...
The main task of the code is to generate a JavaScript file ('formulario.js') that dynamically creates a form by writing HTML elements into a specified div ("contenidoformulario"). It processes a list of form elements (ListadoElementos2), appending JavaScript code for each element type (labels, text inputs, radio button...
def crearformulario(): print("creando formulario...") #[A1.0 Crear JAVASCRIPT ] try: #0.0 Limpia el archivo f = open('formulario.js','w') contenido = "" f.write(contenido) f.close() #[1.2 Abre el archivo] f = open('formulario.js','w') #[2.0 ...
def Flabel(Valor): contenido = """//---------------------------------------------------------------- //[L1.0 LABEL ] contenidoform += '<label class="mb-3">"""+ str(Valor) +"""</label>'""" contenido +=""" """ return contenido def Finputtext(Valor, Fondo): #Quitar Espacios variableV...
The main task of the code is to generate a JavaScript file (`formulario.js`) containing a web form with various elements (labels, text inputs, radio buttons, selects, buttons) by concatenating predefined code snippets. It creates the file, writes dynamic HTML/JS content, handles errors, and returns a success message up...
def crearformulario2funciones(): print("creando formulario...") #[A1.0 Crear JAVASCRIPT ] try: #[1.2 Abre el archivo] f = open('formulario.js','w') #[2.0 Nuevo contenido] #DIV contenedor de formulario contenido = """//Obtener div donde se colocara los elementos del...
def nuevoerror(codigo,funcion,mesajee,excepccion): #Crea nuevo error newerror = Errores(codigo,funcion,mesajee,excepccion) #Guarda el nuevo error global ListaErrores ListaErrores.append(newerror) def imprimirerrores(): print("\n") print("==============[ Errores ]==================") for ...
The function `analizar()` processes and analyzes structured text input to extract form elements. It cleans the input text, identifies form boundaries using keywords, parses elements enclosed in `<` and `>` tags, and extracts attributes like type, value, background, name, event, and values. Errors are logged, and parsed...
def analizar(): #[Limpiar Valores] global Textform Textform = "N/A" global TextVacioVentana TextVacioVentana = "" global ListaErrores ListaErrores = [] #Elementos en Texto global ListadoElementos1 ListadoElementos1 = [] #Elementos dentro de una clase para facilitar su obtenci...
def handle_greeting(event): logger.debug("Parsing a greeting event {}".format(event)) return { 'dialogAction': { "type": "ElicitIntent", 'message': { 'contentType': 'PlainText', 'content': 'Hi there, how can I assist you today?'} } } de...
The code's main task is to dispatch events based on the detected intent type by logging user and intent details, then routing to specific handlers like greetings, dining suggestions, or thanks, while raising an exception for unsupported intents.
def handle_event(event): logger.info( 'dispatch userId={}, intentName={}'.format(event['userId'], event['currentIntent']['name'])) intent_type = event['currentIntent']['name'] if intent_type == 'GreetingIntent': return handle_greeting(event) elif intent_type == 'DiningSuggestio...
def parse_vcf_header(fn): """ This function parses the header of a vcf file and returns a list of the table header (last header line) and a dictionary of the other header entries. """ info_dic = {} fh = gzip.open(fn) if fn[-3:] == ".gz" else open(fn) for line in fh: line = line.d...
This function processes genomic data from a VCF file using a map-reduce approach. It reads the file in chunks, applies a specified function to each chunk, collects results, and combines them using a reduction function. The task involves handling genomic samples, chromosomes, and positions, with customizable data proces...
def map_reduce_geno(fn, fun, samples=None, chrom=None, start=None, end=None, chunksize=50000, apply_fun=None, get_result_fun=None, reduce_fun=None, **read_args): """ """ if apply_fun is None: apply_fun = lambda fun, chunk: fun(chunk) if reduce_fun is None...
def filterFeatureInGFF(gff, feat): ''' Keep/filters GFF records that include specified feature and returns a new GFF ''' filtered_gff = collections.defaultdict() for gene in gff.keys(): filtered_gff[gene] = collections.defaultdict() for gene in gff.keys(): if len(gff[gene][feat]) != ...
The main task of this code is to convert genomic regions/annotations (e.g., CDS, genes) from a GFF/GTF file into FASTA alignments by applying variants from a VCF file to a reference FASTA genome. It parses command-line arguments, reads input files (GFF, VCF, FASTA), processes genomic features, and generates FASTA files...
def main(): print(art.text2art("vcf2fasta")) # parse arguments parser = argparse.ArgumentParser(prog="vcf2fasta.py", #version="0.3", formatter_class=argparse.RawTextHelpFormatter, description=""" Converts regions/intervals in the genome into FASTA alignments provided ...
def load_tree(): tree = Phylo.read(r"data/inversion_samples_noninverted_pwd_nj_tree_ancestral_rooted.newick.nwk", "newick") return tree def load_metadata(): filename = "./Data/inversion_man_mt_2022-11-16.tsv" # load the metadata from inversion_man_mt_2022-11-16.tsv into a pandas dataframe return loa...
The code selects individuals from a phylogenetic tree by identifying nodes that are last common ancestors (LC) of OTUs sharing the same taxon. It filters these LC nodes, extracts two representative OTUs per node, maps them to taxon IDs, and compiles results into a DataFrame. The output is a TSV file listing taxon IDs a...
def select_individuals(): """ Selects individuals from the tree. """ tree: Phylo.Newick = load_tree() # Load the tree dataframe = load_metadata() # Load the metadata lc_list = [] # pairs of (node number, count of OTUS(leaves) under this node (= LC)) species: str # species name of the fi...
def read_data_from_file(filename): try: with open(filename, "r", encoding="utf-8") as file: data = json.load(file) return data except IOError as misc_error: print(f"Error reading from file {filename}: {misc_error}") return None def fetch_characters_info(current_c...
The function updates character data by reading existing information from a file, fetching new character details, printing the updated data, and merging it back into the original file to maintain current records.
def update_character_data(character_file_link): current_characters_info = read_data_from_file(character_file_link) new_characters_info = fetch_characters_info(current_characters_info) print_characters_info(new_characters_info) merge_data_to_file(new_characters_info, character_file_link)
def check_x_typical(p_x, x_in, Hx): # given input sequence x_in # it should be a list sample_mean = compute_sample_mean(p_x, x_in) if abs(sample_mean-Hx)<epsilon: return True else: return False def check_y_typicality(p_y, y_out, Hy): #p(y1, y2, ....) = 2^nH(y) sample_mean=co...
This function checks if input variables x_in and y_in are jointly typical by verifying their individual typicality with respect to their marginal distributions (p_x, p_y) and their joint typicality with respect to the joint distribution p_joint, using entropy parameters H_x, H_y, and H_x_y. It returns True only if all ...
def check_joint_typicality(x_in, y_in, H_x, H_y, H_x_y, p_x, p_y, p_joint): return check_x_typical(p_x, x_in, H_x) and check_y_typicality(p_y, y_in, H_y) and check_both_typicality(p_joint, x_in, y_in, H_x_y)
def get_user_menu_choice(): valid_choices = 'sre' while True: response = input('Send message (s), read inbox (r), or exit (e): ') if response.lower() not in valid_choices: print('Invalid option') else: return response.lower() def send_message(sender): # send a...
The code displays a user menu for logged-in users, allowing them to send messages ('s'), read all messages ('r'), or log out ('e'). It processes the username by removing underscores, prints a welcome message, and loops until the user selects 'e' or an invalid option, triggering logout.
def user_menu(username): orig = username.strip('_') print(f'Logged in, welcome {orig}!') while True: # get user input choice = get_user_menu_choice() match choice: case 's': send_message(username) case 'r': read_all_messages(u...
def get_login_menu_choice(): valid_choices = 'lce' while True: response = input('Log in (l), create new account (c), or exit (e): ') if response.lower() not in valid_choices: print('Invalid option') else: return response.lower() def validate_user(): # check us...
The code presents a login menu allowing users to log in, create an account, or exit. It validates existing users, creates new ones, and directs flow to the user menu or program exit based on input, handling invalid choices by terminating the menu.
def login_menu(): while True: # get user input choice = get_login_menu_choice() match choice: case 'l': # returning user validated, username = validate_user() if validated: user_menu(username) el...
def flatten(smis, y): mols = [] for i, smile in enumerate(smis): mols.append(Chem.MolFromSmiles(smile)) if ((i+1) % 100000 == 0): logger.info(f"finished {i}") if y is not None: mols = [(m, y) for (m, y) in zip(mols, y) if m is not None]# can ghost remove but to bad ...
The main task of the code is to generate novel, diverse molecules (denovo hits) by combining a generative model with a filtering classifier. It filters input molecules based on score thresholds, clusters top candidates, fine-tunes the generative model on the filtered set, and iteratively generates new molecules while e...
def filter_and_generate(smiles: List, labels: List, gen_model_path: str, clf_model_path: Optional[str] = None, do_filter: bool = True, use_cuda: bool = True, tot_hits: int = 10...
def flatten(smis, y): mols = [] for i, smile in enumerate(smis): mols.append(Chem.MolFromSmiles(smile)) if ((i+1) % 100000 == 0): logger.info(f"finished {i}") if y is not None: mols = [(m, y) for (m, y) in zip(mols, y) if m is not None]# can ghost remove but to bad ...
This function generates diverse, non-redundant molecules using a generative model, optionally filtering with a classifier and ensuring diversity based on a biased set. It clusters input molecules, fine-tunes the model if needed, and iteratively generates molecules until a target count is reached, saving results and aux...
def bias_set_filter_and_generate(bias_smiles, gen_model_path: str, clf_model_path: Optional[str] = None, do_filter: bool = False, use_cuda: bool = True, to...
def _is_vertex_on_constraint(vertex, constraint): """ Given a vertex and a constraint, check if the vertex is on the plane defined by the constraint. For inequality constraints, the plane we look at is the extremal plane that separates the elements that fulfill an inequality constraint from the elem...
The function filters vertices to include only those lying on a plane defined by the constraint, then sorts them to form a convex shape. It returns the sorted list of vertices or None if none meet the constraint.
def get_vertices_for_constraint(vertices, constraint): """ Return the list of vertices within a hyperspace. Given a constraint and a list of vertices, we filter the list of vertices such that only the vertices that are on the plane defined by the constraint are returned. We then sort the vertices s...
def plot_set_3d_vertices(vertices): color = colors[0]['dark'] return plot_points(vertices, color) def plot_set_3d_shape(vertices, faces, show_border): color = colors[0]['base'] string = "var tile; var material;" string = "tile = new THREE.Geometry();" string += "material = new THREE.MeshLambertM...
This function generates a 3D visualization of a convex set using input data and optional parameters. It plots vertices, faces, integer points, and borders based on flags like show_vertices, show_shape, show_points, and show_border. The only_hull_points parameter filters displayed points to those on the convex hull. It ...
def _plot_set_3d(set_data, show_vertices=False, show_points=False, show_shape=True, show_border=True, only_hull_points=True): """ This function plots a three dimensional convex set. :param set_data: The set to illustrate. :param show_vertices: Show the vertices at the corner of the set. :pa...
def get_html_page_start(): string = """ <html> <head> <meta charset="UTF-8"> <title>islplot 3D animation</title> </head> <body> """ return string def get_js_includes(): string = """ <script language="JavaScript">""" string += THREE_JS string += ORBIT_CONTROLS string += THREE_JS_DETECTOR...
The main task of the code is to generate an HTML/JavaScript visualization of a 3D convex set, allowing customizable rendering of vertices, integer points, and bounding faces. It constructs a webpage-compatible string with optional full HTML structure, using random identifiers and helper functions to assemble scene elem...
def plot_set_3d(set_data, show_vertices=False, show_points=False, show_shape=True, full_page=False, scale=0.7, show_axes=True, only_hull_points=True): """ This function plots a three dimensional convex set. :param set_data: The set to illustrate. :param show_vertices: Show the vertices ...
def data_label_process(self, data, labels, running_mode): return data.to(device=self.device), labels.to(device=self.device) def pred_process(self, pred, running_mode): return pred def loss_process(self, loss, running_mode): return loss def after_batch_process(self, running_mode): pass de...
The main task of the code is to perform a single training step for a neural network. It processes training data, computes loss, executes backpropagation, updates model parameters, and optionally calculates accuracy. If validation is enabled, it also runs a validation step. The function returns training and validation l...
def train_step( self, validation: bool = False, compute_acc: bool = False, silent: bool = False, ): train_loss, train_acc, train_sample_cnt = 0.0, None, 0 if compute_acc: train_acc = 0 self.net.train() iterable = self.train_loader if silent else tqdm(sel...
def setup_dataframe(self, input_box): ''' Pandas will be used to open and read the values of the CSV file consisting of hotels information After that, a brand new dataframe will be created, The row consisting of Changi Airport Singapore in the original dataframe will be added to the new ...
The function `submit_inputs` processes user inputs to generate a map. It initializes data structures with `setup_dataframe`, constructs a graph using `generate_graph`, and renders the map via `draw_map`, incorporating inputs like location, dropdown selection, and weight values to visualize results.
def submit_inputs(self, n_clicks, input_box, dropdown_value, weight_values): ''' This function is called when the user first clicks on the submit button, Which calls upon all the other functions to generate the map ''' if input_box is None: return None else: ...
def PrintSeparator(): print(GetStr("-", separatorLenght)) return def PrintAllStatusIndex(maxHp): for i in range(0, len(statusEffects)): PrintCalcIndex(maxHp, i) return def PrintCalcIndex(targetHp, index): name, duration, dmgFlat, dmgPercentage = statusEffects[index] #print(f"name={name}...
The function `DoLogicThenPrint` prints the target HP value, a separator line, and either all status indices or calculated indices based on the `index` parameter. It outputs HP-related status information conditionally, using helper functions for formatting and logic.
def DoLogicThenPrint(maxHp, index): print(f"Target HP = {maxHp}") PrintSeparator() if index == 0: PrintAllStatusIndex(maxHp) else: PrintCalcIndex(maxHp, index) return
def RegisterDefaultStatuses(): RegisterStatus("Poison - Standard", 90, 7, 0.07) RegisterStatus("Deadly Poison - Fetid Pot", 30, 12, 0.14) RegisterStatus("Deadly Poison - Venomous Fang/Serpent Arrow", 30, 14, 0.14) RegisterStatus("Perfumer's Poison", 30, 21, 0.21) RegisterStatus("Scarlet Rot - Weapon...
The main task of the code is to parse command-line arguments for max HP and status index, validate inputs, and execute logic with these parameters. It registers default statuses, checks argument count, extracts values, handles errors by showing usage if no arguments are provided, then calls a function to perform calcul...
def Main(): RegisterDefaultStatuses() argsLen = GetArgsCount() maxHp = 0 statusIndex = 0 if argsLen > 1: statusIndex = GetArgInt(1) if argsLen > 0: maxHp = GetArgInt(0) else: ShowUsage() return DoLogicThenPrint(maxHp, statusIndex) return
def play(self, move=None): if move is None: alpha = -float("inf") # worst possible score for maximizing player. beta = float("inf") # worst possible score for minimizing player. max_depth = 10 # max depth to search to best_score, best_move, n = minimax(self, m...
This code initializes a game board for a Connect Four-like game, setting up dimensions, player IDs, and a 2D grid. It tracks the current turn, awards points based on player actions, and checks if the game is over. If it's the bot's turn, it makes a random move and evaluates the game state, printing the time taken for t...
def __init__( self, game_id, player_id, opp_id, turn_id, move_req, rows=6, cols=7, ): self.rows, self.cols = rows, cols # dimensions of the board self.connect_n = 4 # how many coins need to be connected to win? # ids self.game_id = game_id self.player_id = int(play...
def send(data, conn, pickle_data=True, to_bots=True): try: if pickle_data: data = pickle.dumps(data) conn.sendall(data) except Exception as e: print("ERROR TRYING TO SEND DATA: ", e) def send_all_users(conn): active_users_data_bytes = json.dumps(active_users).encode("utf-...
This code manages a threaded client connection for a multiplayer game server. It handles user authentication, sends initial data, processes challenges, game interactions, profile updates, and disconnections. It validates game actions, manages game states, notifies users of updates, and ensures proper cleanup upon disco...
def threaded_client(conn, addr, user_id, user_stats): # send this user some start up info # (this users id, all active users) send(user_id, conn) time.sleep(1) send_all_users(conn) # time.sleep(1) send_all_user_images(conn) # time.sleep(1) # send all other users this user's stats...
def write(self, data): if self.doLog: self.log('SEND', data) self.port.write(data) def readline(self): data = self.port.readline() inkex.debug(data) if self.doLog: self.log('RECV', data) return data def log(self, type, text): ts = datetime.datetime.now() try: with open("costycnc-serial.log", "a...
This code sends a command via a serial port, reads the response with retry logic, handles 'ok' confirmation, and returns the result or None if invalid inputs are provided.
def query(self, cmd): if (self.port is not None) and (cmd is not None): response = '' try: self.write(cmd) response = self.readline() nRetryCount = 0 while (len(response) == 0) and (nRetryCount < 100): if self.doLog: self.log('QUERY', 'read %d' % nRetryCount) response = self.read...
def write(self, data): if self.doLog: self.log('SEND', data) self.port.write(data) def readline(self): data = self.port.readline() inkex.debug(data) if self.doLog: self.log('RECV', data) return data def log(self, type, text): ts = datetime.datetime.now() try: with open("costycnc-serial.log", "a...
The main task of the code is to send a command via a serial port and retrieve the response, with retry logic for empty responses and error handling for serial communication issues. It writes the command, reads the initial response with retries, then reads a secondary "ok" confirmation, logging details if enabled, and r...
def query(self, cmd): if (self.port is not None) and (cmd is not None): response = '' try: self.write(cmd) response = self.readline() nRetryCount = 0 while (len(response) == 0) and (nRetryCount < 100): if self.doLog: self.log('QUERY', 'read %d' % nRetryCount) response = self.read...
def navigate_page(self) -> None: """ This will accept all cookies """ self.accept_cookies = self.driver.find_element(by=By.XPATH, value= "//button[@id='onetrust-accept-btn-handler']") self.accept_cookies.click() self.fourth_element = self.driver.find_element(by=By.XPATH, value="//td[@cla...
The code defines a scraper_main method performing web scraping tasks: navigates to a page, scrolls it, stores extracted data, downloads images, connects to a database, uploads files to AWS, and quits the browser driver.
def scraper_main(self) -> None: self.navigate_page() self.page_scroll() self.data_store() self.download_image() self.connect_to_db() self.aws_upload() self.driver.quit()
def render(): previous_path = bpy.context.scene.render.filepath bpy.context.scene.render.filepath = FILE_PATH bpy.ops.render.render(write_still= True) bpy.context.scene.render.filepath = previous_path def load_image(): try: bpy.data.images.remove(bpy.data.images[FILE_NAME]) except: ...
This function applies a dithering algorithm to an image, modifying its pixel data based on the specified algorithm type, factor, and randomness distribution. It loads an image, converts it to a numpy array, processes it with the dither function, updates the pixel data, and saves the modified image with parameters indic...
def render_and_modify(algo_type='floyd_stein', factor=4, rand_dist=False): render() image = load_image() pixel_array = numpy.array(image.pixels[:]) new_pixels = dither(pixel_array, factor, algo_type=algo_type, rand_dist=rand_dist) image.pixels = new_pixels save_image(image, algo_type, factor, )
def load_image(): try: bpy.data.images.remove(bpy.data.images[FILE_NAME]) except: pass return bpy.data.images.load(FILE_PATH) def dither(arr, factor, algo_type="floyd_stein", rand_dist=False): if algo_type == 'ordered': dm = dither_matrix(factor) return ordered_dithering...
The code applies a dithering algorithm to an image using specified parameters (factor, algorithm type, and randomness). It loads an image, converts it to a pixel array, applies the dithering process, updates the image's pixels, and saves the result as a PNG file with a filename indicating the algorithm type and randomn...
def dither_image(factor, algo_type, rand_dist=False): image = load_image() pixel_array = numpy.array(image.pixels[:]) new_pixels = dither(pixel_array, factor, algo_type, rand_dist=rand_dist) image.pixels = new_pixels file_path = f'//dither_tests/{algo_type}_factor{"_rand" if rand_dist else ""}.png' ...
def render(): previous_path = bpy.context.scene.render.filepath bpy.context.scene.render.filepath = FILE_PATH bpy.ops.render.render(write_still= True) bpy.context.scene.render.filepath = previous_path def load_image(): try: bpy.data.images.remove(bpy.data.images[FILE_NAME]) except: ...
The main task of the code is to generate a dithered animation by rendering each frame with a specified algorithm, applying pixel-level dithering to images, saving them as PNGs, and compiling them into a Blender video sequence. It processes `num_frames` by rendering, modifying pixels via the `dither()` function with par...
def render_video(num_frames, algo_type, factor, rand_dist=False): file_dir = '//dither_frames/' files = [] for f in range(num_frames): print('rendering frame', f, 'of', num_frames) bpy.context.scene.frame_set(f) render() image = load_image() pixel_array = numpy.array(...
def test_perceptron(): df = pd.read_csv('https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data', header=None) print("Creating a two-feature data set") y = df.iloc[0:100, 4].values y = np.where(y == 'Iris-setosa', -1, 1) X = df.iloc[0:100, [0, 2]].values print("Creating Percept...
The main task of the code is to execute a series of test functions for various machine learning models, including Perceptron, 1-d Threshold/Interval learners, Linear/Logistic Regression, k-nearest neighbor, and Soft Vector Machine. It sequentially runs and evaluates these algorithms, printing progress updates for each ...
def main(): print("Running Perceptron Class Tests...") test_perceptron() print("Running the Low VC Learners...") print("Testing the 1-d Threshold Learner...") test_threshold() print("Testing the 1-d Interval Learner...") test_interval() print("Testing More Line Learners...") print("T...
def count_part_source_images(self, source_folder: posix.DirEntry) -> Dict[str, int]: '''count the image files for a part (definition) set''' context_data = { 'total_counts': self.empty_image_folder_counts(), 'source_counts': self.empty_image_folder_counts() } scan...
This function processes directories and files in a source folder to categorize SVG part sets. It checks if a directory matches expected sub-part folders, adds valid ones to the context, counts images, and accumulates totals. Unexpected directories, files, or other entries are logged with counts and details reported.
def process_part_set_source_folders( self, source_file_spec: posix.DirEntry, set_root_folder: posix.DirEntry, context_data: dict) -> None: '''process image view folders in a single part source folder''' if source_file_spec.is_dir(): if source_file_spec.nam...
def empty_part_folder_counts() -> Dict[str, int]: '''create a safe to modify copy of an empty set of counts''' return dict({ 'parts': 0, 'dirs': 0, 'other': 0, 'weird': 0 }) def count_folder_parts(self, parts_folder: posix.DirEntry) -> dict: ...
This function counts Fritzing part definition files in nested subfolders specified by an argument key. It aggregates counts across all subfolders, reports individual folder results, and accumulates totals. If enabled via SVG flag, it also counts associated images. Finally, it returns the aggregated part counts for all ...
def count_nested_parts(self, arg_key: str) -> Dict[str, int]: '''Count the number of Fritzing part definition files in each folder''' folders = getattr(self.command_arguments, arg_key + "_sub") count_totals = self.empty_part_folder_counts() part_sub_folders = [] for one_folder in...
def expecting_wrapper_only_element(self, element, context: dict) -> None: '''default handling trap when expecting an element that should only be a container no text no attrib ''' self.expecting_required_wrapper_element(element, context) # if element is None: # ...
This method validates and collects part properties from XML. It checks required/optional attributes, ensures no duplicate property names, verifies non-empty text values, and confirms the presence of the 'family' property. Exceptions are recorded for invalid elements or missing attributes. Validated properties are store...
def process_part_properties(self) -> None: '''validate and collect information about the part properties''' # only need to get a single element: module element validation checks that it does # not contain any repeated child elements property_required_attributes = ['name'] propert...
def empty_part_folder_counts() -> Dict[str, int]: '''create a safe to modify copy of an empty set of counts''' return dict({ 'parts': 0, 'dirs': 0, 'other': 0, 'weird': 0 }) def _report_folder_processing(self, folder: str, description: str) -> None...
This code initializes an object to count and report part files in specified directories. It processes the 'parts_library' directory, counts its nested parts, and if a user directory is provided, accumulates counts from both library and user directories. It generates reports for each directory and a grand total of part ...
def __init__(self, cmd_args: argparse.Namespace): '''count and report part files in the selected directories''' count_totals = self.empty_part_folder_counts() user_counts = None self.command_arguments = cmd_args self._report_folder_processing(cmd_args.parts_library, self.LIB_DIR_...
def expecting_wrapper_only_element(self, element, context: dict) -> None: '''default handling trap when expecting an element that should only be a container no text no attrib ''' self.expecting_required_wrapper_element(element, context) # if element is None: # ...
This function validates and collects view-specific graphics data for a part, ensuring correct XML structure and layer/image configurations. It processes each view, checks layer attributes, and enforces rules for the required 'breadboardView'—validating its image path folder and layer name based on the part's family. Ex...
def process_part_views(self) -> None: '''validate and collect information about the view specific graphics for the part This does not look at the view information for connectors''' # only need to get a single element: module element validation checks that it does # not contain any repea...
def sanity_check_module_elements(self) -> None: '''global checks of the elements in the root module''' all_child_elements = ( 'author', 'buses', 'connectors', 'date', 'description', 'label', 'properties', 'schematic-subparts', 'spice', 'tags', 'taxonomy', 'title', 'url', 'version...
This method explores and processes the structure of an fzp XML module by performing sanity checks on module elements, extracting and processing part properties, and handling part views to analyze or transform the data.
def walk_fzp_xml_tree(self) -> None: '''explore the fzp content''' self.sanity_check_module_elements() self.process_part_properties() # print(self.data_set['properties']) # DEBUG collected property details self.process_part_views()
def get_binary_message_from_hex_message(hex_message): """Get binary message from hex message""" binary_message = '' for hex_code in hex_message: binary_code = get_binary_code_from_hex_code(hex_code) binary_message += binary_code return binary_message def get_polynomial_degree(polynom...
The main task of the code is to compute and verify a CRC (Cyclic Redundancy Check) code for a given hexadecimal message and polynomial. It converts the hex message to binary, prepares the message with appropriate padding, calculates the CRC code, appends it to the original message, and checks both correct and incorrect...
def print_all_info_for_crc_code(hex_message, polynomial): """Print all info for CRC code""" incomplete_binary_message = get_binary_message_from_hex_message( hex_message ) degree_of_polynomial = get_polynomial_degree(polynomial) full_binary_message = get_full_binary_message( incomple...
def get_symbols_with_frequency(message): """Get frequency for symbols in the message""" symbols_with_frequency = defaultdict(int) for symbol in message: # Increment frequency for current symbol symbols_with_frequency[symbol] += 1 return dict(symbols_with_frequency) def get_sorted_symb...
The function generates and prints Huffman coding information for a given message, including symbol frequencies, probabilities, entropy, average code length, and the Huffman codes themselves. It processes the input message to build a Huffman tree, calculates compression metrics, and outputs detailed results for analysis...
def print_all_info_for_huffman_code(message): """Print all info for Huffman code""" print(f'Initial message: {message}\n') symbols_with_frequency = get_symbols_with_frequency(message) sorted_symbols_with_frequency = get_sorted_symbols_with_frequency( symbols_with_frequency, False ) sym...
def MinMax(self,game,player,depth,playerSide): #Initially depth == 5 if game.gameOver(playerSide) or depth==1: if player ==1: bestValue = game.evaluate(playerSide) else: bestValue = game.evaluate3(playerSide) bestPit = ...
The code implements a computer player's turn in a game, using the MinMax algorithm to determine the best move. If no best move was previously made, it calculates the optimal move, updates the game state, and returns the player's result. If a best move was already made, it updates the game state and recursively calls it...
def computer1(self,game): didbestmove,move=game.state.bestmove(game,1) if didbestmove == 0: bestValue, bestPit = self.MinMax(game, 1, 5, 1) n=game.state.board[bestPit] player,plusgain=game.state.doMove(bestPit,1) update(game,bestPit,n,1,plusgain) ...
def MinMax(self,game,player,depth,playerSide): #Initially depth == 5 if game.gameOver(playerSide) or depth==1: if player ==1: bestValue = game.evaluate(playerSide) else: bestValue = game.evaluate3(playerSide) bestPit = ...
The function `computer2` determines the best move for player 2 using the MinMax algorithm with a depth of 5. If no precomputed best move exists, it calculates the optimal move, updates the game state, and returns the resulting player. If a best move is already available, it applies it, updates the game, and recursively...
def computer2(self,game): didbestmove,move=game.state.bestmove(game,2) if didbestmove == 0: bestValue, bestPit = self.MinMax(game, 1, 5, 2) n=game.state.board[bestPit] player,plusgain=game.state.doMove(bestPit, 2) update(game,bestPit,n,2,plusgain) ...
def mancala_board(): screen.fill(white) printdata("Mancala",(640, 50),100,brown) pygame.draw.rect(screen, brownlight,(150, 150, 1000,350) ) for magasin in magazins : pygame.draw.rect(screen, brown,magasin ) for position in fosses_position : pygame.draw.circle(screen, brown, positi...
The main task of the code is to visually render the current state of a Mancala game board using Pygame. It draws red circles representing seeds in each player's pits (board_player1 and board_player2), calculates their positions dynamically, and displays specific board values. The function updates the screen, pauses for...
def display (game) : mancala_board() for fosse in game.state.board_player1 : for nb in range(game.state.board[fosse]) : pos=game.state.fosse_positions[fosse] pygame.draw.circle(screen, red, get_graine_pos(nb,pos), (10)) for fosse in game.state.board_player2 : for ...
def is_dir_non_empty(directory): """ Returns True if the `directory` exists and is non-empty """ try: if any(os.scandir(directory)): return True except Exception: # noqa pass return False def build_driver_hoc(model): model.run_info["driver"] = os.path.join(model...
The function prepares a model by unzipping its contents from a cache, setting up the working directory, generating necessary files like `driver.hoc`, handling run configurations (Python/HOC), and saving run information in YAML. It checks for existing data, cleans directories if needed, and ensures the model is ready fo...
def prepare_model(model): # unzip model from cache with zipfile.ZipFile( os.path.join(MODELS_ZIP_DIR, str(model.id) + ".zip"), "r" ) as zip_ref: model_dir = os.path.join( model.working_dir, str(model.id), os.path.dirname(zip_ref.infolist()[0].filename)...
def append_log(model, model_sink, text): model_sink.extend(curate_log_string(model, text).split('\n')) def prepare_model(model): # unzip model from cache with zipfile.ZipFile( os.path.join(MODELS_ZIP_DIR, str(model.id) + ".zip"), "r" ) as zip_ref: model_dir = os.path.join( ...
This code prepares and runs a neuronal model by compiling MOD files, handling configuration flags (like 'skip' or 'norun'), logging execution details, and timing the process. It checks for model directories, compiles MOD files if present, executes NEURON with specified commands, captures output, and records runtime met...
def run_model(model): start_time = time.perf_counter() # Some models are skipped on purpose if "skip" in model: append_log(model, model.logs, "Model is skipped according to modeldb-run.yaml:\n\t{}\n".format( model["comment"] ) ) return model ...
def decisionTree(data, featureList): isPure = len(np.unique(data[0])) == 1 if isPure: return np.unique(data[0])[0] elif len(featureList) == 0: return np.unique(data[0])[np.argmax(np.unique(data[0], return_counts=True)[1])] else: maxFeatureIndex = getMaxInfo(data, featureList) ...
The code evaluates a decision tree classifier's performance by repeatedly resampling training data (25% of input) to ensure each of 16 features has exactly 3 unique values. It builds a decision tree, tests accuracy on the remaining 75% data, and prints iteration number, tree size, and accuracy (5 iterations total). The...
def partA_1(df_): for iter in range(5): allDataCount = 3 # number of values featureList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16] count = 0 train_data = df_.sample(frac=.25) while True: if count == 16: break ...
def decisionTree(data, featureList): isPure = len(np.unique(data[0])) == 1 if isPure: return np.unique(data[0])[0] elif len(featureList) == 0: return np.unique(data[0])[np.argmax(np.unique(data[0], return_counts=True)[1])] else: maxFeatureIndex = getMaxInfo(data, featureList) ...
The code evaluates a decision tree classifier's performance by repeatedly sampling training data until all 16 features have exactly 2 unique values, then testing accuracy on the remaining data. It returns the tree size and accuracy percentage.
def partA2(random, df): featureList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16] allDataCount = 2 count = 0 train_data = df.sample(frac=random) while True: if count == 16: break count = 0 train_data = df.sample(frac=random) for index in range(...
def get_tutorial_information(tutorial: dict) -> list: """Get important attributes from a tutorial""" return [str(tutorial["_id"]).strip(), tutorial["title"].strip(), tutorial["language"].strip()] def get_gcf_tutorial_lesson_ids(tutorial: dict) -> list[str]: """Get the ids of the lessons of a tutorial""" # From th...
The function updates a tutorial's vector representation in a database by retrieving tutorial data and lesson content, converting HTML text to a vector, and storing it along with tutorial attributes.
def update_vector_by_id(db: Database, mongo_id: str) -> None: tutorial: dict = get_gcf_tutorial_by_id(db, mongo_id) tutorial_attributes = get_tutorial_information(tutorial) lesson_ids: list = get_gcf_tutorial_lesson_ids(tutorial) lessons_htmls: list = get_gcf_lessons_html(db, lesson_ids) plain_text_html: list = [r...
def adfuller_test(sales): try: result = adfuller(sales) except ValueError: return -1 labels = ['ADF Test Statistic', 'p-value', '#Lags Used', 'Number of Observations Used'] for value, label in zip(result, labels): print(label+' : '+str(value)) if result[1] <= ...
The main task of the code is to perform a grid search for optimal SARIMA model parameters on time-series sales data, ensuring stationarity through differencing, splitting data into training/test sets, updating the best parameters in a PostgreSQL database, and preparing for forecasting. It processes inputs, executes sta...
def user_inp_grid_search(item_id, firm_id, versa_sm): # time.sleep(10) print("Hi") # return 0 item_id = int(item_id) firm_id = int(firm_id) versa_sm1 = versa_sm versa_sm1['log_sales'] = np.log(versa_sm1['delta']).dropna() versa_sm.replace([np.inf, -np.inf],0 , inplace=True) # Calcul...