dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def publish_to_websocket(transactionId,fromNumber,toNumber,streamingStatus,date_,entities): ''' Publish transaction details and extraction results to websocket ''' try: print("payload", json.dumps({"transactionId": transactionId, "fromNumber": fromNumber, "toNumber": toNumber, "streamingSta...
The main task of the code is to insert transaction details into DynamoDB based on the streaming status. When streamingStatus is 'STARTED', it logs initial event data. When 'ENDED', it extracts entities (member/provider info), updates the DynamoDB entry with these entities, publishes websocket notifications, merges S3 a...
def insert_into_table(receivedEventAt,transactionId,fromNumber,toNumber,streamingStatus,date_,time_,count): ''' Publish transaction details and extraction results to dynamodb ''' if streamingStatus == 'STARTED' and count==0: entities={"MemberInfo": [], "ProviderInfo": []} publish_to...
def wificonnect(ssid=ssid,password=password): print('Use: like ugit.wificonnect(SSID,Password)') print('otherwise uses ssid,password in top of ugit.py code') wlan = network.WLAN(network.STA_IF) wlan.active(False) wlan.active(True) wlan.connect(ssid,password) while not wlan.isconnected(): ...
The main task of the code is to synchronize a local file system with a remote Git repository by pulling files, managing directory structures, removing ignored items, updating existing files, and resetting the device after operations. It handles Wi-Fi connection checks, directory creation, file deletion, and logging cha...
def pull_all(tree=call_trees_url,raw = raw,ignore = ignore,isconnected=False): if not isconnected: wlan = wificonnect() os.chdir('/') tree = pull_git_tree() internal_tree = build_internal_tree() internal_tree = remove_ignore(internal_tree) print(' ignore removed ----------------------') print(inter...
def value_changed(self): house_consumption_a = self.slider_house_consumption.value()/1000.0 pv_excess_a = self.slider_pv_excess.value()/1000.0 car_consumption_a = self.slider_car_consumption.value()/1000.0 if self.checkbox_car_connected.isChecked(): self.label...
This code initializes a GUI application for a WARP Energy Manager Tester, setting up sliders and checkboxes to control parameters like main power, house consumption, PV excess, and car consumption. It connects these UI elements to update the simulation state, initializes an SDMSimulator, and configures the window with ...
def __init__(self, parent=None): QMainWindow.__init__(self, parent) self.setupUi(self) self.setWindowTitle('WARP Energy Manager Tester') self.phases = 3 self.sdm_sim = SDMSimulator('W2J') #self.wc_sim = WARPChargerSimulator() self.slider_main.valueChanged.conne...
def get_possible_aa(spectrum, m=20): ''' :param spectrum: - :param m: - :return: most likely aminoacids included in protein ''' possible_aa = [] diffs = get_diffs(spectrum, m) for aa in aminoacids.keys(): for mass in diffs: if abs(aminoacids[aa] - mass) <= 1: ...
This function identifies the most likely peptide sequence from a given mass spectrum by iteratively expanding a leaderboard of candidate peptides, scoring them against the spectrum, and trimming the leaderboard to retain top candidates. It uses amino acids determined from the spectrum, checks peptide masses against the...
def leaderboard_cyclopeptide_sequencing(spectrum, N=1000, M=20, ): ''' Basic algorithm that finds peptide for a given spectrum :param spectrum: - :param N: number of holded possible peptides in leaderboard :param M: number of amino acids to choose from spectrum :return: resulting peptide '''...
def cmd(data): print(f'> {data}') cp.flush() cp.reset_input_buffer() send(data) expect(data) def send(inText): cp.write((inText.replace('\r', '').replace('\n', '\r') + '\r').encode()) def expect(expectedResponse): response = readline() if response != expectedResponse: time.sleep(...
The code transmits a file by processing it in blocks, replacing specific byte sequences, sending the file size, and writing data blocks while interacting with an external system via command and response checks.
def sendFile(filename): shortName = os.path.basename(os.path.realpath(filename)) print(f'Transmitting file:{filename}...') cmd(shortName) with open(filename, 'rb') as f: data = f.read() data = data.replace(b'\x05', b'\x055').replace(b'\x03', b'\x053').replace(b'\r', b'\x05d') cmd(str...
def cmd(data): print(f'> {data}') cp.flush() cp.reset_input_buffer() send(data) expect(data) def sendFile(filename): shortName = os.path.basename(os.path.realpath(filename)) print(f'Transmitting file:{filename}...') cmd(shortName) with open(filename, 'rb') as f: data = f....
The function recursively traverses a directory tree, sending commands to process each directory and file. It starts by sending the current directory's name, then iterates through its contents. For subdirectories, it calls itself recursively; for files, it triggers a separate sendFile function. Finally, it sends a comma...
def sendDir(path): cp.reset_input_buffer() cmd(f'@dir:{os.path.basename(path)}') for fn in os.listdir(path): fn = os.path.join(path, fn) if os.path.isdir(fn): sendDir(fn) else: sendFile(fn) cmd(f'@dir:..')
def getValidMoves(board, tile): # Returns a list of (x,y) tuples of all valid moves. validMoves = [] for x in range(BOARDWIDTH): for y in range(BOARDHEIGHT): if isValidMove(board, tile, x, y) != False: validMoves.append((x, y)) return validMoves def isOnCorner(x, y):...
The function `getComputerMove` determines the computer's optimal move in a board game (likely Reversi/Othello). Its primary task is to prioritize capturing corners if available. If no corners are accessible, it evaluates all valid moves by simulating each on a board copy, calculating the resulting disc count for the co...
def getComputerMove(board, computerTile): # Given a board and the computer's tile, determine where to # move and return that move as a [x, y] list. # This agent has the following strategy: Capture a corner if possible. If not, play the move which captures the # most discs. So corner + max disc strat. ...
def load_precomputed_scenes(self, scene_file: str) -> List[Scene]: # TODO try except like : # attempts = 0 # max_attempts = 20 # while attempts < max_attempts: # try: # with open(scene_file, "r") as f: # scenes = json.load(f) # ...
The function retrieves scenes from a video by loading precomputed scenes if available, otherwise detecting and saving new scenes. It removes duplicates if a threshold is set, adjusts scenes to fit min_max_len constraints, and returns a list of Scene objects with start/end frames.
def retrieve_scenes_from_video( self, video_path: str, ) -> List[Scene]: """Get the scenes from a video. If the scenes have already been computed, they will be loaded from the scene list files. Otherwise, they will be computed and saved in the scene list files. If min_max_len has bee...
def _get_video_paths(self, paths: List[str], recursive: bool) -> List[str]: """Find all the video files in the paths. If a path is a folder, it will search recursively inside the folder if recursive is set to True. Args: paths (List[str]): List of paths to search for videos. recu...
This code initializes a dataset that dynamically loads and processes video scenes detected using PySceneDetect. It handles scene detection methods (content, threshold, adaptive), splits scenes into specified length ranges, removes duplicates via metrics (MSE, MAE, LPIPS), and manages video paths, transformations, and p...
def __init__( self, paths: List[str], transform: Optional[Callable] = None, recursive: bool = False, show_progress: bool = False, min_max_len: Optional[Tuple[int]] = None, detector: Literal["content", "threshold", "adaptive"] = "content", duplicate_thresho...
def find_distance_buildings(self): building_positions = self.find_buildings_positions() worker_pos = self.tile["grid"] if not building_positions: return None, None dist_to_all = [pg.math.Vector2(worker_pos).distance_to( building_pos) for building_pos in building...
The function `util_return` gathers and returns key environmental data for decision-making, including the nearest building's position, distances to all buildings, people's positions, the nearest person's location, distances to all people, the worker at the nearest position, and the corresponding building object. This da...
def util_return(self): # Returns Inventory/Distance of Building and Worker nearest_building_position, dist_to_all_buildings = self.find_distance_buildings() people_positions, nearest_person_position, dist_to_all_persons = self.find_people_distance() worker = self.get_worker_at_nearest_position(...
def load_images(self): scaling_factor = 0.75 # Scale factor for assets image_files = { "building1": "assets/graphics/building01.png", "tree": "assets/graphics/nt1.png", "tree1": "assets/graphics/nt2a.png", "tree2": "assets/graphics/nt2b.png", ...
This code initializes a game world with grid-based structures, collision matrices, and entity tracking. It sets up a grid system for terrain using Perlin noise, loads tiles, creates collision data, and initializes arrays to track worker and building positions for a game environment.
def __init__(self, entities, hud, grid_length_x, grid_length_y, width, height, game): self.entities = entities self.hud = hud self.grid_length_x = grid_length_x self.grid_length_y = grid_length_y self.width = width self.height = height self.game = game #maybe remo...
def handle_events(self): now = pg.time.get_ticks() if now - self.start_time >= self.end_time and False: self.quit_game() for event in pg.event.get(): if event.type == pg.QUIT: self.quit_game() elif event.type == pg.KEYDOWN: if e...
The main task of the code is to execute a game loop that runs while `self.playing` is True. It maintains a 60 FPS frame rate using `self.clock.tick(60)`, processes events with `self.handle_events()`, updates game logic via `self.update()`, and renders visuals with `self.draw()`, creating a continuous cycle until the lo...
def run(self): self.playing = True while self.playing: self.clock.tick(60) self.handle_events() self.update() self.draw()
def util_return(self): # Returns Inventory/Distance of Building and Worker nearest_building_position, dist_to_all_buildings = self.find_distance_buildings() people_positions, nearest_person_position, dist_to_all_persons = self.find_people_distance() worker = self.get_worker_at_nearest_position(...
The code calculates and manages an agent's needs (gathering, giving, stealing) based on proximity to a building. If a building is nearby, it triggers gathering logic; otherwise, gathering need is reset to zero. It then evaluates giving and stealing needs, finally setting interaction need as the maximum of stealing and ...
def need_management(self): # Informations nearest_building_position, _, _, _, _, _, _ = self.util_return() # Calculate needs if nearest_building_position is not None: self.need_m_gather() else: self.need_gather = 0 self.need_m_give() self....
def need_management(self): # Informations nearest_building_position, _, _, _, _, _, _ = self.util_return() # Calculate needs if nearest_building_position is not None: self.need_m_gather() else: self.need_gather = 0 self.need_m_give() self....
This code manages an agent's behavior by updating its state every 500ms, determining interaction type (give/steal/none) based on character value, and selecting actions like following a person, gathering resources, or idling. It prioritizes interaction over gathering if conditions are met, then executes corresponding be...
def brain(self): now = pg.time.get_ticks() if now - self.update_timer > 500: self.update_timer = now self.need_management() self.check_interacting_status() if self.character_value > 0: self.interacting_behaviour = 1 # Give eli...
def update_current_symbol(self, signal): """ Append the current dot or dash onto the end of current symbol """ # Short signal, dot if (0 < signal < 2*T): self.blink_red() self.current_symbol += '.' # Long signal, dash else: self.blink_blue() ...
This code processes incoming signals to determine if they represent a dot/dash (when the button is pressed) or breaks between symbols/words. It checks the signal duration against thresholds (short, medium, long breaks) to decide whether to update the current symbol, end a symbol, or end a word, using the system's state...
def process_signals(self, signal): """ Examine the recently-read signal and call one of several methods""" """ Takes in a signal as a number of seconds """ # If state after signal is 0, the button must have been pressed, # and the signal was a dot or a dash if (self.current_btn_...
def next_pos(measurement, OTHER = None): """Estimate the next (x, y) position of the wandering Traxbot based on noisy (x, y) measurements.""" cond3=False global last,first_calc,num5,P_initialized,predictor,num_list,num2,are_transformed,num_particles,theta,\ edge_length,measuring_tol,a_list,lis...
The function `next_move` calculates the hunter's next movement (turning angle and distance) to intercept a moving target. It uses the target's current position and historical data (`OTHER`) to predict its future location. If a direct approach is feasible (`num5 < 1`), it computes heading and distance to the target's ne...
def next_move(hunter_position, hunter_heading, target_measurement, max_distance, OTHER = None): # This function will be called after each time the target moves. global pos_list,move_num,pred_pos,steps next_position,OTHER,condition=next_pos(target_measurement,OTHER) pos_list.append(next_position) i...
def setup_device(): device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu") return device def get_tem_data_path() -> str: path = "../data/modified_data/modified_data_TEM.csv" return path def get_data(path: str) -> pd.DataFrame: data_path = os.path.join(_dir, path) ...
The main task of the code is to train and evaluate an LSTM model for soil prediction using cross-validation, with options to pretrain the model on TEM data, load a saved model, or train from scratch. It processes input data, splits into training/validation sets, trains the model with Adam optimizer and MSE loss, select...
def main(): parser = argparse.ArgumentParser() parser.add_argument('-pt', '--pretrain', type=int, default=0, help='Pretrain the model with TEM outputs (1 for true, 0 for false)') parser.add_argument('-ld', '--load', type=str, help='Model file to load (state dict)') # option to load a saved model parser....
def replace(a, b, c): return a.replace(b, c) def camel_to_slug(name, sep="-", lower=True): name = re.sub("(.)([A-Z][a-z]+)", r"\1" + sep + r"\2", name) name = re.sub("([a-z0-9])([A-Z])", r"\1" + sep + r"\2", name) return name.lower() if lower else name def create_service_file(symbol, service, filename):...
The code generates documentation files (e.g., .rst) from protocol buffer definitions, organizing services/methods into directories. It creates service indexes, method files with route/websocket info, and an overall index using templates. Deprecated items are skipped, and generated files are tracked in .autogen to avoid...
def generate(parser, destdir, title, additional_docs): service_count = 0 for file in parser.proto.file: service_count += len(file.service) service_links = [] method_links = [] generated_files = [] for file in parser.proto.file: for service in file.service: if service...
def _init(self): GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) GPIO.setup(self.s_data_pin, GPIO.OUT) # (pin 26 = GPIO7) = DATA GPIO.setup(self.s_clk_pin, GPIO.OUT) # (pin 24 = GPIO8) = CLOCK GPIO.setup(self.reset_pin, GPIO.OUT) # (pin 22 = GPIO25) = RESET GPIO.o...
The main task of the code is to initialize a display device by configuring data, clock, and reset pins, setting up font and text mapping dictionaries, and preparing the display for text output through initialization and clearing operations.
def __init__(self, s_data_pin, s_clk_pin, reset_pin) -> None: self.s_data_pin = s_data_pin self.s_clk_pin = s_clk_pin self.reset_pin = reset_pin self.font2 = {} self.txtmapa = {} self._init() self.clear() self._init_text_mode()
def __current_token(self) -> str: return self.line[self.pos] def __parse_crate(self) -> Union[str, None]: # An empty crate represents three spaces in the line if self.__current_token() == SPACE: for _ in range(3): self.__consume_token(token=SPACE) return N...
The main task of the code is to parse a list of crates from the current line of input. It iterates through tokens, extracting crates using `__parse_crate()` and appending them to `crate_list` until a newline (`\n`) is encountered or the line ends. Spaces between crates are consumed, ensuring proper separation. The func...
def parse(self) -> list: # List of crates in the given line crate_list = [] while (self.pos < len(self.line)) and self.__current_token() != "\n": crate = self.__parse_crate() crate_list.append(crate) if self.__current_token() == "\n": break ...
def package_src(self): self.output.info("package_src") conans_tools.copy_src(conanfile=self, folder=self.get_src_folder()) def package_include(self): self.output.info("package_include") conans_tools.copy_includes(conanfile=self, folder=conans_tools.find...
The main task of the code is to orchestrate the packaging process by calling methods to package source files, include directories, and optionally libraries and binaries, depending on the `header_only` flag. It logs the start of packaging and conditionally executes steps for libraries/binaries when `header_only` is Fals...
def package(self): self.output.info("package") self.package_src() self.package_include() if not self.header_only: self.package_lib() self.package_bin()
def predict(self, X, w=None): """ Predicts the labels for a given dataset X: a numpy.ndarray of shape (n, d) containing the dataset Returns: y: a numpy.ndarray of shape (n,) containing the predictions """ if w is None: w=self.w y = np.dot(X, w) ...
This code trains a machine learning model using a specified optimizer, tracking loss and predictions over iterations. It optionally renders training visualizations as an animation (saving as GIF) and plots gradients. The model updates weights iteratively, appending key metrics at intervals determined by adaptive step s...
def fit(self, optimizer='sgd_optimizer', n_iters=500, render_animation=False, gradiant_image=True): """ Trains the model optimizer: the optimization algorithm to use X: a numpy.ndarray of shape (n, d) containing the dataset y: a numpy.ndarray of shape (n, 1) containin...
def create_initial_dicts(m_int, true_p_int=None, true_q_int=None): """ Creates dictionaries representing m, p and q. If true_p_int or true_q_int are provided, algorithm treats their length as known and it sets the leading bits to 1. Args: m_int (int): number to be factored, as an integer....
The function `create_clauses` generates clauses for the VQF (Variational Quantum Factorization) algorithm to solve integer factorization. It constructs dictionaries for variables $ p $, $ q $, and carry bits $ z $, and derives clauses (Sympy expressions) representing constraints. If true factors $ p $ and $ q $ are pro...
def create_clauses(m_int, true_p_int=None, true_q_int=None, apply_preprocessing=True, verbose=True): """ Creates clauses for the VQF algorithm. If true_p_int or true_q_int are provided, algorithm treats their length as known. This also means that it sets the leading bits to 1. It returns dictionari...
def clear_area_workspace(): clear_area(-256, 256, 4, 15, -256, 256) def animate_img_path(name, x, y, z, center=True, time_step=0.1, inc_height=False): path = f'outputs/{name}/ACTUAL/steps' img_names = os.listdir(path) img_names.sort() for img_name in img_names: img = plt.imread(f'{path}/{img...
The main task of the code is to arrange and animate a set of images in a circular pattern using polar coordinates, placing each image at calculated 3D coordinates (x, z) and drawing lines to connect related parent-child image pairs. It loads precomputed image data, resizes images, and uses a sleep delay between steps t...
def main(): # img = plt.imread('init_image_tensor.png') # img = img[::img.shape[0]//16, ::img.shape[1]//16, :] clear_area_workspace() imgi = 0 pop = torch.load('outputs/pop.pth') parent_data = torch.load('outputs/parent_data.pth') name2coor = {} for circle_id in range(7): prin...
def read_data(edges_file): # Read nodes data from a file nodes_df = pd.read_csv(node_file, delimiter=" ") # Read edges data from the specified file and assign column names edges_df = pd.read_csv(edges_file, delimiter=" ", names=["layerID", "nodeID1", "nodeID2", 'weight']) return nodes_df, edges_df d...
The main task of the code is to compute and aggregate centrality measures for multiple disruption edge files. It iterates through each file, reads the graph data, optionally visualizes the graph, calculates centrality metrics, and compiles the results into a list for return.
def calculate_disruption_centrality_measures(visualize_graph): # Initialize an empty list to store centrality data for each disruption edge file disruption_centrality_list = list() # Iterate over each disruption edge file for edge_file in disruption_edge_files: # Read data from the current disr...
def read_data(edges_file): # Read nodes data from a file nodes_df = pd.read_csv(node_file, delimiter=" ") # Read edges data from the specified file and assign column names edges_df = pd.read_csv(edges_file, delimiter=" ", names=["layerID", "nodeID1", "nodeID2", 'weight']) return nodes_df, edges_df d...
The code analyzes network centrality measures under normal and disrupted conditions. It reads graph data, calculates centrality metrics, computes Kendall's tau correlations between normal and disrupted measures, checks matrix validity, performs hierarchical clustering, and visualizes results via a dendrogram to compare...
def main(): # Read data from the main edge file nodes_df, edges_df = read_data(main_edge_file) show_graph(nodes_df, edges_df) # obtain centrality list for the main edge file main_centrality_list = calculate_centrality_measure(nodes_df, edges_df, main_edge_file, top20=True) disruption_centralit...
def head_node_duties(self): """Function to perfrom head node duties""" logging.info("Starting head node duties\n") # Randomly sample a batch of data to send batch = random.sample(files, BATCH_SIZE) # Determine the storage server which contains each item of the batch se...
This code starts a TCP server to handle node communication in a distributed system. It listens for incoming connections, processes data types like 'ALIVE' (liveness checks) and 'TOKEN' (head node transfer), and writes received data batches to a Kafka topic. If the node is the head node, it manages duties like accepting...
def start(self): """Starts a TCP server and listens for incoming connections""" if self.is_head_node: _ = input("Press enter to start service\n") # Start a TCP server with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: # Bind the socket to the port ...
def isCollapsed(self): for row in self.coeffs: for patterns in row: if len(patterns) > 1: return False return True def observe(self): pos = self.minEntropyPos() if pos is None: return patterns = self.p...
The code repeatedly observes and propagates data until the object is collapsed, then initializes each row of `self.coeffs` with the first pattern from each row of `self.coeffs`, effectively resetting or simplifying the coefficient structure post-collapse.
def collapse(self): while not self.isCollapsed(): pos = self.observe() self.propagate(pos) self.coeffs = [[patterns[0] for patterns in row] for row in self.coeffs]
def unpickle_and_get(file_name): un_pkl = pickle.load( open( file_name, "rb" )) model = un_pkl["model"] pca = un_pkl["PCA"] scaler = un_pkl["scaler"] return model, pca, scaler def read_test_data(file_name): file = open(file_name) lines = file.readlines() data_x = pandas.DataFrame() f...
The main task of the code is to load a pre-trained machine learning model and associated preprocessing components (PCA and scaler), apply the same transformations to new test data, and generate predicted class labels. It reads test data from a CSV file, transforms it using the saved scaler and PCA, and returns predicti...
def transform_and_predict(test_file_name="testdata.csv", model_file="model.pkl"): """ Parameters: test_file_name (string) -- File name for test data with .csv extension model_file (string) -- File name of pickled model from train.py Returns: List: Predicted class labels of test data. """ ...
def check_keydown_event(event, ai_settings, screen, ship, aliens, bullets): """ check keydown event """ if event.key == pygame.K_RIGHT: ship.moving_right = True elif event.key == pygame.K_LEFT: ship.moving_left = True elif event.key == pygame.K_SPACE: fire_bullet(ai_settings, scr...
This function handles user input events in a game, checking for quit commands, key presses (movement/shooting), and mouse clicks to start the game. It delegates specific actions to helper functions for keydown/up events and play button activation, using mouse coordinates to determine if the play button was clicked.
def check_events(ai_settings, screen, stats, play_button, ship, aliens, bullets): """ Respond to the different captured events in the game """ for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.KEYDOWN: check_keydown_event(...
def ScanWorkFlow(self) : r''' ## this method is used to Scan the WorkFlow Graph, and get a list of 'READY' work, update the database and workflow ## improve : this algorithm is suitable for small graph, O(en) :return: ''' ini_nodes = [] digraph = {} for id...
This code manages a workflow by repeatedly allocating resources and launching computational nodes (CNodes) in iterative steps until the workflow is completed. It checks if the workflow is done using `ScanWorkFlow()`, and if not, it allocates resources, launches CNodes with an incrementing counter, and rechecks the work...
def RunWorkFlow(self): WorkIsDone = self.ScanWorkFlow() if WorkIsDone: return c = 0 while not WorkIsDone: self.AllocateResources() self.LaunchCNodes(c) WorkIsDone = self.ScanWorkFlow() c+=1 self.ScanWorkFlow() re...
def find_matches(img1, img2): sift = cv2.xfeatures2d.SIFT_create() kp1, des1 = sift.detectAndCompute(img1, None) kp2, des2 = sift.detectAndCompute(img2, None) matches = knnMatch(des1, des2) return matches, kp1, kp2 def findHomography(src, dst): inliers = [] H = None for i in range(500): ...
The main task of the code is to stitch two images using feature matching and homography. It converts input images to grayscale, finds keypoint matches, verifies sufficient matches (≥10), computes a homography matrix, and applies it to stitch images if inliers (≥30% of matches) are valid. If conditions fail, it returns ...
def stitch_images(img1, img2): img1_gray = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY) img2_gray = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY) good_matches, kp1, kp2 = find_matches(img1_gray, img2_gray) if len(good_matches) > 10: src_pts = np.float32([kp1[m['queryIdx']].pt for m in good_matches]).reshape...
def login(): update_config() print("Starting", SERVER, "server") mail = imaplib.IMAP4_SSL(SERVER) print("Logging in with", EMAIL) mail.login(EMAIL, PASSWORD) print("Logged in") mail.select('[Gmail]/Important') return mail def update_config(): global EMAIL, PASSWORD, SERVER, MAX_DEPTH...
This code fetches recent emails from an account, filters out blacklisted senders, extracts unique subjects, and compiles messages into chunks under 4096 characters. It then sends these compiled messages via notifications, updates tracking variables, and logs status. The process avoids duplicates, handles encoding, and ...
def main(): mail = login() global EMAIL, PASSWORD, SERVER, MAX_DEPTH, LAST_ID, INTERVAL update_config() _, data = mail.search(None,'All') mail_ids = [] for block in data: mail_ids += block.split() messages = [""] subject_arr = [""] for i in range(len(mail_ids), 1, -1): ...
def get_user_data(): user = spotify.current_user() if not len(user.images): pfp = 'https://cdn.pixabay.com/photo/2015/10/05/22/37/blank-profile-picture-973460_960_720.png' else: pfp = user.images[0].url data = { 'pfp':pfp, 'name':user.display_name, 'data':[ ...
The main task of the code is to handle user authentication via session tokens, refresh expiring Spotify API credentials, fetch user playback and top track/artist data from Spotify, and render a homepage template with personalized music statistics for authenticated users, redirecting to the login page if authentication ...
def main(): try: print(session) user = session.get('user', None) token = users.get(user, None) page = '' if user is None or token is None: session.pop('user', None) return render_template('index.html') if token.is_expiring: token ...
def split_prompt_into_chunks(prompt, chunk_size=2100): tokens = TOKENIZER.encode(prompt) chunks = [] while len(tokens) > 0: current_chunk = TOKENIZER.decode(tokens[:chunk_size]).strip() if current_chunk: chunks.append(current_chunk) tokens = tokens[chunk_size:] return...
The function performs topic modeling by splitting input text into chunks, extracting keywords related to specified topics, and classifying them into primary and secondary keywords based on relevance to the given topic list.
def apply_topic_modeling(text, topic_list): text_chunks = split_prompt_into_chunks(text) keywords_list = get_keywords_for_text(text_chunks=text_chunks, topic_list=topic_list) primary_keywords, secondary_keywords = get_primary_and_secondary_keywords(keywords_list=keywords_list, ...
def getLogger(): # Create logs folder if not exists if not os.path.isdir(os.path.join(currentDir, "logs")): try: os.mkdir(os.path.join(currentDir, "logs")) except OSError: print("Creation of the logs directory failed") else: print("Successfully created the logs directory") now = dat...
The main task of the code is to scrape data, store it in a SQLite database, and manage configurations, errors, and database connections. It checks for a config file, initializes the database, creates tables, and ensures proper handling of exceptions, including graceful shutdown on interrupts, while logging critical eve...
def mainFunction(): # Initialize the logger log = getLogger() log.info("################################# New run") try: # Check if configuration file exists, and exit if it is not if os.path.isfile(configFile) is False: message = "[FATAL] Config file does not exist. Exiting" log.info(messag...
def get_updates(offset=None): url = URL + "getUpdates" if offset: url += "?offset={}".format(offset) js = get_json_from_url(url) return js def get_last_update_id(updates): update_ids = [] for update in updates["result"]: update_ids.append(int(update["update_id"])) return max(...
The main task of the code is to continuously monitor and process incoming messages from a chatbot interface. It retrieves updates, identifies the latest message ID, and handles different message types: analyzing sentiment if enabled, responding to text messages via `process_text`, and sending photos for stickers. The l...
def main(): #chatbotconfig.init_nltk() last_update_id = None while True: updates = get_updates(last_update_id) if len(updates["result"]) > 0: last_update_id = get_last_update_id(updates) + 1 #echo_all(updates) for update in updates['result']: ...
def populateRandomObstacles(self, n): """Creates n random obstacles boxes in the environment """ tableTop = True self.obstacles.clear() self.obstacle_idx.clear() lb = 0.3 hb = 0.7 if tableTop: self._populateRandomObsTableTop(n) else: ...
The function `reset` reinitializes the Gym environment by resetting counters, updating obstacles if specified, sampling new start/goal positions under constraints, and returning the initial state. It clears the state history, adjusts obstacle configurations, and ensures valid configurations for the robot's workspace. T...
def reset(self, sampleStandGoal = True, new_obstacle=True): """Resets the GymEnvironment """ self.t_step = 0 self.num_resets += 1 ### environment change if new_obstacle: for idx in self.obstacle_idx: self.stspace.remove_body(idx) s...
def sse(actual, predicted): return (residuals(actual, predicted) **2).sum() def ess(actual, predicted): return ((predicted - actual.mean()) ** 2).sum() def tss(actual): return ((actual - actual.mean()) ** 2).sum() def mse(actual, predicted): n = actual.shape[0] return sse(actual, predicted) / n def ...
The code calculates and returns common regression error metrics—SSE, ESS, TSS, MSE, RMSE—as a pandas Series to evaluate model performance.
def regression_errors(actual, predicted): return pd.Series({ 'sse': sse(actual, predicted), 'ess': ess(actual, predicted), 'tss': tss(actual), 'mse': mse(actual, predicted), 'rmse': rmse(actual, predicted), })
def sse(actual, predicted): return (residuals(actual, predicted) **2).sum() def mse(actual, predicted): n = actual.shape[0] return sse(actual, predicted) / n def rmse(actual, predicted): return math.sqrt(mse(actual, predicted))
The function calculates baseline error metrics for a model that predicts the mean of actual values. It computes the sum of squared errors (SSE), mean squared error (MSE), and root mean squared error (RMSE) between the actual data and the predicted mean. These metrics evaluate how well the mean serves as a naive predict...
def baseline_mean_errors(actual): predicted = actual.mean() return { 'sse': sse(actual, predicted), 'mse': mse(actual, predicted), 'rmse': rmse(actual, predicted), }
def LeaderElection(self, firstConnect): sleep(self.id) self.stopConnection = False if self.state.state == "Leader": self.DisconnectReplicas() self.state.ChangeState("Candidate") if not self.stopConnection: self.ConnectReplicas() if not self.stopCon...
The Heartbeat function maintains leader status in a distributed system by periodically checking for re-elections, sending heartbeat signals to replicas, and handling failures. If as a Leader, it triggers re-elections, sends heartbeats, and reconnects replicas on errors. As a Follower, it monitors timeouts and initiates...
def Heartbeat(self): while True: while self.state.state == "Leader": if self.state.ReElectionTimer(): self.LeaderElection(False) try: self.MajorityInvoke(self.id, "Heartbeat", "") except Exception as ex: ...
def MajorityInvoke(self, replicaId, requestLabel, requestData): global results results = [] # [None] * len(self.replicas) # Already excluding itself in the creation of the replicas t = [] for i in range(len(self.replicas)): t.append(Thread(target=self.invoke, args=(i, i, re...
This code processes incoming requests in a distributed system, distinguishing between leader and non-leader states. As a leader, it invokes majority operations, handles requests, logs data, and increments term/log indices. On errors, it triggers leader elections. Non-leaders process requests directly, logging data and ...
def processRequest(self, SenderID, RequestLabel, RequestData): ReplicaID = self.id if SenderID == -1 and self.state.state != "Leader": return "Leader -> " + str(self.state.leader) elif self.state.state == "Leader": try: self.MajorityInvoke(ReplicaID, Reque...
def GetEntries(self, index): return self.logger.get_logs(index) def AppendEntries(self): index = self.state.lastLogIndex leader = self.state.leader entriesData = self.replicas[leader].Invoke(self.id, "Append Entries", str(index)) entries = pickle.loads(entriesData) for en...
The code defines a server listener that handles incoming client requests, processes messages based on their labels (e.g., "Append Entries," "Start Election," "Set Leader," "Heartbeat"), and sends appropriate responses. It manages Raft consensus protocol interactions, including leader elections, log replication, and sta...
def Listen(self): print("Server listening...") self.socketServer.listen(len(self.replicas) + 1) Thread(target=self.LeaderElection, args=(True,)).start() while self.signal: try: (clientsocket, address) = self.socketServer.accept() message = clie...
def create_multiple_choice(self): mcButton1 = QPushButton(self) font = mcButton1.font() font.setPixelSize(int(self.width / 80) ) mcButton1.setFont(font) mcButton1.setGeometry(int(self.width * 1/32), self.height - 50, int(self.width * 3 / 16), 90) mcButton1.clicked.connec...
This method handles post-image-load tasks by storing the background images, removing the progress bar and logo, creating either multiple-choice options or a text box based on the easy mode setting, fetching a new street, and displaying the quiz progress bar.
def handle_images_loaded(self, background_images): self.background_images = background_images # Handle the loaded images self.progress_bar.deleteLater() # Remove progress bar after loading is complete self.logo.deleteLater() if self.easy_mode: self.create_multiple_c...
def font(self, size): myFont = pygame.font.Font('freesansbold.ttf', size) return myFont def help_surface(self): self.canvas.get_screen().fill((52, 77, 105)) fonts = self.font(25) description = pygame.image.load('./images/img/description.png') self.canvas.get_screen().bli...
This code displays the initial game screen, allowing user input for name entry, help, high scores, and exit. It loads background images, renders interactive buttons, and processes keyboard/mouse events to trigger functions like help, score display, or game start. The loop handles real-time input, updates the name field...
def first_surface(self): game_over = False self.canvas.get_screen().fill((36, 37, 81)) geistes_img = pygame.image.load('./images/img/Geistesblitz-5-vor-12(2).jpg') self.canvas.get_screen().blit(geistes_img, (0, 0)) game_img = pygame.image.load('./images/img/71xM7BosVRL.jpg') ...
def main_menu(): # draw main menu window draw_window() write_text('TIC TAC TOE', COLORS['WHITE'], 230, 50) gamemodes = [['EASY', 150], ['NORMAL', 250], ['HARD', 350], ['2 PLAYERS', 450]] for button in gamemodes: draw_button(button[0], 230, button[1]) def pick_a_player(): # draw pick a player w...
This code implements a Tic-Tac-Toe game with Pygame, handling user input for game mode selection (single-player vs 2-player), player symbol choice (X/O), game logic (board updates, win/draw detection), and game states (main menu, gameplay, end-screen). It manages player turns, AI moves (for single-player), and restarts...
def main(): global PLAYER, GAMEMODE, LOOP, PLAYER_TURN, BOARD, BUTTONS, SLEEP run = True while run: if LOOP == 1: # main menu main_menu() elif LOOP == 2: # pick X or O pick_a_player() elif LOOP == 3: # game loop draw_window() draw_b...
def __uci_is_legal_move(self, strMoveUci): for move in self.chessBoard.legal_moves: if move.uci() == strMoveUci: return True return False def __update_move_list(self): #self.moveList.clear() legal_moves = self.chessBoard.legal_moves for moveIdx in rang...
This function handles a player's move input by validating it, updating the chessboard, triggering the AI's response, and refreshing the UI. It first checks if the entered UCI move is legal. If valid, it applies the move, lets the AI generate a countermove, updates the board and move list, and checks for endgame conditi...
def move_list_clicked(self): uciMove = self.moveLineEdit.text().lower() if not self.__uci_is_legal_move(uciMove): self.moveLineEdit.setStyleSheet("color: red") return None self.moveLineEdit.clear() #uciMove = self.moveLineEdit.setText("") self.chessBoard.p...
def soup_to_panda(table): df = pd.DataFrame(pd.read_html(str(table))[0]).fillna("") rows = table.find("tbody").find_all("tr")[1:] assert len(df) == len(rows) food_type, df.attrs[DECK_ATTRIBUTES.DECK_NAME] = build_deck_name(table) df.attrs[DECK_ATTRIBUTES.FOOD_TYPE] = food_type working_dir = "med...
The code extracts data from Wikipedia tables, cleans duplicate Thai script entries, converts them into Anki decks with media files, and exports the results as an .apkg file and a CSV.
def main(): response = requests.get(WIKIPEDIA_URL) soup = BeautifulSoup(response.text, "html.parser") decks = [] media_files = [] dataframes = [] thai_script_set = set() total_duplicates = 0 for table in soup.find_all("table", {"class": "wikitable"}): df = soup_to_panda(table) ...
def parse_args(): parser = argparse.ArgumentParser() # Parameters parser.add_argument("--depth", default=12, type=int, help="Total number of blocks.") parser.add_argument("--patch_size", default=12, type=int, help="Patch Size.") parser.add_argument("--num_classes", default=8, type=int, help="Number...
The main task of the code is to initialize a model based on provided arguments, load a training dataset, generate pseudo ground truth masks (including old and real masks) using the model, and save these masks for further use in an experiment. The process involves parsing command-line arguments, setting up a neural netw...
def main(): args = parse_args() model = setup_model( args.arch, args.imgsize, args.num_classes, args.depth, args.patch_size, args.num_heads, args.prune, args.num_channels, args.pr_rate, args.multimodal, args.model_checkpoin...
def __init_A(self, norm_inducing_matrix, Z): if norm_inducing_matrix == 'identity': self.A = np.eye(self.n) elif norm_inducing_matrix == 'diagonal': z_var = np.zeros([self.n, 1]) for i in range(self.n): tmp = Z[i, :] z_var[i] = 1/np.var(tmp) self.A = np.diagflat(np.reshape(z_var, [self.n, 1]))...
The code initializes variables and validates parameters for a fuzzy clustering algorithm. It sets attributes like the number of clusters (`c`), data dimensions (`N`, `n`), fuzziness parameter (`m`), termination threshold (`epsilon`), and checks their validity. It also initializes matrices (A, V, U) for clustering compu...
def __init_vars(self, Z, c, fuzziness_parameter, termination_criterion, norm_inducing_matrix): self.c = c self.N = Z.shape[1] self.n = Z.shape[0] self.m = fuzziness_parameter self.epsilon = termination_criterion assert 1 < c < self.N, 'c must satisfy 1 < c < Number of samples' assert self.m > 1, 'fuzzine...
def __init_vars(self, Z, c, fuzziness_parameter, termination_criterion, norm_inducing_matrix): self.c = c self.N = Z.shape[1] self.n = Z.shape[0] self.m = fuzziness_parameter self.epsilon = termination_criterion assert 1 < c < self.N, 'c must satisfy 1 < c < Number of samples' assert self.m > 1, 'fuzzine...
This code implements the Fuzzy C-Means (FCM) clustering algorithm. It iteratively computes cluster centroids, updates membership degrees using distance metrics, and terminates when changes in the membership matrix fall below a threshold. The fuzziness parameter controls cluster hardness, while the norm-inducing matrix ...
def fit(self, Z, c, fuzziness_parameter=2, termination_criterion=0.01, norm_inducing_matrix='identity'): """ :param Z: Training instances to cluster :param c: Number of cluster :param fuzziness_parameter: The weighting exponent m influencing the fuzziness of the clusters As m approaches 1, the...
def load_samples(params): return ( utils.deserialise_from( params["SERIALISATION"][f"{name}_samples"] ) for name in ["train", "validation"] ) def set_up_model_and_optimizer(params, meta_tokens, device, ...
The main task of the code is to train or continue training a machine learning model using parameters from a configuration file, meta-tokens, and specified device. It loads training/validation data, initializes the model and optimizer, sets up training parameters, and executes the training process via a trainer. The fun...
def train_model(params, meta_tokens, device, is_extra_trained): """ (Extra) trains a model. :param params: a ConfigParser - the params read from the 'parameters.ini' file. :param meta_tokens: a MetaTokens instance created from the parameters file. :param device: the torch.device to use duri...
def __decode(self, sentences, final_encoder_context): """ Non-public utility method. Given the target sentences for the decoder and the final encoder state, this method feeds the sentences into the decoder, optionally providing it with the final encoder state (if the mod...
The code computes the cross-entropy loss for a sequence-to-sequence model during training. It processes source sentences through an encoder, decodes target sequences using the encoder's context, applies attention mechanisms to align source and target contexts, projects final contexts into word predictions, and compares...
def forward(self, source, target, source_is_sorted=False): """ :param source: a sequence of sentences - each sentence being a sequence of tokens/words (strs); the sentences being translated. :param target: a sequence of sentences - each sentence being a sequence of tokens...
def __encode_sentence(self, s): """ Non-public utility method. Computes the source contexts of shape (sentence_length, 1, num_directions * hidden_size) and the initial decoder context - a pair of tensors of shape (decoder_num_layers, 1, decoder_hidden_size). If initial ...
This function translates an input sentence by iteratively selecting the most probable next word based on contextual probabilities, appending it to the translation until the end token is reached or a specified length limit is met.
def __do_translate_sentence(self, s, limit): sentence_contexts, decoder_context = self.__encode_sentence(s) translation = [] word = self.__meta_tokens.start while (len(translation) < limit): probabilities, decoder_context = self.__distribution_after( word, ...
def getSelectedObjectIndex(self): return self.findIndexFromObjectName(self.selectedObject) def selectObject(self, selectedObject: str): print(selectedObject) self.selectedObject = selectedObject self.setObjectInfoPanel() def saveData(self): data = {} objectList = [] ...
The main task of the code is to remove the selected object from the list by setting its parent to None, popping it from the list, deselecting it, updating the UI, and saving the data. It checks if an object is selected, performs removal operations, and logs the removed index.
def removeObject(self): toRemove = self.getSelectedObjectIndex() if toRemove != -1: self.objects[toRemove].setParent(None) self.objects.pop(toRemove) self.selectObject(None) self.objectListPanel.updateList(self.objects) self.saveData() prin...
def draw_neurons(surface, nn, is_reward): col_center = 10 conn_starts = {} conn_starts = print_column_at(surface, nn.inputs, col_center, conn_starts, is_reward) col_center += 30 for row in nn.net: conn_starts = print_column_at(surface, row, col_center, conn_starts, is_reward) col_cen...
This code handles a game loop for a bug's movement and interaction with light objects. It reinitializes the bug's neural network, attempts movement, updates the HUD with neuron visualizations, checks for collisions with lights (rewarding the bug if caught), spawns new lights periodically, and updates the bug's percepti...
def on_loop(self): self.bug.nn.reinitialize() tried_move = self.bug.move() self.hud_surf.fill((255,255,255)) draw_neurons(self.hud_surf, self.bug.nn, False) if (tried_move): caughtLights = pygame.sprite.spritecollide(self.bug, self.lightSprites, True) if l...
def on_init(self): pygame.init() self.hud_surf = pygame.Surface((MAP_SIZE[0], HUD_HEIGHT)) self.text_surf = pygame.Surface((MAP_SIZE[0]//2, HUD_HEIGHT)) self.reward_overlay = pygame.Surface((MAP_SIZE[0]//2, HUD_HEIGHT), pygame.SRCALPHA) self.input_boxes = [InputBox(10, 10, 100, 2...
The code defines a game loop that initializes the game, processes events, updates the game state, renders graphics, and cleans up resources. It runs continuously while `_running` is True, handling events, looping logic, and rendering each frame until halted by `on_cleanup`.)
def on_execute(self): if self.on_init() == False: self._running = False while( self._running ): for event in pygame.event.get(): self.on_event(event) self.on_loop() self.on_render() self.on_cleanup()
def get_all_academy(): url = all_academy_url str_data = get_page(url).decode('utf-8') dic = json.loads(str_data) return dic def store_academy(academy): try: conn = sqlite3.connect('test.db') conn.execute('''INSERT INTO INSTITUTION(ID, NAME) VALUES(%s, '%s')''' % (aca...
The main task of the code is to retrieve all academies, iterate through each academy to print its name, store it, and fetch its notices and news. This process organizes and processes academy data systematically.
def main(): print('ok') all_academy = get_all_academy() for each in all_academy: print(each['name']) store_academy(each) get_all_notice(each) get_all_news(each)
def get_position_from_response(self, address): # Check types check_type(address, int) # Send out the ?pos self.qpos(address) # Get the ?pos response position_response = self.controller.readline().decode() # Return the position while position_response == '...
The main task of the code is to send a "home" command to a device at a specified address, move it to the home position, and optionally wait for the movement to complete with a timeout. It validates the address, prepares the command, executes the movement, and verifies the position was reached if blocking is enabled.
def home(self, address, block=True): # Check the address type. check_type(address, int) # Get the home command. command = self.__commands['home'] # Replace 'address' with the desired address. command = replace_address(command, address) # Get the current location ...
def _is_legal_movement(self,player,action,board): # player str: "white" or "black" # action int: between 0 and 4671, identifiying the move to take # Retuns false if the move is illegal take_move=True move_dict=self.moves[action] row=move_dict["start_position"][0] ...
This function checks if a player's move is legal by first verifying movement rules, then simulating the move on a test board to ensure it doesn't leave the player's king in check. If movement is valid and the resulting position isn't a check, the move is legal; otherwise, it's rejected.
def _is_legal(self,player,action,board): legal,_=self._is_legal_movement(player,action,board) if legal: # We pre make the move on a test board, this board does not get saved. This si to test for check, a move can't put your own king in check test_board=self._test_take_mo...
def buildCityGraph(graphType): g = graphType() for name in ('Boston', 'Providence', 'New York', 'Chicago', 'Denver', 'Phoenix', 'Los Angeles'): #Creaet 7 nodes g.addNode(Node(name)) g.addEdge(Edge(g.getNode('Boston'), g.getNode('New York'))) g.addEdge(Edge(g.getNode('Bos...
The code tests the shortest path algorithm (BFS) on a directed graph of cities. It constructs a graph, searches for the shortest path from a source to a destination node, and prints the path if found. If no path exists, it reports the absence of a connection between the nodes.
def testSP(source, destination): g = buildCityGraph(Digraph) # Choose one (DFS or BFS) #sp = DFSshortestPath(g, g.getNode(source), g.getNode(destination), toPrint=True) sp = BFSshortestPath(g, g.getNode(source), g.getNode(destination), toPrint=True) if sp!= None: print('Shortest path fro...
def fetch_item_data(self, item_id): # Retrieve data for the selected item self.cursor.execute(f"SELECT * FROM {self.table_name} WHERE ID = ?", (item_id,)) return self.cursor.fetchone() def update_item(self, item_id, edited_values): # Update the selected item with the edited values ...
The main task of the code is to create a dialog window for editing a database item's details (excluding 'ID' and 'password' fields), allowing users to modify text or datetime values, and updating the database with the edited values upon saving.
def edit_item_dialog(self, item_id): if not self.database_name or not self.table_name: return dialog = QDialog(self) dialog.setWindowTitle("Edit Item") dialog_layout = QVBoxLayout() item_data = self.fetch_item_data(item_id) if item_data is None: ...
def login(self): # Set up logging for user login logging.basicConfig( filename="logging_file.txt", level=logging.INFO, format='%(asctime)s - USER LOGGED IN') logger = logging.getLogger() logger.info('') def update_promotions_database(self): sea...
The code initializes a GUI for a promotions dashboard, setting up a window with a header containing a logo, date/time, and logout button. It creates a search bar, fetches promotions from a database, and dynamically generates promotion widgets displayed in a scrollable area. The interface is styled with custom colors an...
def __init__(self, MainWindow): super().__init__() self.promotion_timers = {} self.login() # Set up the main user interface MainWindow.setWindowTitle("Promotions Dashboard") screen = QDesktopWidget().screenGeometry() # MainWindow.setGeometry(0, 0, 1020, 600) ...
def gen_otp(self): otp = f'{random.randint(0, 9999):04d}' return otp def retranslateUi(self, MainWindow): _translate = QtCore.QCoreApplication.translate MainWindow.setWindowTitle(_translate("MainWindow", "This is the Login Page")) self.email_address.setPlaceholderText(_translate(...
The main task of the code is to initialize a login page GUI with fields for email, password, and OTP (One-Time Password), along with buttons for sending OTP, confirming login, and resetting password. It sets up a dark-themed interface with a logo, input fields, and connects buttons to functions for OTP generation, send...
def __init__(self, MainWindow): super().__init__() global OTP_USER_PASSWORD OTP_USER_PASSWORD = self.gen_otp() MainWindow.setObjectName("Login Page") MainWindow.resize(300, 472) self.centralwidget = QtWidgets.QWidget(MainWindow) self.centralwidget.setObjectName("c...
def create_database_buttons(self): database_buttons = QWidget(self) database_layout = QVBoxLayout() # Create a dictionary that maps button text to database and table names # self.database_button_mapping = { # "Users Database": ("users", "users"), # "Promotions Da...
This code initializes a database admin GUI with a table view, buttons for data manipulation (edit/add/delete), database selection, and search functionality. It sets up the window, layout, table styling, and connects UI elements to methods for interacting with a database, including dynamic table switching and data opera...
def __init__(self, email): super().__init__() self.setWindowTitle("Database Admin") self.setGeometry(100, 100, 800, 600) # Create the central widget and layout self.central_widget = QWidget(self) self.setCentralWidget(self.central_widget) self.layout = QVBoxLayou...
def encrypt_password(self, values): # Encrypt the password using MD5 if there is a 'password' column password_column = "password" if password_column in self.column_names: password_index = self.column_names.index(password_column)-1 password = values[password_index] ...
This code creates a dialog to add new items to a database table, generating input fields for each column (excluding 'ID') with appropriate widgets (QDateTimeEdit for DateTime columns, QLineEdit otherwise). It collects user inputs, encrypts passwords, formats datetime values, inserts the data into the database, and relo...
def add_data(self): # Add a new item to the table if not self.database_name or not self.table_name: return dialog = QDialog(self) dialog.setWindowTitle("Add Item") dialog_layout = QVBoxLayout() input_fields = {} for column in self.column_names: ...
def c_cn(spin, r_in, r_peak): l_in = l_k(spin, r_in) l_peak = l_k(spin, r_peak) lambda_in = vz(spin, r_in, l_in) lambda_peak = vz(spin, r_peak, l_peak) n = np.log(l_peak / l_in) / np.log(lambda_peak / lambda_in) c = l_in / lambda_in ** n return c, n def c_l(spin, r, theta, c, n): variable_l_min = 1.0 ...
The function computes the difference between two values, h_out and h_in, derived from geometric or physical calculations involving spin, radii (r_in, r_out), and angles (π/2). It uses helper functions c_cn, c_l, and c_h to calculate intermediate variables (c, n, l, h) based on input parameters, ultimately returning h_o...
def res(r): c, n = c_cn(kwargs['spin'], kwargs['r_in'], r) l_in = c_l(kwargs['spin'], kwargs['r_in'], np.pi / 2.0, c, n) l_out = c_l(kwargs['spin'], kwargs['r_out'], np.pi / 2.0, c, n) h_in = c_h(kwargs['spin'], kwargs['r_in'], np.pi / 2.0, l_in, c, n, kwargs['r_in']) h_out = c_h(kwargs['s...
def _path_of_dep(root, dep): return os.path.abspath(os.path.join(root, dep['local'])) def _execute(args, cwd): print('executing "' + ' '.join(args) + '" in ' + cwd) sys.stdout.flush() subprocess.check_call(args, cwd=cwd) def _getcmdcode(args, engine): cwd = _path_of_dep(engine.root, engine.dep) ...
This function creates a repository by cloning a specified Git remote into a local directory, ensuring the directory doesn't already exist. It checks out a specified branch if provided and sets the working copy to a defined revision. The process avoids overwriting existing directories and clones the full repository, eve...
def create_repo(self): """Create a repository, set the default remote, and set worknig copy to the specified revision.""" # intentionally want this to fail if the directory already exists to avoid blowing over some random directory os.makedirs(_path_of_dep(self.root, self.dep)) # not a g...
def fetch_data(self): for link in self.switches_links: link_list = link.split("-") switch_1 = "dpid:" + link_list[0] if switch_1 in self.dpids_dict.keys(): self.dpids_dict[switch_1]["links"].append((int(link_list[1]), int(link_list[2]))) else: ...
The main task of the code is to optimize the distribution of switches by randomly generating configurations, calculating the total link length for each, and selecting the configuration with the minimal link length to reduce overall network costs.
def first_process(self): """ This function aims to distribute the switches in the best way possible to reduce the total length of links :return: """ self.fetch_data() self.map_locations = self.set_equal_points(len(self.switches_dpids)) # distribute the switches r...
def ketplus(): ''' Constructs the |+> states''' ket = np.asmatrix(np.zeros((2,1),dtype=np.complex)) ket[0,0] = 1 ket[1, 0] = 1 return normalize_state(ket) def hadamard_test(state, U): ''' Applies the Hadamard test with Unitary operation U. The operation Automatically concatenates a |0> state. ''' g = usualket...
The code performs a quantum experiment to analyze the effect of a bitflip operation on |+> and |-> states using a Hadamard test. It initializes quantum states, applies the bitflipper matrix, calculates probability amplitudes, and prints the transformed states' magnitudes to observe the impact of the bitflip on superpos...
def bitflip_experiment(): bitflipper = np.asmatrix(np.array([[0, 1], [1, 0]], dtype=complex)) state = ketplus() state2 = hadamard_test(state, bitflipper) printsection() print("Init State(|+> state):\n") matprint(state) print("\nState after Hadamard Test with bitflip(|+> state):\n") matprint(abs((prob_amplitude...
def usualkets(i): ''' Constructs |0> and |1>''' ket = np.asmatrix(np.zeros((2,1),dtype=np.complex)) ket[i,0]= 1 return ket def hadamard_test(state, U): ''' Applies the Hadamard test with Unitary operation U. The operation Automatically concatenates a |0> state. ''' g = usualkets(0) state = np.kron(g,state) s...
The code performs a quantum phase estimation experiment by varying the phase parameter φ, applying a Hadamard test to a diagonal unitary matrix U, and measuring the probability of obtaining state |1⟩. It plots the probability of measuring |1⟩ as a function of φ, demonstrating how quantum phase estimation relates to the...
def phase_experiment(): precision = 100 probout = np.zeros((precision)) for i, phi in enumerate(np.linspace(0,1,precision)): U = np.diag(np.array([1,np.exp(2j*np.pi*phi)])) state = usualkets(1) state_updated = hadamard_test(state,U) prob1 = measure(state_updated,1) prob0 = measure(state_updated, 0) probo...
def get_common(parameter): if not env: get_environment() if not config: initialize_config() try: section_name = 'COMMON' + '_' + env.upper() value = config.get(section_name, parameter) logger.info(f"Found {parameter} values in config ini") except Exception as e: ...
The code retrieves configuration parameters, initializes AWS services (S3, Athena, Elasticsearch), processes a court CSV file into a DataFrame, creates a Parquet catalog, executes an Athena query to create a database view, and uploads processed data to Elasticsearch for indexing.
def main(): HOST= get_common('HOST') REGION_NAME = get_common('REGION_NAME') COURT_CSV_LOC = get_job_specific_parameters('COURT_CSV_LOC') COURT_OUTPUT_PARQUET_LOC = get_job_specific_parameters('COURT_OUTPUT_PARQUET_LOC') COURT_TABLE = get_job_specific_parameters('COURT_TABLE') ES_DOC=get_job_sp...
def potential_caused_by_cell_list(self, neighbor_list=""): if len(neighbor_list) == 0: neighbor_list = self.neighbor_list self_true_dot_pos = np.array(self.get_true_dot_position()) self_pot_by_neighbors = np.zeros(np.shape(self_true_dot_pos)[0]) for cell in neighbor_list: ...
This function calculates the Hamiltonian matrix for a quantum dot system by combining potentials from neighboring cells, internal potentials, and external fields. It constructs a 3x3 matrix using a predefined gamma structure, adds kink strength and electric field contributions, then incorporates diagonal internal poten...
def calc_hamiltonian(self): # hardcoding mobile charge atm # potential at self_dots due to all others dot_potential = self.potential_caused_by_cell_list(self.neighbor_list) print("Cell(", self.cellID, "): Dot Potentials:", dot_potential) gamma_matrix = -self.gamma * np.matrix([[0, 1, 0...
def realize_model(self, cache=True): if self.binary_model is None: h = self.naive_hash() cache_path = get_cache_path(h, prefix='sbp-ternary') try: if cache is not True: raise FileNotFoundError self.binary_model = np.load(cac...
The code generates elastic parameters (P-wave velocity $v_p$, S-wave velocity $v_s$, and density $b$) for a geological model. It uses a binary model to define sediment/water layers, applies Fourier shifting for depth correction, computes $v_s$ from $v_p$ and a ratio, integrates a water layer via inverse-weighted averag...
def elastic_model(self, ind_x=None, **kwargs): self.realize_model(**kwargs) if ind_x is None: m = self.binary_model else: m = self.binary_model[:, ind_x] v_p = np.where(m == 1, v_p_1, v_p_0) # sediments b = np.where(m == 1, density_1, density_0) ...
def which_chunk(world, part): for chunk in part: if world in chunk: return chunk def posterior(event, chunk, opp_part, opp_chnks): post=len(set(event) & (set(chunk) & set(unionchnks(opp_part, opp_chnks))))/len(set(chunk) & set(unionchnks(opp_part, opp_chnks))) return post def pssblchnks(post, event, part, opp_p...
The code models iterative communication between two agents (A and B) in a world, where each agent updates their possible chunks (beliefs) based on an event and the other agent's evolving beliefs. The process repeats until both agents' possible chunks stabilize, returning their sequences of updated beliefs (A_report, B_...
def communicate(world, event, agent_A, agent_B): chunk_A=which_chunk(world,agent_A) chunk_B=which_chunk(world,agent_B) oldpssblchnks_A=range(len(agent_A)) oldpssblchnks_B=range(len(agent_B)) A_report=[] B_report=[] posterior_A=posterior(event, chunk_A, agent_B, oldpssblchnks_B) A_report.append(posterior_A) ne...
def partition(lst): if len(lst)==1: return [lst] else: part=partition(lst[:-1]) place=random.randint(0,len(part)) if place==len(part): part.append([lst[-1]]) return part else: part[place].append(lst[-1]) return part def communicate(world, event, agent_A, agent_B): chunk_A=which_chunk(world,agen...
The code generates a random scenario with a world value and partitions for two agents. It repeatedly creates agent partitions, simulates communication, and checks if the scenario meets specific constraints (via `check_rtrctv_rgrt`) and a minimum turn count (≥4). If valid, it prints and returns the world, event, agents,...
def gen_scenario(): world=random.randint(1,10) event=[3,6,9] num_turns=0 while(True): print("Generating scenario") agent_A=partition(list(range(1,11))) agent_B=partition(list(range(1,11))) reports=communicate(world,event,agent_A,agent_B) num_turns=len(reports[0]) if check_rtrctv_rgrt(reports)==True: ...
def Dense_Inception_Block(x, model_width, multiplier, num_dense_loop): for _ in range(0, num_dense_loop): IRU = Inception_Res_Block_2(x, model_width, multiplier) x = tf.keras.layers.concatenate([x, IRU], axis=-1) return x def Downsampling_Block(inputs, model_width, multiplier): # Downsampli...
The code defines a Dense-Inception-UNet model for tasks like classification or regression. It constructs an encoder with inception/residual blocks and downsampling, optionally extracts latent features, then decodes with upsampling, skip connections, attention, and dense inception blocks. The model outputs class probabi...
def Dense_Inception_UNet(self): """Variable Dense_Inception_UNet Model Design""" if self.length == 0 or self.model_depth == 0 or self.model_width == 0 or self.num_channel == 0 or self.kernel_size == 0: print("ERROR: Please Check the Values of the Input Parameters!") convs = {} ...
def scale(data, min_screen, max_screen, min_data, max_data): """ get the scaled data with proportions min_data, max_data relative to min and max screen dimentions """ return ((data - min_data) / (max_data - min_data)) * (max_screen - min_screen) + min_screen def _get_x_y(self, src: tuple, dest: tupl...
This code initializes a Pygame-based game interface, rendering a graph structure with nodes and edges, positioning game elements (pokemons, agents) dynamically, and displaying real-time statistics (grade, moves, time). It handles user input via a "Stop" button, scales graphics to the screen, and maintains a 60 FPS loop...
def __init__(self): control = Controller() graph = control.get_graph() pg.init() self.screen = display.set_mode((WIDTH, HEIGHT), depth=32, flags=RESIZABLE) clock = pg.time.Clock() pg.font.init() FONT = pg.font.SysFont('Century', 20, bold=False) FONT2 = pg....
def compute_jsd(self, gt_set=None, pred_set=None, resolution=28): """ Input: gt_set: np.ndarray or torch.Tensor [N1, M1, 3] pred_set: np.ndarray or torch.Tensor [N2, M2, 3] Output: jsd: float """ gt_set = gt_set if gt_set is not None else s...
The function computes and returns multiple metrics (JSD, MMD, COV, 1-NNA) to evaluate the similarity/distance between ground truth and predicted sets. It calculates pairwise distance matrices (Mxx, Mxy, Myy), derives MMD/Cov from Mxy, computes 1-NNA using all matrices, and optionally returns distance matrices. Metrics ...
def compute_all_metrics( self, gt_set=None, pred_set=None, batch_size=None, device=None, verbose=False, return_distance_matrix=False, compute_jsd_together=True, ): """ Output: JSD MMD-{metric} COV-{me...
def ts_metadata( dataset_name: str, ) -> Dict[Any, Any]: """ Get metadata about a dataset. https://knoema.com/dev/docs/meta/datasetdetails :param dataset_name: name indentifying the dataset :return: Deserialized json object """ url = f"{API_BASE}/meta/dataset/{dataset_name}" res = ...
The code retrieves time series metadata and region data for a dataset, optionally infers the country name, fetches time series data via an API, transforms it into a pandas DataFrame with metadata, and exports the result to a CSV file. The main task is to simplify accessing and exporting time series data from an API int...
def simple( dataset: str, guess_country: bool, timeseries_key: int, csv_file: str ) -> None: """ Subcommand for using the simple data API. """ metadata_response = ts_metadata(dataset) region_response = dataset_region(dataset) if guess_country: extract_country_result = extract_country...
def add_filters( dimension_id: str, members: List, dimension_name: str, dim_filter: List = [] ): """ Function to create or modify a list of filters. :param dimension_id: Id of the dimension we want to filter on :param members: List of members we want to include :param dimension_name: Name of the...
The code processes dataset filters, retrieves metadata and region data, constructs a raw API request with specified frequency and filters, transforms the API response into a pandas DataFrame, and exports it to a CSV file. It handles country name extraction if enabled, logging key steps, and ensures data is saved as spe...
def raw(dataset, guess_country, csv_file, frequency, filter): """ Subcommand for using the raw data API. """ dim_filter = None logging.debug("Parsing the filters") for f in filter: dimension_id, dimension_name, member = f.split(";") logging.info(f"{dimension_id}, {dimension_name}...
def needs_update(user): if user.last_synced_repos is None: return True expiration = app.config['REPOSITORY_SYNC_EXPIRATION_MINUTES'] return (datetime.now() - user.last_synced_repos).total_seconds() > expiration * 60 def get_user_orgs(): return get_list('user/orgs', lambda item: { 'name'...
The function synchronizes a user's repositories and organizations with the database, adding new entries and updating the last sync timestamp. It retrieves existing user data, fetches updated orgs/repos via API, creates missing entries, sorts them, and commits changes. The 'force' flag bypasses the update check.
def update_user_repos(force=False): from fish_bundles_web.models import Repository, Organization if g.user is None or (not force and not needs_update(g.user)): return repos = [] user_repos = dict([(repo.repo_name, repo) for repo in Repository.query.filter_by(user=g.user).all()]) user_orgs...
def parse_input(debug): with open(f"input/{'test' if debug else '14'}.txt", 'r') as f: raw = f.read().strip().split('\n') paths = [line.split(' -> ') for line in raw] paths = [[(int(coords.split(',')[0]), int(coords.split(',')[1])) for coords in path] for path in paths] lines = [get_lines(path) ...
This code simulates sand grains falling on a grid. It parses occupied squares, constructs a board, and iteratively drops grains until one cannot fall (returns 'Fell'). The function counts how many grains are successfully placed before this occurs, adjusting coordinates based on the minimum x-value and maximum y-value o...
def part1(debug=False): occupied_squares = parse_input(debug) min_x = min(occupied_squares, key=lambda s: s[0])[0] max_x = max(occupied_squares, key=lambda s: s[0])[0] max_y = max(occupied_squares, key=lambda s: s[1])[1] board = construct_board(occupied_squares, min_x, max_x, max_y) grains = 0 ...
def parse_input(debug): with open(f"input/{'test' if debug else '14'}.txt", 'r') as f: raw = f.read().strip().split('\n') paths = [line.split(' -> ') for line in raw] paths = [[(int(coords.split(',')[0]), int(coords.split(',')[1])) for coords in path] for path in paths] lines = [get_lines(path) ...
The code simulates sand falling on a grid until a grain lands at the original starting position (500, 0). It first parses input to identify occupied squares, expands the grid boundaries to accommodate potential sand movement, constructs a grid representation, and iteratively drops sand grains. Each grain falls until it...
def part2(debug=False): occupied_squares = parse_input(debug) min_x = min(occupied_squares, key=lambda s: s[0])[0] max_x = max(occupied_squares, key=lambda s: s[0])[0] max_y = max(occupied_squares, key=lambda s: s[1])[1] # In worst case, triangle with width equal to twice its height is required to g...
def setup_args(): parser = argparse.ArgumentParser(description="YANG JSON Validator") parser.add_argument( "-json_file", help="JSON to validate against YANG implementation.", default="yang.json", ) parser.add_argument( "-report_file", help="Filename to output vali...
The main task of the code is to validate Cisco YANG modules against a JSON schema, either automatically (if OS/release/product flags are provided) or interactively. It loads a YANG parser, reads input JSON, performs validation, generates a report, and writes it to a file. Error handling ensures required files exist and...
def main(): logging.basicConfig(level=logging.INFO) args = setup_args() module_parser = None try: module_parser = ModuleParser(args.base_cisco_yang_path) except FileNotFoundError: logging.error("Ensure %s exists!", args.base_cisco_yang_path) return 1 validation_json = Non...
def setup_args(): parser = argparse.ArgumentParser( description="YANG JSON Validator against Online Device" ) parser.add_argument( "-json_file", help="JSON to validate against YANG implementation.", default="yang.json", ) parser.add_argument( "-report_file", ...
The code's main task is to validate network configurations using either automated (autopilot) or interactive methods based on command-line arguments. It loads a JSON validation file, suppresses specific logging warnings, executes the chosen validation process, generates a report, and writes it to a specified file. Erro...
def main(): logging.basicConfig(level=logging.INFO) logging.getLogger("ncclient.operations.rpc").setLevel(logging.WARN) logging.getLogger("ncclient.transport.ssh").setLevel(logging.WARN) args = setup_args() validation_json = None try: with open(args.json_file, "r") as json_file_fd: ...
def create_nerf(args): """Instantiate NeRF's MLP model. """ model = TALLSIREN(input_dim=3, z_shape_dim=args.z_shape_dim, z_app_dim=args.z_app_dim, hidden_dim=256, output_dim=1) model.cuda() grad_vars = list(model.parameters()) model_fine = None if args.N_importance > 0: model_fine =...
The code trains a neural network model (likely a NeRF variant) for image synthesis using distributed computing. It loads the CARLA dataset, initializes camera intrinsics, and sets up distributed training with multi-GPU support. The model includes a pose estimator, inference network, and energy-based models (EBMs) for l...
def train(args): dist.init_process_group(backend='nccl') device = torch.device('cuda', args.local_rank) print('running process on ', device, device == torch.device('cuda', 0)) torch.cuda.set_device(device) K = None # Dataloader if args.dataset_type == 'carla': from load_carla_persis...
def joggModeInit(objectFrame, objectOdrv): var = IntVar() r1 = Radiobutton(objectFrame, text = "1 mm", variable=var, value=1, bd = 0, command = lambda: radioButtonSelection(var)) r2 = Radiobutton(objectFrame, text = "2 mm", variable=var, value=2, bd = 0, command = lambda: radioButtonSelection(var)) r5 =...
The code initializes a graphical user interface (GUI) for a 5-Bar Robot application using Tkinter. It sets up a window with a canvas to visualize the robot's position, adds two control modes (Jogg and GoTo) via labeled frames, and includes buttons for quitting, idle mode, and closed-loop control. The GUI is configured ...
def mode1init(objectOdrv): root1 = Tk() root1.title("5-Bar Robot") root1.iconbitmap("C:/Users/Matej/Desktop/5_Bar_Robot/photo_gif/robotIcon.ico") root1.configure(background = backgroundColor) ##Draw robot positon robotPosition = Canvas(root1, width=750, height=500, bg = backgroundColor , cu...
def load_manifest(self): local_filepath = "/home/gunther/dh_datastack_dbt/dh_datastack/target/manifest.json" #"C:/Users/GuntherMeert/Downloads/manifest.json" with open(local_filepath) as f: data = json.load(f) return data def parent_mapping_data(self): data = self.load_manif...
This code initializes a class to integrate dbt with Apache Airflow. It sets up parameters for dbt project configuration, loads the dbt manifest file to map dependencies, and prepares task groups for orchestrating dbt models as Airflow tasks. The main task is to configure and structure dbt model execution within Airflow...
def __init__( self, dag=None, dbt_global_cli_flags=None, dbt_project_dir=None, dbt_profiles_dir=None, dbt_target=None, dbt_tag=None, dbt_run_group_name="dbt_run", dbt_model_run=None, ): self.dag = dag self.dbt_global_cli_flags ...
def generate_all_nodes(self): for node in self.data["nodes"].keys(): if node.split(".")[0] == "model" or node.split(".")[0] == "snapshot" or node.split(".")[0] == "seed": #we specifically choose only models, snapshots & seeds self.dbt_nodes[node] = {} self.dbt_nodes[...
The function `make_dbt_task_groups` generates Airflow tasks for DBT nodes based on the `dbt_model_run` parameter. It creates BashOperator tasks for each node, adding freshness check, refresh, and validation tasks if dependencies exist. It then establishes dependencies between tasks, ensuring proper execution order by l...
def make_dbt_task_groups(self): # check if parameter model_run <> all if self.dbt_model_run == 'all': self.generate_all_nodes() else: if self.dbt_model_run in self.parent_map_data: self.iterate_parent_nodes(self.dbt_model_run) #create a bashopera...
def load_manifest(self): local_filepath = self.dbt_manifest_filepath with open(local_filepath) as f: data = json.load(f) return data def parent_mapping_data(self): data = self.load_manifest() return data["parent_map"] def make_dbt_task_groups(self): # check ...
This code initializes a class to configure dbt (data build tool) integration with Apache Airflow. It sets parameters for dbt project directories, profiles, and CLI flags, loads a dbt manifest file to parse dependencies, maps parent-child relationships between nodes, and generates Airflow task groups based on dbt models...
def __init__( self, dag=None, dbt_global_cli_flags=None, dbt_project_dir=None, dbt_profiles_dir=None, dbt_target=None, dbt_manifest_filepath=None, dbt_tag=None, dbt_run_group_name="dbt_run", dbt_model_run=None, ): self.dag = da...
def get_measured_vs_date_lists_for_assay(self, assay_int): sql_cmd = "select assay_{} from assays;".format(assay_int) measured_list = self.run_sql(sql_cmd) date_list = self.get_all_dates() return measured_list, date_list def make_x_and_y_axis_for_chart(self, measured_list, predicted_li...
The main task of the code is to prepare data for a chart comparing measured values against time. It retrieves measured values and corresponding dates for a given assay, formats the date list as the x-axis, and generates the y-axis data using the measured values. The function returns the formatted x-axis (dates) and y-a...
def get_chart_data_measured_vs_time(self, assay_int): measured_list, date_list = self.get_measured_vs_date_lists_for_assay(assay_int=assay_int) y_axis, not_used = self.make_x_and_y_axis_for_chart(measured_list, measured_list) x_axis = self.format_datelist_for_chart(date_list) return x_...
def error_pause_and_exit(error_msg): print(f"{error_msg}\n") #input("Press enter to exit...") sys.exit(1) def extract_save_folders(save_filepath): save_basename = save_filepath.with_suffix("").name if save_basename == "data": error_pause_and_exit("Save cannot be named data!") save_data ...
The main task of the code is to process either a save file (`.sav`) or a folder, determining its type via file extension. If a save file is provided, it extracts its contents; if a folder is provided, it converts it into a save file. The code validates input existence, checks for correct file types, and handles errors ...
def main(): #ap = configargparse.ArgumentParser( # allow_abbrev=False, # config_file_parser_class=configargparse.YAMLConfigFileParser, # config_file_open_func=lambda filename: open( # filename, "r", encoding="utf-8" # ) #) # #ap.add_argument("-cfg", "--config", des...
def projection(self, z: torch.Tensor) -> torch.Tensor: z = F.elu(self.fc1(z)) return self.fc2(z) def semi_loss(self, z1: torch.Tensor, z2: torch.Tensor): f = lambda x: torch.exp(x / self.tau) refl_sim = f(self.sim(z1, z1)) between_sim = f(self.sim(z1, z2)) return -torch....
This code computes a contrastive loss by projecting input tensors z1 and z2 into feature spaces h1 and h2, then calculating mutual semi-supervised losses (l1 and l2) between the projections. The loss combines both directions (h1→h2 and h2→h1), averages them, and applies mean/sum reduction based on the 'mean' parameter ...
def contrastive_loss(self, z1: torch.Tensor, z2: torch.Tensor, mean: bool = True, batch_size: int = 0): h1 = self.projection(z1) h2 = self.projection(z2) if batch_size == 0: l1 = self.semi_loss(h1, h2) l2 = self.semi_loss(h2, h1) else: l1...
def generate_initial_data(n_samples=1): # generate training data train_x = draw_sobol_samples( bounds=problem_bounds, n=1, q=n_samples, seed=torch.randint(1000000, (1,)).item() ).squeeze(0) train_x = train_x.type(torch.DoubleTensor) train_x_actual = unnormalise_parameters(train_x) print(...
This code performs multi-objective Bayesian optimization using the qEHVI acquisition function. It initializes GP models, iteratively samples new points, updates the Pareto front, and tracks hypervolume improvements over iterations. The goal is to optimize multiple objectives by expanding the Pareto frontier while measu...
def mobo_execute(seed, iterations, initial_samples): torch.manual_seed(seed) hv = Hypervolume(ref_point=ref_point) # Hypervolumes hvs_qehvi = [] # Initial Samples # train_x_qehvi, train_obj_qehvi = load_data() train_x_qehvi, train_x_actual_qehvi, train_obj_qehvi, train_obj_actual_qehvi = g...
def rotate_image(image, angle): #returns inputed image rotated by the specified angle image_center = tuple(np.array(image.shape[1::-1]) / 2) rot_mat = cv2.getRotationMatrix2D(image_center, angle, 1.0) result = cv2.warpAffine(image, rot_mat, image.shape[1::-1], flags=cv2.INTER_LINEAR) return r...
The function processes a video frame to detect ArUco markers, calculate the robot's position (Cx, Cy) and orientation (angle), and identify blue blocks. It undistorts/rotates the frame, updates block tracking based on phase, and returns pose data, the processed image, and block information for navigation or object trac...
def vision(cap, theta, phase, block, last_block): for i in range(6): cap.grab() ret, frame = cap.retrieve() fix_frame = rotate_image(undistort(frame), theta) h,w,_ = fix_frame.shape corners, ids, _ = cv2.aruco.detectMarkers(fix_frame, arucoDict, parameters = arucoParams) ...
def getEvents(): os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1' service = gCalRetrieval() return service def setupDayEvents(service): currentDay = datetime.datetime.utcnow() currentDay = currentDay - datetime.timedelta(days=3) currentDay = currentDay.isoformat() + "Z" nextDay = datetime.d...
The main task of the code is to process event data by organizing it into a daily schedule, generate a response using Gemini AI, extract relevant classes based on the current date, and return the processed event list through the `tryThis` function for further handling or output.
def main(): events = getEvents() eventDict = setupDayEvents(events) sched, todayDate = processDict(eventDict) response = runGemini(sched) eventsList = extractClasses(response, todayDate) return tryThis(eventsList)
def encode_first_order_residuals(wav_file, Fs, win_size, P, L_bounds): sig, Fs = librosa.load(wav_file, sr=Fs) sig = sig - np.mean(sig) frames = split_padded(sig, win_size) lpc_filters = [to_float16(lpc(frame, P)) for frame in frames] residuals = get_residuals(frames, lpc_filters) residuals_prep...
The code encodes a WAV file by processing audio signals through Linear Predictive Coding (LPC) analysis, extracting first- and second-order residuals, refining them with pitch-based filtering, quantizing the second-order residuals using specified bits, and returning the quantized data alongside LPC filters for compress...
def encode_wav(wav_file, Fs, win_size, P, L_bounds, voiced_thr, residual_bits): """Full encoder unit 1. load and frame signal 2. calculate lpc 3. get residuals 4. get second order residuals filtered by pitch 5. quantize second order residuals and cast other coefficients to smaller types""" r...
def encode_first_order_residuals(wav_file, Fs, win_size, P, L_bounds): sig, Fs = librosa.load(wav_file, sr=Fs) sig = sig - np.mean(sig) frames = split_padded(sig, win_size) lpc_filters = [to_float16(lpc(frame, P)) for frame in frames] residuals = get_residuals(frames, lpc_filters) residuals_prep...
This function encodes a WAV file using linear predictive coding (LPC), separating voiced and unvoiced residuals. It models unvoiced frames with Gaussian noise, quantizes second-order residuals, and converts LPC coefficients to smaller data types. Key steps include signal framing, LPC analysis, residual extraction, pitc...
def encode_wav_gaussian(wav_file, Fs, win_size, P, L_bounds, residual_bits, voiced_thr, unvoiced_thr=None): """Full encoder unit with unvoiced frames modeled by Gaussian noise 1. load and frame signal 2. calculate lpc 3. get residuals 4. get second order residuals filtered by pitch and modeled with ...
def load_control_signals(self, doc): print("Control signals:") control_signals = list(doc.get("control-signals").keys()) for i in range(0, len(control_signals)): value = pow(2, i) self.microcode_specification.control_signals[control_signals[i]] = value print(f...
The main task of the code is to load a YAML specification file into an object by parsing its content and distributing data to specialized methods for control signals, fetch sequences, operations, and end sequences, while handling potential YAML parsing errors.
def load(self): with open(self.file_name, 'r') as stream: try: print("Loading specification...\n") doc = yaml.safe_load(stream) self.load_control_signals(doc) self.load_fetch_sequence(doc) self.load_operations(doc) ...