dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def get_inverted_tfs(self, tfs): rank = self.get_rank(tfs) rank = 1 if rank < 1 else rank max = np.max(tfs) * rank scale = Scale(sdomain=(0, max)).scale # Convert to inverted relative freqs trend and scale from 0 to 1 tfs = np.array(tfs) tfs = rolling_avg(tfs, self.window, strip_ends=False) tfs = 1.0 -...
The code transforms term and document frequencies into weighted scores by calculating inverted TF-IDF values, yearly/window-based TF-IDF weights, and combining them with learned weights. It adjusts for rare terms, scales results, and optionally stores debug data. The output is a normalized score array emphasizing term ...
def transform(self, tfs, dfs, debug=False): """ @param tfs: term frequencies for token @type tfs: list of ints @param dfs: document frequencies for single term @type dfs: list if ints """ # Are we dealing with a word not in the db? # We assume it's very rare if np.sum(tfs) == 0: return np.ones(le...
def unrotate(): Arm_constants.ARM.set_servo_angle(1, 0, 100, 50, wait=True) def movePiece(square1 : str, square2 : str): moveToSquare(square1) pickupPiece() moveToSquare(square2) dropPiece() def rotate(): Arm_constants.ARM.set_servo_angle(1, 90, 100, 50, wait=True)
The code's main task is to move a game piece from one square to another while managing rotation states. It first resets any prior rotation with `unrotate()`, executes the movement using `movePiece(square1, square2)`, and then applies a rotation with `rotate()`. This sequence ensures proper positioning and orientation a...
def movePieceAndRotate(square1 : str, square2 : str): unrotate() movePiece(square1, square2) rotate()
def uci_to_position(uci_square): file, rank = uci_square[0], int(uci_square[1]) row = 8 - rank col = ord(file) - ord('a') return row, col def castle_sums(move, diffs): if move == "e8c8": return coord_sum("a8", diffs) + coord_sum("d8", diffs) elif move == "e1c1": return coord_sum(...
The function evaluates chess moves by calculating scores based on a difference matrix (`diffs`), prioritizing moves with higher combined from/to square values. It identifies castling moves separately, aggregates top move scores, and returns the highest-scoring move, castling status, its standard algebraic notation (SAN...
def get_likely_move(board, diffs): move_scores = [] board_sum = 0 for move in board.legal_moves: f_r, f_c = uci_to_position(chess.square_name(move.from_square)) from_sum = diffs[f_r][f_c] t_r, t_c = uci_to_position(chess.square_name(move.to_square)) to_sum = diffs[t_r][t_c] ...
def uci_to_position(uci_square): file, rank = uci_square[0], int(uci_square[1]) row = 8 - rank col = ord(file) - ord('a') return row, col def castle_sums(move, diffs): if move == "e8c8": return coord_sum("a8", diffs) + coord_sum("d8", diffs) elif move == "e1c1": return coord_sum(...
The code evaluates chess moves by calculating scores based on differences in a 2D array 'diffs', selects the highest-scoring move, highlights the source and destination squares of this move on an image, and returns the modified image along with the chosen move and castling status. It prioritizes moves with higher 'diff...
def grid(img, diffs, board): maximum = np.amax(diffs) # np_diffs = np.array(diffs) # most_moved = np.argmax(np_diffs) # first_pos = np.unravel_index(most_moved, np_diffs.shape) # print(first_pos) # np_diffs[first_pos] = 0 # second_most_moved = np.argmax(np_diffs) # second_pos = np.unra...
def instantiateArm(): Arm_constants.ARM = XArmAPI('192.168.1.166') Arm_constants.ARM.motion_enable(enable=True) Arm_constants.ARM.set_mode(0) Arm_constants.ARM.connect() def calibrate(): # code to calibrate the arm # enter a known position for the arm to move relative to the board # arm.set_...
This code tests a robotic arm's functionality by allowing user input to move pieces between specified squares. It initializes the arm, calibrates it, and enters a loop where users input source and target squares. The arm then moves and rotates to transfer pieces. The loop exits when 'quit' is entered, and the arm is de...
def testing(): instantiateArm() calibrate() rotate() command = "" print('Now you can move pieces! First input a square that has a piece to pick up, then input a target square, and voila!~') print('Enter \'quit\' at any time to exit!') while 'quit' not in command.lower(): command ...
def get_newState_acording_to_Policy(self, s): """ The actions are exgenge good 2 from customer 1 to customer 2 at current price p_i, or at price p_(i+1), or at price p_(i-1), exgenge good 2 from customer 2 to customer 1 at current price p_i, at price p_(i+1) or at price p_(i-1) or staying. """ policy...
The code performs a single-step update in a reinforcement learning framework by computing temporal difference (TD) errors for two agents (A and B), updating their weight vectors (WA, WB) and transition matrices (TA, TB) using these errors, utilities of states, and policy probabilities. It calculates state-value differe...
def single_step_update(self, s): """ Uses a single step to update the values. """ #take actions and observe the new state and rewards new_s,A,policyA,policyB = self.get_newState_acording_to_Policy(s) uA = utilityA([s[0]*self.eta1,s[1]*self.eta2]) uB = utilityB([self.x1 - s[0]*self.eta1,self.x2 - s[1]*self...
def get_newState_acording_to_Policy(self, s): """ The actions are exgenge good 2 from customer 1 to customer 2 at current price p_i, or at price p_(i+1), or at price p_(i-1), exgenge good 2 from customer 2 to customer 1 at current price p_i, at price p_(i+1) or at price p_(i-1) or staying. """ policy...
This function updates a reinforcement learning model's parameters using temporal difference learning. It calculates state-action value differences, adjusts weight vectors (WA, WB) based on reward deltas and discounting, and updates transition matrices (TA, TB) with policy-dependent learning rates. The process involves ...
def single_step_update(self, s): """ Uses a single step to update the values. """ #take actions and observe the new state and rewards new_s,A,policyA,policyB = self.get_newState_acording_to_Policy(s) uA = utilityA([s[0]*self.eta1,s[1]*self.eta2]) uB = utilityB([self.x1 - s[0]*self.eta1,self.x2 - s[1]*self...
def reconstruction_h_given_v(a,b,w,v,end='False'): ''' reconstruct the hiden layer given a vector v. ''' return np.array([ np.random.choice( [0,1], p=[ p_h_j_given_v(b[j],w[:,j],v),1-p_h_j_given_v(b[j],w[:,j],v) ] ) for j in range(len(b))]) def CD_reconstruction_bias(n,a,b,w,v): ###################!!!!!!!!!!!...
This function performs one training epoch using mini-batch contrastive divergence (CD) to update a model's weights (w), visible biases (a), and hidden biases (b). It shuffles input vectors, computes gradients via CD reconstruction, and updates parameters using the difference between data-driven and model-generated expe...
def one_epoch(self,v): ''' v is a set of vectors. This function will also return the RSE for training porposes, but will be the E_in. The E_out will be monitored each epoch. ''' print('computing one epoch...') n = len(v) #shuffle shuffle_v = list(v) random.shuffle(shuffle_v) shuffle_v = np.array(shuf...
def get_edge_index(): POSE_CONNECTIONS = [ (3, 2), (20, 8), (8, 9), (9, 10), (10, 11), (11, 24), (11, 23), (20, 4), (4, 5), (5, 6), (6, 7), (7, 21), (7, 22), (0, 1), (1, 20), (0, 16), ...
This code initializes a dataset loader for multi-view skeleton data, processing files from a specified folder. It optionally occludes specific keypoints in a randomly selected view per file, creates pose graphs from skeleton frames, and organizes data into three views (C001-C003) with corresponding labels. The main tas...
def __init__( self, dataset_folder: str, skip: int = 11, occlude: bool = False ) -> None: super().__init__(None, None, None) self.dataset_folder = dataset_folder self.edge_index = get_edge_index() self.view1 = [] self.view2 = [] self.view3 = [] self.l...
def prompt_user_for_uid(prompt): """ Prompts the user to enter a valid user ID. This function will not return until a valid ID is entered. Note that this function does not check if the given user ID actually exists; it only checks that the user ID is an integer. :param prompt: The prompt presented to th...
This function handles user login attempts by verifying a provided UID and password against a database. It retrieves the username using the UID, hashes the password with the username, checks for a matching user record, updates the last login date upon success, and transitions to the logged-in screen or displays an error...
def attempt_login_screen(conn): """ This screen handles attempts to login to the system. :param conn: The connection to the database. :return: None. """ cursor = conn.cursor() uid = prompt_user_for_uid("Please enter your user ID:") username = "" cursor.execute("SELECT username FROM ...
def prompt_user_for_command(prompt, command_set): """ Prompt the user for a command from a given set of commands. This function will only return when the user enters a command that is in the command set. :param prompt: The prompt presented to the user. It should list all valid commands. :param comma...
The main task of the code is to present an initial user interface for account creation or login. It loops until the user selects 'quit', handling commands like 'create' (to generate new accounts) or 'login' (to authenticate existing users) by calling corresponding functions, using the provided database connection for b...
def initial_screen(conn): """ This screen is presented to the user when they first run the application. It allows users to create new accounts or login to existing ones. :param conn: The connection to the database. :return: None. """ while True: print() print() user_c...
def search_scrub(title): """ convert to lowercase remove non number or letter characters """ title = str(title) remove_strs = ['[HTML]', '[PDF]', '<scp>', '</scp>' , '<i>', '</i>', '[CITATION]' , '[C]' ] remove_strs.append('-') remove_strs.append('‐') for remove_str in remove_str...
The function processes a JSON file to enrich publication data with metadata from Crossref, handling affiliations, author checks, and saving the updated data as a new JSON file. It retrieves, modifies, and stores scholarly publication details, ensuring authors and affiliations are correctly formatted and validated befor...
def json_meta(fil_src): """ save meta for json """ list_meta = [] fol_src = os.path.join(retrieve_path('gscholar_json_summary'), fil_src) json_src = retrieve_json(fol_src) for pub in json_src['results']: print('title = ') print(pub['title']) pub['title_search'] = s...
def crossref_not_found(item): """ list crossref not found """ missing_json = {} missing_json['pub_count'] = 0 missing_json['pubs'] = [] if 'reset' not in item.keys(): try: missing_json = retrieve_json('missing_json') except: print('missing_json not ...
The function `meta_pubs` processes Google Scholar JSON data by analyzing two tasks: (1) retrieving Crossref information for "compiled" files and individual titles via `json_meta`, and (2) copying Crossref data to non-compiled files using `json_group`. It iterates through specified directories, filters files based on "c...
def meta_pubs(): """ analyze data """ print("running meta_pubs") tasks = [1, 2] if 1 in tasks: # lookup crossref for only compiled gscholar results crossref_not_found({'reset': 'reset'}) list_crossref_without_aff({'reset': 'reset'}) # lookup each title ...
def calc_amb_entropy(self, list_in): list_in = np.asarray(list_in).T prob = list_in[list_in == 1].shape[0] / len(list_in[0]) ent = self.calc_binary_ent(prob) return ent def matrix_entropy(self, matrix, out): matrix = np.matrix(matrix) hent = list() for collumn in ...
This code constructs a decision tree by recursively splitting training data based on entropy and information gain, selecting the optimal feature column for branching, and creating child nodes for each unique value in that column, continuing until nodes are pure or meet stopping conditions.
def create_tree(self, x_train, y_train, tree: sheet): y_train = np.asarray(y_train) ent_tot = self.calc_amb_entropy(y_train) ent = self.matrix_entropy(x_train, y_train) ent_max = max(ent) pos_max = ent.index(ent_max) options = set(np.asarray(x_train.iloc[:, pos_max:pos_ma...
def ends(word, suffix): print(word[-len(suffix):]) return word[-len(suffix):] == suffix def replace(word, suffix, replacement): return word[:-len(suffix)] + replacement def ends_in_double_consonant(word): if len(word) >= 2 and is_consonant(word, len(word) - 1): if word[-1] == word[-2]: return True return F...
This function applies step 1b of the Porter stemming algorithm to a word. It replaces suffixes like "at"→"ate" and "bl"→"ble" if present, shortens double consonants at the end (unless ending in l/s/z), and adds "e" to words with measure 1 ending in CVC. The goal is to reduce words to their root forms by applying morpho...
def step_1b_helper(word): # notice how we're iterating through a list of lists here for suffix_pair in [ [ "at", "ate" ], [ "bl", "ble" ], [ "iz", "ize" ] ]: suffix = suffix_pair[0] replacement = suffix_pair[1] if ends(word, suffix): return replace(wo...
def ends(word, suffix): print(word[-len(suffix):]) return word[-len(suffix):] == suffix def measure(word): cvs = "" for i in range(len(word)): if is_consonant(word, i): cvs = cvs + "c" else: cvs = cvs + "v" return cvs.count("vc") def replace(word, suffix, replacement): return word[:-len(suffix)] + r...
This function implements Step 1b of the Porter stemming algorithm. It handles two cases: (1) replacing "eed" with "ee" if the preceding part has a non-zero measure, and (2) removing "ed" if the preceding part contains a vowel, then recursively applying helper functions to further process the stem.
def step_1b(word): if ends(word, "eed"): if measure(word[:-3]) > 0: return replace(word, "eed", "ee") else: return word if ends(word, "ed"): if contains_vowel(word[:-2]): stem = replace(word, "ed", "") return step_1b_helper(stem) else: return word # TODO return ...
def step_1a(word): if word[-4:] == "sses": # remember, Porter algorithm matches # the longest suffix in each step # and then finishes the step # without checking the other rules return word[:-4] + "ss" # TODO: the rest is up to you! # no rule matches return word def step_1b(word): if e...
The code applies a sequence of stemming steps to reduce a word to its base form by iteratively applying rules for suffix removal, vowel manipulation, and other morphological transformations, following a structured process to normalize words for text analysis tasks like information retrieval or natural language processi...
def stem(word): stem = step_1a(word) stem = step_1b(stem) stem = step_1c(stem) stem = step_2(stem) stem = step_3(stem) stem = step_4(stem) stem = step_5a(stem) stem = step_5b(stem) return stem
def convertHTML(text): return text.replace('&#39;', "'") def checkEmbeddable(videoId): url = "https://www.googleapis.com/youtube/v3/videos?id=%s&part=status&key=%s" % (videoId, DEVELOPER_KEY) response = urllib.request.urlopen(url) # data structure(json) : items -> status -> embeddable embeddable = json....
The code searches YouTube for videos matching a query, filters embeddable videos with both Korean and English subtitles, and downloads their subtitles. It uses the YouTube API to retrieve results, checks subtitle availability, and triggers downloads for qualifying videos.
def youtube_search(options): youtube = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION, developerKey=DEVELOPER_KEY) # Call the search.list method to retrieve results matching the specified # query term. search_response = youtube.search().list( q=options.q, part='id,snippet', maxResults=options....
def lcd_init_function_set(self) : """ Sets Default Configuration: 8bit, 2 Lines per controller, 5x8 Font size. """ command = LCD_DR_FUNCTION_SET | LCD_FUNC_SET_DATA_LENGTH_8BIT | LCD_FUNC_SET_TWO_LINE_NUMBER | LCD_FUNC_SET_FONT_5x8 self.lcd_send_instruction_write_command( command) def lc...
The code initializes an LCD display via I2C, configuring its function settings, enabling display output, clearing the screen, and setting entry mode to prevent left shifting, followed by a 0.2-second delay for stabilization.
def __init__(self, addr=None): """Inits driver and sets initial display configuration.""" self.addr = addr self.i2c = I2CDevice(addr=self.addr, addr_default=LCD_ADDRESS_3C) self.lcd_init_function_set() self.lcd_set_display_on() self.lcd_clear_display() self.lcd_en...
def get_summary_list(self, failed_only=False, columns=None, max_lines=10, wrap_size=8, add_prefix=False, get_logs=True, exp_list=None, savedir_base=None): savedir_base = savedir_base or self.savedir_base exp_list = exp_list or self.exp_list # get job key j...
This function presents a menu to manage experiments, allowing users to reset, run, check status, kill jobs, or debug. It processes user input to perform actions on experiment lists, filtering and executing tasks based on current job states, and updates experiment statuses accordingly.
def launch_menu(self, command=None, exp_list=None, get_logs=False, wait_seconds=3, in_parallel=True): exp_list = exp_list or self.exp_list summary_list = self.get_summary_list(get_logs=False, exp_list=exp_list) summary_dict = hu.group_list(summary_list, key='job_state', retur...
def update(self, dt): self.dt = dt if self._odometryMsg: self._auvState = odometryToState(self._odometryMsg) else: print("No auv state published") return ret = self._calcControlFrames() if ret is None: self.velAUV = np.array([self....
The code runs a control loop at a specified frequency (`self.hz`), continuously updating the system state, publishing control commands, and broadcasting control frames. It maintains a fixed update rate using `rospy.Rate` to ensure real-time execution, with `rate.sleep()` regulating the loop's timing.
def run(self): rate = rospy.Rate(self.hz) while not rospy.is_shutdown(): self.update(1./self.hz) self.publishControlCommand() self.publishControlFrames() rate.sleep()
def get_actress_string(html, s): """Return the string of the actress names as per the naming convention specified Takes in the html contents to filter out the actress names""" a_list = get_actress_from_html(html, s) actress_string = '' # if javlibrary returns no actresses then we'll just say whateve...
The function renames a file based on user settings, incorporating video ID and actress names if enabled. It constructs a new filename using vid_id, actress string, and video number (if specified), then attempts to rename the file. If renaming fails or is disabled, it returns the original path. The function always retur...
def rename_file(path, html, s, vid_id): """Rename the file per our settings Returns the name of the file regardless of whether it has been renamed""" if s['do-not-rename-file']: return path else: if s['include-actress-in-video-name']: actress_string = get_actress_string(html,...
def strip_definition_from_video(vid_id): """Strip any sort of HD tag from the video""" hd = ['[HD]', '[FHD]', '[SD]', '(SD)', '(HD)', '(FHD)'] for item in hd: vid_id = vid_id.replace(item, '') return vid_id def get_actress_string(html, s): """Return the string of the actress names as per th...
The function creates a folder based on a video ID and optionally an actress name, then attempts to move the video file into this folder. It handles cases where the folder already exists, checks for path length limits, and returns the new path if successful or the original path if errors occur, such as existing files or...
def create_and_move_video_into_folder(path, s, vid_id, html): """Create a folder and then move the given video into it Path is the fullpath of the video Returns the new path of the video Returns the old path if there's an unknown error""" folder_name = strip_definition_from_video(vid_id) if s['i...
def get_image_url_from_html(html): """get the url of the image from the supplied html for the page""" return "http:" + html.split('<img id="video_jacket_img" src="')[1].split('" width')[0] def strip_partial_path_from_file(path): """given a file, strip the path from the file name This is the essentially ...
The function retrieves a cover image from HTML, constructs a filename based on user settings (including actress names, video numbers, and delimiters), saves the image to a specified path, and optionally crops it to a standard size (378x539). It handles renaming and cropping logic conditionally based on configuration fl...
def get_cover_for_video(path, vid_id, s, html): """Get the cover for the video denoted by path from the specified html""" # path needs to be stripped but otherwise we can use it to store the video # html should have the cover there we can take img_link = get_image_url_from_html(html) # TODO: # c...
def df_current_state(self, df, buf, name): self.logger.debug(f"Current {name}.head()\n{df.head()}") df.info(buf=buf) self.logger.debug(f"Current {name}.info()\n{buf.getvalue()}") self.logger.debug(f"Current {name}.describe()\n{df.describe(include='all')}") def create_x_and_y_dfs(self): ...
The code's main task is to initialize and process training/test data, create feature-label datasets, split data, and evaluate multiple machine learning models (k-NN, decision tree, random forest, AdaBoost, XGBoost) for classification. It logs debug messages at key stages, including class initialization and closure.
def start(self): self.logger.debug('Starting Class') self.df_current_state(self.train, self.buf1, 'train') self.df_current_state(self.test, self.buf2, 'test') self.create_x_and_y_dfs() self.make_train_test_split() self.make_test_probability_like() self.test_kneigh...
def init_flow(self): self.vec_flow = np.array([[0] for x in range(self.num_path)], dtype=float) # self._build_const_vec() self._eval_cost_function() for (u, v) in list(self.demand_graph.edges): e = self.demand_graph.edges[(u, v)] vec_temp_D = np.array(self.mat_Dpa...
This function solves for Stochastic User Equilibrium (SUE) by iteratively updating traffic flow until the gap (equilibrium measure) falls below a precision threshold. It initializes flow/cost, computes initial gap, then iterates with step-size adjustments, tracking gap, flow, and cost at each step. Results are printed/...
def solve_sue(self, precision = 1e-3, max_iterations = 500, step_size = 0.5, print_gap = True, plot_gap = True): self.sue_gap_list = list() self.sue_flow_list = list() self.sue_cost_list = list() self.init_flow() self._eval_cost_function() initial_gap = self.compute_sue_g...
def init_flow(self): self.vec_flow = np.array([[0] for x in range(self.num_path)], dtype=float) # self._build_const_vec() self._eval_cost_function() for (u, v) in list(self.demand_graph.edges): e = self.demand_graph.edges[(u, v)] vec_temp_D = np.array(self.mat_Dpa...
This function solves a Stochastic User Equilibrium (SUE) problem via iterative updates. It initializes traffic flows, computes initial gap values, and iteratively adjusts flows using shortest path algorithms. The process continues until the gap (difference from initial) falls below a precision threshold or reaches max ...
def solve_sue_hcg(self, precision = 1e-3, max_iterations = 500, step_size = 0.5, print_gap = True, plot_gap = True): self.sue_gap_list = list() self.sue_flow_list = list() self.init_flow() self._eval_cost_function() initial_gap = self.compute_sue_gap() if print_g...
def init_curbcharge(self): self.vec_curb_charge = np.array([[self.const_initial_curb_charge] for x in range(self.num_link)]) def solve_sue(self, precision = 1e-3, max_iterations = 500, step_size = 0.5, print_gap = True, plot_gap = True): self.sue_gap_list = list() self.sue_flow_list = list() ...
This function optimizes curb charge values to minimize social cost in a network using iterative gradient-based algorithms (e.g., GD, ADAG). It initializes parameters, solves the stochastic user equilibrium (SUE), updates charges iteratively, computes social cost gaps, and records flow, cost, and charge data across iter...
def solve_curbcharge(self, step_size = 1, max_iterations = 15, sue_precision = 1e-3, sue_max_iterations = 3000, \ sue_step_size = 0.5, print_gap = True, nneg = True, alg_type = 'adag'): self.init_curbcharge() # initialize curbcharge = 0.0 self.charge_gap_list = list() se...
def get_egdar_archive_years(data_dir: pathlib.Path, check_page: bool = False) -> pd.DataFrame: file_path = data_dir.joinpath("edgar_archive_years.csv") if not file_path.is_file() or check_page: year_table_rows = extract_year_table_rows_from_edgar_archive_feed() edgar_archive_years_df = extract_d...
The main task of the code is to retrieve metadata files from the Edgar archive by iterating through all available years and quarters in the specified data directory. It fetches yearly data, then processes each quarter, printing progress and collecting metadata files for each quarter. The function includes a random dela...
def retrieve_all_edgar_archive_metadata_files(data_dir: pathlib.Path) -> None: edgar_archive_years_df = get_egdar_archive_years(data_dir=data_dir) for year in edgar_archive_years_df["Name"]: edgar_archive_year_qtrs_df = get_edgar_archive_year_quarters(year=year, data_dir=data_dir) for edgar_arch...
def set_params(self, kern_lengthscale: float=None, kern_variance: float=None, noise_variance: float=None) -> None: if any([kern_lengthscale, kern_variance, noise_variance]) <=0: raise ValueError('paramters must be positive. {}', [kern_lengthscale, kern_variance, noise_variance]) if kern_leng...
This function computes the negative log marginal likelihood (NLML) and its gradients for optimization, handling invalid theta values (zero, NaN, inf) by resetting them to kernel parameters. It converts theta to kernel parameters, evaluates NLML, calculates gradients, and returns the value and gradient for optimization.
def optimize_fcn_and_grad(theta): if theta[0]==0 or theta[1]==0: # print('opt fcn 0') theta = vars_to_theta(self.kern.lengthscale, self.kern.variance) # code.interact(local=locals()) if np.isnan(theta[0]) or np.isinf(theta[0]): #p...
def get_saved_tracks(self): ret = [] data_saved_tracks = self._get_all_saved_tracks_unformatted() for track in data_saved_tracks: ret.append(track["track"]["id"]) return ret def get_saved_albums(self): ret = [] data_saved_albums = self._get_all_saved_albums_un...
The main task of the code is to compile and return a structured dictionary containing a user's account data, including saved tracks, albums, playlists, followed artists, and users. It aggregates data from multiple methods like `get_saved_tracks()` and `get_followed_artists()` into a unified template format for organize...
def get_account_data(self): ''' RETURN TEMPLATE: { "saved_tracks":[TRACK_IDS], "saved_albums":[ALBUM_IDS], "created_playlists":[{ "name":NAME, "description":DESCRIPTION, "id":PLAYLIST_ID, ...
def as_stac_item(dataset: DatasetItem) -> pystac.Item: """ Get a dict corresponding to a stac item """ ds: Dataset = dataset.odc_dataset if ds is not None and is_doc_eo3(ds.metadata_doc): dataset_doc = serialise.from_doc(ds.metadata_doc, skip_validation=True) dataset_doc.locations =...
This function searches for STAC items using filters like product names, time ranges, spatial bounds, and dataset IDs. It handles pagination, applies query extensions, and returns a structured ItemCollection with metadata, including 'next' links for additional results.
def search_stac_items( get_next_url: Callable[[int], str], limit: int = DEFAULT_PAGE_SIZE, offset: int = 0, dataset_ids: Optional[str] = None, product_names: Optional[List[str]] = None, bbox: Optional[Tuple[float, float, float, float]] = None, intersects: Optional[BaseGeometry] = None, t...
def root_catalog(): c = Catalog( **stac_endpoint_information(), ) c.set_self_href(url_for(".root")) return c def url_for(*args, **kwargs): if FORCE_ABSOLUTE_LINKS: kwargs["_external"] = True return flask.url_for(*args, **kwargs) def _stac_response( doc: Union[STACObject, Item...
The main task of the code is to construct a STAC root catalog by generating links to key endpoints like collections, arrivals, item search, and product catalogs, while specifying conformance classes to OGC/STAC standards. It assembles a JSON response with navigation links and compliance information for a standardized A...
def root(): """ The root stac page links to each collection (product) catalog """ c = root_catalog() c.links.extend( [ Link( title="Collections", # description="All product collections", rel="children", media_type="a...
def url_for(*args, **kwargs): if FORCE_ABSOLUTE_LINKS: kwargs["_external"] = True return flask.url_for(*args, **kwargs) def _geojson_stac_response(doc: Union[STACObject, ItemCollection]) -> flask.Response: """Return a stac item""" return _stac_response(doc, content_type="application/geo+json") d...
This function retrieves a dataset by ID, validates if the provided collection name matches the dataset's product name, and returns a GeoJSON STAC response. If the dataset or collection is invalid, it raises a 404 error with a corrective URL suggestion.
def item(collection: str, dataset_id: str): dataset = _model.STORE.get_item(dataset_id) if not dataset: abort(404, f"No dataset found with id {dataset_id!r}") actual_product_name = dataset.product_name if collection != actual_product_name: # We're not doing a redirect as we don't want p...
def _update_subscriber_nodes(self) -> None: """Used to update subscriber nodes by spinning once.""" rclpy.spin_once(self.odometry_subscriber_node) rclpy.spin_once(self.velocity_subscriber_node) rclpy.spin_once(self.laserscan_subscriber_node) def _get_observation(self): """Get obs...
The code simulates a robotic step by executing a given action (velocity/angular velocity), updating observations, and checking for task completion or wall collision. It clamps action values, publishes movement commands, waits, then evaluates distance to the target and laser scan data. If the robot reaches the target or...
def step(self, action: np.ndarray, time_per_action=0.1): """Do a step with specified time (in seconds) per action. Order of execution: action, new observation, calculate potential reward, check if on target position or hitting wall. Args: action (np.ndarray): Action to take (velocity and an...
def write_vcd_trace(steps_start, steps_stop, index): filename = vcdfile.replace("%", index) print_msg("Writing trace to VCD file: %s" % (filename)) with open(filename, "w") as vcd_file: vcd = MkVcd(vcd_file) path_list = list() for netpath in sorted(smt.hiernets(topmod)): ...
The function `write_trace` conditionally writes simulation trace data to various output files based on which global variables (`vcdfile`, `vlogtbfile`, `outconstr`, `outywfile`) are defined. It calls corresponding functions (`write_vcd_trace`, `write_vlogtb_trace`, etc.) with parameters `steps_start`, `steps_stop`, and...
def write_trace(steps_start, steps_stop, index, allregs=False): if vcdfile is not None: write_vcd_trace(steps_start, steps_stop, index) if vlogtbfile is not None: write_vlogtb_trace(steps_start, steps_stop, index) if outconstr is not None: write_constr_trace(steps_start, steps_stop...
def get_current_branch(self): logger.debug("current branch is '%s'", self.repo.active_branch) return self.repo.active_branch def get_targets(self, branches, skip_develop=False, filter_origin=True): major, minor = self._get_major_minor(self.initial_branch.name) # filter all release branch...
The function fetches and checks out missing release branches from the remote repository, then reverts to the original branch. It retrieves remote references, filters for release branches, and ensures each is available locally by checking them out. After processing, it restores the initial branch to maintain the workflo...
def fetch_missing_release_branches(self): original_head = self.get_current_branch() try: targets = self.get_targets(self.remote.refs, skip_develop=True, filter_origin=False) for ref in targets: if self._is_release(ref.remote_head): logger.info(...
def _is_release(self, branch_name): match = self.release_pattern.match(branch_name) return True if match else False def fetch_missing_release_branches(self): original_head = self.get_current_branch() try: targets = self.get_targets(self.remote.refs, skip_develop=True, filter_...
The main task of the code is to merge a sequence of release branches into target branches. It verifies the initial branch is a release branch, fetches required branches, iterates through targets, checks out each target, pulls updates, merges the previous branch, pushes changes to origin, and updates the current branch ...
def main(self): if not self._is_release(self.initial_branch.name): raise Exception("So weird, not on a release branch") self.fetch_missing_release_branches() # 0. figure out the list of branches to merge to targets = self.get_targets(self.repo.refs) last_branch = se...
def _model_config_max_age(self): return self.model_config.max_age if self.model_config else None def _default_max_age(self): max_age = getattr(self.model, 'max_age', self.DEFAULT_MAX_AGE) if isinstance(max_age, int): return timedelta(days=max_age) if isinstance(max_age, time...
This function constructs a Django Q object to filter records based on time constraints and field-specific configurations. It calculates a time limit using model-configured or default max age, then combines field-based queries (using AND/OR logic) with time-based filters. The result is a composite query that either retu...
def _build_filter_query(self): model_max_age = self._model_config_max_age() if self._model_config_max_age() else self._default_max_age() model_time_limit = timezone.now() - model_max_age if model_max_age else None field_configs = self._model_config_field_configs() field_filter_query = N...
def _created_at_field(self): return getattr(self.model, 'created_at_field', self.DEFAULT_CREATED_AT_FIELD) def _initialize(self): self.model_config = self._get_model_config() def _build_filter_query(self): model_max_age = self._model_config_max_age() if self._model_config_max_age() else self._de...
The code's main task is to generate a filtered queryset by checking if the model has a specific timestamp field, initializing necessary state, building a filter query, and applying it. If the field is absent or the filter is empty, it returns an empty queryset.
def get_queryset(self): if not hasattr(self.model, self._created_at_field()): return super().get_queryset().none() self._initialize() query = self._build_filter_query() if query: return super().get_queryset().filter(query) return super().get_queryset().n...
def CreateNotebook(self): """ Creates the notebook widget to contain the tabs for each frame. """ self.sections = ttk.Notebook(self.win) self.sections.pack(fill='both', expand=1,pady=10) self.AddSections() def removeVehicle(self, vehicleID): """ Removes th...
This code initializes a fullscreen GUI application with a database connection, creates styled tabs for different functionalities (Home, Process, Quality, DB), sets up event handlers for tab changes and barcode input, and configures UI elements like buttons, fonts, and progress bars to manage vehicle data and applicatio...
def __init__(self): """ This class creates the main window for the application. Upon initialization, the class creates a new fullscreen window and places the tabs containing each frames functionalities. """ # Lab pass # self.db = Database('localhost', 'root', 'ind...
def prepare_batch(self, batch, force_overfit_batch = False): if (batch is None) or (force_overfit_batch): batch = self.overfit_batch (xlo, xhi), y = batch xlo, xhi, y = xlo.to(self.device), xhi.to(self.device), y.to(self.device) z1 = self.center(xhi) D = {'N': z1...
The main task of the code is to generate samples using an ODE solver on a preloaded overfitting batch, log them for monitoring, and return the results. It sets the model to evaluation mode, prepares a fixed batch, solves the ODE to obtain latent trajectories (zT), and logs these samples via WandB for tracking during tr...
def definitely_sample(self,): self.model.eval() # for monitoring sampling, uses initial condition z0 # and also label y from the saved overfitting batch. data_dict = self.prepare_batch(batch = None, force_overfit_batch = True) zT = self.odeint(data_dict) self.maybe_log_w...
def definitely_sample(self,): self.model.eval() # for monitoring sampling, uses initial condition z0 # and also label y from the saved overfitting batch. data_dict = self.prepare_batch(batch = None, force_overfit_batch = True) zT = self.odeint(data_dict) self.maybe_log_w...
This code trains a machine learning model by iterating over epochs and batches, updating model parameters via backpropagation, tracking training steps, and periodically printing loss values. It includes sampling, data preparation, and optimization steps within a loop constrained by a maximum step limit.
def fit(self,): self.definitely_sample() print("starting training") while self.global_step < self.config.max_steps: print(f"starting epoch {self.current_epoch}") for batch_idx, batch in enumerate(self.loader): if self.global...
def screenCoordToRay(window, x, y): width, height = glfw.get_window_size(window) matProjection=glGetDoublev(GL_PROJECTION_MATRIX).T matProjection=matProjection@wld2cam[cameraIndex]; # use @ for matrix mult. invMatProjection=np.linalg.inv(matProjection); # -1<=v.x<1 when 0<=x<width # -1<=v.y<1 w...
This function handles mouse dragging to manipulate a 3D cow model. It calculates ray-plane intersections for vertical/horizontal dragging, updates the cow's position based on cursor movement, and adjusts transformation matrices. During dragging, it maintains cursor interaction with the cow's bounding box, updating pick...
def onMouseDrag(window, x, y): global isDrag,cursorOnCowBoundingBox, pickInfo, cow2wld, clicked_pos if isDrag: if isDrag==V_DRAG: # vertical dragging # TODO: # create a dragging plane perpendicular to the ray direction, # and test intersection with the ...
def drawOtherCamera(): global cameraIndex,wld2cam, camModel for i in range(len(wld2cam)): if (i != cameraIndex): glPushMatrix(); # Push the current matrix on GL to stack. The matrix is wld2cam[cameraIndex].matrix(). glMultMatrixd(cam2wld[i].T) drawFrame(5);...
The main task of the code is to animate a 3D cow model by updating its transformation matrix (cow2wld) over time, using interpolated positions from a predefined array (cow2wld_arr) to create smooth motion. It renders the animated cow in a 3D scene with multiple camera views, clears the screen, applies viewing transform...
def display(): global cameraIndex, cow2wld, cow2wld_arr, start_time, animate_count, curr_pos, prev_coeff_idx glClearColor(0.8, 0.9, 0.9, 1.0) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); # Clear the screen # set viewing transformation. glLoadMatrixd(wld2cam[cameraIndex].T) drawOtherCa...
def clean_up(): global animate_count, cow2wld_arr, isDrag, first_click, cow2wld, pickInfo, curr_pos, start_cow2wld animate_count = 0 cow2wld_arr.clear() isDrag = 0 first_click = True cow2wld = start_cow2wld.copy() setTranslation(cow2wld, curr_pos) pickInfo.cowPickPosition = curr_po...
This function handles mouse button events for 3D model interaction. It enables vertical/horizontal dragging to capture cow model positions, stores six positions for Catmull-Rom spline animation, and triggers interpolation when six points are collected. Left-click initiates vertical dragging, release switches to horizon...
def onMouseButton(window,button, state, mods): global isDrag, V_DRAG, H_DRAG, first_click, clicked_pos, cow2wld_arr, cow2wld, pickInfo, cursorOnCowBoundingBox, coeff_arr, animate_count, start_time, curr_pos GLFW_DOWN=1; GLFW_UP=0; x, y=glfw.get_cursor_pos(window) if button == glfw.MOUSE_BUTTON_LEFT:...
def episode_step(state, env, policy, Q, memory, ep_no, eps_min, eps_steps_till_min): policy.set_epsilon(get_epsilon(ep_no, eps_min, eps_steps_till_min)) action = policy.sample_action(Q, state) next_state, reward, done, _ = env.step(action) memory.push([state, action, reward, next_state, done]) ret...
This function runs multiple episodes of a reinforcement learning environment, training a Q-network using experience replay. It tracks episode durations, cumulative returns, starting positions, and Mean Squared Temporal Difference (MSTD) errors. The Q-network is updated via the train function, which computes loss and MS...
def run_episodes(train, QWrapper, policy, env, args): # optimizer = optim.Adam(Q.parameters(), args.stepsize) ep_no = 0 global_steps = 0 episode_durations = [] episode_returns = [] starting_positions = [] MSTD_per_update = [] eps_MSTDs = [] for i in range(args.num_episodes): ...
def adjacentLocations(position): ''' Return pieces adjacent to the piece at position @param position: index of the piece ''' adjacent = [ [1, 3], [0, 2, 9], [1, 4], [0, 5, 11], [2, 7, 12], [3, 6], [5, 7, 14], [4, 6], [9, 11], [1, 8, 10, 17], [9, 12], [3, 8, 13, 19], [4, 10, 15, 20], [11...
This function counts the number of a player's pieces on a board that are in positions capable of forming a mill if an adjacent opponent's piece is removed. It iterates through each of the player's pieces, checks adjacent positions, temporarily modifies the board to simulate removing an opponent's piece, and increments ...
def getPiecesInPotentialMillFormation(board, player): ''' ''' count = 0 for i in range(len(board)): if (board[i] == player): adjacent_list = adjacentLocations(i) for pos in adjacent_list: if (player == "1"): if (board[pos] == "2"): board[i] = "2" if isCloseMill(i, board): count ...
def adjacentLocations(position): ''' Return pieces adjacent to the piece at position @param position: index of the piece ''' adjacent = [ [1, 3], [0, 2, 9], [1, 4], [0, 5, 11], [2, 7, 12], [3, 6], [5, 7, 14], [4, 6], [9, 11], [1, 8, 10, 17], [9, 12], [3, 8, 13, 19], [4, 10, 15, 20], [11...
The main task of the code is to generate all valid stage 2 moves on a board by iterating through positions with "1", swapping them with adjacent "X" pieces, and handling mill formations. It creates deep copies of the board for each valid swap, removes pieces if a mill is formed, and returns the list of resulting board ...
def stage2Moves(board): ''' @param board: current list ''' board_list = [] for i in range(len(board)): if (board[i] == "1"): adjacent_list = adjacentLocations(i) for pos in adjacent_list: if (board[pos] == "X"): board_clone = copy.deepcopy(board) board_clone[i] = "X" board_clone[pos] =...
def get_element(self, source, xpath='.'): """Returns an element in the `source` matching the `xpath`. The `source` can be a path to an XML file, a string containing XML, or an already parsed XML element. The `xpath` specifies which element to find. See the `introduction` for more detail...
This function retrieves all text content from an element specified by `source` and `xpath`, including nested descendants. It returns the combined text as a single string, with optional whitespace normalization (removing leading/trailing spaces, converting newlines/tabs to spaces, and collapsing multiple spaces). If no ...
def get_element_text(self, source, xpath='.', normalize_whitespace=False): """Returns all text of the element, possibly whitespace normalized. The element whose text to return is specified using `source` and `xpath`. They have exactly the same semantics as with `Get Element` keyword. ...
def get_element(self, source, xpath='.'): """Returns an element in the `source` matching the `xpath`. The `source` can be a path to an XML file, a string containing XML, or an already parsed XML element. The `xpath` specifies which element to find. See the `introduction` for more detail...
This function removes all elements matching the given XPath from the source structure, modifying and returning it. If no elements match, it's not an error. The `remove_tail` parameter optionally removes element tail text, similar to `Remove Element`. It contrasts with `Remove Element` (for single removal) and `Add Elem...
def remove_elements(self, source, xpath='', remove_tail=False): """Removes all elements matching `xpath` from the `source` structure. The elements to remove from the `source` are specified with `xpath` using the same semantics as with `Get Elements` keyword. The given `source` structure...
def process_file(filename): """Makes a histogram that contains the words from a file. filename: string returns: map from each word to the number of times it appears. """ hist = {} fp = open(filename) for line in fp: process_line(line, hist) return hist def total_words(hist): ...
The main task of the code is to process a financial text file, calculate total word count, identify common words, extract revenue figures from financial statements, and generate a graph visualizing word frequency. It analyzes textual data and financial metrics from Bear Stearns' 10-Q filing, providing statistical insig...
def main(): hist = process_file('Bear Stearns_10Q_2-29-2008.txt') print('Total number of words:', total_words(hist)) print('The most common words are:') most_common(hist) print("Here are the revenue figures from '08 - '07") financial_statements('Bear Stearns_10Q_2-29-2008.txt') print("And...
def _build_model(self): """ Build the FCDSEBM model in TensorFlow. :return: self """ self.input_data = self._create_placeholders() self.W, self.bias, self.global_bias = self._create_variables() optimizer = tf.train.GradientDescentOptimizer(self.learning_rate) h = [None]*len(self.layer_shape) h[0] = s...
This method fits a machine learning model to a training dataset using TensorFlow. It builds the model, initializes a TensorFlow session, sets up utilities, and trains the model. If a validation set is provided, it tracks its size. The training process uses both the training and validation data for model optimization.
def fit(self, train_set, validation_set=None,): """ Fit the model to the training data. :param train_set: training set :param validation_set: validation set. optional, default None :return: self """ if validation_set is not None: self.validation_size = validation_set.shape[0] self._build_model() ...
def _merge_default(self, p, dp): """Add skipped key from default. * copy from dp cnfg level and section levels 'global' if not exist, otherwise ignore. * Copy skipped sections from dp (could be multiple confs). * Copy skipped sub-keys from dp section(s) of the same name. ...
The function processes configuration data by merging default values, resolving global/None placeholders, prioritizing sections, and validating the structured result. It returns a prioritized list of configuration tuples after applying defaults and checks.
def _parse_cnfg(self, p, dp, resolve_none, update_expl): # Apply default. p = self._merge_default(p, dp) # Resolve global / None. p = self._resolve(p, resolve_none, update_expl) # Arrange in priority. res = self._priority_arrange(p) # [('section_id__config__id', config)]...
def make_move_mp(self, row, col, ttt_current_player): try: message = "TicTacToe:"+str(row)+","+str(col) print(row,col,ttt_current_player) if self.board[row][col] == ' ' and ttt_current_player != self.ttt_previous_player: # Check if the selected cell is empty AND the ...
This code initializes a Tic-Tac-Toe game GUI with a 3x3 board, setting up the window, game name, and player tracking. It creates interactive buttons for each grid cell, assigning different move-handling methods based on the specified game type (multiplayer or single-player). The buttons are configured to trigger respec...
def __init__(self, master, type): global gameName gameName="TicTacToe" # setting the game name to "TicTacToe" self.master = master self.master.title("Tic-Tac-Toe") self.type=type self.board = [[' ' for _ in range(3)] for _ in ran...
def exchange(self): _input = self.input.get() _output = self.output.get() self.input.delete(0, 'end') self.input.insert(0, _output) self.output.delete(0, 'end') self.output.insert(0, _input) coin_fx.play() def commands(self, execute): self.validate() ...
This code creates a GUI for a currency conversion tool using Tkinter. It sets up a header with a query preview, input/output sections for selecting coins and entering values, buttons to trigger exchange/calculation, a graphic area to display conversion data, and a footer with metadata. The layout includes labeled frame...
def widgets(self, execute): # Header - Query preview box self.header = tk.Canvas(self, background="black") self.header.grid(column=0, row=0, columnspan=3, rowspan=3, padx=10, pady=15) # Info text self.info_text = tk.Label(self.header, text=self.messages[self.process], anchor='cen...
def filterByPeriod(directory, min_period=60*60*3): path = os.path.join(directory, "Trajectory") trajectories = getTrajectories(path) filtered_trajectories = [] for trajectory in trajectories: with open(trajectory, "r") as f: skipFirstLines(f) firstline = f.readline() ...
The code checks if the number of unique days derived from the first timestamp of each trajectory file in the specified directory meets or exceeds a given minimum threshold (default 90 days). It processes trajectory files, extracts timestamps, converts them to date strings, and verifies if the count of distinct days sat...
def filterByDays(directory, min_days=90): trajectories = filterByPeriod(directory) timestamps = [] for trajectory in trajectories: with open(trajectory, "r") as f: skipFirstLines(f) first_timestamp = getTimestamp(f.readline()) timestamps.append(first_timestamp) ...
def strip_measurements(self, x, metrics): found_metrics = '' keep_words = '' for word in x.split(' '): if word in metrics: found_metrics = found_metrics + ' ' + word else: keep_words = keep_words + ' ' + word return keep_words + '|'...
This code cleans and standardizes recipe ingredients by removing measurements, lemmatizing terms, categorizing ingredients, and aggregating metrics and quantities. It processes the 'ingredient' column to extract and separate metrics, standardizes names using lemmatization and predefined lists, and prepares a structured...
def clean_list(self): lmtzr = WordNetLemmatizer() self.final_df['original_recipe'] = self.final_df['ingredient'] self.final_df['ingredient'] = self.final_df['ingredient'].apply(lambda x: self.strip_measurements(x, self.metrics)) self.final_df['metric'] = self.final_df['ingredient'].apply...
def take_token(self, token_type): if self.token.type != token_type: self.error("Unexpected token: %s" % token_type) if token_type != 'EOF': self.token = self.next_token() def value(self): # value -> NUMBER if self.token.type == 'NUMBER': self.take_token('NUMBER') # value -> ID ...
This code processes deployment configuration by recursively parsing tokens. It handles three cases: setting a mode, specifying replicas, or defining an endpoint mode. For each case, it consumes the keyword token, processes the associated value/number, prints confirmation, and continues parsing. The base case prints "De...
def deploy(self): # deploy -> mode_keyword value if self.token.type == 'mode:': self.take_token('mode:') self.value() print("Mode OK") self.deploy() # deploy -> replicas_keyword NUMBER elif self.token.type == 'replicas:': self.take_token('replicas:') self.take_token('...
def take_token(self, token_type): if self.token.type != token_type: self.error("Unexpected token: %s" % token_type) if token_type != 'EOF': self.token = self.next_token() def value(self): # value -> NUMBER if self.token.type == 'NUMBER': self.take_token('NUMBER') # value -> ID ...
This code parses service configurations by recursively handling keywords like 'networks:', 'image:', 'ports:', etc., validating tokens, and ensuring correct syntax. It processes parameters, calls associated methods, and prints confirmation messages for each parsed element, ultimately verifying the service structure.
def services(self): # services_keyword -> WORD services_keyword if self.token.type == 'WORD': self.take_token('WORD') self.services() # services_keyword -> networks_keyword OP value services_keyword elif self.token.type == 'networks:': self.take_token('networks:') if self.token...
def take_token(self, token_type): if self.token.type != token_type: self.error("Unexpected token: %s" % token_type) if token_type != 'EOF': self.token = self.next_token() def services(self): # services_keyword -> WORD services_keyword if self.token.type == 'WORD': self.take_token('WOR...
This code processes a token to determine which configuration keyword it represents (services, version, volumes, or networks), consumes the token, and invokes the corresponding method to handle that section. If the token doesn't match any valid keyword, it raises an error for invalid input.
def keyword(self): # keyword -> services_keyword if self.token.type == 'services:': self.take_token('services:') self.services() # keyword -> version_keyword elif self.token.type == 'version:': self.take_token('version:') self.version() # keyword -> volumes_keyword elif ...
def n(var): """ Logically negates a variable. """ if var[0] == '~': return var[1:] else: return '~' + var def all_cnf(self, *vlist): if len(vlist) == 0: return self.T elif len(vlist) == 1: ans = self.junkvar() self.l_iff(ans, vlist[0]) ...
This function recursively evaluates a tokenized logical expression into a structured formula, handling operators like negation (~), conjunction (&), disjunction (|), XOR (^), equivalence (=), implication (=, and lists. It converts expressions into CNF (conjunctive normal form) representations, using macros for complex ...
def expr_tree(self, toks): """ get the result of an expression """ if isinstance(toks, str): return toks elif isinstance(toks, int): return self.T if toks else self.F elif len(toks) == 1: return self.expr_tree(toks[0]) else: whichfn...
def l_iff(self, a, b): # a iff b self.ext([n(a), b], [a, n(b)]) def expr_tree(self, toks): """ get the result of an expression """ if isinstance(toks, str): return toks elif isinstance(toks, int): return self.T if toks else self.F elif len(toks) == 1: ...
The code parses a program into tokens, identifies assignments (=) or implications (=, and applies corresponding logical operations (l_iff, l_if) or treats expressions as constraints (l_ist) to enforce truth.
def run(self, prog): """ parse and run a program """ tokens = grammar.parseString(prog).asList() for stat in tokens: if len(stat) == 3 and isinstance(stat[1], str): # check if this is a constr if stat[1] == '=': self.l_iff(self.expr_tree(stat[0]), ...
def create_ref(path): """ Create a json definition reference to a specific path """ return '#/definitions/' + path def add_definition(root_definitions_object: dict, current_path: str, curr_object: dict, queue: list) -> None: """ Create a property or item definition depending on if property or i...
The main task of the code is to flatten a nested Swagger JSON structure into a flat format with references, enabling compatibility with OpenAPI generators. It processes each definition, recursively flattens nested properties by creating $ref links, and constructs a new swagger.json file with simplified definitions, pat...
def flatten(consolidated_crds_object: dict) -> None: """ Flatten and then produce a new swagger.json file that can be processed by open-api-generator """ original_definitions = consolidated_crds_object['definitions'] flattened_swagger_object = { 'definitions': {}, 'paths': {}, ...
def split_value(cd, points): # returns the value to do the splitting in the kd tree pts = points[:, cd] # cd: current dimension split_val = find_i_th_smallest(pts, int(np.ceil(len(pts)/2))-1) return split_val def split_list(cd, points, split_val): # split a list based on the dimension and split val...
The code constructs a k-d tree recursively by splitting points along axes determined by depth modulo k. It partitions points into left and right subtrees using a split value, then recursively builds child nodes until all points are processed.
def buildKdTree(node, points, depth=0, k=2): if len(points) <= 0: return if len(points) == 1: node.val = points[0] return node else: cd = depth % k split_val = split_value(cd, points) node.val = split_val left_list, right_list = split_list(cd, points, ...
def pwlq_coarse2fine_grid_search(w, bits=4.0, scale_bits=0.0, search_range=10, pw_opt=2): ''' Coarse-to-fine grid search for optimal breakpoint to minimize the quantization error Search for optimal breakpoint ratio: bkp_ratio = break_point / abs_max ''' min_err = 10000 abs_max = torch.max(torch....
This function performs Piecewise Linear Quantization (PWLQ) on input weights, returning quantized values, breakpoint ratio, and error. It uses either a grid search for optimal breakpoints or distribution-based methods (Gaussian/Laplacian) to determine breakpoints, then quantizes weights with specified bit-depths, adjus...
def piecewise_linear_quant(w, bits=4.0, scale_bits=0.0, break_point_approach='norm', pw_opt=2, approximate=False): ''' Piecewise Linear Quantization (PWLQ) ''' if break_point_approach == 'search': ## coarse-to-fine grid search for minimizing quantization error w...
def binarySearch(item, l): sortBy(l) min = 0 max = len(l)-1 guess = int(((min + max)/2)) while(min<max and l[guess] != item): if(l[guess]>item): max = guess-1 elif(l[guess]<item): min = guess +1 guess = int(((min + max)/2)) if(item == l[guess]): ...
The code presents a menu allowing users to search for records by ID code, first name, last name, or allegiance. It uses binary search for ID and first name, sequential search for last name and allegiance, displaying matching records or error messages. The goal is to retrieve and display specific data based on user-sele...
def menu(): a = input("\t\t Search Menu\n\t\t1. Search ID Code\n\t\t2. First Name\n\t\t3. Last Name\n\t\t4. Allegiance\nWhich option would you like to choose: ") if(a == '1'): item = input("\nWhat ID code would you like to search for: ") _, i = binarySearch(item, idCode) clear() ...
def _dr_range_info(self, collector: DrInfoBuilder, session_df: pd.DataFrame, session_schedule: tuple, session_type: str): collector.dr_type = session_type collector.dr_open = PricePoint(price=session_df.loc[session_schedule[0]], time=session_schedule[0]) dr_close_time = se...
The function `get_dr_info` extracts technical analysis metrics from trading session data, including DR/IDR ranges, session extremes (open/close/high/low), confirmation signals, and extension/retracement patterns. It aggregates these into a structured `DrInfo` object for further analysis, using helper methods to compute...
def get_dr_info(self, session_df: pd.DataFrame, dr_sessions_times: dict[str, datetime], session_type: str): info_collect: DrInfoBuilder = DrInfoBuilder() session_schedule: tuple = dr_sessions_times[session_type] # DR range info (Only first hour of the session) # Collects: dr_high, dr_lo...
def create_data_segments(self): """Create the data segment dictionaries.""" self.data['ins_t'] = OrderedDict() self.data['ins'] = OrderedDict() self.data['cal'] = OrderedDict() self.data['lab'] = OrderedDict() self.data['pre'] = OrderedDict() self.data['error'] = False self.data['no_lineage'] = [] def ...
This code initializes an object to process and extract structured financial data (likely from XBRL filings) using a ticker symbol, date, and file type. It sets up data storage, loads files, extracts labels, calculations, and formats the data into a standardized structure, preparing it for further analysis or reporting.
def __init__(self, symbol, date, ftype): self.ticker = symbol self.date = date self.ftype = ftype self.symbol = None self.data = OrderedDict() self.ins_sp = None self.schema_sp = None self.cal_sp = None self.def_sp = None self.lab_sp = None self.pre_sp = None self.xl_pd = None self.xbrl_year...
def visualize_scene_image(self, image, kitti_objects, calib, scene_2D_mode=True): # Preprocessing for viz. image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) # image = Image.fromarray(image) self.current_image = image for object in kitti_objects: if object.score < self...
The function combines and visualizes a 2D scene by merging an image and a Bird's Eye View (BEV) of a point cloud. It resizes both to a common width while preserving aspect ratios, stacks them vertically, and displays or returns the combined image.
def visualize_scene_2D(self, pointcloud, image, objects, labels=None, calib=None, visualize=True): # read BEV & image self.__scene_2D_mode = True _image = self.visualize_scene_image(image, objects, calib) _bev = self.visualize_scene_bev(pointcloud, objects, labels, calib) self....
def visuallize_pointcloud(self, pointcloud): pointcloud = self.__to_numpy(pointcloud) mlab.points3d(pointcloud[:,0], pointcloud[:,1], pointcloud[:,2], colormap='gnuplot', scale_factor=1, mode="point", figure=self.figure) self.__draw_axes() def __get_box_color(self, class_id)...
The main task of the code is to visualize a 3D scene containing point cloud data and 3D bounding boxes from both model outputs and dataset labels. It renders the point cloud, draws colored 3D boxes for detected objects with labels, and optionally overlays dataset labels in a distinct color. The visualization aids in ev...
def visualize_scene_3D(self, pointcloud, objects, labels=None, calib=None): """ Visualize the Scene including Point Cloud & 3D Boxes Args: pointcloud: numpy array (points_n, 3) objects: list of KittiObject represents model output labels: l...
def NeedlemanWunsch(A,B): WW,ZZ=[],[] W,Z="","" F=Construct_F(A,B) EnumerateAlignments(A,B,F,W,Z,WW,ZZ) return WW,ZZ def ComputeAlignmentScore(A,B): L=[0]*(len(B)+1) for j in range(0,len(B)+1): L[j]=(j*g) for i in range(1,len(A)+1): K=L.copy() L[0]=i*g ...
The code implements the Hirschberg algorithm for global sequence alignment, using divide-and-conquer to reduce space complexity. It recursively splits sequences, computes alignment scores, identifies optimal split points, and combines subproblem results to align sequences optimally, leveraging Needleman-Wunsch for base...
def Hirschberg(A,B): if len(A)==0: WW=["-"*len(B)] ZZ=[B] elif len(B)==0: WW=[A] ZZ=["-"*len(A)] elif len(A)==1 or len(B)==1: (WW,ZZ)=NeedlemanWunsch(A,B) else: i=math.floor(len(A)/2) Sl=ComputeAlignmentScore(A[:i],B) Sr=ComputeAlignmentSco...
def draw_body(self, joints, jointPoints, color): # Torso self.draw_joint_string(joints, jointPoints, color, [ PyKinectV2.JointType_Head, PyKinectV2.JointType_Neck, PyKinectV2.JointType_SpineShoulder, PyKinectV2.JointType_SpineMid, PyKinectV2.Jo...
This code processes Kinect joint data to detect body movements and actions (e.g., hand gestures, running, jumping) in a game. It creates a body model, parses its state, and draws visual indicators (colored circles/lines) on specific joints based on detected actions like hand raises, foot movements, or item use, updatin...
def parse_game_controls(self, joints, joint_orientations, joint_points): body = game_body.Body() for j in range(PyKinectV2.JointType_Count): joint = joints[j] joint_point = joint_points[j] joint_orientation = joint_orientations[j] body.add_joint(j, joint.P...
def initialize_game(self): pygame.init() pygame.display.set_caption(self.TITLE) self.window.fill(self.GREY) self.draw_cursor(eval(f'self.button_{self.state.lower()}')) self.draw_text('Main menu', self.BLACK, 20, self.SCREEN_WIDTH / 2, self.SCREEN_HEIGHT / 2 + self.offset) ...
This code handles user input in a menu interface, allowing selection of machine learning algorithms (e.g., Adaboost, DBSCAN) via mouse clicks or keyboard navigation. It updates the game state, displays corresponding instructions, and cycles through options using arrow keys. The loop processes events like quitting, sele...
def menu(self, user_id): self.initialize_game() while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.type == pygame.MOUSEBUTTONDOWN: if self.but...
def set_server(self): '''set server attributes''' server = socket.socket() server.bind((self.hostname, self.setting.port)) server.listen(self.setting.players_num) return server def connecting(self): '''accept new clients''' while self.connected_clients_num < self....
The code initializes a server with given settings and recorder, sets up the hostname and server configuration, manages client connections, and prepares to run the server's operations by initializing connection info and starting the running process.
def __init__(self, setting, recorder): self.setting = setting self.recorder = recorder self.hostname = socket.gethostname() self.server = self.set_server() self.clients = [] self.connected_clients_num = 0 self.contri_info = [] self.trial_num = 0 ...
def read_cfg(): with open('cfg.json') as fh: data = json.loads(fh.read()) if os.path.exists(".env"): with open(".env") as fhs: secrets = json.loads(fhs.read()) dict_merge(data, secrets) return data def copy_remote(client, resources): ftp_client...
The code deploys an application by executing pre-install steps locally, establishing an SSH connection to a server, copying files, running remote installation commands, and executing post-install steps. It reads a configuration file, validates the app name, and performs deployment tasks as specified in the config, comb...
def deploy_app(name): apps = read_cfg() if name not in apps.keys(): raise ValueError(f"app not found in configuration: '{name}'") cfg = apps[name] for step in cfg["before_install"]: print(f"> {step}") subprocess.call(step, shell=True) client = paramiko.SSHClient() ...
def get_random_unvisited_neighbour(self): """Returns the cell-coordinates of a random neighbouring cell.""" x, y = self.current_coordinates neighbour_coordinates = [] if (y - 1 >= 0) and (not self.grid[x][y - 1].is_visited()): # upper cell neighbour_coordinates.ap...
This function advances a maze generation algorithm by finding a random unvisited neighboring cell, updating the path stack, opening a wall between cells, and marking the new cell as visited. If no neighbors exist, it backtracks using the stack. It returns coordinates of the newly opened wall or None during backtracking...
def next_step(self): """Advances the grid one step further in the maze generation algorithm execution. """ if self.current_coordinates is None: error = "Variable 'current_coordinates' has not been set" raise UnboundLocalError(error) next_current = self.get...
def kdf(X_, h, x): s=0 K=vars.k e=math.e pi=math.pi X=nearestPoints(X_,x,K) for i in range(K): a=X[i][0]-x[0] b=X[i][1]-x[1] s=s+(e**(-(a**2+b**2)/(2*h)))/(2*pi*h) s = vars.MNIMUM_SCORE-s/K return s def getLenghtOfAttack(cls_new,i): len=0 while cls_new[i-1...
This function calculates anomaly scores for time series data using sliding windows. It computes mean and standard deviation features for each window, scales them, and applies a model (kdf) to determine scores. It updates a sample set based on thresholds and class labels, improving detection by iterating through data an...
def getAnomalyScore(T, sampled, lag, scaler, cls_new, h, thres1): score=np.zeros(len(T)-lag+1, dtype=float) x=np.zeros(2,dtype=float) q.queue.clear() lenAtt=0 for i in range(lag-1,len(T)): seq=T[i-lag+1:i+1] x[0]=np.mean(seq) x[1]=np.std(seq) x=scaler.transform(x.res...
def check_winner(self): # Check if a player has won, there are 8 ways to win. # Return the player who won 0 if nobody has won, and -1 if it is a draw result = -1 # check for draw for row in self.board: for ele in row: if ele == 0: r...
This code runs a game loop where players take turns making moves, either against an AI or each other. It alternates turns, checks for a win/draw after each move, and prints the result. If playing with AI, the user selects their player number; the AI uses a smart move strategy. The loop ends when a winner is determined ...
def play_game(self): # This is the driver method for the simulation self.AI = input("Would you like to play against an AI? True/False: ") # Play with AI if self.AI == "True": self.turn = int(input("Would you like to be player 1 or 2? 1/2: ")) print("Player 1 goes ...
def init(self): self.screen = pygame.display.set_mode((self.__displayWIDTH, self.__displayHEIGHT)) pygame.display.set_caption("Snake") windowIcon = pygame.image.load("SnakeAssets/WindowIcon.png").convert(self.screen) pygame.display.set_icon(windowIcon) self.clock = pygame.time.Cl...
The main task of the code is to execute a game loop for a snake game, initializing game elements (snake, apple), maintaining a frame rate of 24 FPS, updating game state, rendering graphics, handling events, displaying the score, and cleaning up resources upon exit.
def run(self): self.init() Frames = 24 self.snake = Snake() self.apple = Apple() while self.running: self.clock.tick(Frames) self.update() self.render() self.events() self.displayScore() pygame.display.flip(...
def print_dangerous(message): dangerous_icon = colored("[✔] 💀", 'red') # You can customize the icon decorated_message = f"{dangerous_icon} {colored(message, 'red')}\n" stylePrint(decorated_message) def sendVimCommand(connection, command): try: connection.write(command.encode('utf-8') + b'\n') ...
This code performs SSH key injection and process hijacking on a remote system via Telnet. It connects to port 8065, injects a public key into the root user's authorized_keys file, and executes commands to hijack processes using nsenter. The script attempts to establish unauthorized access by configuring SSH credentials...
def hijack(address): connection=telnetlib.Telnet(address, port=8065) with open('./binaries/id_rsa.pub', 'r') as f: content = f.read() try: injection = f'echo "{content}" > /root/.ssh/authorized_keys && chmod 600 /root/.ssh/authorized_keys' except IOError: print(f"Error id_rsa.pu...
def print_dangerous(message): dangerous_icon = colored("[✔] 💀", 'red') # You can customize the icon decorated_message = f"{dangerous_icon} {colored(message, 'red')}\n" stylePrint(decorated_message) def print_statement(setting_name, success=True): if success: tick_mark = colored("[✔]", 'yellow'...
The main task of the code is to execute remote command injection attacks via Telnet to upload and configure network tools (socat, netstat) on a target machine. It kills existing web services, establishes port forwarding from port 50628 to 8080, and sets executable permissions for the uploaded binaries, likely to create...
def main(machineInstance,attackerInstance): attackerIP=attackerInstance.address attackerPort=attackerInstance.port script_1="kill -9 $(~/netstat -tulnp | grep webs | sed 's/[:[:space:]]/,/g' | cut -d ',' -f 50 | cut -d '/' -f 1);" script_2=f"~/socat tcp-listen:50628,fork,reuseaddr tcp:{machineInstance.a...
def BoW(wrapped_dict,text_word_dict_to_ix,issue_word_dict_to_ix,author_word_dict_to_ix): wrapped_dict = one_hot_encoding_for_dict(wrapped_dict,text,text_word_dict_to_ix) wrapped_dict = one_hot_encoding_for_dict(wrapped_dict,issue,issue_word_dict_to_ix) wrapped_dict = one_hot_encoding_for_dict(wrapped...
The code initializes a neural network with two linear layers and a ReLU activation, processes input data based on the specified `data_format` (e.g., BoW, WordEmbedding, Doc2Vec), generates feature matrices and labels, and stores them in `output_dict` for subsequent training or evaluation.
def __init__(self, total_embedding_size, label_num, data_format,wrapped_train_dict,text_word_dict_to_ix,issue_word_dict_to_ix,author_word_dict_to_ix, embedding_way_for_diff_length_sentence,copied_train_text,output_dict): super(NeuralNet, self).__init__() self.linear1 = nn.Linear(total_e...
def ReadFile(input_csv_file): # Reads input_csv_file and returns four dictionaries tweet_id2text, tweet_id2issue, tweet_id2author_label, tweet_id2label tweet_id2text = {} tweet_id2issue = {} tweet_id2author_label = {} tweet_id2label = {} f = open(input_csv_file, "r") csv_reader = csv.reader...
The code trains and evaluates a neural network classifier for text data using specified formats (e.g., WordEmbedding), model types, and hyperparameters (learning rate, embedding size). It processes training data, builds word dictionaries, trains the model with validation, plots accuracy curves if enabled, and returns t...
def execute(data_format,model_type,train_ratio,validation_ratio,test_ratio, learning_rate,weight_decay_rate,number_of_epoches,embedding_size, whether_analyze,num_of_record_results,image_folder,update_method, loss_function_choice,embedding_way_for_diff_length_sentence): # Read training data train_tw...
def get_embedding_form(wrapped_dict,embedding_size,embedding_way_for_diff_length_sentence,Max_padding_size,text_embedding,issue_embedding): text_word_dict_to_ix,issue_word_dict_to_ix = get_all_dict_to_ix(wrapped_dict) if use_pretrained: text_to_embedding = torch.load(vocab_file) else: #tex...
The code trains a model using specified loss functions (NLL or CrossEntropy) and optimizers (SGD/Adam). It iterates over epochs, computes loss, backpropagates, and updates parameters. It evaluates training/validation accuracy periodically, stores results, and returns the trained model with performance metrics.
def train(model,train_x,train_y,validation_x,validation_y,label_type_list,learning_rate,weight_decay_rate,number_of_epoches, embedding_size,whether_analyze,num_of_record_results,model_type,loss_function_choice,update_method, wrapped_train_dict,embedding_way_for_diff_length_sentence,Max_padding_size,text_embeddi...
def wrap_data_dict(preprocessed_text, train_tweet_id2issue, train_tweet_id2label): output_dict = {} for key in preprocessed_text: cur_dict = {} cur_dict[text] = preprocessed_text[key] cur_dict[issue] = train_tweet_id2issue[key] cur_dict[label] = train_tweet_id2label[key] ...
The code processes unlabeled data by loading tweets, preparing features (BoW/embeddings), and using a neural network model to predict labels. It implements a top-k selection strategy, refining predictions by replacing low-confidence entries with higher-confidence ones, returning predicted labels and processed data for ...
def infer_unlabeled_data(model,text_word_dict_to_ix,issue_word_dict_to_ix,text_to_embedding,issue_to_embedding, data_folder_name,value_of_top_k,Max_padding_size): unlabeled_text = {} unlabeled_issue = {} unlabeled_label = {} temp_label_dict = {} with open('data.json', 'r') as fi: [...
def ReadFile(input_csv_file): # Reads input_csv_file and returns four dictionaries tweet_id2text, tweet_id2issue, tweet_id2author_label, tweet_id2label tweet_id2text = {} tweet_id2issue = {} tweet_id2label = {} f = open(input_csv_file, "r") csv_reader = csv.reader(f) row_count=-1 for ro...
The function trains a neural network classifier (NN, NN2, or CNN) using specified data formats (BoW, embeddings) and hyperparameters (learning rate, epochs). It processes text/issue data, prepares input features, splits data into train/validation/test sets, trains the model, and returns the trained model, embeddings, d...
def first_train(data_format,model_type,train_ratio,validation_ratio,test_ratio, learning_rate,weight_decay_rate,number_of_epoches,embedding_size, whether_analyze,num_of_record_results,image_folder,update_method, loss_function_choice,embedding_way_for_diff_length_sentence,Max_padding_size): # Read train...
def read_excel_file(folder_directory: str, file_name: str, sheetname: Optional[str] = None) -> pd.DataFrame: """Read a pending report file and return its data.""" if sheetname is None: return pd.read_excel(f'{folder_directory}/{file_name}') return pd.read_excel(f'{folder_directory}/{file_name}', she...
The main task of the code is to process all pending reports by reading Excel files, aggregating their data, and compiling the results into a list of DataFrames. It iterates through each pending file, reads the data, applies aggregation logic, stores the aggregated results, moves completed files, and returns the list of...
def process_pending_reports(self) -> List[pd.DataFrame]: """Process all pending reports and return a list of employee data.""" employee_data_list = [] for file_name in self.pending_files: employee_data = read_excel_file(self.config.get_folder_path('PENDING_FOLDER_NAME'), file_name) ...
def check_files(self) -> List[str]: """Check if the necessary files exist and return a list of pending files.""" master_file_path = f"{self.config.get_folder_path('MASTER_FOLDER_PATH')}/{self.config.get_file_name('MASTER_FILE_NAME')}" pending_folder_name = self.config.get_folder_path('PENDING_FO...
The code's main task is to initialize a processor for pending report files by configuring settings, identifying unprocessed reports, extracting employee data from them, and consolidating the data into structured dataframes for inclusion in a master report. It leverages a configuration object to access file paths and se...
def __init__(self, config): """ Process pending report files and prepare them for inclusion in the master report. Inherits from FilesystemPreparer to ensure all directories are properly set up, then proceeds to identify and process all pending reports, aggregating necessary empl...
def reset_pheromones(self) -> None: self.pheromones_amounts = np.ones_like(self.pheromones_amounts) def get_node_by_id(self, id: str): try: return self.nodes[self.nodes_ids_map.index(id)] except ValueError as err: raise ValueError(f'there is no node with {id} id') from er...
This function implements a modified Ant Colony Optimization (ACO) algorithm to find paths in a graph. It iteratively sends multiple copies of 'RivalAnt' instances to explore routes between start and destination nodes, updating pheromones over 'generations_number' generations. Finally, it returns optimal paths for each ...
def rival_ants_algorithm(self, start_id: str, destination_id: str, ants_originals: list[RivalAnt], cost_func, ants_per_generation: int = 5, generations_number: int = 100)\ -> list[list[str]]: """ `ants_per_generat...
def getPossibleMoves(self,squareNumber,pieceName): self.moves = [] falses = [] for i in range(8): falses.append(False) left,right,top,bottom,twoLeft,twoRight,twoTop,twoBottom = falses if squareNumber >= 8 and squareNumber < 16: twoLeft = True if sq...
This function checks if the current player is in checkmate by iterating through all pieces, evaluating their possible moves, and verifying if any move avoids check. If all moves result in check, it returns True (checkmate); otherwise, it returns False.
def checkIfMate(self): for i in range(len(self.squares)): square = self.squares[i] pieceName = square.pieceName if pieceName is None: pass else: if pieceName[len(pieceName)-1:len(pieceName)] == "W": colour = "whi...
def checkIfPiece(self,squareNumber): if self.squares[squareNumber].pieceName is None: return False else: return self.squares[squareNumber].pieceName def checkIfCheck(self,squareNumber,currentPiece,selectedSquareNumber = None): currentBoard = [] for square in self....
The function determines if a chess move is valid by checking if the target square is empty or occupied by an opposing piece, ensuring the move doesn't result in check, and handling special cases like castling. It returns True if the square is empty and safe, or False if the move is invalid due to piece color, check sta...
def displayMoveOption(self,squareNumber,currentPiece,castling=False): piece = self.checkIfPiece(squareNumber) if piece == False: self.check = self.checkIfCheck(squareNumber,currentPiece) if self.check: return False self.setSquarePiece(squareNumber,"dis...
def promotePawn(self,squareNumber,colour): #add choose ability so not just queen self.promotionWindow = PawnPromotionWindow(colour,self,squareNumber) def setSquarePiece(self,squareNumber,pieceName): #square number is 0 indexed. Piece 0 is top left and moved down first if pieceName != False: ...
This function handles moving a chess piece to a specified square, including pawn promotion, castling logic, updating the board state, and checking for checkmate. It clears the source square, sets the piece on the target square, adjusts rook positions for castling, tracks king/rook movements, and changes turns. If a paw...
def movePiece(self,squareNumber): pieceName = self.selectedSquare.pieceName if pieceName[len(pieceName)-1:len(pieceName)] == "W": colour = "white" else: colour = "black" promoted = False if squareNumber % 8 == 0 or squareNumber % 8 == 7: if pie...
def getPossibleMoves(self,squareNumber,pieceName): self.moves = [] falses = [] for i in range(8): falses.append(False) left,right,top,bottom,twoLeft,twoRight,twoTop,twoBottom = falses if squareNumber >= 8 and squareNumber < 16: twoLeft = True if sq...
The main task of the code is to display possible moves for a chess piece, handling special cases like castling and pawn captures. It processes each move, checks for move type (e.g., castling or pawn), and calls appropriate display functions. Exception handling ensures regular move display if errors occur during process...
def showMoves(self,square,pieceName,squareNumber): moves = self.getPossibleMoves(squareNumber,pieceName) for move in moves: try: if len(move) > 1: if move[1] == "castling": self.displayMoveOption(move[0],pieceName,castling=True) ...
def movePiece(self,squareNumber): pieceName = self.selectedSquare.pieceName if pieceName[len(pieceName)-1:len(pieceName)] == "W": colour = "white" else: colour = "black" promoted = False if squareNumber % 8 == 0 or squareNumber % 8 == 7: if pie...
This function handles a square click in a board game, determining if a piece exists, identifying its color, and triggering moves or updates. It checks if the square is movable, updates selections, and displays valid moves based on the player's turn, ensuring proper game logic and UI feedback.
def squareClicked(self,squareNumber): square = self.squares[squareNumber] pieceName = square.pieceName if pieceName is None: pass else: if pieceName[len(pieceName)-1:len(pieceName)] == "W": pieceColour = "white" else: pi...
def euclidean_distance(self, goal_pose): """Euclidean distance between current pose and the goal.""" return sqrt(pow((goal_pose[0] - self.pose_x), 2) + pow((goal_pose[1] - self.pose_y), 2)) def PID_controller_linear(self, goal_pose): pid_control_linear = self.proportional_linear_vel(goal_pose) +...
This code implements a PID-based navigation controller for a robot to move towards user-specified goal coordinates (x, y, θ). It continuously calculates linear and angular velocities using PID controllers, publishes them to drive the robot, and halts once the target is reached within a 0.05m tolerance. The system reset...
def move2goal(self): while not rospy.is_shutdown(): # Get the input from the user. goal_pose_x = float(input("Set your x goal: ")) goal_pose_y = float(input("Set your y goal: ")) goal_pose_theta = float(input("Set your theta goal: ")) goal_pose = [goal_pos...
def euclidean_distance(self, goal_pose): """Euclidean distance between current pose and the goal.""" return sqrt(pow((goal_pose[0] - self.pose_x), 2) + pow((goal_pose[1] - self.pose_y), 2)) def PID_controller_linear(self, goal_pose): pid_control_linear = self.proportional_linear_vel(goal_pose) +...
This code implements a PID controller to navigate a robot towards a target pose. It continuously calculates linear and angular velocities based on the distance to the goal, publishes these velocities to move the robot, and stops once within a 0.05m tolerance. It resets PID error terms upon reaching the target.
def reference_pose_callback(self,msg): # print('Im here') self.reference_pose = msg goal_pose_x, goal_pose_y, goal_pose_theta = self.reference_pose.data # print('Im here2') goal_pose = [goal_pose_x, goal_pose_y, goal_pose_theta] distance_tolerance = 0.05 vel_msg =...
def euclidean_distance(self, goal_pose): """Euclidean distance between current pose and the goal.""" return sqrt(pow((goal_pose[0] - self.pose_x), 2) + pow((goal_pose[1] - self.pose_y), 2)) def PID_controller_linear(self, goal_pose): pid_control_linear = self.proportional_linear_vel(goal_pose) +...
The code implements a PID controller to navigate a robot toward a goal pose. It continuously calculates linear and angular velocities based on the distance to the goal, publishes these velocities to move the robot, and stops once the target is reached within a tolerance. The PID parameters are reset after achieving the...
def move2goal(self): # print('Im here3') while not rospy.is_shutdown(): # Wait until the reference pose message is received # if self.reference_pose is None: # continue # print('Im here 4') # Get the goal pose from the reference pose messag...
def printBoard(self): for row in range(self.board_size): for col in range(self.board_size): print(self.board[row][col], end='') print() def doPlayerMove(self): row, col = map(int, input("Enter col and row X: ").split()) self.insertSymbol(self.player, row ...
The main task of the code is to run a game loop that continuously prints the game board, processes the player's move, then the bot's move, repeating until the game stops. The loop terminates when `isGameWork` becomes false, after which the final board state is printed.
def start(self): while self.isGameWork: self.printBoard() self.doPlayerMove() self.doBotMove() self.printBoard()
def get_id(self): '''Returns the id value from the given student record.''' return self.id def get_name(self): ''' Returns student name as a list from the student record''' return [self.fname,self.lname] def calc_gpa(self): '''Returns gpa t...
The main task of the code is to print a student's ID, name, and GPA by calling methods `get_id()`, `get_name()`, and `calc_gpa()`. It outputs these details in a formatted manner, with the GPA calculated using the `calc_gpa()` method.
def print_student_gpa(self): '''Prints Student id, along with student name as list and student gpa''' print("Student Id: ", self.get_id()) print("Student Name: ", self.get_name()) print("GPA:", self.calc_gpa())