dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def import_data(): os.chdir('../../data/MachineLearning') with open('Friday-WorkingHours-Afternoon-PortScan.pcap_ISCX.csv') as csvfile: data = pd.read_csv(csvfile, header= 0, sep=',') train_features, test_features , train_labels, test_labels = split(data) train_features, train_labels = ...
The code trains a Multi-Layer Perceptron (MLP) classifier using the Adam solver on training data, evaluates its performance on test data, computes accuracy, detection rate, and false acceptance rate (FAR), saves these metrics along with training time and dataset sizes, and returns test features, predictions, and solver...
def process(): train_features, train_labels, test_features,test_labels = import_data() #training the data t0 = time() solver='adam' clf = MLPClassifier(solver=solver, alpha=1e-5, hidden_layer_sizes=(5, 2), random_state=1) clf.fit(train_features,train_labels) tt = time()-t0 print("Cl...
def user_choice(): while True: inp = raw_input('Are you making the first move (y/n) :') if inp in ['y', 'Y']: print('Your moves are Xs') return 'y', 'n' elif inp in ['N', 'n']: print('Your moves are Xs') return 'n', 'y' else: ...
The code implements a tic-tac-toe game where a human and CPU take turns placing 'X' and 'O' on a 3x3 board. It initializes the board, handles user input, alternates moves based on player choice, updates the board display, and checks for win/loss conditions after each move. The game loop continues until a player wins or...
def game(): global board play = True board = ['', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '] human, cpu = user_choice() human_i='X' cpu_i='O' bboard() while play: if human == 'y': x = human_input(human_i) board[x] = human_i display_board() ...
def resizeImage(image, size=None, factor=None): ''' Resize image to specified size or scale by specified factor :param image: Image to resize :param size: Desired final size of image :param factor: Desired scale factor by which to modify the image :return: Resized image ''' if facto...
The function recursively blurs, downscale, and blends an image multiple times, then applies the DeepDream algorithm to amplify patterns perceived by an Inception model, returning the optimized image. It enhances neural network feature visualization by iteratively refining image details through recursive processing and ...
def recursiveOptimize(layer_tensor, image, num_repeats=4, rescale_factor=0.7, blend=0.2, num_iterations=10, step_size=3.0, tile_size=400): ''' Recursively blur and downscale the input image. Each downscaled image is run through the optimizeImage() function to amplify the patterns that the Inception model se...
def win_board(board): return len(calcular_madelinette_moves(board,-1))==0 def lose_board(board): return len(calcular_madelinette_moves(board,1))==0 def calcular_madelinette_moves(tablero,player=1)->list: available_moves=[] #Esta basado en las reglas, capaz sea mejor refactorizar pero por ahora #remi...
The main task of the code is to simulate a turn-based game using random moves until a win or loss condition is met. It copies the input board, alternates players, applies random valid moves, and returns 3 if the final state is a win, or 0 otherwise. The function evaluates game outcomes by iterating through possible mov...
def DEFAULT_POLICY(board): tablero=board.copy() player=1 while not win_board(tablero) and not lose_board(tablero): accion=random.choice(calcular_madelinette_moves(tablero,player)) tablero=cambiar_tablero(tablero,accion,player) player=-1*player if(win_board(tablero)): retu...
def tree_policy(nodo : MCST_node)->MCST_node: #Debo encontrar la manera de revisar si es terminal win or terminal lose while not nodo.is_terminal(): if not nodo.full_expanded(): return expand(nodo) else: nodo=best_child(nodo,cp) return nodo def default_policy(board)->...
The code performs a Monte Carlo Tree Search (MCTS) to determine the optimal move on a board. It runs simulations within a time limit, selecting nodes via the tree policy, simulating outcomes with the default policy, and backpropagating rewards. The process iterates until the time or simulation limit is reached, then re...
def monte_carlo_search(root,board)->tuple: simulations=0 time=simulations_limit root=MCST_node(board) while(time>0 or simulations<simulations_limit): tiempo_actual=time() node=tree_policy(root) reward=default_policy(node.board) backup(node,reward) simulations=simu...
def TREE_POLICY(nodo : Nodo)->Nodo: vl=nodo iter=0 while not vl.is_terminal(): #print("iteraciones tree policy: "+str(iter)) #print_not_expanded(vl) if not vl.is_expanded(): #print_not_expanded(vl) return vl.expand() else: #print_expanded(v...
(The code performs a Monte Carlo Tree Search (MCTS) using the UCT algorithm to find the optimal move on a given board. It iteratively selects nodes via the tree policy, simulates outcomes with the default policy, and updates scores through backup. The search limits simulations or time, returning the best action from th...
def uct_search(board,cp=2/sqrt(2),max_sim=50,max_time=5)->tuple: root=Nodo(board,None,cp) tiempo=0 simulations=0 while(tiempo<max_time and simulations<max_sim): t=time.time() vl=TREE_POLICY(root) reward=DEFAULT_POLICY(vl.board) BACKUP(vl,reward) tiempo=tiempo+(t...
def check_db() -> None: """Check local mac db file.""" try: print(f"[+] Last updated: {modified_date(Path(macaddress_db))}") update_db() except FileNotFoundError: rprint("[-][red] Database file not found[/red]") update_db() def update_db() -> None: """Update local mac db ...
The main task of the code is to parse command-line arguments for MAC address lookup, handle database updates, and process either a single MAC address or a file containing MAC addresses using an offline/online database. It ensures mutual exclusivity between MAC and file inputs, checks for database existence, and execute...
def main() -> None: """Run main program.""" parser = argparse.ArgumentParser( prog="macLookup", description="Look up MAC addresses using an offline/online database.", formatter_class=lambda prog: argparse.HelpFormatter(prog, max_help_position=35), ) # mutually exclusive group fo...
def get_best_split(X, y, node_indices): """ Returns the optimal feature and threshold value to split the node data Args: X (ndarray): Data matrix of shape(n_samples, n_features) y (array like): list or ndarray with n_samples containing the target variable ...
The function recursively builds a decision tree by splitting the dataset into two subgroups at each node. It prints the tree structure, identifies the best feature to split on, and stores splits in a list. Recursion stops when the maximum depth is reached, creating leaf nodes. The tree is constructed by recursively pro...
def build_tree_recursive(X, y, node_indices, branch_name, max_depth, current_depth): """ Build a tree using the recursive algorithm that split the dataset into 2 subgroups at each node. This function just prints the tree. Args: X (ndarray): Data matrix of shape(n_samples, n_featu...
def find_faces(picture, hog=False): if hog: return find_objects_hog(picture, face_detector_hog) else: return find_objects_cascade(picture, face_detector_haar) def get_landmarks(picture, bounding, predictor): return numpy.matrix([[p.x, p.y] for p in predictor(picture, bounding).parts()]) def ...
The code performs face swapping by detecting faces and landmarks in both input images, aligning the replace face to the source using procrustes transformation, warping the replace image, generating a mask, and blending the corrected colors to produce the swapped face. It returns the result along with landmarks and mask...
def face_swap(mat_picture, mat_replace, poisson = False): p_gray = cv2.cvtColor(mat_picture, cv2.COLOR_BGR2GRAY) r_gray = cv2.cvtColor(mat_replace, cv2.COLOR_BGR2GRAY) f_faces = find_faces(p_gray, HOG_DETECT) if len(f_faces) == 0: return (False, 0, 0, 0, 0) f = f_faces[0] f_landmarks = g...
def get_lots_params(): return { 'query': '', 'start': 0, 'count': 100, 'country': 'UA', 'language': 'russian', 'currency': 1, } def print_error(error): print(f'{Fore.RED}│') print(f'{Back.RED}{Fore.WHITE} ! {error} ') time.sleep(TIMEOUT * 5) def get_lot_link_tail(link): regexp = f'M%...
The code parses a list of URLs to extract market listing data, processes HTML responses to collect item details (e.g., float values, prices), filters valid entries, and writes them to a file. It handles errors, displays progress, and skips invalid listings.
def parse_lots(list): if list is None: return False for list_index, list_item in enumerate(list): params = get_lots_params() html = requests.get(list_item['url'] + '/render/', headers=HEADERS, params=params) if html.status_code == 200: json_object = json.loads(html.text) text = json_ob...
def get_total_count(): html = get_main_list_html(0, 1) if html: json_object = json.loads(html.text) return json_object['total_count'] else: return 0 def get_parsed_skins(start_from, count, filters): html = get_main_list_html(start_from, count) if html: json_object = json.loads(html.text) ...
This function retrieves a list of skins by paginating through results in chunks, applying specified filters. It loads data in batches, prints progress, handles delays between requests, and aggregates results into a single list. Error handling is included for robustness.
def get_skins_list(filters): page = 0 skins = [] chunk_count = 100 total_count = get_total_count() time.sleep(TIMEOUT * 2) try: while page * chunk_count < total_count: shift = 0 if page == 0 else 1 start_from = chunk_count * page + shift current_range = [chunk_count * page + 1, chunk...
def remove_old_lots(): if os.path.exists(FILE_STEAM): os.remove(FILE_STEAM) def get_filters(): if os.path.exists(FILE_FILTER): print(f'{Back.CYAN}{Fore.BLACK} » File "{FILE_FILTER}" found. Reading…{Back.BLACK}{Fore.CYAN}█▓▒░') file = open(FILE_FILTER, 'r') data = file.read() file.close() n...
The code's main task is to repeatedly fetch and process skin lots using specified filters, handling empty results by retrying after a delay. It removes old lots, retrieves skin data, parses valid entries, and displays status messages with colored text for feedback. The loop ensures continuous operation, restarting when...
def main(): remove_old_lots() print(f'{Back.GREEN}{Fore.BLACK} » Let´s rock!{Back.BLACK}{Fore.GREEN}█▓▒░') filters = get_filters() while True: skins = get_skins_list(filters) if skins: parse_lots(skins) else: print(f'{Back.RED}{Fore.WHITE} » Fail! Skins list is empty. Restarting…{Back....
def get(self, i): return 0 if i >= len(self.ints) else self.ints[i] def getArgs(self, n_args, modes): return [self.getArg(self.get(self.i+1 + i), modes[i]) for i in range(n_args)] def getOut(self, out, mode): if mode == 0: return out if mode == 2: return out + self.relative_base def set(...
This code executes a series of operations based on opcode values from a program, handling arithmetic, input/output, conditional jumps, comparisons, and relative base adjustments. It processes each instruction by decoding opcodes, retrieving arguments with specified modes, modifying memory, and updating the instruction ...
def run(self): while self.get(self.i) != 99: self.paused = False opcode = self.get(self.i) modes = [int(s) for s in ('0000' + str(opcode))[-3::-1]] opcode = int(str(opcode)[-1]) # add & mult if opcode == 1 or opcode == 2: ar...
def _adapt_input(**kwargs): start_from = kwargs.get('start_from', None) end_before = kwargs.get('end_before', None) start_from_timestamp = kwargs.get('start_from_timestamp', None) end_before_timestamp = kwargs.get('end_before_timestamp', None) if start_from_timestamp is None and start_from: ...
This function loads cryptocurrency price data from a CSV file, filters it by a specified time range, selects specific price types (e.g., 'close'), handles missing values if requested, and returns a structured pandas DataFrame with timestamps converted to datetime objects and unnecessary columns removed.
def load_data(start_from, end_before, file_path, fill_na=False, price='close', interval=None, **kwargs) -> pd.DataFrame: start_from_timestamp, end_before_timestamp = _adapt_input(start_from=start_from, end_before=end_before, **kwargs) prices = ['open', 'close', 'high', 'low'] select_prices = price.split(','...
def string_to_sign(algorithm,date,scope,canonical_req): global credential_scope date = date[:8] region = 'cn-beijing' scope = scope hashed_canon_req = Util.sha256(canonical_req) credential_scope = '/'.join([date, region, scope, 'request']) signing_str = '\n'.join([algorithm, timestamp...
The code generates an authenticated API request using HMAC-SHA256 signing, constructs headers with the computed signature, and sends a POST request to create a document via the i18n_openapi service, returning the JSON response.
def api(): string_to_sign('HMAC-SHA256', timestamp, 'i18n_openapi', canonical_request()) signing_key() signature() a = authHeader() headers ={ "Authorization": authHeader() } print(authHeader()) params = { "Action":"DocumentCreate", "Version":"2021-05-21" } re...
def find_none_blank_tile_indexes(self, direction_indexes): blank_tile_indexes = self.initial_node.index_of_blank_tile none_blank_tile_i = blank_tile_indexes.i + direction_indexes.i none_blank_tile_j = blank_tile_indexes.j + direction_indexes.j return Indexes(none_blank_tile_i, none_blank...
This function generates a new puzzle state by swapping non-blank tiles in specified directions, checks if the state has been reached before, and returns a new Node with the updated state and incremented depth if valid. If the state is already reached or an error occurs, it returns nothing.
def swap_tile_and_return_child(self, direction_indexes): none_blank_tile_indexes = self.find_none_blank_tile_indexes( direction_indexes) try: new_state = self.get_new_state(none_blank_tile_indexes) if self.is_state_in_reached_state(new_state): return ...
def is_limit_reached(self): new_node_depth = self.initial_node.depth + 1 if self.depth_limit != 0 and new_node_depth > self.depth_limit: return True else: return False def swap_up_tile_and_get_child(self): return self.swap_tile_and_return_child(Indexes(1, 0)) def...
This function expands the initial node by generating child nodes through tile swaps in four directions. It checks if any child is the goal state, updates the expanded node count, and ensures the search limit isn't exceeded. It returns whether a goal state was found during expansion.
def expand_initial_node_and_check_for_goal_and_reached_and_limit(self): is_goal = False if self.is_limit_reached(): return is_goal self.count_of_expanded_nodes += 1 childs = [] childs.append(self.swap_up_tile_and_get_child()) childs.append(self.swap_down_tile...
def calc_percent(self): now = dt_util.utcnow() now_ts = now.timestamp() today = self._relevant_events(now) # Figure out where we are in time so we know which half of the # parabola to calculate. We're generating a different # sunset-sunrise parabola for before and after s...
This code initializes a component to adjust color temperature and related settings based on sunrise/sunset times or manual inputs. It sets up event triggers for time-based updates using either manual times or calculated sunrise/sunset events with offsets. The class calculates color values (RGB, XY, HS) and schedules pe...
def __init__( self, hass, min_colortemp, max_colortemp, sunrise_offset, sunset_offset, sunrise_time, sunset_time, latitude, longitude, elevation, interval, transition, ): self.hass = hass self._mi...
def get_movie_urls(self): movie_urls_list = self.get_movie_dim(self.start_url) for i in movie_urls_list: long_url = "https://www.boxofficemojo.com" + i short_url = long_url.split("?")[0] self.movie_urls.append(short_url) return self.movie_urls def get_dom(self...
The code scrapes movie data from IMDb by extracting IDs, names, genres, and abstracts from URLs, then writes this information into a JSON file named 'data_v1.json'. It processes multiple movie URLs, retrieves structured details using XPath, and stores them in a list of dictionaries under 'self.movies_info' for later us...
def get_movie_info(self): movie_urls = self.get_movie_urls() for movie_url in movie_urls: dom = self.get_dom(movie_url) id = movie_url.split("/")[4] ref_id = dom.xpath('//div[@id="title-summary-refiner"]/a/@href')[0].split("/")[2] dom_ref_id = self.get_dom...
def flatten(self, df): return df.to_numpy().flatten() def get_kart_numbers(self): return pd.read_excel(self.results_link, sheet_name="Karts", index_col=0) def get_mean_lap(self, for_drivers=True): return self.get_race_finish_times() / self.get_lap_count(for_drivers=True) def get_filtered_lap_mea...
The code creates a structured DataFrame to compile race results, aggregating kart numbers, drivers, lap times, and positions across multiple races. It initializes columns with repeated race numbers, flattens nested data from methods like get_mean_lap(), and duplicates driver names for each race. The table consolidates ...
def make_results_table(self): df = pd.DataFrame( columns=[ "Race Number", "Kart Number", "Driver", "Mean Lap", "Filtered Mean Lap", "Fastest Lap", "Start Position", ] )...
def build_tree(train, max_depth, min_size): print('building tree...') root = get_split(train) split(root, max_depth, min_size, 1) return root def print_tree(node, depth=0): if isinstance(node, dict): print('%s[a%d < %.3f]' % ((depth*' ', (node['index']+1), node['value']))) print_tree...
The code trains a decision tree classifier using the provided training data, builds the tree with specified maximum depth and minimum size constraints, prints the tree structure, tests the model on the test data by predicting each row, and returns the list of predictions.
def decision_tree(train, test, max_depth, min_size): tree = build_tree(train, max_depth, min_size) print_tree(tree) print('testing...') predictions = list() for row in test: prediction = predict(tree, row) predictions.append(prediction) return(predictions)
def get_hidden(self,x): # extract the intermediate features computed at the hidden layers (after applying activation function) z = sigmoid(np.dot(x, self.weight_1) + self.bias_1) return z def predict(self,x): # generate the predicted probability of different classes ...
This function trains a neural network using full-batch gradient descent with backpropagation. It updates weights and biases based on training data, evaluates validation accuracy, and implements early stopping by halting training if validation accuracy fails to improve for a set number of epochs. The model uses a hidden...
def fit(self,train_x,train_y, valid_x, valid_y): #train_x shape: 1000x64 lr = 5e-3 # learning rate count = 0 # counter for recording the number of epochs without improvement best_valid_acc = 0 epochs = 100 while count<=epochs: # training...
def compute_node_entropy(label): # compute the entropy of a tree node (add 1e-15 inside the log2 when computing the entropy to prevent numerical issue) label = np.array(label) classes = np.unique(label) node_entropy = 0 for i in classes: p_i = len(label[np.where(label==i)])/len(label) ...
The function generates a decision tree recursively by splitting data based on features with the lowest split entropy. If node entropy falls below a threshold, it creates a leaf node labeled with the majority class. Otherwise, it selects the optimal feature, partitions data into left/right subsets, and recursively build...
def generate_tree(data,label,min_entropy): cur_node = Tree_node() # initialize the current tree node left_data = [] right_data = [] left_label = [] right_label = [] node_entropy = compute_node_entropy(label) # compute the node entrop...
def plot_worldpoints(worldpoints, dlc_metadata, pickle_metadata, i_frame, videos_parent='/home/levlab/Public/mouse_SR_videos_to_analyze'): bodyparts = dlc_metadata['data']['DLC-model-config file']['all_joints_names'] fig = plt.figure() ax = fig.add_subplot(projection='3d') dotsize = 6 video_root...
This function checks 3D point reprojection accuracy across multiple cameras by projecting worldpoints onto each camera's image plane, calculating reprojection errors, and visualizing results through 3D plots, epipolar lines, and overlaid points on original images to validate triangulation and camera calibration consist...
def check_3d_reprojection(worldpoints, frame_pts, cal_data, frame_conf, pickle_metadata, dlc_metadata, frame_num, videos_parent): num_cams = len(frame_pts) #3d plot of worldpoints #todo: plot worldpoints in 3d. Is the problem with the triangulation or reprojection? plot_worldpoints(worldpoints, dlc_me...
def input_props(content_type): props = { "Hidden": True, "MacroExecutionMode": 0, "ReadOnly": True, "Overwrite": True, "OpenNewView": True, "StartPresentation": False, "RepairPackage": False, } extension = mimetypes.guess_extension(content_type) if...
This code converts a document using LibreOffice by loading input data (URL or stream), configuring properties, retrying connection if failed, storing the converted document to a memory stream or temporary file, and returning the resulting content as a BytesIO object or file.
def convert(self, format, url=None, data=None, content_type=None, pages=None, size=None): # Ulitmately, this is the function called by convert() in_props = input_props(content_type) if data: in_stream, url = self.input_stream(data) in_props += (property("...
def normalize_vector(v): norm = math.sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]) return np.array([v[0]/norm, v[1]/norm, v[2]/norm]) def check_inside(origin, shape, mask): r_origin = point_to_int(origin) if r_origin[0] < 0 or r_origin[0] >= shape[0]: return False if r_origin[1] < 0 or r_orig...
The main task of the code is to generate 3D artifacts in a mask by creating random line-like and spherical structures within a 3D image. It generates a specified number of line artifacts by drawing random lines through the image, ensuring they stay within bounds and masks, and fills the mask with these lines. It also c...
def generate_3d_artifact(img, masks, nb_artefacts=3, len_artefacts=500, size_artefacts=10): coil_nb = np.random.randint(nb_artefacts, size=1)[0] line_nb = nb_artefacts - coil_nb mask = np.zeros(img.shape, dtype=bool) radius = size_artefacts for i in range(line_nb): origin = np.array([ra...
def check_connection(): print ('Scanning connection buttons') buttons = ['retry.PNG','initiate_link.PNG'] for button in buttons: if click_template(button): check_connection() time.sleep(10) def get_screen(screen_padding= (0,0,x_frame,y_frame)): box = (x_pad + screen_paddi...
The code automates entering an "auto-duel" mode in a game by detecting a specific on-screen element ("bubble_point") via template matching, clicking on it (excluding certain areas), handling dialog prompts, and initiating the auto-duel function. It repeats this process four times, swiping right after each attempt to cl...
def enter_auto_duel(): check_connection() for i in range(4): img = get_screen() #player's monster zones screen_padding=(660, 470, 970 , 600) img_gray = cv2.cvtColor(np.array(img), cv2.COLOR_BGR2GRAY) template = cv2.imread('templates/bubble_point.PNG',0) print('Checking bubble') ...
def check_template(template_path): current_screen = get_screen() img = cv2.cvtColor(np.array(current_screen), cv2.COLOR_BGR2GRAY) template = cv2.imread('templates/' + template_path,0) w, h = template.shape[::-1] threshold = 0.75 if template_path == 'npc_diamond.png': threshold = 0.5 ...
This code automates a turn-based duel in a game by detecting game states via image templates, handling phases like draw, main, and battle. It uses OpenCV to identify monsters, performs attacks, clicks buttons, and manages turn progression. If the opponent's turn is detected, it resets the cursor; otherwise, it attempts...
def timmy_duel(): if check_template('opponent.png'): reset_cursor() if check_template('you.png'): #draw_phase print('in duel turn, checking phase') #main_phase if check_template('phase_draw.png'): print('enter draw phase') draw() if check_t...
def reset_cursor(): click(950,610) def click_template(template_path): current_screen = get_screen() img = cv2.cvtColor(np.array(current_screen), cv2.COLOR_BGR2GRAY) img2 = img.copy() threshold = 0.7 template = cv2.imread('templates/' + template_path,0) w, h = template.shape[::-1] img = i...
The main task of the code is to navigate through a game phase by resetting the cursor, checking for an "OK" button click to exit if on the last winning turn, then waiting to click a "Phase" button followed by an "End" button to proceed to the next phase or conclude the current one.
def change_phase(): reset_cursor() if click_template('ok_btn.png'): #exit on last winning turn return wait_to_click('phase_btn.png',1) wait_to_click('end.png', 1)
def click(x,y): if not ( 480 <= x <= 2080 and 70 <= y <= 1000): # check if click is within window frame logging.warn("out of bound click blocked! at " + str(x) +"," + str(y)) return pyautogui.click(x,y) def wait_to_click(template, duration): t_end = time.time() + duration while time.time...
The main task of the code is to automate a sequence of actions (screen clicks and image recognition checks) for a specified duration to activate and confirm an effect in a game or application. It repeatedly clicks a specific coordinate, checks for an activation image, confirms with two additional clicks, or triggers an...
def cast_st(duration): print('casting st') t_end = time.time() + duration while time.time() < t_end: click(1256,967) #select if wait_to_click('activate_effect.png',0.5): wait_to_click('confirm_rug.png', 0.8) wait_to_click('confirm_rug.png', 0.8) return T...
def check_template(template_path): current_screen = get_screen() img = cv2.cvtColor(np.array(current_screen), cv2.COLOR_BGR2GRAY) template = cv2.imread('templates/' + template_path,0) w, h = template.shape[::-1] threshold = 0.75 if template_path == 'npc_diamond.png': threshold = 0.5 ...
The code automates a turn-based duel by detecting the player's and opponent's turns using image templates. It performs actions like dodging, casting spells, and advancing phases during the player's turn, while handling opponent actions and phase transitions. The script checks for specific game states, executes correspo...
def timmy_duel(): if check_template('opponent.png'): #opponent's turn if wait_to_click('dod.png', 0.5): wait_to_click('activate_dod.png', 3) wait_to_click('ok_btn.png', 0.3) if wait_to_click('cybernetic.png', 0.5): wait_to_click('activate_dod.png', 3) ...
def _extract_property_details(listing: dict, detail=None): try: if detail == 'coords': return (float(listing[rmv_constants.RmvPropDetails.geo_lat.name]), float(listing[rmv_constants.RmvPropDetails.geo_long.name])) elif detail == 'desc': ...
This code calculates a weighted score for a property listing based on matches with user preferences: area proximity (10x weight), category alignment (0.5x), and keyword presence (1x). It extracts property data, checks matches against user inputs, sums results, and returns the weighted total. Exceptions are caught to re...
def score(self, listing: dict, user_desired_areas: [str], user_desired_cats: [general_constants.NhoodCategorisation], user_keywords: [general_constants.CheckboxFeatures]): property_coords = self._extract_property_details(listing, 'coords') try: description = sel...
def generate_population(parameters: dict): population = [] size: int = parameters["population_size"] dimensions: int = parameters["dimensions"] for i in range(size): individual: list = [] for j in range(0, dimensions): gene = build_real_gene(parameters) individua...
The code implements a real-valued genetic algorithm (GA) to optimize a problem by evolving a population over multiple generations. It tracks the best individual and its fitness, updates progress, and returns the optimal solution. The GA iteratively generates new populations, selects elites, and applies genetic operator...
def real_ga(parameters, debug=False): population: list = generate_population(parameters) generations: list = parameters["generations"] best_individual: list = [] best_fitness: float = 0.0 best_f: float = 0.0 i = 1 while True: if i == generations + 1: break if debug: print(f'\...
def replot(): """Re-plots and updates the current canvas with the new values.""" global fig, ax time_signal = get_time_signal(current_values) ax[0].cla() ax[0].plot(time_signal, color='k', scalex=True) ax[0].set_xlim(0, len(time_signal)) ax[1].cla() ax[1].imshow(current_values, vmin=v...
The function `check_state` modifies a plot's data or visualization parameters based on the input `state` value, then updates the graph. It handles actions like resetting to original data, reducing resolution/rows/columns, or adjusting the `vmin` threshold, with error checks for valid ranges. Each state triggers `replot...
def check_state(state): """Checks the current state and updates the graph accordingly.""" global current_values, static_data, current_data, vmin if state == 0: print('Returning to original plot') current_data = copy.deepcopy(static_data) current_values = np.copy(current_data.data) ...
def checkWalls(currentPosition, maze, WALL): c1 = (currentPosition[0] + 1, currentPosition[1]) c2 = (currentPosition[0] - 1, currentPosition[1]) c3 = (currentPosition[0], currentPosition[1] + 1) c4 = (currentPosition[0], currentPosition[1] - 1) c = [c1, c2, c3, c4] for cell in c: try: ...
The main task of the code is to find a path through a maze using an adaptive A* algorithm that dynamically updates walls and explores the maze. It iteratively computes paths, tracks explored cells, and adjusts to obstacles by expanding search areas, returning the walls encountered, explored nodes, and the solution path...
def MaxRepeatAdaptive(maze): SOLUTION = Node(str(start)) parentNode = SOLUTION WALL = set() currentPosition = start checkWalls(currentPosition, maze, WALL) EXPLORED = [] EXPAND = set() iterations = 0 H = np.array([[manhattanDistance((row,col), goal) for col in range(len(maze[0]))] fo...
def randomBetweenAB(min, max): # I've read online that something like: # Math.floor(Math.random() * (myMax - myMin +1)) + myMin; # should work? Much like the randomNumber() function below. return int(rnd() % (max - min + 1) + min) def CreateTunnel(self, x, y, x1, y1, join='xy'): if x == x1 and y...
This function connects two dungeon rooms (rooma and roomb) by generating tunnels between them. It sorts rooms by position, checks for horizontal/vertical overlaps, and creates tunnels in overlapping regions. If no overlap exists, it uses the 'join' parameter to connect via top/bottom edges, ensuring proper alignment an...
def DungeonConnections(self, rooma, roomb, join='xy'): # Store room a and b in a list. sorted_room = [rooma, roomb] # Use a lambda to sort the rooms. This essentially sets the # lesser of the two rooms as the first room. sorted_room.sort(key=lambda x_y: x_y[0]) rooma_x ...
def randomNumber(max): return int((rnd() % max) + 1) def DungeonBuildRoomCrossShaped(self): vertical = 0 horizontal = 0 x = 0 y = 0 random_offset = 2 + randomNumber(2) vertical = randomBetweenAB(self.min_size, self.max_size) horizontal = ra...
The main task of the code is to generate a dungeon layout by creating rooms of varying shapes, connecting them with tunnels, and populating the grid with floors, walls, and doors. It initializes an empty grid, generates rooms while avoiding overlaps, connects adjacent rooms, draws tunnels with doors, and sets walls by ...
def DungeonGenerate(self): # Start by building a dungeon of empty tiles. for x in range(self.height): self.dungeon.append(['empty'] * self.width) # Double check we're setting the rooms list AND tunnels to empty - it's done in the # constructor but may have been changed in other functions. ...
def remove_prefix(text, prefix): return text[len(prefix):] if text.startswith(prefix) else text def getOppOfChar(charToCheck): if (charToCheck[-1:] == "1"): oppChar = charToCheck[:-1] + "0" else: oppChar = charToCheck[:-1] + "1" return oppChar def checkNumOfTimesKeyOneLessInSegment(segme...
This function processes a decompression segment by checking key availability in a dictionary, determining if a backup is needed, and executing decompression logic (either real or fake) based on conditions like key counts and character matches. It resets global state variables after processing to prepare for the next se...
def decomp_processFinishedSegment(): global my_dict, myDictOneLess, sorted_dict, numOfChars, segmentString, remainder, largestKey, numOfLargestKey, getCurrentKey, decompAddAsRemainder global justStarted, numOfKeysFound, needBackup, backupSegmentString, alreadyMadeBackup, decompLargeChar, unusedCharInBackup, get...
def getOppOfChar(charToCheck): if (charToCheck[-1:] == "1"): oppChar = charToCheck[:-1] + "0" else: oppChar = charToCheck[:-1] + "1" return oppChar def checkUnusedChar(sorted_dict): for k, v in sorted_dict.items(): valueToCheck = k[:-1] if (k[-1] == "1"): valu...
This function processes a completed data segment by sorting a dictionary by frequency, identifying the most frequent key and its counterpart, checking if additional bytes are needed for compression, and resetting state variables for subsequent processing. It updates global parameters for decompression logic, manages di...
def processFinishedSegment(): global my_dict, myDictOneLess, sorted_dict, numOfChars, remainder, largestKey, stillNeedBytes global numOfLargestKey, unusedKeyOneLess, oppLargeKeyValue, oppLargeKey, writeFakeFlag, getDecompLargeChar sorted_dict = collections.OrderedDict(sorted(my_dict.items(), key=operator.i...
def realCompSixteen(): global segmentString, remainder, largestKey, unusedKeyOneLess, goBeforeNextSection global bigCharSixteen, unusedKeyOneLess, tempLargerUnusedChar, tempCharFifteen #1. Get the unused char #2. First eight digits are the bigChar16 #3. Next eight digits are from the remainder ...
This function determines whether to compress or decompress data based on `typeCompress` and `globalProcessType`. If compressing, it executes methods like `realCompSixteen`, `fakeComp7seq`, or `fakeComp128`. If decompressing, it handles scenarios like `decompReal`, `fakeKey128_1/0`, or `fakeKey7seq`, adjusting `segmentS...
def getValuesForComp(): global segmentString, numOfLargestKey, largestKey global sorted_dict, unusedKeyOneLess, remainder, myDictOneLess, unusedKeyOneLess, bigCharSixteen global numOfSixteenDetected, numOfCheckFakeKey, injectAfterThisChar, dirtyFix_afterFirstSeg if (typeCompress == True): if (g...
def isDecompSegmentFinished(): #This will be less than OneLessFull UNLESS the oppLarge isn't defined if (decompIsDictOneLessFull() is True): return True else: return False def decomp_processFinishedSegment(): global my_dict, myDictOneLess, sorted_dict, numOfChars, segmentString, remainde...
This function processes the remaining data in chunks of size 'bitSize', updating a dictionary and appending segments to 'segmentString'. It iteratively checks if a decomposition segment is complete, then slices and stores the remainder in chunks, adjusting the remaining data each iteration until all bits are processed.
def decomp_processRemainder(): global remainder, segmentString #Process Remainder First Section - add to dict if (len(remainder) >= bitSize): remainingRemainderLength = len(remainder) while (remainingRemainderLength >= bitSize): if (isDecompSegmentFinished() is True): ...
def isSegmentFinished(): if (isDictOneLessFull() is True): return True else: return False def processFinishedSegment(): global my_dict, myDictOneLess, sorted_dict, numOfChars, remainder, largestKey, stillNeedBytes global numOfLargestKey, unusedKeyOneLess, oppLargeKeyValue, oppLargeKey, w...
The function processes the 'remainder' data in chunks of 'bitSize', adding each chunk to a dictionary and appending it to 'segmentString'. It iteratively reduces the remainder by slicing off processed chunks, stopping when the remainder is smaller than 'bitSize'. The loop checks if segments are finished, processes them...
def processRemainder(): global remainder, segmentString #Process Remainder First Section - add to dict if (len(remainder) >= bitSize): remainingRemainderLength = len(remainder) while (remainingRemainderLength >= bitSize): if (isSegmentFinished() is True): processF...
def isSegmentFinished(): if (isDictOneLessFull() is True): return True else: return False def processFinishedSegment(): global my_dict, myDictOneLess, sorted_dict, numOfChars, remainder, largestKey, stillNeedBytes global numOfLargestKey, unusedKeyOneLess, oppLargeKeyValue, oppLargeKey, w...
The function processes a binary string in chunks of a fixed size (`bitSize`), appending any remaining data to a global `remainder` variable. It iteratively segments the input, checks if a segment is complete, and either stores the segment or defers processing. If the remaining data is insufficient for a full segment, i...
def processBinary(binCode): global remainder, segmentString #first, add remainder to beginning binCode = remainder + binCode remainder = "" remainingBinLength = len(binCode) while (remainingBinLength > 0): if (remainingBinLength < bitSize): remainder = binCode b...
def checkUnusedChar(sorted_dict): for k, v in sorted_dict.items(): valueToCheck = k[:-1] if (k[-1] == "1"): valueToCheck = valueToCheck + "0" else: valueToCheck = valueToCheck + "1" if (str(sorted_dict.get(str(valueToCheck))) == "None"): return val...
This function processes a completed data segment by sorting the dictionary, identifying the largest key, checking for unused characters, determining if additional bytes are needed for compression, and resetting variables for the next segment. It handles compression state management, updates global variables for diction...
def processFinishedSegment(): global my_dict, myDictOneLess, sorted_dict, numOfChars, remainder, largestKey, stillNeedBytes, unusedKeyOneLessList, numOfLargestKey, segmentString global unusedKeyOneLess, getDecompLargeChar, checkedFirstInDict, checkedSecondInDict, checkedThirdInDict, checkedFourthInDict sor...
def decomp_processRemainder(): global remainder, segmentString #Process Remainder First Section - add to dict if (len(remainder) >= bitSize): remainingRemainderLength = len(remainder) while (remainingRemainderLength >= bitSize): if (isDecompSegmentFinished() is True): ...
This function processes binary data for decompression by managing leftover bits (remainder) and segment strings. It initializes decompression state, extracts keys from the binary input, and processes chunks of bits (bitSize) to reconstruct characters. It checks if current bits match the key, appending valid bits to dec...
def decomp_processBinary(binCode): global remainder, segmentString, justStarted, decompLargeChar, getCurrentKey, decompAddAsRemainder, isValidBit if (justStarted == 1): #Determine whether valid if (len(segmentString) != 0): remainder = segmentString + remainder segmentSt...
def getFileSize(filePath): return str(os.path.getsize(filePath)) def hex2bin(hexCode): binCode = bin(int(hexCode, 16))[2:].zfill(len(hexCode) * 4) binCode = binCode[binCode.find('b')+1:] return binCode def getValuesForComp(): global segmentString, numOfLargestKey, largestKey, goBeforeNextSection, di...
The code compresses a file using a custom algorithm by reading 16-byte chunks, converting them to binary, and processing segments. It handles remainders, alerts for large uncompressed data blocks, and compares original vs. compressed sizes. The goal is to reduce file size, with efficiency feedback provided.
def compressMain(arg2): global remainder, stillNeedBytes, segmentString, inputFileSize, alertedForUncompressedDataBlock #open file here print("Now compressing: " + arg2) inputFileSize = getFileSize(arg2) with open(arg2, 'rb') as f: #Read file as hex 16 bytes at a time entry = (str(b...
def isSegmentFinished(tempRemainder): global segmentString, remainder, my_dict, myDictOneLess, numOfSixteenDetected, lastCharAfter127 global numOfCheckFakeKey, searchingForFakeCharOr128, checkFakeKey, globalProcessType, theBitsFrom7seq, getOneMoreBit global startedDecomp, firstChar, typeCompress, injectAfte...
This function processes the 'remainder' string in chunks of 'bitSize', checking if each segment is complete. If so, it processes finished segments, updates the 'segmentString', and manages the dictionary by either adding new characters or starting decompression. It adjusts the 'remainder' by removing processed chunks a...
def processRemainder(): global remainder, segmentString, startedDecomp, firstChar #Process remainder - add to dict if (len(remainder) >= bitSize): remainingRemainderLength = len(remainder) while (remainingRemainderLength >= bitSize): if (isSegmentFinished(remainder) is True): ...
def isSegmentFinished(tempRemainder): global segmentString, remainder, my_dict, myDictOneLess, numOfSixteenDetected, lastCharAfter127 global numOfCheckFakeKey, searchingForFakeCharOr128, checkFakeKey, globalProcessType, theBitsFrom7seq, getOneMoreBit global startedDecomp, firstChar, typeCompress, injectAfte...
This function processes a binary string in fixed-size segments, appending a global remainder to the input. It iterates through the binary data, checking if each segment is complete. If a segment is finished, it processes it and resets variables; otherwise, it stores the segment in a dictionary or accumulates it. The fu...
def processBinary(binCode): global remainder, segmentString, startedDecomp, firstChar #Add remainder to beginning binCode = remainder + binCode remainder = "" remainingBinLength = len(binCode) while (remainingBinLength > 0): if (remainingBinLength < bitSize): remainder = bi...
def hex2binSmall(hexCode): binCode = bin(int(hexCode, 16))[2:].zfill(len(hexCode) * 4) binCode = binCode[binCode.find('b')+1:] while (len(binCode)%8 != 0): binCode = "0" + binCode return binCode def hex2bin(hexCode): binCode = bin(int(hexCode, 16))[2:].zfill(len(hexCode) * 4) binCode = b...
The main task of the code is to decompress a binary file by reading 16-byte chunks, converting them to hexadecimal strings, processing them into binary data, and handling decompression segments. It processes each segment, checks for completion, and manages leftover data at the end of the file, ensuring full decompressi...
def decompressMain(arg2): global remainder, stillNeedBytes, justStarted, binaryString, segmentString print("Now decompressing: " + arg2) lastEntryRead = "" with open(arg2, 'rb') as f: #Read file as hex 16 bytes at a time entry = (str(binascii.hexlify(f.read(16))))[2:-1] while e...
def getFileSize(filePath): return str(os.path.getsize(filePath)) def hex2bin(hexCode): binCode = bin(int(hexCode, 16))[2:].zfill(len(hexCode) * 4) binCode = binCode[binCode.find('b')+1:] return binCode def getValuesForComp(): global segmentString, numOfLargestKey, largestKey global sorted_dict, ...
This function compresses a file using a custom algorithm (UZ1) by reading 16-byte chunks, converting them to binary, and processing them in segments. It handles remainders, detects large uncompressed data blocks, and compares the compressed size to the original, outputting the result with size savings or growth.
def compressMain(arg2): global remainder, stillNeedBytes, segmentString, inputFileSize, alertedForUncompressedDataBlock, typeCompress typeCompress = True print("Now compressing: " + arg2) inputFileSize = getFileSize(arg2) with open(arg2, 'rb') as f: #Read file as hex 16 bytes at a time ...
def getFileSize(filePath): return str(os.path.getsize(filePath)) def hex2bin(hexCode): binCode = bin(int(hexCode, 16))[2:].zfill(len(hexCode) * 4) binCode = binCode[binCode.find('b')+1:] return binCode def processRemainder(): global remainder, segmentString, startedDecomp, firstChar #Process re...
This code decompresses a file by reading it in 16-byte chunks, converting each chunk to binary, processing remainder data, and handling leftover bytes. It uses global variables to track decompression state, processes binary data segment-by-segment, and ensures all data is handled even at EOF. The main task is decompres...
def new_decompressMain(arg2): global segmentString, remainder, stillNeedBytes, inputFileSize global alertedForUncompressedDataBlock, startedDecomp, typeCompress startedDecomp = 1 typeCompress = False print("Now decompressing: " + arg2) inputFileSize = getFileSize(arg2) with open(arg2, 'rb'...
def _events(self): # catch all events here for event in pygame.event.get(): if event.type == pygame.QUIT: self._quit() if event.type == pg.KEYDOWN: if event.key == pg.K_ESCAPE: self._quit() if event.key == pg.K_L...
The code defines a game loop that runs while `self.playing` is True. It controls the frame rate using `self.clock.tick(FPS)`, processes events, updates game state, and renders the display in each iteration, ensuring consistent performance and responsiveness.
def run (self): self.playing = True while self.playing: self.dt = self.clock.tick(FPS)/1000 self._events() self._update() self._draw()
def learn_pr_roc(data): global learned_pr learned_pr = pd.DataFrame(columns = learned_pr.columns) """ P(wi|x) """ for i in range(0, data.shape[0]): likeli_0 = MultivariateNormal(data.iloc[i,0:2].values, mean_all[0], var_all[0]) likeli_1 = MultivariateNormal(data.iloc[i,0:2].values, me...
This function generates ROC curves for classification models. When 'risk' is False, it calculates and plots a standard ROC curve using thresholds on the provided data. When 'risk' is True, it iterates through multiple risk factors, computes ROC points for each, and plots them with distinct hues. The function handles da...
def drawROC(data, st, pi, risk = False): thresholds = np.linspace(0,1, num = 100) if(not risk): learn_pr_roc(data) roc_points = pd.DataFrame(columns = ['FPR', 'TPR']) for threshold in thresholds: roc_pt = classify(data, threshold, True) roc_points = roc_p...
def create_db(): global conn global cursor conn = sqlite3.connect("database/programlist.db") cursor = conn.cursor() def get_data_in_array(): global ALL_PROGRAM try: ALL_PROGRAM = cursor.execute("SELECT * FROM program_list").fetchall() except sqlite3.OperationalError: say.say(...
The main task of the code is to initialize a database, retrieve data, locate programs with a specified name, allow user selection of a specific program from matching results, and fetch details of the chosen program if a valid selection is made. The function orchestrates data setup, filtering, user interaction, and prog...
def start_program(program_name): create_db() get_data_in_array() programs_with_same_name = get_requested_program_loc(program_name) program_requested, programs_with_same_name = specify_program( programs_with_same_name) if program_requested != 0: getting_specified_program(program_reque...
def read_params(params): P.all_wheels_on_track = params['all_wheels_on_track'] P.x = params['x'] P.y = params['y'] P.distance_from_center = params['distance_from_center'] P.is_left_of_center = params['is_left_of_center'] P.heading = params['heading'] P.progress = params['progress'] P.ste...
This function calculates a reward for a racing car based on proximity to an optimal racing line, progress, and track adherence. It adjusts multipliers depending on the stage, penalizes off-track or wrong-direction movement, and incentivizes efficient lap completion. The reward encourages staying on the predefined racin...
def reward_function(params): if SETTINGS.STAGE == 2: SETTINGS.DISTANCE_MULTIPLIER = 1 SETTINGS.STEERING_MULTIPLIER = 0.5 SETTINGS.SPEED_MULTIPLIER = 1 SETTINGS.PROGRESS_MULTIPLIER = 0.5 read_params(params) #################### RACING LINE ###################### # Optimal rac...
def getEnvironmentVariable(): # get environment variable with open("env.txt", 'r') as f: [env_hasPromptLogin, env_aws_id, env_username, env_password, env_prompt_email, env_prompt_password, env_race_id, env_modelname] = f.read().splitlines() global hasPromptLogin hasPromptLogin = env...
The main task of the code is to automate AWS login and model submission to a "summit race" via a browser. It initializes a browser, logs into AWS (with parameters commented out), submits a model once, and then repeatedly submits it for 12 hours using `submit_to_race_multiple`. The code focuses on automated, repeated mo...
def main(): getEnvironmentVariable() # open browser browser = newBrowser() # login to aws # awsLogin(browser, aws_id, username, password) awsLogin(browser) # Submit the model to the summit race once # submit_to_race(browser, aws_id, race_id, modelname=modelname) # Submit the model...
def to_delete(retention_policy, elements, now=None): """ Determine what should be removed from `elements` so that `retention_policy` is honoured. :param retention_policy: dictionary representing the retention_policy. keys should be timdeltas, values integers. :type retention_policy: dict :p...
The code generates a table displaying elements slated for deletion based on a retention policy, including their timestamps, slot durations, and deletion markers. It processes elements to identify deletions, calculates time slots, and formats the data into a structured table with colored rows for clarity, using the curr...
def table_info(elements, now, retention_policy): """Print a table showing the elements that should be deleted alongside the periods they pertain to. """ elements = sorted(elements, key=lambda x: x[0], reverse=True) elements_to_delete = { el[1] for el in to_delete(retention_policy, elements,...
def get_profiles_from_simulation(model_path: str, reactor_type: str, times: List[float], composition: Dict[str, float], T: float, P: float, ...
The main task of the code is to generate flux diagrams (reaction pathway diagrams) for specified species at given times using a Cantera model. It simulates reactor conditions, computes reaction rates, and visualizes flux pathways, with options to customize reactor types, tolerances, output formats, and diagram details.
def generate_flux(model_path: str, folder_path: str, observables: List[str], times: List[float], composition: Dict[str, float], T: float, P: float, V: Optional[float] = None, r...
def setting_values(self): " ADDING DATA TO LABEL OF THE MAIN WINDOW" self.dic_setting_values['points_avail']=1000-self.dic_setting_values['points_used'] self.VALUE_TEAM_NAME.setText(self.team_name) self.VALUE_TOTAL_BATSMEN.setText(str(self.dic_setting_valu...
The code removes a player from the selected players list, adds them to the available players list, subtracts their points from the total, and updates UI settings. It queries the player's points from a database, adjusts counters, and handles exceptions by calling additional methods for team removal and selection updates...
def selec_rmv(self,value): " TO REMOVE PLAYERS FROM LIST_SELECTED_PLAYERS AND ADD TO LIST_AVAILABLE_PLAYERS" ele = value.text() self.rm_player = ele self.cursor.execute("SELECT VALUE FROM STATS WHERE PLAYER = '"+ele+"';") points = self.curs...
def drawPatchWindowFinal(win,color,p1,p2): p2=p2+100 for i in range(1,11,+1): square=Rectangle(Point(p1,p1),Point(p2,p2)) square.draw(win) if i%2!=0: square.setFill(color) square.setOutline(color) else: square.setFill("white") squar...
The main task of the code is to draw a window pattern by placing colored patches in specific regions. It uses nested loops to iterate over grid positions, applying `color1`, `color2`, or `color3` based on edge/middle conditions. Edge regions use alternating colors, while the central area uses a third color. The `challe...
def drawWindow(win,size,color1,color2,color3): for i in range (0,size,+100): for j in range (0,size,+100): if i<100 or i>=size-100: if (j/100)%2==0: if i==j: drawPatchWindowFinal(win,color1,i,j) else: ...
def filter(request): categories = [] categories = Category.objects.all() select = request.POST.get("option") if select is None: return render(request,"auctions/cate.html",{ "categories" : categories, }) else: se = Category.objects.get(list_category=select) ...
The code handles a POST request to create a new auction listing by extracting form data, associating it with a user and category, and saving it to the database. It then retrieves the newly created item's ID and redirects to a display page for that auction item.
def save(request): if request.method == "POST": title = request.POST["title"] description = request.POST["description"] start_bid = request.POST["start_bid"] image = request.POST["image"] category = Category.objects.filter(list_category=request.POST["category"]).first() ...
def snapToDiscreteValue (canonicalValue, divisions, scale): spacing = 1 / (divisions - 1) snapIndex = int ((canonicalValue + (spacing / 2)) / spacing) snappedX = snapIndex * spacing return snappedX * scale def debug (msg, end = "\n"): if (verbose[0]): print (msg, end = end); def trapezoid (hueVec, s...
This function converts HSL/HSV color values to RGB by normalizing hue and saturation, discretizing them, and applying a trapezoid function to generate the color. It processes hue (0-360°), adjusts it to [0,1), snaps to discrete steps, converts to radians, creates a hue vector, normalizes saturation (0-100%), discretize...
def hs2rgbcw (hs, brightness): # convert hue to a canonical value hueCanonical = hs[0] / 360 while (hueCanonical >= 1): hueCanonical -= 1; # compute hue in a discretized space and convert to radians, then a vector hueRadians = snapToDiscreteValue (hueCanonical, 3 * 8, math.pi * 2) hueVec = vecF...
def get_cwd(args, file_path): """Get the current working directory determining where to run the experiments By default assumes that the directory contains the script_manager""" path = Path(file_path) cwd = None if args.cwd is None: script_manager_found = False c_path = path ...
The function `do_everything` orchestrates parallel/sequential execution of experiments by generating and running commands based on configurations, parameters, and script paths. It constructs output directories using specified keys, manages experiment naming, and leverages `configs2cmds` and `run_cmds` to execute tasks....
def do_everything( default_parameters, configs, extra_folder_keys, appendix_keys, main_script, test_parameters, wandb_project_name, script_file, ): """Function that will execute experiments in parallel or sequentially Args: default_parameters : dict of default parameters ...
def fix_polygon( polygon: Polygon, *, force_north_pole: bool = False, force_south_pole: bool = False, fix_winding: bool = True, ) -> Union[Polygon, MultiPolygon]: """Fixes a :py:class:`shapely.geometry.Polygon`. If the input polygon is wound clockwise, it will be fixed to be wound count...
The main task of the code is to fix geometries that cross the antimeridian (180° longitude) by adjusting their coordinates to prevent distortion. It accepts a shape (polygon, multipolygon, linestring, or multilinestring) and parameters to enforce north/south pole enclosure or correct winding order. The function identif...
def fix_shape( shape: Dict[str, Any] | GeoInterface, *, force_north_pole: bool = False, force_south_pole: bool = False, fix_winding: bool = True, ) -> Dict[str, Any]: """Fixes a shape that crosses the antimeridian. See :py:func:`fix_polygon` for a description of the ``force_north_pole``, ...
def run_basic_basebackup(self): basebackup_directory, _ = self.get_paths_for_backup(self.basebackup_path) basebackup_tar_file = os.path.join(basebackup_directory, "base.tar") command = self.get_command_line(basebackup_directory) self.log.debug("Starting to run: %r", command) pro...
The code's main task is to execute a base backup operation based on the configured `basebackup_mode`. It checks the mode (basic, local-tar, pipe) and invokes the corresponding method. If the mode is unsupported, it raises an error. Finally, it sets `self.running` to False regardless of success/failure, ensuring cleanup...
def run(self): try: basebackup_mode = self.config["backup_sites"][self.site]["basebackup_mode"] if basebackup_mode == "basic": self.run_basic_basebackup() elif basebackup_mode == "local-tar": self.run_local_tar_basebackup() elif bas...
def get_model(graph_file): model_node = { 'alexnet': ['import/conv2d_1_input', 'import/batch_normalization_1/keras_learning_phase', 'import/output0'], 'mobilenetv2': ['import/input_1', 'import/bn_Conv1/keras_learning_phase', ...
The code runs a real-time audio prediction system using a loaded model. It supports three modes: processing audio from a file, listing audio devices, or capturing live input. In real-time mode, it initializes a PyAudio stream, processes incoming audio chunks with the model, and triggers predictions via a callback. The ...
def run_predictor(): model = get_model(args.model_pb_graph) # file mode if args.input_file != '': process_file(model, args.input_file) my_exit(model) # device list display mode if args.input < 0: print_pyaudio_devices() my_exit(model) # normal: realtime mode F...
def startup(): update_viewport(None, 400, 400) glClearColor(0.0, 0.0, 0.0, 1.0) glEnable(GL_DEPTH_TEST) def render(time): glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) glLoadIdentity() spin(time * 180 / 3.1415) lines_egg() axes() glFlush() def shutdown(): pass
The main task of the code is to create a GLFW window, initialize OpenGL context, and perform rendering in a loop until the window is closed. It handles window events, updates the viewport, and manages OpenGL resources by calling startup(), render(), and shutdown() functions.
def main(): if not glfwInit(): sys.exit(-1) window = glfwCreateWindow(400, 400, __file__, None, None) if not window: glfwTerminate() sys.exit(-1) glfwMakeContextCurrent(window) glfwSetFramebufferSizeCallback(window, update_viewport) glfwSwapInterval(1) startup() ...
def startup(): update_viewport(None, 400, 400) glClearColor(0.0, 0.0, 0.0, 1.0) glEnable(GL_DEPTH_TEST) glMaterialfv(GL_FRONT, GL_AMBIENT, mat_ambient) glMaterialfv(GL_FRONT, GL_DIFFUSE, mat_diffuse) glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular) glMaterialf(GL_FRONT, GL_SHININESS, mat_s...
The main task of the code is to create a GLFW window for rendering, set up input and viewport callbacks, and run a rendering loop that updates the screen with time-based rendering, handling user input and events until the window is closed. It initializes resources, processes rendering in a loop, and properly shuts down...
def main(): if not glfwInit(): sys.exit(-1) window = glfwCreateWindow(400, 400, __file__, None, None) if not window: glfwTerminate() sys.exit(-1) glfwMakeContextCurrent(window) glfwSetFramebufferSizeCallback(window, update_viewport) glfwSetKeyCallback(window, keyboard_k...
def _get_solar(self, start, end): self.log(" - Getting yesterday's solar generation") entity_id = self.config["id_daily_solar"] if entity_id is None or not self.entity_exists(entity_id): return dt = pd.date_range( start, end, freq="30min"...
The main task of the code is to compare electricity tariffs by calculating costs for a base scenario and optimized scenarios using solar and consumption data. It loads historical data, initializes battery state, evaluates baseline costs, iterates through alternative tariffs, computes optimized costs via PV system optim...
def _compare_tariffs(self): self.log("") self.log("Comparing yesterday's tariffs") end = pd.Timestamp.now(tz="UTC").normalize() start = end - pd.Timedelta(24, "hours") solar = self._get_solar(start, end) consumption = self.load_consumption(start, end) static = pd...
def _solis_set_mode_switch(self, **kwargs): if self.type == "SOLIS_SOLAX_MODBUS" or self.type == "SOLIS_SOLARMAN": status = self._solis_solax_solarman_mode_switch() elif self.type == "SOLIS_CORE_MODBUS": status = self._solis_core_mode_switch() switches = status["switche...
This function sets the backup state of charge (SOC) for specific inverter types (SOLIS_SOLAX_MODBUS, SOLIS_CORE_MODBUS, SOLIS_SOLARMAN). It configures operational modes based on the 'enable' flag, retrieves or sets the SOC value, and writes it to the inverter's register using type-specific methods. If the inverter type...
def hold_soc(self, enable, soc=None): if ( self.type == "SOLIS_SOLAX_MODBUS" or self.type == "SOLIS_CORE_MODBUS" or self.type == "SOLIS_SOLARMAN" ): if enable: self._solis_set_mode_switch( SelfUse=True, Timed=False, Grid...
def get_config(self, item): if item in self.config_state: return self._value_from_state(self.config_state[item]) if item in self.config: if isinstance(self.config[item], str) and self.entity_exists( self.config[item] ): x = self.get_ha...
The main task of the code is to calculate and log the average unit electricity cost for the day, then update Home Assistant (HASS) with multiple sensors tracking energy costs, charging schedules, and predicted state-of-charge (SOC) values. It writes today's unit cost, base/optimized costs, charge start/end times, charg...
def _write_output(self): if self.get_config("id_consumption_today") > 0: unit_cost_today = round( self._cost_actual().sum() / self.get_config("id_consumption_today"), 1 ) else: unit_cost_today = 0 self.log(f"Average unit cost today: {unit_cost...
def _setup_schedule(self): if self.get_config("forced_charge"): start_opt = ( pd.Timestamp.now() .ceil(f"{self.get_config('optimise_frequency_minutes')}T") .to_pydatetime() ) self.timer_handle = self.run_every( s...
This method handles state changes for specified entities by logging updates, adjusting configuration states, and triggering optimization. It checks if the changed attribute requires schedule setup or PV system model reloading, then initiates optimization.
def optimise_state_change(self, entity_id, attribute, old, new, kwargs): item = self.change_items[entity_id] self.log( f"State change detected for {entity_id} [config item: {item}] from {old} to {new}:" ) self.config_state[item] = new if "forced" in item: ...
def prepare(FPS, properties): TMP_PATH = "E:\\Martin\\Kapljice\\meritve\\" opt = Camera() fname = "uncrossed" fpath = TMP_PATH + fname + '.jpg' opt.setFolder(TMP_PATH) print("Saving image to file {}".format(fpath)) opt.takeImage(fname) sleep(2/FPS) img = read_img(fpath, FPS)...
The function `run_multiple` processes multiple measurement paths by saving properties and images, then executing either normal or hysteresis measurements based on input types. It iterates through paths, writes properties to JSON, saves images, and calls measurement functions with specified parameters. The process inclu...
def run_multiple(paths, properties, Ixs, Iys, Izs, IP, FPS, types): img, ROIsignal, mask, properties = prepare(FPS, properties) messagebox.showinfo("Cross polarizers", "Cross polarizers") for path, Ix, Iy, Iz, meas_type in zip(paths, Ixs, Iys, Izs, types): with open(path + "properties.json", "w") ...
def check_funds(self, amount): self.get_balance() if amount > self.balance: return False else: return True def withdraw(self, amount, description = None): #Use check_funds method if description == None: description = "" #Withdrawl did take place if self.check_funds(amount)...
This method transfers a specified amount from the current instance to another object if sufficient funds are available. It checks funds, deducts the amount from the current instance with a "Transfer to" description, and adds it to the target object with a "Transfer from" description. It returns True on success or False...
def transfer(self, amount, obj): #User check_funds method if self.check_funds(amount): description = "Transfer to " + obj.category self.withdraw(amount, description) description = "Transfer from " + self.category obj.deposit(amount, description) self.get_balance() return Tr...
def match_streaminfos(stream_infos, parameters): """Find stream IDs matching specified criteria. Parameters ---------- stream_infos : list of dicts List of dicts containing information on each stream. This information can be obtained using the function resolve_streams. parameters : ...
The main task of the code is to import and process multi-stream XDF (Extensible Data Format) files, synchronizing timestamps across streams, handling clock resets, and applying jitter removal. It reads data chunks, filters streams based on criteria, and returns structured time-series data with metadata, supporting robu...
def load_xdf( filename, select_streams=None, *, on_chunk=None, synchronize_clocks=True, handle_clock_resets=True, dejitter_timestamps=True, jitter_break_threshold_seconds=1, jitter_break_threshold_samples=500, clock_reset_threshold_seconds=5, clock_reset_threshold_stds=5, ...
def precompute(ID, a, b, G_X, G_Y, x_A, y_A): a = str(a) b = str(b) G_X = str(G_X) G_Y = str(G_Y) x_A = str(x_A) y_A = str(y_A) ENTL = str(get_bit_num(ID)) joint = ENTL + ID + a + b + G_X + G_Y + x_A + y_A joint_b = bytes(joint, encoding='utf-8') digest = sm3.sm3_hash(func.bytes...
This code verifies a digital signature using elliptic curve cryptography. It computes a hash of the message and precomputed value Z, performs elliptic curve operations on the signature components and public key, then checks if the derived value R matches the signature's r component, confirming validity if they match.
def verify(public_key, ID, message, signature): r = signature[0] s = signature[1] Z = precompute(ID, A, B, G_X, G_Y, public_key[0], public_key[1]) _M = str(Z) + message _M_b = bytes(_M, encoding='utf-8') e = sm3.sm3_hash(func.bytes_to_list(_M_b)) # str e = int(e, 16) t = (r + s) % N ...
def _check_raw_data_directory(self, ds): """ Check if dataset include directory 'inputs' and 'labels' and file 'stats.csv' """ if not os.path.exists(os.path.join(self.datapath, ds, 'inputs')): raise FileNotFoundError('Dataset does not contain directory "inputs".') if ...
The main task of the code is to preprocess images by initializing data structures for image statistics and counts, checking raw data directories, setting up saving directories, optionally loading and filtering specific columns from CSV stats files, and cropping images. It processes each dataset entry to prepare data fo...
def _preprocess(self): """ Main function to preprocess images. """ self.img_stats = [None] * len(self.dataset) self.img_count = [0] * len(self.dataset) for i, ds in enumerate(self.dataset): self._check_raw_data_directory(ds) if self._setup_...
def getname(name): return name[0:name.find(b'\0')].decode() def getlong(f): data = f.read(4) if not data or len(data) != 4: return None (r,) = unpack('>L', data) return r def convlog(msg): if verbose: print(msg, end='') def getfdate(date): return f'{1980 + (date >> 25)}-{(dat...
The main task of the code is to extract files from an archive format (like `.a` or `.ar`), using a temporary directory to store extracted files. It reads file names, sizes, and timestamps, logs details, and extracts each file into the temporary directory. Finally, it creates a new archive (`mkarchive`) containing all e...
def arfile(f, fn): with tempfile.TemporaryDirectory() as tmpdir: f.seek(6) files = [] while True: name = getname(f.read(24)) if not name: break size = getlong(f) date = getlong(f) date = (date >> 16) | ((date & 0xfff...
def getname(name): return name[0:name.find(b'\0')].decode() def getlong(f): data = f.read(4) if not data or len(data) != 4: return None (r,) = unpack('>L', data) return r def convlog(msg): if verbose: print(msg, end='') def getfdate(date): return f'{1980 + (date >> 25)}-{(dat...
This code extracts files from a structured archive format by reading headers, offsets, and sizes, then writes each file to a temporary directory. It logs details of each extracted file and finally creates a new archive containing all extracted files.
def libfile(f, fn): with tempfile.TemporaryDirectory() as tmpdir: f.seek(2) name = getname(f.read(24)) size = getlong(f) f.read(2) fofst = getlong(f) fsize = getlong(f) sofst = getlong(f) ssize = getlong(f) nofst = getlong(f) nsize = ge...
def _build_data_volume(self): shape = (0, 4, self.slice_length) chunks = (self.chunk_size, 4, self.slice_length) maxshape = (None, shape[1], shape[2]) data_volume = self.hdf5.create_dataset( "data", shape, chunks=chunks, maxshape=maxshape, dtype=np.int8, compress...
The code generates and writes data chunks into an HDF5 file. It initializes an HDF5 file, constructs data, labels, and binary labels volumes, iterates over chunks, generates each chunk, writes them into the respective volumes, and finally closes the HDF5 file.
def generate(self, chunks): self.hdf5 = h5py.File(self.filename, 'w') data_volume = self._build_data_volume() labels_volume = self._build_labels_volume() binlabels_volume = self._build_binlabels_volume() for i in range(chunks): data_chunk, labels_chunk, binlabels_...
def get_sorted_pending_requests(): temp_acceptable = [] requests = Request.objects.filter(request_status='Pending').order_by('date') for request in requests: result = get_matched_query_for_request(request) if result: temp_acceptable.append(result) temp_acceptable = sorted(tem...
The code automatically processes pending blood requests by matching them with available blood stock. It reduces the stock quantity upon acceptance, deletes the stock if fully used, and retries if stock is missing. The loop continues until all pending requests are handled, updating statuses and quantities accordingly.
def handle_request_automatically(): while get_sorted_pending_requests().count: for request in get_sorted_pending_requests(): try: request['matched_blood_record']= BloodStock.objects.get(pk=request['matched_blood_record'].pk) if request['matched_blood_record'].quan...
def create_sine(sampling_rate, frequency, amplitude, show_plot = True): # Creates a sine wave for the by parameters used at the beginning of the program Fs = sampling_rate # Sampling rate f = frequency # Signal frequency x = np.arange(1,Fs +1) amp = amplitude # Amplitude of sine wave y = amp*np....
The code generates a sine wave, creates delayed segments, computes cross-correlation and mutual information metrics, plots these metrics, and saves results to CSV files for analysis of time delay and signal relationships.
def model_head_first(): sine = create_sine(sine_length, sine_freq, 1) delayed_segments = create_delay_segments(sine, num_segments, delay_per_seg) cross_avg, cross_peak_avg = correlate_slice_calc(delayed_segments, sampling_rate) plots_to_plottt(cross_avg, y = 'time delay to peak cross correlation...
def create_sine(sampling_rate, frequency, amplitude, show_plot = True): # Creates a sine wave for the by parameters used at the beginning of the program Fs = sampling_rate # Sampling rate f = frequency # Signal frequency x = np.arange(1,Fs +1) amp = amplitude # Amplitude of sine wave y = amp*np....
The code runs a model multiple times (default: 10 cycles), calculating cross-correlation time lag, peak values, and mutual information for each iteration. It stores results in lists, averages them across cycles, generates plots, and saves the averaged data (cross-correlation delays, peak values, mutual information) to ...
def repeat_model(cycles = 10): ##create empty variables MI_total = [0 for i in range(cycles)] cross_timelag_total = [0 for i in range(cycles)] cross_peak_total = [0 for i in range(cycles)] # Run the model for however many cycles for i in range(cycles): sine = create_sine(sine_length, ...
def run_once(name, start_frame, stop_frame, frame_rate, corr_seg = corr_seg): # Run everything on a single worm print('File name: ' + name) print('Start frame: ' + str(start_frame)) print('Stop frame: ' + str(stop_frame)) print('Segment to compare to: '+ str(corr_seg)) total_frames = stop_frame...
The main task of the code is to process multiple worm tracking data files by calculating cross-correlation, mutual information, and velocity metrics for each, normalizing data lengths, averaging results across trials, generating plots, and saving outputs as CSV files. It returns aggregated metrics and visualizations fo...
def combine_worms(name_list, start_list,stop_list, frame_rate_list, corr_seg=corr_seg): # Create cross correlation average matrix and mutual info cross_total = [0 for i in range(len(name_list))] # Time lage for peak cross correlation cross_peak_total = [0 for i in range(len(name_list))] #Peak cross correla...
def record_clicks(self): self.boxclick += 1 self.clicks_label.config(text=f"Clicks: {self.boxclick}") def record_timestamp(self): # Record the timestamp for each press timestamp = time.time() self.click_timestamps.append(timestamp) if self.prev_timestamp is not None: ...
This code manages right mouse button press tracking, prevents overclicking by comparing with left press counts, records timestamps and clicks, and triggers a stopwatch stop, time recording, timer reset, and result display when right press count exceeds 5.
def record_right_press(self): # Prevents overclicking of the right box if self.left_press_count > self.right_press_count: self.right_press_count += 1 self.record_clicks() self.record_timestamp() # if-statement for whenever right press count is over 5 ...
def _process_bad_server_salt(self, body): # TODO: dont store messages and use future_salts method instead if self._mtproto.get_server_salt != 0: #self._last_seqno = 0 self._stable_seqno = False self._mtproto.set_server_salt(body.new_server_salt) self.log('updating...
This function processes Telegram message bodies by routing them to specific handlers based on their type. It checks the message type and delegates to methods like _process_bad_server_salt, _process_bad_msg_notification_msg_seqno_too_low, and _process_rpc_error_flood_wait for error cases, while defaulting to _process_an...
def _process_telegram_message_body(self, body): if body == 'new_session_created': pass elif body == 'msgs_ack': pass elif body == 'bad_server_salt': self._process_bad_server_salt(body) elif body == 'bad_msg_notification' and body.error_code == 32 and n...
def _update_last_seqno_from_incoming_message(self, message): self._last_seqno = max(self._last_seqno, message.seqno) def log(self, message): print(str(datetime.datetime.now()), self._peername, message, file=sys.stdout) def _process_telegram_message_body(self, body): if body == 'new_session_creat...
This function processes incoming Telegram messages by updating the last sequence number, logging if enabled, unpacking gzip data, recursively handling message containers, and acknowledging messages after processing their content.
def _process_telegram_message(self, message) -> None: self._update_last_seqno_from_incoming_message(message) if self._print_objects: self.log("v %r" % message) body = message.body.packed_data if message.body == 'gzip_packed' else message.body if body == 'msg_container': ...
def mygradCAM(input_path): Model = ResNet50 # load the pre-trained CNN model imagenet print("[INFO] loading model...") model = Model(weights="imagenet") # load the image for predicting origImg = cv2.imread(input_path) # resize the image resized = cv2.resize(origImg, (224, 224)) # pr...
The code processes an input image by generating a gradient map, segmenting the image using the gradient, clustering colors, creating a matrix, calculating color statistics, and sorting distances between color means. The main task is to analyze and transform the image through gradient-based segmentation, color clusterin...
def dodo(input_path): gradImg=mygradCAM(input_path) cutImg=mygrabCUT(input_path,gradImg) barImg=image_color_cluster(1,cutImg) makeMatrix(barImg) aaa=colorMatrix() sums,aaa=colorMean(aaa) Distance_Dict=calDistance(sums,aaa) sortDistance(Distance_Dict,200) return barImg
def connect_wifi(): """ A function to connect to the wifi in breakiron """ network.country('US') # set the wifi country code to the US # set the hostname of the device hostname = f"motionsensor-{machine.unique_id().hex()[:4]}" network.hostname(hostname) # enable the wifi interface in...
The main task of the code is to set up an MQTT client for connecting to a broker, subscribe to an alarm topic, synchronize time via Wi-Fi, and continuously monitor for incoming messages or alarms while maintaining a clock display, with a loop that terminates on message receipt or keyboard interrupt.
def main(): """ Main function that sets up the MQTT client, connects to the broker, and checks for alarm set by the user. """ connect_wifi() ntptime.settime() clock_time() client = mqtt.MQTTClient(client_id=machine.unique_id().hex(), server=MQTT_BROKER_HOST, port=MQTT_BROKER_PORT) client...
def copyState( state1, state2): for i in range(N): state1[i] = state2[i] def generateBoard( board, state): fill(board, 0) for i in range(N): board[state[i]][i] = 1 def getNeighbour(board, state): # Declaring and initializing the # optimal board and state with # the current board and the state # as the star...
The code implements a **hill-climbing algorithm** to solve a problem (likely N-Queens or similar) by iteratively improving a board state. It initializes a neighbor board/state, then enters a loop where it generates optimal neighbors. If the neighbor equals the current state (no improvement), it outputs the result. If o...
def hillClimbing(board, state): # Declaring and initializing the # neighbour board and state with # the current board and the state # as the starting point. neighbourBoard = [[0 for _ in range(N)] for _ in range(N)] neighbourState = [0 for _ in range(N)] copyState(neighbourState, state) generateBoard(neighbo...
def H_alternative_way(Max_gates, U_gates, U_gener, Thets, matrix_length, Hamil_array, Hamil_coeffs, entangle_gates): H_matrix = np.zeros(shape=(matrix_length, matrix_length), dtype=np.complex128) for i in range(matrix_length): for n in range(matrix_length): print("This is the matrix element ...
The code performs iterative optimization of quantum circuit parameters (Thets) to minimize energy using a Hamiltonian (H), with regularization and shaking mechanisms to escape local minima. It constructs modified Hamiltonian (H_tilde) and overlap (S_tilde) matrices, tests parameter updates with varying regularization s...
def actual_optimization(S_tilde, H_tilde, Thets, circuit, Hamilt_written_outt, dev2, U_gates, U_gener, matrix_length, H_gates, H_coeffs, entangel_gates): energy_array = [] n_array = [] energy_old =0 shakey = [] eigvals_args = [] times_shaken = 0 for n in range(50): ##100 is atm the maximum v...
def lessThan70000(cross_income): taxrate = 30 tax_range = calculation.subtract(cross_income, 48000) tax = calculation.multiply(tax_range, taxrate / 100) tax = tax + lessThan48000(48000) tax = tax + lessThan14000(14000) return tax def lessThan48000(cross_income): taxrate = 17.5 tax_range ...
This code calculates the total tax for an income bracket under 180,000 by applying a 33% tax rate to the amount exceeding 70,000, then summing it with precomputed taxes from lower income brackets (70,000, 48,000, and 14,000). It uses a progressive tax system where higher income portions are taxed at higher rates, combi...
def lessThan180000(cross_income): taxrate = 33 tax_range = calculation.subtract(cross_income, 70000) tax = calculation.multiply(tax_range, taxrate / 100) tax = tax + lessThan70000(70000) tax = tax + lessThan48000(48000) tax = tax + lessThan14000(14000) return tax
def lessThan180000(cross_income): taxrate = 33 tax_range = calculation.subtract(cross_income, 70000) tax = calculation.multiply(tax_range, taxrate / 100) tax = tax + lessThan70000(70000) tax = tax + lessThan48000(48000) tax = tax + lessThan14000(14000) return tax def lessThan70000(cross_inco...
This function calculates total tax for income exceeding 180,000 by applying a 39% rate to the amount over 180,000 and summing it with precomputed taxes from lower income brackets (180,000, 70,000, 48,000, 14,000) using recursive calls to bracket-specific tax functions.
def overThan180000(cross_income): taxrate = 39 tax_range = calculation.subtract(cross_income, 180000) tax = calculation.multiply(tax_range, taxrate / 100) tax = tax + lessThan180000(180000) tax = tax + lessThan70000(70000) tax = tax + lessThan48000(48000) tax = tax + lessThan14000(14000) ...
def overThan180000(cross_income): taxrate = 39 tax_range = calculation.subtract(cross_income, 180000) tax = calculation.multiply(tax_range, taxrate / 100) tax = tax + lessThan180000(180000) tax = tax + lessThan70000(70000) tax = tax + lessThan48000(48000) tax = tax + lessThan14000(14000) ...
This function calculates total tax based on income brackets by calling specific helper functions for each range: over 180,000, 70,000–180,000, 48,000–70,000, 14,000–48,000, and below 14,000. It determines the applicable tax calculation method depending on the input income value.
def totalTax(cross_income): if cross_income > 180000: return overThan180000(cross_income) elif cross_income > 70000: # 70000 - 180000 return lessThan180000(cross_income) elif cross_income > 48000: # 48000 - 70000 return lessThan70000(cross_income) elif cross_income > 14000: # 140...
def produce_dcase_foreground_source_material(dcase_base_dir, source_base_dir): # split, read, convert, and write data csv_paths = glob.glob(os.path.join(dcase_base_dir, '*.csv')) class_name = 'me' print("class_name: {}, csv_paths: {}".format(class_name, csv_paths)) dcase_to_scaper_source_material(c...
The main task of the code is to convert and organize audio data from DCASE, NIGENS, and TUT datasets into a specified output directory. It parses input paths, defines dataset classes, and invokes functions to generate foreground (DCASE, NIGENS) and background (TUT) source materials for sound event detection tasks, thou...
def main(): parser = argparse.ArgumentParser(description='A data conversion script.') #parser.add_argument('--dcase_base_dir', type=str, help='Path to the DCASE directory.') #parser.add_argument('--nigens_base_dir', type=str, help='Path to the NIGENS directory.') #parser.add_argument('--tut_base_dir', ...
def all_site_intent(event, context): data = get_all_site_data(1) if (len(data)) == 0: speak_response = "There is no contest available now on any website." card_response = speak_response else: site = data[0][3].title() contest_name = data[0][0] startdate_string = data[...
This function routes incoming intents to appropriate handlers by checking the intent name in the event. It directs custom intents (e.g., site-specific queries) to dedicated functions and required intents (e.g., Cancel, Help) to standard handlers. If no match is found, it triggers an error response.
def intent_router(event, context): intent = event['request']['intent']['name'] # Custom Intents if intent == "AllSiteIntent": return all_site_intent(event, context) if intent == "SingleSiteIntent": return single_site_intent(event, context) if intent == "SingleSiteAllContestIntent...
def on_launch(event, context): response = "Welcome from Contest Reminder. Ask me about the contests." return statement("Contest Reminder", response) def intent_router(event, context): intent = event['request']['intent']['name'] # Custom Intents if intent == "AllSiteIntent": return all_site...
This code defines an AWS Lambda handler function that processes incoming events by routing them to specific handlers based on the request type. It prints the event, checks if the request is a LaunchRequest (triggering on_launch), IntentRequest (using intent_router), or other types (calling on_error). The main task is t...
def lambda_handler(event, context): print(event) if event['request']['type'] == "LaunchRequest": return on_launch(event, context) elif event['request']['type'] == "IntentRequest": return intent_router(event, context) elif event['request']['type'] != 'SessionEndedRequest': retu...
def get_capability(body): global screen_capability try: capabilities = body['originalDetectIntentRequest']['payload']['surface']['capabilities'] for capability in capabilities: # print(capability['name']) if capability['name'] == 'actions.capability.SCREEN_OUTPUT': ...
This code processes incoming events by parsing JSON data, determining the intent action, and generating appropriate responses. It handles specific intents like 'single_site_intent' or 'all_site_intent' by calling corresponding functions, sets global variables for source and capability, and returns a structured JSON res...
def endpoint(event, context): body = event['body'] print(body) body = json.loads(body) action = body['queryResult']['action'] global source source = body['originalDetectIntentRequest']['source'] get_capability(body) print(action) if action == 'input.single_site_intent': re...
def draw_grid(win, grid): global selected,selection_points for i, row in enumerate(grid): for j, pixel in enumerate(row): pygame.draw.rect(win, pixel, (j * PIXEL_SIZE, i * PIXEL_SIZE, PIXEL_SIZE, PIXEL_SIZE)) if DRAW_GRID_LINES: for i in range(ROWS + 1): pygame.dra...
The main task of the code is to render a game window by drawing the grid, buttons, slider, brush size indicators, and mouse position text, while handling events and updating the display. It fills the screen with a background color, processes user interactions via the slider and buttons, and dynamically updates the visu...
def draw(win, grid, buttons): win.fill(BG_COLOR) draw_grid(win, grid) pygame.event.get() #Draws The Slider slider.render(win) slider.changeValue() # Draws The Buttons button: object for button in buttons: button.draw(win) #Draws The Brush Size Buttons draw_brus...
def _build_command_list(): import assignments ispublic = lambda item: not item[0].startswith("_") for loader, name, _ in _iter_ns_modules(assignments.__path__, "."): module = loader.find_module(name).load_module(name) all_funcs = getmembers(module, isfunction) public_funcs = filter...
The main task of the code is to handle command-line arguments for a CLI tool. It builds available commands, checks for required arguments, parses inputs into a function and parameters, executes the function, and handles errors by displaying help messages and exiting with status code 2 when invalid arguments are provide...
def main(): _build_command_list() if len(sys.argv) < 2: _list_commands() return func, kwargs = _parse_args() try: func(**kwargs) except TypeError: print("Missing or bad arguments provided") _show_help(func) raise SystemExit(2)