dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def send_directory_service(filename, RW, list_files): serverName = 'localhost' serverPort = 9090 # port of directory service #for reading and writing if not list_files: msg = filename + '|' + RW # send the string requesting file info to directory send_directory_service proxy = x...
The main task of the code is to read a file from a distributed file system by querying the directory service for the file's location, retrieving the file content from the identified file server, caching the updated content if non-empty, and managing file version tracking. It handles cases where the file does not exist ...
def handle_read(filename, file_version_map, client_id): reply_DS = send_directory_service(filename, 'r', False) # send file name to directory service if reply_DS == "FILE_DOES_NOT_EXIST": print(filename + " does not exist on a fileserver") else: # parse info received from the directory s...
def read_training_sentences_file(file_name): training_sentences = [] frequencies = {'words': [], 'frequencies': [], 'frequencies, index by word': {}} sense_inventory = set() with open(file_name, 'r') as f: for line in f.readlines(): line = line.split('\t') # If there is...
The code computes distributional similarity between test and training sentences. It reads input files, builds a vocabulary from training data, creates signature vectors for training sentences, and calculates distances between test sentences and training signatures. Results are written to an output file. The process inv...
def main(): # Read in arguments. args = sys.argv[1:] training_sentences_file = args[0] test_sentences_file = args[1] stopwords_file = args[2] k = int(args[3]) output_file_name = test_sentences_file + '.distsim' # Read in data from given files. training_sentences, training_frequenci...
def read_test_sentences_file(file_name): test_sentences = [] with open(file_name, 'r') as f: for line in f.readlines(): line = line.split() # If there is data in the line. if len(line) > 0: # Trim newline character. tagged_sentence = ...
The main task of the code is to execute the Lesk algorithm for word sense disambiguation. It reads test sentences, sense definitions, and stopwords from input files, filters sentences by removing stopwords, applies the Lesk algorithm to determine the most appropriate sense for each word, and writes the results to an ou...
def main(): # Read in arguments. args = sys.argv[1:] test_sentences_file = args[0] sense_definitions_file = args[1] stopwords_file = args[2] output_file_name = test_sentences_file + '.lesk' # Read in data from given files. test_sentences = read_test_sentences_file(test_sentences_file) ...
def ner_on_doc(document): trees = [] entities = [] all_chunks = {'GPE': [], 'PERSON': [], 'ORGANIZATION': []} tagged_sentences = tag_PoS_doc(document) for sentence in tagged_sentences: # Create tree. bio_tagging, chunked_sentence_tree = chunking_on_sentence(sentence) trees....
This code processes a list of stories to generate answers for associated questions by extracting named entities, numerical data, and using NLP analysis. For each story and its questions, it leverages NER results, chunked entities, and spaCy entity recognition to formulate answers, appending them with question IDs for t...
def answer_questions(story_IDs): answers = [] # For every story, examine the questions associated. for story_meta in story_IDs: ner_results_tree, entities, chunked_entities = ner_on_doc(story_meta['story']['text']) numbers = get_numbers(story_meta['story']['text']) doc = nlp(story_...
def statusON(): ##update bb logs with on status status= open("./logs/bbserverver_status.log","w") status.write("BBServer is ON") status.close() def start_evaluation(timet,pulse): #button has been pressed ONCE. Now the countdown has been started GPIO.remove_event_detect(18) #clean the event detection ...
The code monitors a GPIO pin (BCM 18) for a rising edge signal, triggering a evaluation process (`start_evaluation`) once detected. It initializes the pin, waits for input, and handles exceptions by reporting errors. The loop resets the pulse counter and maintains the status until the event is detected.
def listen_socket(pulse,timet): try: statusON() while True: global actualPULSE actualPULSE = 0 GPIO.setwarnings(False) # Ignore warning for now GPIO.setmode(GPIO.BCM) # Use physical pin numbering GPIO.setup(18, GPIO.IN,pull_up_down=GPIO.P...
def add_action(self, action): self.action_list.append(action) print(action) self.append_event_to_output_file(action.name) if action == Action.TURN_LEFT: pass elif action == Action.TURN_RIGHT: pass elif action == Action.TURN_UP: pass ...
This function implements a backtracking search algorithm for an agent in a Wumpus world. The agent checks for hazards (pit/wumpus), collects gold, perceives environmental cues (breeze/stench), and uses logical inference with a knowledge base (KB) to safely navigate. It explores unvisited cells, avoids inferred dangers,...
def backtracking_search(self): # If there is a Pit, Agent dies. if self.agent_cell.exist_pit(): self.add_action(Action.FALL_INTO_PIT) return False # If there is a Wumpus, Agent dies. if self.agent_cell.exist_wumpus(): self.add_action(Action.BE_EATEN_B...
def _write(self, data): """Writing data using Serial interface. Parameters ---------- data : Whatever you want :) Transmitting data. """ self.ser._write(struct.pack('>B', data)) def _read(self, bytes=1): """Reading data unsing Serial interface. For ...
The function retrieves telemetry data by transmitting an identifier, verifying a start byte, reading the data type, and receiving data (as array, float, or signed value). It returns a dictionary containing the data, its type, and array-specific metadata if applicable.
def get_data(self, id): """Getting telemetry data after transmitting identifier. Parameters ---------- id : Integer Data identifier. Returns ------- type Dict Telemetry item that has been received. Contains: `type`, `data`, `i...
def build_data(data: dict, mapping: dict) -> dict: """ Returns the transformed Python dictionary from a key mapping. """ output = dict() for key1, key2 in mapping.items(): if isinstance(key2, dict): output[key1] = build_data(data, key2) elif key2 != "": output...
The function transforms data from a MongoDB collection by mapping fields, generating unique IDs, and inserting/updating documents in another collection. It processes batches, handles errors by reinserting failed data, and ensures data is moved with timestamps.
def transform(batch_id: str, mapping: dict, keys: list) -> None: if len(mapping) == 0: raise AirflowException("Mapping provided is empty") if len(keys) == 0: raise AirflowException("Unique Keys provided is empty") mongo_conn = MongoHook(conn_id="default_mongo") results_to_transform_co...
def build_data(data: dict, mapping: dict) -> dict: """ Returns the transformed Python dictionary from a key mapping. """ output = dict() for key1, key2 in mapping.items(): if isinstance(key2, dict): output[key1] = build_data(data, key2) elif key2 != "": output...
This function processes batch data from MongoDB by transforming JSON files using a provided mapping, generating unique IDs based on specified keys, and upserting the transformed data into a target collection. It handles errors by logging exceptions and reinserting failed batches.
def local_transform(batch_id: str, mapping: dict, keys: list) -> None: if len(mapping) == 0: raise AirflowException("Mapping provided is empty") if len(keys) == 0: raise AirflowException("Unique Keys provided is empty") mongo_conn = MongoHook(conn_id="default_mongo") local_results_to_...
def split_names(names: str) -> list: return [x.strip() for x in names.split(',')] def greet_uppercase(names): return f"HELLO {get_string_with_all_names(names)}!" def handle_many_names(names): names_uppercase = [] filtered_names = [] for name in names: if name.isupper(): names_up...
The main task of the code is to generate a greeting message based on input names, handling various formats: splitting strings into names, processing lists/tuples with quoted/unquoted entries, defaulting to "my friend" if input is None, and returning "Hello, {names}." with appropriate name formatting.
def greet(names): if isinstance(names, str): names_list = split_names(names) if names.isupper(): return greet_uppercase(names_list) return handle_many_names(names_list) elif isinstance(names, (list, tuple)): names_list = [] for name in names: if na...
def slide_window(img, x_start_stop=[None, None], y_start_stop=[None, None], xy_window=(64, 64), xy_overlap=(0.5, 0.5)): # If x and/or y start/stop positions not defined, set to image size if x_start_stop[0] == None: x_start_stop[0] = 0 if x_start_stop[1] == None: x_start...
The main task of the code is to detect vehicles in an image using sliding windows, HOG features, and a trained classifier. It generates candidate windows, applies the classifier to identify potential vehicles, creates a heatmap to aggregate detections, applies thresholding to reduce false positives, and draws bounding ...
def detect_vehicles(img, detection, singleImage, clf, X_scaler, color_space, spatial_size, hist_bins, orient, pix_per_cell, cell_per_block, hog_channel, spatial_feat, hist_feat, hog_feat, x_start_stop=[None, None], y_start_stop=[None, None], subsampling=False, retNr=False, format='normal'): # store for the int...
def log(stage, msg): ''' function to print out logging statement in this format: format <time> : <stage> : <msg> example: 2017-04-28 12:48:45 : info : chess board corners found in image calibration20.jpg ''' print(str(datetime.datetime.now(...
The code creates or loads a trained classifier for vehicle detection using HOG features, color histograms, and spatial data. It checks for an existing pre-trained model in `mlDir`; if not found, it processes vehicle and non-vehicle images to extract features, scales them, trains a Linear SVM classifier, and saves the m...
def createClassifier(mlDir, color_space, spatial_size, hist_bins, orient, pix_per_cell, cell_per_block, hog_channel, spatial_feat, hist_feat, hog_feat): ''' function to create a trained classifier of vehicles in images 1) if a trained classifier already exists in mlDir, then this classifier...
def add_item_skus_in_list_to_space(list_of_items, space): ''' list of items get added to a space''' for item in list_of_items: add_item_sku_to_space(item, space) def sales(self): # when the demand is entered, the store.stock and inventory reduces # and those items are poped into th...
The code advances the simulation day, updates inventory by adding incoming items to locations, processes daily sales, calculates total holding costs, and checks stock levels to manage inventory efficiently. It handles item transfers, sales computation, and end-of-day planning tasks like stock level verification and hol...
def run(self): Simulator.instance.day += 1 # do some sending and transfering # store has sales so it's out_list goes nowhere, just get's deleted # also the store sales have to be calculated # transport has some other location is going to so the time delay aspect # shou...
def load(file): with open(file) as f: return [[int(c) for c in l[:-1]] for l in f.readlines()] def is_low(tab, l, c): return tab[l][c] < min([tab[nc[0]][nc[1]] for nc in neighbors_coords(tab, l, c)]) def explore(tab, l, c): if (l, c) not in visited: visited.append((l, c)) for coord in ne...
The code reads a grid from a file, identifies low points (cells with values lower than adjacent cells), calculates the size of each basin (connected region of cells drained by the low point), stores these sizes, sorts them, and outputs the product of the three largest basin sizes.
def part2(file): tab = load(file) lines = len(tab) cols = len(tab[0]) areas = [] for l in range(0, lines): for c in range(0, cols): if is_low(tab, l, c): explore(tab, l, c) areas.append( len(visited)) visited.clear() areas.sort(...
def create_dataset(num_machines, csv_file, save_filename, num_cpus=multiprocessing.cpu_count()-1): df = pd.DataFrame(columns = [ "graph_object", "num_tasks", "num_machines", "weights", "order", "features", "psize", "GD_cost", "LR_cost", ...
The code trains a linear regression model on graph-based training data to predict system costs, evaluates it on test data, and applies gradient descent optimization to refine coefficients. It processes features like node properties, computes predicted performance metrics, and calculates scheduling costs using graph alg...
def main(): training_data_filename = "small_graph_full1_training_data.csv" testing_data_filename = "small_graph_full1_testing_data.csv" num_machines = 2 feature_id = ['constant', 'num_descendants', 'out_degree_betweenness_centrality', 'trophic_levels'] df_train = create_dataset(num_machines, train...
def create_dataset(num_machines, csv_file): df = pd.DataFrame(columns = [ "graph_object", "num_tasks", "num_machines", "weights", "order", "features", "psize", "GD_cost", "LR_cost", "RLP_cost", "ETF-H_cost", "weak_s...
This code evaluates linear regression (LR) and gradient descent (GD) models for scheduling optimization across real-life datasets. It iterates through different machine counts and traces, trains LR models on training data to predict costs, applies GD to refine coefficients, and tests models on test data. Results are sa...
def main(): # All the train test files traces = ["1000genome", "cycles", "epigenomics", "montage", "seismology", "soykb"] feature_id = ['constant', 'num_descendants', 'out_degree_betweenness_centrality', 'trophic_levels'] num_machine_combos = [3, 10, 50, 100] for num_machines in num_machine_combos: ...
def makeModList(): """ creates the value of (modInfo) based on contents of the mod/ directory. Every mod must have a {MOD}.md file and a {MOD}/ directory, where "{MOD}" must be the name of the mod. Mod names: * are 1-32 chars long * contain only lower case letters (a-z), digits (0-9)...
The main task of the code is to implement a command-line mod manager for RTW2, handling operations like listing mods, displaying mod info, adding mods, resetting modded files, and logging mod actions. It uses argparse for argument parsing, with flags such as --list, --info, --add, --reset, and --log to trigger specific...
def main(): global verbosity makeModList() parser = argparse.ArgumentParser(description= "*** Rule the Mods -- a mod manager for RTW2 ***") parser.add_argument("-v", "--verbose", action="count", help="increase output verbosity") parser.add_argument("-l", "--list", action='s...
def calc_next_goal(self): # Prefer to move in order: Ahead, left, right, back, Next_available_job theta = self.dirs_dict[self.dir] c, s = np.cos(theta), np.sin(theta) R = np.array(((c, -s), (s, c))) positions_to_check = R@(np.array([[1,0], [0,1], [0,-1], [-1,0]]).T) posit...
The code's main task is to determine if the agent should continue moving or stop. It checks if the current path is empty or if the goal is obsolete (no unknown neighbors). If so, it recalculates the next goal. If not done, it advances the agent by taking a step and discovering new states. The function returns `True` wh...
def advance(self): done = False if len(self.path) == 0: done = self.calc_next_goal() if len(self.path) == 0: done = True else: # Check if the current goal is obsolete state_of_goal_neighbours = self.states_of_neighbours(self.path[...
def clone_assets_folder(folder_name, branch, local_openspace_folder): """ Clones asset directory from OpenSpace git repository Uses the latest master Returns absolute path to the asset folder """ data_assets_path = "data/assets" if local_openspace_folder: print(f"Using local OpenSpace folder {local_o...
The function generates Markdown documentation for asset components using Jinja templates, creates an index file linking all components, and compiles a summary table of components with their categories and example availability. It processes asset files from a cloned repository, sorts them by size, and dynamically render...
def generate_asset_components(environment, output_folder, folder_name_assets, json_location, branch, local_openspace_folder): """ Creates the Markdown files for the asset components, as well as an index file which links to them """ assets_examples_folder_name = "asset_examples" # Download assets files from ...
def generate_asset_components(environment, output_folder, folder_name_assets, json_location, branch, local_openspace_folder): """ Creates the Markdown files for the asset components, as well as an index file which links to them """ assets_examples_folder_name = "asset_examples" # Download assets files from ...
The main task of the code is to generate dynamic documentation using Jinja templates. It initializes a template environment, then generates asset-component, scripting API, and renderable overview documentation by processing JSON data and outputting files to a specified folder. The function orchestrates three documentat...
def generate_docs(branch, local_openspace_folder): print("Generating dynamic documentation") json_location = "json" output_folder = "generated" folder_name_assets = "asset-components" folder_name_scripting = "scripting-api" # Load jinja templates folder environment = Environment(loader=FileSystemLoader(...
def Profile(Motifs): t = len(Motifs) k = len(Motifs[0]) profile = {} profile = Count(Motifs) for i in profile: for j in range(k): profile[i][j] = profile[i][j]/t return profile def ProfileMostProbableKmer(text, k, profile): maxim = -1 x = 0 for i in range(len(text...
The function `GreedyMotifSearch` identifies the best set of motifs (k-length subsequences) from multiple DNA sequences using a greedy algorithm. It initializes candidate motifs, iterates through all possible starting positions in the first DNA string, and constructs motifs for subsequent sequences by selecting the most...
def GreedyMotifSearch(Dna, k, t): BestMotifs = [] for i in range(0, t): BestMotifs.append(Dna[i][0:k]) n = len(Dna[0]) for i in range(n-k+1): Motifs = [] Motifs.append(Dna[0][i:i+k]) for j in range(1, t): P = Profile(Motifs[0:j]) Motifs.append(Prof...
def ProfileWithPseudocounts(Motifs): # t = len(Motifs) k = len(Motifs[0]) profile = {} # output variable count = CountWithPsuedocounts(Motifs) for i in range(k): s = 0 for symbol in "ACGT": s = s + count[symbol][i] for symbol in "ACGT": count[symbol][i...
This function performs Greedy Motif Search with pseudocounts to identify the best set of k-length motifs (one per DNA string in Dna) that minimize the score. It initializes candidate motifs, iterates over all possible starting positions in the first DNA string, constructs motifs using pseudocount-based profiles, and up...
def GreedyMotifSearchWithPseudocounts(Dna,k,t): BestMotifs = [] for i in range(0, t): BestMotifs.append(Dna[i][0:k]) n = len(Dna[0]) for m in range(n-k+1): Motifs = [] Motifs.append(Dna[0][m:m+k]) for j in range(1, t): P = ProfileWithPseudocounts(Motifs[0:j]) ...
def RandomMotifs(Dna, k, t): t = len(Dna) l = len(Dna[0]) RandomMotif =[] for i in range(t): r = random.randint(0,l-k) RandomMotif.append(Dna[i][r:r+k]) return RandomMotif def ProfileWithPseudocounts(Motifs): # t = len(Motifs) k = len(Motifs[0]) profile = {} # output vari...
The GibbsSampler function iteratively refines a set of motifs by randomly selecting a DNA string, generating a profile from remaining motifs, creating a new motif using the profile, and updating the set if the new score is lower. It repeats this N times to converge toward optimal motifs with minimal score, improving al...
def GibbsSampler(Dna, k, t, N): BestMotifs = [] # output variable Motifs = RandomMotifs(Dna, k, t) BestMotifs = Motifs for j in range(1,N): i = random.randint(0,t-1) ReducedMotifs = [] for j in range(0,t): if j != i: ReducedMotifs.append(Motifs[j]) ...
def RandomMotifs(Dna, k, t): t = len(Dna) l = len(Dna[0]) RandomMotif =[] for i in range(t): r = random.randint(0,l-k) RandomMotif.append(Dna[i][r:r+k]) return RandomMotif def ProfileWithPseudocounts(Motifs): # t = len(Motifs) k = len(Motifs[0]) profile = {} # output vari...
The code implements the Randomized Motif Search algorithm to identify the best set of motifs in DNA sequences. It starts with random motifs, iteratively generates a profile with pseudocounts, creates new motifs from the profile, and updates the best motifs if the new score is lower. The process halts when no improvemen...
def RandomizedMotifSearch(Dna, k, t): M = RandomMotifs(Dna, k, t) BestMotifs = M while True: Profile = ProfileWithPseudocounts(M) M = Motifs(Profile, Dna) if Score(M) < Score(BestMotifs): BestMotifs = M else: return BestMotifs
def register_users(self) -> None: for i in range(self.users_info["number_of_users"]): user = { "username": f"{self.base_user_name}_{i}", "password": self.user_password } res = requests.post(self.base_url + "/auth/signup", headers=self.headers, data=json.dumps(user)) if res.s...
The main task of the code is to simulate a bot's operation by initializing with a URL, registering users, creating posts, liking posts, and saving all user data to a file. The method orchestrates automated actions typical in social media bots, such as user registration, content generation, interaction (liking), and dat...
def run(self) -> None: print(f"Bot started with url {self.base_url}") self.register_users() self.create_posts() self.like_posts() self.dump_all_users_to_file()
def get_seeds(doc_count, k): return list(np.random.choice(range(1,doc_count+1), k, replace=False)) def clusterize(doc_count, k, seed, doc_list_voc, doc): #to initialise the cluster_to_id and id_cluster dictionaries using the seeds provided clusters = {} rev_clusters = {} for i in range(1,doc_count...
The code implements Jaccard clustering by iteratively grouping documents into k clusters using seed-based initialization. It calculates cluster assignments, updates seeds based on document-vocabulary overlaps, and terminates when seeds stabilize (convergence). The function returns final cluster seeds and inertia (a mea...
def jaccard_clustering(k, doc_count, iters, doc_list_voc, doc, vocab_count): seed = get_seeds(doc_count, k) inv_inertia = 0 for i in range(iters): start = time.time() print("Seed is: ",set(seed)) clus,rev_clus,inv_inertia = clusterize(doc_count, k, seed, doc_list_voc, doc) ne...
def despawnPlayerBroadcast(server, connList, playerID): print("BROADCAST DESPAWN") for p in range(128): if (connList[p] != None): despawnPlayer(server,connList[p],playerID) def levelInitialize(server,conn,playerID): world = server.playerData[playerID].world data = struct.pack('!B',0x...
This function loads a player's world in a server environment by initializing level data, setting spawn coordinates, updating player positions, and broadcasting the player's presence to connected clients. It handles world-specific settings, chunk loading, and ensures visibility across all relevant connections, completin...
def loadWorld(server, conn, world, playerID): print("Loading world "+ world.fileName +"for player: "+str(playerID)) username = server.playerData[playerID].playerName worldX = world.worldX worldZ = world.worldZ worldY = world.worldY spawnX = world.spawnX spawnZ = world.spawnZ spawnY ...
def disconnectPlayer(server, conn,disconnectReason): packetID = struct.pack('!B',0x0e) disconnectReason = bytes(disconnectReason + " "*(64-len(disconnectReason)),'utf-8') data = packetID + disconnectReason try: sendMessage(conn, server, data) except Exception as e: print(e) ...
This function handles player identification upon connection. It extracts username and verification data, checks for duplicate logins, associates the username with the playerID, detects CPE support, and initiates server-side setup including world loading and broadcast notifications. If CPE is unsupported, it sends stand...
def playerIdentification(playerID,data,conn,server): world = server.worlds["world"] connList = server.connList packetID = data[0] protocolVersion = data[1] username = (data[2:66]).decode("utf-8").strip() verificationKey = (data[66:130]).decode("utf-8").strip() padding = int(data[13...
def serverIdentification(playerID, conn, server, motd): world = server.worlds["world"] connList = server.connList packetIDS = bytes((0,)) serverProtocol = bytes((7,)) serverName = bytes(server.SERVER_NAME + " "*(64 - len(server.SERVER_NAME)),'utf-8') serverMOTD = bytes(motd + " "*(64 - len(mot...
This function processes a client's CPE (Custom Protocol Extension) handshake packet. It extracts extension name/version from the data, updates the player's extension count, checks if the server supports the extension, and triggers world loading and status messages if all extensions are confirmed. It handles protocol ne...
def extEntryPacketClient(playerID, data, conn, server): packetID = struct.unpack('!B', data[0:1]) extName = data[1:65] version = struct.unpack('!I',data[65:69])[0] #print("Client reports CPE Extension:",extName.decode('utf-8'),"Version:",version) server.playerData[playerID]._extensionsLeft -= 1 ...
def substitute_in_clause(self, clause: grammar.Clause) -> grammar.Clause: """ Apply the substitution to something which is known to be a ``Clause``. :param clause: a clause to apply substitution to :returns: the result of the substitution """ literals = tuple( ...
This method applies a substitution to a given target clause or proposition by checking its type and delegating to the appropriate substitution method: `substitute_in_clause` for clauses, `_substitute_in_predicate` for predicates, and `_substitute_in_term` for other terms.
def __call__( self, target: Union[grammar.Clause, grammar.Proposition] ) -> Union[grammar.Clause, grammar.Proposition]: """ Apply a substitution to a given target clause. :param target: a clause to which to apply the substitution """ if isinstance(target, grammar.Cla...
def get_choice(self, person: Person): """ Gets the choice of a person """ choices = ['fight', 'run'] if person.ai: return random.choice(choices) else: return input(f'What do you want to do? {choices}: ') def make_matches(self): """ ...
The code's main task is to simulate a day's operations by collecting each person's choices, updating their health, creating matches based on these choices, executing the matches, and returning the results. It initializes daily choices, adds health points, processes match creation, runs the matches, and outputs the fina...
def run(self): """ Runs the day """ # Get the choices of the people for person in self.people: choice = self.get_choice(person) person.set_day_choice(self.game_data['day'], choice) # at the start of the day, add health person.add_...
def input_data(): data = [] jumlah_data = int(input("Masukkan jumlah data: ")) for i in range(jumlah_data): nilai = float(input(f"Masukkan data ke-{i+1}: ")) data.append(nilai) return data def hitung_rata_rata(data): return sum(data) / len(data) def hitung_ragam(data): rata_rata ...
The main task of the code is to calculate and display the mean, variance, and standard deviation of input data. It retrieves data via `input_data()`, computes statistical measures using helper functions, and prints the results in a formatted manner.
def main(): data = input_data() rata_rata = hitung_rata_rata(data) ragam = hitung_ragam(data) simpangan_baku = hitung_simpangan_baku(data) print("\nHasil:") print("Rata-rata:", rata_rata) print("Ragam:", ragam) print("Simpangan baku:", simpangan_baku)
def convert_to_date_object(date_input): # Define a function that gets the last day for the given year and month def get_last_day(year, month): last_day = monthrange(year, month)[1] return last_day # Default date dictionary structure date_dict = { "start": {"year": "", "month...
The code processes user input by generating function calls to extract parameters (date, location, category, description), then queries a database (knowledge base or MySQL) to retrieve and filter event records based on these parameters, returning their IDs after timing the process.
def run(self, user_input): start_time = time.time() self.history.append({HUMAN_PROMPT: user_input}) function_prompt = function_call_prompt(user_input) function_response = self.model.completions.create( prompt=function_prompt, stop_sequences=["\n\nHuman:", "</param...
def __clean_target(self, interval: Interval): if self.dest_remote: self.__clean_remote_target(interval) else: self.__clean_local_target(interval) def build_rsync_command(self, interval: Interval, increment_name: str, temp_increment_name: str): cmd = f"{self.rsync_bin} -a ...
The main task of the code is to perform an incremental backup using rsync for a specified interval. It checks SSH status for remote connections, prepares the target directory, executes the rsync command, and handles success/failure scenarios. On success, it renames temporary files, rotates backups, and updates the last...
def synchronize(self, interval: Interval): if self.src_remote or self.dest_remote: status = self.__ssh.check_status() if not status: return self.logger.log(logging.INFO, "Running incremental backup for Interval: %s", interval.name) increme...
def muonConePt(muons): return op.map(muons, lambda lep: op.multiSwitch( (op.AND(op.abs(lep.pdgId) != 11, op.abs(lep.pdgId) != 13), lep.pt), (op.AND(op.abs(lep.pdgId) == 13, lep.mediumId, lep.mvaTTH > 0.50), lep.pt), 0.9*lep.pt*(1.+lep.jetRelIso) )) def lepton_associatedJetLessThanMediumB...
The code selects muons based on two criteria: (1) their cone Pt ≥ 10 GeV, and (2) either their associated jet is not a medium b-tag or they meet jet isolation (jetRelIso < 0.8) and pass a deepJet interpolation check. This filters muons likely to be "fake" (non-prompt) for analysis, excluding those with high jet activit...
def muonFakeSel(muons): return op.select(muons, lambda mu: op.AND( muonConePt(muons)[mu.idx] >= 10., op.OR(lepton_associatedJetLessThanMediumBtag(mu), op.AND(mu.jetRelIso < 0.8, muon_deepJetInterpIfMvaFailed(mu)))) )
def create(self): _, enc_file, acc = self.get_input_files() service, login, kw = self.get_input("create") c = Service(service, login, kw) new_acc = [] found = False for a in acc: if self.check_eq(a, c) and not found: self.log_out("(info) service/login found") found = True new_acc.append(c) ...
The code defines a `run` method that executes different operations based on the input command (`cmd`). Depending on the value of `cmd`, it calls corresponding methods like `create()`, `fetch()`, `update()`, `delete()`, or `list_data()` to handle specific tasks. This structure allows the class to dynamically route comma...
def run(self, cmd): if cmd == "create": self.create() elif cmd == "fetch": self.fetch() elif cmd == "update": self.update() elif cmd == "delete": self.delete() elif cmd == "list": self.list_data()
def _create_cells(self): for i in range(self._num_cols): col_cells = [] for j in range(self._num_rows): col_cells.append(Cell(self._win)) self._cells.append(col_cells) for i in range(self._num_cols): for j in range(self._num_rows): ...
This code initializes a maze structure by setting up grid dimensions, cell sizes, and creating a 2D cell array. It generates a random seed for reproducible maze patterns, breaks walls recursively to form paths, and establishes entrance/exit points. The main task is to construct a solvable maze with configurable size an...
def __init__(self, x1, y1, num_rows, num_cols, cell_size_x, cell_size_y, win=None, seed=None): self.root = self self._x1 = x1 self._y1 = y1 self._num_rows = num_rows self._num_cols = num_cols self._cell_size_x = cell_size_x self._cell_size_y = ce...
def fetch_kline_data(symbol, interval, limit=100): global accumulated_pnl base_url = 'https://fapi.binance.com/fapi/v1/klines' params = {'symbol': symbol, 'interval': interval, 'limit': limit} response = requests.get(base_url, params=params) data = response.json() df = pd.DataFrame(data, columns...
This function updates real-time cryptocurrency trading data by fetching kline information, calculating technical indicators (RSI, MACD, Bollinger Bands), analyzing market sentiment, and executing trading decisions based on predefined conditions. It visualizes price charts, order history, PNL metrics, and technical indi...
def update_kline_data(): global position, entry_price, margin, accumulated_pnl, order_type, scatter_points, last_price kline_data = fetch_kline_data(symbol, interval, limit) earliest_kline_time = kline_data.index.min() latest_kline_time = kline_data.index.max() get_position_risk(symbol, pnl_var) ...
def openingMove(self, board): return self.countSymbol(board, ".") <= 1 def generateFirstMoves(self, board): moves = [] moves.append([0] * 4) moves.append([self.size - 1] * 4) moves.append([self.half_the_size] * 4) moves.append([self.half_the_size - 1] * 4) return ...
The function generates valid moves for a player on a board. If it's the opening move, it returns pre-defined first or second moves based on the player. Otherwise, it iterates through each cell, checks for the player's pieces, and explores four directions (up, right, down, left) to find valid moves using the `check` met...
def generateMoves(self, board, player): if self.openingMove(board): if player == 'B': return self.generateFirstMoves(board) else: return self.generateSecondMoves(board) else: moves = [] rd = [-1, 0, 1, 0] cd = [0...
def f(self, state): return self.g(state) + self.h(state) def count_explored_state(self, state): self.num_of_explored_states += 1 if state.get_hash() not in self.unique_states_hash: self.unique_states_hash.add(state.get_hash()) self.num_of_unique_explored_states += 1 def a...
This code implements a search algorithm using a priority queue to explore states, checking if constraints are satisfied. It tracks explored states, manages state depth, and returns True if a goal state is found, otherwise False after exhausting the queue.
def start(self): self.goal_state_is_found = False self.frontier_states_queue = PriorityQueue() self.frontier_states_queue.push(self.start_state, self.f(self.start_state)) self.explored_states_hash = set() self.explored_states_hash_best_depth = dict() self.unique_states_ha...
def form_profile(motifs, k): nucleotides = ['A', 'C', 'G', 'T'] profile = { nucleotide: [0] * k for nucleotide in nucleotides } for motif in motifs: for i in range(k): nucleotide = motif[i] profile[nucleotide][i] += 1 for i in nucleotides: for j in range(k): profile[i][j] /= len(...
The function performs greedy motif search to find the best set of k-length motifs in t DNA sequences. It initializes with the first k-mers of each DNA, then iterates through all possible starting positions in the first DNA. For each position, it builds motifs by selecting the most probable k-mers in subsequent DNAs usi...
def greedy_motif_search(Dnas, k, t): bestmotifs = [ Dna[0:k] for Dna in Dnas ] L = len(Dnas[0]) for j in range(L - k + 1): window = Dnas[0][j:j+k] motifs = [ window ] for i in range(1, t): profile = form_profile(motifs, k) motif_i = most_probable_kmer(Dnas[i], profile, k) motif...
def min_list(num_digits): digit_list = [] for digit in range(1, num_digits+1): digit_list.append(digit) return digit_list def max_list(num_digits): max_digits_list = [] for digit in range(10 - num_digits, 10): max_digits_list.append(digit) return max_digits_list def sums(total, n...
The code generates a dictionary mapping each possible sum (from min to max) of a specified number of digits to the count of numbers with that sum. It calculates min and max totals, iterates through all possible sums, and populates the dictionary with sums computed via a helper function.
def create_dict_for_num_digits(num_digits): min_total = sum(min_list(num_digits)) max_total = sum(max_list(num_digits)) cur_total = min_total num_dict = {} print(f'\nCreating dictionary for {num_digits}, whose min total is {min_total} and max total is {max_total}') while cur_total <= max_total: ...
def calculate_level_2(self, word): n = int(len(word) / 2) one, two = word[:n], word[n:] result = self.calculate_frequency(one) result += self.calculate_frequency(two) return result def calculate_level_3(self, word): n = int(len(word) / 3) one, two = word[:n], word...
The code processes an input word by generating features through four methods: level-2, level-3, level-4 calculations, and level-2 bigram analysis. It converts the word to lowercase, deep-copies it to avoid mutation, concatenates results from each method into a list, and returns the combined output for further processin...
def __call__(self, word_in): word = deepcopy(word_in).lower() result = [] result += self.calculate_level_2(word) result += self.calculate_level_3(word) result += self.calculate_level_4(word) result += self.calculate_level_2_bigram(word) return result
def match(self,dict1,dict_item,param1,param2): """The function matches different keys/values of a dictionary""" current_value="" for i in dict1: if i[param1] == dict_item: current_value = i.get(param2) return current_value def get_info(self,url_file,offset=20)...
The function creates meals for a specified nutrition plan using TOML data, retrieves the nutrition plan's ID, iterates through meal entries in the TOML file, creates each meal with associated time, adds meal items if present, and returns the creation result.
def create_meals_with_tomlfile(self, toml_data, nutritionplan_name): """The function creates new meals for a specific nutrition plan""" nutritionplan_id=self.match(self.get_info('nutritionplan/')[1].get('results'),nutritionplan_name,'description','id') for meal in toml_data: request ...
def match(self,dict1,dict_item,param1,param2): """The function matches different keys/values of a dictionary""" current_value="" for i in dict1: if i[param1] == dict_item: current_value = i.get(param2) return current_value def get_info(self,url_file,offset=20)...
The function creates training days for a specified workout using TOML data. It retrieves the workout ID, iterates through each day in the TOML data, creates a training day with details, checks for exercise data, and adds exercises if present. It returns success/failure status and relevant data, halting on the first err...
def create_trainingdays_with_tomlfile(self,toml_data,workout_name): """The function creates new training days for a specific workout""" workout_id=self.match(self.get_info('workout/')[1].get('results'),workout_name,"name","id") for day in toml_data.get("days",{}): request=self.create...
def create_workout(self, workout_name="",description=""): """This function creates a new workout""" workout_data = {"id": "", "creation_date": "", "name": workout_name, "description": description} request = self.post_info('w...
The function creates a workout plan with a specified name and number of training days. It generates exercises per day, using parameters for total exercises and muscle-group-specific exercises. It retrieves the workout ID, creates each training day iteratively, and verifies the workout's existence in the system.
def create_complete_workout(self, workout_name, no_days, total_exercise_number=6, muscle_group_exercise_number=2): """ The function creates a complete workout. You can chose the number of training days and also the name of the workout. Also, the function select a given number of exercise...
def toml_to_dict(self, toml_file): """The function takes a toml file as argument and returns a dictionary""" with open(toml_file) as f: data = f.read() data = toml.loads(data) return data def create_nutritionplans_with_tomlfile(self, toml_data): """The function takes ...
This method generates workout and nutrition plans by converting TOML files into dictionaries and using them to create structured workout and nutrition plan data through dedicated helper methods.
def create_workouts_and_nutritionplans(self,workouts_file,nutritionplans_file): """This method creates workouts and nutrition plans""" workouts_data=self.toml_to_dict(workouts_file) nutritionplans_data=self.toml_to_dict(nutritionplans_file) self.create_nutritionplans_with_tomlfile(nutrit...
def masterKey( x1: list[float], x2: list[float], y1: list[float], y2: list[float] ) -> bytes: """Generate the AES master key using the four co-ordinate samples generated using a chaotic function Args: x1 (list[float]): One of the co-ordinates generated via chaotic function map x2 (list[floa...
The main task of the code is to encrypt and decrypt an image using a custom key generated from coordinates. It reads an image's byte data, encrypts it with the key, saves the encrypted image, decrypts it back, and verifies if the decrypted data matches the original. The code also checks the encryption/decryption succes...
def __main(): # x1, x2, y1, y2 = getCoordinates(total_samples=4) # key = masterKey(x1,x2,y1,y2, ) # x1, x2, y1, y2 = getCoordinates(total_samples=4, length_1=2.0000000000000001) # key1 = masterKey(x1,x2,y1,y2) key = masterKey([0,1,2,3],[0,1,2,3],[0,1,2,3],[0,1,2,3]) print(f"master key length: {...
def create_empty_directory(path: Path): logging.info(f'Creating empty directory: "{path}"') if path.exists(): shutil.rmtree(path) path.mkdir(parents=True) def read_from_file(path: Path) -> List[str]: logging.info(f'Reading from file: "{path}"') with path.open("r") as file: return fil...
The main task of the code is to process a LaTeX slide deck by reading input from a specified file path, generating output in a newly created directory named "out_<input filename>", executing slide processing tasks, cleaning up the output directory, and logging completion. The workflow includes resolving input paths, cr...
def main(_): input_path = Path(FLAGS.input).resolve() output_directory = input_path.parent / f"out_{input_path.stem}" create_empty_directory(output_directory) slide_deck = LatexSlideDeck(read_from_file(input_path)) process_deck(slide_deck, input_path, output_directory) cleanup_output_directory(o...
def deconvolveHE(I): I = I.astype(np.float32) h = I.shape[0] w = I.shape[1] c = I.shape[2] assert (c == 3), "An image must be RGB!" M = np.array([[0.644211, 0.716556, 0.266844], [0.092789, 0.954111, 0.283111]]) M = np.vstack((M, np.cross(M[0, :], M[1, :]))) M = M / np.transpose(np.tile(...
The code aligns an input image with a DAPI image using a registration technique. It processes the HE image (deconvolution, grayscale conversion, inversion), prepares DAPI and input images, calculates a translation transformation between them, applies it to the input image via affine warping, and returns the aligned ima...
def register_dapi2he(dapi, he, img): dapi = copy.copy(dapi) H = deconvolveHE(he) H = rgb2gray(H) H = 255 - H dapi[:,:,0] = 0 dapi[:,:,1] = 0 DAPI = np.uint8(np.zeros(he.shape)) DAPI[:dapi.shape[0],:dapi.shape[1],:] = dapi new_img = np.uint8(np.zeros(he.shape)) ...
def deconvolveHE(I): I = I.astype(np.float32) h = I.shape[0] w = I.shape[1] c = I.shape[2] assert (c == 3), "An image must be RGB!" M = np.array([[0.644211, 0.716556, 0.266844], [0.092789, 0.954111, 0.283111]]) M = np.vstack((M, np.cross(M[0, :], M[1, :]))) M = M / np.transpose(np.tile(...
The main task of the code is to register an H&E-stained image (he) with a FISH image (fish) by aligning their DAPI channel using translation-based registration. It deconvolves and inverts the HE image, extracts the DAPI channel from the FISH image, computes the translation transformation, and applies it to both the HE ...
def register_HE2FISH_translation(he, mask, fish): H = deconvolveHE(he) H = rgb2gray(H) H = 255 - H DAPI = fish[:, :, 2] Transformation = registration_corr2_translation(H, DAPI) new_he = cv2.warpAffine(he, Transformation, (he.shape[1], he.shape[0]), flags=cv2.INTER_LINEAR, ...
def create_dominoes(): dominoes = [] for i in range(7): for j in range(i, 7): dominoes.append([i, j]) random.shuffle(dominoes) return dominoes def print_snake(snake): shown = "" if len(snake) < 7: for domino in snake: shown += str(domino) else: ...
The code simulates a dominoes game where the computer and player take turns placing dominoes. It initializes game pieces, determines the starting player based on the highest double, and alternates turns until a winner is decided. The game checks for a win condition each round, displaying the state of the board, stock, ...
def main(): doubles = [[6, 6], [5, 5], [4, 4], [3, 3], [2, 2], [1, 1], [0, 0]] while True: dominoes = create_dominoes() computer = dominoes[:7] player = dominoes[7:14] stock = dominoes[14:] snake = [] status = "" for double in doubles: if dou...
def print_board(board): for row in board: print(" | ".join(row)) print("-" * 9) def is_game_over(board): # Check rows, columns, and diagonals for i in range(3): if board[i][0] == board[i][1] == board[i][2] != ' ': return True if board[0][i] == board[1][i] == board...
The code implements a Tic-Tac-Toe game where a human player (O) competes against an AI (X). It initializes a 3x3 board, alternates turns, validates player moves, and uses the `find_best_move` function for AI decisions. The game checks for win/draw conditions, evaluates the board's state, and displays results. The core ...
def main(): board = [[' ' for _ in range(3)] for _ in range(3)] player_turn = True # True for player, False for AI print("Welcome to Tic-Tac-Toe!") print_board(board) while not is_game_over(board): if player_turn: row, col = map(int, input("Enter your move (row and column): ")...
def __read_images_from_disk_and_calibrate(self): if not os.path.exists(gc.g_calib_images_folder): sys.exit("No saved images found") images = glob.glob(os.path.join(gc.g_calib_images_folder, "*.jpg")) if len(images) < gc.g_minimum_calib_images: sys.exit("Insufficient cali...
The main task of the code is to calibrate a camera using either pre-captured images or real-time input. If pre-captured images are used, it directly calibrates them. Otherwise, it initializes a camera feed, displays live frames with chessboard corner detection, and allows user interaction via keyboard commands to save ...
def calibrate_camera(self): if self.__use_precaptured_images: self.__read_images_from_disk_and_calibrate() else: self.__initialize_capture() print( "space to save image, c to start calibration, d to dump images to disk, q to quit") while(Tr...
def login(self, email=None, password=None): self.logger.debug("Logging into eWeLink") if email is None and password is None: return body = { "appid": APP_ID, "email": email, "password": password, "ts": time.time(), "version...
The code initializes a class instance by loading credentials from a CSV file, setting up authentication parameters, handling login, and starting a device refresh loop. It configures email/password, switches to development mode if credentials are missing, populates device data, and initiates a background refresh process...
def __init__(self): self.headers = None self.bearer_token = None self.user_apikey = None self.email = None self.password = None self.dev_mode = False self.devices = {} self.refresh_list = {} try: with open('credentials.csv', 'r') as ...
def on(self, outlet=-1): try: self.set_switch('on', outlet) except Exception as e: self.logger.error(f"\tFailed to turn switch on {e}, refreshing login and seeing if that fixes it") self.device_manager.login() self.set_switch('on', outlet) def off(self, ou...
This function toggles a device's power state or a specific outlet's state. If outlet=-1, it switches the device's overall state (on/off). For a specific outlet, it reverses its current state. After toggling, it triggers a hard reload of the device via the device manager to apply changes.
def toggle(self, outlet=-1): if outlet == -1: if self.switch == 'off': self.on() elif self.switch == 'on': self.off() else: raise Exception('Trying to toggle a device outlet that returns None') else: if self....
def getData(): if not path.exists(local_store_file): save_object([]) with open(local_store_file, 'rb') as inp: data_list = pickle.load(inp) return data_list def get_all_address(): return [node.get_ip_addr() for node in getData()] def match_port(addr, port): for node in getData(): ...
The code validates a node's address and port. If the address exists in the address book, it checks port validity using `match_port` and returns the result. If invalid, it returns `None`. If the address is new, it creates a `Node` object, adds it to the node list, saves the data, and returns the new node.
def check_node_valid(address, port): node_list = getData() address_book = get_all_address() if address in address_book: result = match_port(address, port) if result: return result else: return None else: new_node = Node(address, port) node...
def get_all_filename(): return [file.getName() for file in getData()] def getData(): if not path.exists(local_store_file): save_object([]) with open(local_store_file, 'rb') as inp: data_list = pickle.load(inp) return data_list def saveData(data): save_object(data)
The function registers new files from the input list into a system by checking if each file is not already present in the existing filename set. It creates new File objects for unseen files, updates the data storage, and returns the list of newly added files.
def register_local_file(file_list): added_file = [] filename_space = get_all_filename() data = getData() for file in file_list: if file not in filename_space: new_file = File(file) data.append(new_file) added_file.append(new_file) saveData(data) return...
def getData(): if not path.exists(local_store_file): save_object([]) with open(local_store_file, 'rb') as inp: data_list = pickle.load(inp) return data_list def remove_file_by_name(name): data = getData() for file in data: if file.getName() == name: data.remove(fi...
The main task of the code is to remove specified files from a data structure based on the given type ("obj" or "name"). If type is "obj", it directly removes each file object from the data; if type is "name", it calls a separate function to remove files by their names. Finally, the modified data is saved.
def remove_files(files, type): data = getData() if type == "obj": for file in files: data.remove(file) if type == "name": for file in files: remove_file_by_name(file) saveData(data)
def getData(): if not path.exists(local_store_file): save_object([]) with open(local_store_file, 'rb') as inp: data_list = pickle.load(inp) return data_list def check_node_valid(address, port): node_list = getData() address_book = get_all_address() if address in address_book: ...
This function registers a file chunk with a peer node by validating the peer's address/port, locating the corresponding node in the data list, updating its chunk information, and saving the changes. It returns the registration status or False if the peer is invalid.
def register_file_chunk(chunk_index, peer_addr, peer_port, filename, file_size): data_list = getData() check_node_valid(peer_addr, peer_port) index = -999 for i in range(len(data_list)): if data_list[i].get_ip_addr() == peer_addr and data_list[i].get_port() == peer_port: index =...
def check_node_valid(address, port): node_list = getData() address_book = get_all_address() if address in address_book: result = match_port(address, port) if result: return result else: return None else: new_node = Node(address, port) node...
This function handles client requests in a distributed file system by processing different operation codes. It registers files on nodes, retrieves file lists, locates files, and manages chunk registration. It validates nodes, sends success/failure responses, and closes connections after handling requests like file regi...
def threaded_client(connection, addr): address, port = addr print("incoming connection: ", address) # giving success response code connection.send(str.encode('200')) # recieving main content of data data = connection.recv(2048) data = json.loads(data.decode("utf-8")) if data['code'] == 1...
def menu_1(): return input(""" 1. Add flashcards 2. Practice flashcards 3. Exit """) def add_flash_card(): global session while True: choice_2 = menu_2() if choice_2 == "1": while True: question = input("\nQuestion:\n") if question.replace(" ", "")...
The main task of the code is to present a menu-driven interface for flashcard management. It repeatedly displays options to add a flashcard, practice, or exit. Based on user input, it executes corresponding actions: '1' triggers adding a flashcard, '2' initiates practice mode, and '3' exits the loop. Invalid inputs pro...
def main(): while True: choice_1 = menu_1() if choice_1 == "1": add_flash_card() elif choice_1 == "2": practice() elif choice_1 == "3": print('\nBye!') break else: print(f"{choice_1} is not an option")
def add_heuristic(master_table: MovieTableWrapper, matches: List[Tuple], title: str, year: int) -> List[Tuple]: new_matches = [] for match in matches: # if no_matches < settings.MATCH_LIST_LIMIT rest is padded with pandas nan if pd.isnull(match[0]): continue match_year = mas...
The code merges two movie tables by adding non-duplicate entries from a supplementary table into a master table. It checks for exact IMDb ID matches, uses fuzzy title matching for potential duplicates, and allows interactive confirmation for conflicts. Non-matching entries are added by default, with the updated master ...
def merge_tables(args: Namespace) -> None: if args.interactive: log.info('Starting in interactive mode') else: log.warning('Not in interactive mode!') if not Gui.prompt_confirm('Do you want to continue?'): sys.exit(0) master_table = MovieTableWrapper.from_csv(args.master...
def check_winner(self,screen): if self.board.get_winner(): self.game_over = True self.board.draw(screen) #issues self.winner = self.current_player.name return True elif self.board.is_full(): self.game_over = True return True...
The code runs a Connect-4 game using Pygame, handling user input, AI moves, timer logic, and rendering. It initializes the game window, processes events like mouse clicks and timer updates, toggles pause/resume for the timer, draws player pieces, executes moves for human and AI players, checks for a winner, updates the...
def run(self): pygame.init() screen = pygame.display.set_mode((self.width, self.height)) pygame.display.set_caption("Connect-4") screen.fill((255, 255, 255)) self.board.draw(screen) # Start the main loop for the game while not self.game_over: for ev...
def handle_args(): parser = ArgumentParser() #num_gpus = 0 #backend = "ddp_cpu" #batch_size = 1 if backend == "ddp" else num_gpus #batch_size = 2 # client arguments parser.add_argument( "--mode", default="train", choices=("train", "test"), type=str, ...
The main task of the code is to train or test a self-supervised MRI reconstruction model using the FastMRI dataset. It applies k-space masking for subsampling, initializes data loaders with transformations, and runs either training (with optional checkpointing) or inference based on the specified mode. The model is exe...
def main(): args = handle_args() pl.seed_everything(args.seed) # creates k-space mask for transforming mask = subsample.create_mask_for_mask_type(args.mask_type, args.center_fractions, args.accelerations) train_transform = SslTransform(mask_func=mask, use_seed=False) val_transform = SslTransfor...
def intro(): print("Do you wish to enter SAGA") print("Enter [1|0]") print("Enter '1' to add or book a room") print("Enter '0' to exit") def loginSystem(): while True: email = input("Enter your email:") if (email_validation(email)): print("Your Email Address is valid") ...
The code manages a room booking system with a login interface. It initializes a room array, handles user choices (login, booking), and uses a loop for menu navigation. The main tasks include user authentication, room allocation, and maintaining a list of room numbers.
def main(): global intRoomNumber intRoomNumber = [0 for _ in range(100)] # Main Array choice = -1 logged_in = False option = "" email = "" intro() while True: choice = int(input("Enter your choice:")) if choice == 0: print("* Thank you for visiting...
def calc_gamma(): gamma = '' with open('data/diagnostic.txt', 'r') as diag: bit = diag.readline().strip() bit_len = len(bit) tracker = [0] * bit_len eof = len(bit) == 0 lines = 0 while not eof: lines += 1 i = 0 for digit in bit...
The code calculates power consumption by multiplying gamma and epsilon rates derived from binary data, then determines life support ratings by multiplying O2 and CO2 values obtained from a driver function. Both tasks involve processing binary numbers to compute critical metrics for energy and life support systems.
def main(): gamma = calc_gamma() epsilon = int(calc_epsilon(gamma), 2) gamma = int(gamma, 2) print(f'Gamma: {gamma}\nEpsilon: {epsilon}\nPower Consumption: {gamma * epsilon}') o2 = driver(True) co2 = driver(False) print(f'O2: {o2}\nCO2: {co2}\nLife support rating: {o2 * co2}')
def get_broadcast(): with open('data/BITS_stream.txt', 'r') as stream: return d_code(stream.read()) def parse(packet, count=-1): if packet == '' or int(packet, 2) == 0: return 0 if count == 0: return parse(packet) version = int(packet[:3], 2) typeID = int(packet[3:6], 2)...
The main task of the code is to retrieve broadcast data using `get_broadcast()`, compute and print a "version sum" via `parse()`, and calculate a "data sum" using a faster method `parse_faster()` with an offset of 0. The function structure is defined but currently lacks implementation details for the helper functions.
def main(): broadcast = get_broadcast() print(f'Version sum is: {parse(broadcast)}') print(f'Data sum is: {parse_faster(broadcast, 0)}') pass
def read_heightmap(): with open('data/heightmap.txt', 'r') as raw: heightmap = [[int(height) for height in line] for line in raw.read().split('\n')] return heightmap def find_low_points(heightmap): height = len(heightmap) length = len(heightmap[0]) low_points = {} for x in range(heig...
The code processes a heightmap to identify low points, calculates the risk level based on these points, determines basins around the low points, and prints the risk level and basin index. The main task involves analyzing terrain data to assess risks and locate basins in a heightmap.
def main(): heightmap = read_heightmap() points = find_low_points(heightmap) risk = risk_level(points) basin = basins(heightmap, points) print(f'Risk level: {risk}\nBasin index: {basin}')
def map_instructions(): with open('data/thermal_instructions.txt', 'r') as raw: coords = [] folds = [] lines = [line.strip() for line in raw.readlines()] for line in lines: if line == '': ind = lines.index(line) folds = [[el for el in re.su...
The code processes folding instructions on a set of coordinates. It retrieves coordinates and fold steps via `map_instructions()`, applies each fold to the coordinates using `do_folds()`, maps the resulting coordinate positions with `map_coords()`, and prints the final mapped output. The primary task is to simulate pap...
def main(): coords, folds = map_instructions() coords = do_folds(coords, folds) mapped = map_coords(coords) print(mapped)
def noise_to_image(self, frame): noisy = frame.astype(np.int16) noisy = frame + np.random.randint(-10, 11, size=(self.height, self.width)) noisy[noisy > 255] = 255 noisy[noisy < 0] = 0 noisy = noisy.astype(np.uint8) return noisy def compute_lbsp(frame, threshold=0.3): ...
This code processes a video frame to update a background model using multiple reference frames (N models), incorporating both color and texture (LBP) features. It computes a mask identifying foreground regions by comparing the current frame with stored background models, then replaces selected background pixels with cu...
def apply(self, frame, flow_bg=None): if not self.got_first_frame: self.height, self.width = frame.shape[0], frame.shape[1] self.got_first_frame = True self.N = self.bootstrap_frames self.R = np.ones((self.height, self.width, self.N), dtype=np.uint8) * self.R ...
def darknet53(name=None): x = input = keras.Input([None, None, 3]) x = darknetConv(x, 32, 3) x = darknetConv(x, 64, 3, strides=2) x = darknetBlock(x, 64, 1) x = darknetConv(x, 128, 3, strides=2) x = darknetBlock(x, 128, 2) x = darknetConv(x, 256, 3, strides=2) x = x_36 = darknetBlock(x, ...
This code defines a YOLOv3 object detection model using Keras. It constructs a neural network with Darknet-53 backbone, processes multi-scale feature maps (512/256/128 filters), generates bounding box predictions via YoloOutput layers, applies post-processing (yolo_boxes) with anchor scaling, and performs non-max suppr...
def YOLOv3(size=320, channels=3, anchors=yolo_anchors, masks=yolo_anchor_masks, classes=80): x = input = keras.Input([size, size, channels], name='input') x_36, x_61, x = darknet53(name='Darknet_53')(x) x = YoloConv(512, name='yolo_conv_0')(x) output_0 = YoloOutput(512, len(masks[0]), cla...
def useTracesToColor(profitLossRegions, updated_fig): greenTraceX = profitLossRegions[0] breakEvenTraceX = profitLossRegions[1] redTraceX = profitLossRegions[2] greenTraceY = profitLossRegions[3] breakEvenTraceY = profitLossRegions[4] redTraceY = profitLossRegions[5] # print(greenTra...
The function updates an equity chart by processing user interactions (relayoutData) to adjust trading positions, calculate equity changes from executed trades, and redraw the chart with updated values. It handles position entry/exit parameters, profit/loss regions, and modifies global variables tracking equity, positio...
def update_equity_chart(children, relayoutData, equity_chart_fig): global equity_values global isAddedPosition global firstWasChangedShape global newVal global perecentToRisk global lastCategory global count2 global histData updated_fig = initEquityChart(equity_values) profitL...
def isAutoSized(relayout_data): # print(relayout_data) first_key = getFirstKeyOfRelayoutData(relayout_data) return first_key.startswith('xaxis.autorange') def autoRangeRelayout(): # find date od the first candle and date of the last candle # find min and max value of yaxis # return relayout_dat...
The main task of the code is to adjust the relayout data's axis ranges when a zoomed-in view is applied. It calculates appropriate y-axis margins based on min/max values in the selected date range, updates the x-axis to match the zoomed dates, and adjusts the secondary y-axis (Volume) scale. The function returns adjust...
def makeAdjustedRelayout(fig, relayout_data): # if autorange return relayout_data and do not proceed if isAutoSized(relayout_data): return autoRangeRelayout() if not isChangedZoom(relayout_data): return global_result adjustedRel = {} dates = getDatesFromRelayoutData(re...
def isClickedAnnotation(relayout_data): first_key = getFirstKeyOfRelayoutData(relayout_data) return first_key.startswith('annotations') def whatKindOfAnnotation(relayout_data): first_value = next(iter(relayout_data.values())) # exception for dashed line when up to date, stupid af i know if first...
The code dynamically adjusts a candlestick chart's data and visualization based on user annotations. It extends or trims the global `data` DataFrame by loading new candle data or removing old entries, updates the `occupiedCandle` tracking list, and regenerates the plot with preserved shapes and axis ranges. The functio...
def loadNewData(relayout_data): global data global selected_option global fig global occupiedCandle global timeframe if not isClickedAnnotation(relayout_data): return dash.no_update else: kindOfAnnotation = whatKindOfAnnotation(relayout_data) if kindOfAnnotation =...
def addRRRatioAnnotation(fig, entryPrice, entryDate, endDate, stopLoss, takeProfit): RRratio = abs(takeProfit - entryPrice) / abs(entryPrice - stopLoss) fig.add_annotation( go.layout.Annotation( name= str(entryDate), text="RR ratio: " + str(round(RRratio, 2)), x =...
This function processes click events on a candlestick chart to add trade positions (long/short) with visual indicators (rectangles for risk/reward). It updates global state variables for equity tracking, position data, and chart zoom/pan adjustments. The function returns the modified chart figure and a counter, handlin...
def display_click_data(clickData, n_clicks, value, children, relayout_data): ctx = dash.callback_context # print(dash.callback_context.triggered[0]['prop_id'].split('.')[1]) point_index = None global occupiedCandle global wasRadioChanged global prevRadio global lastRelDataOfZoom global ...
def reset(self): self.board.fill(0) self.number.fill(0) self.k = 1 self.result = 0 def draw(self): if self.gui: self.gui._draw_background() self.gui._draw_chessman(self.board[0, :, :]-self.board[1, :, :], self.number) def execute_move(self, p, x, y): ...
This code implements a turn-based game where two players alternate making moves on a board. It initializes the game, alternates between players, executes moves, checks for a win condition, and displays the board state. The loop continues until a player wins or an invalid move is made, with moves logged and printed for ...
def play(self, p1, p2): players = {1:p1, -1:p2} self.reset() pi = 1 self.draw() while True: if pi == 1: standardBoard = self.board else: standardBoard = self.board[[1, 0]] x, y = players[pi].get_move(standardBoar...
def accuracy_score(y_act, y_pred): '''Computes accuracy. Args: y_act: actual labels: y_pred: predicted labels. Returns: accuracy ''' y_act = np.squeeze(y_act) y_pred = np.squeeze(y_pred) return np.mean(y_act == y_pred) def mean_absolute_error(y_act, y_pred): '''C...
The function `compute_score` calculates a specified evaluation metric (e.g., accuracy, precision, F1-score) for a given pair of actual and predicted labels. It selects the appropriate scoring method based on the `name` parameter and returns the computed score, enabling flexible model performance assessment. Your return
def compute_score(y_act, y_pred, name): '''computes the score of a specified type. Args: y_act: actual labels: y_pred: predicted labels. name: type of score to apply. Returns: the score of the specified type. ''' if name =='accuracy': return accuracy_score(y_...
def get_base_model(model_name: str) -> object: logging.info("Entered the get_base_model method of MainUtils class") try: if model_name.lower().startswith("xgb") is True: model = xgboost.__dict__[model_name]() elif model_name.lower().startswith("cat") is True: ...
The main task of the code is to tune a machine learning model's hyperparameters using provided training and test data. It retrieves a base model, identifies optimal parameters, applies them, trains the model, evaluates performance on test data, and returns the model's score, the tuned model object, and its class name. ...
def get_tuned_model( self, model_name: str, train_x: DataFrame, train_y: DataFrame, test_x: DataFrame, test_y: DataFrame, ) -> Tuple[float, object, str]: logging.info("Entered the get_tuned_model method of MainUtils class") try: model = s...
def clear_files(): temp_folder = os.getcwd() + '/temp' for item in os.listdir(temp_folder): if item.endswith('.csv'): os.remove(os.path.join(temp_folder, item)) def collect_data(state, cities, year): for city in cities: if not os.path.exists(f"{os.getcwd()}/data/{state}/{cit...
The main task of the code is to collect data for specified states, cities, and years while handling exceptions by restarting the process up to four times, with a 30-minute pause if maximum exceptions are reached, ensuring data collection completion through iterative retries and error logging.
def main(state, cities, year, exceptions): clear_files() try: collect_data(state, cities, year) except KeyboardInterrupt: logging.exception('Script interrupted.') except Exception as e: logging.exception(f"Exception Thrown ({exceptions + 1}).") if exceptions...
def input_number(self, v): if self.state == READY: self.state = INPUT self.stak[-1] = v self.show_number() else: try: self.stak[-1] = self.stak[-1] * 10 + v self.show_number() except Exception: se...
This code initializes a calculator GUI by connecting buttons to mathematical operations, memory functions, and display controls. It sets up 10 number buttons, links operation buttons to corresponding functions, initializes memory variables, and resets the display.
def __init__(self, parent=None): QtWidgets.QWidget.__init__(self, parent) self.setupUi(self) for n in range(0, 10): getattr(self, "btn{}".format(n)).pressed.connect( lambda v=n: self.input_number(v) ) self.btn_ac.pressed.connect(self.reset) ...
def tableSection(self, frame): # Table Frame self.frameTable = tk.Frame(frame, bg="#D2B48C") self.frameTable.pack() #Button to sign out self.backButton = tk.Button(frame, text="↩Back to Main Menu", f...
This code initializes a GUI application for a library system, setting up the main window, connecting to a database, and creating user interface elements such as tables for displaying library books and user-owned books, along with buttons for loaning and returning books. It configures the layout, styling, and interactiv...
def __init__(self, root, username): self.name = username self.root = root self.root.title("Browse the library") self.root.geometry("1000x700") self.root.minsize(1400, 700) self.root.maxsize(1800, 900) #Inittialize the library self.library = Database("Libra...
def tableSection(self, frame): # Table Frame self.frameTable = tk.Frame(frame, bg="#D2B48C") self.frameTable.pack() #Button to sign out self.backButton = tk.Button(frame, text="↩Back to Main Menu", f...
The main task of the code is to initialize a GUI-based library management system. It sets up a window with two frames: one for displaying library books and another for managing user-owned books. Features include loan/return buttons, interactive tables with sorting, and database integration via SQLite. The interface all...
def __init__(self, root, username): self.name = username self.root = root self.root.title("Browse the library") self.root.geometry("1000x700") self.root.minsize(1400, 700) self.root.maxsize(1800, 900) #Inittialize the library self.library = Database("Libra...
def isLeapYear(md): centuryRemainder = getCenturyRemainder(md.year) endOfCentury = md.year % 100 == 0 divisibleBy400 = md.year % 400 == 0 if endOfCentury: if divisibleBy400: return True else: return False else: if centuryRemainder % 4 == 0: ...
The main task of the code is to calculate and explain the day of the week for a given "mysteryDate" using the Doomsday algorithm. It breaks down steps like checking leap years, determining the doomsday reference date, adjusting totals with century anchors, and accounting for year components (twelves, additional years, ...
def printExplanation(dateParts, mysteryDate, dayDict): print(f'\nThe day you are trying to find is {mysteryDate.strftime("%B %d, %Y")}') if isLeapYear(mysteryDate): print('This is a leap year') doomsday = calculateDoomsDay(mysteryDate) print(f'The Doomsday for {mysteryDate.strftime("%B")} is {d...
def set_projectile_data(self, projectile_data, provided_beta=True): """ Sets the projectile data: Z_p : Z of projectile q : charge of projectile. e_kin : collision energy in MeV/u. I_p : first ionization potential of projectile in keV n_0: prin...
The main task of the code is to calculate the total beam lifetime (tau) in seconds by summing contributions from electron loss (EL) and electron capture (EC) processes for all compound gases. It computes cross-sections for each gas type, estimates lifetimes using additivity rules, and combines them via inverse summatio...
def calculate_total_lifetime_full_gas(self, projectile_data=None): """ Calculates beam lifetime contributions for electron loss and electron capture from beam gas interactions with all compound gases Parameters ---------- projectile_data: optional, not needed if ...
def mat_mul_vec(M, v): return [dotp(row, v) for row in M] def matrix(i, o): M = [[0,0,0] for i in [0,1,2]] j = (i + 1) % 3 k = (i + 2) % 3 M[i][i] = 1 M[j][k] = -o M[k][j] = o return M def rot_colors(i, colors): new_colors = copy.copy(colors) j = (i + 1) % 3 k = (i + 2) % 3 ...
The function `rot_cube` applies a rotation to a Rubik's cube representation based on the given axis `i` and rotation mask. It transforms each coordinate in the cube by rotating it around the specified axis, updating positions and colors accordingly. Coordinates with a rotation orientation of 0 remain unchanged, while o...
def rot_cube(move, cube): (i, mask) = move new_cube = {} for xyz, cs in cube.items(): c = xyz[i] # the coordinate on the axis along which we rotate o = mask[c+1] # the orientation of the rotation if o == 0: new_cube[xyz] = cs else: new_xyz = tuple(mat...
def getArgs(): return sys.argv[1:] def getData(options): logger.log("Getting data for " + str(options[0]) + " with options " + str(options[1:]), debug) if options[3] == None and options[4] == None: data = yf.download(options[0], start=options[1], end=options[2]) elif options[3] != None and opti...
The main task of the code is to parse command-line arguments, validate stock data intervals, fetch stock price data using the parsed options, and save the retrieved data to a file. It handles two modes: a single 60-minute interval data fetch or a loop over date ranges for other intervals, with error handling for invali...
def main(): validArgList = ["-t", "-s", "-e", "-p", "-i"] args = getArgs() # get the arguments frome the command line and organize them options = argParser.parseArgs(args, validArgList) if options == -1: logger.error("Exiting", debug) return -1 # checks if stock data is up...
def generate_points_2d(N, seed=1234) : """ Generate toy dataset of 3 clusters each with N points. Parameters -------------------- N -- int, number of points to generate per cluster seed -- random seed Returns -------------------- points -- list of Points, dataset...
The code performs three main tasks: (1) Analyzes the LFW face dataset by visualizing samples, computing mean images, and applying PCA to explore dimensionality effects on image reconstruction. (2) Clusters a synthetic 2D dataset using k-means and k-medoids with random and optimal initializations. (3) Evaluates clusteri...
def main() : ### ========== TODO : START ========== ### # part 1: explore LFW data set #get LFW dataset with labels X, y = get_lfw_data() #plot a couple of input images show_image(X[0]) show_image(X[1]) show_image(X[2]) show_image(X[3]) #compute the mean of all the images and plo...
def scrape_booklist_from_blog(entry_url, target_json): entry_url = MY_BLOG_URL.format(entry_url) print(f"Scraping from {entry_url} to {target_json}...") booklist = list() pattern = re.compile(r'<li>(.+?) – <a href="(.+?)">(.+?)</a> \((\d{4}|\?)\)</li>') for line in BeautifulSoup( requests.ge...
The main task of the code is to aggregate book data from multiple sources (URL or JSON file, and a text file), remove duplicates, sort the combined list, and output the result as JSON or HTML. It processes book entries by either scraping from a blog or loading from a JSON file, then appending additional entries from a ...
def add_books(src_entry_url, booklist_json, links_src_txt, target_html, target_json): print(f"Adding books from {links_src_txt} to {target_html}...") assert src_entry_url or booklist_json, "Neither source entry URL nor source .json provided" if not src_entry_url: booklist = load_utf_json(booklist_js...
def refresh_firsttime(self): print('first time?') new_names = np.array([]) for opendir in self.opendirs: new_names= np.concatenate([get_waves(opendir),new_names]) print('making auds') self.sounds = [] true_names = [] for name in new_names: ...
This function checks for new audio files by comparing recently discovered files against a previously stored list. If new files are detected, it triggers a refresh with the new sounds; otherwise, it indicates no new sounds were found and refreshes accordingly.
def check_newbies(self): if self.filecheck==False: self.refresh_firsttime() return else: with open(os.getcwd() + '\\HnKfile_list.dat','r') as f: old_file_list = np.array([file[:-1] for file in f.readlines()]) f.close() new_files...
def update_graph(self): num_pts = len(self.backend.files) Xdim = ceil(np.sqrt(num_pts)) Xarray = np.tile(np.arange(Xdim),Xdim).astype(float) Yarray = np.transpose(Xarray.reshape(Xdim,Xdim)).ravel().astype(float) self.pointset = np.array([Yarray[:num_pts],Xarray[:num_pts]]) ...
This code initializes an application by checking for an existing data file (HnK_paths.dat). If found, it displays a loading GUI with a progress message and image, loads the file's paths, processes data via a backend, updates visuals, then opens the main window. If the file is absent, it triggers a path creation process...
def Initialize(self): if os.path.exists(os.getcwd() + '\\HnK_paths.dat'): openwindow = QtGui.QWidget() openwindow.setWindowIcon(self.icon) openwindow.resize(QtCore.QSize(300,300)) openwindow.setWindowTitle('Hugs\'n\'Kisses') Initialtext = QtGui.QLabel(...
def setup(): print("") print("") print("") def intro(animal): add_repeating(animal) assemble(verse) def phrase(animal): for animal in animals: stanza(animal) def finish(animal): print(dict_verse[animal])
The code's main task is to recite a structured poem by sequentially executing setup, introduction with "fly," a phrase about animals, and a conclusion with "horse," likely generating or presenting a narrative or lyrical sequence with these elements.
def recite_poem(): setup() intro("fly") phrase(animals) finish("horse")
def pop_key(dictionary, key): key_data = '[]' if key in dictionary.keys(): key_data = dictionary[key] del dictionary[key] return key_data def validate_data(data, columns, table_name): is_valid = True errors = {} # Check data for column in columns: if column not in DB_...
The main task of the code is to create a user by validating input data, storing user information in a database, saving an uploaded photo, and associating additional data (emails, phones) with the user. It returns a result indicating success or errors, including transaction completion and handling of related database re...
def create_user(user_data, photo_file): user_data['photo_path'] = '' # Get emails and phones fields as string and parse to dict emails = json.loads(pop_key(user_data, 'emails')) phones = json.loads(pop_key(user_data, 'photos')) # Check if user data is valid is_valid, errors = validate_data(dat...
def splitNodes(self, Node, value=None): """ Splits the Node into two Nodes : L1 & L2 It inserts the entry in the Leaf Node. Args: - self: mandatory object refrence. - Node : the Node which is to be split. - value : the MBR (Mininimum Bounding Region) of the the entry wh...
This method inserts a given MBR (Minimum Bounding Region) into a leaf node of a tree structure. If the leaf node overflows (contains more than two entries), it splits the node into two, adjusts the tree hierarchy, and propagates any necessary changes upward. The method ensures proper node splitting and tree rebalancing...
def addRecord(self, LeafNode, value): """ Enters the entry in the leaf Node. It inserts the entry in the Leaf Node. Args: - self: mandatory object refrence - LeafNode : the Leaf Node in which the entry is to be inserted. - value : the MBR (Mininimum Bounding Region) of ...
def splitNodes(self, Node, value=None): self.IsRootSplit = Node is self.Root Entry_List = Node.Pointer min_x = min(Entry_List, key=lambda x: x[0][0][0]) max_x = max(Entry_List, key=lambda x: x[0][0][1]) min_y = min(Entry_List, key=lambda x: x[0][1][0]) max_y = min(Entry_...
This function adds a new record to a tree structure by inserting a value with a None child, splits nodes if necessary, adjusts the tree for balance, and updates the root if a split occurs, ensuring the tree remains properly structured and balanced.
def addRecord(self, L, value): x = L.add([value, None]) X = None if x > 2: L, X = self.splitNodes(L, value) L, X = self.adjustTree(L, X) if self.IsRootSplit: self.RootAdjust(L, X)
def _sendAllResourceRequestsWithRetry(self, need: list[int]) -> bool: """Makes all resource requests below the process need vector with retries and cooldowns. This method is necessary because of the behavior of concurrent threads. It is possible that on all resource request sends in a given time interv...
The code's main task is to repeatedly request resources for a process until all required resources are allocated or a timeout occurs. It calculates the remaining resource needs, sends requests with retries, updates the need vector upon approval, and handles failures or success accordingly. The loop continues until the ...
def run(self): """While the process needs resources to complete, makes resource requests until a timeout or process completion. Runs while timeout hasn't occurred for a process state or process has recieved all needed resources Overrides threading.Thread run() function. """ ne...
def dropCollection(db): db.course.drop() dire=os.getcwd() os.chdir(dire+"/result") for file in glob.glob("*.txt"): os.remove(file) print ("Collection dropping and empty collection creating are successful") os.chdir(dire) def crawlData(db): try: data = input("Please input the...
The main task of the code is to provide a menu-driven interface for interacting with a MongoDB database named "comp4332". It allows users to drop collections, crawl data, search courses, predict waiting list sizes, train models, or exit. The program connects to MongoDB, displays a menu, processes user choices, executes...
def main(): # here, we need to implement for the flow # display the menu try: print("Making a MongoDB connection...") client = MongoClient("mongodb://localhost:27017") # Getting a Database named "university" print("Getting a database named \"comp4332\"") ...
def obtain_flags(flags): byte1 = bytes(flags[:1]) QR = '1' OPCODE = '' for bit in range(1,5): OPCODE += str(ord(byte1)&(1<<bit)) AA = '1' TC = '0' RD = '0' RA = '0' Z = '000' RCODE = '0000' return int(QR+OPCODE+AA+TC+RD, 2).to_bytes(1, byteorder='big')+int(R...
The function constructs a DNS response packet by extracting transaction IDs, flags, and query counts from input data, resolving domain names, and formatting response sections (header, question, and resource records) into byte streams for network transmission.
def buildresponse(data): # Transaction ID Transaction_ID = data[:2] # Build flags Flags = obtain_flags(data[2:4]) # Question count QDCOUNT = b'\x00\x01' # Answer count name_type = get_recources(data[12:]) if not name_type[0]: print("No local Domain with the name: " + name...
def items(chat_id): mydb = connect() mycursor = mydb.cursor() mycursor.execute("SELECT name, category, price, description, image, id FROM pizzas_items") rows = mycursor.fetchall() n = 0 for row in rows: # TODO caption = f"{row[0]}\nCategory: {row[1]}\n Price: {row[2]}\n{row[3]}" ...
The code manages a user session for a shopping cart, handling item additions/removals, user info collection (name, phone, address), and state transitions. It updates a database with session data, edits cart messages dynamically, and guides users through steps to finalize orders.
def handle_session(chat_id, sessiondb, command, session_id, message_id): mycursor = sessiondb.cursor() mycursor.execute("SELECT state, cart_id FROM sessions WHERE chat_id = " + str(chat_id)) row = mycursor.fetchall() if not row: # calculate cart_id (message will be edited cart_id = messa...
def connect(): db = mysql.connector.connect( host="localhost", user="root", password="", database="luay's_users" ) return db def checkSession(chat_id, db): mycursor = db.cursor() mycursor.execute("SELECT state FROM sessions WHERE chat_id = " + str(chat_id)) row = ...
This code processes incoming messages by extracting data like message ID, chat ID, and command (from text/data). It handles user sessions, sends pizza menu images, and interacts with a database to fetch items. Commands like /buy, /start, /menu, and /all trigger specific actions, including sending photos, managing sessi...
def handle(msg): print(msg) if "message_id" in dict.keys(msg): message_id = msg['message_id'] else: message_id = 0 mydb = connect() if "chat" in dict.keys(msg): chat_id = msg['chat']['id'] else: chat_id = msg['from']['id'] if "location" in dict.keys(msg): ...