dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def get_account(index=None, id=None): if index: return accounts[index] if network.show_active() in ["hardhat", "development", "ganache", "mainnet-fork"]: return accounts[0] if id: return accounts.load(id) return accounts.add(config["wallets"]["from_key"]) def get_contract(contrac...
The function deploys an `AdvancedCollectible` contract using Chainlink's VRF coordinator and LINK token, pays the required LINK fee, creates a collectible NFT, waits for transaction confirmation, and returns the deployed contract and creation transaction.
def deploy_and_create(): account = get_account() advanced_collectible = AdvancedCollectible.deploy( get_contract("vrf_coordinator"), get_contract("link_token"), config["networks"][network.show_active()]["keyhash"], config["networks"][network.show_active()]["fee"], {"from"...
def deploy_snft(): account = get_account() smart_nft = SmartNFT.deploy({"from": account}) tx = smart_nft.createCollectible(sample_token_uri, {"from": account}) tx.wait(1) print( f"Awesome, you can view your NFT at {OPENSEA_URL.format(smart_nft.address, smart_nft.tokenCounter() - 1)}" ) ...
The main task of the code is to execute a sequence of deployment and creation processes, including deploying SNFTs, setting up mocks, deploying and creating assets, and generating metadata, likely for blockchain-based projects or smart contracts.
def main(): deploy_snft() deploy_mocks() deploy_and_create() create_metadata()
def __map_conversations(self): conversations = self.get_conversations() histories = [self.get_msg_history(x["id"]) for x in conversations] for x, y in zip(conversations, histories): self.conversation_mapping[x["id"]] = y["current_node"] def __check_response(self, response): i...
The code sends a user prompt to a chatbot API, managing conversation history via UUIDs. It constructs a request with metadata, streams the response, and yields incremental results including message content and IDs. It handles new or existing conversations, maps IDs if needed, and updates internal state for continuity.
def ask(self, prompt, conversation_id=None, parent_id=None): """ Ask a question to the chatbot :param prompt: String :param conversation_id: UUID :param parent_id: UUID """ if conversation_id is None: # new conversation parent_id = str(uuid.uuid4()) ...
def read_window(window: sg.Window): read_result = window.read() if read_result is None: print("Window not found") end_loop() return read_result def unfollow_mode_main(): time.sleep(3) orientate_terminal() state_restart() while True: state = "unfollow_mode" if ...
The code creates a GUI for a Twitter bot with options to select follow, unfollow, or block modes. It displays instructions, allows mode selection via radio buttons, and triggers corresponding functions when "Start" is clicked. Additional buttons provide help, donation links, and exit options. The GUI uses PySimpleGUI, ...
def main_gui(): out_text = """-Python Twitter bot - Matthew Miglio ~June 2022\n\n -1. Holding space terminates the program, and holding pause pauses the program.\n\n -2. Specify the location of your microsoft edge in the config file @ \\AppData\\Roaming\\py-tb\\config.json\n Make sure the path is sp...
def check_quit_key_press(): if keyboard.is_pressed("space"): print("Space is held. Quitting the program") sys.exit() if keyboard.is_pressed("pause"): print("Pausing program until pause is held again") time.sleep(5) pressed=False while not(pressed): tim...
The function navigates to a profile page by clicking a specified location on the screen, verifies if the action was successful, and returns "restart" if it fails. It logs each step using a provided logger and checks for a quit key press to allow termination.
def get_to_profile_page(logger): logger.log("Getting to profile page.") check_quit_key_press() #click profile icon on the left side logger.log('Clicking profile page') click(93,517) time.sleep(1) if not(check_if_on_profile_page()): logger.log("Failed to get to profile page.") ...
def check_quit_key_press(): if keyboard.is_pressed("space"): print("Space is held. Quitting the program") sys.exit() if keyboard.is_pressed("pause"): print("Pausing program until pause is held again") time.sleep(5) pressed=False while not(pressed): tim...
The code automates unfollowing users on a social media platform by locating and clicking "unfollow" buttons, handling confirmation popups, and refreshing the page when no more targets are found. It uses image recognition to detect buttons, pyautogui for clicks, and checks for a quit key press to terminate the process.
def unfollow_from_following_page(logger): check_quit_key_press() has_more_to_unfollow=True while has_more_to_unfollow: #find coord of unfollow following_button_coords = look_for_unfollow_button_in_unfollow_page() #unfollow if given a coord if following_button_coords is not N...
def check_quit_key_press(): if keyboard.is_pressed("space"): print("Space is held. Quitting the program") sys.exit() if keyboard.is_pressed("pause"): print("Pausing program until pause is held again") time.sleep(5) pressed=False while not(pressed): tim...
This function performs random downward scrolling actions a variable number of times (0 to 7), alternating between fast and regular scrolling with different sleep intervals, while logging progress and checking for a quit key press in each iteration.
def randomly_scroll_down(logger,scroll_limit=7): scrolls=random.randint(0,scroll_limit) while scrolls>0: check_quit_key_press() logger.log(f"Scrolling: {scrolls}") if random.randint(1,2)==1: fast_scroll_down() time.sleep(3) else: scroll_down()...
def check_quit_key_press(): if keyboard.is_pressed("space"): print("Space is held. Quitting the program") sys.exit() if keyboard.is_pressed("pause"): print("Pausing program until pause is held again") time.sleep(5) pressed=False while not(pressed): tim...
This function clicks a list of follow buttons at specified coordinates, logs actions, and manages follow throttling. It randomly skips some clicks, logs each follow, and checks for user quit commands. If throttling is detected, it reduces the follow count and waits for a set duration to avoid limits.
def click_list_of_follow_buttons(follow_button_list,logger): length=len(follow_button_list) logger.log(f"Clicking the follow buttons that were given. I have {length} coords") index=0 while index<length: check_quit_key_press() current_coord=follow_button_list[index] if (random . r...
def randomly_scroll_down(logger,scroll_limit=7): scrolls=random.randint(0,scroll_limit) while scrolls>0: check_quit_key_press() logger.log(f"Scrolling: {scrolls}") if random.randint(1,2)==1: fast_scroll_down() time.sleep(3) else: scroll_down()...
The main task of the code is to navigate from a followers list page to a random follower's profile page by scrolling randomly and clicking on a randomly generated coordinate within the followers list. The function uses a logger to track progress, scrolls down to load followers, selects a random vertical position, click...
def get_to_random_account_from_followers_list(logger): #starts on followers list page, ends on the page of a random follower #randomly scroll logger.log("Randomly scrolling.") randomly_scroll_down(logger,scroll_limit=20) #target account logger.log("Clicking chosen random account.") x_c...
def get_to_profile_page(logger): logger.log("Getting to profile page.") check_quit_key_press() #click profile icon on the left side logger.log('Clicking profile page') click(93,517) time.sleep(1) if not(check_if_on_profile_page()): logger.log("Failed to get to profile page.") ...
The main task of the code is to randomly select a follower from the user's followers list, check if the account's name and bio contain blacklisted strings, and ensure it hasn't been followed before. If valid, it logs the account and adds it to the database; otherwise, it restarts the process. The function navigates to ...
def get_to_random_account_from_followers_list_with_blacklist(logger,users_ive_followed_from_database): # get to profile page if get_to_profile_page(logger) == "restart": return "restart" time.sleep(1) # get to list of my followers if get_to_followers_page(logger) == "restart": retur...
def _print_discriminant(self): discriminant = self.discriminant() if discriminant > 0: print("Strictly positive discriminant.") if discriminant == 0: print("Nul discriminant.") if discriminant < 0: print("Negative discriminant.") def _second_...
The code's main task is to print the number of solutions and their values for a polynomial equation based on its degree. For degree 2, it calculates and prints quadratic solutions after displaying the discriminant. For degree 1, it prints the single solution. For degree 0, it handles the constant equation case. The met...
def solve_print(self): if self.degree == 2: self._print_discriminant() solutions = self._second_degree_solution() if len(solutions) == 1: print(f"There is 1 solution: {solutions[0]:.2f}") if len(solutions) == 2: print(f"There are 2 ...
def _second_degree_solution(self): a, b, c = self.get_a_b_c() discriminant = self.discriminant() if discriminant >= 0: return ((-b - math.sqrt(discriminant)) / (2*a)), if discriminant < 0: thingy = math.sqrt(-discriminant) / (2*a) ret...
The code solves equations by checking their degree and delegating to specific methods: `_second_degree_solution()` for degree 2, `_first_degree_solution()` for degree 1, and `_zero_degree_solution()` for degree 0.
def solve(self): if self.degree == 2: return self._second_degree_solution() if self.degree == 1: return self._first_degree_solution() if self.degree == 0: return self._zero_degree_solution()
def sleep(self, time_in_sec): """Sleeps for the specified amount of time while keeping odometry up-to-date Args: time_in_sec (float): time to sleep in seconds """ start = self.time.time() while True: state = self.create.update() if state is not...
The main task of the code is to navigate a robot to a goal using RRT path planning, obstacle avoidance via wall-following, and particle filter localization. It initializes sensors, generates a path, converts it to waypoints, follows each waypoint while switching between goal-seeking and wall-following modes, and execut...
def run(self): """main function""" '''initialization''' self.create.start() self.create.safe() self.create.sim_get_position() self.create.drive_direct(0, 0) # request sensors self.create.start_stream([ create2.Sensor.LeftEncoderCounts, ...
def parseCommandLine(): """ Read command line parameters """ parser = argparse.ArgumentParser( description='Calculate long-term trends in photometric database.') parser.add_argument('--log_level', dest='log_level', default='INFO', choices=['DEBUG', 'INFO'], help='Set th...
This code generates long-term photometric zero-point (ZP) trend plots for specified telescopes/sites, using a database interface. It creates individual telescope plots, summary plots for multiple telescope types, color term plots, and optionally renders an HTML page with all generated figures. The task involves parsing...
def longtermphotzp(): plt.style.use('ggplot') matplotlib.rcParams['savefig.dpi'] = 300 matplotlib.rcParams['figure.figsize'] = (8.0, 6.0) filenames = [] args = parseCommandLine() if args.site is not None: crawlsites = [args.site, ] else: crawlsites = telescopedict if a...
def draw_computer(self, i): image = self.get_correct_pic(i) keys_list = list(self.comp_dict.keys()) self.row_count += 1 self.image = QtWidgets.QLabel(self.centralwidget) self.image.setGeometry(QtCore.QRect(self.x_image, self.y_image, 171, 171)) self.image.setText("") ...
The main task of the code is to set up a graphical user interface (GUI) for a window displaying paginated components. It initializes UI elements like a headline, navigation arrows, page indicators, and an options button, while configuring layout parameters and connecting interaction events to handle page navigation and...
def setupUi(self, MainWindow, num_of_comps, comp_dict): self.is_sub_wnd_open = False self.comp_dict = comp_dict self.setFocusPolicy(QtCore.Qt.StrongFocus) self.comp_arr = [] self.x_image = X_DRAW_START self.y_image = Y_DRAW_START self.row_count = 0 self.cu...
def generate_config_and_query(self, build_message: BuildMessage) -> Tuple[TrainConfig, dict]: logger.info(f"Generating config for Train {build_message.id}") config = TrainConfig.construct() # transcribe values from build message config.id = build_message.id config.source = { ...
The main task of the code is to build a Docker image for a training process based on a provided BuildMessage. It generates configuration and query data, constructs a container image, adds necessary files (config, query, train data) to the container, commits and pushes the image to a registry, and updates the build stat...
def build(self, build_message: BuildMessage) -> BuilderResponse: # generate the config and query based on the build message try: logger.info(f"Generating train config from message - Train {build_message.id}") config, query = self.generate_config_and_query(build_message) ...
def build(self, build_message: BuildMessage) -> BuilderResponse: # generate the config and query based on the build message try: logger.info(f"Generating train config from message - Train {build_message.id}") config, query = self.generate_config_and_query(build_message) ...
This method processes incoming messages to handle train build commands. It validates START requests, initiates builds, registers META data, stops builds via STOP, and checks STATUS. It interacts with Redis/Vault stores, logs errors, and returns BuilderResponse status objects with train ID and status. The core task is o...
def process_message(self, msg: dict) -> BuilderResponse: message = QueueMessage(**msg) logger.info(f"Processing message: {message}") train_id = message.data.get("id") if not train_id: logger.error("Train id not found in message") status = BuildStatus.NOT_FOUND ...
def get_doc_dicts(): bow_df = load_bow() grouped_df = bow_df.groupby(['doc_index', 'doc_id']).max().reset_index(drop=False) idx_id_dict = grouped_df[['doc_id']].to_dict()['doc_id'] id_idx_dict = {v: k for k, v in idx_id_dict.items()} del grouped_df return idx_id_dict, id_idx_dict def load_course...
The code generates course recommendations using different models: Course Similarity (based on cosine similarity with a threshold), User Profile (directly returns profile-based scores), K-means clustering (recommends courses from the user's cluster), and KNN (predicts ratings for unseen courses). It constructs a DataFra...
def predict(model_name, params): if model_name==models[0]: # Course Similarity model sim_threshold = 0.6 if "sim_threshold" in params: sim_threshold = params["sim_threshold"] / 100.0 idx_id_dict, id_idx_dict = get_doc_dicts() si...
def find_leaf_state(self, start_node): path_to_node = [] node = start_node while len(self.get_children(node)) > 0: path_to_node.append(node) node = max(self.get_children(node), key=lambda n: self.ucb(n, self.curr_player_id)) return node, path_to_node def expand(se...
This code performs a Monte Carlo Tree Search (MCTS) step: it finds a leaf node, checks if the game is done, expands the node if unvisited, selects the best child via UCB, rolls out to get results, then backpropagates the outcome (visits and values) along the path from the leaf to root, updating all nodes with the new e...
def step(self, parent_nodes_path): node, path_to_node = self.find_leaf_state(self.curr_start) full_path_from_root = parent_nodes_path + path_to_node + [node] game = node['game'] # If the game is done, just get the evaluation if game.is_done(): ts = game.get_evaluat...
def physicsDraw(self): if mouse_buttons()[0]: self.physicsPoints[self.physicsDrawIndex].append(mouse_pos()) if mouse_buttons()[2] and len(self.physicsPoints[self.physicsDrawIndex]) > 2: self.physicsDrawIndex += 1 self.physicsPoints.append([]) def offGridDraw(self): ...
The code's main task is to determine which drawing method to execute based on the current state (physicsEnabled or offGridEnabled) and mouse position. It skips drawing if the mouse hovers over specific buttons, then calls either physicsDraw(), offGridDraw(), or gridDraw() accordingly to render the appropriate visual el...
def draw(self)->None: if self.saveButton.rect.collidepoint(mouse_pos()) or self.loadButton.rect.collidepoint(mouse_pos()) or self.physicsEnabledButton.rect.collidepoint(mouse_pos()) or self.offGridButton.rect.collidepoint(mouse_pos()): return if self.physicsEnabled: self...
def eventLoop(self)->None: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() self.panInput(event) self.draw() def drawTileBorders(self)->None: scaledTileSize = self.getScaledTileSize(self.tileSize) ...
This method clears the display, handles events, draws game elements (tiles, borders), UI buttons, and a red origin marker, updating the visual state for each frame in a game or application interface.
def run(self, dt:float)->None: self.displaySurface.fill('white') # drawing self.eventLoop() self.drawTileBorders() self.drawTiles() self.saveButton.draw() self.loadButton.draw() self.physicsEnabledButton.draw() self.offGridButton.d...
def nibli(r,tr, traj1, t_start): return r - interpolate(tr,traj1, t_start) def u_vel(r,tr,traj1,traj_v1, t_start): # need to build up trajectory of particle speeds! nib = nibli(r,tr,traj1, t_start) return (c*nib/np.linalg.norm(nib,axis=0))-interpolate(tr,traj_v1, t_start) def interpolate(tr,hist, t_start): ...
The code computes the electric field (E-field) at position r, incorporating relativistic effects from velocity (v) and acceleration (a) terms. It calculates contributions from the position-velocity product (term2) and a cross product involving acceleration (term3), scaled by a normalization factor (term1). The result c...
def E_field(r,tr,traj1,traj_v1,traj_a1, t_start): # disregard acceleration dependent term and run again # then compare to see what difference the acceleration makes. const = Q / (4*np.pi*epsilon) nib = nibli(r,tr, traj1,t_start) u0 = u_vel(r,tr, traj1,traj_v1, t_start) dot_prod = nib...
def handle_user_input(self): for event in pg.event.get(): if event.type == pg.QUIT or (event.type == pg.KEYDOWN and event.key == pg.K_ESCAPE): self.running = False elif event.type == pg.MOUSEBUTTONDOWN and not self.board.final_state() and not self.board.is_full(): ...
This code manages a game loop for a Tic-Tac-Toe-like game using Pygame. It handles user input, AI moves, updates the screen, checks for win/draw conditions, displays winning lines, pauses, and resets the game. The loop runs at a set FPS, ensuring smooth gameplay and proper state transitions between player turns and gam...
def run(self): clock = pg.time.Clock() while self.running: self.handle_user_input() if self.mode == 'AI' and self.player == AI and not self.board.final_state() and not self.board.is_full(): self.handle_ai_move() self.player = 'X' ...
def get_args(): p = ap.ArgumentParser() # IO Parameters p.add_argument("--log_dir", default="experiments/t5/testing", help="output directory") p.add_argument("--cached_dataset_path", default=None, help="location of pre-trained dataset") p.add_argument("--raw_d...
The code's main task is to run an experiment using a T5 model for a specified benchmark. It processes command-line arguments, initializes a T5 tokenizer and model configuration, loads or caches a dataset, adjusts dropout rates, and executes the experiment. Key steps include argument validation, dataset handling, model ...
def main(): args = get_args() if args is None: return # Clean up args. args.benchmark = args.benchmark.lower() if args.train_tasks == ['all-tasks']: args.train_tasks = DATASET_MAP[args.benchmark].all_tasks # Initialize seed and args. device = set_seed(args) logger = in...
def load_squad(self, tokenizer, mode): extension = 'v1.1.json' train_split = False if mode == 'train': train_split = True if mode == 'dev' or mode == 'train': mode = 'train' elif mode == 'test': mode = 'dev' path = os.path.join(self.raw...
This method routes data loading to task-specific functions based on the input task parameter, using a tokenizer and mode. It delegates to methods like load_squad, load_sst, etc., each handling unique data formats. The function acts as a dispatcher, simplifying task-specific data processing by calling the appropriate lo...
def load_data(self, task, tokenizer, mode='dev'): # All of these tasks have a unique loading functions, for which I am very sorry. # The actual loading & processing code itself comes from: # https://github.com/salesforce/decaNLP if task == 'squad': return self.load_squad(tok...
def get_3d_station_location(stationsfile, station=str(), colname_lon=str(), colname_lat=str(), colname_agl=str()): """ Function to get the lat, lon and agl of a station given the station name and the stationsfile. """ lat = stationsfile[stationsfile['code'] == station][colname_lat].values[0] lon = stat...
The main task of the code is to execute a footprint-flux multiplication process for atmospheric modeling, combining footprint data with flux datasets (e.g., PARIS, CTEHR) to simulate observed concentrations at specific stations. It filters flux and footprint files by date ranges, processes variables, and writes results...
def main(filepath, sim_length, fluxdir, stilt_rundir, fluxvarnamelist, stationsfile, stationcode, outpath, bgfilepath, obspack_list, lats, lons, non_obspack_sites=None, perturbationcode=None, sum_vars=None, verbose=None, fluxtype=None, start_date=None, end_date=None, mp_start_date = None, mp_end_date...
def getLinkID(yt_link: str, split_by: str = 'v=') -> str: meta = yt_link.split('?') if '&' in meta[-1]: meta = [string for string in meta[-1].split('&') if split_by in string] return meta[-1].split(split_by)[-1] def getCaptions(vid_id: str) -> str: try: captions = YouTubeTranscriptApi.ge...
The code processes a list of video entries to extract metadata (title, captions, comments, URL) using YouTube API, handling errors like missing data or API quota limits. It constructs a list of dictionaries containing video information, logging issues and halting on quota exceedance.
def videoData(self, videos: list) -> list: final_list = [] for video in tqdm(videos, desc='Processing Videos'): data_dict = {} try: # get title data_dict['title'] = video['title'] except TypeError: logging.debug("Getting data for a sin...
def get_data(file): return pd.read_csv(file, header=0) def normalize(data): for col in data.columns: avg = data.loc[:, col].mean() stdev = data.loc[:, col].std() data.loc[:, col] = (data.loc[:, col] - avg) / stdev def run_gradient_descent(features, targets, coefficients, alpha, iters): ...
The code performs linear and kernel regression on life expectancy data, using command-line or default parameters. It loads, cleans, and normalizes data, splits into training/test sets, trains models via gradient descent, evaluates with R²/adjusted R², visualizes results, and outputs coefficients. It also compares predi...
def main(): if len(sys.argv) >= 4: """ command-line input option """ filename = sys.argv[1] feature_headers = sys.argv[2:-1] target_header = [sys.argv[-1]] data_headers = target_header + feature_headers else: #Data source: https://www.kaggle.com/ku...
def createTables(conn, cursor): tables = ['Movie_Has_Genres', 'Movie_Has_Keywords', 'Movie_Has_Production_Companies', 'Movie_Has_Production_Countries', 'Movie_Has_Spoken_Languages', 'Genres', 'Keywords', 'Production_Companies', 'Production_Countries', 'Spoken_Languages', 'Movie...
This code sets up a local MySQL database named 'imdb' by creating its schema, importing data from CSV files, and executing predefined queries to answer homework questions. It connects to the database using credentials from command-line arguments or a default password, creates tables, populates them with data, and runs ...
def main(): password = 'password' if len(sys.argv) < 2 else sys.argv[1] conn = pymysql.connect( host = 'localhost', port = 3306, user = 'root', passwd = password) cursor = conn.cursor() # create DB # cursor.execute("DROP DATABASE IF EXISTS imdb") cursor.execute("CREATE DATABASE IF NOT EXISTS imd...
def getIsLaptop(): return hostnameInList(laptopNames) def getKeyboardLayouts(): layouts = ["no", "us"] if useUsKeyboardAsDefault(): layouts.sort(reverse=True) return layouts def get_display_info(): d = display.Display(':0') screen_count = d.screen_count() default_screen = d.get_default_screen() result = [] ...
This function initializes global configuration settings including terminal choice, color schemes, device type detection, keyboard layouts, OpenWeather API key retrieval, and screen count determination for system-specific customization.
def settingsInit(): global myTerm global colors global colors2 global isLaptop global keyBoardLayouts global openWeaterApiKey global numberOfScreens myTerm = "alacritty" # My terminal of choice colors = [["#16213E", "#0F3460"], ["#1c1f24", "#1c1f24"], ["#dfdfdf", "#dfdfdf"], ["#507DBC", "#507DBC"], ...
def _process_frame(self) -> results_collection.Results | None: try: frame = cv2.resize(self.input[region[0]:region[1], region[2]:region[3]], ISIZE) return self.model(frame, classes=0, verbose=self.log_inference)[0] except KeyboardInterrupt: msg = 'Tracker is shutting ...
The code processes video frames by detecting objects (boxes) and updating the current frame visualization. It triggers `on_absence()` if no objects are detected or `on_return(boxes)` if objects are present, while logging telemetry data. The update cycle is controlled by `_cnt_trigger` and `_cnt_update()` for frame coun...
def _update(self): if self._cnt_trigger: results = self._process_frame() if self.stopped or results is None: return self.current_frame = results.plot() boxes = results.boxes if not boxes: self.on_absence() ...
def _retrieve(self) -> bool: try: result, self.input = self.capture.read() return result except KeyboardInterrupt: msg = 'Tracker is shutting down (:retrieve)' self.release_with_telemetry(msg) def _update(self): if self._cnt_trigger: re...
The code's main task is to execute retrieval and update operations. It handles interruptions (KeyboardInterrupt) by logging a shutdown message and releases resources. For other errors, it logs the exception, prevents further execution by setting `stopped=True`, and returns `not self.stopped` to indicate success/failure...
def update(self) -> bool: try: self._retrieve() self._update() except KeyboardInterrupt: msg = 'Tracker is shutting down (:force)' self.release_with_telemetry(msg) except Exception as e: LOGGER.error(f'Error: {e}') msg = f'...
def first_bare_match(string, tr_list, rn_dict, rg_dict, rr_dict): # tar_str = string.lower() tar_gen = tar_str.split()[0] tar_corr, tar_cstat = input_correction(tar_str) fb_match = [[] for j in tr_list] fb_stat = [1000 for j in tr_list] # Exact matching for fb_1 in range(len(tr_list)): if tar_str in rr_dict...
This function sequentially maps an input string to taxonomic entries using multiple strategies: exact matching, closest taxon mapping, rule-based screening, and edit-distance-based intrageneric/intergeneric matching. It prioritizes results based on confidence scores, updating mappings iteratively. If rule-based screeni...
def phylosophos_sequential_mapping(string, ref_sel, cut_dist, tr_list, rn_dict, rg_dict, rr_dict): # Initialization ref_ord = 0 for pcm_1 in range(len(tr_list)): if ref_sel == tr_list[pcm_1]: ref_ord += pcm_1 break pc_map_map = [[] for j in tr_list] pc_map_stat = [1000 for j in tr_list] # Step 1. Exact...
def string_split_correction(string): sst = "" if len(string) >= 1: for ssc_1 in range(len(string)): if ssc_1 >= 1: if string[ssc_1-1] in [",", ".", ")"] and string[ssc_1] not in [" ", ")"]: sst += " " elif string[ssc_1] in ["("] and string[ssc_1-1] not in [" "]: sst += " " # if string[ssc...
The function performs core analysis by processing input names with manual corrections, mapping them against reference data using sequential mapping, and exporting results. It initializes reference order, applies name corrections via a manual dictionary or splitting, iterates through inputs to generate mapping outcomes,...
def phylosophos_core_analysis(input_list, tr_list, rn_dict, rg_dict, rr_dict, ref_type, lev_cutoff, manual_stat): # Initialization ref_ord = 0 for pcm_1 in range(len(tr_list)): if ref_type == tr_list[pcm_1]: ref_ord += pcm_1 break # Manual curation file import manual_dict = {} if manual_stat == True...
def _handle_input(self): for event in pygame.event.get(): if event.type == pygame.QUIT or (event.type == pygame.KEYDOWN ## to check input is from keyboard and event.key == pygame.K_ESCAPE): quit() is_key_presse...
The main task of the code is to run a game loop that continuously handles user input, updates game logic, and renders the game state while a flag (`self.flag`) remains `True`. The loop repeats these steps until the flag is set to `False`, effectively controlling the game's runtime.
def main_loop(self): while self.flag: self._handle_input() self._process_game_logic() self._draw()
def roll1(): dice = [] for _ in range(5): dice.append(randint(1,6)) return dice def display_values_on_dice(dice): for die in dice: print(str(die) + ' ', end="") print("\n") def reroll(dice): positions = list(map(int, input("What are the positions of dice you want to reroll: ").st...
The code handles a dice game turn for a player, allowing them to roll dice, reroll selected dice, and assign the resulting score to a category in their scoreboard. It validates user input, manages reroll options, checks for duplicate category selections, and applies a bonus for choosing the 'y' category. The function u...
def rolling(name, turn): bonus = 0 print("\n") print(f"Its {name}'s -----------> turn{turn+1}") roll_values = roll1() print("The values on 5 dice in first roll are: ") display_values_on_dice(roll_values) option = input("Do you want to reroll (y/n/q): ") if option == "q": quit() ...
def rolling(name, turn): bonus = 0 print("\n") print(f"Its {name}'s -----------> turn{turn+1}") roll_values = roll1() print("The values on 5 dice in first roll are: ") display_values_on_dice(roll_values) option = input("Do you want to reroll (y/n/q): ") if option == "q": quit() ...
This code simulates a turn-based game for a specified number of players. It collects player names, initializes a score board, and runs 13 rounds where each player takes a turn (via the `rolling` function). After each round, the score board is printed. Finally, it calculates final scores for all players, displays them, ...
def game(num_of_players): players = list(map(str, input(f"Enter names of {num_of_players} players: ").strip().split(" ")))[:] while(len(players) != num_of_players): players.extend(list(map(str, input("Enter names of other players: ").strip().split(" ")))[:]) for player in players: score_boar...
def cut_fold8(sk): Y = [] X = int_to_nparray32(sk) a = 0 for i in reversed(range(32)): for j in reversed(range(8)): a = ((a << 1) + ((X[j] >> i) & 1)) Y.append(a%256) return Y def edwards_double(P): (x1, y1, z1, t1) = P a = x1*x1 % q b = y1*y1 % q c = 2*...
This function performs scalar multiplication on an Edwards curve using a precomputed table. It initializes a point from a lookup table, applies a series of doubling and addition operations based on the input key's folded indices, and computes affine coordinates (x, y) and their product t modulo q. The result includes t...
def edp_BasePointMult(sk): cut = cut_fold8(sk) P0 = table_b_0[cut[0]] Sx = (P0[0] - P0[1]) % q Sy = (P0[0] + P0[1]) % q S = (Sx, Sy, 2, 0) for i in range(1, 32): S = edwards_double(S) S = edwards_add2(S, table_b_0[cut[i]]) (x, y, z, t) = S invz = inv(z) % q x = (...
def bit(h, i): return (indexbytes(h, i // 8) >> (i % 8)) & 1 def xrecover(y): xx = (y * y - 1) * inv(d * y * y + 1) x = pow(xx, (q + 3) // 8, q) if (x * x - xx) % q != 0: x = (x * I) % q if x % 2 != 0: x = q-x return x def isoncurve(P): (x, y, z, t) = P return (z % q !...
The function `decodepoint` decodes a point on an elliptic curve from a string `s`. It computes the `y`-coordinate by summing bits of `s` weighted by powers of 2, recovers the `x`-coordinate using `xrecover(y)`, adjusts `x` based on the parity of `x` and the last bit of `s`, constructs a point `P = (x, y, 1, (x*y) % q)`...
def decodepoint(s): y = sum(2 ** i * bit(s, i) for i in range(0, b - 1)) x = xrecover(y) if x & 1 != bit(s, b-1): x = q - x P = (x, y, 1, (x*y) % q) if not isoncurve(P): return "decoding point that is not on curve" return P
def hex_to_int(x): return nparray_to_int(hex_to_nparray(x)) def scalarmult_B(e): e = e % l P = ident for i in range(253): if e & 1: P = edwards_add(P, Bpow[i]) e = e // 2 assert e == 0, e return P def Hint(m): h = H(m) return sum(2 ** i * bit(h, i) for i in ra...
The function generates a digital signature for a message `m` using a secret key `sk` and public key `pk`, but is explicitly marked as unsafe for handling secret keys/data. It computes a random value `r`, derives a point `R` via scalar multiplication, and calculates a signature component `S` combining `r` with a hashed ...
def signature_unsafe(m, sk, pk): """ Not safe to use with secret keys or secret data. This function should be used for testing only. """ sk_int = hex_to_int(sk) r = (secrets.randbelow(2**200)) R = scalarmult_B(r) S = (r + Hint(encodepoint(R) + pk + m) * sk_int) % l return encodepoint...
def edp_BasePointMult(sk): cut = cut_fold8(sk) P0 = table_b_0[cut[0]] Sx = (P0[0] - P0[1]) % q Sy = (P0[0] + P0[1]) % q S = (Sx, Sy, 2, 0) for i in range(1, 32): S = edwards_double(S) S = edwards_add2(S, table_b_0[cut[i]]) (x, y, z, t) = S invz = inv(z) % q x = (...
The code converts a private key into multiple public key representations by performing elliptic curve operations, including point multiplication, addition with low-order points, and encoding. It generates eight distinct encoded public keys by manipulating the original private key and its inverse modulo l, then returns ...
def privatetopublickey(pk): pk1_edp = edp_BasePointMult(pk) (x, y, z, t, cut) = pk1_edp pk1 = (x, y, z, t) pk2_edp = edp_BasePointMult((l-pk)%l) (x, y, z, t, cut) = pk2_edp pk2 = (x, y, z, t) A0 = pk1 encoded0 = encodepoint(A0) A1 = pk2 encoded1 = encodepoint(A1) loword...
def int_to_pk(a): A = edp_BasePointMult(a) (x, y, z, t, cut) = A return (x%q, y%q) def public_key_sha256_dual(pk): hashed = hashlib.sha256(pk).digest() addr1 = int.from_bytes(hashed[0:8], 'little') pk[31] ^= 128; hashed = hashlib.sha256(pk).digest() addr2 = int.from_bytes(hashed[0:8], 'little'...
The code generates test addresses by randomly modifying secret keys, computing corresponding public keys, hashing them, and updating the address list with these generated test addresses for debugging or validation purposes.
def debug_generate(blocks, n_batch, regen_sk, B_mult_table_sk, random_sk_array, n_address_list, address_list_orig): sk_index_test = random.randint(0, blocks-1) B_mult_table_sk_random = random.randint(0, (n_batch-1)) regen_sk_random = random.randint(0, regen_sk-1) test_inc = (B_mult_table_sk[B_mult_tabl...
def get_t0(name_file): res = minimize_scalar(min_sum_r_sq) return res.x def get_idf_params1(t0, name_file, return_period): duration, ln_i_RP_ = get_idf_for_fit(name_file, return_period) ln_cte_list = [np.log(t0+d) for d in duration] #cte = ln(d * t0) (for IDF linearization) x = np.array(ln...
This function retrieves IDF (Infiltration-Detachment-Transport) parameters (t0, n, K, m) from input data files. It calculates t0 using `get_t0`, derives n from `get_idf_params1`, and extracts K/m from `get_idf_params2`. If `save_file=True`, it stores these parameters in a CSV file under 'Results/'. The main task is to ...
def get_final_idf_params(name_file, id_file = 'INMET_average', save_file = False): #t0 = 11.827 t0 = get_t0(name_file) n = get_idf_params1(t0, name_file, 2)[2] n = abs(n) #print(t0, n) K = get_idf_params2(t0, name_file)[1] m = get_idf_params2(t0, name_file)[2] #print(K, m) if sa...
def get_t0(name_file, MY_DISTRIBUTIONS, name_disag_file): res = minimize_scalar(min_sum_r_sq) return res.x def get_idf_params1(t0, name_file, MY_DISTRIBUTIONS, name_disag_file, return_period_list): duration, ln_i_RP_ = get_idf_for_fit(name_file, MY_DISTRIBUTIONS, name_disag_file, return_period_list) ...
This function computes IDF parameters (t0, n, K, m) by calling helper functions, then optionally saves these values to a CSV file. It retrieves t0 from `get_t0`, calculates `n` from `get_idf_params1`, and extracts `K` and `m` from `get_idf_params2`. Results are stored in a DataFrame and saved if `save_file` is True.
def get_final_idf_params(name_file, MY_DISTRIBUTIONS, name_disag_file, save_file = False): #t0 = 11.827 t0 = get_t0(name_file, MY_DISTRIBUTIONS, name_disag_file) n = get_idf_params1(t0, name_file, MY_DISTRIBUTIONS, name_disag_file, [2])[2] n = abs(n) #print(t0, n) K = get_idf_params2(t0, name_fi...
def get_t0(name_file, MY_DISTRIBUTIONS, dist, directory, disag_factor): res = minimize_scalar(min_sum_r_sq) return res.x def get_idf_params1(t0, name_file, MY_DISTRIBUTIONS, dist, return_period_list, directory = 'Results', disag_factor = 'nan'): duration, ln_i_RP_ = get_idf_for_fit(name_file, MY_DISTRIBUTIO...
This function computes IDF parameters (t0, n, K, m) by calling helper functions, then optionally saves these values to a CSV file in the specified directory. It retrieves t0 from `get_t0`, calculates `n` and `m` from `get_idf_params1` and `get_idf_params2`, and stores results if `save_file` is True.
def get_final_idf_params(name_file, MY_DISTRIBUTIONS, dist, directory = 'Results', disag_factor = 'nan', save_file = False): #t0 = 11.827 t0 = get_t0(name_file, MY_DISTRIBUTIONS, dist, directory, disag_factor) n = get_idf_params1(t0, name_file, MY_DISTRIBUTIONS, dist, [2], directory, disag_factor)[2] n ...
def execute_proper(): logger.info("Creating proper data files ...") then = time() wro = os.path.join(RMC.INPUT_DIR, RMC.PROPHET_INPUT_ALL + '.fac') pro = os.path.join(RMC.OUTPUT_DIR, RMC.PROPHET_INPUT_ALL_PROPER + '.csv') with open(wro, 'r') as orig: print("open orig") with open(p...
The main task of the code is to execute data processing tasks (proper, transpose, to_numpy, trim_and_split) based on command-line arguments, using Apache Spark for transpose and to_numpy operations. It initializes Spark context/session if required, runs corresponding functions conditionally, defaults all tasks to execu...
def main(): overall = time() logger.info("Main script started ...") proper = False transpose = False to_numpy = False trim_and_split = False spark = None sc = None for arg in sys.argv[1:]: if arg == 'proper': proper = True if arg == 'transpose': ...
def execute_pre_init(): from pyspark import SparkContext from pyspark.sql import SparkSession logger.info("Pre-initial data preparation ...") then = time() logger.info("Creating proper header ...") fac = os.path.join(RMC.INPUT_DIR, RMC.PROPHET_INPUT + '.fac') csv = os.path.join(RMC.OUTPU...
The main task of the code is to manage a machine learning workflow that initializes, trains, and tests models based on command-line arguments. It processes flags to load data, execute preprocessing, train models, and run tests, while handling data saving/loading and model configuration. The script defaults to training ...
def main(): overall = time() logger.info("Main script started ...") pre_init = False init = False train = False test = False fpp = None model = None model_file_name = None model_dir = None for arg in sys.argv[1:]: if arg == 'pre_init': pre_init = True ...
def parse_rock(rock, mappings): highest = get_highest(mappings) current = set() for y, line in enumerate(reversed(rock)): for x, char in enumerate(line): if char == ' ': continue current.add((x + 2, highest + 3 + y)) return current def put_and_illustrate...
The function simulates a rock falling through a grid, applying horizontal jet pushes and vertical drops until the rock can no longer move downward. It checks for valid movements, updates the rock's position, and marks its final resting place in the grid. Debug mode visualizes each step. The function returns the next je...
def drop_rock(rock, p_jet, mappings, debug=False): current = parse_rock(rock, mappings) if debug: print("Rock starts dropping") put_and_illustrate(current, mappings) print() while True: # Jet if can_move(current, jets[p_jet], mappings): current = move(cu...
def map_graph(): graph = {} for line in lines: coords = line.split(" -> ") for i in range(0, len(coords) - 1): srcX, srcY = [int(s) for s in coords[i].split(",")] destX, destY = [int(s) for s in coords[i + 1].split(",")] draw_line(graph, srcX, srcY, destX, des...
This code simulates sand falling into a grid structure until no more sand can be added. It initializes a map, determines the maximum y-coordinate, then iteratively drops sand units until the process completes. The final count of successfully placed sand units is printed as the result.
def solve_part_one(): graph = map_graph() max_y = find_max_y(graph) units = 0 done = False while not done: units += 1 done = drop_sand(graph, max_y) print(units - 1)
def map_graph(): graph = {} for line in lines: coords = line.split(" -> ") for i in range(0, len(coords) - 1): srcX, srcY = [int(s) for s in coords[i].split(",")] destX, destY = [int(s) for s in coords[i + 1].split(",")] draw_line(graph, srcX, srcY, destX, des...
The code simulates sand falling into a graph until the point (500,0) is occupied. It initializes a graph, calculates the maximum y-coordinate, and iteratively adds sand units, incrementing a counter each time, until (500,0) is blocked. The final count of sand units is printed.
def solve_part_two(): graph = map_graph() max_y = find_max_y(graph) + 2 units = 0 while (500, 0) not in graph: units += 1 drop_sand(graph, max_y, floor=True) print(units)
def read_input(): elves.clear() lines = [s.strip() for s in open("./input.txt").readlines()] for y, line in enumerate(lines): for x, char in enumerate(line): if char == '#': elves.add((x, y)) def spread(): destinations = {} proposals = set() movement = False ...
The code simulates 10 rounds of elves spreading, then calculates the number of empty spaces within the rectangular area bounded by the minimum and maximum coordinates of the elves. It iterates through each cell in this area, counting cells not occupied by elves, and prints the total count.
def solve_part_one(): read_input() for _ in range(10): spread() min_point, max_point = find_endpoints() space = 0 for y in range(min_point[1], max_point[1] + 1): for x in range(min_point[0], max_point[0] + 1): if (x, y) not in elves: space += 1 prin...
def _build_encoder(self): encoder_input = self._add_encoder_input() conv_layers = self._add_conv_layers(encoder_input) bottleneck = self._add_bottleneck(conv_layers) self._model_input = encoder_input self.encoder = Model(encoder_input, bottleneck, name="encoder") def _build_decod...
The main task of the code is to construct the components of an autoencoder model by initializing the encoder, decoder, and autoencoder itself. This method orchestrates the building process of the neural network's architecture, preparing it for training or inference by defining essential layers and connections between t...
def _build(self): self._build_encoder() self._build_decoder() self._build_autoencoder()
def recv_json_msg(self): status, msg_str = self.recv_msg() if status != True: return status, { "Error" : msg_str } json_dict = json.loads("{}".format(msg_str)) print(type(json_dict)) return True, json_dict def authenticate(self, auth_json): if auth_json == N...
The main task of the code is to handle an authentication request by receiving a JSON message, authenticating it, and returning a status and response. It checks the authentication result, sends a success response if valid, and propagates errors if any step fails. The function ensures proper message handling and authenti...
def request_authenticaton(self ): #return True, { "user_uid":"mtconnect", # "pass_key":"mtconnect", # "shopfloor_uid":"ShopFloor001", # "agent_uid": "Agent001", # "client_uid": "001" } status, auth_json = self.recv_js...
def request_authenticaton(self ): #return True, { "user_uid":"mtconnect", # "pass_key":"mtconnect", # "shopfloor_uid":"ShopFloor001", # "agent_uid": "Agent001", # "client_uid": "001" } status, auth_json = self.recv_js...
The main task of the code is to handle client authentication, establish a connection, and relay messages between the client and server until the client sends "BYE". It adds the client to a map, verifies authentication, stores session data, and maintains a bidirectional communication loop, terminating gracefully upon re...
def start(self, clientObj): #add client obj to client obj map auth_status, auth_data = self.request_authenticaton() if auth_status == False : print("Authentication Failed "); print(auth_data) self.cleanup() return #self.shopfloor_uid = co...
def preproc(df, df1, i_frame, d_hyper): t1 = time() h_framecols = d_hyper.h_framecols h_framecols = [k for k in h_framecols if k] # Remove empty entries from framecols # Should merge filter params below into hyper params order = 15 #order = 12 fs = 1/3600 # sampling frequency in Hz c...
The code performs time series forecasting by iteratively splitting the input DataFrame into training and test windows using sliding/expanding window strategies. It preprocesses data, trains models, generates forecasts, calculates RMSE for evaluation, and accumulates results across iterations. The hyperparameters dictat...
def framestudy(df, df_iter, d_hyper): t1 = time() h_framestudy = d_hyper.h_framestudy k = 0 # i iterates in h_frame[0] increments between 0 and len(df) - max_win_size # Why max_win_size? Should probably be stepsize or forecast size. for i in range(0,len(df),h_framestudy[0]): # If i+min_...
def searchCompanyFromPO(self, text): poLike = re.search('T-P[0,O]-(\d{8})',text) if poLike != None: query = 'select id, supplier_id from purchase_orders where po_number=\''+poLike.group(1)+'\'' self.myCursor.execute(query) descr = self.myCursor.description ...
The code processes an image frame using OCR to extract text, searches for company names from both a purchase order (PO) and YAML data, matches them if consistent, and either registers the company or queries a database based on extracted fields like date and quantity. It handles debugging and state transitions for docum...
def run(self, frame): if self.companyNameMatched == False: ocr_text = pytesseract.image_to_string(frame) if self.companyNameFoundFromPO == False: self.searchCompanyFromPO(ocr_text) if self.companyNameFoundFromYaml == False: self.searchCompanyFr...
def get_cities_coordinates(cities): """Returns coordinates of the cities.""" cities_coordinates = [] for city in cities: url = generate_url(city) result = convert_city_to_coordinates(city) if not result: continue cities_coordinates.append(result) return ci...
The main task of the code is to retrieve and store weather data for specified cities. It initializes a database, fetches geographic coordinates for each city, constructs API URLs using these coordinates, retrieves weather data from the API, and inserts the parsed data into the database. The process skips cities with in...
def main(cities): """Fills the entire table with data.""" db = DataBase() db.init_db() cities_coordinates = get_cities_coordinates(cities) for name, lat, lon in cities_coordinates: url = build_city_url(lat, lon) response = get_response(url, name) if not response: ...
def read_json(user_file): # Get a list of facilites and id facilities = [] items = [] # Start Try/Except try: file = open(user_file, 'r+') json_data = json.load(file) i = 0 #first for loop gets the names of all of the objects and stores them globally for array...
The main task of the code is to manage user interaction for handling a database by checking for existing .db and .json files in the directory. It removes 'results.txt' if present, identifies file types, and prompts the user to either analyze an existing .db file or overwrite it with data from a .json file. If no .db fi...
def user_prompt(): try: os.remove('results.txt') except: pass json_files = [] db_files = [] for file in os.listdir(os.curdir): if file.endswith('db'): db_files.append(file) if file.endswith('.json'): json_files.append(file) if len(db_files)...
def _intersectH5s(self, inFiles: list, env: Envelope) -> list: filtered = [] envBox = box(env.ulx(), env.lry(), env.lrx(), env.uly()) for f in inFiles: minX, minY = [int(n) for n in f.stem.split('_')[5:7]] inBox = box(minX, minY, minX+1000, minY+1000) if e...
The code clips hyperspectral H5 files and Albedo data to a geographic envelope, mosaics them into a virtual raster, combines the clipped datasets, and computes vegetation indices (VIs) for output. It filters input files, converts H5 to TIFF, clips both H5 and Albedo data, merges them, then generates VIs from the combin...
def _myClip(self, inFiles: list, envelope: Envelope, outFile: Path) -> None: # --- # Filter inFiles by the envelope to reduce H5s to read. # --- self._logger.info('Intersecting H5 files.') filteredFiles = self._intersectH5s(inFiles...
def order_param_init(calculated_order_params, guess = False): if(guess): A = 2 else: A = 1 calculated_order_params['xi1_up'] = A calculated_order_params['xi1_down'] = A calculated_order_params['xi2_up'] = .2 calculated_order_params['xi2_down'] = .3 calculated_order_params['M1_c'] = 0 calculated_order...
The code performs a self-consistent calculation to determine order parameters by iteratively updating initial guesses until convergence, using a set of parameters (j, mu_c, mu_f) and K-points. It initializes parameters, compares calculated vs. guessed values in a loop, updates guesses, recalculates order parameters, an...
def self_consistent(j, K_POINTS): calculated_order_params = {} guess_order_params = {} params = {} params['mu_c'] = 0 params['mu_f'] = 0 params['j'] = j guess_order_params = order_param_init(guess_order_params, True) # generate_U(guess_order_params, params, K_POINTS) calculated_order_params = order_param_in...
def check_piece_touch(self): for other_piece in self.placed_pieces: for other_tile in other_piece.get_tile_positions(): for active_tile in self.active_piece.get_tile_positions(): if active_tile[0] == other_tile[0] and active_tile[1] + 1 == other_tile[1]: return True for acti...
This code handles a game step by updating the active piece's position based on x_action, checking for collisions. If the piece touches the bottom or another piece, it's marked as placed. A second collision triggers game over. Finally, it processes completed rows.
def step(self, x_action): if self.game_over: return self.steps += 1 self.active_piece.start = (self.active_piece.start[0] + x_action, self.active_piece.start[1] + 1) if self.check_piece_touch(): self.mark_active_as_placed() if self.check_piece_touch(): self.game_over = True...
def network_subnet(): auestion_and_ans = random_ip_network_subnet() question = "How many subnets and hosts per subnet can you get from the network " + auestion_and_ans[0] + "?" return [question, auestion_and_ans[1]] def subnet_does(): get_ip = ip_generat() ip = get_ip[0] ip_address = get_ip[1] ...
The code defines a function `gen_questions()` that randomly selects and returns one of several predefined networking-related functions, each likely generating a specific type of question (e.g., about subnets, valid host ranges, or first/last hosts). Its main task is to produce a random question related to subnetting or...
def gen_questions(): return random.choice([network_subnet(), subnet_does(), valid_host_range(), last_valid_host(), first_valid_host()])
def get_training_values(): mutag = TUDataset(root='./data/', name='MUTAG') train_loader = DataLoader(mutag, batch_size=1) node_list = [] probability_list = [] max_nodes = 0 for data in train_loader: max_nodes = max(max_nodes, data.num_nodes) total_possible_edges = data.num_nod...
The code generates 1000 baseline Erdos-Renyi graphs using training data probabilities, loads 1000 VAE-generated graphs, computes graph statistics (node degree, clustering, centrality) for training, baseline, and VAE graphs, and evaluates novelty through comparison. It visualizes statistical distributions to analyze str...
def main(): training_node_list, training_probability_list, max_nodes = get_training_values() max_index = len(training_node_list) - 1 baseline_graphs = [] for i in range(1000): ran_index = random.randint(0,max_index) nodes = training_node_list[ran_index] indexes = [index for ind...
def mutation(child, probability): mut_child = child[0:-1].copy() i = random.randrange(len(mut_child)) j = random.randrange(len(mut_child)) if i == j: mutation(child, probability) select_random = random.random() if probability >= select_random: mut_child[i], mut_child[j] = mut_chi...
The main task of the code is to generate the next generation in a genetic algorithm by iteratively creating offspring through selection, crossover, and mutation operations. Each child is produced by combining two selected parents, applying crossover, then mutation based on the given rate, and appending the result to th...
def next_generation(current_generation, mutation_rate): next_gen = [] i=0 while i < len(current_generation): child = mutation(crossover(selection(current_generation), selection(current_generation)), mutation_rate) next_gen.append(child[:]) i +=1 return next_gen
def fitness(population): fitnesses = [] for tour in population: check_path_cost = path_cost(tour) if check_path_cost == 0: tour_fitness = 101 else: tour_fitness = 100*(1/check_path_cost) fitnesses.append(tour_fitness) return fitnesses def fittest_indiv...
The function generates the next generation in an evolutionary algorithm by applying elitism to retain the fittest individuals, creating a mating pool from the top half of the population, and producing offspring through crossover with the fittest member and tournament selection. It adjusts mutation rate to 1 if early co...
def next_generation(current_generation, elitism, crossover_rate, mutation_rate): next_gen = [] current_gen_fitness = fitness(current_generation) sorted_fitnesses = sorted(current_gen_fitness,reverse=True) pop_size = len(current_generation) fitq = fittest_individual(current_generation) #Check to ...
def population(pop_size): #Generate a sample city tour sample = [] for i in range(0,num_cities): sample.append(i) sample.append(sample[0]) population = [] #Shuffle sample tour and add to initial population for i in range(0,pop_size): randomized_tour = sample[0:-1].copy() ...
The code implements a genetic algorithm to find the optimal tour (likely for a Traveling Salesman Problem) by iteratively generating new populations through selection, crossover, and mutation. It initializes a population, evaluates the fittest individual, and evolves subsequent generations. After each generation, it co...
def genetic_algorithm(pop_size, generations, mutation_rate): #Create an initial population current_population = population(pop_size) #Identify an initial best tour; used as a basis of comparison for all future tours generated best_tour = fittest_individual(current_population) best_tour_cost = path_c...
def population(pop_size): #Generate a sample city tour sample = [] for i in range(0,num_cities): sample.append(i) sample.append(sample[0]) population = [] #Shuffle sample tour and add to initial population for i in range(0,pop_size): randomized_tour = sample[0:-1].copy() ...
Your return The code implements a genetic algorithm to optimize a tour (likely for a Traveling Salesman Problem). It initializes a population, iteratively evolves it over generations using elitism, crossover, and mutation, and tracks the fittest individual. Each generation replaces the population with a new one, upda...
def genetic_algorithm(pop_size, generations, elitism, crossover_rate, mutation_rate): #Create an initial population current_population = population(pop_size) #Identify an initial best tour; used as a basis of comparison for all future tours generated best_tour = fittest_individual(current_population) ...
def _get_bbox(self, cell: tuple[int, int]) -> tuple[int, int, int, int]: row, col = cell cell_width, cell_height = self._get_cell_size() x_min, y_min = col * cell_width, row * cell_height x_max, y_max = x_min + cell_width, y_min + cell_height return x_min, y_min, x_max, y_max def _get_midpoint(self, cell: tup...
This code renders a grid cell with visual elements representing the state's reward, Q-values for each action (up/down/left/right), visit counts (n_sa), and the current policy. It uses color coding for rewards, text annotations for Q-values and counts, and a pink box to highlight the state's visit count and policy.
def draw_cell(self, state, reward, q_sa, n_sa, n_s, policy): if n_s.get(state) is None: return colour = 'light grey' if reward: colour = 'light green' if reward > 0 else 'orange' self.create_rectangle(self._get_bbox(state), fill=colour) if reward: self.create_text(self._get_midpoint(state), text=st...
def isWall(self, x, y): state = self.compute_coordinates(x,y) return state in [self.env.canvas.coords(w) for w in self.env.wallblocks] def isGoal(self, x, y): state = self.compute_coordinates(x,y) return state == self.env.canvas.coords(self.env.goal) def isPit(self, x, y): state ...
The main task of the code is to update the value function and policy in a reinforcement learning agent when reaching a terminal state. It performs policy evaluation by recalculating state values using `calculate_value`, then conducts policy improvement by selecting optimal actions for each state based on maximum expect...
def learn(self, s, a, r, s_): if s_ == 'terminal': new_values = np.zeros((10,10)) #Policy evaluation #while True: #delta = 0.0 # for all 100 states for i in range(10): for j i...
def stop(): global server_socket if server_socket: server_socket.close() server_socket = None def handle_root(client): send_header(client) client.sendall("""\ <html> <h1 style="color: #5e9ca0; text-align: center;"> <span style="color: #ff0000;"> ...
This code sets up a simple HTTP server on a specified port (default 80) using sockets. It listens for client connections, parses incoming HTTP requests, extracts URLs, and routes them to handlers for root, configuration, or not-found cases. The server processes each request by reading headers, validating HTTP requests,...
def start(port=80): global server_socket addr = socket.getaddrinfo('0.0.0.0', port)[0][-1] stop() server_socket = socket.socket() server_socket.bind(addr) server_socket.listen(1) while True: client, addr = server_socket.accept() print('client connected from', addr) ...
def initialize_particles(): for i in range(MAX_PARTICLES): newParticle = Particle() total = 0 for j in range(MAX_INPUTS): newParticle.set_data(j, random.randrange( START_RANGE_MIN, START_RANGE_MAX)) total += newParticle.get_data(j) newParticle...
The code implements a Particle Swarm Optimization (PSO) algorithm to find a target value by iteratively updating particle positions and velocities. It initializes particles, evaluates their fitness using `test_problem`, updates the global best (gBest) solution, and adjusts particle velocities and positions until the ta...
def PSO_algorithm(): gBest = 0 gBestTest = 0 aParticle = None epoch = 0 done = False initialize_particles() while not done: # Two conditions can end this loop: # if the maximum number of epochs allowed has been reached, or, # if the Target value has been found. ...
def make_board(): """Create empty 4x4 board.""" return [[0 for _ in range(4)] for _ in range(4)] def is_full(board): """Check if the board is full. If so, terminate the game.""" return all([all([item != 0 for item in row]) for row in board]) def spawn(board): """ Spawn 2 with 90% probability or ...
The main task of the code is to simulate a 2048 game session where a player interacts with the game board. It initializes the board, handles tile spawning, processes player moves, updates the game state, and triggers a callback for each move. The loop continues until the board is full, then finalizes the state with the...
def play(player, callback=lambda move, board, state: None): """Play game of 2048 with user.""" board = make_board() state = {'score': 0} while not is_full(board): spawn(board) move = player(board, state) callback(move, board, state) board = shift(board, move, state) s...
def print_board(moves): cells = [' ' for _ in range(9)] for i, move in enumerate(moves): player = i % 2 cells[int(move)] = 'O' if player == 0 else 'X' print('=' * 15) for start in range(0, 9, 3): print(cells[start:start + 3]) def play(node, you=lambda node: input('> '), enemy=lam...
The code's main task is to solve a board game by analyzing possible outcomes using specified agents. It parses command-line arguments for starting states, agent selection, and interactive play. The code processes game states, computes win probabilities, prints outcomes, and identifies definite victory paths, returning ...
def main(): parser = argparse.ArgumentParser() parser.add_argument('--play', action='store_true') parser.add_argument('--start', default='', help='Starting state') # Interesting states: 30674, 01234, 014 parser.add_argument('--agent', default='basic', choices=AGENTS.keys(), help='Which agent to use, to...
def count_class(data: List[List[str]]) -> List[int]: size = len(data[0]) counts = [] for i in range(size): uniques = set([val[i] for val in data]) counts.append(len(uniques)) return counts def count_occurences(data: List[List[str]]) -> List[Dict[str, int]]: """ Count the occurren...
This function builds a decision tree using a recursive approach, selecting attributes based on maximum gain ratio (C4.5 algorithm). It calculates entropy, information gain, and split information for each attribute, splits data subsets, and prints the tree structure with attributes and decisions. The process continues u...
def build_tree(data, prev=-1, margin="\t\t", color=1): classes = count_class(data) occurrences = count_occurences(data) probabilities = count_probabilities(occurrences) entropy = get_entropy(probabilities) info = [get_info(index, data) for index in range(len(classes) - 1)] gain = get_gain(entrop...
def parse(input_str: str): pairs = [pair.split('\n') for pair in input_str.split('\n\n')] parsed = [list(map(json.loads, pair)) for pair in pairs] return parsed def part1(pairs): counter = 0 for i, pair in enumerate(pairs): left, right = pair if rightOrder(left, right) < 0: ...
The code's main task is to read input data, parse it into a structured format, compute solutions for two problem parts (Part 1 and Part 2), and print the results. It orchestrates input handling, data processing, and solution execution for a programming challenge, likely from an Advent of Code-style problem.
def main(): input_str = read_input(day=DAY, test=TEST) data = parse(input_str) print(f"Part 1: {part1(data)}") print(f"Part 2: {part2(data)}")
def parse(input_str: str): data = [(line.split()[0], int(line.split()[1])) for line in input_str.split('\n')] return data def part1(data): # change ROPE_LENGTH pass def part2(data): snake = [[0, 0] for _ in range(ROPE_LENGTH)] tail_visited = set() tail_visited.add(tuple(snake[-1...
The main task of the code is to read input data, parse it into a structured format, compute solutions for two parts of a problem, and print the results. The `main()` function orchestrates reading input, parsing it, and executing `part1()` and `part2()` functions on the parsed data to produce outputs for both parts of t...
def main(): input_str = read_input(day=DAY, test=TEST) data = parse(input_str) print(f"Part 1: {part1(data)}") print(f"Part 2: {part2(data)}")
def poss_move(board, pc): if pc: ai = 1 else: ai = -1 moves = {} legit_move = 0 for i in range(s): for j in range(s): # here we find our own tile, we investigate its neighborhood if board[i][j] == ai: moves, lm = check_env(board, i, j,...
The function `optimal_move` determines the best move for a player in a game using the minimax algorithm with alpha-beta pruning. It evaluates all possible moves, recursively assessing their outcomes with `alpha_beta`, and selects the move yielding the highest (for maximizing player) or lowest (for minimizing player) sc...
def optimal_move(board, pc, nbr_of_layers, time_vector): optimal_points = 65 optimal_move = {} moves = poss_move(board, pc) maximizing_player = False if moves == 0: return 0 if pc: maximizing_player = True optimal_points = -65 for key, values in moves.items(): ...
def check_human_env(pos, opponent): if not opponent: opponent = -1 moves = {} x, y = ord(pos[1]) - 49, ord(pos[0]) - 97 if x < 0 or x > 7 or y < 0 or y > 7: return -1 elif board[x][y] != 0: return -1 moves[s * x + y] = [0] for ii in range(-1, 2): if not 0 <= ...
The function `make_move` alternates between handling human and computer turns in a game. For human input, it validates moves or allows passing. For the computer, it searches for an optimal move within time constraints using increasing search depths. It updates the game board on valid moves or returns errors for invalid...
def make_move(counter, pc, time_vector): if counter % 2: moves = -1 c = 0 while True: if c > 0 and moves == -1: print('Not a valid move, try again') move_input = input('Choose position of type \'a-h 1-8\', ex. b3. Or \'pass\' : ') if len(m...
def get_median_data(set_path): class_dirs = next(os.walk(set_path))[1] lengths = [] for path in class_dirs: original_images = np.array(load_images_from_folder(os.path.join(set_path,path))) lengths = lengths + [original_images.shape[0]] return statistics.median(lengths) def load_images_fr...
This function creates an augmented dataset by adjusting the number of images in each class to match a median count. It generates a new directory, processes images from input classes, either shrinking or expanding their counts, and saves the adjusted images into a structured augmented folder.
def create_augment_folder(set_path, dataset_path, set_dir): new_set_dir = os.path.join(dataset_path,set_dir+'_augmented') try: os.mkdir(new_set_dir) except OSError as error: print(error) #data_lengths_median = 100 data_lengths_median = int(get_median_data(set_path)) print("Media...
def removeDuplicates(options): s = set() for word in options: s.add(word) return list(s) def addWord(i): global sentence global structure global word_options if i == len(structure): rateSentence() else: prev = "<s>" if i >= 1: prev = sentence[i - 1] for index, word in enumerate(word_options): ...
The function `run` generates valid sentences using a given structure and word lists. It initializes global variables, builds sentences by recursively adding words from `primary_words` (and later `secondary_words` if invalid), checks validity, and filters results. If valid, it sorts sentences by rating, returning a rand...
def run(struct, user_keywords, primary_words, secondary_words): global sentence global structure global word_options global finished_sentences global max_rating finished_sentences = [] max_rating = 0 sentence = [""] * len(struct) structure = struct word_options = primary_words word_options = removeDuplicate...
def bulb_instance(onto, jsonData): bulbID = jsonData["id"] bulbState = jsonData["state"] bulb_1 = onto.Bulb(bulbID) bulb_1.bulbState = [bulbState] bulbs.append(bulb_1) def air_cond_instance(onto, jsonData): airCondID = jsonData["id"] airCondState= jsonData["state"] airCond_1 = onto.Air_c...
The code processes device and sensor data to create ontology instances, applies predefined rules to the ontology, and resets state variables for subsequent rounds. It iterates through 'things' and 'sensorData' dictionaries, generating specific instances (e.g., bulbs, sensors) and invoking rule application. If no rules ...
def apply_instances(onto): global v global ruleApplied global canReceive for key in things.keys(): jsonData = things[key] thingType = jsonData["type"] if thingType == "bulb": bulb_instance(onto, jsonData) elif thingType == "air_conditioner": air...
def has_all_sensors(): return ("temperature" in sensorData and "light_in" in sensorData and "light_out" in sensorData and "motion" in sensorData) def has_all_things(): return ("air_conditioner" in thingsType and "bulb" in thingsType and "door" in t...
The code processes incoming MQTT messages. It stores device states in dictionaries when the "DevicesStates" topic is received. If `canReceive` is True, it also processes sensor data from the "JsonData" topic, updates sensor data storage, checks for complete data sets, and triggers printing of data and ontology instance...
def on_message(client, userdata, message): global canReceive if message.topic == "DevicesStates": messageReceive = message.payload.decode("utf-8") data = json.loads(messageReceive) id = data["id"] type = data["type"] things[id] = data thingsType[type] = id ...
def make_testcases(iter_num, sample_init=False): if sample_init: testcases = {"A": [2, "aa", "a"], "B": [4, "abcd", "acd"], "C": [10, "aaaaaaaabb", "aaaab"], "D": [6, "xskszy", "sky"], } else: testcases = {} ...
The code defines a `test` function that generates test cases using `make_testcases` and optionally runs them with `main_with_test` (if `ans=True`) and/or measures execution time with `main_with_timer` (if `time=True`). Its main task is to execute predefined test cases and optionally report results or benchmark performa...
def test(iter_num=10, ans=True, time=True): testcases = make_testcases(iter_num) if ans: main_with_test(testcases) if time: main_with_timer(testcases, print_time=True)
def writeCell(self, y, x, i, t="ans"): cell = self.grid[y][x] i = ''.join(sorted(str(i))) if t == "ans": cell.config(state='normal') cell.delete(0, 'end') cell.insert(0, str(i)) cell.config(state='disabled', font=Font(size=self.font_size, weight="...
This function inserts a number into the currently selected editable cell of a board, updates the board state, removes candidate numbers, and refreshes the UI's highlight visuals to reflect the change.
def insertNumberCallback(self, n, e): if self.current_selected_cell: y, x = self.current_selected_cell if self.current_board_editable_map[y][x]: self.writeCell(y, x, n) self.cleanupCandidate(y, x, n) self.updateBoard() self...
def setupWidget(self): self.left_container = Frame(self, bg=self.background) self.grid_container = Frame(self.left_container, bg=self.uneditable_foreground) self.cell_container = [[Frame(self.grid_container, width=self.cell_width, height=self.cell_height) for _ in range(self.board_width)] for _ ...
The code initializes a Sudoku game application by setting up the game board dimensions, color schemes, icons, and GUI components. It configures game states like time tracking, editable cells, and board generation, while preparing event handlers and widget placements for user interactions. The main task is to create a f...
def __init__(self): super(MainGame, self).__init__() self.board_width, self.board_height = (9, 9) self.region_width, self.region_height = (3, 3) self.outer_border_width, self.inner_border_width = (5, 2) self.cell_width, self.cell_height = (70, 70) self.font_size ...
def newBoard(self, master): if not master.newgame_window: master.newgame_window = MenuWindow(master) else: master.newgame_window.lift() master.newgame_window.focus_force() def quit(self, master): master.deiconify() master.resumeGame() self.de...
This code initializes a child window (Game Archive) by copying configuration parameters from the master window, setting up UI elements, loading icons, defining button commands, and preparing to handle user interactions and data history. It configures window properties, manages board dimensions, color schemes, and estab...
def __init__(self, master): super().__init__(master) master.withdraw() master.is_playing = False self.board_width, self.board_height = self.master.board_width, self.master.board_height self.region_width, self.region_height = self.master.region_width, self.master.region_height ...
def make_dirs(dir): if not os.path.exists(dir): os.makedirs(dir) def load_brain_data(dimension=100, label_col="PicVocab_AgeAdj", normalize=False): root = './data' edge_sub_exp_name = 'netmat' subject_name = f"3T_HCP1200_MSMAll_d{str(dimension)}_ts2" edge_directory = os.path.join(root, e...
This function processes brain data by splitting it into training, validation, and test sets, saving edge and label arrays in specified directories. It handles normalization, creates directory structures, loads data, splits datasets equally, and stores distribution statistics for each subset. The task involves organizin...
def process_data_splits(normalize=True, split_num=""): if normalize: root = f'./normalized_edge_dataSplits{split_num}' else: root = './dataSplits' make_dirs(root) for label_col in meaingfulcol_name_list: save_exp = os.path.join(root, label_col) make_dirs(save_exp) ...
def write_log(texto): try: try: file1 = open("log.txt","a") file1.write("\n" + datetime.now().strftime("%Y-%m-%d %H:%M:%S ") + texto) file1.close() except: print("No se encuentra el archivo de log") except: print("Fallo en la escritura de ...
The code updates a database with Google Drive file metadata, removes non-owner permissions from shared files, and sends email notifications. It checks if files exist in the database, inserting new entries or updating existing ones based on modification times. Exception handling ensures compatibility with files lacking ...
def update_database(service): write_log(" __ __ ________ __ ______ ______ _______ _______ ") write_log("/ \ / |/ |/ | / | / \ / \ / \ ") write_log("$$ \ /$$ |$$$$$$$$/ $$ | $$$$$$/ /$$$$$$ |$$$$$$$ |$$$$$$$ |") w...
def authenticate(): try: creds = None if os.path.exists('token.pickle'): with open('token.pickle', 'rb') as token: creds = pickle.load(token) if not creds or not creds.valid: #si no hay credenciales, te manda a logearte if creds and creds.expired and c...
The main task of the code is to execute "db.py", authenticate a service, update a database using the authenticated service, save data to a CSV file, and pause execution until the user presses Enter to exit.
def main(): os.system("db.py") service = authenticate() update_database(service) save_csv() input("Press enter to exit ;)")
def GetCustomer(request,custId): #print(f"get customer dup check cust id used is: {custId}") request.session['customerFound'] = "No" urlPrefix = os.environ['A80UrlPrefix'] apiSelect = "/cust?id=" + custId apiString = urlPrefix + apiSelect response = requests.request("GET",...
The main task of the code is to assemble a `Customer` object based on the `action` parameter (buildonly, add, or update), populate it with form data from the request, handle session-stored values, validate the birth date, and save the customer if updating. It returns the populated customer object after applying action-...
def AssembleNewCustomer(request, action): if action == "buildonly": c = Customer() # create customer to show screen only edit errors have occurred. c.customer_id = request.POST['custId'] c.plan = request.session['uplan'] # not on screen stored in session c.birth_date = request.POS...
def NotSignedIn(request): signIn = request.session['signIn'] if signIn != "Yes": return True else: return False def GetDropDownData(claimType): #get('/readPlans') urlPrefix = os.environ['A80UrlPrefix'] apiSelect = "/readServices" url = urlPrefix + apiS...
The main task of the code is to handle claim form processing for creating/editing insurance claims, including user authentication checks, claim type selection, form validation, and data submission. It manages GET requests to display blank claims with default settings, POST requests to handle claim type changes, plan as...
def claim(request): if request.method == "GET": if NotSignedIn(request) == True: return render(request, "A80Insurance/notauthorized.html") message = "" # # build blank claim for claim entry # when no history action used. # claim = Claim(...
def AdmNotSignedIn(request): try: admSignIn = request.session['admSignin'] if admSignIn != "Yes": return True else: return True except: return False def ListCustomers(request): # app.get('/custList', urlPrefix = os.environ['A80Ur...
The code handles user actions in a web application, primarily processing GET and POST requests. For GET, it checks authentication and displays a form. For POST, it processes actions like listing customers, resetting customer data, or password resets by calling specific functions, then renders appropriate templates with...
def action(request): if request.method == "GET": # check for valid url must be signed in. if AdmNotSignedIn(request) == True: return render(request, "A80Insurance/notauthorized.html") message = "" return render(request, "A80Insurance/action.htm...
def AssembleNewCustomer(request, action): if action == "buildonly": c = Customer() # create customer to show screen only edit errors have occurred. c.customer_id = request.POST['custId'] c.plan = request.session['uplan'] # not on screen stored in session c.birth_date = request.POS...
The main task of the code is to add a new customer by assembling customer data from the request, converting it to a dictionary, attempting to save it via RegisterCustomerSave, checking the result, and returning a dictionary with the operation's status, message, and customer object.
def AddCustomer(request): customer = AssembleNewCustomer(request, "add") custDictionary = CustomerToDictionary(customer) notused = "" request.session["A45Token"] = notused message = RegisterCustomerSave(request, custDictionary) good = "" if message == good: result = "good" ...
def RegisterEdits(request): # edit cust id here and emit msg if bad # call rest of editsf editMessage = CustomerEdits(request, "register") return editMessage def AddCustomer(request): customer = AssembleNewCustomer(request, "add") custDictionary = CustomerToDictionary(customer) notuse...
The code handles customer registration via a web form. It processes GET requests by initializing session variables and rendering the registration template. For POST requests, it validates form data using `RegisterEdits`. If valid, it adds the customer via `AddCustomer`, updates session state, and redirects to the menu....
def register(request): noErrorsAreFound = "" if request.method == "GET": request.session['regPassword'] = "" # for password edits request.session['signIn'] = "No" message = "Enter Customer Information" customer = Customer() return render(request, "A80Insurance/regis...
def NotSignedIn(request): signIn = request.session['signIn'] if signIn != "Yes": return True else: return False def BuildCustomerFromDict(o): c = Customer() c.customer_id = o.get('custId').rstrip() c.password = o.get('custPassword').rstrip() c.first_name = o.get('custFirst')...
The code handles customer update functionality in a web application. It processes GET requests to fetch customer data via an API after verifying user authentication, then renders an update form. For POST requests, it validates submitted edits, updates the customer data if valid, and redirects to a menu with success/fai...
def update(request): noErrorsAreFound = "" if request.method == "GET": # check for valid url must be signed in. if NotSignedIn(request) == True: return render(request, "A80Insurance/notauthorized.html") message = "Enter Customer Update Information" custI...
def breastCancer(attribute_selection_measure): # Load the dataset (you can replace this with your dataset) url = "https://archive.ics.uci.edu/ml/machine-learning-databases/breast-cancer/breast-cancer.data" column_names = ['class', 'age', 'menopause', 'tumor-size', 'inv-nodes', 'node-caps', 'deg-malig', 'bre...
The function `stats3` processes incoming HTTP requests by parsing JSON data to determine a dataset type (`att1`) and an attribute selection measure (`att2`), then delegates to specific analysis functions (`breastCancer`, `carEvaluation`, `balanceScale`) based on the dataset type.
def stats3(request): twoattris = json.loads(request.body) attribute_selection_measure = twoattris['att2'] if (twoattris['att1'] == 'Breast Cancer'): return breastCancer(attribute_selection_measure) elif (twoattris['att1'] == 'Car Evaluation'): return carEvaluation(attribute_selection_mea...
def prepare(self, img_message): self._check_and_save_message_image(img_message) halftoning_message = error_diffusion.color_halftoning( self._cmy_message) self._encryption_shares = matrices_distribution.distribute_matrices( halftoning_message, self.basis_matrices, (*self.s...
The code encrypts input images by generating shares using error diffusion (Floyd-Steinberg method) with threshold modulation and a scale factor. It converts CMY shares to RGB and returns them. If a message is provided, it first prepares encryption parameters. The process involves splitting images into shares, applying ...
def encrypt(self, img_inputs, img_message=None): if img_message is not None: self.prepare(img_message) self._check_and_save_input_image(img_inputs) cmy_shares = [] for idx in range(self.num_shares): cmy_shares.append(error_diffusion.error_diffusion( ...
def set_measurement_interval(self, interval): try: cmd_set_measurement_interval = create_cmd(interval, 0x00) self.bus_number.write_i2c_block_data(self.i2c_address, 0X46, cmd_set_measurement_interval) except OSError as e: print("set_measurement_interval: " + str(e)) de...
The code initializes an SCD30 sensor by setting its I2C address, configuring measurement interval, auto-calibration, and starting periodic pressure measurements. It uses SMBus for communication, applies delays between configurations to ensure stability, and prepares the sensor for continuous environmental data collecti...
def __init__(self, measurement_interval, auto_calibration, pressure): super(SCD30, self).__init__() self.i2c_address = 0x61 self.bus_number = smbus2.SMBus(1) self.set_measurement_interval(measurement_interval) time.sleep(0.1) self.set_auto_calibration(auto_calibration) ...
def slide_bars_place(self): x_pos = 10 label_spacing = 110 self.day_var = IntVar() self.day_var.set(1) day = Label(self.root, text="Day: ").place(x=x_pos + label_spacing, y=10) day_label = Label(self.root, text=str(self.day_var.get())) # day_label.place(x=x_pos ...
The code initializes a GUI application with a fixed-size window, sets up sliders for input parameters, generates solar time data, configures plot elements, updates visualizations based on default geographical and temporal inputs, and launches the Tkinter main loop for interactive operation.
def __init__(self, root=tk.Tk()): self.root = root self.root.geometry('1250x750') self.root.resizable(False, False) self.slide_bars_place() self.solar_time = np.arange(-7, 12.1, .5) self.Inso_b_n = 0 self.plot_place() self.caculation_static_labels() ...
def handle_cmd_options(): parser = OptionParser() # parser.add_option( # '-t', "--threads", # dest="number_threads", # type="int", # help="number of threads EACH CRMod/CRTomo instance uses. If not " + # "set, will be determined automatically", # default=None, ...
The main task of the code is to register unfinished directories for modeling or inversion processing. It retrieves configuration and command-line options, identifies directories requiring 'mod' (modeling) or 'inv' (inversion) tasks, and registers them for processing using global settings and command options.
def crh_add(): print('CRH Add') global_settings = get_config() cmd_options = handle_cmd_options() needs_modeling, needs_inversion = find_unfinished_tomodirs('.') print('-' * 20) print('modeling:', needs_modeling) print('inversion:', needs_inversion) print('-' * 20) for directory in ...