dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def possibleLetters(i, z, currentMoves): letterarray = [] currentMoves.append((i,z)) possibleMoves = [(1,0),(-1,0),(0,1),(0,-1),(1,1),(-1,-1),(-1,1),(1,-1)] for move in possibleMoves: if(minmax(i+move[0],z+move[1],currentMoves)): letterarray.append((i+move[0],z+move[1])) return l...
The function `validWords` recursively explores valid word paths in a grid by traversing a tree structure (`tn`). It checks if letters from the grid match node types in the tree, accumulates valid words (`accum`) and their paths (`accumpos`), and ensures words meet length requirements. It uses backtracking to explore al...
def validWords(it, tn, accumlet, accum, i, z, moves, accumpos, arr): PL = possibleLetters(i,z, moves.copy()) for nodes in tn.subnodes: lett = nodes.type for let in PL: lettF = arr[let[0]][let[1]] if(lett[0:1]==lettF): tempmoves = moves.copy() ...
def possibleLetters(i, z, currentMoves): letterarray = [] currentMoves2 = currentMoves.copy() currentMoves2.append(((i,z), False)) possibleMoves = [(1,0),(-1,0),(0,1),(0,-1),(1,1),(-1,-1),(-1,1),(1,-1)] for move in possibleMoves: if(minmax(i+move[0],z+move[1],currentMoves2)): let...
This function recursively generates valid words by traversing a tree structure (tn), checking possible letters (PL) at each position, accumulating valid word paths (accum) and their move sequences (accumpos), and storing words longer than 4 characters in a global list (bigwordl). It uses backtracking with depth (it) to...
def validWords(it, tn, accumlet, accum, i, z, moves, accumpos): global bigwordl PL = possibleLetters(i,z, moves.copy()) for nodes in tn.subnodes: lett = nodes.type for let in PL: lettF = arr[let[0]][let[1]] tempmoves = moves.copy() if(lett[0:1]==lettF): ...
def letterwordsthreads(num): threads = [None] * 16 results = [None] * 16 for i in range(len(threads)): threads[i] = Thread(target=letterwords, args=(num, results, i)) threads[i].start() for i in range(len(threads)): threads[i].join() return results def flatten(t): re...
The code generates a list of unique valid words by processing the output of `letterwordsthreads(maxNum)`, flattening nested structures twice, removing duplicates, and filtering words using `check_if_word(word)`. It returns the validated list of words.
def validWords(maxNum): returnArray = [] tra = [] returnArray = letterwordsthreads(maxNum) for u in range(2): returnArray = flatten(returnArray) returnArray = np.unique(returnArray).tolist() for word in returnArray: if(check_if_word(word)): tra.append(word) return...
def validWords(it, tn, accumlet, accum, i, z, moves, accumpos): global bigwordl PL = possibleLetters(i,z, moves.copy()) for nodes in tn.subnodes: lett = nodes.type for let in PL: lettF = arr[let[0]][let[1]] tempmoves = moves.copy() if(lett[0:1]==lettF): ...
The code generates valid words through a loop, processes them with image rendering (if export is True), filters and sorts unique words by length, and returns a list of the longest 15 unique words. It also optionally exports processed frames as a video.
def finalWords(radix, export): global bigwordl global bwl2 words = [] frames = [] wordl = [] for reps in range(16): i2 = int(reps % 4) z2 = int((reps - (reps % 4))/4) (v, uv) = validWords(100, topnode, "", [], i2, z2, [], []) xz = 0 for uvi in uv: ...
def _get_log_level_from_settings() -> int: log_level = os.getenv("LOG_LEVEL", "DEBUG") print(f'Value of "LOG_LEVEL" is: {log_level}') level_str = log_level.upper() if level_str == "DEBUG": log_level = logging.DEBUG elif level_str == "INFO": log_level = logging.INFO elif level_s...
The main task of the code is to configure and return a logging.Logger instance by retrieving environment variables for log name, format, and date format, setting the log level, creating a formatter, adding specified handlers with configured levels and formats, and logging an initialization message. It dynamically adjus...
def initialize_logger() -> logging.Logger: """""" print("Initializing Logger...") log_name = os.getenv("LOG_NAME", "scadmin_logger") root_logger = logging.getLogger(log_name) log_level = _get_log_level_from_settings() root_logger.setLevel(log_level) log_format = os.getenv( "LOG_F...
def create_pagerduty_header(): email = pagerduty_email() return { "Authorization": get_pagerduty_token(), "Accept": "application/vnd.pagerduty+json;version=2", "From": email, "Content-Type": "application/json" } def get_pagerduty_url(): return os.environ.get("pagerduty_u...
The main task of the code is to check if an incident with a specified title exists among PagerDuty's active incidents (statuses: "triggered" or "acknowledged"). If found, it adds a note to that incident and returns `True`; otherwise, it returns `False`.
def active_incident(title): header = create_pagerduty_header() url = get_pagerduty_url() + "incidents" active_incidents = { "statuses": ["triggered", "acknowledged"] } res = requests.get(url=url, headers=header, json=active_incidents) for i in res.json()["incidents"]: if i["tit...
def active_incident(title): header = create_pagerduty_header() url = get_pagerduty_url() + "incidents" active_incidents = { "statuses": ["triggered", "acknowledged"] } res = requests.get(url=url, headers=header, json=active_incidents) for i in res.json()["incidents"]: if i["tit...
The code raises a PagerDuty incident with a specified title and details if no active incident exists. It checks for an existing incident, constructs a JSON payload with a fixed service ID, and sends a POST request to PagerDuty's API. If successful (201 status), it confirms creation; otherwise, it returns the error resp...
def raise_pagerduty_incident(title, service=None, details=""): # Determines if the incident is currently active, add note only if active if active_incident(title): return "Incident already active in Pagerduty" else: # Incident is not yet existing header = create_pagerduty_header() ...
def wait_for_vespa(): print('PDF Import - Waiting for vespa application to be up') while not vespa_util.health_check(): time.sleep(0.5) print('PDF Import - vespa application is running - starting data import!') def find_files(folder, suffix=".pdf"): """ Recursively walk a folder and collect ...
(The main task of the code is to import PDF documents from a specified folder, process each page by converting it to images and thumbnails, extract text and layout data, generate metadata in JSON format, and feed this information into Vespa for indexing. The script handles file operations, error logging, and ensures da...
def main(): wait_for_vespa() parser = argparse.ArgumentParser() parser.add_argument("folder", type=str, help="the folder containing PDFs to import", default="data") args = parser.parse_args() files = find_files(args.folder) if not os.path.isdir(config.metadata_path): os.mkdir(config.me...
def handle_missed_days(today_utc, yesterday_utc, previous_date, previously_updated): missed_days = get_missed_days(today_utc.split(' ')[0], previous_date.split(' ')[0]) if not previously_updated: missed_days = [str(datetime.datetime.strptime(previous_date.split(' ')[0], '%Y-%m-%d') - datetime.timedelta(...
The main task of the code is to handle daily updates for scores and game data. It checks if yesterday's scores have already been processed, updates missed days if needed, resets daily scores, updates medals, and removes predictions. It interacts with a database to track the last update date and status, returning messag...
def daily_update(): """ Toys in the Attic, 1975 What does this do? Handles all updating, the big one """ fetched = db.postedscores.find_one() previous_date, had_scores = fetched['date'], fetched['scores_last_time'] current_unix_time = round(time.time()) today = datetime.datetime.utcf...
def find_prefix_path(basePat, TreeNode): Conditional_patterns_base = {} while TreeNode != None: prefixPath = [] FPTree_uptransveral(TreeNode, prefixPath) if len(prefixPath) > 1: Conditional_patterns_base[frozenset(prefixPath[1:])] = TreeNode.count TreeNode = TreeNode.nodeLink return Conditi...
The function `Mine_Tree` recursively extracts frequent itemsets from an FP-Tree by iterating through sorted header table items, constructing new itemsets, generating conditional pattern bases, building conditional FP-Trees, and recursively mining deeper patterns. It appends valid frequent itemsets meeting `minSupport` ...
def Mine_Tree(HeaderTable, minSupport, prefix, frequent_itemset): bigL = [v[0] for v in sorted(HeaderTable.items(),key=lambda p: p[1][0])] for basePat in bigL: new_frequentset = prefix.copy() new_frequentset.add(basePat) frequent_itemset.append(new_frequentset) Condition...
def get_wtg_inds(cropland_only, var, ds): if cropland_only and (var == "GRAINC_TO_FOOD_ANN" or "gridcell" in ds[var].dims): raise RuntimeError(f"{var} can't be used with cropland_only=True") dims = ds[var].dims if "pft" in dims: wtg = "pfts1d_wtgcell" inds = "pfts1d_gi" elif "gr...
This function processes time-series data from multiple experiments, handling variables with optional modifiers like ".CUMSUM". It validates mutually exclusive flags (e.g., rel_diff vs. abs_diff/y2y_diff), extracts relevant data subsets, shifts timestamps, and generates plots using make_ts_plot. The core task is to visu...
def process_and_make_plot( expt_list, ds, var_list, abs_diff, rel_diff, y2y_diff, cropland_only, rolling=None ): if isinstance(var_list, str): var_list = [var_list] if rel_diff and y2y_diff: raise RuntimeError("rel_diff and y2y_diff are mutually exclusive") if rel_diff and abs_diff: ...
def calc_probs(t_index, unique_inverse, label, b, b1, len_unique_a): """Calculate the p(x|T) and p(y|T)""" indexs = unique_inverse == t_index p_y_ts = np.sum(label[indexs], axis=0) / label[indexs].shape[0] unique_array_internal, unique_counts_internal = \ np.unique(b[indexs], return_index=False,...
This function calculates mutual information between variables using binned data and probability distributions. It computes probability estimates for binned data (p_ts), derives conditional probabilities (p_XgT, p_YgT), and calculates KL divergence (DKL_YgX_YgT) and entropy (H_Xgt) if requested. It ultimately returns lo...
def calc_information_sampling(data, bins, pys1, pxs, label, b, b1, len_unique_a, p_YgX, unique_inverse_x, unique_inverse_y, calc_DKL=False): bins = bins.astype(np.float32) num_of_bins = bins.shape[0] # bins = stats.mstats.mquantiles(np.squeeze(data.reshape(1, -1)), np.linspace(...
def printdeljtheta(network): print("deljtheta is") templist=[] for i in range(len(network)): templist.append([]) for j in range(len(network[i])): templist[i].append([]) for k in range(len(network[i][j].theta)): templist[i][j].append(network[i][j].deljt...
The code implements a neural network training algorithm using backpropagation. It initializes a network with specified hidden layers, computes forward and backward passes, updates weights via gradient descent, and iterates over epochs until the cost threshold is met. The function adjusts node parameters based on input-...
def neuralnet(inparr, outarr, hiddeninfo,learningrate, epochsize,costthres, sampletheta): numtrain = len(inparr) diminput= len(inparr[0]) dimoutput = len(outarr[0]) network=[] for i in range(len(hiddeninfo)): network.append([]) network.append([]) for i in range(len(hiddeninfo)): ...
def load_icons(self, files): icons = {} for file in files: icons[os.path.splitext(file)[0]] = QtGui.QIcon(icon_path+"/"+file) return icons def setup_widgets(self): #splitter between top and bottom widgets self.splitter = QtWidgets.QSplitter(QtCore.Qt.Vertical) ...
The code initializes a MainView class by setting up a panel, loading SVG icons, configuring UI widgets and layouts, establishing scene callbacks, and retrieving bookmarks from a session to build the application's interface and functionality.
def __init__(self, panel = None): super(MainView, self).__init__() self.panel = panel self.icons = self.load_icons(["add.svg", "jump.svg", "show_parms.svg", "file.svg", "delete.svg", "blank.svg", "internet.svg"]) self.setup_widgets() self.setup_layouts() self.setup_scene_...
def check_input_cmd(): ''' Function--Show the user the option list and keep prompting user to input until an integer number which is in the range from 1 to 5. This function might raise Valuerror when the input is not an integer or not in the right range. The error will ...
The main task of the code is to manage a maze game by allowing users to input/load a maze, find the closest exit, and display the solved path or original maze. It handles command-driven interactions, initializes game data, processes maze operations, and includes error handling for missing maze data or invalid operation...
def main(): cmd = check_input_cmd() while cmd != 5: if cmd == 1 or cmd == 2: # Intialize all the variables of the maze or # clear up the datas of the last game to begin a new game. width = height = start_row = 0 start_column = exit_row = exit_column = 0 ...
def render_siderbar(self, pages, select_label): st.sidebar.markdown("# Pages") self.page = st.sidebar.selectbox(f'{select_label}', pages) def render_data_page(self): location = author = hashtag = lang = polarity = user_mentions = None filters = st.sidebar.multiselect( label=...
The code renders a web application with a sidebar for navigation between two pages: "Data" and "Data Visualizations". It displays the selected page's content by calling respective methods (`render_data_page` for "Data" and `render_visulazation` for "Data Visualizations") after setting the title dynamically based on the...
def render(self): st.title(f"Welcome To {self.title}") self.render_siderbar(['Data', "Data Visualizations"], "select page: ") if (self.page == "Data"): st.title("Data") self.render_data_page() elif (self.page == "Data Visualizations"): st.title("Dat...
def browse_file(self, main_win, placement_x, placement_y): self.topframe = Frame(main_win, width=800, height=100) self.topframe.place(x=placement_x, y=placement_y) # position self.button = Button(self.topframe, text="Browse", bg="white", fg="black", height=1, width...
The code creates a GUI application using Tkinter to convert files, setting up windows, labels, and buttons for file selection, conversion settings, target location, and conversion initiation. It initializes UI elements with default texts and organizes them into frames for a structured interface.
def run(self): self.main_win = Tk() # main window is created == master self.main_win.geometry("800x600+100+100") # window size self.file_location_text = tk.StringVar() self.file_location_text.set("Select a file or Input a Website with Web Mode") self.convert_to_text = tk.Str...
def get_link_flag(self): link_flag_file = open(config.LINK_FLAG_FILE, "r") value = link_flag_file.read().splitlines()[0] link_flag_file.close() return value def generate_links(self, category): query = re.sub("([A-Z])"," \g<0>", category) query = query.replace(' ', '+') ...
The code generates and saves links for given categories by checking a flag, creating a directory, processing each category to generate links, writing them to files with camel-case names, and resetting counters. It ensures the output directory is clean by deleting existing files before creating new ones, then updates th...
def run(self, categories): link_flag = self.get_link_flag() if link_flag == "0": print("Skipping link generation\n") return print("Generating links\n") cwd = os.getcwd() download_path = cwd + '/' + config.LINKS_FOLDER if os.path.exists(download...
def initial(): engine = pyttsx3.init('sapi5') voices = engine.getProperty('voices') engine.setProperty('voice', voices[1].id) return engine def wishMe(): hour = int(datetime.datetime.now().hour) if hour>= 0 and hour<12: speak("Good Morning Sir !") elif hour>= 12 and hour<18: ...
The code listens for voice commands using a microphone, recognizes speech with Google's API, and redirects to specific web routes based on detected keywords like "login," "learn," or "play." If no match is found, it informs the user and reloads the home page.
def speech(): initial() while True: r=sr.Recognizer() with sr.Microphone() as source: r.adjust_for_ambient_noise(source) wishMe() speak("ok I am ready You can Speak now") audio = r.listen(source,phrase_time_limit=4) try: ...
def prepare(psi0): gates = [] for i,b in enumerate(psi0): if b=='1': gates +=[('X', i)] if b=='+': gates +=[('H', i)] if b=='-': gates +=[('X', i),('H', i)] return gates def print_psi(qc): for i,p in enumerate(qc.psi.to_dense().round(4)): ...
The code prepares a quantum state using a custom 'prepare' function, applies the Quantum Fourier Transform (QFT) to it, and analyzes the resulting state. It computes the partial trace of the density matrix for half the qubits and calculates the von Neumann entropy from this trace, demonstrating quantum state manipulati...
def main1(): n=8 qc = qtn.Circuit(n) qc.apply_gates(prepare(input())) print("PREPARED STATE:") print_psi(qc) qc.apply_gates(QFT(n)) print("OUTPUT STATE:") print_psi(qc) print(qc.psi.draw(color=['PSI0'])) print(qc.psi^...) print((qc.psi^...).draw(color=['PSI0'])) #prin...
def print_state(state, shorten=True, postfix=''): state = state.flatten() (size,) = state.shape size -= 1 print(f'{"#".rjust(len(str(size)))} {"state".ljust(size.bit_length()+2)} probability') for i,s in enumerate(state): if not shorten or s != 0: print(f'{str(i).rjust(len(str(si...
This function applies a quantum state transformation using a matrix derived from a path, optionally reversing the operation, then calculates the von Neumann entropy of the resulting state. Debug mode prints intermediate states and measurements.
def interpret(path, state_string, reverse = False, debug=False): if debug: print("before:") print_state(state) print_measurement(state) n, m = combine(path) if reverse: m = m.conj().T state = np.dot(state, m) if debug: print("after:") print_state(state...
def forward(self, data: torch_geometric.data.Batch) -> torch.Tensor: data.pos = data.pos[:, :self.dim] data.edge_attr = data.edge_attr[:, :self.dim] x = self.model.forward(data) return x.view(-1, *self.cell_map_shape, self.num_outputs_per_cell) def loss(self, model_output: torch.Tensor, ...
This training step computes model outputs, calculates a weighted loss from multiple functions, evaluates detection accuracy and mAP metrics, logs losses and metrics, then returns the loss for optimization. It processes ground-truth bounding boxes, applies NMS to outputs, and logs training performance metrics like loss,...
def training_step(self, batch: torch_geometric.data.Batch, batch_idx: int) -> torch.Tensor: outputs = self.forward(data=batch.clone()) # Compute loss, as weighted sum of multiple loss functions. gt_bb = getattr(batch, "bbox").to(self.device) gt_bb_batch = getattr(batch, "batch_bbox") ...
def forward(self, data: torch_geometric.data.Batch) -> torch.Tensor: data.pos = data.pos[:, :self.dim] data.edge_attr = data.edge_attr[:, :self.dim] x = self.model.forward(data) return x.view(-1, *self.cell_map_shape, self.num_outputs_per_cell) def detect_nms(self, model_outputs: torch.T...
The code performs a validation step by processing a batch through the model, detecting bounding boxes with NMS, comparing predictions to ground-truth boxes, computing loss, IoU, accuracy, and mAP metrics, then logging these values for evaluation. It accumulates metrics in a validation log dictionary for later aggregati...
def validation_step(self, batch: torch_geometric.data.Batch, batch_idx: int) -> torch.Tensor: outputs = self.forward(data=batch) detected_bbox = self.detect_nms(model_outputs=outputs) gt_bb = getattr(batch, "bbox").to(self.device) gt_bb_batch = getattr(batch, "batch_bbox") # Com...
def events(self): # handle events for event in pygame.event.get(): # check for closing window if event.type == pygame.QUIT: self.playing = False self.running = False elif event.type == pygame.KEYDOWN: if event.key == pyg...
The main task of the code is to manage the game loop, handling events, updating game state, and rendering graphics at a consistent frame rate (FPS) while the game is active. It runs continuously until the player dies or quits, controlled by the `self.playing` flag.
def run(self): # game loop # self.playing controls the current game (until you die or quit). # self.running controls the game window (until you hit ESCAPE or click "x") self.playing = True while self.playing: self.clock.tick(FPS) self.events() ...
def get_nondominated_consumption_choices(investment: InvestmentMinimal, resources: int): """ Assume: we can't pay over the discharge threshold for a given investment. If the investment cannot deliver a resource profit on the current turn, include every choice up to the discharge threshold. If the in...
The code implements a branch-and-bound algorithm to find the optimal investment path over a fixed number of time steps (`lookahead_steps`) that maximizes reward while adhering to resource constraints. It explores all possible paths through a set of investments, pruning non-viable options using bounds on resource and re...
def boundedly_optimise_max_investment( investments: set[InvestmentMinimal], resources: int, lookahead_steps: int ) -> ResourcePath: """ A branch-and-bound programming approach considering all optimal paths through time for a given level of total resource consumption. The search needs to be bounded by lo...
def get_arg_schemes_full_aif(json_path): cent = Centrality() graph, json_data = get_graph_json(json_path) ras = cent.get_ras(graph) ras_i_list = cent.get_full_ra_i_nodes(graph, ras) ra_changes = [] for ns in ras_i_list: ra_id = ns[0] conc_id = ns[1] conc_text = ns[2...
The function collects rules and scheme data from JSON files in a specified directory, merges them with corresponding 'hevy' rules from another path, and returns aggregated rule data and filtered scheme information.
def get_rules_data(rules_path, hevy_rules_path): data = [] rules = [] full_scheme_data = [] for subdir, dirs, files in os.walk(os.path.join(application.static_folder, rules_path)): for file_name in files: if '.json' in file_name and not 'hevy' in file_name: #base...
def parse_question(question_text): first_word = question_text.split()[0] domain = check_domain(question_text) return first_word, domain def get_search_type(question_type): question_type = question_type.lower() search_type = '' if 'is/are' in question_type or 'do/does' in question_type or 'has/h...
The main task of the code is to process user input text by parsing questions, generating hypotheses from JSON data, aggregating results, performing searches, and rendering web results. It loads spaCy models, traverses JSON files, combines hypotheses, calculates graph centrality, and returns rendered HTML with findings,...
def render_text(): text = session.get('text_var', None) first_word, context = parse_question(text) search_type = get_search_type(first_word) #context = 'militant' #20088_target nlp = spacy.load("en") overall_json = '' overall_hyp_explain = [] overall_hyp_list = [] overall_alt_...
def _build_similarity_matrix(sentences, stopwords=None): sm = np.zeros([len(sentences), len(sentences)]) for idx1 in range(len(sentences)): for idx2 in range(len(sentences)): if idx1 == idx2: continue sm[idx1][idx2] = _sentence_similarity(sentences[idx1], sentence...
The code identifies the top 3 most important sentences in the input text using PageRank algorithm on a similarity matrix of tokenized sentences, returning them as a summary. It tokenizes text, calculates sentence similarities, ranks sentences via PageRank, and extracts highest-ranked sentences for summary.
def analyze(text, stop_words=None): text_str = text sentences = sent_tokenize(text_str) tokenized_sentences = [word_tokenize(sent) for sent in sentences] similarity_matrix = _build_similarity_matrix(tokenized_sentences, stop_words) pr_vector = _run_page_rank(similarity_matrix) #st.write(pr_vecto...
def read_json(file): with open(file, 'r') as f: return json.load(f) def extract_player_props(data): keys_order = ["props_last_updated_at", "player_full_name", "position", "team_name", "opponent_team_name", "prop_type", "projection", "line", "over", "under"] player_props_list = [] ...
The main task of the code is to locate the latest 'pff_prop_bets' JSON file, parse its player prop data, standardize position abbreviations using a database connection, and insert/update the processed data into a database. It ensures data consistency by matching key-value structures, handling file sorting, and executin...
def main(): conn = create_connection() # Pattern to match files like file_pattern = re.compile(r'pff_prop_bets.*\.json$') matched_files = [f for f in os.listdir('.') if file_pattern.match(f)] if not matched_files: print("No matching 'pff_prop_bets' file found in the directory.") r...
def add_to_link_dict(response, title_to_link_dict): """Adds the title as a key to a title-to-link dictionary, with the url as the value; the input is the requests.get object for the url Parameters ---------------- response : requests.get object The result of a request to a Wikipedia pa...
This function performs a breadth-first search starting from a given Wikipedia URL, exploring outward up to a specified depth. It updates three dictionaries in-place: graph_dict (tracking links from "See Also" sections), text_to_link_dict (mapping page titles to URLs), and category_dict (recording categories). It collec...
def bfs_search(url, dictionaries, depth=3): """Starting at a given url, searches outward to a depth of depth and adds the linkage data to a dictionary Parameters --------------- url : str The url of a Wikipedia page dictionaries : List A list of dictionaries, graph_dict, te...
def check_if_sequences_file_exists(sequences_file_path: Path): if not sequences_file_path.is_file(): file_not_found_message = "FASTA Sequences File not Found!" raise FileNotFoundError(file_not_found_message) def check_if_sequences_file_has_fasta_extension(sequences_file_path: Path): if get_seque...
This function validates a FASTA sequences file by checking its existence, correct file extension, presence of valid description lines, absence of invalid description lines, and ensuring it contains data. It performs multiple checks to confirm the file adheres to FASTA format standards, including verifying line counts a...
def check_if_is_valid_fasta_sequences_file(sequences_file_path: Path): check_if_sequences_file_exists(sequences_file_path) check_if_sequences_file_has_fasta_extension(sequences_file_path) description_lines_count, invalid_description_lines_count, lines_count = \ get_sequences_file_counters(sequences_...
def check_if_is_valid_number_of_arguments(number_of_arguments_provided: int): if number_of_arguments_provided != 2: invalid_number_of_arguments_message = "Invalid Number of Arguments Provided! \n" \ "Expected: 1 Argument (FASTA Sequences File). \n" \ ...
The main task of the code is to split a FASTA-formatted sequences file into individual sequence files, validate input parameters, extract sequence data, and generate an index list of the resulting files. It processes command-line arguments, checks file validity, reads sequence data, and writes output files with proper ...
def main(argv: list): # BEGIN # GET NUMBER OF ARGUMENTS PROVIDED number_of_arguments_provided = len(argv) # VALIDATE NUMBER OF ARGUMENTS PROVIDED check_if_is_valid_number_of_arguments(number_of_arguments_provided) # GET SEQUENCES FILE PATH sequences_file_path = Path(argv[1]) # VALIDA...
def store_country_capital(country_name, capital_name): cursor = db_connection.cursor() cursor.execute("INSERT INTO country_capital (country_name, capital_name) VALUES (%s, %s)", (country_name, capital_name)) db_connection.commit() cursor.close() def speak(text): tts = gTTS(text=text, lang='en') ...
This code processes voice commands to perform tasks like storing/updating/deleting country-capital data, retrieving information, handling greetings, time/date queries, calculations, and web actions. It uses conditional checks to identify commands, extracts relevant data, and triggers corresponding functions or response...
def process_command(command): if "store country capital" in command: # Extract country and capital information from the command # Assuming command format: "store country capital [country] [capital]" _, _, _, country_name, capital_name = command.split(maxsplit=4) store_country_capital...
def speak(text): tts = gTTS(text=text, lang='en') tts.save("response.mp3") os.system("start response.mp3") # Wait for the duration of the audio file time.sleep(get_audio_duration("response.mp3")) def get_audio(): recognizer = sr.Recognizer() # Define the recognizer object with sr.Microphone...
The code defines a voice assistant that continuously listens for user commands, converts audio input to text using Google's Speech Recognition, processes the recognized commands, and handles unrecognizable input by prompting the user to repeat.
def main(): recognizer = sr.Recognizer() speak("Hello! I am your voice assistant") while True: # Continuously listen for user commands audio_input = get_audio() try: command = recognizer.recognize_google(audio_input).lower() # Convert audio input to text using Google's S...
def ExitEditDeleteUI(self): self.ui.pushButtonEdit.setVisible(True) self.ui.pushButtonDelete.setVisible(True) self.ui.pushButtonCancel.setVisible(False) self.ui.pushButtonSave.setVisible(False) self.ui.lineEditNameSearch.setEnabled(True) self.ui.lineEditEmailSear...
The main task of the code is to handle the "Save" operation by applying edits or deleting rows based on the `self.action` value, then resetting the UI state. It prints a message, exits an edit/delete UI, executes the relevant action (Edit/Delete), clears the action flag, and deselects the table widget to finalize the s...
def OnSave(self): print("Saving changes") self.ExitEditDeleteUI() if self.action == "Edit": self.ApplyEdits() elif self.action == "Delete": self.DeleteRows() self.action = "" self.ui.tableWidgetLoginData.clearSelection()
def __elitism_selection(self, elite_percentage): fitness_values = self.get_fitness_values() maintain = int(self.population_number*elite_percentage) arg_indexes = np.argsort(fitness_values)[:maintain] elite_individuals = self.individuals[arg_indexes] return elite_individuals def _...
This function applies genetic operators to generate a new population by selecting elite individuals, mutating some, and creating children via crossover. It ensures percentages of elites, mutants, and children sum to 1, then combines them into the population.
def genetic_operators(self, elite_percentage, children_percentage, mutant_percentage): assert elite_percentage+children_percentage+mutant_percentage == 1, 'The percentages sum must be equals to 1' elite_individuals = self.__elitism_selection(elite_percentage) mutant_individuals = self.__mutate(m...
def residence_maintenance(state): """Maintain a residence in need of maintenance Args: state (GameState) - The current game state """ if len(state.residences) < 1: return False residence = min(state.residences, key=lambda x: x.health) blueprint = GAME_LAYER.get_residence_bluepr...
The code defines a game strategy function that evaluates the current game state and prioritizes actions in a specific order. It checks conditions like maintenance, regulation, temperature control, construction, and placement of utilities/residences, executing the first applicable action. If none apply, it waits. The co...
def strategy(state): """Main logic/strategy for game plan. Args: state (GameState) - The current game state """ # Take one of the following actions in order of priority # if residence_maintenance(state): pass elif residence_regulator(state): pass elif regulate_temper...
def __getHint(self) -> str: return self.__driver.find_element(By.ID, "currentWord").get_attribute("textContent") def __cleanGuesses(self, guesses: List[str], wordToGuess: str) -> None: for guess in guesses: if self.__guessNotMatchesHint(guess, wordToGuess): guesses.remove(gue...
The main task of the code is to manage a guessing process in a game by selecting and submitting guesses based on hints. It retrieves potential guesses, filters them iteratively using updated hints, and submits the first valid guess from the list. If a narrow guess is identified, it finalizes the process. The loop conti...
def Guess(self) -> None: print("time to guess.") if self.exaustedGuesses: return numHints: int = 0 wordToGuess: str = self.__getHint() guesses: List[str] = self.__wordDictionary.GetBestRandomGuess(wordToGuess) # TODO maybe this breaks because i pass wordTOGues...
def fold_lc(times,fluxes,errs,Pfold): phases=(np.array(times)/Pfold)%1 isort=np.argsort(phases) phases=phases[isort] fluxes=np.array(fluxes)[isort] errs=np.array(errs)[isort] nold=len(times) groupwidth=(times[-1]-times[0])*(1+0.1/nold)/nold/Pfold groupwidth*=1.0 #print('mean errs=',e...
The function analyzes light curves of stars to detect periodic variability, estimate signal-to-noise ratios (SNR) of potential transit signals, and fit astrophysical models. It queries stellar properties (TIC catalog), normalizes light curves across sectors, identifies dominant periods via Lomb-Scargle analysis, folds ...
def g(id,lcs,fit=False,method='loop',useM=True,massTol=0,lensMax=0,eMax=0,doGAIA=False,maxperiod=14,skipGiants=False,minCycles=0,SNRonly=False): if 'id' in lcs: data=lcs[lcs['id']==id].copy() else: #assume just one lightcurve data=lcs try: TICData = Catalogs.query_object(str(id),rad...
def find_imsmanifest_root(self, imsmanifest): """ Read imsmanifest.xml into an element tree, find root. Args: imsmanifest - full path for imsmanifest file Returns: Root element of imsmanifest document's tree """ tree = ElementTree.parse(imsmanifest) root = tree.getroot() root_attribs = root.attrib ...
The main task of the code is to parse an IMS manifest file, extract structured data such as course metadata, resources, and organizational hierarchy, and pass this information to a builder object to construct a product. The method processes input by identifying key elements like course name, code, version, instructor, ...
def process(self): """ Parse input, pass data to builder for construction of product. """ root = self.find_imsmanifest_root(self.imsmanifest) item_parent_map = self.map_parents_items(self.imsmanifest) organizations = self.read_organizations(root, item_parent_map) resources = self.read_resources(root) m...
def push_math_buttons(self, symbol): self.value += symbol if (self.total_value == "" or self.total_value != "" and self.value not in self.symbols[1]): self.total_value += self.value # elif self.total_value[-1] in self.symbols: else: new = self.total_value.replace(...
The code creates math operation buttons in a GUI, looping through symbol lists to generate buttons with specific commands for mathematical functions, positioning them in a grid layout for organized display and interaction.
def create_math_buttons(self): i = 1 for symbol in self.symbols[1]: tk.Button(self.buttons_frame, text=symbol, font=BUTTONS_FONT, command=lambda symbol=symbol: self.push_math_buttons(symbol)).grid(row=i, column=3, sticky=tk.NSEW) i += 1 i = 1 for symbol in self.s...
def create_window_frame(self): frame = tk.Frame(self, height="150") frame.pack(expand=True, fill="both") return frame def create_buttons_frame(self): frame = tk.Frame(self) frame.pack(side="top", expand=True, fill="both") return frame def create_system_frame(self): ...
This code initializes a calculator GUI with support for multiple number systems (binary/decimal). It sets up digit/symbol mappings, creates UI frames, labels, and buttons for input/output, arithmetic operations, and system selection, configuring grid layouts for responsive button placement and interface elements.
def __init__(self, parent, controller): tk.Frame.__init__(self, parent) self.value = "" self.total_value = "" self.digit_systems = ['dec', 'bin'] self.digits = { 1:(1,1), 2:(1,2), 3:(1,3), 4:(2,1), 5:(2,2), 6:(2,3), 7:(3,1), 8:(3,2), 9:(3,3)...
def create_window_frame(self): frame = tk.Frame(self, height="150") # frame.grid(row=0, column=0, sticky=tk.NSEW) frame.pack(expand=True, fill="both") return frame def create_buttons_frame(self): frame = tk.Frame(self) # frame.grid(row=1, column=0, sticky=tk.NSEW) ...
This code initializes a calculator GUI interface by setting up a frame, configuring grid layouts for digit and symbol buttons, creating display labels, and generating buttons for numbers, operations, equals, and clear functions. It organizes the UI structure and prepares components for arithmetic input and calculation.
def __init__(self, parent, controller): tk.Frame.__init__(self, parent) self.value = "" self.total_value = "" self.digits = { 1:(1,0), 2:(1,1), 3:(1,2), 4:(2,0), 5:(2,1), 6:(2,2), 7:(3,0), 8:(3,1), 9:(3,2), ".":(4,0), 0:(4,1) } ...
def create_window_frame(self): frame = tk.Frame(self, height="150") # frame.grid(row=0, column=0, sticky=tk.NSEW) frame.pack(expand=True, fill="both") return frame def create_buttons_frame(self): frame = tk.Frame(self) # frame.grid(row=1, column=0, sticky=tk.NSEW) ...
This code initializes a GUI calculator interface by setting up a frame with digit and symbol buttons, configuring grid layouts, and creating labels and buttons for input and operations. It defines positions for digits (1-9, 0, .) and mathematical symbols (operators, functions) using dictionaries. The interface includes...
def __init__(self, parent, controller): tk.Frame.__init__(self, parent) self.value = "" self.total_value = "" self.digits = { 1:(1,0), 2:(1,1), 3:(1,2), 4:(2,0), 5:(2,1), 6:(2,2), 7:(3,0), 8:(3,1), 9:(3,2), ".":(4,0), 0:(4,1) } ...
def util_db_open_conn_sess(param_sqlalch_conn_url): """ create sqlalch engine,connection,session maker and get session after check database exists Args: :param param_sqlalch_conn_url: the database connection url Returns :rtype: sqlalchemy session object and engine object """ try...
The main task of the code is to initiate telnet connections for devices retrieved from a database, using a function that reads device data and establishes communication. It opens a database connection, calls a telnet connection/read function with device-specific parameters, then closes the database session. The functio...
def app_start_listeners(): """ start a telnet listener for all devices retrieved from the db Returns: :rtype|list: list of threads """ # open db connection db_conn_engine,db_conn_session = util_db_open_conn_sess(CONST_DATABASE_URL) app_telnet_connect_and_read( devic...
def ping_device(param_device_id, param_device_address): # Ping the device to see if it is up before trying to telnet to it. # print("Pinging Telnet device...") # ping_cmd = "ping -c 1 -W 3 " + param_device_address # ping_device = os.system(ping_cmd) resp = ping(param_device_address, count=1, timeout...
The code initializes and runs a Data Acquisition (DAQ) application for a specified device. It clears the terminal, checks device reachability via ping, sets initial global variables, and starts a loop to continuously connect via Telnet and read data from the device. The main task is to ensure data collection from the d...
def run(): """ run main """ os.system("clear") print("\nStarting Data Acquisition (DAQ) App for DeviceID: " + str(deviceID) + "\n") # Check that the device is reachable ping_device(deviceID, param_device_address=READ_DEVICES[deviceID]) # Set startup global variables set_global_...
def ping_device(param_device_id, param_device_address): # Ping the device to see if it is up before trying to telnet to it. print("Pinging device...") ping_cmd = "ping -c 1 -W 3 " + param_device_address ping_device = os.system(ping_cmd) if not ping_device == 0: count = 10 print("Devi...
The code initializes a data acquisition process for a specific device, sets global extruder counters, and starts listeners. It clears the screen, prints a start message, pings the device, initializes global variables with extruder counts, and triggers listener functions for data monitoring.
def run(): """ run main """ os.system("clear") print("\nStarting Data Acquisition App for DeviceID: " + str(deviceID) + "\n") ping_device(deviceID, param_device_address=READ_DEVICES[deviceID]) exc_box_last, exe2_box_last, exc_db_last, exe2_db_last = app_set_global_extruder_counts() globa...
def get_chart_asset_from_url(chart_asset_url): chart_zip = os.path.join(outdir, 'chart.zip') shutil.rmtree(chart_zip, ignore_errors=True) subprocess.check_call(['aws', 's3', 'cp', chart_asset_url, chart_zip]) chart_dir = os.path.join(outdir, 'chart') shutil.rmtree(chart_dir, ignore_errors=True) ...
(The main task of the code is to handle CloudFormation events for deploying/updating/uninstalling Helm charts in an EKS cluster. It processes `Create`, `Update`, and `Delete` requests, configures kubeconfig with AWS EKS, manages chart sources (S3, OCI, local), generates values files, and executes Helm commands with spe...
def helm_handler(event, context): logger.info(json.dumps(dict(event, ResponseURL='...'))) request_type = event['RequestType'] props = event['ResourceProperties'] # resource properties cluster_name = props['ClusterName'] role_arn = props['RoleArn'] release = props['Rele...
def connect(): # Implement Code my_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) my_socket.connect((SERVER_IP, SERVER_PORT)) return my_socket def login(conn): server_cmd = "ERROR" server_msg = "" while(server_cmd != "LOGIN_OK" and server_msg != "You are already connected"): ...
The main task of the code is to manage user interactions for a system requiring login authentication. It enforces users to log in first before performing actions like retrieving scores, playing questions, checking high scores, or viewing logged users. The loop continues processing user actions until "logout" is selecte...
def main(): conn = connect() choose_action = input("Please enter one action from the options: \n" + "options: login, logout, get score, play question, get highscore, get logged users \n") while choose_action != "login": print("you have to login before you can do any other actions") choose_a...
def setup_socket(): """ Creates new listening socket and returns it Recieves: - Returns: the socket object """ # Implement code ... server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_socket.bind((SERVER_IP, SERVER_PORT)) print(f"SERVER IS UP ON PORT {SERVER_PORT...
The main task of the code is to create a trivia server that initializes user and question databases, manages client connections via sockets, processes incoming messages using a select-based event loop, and handles client interactions including message parsing, handling, and broadcasting. It continuously accepts new con...
def main(): # Initializes global users and questions dicionaries using load functions, will be used later global users global questions global open_client_sockets print("Welcome to Trivia Server!") conn = setup_socket() questions = load_questions() users = load_user_database() whil...
def sortingEdges(graph): #sorting using bruteforce method for i in range(len(graph)): min = graph[i][2] index = i #initial index of min edge for j in range(i+1,len(graph)): # find max if min > graph[j][2]: min = graph[j][2] index = j ...
The code implements Kruskal's algorithm to compute the Minimum Spanning Tree (MST) of a graph. It processes an adjacency matrix, extracts unique edges, sorts them by weight, and uses Union-Find to detect cycles. It iteratively selects edges, adding them to the MST if they connect disjoint sets, until the MST contains a...
def KruskalMST(graph): '''KrusalMST will find minimum spaning tree with input adjacency matrix ''' #stop duplicate (1 -- 4, w: 6 the same with 4 -- 1, w: 6) #we stop by do u -- v with u < v (u is start vertice and v is end vertice) newGraph = [] for i in range(len(graph)): for j in range...
def _update_players(self): fires = filter(lambda i: i.type == "fire", self.items.copy().values()) players = self.players.values() for player in players: if player.is_dead(): continue # update fire for fire in fires: if player....
The code's main task is to orchestrate three update processes: updating player states, managing item-related changes, and advancing the current round's progression. This method likely serves as a central coordinator in a game or simulation system, ensuring all critical components (players, items, round logic) are synch...
def update(self): self._update_players() self._update_items() self._update_round()
def squareUnderAttack(self, r, c): self.whiteToMove = not self.whiteToMove #switch to opponents turn oppMoves = self.getAllPossibleMoves() self.whiteToMove = not self.whiteToMove #switch turn back for move in oppMoves: if move.endRow == r and move.endCol == c: #square under a...
The main task of the code is to generate valid castling moves for a king in a chess game. It checks if the current square is under attack, then verifies castling rights (kingside/queenside) based on the player's turn. If conditions are met, it calls helper methods to add corresponding castling moves to the list, ensuri...
def getCastleMoves(self, r, c, moves): if self.squareUnderAttack(r, c): return #cant castle while in check if (self.whiteToMove and self.currentCastlingRights.wks) or (not self.whiteToMove and self.currentCastlingRights.bks): self.getKingsideCastleMoves(r, c, moves) if (s...
def checkForPinsAndChecks(self): pins = [] checks = [] in_check = False if self.whiteToMove: enemyColor = "b" allyColor = "w" startRow = self.whiteKingLocation[0] startCol = self.whiteKingLocation[1] else: enemyColor = "...
This function generates valid chess moves by checking for pins, checks, and castling rights. It filters moves to ensure the king isn't exposed to check, handles single/double check scenarios, and determines checkmate/stalemate outcomes. It returns all legal moves considering the current game state, including castling a...
def getValidMoves(self): tempCastleRights = CastleRights(self.currentCastlingRights.wks, self.currentCastlingRights.bks, self.currentCastlingRights.wqs, self.currentCastlingRights.bqs) #copy current castle rights moves = [] self.in_check, self.pins, self.checks = self.checkForPinsAndChe...
def shutdown(self): """Gracefully shuts down the client""" self.socket.close() self.state.shutdown_signal.clear() self.state.connect_signal.clear() self.state.client.is_connected = False print("shutting down gracefully") exit(0) def connect(self): """Estab...
The main task of the code is to orchestrate the client's functionality by connecting to a server, sharing the clipboard, and handling shutdowns triggered by errors (e.g., ConnectionError, socket errors) or shutdown signals, ensuring proper termination and state updates.
def run(self): """Main method orchestrating the client's functionality""" if self.state.shutdown_signal.is_set(): self.shutdown() try: # Connect to server self.connect() print("connected") self.state.client.is_connected = True ...
def get_last_pr(symbol): client = Client(api_key, api_secret, base_url='https://api.binance.com') response = client.ticker_price(symbol) last_pr = round((float(response['price'])), 2) return last_pr def place_oco_order(symbol, qty, order_pr, last_pr): # TAKE PROFIT price ...
The code processes filled buy orders from a trading message, checks if they match a user-selected coin pair (or all pairs), extracts order details like quantity and price, retrieves the latest market price, and places corresponding OCO, Take Profit, or Stop Loss orders based on the original order type.
def listen_to_filled_orders(message): try: # get order type order_type = message['e'] # if order was executed if order_type == 'executionReport': order_status = message['X'] side = message['S'] if order_status == 'F...
def get_interval(pattern, read_seq): intervals_lst = [] repeat_lst = [] start_previous, end_previous = 0, 0 for inds, repeat_inds in enumerate(re.finditer(pattern, read_seq)): start, end = repeat_inds.span() if inds == 0: repeat_lst.append([read_seq[start:end]]) ...
This function calculates the copy number of a repeating allele from a list of reads based on a given pattern. It processes each read to identify intervals, determines repeat intervals, and computes the copy number by dividing the maximum repeat interval length by the pattern length. If coverage is insufficient (≤10 rea...
def func_get_repeat_allele(read_lst, pattern): copy_number_lst = [] if len(read_lst) <= 10: ## coverage return copy_number_lst for read_ind, read_seq in enumerate(read_lst): intervals_lst, repeat_lst = get_interval(pattern, read_seq) if len(intervals_lst) > 1: ...
def read_datestamped_data_file( file_path: str, filename: Union[str, float], file_ending: str, file_choice: Literal['latest', 'all'], read_function: Callable, **kwargs, ) -> Union[list, dict, pd.DataFrame]: ''' Read in data from a datestamped spreadsheet, flat file or pickle ...
This function reads data from files with various formats (CSV, ODS, TXT, XLSX, PKL) and optional date-stamping. It determines the appropriate reading method based on the file extension and date_stamped flag, delegating to helper functions or pandas methods like read_pickle. It returns the parsed data as a list, dict, o...
def read_data_file( file_path: str, filename: Union[str, float], file_ending: str, date_stamped: bool = False, **kwargs, ) -> Union[list, dict, pd.DataFrame]: ''' Read in data from spreadsheet, flat file or pickle Parameters file_path: Path to folder file...
def writeObjectProperties(self): self.writeHashTagSeparator("Object Properties") for _ , d in self.domains.items(): for v in d.vars: self.fileOutOWL.write("# Object Property: :" + v + " (:" + v + ")\n\n") self.fileOutOWL.write("FunctionalObjectProperty(:" + v ...
This code converts an F2CSP input file into an OWL ontology by parsing domains, variables, and constraints. It writes OWL prefixes, declares classes (Domains, Fml, Var), object properties, and named individuals based on input data, then outputs the structured ontology to a .owl file.
def run(self): self.inFileName = input("Enter F2CSP file name:") self.outFileName = input("Enter output file name:") self.fileOutOWL = open(self.outFileName + ".owl","w+") self.fileOutOWL.write("Prefix(:=<http://www.semanticweb.org/grupo21/ontologies/2019/4/grupo21#>)\n") self.fi...
def do_line_segments_intersect(line1_start, line1_end, line2_start, line2_end): """ Check if two line segments intersect. Parameters: line1_start (tuple): A tuple representing the starting point of line segment 1. line1_end (tuple): A tuple representing the ending point of line segment 1. ...
The main task of the code is to determine whether two polygons overlap by checking if their edges intersect, if one polygon is entirely inside the other, or if any vertex of one polygon lies inside the other. It returns `True` if any of these overlap conditions are met, otherwise `False`.)
def do_polygons_overlap(polygon1, polygon2): """ Check if two polygons with different numbers of vertices overlap. Parameters: polygon1 (list): A list of tuples representing the vertices of polygon1. polygon2 (list): A list of tuples representing the vertices of polygon2. Returns: ...
def component_exists(path: Union[str, Path]) -> bool: """ Returns true if the given path exists, as well as the `path + ".done"` file, which indicates that the component has been downloaded and verified. """ return Path(path).exists() and done_path(path).exists() def mark_done(path: Union[str, Path]...
The main task of the code is to download a file from a specified URL to a given path, with optional checksum verification. If the initial download fails, it recursively attempts mirrors. It ensures the file is only downloaded if not already present (unless forced) and creates necessary directories. The function handles...
def download( url: str, out_path: Union[str, Path], mirrors: List[Union[str, Path]] = None, checksum=None, force=False, ): """Downloads a file to out_path, and optionally checks its sha_256 checksum. If any mirrors are provided, it will attempt to download from each of these if the ...
def redux_result_column(result, columns, remove_anomoly): new_dict = {} for column in columns: if "." in column: two_part_key = column.split(".") if two_part_key[0] in result['_source'].keys(): if two_part_key[1] in result['_source'][two_part_key[0]].keys(): ...
The function processes a list of results by reducing each to specified columns, converts the processed list into a dictionary, and updates data using the provided parameters. It applies column filtering, structure transformation, and data updating steps to refine and store the results.
def redux_results(results,index,columns,path2result,postfix): new_list = [] for result in results: new_list.append(redux_result_column(result, columns)) new_dict = redux_list2dict(new_list, columns) redux_updater(new_dict,index,columns,path2result,postfix)
def redux_result_column(result, columns): new_dict = {} for column in columns: if column.split('.')[0] in result['_source'].keys(): if column.split('.')[1] in result['_source'][column.split('.')[0]].keys(): new_dict[column] = result['_source'][column.split('.')[0]][column.spl...
The function `redux_results` processes a list of results by applying a column reduction to each item, converts the processed list into a dictionary structure, and then updates a data structure using the dictionary, specified index, and columns.
def redux_results(results, index, columns): new_list = [] for result in results: new_list.append(redux_result_column(result, columns)) new_dict = redux_list2dict(new_list, columns) redux_updater(new_dict, index, columns)
def time_update(refresh_time, original): current_time = time.time() if (current_time - refresh_time) > 60: updated = current_time - original print("//SEARCH STILL RUNNING//", updated,"SECs//") refresh_time = current_time return refresh_time def nonstd_redux_results(results,index,colu...
This function retrieves large Elasticsearch query results using scroll search, processes each batch to reduce anomalies (nonstd_redux_results), aggregates results into a dictionary, and cleans up scroll context. It iterates through paginated data, combines processed results, and returns the final consolidated output wh...
def long_nonstd_search(es,es_index,query_body,columns,remove_anomoly): original_start_time = time.time() refresh = time_update(original_start_time, original_start_time) elastisearch_results=es.search(index=es_index,query=query_body, scroll='5m',size=max_size) results =...
def json2dict(filename): data = {} try: with open(filename) as json_file: data = json.load(json_file) except: dict2json(data, filename) return data def nonstd_search_day(es,index,query_body,day,columns,remove_anomoly): es_index = index + day day_start_time = time.time...
The code performs a multi-day Elasticsearch search using boolean queries to filter data based on an IP whitelist and query terms. It aggregates results across specified days, saves intermediate data to a temporary JSON file, and returns the compiled results if non-empty. The function handles query construction, iterati...
def nonstd_search(es_node, index, days, query_list, ip_whitelist, columns,remove_anomoly): es = Elasticsearch(es_node, timeout=30000) print("Searching for Desired Fields") print("//STARTING SEARCH FOR PLEASE WAIT//") days_start_time = time.time() logging.getLogger('elasticsearch').setLevel(logging.E...
def remove_random_nodes(graph, num_nodes): while graph.number_of_nodes() > num_nodes: graph = remove_random_node(graph) return graph def add_random_nodes( graph, num_nodes, id_node_start, number_label_node, number_label_edge, min_edges, max_edges, ): graph_nodes = graph....
The function generates a non-isomorphic subgraph from an input graph by randomly sampling nodes, adjusting node/edge counts, modifying edges, and ensuring the subgraph differs in structure from the original through iterative checks and random alterations.
def generate_noniso_subgraph( graph, no_of_nodes, avg_degree, std_degree, number_label_node, number_label_edge, *args, **kwargs ): graph_nodes = graph.number_of_nodes() node_ratio = no_of_nodes / graph_nodes if node_ratio > 1: node_ratio = 1 min_edges = int(no_of...
def _isatomic(subex): return isinstance(subex, _AtomicType) def _num_toks_in_tree(tree): ''' Return number of tokens in tree. ''' return (1 if _isatomic(tree) else 1 + _num_toks_in_tree(tree[1]) + _num_toks_in_tree(tree[2])) def _range(toklis, pos): ''' Return left and right range as pair. ...
This function recursively checks if a parse tree's token range matches specified bounds. It validates that the tree's structure spans exactly from position rfrom to rto in the token list, ensuring both subtrees also adhere to their respective range constraints through recursive calls.
def _is_range_correct(toklis, tree, rfrom, rto): ''' Given a list of tokens and a tree for this list, is the tree 'range correct'? rfrom and rto are the start and the end position (one based) in toklist for tree. The function is recursive. At start, rfrom = 1 and rto = len(toklis). ''' ...
def _makebintrees(toklis): ''' Create a list of all possible binary trees from a valid token list. ''' if not toklis or _isatomic(toklis) or len(toklis) % 2 == 0: # This should not happen: print("Creation of all parse trees not possible. Invalid argument.") return None if len(to...
This function checks all possible parse trees for a given token list, verifying their weight and range correctness. It prints parse trees, highlighting correctness status, ensuring only one valid parse exists. For multiple trees, it filters and displays results based on token length constraints, indicating which are we...
def _check_all_parsings(toklis): ''' Helper function for 'run_parser': print possible parse trees for toklis, check for correctness. Does not depend on the parse result. ''' if not (all_parse_trees := _makebintrees(toklis)): return if (nppt := len(all_parse_trees)) == 1: print("...
def tokenizer_a(code): ''' Standard tokenizer, to be used with 4 out of the 9 standard parsers. Return a tokenizer function. ''' toklist = list(tokenizer_e(code)) pos = 0 # Initialise state def toks(advance=0): ''' Function to be returned by tokenizer_a. ''...
This function prints parse results of a given code, including the parse tree, correctness checks (weight and range), and token positions. It adjusts output detail based on the 'quiet' parameter, which controls verbosity, and the 'upsidedown' flag for tree display orientation. It also returns 0 or 1 to indicate if the p...
def _print_result(res, res1, quiet, code, upsidedown): ''' Print parse results. Output depends on 'quiet' and 'upsidedown', it may include parse tree, all possible parsings, correctness. res -- parse result (tree), possibly without virtual tokens res1 -- parse result with vir...
def _prepare_command(): ''' Prepare command line arguments for 'run_parser'. Caution: Values of global dicts LBP, RBP can be changed here. ''' valid = True random_or_cl_defined = False # option -r or -d in effect? options_valid, options, quiet, start_of_args, upsidedown = _get_options()...
The `run_parser` function serves as a test driver for evaluating parsers that follow a specific format ("pcp*0*.py"). It executes a given parsing function (`parsefun`) using a specified tokenizer, handling error cases like `KeyError`, `IndexError`, and `TypeError`. The function prepares input data, configures operator ...
def run_parser(parsefun, tokenizer, fake_tokens_inserted=True): ''' Test driver for standard basic parsers (parsers matching "pcp*0*.py"). parsefun -- High level parse function, as defined in parser module. tokenizer -- Tokenizer to be used for parsefun (one of tokenizer_a ...
def connect(): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((exchange_hostname, port)) return s.makefile("rw", 1) def write_to_exchange(exchange, obj): json.dump(obj, exchange) exchange.write("\n") def read_from_exchange(exchange): return json.loads(exchange.readline()) def pr...
The code connects to a financial exchange, sends a "hello" message with the team name, and enters a loop to process incoming messages. It checks for bond data in `bondBook` and triggers the `penny_pinching` function to place bond orders, incrementing `order_id` each iteration. The main task is to interact with the exch...
def main(): order_id=0 exchange = connect() write_to_exchange(exchange, {"type": "hello", "team": team_name.upper()}) hello_from_exchange = read_from_exchange(exchange) # A common mistake people make is to call write_to_exchange() > 1 # time for every read_from_exchange() response. # Si...
def C_name(self): return self.module_name() def indent(s, n): lines = s.split("\n") return "\n".join((" " * n) + line for line in lines) def C_constructor(self, implem = False): if implem: prefix = self.C_name() + "::" else: prefix = "" args = ", ".joi...
The main task of the code is to generate a C++ class definition string that includes shader program members, framebuffer objects, and method declarations for construction, data retrieval, and rendering. It structures the class with public constructors/getters and private member variables, returning the fully formatted ...
def C_class(self): program_members = "\n".join(s.C_name() + " m" + s.C_name() + ";" for s in self.shaderlist) framebuffer_members = "\n".join("Framebuffer fb" + str(i) + ";" for i in range(len(self.render_order) - 1)) return "class " + self.C_name() \ + "\n{\n public:\n" \...
def C_code_arg(shadertype): return "code" + shadertype def C_constructor(self, implem = False): args = self.C_constructor_args() tmp = self.C_name() + "(" + args + ")" if implem: return self.C_name() + "::" + tmp return tmp def indent(s, n): lines = s.split("\n") ...
The function generates C++ code for a constructor that initializes OpenGL resources, including shader programs, vertex attributes, and uniforms. It creates a vertex array object (VAO) and buffer object (VBO), binds them, configures vertex attributes, enables attribute arrays, and finalizes shader setup. The code dynami...
def C_constructor_source(self): emplace = "\n".join("EmplaceShader(" + STYPE_TO_GL[i] + ", " + C_code_arg(i) + ");" for i in self.shadertypes) attributes = "\n".join(map(C_assign_attribute, self.attributes.items())) uniforms = "\n".join(map(C_assign_uniform, self.merged_uniforms.items())) ...
def C_constructor_source(self): ret = self.C_constructor(True) + ":\n" ret += indent(",\n".join("m" + s.C_name() + "(" + s.C_constructor_args(str(i), True) + ")" for i, s in enumerate(self.shaderlist)), 1) ret += ",\n" ret += indent(",\n".join("fb" + str(i) + "(width" + str(i) + ", heigh...
The main task of the code is to generate a complete C source code body by concatenating four components: constructor code, program getters, framebuffer getters, and draw functions. This function aggregates these parts to form the full implementation of a C component, likely for a graphics or simulation system.
def C_source_body(self): return self.C_constructor_source() \ + self.C_program_getters_source() \ + self.C_fb_getters_source() \ + self.C_draw_functions_source()
def uniform_type_of(_type): mvec = typevec.match(_type) mmat = typemat.match(_type) msampler = typesampler.match(_type) if _type == "uint" or _type == "bool": return "1ui" if _type == "int": return "1i" if _type == "float" or _type == "double": return "1f" if mvec: ...
This function generates C++ code for OpenGL uniform setters. It iterates over uniform variables, constructs function prototypes, and writes glUniform calls with type-specific parameters (e.g., matrix handling, data pointers). The output strings define methods that set shader uniform values, handling scalars, vectors, a...
def C_setters_source(self): tmp = "" for name, _type in self.merged_uniforms.items(): uniform_type = uniform_type_of(_type) scalar = is_scalar(_type) args = "(" + name + ", " if not scalar: args += "1, " if uniform_type[0] ...
def C_name(self): return self.module_name() def indent(s, n): lines = s.split("\n") return "\n".join((" " * n) + line for line in lines) def C_constructor(self, implem = False): args = self.C_constructor_args() tmp = self.C_name() + "(" + args + ")" if implem: retu...
The main task of the code is to generate a C++ class definition string with proper syntax and indentation. It constructs a class derived from `glutils::Program`, incorporating vertex attributes, constructors, destructors, bind prototypes, setters, and private member variables. The output combines these components into ...
def C_class(self): v = Vertex(self.attributes) return "class " + self.C_name() + " : public glutils::Program\n" \ + "{\n public:\n" \ + indent(v.C_source(), 2) + "\n" \ + indent(self.C_constructor(), 2) + ";\n" \ + indent(self.C_dest...
def C_constructor_source(self): emplace = "\n".join("EmplaceShader(" + STYPE_TO_GL[i] + ", " + C_code_arg(i) + ");" for i in self.shadertypes) attributes = "\n".join(map(C_assign_attribute, self.attributes.items())) uniforms = "\n".join(map(C_assign_uniform, self.merged_uniforms.items())) ...
The main task of the code is to generate a C source code body for a class by concatenating four components: the constructor, destructor, bind method, and setters. It combines these elements using string concatenation to form a complete implementation, likely for a class interface or framework that requires modular code...
def C_source_body(self): return self.C_constructor_source() \ + self.C_destructor_source() \ + self.C_bind_source() \ + self.C_setters_source()
def incline(): h = angularMomentum() i = m.atan(((h[0]**2 + h[1]**2)**(1/2)) / h[2]) i = i *180 / m.pi return i def longitude_ascending_node(): h = angularMomentum() hmag = np.linalg.norm(h) i = incline() / 180 * m.pi sin_omega = (h[0] / (hmag*m.sin(i))) cos_omega = (-h[1] / (hmag*m....
The code calculates the argument of periapsis (w) in orbital mechanics. It uses the inclination (i), position vector (r2), and orbital elements like the longitude of the ascending node (om) and true anomaly (v). By computing intermediate angles U and v, it derives w as the angular difference between U (a function of po...
def argument_of_periapsis(): i = incline() / 180 * m.pi r = (r2[0]**2 +r2[1]**2 +r2[2]**2)**(1/2) om = longitude_ascending_node() * m.pi / 180 x = r2[0] y = r2[1] z = r2[2] sinU = (z / (r*m.sin(i))) cosU = ((x*m.cos(om)) + y*m.sin(om)) / r U = od.return_angle(cosU, sinU) * m.pi / 180 v = t...
def e(): h = np.linalg.norm(angularMomentum()) A = a() e = (1 - h**2 / A)**(1/2) return e def a(): r = (r2[0]**2 +r2[1]**2 +r2[2]**2)**(1/2) v = (r2dot[0]**2 +r2dot[1]**2 +r2dot[2]**2)**(1/2) a = 1 / (2 / r - v**2) return a def true_anomaly(): A = a() E = e() h = np.linalg.no...
The function calculates the mean anomaly in degrees for an orbit, adjusting the result based on the true anomaly's quadrant. It computes the eccentric anomaly (E0), derives the mean anomaly (M) from it, converts M to degrees, and returns 360-M if the true anomaly is less than 180°, ensuring the angle falls within the c...
def mean_anomaly(): E = e() A = a() r = (r2[0]**2 +r2[1]**2 +r2[2]**2)**(1/2) E0 = m.acos((1 / E)*(1 - r / A)) M = E0 - E*m.sin(E0) M = M * 180 / m.pi if (true_anomaly() < 180): return 360 - M else: return M
def a(): r = (r2[0]**2 +r2[1]**2 +r2[2]**2)**(1/2) v = (r2dot[0]**2 +r2dot[1]**2 +r2dot[2]**2)**(1/2) a = 1 / (2 / r - v**2) return a def e(): h = np.linalg.norm(angularMomentum()) A = a() e = (1 - h**2 / A)**(1/2) return e def mean_anomaly_2(): t0 = t2 t = 2459419.7916667 M ...
The code transforms orbital elements into equatorial coordinates (right ascension and declination) by applying rotation matrices for orbital orientation, converting from ecliptic to equatorial coordinates, and calculating celestial coordinates from a normalized position vector. It uses Kepler's equation to compute ecce...
def transform(): A = a() E = e() M = mean_anomaly_2() om = m.radians(longitude_ascending_node()) i = m.radians(incline()) w = m.radians(argument_of_periapsis()) ta = m.radians(true_anomaly()) exp = (1-E)*(1 - ((np.linalg.norm(r2)) / A)) if (ta >= 0 and ta <= m.pi): E0 = m.aco...
def load_data(): x = [] y = [] with open('data.csv', mode='r') as csv_file: csv_reader = csv.DictReader(csv_file) line_count = 0 for row in csv_reader: x.append(int(row['km'])) y.append(int(row['price'])) return (x, y) def normalize(d): mean = statisti...
The code transforms normalized linear regression parameters (t0, t1) derived from standardized data (x_n, y_n) back to the original data scale. It calculates new parameters (t0_2, t1_2) by adjusting for the mean and standard deviation of x and y, enabling predictions on raw data values. The function returns these trans...
def prog2(): (x, y) = load_data() (x_n, x_mean, x_sd) = normalize(x) (y_n, y_mean, y_sd) = normalize(y) (t0, t1) = get_params((x_n, y_n)) #(t0 + t1 * ((x - m(x)) / stdev(x))) * stdev(y) + m(y) #(t0 + t1 * (x / stdev(x) - m(x) / stdev(x))) * stdev(y) + m(y) #(t0 + (x * t1)/stdev(x) - (t1 *...
def is_solved(self, csp): """ Given a CSP csp, determined whether the CSP is solved. If a CSP is solved, no domain has a size greater than 1. """ # separate and store the components of a CSP (V, D, C) = csp # iterate through new domains for domain in D.va...
The code determines if a valid assignment exists for a Constraint Satisfaction Problem (CSP) by enforcing arc consistency (AC3) and using heuristics (MRV and LCV). It checks initial solvability, applies AC3, and iteratively selects variables and values to assign, reapplying AC3 after each assignment. If at any point th...
def exists_valid_assignment(self, csp): """ Given a CSP csp, finds a valid assignment to variables in csp which is a solution to the CSP. If a valid assignment exists, returns True. If no valid assignment exists, returns False. """ # determine whether the CSP is s...
def heuristicEuclidean(now, goal): cost=0.0 if now is not None: cost=np.sqrt((now[0]-goal[0])**2 + (now[1]-goal[1])**2) return cost def get_path(dict_path, start, goal): current = goal path = [current] #print(cost(current,start)) print(dict_path.items()) while current != st...
The code implements the A* algorithm to find the shortest path from a start to a goal position on a grid map, avoiding obstacles. It uses a priority queue (open list) to explore nodes, tracking costs and predecessors (closed list). The grid is discretized into cells based on a threshold, and directional movements (e.g....
def astar(map, start, goal,step_size,threshold): #start = #goal = pq = PriorityQueue() # OpenList pq.put(start, 0) # We add the start to our priority_queue predecessors = {start: None} # Closed List cost_to_come = {start: 0} # To store the cost2come values V = np.zeros((int(map.shape[0]/th...
def get_path(dict_path, start, goal): current = goal path = [] while current != start: path.append(current) current = dict_path[current] path.append(start) path.reverse() #print(dict_path) return path,dict_path def is_legal_pos(map, pos): i, j = pos num_rows = len(map...
The code implements Dijkstra's algorithm to find the shortest path from a start to a goal node on a grid. It uses a priority queue (open list) to explore nodes, tracks predecessors for path reconstruction, and calculates movement costs (1 for orthogonal, 1.4 for diagonal). The algorithm returns the optimal path if the ...
def dijkstra(map, start, goal): pq = PriorityQueue() # OpenList pq.put(start, 0) # We add the start to our priority_queue predecessors = {start: None} # Closed List cost_to_come = {start: 0} # To store the cost2come values while not pq.is_empty(): # Checking all the explored nodes curr...
def left_click(p): win32api.SetCursorPos(p) win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, 0, 0) win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, 0, 0) def cast_action(action, hold): pydirectinput.keyDown(action) time.sleep(hold) pydirectinput.keyUp(action) def type_word(word): pydirec...
This code automates in-game actions by scanning for specific elements ("timer" and "small_camp") within a 5-minute timeout. Once located, it performs a left-click, enters an action, types "muting all," levels up the player's ability, and purchases an item, likely for a game bot or automation script.
def on_start(active_player): tm_loc = None sc_loc = None start_time = time.time() while not tm_loc and not sc_loc: tm_loc = scan.find(active_player.team, "map", "timer") sc_loc = scan.find(active_player.team, "map", "small_camp") if int(time.time() - start_time) > 305: ...
def path_to_fountain(active_player): if active_player.team == "ORDER": right_click(MAP_COORDS["blue_base"]) elif active_player.team == "CHAOS": right_click(MAP_COORDS["red_base"]) def cast_action(action, hold): pydirectinput.keyDown(action) time.sleep(hold) pydirectinput.keyUp(action...
The code executes a "recall" action for a game player, moving them to the fountain, waiting for health regeneration, and purchasing an item upon successful recovery. It checks if health regen meets expectations, retries recall if failed, and times out after 20 seconds. The main task is to ensure the player fully regain...
def recall(active_player): path_to_fountain(active_player) time.sleep(8) cast_action('b', 1) try: active_player.update() except: return prev_health = active_player.stats["championStats"]["currentHealth"] time.sleep(6.8) try: active_player.update() except: ...
def detect(object, dat={}): obj_loc = scan.find(None, "screen", object) if obj_loc: dat[object] = True else: dat[object] = False return dat[object] def path_turret(active_player): m_loc = MAP_COORDS["map"] turret = scan.find(None, "screen", "turret") turret = scan.scale_point...
The code's main task is to control an active player in a game to attack enemies while managing health and positioning. It scans for enemies and allies, uses abilities (Q, W, E, R) to attack when health is high and allies outnumber enemies, or flees and uses defensive actions (R, D) when health is low. It also navigates...
def attack_enemy(active_player): m_loc = MAP_COORDS["map"] use_rd = False cast_time = active_player.champ_info["cast_time"] enemies = scan.find(None, "screen", "enemy_health") if not enemies: return False allies = scan.find(None, "screen", "ally_health") allies = 0 if allies is ...
def attack_enemy(active_player): m_loc = MAP_COORDS["map"] use_rd = False cast_time = active_player.champ_info["cast_time"] enemies = scan.find(None, "screen", "enemy_health") if not enemies: return False allies = scan.find(None, "screen", "ally_health") allies = 0 if allies is ...
The code monitors a player's state in a game, detecting enemies, turrets, health, gold, and level changes. It triggers actions like attacking, pathing around turrets, recalling, leveling up, or surrendering based on conditions. Threads detect threats, and the function returns True if any action is taken, otherwise Fals...
def check_player(active_player): # Returning true means you disrupt the clearing try: active_player.update() except: print("Error updating") return None threads = [] dat = {} threads.append(threading.Thread(target=detect, args=("enemy_health", dat))) threads.append(thre...
def cast_action(action, hold): pydirectinput.keyDown(action) time.sleep(hold) pydirectinput.keyUp(action) def check_player(active_player): # Returning true means you disrupt the clearing try: active_player.update() except: print("Error updating") return None threads = [...
The code automates attacking an enemy camp by targeting red bars (enemies) on the screen. It casts spells (Q, E, W, F), alternates attack positions, monitors player health, and ensures the player doesn't die. The loop continues until the target's health is sufficiently reduced or the player's health drops below 75%. It...
def attack_camp(active_player): cast_action("y", 0.5) cast_time = active_player.champ_info["cast_time"] target = scan.find(None, "screen", "red_bar") start_time = time.time() while not target: status = check_player(active_player) if status or status is None: return statu...
def cast_action(action, hold): pydirectinput.keyDown(action) time.sleep(hold) pydirectinput.keyUp(action) def left_click(p): win32api.SetCursorPos(p) win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, 0, 0) win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, 0, 0) def right_click(p): win32api...
The function `path_to_camp` directs an active player to attack a camp (big, small, or timer) on a map based on their team. It first clicks the team's base, scans for camp locations, and right-clicks the first found camp to trigger an attack. If no camps remain, it logs a message and checks the player's status.
def path_to_camp(active_player): m_loc = MAP_COORDS["map"] cast_action("y", 0.5) if active_player.team == "ORDER": left_click(MAP_COORDS["blue_base"]) elif active_player.team == "CHAOS": left_click(MAP_COORDS["red_base"]) bc_loc = scan.find(active_player.team, "map", "big_camp")...
def get_market_history(market: str) -> bytes: """ Get historic data from finance.yahoo :param market: market name from list of available in finance.yahoo :return: file as binary string """ market = re.sub('^A-Za-z0-9', '', market) error_message = b'404 Not Found: No data found, symbol may be...
The function `load_market_data_to_db` loads historical market data into a database by iterating over a list of market names. For each market, it retrieves historical data using `get_market_history`, saves it to a file with `save_market_data_to_file`, and stores it in the database via `save_market_data_to_db`. The task ...
def load_market_data_to_db(market_list=MARKETS_LIST) -> None: """ Load market data to database with given list of names :param market_list: List of given markets :return: None """ for market_name in MARKETS_LIST: logger.info(f"Processing data to database") market_data = get_marke...
def df_cols_to_list(filenames): ticks_and_names = df_concat(filenames) ticks = ticks_and_names['Symbol'].tolist() companies = ticks_and_names['Name'].tolist() return ticks, companies def company_pruner(company_list, cutoff_frequency): pruned_list = [] cl_copy = company_list.copy() split_list...
The function processes stock data from AMEX, NYSE, and NASDAQ by pruning companies based on a threshold (18), pairing valid tickers with company names, and removing entries with empty/namespaced company names, returning a cleaned list of ticker-company associations.
def pruner_bigboy(): ticks, companies = df_cols_to_list(['amex.csv', 'nyse.csv', 'nasdaq.csv']) pruned_companies = company_pruner(companies, 18) ticks_names = zip_list(ticks, pruned_companies) tn_copy = ticks_names.copy() for item in ticks_names: if item[1] == "" or item [1] == " ": ...
def prepare_feature(feature): for ch in unsafe_characters: feature = str(feature).replace(ch, "") return f'"{feature}"' def get_youtube_video_duration(video_id): url = f"https://www.googleapis.com/youtube/v3/videos?part=contentDetails,snippet&id={video_id}&key={api_key}" tags = ["none"] resp...
The function extracts metadata from YouTube video items, including IDs, descriptions, thumbnails, duration, category, tags, and channel information, then formats them into CSV-like strings for output.
def get_videos(orig_vid_id, items): lines = [] for video in items: if 'snippet' not in video: continue video_id = video['id']['videoId'] snippet = video['snippet'] description = snippet.get("description", "") channel_id = snippet.get('channelId') featu...
def prepare_feature(feature): for ch in unsafe_characters: feature = str(feature).replace(ch, "") return f'"{feature}"' def get_youtube_video_duration(video_id): url = f"https://www.googleapis.com/youtube/v3/videos?part=contentDetails,snippet&id={video_id}&key={API_KEY}" # tags = ["none"] re...
This function processes a list of YouTube video items to extract and format specific data fields (e.g., video ID, description, duration, channel info) into comma-separated strings. It prepares features from video snippets, retrieves additional metadata like duration and channel details, and compiles all information int...
def related_get_videos(orig_vid_id, items): lines = [] for video in items: if 'snippet' not in video: continue video_id = video['id']['videoId'] snippet = video['snippet'] description = snippet.get("description", "") channel_id = snippet.get('channelId') ...
def api_request(page_token, vid_id): request_url = f"https://www.googleapis.com/youtube/v3/{api_name}?part=snippet{page_token}relatedToVideoId={vid_id}&type=video&regionCode=US&maxResults=50&key={api_key}" request = requests.get(request_url) return request.json() def get_videos(orig_vid_id, items): line...
This function retrieves video data in paginated requests using an API, aggregates the results into a list, prepends a header row, and writes the combined data to a file. It handles pagination via nextPageToken, iteratively fetching and processing video entries until all pages are retrieved.
def get_pages(vid_id, next_page_token="&"): country_data = [] while next_page_token is not None: video_data_page = api_request(next_page_token, vid_id) next_page_token = video_data_page.get("nextPageToken", None) next_page_token = f"&pageToken={next_page_token}&" if next_page_token is n...
def related_api_request(page_token, vid_id): request_url = f"https://www.googleapis.com/youtube/v3/{api_name}?part=snippet{page_token}relatedToVideoId={vid_id}&type=video&regionCode=US&maxResults=50&key={API_KEY}" request = requests.get(request_url) print('RELATED API REQUEST') return request.json() de...
This function retrieves related video data in a loop using pagination. It appends processed video information to a list, prefixes it with headers, and writes the aggregated data to a file. The loop continues until all pages are exhausted, using nextPageToken from API responses to fetch subsequent pages of related video...
def related_get_pages(vid_id, next_page_token="&"): country_data = [] while next_page_token is not None: video_data_page = related_api_request(next_page_token, vid_id) # if video_data_page == -1: # print('BLOCKED') # break next_page_token = video_data_page.get("n...
def get_closest_nodes(self, lat, lon): # Start timing current procedure start_time = time.time() low, high = 0, len(self.sorted_nodes) - 1 nearest = None min_distance = float("inf") while low <= high: mid = (low + high) // 2 current_node, _ = se...
The function matches the closest available driver to a passenger based on Euclidean distance, prioritizing drivers with the shortest pickup time. It calculates driving times considering time-of-day constraints, optimizes by checking top 10 drivers, and handles edge cases like single drivers. The selected driver complet...
def match(self, availible_drivers, passenger_id): # Get the closest available driver by euclidean distance min_time = float("inf") min_driver = None # Minor optimization since if there's only 1 driver availible, then we don't need to check the pickup time if len(availible_drive...
def updateDisplayParams(self, param_dict): self.le_wd.setText(param_dict["wd"]) self.le_scan_num.setText(str(param_dict["scan_num"])) index = self.cb_detector.findText(param_dict["detector"], QtCore.Qt.MatchFixedString ) if index >= 0: self.cb_detector.setCurrentIndex(index)...
The code initializes a GUI for a Ptycho data processing tool by loading a UI file, configuring parameters like detector settings, ROI, and pixel corrections, and connecting UI elements to functions for data loading, parameter updates, ROI adjustments, and saving. It sets up event handlers for user interactions, initial...
def __init__(self): super(ptychoWindow, self).__init__() uic.loadUi(os.path.join(ui_path,'ptychoSave_v2.ui'), self) self.config = {"wd": os.getcwd(), "scan_num":'', "detector": "merlin1", "crop_roi": (0,0,0,0), ...
def arg_check(): if (args.file is not None and args.url is not None) or (not sys.stdin.isatty() and args.file is not None) or (not sys.stdin.isatty() and args.url is not None): print_error() if args.file is None and args.url is None and sys.stdin.isatty(): print("No arguments specfied! Use pyth...
The main task of the code is to process URLs from command-line arguments, files, or standard input, validate them, and establish socket connections to specified domains and ports by removing HTTP prefixes and initiating network communication.
def main(): arg_check() url = "" if args.url: url = args.url check_url([url]) if args.file: url = args.file.readlines() check_url(url) if not sys.stdin.isatty(): url = sys.stdin.readlines() check_url(url) if args.connect: for urls in url:...
def processFile(filename = "dates"): inFile = open(filename) dateList = [] MONTH = {"JAN":31,"FEB":28,"MAR":31,"APR":30,"MAY":31,"JUN":30,"JUL":31,"AUG":31,"SEP":30,"OCT":31,"NOV":30,"DEC":31} try: if inFile is None: raise OSError except FileNotFoundError: prin...
The main task of the code is to process a file containing date data, convert dates into American and International formats, compute differences between dates, identify the most recent year, sort dates using a custom comparator, and compare all dates against a fixed reference date (JAN 1, 2000), outputting formatted res...
def main(): if len(sys.argv) > 1: filename = sys.argv[1] dateList = processFile(filename) print([''.join(month + " " + str(day) + ", " + str(year)) for (month, day, year) in dateList],"\n") AmGen = dateConvertGen(dateList, "American") print(AmGen[0], "\n") IntGen...