dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def get_best_fitness(df, maximize): return df["Fitness"].max() if maximize else df["Fitness"].min() def fitness_chart( df, line_col, all_line_cols, title="TITLE", sup_title="SUPTITLE", maximize=True, xscale_log=False, info_settings={}, external_ax=None, include_legend=True, ...
The main task of the code is to generate a combination of fitness, time, and evaluation comparison charts for different algorithms (GA, MIMIC, RHC, SA) on a specified optimization problem. It reads CSV data, processes algorithm performance metrics, and plots fitness curves, time efficiency, and evaluation counts, custo...
def combination_chart( problem_type, experiment_name, xscale_log=True, ax_line=None, ax_time=None, ax_eval=None, curve_title=None, include_legend=True, output_directory=None, include_y_label=True, ): problem_dict = {"four_peaks": "Four Peaks", "knapsack": "Knapsack", "k_colo...
def extract_img_feat(self, img_data, batch_size): img_feat = self.ResNet50Truncated(img_data) # Resize the features to the image/depth resolution img_feat = F.interpolate(img_feat, size=(self.crop_size[1], self.crop_size[0]), mode='nearest') return img_feat def groundProjectio...
The main task of the code is to process sequential inputs (images, points, etc.) through MapNet to predict position probabilities (p_pred) and update a global map (map_pred) using an LSTM. It projects image features onto a ground grid, applies rotational stacking, and iteratively predicts positions, registers observati...
def forward(self, local_info, update_type, input_flags, p_gt=None): # Runs MapNet for an entire episode (img_data, points2D, local3D, sseg, dets) = local_info batch_size = img_data.shape[0] seq_len = img_data.shape[1] # Extract the img features with_feat = input_flags[0]...
def intensityAdjusted(image_to_adjust: np.ndarray, adjust_gamma: bool = False) -> np.ndarray: """ Performs an automatic adjustment of the input intensity range to enhance contrast. Args: image_to_adjust: a gray scale image to adjust the intensity of. adjust_gamma: use gamma rescaling to adju...
The function tracks a template image through each frame of a video, adjusting for rotation, translation, and blank frames. It returns tracking results, displacement metrics, frame rate, and frequency estimates. The template is matched using sub-pixel refinement, with options for ROI selection, motion constraints, and o...
def trackTemplate( input_video_path: str, template_guide_image_path: str, template_rgb: np.ndarray = None, template_gray: np.ndarray = None, output_video_path: str = None, guide_match_search_seconds: float = None, microns_per_pixel: float = None, output_conversion_factor: float = None, ...
def config_from_json(json_config_path) -> Tuple[str, List[Dict]]: json_file = open(json_config_path) config = json.load(json_file) return config def config_from_cmdline(cmdline_args) -> dict: return { 'input_video_path': cmdline_args.input_video_path, 'template_guide_image_path': cmdline...
The main task of the code is to track a template image through each frame of a video using configurable parameters. It parses command-line arguments for input video, template image, Excel output, JSON config, and tracking settings. The code loads configuration data from either a JSON file or command-line inputs, then e...
def main(): # read in a config file & parse the input args parser = argparse.ArgumentParser( description='Tracks a template image through each frame of a video.', ) parser.add_argument( '--input_video_path', default=None, help='Path of input video/s to track a template.',...
def roiInfoFromTemplates( search_image: np.ndarray, template_info: Dict, sub_pixel_search_increment: float=None, sub_pixel_refinement_radius: float=None ) -> Dict: """ Finds the best match ROI for templates within search_image, and passes back the location information for all ROIs found. ...
The function computes morphology metrics (e.g., distances, thicknesses, area, orientation) between user-defined ROIs in search images and reference/dynamic templates. It processes multiple image files, generates visualizations, logs warnings, and exports results to CSV/Excel with parameters.
def computeMorphologyMetrics( search_image_path: str, left_template_image_path: str, right_template_image_path: str, sub_pixel_search_increment: float = None, sub_pixel_refinement_radius: float = None, template_refinement_radius: int = 40, edge_finding_smoothing_radius: int = 1, microns_...
def apply_kernel(image: SingleChannelImage, kernel: Kernel) -> SingleChannelImage: """ in this func we are implementing the kernel in to the image to do the changes that we want it to do. :param image: in image presented in a form of 3D list that contains the image data. :param ...
The main task of the code is to generate a binary edge map from an input image. It applies a blur kernel to reduce noise, then computes an adaptive threshold for each pixel based on a local block of pixels. Pixels in the blurred image are compared against this threshold (adjusted by parameter `c`) to produce a two-colo...
def get_edges(image: SingleChannelImage, blur_size: int, block_size: int, c: int) -> SingleChannelImage: """ this func is getting the edges from the original image. :param image:a 2D list that contains an image data :param blur_size:a temporary version for the image. :param block_size:...
def separate_channels(image: h.ColoredImage) -> List[List[List[int]]]: """ reorder of the image data in to channels X rows X columns. :param image:3D list that contains an image data :return: separate_channels """ columns = len(image[0]) rows = len(image) channels = len(image[0][0]) ...
This function scales down a colored image if its dimensions exceed the specified max_size. It calculates a scaling ratio, resizes each color channel (R, G, B) proportionally, and returns the scaled image. If the original image already meets the size requirements, it returns None.
def scale_down_colored_image(image: ColoredImage, max_size: int) -> Optional[ ColoredImage]: """ this func is will check if an image data stands with if the requirements :param image: 2D list that contains an image data. :param max_size: number of the max size. :return: if it stands in the requ...
def quantize_colored_image(image: ColoredImage, N: int) -> ColoredImage: """ this func is calculating from a given formula. :param image:a 3D list that contains an image data. :param N:num of channels. :return:an image calculated from a given formula. """ res = [] sep = separate_channels...
The function cartoonifies an image by quantizing colors, converting to grayscale, detecting edges via thresholding, and applying a mask to blend edges with quantized colors, resulting in a stylized cartoon effect.
def cartoonify(image: ColoredImage, blur_size: int, th_block_size: int, th_c: int, quant_num_shades: int) -> ColoredImage: """ this func is combining the hole program together into the sole purpose to cartoonify an image. :param image: image:3D list that contains an image data...
def scan(self): try: self.i2cbus.read_byte(self.i2c_addr) return True except: print("I2C init fail") return False def set_bus_RNG(self, value): ''' @fn set_bus_RNG @brief Set BRNG (Bus Voltage Range) @param value bus_vol_range_16V < ...
The code initializes an I2C bus and configures the INA219 sensor's registers for data collection. It sets calibration values, bus voltage range, PGA, ADC resolutions, sampling rates, and operating mode to ensure accurate measurements. The function returns True if successful, False otherwise.
def begin(self): '''! @fn begin @brief Initialize I2C bus and configure INA219 config register before reading data @return True (succeeded)/False (failed) ''' if not self.scan(): return False else: self.cal_value = 4096 self.set_bus_RNG(self.bus_vol_range_32V) ...
def process_board(player_index): # Converts the board to the state that your AI will receive it. new_board = [] # Initializing the new board. for row in board: new_row = [] for square in row: new_square = [] for i in range(4): # Reindexing the board to make your AI ind...
The function `run_round` executes one game turn by collecting and validating moves from four players, applying visual effects, updating the display, and recursively advancing to the next round until 300 rounds are completed. It checks move legality, dims the screen, handles player inputs, and manages game state progres...
def run_round(screen): # Runs one turn of the game. global round_number moves = [] # Each move is of the form [row, col]. for i in range(4): moves.append(Players[i](process_board(i), copy.copy(walls)))# Getting the moves of each player. banned_indexes = [] # Checking whether all the moves a...
def is_addon_installed(self, addon_name="managed-odh"): """Check if given addon is installed""" addon_state = self.get_addon_state(addon_name) if addon_state == "not installed": log.info( "Addon {} not installed in cluster " "{}".format(addon_name, se...
The code installs the "gpu-operator-certified-addon" if it is not already installed, waits for the installation to complete, and then pauses for 5 minutes to ensure all related services are fully operational.
def install_gpu_addon(self): if not self.is_addon_installed(addon_name="gpu-operator-certified-addon"): self.install_addon(addon_name="gpu-operator-certified-addon") self.wait_for_addon_installation_to_complete( addon_name="gpu-operator-certified-addon" ) ...
def is_addon_installed(self, addon_name="managed-odh"): """Check if given addon is installed""" addon_state = self.get_addon_state(addon_name) if addon_state == "not installed": log.info( "Addon {} not installed in cluster " "{}".format(addon_name, se...
This function ensures the 'dbaas-operator' addon is installed. If not already installed, it triggers the installation, waits for completion, and pauses for 5 minutes. If installed, it logs confirmation.
def install_rhoda_addon(self): if not self.is_addon_installed("dbaas-operator"): self.install_addon("dbaas-operator") self.wait_for_addon_installation_to_complete("dbaas-operator") time.sleep(300) else: log.info("Operator installed already")
def is_addon_installed(self, addon_name="managed-odh"): """Check if given addon is installed""" addon_state = self.get_addon_state(addon_name) if addon_state == "not installed": log.info( "Addon {} not installed in cluster " "{}".format(addon_name, se...
This function uninstalls the 'dbaas-operator' addon if it is installed on the cluster. It first checks for its installation status, triggers uninstallation if present, and waits for the process to complete. If the addon is not installed, it logs an informational message indicating the absence of the operator on the clu...
def uninstall_rhoda_addon(self): if self.is_addon_installed("dbaas-operator"): self.uninstall_addon("dbaas-operator") self.wait_for_addon_uninstallation_to_complete("dbaas-operator") else: log.info("Operator is not installed on this cluster")
def retrieve_instances(isv, namespace): """To retrieve DB instances for Imported Provider Account""" inst_list = [] counter = 0 pa_reconcile = "True" provider_account = BuiltIn().get_variable_value(r"\${provaccname}") if provider_account == "": create_secret_cli(isv, "true") impo...
This function deploys a database instance for a provider account by retrieving existing instances, creating a new project, and deploying the instance using the retrieved list. It uses the provided namespace or defaults to an operator namespace, then executes deployment with the new project and instance data.
def deploy_db_instance_cli(isv, project, namespace=None): """To deploy a DB instance on given namespace for the imported provider account""" if namespace is None: namespace = BuiltIn().get_variable_value(r"\${operatorNamespace}") instance_list = retrieve_instances(isv, namespace) create_new_...
def create_new_project(project_name): """To create new project to deploy provider account""" project_name = util.get_project_name(project_name) oc_cli = BuiltIn().get_library_instance("OpenshiftLibrary") oc_cli.new_project(project_name) BuiltIn().set_suite_variable(r"\${newProject}", project_name) ...
This function provisions a new database instance in an OpenShift environment by configuring namespaces, creating projects, generating YAML manifests, and applying them via the OpenshiftLibrary. It uses parameters to determine target namespaces for deployment and provider account setup, handles "user"-specific configura...
def provision_db_instance(isv, deploy_view, default_pa_ns="Yes"): """To Provision New DB Instance Under Provider Account. Arguments deploy_view and default_pa_ns defines the target namespaces to deploy database instance and import provider account respectively""" prov_acc_ns = BuiltIn().get_variable_val...
def is_addon_installed(self, addon_name="managed-odh"): """Check if given addon is installed""" addon_state = self.get_addon_state(addon_name) if addon_state == "not installed": log.info( "Addon {} not installed in cluster " "{}".format(addon_name, se...
The main task of the code is to install the RHODS addon if it is not already installed. It checks the installation status, triggers the installation process, waits for completion, and then pauses for 5 minutes to ensure all services are fully operational. This ensures the addon and its dependencies are properly initial...
def install_rhods_addon(self): if not self.is_addon_installed(): self.install_rhods() self.wait_for_addon_installation_to_complete() # Waiting 5 minutes to ensure all the services are up time.sleep(300)
def tokenize_integer(self): # -> str: optional_minus_sign = '' if self.next() == '-': optional_minus_sign = self.consume() if TokenizerHelpers.isdigit(self.next()): if self.next() == '0': if TokenizerHelpers.isdigit(self.next_n(2)[-1]): ...
The main task of the code is to parse a numeric value into its integer, fractional, and exponent components using separate tokenization methods, then combine them into a JSONNumber object. This function constructs a JSON-compliant number string by concatenating these parts, ensuring proper formatting for numbers with d...
def tokenize_number(self): # -> JSONNumber: integer = self.tokenize_integer() fraction = self.tokenize_fraction() exponent = self.tokenize_exponent() return JSONNumber(f'{integer}{fraction}{exponent}')
def check_command_line(path_to_apk, output): """Checks the correctness of the command line. Args: path_to_apk: Absolute path of apk placement. output: Absolute path of report placement. Returns: Nothing. Raises: SystemExit: If no path to apk is found. OSError: If error ...
The main task of the code is to analyze an APK file by performing static and dynamic analysis. It checks device compatibility, installs the APK, extracts metadata, runs security checks, and generates a report. The function handles APK installation, permission validation, analysis execution, and cleanup, using tools lik...
def main(path_to_apk, device_ip, su_pass, output, activity_time, allow_permissions, tempdir): check_command_line(path_to_apk, output) start_jadx(path_to_apk, tempdir) device_data = check_device() badging = get_badging(path_to_apk) install_apk(badging['package'], path_to_apk, device_data['m...
def check_splitable(bucket): """ Check if the bucket can be further splitted down. """ check_list = [t for t in bucket.value if t not in set(bucket.split_list)] if bucket.splitable: for t in check_list: if len(ATT_TREE[t].child) != 0: return True bucket.s...
The main task of the code is to recursively split a dataset into anonymization buckets by selecting a node, distributing data, balancing partitions, and recursively processing sub-buckets until they can no longer be split, ensuring data anonymity while maintaining structural integrity.
def anonymize(bucket, K): """ Recursively split the dataset to create anonymization buckets. """ global RESULT if check_splitable(bucket) is False: RESULT.append(bucket) return (pick_value, expandNode) = pick_node(bucket) distribute_data(bucket, expandNode, pick_value) ...
def init(att_tree, data, k): """ Initialize global variables. """ global LEAF_NUM, PARENT_LIST, ATT_TREE, ELEMENT_NUM, RESULT PARENT_LIST = {} RESULT = [] LEAF_NUM = 0 ELEMENT_NUM = 0 for tran in data: ELEMENT_NUM += len(tran) ATT_TREE = att_tree LEAF_NUM = len(ATT...
The code partitions transaction data into k-anonymous groups while preserving privacy. It initializes data structures, anonymizes the dataset using a bucketing approach, calculates information loss for each partition, and returns the anonymized partitions along with metrics (normalized information loss and runtime). Th...
def partition(att_tree, data, k): """ data: original transactions data """ init(att_tree, data, k) result = [] start_time = time.time() anonymize(Bucket(data, ["*"]), k) rtime = float(time.time() - start_time) ncp = 0.0 for partition in RESULT: pncp = 0.0 for ...
def create_graph(img, sigma): # Gaussian filter applied on the input image img = gaussian_filter(img, sigma) rows = img.shape[0] cols = img.shape[1] total_edges = (rows-1)*cols + (cols-1)*rows graph = [] for channel in range(img.shape[2]): edges = np.empty((total_edges, 3), dtype=np....
The code performs image segmentation using a graph-based approach. It reads an input image, converts GIFs to PNG, normalizes pixel values, constructs a graph with a specified sigma value, segments the image into k regions, and saves the segmented result to an output file.
def main(): if len(sys.argv) < 4: print('Usage: graphSegment.py inputImageFile k outputImageFile') sys.exit(1) inputImageFile = sys.argv[1] k = int(sys.argv[2]) outputImageFile = sys.argv[3] # -------------------------------------- if '.gif' in inputImageFile: img = Image.o...
def validate_insurance_limit(doc): # SALES INVOICE insurance, patient = doc.get("customer"), doc.get("patient") if not patient: return # Works for patients only limits = frappe.get_value("Patient Insurance", dict(parent=patient, insurance_name=insurance), [ 'outpatient_limit', 'inpatient_limit'], as_dic...
The main task of the code is to validate a customer's payment balance before proceeding with a transaction. It checks if the customer is a company (requiring insurance validation) or has an associated patient. If not, it calculates the customer's outstanding balance, compares it with the invoice total, and ensures suff...
def validate_payment(doc, handler=None, ignore_zero_balance=False): # IF CUSTOMER IS OF TYPE COMPANY, THEN RETURN AS WE WILL ACCEPT INVOICING. IF NOT, THERE BETTER BE MONEY FIRST. if doc.get('generated_by') != 'Lonius Health': return company = frappe.defaults.get_user_default("company") customer_type = frappe.db....
def process_servo(self, save_to_csv = True): ''' This function preprocess the servo data by: 1. Convert the datetime to seconds for each timestamp. 2. Extract only the timestamp where the gripper state changes. parameters ---------- save_to_csv: bool ...
The main task of the code is to orchestrate three processing steps: servo control, NDI (Network Data Interface) handling, and video processing. The function sequentially invokes `process_servo()` for servo operations, `process_ndi()` for NDI-related tasks, and `process_video()` for video data processing, likely integra...
def process_servo_video_ndi(self): self.process_servo() self.process_ndi() self.process_video()
def forwardPass(mydata): ntask = mydata.shape[0] ES = np.zeros(ntask, dtype = np.int8) EF = np.zeros(ntask, dtype = np.int8) temp = [] #hold temporary codes for i in range(ntask): if(mydata['PREDECESSORS'][i] == None): ES[i] = 0 try: EF[i] = ES[i] + mydata['DAYS'][i] except: errorDaysMsg() ...
The code computes the Critical Path Method (CPM) for a project schedule by performing a forward pass to determine early start/finish times, a backward pass to calculate late start/finish times, and slack analysis to identify non-critical activities. The function processes input data through these steps to determine the...
def computeCPM(mydata): mydata = forwardPass(mydata) mydata = backwardPass(mydata) mydata = slack(mydata) return mydata
def reset_game(self): self.obstacle_manager.reset_obstacles() self.score = 0 self.game_speed = 20 self.power_ups_manager.reset_power_ups() def events(self): for event in pygame.event.get(): if event.type == pygame.QUIT: self.playing = False def update(...
The main task of the code is to execute a game loop that continuously processes events, updates the game state, and renders the game until the 'playing' flag is set to False. It initializes the game with 'reset_game()', then runs in a loop calling 'events()', 'update()', and 'draw()' methods sequentially to handle inpu...
def run(self): # Game loop: events - update - draw self.reset_game() self.playing = True while self.playing: self.events() self.update() self.draw()
def get_user_input(m): input_string = m # emit('recommendations', "==================================\n\n") if "CONFIRM" in input_string: return True, 0, 0, "" inputs = input_string.split(",", 2) edit_stage = int(inputs[0]) button = int(inputs[1]) message = "" if len(inputs) > ...
The main task of the code is to process user input by interpreting button presses and message content to set flags (e.g., reroll, increase_level) and parameters (e.g., selected_option_idx, user_message) for session control. It evaluates the button value to determine actions like rerolling, adjusting levels, enabling di...
def get_user_input_buttons(message): print (f"get_user_input_buttons") confirm, edit_stage, button, message = get_user_input(message) print(confirm, edit_stage, button, message) selected_option_idx = None user_message = "" reroll = False increase_level = False direct_manipulation =...
def get_init_level_guess(user_name, user_input): if CONTROL_GROUP_FLAG: return np.array([0,0,0,0]) # estimate this user's preference in this context context_level = np.array(init_llm_level_guess(user_input)) # estimate all user's preference all_user_level_default = np.array([1,1,1,1]) ...
The function initializes user session data by parsing the input message, generating initial guesses for user level and adaptation time, and setting up a state dictionary. It splits the input into user name and initial input, computes initial guesses using helper functions, populates a state structure with these guesses...
def getUserInfo(init_message): print("init_message") global curr_stage_idx global state_dict global user_name global init_input global init_level_guess curr_stage_idx = 0 user_name, init_input = init_message.split(";", 1) print(f"User {user_name} is starting the session with input:...
def checkcol(self,color,row,col,board2D,score): score = self.count(color,row,col,board2D,score,row,col,0,-1,0,0) score = self.count(color,row,col,board2D,score,row,col,0,1,0,0) return score def checkrow(self,color,row,col,board2D,score): score = self.count(color,row,col,board2D,score,row...
The main task of the code is to calculate a score for a given color on a 7x7 Go board by analyzing all empty cells. For each empty cell, it checks four directions (column, row, and two diagonals) using helper methods to update a 3D score array, likely evaluating potential moves or patterns. The score array accumulates ...
def Score(self,color): board2D = GoBoardUtil.get_twoD_board(self.board) score = [[[0 for dirc in range(5)] for col in range(7)] for row in range(7)] for i in range(7): for j in range(7): if board2D[i][j] == 0: row = i c...
def Score(self,color): board2D = GoBoardUtil.get_twoD_board(self.board) score = [[[0 for dirc in range(5)] for col in range(7)] for row in range(7)] for i in range(7): for j in range(7): if board2D[i][j] == 0: row = i c...
The code evaluates and compares scores for the current player's and opponent's moves, selects the position with the higher score (or the current player's if the opponent's score is not significantly higher), and converts the coordinates to a game move. It prioritizes the opponent's move if their score is notably higher...
def get_move_score_based(self,color): score_c = self.Score(color) score_p = self.Score(3-color) #self.respond(score_c) score_c = self.Sort(score_c,1) score_p = self.Sort(score_p,2) x_P, y_P, max_P = self.Evaluate(score_p) x_C, y_C, max_C = self.Evaluate(score_c) ...
def game_result(board): game_end, winner = board.check_game_end_gomoku() moves = board.get_empty_points() board_full = (len(moves) == 0) if game_end: #return 1 if winner == board.current_player else -1 return winner if board_full: return 'draw' return None def policy_move...
This function performs a random playout simulation in a game, starting from the given board state and current player's turn. It repeatedly selects random moves until the game ends, then backtracks by undoing all moves. The function returns a score: +1.0 if the original player (color_to_play) wins, 0.0 for a draw, or -1...
def _do_playout(self, board, color_to_play): res=game_result(board) simulation_moves=[] while(res is None): _ , candidate_moves = self.policy_moves(board, board.current_player) playout_move=random.choice(candidate_moves) play_move(board, playout_move, board.cu...
def get_lemmas(self, query): lemmas = list() for token in set(self.tokenizer.tokenize(query)): morph = self.morph_analyzer.parse(token) if ( any([x for x in self.BAD_TOKENS_TAGS if x in morph[0].tag]) or token in self.stop_words ): ...
The code's main task is to process a query by lemmatizing it, converting the lemmatized terms into a vector representation, and then retrieving similarities between this vector and other data points. This is typically used in information retrieval or semantic search tasks to find items most relevant to the input query.
def search(self, query): query_lemmas = self.get_lemmas(query) query_vector = self.get_query_vector(query_lemmas) return self.get_similarities(list(query_vector.values()))
def get_dists(self, specs, max_only=False, filtered=False): dists = {} if filtered: filtered = self.prune_packages(specs) for spec in specs: found = False notfound = [] for pkg in self.get_pkgs(MatchSpec(spec), max_only=max_only): i...
The function `solve2` resolves package dependencies by finding compatible versions that satisfy given specifications and constraints. It uses SAT solving techniques to determine valid package combinations, checks for unsatisfiability, and handles version constraints. The code generates logical clauses, evaluates soluti...
def solve2(self, specs, features, installed=(), guess=True, alg='BDD', returnall=False, minimal_hint=False, unsat_only=False, update_deps=True, try_max_only=None): log.debug("Solving for %s" % str(specs)) log.debug("Features: %s" % str(features)) log.debug("Installed: %s" % str(i...
def installed_features(self, installed): """ Return the set of all features of all `installed` packages, """ res = set() for fn in installed: try: res.update(self.track_features(fn)) except KeyError: pass return res ...
The function solves package specifications by resolving dependencies, updating features based on installed packages, and returning a solution using explicit or solve2 methods, with platform-specific handling and error management.
def solve(self, specs, installed=None, features=None, max_only=False, minimal_hint=False, update_deps=True): if installed is None: installed = [] if features is None: features = self.installed_features(installed) for spec in specs: if sys.platfor...
def add_cylinder(tag): ## used to create collision object for "blue object" (small ) and the obstacle (big) # small cylinders dimensions (radius,height) small_hexagon_dim = (.03,.1) # big cylinders dimensions (radius,height) big_hexagon_dim = (.05,.2) identifier = tag.id[0] name = "tag_"...
This function adds detected objects to a planning scene based on their ID. It checks each tag in the input array, appends new IDs to a global list, and creates 3D objects (cylinders, cubes) using specific functions depending on the tag's ID prefix. The task involves dynamically populating the environment with obstacles...
def april_callback(tag_array): # add objects and obstacles to planning scene global add_objs,ojects_list # objects and obstacles ID's that have Hexagon shape prism_list = [1, 4, 5, 6, 7] if add_objs: for tag in tag_array.detections: if tag.id not in ojects_list: ...
def reset_head(): return move_head(0, -0.3) def abort(msg): rospy.logerr(msg) action_server.set_aborted(MoveResult(msg)) def feedback(msg): rospy.loginfo(msg) action_server.publish_feedback(MoveFeedback(msg)) def go_to_goal(pose): #define a client for to send goal requests to the "move_base" se...
The code moves a robotic arm to a predefined picking position for a specified object (blue, green, or red) by retrieving poses from the parameter server, adjusting the robot's head and arm positions sequentially, and validating each step's success. It initializes the head, moves to a safe pose, then navigates to the ob...
def move_to_pick(obj_id): # # Get picking poses from parameter server blue_object_pick = rospy.get_param('/blue_object_pick') green_object_pick = rospy.get_param('/green_object_pick') red_object_pick = rospy.get_param('/red_object_pick') pick_poses = {blue_object: Pose(Point(blue_object_pick[0...
def reset_head(): return move_head(0, -0.3) def abort(msg): rospy.logerr(msg) action_server.set_aborted(MoveResult(msg)) def feedback(msg): rospy.loginfo(msg) action_server.publish_feedback(MoveFeedback(msg)) def go_to_goal(pose): #define a client for to send goal requests to the "move_base" se...
The function `move_to_place` orchestrates a robotic arm's motion to position an object (specified by `obj_id`) at a predefined target location. It retrieves object-specific placement poses, navigates the robot through an initial safe pose, final placement pose, and adjusts the head to a target orientation. The process ...
def move_to_place(obj_id): # Get placing poses from parameter server blue_object_place = rospy.get_param('/blue_object_place') green_object_place = rospy.get_param('/green_object_place') red_object_place = rospy.get_param('/red_object_place') place_poses = {blue_object: Pose(Point(blue_object_p...
def generate_scene(obj_id): start_scene_gen.publish(Tag_Spawn(place_mode, obj_id)) rospy.sleep(.2) def move_torso(): torso_client.wait_for_server() feedback("Moving torso up") waypoint = JointTrajectoryPoint(positions=[0.34], time_from_start=rospy.Duration(2)) trajectory = JointTrajectory...
This function places a specified object in a simulated environment by generating collision objects, adjusting their positions based on object dimensions, maneuvering a robotic arm to a safe placement position, detaching the object, and clearing collision objects. It handles object detection, arm movement, gripper contr...
def place_pipeline(obj_id): collision_cylinders = {blue_object: "blue_cylinder", green_object: "green_cylinder", red_object: "red_cylinder"} # links names links_tag = {blue_object: "tag_1", green_object: "tag_2", red_object: "tag_3"} # generate collision ob...
def abort(msg): rospy.logerr(msg) action_server.set_aborted(MoveResult(msg)) def move_to_pick(obj_id): # # Get picking poses from parameter server blue_object_pick = rospy.get_param('/blue_object_pick') green_object_pick = rospy.get_param('/green_object_pick') red_object_pick = rospy.get_par...
The main task of the code is to handle object movement requests by validating the target object's ID and status. If valid, it executes 'pick' or 'place' actions using corresponding functions; otherwise, it aborts with error messages for invalid IDs or unimplemented statuses.
def main_cb(req): obj_id = req.goal_id obj_status = req.status # Check valid objects only if obj_id not in [blue_object, green_object, red_object]: abort("Target {"+str(obj_id)+"} not valid") return if obj_status == pick_status: move_to_pick(obj_id) elif obj_stat...
def load(image_file): image = tf.io.read_file(image_file) image = tf.image.decode_jpeg(image) w = tf.shape(image)[1] w = w // 2 input_image = image[:, :w, :] real_image = image[:, w:, :] input_image = tf.cast(input_image, tf.float32) real_image = tf.cast(real_image, tf.float32) r...
The code processes training images by loading input and real images, applying random jittering for data augmentation, normalizing pixel values, and returning the processed images for training a neural network.
def load_image_train(image_file): input_image, real_image = load(image_file) input_image, real_image = random_jitter(input_image, real_image) input_image, real_image = normalize(input_image, real_image) return input_image, real_image
def load(image_file): image = tf.io.read_file(image_file) image = tf.image.decode_jpeg(image) w = tf.shape(image)[1] w = w // 2 input_image = image[:, :w, :] real_image = image[:, w:, :] input_image = tf.cast(input_image, tf.float32) real_image = tf.cast(real_image, tf.float32) r...
The function `load_image_train` processes an input image file by loading it, applying random jittering for data augmentation, normalizing the images, and returning the processed input and real images for training. It prepares images for machine learning models by enhancing variability and ensuring proper scaling.
def load_image_train(image_file): input_image, real_image = load(image_file) input_image, real_image = random_jitter(input_image, real_image) input_image, real_image = normalize(input_image, real_image) return input_image, real_image
def get_available_gpus(): local_device_protos = device_lib.list_local_devices() return [x.name for x in local_device_protos if x.device_type == 'GPU'] def fit(train_ds, epochs, test_ds): ssim_arr = [] mse_arr = [] ssim_arr2 = [] mse_arr2 = [] for epoch in range(epochs): start = time....
The code trains a Generative Adversarial Network (GAN) to generate images. It loads and preprocesses training/test datasets, initializes generator and discriminator models, configures Adam optimizers, sets up checkpointing for model saving, and executes training for specified epochs. The generator creates images, while...
def generate_hand(): print(f'Hi beautiful {"Ioana"}') print(get_available_gpus()) global generator, discriminator, generator_optimizer, discriminator_optimizer, checkpoint, checkpoint_prefix #inp, re = load(image_path + "/0.jpg") '''plt.figure() plt.imshow(inp) plt.figure() plt.imshow(r...
def getSymbolList(self): r = requests.get('https://www.binance.com/gateway-api/v1/public/asset/asset/get-all-asset').json()['data'] symbols = {} for asset in r: if 'UP' not in asset['assetCode'] and 'DOWN' not in asset['assetCode'] and asset['trading'] and not asset['...
The function processes incoming news data by extracting relevant cryptocurrency symbols, modifying title/en content, updating UI elements (title, body, link, coin buttons), and sending Pushover notifications if "XRP" or "RIPPLE" are detected. It prioritizes dynamic coin identification from multiple data sources and han...
def update_news(self, new_data): if not new_data: return symbol_data = self.getSymbolList() symbols = symbol_data['symbols'] names = symbol_data['names'] found_symbols_and_names = list(set(self.find_symbols_and_names(new_data, symbols, names))) coin = ', '.j...
def getBordersMaskImages(images): (borders, maskCase, quadColors) = extractStartingScreen(images[0]) endOfStartingSequence = findEndOfStartingSequence(images, borders, quadColors[0], quadColors[1]) images = images[endOfStartingSequence:] images = images[timingInterpolationStart::timingInterpolationJu...
The function decodes a message from images by extracting quadrants, sorting them, converting color sequences to letters using an alphabet, handling padding, and trimming unnecessary parts to retrieve the decoded message.
def decodeImage(images, alphabetLength, coding, v_part, h_part): quadSize = v_part * h_part # Get borders needed to extract visible quads, the mask type (maskCase) # and the images without the starting sequence. (i.e. the image set # where the first screen contains the alphabet) (borders, maskCase,...
def Deal(self): for p in range(self.players): card_index = rand.randrange(0,len(self.deck)) self.player_hands[p] = self.player_hands[p] + self.deck[card_index] self.deck.remove(self.deck[card_index]) card_index = rand.randrange(0,len(self.deck)) self.dealer_ha...
This code implements a card game where players set initial bets, take turns hitting/standing, and compare scores against the dealer. It manages player funds, enforces betting rules, handles game progression, and removes players with insufficient funds. The loop continues until all players leave or the deck is reshuffle...
def Game(self): self.turn = 0 while self.turn < self.players: self.player_pot[self.turn] = input(f"Player {self.turn+1}: How much money would you like to start with? ") try: self.player_pot[self.turn] = float(self.player_pot[self.turn]) self.turn ...
def get_system_names() -> List[Path]: """Get system directory paths from stdin. Returns ------- List[Path] list of system directories paths """ dirs = input("Enter system path(s) (seperated by space, wild card supported): \n") system_dirs = [] for dir_str in dirs.split(): ...
The main task of the code is to automatically generate a configuration file (JSON or YAML) containing system-specific parameters like cutoffs, batch sizes, and decay settings. It collects system data, computes optimal values using helper functions, and writes them to the specified output file, validating the file type ...
def config(*, output: str, **kwargs): """Auto config file generator. Parameters ---------- output: str file to write config file Raises ------ RuntimeError if user does not input any systems ValueError if output file is of wrong type """ all_sys = get_sy...
def _filter( self, inputs, type_input, natoms, type_embedding = None, activation_fn=tf.nn.tanh, stddev=1.0, bavg=0.0, name='linear', reuse=None, trainable = True, #cjx mod ...
This function processes input tensors through a filter operation, splitting data by atom types (if applicable) and applying type-specific transformations. It reshapes inputs, applies the `_filter` method to generate output layers and rotation matrices (qmat), and concatenates results. The function handles cases with an...
def _pass_filter(self, inputs, atype, natoms, natoms_banidx, #cjxmod input_dict, reuse = None, suffix = '', trainable = True) : if input_dict ...
def get_classes(args): """ Get classes for dataset, model, training func, and eval func """ task, model = args.task, args.model_name_or_path if task.lower() == "generation": gen_task = args.dataset_args["gen_task"] if gen_task.lower() == "seq2seq_lm": return ResponseGenerationDat...
The code defines a `main()` function for training/evaluating models (detection, selection, or generation tasks) using Hugging Face transformers. It parses command-line arguments, loads configuration from a JSON file, initializes models/tokenizers, and handles PEFT (parameter-efficient fine-tuning). If `--eval_only` is ...
def main(): parser = argparse.ArgumentParser() # Required parameters parser.add_argument("--params_file", type=str, help="JSON configuration file") parser.add_argument("--model_name_or_path", type=str, help="model_name_or_path") parser.add_argument("--gen_task", type=str, choices=("causal_lm", "seq...
def _rank_by_chain_prob(words: Tuple[str, ...]) -> Tuple[str, ...]: word_set = set(words) probs = {w: _word_prob(w, words) for w in word_set} return tuple(w for w in sorted(word_set, key=lambda w: -probs[w])) def _rank_by_average_split(words: Tuple[str, ...]) -> Tuple[str, ...]: avg_words = {w: _avg_wor...
The function `_rank_by_win_percentage` ranks input words based on their win percentage, selecting an algorithm depending on the number of words: chain probability for large sets (>128), average split for medium sets (16–128), and exhaustive search for small sets (≤16). This ensures efficient ranking by adapting to inpu...
def _rank_by_win_percentage(words: Tuple[str, ...]) -> Tuple[str, ...]: if len(words) > 128: return _rank_by_chain_prob(words) elif len(words) > 16: return _rank_by_average_split(words) else: return _rank_by_exhaustive_search(words)
def _rank_by_win_percentage(words: Tuple[str, ...]) -> Tuple[str, ...]: if len(words) > 128: return _rank_by_chain_prob(words) elif len(words) > 16: return _rank_by_average_split(words) else: return _rank_by_exhaustive_search(words) def _rank_by_turns_to_win(words: Tuple[str, ...]) -...
This code recommends a word and alternative options based on a specified mode. It checks if the word list is complete, applies sorting logic according to the mode (e.g., win percentage, probability), and returns the top-ranked word along with up to `max_alternatives` substitutes. If no words are available, it returns `...
def recommend(self, max_alternatives: int = 5) -> WordRecommendations: if len(self.words) == len(load_words()): if self.mode == "win-percentage": return WordRecommendations( recommended="ralph", alternatives=["blast", "plush"], ...
def drive(self): if self.proportional is None: self.twist.omega = 0 self.last_error = 0 else: # P Term P = -self.proportional * self.P # D Term d_error = (self.proportional - self.last_error) / (rospy.get_time() - self.la...
The code navigates a Duckiebot through a town, driving until it detects a stop line, broken bot, or blue signal. Upon stopping, it parks if at a parking lot or performs turns based on detected signs. It resumes movement after stopping, adjusting for obstacles or signals, ensuring safe navigation and parking operations.
def traverse_town(self): global STOP_RED, STOP_BLUE, STOP_BROKEN rate = rospy.Rate(8) # 8hz while not rospy.is_shutdown(): # Continue driving until stopline, or broken bot while not STOP_RED and not STOP_BLUE and not STOP_BROKEN: self.drive...
def clean_train_data(self, df): col = df.iloc[:,11] df.iloc[:,11].replace(to_replace = "?", value = col.mode()[0], inplace=True) return df def train_validation_split(self, df): dataLen=int(0.9*df.shape[0]) # dataLen=df.shape[0]-60 return df.iloc[0:dataLen, :], df.iloc[dat...
This code prepares training and validation datasets by reading, cleaning, splitting data, and extracting features/labels. It sets up parameters for a k-NN algorithm (with k=5) but does not execute training or evaluation, as the core loop for k-values is commented out. The main task is data preprocessing and configurati...
def train(self, train_file_name): df = pd.read_csv(train_file_name)[:] df = self.clean_train_data(df) self.train_df, validation_df = self.train_validation_split(df) global label_of_train_data label_of_train_data = self.train_df.iloc[:,:1].to_numpy() self.train_df = self...
def set_robot(self, position): self.__robot = position def set_reward(self, reward): self.total_reward = reward def __view_update(self, mode="human"): if not self.__game_over: # update the robot's position self.__draw_path() self.draw_shortest_path() ...
This code updates the game state by setting the robot's position, marking its path, applying rewards, updating the game view, and triggering controller logic. It handles errors by terminating the game if exceptions occur during execution.
def update(self, mode="human", position=None, total_reward=0): try: self.set_robot(position) if position is not None else None self.path_matrix[self.robot[0], self.robot[1]] = 1 self.set_reward(total_reward) self.__view_update(mode) return self.__contr...
def all_walls_intact(cls, cell): return cell & 0xF == 0 def __break_walls(cls, cell, dirs): if "N" in dirs: cell |= 0x1 if "E" in dirs: cell |= 0x2 if "S" in dirs: cell |= 0x4 if "W" in dirs: cell |= 0x8 return cell def __ge...
This code generates a maze using a depth-first search algorithm, connecting cells by breaking walls between them to ensure full connectivity. It starts at a random cell, explores unvisited neighbors, and uses a stack to backtrack when necessary. After generating the maze, it optionally introduces loops and portals for ...
def _generate_maze(self): # list of all cell locations self.maze_cells = np.zeros(self.maze_size, dtype=int) # Initializing constants and variables needed for maze generation current_cell = (random.randint(0, self.MAZE_W-1), random.randint(0, self.MAZE_H-1)) num_cells_visited =...
def scrape_instagram_impl(handle: str, instagram_account_id: str, session: Session): medias = [] try: cl = None user_info = None try: cl, user_info, login_account = scrape_instagram_init(handle) # Check if cancelled via the magic of triple tap session = Session.objects.get(pk=session.pk) if sess...
The code scrapes Instagram posts for a given account, synthesizes audio from captions, and plays them with intermissions. It handles timeouts, user interruptions, and media selection based on timing and caption length, updating the session state and audio stream end time accordingly.
def scrape_instagram(instagram_account_id, session, handle): logger.info("scrape_instagram") t_global = Timer() t_global.start("Entire script", False) utils.send_frontend_message({ 'type': 'LOAD' }) utils.send_audio_message({ 'type': 'LOAD' }) # Start the instagram task. This will run as a second task i...
def testGetCallingCodes(): assert getCallingCodes("(080)62164823") == "(080)" assert getCallingCodes("(0821)3602212") == "(0821)" assert getCallingCodes("(04344)322628") == "(04344)" assert getCallingCodes("1408371942") == "140" assert getCallingCodes("78130 00821") == "7813" assert getCallingCo...
The code defines a function `testAll()` that executes three test functions: `testGetCallingCodes()`, `testIsBangaloreCallingCode()`, and `testGetBangaloreCallDetails()`. Its main task is to run a suite of unit tests to validate functionalities related to retrieving and verifying phone calling codes, specifically checki...
def testAll(): testGetCallingCodes() testIsBangaloreCallingCode() testGetBangaloreCallDetails()
def default(val, d): if exists(val): return val return (d() if isfunction(d) else d) def Downsample(dim, dim_out=None): return nn.Conv(dim, default(dim_out, dim), 4, stride=2, padding=1) def Upsample(dim, dim_out=None): return nn.Sequential(nn.Upsample(scale_factor=2, mode='nearest'), nn.Conv(di...
This code defines a UNet-like neural network architecture with time conditioning. It initializes convolutional layers, residual blocks, attention mechanisms, and downsampling/upsampling paths. The model processes input channels through multiple resolutions, applies time embeddings via sinusoidal positional encoding, an...
def __init__(self, dim, init_dim=None, out_dim=None, dim_mults=(1, 2, 4, 8), channels=3, resnet_block_groups=8, learned_variance=False, learned_sinusoidal_cond=False, learned_sinusoidal_dim=16): super().__init__() self.channels = channels init_dim = default(init_dim, dim) self.init_conv ...
def default(val, d): if exists(val): return val return (d() if isfunction(d) else d) def q_sample(self, x_start, t, noise=None): noise = default(noise, (lambda : jt.randn_like(x_start))) return ((extract(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start) + (extract(self.sqrt_one_minu...
The main task of the code is to compute the loss for a diffusion model. It generates noisy samples at time step t, predicts either noise or original data (x0) via the model, compares predictions to targets, applies a weighted loss function, and returns the average loss across the batch. The objective determines whether...
def p_losses(self, x_start, t, noise=None): (b, c, h, w) = x_start.shape noise = default(noise, (lambda : jt.randn_like(x_start))) x = self.q_sample(x_start=x_start, t=t, noise=noise) model_out = self.model(x, t) if (self.objective == 'pred_noise'): target = noise ...
def model_predictions(self, x, t): t = t.float32() model_output = self.model(x, t) if (self.objective == 'pred_noise'): pred_noise = model_output x_start = self.predict_start_from_noise(x, t, model_output) elif (self.objective == 'pred_x0'): pred_noise...
The code computes the mean and variance for the denoising process in a diffusion model. It predicts the initial state (x_start), clips it if specified, and calculates posterior distribution parameters (model_mean, posterior_variance, posterior_log_variance) using the predicted x_start, current state (x_t), and time ste...
def p_mean_variance(self, x, t, clip_denoised: bool): preds = self.model_predictions(x, t) x_start = preds.pred_x_start if clip_denoised: #x_start.assign(x_start.clamp((- 1.0), 1.0)) assign_keep_grad(x_start, x_start.clamp((- 1.0), 1.0)) (model_mean, posterior_var...
def model_predictions(self, x, t): t = t.float32() model_output = self.model(x, t) if (self.objective == 'pred_noise'): pred_noise = model_output x_start = self.predict_start_from_noise(x, t, model_output) elif (self.objective == 'pred_x0'): pred_noise...
This code implements the DDIM sampling method to generate images by iteratively denoising a random noise tensor. It uses predefined time steps, model predictions for noise and initial image, and mathematical operations involving alphas and sigma to refine the image at each step. The process reverses diffusion steps, ap...
def ddim_sample(self, shape, clip_denoised=True): (batch, total_timesteps, sampling_timesteps, eta, objective) = (shape[0], self.num_timesteps, self.sampling_timesteps, self.ddim_sampling_eta, self.objective) times = jt.linspace(0.0, total_timesteps, steps=(sampling_timesteps + 2))[:(- 1)] times...
def default(val, d): if exists(val): return val return (d() if isfunction(d) else d) def q_sample(self, x_start, t, noise=None): noise = default(noise, (lambda : jt.randn_like(x_start))) return ((extract(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start) + (extract(self.sqrt_one_minu...
This function interpolates between two input tensors x1 and x2 by combining their noisy versions at time step t using a weighted average (controlled by lam). It then reverses the diffusion process through iterative denoising steps from t to 0, producing a refined interpolated image.
def interpolate(self, x1, x2, t=None, lam=0.5): (b, *_) = x1.shape t = default(t, (self.num_timesteps - 1)) assert (x1.shape == x2.shape) t_batched = jt.stack(([jt.Var(t)] * b)) (xt1, xt2) = map((lambda x: self.q_sample(x, t=t_batched)), (x1, x2)) img = (((1 - lam) * xt1)...
def rho(E, Delta): if E <= Delta: return 0 return E / np.sqrt(E**2 - Delta**2) def I_qp(E, Ep, Delta, B, N, f): if E+Ep-Delta >= N: return 2*B*(-rho(E-Ep, Delta)*(1+Delta**2/(E*(E-Ep)))*(f[E-Delta]-f[E-Ep-Delta])) elif E-Ep-Delta < 0: return 2*B*(rho(E+Ep, Delta)*(1+Delta**2/(E*...
The code computes the Jacobian matrix element $ J_{ij} $ for a physical system, incorporating terms involving energy differences ($ \Omega $), occupation numbers ($ f, n $), and relaxation parameters ($ \tau_0, \tau_{\text{ph}}, \tau_l $). It accumulates contributions from direct and indirect transitions, weighted by f...
def Jacobian(i, j, N, alpha, Ep, Delta, tau0, Tc, N0, tau0_ph, tau_l, Tb): result = 0 f = alpha[:N] B = alpha[N] n = alpha[N+1:2*N+1] kb = 8.617333262145e-5 * 1e6 if i < N: if j == i: for k in range(N): Omega = k+1 if i+Omega < N: ...
def load_dependencies(self, dep_filename): """ Dependencies file has the following format for each line: source, destination, size (temporarily remove shape) Use source layer name as the name of the data Update Layer's dependencies and next lists """ df_list =...
The code initializes a system to optimize layer-to-device assignment in a distributed computing environment, minimizing execution time while respecting constraints like bandwidth, dependencies, and partitions. It iterates through all possible device combinations for layers, simulates performance, and identifies the opt...
def __init__(self, dep_filename, prof_filenames, bandwidth=200, device_names=None, priority_filename=None, partition_filename=None, ignore_latency=False, detailed=False, ...
def check_winner(self, player): for row in range(3): if all(self.buttons[row][col]["text"] == player for col in range(3)): return player for col in range(3): if all(self.buttons[row][col]["text"] == player for row in range(3)): return player ...
The function `make_move` handles a player's turn in a tic-tac-toe game by placing an "X" at the specified grid position if it's empty. It checks for a win or draw, updates the game state, and switches to the AI player ("O") if the game continues. The AI's move is triggered via `ai_move()` to complete the turn.
def make_move(self, row, col): if self.buttons[row][col]["text"] == "" and self.current_player == "X": self.buttons[row][col]["text"] = "X" if self.check_winner("X"): self.end_game("X wins!") elif self.check_draw(): self.end_game("It's a draw!"...
def construct_graph_from_file(filename, geoid_col=None, cols_to_add=None): """Constucts initial graph from either json(networkx adjacency_graph format) file or from a shapefile NOTE: at this point only supports the following 2 file formats: - ESRI shapefile - networkx.readwrite.json_data serialized...
This function constructs a networkx graph from diverse data sources by selecting the appropriate constructor based on the specified data type. It accepts parameters like data_source, geoid_col, data_cols, and data_source_type, routing to methods such as file, JSON, or DataFrame processing. The goal is to generate a gra...
def construct_graph(data_source, geoid_col=None, data_cols=None, data_source_type="filename"): """Constructs initial graph using the graph constructor that best matches the data_source and dataType formats :data_source: data from which to create graph (file name, graph object, json, etc) :geoid_col: na...
def eval(data1,model,selectmodel,args,always_update=False, record_iter_steps=None): print('evaluation starts.') batch=args.eval_batch_size iter_step=args.iter_step_eval beta=args.beta K_means_step=args.K_means_step multiple=batch select=selectmodel K=round(data1[0]['loc'].shap...
The code trains a neural network model (`model`) and a selection model (`selectmodel`) using stochastic gradient descent (SGD) with learning rates `lr1` and `lr2`. It iteratively optimizes the model on generated data batches, evaluates validation costs, and updates a fixed model (`fixed_model`) only when validation per...
def train(model,fixed_model,selectmodel,fixed_selectmodel,args,val_dataset): seed=torch.random.get_rng_state() torch.manual_seed(args.seed) costs,_=eval(val_dataset,fixed_model,fixed_selectmodel,args,always_update=False) torch.random.set_rng_state(seed) print('epoch 0, val_cost=',costs.mean()) ...
def inference(self, x): """Make prediction on input x. Args: x (tf.placeholder): Input batch. Returns: y_predict (tf.Variable): Prediction. """ tf.summary.image('input', x, 1) layer = conv_layer(x, 1, 8, 'conv1') layer = conv_layer(laye...
This code initializes a TensorFlow model with placeholders for input data and labels, defines the neural network architecture via `inference`, computes loss, sets up an optimizer, and configures evaluation metrics like accuracy. It also prepares summaries for monitoring and a saver for model checkpoints, enabling train...
def __init__(self, base_learning_rate, train_size): self.base_learning_rate = base_learning_rate self.batch_step = tf.Variable(0, dtype=tf.float32) self.train_size = train_size self.x = tf.placeholder(tf.float32, [None, HEIGHT, WIDTH, 1], name='x') self.y = tf.placeholder(tf.flo...
def reset(self): if self.fiducialPlacementToggle.placeModeEnabled: self.fiducialPlacementToggle.setPlaceModeEnabled(False) if not self.editButton.isEnabled(): self.editButton.setEnabled(True) if self.segmentModel: if self.segmentModel.GetScene(): slicer.mrmlScene.RemoveNode(self....
The main task of the code is to deactivate an effect by saving the current segmentation points to prevent data loss, resetting the editor's state, stopping segmentation observation, and disconnecting the segment editor node. This ensures the user's work is preserved while disabling the effect's active functionality.
def deactivate(self): # Save points when the effect is deactivated to prevent the user from losing his work self.pointsBeingEdited = self.logic.getPointsAsString(self.segmentMarkupNode) self.reset() self.observeSegmentation(False) self.setAndObserveSegmentEditorNode(None)
def createNewModelNode(self): if self.segmentModel is None: self.segmentModel = slicer.mrmlScene.AddNewNodeByClass("vtkMRMLModelNode") self.segmentModel.SetSaveWithScene(False) # prevent temporary node from being saved into the scene self.segmentModel.SetName("SegmentEditorDrawTubeModel") ...
The code initializes segmentation tools by creating model and markup nodes if they don't exist, configures fiducial placement settings, links the editor to the parameter set, observes segmentation changes, updates the GUI, and applies pre-edited points to the markup node for interactive 3D segmentation in a medical ima...
def activate(self): self.scriptedEffect.showEffectCursorInSliceView = False # Create model node prior to markup node to display markups over the model if not self.segmentModel: self.createNewModelNode() # Create empty markup fiducial node if not self.segmentMarkupNode: self.createNewMark...
def reset(self): if self.fiducialPlacementToggle.placeModeEnabled: self.fiducialPlacementToggle.setPlaceModeEnabled(False) if not self.editButton.isEnabled(): self.editButton.setEnabled(True) if self.segmentModel: if self.segmentModel.GetScene(): slicer.mrmlScene.RemoveNode(self....
The main task of the code is to synchronize the model's display color with the edited segment's color in a 3D segmentation tool. It checks if the edit button is disabled and control points exist, then resets and creates new model/markup nodes. If a segment model exists, it retrieves the segment's color from the segment...
def onSegmentModified(self, caller, event): if not self.editButton.isEnabled() and self.segmentMarkupNode.GetNumberOfControlPoints() != 0: self.reset() # Create model node prior to markup node for display order self.createNewModelNode() self.createNewMarkupNode() self.fiducialPlacement...
def reset(self): if self.fiducialPlacementToggle.placeModeEnabled: self.fiducialPlacementToggle.setPlaceModeEnabled(False) if not self.editButton.isEnabled(): self.editButton.setEnabled(True) if self.segmentModel: if self.segmentModel.GetScene(): slicer.mrmlScene.RemoveNode(self....
The `onCancel` method resets the current state, creates a model node followed by a markup node to ensure correct display order, and sets the markup node as the current selection in a UI toggle element for fiducial placement.
def onCancel(self): self.reset() # Create model node prior to markup node for display order self.createNewModelNode() self.createNewMarkupNode() self.fiducialPlacementToggle.setCurrentNode(self.segmentMarkupNode)
def getNumberOfDefinedControlPoints(self): count = 0 if self.segmentMarkupNode: if slicer.app.majorVersion >= 5 or (slicer.app.majorVersion == 4 and slicer.app.minorVersion >= 11): count = self.segmentMarkupNode.GetNumberOfDefinedControlPoints() else: count = self.segmentMarkupNode.G...
The main task of the code is to apply a segmentation operation by cutting a surface model using defined control points. It checks for at least two control points, saves the state for undo, performs the cut operation, resets the state, creates new model and markup nodes, and restores the display order. The process inclu...
def onApply(self): if self.getNumberOfDefinedControlPoints() < 2: logging.warning("Cannot apply, segment markup node has less than 2 control points") return # Allow users revert to this state by clicking Undo self.scriptedEffect.saveStateForUndo() # This can be a long operation - indicate ...
def add_placeholders(self): self.user_A = tf.placeholder(tf.int32) self.item_A = tf.placeholder(tf.int32) self.rate_A = tf.placeholder(tf.float32) self.drop_A = tf.placeholder(tf.float32) self.user_B = tf.placeholder(tf.int32) self.item_B = tf.placeholder(tf.int32) ...
This code initializes a machine learning model for recommendation systems by loading pre-trained Node2Vec and Doc2Vec embeddings, preparing datasets, configuring hyperparameters (layers, regularization, learning rate), setting up training components (placeholders, loss functions, optimizers), and preparing evaluation m...
def __init__(self, args): self.dataName_A = args.dataName_A self.dataName_B = args.dataName_B self.KSize = args.KSize self.model_N2V_A = KeyedVectors.load_word2vec_format( "Node2vec_" + self.dataName_A + "_KSize_" + str(self.KSize) + ".emb", binary=False) self.model_...
def show(interface: str = 'all', *, raw: bool = False, json: bool = False, _wg: str = WG): """Yields status information.""" if interface == 'all': text = check_output((_wg, 'show', 'all'), text=True).strip() return parse_interfaces(text, raw=raw, json=json) if interface == 'interf...
This function removes all peers from a specified WireGuard interface or all interfaces. If 'all' is specified, it recursively clears peers from every interface. For a single interface, it retrieves existing peers, marks them for removal, and applies the change. The operation uses helper functions to inspect current con...
def clear_peers(interface: str, *, _wg: str = WG): """Removes all peers from the selected interface or all interfaces.""" if interface == 'interfaces': raise ValueError('Invalid interface name:', interface) if interface == 'all': for interface in show('interfaces', _wg=_wg): # pylint: dis...
def oneword(self, string): return Counter(self.lookup_dict[string]).most_common()[:3] def twowords(self, string): suggest = Counter(self.lookup_dict[tuple(string)]).most_common()[:3] if len(suggest) == 0: return self.oneword(string[-1]) return suggest def threewords(self, str...
The code generates predictions based on the number of words in the input string. It splits the string into tokens and uses different methods (`oneword`, `twowords`, etc.) to process 1, 2, 3, or more words, appending results to `prediction_list`, which is returned.
def predictions(self, string): if len(self.lookup_dict) > 0: tokens = string.split(" ") if len(tokens) == 1: predictions = self.oneword(string.split(" ")) for prediction in predictions: self.prediction_list.append(prediction[0]) ...
def _validate_config(config: dict): if 'general' not in config: raise ValueError("Config must have a 'general' section") if 'sheet' not in config: raise ValueError("Config must have at least one 'sheet' section") if 'source' not in config['general']: raise ValueError("Config must h...
The code generates a report by loading and validating a configuration file, reading associated data from a JSON source, loading a glossary, and executing the generation process with the configured data and settings.
def generate_from_files(config_file: Union[str, PathLike]): """Generate the report using the data and configuration in the given files.""" config = toml.loads(Path(config_file).read_text('utf-8')) _validate_config(config) data = json.loads(Path(config['general']['source']).read_text('utf-8')) load_...
def multi_bootstrap(data, boots): """ Keyword arguments: data -- numpy multi-dimentional array boot -- number of bootstraps """ designs = data.shape[0] to_return = np.empty((designs, boots)) for design in range(designs): to_return[design:design+1] = bootstrap(data[design], bo...
The function `quality_bootstrap` identifies systems within a specified tolerance of the best system's performance across a majority of bootstrap samples. It calculates differences between each feasible system and the best system, generates bootstrap datasets, and filters systems that meet the tolerance threshold in at ...
def quality_bootstrap(feasible_systems, headers, best_system_index, x=0.1, y=0.95, nboots=1000, cores='s'): """ 1. Create differences of systems from best system 2. Create nboots bootstrap datasets of the differences 3. Return a DataFrame with all systems that are x% of feas...
def question_to_query_examples(similar_questions): similar_questions_str = '' if len(similar_questions) > 0: similar_questions_str = "[Good SQL Examples]:\n" for similar_question in similar_questions: similar_questions_str += "- Question:\n" + similar_question['question'] + "\n-SQL Query:\n" + full_cl...
The function generates a BigQuery SQL query to answer a given question using either a fast model (if similar questions exist) or a fine-tuned model. It constructs a prompt with guidelines, table schemas, and similar questions, then uses the selected model to generate and clean the SQL query for accurate execution.
def gen_dyn_rag_sql(question,table_result_joined, similar_questions): similar_questions_str = question_to_query_examples(similar_questions) # If no similar question found, use more performant model to generate SQL Query (yet much slower) if fast := (len(similar_questions) > 0): logger.info("Similar question...
def add_iteration(self, sql, errors): self.iterations_history.append({ 'sql': sql.replace('\n', ' '), 'errors': errors.replace('\n', '') }) def question_to_query_examples(similar_questions): similar_questions_str = '' if len(similar_questions) > 0: similar_questions_str = "[Good SQL Examples...
The function `get_corrected_sql` generates a corrected SQL query by analyzing syntax/semantic errors from BigQuery and a validator. It constructs a prompt with guidelines, table schema, forbidden queries, and error context, then uses a model to produce a valid SQL query that addresses the original question while adheri...
def get_corrected_sql(self, sql: str, bq_error_msg: str, validation_error_msg: str) -> str: logger.info("Sending prompt...") error_msg = ('- Syntax error returned from BigQuery: ' + bq_error_msg + '\n ' if bq_error_msg != None else '') + ('- Semantics errors returned from SQL Validator: ' + validation_error_ms...
def write_json_regressions(self, url): self.regressions.sort(key=lambda x: (x.stacktrace, x.slack_report_name)) if self.regressions.__len__() > 0: regression_fields = [] group_by_stacktrace = {} for regression in self.regressions: if regression.stack...
The code generates a Slack report for a test run, determining the platform logo, creating a footer with environment/branch info, and structuring message attachments based on test outcomes. It returns a JSON object with test stats, issues, and metadata for Slack notification, using different colors/statuses for success/...
def build_report(self, test_run, slack_channel, minutes, url): if test_run.platform == "android": message_logo = android_logo elif test_run.platform == "ios": message_logo = ios_logo else: message_logo = web_logo footer_text = "Environment - %s | Bra...
def conflicts(var, val, assignment, neighbours): def conflict(var2): return var2 in assignment and not kakuro_constraint(var, val, var2, assignment[var2]) # count = 0 # for v in neighbours[var]: # if conflict(v) == True: # count += 1 # return count return count(conflict(v...
This function performs backtracking search for a constraint satisfaction problem, selecting variables from 'rem' and assigning values while checking for conflicts. It uses MAC (Maintaining Arc Consistency) to prune domains, recursively explores assignments, and backtracks by restoring domains if no solution is found.
def backtrack(assignment, original_variables, constraints, key_map, neighbours, domains, rem): if len(assignment) == len(original_variables): return assignment var = rem.pop() copy = domains.copy() for value in domains[var]: if 0 == conflicts(var, value, assignmen...
def check_panic_decode_trigger(self, line): # type: (bytes) -> None if self._decode_panic == PANIC_DECODE_DISABLE: return if self._reading_panic == PANIC_IDLE and re.search(PANIC_START, line.decode('ascii', errors='ignore')): self._reading_panic = PANIC_READING yell...
This function processes serial input data by splitting it into lines, handling partial lines across calls, checking for exit commands, panic triggers, and coredumps, and printing or buffering lines based on matching rules. It manages incomplete lines by deciding to print or buffer them, while also preserving partial PC...
def handle_serial_input(self, data, finalize_line=False): # type: (bytes, bool) -> None sp = data.split(b'\n') if self._last_line_part != b'': # add unprocessed part from previous "data" to the first line sp[0] = self._last_line_part + sp[0] self._last_line_pa...
def handle_commands(self, cmd, chip): # type: (int, str) -> None config = get_chip_config(chip) reset_delay = config['reset'] enter_boot_set = config['enter_boot_set'] enter_boot_unset = config['enter_boot_unset'] high = False low = True if cmd == CMD_STOP: ...
The main task of the code is to manage a loop that processes commands and serial input by reading from two queues (cmd_queue and event_queue), handling command execution, serial data transmission, and line-finalization timers. It continuously checks for incoming data, processes events like commands or key inputs, manag...
def main_loop(self): # type: () -> None self.console_reader.start() self.serial_reader.start() try: while self.console_reader.alive and self.serial_reader.alive: try: item = self.cmd_queue.get_nowait() except queue.Empty: ...
def set_color(data): color = (data["R"], data["G"], data["B"]) print(f"(Synthesis) Set color to:{color}") pygame.draw.rect(surface, color, pygame.Rect(0, 100, 500, 500)) pygame.display.flip() def measure_outcome(): time.sleep(0.4) print('(Characterisation) Measure RGB sample:') ser.write(b",...
The code generates up to 120 samples by iteratively running a strategy, each with random RGB colors, measuring outcomes, and storing results in a DataFrame. It initializes the first sample, then loops to create subsequent samples, appending them until the limit is reached, finally returning the collected data.
def run_strategy(s): samples = pd.DataFrame(columns=['R', 'G', 'B', 'outcome', 'time', 'ID']) set_color({key:np.random.randint(0,255) for key in ["R", "G", "B"] }) new_sample = measure_outcome() new_sample["ID"] = 0 print(new_sample) samples = pd.concat([samples, pd.DataFrame([new_sample])], ign...
def ID_note(): return generate_note(random_select).give_letter() def correct(): global SCORE global score_frame global random_select # when score frame is rebuilt, then it should rebuild with a point added on SCORE += 1 score_frame = Label(window, text="Score: {}\nMistakes: {}".format(SCORE,...
The code checks if the output of `ID_note()` matches the `correct_letter`. If they match, it executes the `correct()` function; otherwise, it runs the `wrong()` function. The main task is to determine whether a note's ID is correct and trigger appropriate actions based on the result.
def right_or_wrong(correct_letter): if ID_note() == correct_letter: # call correct function correct() else: # call wrong function wrong()
def get_now_epoch(): # @see https://www.linuxquestions.org/questions/programming-9/python-datetime-to-epoch-4175520007/#post5244109 return int(time.time()) def get_cookie_crumb(symbol): cookie, lines = get_page_data(symbol) crumb = split_crumb_store(find_crumb_store(lines)) return cookie, crumb def ...
The main task of the code is to download historical stock quotes for a given symbol by retrieving authentication credentials (cookie and crumb), then fetching data between a start date (set to 0) and the current epoch time. It uses `get_data` with parameters including the symbol, date range, and authentication tokens t...
def download_quotes(symbol): start_date = 0 end_date = get_now_epoch() cookie, crumb = get_cookie_crumb(symbol) get_data(symbol, start_date, end_date, cookie, crumb)
def dprint(*args): if DEBUG: print(*args) def get_workspace_datapoints(ws: dict, start_ts: float, end_ts: float) -> list[dict]: workspace_datapoints = [] workspace_id = ws["uuid"] metrics = metric_client.list_metrics(workspace_id) monitors = monitor_client.list_monitors(workspace_id) s...
The main task of the code is to export metric data from multiple workspaces into CSV files over a specified number of days. It calculates a time range, retrieves workspace data, processes each workspace's datapoints, and saves them with a timestamped filename. The function logs durations for each step, including total ...
def main(num_days: int = 1): main_start_ts = time.time() end_ts = arrow.utcnow().floor("day") start_ts = end_ts.shift(days=-num_days).timestamp() end_ts = end_ts.timestamp() dprint( f"start_ts={arrow.get(start_ts).format()}, end_ts={arrow.get(end_ts).format()}" ) workspaces = work...
def get_metric_info_map(self, sources, metrics): source_map = {source["metadata"]["uuid"]: source for source in sources} metric_info_map = {} for metric in metrics: if metric["config"]["configType"] not in [ "metricConfig", "fullTableMetricConfig", ...
The code retrieves Lightup's monitor, metric, and incident data for specified workspaces and sources, filters relevant configurations, maps monitor-metric relationships, counts ongoing incidents, and aggregates table-level insights into a structured dictionary for analysis.
def get_lightup_state( self, lightup_workspace_id, lightup_source_id, collibra_source_id ): """ Retrieves the lightup state by performing the following steps: 1. Get the list of workspaces. 2. For each workspace, retrieve the list of datasources with Collibra configuration. ...
def get_lightup_state( self, lightup_workspace_id, lightup_source_id, collibra_source_id ): """ Retrieves the lightup state by performing the following steps: 1. Get the list of workspaces. 2. For each workspace, retrieve the list of datasources with Collibra configuration. ...
This code synchronizes Lightup and Collibra systems by iterating through source mappings, fetching Collibra assets, deleting existing relations, updating Collibra with new assets from Lightup sources, and creating relations between Collibra sources and updated assets. It tracks metrics, manages asset deletions, and log...
def run(self): # for collibra source id in the mapping run the sync for each source id for cs in self.workspace_source_to_collibra_mapping["collibra_sources"]: # for each sync, get the lightup source id and collibra source id to match with the source id from the mapping and run the sync ...
def comment_to_str(comment_text: str, indentation: str) -> str: comment_text = comment_text.strip() if not comment_text: return "" lines = [line.strip() for line in comment_text.splitlines()] return "\n".join([f"{indentation}// {line}" for line in lines]) + "\n" def ts_type_to_str(type_node: Ty...
This function converts TypeScript declaration nodes into string representations. It handles interfaces and type aliases, formatting them with names, type parameters, base types, and members, while incorporating comments and adhering to TypeScript syntax.
def ts_declaration_to_str(declaration: TopLevelDeclarationNode) -> str: match declaration: case InterfaceDeclarationNode(name, type_parameters, comment, base_types, members): comment = comment_to_str(comment, "") type_param_str = f"<{', '.join([param.name for param in type_parameters...
def greedy(locations): completed = set() truck_path = [] last, cost = find_closest_unfulfilled_order(BASE, locations, completed) truck_path.append(last[0]) for i in range(len(locations)-1): last, c = find_closest_unfulfilled_order(last, locations, completed) truck_path.append(last[0]) cost += c return t...
The code optimizes a delivery route using a greedy algorithm followed by 2-opt improvement to minimize cost, then splits the optimized route into multiple truck tracks based on the given number of trucks. It measures and prints the execution time.
def schedule_q1(orders, number_trucks): start = time.time() #Transforming data given locations = {item[0]:[item[0], float(item[1]), float(item[2])] for item in orders} #get a route from greedy existing, best_cost = greedy(locations) #begin 2-opt to improve route improvement = True while improvement: r, c =...
def setup_sym_estimator(px, lmin, lmax, mlmax, cltot_X, cltot_Y, cltot_XY): """ Setup quadratic estimators for case of a pair of temperature maps X and Y. In particular, return 'qfuncs' for the two asymmetric estimators (i.e. Q[X,Y] and Q[Y,X]) and also the symmetrized es...
This code tests symmetric lensing estimators by simulating CMB and noise maps, computing lensing potentials via XY, YX, and symmetric estimators, then cross-correlating results with input kappa maps. It evaluates estimator accuracy through cross- and auto-power spectra, comparing outputs to true signals. Results are sa...
def test_signal(nsim=10, use_mpi=False, from_pkl=False): if use_mpi: from mpi4py import MPI comm = MPI.COMM_WORLD rank,size = comm.Get_rank(), comm.Get_size() else: comm = None rank,size = 0,1 if rank==0: outdir="sym_estimator_test_output" if not os.pa...
def setup_sym_estimator(px, lmin, lmax, mlmax, cltot_X, cltot_Y, cltot_XY): """ Setup quadratic estimators for case of a pair of temperature maps X and Y. In particular, return 'qfuncs' for the two asymmetric estimators (i.e. Q[X,Y] and Q[Y,X]) and also the symmetrized es...
The code tests the accuracy of a symmetric lensing estimator by generating Gaussian and foreground-only simulations, computing convergence maps using theoretical power spectra and noise models, and comparing the results' power spectra against expected theoretical noise levels (N0) to validate the estimator's performanc...
def test_N0(use_mpi=False, nsim=10, from_pkl=False): if use_mpi: from mpi4py import MPI comm = MPI.COMM_WORLD rank,size = comm.Get_rank(), comm.Get_size() else: comm = None rank,size = 0,1 if rank==0: outdir="sym_estimator_test_output" if not os.path.i...
def setup_sym_estimator(px, lmin, lmax, mlmax, cltot_X, cltot_Y, cltot_XY): """ Setup quadratic estimators for case of a pair of temperature maps X and Y. In particular, return 'qfuncs' for the two asymmetric estimators (i.e. Q[X,Y] and Q[Y,X]) and also the symmetrized es...
The code tests a symmetrized estimator for CMB secondary anisotropies by generating simulations with noise, foregrounds, and theoretical signals. It computes secondary signals using raw, Gaussian, and symmetric methods, compares their power spectra, and validates against theory. Results are saved, and plots show differ...
def test_sym_secondary(use_mpi=False, nsim=10, from_pkl=False): if use_mpi: from mpi4py import MPI comm = MPI.COMM_WORLD rank,size = comm.Get_rank(), comm.Get_size() else: comm = None rank,size = 0,1 if rank==0: outdir="sym_estimator_test_output" if no...
def game_over(self) -> bool: return False def show_board(self) -> None: os.system("cls") if self.compact: self.piece_repr('place') for i in range(len(self.board)): print('|', end='') for j in range(len(self.board[i])): if self.board[i][j] == '#'...
The main task of the code is to run a game loop that continuously checks if the game is over. If not, it appends a vertical movement event to the queue, displays the game board, pauses for 0.6 seconds, and executes queued events. This creates a cycle of automatic movement, rendering, and event processing until the game...
def main_loop(self) -> None: while not self.game_over(): self.event_queue.append('v') # automatic vertical movement self.show_board() time.sleep(0.6) self.execute_event_queue()
def show_board(self) -> None: os.system("cls") print(f"Score: {self.score}", end='\n\n') self.piece_repr('place') for i in range(len(self.board)): print('|', end=' ') for j in range(len(self.board[i])): if self.board[i][j] == '#' or self.board[i][j] == '@': ...
The main task of the code is to run a game loop that continuously processes events, updates the game state, renders the board, checks for completed lines, and manages the game over condition. The loop appends automatic vertical movement events, executes the event queue multiple times to handle game actions, introduces ...
def main_loop(self) -> None: while not self.game_over: self.event_queue.append('v') # automatic vertical movement self.show_board() self.execute_event_queue() # 1 time.sleep(self.speed) self.execute_event_queue() # 2 self.check_lines() self.execute_ev...
def getPageListingUrls(self, searchTerm, pageNumber, ifSold=False, ifCompleted=False, ifLowToHigh=False, ifHighToLow=False): url = self.getEbayUrl(searchTerm, pageNumber, ifSold, ifCompleted, ifLowToHigh, ifHighToLow) page = requests.get(url) soup = BeautifulSoup(page.content, 'html.parser') ...
The function `getAllAttributes` fetches product details (names, prices, shipping, URLs) from multiple pages using multithreading. It processes listings based on parameters like search term, category, and sorting, appending extracted data to a list. If `number_of_listings` is specified, it repeats extraction per page; o...
def getAllAttributes(self, searchTerm, categoryName, enableLots, pageNumber, number_of_listings=0, ifSold=False, ifCompleted=False, ifLowToHigh=False, ifHighToLow=False): links = self.getPageListingUrls(searchTerm, pageNumber, ifSold, ifCompleted, ifLowToHigh, ifHighToLow) all_attr = [] # Fetc...
def generate_signals(context, data): """ A function to define define the signal generation """ try: price_data = data.history(context.securities, ['high', 'low', 'open', 'close'], context.params['indicator_lookback'], context.params['indicator_freq']) except: ...
The function `run_strategy` executes a trading strategy when trading is enabled. It generates trading signals, calculates target asset positions, and rebalances the portfolio based on input data, forming the core logic for investment decisions and position adjustments in a quantitative trading system.
def run_strategy(context, data): """ A function to define core strategy steps """ if not context.trade: return generate_signals(context, data) generate_target_position(context, data) rebalance(context, data)
def non_deterministic_ints(shape, dtype=dtypes.int64): """Non-deterministically generates some integers. This op may use some OS-provided source of non-determinism (e.g. an RNG), so each execution will give different results. Args: shape: the shape of the result. dtype: (optional) the dtype of the res...
This code initializes a random number generator, either by copying an existing generator's state and algorithm or by creating a new one with specified or default algorithm and seed values. It sets up internal variables to store the generator's state and algorithm, handling cases where parameters are omitted by using de...
def __init__(self, copy_from=None, seed=None, algorithm=None): """Creates a generator. Args: copy_from: (optional) a generator to be copied from. seed: (optional) the seed for the RNG. If None, it will be chosen nondeterministically algorithm: (optional) the RNG algorithm. If None...
def report_state(w1, w2, b, train): """ Prints out the current state of the model """ # prints out the parameter states and the cost print("Parameters:") print("W1: ", w1, "\n", "W2: ", w2, "\n", "Bias: ", b, sep='') print("\nCost:", cost(w1, w2, b, train)) # pushes the input data th...
The function trains a single neuron using finite differences to approximate gradients, updating weights (w1, w2) and bias (b) via gradient descent over n iterations. It initializes parameters randomly, computes cost, estimates derivatives with small perturbations (eps), adjusts parameters to minimize cost, and tracks/v...
def finite_diff(train, n): """ Approximates the parameter values of a single neuron on the <train> data set. Uses finite differences approach for estimating the value of the derivative for each of parameters. Input: training data set, <n> - number of training iterations Output: trained state of...
def report_state(w1, w2, b, train): """ Prints out the current state of the model """ # prints out the parameter states and the cost print("Parameters:") print("W1: ", w1, "\n", "W2: ", w2, "\n", "Bias: ", b, sep='') print("\nCost:", cost(w1, w2, b, train)) # pushes the input data th...
This function performs gradient descent to train a single neuron's parameters (w1, w2, b) on a given dataset. It initializes weights and bias randomly, iterates n times to adjust parameters using partial derivatives of the cost function, and minimizes error via a learning rate. It tracks cost over iterations, reports i...
def gradient(train, n): """ Approximates the parameter values of a single neuron on the <train> data set. Uses partial derivative approach for estimating the value of the derivative for each of parameters. Input: training data set, <n> - number of training iterations Output: trained state of th...