dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def generateRandomTransaction(): txid, inputPrevTxid, inputPrevOutputIndex = generateTxid(), *generateInput() outputRecipientAddress, outputAmount = generateOutput() transactionFee = generateTransactionFee() return txid, inputPrevTxid, inputPrevOutputIndex, outputRecipientAddress, outputAmount, transact...
The code generates a random transaction, hashes its data with SHA-256, creates an ECDSA key pair, signs the hash with the private key, and verifies the signature using the public key. It outputs the public/private keys, hashed transaction data, digital signature, and verification result to demonstrate ECDSA signing and...
def main(): txid, inputPrevTxid, inputPrevOutputIndex, outputRecipientAddress, outputAmount, transactionFee = generateRandomTransaction() transactionDataAsMessage = concatenateString(txid, inputPrevTxid, inputPrevOutputIndex, outputRecipientAddress, outputAmount, transactionFee).encode() transactionDataAsMe...
def prepare_input_batch(para): """ :param xy, a, u_info: B x N x len_feature :return: """ xy, a, u_info = para a = a[:, :, 0] B, N = a.size(0), a.size(1) ''' node_attr: B x N x 11 ''' is_input = np.zeros((B, N)) is_output = np.zeros((B, N)) is_input[:, 0] = 1 is...
The main task of the code is to train a model to optimize circuit parameters for achieving a target frequency band. It iteratively computes predictions, calculates loss using a custom objective function, and updates parameters via backpropagation. The learning rate decreases periodically. If visualization is enabled, i...
def main(self, vis=False): iter_step = 20 num_iter = 10 total_step = iter_step * num_iter for it in range(num_iter): if (it + 1) % 5 == 0: self.lr *= 0.3 for step in range(iter_step): node_attr, edge_attr, adj = prepare_input_batch...
def load_environ() -> EnvironmentVariables: return EnvironmentVariables( **{k: os.environ[v] for k, v in {"dynamodb_table": "DYNAMODB_TABLE"}.items()} ) def get_parameters(ssm_client: SSMClient) -> Parameters: option = {"Path": "/GithubPrNotification/", "WithDecryption": True} logger.add_functio...
(The code retrieves environment variables, SSM parameters, and repository names from DynamoDB. It fetches GitHub notification targets, constructs a Slack message body, and posts it to a webhook URL if valid, facilitating automated notifications for repository updates.)
def main( ssm_client: SSMClient = boto3.client("ssm"), dynamodb_client: DynamoDBServiceResource = boto3.resource("dynamodb"), ): env = load_environ() params = get_parameters(ssm_client) repositories = get_repository_names(env.dynamodb_table, dynamodb_client) targets, target_id = get_notification...
def read_device(self): """read device database """ dr = {'var':{}, 'table':None} dr['var']['device'] = read_worksheet(self.device_filename, 'var') dr['table'] = self.merged_table_columns() self.device_details = dr['var']['device'] return dr def get_wkl(self): """get the work location (site code) deta...
The main task of the code is to initialize device data by reading device details, processing optional parameters (workload, region, region details), merging variables and region data, converting device tables to dictionaries, and structuring final data as a dictionary containing variables and transformed tables.
def read(self): """start executing """ self.dev_details = self.read_device() ## require self.wkl = self.get_wkl() ## optional remove after global file removed self.region = self.get_region() ## optional remove after global file removed all_region_details = self.read_region_details(...
def shapes(map, image, clearance, radius): clearance_radius = clearance+radius ##hexagon## hexagon_vertices = [[300,50],[365,88],[365,162],[300,200],[235,162],[235,88]] hexagon_vertices = np.array(hexagon_vertices) map = cv2.fillPoly(map, [hexagon_vertices], color=255) map = cv2.polylines(map, [...
The code implements a path-planning algorithm using A* to navigate a robot through a 2D grid map with obstacles. It initializes a map, collects free space coordinates, validates start/goal positions, and computes an optimal path considering robot clearance, radius, and orientation constraints. The path is visualized an...
def main(): map = np.zeros((250, 600)) image = np.zeros((250, 600,3), dtype=np.uint8) clearance = int(input("Enter the clearance value: ")) radius = int(input("Enter the robot radius: ")) step_size = int(input("Enter the step size: ")) img, map = shapes(map, image, clearance, radius) y,x = ...
def get_mipmap_length(mipmaps): return sum(len(mipmap_subcon.build(mipmap)) for mipmap in mipmaps) def get_upscaled_texture_db( package, obj, factor, db_filename, blur=4, grow=3, shrink=3, threshold=128, model_hash=None, ): palette_array = get_palette(obj, package) image_...
This function rescales textures in a game package's database by adjusting texture sizes, generating new mipmaps, and updating offsets/size values. It iterates through objects, applies scaling factors to textures, handles mipmap recalculations, and adjusts mesh positions. The process ensures texture data aligns with new...
def rescale_package_db( package, factor, db_filename, blur=4, grow=3, shrink=3, threshold=128, model_hash=None, ): """Rescales textures in a package from a source db""" offset = 0 for obj, header in zip(package.export_objects, package.export_headers): header.serial_of...
def get_palette(texture, construct): palette_prop = get_named_property(texture, "Palette") palette_obj = construct.export_objects[palette_prop.value.data.index - 1] palette_array = get_palette_array(palette_obj) return palette_array def get_image_array(obj, mipmap_index=0): img = obj.object.img_data...
The function `get_upscaled_texture` processes an object's texture by palettizing its image, upscaling it using a model, and applying a scaled mask. It retrieves palette and image data, generates a palettized image, upscales it, then applies a mask derived from the original image. The mask is scaled with parameters like...
def get_upscaled_texture( package, obj, model, device, factor, db_filename, blur=4, grow=3, shrink=3, threshold=128, model_hash=None, ): palette_array = get_palette(obj, package) image_array = get_image_array(obj) image = get_image(image_array, palette_array) ...
def get_mipmap_length(mipmaps): return sum(len(mipmap_subcon.build(mipmap)) for mipmap in mipmaps) def get_upscaled_texture( package, obj, model, device, factor, db_filename, blur=4, grow=3, shrink=3, threshold=128, model_hash=None, ): palette_array = get_palette(obj,...
This function rescales textures in a package by upsampling them, adjusting mipmap data, and updating offsets/sizes to maintain structural integrity. It processes each texture, calculates size changes, generates new mipmaps, updates object properties, and adjusts mesh positions. The function ensures the package remains ...
def rescale_package( package, model, device, factor, model_hash, db_filename=None, blur=4, grow=3, shrink=3, threshold=128, ): offset = 0 for obj, header in zip(package.export_objects, package.export_headers): header.serial_offset += offset obj.serial_offs...
def data_list(): return list(map(get_data, url_list())) def get_data(url): with urllib.request.urlopen(url) as url: data = json.loads(url.read().decode()) return data def next_page_url(page_token, key=enums.enums()._key): return 'https://maps.googleapis.com/maps/api/place/nearbysearch/json?paget...
The main task of the code is to recursively fetch all data by following 'next_page_token' values from each item, appending subsequent page data to the list until no more tokens remain, effectively paginating through a dataset.
def fetch_data(data=data_list()): for datum in data: next_page = data_helper.get_value(datum, 'next_page_token') while next_page is not None: next_page_datum = get_data(next_page_url(next_page)) data.append(next_page_datum) next_page = data_helper.get_val...
def plot_image_aps_or_a3daps(path): """ # Example plotting function: .aps or .a3daps file animation """ data = read_data(path) #np.save('E:/Kaggle_SavedData/Converta3d', data) # change fig = plt.figure(figsize = (16, 16)) ax = fig.add_subplot(1, 1, 1) def animate(i): im = ax.imshow(np.flipud(data[:, :, i...
The main task of the code is to convert 3D data files (e.g., .a3d, .aps) into MP4 animations using matplotlib's animation module. It processes input files, generates vertical/horizontal/depth slices for .a3d files, and saves them with specific naming conventions. The code also handles directory creation, file extension...
def main(): """ Main entry point for execution """ # Set up formatting for the movie files # Convert the data file from .a3d to .mp4 # read all the file names in a directory # store all the files name in a variable # loop through all the files names and convert to .mp4 files # save all the files in the specif...
def get_points(self): fields = self.values.flatten() points = 0 for number in fields: points += self.points_dic[number] self.reward = points - self.points self.points = points return self.points def generate_next_number(self...
This code initializes a game similar to 2048, setting up a grid with random tile spawning, scoring mechanics, and visual elements using Pygame. It configures tile values, color mappings, point calculations, and prepares the game state for interaction, including generating initial numbers and updating game mechanics.
def __init__(self, height, width, number): pygame.init() self.running = True self.font_name = pygame.font.get_default_font() self.size = 40 self.font = pygame.font.Font(self.font_name, self.size) self.colors = {3*2 ** i: (100, 100, 100) for i in...
def move(self, key): if key == 'left': self.shift_left() if key == 'right': self.values = np.flip(self.values, axis=0) self.shift_left() self.values = np.flip(self.values, axis=0) ...
This code handles user input for movement, updates the game state by generating numbers, checks if the game should end when no directions remain, and updates the display. It processes input keys, triggers movement and number generation, updates direction options, and either ends the game or renders the current state.
def input(self, key): if key in self.direction_list: self.move(key) self.generate_next_number() self.update_direction_list() if len(self.direction_list) == 0: self.running = False self.show_endscreen() ...
def search_for_playlists(self): search_query = input('Search for playlist: ') all_playlists = self.get_playlists() return [playlist for playlist in all_playlists if search_query.lower() in playlist['name'].lower()] def print_playlist_options(self, playlists): for index, playlist in enume...
This function prompts the user to select a playlist from a list, allowing them to search and refresh the playlist options. It validates the input to ensure the selected index is within bounds, repeating until a valid choice is made. The function returns the validated playlist index once confirmed.
def get_playlist_selection(self, playlists): selected_index = -1 valid = False while not valid: user_input = input('Select playlist: ') if user_input == 's': playlists = self.search_for_playlists() self.print_playlist_options(playlists) ...
def search_for_playlists(self): search_query = input('Search for playlist: ') all_playlists = self.get_playlists() return [playlist for playlist in all_playlists if search_query.lower() in playlist['name'].lower()] def print_playlist_options(self, playlists): for index, playlist in enume...
The main task of the code is to allow a user to select a playlist from a list of options. It searches for playlists, displays them, retrieves the user's selection, extracts the selected playlist's ID and name, and returns a Playlist object initialized with those details.
def select_playlist(self): playlists = self.search_for_playlists() self.print_playlist_options(playlists) selected_index = self.get_playlist_selection(playlists) id = playlists[selected_index]['id'] name = playlists[selected_index]['name'] return Playlist(id, name)
def create_playlist(self): playlist_name = input('Enter playlist name: ') is_public = False result = self.spotify.user_playlist_create(self.user_id, playlist_name, public = is_public) created_playlist = Playlist(result['id'], result['name']) # TODO: Store playlist object instead ...
The function prompts the user to select an existing playlist or create a new one. It validates the choice, checks if the selected playlist exists, and returns the valid playlist name. If the playlist doesn't exist, it exits with an error.
def select_playlist_or_create_new(self): print('1: Select existing playlist') print('2: Create new playlist') user_reponse = input('Select your option: ') should_create_playlist = user_reponse == '2' playlist = None if should_create_playlist: playlist = self.c...
def select_playlist_or_create_new(self): print('1: Select existing playlist') print('2: Create new playlist') user_reponse = input('Select your option: ') should_create_playlist = user_reponse == '2' playlist = None if should_create_playlist: playlist = self.c...
The main task of the code is to add a list of tracks to a Spotify playlist. It selects or creates a playlist, retrieves existing tracks, attempts to find each input track (with metadata cleaning if needed), appends found tracks to the playlist, and logs failed tracks. A summary of additions and failures is printed afte...
def add_tracks_to_spotify(self, tracks_to_add): playlist = self.select_playlist_or_create_new() playlist_tracks = self.get_playlist_tracks(playlist.id) self.store_playlist_tracks(playlist_tracks) for track in tracks_to_add: spotify_track = self.find_track(track) ...
def check_for_collision(self): # Check for collisions with various game elements # Check for backboard collision if self.check_backboard_collision(): return # Check for rim and surface collisions self.check_rim_collision() self.check_surface_collision() def ...
The code updates the game state by checking collisions, updating the ball's position, and handling game logic. It resets the ball if it goes out of bounds or exceeds its lifespan, checks for scoring conditions when the ball enters the rim, and increments a frame counter. The function processes player input, manages gam...
def update(self, dt, power): # Update the game state based on elapsed time and player input # Check for collisions with various game elements self.check_for_collision() # Update the ball's state self.ball.update(dt) # Check if the ball is out of bounds if ( ...
def getProjectDir(self): with open(self.configdir) as f: projectdir = f.read() return projectdir.split('\n')[0] def __setDate(self): import datetime date = datetime.datetime.now() return str(date.year) + str(date.month) + str(date.day) + "/" def dirStructure(self,Prin...
The code initializes a class instance by setting up project directories, configuration paths, and file storage locations based on input parameters like 'path', 'selection', and 'era'. It constructs directories for figures and JSON data, ensuring proper organization of project files. The 'dirStructure()' method is calle...
def __init__(self, path, selection, era = "Theory"): self.configdir = os.getcwd()+"/../conf/config" self.projectdir = self.getProjectDir() self.path = path self.era = era self.selection = selection self.date = self.__setDate() self.figpath = self.proje...
def q_sample(self, x_start, t, noise=None): noise = default(noise, lambda: torch.randn_like(x_start)) return extract(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start + extract(self.sqrt_one_minus_alphas_cumprod, t, x_start.shape) * noise def model_predictions(self, x, t, x_self_cond=None, clip_x_st...
This function computes the loss for training a diffusion model by predicting either noise, initial image (x0), or velocity (v) based on the specified objective. It adds noise to inputs, applies self-conditioning when enabled, calculates mean squared error (MSE) loss, and optionally computes a maximum mean discrepancy (...
def p_losses(self, x_start, t, noise=None, offset_noise_strength=None): b, c, h, w = x_start.shape noise = default(noise, lambda: torch.randn_like(x_start)) # offset noise - https://www.crosslabs.org/blog/diffusion-with-offset-noise offset_noise_strength = default(offset_noise_strength,...
def pdf_to_png(pdf_name, output_directory="report_images"): if not os.path.exists(output_directory): os.makedirs(output_directory) prefix = os.path.basename(pdf_name).replace(".pdf", "") os.system("pdftoppm %s %s/%s -png" % (pdf_name, output_directory, prefix)) return sorted(glob.glob("%s/%s*.p...
This function generates a LaTeX section titled "Negative Control" by incorporating depth plots (converted from PDF to PNG) and a formatted summary table from specified files. It checks for file existence, processes plots and tables with custom formatting, and handles missing files by displaying error messages. The tabl...
def write_negative_control_section(): print(r"\section{Negative Control}") plot_path = args.negative_control_depth_figure.format(run_name=args.run_name) if os.path.exists(plot_path): nc_depth_figures = pdf_to_png(plot_path) # plot each depth image for the negative control samples ...
def write_image(image_filename, scale=1.0): print(r"\begin{center}") print("\includegraphics[scale=%f]{%s}" % (scale, image_filename)) print(r"\end{center}") def count_tsv(filename): c = 0 with(open(filename)) as f: reader = csv.DictReader(f, delimiter="\t") for row in reader: ...
The code generates a LaTeX section titled "Sequence Variation," including a tree plot if available, and subsections on ambiguity and mixture reports. For Illumina data, it processes ambiguity and mixture tables, formatting them into LaTeX with warnings about contamination. Nanopore data lacks support for these reports....
def write_tree_section(): print("\section{Sequence Variation}") tree_plot_path = args.tree_figure.format(run_name=args.run_name) if os.path.isfile(tree_plot_path): write_image(tree_plot_path, 0.4) else: print(r"SNP tree plot not found") # Ambiguity subsection print(r"\subse...
def makeEdges(self): E = [] for id, (x, y) in enumerate(self.Maze.keys()): neighbors = self.checkNeighbors(x, y) for neighbor in neighbors: E.append((id, self.getValueLocation(*neighbor))) return E def getXYLocation(self, val): x, y = list(self.Maz...
This code generates a maze using the Disjoint Sets (Union-Find) method. It randomly selects edges, checks if they connect distinct sets, and merges them while removing walls between cells. The process continues until all cells belong to a single connected component, ensuring a complete, cycle-free maze.
def generateMaze_Disjoint_Sets_Method(self): if self.doOnce1: self.E = self.makeEdges() randomNeighbor = random.choice(self.E) self.E.remove(randomNeighbor) currentCell, neighborCell = randomNeighbor currentXY = self.getXYLocation(currentCell) neighborXY = s...
def is_this_existing_directory(path_dir): #return os.path.isdir(path_dir) #print('os.path.expanduser(path_dir) : ', os.path.expanduser(path_dir)) return os.path.isdir(os.path.expanduser(path_dir)) def get_list_of_image_path_under_this_directory(dir_img, ext = ''): li_fn_img = get_list_of_file_path_und...
This function processes a video or image sequence (from camera, video file, or folder) by applying cropping, rotation, mirroring, and saving each transformed frame as PNG images in a specified directory. It handles both image sequences and video streams, applying user-defined margins, shifts, and transformations to eac...
def camVidImgSeq2ImgSeq(idx_cam_or_fn_video_or_img_folder, dir_seq, idx_frm_start = 0, margin_lrtb=[0, 0, 0, 0], xy_shift=[0, 0], rotation='none', mirror='none'): idx_frm = idx_frm_start; is_this_image_sequence = False li_path_img = [] #cap = cv2.VideoCapture(opt.idx_cam if opt.is_cam else opt.fn_v...
def fetch_risk_free_rate(): # """ # Fetch the risk-free rate from Yahoo Finance. # Returns: # float: Risk-free rate in decimal form. # """ try: tbill = yf.Ticker("^IRX") tbill_info = tbill.info return tbill_info['previousClose'] / 100 # Convert to decimal ex...
The function updates financial visualizations by calculating portfolio metrics like returns, Sharpe ratios, and optimal asset allocation based on user interactions. It processes stock data, computes current prices, risk-adjusted returns, and generates plots for efficient frontier, asset allocation, and Sharpe ratios, i...
def update_plots(table_data, add_clicks, remove_clicks, annualized_clicks, non_annualized_clicks): # Determine which button was clicked ctx = dash.callback_context button_id = ctx.triggered[0]['prop_id'].split('.')[0] # Fetch the annual risk-free rate risk_free_rate_annual = fetch_risk_free_rat...
def set_backend_password(): if sys.platform == "linux": from keyrings.cryptfile.cryptfile import CryptFileKeyring kr = CryptFileKeyring() kr.keyring_key = os.environ.get('KEYRING_CRYPTFILE_PASSWORD') or getpass.getpass("Enter keyring password: ") keyring.set_keyring(kr) def store_use...
The main task of the code is to securely collect and store user credentials (email/password) and an API key. It validates inputs, encrypts and stores them if provided, and informs the user of success or exit. It checks for empty passwords, stores data using backend functions, and outputs a confirmation message based on...
def main(): is_stored = False set_backend_password() user_email = input("Enter user email: ") user_password = getpass.getpass("Enter user password: ") if user_password == "" and user_email != "": print("No user password entered, please ensure you don't use empty password") elif user_...
def replace_bad_bands_reflectance(datacube): """ Replaces bad bands in a datacube with interpolated values. Parameters: datacube (numpy.ndarray): A 3D numpy array with shape (bands, rows, columns) where -32768 indicates a bad value. Returns: numpy.ndarray: The datacube with bad bands replaced ...
The function preprocesses raster data by replacing bad bands with reflectance values, rescaling the data, converting wavelength units from nanometers to micrometers, and removing specified wavelength bands (1 and 2.5 μm). It returns the modified raster datacube after these operations.
def preprocess(raster: Raster): """ Preprocesses the given raster data. Args: raster (Raster): The input raster data. Returns: Raster: The preprocessed raster data. """ # TODO consider smoothing by Savitzky-Golay filter raster.datacube = replace_bad_bands_reflectance(raste...
def draw_pts_from_reach_area(n_samples, ex_kdtree, reach_area=None): # draw points uniformly from the specified reach area. If reach_area=None, draw # points from the whole reachable space if reach_area == None: (x_min, x_max, y_min, y_max) = (-0.298, 0.298, -0.298, 0.298) else: (x_min,...
The function generates target positions and initial conditions for robotic movement simulations by sampling from a distribution. It creates target points uniformly within a reachable area, then samples starting positions at random distances from targets, ensuring they are reachable using a KDTree. It matches these posi...
def make_targets_init_conds_from_distribution(n_samples, dist_sampler, reach_area, ex_kdtree, params, dims): # make list of targets and starting positions (and corresponding list of initial conditions) # dist_sampler: dist_sampler() returns a samples from some distr...
def pos_a0(q, params): return array([0., 0, 0]) def pos_b0(q, params): # Gives pos of endpoint of a1 in n_hat coords q1, q2 = q[0:2] LA = params[2] # pos_a0 + LA*a1_hat a1_hat = array([cos(q1), sin(q1), 0]) # in n_hat coords pos = pos_a0(q, params) + LA * a1_hat return pos def pos_c0(q...
The code generates x and y coordinate arrays by calculating positions (a0, b0, c0) using input parameters q and params, then extracting their x/y components. It returns these arrays for plotting.
def make_plot(q, params): q1, q2, dq1, dq2 = q a0 = pos_a0(q, params) b0 = pos_b0(q, params) c0 = pos_c0(q, params) x = array([a0[0], b0[0], c0[0]]) y = array([a0[1], b0[1], c0[1]]) return x, y
def pos_c0(q, params): # Gives pos of endpoint of B in n_hat coords # q can be either the full q or just q1, q2. q1, q2 = q[0:2] LB = params[3] c1 = cos(q1) c2 = cos(q2) s1 = sin(q1) s2 = sin(q2) # pos_b0 + LB*b1_hat b1_hat = array([c1 * c2 - s1 * s2, s1 * c2 + c1 * s2, 0]) # ...
This function computes the derivative of a cost function with respect to variables x, m, and r (represented by df_dx, df_dm, df_dr). It combines weighted terms involving position error, joint angle error, and dynamic derivatives (dv2_dr, dpos_error_dr) using parameters from 'params'. The result is a concatenated array ...
def df_dz(t, x, m, q, start, q_start, u1, u3, v2, params): pos_error = pos_c0(q, params) - u1 q_error = q[0:2] - u3 dq_dr = hstack((eye(2), zeros((2, 2)))) df_dx = 2 * params[15] * x df_dm = 2 * params[16] * m df_dr = (2 * params[18] * dot(v2, dv2_dr(q, params)) + ...
def make_target_list(n_samples, params): target_list = [] for i in range(n_samples): q1 = (pi * random.rand()) - (pi / 4) q2 = (3 * pi / 4) * random.rand() dq1 = 0 dq2 = 0 q = array([q1, q2, dq1, dq2]) c0 = pos_c0(q, params) target_list += [c0] return...
This function generates uniformly distributed start and target points in a 3D reachable area, converts them to joint configurations using inverse kinematics, and constructs initial condition arrays for simulations. It samples Cartesian points, maps them to joint angles via KDTree interpolation, and returns Cartesian po...
def make_targets_init_cond_uniformly_from_reach_area(n_samples, reach_area, params, dims): # draw start and stop points uniformly from the x,y,z reachable space rather than q1,q2 angle space # reach_area = (x_min, x_max, y_min, y_max) ex_pts = vstack(make_target_list(int(1e5), params)) ex_kdtree = KDTr...
def dh_dx(x, A, D0, D1, params, dims): sigma_prime = dsigma_dx(D0 + dot(D1, x)) dhx_dx = -A dhm_dx = -(1.0 / params[13]) * dot(sigma_prime, D1) dhr_dx = zeros((dims[5], dims[0]), dtype=float64) out = vstack((dhx_dx, dhm_dx, dhr_dx)) return out def dh_dm(q, C3, params, dims): dhx_dm = -C3...
This function computes the derivative of a function h with respect to variables x, m, and q by calling three sub-functions (dh_dx, dh_dm, dh_dr), then horizontally concatenates their results into a single output array, likely for use in dynamical system modeling or optimization tasks.
def dh_dz(t, x, m, q, ext_force, A, C1, C3, C4, D0, D1, params, dims): out1 = dh_dx(x, A, D0, D1, params, dims) out2 = dh_dm(q, C3, params, dims) out3 = dh_dr(t, q, m, ext_force, C1, C4, params, dims) return hstack((out1, out2, out3))
def df_dz(t, x, m, q, start, q_start, u1, u3, v2, params): pos_error = pos_c0(q, params) - u1 q_error = q[0:2] - u3 dq_dr = hstack((eye(2), zeros((2, 2)))) df_dx = 2 * params[15] * x df_dm = 2 * params[16] * m df_dr = (2 * params[18] * dot(v2, dv2_dr(q, params)) + ...
The function computes the right-hand side (rhs) of an adjoint equation by combining derivative terms and solving a linear system. It takes parameters like time `t`, adjoint variable `y`, state variables, and model coefficients. The calculation involves transposing derivative matrices, dot products with the adjoint vari...
def make_rhs_adjoint(t, y, x, m, q, start, target, q_start, q_target, u1, u3, ext_force, v2, A, C1, C3, C4, D0, D1, params, dims): # y is the adjoint variable rhs_temp = df_dz(t, x, m, q, start, q_start, u1, u3, v2, params).T + dot( dh_dz(t, x, m, q, ext_force, A, C1, C3, C4, D0, D1, params, dims).T - ...
def omit_character(data_dict, prefix, length, completion_list): reversed_prefix = prefix[::-1] list = [] no_dup_list = [[x.source_text, x.offset] for x in completion_list] for i in range(len(prefix)): try: path_list = data_dict[(reversed_prefix[:i] + reversed_prefix[i + 1:])[::-1]] ...
The function generates all similar completions by omitting, adding, and replacing characters in the given prefix, then merges these three sets of results into a combined list. It uses helper functions to handle each modification type and aggregates them for comprehensive completion suggestions.
def get_all_similar_completions(data_dic, prefix, length, completion_list): omit_completions = omit_character(data_dic, prefix, length, completion_list) add_completions = add_character(data_dic, prefix, length, completion_list) replace_completions = replace_character(data_dic, prefix, length, completion_lis...
def updateStock(itemNumber, value): """Update the value of the stock with the given value for the item Args: itemNumber(str): the item number value(str): the value of the stock Returns: item: the catalog item matching the item number """ with app.app_context(): books = ...
This function updates an item's stock value, invalidates related caches on the frontend, and replicates the update to other server replicas by sending HTTP requests to their endpoints, ensuring data consistency across distributed systems.
def updateStockRoute(itemNumber, value, dataLoading=False): """ Update the stock value of an item with a given value """ requests.get(app.config.get("frontend_uri") + "/invalidate/" + str(itemNumber)) with lock: response = updateStock(itemNumber, value) topic = response[0]['topic'] ...
def reduceStock(itemNumber): """Reduces the value of the stock by 1 Args: itemNumber(str): the item number Returns: item: the catalog item matching the item number """ with app.app_context(): books = query_db( "update books set stock = cast((cast(stock as int) - 1) ...
This function reduces the stock of a specific item by 1, invalidates frontend caches for the item and its topic, updates replicas excluding the current server, and logs the operation. It ensures thread safety using a lock and handles potential replica update errors.
def reduceOneStock(itemNumber, dataLoading=False): """ Reduces the stock value by 1 """ requests.get(app.config.get("frontend_uri") + "/invalidate/" + str(itemNumber)) with lock: response = reduceStock(itemNumber) topic = response[0]['topic'] requests.get(app.config.get("frontend_ur...
def updateCost(itemNumber, value): """Update the value of the cost with the given value for the item Args: itemNumber(str): the item number value(str): the value of the cost Returns: item: the catalog item matching the item number """ with app.app_context(): books = que...
This function updates an item's cost value by invalidating caches, replicating changes to other servers, and logging updates. It sends invalidation requests to the frontend and replicas, skips the current server, and stores the update in the database.
def updateCostRoute(itemNumber, value, dataLoading=False): """ Update the cost value of an item with a given value """ requests.get(app.config.get("frontend_uri") + "/invalidate/" + str(itemNumber)) with lock: response = updateCost(itemNumber, value) topic = response[0]['topic'] req...
def draw_window(window): #window.fill(WHITE) row = 0 box_width = (WIDTH - 30)/8 box_height = (HEIGHT - 30)/8 while row * box_width < HEIGHT - 30: col = 0 while col * box_width < WIDTH - 30: squareColor = DARK if (row + col) % 2 == 1 else LIGHT #print(squareCol...
This function handles user input for a chess move in a GUI, displaying legal moves, highlighting selected pieces and possible moves, and returning the SAN notation of a valid move. It tracks mouse clicks to select a piece and its destination, processes promotions, updates the board state, and manages timers and evaluat...
def playerMoveGUI(board, window, curr_eval, whitePlayer, blackPlayer, whiteTimer, blackTimer): map = board.piece_map() legal_moves = {} for move in board.legal_moves: uci_move = board.uci(move) start_square = uci_move[:2] if start_square in legal_moves: legal_moves[start_...
def dilation(self, x: torch.Tensor, kernel_size: int) -> torch.Tensor: return F.max_pool2d(x, kernel_size, stride=1, padding=kernel_size//2) def closing(self, x: torch.Tensor, kernel_size: int) -> torch.Tensor: y = self.dilation(x, kernel_size) return self.erosion(y, kernel_size) def median_blur...
The code processes a depth map by inverting depth values, applying dilation and hole-closing operations, filling empty spaces, optionally extrapolating, applying median and Gaussian blurs, and re-inverting depth values to refine the depth map for improved quality and consistency.
def forward(self, in_depth: torch.Tensor) -> torch.Tensor: # Invert if self.invert is True: depth_map: torch.Tensor = torch.where(in_depth > self.min_depth, self.max_depth - in_depth, in_depth) else: depth_map: torch.Tensor = in_depth # Dilate depth_map =...
def sheet_as_df(range: str) -> pd.DataFrame: values = get_sheet(range)["values"] return pd.DataFrame(values[1:], columns=values[0]) def _add_per_category_amount(transaction_data: pd.DataFrame) -> pd.DataFrame: gb = transaction_data.groupby(["Category"])["Amount"].sum().reset_index() for i, row in transa...
The main task of the code is to process transaction data by converting dates to datetime format, cleaning amount values, adding per-category and category-group columns, and grouping dates by month-year, then returning the structured DataFrame for analysis.
def get_transaction_data_df() -> pd.DataFrame: df = sheet_as_df("Transactions") df["Date"] = pd.to_datetime(df["Date"]) df["Amount"] = df["Amount"].apply(clean_amount) _add_per_category_amount(df) _add_category_group(df) df["month_year"] = df["Date"].dt.to_period("M") return df
def turn_on_spot(self, angle, gain = 0.3): power=np.sign(angle)*self.total_power for port in self.ports: self.BP.offset_motor_encoder(port, self.BP.get_motor_encoder(port)) start_time = time.time() positions = np.array([self.BP.get_motor_encoder(port) for port in self.ports]...
The main task of the code is to navigate a robot to a specified waypoint (wx, wy) by calculating the angular difference between the robot's current orientation and the direction to the target. If the distance exceeds 20 units, it rotates on the spot to align with the target direction, then moves forward. For shorter di...
def navigate_to_waypoint(self, wx, wy): #print(f"I think I'm at {self.pos}") #print(f"navigating to {wx}, {wy}") dx = wx - self.pos[0] dy = wy - self.pos[1] dist=np.sqrt(np.square(dx) + np.square(dy)) if (dist >20): alpha = np.rad2deg(np.arctan2(...
def go_straight(self, distance, gain = 0.5): for port in self.ports: self.BP.offset_motor_encoder(port, self.BP.get_motor_encoder(port)) positions = np.array([self.BP.get_motor_encoder(port) for port in self.ports]) degrees_to_rotate = self.convert_distance_to_rotation(distance) ...
The code's main task is to draw a square by repeatedly moving the robot forward four times per side, updating particle positions for straight motion, waiting, then turning 90 degrees and updating rotation particles, repeating this four times to complete the square.
def draw_square(self): for _ in range(4): for _ in range(4): self.go_straight(0.085) self.update_particles_straight(10) time.sleep(5) self.turn_on_spot(90) self.update_particles_rotate(90)
def sig_sub_exp_FFT(signal, Vg1, p0, threshold, n): signal_sub_exp = sig_sub_exp(signal, Vg1, p0) signal_sub_FFT = sig_sub_FFT_noise(signal_sub_exp, threshold, n) return signal_sub_FFT def smooth_peaks(sig_sub_noise, window_length = 20, poly=2): smooth_signal = savgol_filter(sig_sub_noise, window_lengt...
This function processes a signal by subtracting an exponential fit and applying FFT, identifies the final peak, estimates its center, and fits a Lorentzian curve to determine the optimized amplitude, center, and width of the peak. It returns these fitted parameters along with their uncertainties.
def find_final_peak_Lorentz(signal, Vg2, p0, threshold, n): """ This function finds the final peak in the signal and fits a Lorentzian to it, returning the fitted amp, centre and width :param signal: raw, noisy, unprocessed signal :param Vg2: :param p0: initial conditions for the exponential fit ...
def calc_mean_shift(current, Vg1, Vg2): """ This function calculates the mean difference between consecutive final peaks of the first 40 signals 40 because after this the final peaks are associated with a different transition line- how can this be automated? :param current: :param Vg1: :param V...
The function `verify_each_peak` processes consecutive signals to identify peaks and checks if corresponding peaks exist in adjacent signals within a calculated shift range. It filters and smooths each signal, detects peaks, and marks positions in a binary mesh grid where peaks in subsequent signals align within the thr...
def verify_each_peak(current, Vg1, Vg2, X, Y, p0, threshold, n): """ This function goes through each signal and for each peak in the signal #checks if there is another signal within range of it in the signal before. Is so then it is not noise and is plotted. :param current: :param Vg1: :param Vg...
def cycles_list2vec(regions, repeat_first : bool = True): ''' convert list of cycles to vec and list of lengths ''' regions = regions.copy() if repeat_first: for i in range(len(regions)): regions[i] = torch.vstack([ regions[i],regions[i][:1] ]) ...
The function processes input cycles through a neural network layer, identifies intersecting hyperplanes, constructs a graph representation, and computes new regions (cycles) formed by these intersections. It returns the updated regions and their corresponding indices, handling both intersected and non-intersected cycle...
def to_next_layer_partition(cycles, Abw, current_layer, NN, dtype=torch.float64, device='cuda'): vec_cyc,cyc_idx,ends = cycles_list2vec(cycles) cycles_next = NN.layers[:current_layer].forward(vec_cyc.to(device)) q = NN.layers[current_layer].get_intersection_pattern(cycles_next) ## edge interse...
def to_next_layer_partition(cycles, Abw, current_layer, NN, dtype=torch.float64, device='cuda'): vec_cyc,cyc_idx,ends = cycles_list2vec(cycles) cycles_next = NN.layers[:current_layer].forward(vec_cyc.to(device)) q = NN.layers[current_layer].get_intersection_pattern(cycles_next) ## edge interse...
This function processes a batch of cycles through a neural network layer to compute new regions (cycles) by analyzing intersections with hypotheses. It handles both batched and non-batched operations, constructs graphs from cycle-hypothesis interactions, and partitions cycles into new regions using graph-based cycle de...
def to_next_layer_partition_batched(cycles, Abw, current_layer, NN, dtype=torch.float64, device='cuda', batch_size=-1, fwd_batch_size=-1, workers=2): if batch_size == -1: ## revert to non-batched res_regions, new_cyc_idx = to_next_...
def expandSearch(self, map, x, y): #on a cell, add corridors to all possible sides if self.up(map,x,y)==0: map[x-1][y]=4 if self.down(map,x,y)==0: map[x+1][y]=4 if self.left(map,x,y)==0: map[x][y-1]=4 if self.right(map,x,y)==0: map[x][y+1]=...
This code generates a connected map of rooms and corridors by initializing a grid, marking room positions, start/end points, and iteratively expanding corridors to ensure all rooms are connected. It checks for connectivity, adjusts corridor lengths, and repeats until no further expansions are needed, returning the fina...
def connectRooms(self): map = [[0 for _ in range(cols)] for _ in range(rows)] #initializing matrix to use for connecting the rooms #if in the world there's a room at location pos, place 3 on the map to mark it for pos, room in self._world.items(): if room != None: map...
def setStart(self):#set the start and finish locations at random x = random.randint(0,rows-1) y = random.randint(0,cols-1) self.start = (x,y) self._world[(x,y)] = getattr(__import__('MapTile'), "StartRoom")(x,y) x = random.randint(0,rows-1) y = random.randint(0,cols-1) ...
The code initializes a maze-like world by setting up rooms, randomly placing start/end points, generating rooms with weighted randomness, connecting them into corridors, and printing the final map structure.
def __init__(self): self._world = {} self.start = (0,0) self.end = (0,0) self.fullMap = [] for i in range(rows): for j in range(cols): self._world[(i,j)] = None #print("setting start and end") self.setStart()#set start and end rooms at ...
def binarizer(claims, outcomes, mlb, fit=False): if fit: claims = mlb.fit_transform(claims) outcomes = mlb.transform(outcomes) else: claims = mlb.transform(claims) outcomes = mlb.transform(outcomes) return claims, outcomes def data_stats(claims, outcomes, type): c_stats,...
The main task of the code is to split a dataset into training, validation, and test sets, tokenize text data using a BERT tokenizer, binarize multi-label claims and outcomes, and save the processed data in pickle files for machine learning tasks. It ensures reproducible splits, handles text preprocessing, and prepares ...
def split_dataset(pretokenized_dir, tokenizer, max_len, dataset_ids, dataset_facts, dataset_arguments, dataset_claims, dataset_outcomes): train_ids, train_facts, train_arguments, train_claims, train_outcomes = [], [], [], [], [] val_ids, val_facts, val_arguments, val_claims, val_outcomes = [], [], [], [], [] ...
def simple_data(path="dataset/dev.jsonl"): all_facts, all_claims, all_outcomes, all_ids = [], [], [], [] with open(path, 'r') as json_file: json_list = list(json_file) for json_str in json_list: result = json.loads(json_str) claims = get_allowed(result["allegedly_violated_articles"...
The code processes and splits a dataset into training, validation, and test sets, binarizes multi-label claims/outcomes using `MultiLabelBinarizer`, tokenizes text with a BERT tokenizer, generates attention masks, and saves the preprocessed data (facts, masks, labels) into pickle files for downstream tasks like multi-l...
def simple_split(pretokenized_dir, tokenizer, max_len): val_facts, val_claims, val_outcomes, val_ids = simple_data("ECHR/Chalkidis/dev.jsonl") test_facts, test_claims, test_outcomes, test_ids = simple_data("ECHR/Chalkidis/test.jsonl") train_facts, train_claims, train_outcomes, train_ids = simple_data("ECHR/...
def get_arguments(data): try: arguments = data["text"].split("THE LAW")[1].split("FOR THESE REASONS, THE COURT UNANIMOUSLY")[0] arguments = arguments.split("\n") arguments = [a.strip() for a in arguments] arguments = list(filter(None, arguments)) except: return [] ret...
The code processes ECHR case data by extracting claims, arguments, and outcomes from JSON files. It splits text to identify legal articles, handles exceptions, and writes augmented datasets. It aggregates data across train/dev/test splits, fixes claim inconsistencies, and prepares inputs for tokenization and model trai...
def get_data(pretokenized_dir, tokenizer, max_len): dataset_facts = [] dataset_arguments = [] dataset_claims = [] dataset_outcomes = [] dataset_ids = [] paths = ['train', 'dev', 'test'] out_path = ['train_augmented', 'dev_augmented', 'test_augmented'] for case_path, out in zip(paths, o...
def train(self, X, Z_seq=np.array([])): self.trained = True X_length = len(X) self._init(X) if Z_seq.any(): Z = np.zeros((X_length, self.n_state)) for i in range(X_length): Z[i][int(Z_seq[i])] = 1 else: Z = np.ones((X_length, s...
This code implements the Viterbi algorithm to decode the most probable hidden states sequence from observations in a Hidden Markov Model. It first ensures the model is trained, then computes forward probabilities with scaling, tracks maximum state probabilities, and reconstructs the optimal state sequence via backtrack...
def decode(self, X, istrain=True): """ Viterbi :param X: observations :param istrain: :return: hidden states """ if self.trained == False or istrain == False: self.train(X) X_length = len(X) state = np.zeros(X_length) pre_stat...
def convolutional_layer(num_filters=8,ksize=3,padding="same",stride=1): """This function creates a convolutional layer for use in the residual blocks of Resnet. Parameters: num_filters (int) : Number of filters to use in Convolutional layer ksize (int) : Kernel size of ...
This function constructs a customizable ResNet convolutional base with configurable residual blocks, stacks, and filters. It processes input through initial convolutional layers, builds multiple residual block stacks (with filter doubling), applies average pooling, and adds extra residual layers for multi-scale feature...
def custom_resnet_convolutional_base(input_shape,num_extra_layers=2,num_residual_blocks=3,num_stacks=4,num_filters=8): """This function creates a Resnet having specific number of Residual blocks. Parameters: input_shape (tuple) : Shape of the input tensor which will be feed into the Resnet ...
def restart(): global instances, obstacles, run, gradient_colors, nets, ge, epoch_scores, current_max_score, max_score, current_max_score run = True if current_max_score > max_score: max_score = current_max_score epoch_scores.append(current_max_score) if PLAY_TYPE == 0: f = open("log.txt",...
The code simulates a NEAT-based evolutionary algorithm where neural networks control agents to navigate obstacles. It initializes genomes, creates feedforward networks, and runs a game loop where agents jump based on network outputs. Fitness is updated based on performance (e.g., reaching targets), and the simulation t...
def main(genomes, config): global instances, ge, nets, t_last_fast_update, cam_x, cam_offset_x, run, nearestPile, obstacles, generation, FPS, current_FPS, fps_last_time, t_last_fast_update, EPOCHS, SCORE_MAX, current_Total, PLAY_TYPE, current_max_score, max_score restart() generation += 1 cam_x = -cam_o...
def handle_error(self, status:int, msg_str: str) -> None: """ Function to handle any errors that are encountered during request handling and response processing. status(int): A status code describing the error encountered. msg_str(str): A more descriptive response deta...
The code handles incoming requests by parsing username, signature, and request data from received bytes, validates the request length, and routes the request to either user registration or specific handling functions. It ensures data integrity through checks and gracefully handles errors with a fallback response.
def handle(self): """ Function to initially handle any requests received. This will read a request, perform some curseory validation before calling more specific handling functions. Nothing is returned. """ try: # Read request bytes_mess...
def lessDigitsValueCount(digitsCount, n): noOfDigits = int(log10(n))+1 count = 0 for i in range(1, noOfDigits): count = count + pow(digitsCount, i) return count def intToList(x): l = [] while (x): l.append(x % 10) x //= 10 l.reverse() return l def equalDigitsValue...
The code calculates the total count of valid numbers by summing those with fewer digits than `m` (using `lessDigitsValueCount`) and those with exactly `m` digits (using `equalDigitsValueCount`), based on given constraints. It converts `n` to a list for digit analysis and returns the combined result.
def possibleNumbers(n, m, digits): less = lessDigitsValueCount(m, n) listN = intToList(n) equal = equalDigitsValueCount(listN, m, digits) return less + equal
def applyActions(gp, allActions, negate): """ This function is responsible for computing the the next step in the graph planning, each time this function called it generates the next action layer and the proceeding state layer for the graph provided in the parameters. Args: ...
The function repeatedly applies actions to a graph plan, generating new states until a solution is found. It uses `applyActions` to progress the plan, checks for valid solutions via `extractSolution`, and terminates early if a solution is identified. If no solution is found after all iterations, it returns False.
def getSolution(gp, allActions, gStates, iStates, negate): """ This function is responsible for performing the graph plan while repeatedly calling the apply Actions function which progesses the graph plan along two steps. Args: gp (Graph): The graph plan object allAction...
def displayFile(inFile): """ This function is responsible for printing out the problem file for which the graph planning problem will be solved. Args: inFile (string): File path of the problem """ print("\nThe problem in the file " + inFile + " will be solved with grap...
The main task of the code is to generate a graph plan by validating input arguments, loading problem specifications from an input file, initializing a plan, solving it using available actions and states, and writing the solution to an output file while printing it to the terminal. The function orchestrates graph plan c...
def graphPlanGenerate(): """ This function is the main function where he program starts. It created the variable and objects required to perform the graph plan. """ # expected number of arguments nArgExpected = 2 + 1 # +1 is for the filename itself iStates = [] gStates = [] allActio...
def _get_nodes_hierarchy(self): nodes = [] for node in self.top_level_nodes: nodes.append(node.get_children_recursive()) return nodes def _draw_engine_sections(self): raylib.DrawRectangle(0, 0, raylib.GetScreenWidth(), 50, (180, 180, 180, 255)) raylib.DrawRe...
The main task of the code is to update and render a graphical editor interface. It clears the screen, updates all nodes, manages the selected node, draws UI elements like engine sections, buttons, and project titles, renders node-specific options based on type, handles node addition dialogs, updates the node hierarchy ...
def update(self): raylib.BeginDrawing() raylib.ClearBackground(raylib.RAYWHITE) # IMPORTANT: Update all nodes! for node in self.top_level_nodes: node.editor_update(self.origin_offset) # Set selected_node variable. if self.node_hierarchy_display.selec...
def preprocess_single_root(imgcopy, prune = True, prunesize = 150): #imgcopy = self.singlerootimg.copy() ## skeletonize skimg = (skeletonize(imgcopy/255.)*255).astype(np.uint8) npones = np.ones(skimg.shape) npones[skimg == 0] = 0 if prune: skimg= pc...
The function detects and identifies the main root from an image by analyzing bifurcations and lateral roots. It processes the image in multiple directions, reconstructs the main root path, and selects the longest valid main root. It returns the detected main root and associated lateral roots, prioritizing the longest d...
def detect_main_root(self, image=None, max_lateralrootdist = 300): root_dict = {'main':[], 'lateral': []} self.singlerootimg = image imgcopy = self.preprocess_single_root(self.singlerootimg.copy()) startingdirections = ['top', 'left', 'right', 'bot...
def set_game_obj_images(self, screen): """ Load images, assign to sprite classes (do this before the classes are used, after screen setup) """ print("RevisitingHorrorGame - set_game_obj_images()") main_menu_background_image = Utility.load_image( "revi...
The main task of the code is to initialize a Pygame game window, configure display settings, load game assets (images and sounds), and execute the game loop. It checks SDL version, sets up audio parameters, creates a display surface, loads game objects' images, enables sound, runs the game loop with an intro background...
def main(self): # Initialize pygame if pygame.get_sdl_version()[0] == 2: pygame.mixer.pre_init(44100, 32, 2, 1024) pygame.init() fullscreen = False # Set the display mode window_style = 0 # |FULLSCREEN bestdepth = pygame.display.mode_ok( ...
def initializePopulation(self,cities, ncities): numPathsToGenerate = math.ceil(math.sqrt(len(self._scenario.getCities()))) populationSet = [] # initialize an empty array populationSet = self.greedyPathGenerator(populationSet, cities, ncities) return self.randomPathGenerator(populationSet, numPathsToGenerate, ci...
This code implements a genetic algorithm to solve the Traveling Salesman Problem (TSP). It initializes a population of routes, iteratively selects parents, applies crossover and mutation to generate new routes, and updates the best solution (bssf) based on cost. The process repeats for a fixed number of iterations (con...
def fancy( self,time_allowance=60.0 ): start_time = time.time() cities = self._scenario.getCities() ncities = len(cities) populationSet = self.initializePopulation(cities, ncities) bssf = TSPSolution(self.create_route(populationSet[0],cities)) new_bssf = TSPSolution(self.create_route(populationSet[1], citie...
def queuesEmpty(self): for i in range(len(self.queues)): if not self.queues[i].empty(): return False return True def generateStates(self, parentState): states = [] # Run through all the cities and if one is not in the partial path ...
The code implements a branch-and-bound algorithm to find the optimal solution (BSSF) for a problem, likely the Traveling Salesman Problem. It explores states via priority queues, prioritizing deeper levels to enhance efficiency. When a better solution is found, it updates the BSSF and prunes inferior states. The algori...
def branchAndBoundAlgorithm(self, currTime): # This while loop keeps trying while the queues are not empty # # The following time/space is worst case scenario # Time/Space Complexity: O(bmnqz) where b is the number of states that # were generated, m is the size of the bi...
def game_result(board, config) -> Optional[dict]: if all([cell != EMPTY for cell in board]): return {1: 0.5, 2: 0.5} if has_won(board, 1, config): return {1: 1., 2: 0.} if has_won(board, 2, config): return {1: 0., 2: 1.} return None def legal_moves(board, config): return [col...
The code simulates a game by randomly selecting legal moves until the game ends, then returns the result for the current player's turn.
def rollout(self): current_rollout_board = self.board.copy() turn = self.turn while game_result(current_rollout_board, self.config) is None: possible_moves = legal_moves(current_rollout_board, self.config) move = random.choice(possible_moves) play(current_roll...
def game_over(board): """ returns 1 or 2 or 0 if there is a winner and -1 if the game is still going on. 1: the winner is the trainer 2: the winner is the ai 0: there is a draw -1: the game is still going on :param board: list[] :return: int """ # check for horizontal wins i...
This code trains an AI by playing multiple tic-tac-toe games against a trainer (or another AI), tracking wins, losses, and draws. It alternates turns, updates game state, and adjusts AI/trainer performance metrics. The function returns a list with trainer wins, AI wins, and draw counts after 'num' training iterations.
def train(num, ai1=None,vs_ai=None): """ Train the ai num times, using the default ai trainer. Or using another ai if desired. :param num: int :param vs_ai: boolean :return: lst[] """ board = [0, 0, 0, 0, 0, 0, 0, 0, 0] turn = True if ai1 != None: ai = ai1 else...
def train_main(): """ Test and train the AI using test_train(...) :return: None """ # change the length of training time here # (It is the number of iterations that the trainer trains the AI for) num_iterations = 50 ai1 = AI() wins_ai1, wins_ai2, draws_all = train_test...
The main task of the code is to parse command-line arguments to determine the training mode (time-based or iteration-based) and duration, then execute the corresponding training process. It checks for valid input parameters, handles special cases (like 'm' for main training), and triggers training functions (`train_for...
def main(sys): """ Get data from arguments and use trainer. Usage: pythonX trainer.py [ s | n | m ] [ time_in_seconds | num_in_iterations ] Example: $> python trainer.py s 30 Training for 30 seconds ... $> python trainer.py n 30 Training for 30 iterations ... """ ...
def remove_highlighting(self): self.selected_piece = None self.hilighted = None self.pieces = {} self.refresh() self.draw_pieces() def move(self, p1, p2): piece = self.chessboard[p1] dest_piece = self.chessboard[p2] if dest_piece is None or dest_piece.colo...
This code handles mouse clicks on a chessboard GUI to select and move pieces. It checks if the game is active, identifies the clicked square, validates moves, updates the board state, and highlights selected pieces. It also checks for check conditions after moves and prints move details.
def click(self, event): if not self.chessboard.game_ended: if ((self.chessboard.player_turn == "white" and self.chessboard.PLAYER_1==1) or (self.chessboard.player_turn == "black" and self.chessboard.PLAYER_2==1)): # Figure out which square we've cli...
def finalPos(self, state: GameState): column = np.all(np.ravel(state.col_status) == 1) row = np.all(np.ravel(state.row_status) == 1) return column and row def get_objective_value(self, state: GameState) -> int: total = 0 for i in state.board_status: for j in i: ...
This code implements the Minimax algorithm with alpha-beta pruning to determine the optimal move in a game. It recursively evaluates game states, maximizing/minimizing scores based on the player's turn, and returns either the best score or a path of moves at depth 4. Alpha-beta pruning optimizes by cutting branches whe...
def minimax (self, state: GameState, depth, alpha, beta, player1): if depth == 0 or self.finalPos(state): return self.get_objective_value(state) if not player1: path = {} maxValue = -100 successor = self.generate_successor(state,player1) for k...
def _get_environment(self) -> Environment: environment = eval(self._config['environment_type']) kwargs = self._parse_config(self._config['environment_params']) return environment(**kwargs) def _get_actor_critic(self) -> ActorCritic: actor = self._get_actor() critic = self._get_cr...
The code initializes an object by loading a YAML configuration file, then sets up environment, actor-critic model, fitting parameters, and visualization settings using private methods. It prepares components for tasks like reinforcement learning or simulation by parsing config data and instantiating necessary modules.
def __init__(self, config_file: str): with open(config_file, "r") as stream: self._config = yaml.safe_load(stream) self.environment: Environment = self._get_environment() self.actor_critic: ActorCritic = self._get_actor_critic() self.fit_parameters: dict = self._get_fit_para...
def validate_name(prompt): name = input(prompt).title() # Added title so names are capitalized while not name.isalpha(): # Checks that at least one letter is entered print("Name cannot be blank, please enter again.") # Error message name = input(prompt) return name def get_age(prompt): ...
The main task of the code is to process movie ticket sales, including calculating ticket prices, handling snack orders, applying surcharges, and updating a dictionary with transaction data. It tracks sold tickets, profit, and remaining seats, providing a summary upon completion or when all tickets are sold.
def loop(movie_data_dict): constants = namedtuple("consts", ["MAX_TICKETS", "SURCHARGE_RATE", "SNACK_PROFIT_MARGIN"]) consts = constants(5, .05, .2) # Creating the MAX_TICKETS constant count = 0 # How many tickets have been sold profit = 0 # Total profit made ...
def shape_rewards(self, initial_reward: float): frag_reward = self.compute_frag_reward() damage_reward = self.compute_damage_reward() ammo_reward = self.compute_ammo_reward() health_reward = self.compute_health_reward() armor_reward = self.compute_armor_reward() distance_...
The code executes a specified action in a game environment, calculates a reward, checks if the episode is finished, updates the game state, and returns the new state, reward, completion status, and frag count for reinforcement learning training.
def step(self, action): # Specify action and take step actions = np.identity(7) self.game.make_action(actions[action], 4) reward = self.shape_rewards(initial_reward=0) self.total_rew += reward self.respawn_if_dead() done = self.game.i...
def user_info(user, logged_in_user): while True: print(f'1. First Name: {user[1]}') print(f'2. Last Name: {user[2]}') print(f'3. Phone: {user[3]}') print(f'4. Email: {user[4]}') print('5. Password') if logged_in_user[9] == 2: print('6. Assessment Results')...
The code presents a user menu with options to view personal information, competencies, and manage users (if the user has admin privileges). It handles input validation, routes selections to corresponding functions, and allows returning to the previous menu by pressing Enter.
def user_menu(logged_in_user): while True: print('--- User Menu ---') print('1. View My Information') print('2. View My Competencies') if logged_in_user[9] == 2: print('3. View All Users') print('4. Search Users') print('5. Get All Users Competenc...
def getDocumentProperties(content): properties = dict() for key in meta_keys: m = re.search(r"<!--[\s\S]*@" + key + r":\s*(.*)[\s\S]*-->", content) if m: properties[key] = m.group(1) return properties def createNavIndex(open_directory, directory): nav = addListEntries(open_di...
The main task of the code is to extract document properties, generate a navigation index, retrieve the modification date, and extract HTML content from a file specified by the given path, compiling these into a dictionary for template rendering.
def getTemplateValues(path): raw_content = "" with open(path, "r") as f: raw_content = f.read() values = getDocumentProperties(raw_content) values["nav"] = createNavIndex(path, raw_html_dir) values["mdate"] = getDocumentMDate(path) values["html"] = getDocumentHTMLContent(raw_content) ...
def getTemplateValues(path): raw_content = "" with open(path, "r") as f: raw_content = f.read() values = getDocumentProperties(raw_content) values["nav"] = createNavIndex(path, raw_html_dir) values["mdate"] = getDocumentMDate(path) values["html"] = getDocumentHTMLContent(raw_content) ...
The function generates an index page content by populating a template with dynamic values. It retrieves template variables, adds an index list and PDF filename, then replaces placeholders in the template with escaped values using regular expressions, returning the final rendered content.
def createIndexPage(path, root): values = getTemplateValues(path) values["index"] = createIndexPageList(root) values['filenamepdf'] = 'index.pdf' content = template_index for key in template_index_keys: content = re.sub(r":"+key+r":", escapeBackSlashes(values.get(key,"")), content...
def randomize_QUBO_small_gap(num_of_qubits): gap = 0.1 norm_f = gap * 2 gap_is_good = False while not gap_is_good: # QUBO_mat = norm_f*(np.random.randn(1)+1)*(np.random.randn(num_of_qubits, num_of_qubits)) QUBO_mat = norm_f * (np.random.randn(1)) * (np.random.randn(num_of_qubits, num_of_...
The code generates a random QUBO matrix, converts it to a Hamiltonian, saves the Hamiltonian's matrix to a CSV file, and returns the initial Hamiltonian (H0) and the final Hamiltonian (H_final) for quantum optimization tasks.
def get_random_QUBO_Hf(num_of_qubits, output_problem_path='output/qubo_problem.csv'): QUBO_mat = randomize_QUBO_small_gap(num_of_qubits) H_f_sparse = QUBO_to_Hamiltonian(QUBO_mat) H_final = Qobj(H_f_sparse.toarray()) output_problem = pd.DataFrame(H_f_sparse.toarray()) output_problem.to_csv(output_pr...
def _downward_scroller(self): '''A method that scrolls to a given set of coordinates when called''' time.sleep(5) scroll_down = self.driver.execute_script("window.scrollTo(0, 300);") return scroll_down def _get_products_page(self): '''A method that finds the page element correspo...
This method navigates through product pages by scrolling down, retrieves products from the current page, and extracts their properties. It sequentially calls downward scrolling, page product retrieval, and property scraping to gather product data.
def _get_product_info_from_each_page(self): '''A method that navigates to each product, scraping the properties of each product''' self._downward_scroller() self._get_products_page() self._get_product_properties()
def format_metadata(): metadata = json.loads(bucket.Object('config/table_metadata.json').get()['Body'].read().decode('utf-8')) tables = {} for row in metadata: table = row['table_name'].replace('aws_', '') table = table_overrides.get(table, table) # have to handle the special cases for tabl...
The code synchronizes database tables by comparing expected and actual tables. It identifies tables to create (missing in actual) and delete (extra in actual), then executes these operations using metadata. This ensures the database schema matches the expected structure.
def handler(event, context): metadata = format_metadata() expected_tables = get_expected_tables() actual_tables = get_actual_tables() creates = list(set(expected_tables) - set(actual_tables)) deletes = list(set(actual_tables) - set(expected_tables)) if len(creates) > 0: create_tables(c...
def show_player_turn(self): """ This function will show the player's image :param side: 1 if left and 2 for right :param player_type: 'ai' or 'human' :return: None """ # self.list_of_images.pop() if not self.game_won(): side = self.game.current_player if side<2: side += 1 else: side -...
This function handles a player's move in a game, supporting player vs AI, player vs player, and AI vs AI modes. If the move is an AI action, it selects a legal move for the current player's AI, executes it, updates the game board, and checks for a win. For direct player moves, it applies the column choice, updates the ...
def make_move(self, col): """ Makes a turn :param player_id: int, player number ( 1 or 2) :param col: :return: """ ''' THIS WORKS FOR PLAYER VS AI , PLAYER VS PLAYER,AI VS AI''' if col == self.MAKE_AI_MOVE: if self.game.current_player == 1: self.show_player_turn() ai_move = self.player_1_ai....
def rel_path(file): """ This function will find the relative path of the file and make it available for opening. :param file: :return: """ return os.path.join(os.path.dirname(__file__), file) def make_move(self, col): """ Makes a turn :param player_id: int, player number ( 1 or 2) :param col: :return: ...
This code initializes a game interface with AI and human player options, sets up a canvas for the game board, and configures automatic AI moves or human interaction. It creates AI players if needed, handles initial moves for AI-first scenarios, and binds mouse clicks for human players, while updating the game state and...
def __init__(self, root, p1_type, p2_type): """ :param root: :param p1_type: 'ai' or 'human' :param p2_type: 'ai' or 'human' """ self.player1type = p1_type self.player2type = p2_type self.ai = [p1_type == 'ai', p2_type == 'ai'] self.root = root self.game = Game() self.current_player_imgs = [] ...
def get_mouse(self, event): """ This function will receive the event and check which column it matches. :param event: the mouse click :return: the column if the click is valid or None if it's not """ mouse_x = event.x if mouse_x < 200 and mouse_x > 120: column = 0 if mouse_x < 110: column = None...
This function handles mouse clicks on a game board to make moves. It checks if a winner exists, determines the clicked column, attempts to make a move, and triggers a win check. It ignores exceptions during moves and updates game state accordingly.
def handle_click(self, mouse_event, column=None): """ This function will transfer the user's interaction with the board :param mouse_event: the click of the mouse :param column: the column the mouse clicked on :return: None """ if self.winner is not None: return if column is None: column = self.ge...
def predict(self, X:np.ndarray, return_proba=False): ''' Return predictions for a given X using the trained model. return_proba: If True, passes the probability of the sample belonging to class = 1 ''' pred = [] z = np.dot(X, self.theta) pred = z p...
The code trains a logistic regression model by iterating over the dataset for a specified number of epochs. It updates model parameters using the training data, computes training loss, and optionally validates on a separate dataset at regular intervals. It stores loss values and predictions for both training and valida...
def fit(self, X:np.ndarray, y:np.ndarray, X_val:np.ndarray=None, y_val:np.ndarray=None, \ val_freq:int=0, store_train_pred:bool=False): ''' Method to train the logistic regression model ''' for i in (range(self.iters)): if (val_freq != 0 and i%v...
def predict(self, X:np.ndarray, return_proba=False): ''' Return predictions for a given X using the trained model. return_proba: If True, passes the probability of the sample belonging to class = 1 ''' pred = [] z = np.dot(X, self.theta) pred = z p...
This code trains a logistic regression model by iteratively updating its parameters (theta) using the training data (X, y). It optionally tracks training and validation predictions/losses at specified intervals, stores them for analysis, and returns the trained model. The validation data (X_val, y_val) is used to evalu...
def fit(self, X:np.ndarray, y:np.ndarray, X_val:np.ndarray=None, y_val:np.ndarray=None, \ val_freq:int=0, store_train_pred:bool=False): ''' Method to train the logistic regression model ''' for i in (range(self.iters)): if (val_freq != 0 and i%va...
def move_pos(self, pos_dest, yaw=0): """Move arm to position specified using forward and inverse kinematics.""" theta_dest = self._invk(pos_dest, yaw) self.move_theta(theta_dest) def sucker(self, suck_set=False): """Turn suction on or off.""" self.suck_set = suck_set ...
This function moves a block (piece) from a start position to an end position using robotic arm movements and suction. It calculates position offsets based on the piece type (pawn, queen/king, or other), navigates the arm to grasp the block, transfers it, and releases it. Error handling checks if the block is successful...
def move_block(self, start, end, piece_id): """Move block from starting to end position.""" if piece_id in PAWNS: P_OFFSET = 0.022 elif piece_id in QUEENS or piece_id in KINGS: P_OFFSET = 0.062 else: P_OFFSET = 0.042 Z_OFFSET = 0.1 of...
def user_input(self): """prompt virtual player for a start and end location""" start = 0 end = 0 while start == end: start = 0 end = 0 while start == 0: input_string_srt = raw_input("Enter a start coordinate using an uppercase l...
The code's main task is to control a robotic arm (UR3) to play a chess game by repeatedly taking user input for moves, validating them against the board state, executing physical moves via the robot, and repeating this process up to 20 times before exiting. It initializes the robot's position, waits for camera-based bo...
def play(self): """Play the chess game with the ur3_controller and the image manager.""" self.ur3_ctrl.move_theta(home) # right = np.radians([270, 25, -25, -90, 0, 100]) # left = np.radians([90, 25, -25, -90, 0, 100]) # self.ur3_ctrl.move_theta(right) # self.ur3_ctrl.mo...
def train_epoch(model, device, train_loader, optimizer): model.train() total_loss = [] for idx, (img_group, label) in enumerate(train_loader): for k, v in img_group.items(): img_group[k] = v.to(device) label = label.to(device) with autocast(enabled=use_amp): i...
The code trains a model over multiple epochs, validating performance using a validation loader and updating the best model based on AUROC (Area Under the ROC Curve). It computes training loss, evaluates validation AUROC, saves the model if AUROC improves, and finally tests the best model on a test loader. The training ...
def train(model, device, train_loader, val_loader, test_loader, optimizer, epoch): best_roc = 0 for epoch_idx in tqdm(range(epoch)): print('Epoch [{}/{}] '.format(epoch_idx + 1, epoch)) epoch_loss = train_epoch(model, device, train_loader, optimizer) print('Epoch [{}/{}] loss:{:.3f}'.for...
def set_sizes(self): self.max_length=0.0 for e in self.elements: self.max_length=max(self.max_length,e.length) if self.support_size is None: self.support_size=0.06*self.max_length if self.hinge_size is None: self.hinge_size=0....
The main task of the code is to generate a graphical plot of a structural model. It creates a figure with equal axes scaling, optionally displays node/element numbers based on input flags, plots structural members, nodes, and supports, then displays and closes the plot. The function visualizes engineering structures wi...
def plot_structure(self,show_node_number,show_element_number): self.set_sizes() self.fig,self.ax=plt.subplots() self.ax.axis('equal') if(show_node_number==True): self.plot_node_number() if(show_element_number==True): self.plot_element_number() self...
def set_sizes(self): self.max_length=0.0 for e in self.elements: self.max_length=max(self.max_length,e.length) if self.support_size is None: self.support_size=0.06*self.max_length if self.hinge_size is None: self.hinge_size=0....
The main task of the code is to visualize structural deformation by plotting original and deformed members, nodes, and supports on an equal-scale figure. It creates a subplot, sets equal axis scaling, draws undeformed members, applies deformation scaling to show deformed members, and overlays nodes and supports before ...
def plot_deformation(self,deformation_scale): self.set_sizes() self.fig,self.ax=plt.subplots() self.ax.axis('equal') self.plot_member() self.plot_deformed_member(deformation_scale) self.plot_node() self.plot_support() plt.show() plt.close()
def set_sizes(self): self.max_length=0.0 for e in self.elements: self.max_length=max(self.max_length,e.length) if self.support_size is None: self.support_size=0.06*self.max_length if self.hinge_size is None: self.hinge_size=0....
The main task of the code is to generate and display a moment diagram for structural analysis. It initializes a plot with equal scaling, draws structural members, bending moments, nodes, and supports, then visualizes and closes the plot.
def plot_moment_diagram(self): self.set_sizes() self.fig,self.ax=plt.subplots() self.ax.axis('equal') self.plot_member() self.plot_bending_moment() self.plot_node() self.plot_support() plt.show() plt.close()
def image_indexes(cell, n_iteration): coords = [] coords.append([cell.midpoint().x(), cell.midpoint().y()]) coords.append(cell.get_vertex_coordinates()[:2]) coords.append(cell.get_vertex_coordinates()[2:4]) coords.append(cell.get_vertex_coordinates()[4:6]) coords1 = np.array(coords) if n_it...
The main task of the code is to modify a mesh's subdomains based on an image array, marking cells inside a shape defined by the image. It adjusts mesh coordinates, applies scaling, and optionally deletes cells depending on the flow method. The function returns the transformed mesh and updated subdomains for further sim...
def mark_inside(square_mesh, coquina_array, n_iteration, free_flow_pixel, flowMethod, del_cells = False): pixels_len = np.zeros(2) # coquina_array = np.transpose(coquina_array) pixels_len[0] = coquina_array.shape[0]-1 pixels_len[1] = coquina_array.shape[1]-1 aspect_image = (pixels_len / pixels_le...
def throwParamException(param): response = JsonResponse({"error": str(param) + " is empty, this field is required!"}) response.status_code = 403 return response def save_db_buy(param_project_name, param_shop_name, param_goods_name, param_coupon_code, param_buy_amount, param_buy_time, param_b...
The main task of the code is to handle a POST request for purchase notification. It validates required parameters, sanitizes input, saves data to a database, sends the data to an external API via `requestApi`, and returns the API's response. The function ensures all parameters are present and non-empty, throwing except...
def buyNotify(request): return_data = "success" if request.method == 'POST': try: projectName = request.POST['projectName'] shopName = request.POST['shopName'] goodsName = request.POST['goodsName'] couponCode = request.POST['couponCode'] buyAmo...
def throwParamException(param): response = JsonResponse({"error": str(param) + " is empty, this field is required!"}) response.status_code = 403 return response def save_db_use(param_project_name, param_shop_name, param_goods_name, param_coupon_code, param_buy_amount, param_buy_time, param_u...
The function processes a POST request to handle coupon usage notifications. It extracts and validates parameters like project name, shop details, and usage data. If any required field is missing, it returns a 404 error. Valid data is saved to the database, sent to an external API via `requestApi`, and the API response ...
def useNotify(request): return_data = "success" if request.method == 'POST': try: projectName = request.POST['projectName'] shopName = request.POST['shopName'] goodsName = request.POST['goodsName'] couponCode = request.POST['couponCode'] buyAmo...
def get_log_entries(incident): log_entries = incident.log_entries(is_overview=False) return log_entries def user_credited_for_incident(users_acked, users_notified): # if incident was acked, credit to first user who acked it if users_acked: return users_acked[-1] # if not acked, credit to fir...
The code processes incident logs to count acknowledgments, unique notified users, identify the credited user, and check if the incident occurred out-of-hours, returning these metrics in a dictionary.
def user_data(incident): log_entries = get_log_entries(incident) users_acked = [log['agent']['summary'] for log in log_entries if log['type'] == 'acknowledge_log_entry'] users_notified = [log['user']['summary'] for log in log_entries if log['type'] == 'notify_log_entry'] num_acknowledgments = len(users_...
def get_components(): components = [] offset = 1 r = statuspage_request('components.json', offset) components = components + r while len(r) == 100: offset += 1 r = statuspage_request("components.json", offset) components = components + r return components def find_groups(...
The main task of the code is to generate and upload SLO and incident reports for each day in a specified range. It retrieves components and incidents, processes them to group by day, calculates downtimes, generates reports in JSON format, saves them temporarily, and uploads them to a storage system. The process include...
def lambda_handler(event, context): components = get_components() with open("components.json", "w") as output: output.write(json.dumps(components)) groups_by_id = find_groups(components) incidents = get_incidents() with open("incidents.json", "w") as output: output.write(json.dumps(i...
def get_incidents(since, until): incidents = pypd.Incident.find(since=since, until=until, time_zone='UTC') return incidents def service_is_excluded(incident): service_name = incident['service']['summary'] for pattern in settings.SERVICE_NAMES_TO_EXCLUDE: if pattern in service_name: r...
The code generates a report by filtering incidents based on urgency and service exclusion, then compiles relevant data into structured rows. It retrieves incidents within a date range, skips excluded or low-urgency cases, and aggregates incident, time, and user details into a list of dictionaries for output.
def generate_report(since, until): incidents = get_incidents(since, until) rows = [] for incident in incidents: row = {} if service_is_excluded(incident): continue if incident['urgency'] == 'low' and settings.EXCLUDE_LOW_URGENCY: continue row.update(in...
def timerange_for_report(): days = settings.DAYS_BACK today = settings.END_DATE start_day = today - timedelta(days=days) until = today.strftime('%Y-%m-%d') since = start_day.strftime('%Y-%m-%d') return (since, until) def generate_report(since, until): incidents = get_incidents(since, until) ...
The code defines an AWS Lambda function that generates a report for a specified time range, saves it as a JSON file in the temporary directory, and uploads it. It sets a Pivotal Tracker API key, retrieves the report data, writes it to a file, and triggers the upload process.
def lambda_handler(event, context): pypd.api_key = settings.API_KEY since, until = timerange_for_report() output_path = '/tmp/%s.json' % since rows = generate_report(since, until) write_report(rows, output_path) upload_report(output_path)
def basic_net(channels, weight, pool, **kw): return { 'prep': conv_bn(channels["reg"], channels['prep'], **kw), # 'prep': conv_bn(3, channels['prep'], **kw), 'layer1': dict(conv_bn(channels['prep'], channels['layer1'], **kw), pool=pool), 'layer2': dict(conv_bn(channels['layer1'], ch...
This function constructs a neural network by combining a basic network with residual and extra layers. It initializes default channel configurations, adds residual connections to specified layers, and incorporates extra convolutional layers with batch normalization. The network structure is customized using provided pa...
def net(reg_channel, channels=None, weight=0.2, pool=nn.MaxPool2d(2), extra_layers=(), res_layers=('layer1', 'layer2'), **kw): channels = channels or {'reg': reg_channel, 'prep': 64, 'layer1': 128, 'layer2': 256, 'layer3': 256, } n = basic_net(channels, weight, pool, **kw) for layer in res_layers: n...
def calculate_activation_by_dataset_new(self,dataset,normalized=True): if len(np.shape(dataset)) == 1: dataset = np.array([dataset,]) self.neuron_data = dataset[:,self.syn_to_pix] x_w = self.neuron_data*self.weights fi_mins_j_matrix = np.dot(x_w,self.gaussian_matrix) ...
The code trains a neural network model over multiple epochs by adjusting synapse connections (swaps) based on positive/negative examples. It calculates activations, computes accuracy, updates outputs, and tracks performance via ROC curves. The model iteratively optimizes synapse weights to maximize classification accur...
def learning_algo(self,number_of_epochs,pos_neg='positive',plot=False): self.initial_pos_exmpl_activations = self.calculate_activation_by_dataset_new(self.testXPos[0]) self.initial_neg_exmpl_activations = self.calculate_activation_by_dataset_new(self.testXNeg[0]) self.calculate_output(self.train...
def get(self, endpoint: str, qWhere: str = None) -> requests.Response: """Simple GET Request to Caspio API. Args: endpoint (str): endpoint of GET request. Returns: requests.Response: The Response <Response> object, which contains a server's response to an HTTP request. ...
This function merges user data into a Caspio table by checking if a CustomerID exists. If found, it updates the existing record using PUT; if not, it creates a new record via POST. The function returns the HTTP response from the operation, handling both update and create scenarios based on the presence of the CustomerI...
def mergeUser(self, data: dict, endpoint: str) -> requests.Response: """Attempts to find user for the new data being submitted via CustomerID. If CustomerID is found the row is updated with information in the dict. If no CustomerID exists in Caspio Table then create a new record in that table wi...
def get_height(self, node): if not node: return 0 return node.height def get_balance(self, node): if not node: return 0 return self.get_height(node.left) - self.get_height(node.right) def balance_tree(self, node, balance_factor): # Balance the tree ...
This function inserts a key into an AVL tree, recursively positioning it in the correct location, updating the node's height, calculating the balance factor, and rebalancing the tree if necessary to maintain AVL properties.
def _insert(node, key): # Find the correct location and insert the node if not node: return TreeNode(key) elif key < node.key: node.left = _insert(node.left, key) else: node.right = _insert(node.right, key) node...
def get_min_value_node(self, node): if node is None or node.left is None: return node return self.get_min_value_node(node.left) def get_height(self, node): if not node: return 0 return node.height def get_balance(self, node): if not node: retur...
This function deletes a node with the specified key from an AVL tree, handling three cases: nodes with no children, one child, or two children. After deletion, it updates the node's height and balance factor, then rebalances the tree using the balance_tree method to maintain AVL properties.
def _delete(node, key): # Find the node to be deleted and remove it if not node: return node elif key < node.key: node.left = _delete(node.left, key) elif key > node.key: node.right = _delete(node.right, key) els...
def add_shot( data: DataSetBase, reconstruction: types.Reconstruction, rig_assignments: Dict[str, Tuple[int, str, List[str]]], shot_id: str, pose: pygeometry.Pose, ) -> Set[str]: """Add a shot to the recontruction. In case of a shot belonging to a rig instance, the pose of shot will dri...
The function attempts to resect a shot (image) into a 3D reconstruction by estimating its camera pose using RANSAC on observed points. It checks if sufficient inliers exist, then adds the shot to the reconstruction with the computed pose if valid. Returns success status, added shot IDs, and a report containing statisti...
def resect( data: DataSetBase, tracks_manager: pymap.TracksManager, reconstruction: types.Reconstruction, shot_id: str, threshold: float, min_inliers: int, ) -> Tuple[bool, Set[str], Dict[str, Any]]: """Try resecting and adding a shot to the reconstruction. Return: True on succe...