dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def tensorboard_writer(args): tensorboard_filepath_tmp = os.path.join(args.root_dir, args.exp_name) tensorboard_filepath = os.path.join(tensorboard_filepath_tmp, 'visualize_training') try: shutil.rmtree(tensorboard_filepath) except: pass os.makedirs(tensorboard_filepath, exist_ok=Tru...
This code defines a main function for training machine learning models on the imbalanced CIFAR10 dataset, supporting end-to-end, separate, or classification-only training modes. It configures hyperparameters, data loaders, loss functions (MSE/BCE for autoencoders, weighted losses for classification), and experiment tra...
def main(): parser = argparse.ArgumentParser(description='Models Training arguments on Cifar10 strictly imbalanced Dataset') parser.add_argument('--is_end_to_end_training', action='store_true', help='Encoder, Decoder, Classifier all will be trained together in a shared loss') parser.add_argument('--is_separ...
def get_color_turn(self): if(self.turn % 2 == 1): return self.start else: return self.second def color(self,x,y): if x % 2 == 0: # which means it is an even row if y % 2 != 0: # which means it is an odd column pygame.draw.rect(self....
This function highlights the king's position on a chessboard when it is in check. If no check is detected, it places or colors the respective king's position based on the current player's turn. If a check is detected (for 'black' or 'white'), it draws red rectangular outlines around the king's square using Pygame, crea...
def highlight_check(self): if(self.king_check == None): if(self.get_color_turn() == 'black'): self.color(self.wk.position[0],self.wk.position[1]) self.place_piece(self.wk.position[0],self.wk.position[1]) else: self.place_piece(self.bk.posit...
def get_piece(self,x,y): return str(self.board_pieces[x][y]) def color(self,x,y): if x % 2 == 0: # which means it is an even row if y % 2 != 0: # which means it is an odd column pygame.draw.rect(self.chess_board_surface, self.black, pygame.Rect((x) * self.width, (...
This function promotes a pawn to a queen when it reaches the opposite end of the board. It checks if the piece is a pawn, verifies its color and position (y=0 or y=7), creates a new Queen object with unique naming, updates the board, adds it to the piece list, and clears the original pawn's movement data. The promotion...
def promote(self,x,y,color): namepawn = self.get_piece(x, y) if fnmatch.fnmatch(namepawn, '?p?'): if(color != self.top and y == 0): if(color == 'black'): self.nbr_queens_b += 1 name = 'bq' + str(self.nbr_queens_b) ...
def is_pinned(self,piece): if(piece.color == self.get_color_turn()): x_king = self.get_place('bk' if self.get_color_turn() == 'black' else 'wk')[0] y_king = self.get_place('bk' if self.get_color_turn() == 'black' else 'wk')[1] square_between = self.get_points_bet...
The main task of this code is to calculate all valid moves for a chess piece, considering its type (knight, bishop, rook, queen, king, pawn), board boundaries, blocked paths, pinning (protecting the king), and special rules like en passant and castling. It populates `can_move` (legal moves), `does_protect` (squares occ...
def all_movement(self,piece): piece.can_move.clear() piece.does_protect.clear() piece.move_not_eat.clear() #The logic for all pieces is the same, first get all the possible moves if the board was empty, then remove squares that are blocked #by other pieces, it will alos ...
def color(self,x,y): if x % 2 == 0: # which means it is an even row if y % 2 != 0: # which means it is an odd column pygame.draw.rect(self.chess_board_surface, self.black, pygame.Rect((x) * self.width, (y+1) * self.width, self.width, self.width)) sel...
This function highlights a chess board square at (x,y) by checking its color. If it matches the highlight color, it resets the click state; otherwise, it draws the highlight and places a piece. Conditional logic determines the square's color based on row/column parity, redrawing the clicked square in black/white. Final...
def highlight_square(self,x,y): self.original_color = self.chess_board_surface.get_at((x * self.width + 10, (y+1) * self.width + 10)) if self.original_color.r == self.highlight[0] and self.original_color.g == self.highlight[1] and self.original_color.b == self.highlight[2]: self.color(x,y) ...
def populate_moves(self): for i in self.pieces_list: if(i.color != self.get_color_turn()): self.all_movement(i) for i in self.pieces_list: if(i.color == self.get_color_turn()): self.all_movement(i) def is_done(self): if(self.king_check != N...
The code generates algebraic chess notation for a move, appending symbols for piece types, captures, castling, promotions, and check/checkmate status to a game string. It formats coordinates based on board orientation, adds move numbers, and ensures proper spacing and line breaks for the notation.
def notation(self, x, y, name, take, castle, promote, orig_x, orig_y): verify = False nbr_chr = 0 if(self.turn % 2 == 1): self.textgame_string += (str(self.turn // 2 + self.turn % 2) + '. ') if((self.turn // 2 + self.turn % 2) < 10): self.textgame...
def get_piece(self,x,y): return str(self.board_pieces[x][y]) def color(self,x,y): if x % 2 == 0: # which means it is an even row if y % 2 != 0: # which means it is an odd column pygame.draw.rect(self.chess_board_surface, self.black, pygame.Rect((x) * self.width, (...
This function moves a selected chess piece to a new position if valid, handling en passant, captures, promotion, and castling. It updates the board, recalculates moves, checks for check, updates turn state, and records move notation.
def move_piece(self,x,y): castle = False take = False promote = False if(len(self.selected_piece.can_move) != 0 or len(self.selected_piece.move_not_eat) != 0): old_x = self.selected_piece.position[0] old_y = self.selected_piece.position[1] nam...
def pathProc(self, history_graph, h_index, query, separate_grad=False): batch_size = len(h_index) index = h_index.unsqueeze(-1).expand_as(query) # initialize all pairs states as zeros in memory initial_stat = torch.zeros(batch_size, history_graph.num_nodes(), self.dims[0], devi...
The main task of the code is to visualize paths in a graph by computing gradients of a score derived from node features and relation queries, then using beam search to identify top paths connecting head and tail nodes based on edge weights, returning these paths and their associated weights for visualization.
def visualize(self, data, batch): # data: history graph # batch: the triplet to be visualized assert batch.shape == (1, 3) h_index, r_index, t_index = batch.unbind(-1) query = self.query(r_index) output = self.pathProc(data, h_index, query, separate_grad=True) f...
def envelope_handler(event: Envelope, context: LambdaContext) -> HTTPResponse: return request_handler(parse_obj_as(RequestModel, event.body), context) def request_handler(event: RequestModel, context: LambdaContext) -> HTTPResponse: # logger.debug("RequestModel: %s", repr(event)) try: bytes_copied, ...
This Lambda function handles data transfer between various storage systems (Oracle directory, SCP, S3) by parsing event parameters, validating input, and routing requests to appropriate handlers. It processes source/destination URIs, manages request envelopes, and returns HTTP responses, with error handling for validat...
def lambda_handler(event: dict, context: LambdaContext) -> HTTPResponse: """ sample events: event = { "source_uri": "oracledirectory://system:manager@host1/orclpdb1?dir=DATA_PUMP_DIR&file=export.dmp.gz", "destination_uri": "oracledirectory://system:manager@host2/orclpdb2?dir=DATA_PUMP_DIR&fi...
def get_random_fire_location(): y = random.randint(fire_square[0],fire_square[1]) x = random.randint(fire_square[0],fire_square[1]) while (x,y) in fire_locations.values(): y = random.randint(fire_square[0],fire_square[1]) x = random.randint(fire_square[0],fire_square[1]) light_id = add_fire_location(x,y) retur...
The main task of the code is to generate fire effects by dynamically creating PointLight nodes in a 3D scene. It either places lights at random locations or uses predefined formation patterns based on the formation_id parameter. The function adds these lights to the scene graph and triggers a fire simulation, with opti...
def generateFire(random_spread = False,formation_id = 0): children = root.getField('children') if random_spread: for _ in range(no_lights): id,x,y = get_random_fire_location() children.importMFNodeFromString(-1,'DEF PointLight'+str(id)+' PointLight { location '+str(x)+' '+str(y)+' 0.1 attenuation 0 0 5 intens...
def cancel_substring(input_prompt: torch.tensor, query: str, tokenizer): #in the case we are doing casual language modelling, we want to cancel the substring input_prompt = tokenizer.decode( input_prompt, skip_special_tokens = True).strip() return query.replace(input_prompt,"").strip() def execute_query(db_...
The function `bestFirstSearchWithChecks` performs a best-first search to generate valid SQL queries that match a target execution result. It uses a priority queue to explore potential query paths, validating partial SQL syntax, checking execution results against expected outputs, and ensuring correctness through multip...
def bestFirstSearchWithChecks(model_query, q, tokenizer, simple_sql_fn, bm_size = 2, check_example = True, db_full = {}, check_exec_result = True, check_partial_sql = True, enum_part_quer_check = True, seq2seq = True, device = "cpu"): bos_token = tokenize...
def bestFirstSearchWithChecks(model_query, q, tokenizer, simple_sql_fn, bm_size = 2, check_example = True, db_full = {}, check_exec_result = True, check_partial_sql = True, enum_part_quer_check = True, seq2seq = True, device = "cpu"): bos_token = tokenize...
The function `evaluate_model` evaluates a model's ability to generate correct SQL queries by comparing its predictions against gold-standard queries on a dataset. It uses beam search or best-first search to generate candidate queries, executes them on a database, and checks for syntax errors, runtime errors, or correct...
def evaluate_model(model, tokenizer, spider, num_beams=1, max_output_sequence_length=200, save_after_eval = False, use_train = False, debug = False, start_idx = 0, end_idx = 1, filename="predsRLbeam", break_early = True, simple_sql_fn=None, dbs_full_schema = {}, use_bes...
def gather_nd(params, indices): """ just work for 3D tensor with 2D indices ref: cruvadom's implementation for gather_nd with some modification, https://github.com/tensorflow/tensorflow/issues/206 e.g: params = [[[1,3],[2,2]]] indices = [[0,1]] ...
The main task of the code is to compute pairwise interactions between elements in the input tensor X using specified indices, apply a gate operation and normalization, then perform max-pooling by selecting top-k interactions. It returns the pooled results, combining element-wise interaction computation with selective a...
def pair_wise_interaction_and_max_pooling(X, batch_size, k, sequence_length, first_indices, second_indices, gate_type='sum', ...
def processImage(self): for file in self.listFiles: """ Captures frame from webcam & tries to detect corners on chess board """ print('Processing: ' + file) frame = cv2.imread('./input/' + file) resize_frame = cv2.resize(frame, (1280, 720), interpolation=cv2.INTER...
The main task of the code is to process input images to compute intrinsic and extrinsic camera parameters using SVD. It first checks if at least three images are present in the input directory, processes them, builds a matrix M, calculates the minimum eigenvector, and derives intrinsic parameters (v0, lambda, alpha, be...
def main(self): self.listFiles = os.listdir('./input/') if len(self.listFiles) < 3: rem = 3 - len(self.listFiles) print('\33[1m' + '\33[31m' + 'Warning! The number of captured photos should be at least 3. Please take ' + str(rem) + ' more photos!' + '\33[0m') else: ...
def load_gold_information(): def load_jsonlines(f): data = [] with open(f) as f: for line in f: data.append(json.loads(line)) return data # data = load_jsonlines(f"../coref-hoi/winobias/{split}_type{t}_pro_stereotype.128.jsonlines") + load_jsonlines( # f"../coref-hoi/winobias/{split}_type{t}_anti_ste...
This code evaluates model fairness in classification by calculating statistical disparities (e.g., TPR, FPR, precision gaps) between genders for each profession. It loads predicted probabilities from trained models, computes metric gaps for male vs. female groups, and logs Pearson correlations, absolute sum gaps, and A...
def log_classification_gaps(args): tpr_gaps_pearson = [] tpr_gaps_abs_sum = [] fpr_gaps_pearson = [] fpr_gaps_abs_sum = [] precision_gaps_pearson = [] precision_gaps_abs_sum = [] independence_sum = [] separation_abs_sum = [] # sufficiency_abs_sum = [] sufficiency = [] if args.retrain_seed: preds_pro = to...
def _show(self, signal: str) -> Tuple[bool, Dict]: results = {} frames = [] for name, engine in self.engines.items(): frame = engine.get_frame() # Perform callback on the engine if signal == "SCAN": frame, results[name] = engine.process(frame...
The code processes camera data to map coordinates from left and right camera feeds, matches detected items using calculated distances, and updates product counts in real-time. It maintains a matrix to track item positions, pairs left-right correspondences, and updates server status/products based on detected matches. T...
def run(self) -> None: Server.set("status", "SCAN") stop = False width, height = self.engines["top"].camera.size() # Main loop for capturing frames from cameras while not stop: signal = Server.get("status") stop, results = self._show(signal) ...
def tuples_sum(nbval,total,order=True) : """ Generate all the tuples L of nbval positive or nul integer such that sum(L)=total. The tuples may be ordered (decreasing order) or not """ if nbval == 0 and total == 0 : yield tuple() ; return #raise StopIteration if nbval == 1 : yield...
The code generates all distinct assignments of derivatives to fields in `field_multiset`, considering both outer and inner partitions. It first creates outer partitions (distributing derivatives across field types), then inner partitions (splitting derivatives between psi and psi_bar within each field). The result is a...
def generate_derivative_assignments(field_multiset): # INPUT: # field_multiset: encodes the set of fields and derivatives making up the term # e.g., field_multiset = {D:3, F:2, S:1, T:2}; # if a field is absent, simply omit it - e.g., write {D:3, F:2, S:1, T:2}, not {D:3, F:2, S:1, T:2, V:0} ...
def generate_derivative_assignments(field_multiset): # INPUT: # field_multiset: encodes the set of fields and derivatives making up the term # e.g., field_multiset = {D:3, F:2, S:1, T:2}; # if a field is absent, simply omit it - e.g., write {D:3, F:2, S:1, T:2}, not {D:3, F:2, S:1, T:2, V:0} ...
This function applies IBP (Integration-By-Parts) and CPT (Charge-Parity-Time) symmetry reductions to filter redundant derivative assignments from a given field multiset. It generates derivative assignments, then removes those violating IBP or CPT symmetry criteria, based on input flags. The output includes the reduced ...
def generate_derivative_assignments_IBP_CPT_filtered(field_multiset, IBP=True, C=True, P=True, T=True): # INPUT: # field_multiset: dictionary containing multiplicities o f derivative and field types # OUTPUT: # reduced_derivative_assignments_dict: a dictionary containing an IBP-reduced set of derivative...
def configDriver(self): options = webdriver.ChromeOptions() options.add_argument("--headless") options.add_argument("--incognito") options.add_argument("--nogpu") options.add_argument("--disable-gpu") options.add_argument("--window-size=1280,1280") options.add_ar...
The code initializes a web crawler/scraper by configuring keywords from a JSON file, setting up a tree structure for data organization, tracking visited URLs, and handling timeouts. It prepares for crawling by loading keywords, separating wildcards, initializing a driver, and starting a timer. The class manages URL pro...
def __init__(self, data, protocal, idx, branchSize=100, timeOutAfter=1000) -> None: self.idx = idx self.driver = self.configDriver() self.keywords = [ prepareString(word) for word in fileManager("keywords.json").loadData() ] self.wildCards = [ word[1:] ...
def getRunTime(self): if (time.time() - self.startTime) > self.timeOutAfter: self.timeout = True def getPageData(self, url): goturl = self.openUrl(url) self.findTextWithKeyword() self.getInternalLinks() return goturl def sortInternalLinks(self): self.internal...
The main task of the code is to iteratively process internal links by fetching data from each URL in a queue, tracking recursion depth, checking for timeouts, maintaining a list of visited URLs, and re-sorting remaining links after each iteration. It processes links sequentially, removes them from the queue, and termin...
def iterateThroughInternalLinks(self): recusions = 0 while self.internalLinks: self.getRunTime() if self.timeout: print("timeout") break recusions += 1 self.getPageData(self.internalLinks[0]) if self.internalLink...
def collectRawDisk(file): data = [] try: count = 0 for line in file: if count > 1: data.append(str(line[3:64])) count += 1 return data except: pass def printRawDisk(disk): for line in disk: print(line) def crawlRawDisk(*args...
The code processes disk data from stdin or a file specified by argsData.file, collects and prints raw disk information, and triggers a crawl if the directory flag is set. It handles errors like invalid files or missing inputs, ensuring proper data processing and user feedback.
def evalArgs(argsData): try: #print("test") # Predefine vars fileName = None diskFile = None # Check for stdin if not sys.stdin.isatty(): diskFile = sys.stdin#fileinput.input() # Check for file input flag if argsData.file != None: ...
def sgpe2(l_vf, end): T = len(l_vf[0]) - 1 nb_p = len(l_vf) value = [0]*(T+1) winner = [0]*(T+1) price_t = [0]*(T+1) bids_t = [0]*(T+1) for i in range(T+1): x = init(i,0,l_vf, end) value[i] = {j:0 for j in x} #Creation of nodes winner[i] = {j:0 for j in x} #Creation of nodes price_t[i] = {j:0 for j in x...
The code simulates an auction mechanism to check for subgame perfect equilibrium (SGPE) by iterating through item allocations, calculating marginal gains, and validating outcomes through plots and user input. It processes bidders' valuations, computes cumulative values, and verifies equilibrium conditions by comparing ...
def run(): v = [[0, 44, 44, 44, 44, 0, 0, 0, 0], [0, 32, 20, 0, 0, 0, 0, 0, 0], [0, 55, 55, 55, 55, 30, 20, 0, 0]] n = len(v) nb_p = n T2 = len(v[0]) - 1 #marginal valuation for bidder 1 #v[0] = vtype("custom",T,vals=[T+1]*T) #marginal valuation for bidder 2 #for i in range(1,n): # v[i] = vtype("custom",T,val...
def _get_basekit_path(): return _get_toolkit_path().split("/compiler/")[0] def _get_toolkit_path(): """Determines and returns the SYCL installation path.""" sycl_toolkit_path = None sycl_toolkit_path = _get_default_sycl_toolkit_path() if "SYCL_TOOLKIT_PATH" in os.environ: sycl_toolkit_path = os.environ["S...
The function `find_sycl_config` retrieves and returns a dictionary containing SYCL configuration information, including paths to the SYCL basekit and toolkit. It validates the existence of the basekit path, constructs the configuration dictionary, and updates it with additional details from an internal helper function ...
def find_sycl_config(): """Returns a dictionary of SYCL components config info.""" basekit_path = _get_basekit_path() toolkit_path = _get_toolkit_path() if not os.path.exists(basekit_path): raise ConfigError( 'Specified SYCL_TOOLKIT_PATH "{}" does not exist'.format(basekit_path)) result = {} r...
def controls(self): for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() def _path_finding(self): available = [] for i in self.to_check: neighbours = [] for j in range(-1, 2): if j ...
The code's main task is to execute a game loop step by handling controls, performing pathfinding up to 700 iterations if needed, updating the UI, and maintaining frame rate via a clock. It ensures pathfinding occurs only when the route isn't predefined and within a loop limit, then refreshes the display and regulates g...
def play_step(self): self.controls() if self.loops < 700 and type(self.route) != list: self._path_finding() self.loops += 1 self._update_ui() self.clock.tick(SPEED)
def get_all_usernames_in_radius(searchzip, searchradius): search = ZipcodeSearchEngine() lookupzip = search.by_zipcode(searchzip) city = lookupzip.City lat = lookupzip.Latitude longi = lookupzip.Longitude res = search.by_coordinate(lat, longi, radius=int(searchradius), returns=50) allzips = ...
This function retrieves user data and song information within a specified geographic radius of a zip code, aggregates it into lists/dictionaries, and renders a search results HTML template with the collected data for display.
def searchresults(searchzip, searchradius): sc_users_in_radius = get_all_usernames_in_radius(searchzip, searchradius) all_song_codes_in_radius = [] all_user_dictionaries=[] for username in sc_users_in_radius: user_songlinks = get_sc_account_songlinks(username) all_song_codes_in...
def getSetupFileVersion(filepath): with open(filepath + "/setup.py", "r") as file: data = file.readlines() for rawLine in data: line = rawLine.split() if not len(line): continue if line[0].startswith("version"): fullLine = "".join(line) ...
The function ensures the setup file's version number aligns with the package's version. It retrieves both versions, updates the setup version if it's not greater than the package version, and returns the valid setup version for consistency.
def getValidVersionNumberForSetupFile(filepath): currentSetupFileVersion = getSetupFileVersion(filepath) currentPackageVersion = getCurrentPackageVersion(getPackageNameFromSetupFile(filepath)) if not versionNumberGreater(currentSetupFileVersion, currentPackageVersion): currentSetupFileVersion = getN...
def getPyModules(filepath): pyModules = [] searchForModules(filepath, filepath, pyModules) return pyModules def getAuthorsNameLine(authorsArray): if not len(authorsArray): return "" else: return f"\n author='{getAuthorNamesInline(authorsArray)}'," def getAuthorEmailLine(correspondingEmail): return f"\n ...
The main task of the code is to generate a `setup.py` file for a Python package. It compiles metadata like authors, email, project name, description, classifiers, and GitHub info into a formatted `setup()` function call. The generated file includes package configuration, module listings, and entry points for console sc...
def generateSetupFile(filepath, authorsArray, correspondingEmail, githubUsername, projectName, shortDescription, classifier): pyModules = getPyModules(filepath) authorNameLine = getAuthorsNameLine(authorsArray) authorEmailLine = getAuthorEmailLine(correspondingEmail) descriptionLine = getDescriptionLine(shortDe...
def checkForRequiredFiles(filepath): requiredFiles = ["LICENSE", "README.md", "requirements.txt", "setup.py"] topLevelDirectoryFiles = set(os.listdir(filepath)) for file in requiredFiles: if file not in topLevelDirectoryFiles: print(f"{file} not yet created. Run generatefiles.py first!")...
The code's main task is to prepare and upload a Python package by verifying required files, ensuring dependencies (Wheel, Twine) are installed, updating the setup file's version number, creating distribution files, uploading them to a repository, and subsequently removing the generated distribution files to clean up th...
def upload(filepath): checkForRequiredFiles(filepath) checkWheelInstallation() checkTwineInstallation() versionNumber = getValidVersionNumberForSetupFile(filepath) setNewSetupFileVersion(filepath, versionNumber) createDistributionFiles(filepath) uploadDistributionFiles(filepath) r...
def checkForUnitTests(filepath): if "tests" not in os.listdir(filepath): dialogWindow = DialogWindow("No unit tests found", UNIT_TEST_CREATION_PROMPT_TEXT, positiveButtonText="Create", negativeButtonText="Don't", positiveButtonAction=lambda: createUnitTestTemplates(filepath), negativeButtonColor="red") d...
The code generates a new Python project structure by creating essential files such as requirements.txt, .gitignore, LICENSE, README, __init__.py, and setup.py, using provided metadata like project name, authors, emails, and classifiers to populate content and configurations.
def generate(filepath, projectName, authorsArray, emailsArray, correspondingEmail, githubUsername, shortDescription, classifier): checkForUnitTests(filepath) generateRequirementsFile(filepath) generateGitIgnoreFile(filepath) generateLicenseFile(filepath, authorsArray) generateReadmeFile(filepath, projectName, sho...
def get_default_repo(config): repo = '' if 'repository' not in config: raise Exception("Repository section not found in the config file") if 'default' not in config['repository']: raise Exception("No 'default' in repository section") default_repo = "repo-%s" % config['repository']['defau...
This script processes backporting tasks for git repositories, handling cache updates, commit checks, and quilt series pruning. It reads configurations, parses command-line options (e.g., --update, --check, --repo), and executes actions like checking commit backports, updating caches, or pruning quilt entries based on u...
def main(argv): config = configparser.ConfigParser() config.read(os.path.expanduser(CONFIG_DEFAULT)) default_repo = get_default_repo(config) repo_name = default_repo usage = "usage: %prog [options]" parser = optparse.OptionParser(usage=usage) parser.add_option("-u", "--update", dest="do_upd...
def update_cache(repo, cache, branch, last): try: os.mkdir(cache) except OSError as error: if error.errno != errno.EEXIST: raise(error) for c in ['a','b','c','d','e','f', '0','1','2','3','4','5','6','7','8','9']: try: os.mkdir("%s/%s" % (cache, c)) ex...
The main task of the code is to manage a git repository's cache of fixes, allowing users to update the cache from a configured upstream repository, purge the cache, or retrieve specific commits as fixes. It reads configuration settings, validates repository paths, and processes command-line options to either update, pu...
def main(argv): usage = "usage: %prog [options]" parser = optparse.OptionParser(usage=usage) parser.add_option("-u", "--update", dest="do_update", default=False, help="Update cache using configured git repository", action="store_true") parser.add_option("-p", "--purge", dest="do_purge", default=False, h...
def set_x(self, x: int): self.__send_new_position(self.__DISPLACEMENT_X_COMMAND, self.get_x(), x) def set_y(self, y: int): self.__send_new_position(self.__DISPLACEMENT_Y_COMMAND, self.get_y(), y) def set_z(self, z: int): self.__send_new_position(self.__DISPLACEMENT_Z_COMMAND, self.get_z(), z)
The main task of the code is to update an object's position by assigning the x, y, and z coordinates from a given tuple. It decomposes the input position (int, int, int) and applies each value to the corresponding axis via `set_x`, `set_y`, and `set_z` methods, effectively setting the object's 3D position in space.
def set_position(self, position: (int, int, int)): self.set_x(position[0]) self.set_y(position[1]) self.set_z(position[2])
def check_version(): global version if version == 0: for i in range(10): raw=analogRead(7) if raw>v16_thresh: version=16 else: version=14 return version def pinMode(pin, mode): # if pin ==10 or pin ==15 or pin ==0 or pin ==1: if mode == "OUTPUT": write_i2c_block(pin_mode_cmd, [pin, 1, unused])...
The main task of the code is to turn on a specified LED (left or right) based on the system version. It assigns different GPIO pins for LED control depending on the version check, sets the pin as an output, activates the LED by writing a high signal, and returns 1 on success or -1 if the LED ID is invalid.
def led_on(l_id): if check_version() > 14: r_led=16 l_led=17 else: r_led=5 l_led=10 if l_id==LED_L or l_id==LED_R: if l_id==LED_L: pinMode(l_led,"OUTPUT") digitalWrite(l_led,1) elif l_id==LED_R: pinMode(r_led,"OUTPUT") digitalWrite(r_led,1) return 1 else: return -1
def check_version(): global version if version == 0: for i in range(10): raw=analogRead(7) if raw>v16_thresh: version=16 else: version=14 return version def pinMode(pin, mode): # if pin ==10 or pin ==15 or pin ==0 or pin ==1: if mode == "OUTPUT": write_i2c_block(pin_mode_cmd, [pin, 1, unused])...
The code turns off a specified LED (left or right) by setting the appropriate GPIO pin based on the system version. It checks the version to determine pin numbers, configures the pin as output, and writes a low signal (0) to turn off the LED. It returns 1 if successful or -1 if the input LED ID is invalid.
def led_off(l_id): if check_version()>14: r_led=16 l_led=17 else: r_led=5 l_led=10 if l_id==LED_L or l_id==LED_R: if l_id==LED_L: pinMode(l_led,"OUTPUT") digitalWrite(l_led,0) elif l_id==LED_R: pinMode(r_led,"OUTPUT") digitalWrite(r_led,0) return 1 else: return -1
def swap_sample(self, sample): """ target: no <eos> prev_output_tokens: first <eos> src_tokens: no <eos> default left padding """ target = sample["target"] prev_output_tokens = sample["net_input"]["prev_output_tokens"] src_tokens = torch.cat((prev_...
The code computes the total loss for a neural network model during training, combining language modeling loss (nll_loss) with optional adversarial (op_loss) and knowledge distillation (kd_loss) components when pre-training is disabled. It returns the aggregated loss, sample size, and logging outputs including loss valu...
def forward(self, model, sample, reduce=True): """Compute the loss for the given sample. Returns a tuple with three elements: 1) the loss 2) the sample size, which is used as the denominator for the gradient 3) logging outputs to display while training """ #net_o...
def __has_left_child(self,parent_index:int)->bool: return self.__get_left_child_index(parent_index) < len(self.nodes) def __get_left_child_index(self,parent_index:int) -> int: return (2 * parent_index) +1 def __has_right_child(self,parent_index:int)->bool: return self.__get_right_child_index(par...
The main task of the code is to maintain the min-heap property by recursively comparing a parent node with its smallest child, swapping them if necessary, and propagating the adjustment downward until the heap structure is restored.
def __heapify_down(self,parent_index:int = 0): if parent_index > len(self.nodes) or not self.__has_left_child(parent_index): return # finding the smallest child index smallest_child_index = self.__get_left_child_index(parent_index) # validate whether the right child is prese...
def create_database(self, scrabing_attr, details): self.db = sqlite3.connect(details['db_name']) self.cursor = self.db.cursor() self.table_name = details['table_name'] order = f"CREATE TABLE {self.table_name} ( id INTEGER PRIMARY KEY AUTOINCREMENT, link TEXT," for parcing_object...
This code scrapes paginated web content by dynamically generating URLs, counting total pages, and extracting data using specified attributes. It initializes a database, iterates through each page, and processes scraped titles or details, storing results systematically.
def super_scrabing(self, pagination_attr, source_attr, scrabing_attr, details): self.create_database(scrabing_attr, details) url = details['source'] url_arr = url.split('%%') response = requests.get(url_arr[0] + '1' + url_arr[1]) pages = self.count_pages(response.text, pagination...
def bitlist_to_int(bitlist: list) -> int: """Converts a list of Truthy values (bits) to an integer value Args: bitlist (list): list of truthy/falsy values (0/1, True/False, ...) Returns: int: integer value of the bitlist """ return sum(i * 2 ** n for n, i in enumerate(bitlist[::-1]...
The code reads a binary diagnostic report, computes the power consumption by determining gamma and epsilon rates, and calculates the life support rating using oxygen and CO2 scrubber ratings. It processes the input data with NumPy for efficient array operations, transposes the data to analyze bit frequencies, and appli...
def main(): with open(IMPORT_FILE, 'rt') as filehandler: report = numpy.array([list(map(int, line.strip())) for line in filehandler]) logging.debug(f'{report=}') # Transpose, do a bincount an get the argmax/argmin for each row report_t = numpy.copy(report).transpo...
def get_notes_and_mines(ssc: simfile.ssc.SSCSimfile) -> NotesAndMines: """ Populate & return a NotesAndMines instance for the simfile. """ output = NotesAndMines() for c, chart in enumerate(ssc.charts): chart_note_positions: List[BeatChartIndex] = [] """All of the non-fake, non-mine...
The function `make_mines_fake` adds short fake segments to each mine in every chart of a simfile, modifying the in-memory simfile object. It checks for conflicts between mines and notes on the same beat, raising an error if prohibited by arguments. The function logs all actions (e.g., adding fakes, skipping existing fa...
def make_mines_fake( ssc: simfile.ssc.SSCSimfile, args: MakeMinesFakeArgs ) -> List[Action]: """ Add a short fake segment on each mine in each chart in the simfile, updating the in-memory simfile object. Returns a list of actions (human-readable strings) that were taken on the simfile. Rai...
def argparser(): """Get an ArgumentParser instance for this command-line script.""" parser = argparse.ArgumentParser() parser.add_argument("simfile", type=str, help="path to the simfile to modify") parser.add_argument( "-d", "--dry-run", action=argparse.BooleanOptionalAction, ...
This script processes a simfile to generate fake mine data, modifies the SSC file with backup, handles errors like conflicting beats, and returns exit codes. It parses arguments, checks for required files, applies changes conditionally, and outputs actions taken or warnings.
def main(argv) -> int: """ Run the script & return an exit code (0 for success, nonzero for error). """ error = False # Parse command-line arguments args = argparser().parse_args(argv[1:], namespace=MakeMinesFakeArgs()) sm_present = False printed_sm_present_warning = False if os.p...
def draw_area(self): """ Does the setup for the pygame window and draws the CSV data as a colored field """ if len(self.fields) <= 0: # Exit when field is empty return #Initialize pygame with width and size of area for window self.display = pygame.display.set_...
The code initializes a Pygame window, processes mouse inputs to set start and target positions on a grid, calculates the path between them using `get_path`, and visualizes the path while displaying its total cost. It handles user interactions, updates the display dynamically, and exits on window closure.
def start_window(self): """ Handles the pygame window input including the mouse interaction. Calls the get_path function """ self.draw_area() pygame.display.update() start: Union[Field, None] = None target: Union[Field, None] = None #Event Loop whi...
def shut_down(): pygame.quit() sys.exit() def update_state(self) -> None: self.tetromino.occupied_cells_on_gird = self.occupied_cells if self.tetromino.move(Vector2(0, 1)): return self.occupied_cells.extend(self.tetromino.get_vectors()) self.tetromino = Tetrom...
This code runs a game loop for a Tetris-like game, handling events such as quitting, updating the game state, and processing keyboard inputs to rotate and move tetrominoes. It continuously renders graphics and maintains a target frame rate (FPS) using a clock.
def run(self) -> None: while True: for event in pygame.event.get(): if event.type == QUIT: self.shut_down() if event.type == self.update: self.update_state() if event.type == pygame.KEYDOWN: i...
def get_products(row): products_in_row = row["products"].split(",") for product_index, product in enumerate(products_in_row): products_in_row[product_index] = product.strip() return products_in_row def to_dict(row_index, unique_product): unique_product = { "product_name": get_product_nam...
The function processes a row of data to extract product information, converts each product into a dictionary with the row index, updates product quantities, and returns the cleaned list of product dictionaries.
def clean_product_row(row, row_index): products = get_products(row) products = [to_dict(row_index, product) for product in products] products = update_quantity(products) return products
def extract1(data): new_data=[[],[],[]] dates=[data['documents'][str(5-i)]['uploaded_at'] for i in range(len(data['documents'])-2)] # dates=[data['documents'][int(5-i)]['uploaded_at'] for i in range(len(data['documents'])-2)] for i in range(len(dates)): dates[i]=dates[i][:10] for key in data...
The code generates a PDF report by processing input data, formatting labeled sections with dynamic text placement, color-coded value boxes, and page breaks. It structures medical/technical data into headers, detailed entries, and summary sections, using PyPDF library methods for layout and styling.
def run(data,user_id, patient): # print("saved pdf at " +settings.MEDIA_ROOT) print("creating pdf") pdf = canvas.Canvas(settings.MEDIA_ROOT.replace('/','//')+"//Generated_reports//"+str(user_id)+".pdf",bottomup=0) # pdf = canvas.Canvas("latest.pdf",bottomup=0) # pdf.showPage() data1= extract1(da...
def is_valid_pawn_move(self, start, end): # Check if the move is within the board and follows the knight's move pattern if not (0 <= start[0] < 8 and 0 <= start[1] < 7 and 0 <= end[0] < 8 and 0 <= end[1] < 7): return False # Check if there is another pawn (current player's or oppone...
The code's main task is to validate and execute a player's move on a board, either moving a pawn or a ball based on specific conditions. It checks if the move is valid, updates the board state by transferring the piece from the start to the end position, resets the start position to zero or a neutral value, switches th...
def make_move(self, start, end): is_valid = False if self.is_valid_pawn_move(start, end) and self.board[start] == self.players[self.player_turn]: self.board[end] = self.board[start] self.board[start] = 0 is_valid = True elif self.is_valid_ball_move(start, end)...
def display_board(self): pawn_symbols = {0: '·', 1: '○', 2: '●', 3: '◇', 4: '◆'} # Print column indices with a space in front print(" ", end="") for col in range(7): print(f" {col}", end="") print("\n" + " +" + "--" * 7 + "+") # Print board with r...
The code's main task is to manage a turn-based game loop where players take turns making moves on a board. It displays the board, prompts for start and end positions, executes the move, checks for a win, and ends the game when a player wins, displaying the result.
def play(self): while True: self.display_board() print(f"{self.player_turn}'s turn:") # Get input for move start = tuple(map(int, input("Enter starting position (row col): ").split())) end = tuple(map(int, input("Enter ending position (row...
def _get_best_action(self, state): state_q_values = [self.q_values[(state, action)] for action in range(self.env.action_space.n)] best_action = np.argmax(state_q_values) return best_action def _update_q_table(self, current_state, action, reward, new_state): next_best_action = self._get_b...
The code simulates an agent interacting with an environment for a specified number of steps. It selects actions using a Q-table, updates the Q-values, and stores experiences in a buffer. If enabled, it trains the agent using experience replay. Upon episode completion, it resets the environment, records cumulative rewar...
def play_n_steps(self, steps=10000, train_with_replay=True): current_state = self.env.reset() total_rewards = [] total_reward = 0.0 episode_counter = 1 for step in range(steps): action = self._get_best_action(current_state) new_state, reward, done, _ = sel...
def make_directory_if_not_exists(path): '''Crea un directorio si este no existe''' os.makedirs(path,exist_ok=True) def copy_file(from_path:str,to_path:str,replace_if_exists=False,move=False): '''Copia, mueve o reemplaza un archivo o directorio de from_path a to_path''' if is_file(from_path): ...
This function extracts the first file from a byte stream containing a ZIP archive to a specified path, creates the directory if needed, copies the extracted file to the path (replacing existing files), and then deletes the original extracted file to avoid duplication.
def unzip_bytes(data:bytes,path:str): '''unzipea un archivo en el path especificado a traves de los bytes''' z = zipfile.ZipFile(io.BytesIO(data), "r") # z.read(path) # Reads the data from "foo.txt" #z.read(z.infolist()[0]) # Reads the data from the first file filename = z.infolist()[0].fil...
def get_all_courses() -> list[Course]: """gets all courses from the database file. doesn't throw good errors currently Returns: list[Course]: all the courses it found in the database """ courses_list: list[Course] = [] with open(database_file) as f: db = json.load(f) courses...
The main task of the code is to prompt the user to input course names and assign priority levels (1-3) to each, retrieving matching database courses and updating their priority fields. It allows adding all database courses at once, handles input validation, and ensures no duplicate entries. Finally, it collects the max...
def prompt_for_courses() -> tuple[list[Course], int]: """prompts the user to input a list of course names, then returns a list of the corresponding courses and sections from the database. Course names must be in database Returns: tuple[list[Course], int]: all the courses it found in the databa...
def extract_ner_coref(train_data:dict): ner_dict = [] # Parses through ner to form ner dict for key_dict, text_dict in zip(train_data['ner_keys'][0], train_data['ner_text'][0]): doc_id = text_dict['DOC'][0]['DOCID'].replace(' ', '').replace('.', '').replace('nyt', '') story_id = text_dict['D...
The main task of the code is to process a training dataset by extracting named entities (NER), coreferences, and template-based elements (entities, relations, events). It aligns these components per document, enriches NER entries with coref data, and maps entities/relations/events to sentences. The result is a structur...
def format_dataset(train_data: dict): ner_dict, coref_dict = extract_ner_coref(train_data) # entities from each doc entities = extract_template_keys(train_data['template_elements']) # entity relations consist of multiple entities relations = extract_template_keys(train_data['template_relations']) ...
def is_valid_input(self, number: int, row: int, column: int) -> bool: if ( self.is_immutable_cell(row=row, column=column) or not self.meets_row_rule(number=number, row=row) or not self.meets_column_rule(number=number, column=column) or not self.meets_square_rule(n...
This function adds a number to a Sudoku grid at specified coordinates, validates its placement, updates row/column/square structures, logs the action, and checks if the move allows for possible solutions. It ensures no duplicates in rows, columns, or 3x3 squares via assertions and raises an error for invalid inputs.
def add_number(self, number: int, row: int, column: int) -> bool: if self.is_valid_input(number=number, row=row, column=column): _square = self.get_square(row, column) cell = self.Coordinates(row=row, column=column) self.grid[cell] = number self._row_structure[row...
def minimax(board_size, connect, board, player): result = check_game(board_size, connect, board) # check if any player wins ############################################################################# # if terminal state is achieved, return the terminal result # otherwise, call minimax recursively to ...
The function `ai_turn` determines the optimal move for an AI player in a game (like Connect Four) using a specified strategy (minimax, minimax with alpha-beta pruning, etc.). It iterates through all empty cells on the board, temporarily places the AI's mark ('X'), calculates the resulting score using the chosen strateg...
def ai_turn(board_size, connect, board, strategy): pos = -1 # initialize pos to illegal value, -1 here max_value = -2 # initialize max value so far to -2, which is a value smaller than possible min value for i in range(board_size**2): if board[i] == 0: # if the cell is empty board[i] = ...
def DeletePages(self): """(wx.Frame) -> null Deletes all the pages of the notebook """ auinotebook = self._mgr.GetPane("notebook_content").window for pages in range (auinotebook.GetPageCount()): auinotebook.DeletePage(0) def UpdateNotebook(self): """ ...
The main task of the code is to handle a button event (wx.EVT_BUTTON) by updating the user interface. It deletes existing notebook tabs, creates and populates a new notebook, updates the DataPane display, and refreshes the window to reflect changes. This sequence ensures the interface is dynamically reconfigured and da...
def RunExpt(self, event): """ (wx.Frame, event [that has been handled]) -> Null The function is called by event [wx.EVT_BUTTON] with ID = [ID_Button_Expt_Run], calls 4 functions which: 1) cause the program to delete tabs from notebook object, 2) create a new notebook obj...
def merge_all_down(board): board = transpose(board) board = merge_all_right(board) board = transpose(board) return board def merge_all_up(board): board = transpose(board) board = merge_all_left(board) board = transpose(board) return board def merge_all_left(board): for i in range(boa...
The function checks if a game board is in a state where no moves are possible by attempting to merge tiles in all four directions (down, up, left, right). If none of these operations change the board, it returns True, indicating the game cannot move; otherwise, it returns False.
def cannotMove(board): tempboard1 = copy.deepcopy(board) tempboard2 = copy.deepcopy(board) tempboard1 = merge_all_down(tempboard1) if tempboard1 == tempboard2: tempboard1 = merge_all_up(tempboard1) if tempboard1 == tempboard2: tempboard1 = merge_all_left(tempboard1) ...
def RandomMotifs(Dna, k, t): # place your code here. lst = [] for item in Dna: randIdx = random.randint(0, t-k) lst.append(item[randIdx:randIdx+k]) #print(lst) return lst def ProfileWithPseudocounts(MotIn): #print(MotIn) t = len(MotIn)+4 k = len(MotIn[0]) count = {'A'...
The code performs randomized motif search to identify the best set of DNA motifs by iteratively generating new motifs using a profile with pseudocounts, comparing their scores, and updating the best motifs found. It runs for N iterations, returning the lowest-scoring motif set, which likely represents conserved sequenc...
def RandomizedMotifSearch(Dna, k, t, N): count = N M = RandomMotifs(Dna, k, len(Dna[0])) BestMotifs = M while count: #print(M) Profile = ProfileWithPseudocounts(M) #print(Profile) M = MotifsT(Profile, Dna) if Score(M) < Score(BestMotifs): BestMotifs = ...
def tran_name(app, name): return f"/Users/batu/Desktop/project_dal/android_pcap_data_collection_and_analysis/flows/{name}/{name}_encrypted_traffic_sanitized_flows.txt" def choose_features(comb, features, name, typee="intra"): label_mapping = {"in": 0, "out": 1} if typee == "inter" else app_to_num comb["labe...
The main task of the code is to evaluate multiple machine learning classifiers on application-based datasets, comparing their performance (accuracy, precision, recall, F1) through either a single train-test split or cross-validation. It processes labeled data, applies feature selection, balances class distributions, an...
def process(name, direction, features, cdic=cdic, cross_validateq=False): arr = [] for app in apps: df = pd.read_csv(tran_name(app,name), delimiter= ',') df = df.sample(n=len(df.index)) df["label"] = app arr.append(df) Path(f"{plots_root}/{name}").mkdir(parents=True, exist_ok...
def list_pseudonym(): f = open(reader_file, "r") cpt = 0 readFile = f.read() lst_pseudonym = [] for i in readFile: if i == "\n": cpt += 1 for i in range(cpt): lst_pseudonym.append(readFile.split("\n")[i].split(",")[0]) return lst_pseudonym def rateBook(reader, ind...
This function provides a menu for users to rate a book, get book recommendations, or reset data matrices. It validates user pseudonyms against a list, handles navigation (back/exit), and returns status codes (0 for exit, 1 for back) or recursively restarts the menu based on input and function outcomes.
def menu_part3(): power = 1 print("Write 1 to rate a book") print("Write 2 to get recommended a book") choice = input("What do you want to do ?\n") if choice == "1": pseudo = input("what is your pseudonym ?\n") while pseudo not in list_pseudonym(): if pseudo == 'back': ...
def conv_bn_relu_drop(x, kernal, phase, drop, image_z=None, height=None, width=None, scope=None): with tf.name_scope(scope): W = weight_xavier_init(shape=kernal, n_inputs=kernal[0] * kernal[1] * kernal[2] * kernal[3], n_outputs=kernal[-1], activefunction='relu', variable_name=...
This function constructs a 3D VNet-like architecture for semantic segmentation. It processes input volumes through encoder (convolutional, downsampling) and decoder (deconvolutional, upsampling) stages with residual connections, squeeze-excitation modules, and skip connections. The model uses batch normalization, ReLU,...
def _createSEvnet(X, image_z, image_width, image_height, image_channel, phase, drop, n_class=1): inputX = tf.reshape(X, [-1, image_z, image_width, image_height, image_channel]) # shape=(?, 32, 32, 1) # Vnet model # layer1->convolution layer0 = conv_bn_relu_drop(x=inputX, kernal=(3, 3, 3, image_channel,...
def set_command(self, data): global VELOCITY_CMD_DURATION VELOCITY_CMD_DURATION = float(data) def arm_grasp(self): image_client = self._robot.ensure_client(ImageClient.default_service_name) # Take a picture with a camera print('Getting an image from: frontleft_fisheye_image') i...
The code `fetch_tug` executes a sequence of robotic actions: setting a velocity command, grasping an object, moving backward, toggling a mouth mechanism twice, stowing the arm, and restoring the original velocity command. Its primary task is to perform a coordinated motion and manipulation sequence, likely for grasping...
def fetch_tug(self): global VELOCITY_CMD_DURATION cmd = VELOCITY_CMD_DURATION self.set_command(1.5) self.arm_grasp() self.move_backward() self.toggle_mouth() self.stow() self.toggle_mouth() self.set_command(cmd)
def downloadAndPrepareWorkspace(): # Define the training and validation base directories train_dir = './dataset/training' source_path = './' source_list_names = os.listdir(source_path) temp_path = os.path.join(source_path, 'temp') images_path = os.path.join(source_path, 'images') metadata_pa...
The code processes medical image data for multi-label classification, prepares datasets with preprocessing, calculates class weights for imbalanced labels, trains a model using TensorFlow with custom callbacks, evaluates performance, and visualizes Class Activation Maps (CAM) for interpretability. It loads a pre-traine...
def main(): downloadAndPrepareWorkspace() imagePrefix = "./images/" df = pd.read_csv('./metadata/Data_Entry_2017_v2020UPDATED.csv', usecols=[0, 1]) df['Image Index'] = imagePrefix + df['Image Index'].astype(str) y_entry = df.pop('Finding Labels') y = y_entry.str.get_dummies() y.pop('No Findi...
def find_best_attr(self, data_part): attributes = data_part.columns.drop(self.label) best_info_gain = -1 for attr in attributes: attr_info_gain = self.calc_attr_info_gain(attr, data_part) if attr_info_gain > best_info_gain: best_info_gain = attr_info_gain best_attr = at...
The code implements the ID3 algorithm to recursively build a decision tree. It selects the best attribute to split data, creates subtrees, and assigns class labels when the maximum depth is reached. Nodes are constructed based on attribute values, with data partitioning and depth checks ensuring proper tree growth. If ...
def id3(self, node, prev_attr_value, data_part, current_depth): if data_part.shape[0] != 0: # find most informative attribute best_attr = self.find_best_attr(data_part) # print(f'current depth= {current_depth}, max_depth= {self.max_depth}, best_attr: {best_attr}') # create subt...
def fit(self, X, y, numerical_attrs, label): train_data = pd.concat([X, y], axis=1) self.numerical_attrs = numerical_attrs self.label = label self.all_labels = train_data[label].unique() self.__calculate_data_info(train_data) def predict(self, X): predictions = [] ...
The code evaluates a model's accuracy on validation data by first training the model using the training data, then predicting outcomes on the validation set, and finally calculating the accuracy against the true validation labels.
def evaluate(self, train_X, train_y, val_X, val_y, numerical_attrs, label): self.fit(train_X, train_y, numerical_attrs, label) predictions = self.predict(val_X) return self.__calculate_accuracy(val_y, predictions)
def init_layers(self, input_size, output_size): hidden_layers = [] for i in range(self.hidden_count): if i == 0: layer = Layer(self.hidden_size, input_size) else: layer = Layer(self.hidden_size, self.hidden_size) hidden_layers.append(la...
This method trains a neural network model using batched data over multiple epochs. It initializes layers, performs forward and backward propagation, updates parameters, and evaluates training/validation accuracy/loss per epoch, returning lists of metrics for each epoch.
def fit( self, epochs, batch_size, train_data, train_labels, valid_data, valid_labels ): """A method to train the model. Args: epochs (int): number of epochs. batch_size (int): size of the batch. train_data (np.array): training data. train_lab...
def _generate_mines(self): mines = np.zeros((self.width, self.height)) mines1d = random.sample(range(self.width * self.height), self.num_mines) for coord in mines1d: x = coord % self.width y = coord // self.width mines[x, y] = 1...
The code resets the game environment by initializing the grid, placing mines, and resetting step counters. It prepares the state for a new episode, ensuring consistency through invariant checks in debug mode, then returns the initial observation for the agent.
def reset(self): self.open_cells = np.zeros((self.width, self.height)) self.mines = self._generate_mines() self.steps = 0 self.unnecessary_steps = 0 if self.debug: self._assert_invariants() return self._get_observation()
def _get_reward(self): openable = self.width * self.height - self.num_mines open_cells = np.count_nonzero(self.open_cells) open_mine = self._game_over() punishment = self.unnecessary_steps * self.punishment open_cells_reward = (open_cells - punishment) / openable return o...
The code processes a game action by updating the game state, checking for game-over conditions, and returning the current state. It handles the first move by ensuring initial reward is zero, increments steps, parses the action to open a cell, and resets the game if the first move triggers a game over. Debug checks and ...
def step(self, action): first_move = False if self.steps == 0: first_move = True assert self._get_reward() == 0 if self._get_reward() == 0: assert self.steps == 0 self.steps += 1 x, y = self._parse_action(action) self._open_cell(x, y...
def iuint(x): lx = len(x) assert lx <= 4, "Too long int leaked for struct unpack" # int data types for unpack b,s,i,l. Upper for unsigned if lx == 4: return struct.unpack('I', x)[0] else: return struct.unpack('I', x + b'\x00'*(4-lx))[0] def iubint(x): return struct.unpack('B', x)[0] ...
The function `parseMStreamBlock` parses an MStream block by reading 3 bytes to extract payload length and subtype, then reads a single byte for subtype bits. It logs debug information if enabled and delegates payload parsing to `parseMStreamPayload`, returning its result. The core task involves decoding structured bina...
def parseMStreamBlock(get): if oformat == "debug": print("TRACE: parsing mstream block") dense3bytes = iuint(get(3)) subtypeBits = iubint(get(1)) payloadLengthWords = dense3bytes >> 2 mStreamSubtype = dense3bytes & 0b11 if oformat == "debug": print( f"DEBUG: subtype b...
def iuint(x): lx = len(x) assert lx <= 4, "Too long int leaked for struct unpack" # int data types for unpack b,s,i,l. Upper for unsigned if lx == 4: return struct.unpack('I', x)[0] else: return struct.unpack('I', x + b'\x00'*(4-lx))[0] def iubint(x): return struct.unpack('B', x)[0] ...
The main task of the code is to parse a device event block from a data stream. It reads the block's serial number, payload length, and device ID, calculates the end position of the block, and returns the result of parsing the block using `parseMStreamBlock`. Debug logs track the parsing process.
def parseDeviceEventBlock(get): if oformat == "debug": print("TRACE: parsing device event block") serial = iuint(get(4)) payloadLength = iuint(get(3)) deviceID = iubint(get(1)) if oformat == "debug": print( f"DEBUG: reading Device Event Block from serial {hex(serial)}, ID...
def create_hadamard_circuit_layer(self): hadamard_circuit_layer = cirq.Circuit() for qubit in self.qubits: hadamard_circuit_layer += cirq.H(qubit) return hadamard_circuit_layer def create_cost_operator(self): A_1 = self.weights['constraint_each_visited'] A_2 = self.we...
The main task of the code is to construct a QAOA (Quantum Approximate Optimization Algorithm) circuit by combining a Hadamard layer with parameterized layers generated from cost and mixing operators. It uses TensorFlow Quantum's exponential function to apply these operators repeatedly, creating a variational quantum ci...
def create_qaoa_circuit(self): hadamard_circuit_layer = self.create_hadamard_circuit_layer() cost_operator = self.create_cost_operator() mixing_operator = self.create_mixing_operator() parameterized_circuit_layers = tfq.util.exponential(operators=[cost_operator, mixing_operator] * self.p...
def generate_sympy_parameters(self): return sympy.symbols('parameter_:%d' % (2 * self.p)) def create_cost_operator(self): A_1 = self.weights['constraint_each_visited'] A_2 = self.weights['constraint_each_visited_once'] B = self.weights['cost_weight'] cost_of_constraint_each_visi...
This code initializes a Quantum Approximate Optimization Algorithm (QAOA) for solving the Traveling Salesman Problem (TSP). It sets up qubits, parameters, cost operators, and constructs a QAOA circuit using specified weights for cost and constraints. The TSP instance, penalty parameters (A₁, A₂), and B determine the op...
def __init__(self, tsp_instance, p, A_1=4, A_2=4, B=1): self.tsp_instance = tsp_instance self.qubits = cirq.GridQubit.rect(1, tsp_instance.number_of_cities ** 2) self.p = p self.weights = {'cost_weight': B, 'constraint_each_visited': A_1, '...
def _read_films_file(cls, films_txt) -> list: with open(films_txt) as fileobj: files = [Path(file.strip()) for file in list(fileobj) if Path(file.strip()).suffix in cls.ext] return files def _read_patch_csv(cls, patch_csv) -> dict: """ Return dict from csv file """ # make pat...
This method populates a database with film records by reading a list of film filenames from a text file. It optionally uses a CSV file to override metadata instead of fetching it via Cinemagoer. For each file, it retrieves movie information, creates database entries, and tracks progress. It returns the number of record...
def populate(self, films_txt, patch_csv=None) -> int: """ Read file of film file names and create database entries for all Parameters ---------- films_txt : str Path to file containing list of file names patch_csv : str Path to csv file o...
def _read_patch_csv(cls, patch_csv) -> dict: """ Return dict from csv file """ # make patch dict with open(patch_csv) as fileobj: header, *lines = fileobj.readlines() _, *header = header.strip().split(cls.sep) # drop 'filename' patch = {} for line in ...
The code updates a database with new or modified film records from provided text or CSV files. It checks existing entries, deletes mismatched records, and creates new ones using patch data. It returns the count of updated records, raising an error if no files are provided.
def update(self, films_txt=None, patch_csv=None) -> int: """ If `films_txt` is not None, add any new entries to the database, using `patch_csv`, if provided. If `patch_csv` is provided, the corresponding item is retrieved from database. If the IDs don't match, the item...
def _get_context_from_request(request) -> dict: """ Try to get year and runtime min and max from `request` """ context = {} # assigning to context dict in for loop with variable key names wasn't working # so store in separate lists genre_and = [] genre_or = [] genre_not = [] fo...
This code handles a search request by retrieving context from the request, performing a search with the query string, updating the context with results, applying filters, and rendering the appropriate template. It switches to a film list template for AJAX requests, ensuring dynamic content delivery.
def search(request, search_str, template='mediabrowser/index.html', filmlist_template='mediabrowser/filmlist.html'): context = _get_context_from_request(request) search_results = _search(search_str, **context) context.update(search_results) context = _set_search_filters(context, re...
def get_metadata_dict(metadata_file): """Little function to read a JSON metadata file into a dict.""" metadata_handle = open(metadata_file) metadata = json.loads(metadata_handle.read()) _ = metadata.pop('name') return metadata def read_entry_exit_table(metadata, county=None, file_spec=None, data_dir...
The main task of the code is to transform raw disability data into a structured format where each row represents a person's enrollment, with columns indicating the presence of specific disability types at entry and exit. It reads metadata, maps numeric codes to disability descriptions, and pivots rows into columns usin...
def get_disabilities(county=None, file_spec=None, data_dir=None, paths=None, metadata_file=METADATA_FILES['disabilities'], disability_type_file=op.join(DATA_PATH, 'metadata', 'disability_type.json')): """ Read in the ra...
def get_enrollment(county=None, groups=True, file_spec=None, data_dir=None, paths=None, metadata_file=METADATA_FILES['enrollment']): """ Read in the raw Enrollment tables. Return rows with some minor clean-up that includes dropping unusable columns de-deplication. Parameters ...
The function `merge_tables` consolidates multiple raw data tables (enrollment, exit, client, disabilities, etc.) into a unified enrollment table, where each row represents an individual's project enrollment. It retrieves and cleans data using metadata, merges tables via common identifiers (e.g., person IDs), validates ...
def merge_tables(county=None, meta_files=METADATA_FILES, data_dir=None, paths=None, files=None, groups=True, name_exclusion=False): """ Run all functions that clean up raw tables separately, and merge them all into the enrollment table, where each row represents the project enrollme...
def element(self, r, c): """Return the element at the given coordinates.""" return self.matrix[r][c] def neighbors(self, r, c): """ Return an array of tuples (row, column) representing elements adjacent to the one at the given coordinates. Empty elements are not included. Adjacent elements incl...
This function recursively finds all valid word coordinates in a grid starting from a specified position, ensuring words match a given length and prefix while avoiding reused coordinates. It checks if the starting letter aligns with the prefix, then explores neighboring cells for subsequent letters, accumulating valid c...
def _rec_find_word_coords( self, length, start_row, start_col, used_coords, prefix ): """ Find word locations in the matrix as described in `find_word_coords` matching the given requirements. length (int) -- Return words of exactly this length start_row (int), start_col (int) -- the coordi...
def column_count(self): """Returns the number of columns in the matrix.""" return len(self.matrix[0]) def row_count(self): """Returns the number of rows in the matrix.""" return len(self.matrix) def element(self, r, c): """Return the element at the given coordinates.""" return self.matrix[r][c] ...
The code collapses each column of the matrix by shifting letters downward and empty elements upward, ensuring all empty cells are positioned above letters within each column while maintaining the original order of letters in their respective columns.
def collapse_columns(self): """ Shift the elements in the matrix so that each column is "collapsed." Within each column, all empty elements should be in rows higher than all letters. To achieve this, we shift letters down to lower rows in each column. No letter changes column, and letters retain ...
def row_count(self): """Returns the number of rows in the matrix.""" return len(self.matrix) def column_count(self): """Returns the number of columns in the matrix.""" return len(self.matrix[0]) def is_letter(self, r, c): """True if the given element exists and is a letter, False otherwise.""" r...
The main task of the code is to find all possible coordinate paths in a matrix that form words of a specified length, starting with a given prefix, where adjacent letters are neighbors in the matrix and each cell is used only once. If a dictionary is provided, only valid words from the dictionary are included. The func...
def find_word_coords(self, length, prefix="", dictionary=None): """ Return a list of coordinate lists of the given length that correspond to words that can be made by combining the letters in the matrix, following these rules: - The first element in the word can be any element in the matrix -...
def init_custom_train(args): if args.load_model: print('load model from [%s]' % args.load_model, file=sys.stderr) params = torch.load(args.load_model, map_location=lambda storage, loc: storage) vocab = params['vocab'] saved_args = params['args'] state_dict = params['state_dic...
The code implements a REINFORCE algorithm for training a sequence-to-sequence model using policy gradients. It processes paired source-target data, computes model scores, generates samples, and calculates rewards based on BLEU scores. The algorithm updates the model via gradient descent, applies gradient clipping, and ...
def custom_train3(args): """ Training with reinforce algorithm """ train_data_src = read_corpus(args.train_src, source='src') train_data_tgt = read_corpus(args.train_tgt, source='tgt') dev_data_src = read_corpus(args.dev_src, source='src') dev_data_tgt = read_corpus(args.dev_tgt, source='tg...
def init_custom_train(args): if args.load_model: print('load model from [%s]' % args.load_model, file=sys.stderr) params = torch.load(args.load_model, map_location=lambda storage, loc: storage) vocab = params['vocab'] saved_args = params['args'] state_dict = params['state_dic...
The code trains a sequence-to-sequence model (e.g., neural machine translation) using maximum likelihood estimation (MLE). It loads training/dev data, initializes the model, optimizer, and loss functions, then iteratively trains on batches, computes cross-entropy loss with teacher forcing, and performs gradient updates...
def train(args): print("Device {} available".format(device)) train_data_src = read_corpus(args.train_src, source='src') train_data_tgt = read_corpus(args.train_tgt, source='tgt') dev_data_src = read_corpus(args.dev_src, source='src') dev_data_tgt = read_corpus(args.dev_tgt, source='tgt') trai...
def init_custom_train(args): if args.load_model: print('load model from [%s]' % args.load_model, file=sys.stderr) params = torch.load(args.load_model, map_location=lambda storage, loc: storage) vocab = params['vocab'] saved_args = params['args'] state_dict = params['state_dic...
The code implements a training loop using the REINFORCE algorithm with sampling for a sequence-to-sequence model. It trains on paired source-target data, computes loss via sampled outputs' BLEU scores compared to greedy decoding, and optimizes using gradient ascent on the advantage. Validation evaluates perplexity and ...
def train_with_sampling(args): """ Training with reinforce algorithm and sampling """ train_data_src = read_corpus(args.train_src, source='src') train_data_tgt = read_corpus(args.train_tgt, source='tgt') dev_data_src = read_corpus(args.dev_src, source='src') dev_data_tgt = read_corpus(args...
def init_training(args): if args.load_model: print('load model from [%s]' % args.load_model, file=sys.stderr) params = torch.load(args.load_model, map_location=lambda storage, loc: storage) vocab = params['vocab'] saved_args = params['args'] state_dict = params['state_dict'] ...
The code trains a sequence model (e.g., neural machine translation) using RAML (Reinforcement Learning for Maximum Likelihood Estimation). It samples diverse target sequences with importance weights, computes weighted log-likelihood loss, and optimizes the model via backpropagation. Validation is performed periodically...
def train_raml(args): tau = args.temp train_data_src = read_corpus(args.train_src, source='src') train_data_tgt = read_corpus(args.train_tgt, source='tgt') train_data = zip(train_data_src, train_data_tgt) dev_data_src = read_corpus(args.dev_src, source='src') dev_data_tgt = read_corpus(args.de...
def create_sdk_stream(): # build Create request op = sdk_service_pb2.NotificationRegisterRequest.Create request=sdk_service_pb2.NotificationRegisterRequest(op=op) # call SDK RPC to create a new stream notification_response = stub.NotificationRegister( request=request, metadata=meta...
The code registers an agent with a service, maintains its presence via periodic keep-alives, subscribes to configuration change notifications for specific YANG models, and processes real-time notifications from SR Linux. It handles registration status, initializes communication streams, and ensures continuous monitorin...
def run_agent(): ## Register Agent register_request = sdk_service_pb2.AgentRegistrationRequest() register_request.agent_liveliness=10 register_response = stub.AgentRegister(request=register_request, metadata=metadata) if register_response.status == sdk_common_pb2.SdkMgrStatus.Value("kSdkMgrFailed")...
def create_sdk_stream(): # build Create request op = sdk_service_pb2.NotificationRegisterRequest.Create request=sdk_service_pb2.NotificationRegisterRequest(op=op) # call SDK RPC to create a new stream notification_response = stub.NotificationRegister( request=request, metadata=meta...
The code registers an agent with a specified liveliness, initiates a keep-alive thread, creates a notification stream, subscribes to config and IP route updates, and processes real-time notifications from SR Linux. It handles registration status, maintains session liveness, and streams configuration changes for further...
def run_agent(): ## Register Agent register_request = sdk_service_pb2.AgentRegistrationRequest() register_request.agent_liveliness=10 register_response = stub.AgentRegister(request=register_request, metadata=metadata) if register_response.status == sdk_common_pb2.SdkMgrStatus.Value("kSdkMgrFailed")...
def full_stitch(self): for conn in self.stitch_network_connection_list: network_conn_name=self.core.get_attribute(conn,"name") self.create_config(conn) self.process_simple_network_connection(network_conn_name,stitch="yes") self.process_stitch_connection(network_...
This function determines the experiment type by checking nodes' credentials (Fabric/Chi) and network connections. It validates required credentials for nodes/networks, raises errors if missing, and classifies the experiment into 'full stitch', 'single provider', 'networks only', or 'simple node' based on connection typ...
def check_experiment_type(self): simple_fabric_connection_list=[] simple_chi_connection_list=[] for path in self.nodes: node = self.nodes[path] if(self.core.is_instance_of(node,self.META['chi_credentials'])): self.chi_credential=True ...
def load_nodes(self): nodes_list = self.core.load_sub_tree(self.active_node) for node in nodes_list: self.nodes[self.core.get_path(node)] = node def check_experiment_type(self): simple_fabric_connection_list=[] simple_chi_connection_list=[] for pat...
The main task of the code is to initialize variables and configurations for an experiment involving nodes, networks, and credentials. It sets up data structures to track nodes, networks, and connections, then calls methods to load nodes, check the experiment type, create a provider, and generate a FAB file. This prepar...
def main(self): self.count_of_nodes=0 self.resource_type_node_initialized = False self.resource_type_node = {'node': []} self.resource_type_network_initialized = False self.resource_type_network = {'network': []} self.fabric_networks_with_multiple_nodes=...
def normalize_util(img, alpha=0, beta=255): return cv2.normalize(img, alpha, beta, norm_type=cv2.NORM_MINMAX) def getBestMatch(image_eroded_sub, marker): descent_per_step = ( config.marker_rescale_range[1] - config.marker_rescale_range[0]) // config.marker_rescale_steps h, w = marker.shape[:2] ...
The main task of the code is to detect and locate a marker within an image by dividing it into quadrants, performing template matching to identify the marker's position, and applying a perspective transformation to warp the image based on detected marker locations. The process involves image normalization, erosion, qua...
def handle_markers(image_norm, marker, curr_filename): if config.ERODE_SUB_OFF: image_eroded_sub = normalize_util(image_norm) else: image_eroded_sub = normalize_util(image_norm - cv2.erode(image_norm, ...
def normalize_util(img, alpha=0, beta=255): return cv2.normalize(img, alpha, beta, norm_type=cv2.NORM_MINMAX) def appendSaveImg(key, img): if(config.saveimglvl >= int(key)): global saveImgList if(key not in saveImgList): saveImgList[key] = [] saveImgList[key].append(img.copy(...
The code detects a rectangular page in an image by normalizing, thresholding, enhancing edges via morphological operations, applying Canny edge detection, and validating contours for rectangularity. It returns the coordinates of the detected page as a 4-point polygon.
def findPage(image_norm): # Done: find ORIGIN for the quadrants # Done, Auto tune! : Get canny parameters tuned # (https://www.pyimagesearch.com/2015/04/06/zero-parameter-automatic-canny-edge-detection-with-python-and-opencv/) image_norm = normalize_util(image_norm) ret, image_norm = cv2.threshold(...
def resetSaveImg(key): global saveImgList saveImgList[key] = [] def appendSaveImg(key, img): if(config.saveimglvl >= int(key)): global saveImgList if(key not in saveImgList): saveImgList[key] = [] saveImgList[key].append(img.copy()) def normalize_util(img, alpha=0, beta=2...
The function `getROI` processes an input image by normalizing it, detecting and correcting page boundaries via perspective transformation, resizing to uniform dimensions, and returning the preprocessed image for downstream tasks like OCR. It includes optional cropping and handles edge cases like missing page boundaries...
def getROI(image, filename, noCropping=False): global clahe for i in range(config.saveimglvl): resetSaveImg(i + 1) appendSaveImg(1, image) """ TODO later Autorotate: - Rotate 90 : check page width:height, CW/ACW? - do CW, then pass to 180 check. - Rotate 180 : No...
def ask_user_likes_query(userId, artistId): query_body = f''' ASK {{ SELECT ?user ?artist WHERE {{ ?user ex:userId "{userId}" . ?artist ex:artist_id "{artistId}" . FILTER NOT EXISTS {{ ?user rel:LIKES ?artist }} }} }} ''' return query_body def exe...
The main task of the code is to handle a POST request for a user to like an artist. It retrieves userId and artistId from the request, validates their presence, checks if the user already likes/dislikes the artist via SPARQL, and inserts the like if valid. It returns appropriate error messages or a success response, en...
def post_user_likes(): # get the userId and artistId from the request body userId = request.json.get('userId') artistId = request.json.get('artistId') if not userId or not artistId: return jsonify({"error": "Missing 'userId' or 'artistId' in request body"}), 400 ask_query = ask_user_likes_q...
def ask_user_dislikes_query(userId, artistId): query_body = f''' ASK {{ SELECT ?user ?artist WHERE {{ ?user ex:userId "{userId}" . ?artist ex:artist_id "{artistId}" . FILTER NOT EXISTS {{ ?user rel:DISLIKES ?artist }} }} }} ''' return query_body d...
The function handles a POST request to add a user's dislike for an artist. It validates the presence of userId and artistId, checks if the user already dislikes or likes the artist via SPARQL query, and inserts the dislike if valid. It returns appropriate JSON responses for errors or success.
def post_user_dislikes(): # get the userId and artistId from the request body userId = request.json.get('userId') artistId = request.json.get('artistId') if not userId or not artistId: return jsonify({"error": "Missing 'userId' or 'artistId' in request body"}), 400 ask_query = ask_user_disl...
def delete_user_relationship_query(userId, artistId): user_iri = get_user_iri(userId) artist_iri = get_artist_iri(artistId) query_body = f''' DELETE {{ ?user rel:LIKES ?artist . ?user rel:DISLIKES ?artist . }} WHERE {{ BIND (IRI("{user_iri}") AS ?user) BIND (IRI(...
The function deletes a relationship between a user and an artist by extracting `userId` and `artistId` from the request, validating their presence, constructing a SPARQL query to remove the link, executing it, and returning a success message if successful.
def delete_user_relationship(): # get the userId and artistId from the request body userId = request.json.get('userId') artistId = request.json.get('artistId') if not userId or not artistId: return jsonify({"error": "Missing 'userId' or 'artistId' in request body"}), 400 query_body = delete...
def get_user_history_query(userId, limit, skip): user_iri = get_user_iri(userId) query_body = f''' SELECT DISTINCT ?relationshipType ?artist WHERE {{ BIND (IRI("{user_iri}") AS ?user) ?user ?relationshipType ?artist . ?relationshipNode ex:created ?timestamp . FILTER EXISTS {{ ?rela...
The main task of the code is to fetch a user's history data by retrieving 'userId', 'limit', and 'skip' parameters from the request. It validates the 'userId', constructs a SPARQL query, executes it, and returns processed results. If 'userId' is missing, it returns an error. The function debugs parameter values and upd...
def get_user_history(): limit = request.args.get('limit') skip = request.args.get('skip') userId = request.args.get('userId') print("Debug - :", userId, limit, skip) # Debugging line if not userId: return jsonify({"error": "Missing 'userId' in request query parameter"}), 400 query_bod...
def MakeWalls(self): WallsIndex = np.random.randint(0, len(self.WallsDataset[0])) Walls = self.WallsDataset[0][WallsIndex] WallsPoints = self.WallsDataset[1][WallsIndex] return Walls, WallsPoints def InitialState(self): self.done = False self.HistoryPath = [] sel...
This code resets the environment by initializing agent and target positions, generating walls, setting up maps for locations, readings, and visit counts, computing initial agent readings, and preparing observations and invalid actions for all agents. It prepares the environment for a new episode in a multi-agent reinfo...
def reset(self): self.AgentsLocations = [] self.TargetLocations = [] self.TargetLocationsGrid = [] self.AgentsLocationsGrid = [] self.AgentsPrevLocations = [] self.AgentsPrevLocationsGrid = [] self.done = False self.Found = [0] * self.NumOfTargets ...
def build_graph(config: dict) -> Graph: refs = {obj['Id']: set(find_guids(obj)) for obj in config["Content"]["Added"]} nodes = {obj['Id']: obj for obj in config["Content"]["Added"]} return Graph(nodes, refs) def __with_follow_symlinks(func): visited = set() def _wrapper(graph, cur_value, cur_path): ...
The function `walk_config` traverses a configuration graph, either following symbolic links (if enabled) or ignoring them. It constructs a graph from the input config, prepares starting nodes based on symlink handling, and initiates a traversal using the provided walker and provider. The traversal processes nodes and t...
def walk_config(walker, config, follow_symlinks=False): graph = build_graph(config) if follow_symlinks: provider = __with_follow_symlinks(__nodes_provider) starting_nodes = [(graph.nodes[k], [k]) for k in find_roots(graph)] else: provider = __ignore_targets(__nodes_provider) ...
def forward_prop(X, w, b): """ Do the forward computation and return f(x)= \sigma (Wx+b) """ return sigmoid(np.dot(w.T, X) + b) def compute_loss(A, Y, m): """ TODO: Compute the loss function based on the formula you derived. loss is a scalar Hint: 1) The formu...
The code implements an optimization loop for training a model using gradient descent with optional momentum. It iteratively updates weights and bias parameters, computes training and validation accuracy, logs results, and retains the best parameters based on validation performance. Momentum accelerates convergence by i...
def optimize(w, b, X, Y, X_dev, Y_dev, num_iterations, learning_rate, output_name, momentum): # Added momentum as argument m = X.shape[1] # m is the number of the samples max_acc = 0 max_train_acc = 0 max_w, max_b = w, b start_time = time.time() log = open(output_name+'.log', 'w') log.wr...
def initialize_w_and_b(dimension): w = np.zeros((dimension,1)) b = 0 return w, b def optimize(w, b, X, Y, X_dev, Y_dev, num_iterations, learning_rate, output_name, momentum): # Added momentum as argument m = X.shape[1] # m is the number of the samples max_acc = 0 max_train_acc = 0 max_w,...
The code trains a machine learning model using the provided training data, optimizes parameters (weights and bias) over a specified number of iterations with an optional momentum term, evaluates the model's performance on a development dataset, saves the optimized parameters to a file, and returns them. It initializes ...
def model(X_train, Y_train, X_dev, Y_dev, output_name, num_iterations=100, learning_rate=0.005, momentum=False): w, b = initialize_w_and_b(X_train.shape[0]) parameters = optimize(w, b, X_train, Y_train, X_dev, Y_dev, num_iterations, learning_rate, output_name, momentum) Y_prediction_dev = predict(paramete...
def read (self, dataSet): self.dataSet = dataSet self.inputs = np.array ([list (it.chain (*item [0])) for item in self.dataSet]) .T self.refOutputs = np.array ([self.outputDict[item [1]] for item in self.dataSet]) .T def classify (self): self.outputs0 = sigmoid (self.weights0 @ self.inpu...
The code trains a model using a training set until the cost falls below a specified threshold. It repeatedly classifies data, visualizes progress with asterisks, adjusts the model if the cost is too high, and finally reports training results.
def train (self, trainingSet, maxCost): self.read (trainingSet) while True: self.classify () print (int (self.cost () * 100) * '*') if self.cost () < maxCost: break self.correct () self.report ('Training set')
def flatten(self, matrix): # Create empty matrix flat_matrix = [] # trainsform to 1*9 prep_matrix = matrix[0] + matrix[1] + matrix[2] # convert to floats for i in range(len(prep_matrix)): prep_matrix[i] = float(prep_matrix[i]) # Transfor...
The code trains a neural network model by iteratively updating weights and biases to minimize cross-entropy error. It flattens input data, initializes weight/bias matrices, and runs epochs where weights are randomly adjusted if current error is lower than the previous minimum. The model computes prediction errors using...
def train(self, x, y, epochs=100, learning_rate=0.1): y_train = y # Create x_train self.x_train = [] # Flatten matrix + append into x_train for i in range(len(x)): logging.info(len(x)) self.x_train.append(self.flatten(x[i])) logging.debug(f'Flatt...
def exists(val): return val is not None def maybe_get_condition(self, token_ids = None, length = None): assert not (exists(token_ids) ^ self.should_condition), 'you either have text-conditioning turned on and have not passed in any conditioning semantic token ids, or vice versa' if not exists(token...
This code generates audio samples by iteratively sampling latent tokens using a mask that evolves over time, with optional text or acoustic prompts for conditioning. It handles quantizer levels, temperature scaling, and masking strategies to control the generation process, ultimately decoding token indices into audio u...
def generate( self, num_latents = None, *, mask = None, texts: Optional[Union[List[str], Tensor]] = None, cond_semantic_token_ids = None, prompt_acoustic_token_ids = None, seconds = None, batch_size = None, start_temperature = 1., f...
def exists(val): return val is not None def maybe_get_condition(self, token_ids = None, length = None): assert not (exists(token_ids) ^ self.should_condition), 'you either have text-conditioning turned on and have not passed in any conditioning semantic token ids, or vice versa' if not exists(token...
This code implements a masked language modeling task on quantized audio representations using a transformer-based model. It processes raw audio inputs through wav2vec and soundstream encoders, applies dynamic masking strategies, and computes cross-entropy loss for token prediction. The model supports conditional genera...
def forward( self, x, *, mask = None, cond_semantic_token_ids = None, only_train_generator = False, only_train_critic = False, generator_sample_temperature = None, **kwargs ): # if raw audio passed in, convert to residual quantized vect...