dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def merge_db_all(self): ''' merge_db_all :: None -> None ./ ''' with closing(shelve.open('members_lessons.db', 'c', writeback=True)) as db: dates = list(db.keys()) print("Length of dates: ", len(dates)) for date in dates: db[da...
The main task of the code is to act as a dispatcher for interval merging operations, selecting between three modes ('ALL', 'ADMIN', 'MANUAL') to execute corresponding merging methods. It checks the 'mode' attribute and invokes either merge_db_all(), merge_db_admin(), or merge_db_manual() accordingly. If an invalid mode...
def merge_db(self): ''' merge_db :: None -> None Wrapper around interval merging. ''' if self.mode == 'ALL': self.merge_db_all() elif self.mode == 'ADMIN': self.merge_db_admin() elif self.mode == 'MANUAL': self.merge_db_manual(...
def init_db_all(self): ''' init_db_all :: None -> None ./ ''' for dirpath, dirnames, filenames in os.walk(self.csv_folder): for filename in filenames: if filename.endswith('.csv'): with open(os.path.join(dirpath, filename)) as f: ...
The main task of the code is to initialize a shelf database by selecting the appropriate initialization method based on the `self.mode` value. It acts as a wrapper that calls either `init_db_all()`, `init_db_admin()`, or `init_db_manual()` depending on the mode, or prints an error if the mode is unrecognized.
def init_db(self): ''' init_db :: None -> None Wrapper around shelf database creation. ''' if self.mode == 'ALL': self.init_db_all() elif self.mode == 'ADMIN': self.init_db_admin() elif self.mode == 'MANUAL': self.init_db_manua...
def identify(self): print('* identifying i2c device') val = self.read_byte(MPU6050_RA_WHO_AM_I) if val != MPU6050_ADDRESS_AD0_LOW: raise OSError("No mpu6050 at address {}".format(self.address)) def write_byte(self, reg, val): self.bytebuf[0] = val self.bus.writeto_mem...
This function initializes the MPU6050 sensor by configuring power management settings, selecting the clock source, enabling all sensors, setting the sampling rate, activating the digital low-pass filter, and specifying accelerometer/gyroscope ranges for accurate motion data collection.
def init_device(self): print('* initializing mpu') self.identify() # disable sleep mode and select clock source self.write_byte(MPU6050_RA_PWR_MGMT_1, MPU6050_CLOCK_PLL_XGYRO) # enable all sensors self.write_byte(MPU6050_RA_PWR_MGMT_2, 0) # set sampling rate ...
def init_pins(self): print('* initializing pins') self.pin_sda = Pin(self.sda) self.pin_scl = Pin(self.scl) self.pin_intr = Pin(self.intr, mode=Pin.IN) self.pin_led = PWM(Pin(self.led, mode=Pin.OUT)) def init_led(self): self.set_state_uncalibrated() def init_i2c(self): ...
This code initializes a sensor interface by setting up hardware pins (SCL, SDA, interrupt, LED) with default values if not provided. It configures I2C communication, initializes data buffers for sensor readings, calibration parameters, and a complementary filter. The main task is to prepare the sensor device for operat...
def __init__(self, scl=None, sda=None, intr=None, led=None, rate=None, address=None): self.scl = scl if scl is not None else default_pin_scl self.sda = sda if sda is not None else default_pin_sda self.intr = intr if intr is not None else default_pin_intr ...
def init_argparse() -> argparse.ArgumentParser: ''' Initialize the argument parsing. Returns: argparse.ArgumentParser. ''' parser = argparse.ArgumentParser( prog='pest_control.py', usage='%(prog)s [OPTIONS]... BUG_FILE FILE', description='Search a text file for bugs ...
The main task of the code is to parse command-line arguments, read input files containing bug data and landscape information, handle file-related errors, and search for bugs in the landscape using the provided bug data. It outputs the number of bugs found. The code also supports a debug mode for detailed logging. Your ...
def main() -> None: ''' Main function. ''' global DEBUG # Parse the arguments parser = init_argparse() args = parser.parse_args() # Set DEBUG variable if args.debug: DEBUG = True # Read the input files try: bug = read_file(args.BUG_FILE[0]) printd(f...
def fibonacci(n): if n <= 0: print("Wrong input") elif n == 1: return 0 elif n == 2: return 1 else: return fibonacci(n - 1) + fibonacci(n - 2) def return_fib_fact(n): fib = fibonacci(n) fact = factorial(fib) return [fib, fact] def ordinal(number): if numb...
The main task of the code is to compute the nth Fibonacci number and its factorial for a given positive integer. It uses the `return_fib_fact` function to obtain both values, then prints the result with ordinal formatting (e.g., "1st", "2nd") for the Fibonacci number and its factorial. The code combines input handling,...
def main(): number = int(input("Enter the positive number : ")) term = fibonacci(number) [fib, fact] = return_fib_fact(number) print("\nThe {0}{1} number in the Fibonacci sequence is {2}".format(number, ordinal(number), fib)) print("The factorial of {0} is {1}".format(fibonacci(number), fact))
def createModelMatrix(self, translate=(0,0,0), scale=(1,1,1), rotate=(0,0,0)): translateMatrix = [ [1, 0, 0, translate[0]], [0, 1, 0, translate[1]], [0, 0, 1, translate[2]], [0, 0, 0, 1] ] scaleMatrix = [ ...
This code loads a 3D model from an .obj file, applies translation, scaling, and rotation transformations, processes vertices, texture coordinates, and normals, and renders each face as triangles with camera transformations and lighting data for rendering.
def load(self, filename, translate=(0,0,0), scale=(1,1,1), rotate=(0,0,0)): model = Obj(filename) modelMatrix = self.createModelMatrix(translate, scale, rotate) rotationMatrix = self.createRotationMatrix(rotate) for face in model.faces: vertCount...
def CreateW(self, width, height): self.width = width self.height = height self.clear() self.ViewP(0, 0, width, height) def createViewMatrix(self, camPosition = (0, 0, 0), camRotation = (0, 0, 0)): camMatrix = self.createModelMatrix(translate = camPosition, rotate = camRotati...
Your return The code initializes a 3D graphics context by setting up a window with specified dimensions, defining a light source direction, and preparing essential matrices (view and projection) for rendering. It also initializes placeholders for textures, maps, and shaders, while configuring default colors for renderi...
def __init__(self, width, height): self.current_color = WHITE self.bmp_color = BLACK self.CreateW(width, height) self.luzX, self.luzY, self.luzZ = 0, 0, 1 self.luz = (self.luzX, self.luzY, self.luzZ) self.atexture = None self....
def getMaxRow(self,sheet): '''get the max row number, not the count of used row number''' return self.getSheet(sheet).Rows.Count def getMaxCol(self,sheet): '''get the max col number, not the count of used col number''' return self.getSheet(sheet).Columns.Count def getRange(self,sheet,row...
This function deletes a specified number of rows starting from a given row in an Excel sheet. It validates the input range to ensure deletion is within the sheet's bounds, then uses the getRange method to delete the selected rows.
def deleteRows(self,sheet,fromRow,count=1): '''delete count rows of the sheet''' maxRow = self.getMaxRow(sheet) maxCol = self.getMaxCol(sheet) endRow = fromRow+count-1 if fromRow > maxRow or endRow <1: return self.getRange(sheet,fromRow,1,endRow,maxCol).Delete...
def start(self, value): try: size = int(value) if size < 5: self.output = "ERROR wrong size\n" return self.gameBoard.createBoard(size) self.boardSize = size self.output = "OK\n" except ValueError: sel...
This method processes input commands by checking the first argument. It executes corresponding actions like starting a game, handling turns, displaying the board, or ending the game. It calls specific functions based on commands such as "START," "TURN," "BEGIN," "BOARD," etc., and uses printOutput() to display results ...
def computeInput(self, args, file): self.arg = self.input.split() nbArg = len(self.arg) if (self.arg[0] == "START" and nbArg == 2): self.start(self.arg[1]) self.printOutput() elif (self.arg[0] == "TURN" and nbArg == 2): self.turn(self.arg[1]) ...
def check(cosplay): m, e = "m", "e" while not m.isdigit() or not e.isdigit(): try: if cosplay == 1 or cosplay == 3: m, e = input("Enter public key m and e (split with space): ").split(" ") else: m, e = input("Enter private key m and e (split with s...
The code defines a `Driver` function that runs a menu-driven interface for RSA operations. It loops until the user quits, allowing selection of roles (Alice, Bob, Eve) or key generation. Input validation ensures valid choices, and corresponding functions handle encryption, decryption, or key generation based on user se...
def Driver(): while True: # Loop till user quits cosplay = None print("\n\n***************-------------------------------------***************\n") print("Hi! I can do RSA\n") print("I have a few cosplays for you to play, choose one from below\n") while cosplay is None: ...
def get_white_lanes(obs,isTurn=False, horizon=1/7, houghTreshold=300, white_treshold=168, side_tresholds=1/2.3,minLineLength=200): image=select_white(obs) return get_lanes(image, isTurn, horizon, houghTreshold, side_tresholds, minLineLength) def get_yellow_lanes(obs, isTurn=False, horizon=1/7, houghTreshold=300...
The code detects lane markers (white/yellow) from an observation, prioritizing yellow lanes. It calculates the vehicle's angle and distance from the lane center using detected lines, adjusting values based on lane type and position. Returns localized pose (angle, distance) or None if no valid markers are found.
def get_pose(obs, isTurn=False, horizon=1/7, houghTreshold=300, white_treshold=168, side_tresholds=1/2.3,minLineLength=200): white_left, white_right = get_white_lanes(obs.copy(), isTurn, horizon, houghTreshold, white_treshold, side_tresholds, minLineLength=minLineLength) yellow_left, yellow_right = get_yellow_l...
def is_drivable(self, i, j): if i < 0 or i >= self.tile_height or j < 0 or j >= self.tile_width: return False return self.grid[i][j] def is_junction(self, i, j): return self.is_drivable(i, j) and self.get_drivable_around(i, j) > 2 def is_straight(self, i, j): hor = self.is_dr...
The main task of the code is to determine whether a given cell (i, j) is suitable for a turn by checking if it is drivable, not a junction, and not part of a straight path. The function returns `True` if all three conditions are met, indicating the cell allows for a valid turn.
def is_turn(self, i, j): return (self.is_drivable(i, j) and not self.is_junction(i, j) and not self.is_straight(i, j))
def is_junction(self, i, j): return self.is_drivable(i, j) and self.get_drivable_around(i, j) > 2 def is_turn(self, i, j): return (self.is_drivable(i, j) and not self.is_junction(i, j) and not self.is_straight(i, j)) def is_drivable(self, i, j): if i < 0 or i >=...
The code generates a grid of characters representing drivable areas, junctions, and turns. It initializes a grid with 'N's, then replaces each cell with 'J' (junction), 'T' (turn), or 'D' (drivable) based on the terrain type. It prints each row as a string and returns the final labeled grid.
def get_letter_grid(self): self.letter_grid = [['N' for _ in range(self.tile_width)] for _ in range(self.tile_height)] for i in range(self.tile_height): for j in range(self.tile_width): # s += str(self.get_drivable_around(i, j)) if self.is_junction(i, j): ...
def update_face(self): ''' Update direction faced 0, 1, 2, 3: Right, Up, Left, Down ''' self.face = self.get_dir_next_tile(self.prev_tile, self.cur_tile) return self.face def localize_tile_change(self): # Localize rough pose rough_orientation=self.get_dir_...
The code predicts the robot's action (speed, steering) based on localization, orientation adjustment, and grid navigation rules. It handles initial position adjustment, relative pose estimation from sensor data, tile transitions, and decision-making for turns or straight movement using grid properties and previous acti...
def predict(self, obs, cur_pos=None): if cur_pos is None: return 0, 0 self.cur_tile = cur_pos if self.cur_tile == self.goal_tile: self.reached_goal = True return 0, 0 prev_prev_act=self.prev_act # GET ACTION # Just started - adjust fi...
def val_dataloader(self): return self._get_dataloader(self.val_image_folder, is_val=True) def train_dataloader(self): return self._get_dataloader(self.train_image_folder, is_val=False) def _construct_class_hierarchy_graph(self): graph = nx.Graph() graph.add_node('0') classes = li...
This code initializes a trainer/model for hierarchical image classification, setting up parameters like data folders, batch size, learning rate, and class hierarchy. It merges training/validation class mappings, constructs a hierarchy graph, and prepares tools for label conversion and loss computation using CrossEntrop...
def __init__(self, train_image_folder, val_image_folder, n_jobs, batch_size, hierarchy_weights, seq_len=None, lr=1e-3, epoch_size=None, reader=None, stratified_input=False): super().__init__() self.train_image_folder = train_image_folder self.val_image_folder = val_image_folder...
def execute_move(move): copy = [row[:] for row in board] last_boards.append(copy) piece, last_i, last_j, i, j = move board[last_i][last_j] = ' ' board[i][j] = piece def mark_threats(pieces_set): global possible_moves, is_check possible_moves = [] is_check = False pieces = pieces_set ...
This function filters out moves from white's possible moves that would leave the white king in check. It simulates each move, checks if it results in a check using black's threats, and removes such moves from the list.
def remove_forbidden_white_moves(white_poss_moves): del_white_moves = [] for move in white_poss_moves: # piece, last_i, last_j, i, j = move # if piece == 'K': # if black_threats[i][j] == THREAT: # del_white_moves.append(move) # continue execut...
def execute_move(move): copy = [row[:] for row in board] last_boards.append(copy) piece, last_i, last_j, i, j = move board[last_i][last_j] = ' ' board[i][j] = piece def mark_threats(pieces_set): global possible_moves, is_check possible_moves = [] is_check = False pieces = pieces_set ...
The function filters out invalid moves from black's possible moves by checking if each move leaves the black king in check. It temporarily applies each move, assesses if the black king is threatened, and removes the move if it results in a check. This ensures only legal moves remain in the list.
def remove_forbidden_black_moves(black_poss_moves): del_black_moves = [] for move in black_poss_moves: # piece, last_i, last_j, i, j = move # if piece == 'k': # if white_threats[i][j] == THREAT: # del_black_moves.append(move) # continue execut...
def mark_threats(pieces_set): global possible_moves, is_check possible_moves = [] is_check = False pieces = pieces_set copy = [row[:] for row in board] for i, row in enumerate(board): for j, piece in enumerate(row): if piece == ' ': continue if pie...
This code determines if a checkmate can be forced within a specified number of moves. It recursively explores white's possible moves, checks if black has no valid responses, and verifies if subsequent moves lead to a forced mate. If black has only one move, it executes it and continues checking. The function returns Tr...
def solve(moves_num): mark_threats(white_pieces) white_poss_moves = [move[:] for move in possible_moves] check_for_black = is_check remove_forbidden_white_moves(white_poss_moves) # check for mate if moves_num == 0: if check_for_black: mark_threats(black_pieces) b...
def mark_threats(pieces_set): global possible_moves, is_check possible_moves = [] is_check = False pieces = pieces_set copy = [row[:] for row in board] for i, row in enumerate(board): for j, piece in enumerate(row): if piece == ' ': continue if pie...
The main task of the code is to analyze a game state by marking threats on the board, evaluating valid moves for both players, checking for check conditions, removing invalid moves, and solving the game. It then prints the remaining possible moves, check statuses, and final board states after processing, likely for deb...
def main(): white_threats = mark_threats(white_pieces) white_poss_moves = [move[:] for move in possible_moves] check_for_black = is_check # print_board(white_threats) black_threats = mark_threats(black_pieces) black_poss_moves = [move[:] for move in possible_moves] check_for_white = is_chec...
def get_refresh_tags_time(self): if os.path.exists(self.db): with open(self.db, 'r') as f: return json.load(f)['refresh_tags_time'] else: return None def get_latest_tag(self, p): res = self.get('/projects/' + str(p['id']) + '/repository/tags?order_by=name&...
The function `refresh_tags` checks if sufficient time has elapsed since the last tag refresh. If not, it skips refreshing; otherwise, it retrieves the latest tags for all projects and saves them with the current timestamp. The delta parameter determines the minimum interval between refreshes, ensuring tags are updated ...
def refresh_tags(self, delta=None): previous = self.get_refresh_tags_time() if previous is not None and delta is not None: from datetime import datetime, timedelta if type(delta) == str: delta = int(delta) if type(delta) == int: delta =...
def _add_terminal(self, seq: AtomicSequence, value: str): seq.elements.append(Terminal(value=value)) def _snakify(s: str) -> str: return inflection.underscore(str(s)).replace(" ", "_") def _atomic_range_as_symbol(self, range: str, schemaview: SchemaView = None): if range is None: range =...
This function generates a production rule for a class slot in a schema grammar, handling both single and multivalued slots. It constructs the right-hand side of the rule with terminals (e.g., "address="), brackets for multivalued slots, and non-terminals representing the slot's range. It processes unions, cardinality, ...
def _add_slot( self, sg: SchemaGrammar, slot: ClassDefinition, slot_sym: str, schemaview: SchemaView = None ): """ Generates a production rule for a slot in the context of a class. For example: .. code :: Person_address : "address=" Address If the slot...
def _add_abstract_class(self, sg: SchemaGrammar, cls: ClassDefinition, schemaview: SchemaView): sym = self._class_symbol(cls.name) rule = ProductionRule(lhs_symbol=sym) disj = Disjunction(operands=[]) for child in schemaview.class_children(cls.name): child_sym = self._class_s...
This function generates production rules for a class in a schema grammar. It creates a rule for the class symbol, constructs its RHS from annotations, and adds slot-specific rules if needed. For non-abstract classes, it builds syntax with terminals for class name and slots, using "?" for optional slots. It handles both...
def _add_class(self, sg: SchemaGrammar, cls: ClassDefinition, schemaview: SchemaView): abstract = cls.abstract or cls.mixin if abstract: return self._add_abstract_class(sg, cls, schemaview) sym = self._class_symbol(cls.name) rule = ProductionRule(lhs_symbol=sym) rule....
def _class_symbol(self, class_name: str) -> str: return f"class_{_snakify(str(class_name))}" def _add_class(self, sg: SchemaGrammar, cls: ClassDefinition, schemaview: SchemaView): abstract = cls.abstract or cls.mixin if abstract: return self._add_abstract_class(sg, cls, schemaview) ...
This function converts input (string, file, or SchemaDefinition) into a SchemaGrammar by parsing classes, types, and enums from the input, setting start symbols, and configuring grammar rules with specified pragmas like "ignore WS"
def convert( self, input: Union[str, TextIO, SchemaDefinition], starts: List[str] = None, **kwargs ) -> SchemaGrammar: """ Convert input to a SchemaGrammar :param input: input to convert :param kwargs: additional arguments :return: SchemaGrammar """ if...
def action(self, player): playableActions = [] if(player == 1): hand = self.hand1 discard = self.discard1 else: hand = self.hand2 discard = self.discard2 # gets all of the actions in the hand for card in hand: if(card[...
This function manages a player's turn in a game, resetting action/buy counters, logging game state (e.g., card counts, hand) to a file, executing the player's action phase, buying phase, and cleanup. It differentiates between two players by tracking their respective hand states and game-specific metrics, ensuring turn ...
def turn(self, player): self.turnNumber += 1 self.costReduction = 0 self.actions = 1 self.buys = 1 self.coins = 0 if(self.currentPlayer == 1): self.file.write(str(self.turnNumber) + ": " + str(self.numWorkshop) + ", " + str(self.numGarden) + ", " + s...
def action(self): playableActions = [] # gets all of the actions in the hand for card in self.hand: if(card[:6] == "action"): playableActions.append(card) # plays the actions while(len(playableActions) > 0 and self.actions > 0): #print(pl...
The code's main task is to manage a game turn by incrementing the turn count, initializing resources (actions, buys, coins), logging game state data (provinces, game pieces, hand status) to a file, executing actions, making purchases, and cleaning up. It tracks progress, maintains game variables, and records turn detai...
def turn(self): self.costReduction = 0 self.turnNumber += 1 self.actions = 1 self.buys = 1 self.coins = 0 self.file.write(str(self.turnNumber) + ": " + str(self.provinces) + ", " + str(self.numInventor) + ", " + str(self.numVillage) + ", " + str(self.numLaboratory) + "...
def action(self): playableActions = [] # gets all of the actions in the hand for card in self.hand: if(card[:6] == "action"): playableActions.append(card) # plays the actions while(len(playableActions) > 0 and self.actions > 0): if("actio...
The code manages a game turn by incrementing the turn counter, initializing action and buy limits, resetting coins, and executing action, buy, and cleanup phases to progress the game state.
def turn(self): self.turnNumber += 1 self.actions = 1 self.buys = 1 self.coins = 0 self.action() self.buy() self.cleanUp()
def possDraws(deck,base={},n=5): # Makes copies so as to not disturb the originals d = deck.copy() b = base.copy() # If the deck is empty, return base (as long at it is a valid hand) if len(d)==0: spots = spotsLeft(b) if spots > 0: return [] elif spots == 0: ...
The code calculates probabilities for all possible hands drawn from a deck, then iterates through each hand to execute actions (e.g., game logic) with the deck and hand, using a depth parameter of 1. It combines probability analysis with decision-making in a card game context.
def turn(deck,handHistProb,): # Generate possible hands and probabilities possibleHands = possDraws(deck) probabilities = {} for hand in possibleHands: prob = probDraw(hand,deck) probabilities[tuple(hand.items())] = prob # Loop through each possible hand for hand in possible...
def action(self, player): playableActions = [] if(player == 1): hand = self.hand1 discard = self.discard1 else: hand = self.hand2 discard = self.discard2 # gets all of the actions in the hand for card in hand: if(card[...
This code manages a game turn by initializing resources (actions, buys, coins), logging game state data to a file, executing player actions, handling purchases, and cleaning up after the turn. It differentiates between players by tracking their specific game elements and hand states, ensuring turn progression and data ...
def turn(self, player): self.turnNumber += 1 self.costReduction = 0 self.actions = 1 self.buys = 1 self.coins = 0 if(self.currentPlayer == 1): self.file.write(str(self.turnNumber) + ": " + str(self.provinces) + ", " + str(self.numInventor) + ", " + s...
def action(self, player): playableActions = [] if(player == 1): hand = self.hand1 discard = self.discard1 else: hand = self.hand2 discard = self.discard2 # gets all of the actions in the hand for card in hand: if(card[...
This code handles a player's turn in a game, tracking the turn number, resetting resources (actions, buys, coins), logging game state to a file, executing the player's action phase, buy phase, and cleanup. It differentiates between two players by accessing respective card counts and hands, writing hand states before an...
def turn(self, player): self.turnNumber += 1 self.costReduction = 0 self.actions = 1 self.buys = 1 self.coins = 0 if(self.currentPlayer == 1): self.file.write(str(self.turnNumber) + ": " + str(self.provinces) + ", " + str(self.numInventor1) + ", " + ...
def shuffleDeck(self, player): # just shuffles the deck if(player == 1): random.shuffle(self.deck1) else: random.shuffle(self.deck2) def draw(self, numCardsWanted, player): if(player == 1): deck = self.deck1 hand = self.hand1 else:...
This code simulates a game turn sequence by shuffling decks, dealing cards to two players, and alternating turns until provinces are exhausted or three termination conditions (card count thresholds) are met. It tracks empty piles based on specific card quantities, switches players each iteration, and closes a file afte...
def simulateRun(self): self.shuffleDeck(1) self.shuffleDeck(2) self.draw(5, 1) self.draw(5, 2) emptyPiles = 0 while(self.provinces > 0 and emptyPiles < 3): emptyPiles = 0 if(self.numWorkshop == 10): emptyPiles += 1 if...
def shuffleDeck(self): # just shuffles the deck random.shuffle(self.deck) def draw(self, numCardsWanted): # how many cards have been drawn numDrawn = 0 # run this if there are not enough cards in the deck if(len(self.deck) < numCardsWanted): # put the cards i...
This method simulates a game run by shuffling the deck, drawing 5 initial cards, and repeatedly executing game turns until all provinces are exhausted, then closing the associated file.
def simulateRun(self): self.shuffleDeck() self.draw(5) while(self.provinces > 0): self.turn() self.file.close()
def shuffleDeck(self): # just shuffles the deck random.shuffle(self.deck) def draw(self, numCardsWanted): # how many cards have been drawn numDrawn = 0 # run this if there are not enough cards in the deck if(len(self.deck) < numCardsWanted): # put the cards i...
The code simulates a game scenario by shuffling a deck, drawing 5 cards, and executing two turns. Its main task is to initialize and progress a card game sequence, likely for testing or simulation purposes.
def simulateRun(self): self.shuffleDeck() self.draw(5) for number in range(2): self.turn()
def shuffleDeck(self, player): # just shuffles the deck if(player == 1): random.shuffle(self.deck1) else: random.shuffle(self.deck2) def draw(self, numCardsWanted, player): if(player == 1): deck = self.deck1 hand = self.hand1 else:...
The code simulates a turn-based card game between two players. It initializes the game by shuffling decks and dealing cards, then alternates turns until either all provinces are exhausted or three specific card types (duchies, inventor, village, laboratory, festival2, smithy2) reach a maximum count. The loop tracks emp...
def simulateRun(self): self.shuffleDeck(1) self.shuffleDeck(2) self.draw(5, 1) self.draw(5, 2) emptyPiles = 0 while(self.provinces > 0 and emptyPiles < 3): self.turn(self.currentPlayer) self.currentPlayer = self.currentPlayer % 2 + 1 ...
def shuffleDeck(self, player): # just shuffles the deck if(player == 1): random.shuffle(self.deck1) else: random.shuffle(self.deck2) def draw(self, numCardsWanted, player): if(player == 1): deck = self.deck1 hand = self.hand1 else:...
The code simulates a turn-based card game where two players alternately draw cards, track game state variables (provinces, duchies, etc.), and check termination conditions. The loop continues until provinces are exhausted, three specific card piles are depleted, or 2000 turns pass. The function shuffles decks, manages ...
def simulateRun(self): self.shuffleDeck(1) self.shuffleDeck(2) self.draw(5, 1) self.draw(5, 2) emptyPiles = 0 while(self.provinces > 0 and emptyPiles < 3 and self.turnNumber < 2000): self.turn(self.currentPlayer) self.currentPlayer = self.current...
def thetaforecast(states, n, modeltype, f, h, alpha, theta): # compute forecasts new_states = thetafcst( states=states, i=n, modeltype=modeltype, f=f, h=h, alpha=alpha, theta=theta ) return new_states def switch_theta(x: str): return {"STM": 0, "OTM": 1, "DSTM": 2, "DOTM": 3}[x] def compute_...
This function generates forecasts using the theta method, computes prediction intervals for specified confidence levels, and adjusts forecasts with seasonal components if decomposition is enabled. It initializes a forecast array, applies theta forecasting, calculates standard deviation for intervals, and combines seaso...
def forecast_theta(obj, h, level=None): forecast = np.full(h, fill_value=np.nan) n = obj["n"] states = obj["states"] alpha = obj["par"]["alpha"] theta = obj["par"]["theta"] thetaforecast( states=states, n=n, modeltype=switch_theta(obj["modeltype"]), h=h, f...
def initparamtheta( initial_smoothed: float, alpha: float, theta: float, y: np.ndarray, modeltype: str ): if modeltype in ["STM", "DSTM"]: if np.isnan(initial_smoothed): initial_smoothed = y[0] / 2 optimize_level = 1 else: optimize_level = 0 if np.isna...
The code optimizes smoothing parameters (alpha, theta, initial_smoothed) for a time series model using the provided data `y`. It initializes parameters, performs optimization via `optimize_theta_target_fn`, updates optimized values, computes residuals and error metrics (MSE/AMSE), and returns results including model st...
def thetamodel( y: np.ndarray, m: int, modeltype: str, initial_smoothed: float, alpha: float, theta: float, nmse: int, ): # initial parameters par = initparamtheta( initial_smoothed=initial_smoothed, alpha=alpha, theta=theta, y=y, modeltype=mod...
def initparamces( alpha_0: float, alpha_1: float, beta_0: float, beta_1: float, seasontype: str ): if np.isnan(alpha_0): alpha_0 = 1.3 optimize_alpha_0 = 1 else: optimize_alpha_0 = 0 if np.isnan(alpha_1): alpha_1 = 1.0 optimize_alpha_1 = 1 else: optimi...
The code implements a CES (Constant Elasticity of Substitution) model for time series analysis, optimizing selected parameters (alpha_0, alpha_1, beta_0, beta_1) using provided data. It initializes model states, performs parameter optimization via `optimize_ces_target_fn`, computes residuals, fitted values, and statist...
def cesmodel( y: np.ndarray, m: int, seasontype: str, alpha_0: float, alpha_1: float, beta_0: float, beta_1: float, nmse: int, ): if seasontype == "N": m = 1 # initial parameters par = initparamces( alpha_0=alpha_0, alpha_1=alpha_1, beta_1=beta...
def gen_faces_video(length, person_1, person_2, i, output_path): faceVid1 = f"face_videos/{person_1} D Video.mp4" faceVid2 = f"face_videos/{person_2} A Video.mp4" if i%2==0: faceVid1 = f"face_videos/{person_1} A Video.mp4" faceVid2 = f"face_videos/{person_2} D Video.mp4" vid1 = "roaster...
The code generates a video by processing each audio file to create face animations, combining them sequentially with audio and beat overlays, then cleaning up temporary files. It initializes with an intro video, generates face videos for each audio segment, appends them, mixes audio with a beat, and outputs the final v...
def create_video(audio_files, first_speaker, second_speaker): """ init_video = intro vid for each audio file: get length of audio file generate face videos of length audio file combine face vids add audio to vid add beat overlay to vid append vid to init_video """ ...
def read_summary_file(nex_session, summary_type, summary_file_reader, all_Locusdbentity, all_Referencedbentity): name_to_dbentity = dict([(x.systematic_name, x) for x in all_Locusdbentity]) sgdid_to_dbentity_id = dict([(x.sgdid, x.dbentity_id) for x in all_Locusdbentity]) pmid_to_reference_id = dict([(x.pmi...
The code loads summary data from a file into a database, comparing it with existing records. It updates or inserts summaries and their references, tracking changes (added/updated). The function uses SQLAlchemy to query and modify database entries, ensuring consistency by checking text/html content before updates. It re...
def load_summaries(nex_session, summary_file_reader, username, summary_type=None, ): CREATED_BY = username if summary_type is None: summary_type = "Phenotype_Regulation" # load lots of data into memory, perhaps could be filtered global all_Locusdbentity all_Locusdbentity = nex_session.query(...
def fov2f(self, R, fov, k=-0.5): ''' calculate focal length from fov and distance to image edge based on PTGui 11 fisheye projection with fisheye factor k (https://wiki.panotools.org/Fisheye_Projection) R : distance from principal point to image edge in mm fov : fov angle in ra...
This function generates a virtual sphere patch of size 'height x width', where each pixel contains spherical (longitude/latitude) coordinates. It calculates these coordinates by mapping pixel positions to a 3D sphere's surface, adjusting for sensor parameters, focal length, and rotation. The output is a tensor of spher...
def patch_of_sphere(self, height, width, fov, lon_rot, center): ''' make patch sized 'height x width' that each pixel of which contains spherical(geographic) coordinates of virtual sphere ''' # sensor pitch d = self.sensor_height/height # principal point ...
def uvwha2corners(self, u, v, w, h, a): ''' calculate corner coordinates from uvwha bbox information ''' center = torch.tensor([[u],[v]]) corners = torch.tensor([[-h/2, -w/2], [-h/2, w/2], [h/2, -w/2], ...
This function computes tangent image patches from UVWHA bounding boxes on a fisheye image, converting them to spherical coordinates (longitude/latitude) and sampling patches via grid interpolation. It returns patches, optionally spherical coordinates, and scale factors, with visualization support.
def get_tangent_patch(self, uvwha, visualize=False, detectnet=False, height=None, width=None, scale=None): ''' compute tangent image patch f...
def __load_cache(self, key): try: return jsonloader.loadfile(f"cache/{key}__cache.json") except: return None def get_events_year_keys(self, year): return self.__get_data(f"/events/{year}/keys") def get_event_teams_keys(self, event_key): return self.__get_data(f"/e...
The function retrieves and returns a sorted list of active teams for a specific year, either from memory/cache or by fetching event data, extracting team participants, deduplicating them, and sorting by numeric team identifiers.
def get_active_teams_year(self, year): name = f"active_{year}" if name in self.memory: return self.memory[name] cache = self.__load_cache(name) if cache is not None: self.memory[name] = cache['data'] return cache['data'] events = self.get_event...
def __load_cache(self, key): try: return jsonloader.loadfile(f"cache/{key}__cache.json") except: return None def get_events_year_keys(self, year): return self.__get_data(f"/events/{year}/keys") def get_event_teams_keys(self, event_key): return self.__get_data(f"/e...
This function retrieves or generates a dictionary mapping teams to their associated events for a specific year, using caching to optimize performance. It first checks memory/cache for precomputed data; if unavailable, it fetches events for the year, maps each event's participating teams, and constructs the team-event r...
def get_team_events_year(self, year): name = f"team_events_{year}" if name in self.memory: return self.memory[name] cache = self.__load_cache(name) if cache is not None: self.memory[name] = cache['data'] return cache['data'] team_events = defau...
def _check_events(self): """Responds to keypresses and mouse events.""" for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.KEYDOWN: self._check_keydown_events(event) elif event.type == py...
The code defines a method `run_game` that initiates an infinite loop to manage the game's main operations. It continuously checks for events, updates the player's ship, bullets, and aliens, then redraws the screen, creating an interactive game loop for real-time gameplay.
def run_game(self): """Start the main loop for the game.""" while True: self._check_events() self.ship.update() self._update_bullets() self._update_aliens() self._update_screen()
def get_neighbourhood(self): # deprecated x, y = self.grid_location[0], self.grid_location[1] delta = self.board.grid_spacing + 1 return (x - delta, y - (2 * delta), x + (2 * delta), y + delta + 2) def find_neighbours(self): # deprecated # self.neighbours = self.board.fin...
This code initializes a game element (likely a cell in a grid-based simulation) by setting up its board reference, visual properties (rectangle with tags), grid position, neighbor relationships, and interaction bindings. It creates a graphical cell, defines its initial state (alive/active), identifies adjacent cells, a...
def __init__(self, board, x0, y0, x1, y1, **kwargs): self.board: LifeBoard = board self.alive: bool = False self.activate_next: bool = False self.grid_location = (x0, y0) self.id = self.board.create_rectangle(x0, y0, x1, y1, tags=(f"x{x0}", f"y{y0}"), outline=self.OUTLINE_COLOUR,...
def handle_kwarg(self, key, value): if key == "pan" and value: self.make_pannable = True elif key == "zoom" and value: self.make_zoomable = True elif key == 'logger' and value: self.log_widget = value def do_binds(self): self.bind("<Button-3>", self.al...
This code initializes a Game of Life canvas with zoom/pan controls, setting up parameters like grid spacing, frame rate, and cell dictionaries. It processes keyword arguments, configures drawing settings, and prepares the initial game state for rendering and interaction.
def __init__(self, parent, **kwargs): self.parent: GameOfLife = parent canvas_args: dict = {} self.make_pannable = False self.make_zoomable = False self.log_widget: Text = None self.max_zoom = 1 self.min_zoom = -3 self.factor = 1 self.drawing_facto...
def initial_population(pop_size, city_list): population = [] for i in range(pop_size): population.append(create_route(city_list)) return population def rank_routes(population): fitness_results = {} for i in range(0,len(population)): fitness_results[i] = Fitness(population[i]).route_...
The main task of the code is to implement a genetic algorithm for optimizing a route (likely for the Traveling Salesman Problem), iteratively evolving a population of solutions over generations using selection, crossover, and mutation. It tracks and prints the best route's distance, with an optional visualization of pr...
def genetic_algorithm(population, pop_size, elite_size, mutation_rate, generations,visualize=True): pop = initial_population(pop_size, population) print("Initial distance: " + str(1 / rank_routes(pop)[0][1])) # inverse since what was returned was route fitness which is 1/route_distance() for i in range(0, ...
def boundaries(game): if len(game) > 1: left = game[0][0] right = game[-1][-1] return left, right else: left = game[0][0] right = game[0][-1] return left, right def game_result(game, computer, player, number_of_stock_pieces): # checks game results if le...
The main task of the code is to validate if a game has ended in a draw by checking if 8 or more game pieces meet specific boundary conditions. If so, it returns a draw status and prints results; otherwise, it directly prints the game outcome. The function uses helper functions to determine boundaries, count occurrences...
def check_game_result(game, computer, player, number_of_stock_pieces): # validating game results if len(game) >= 8: left, right = boundaries(game) # calling boundaries function times = 0 # couting how many times a border was met for i in game: if...
def Lv(inpic, shape = 'same'): Lx = convolve2d(inpic, deltax(), shape) Ly = convolve2d(inpic, deltay(), shape) return np.sqrt(Lx**2 + Ly**2) def Lvvtilde(inpic, shape = 'same'): dxmask = np.array([[0, 0, 0, 0, 0],[0, 0, 0, 0, 0],[0, -1/2, 0, 1/2, 0],[0, 0, 0, 0, 0],[0, 0, 0, 0, 0]]) # sh...
The code performs edge detection by applying Gaussian smoothing, calculating gradient magnitude and higher-order derivatives, and extracting zero-crossing curves with thresholding to identify contours in an image.
def extractedge(inpic, scale, threshold, shape = 'same'): gaussianSmooth = discgaussfft(inpic, scale) gradmagn = Lv(gaussianSmooth, "same") Lvv = Lvvtilde(gaussianSmooth, shape) Lvvv = Lvvvtilde(gaussianSmooth, shape) Lvmask = gradmagn > threshold LvvvMask = Lvvv < 0 curves = zerocrosscurv...
def extractedge(inpic, scale, threshold, shape = 'same'): gaussianSmooth = discgaussfft(inpic, scale) gradmagn = Lv(gaussianSmooth, "same") Lvv = Lvvtilde(gaussianSmooth, shape) Lvvv = Lvvvtilde(gaussianSmooth, shape) Lvmask = gradmagn > threshold LvvvMask = Lvvv < 0 curves = zerocrosscurv...
The function `houghedgeline` detects lines in an image using the Hough transform. It first extracts edges, applies Gaussian smoothing, computes gradient magnitudes, and then performs the Hough line detection to identify line parameters (`linepar`) and the accumulator array (`acc`), returning them for further analysis o...
def houghedgeline(pic, scale, gradmagnthreshold, nrho, ntheta, nlines=20, verbose=False): curves = extractedge(pic, scale, gradmagnthreshold, "same") gaussianSmooth = discgaussfft(pic, scale) gradmagn = Lv(gaussianSmooth, "same") linepar, acc = houghline(pic, curves, gradmagn, nrho, ntheta, gradmagnthr...
def representative_msa(seq_list, mode='asm'): align_function = {'asm': asm_align, 'nw': nw_align} same_seq = sorted(set(seq_list), key=lambda x: -len(x)) inter_align_array = [] represent = same_seq[0] for s in same_seq: s_align, p_align = align_function[mode](s, represent, 1) inter_a...
The function aligns and adapts shortcut sequences by reconciling them with reference profiles, adjusting for gaps through alignment and insertion merging. It processes grouped shortcuts, computes aligned profiles, tracks gap indices, and merges insertions into a unified "starline" for each shortcut type. The result upd...
def shortcut_adapting(shortcuts, anchor_profile, inter_profile, mode='asm'): # initialize gap array for representative msa gap accumulation anchor_gap_array = [np.zeros([ap.shape[1] - 1]).astype(int) for ap in anchor_profile] inter_gap_array = [np.zeros([ip.shape[1] + 1]).astype(int)...
def create_kimoji(self): new_kimoji = enemy_objects.Kimoji(self.kimoji_img) self.kimojis.add(new_kimoji) self.all_sprites.add(new_kimoji) def create_star(self): new_star = player_objects.MultiShootBonus(self.star_img) self.stars.add(new_star) self.all_sprites.add(new_star...
The main task of the code is to manage game loop logic: trigger a boss fight when points exceed 1000 by spawning KIMOJI and eliminating existing enemies, dynamically spawn stars and enemies based on point thresholds, handle collisions, update game objects, and manage enemy shooting mechanics for rogers and KIMOJI, addi...
def on_loop(self): # initiate boss fight! (kill mobs and spawn KIMOJI) if self.points > 1000 and not self.boss_on: pygame.mixer.music.stop() boss_music = pygame.mixer.music.load("boss_music.mp3") pygame.mixer.music.play() self.boss_on = True se...
def on_init(self): pygame.display.set_caption("Laser Space Shooter 0.4") pygame.display.set_icon(pygame.image.load("shooter_icon.jpg")) self.all_sprites.add(ship) pygame.mixer.music.play(-1) self.high_score = self.get_high_score() def on_event(self, event): if event.type ...
The code defines a game loop that initializes the game, processes events, updates game logic, renders graphics, and cleans up resources. It runs continuously while `self.running` is True, handling user input, updating the game state, and redrawing the screen in each iteration. The loop ensures smooth gameplay by repeat...
def on_execute(self): self.on_init() while self.running: for event in pygame.event.get(): self.on_event(event) self.on_loop() self.on_render() self.on_cleanup()
def _eval_maha(self, loader, class_means, cov_mats): self._network.eval() vectors, y_true = self._extract_vectors(loader) dists = self._maha_dist(vectors, class_means, cov_mats) scores = dists.T # [N, nb_classes], choose the one with the smallest distance return np.argsort(score...
The code evaluates a model's performance on a test set using either Mahalanobis distance (if fecam is enabled) or a CNN-based approach. It computes the CNN accuracy (cnn_accy) by comparing predicted and true labels, while NME accuracy (nme_accy) remains uncomputed (None). The task involves conditional model evaluation ...
def eval_task(self): if self.args["fecam"]: y_pred, y_true = self._eval_maha(self.test_loader, self._network.fc.weight.data, self.cov_mats) else: y_pred, y_true = self._eval_cnn(self.test_loader) cnn_accy = self._evaluate(y_pred, y_true) nme_accy = None ...
def coinToss(p: float = 0.5): if random.random() < p: return True else: return False def AdverbialPhrase(): result = "" if coinToss(): result = f"{ModifyingAdverb()} {Adverb()}" return result def Adjective(): adj = getData("Adjective") return randomFromList(adj)
The main task of the code is to generate an adjective phrase, optionally prefixed with an adverbial phrase, based on a random coin toss. If the coin toss returns true, it combines outputs from AdverbialPhrase() and Adjective() into a string; otherwise, it returns an empty string.
def AdjecivePhrase(): result = "" if coinToss(): result = f"{AdverbialPhrase()} {Adjective()}" return result
def remove_stopwords(stopword_f,terms): with open(stopword_f) as file: stopword_list = [x.strip() for x in file]; stopword_list = normalize(stopword_list); result = [i for i in terms if i not in stopword_list]; return result; def tokenize(document): if os.path.isfile(os.path.join('.',docume...
This code indexes a collection of text documents by building an inverted index. It processes documents to extract terms, removes stopwords, applies stemming, and counts term frequencies. The vocabulary of unique terms with their frequencies is saved. Each document is assigned an ID and indexed with its terms. IDF value...
def index_collection(collection_dir,index_dir = './index',stopword_f ='stopwords.txt'): collection_dir = os.path.abspath(collection_dir) documents = [os.path.join(collection_dir,x) for x in os.listdir(collection_dir) if os.path.isfile(os.path.join(collection_dir,x)) and os.path.splitext(x)[1] == '.txt']; in...
def horizon(data, forecast_horizon, freq, series_type): #Input: Data, number of forecast, frequency of date, frequency of series a = max(data.index) if series_type == 0: b = timedelta(days = 1) #a = a + b dates = [] x = 0 while x < forecast_horizon: a = a + b dates.append(a.to_pyda...
The main task of the code is to process time-series data through ingestion, interpolation of missing values, imputation of missing dates, roll-up checks, stationarity/seasonality analysis, and forecasting using baseline and model-based predictions. It returns forecasted values for the specified horizon as a DataFrame.
def pipeline(data, forecast_horizon, freq, series_type): print('Ingesting Data....') horizon_dates = horizon(data, forecast_horizon, freq, series_type) print(f'Total datapoints: {data.shape[0]}') data.interpolate(method = 'time', inplace = True) #fill missing values print('Checking for missing Dates....'...
def horizon(data, forecast_horizon, freq, series_type): #Input: Data, number of forecast, frequency of date, frequency of series a = max(data.index) if series_type == 0: b = timedelta(days = 1) #a = a + b dates = [] x = 0 while x < forecast_horizon: a = a + b dates.append(a.to_pyda...
The main task of the code is to process time series data through ingestion, missing value imputation, roll-up checks, stationarity/seasonality analysis, and forecasting using baseline and additional models, returning predicted values for forecasted dates.
def pipeline(): st.write('Ingesting Data....') horizon_dates = horizon(data, forecast_horizon, freq, series_type) st.write(f'Total datapoints: {data.shape[0]}') data.interpolate(method = 'time', inplace = True) #fill missing values st.write('Checking for missing Dates....') if missing_dates(data) > 0: ...
def get_browser(): chrome_options = Options() chrome_options.add_argument('--headless') chrome_options.add_experimental_option('excludeSwitches', ['enable-logging']) return webdriver.Chrome(chrome_options=chrome_options) def isDone(text_urls, download_queue): return len(text_urls) == 0 and download_...
The code manages URL conversion tasks by processing URLs from a queue, converting them using a browser with retry logic, and updating status queues. It handles failures with retries, logs progress, and notifies a manager of state changes. The process continues until all tasks are done, ensuring efficient resource use w...
def run(url_manager, log_setting, pool_capacity, text_urlL, raw_urlQ, converting_urlQ, converted_urlQ, downloadQ, download_repo): logger = get_logger('UrlConverter', log_setting) browser = get_browser() while not isDone(text_urlL, downloadQ): if canContinue(raw_urlQ, downloadQ, converted_url...
def get_keystone(): return ks3client.Client(session=get_sess()) def get_var(varname): ''' MENGAMBIL VARENV DARI LUARM PYTHON ''' nf = open("rc.api3", "r") rc = nf.read() CMD = 'echo $(source ' + rc + '; echo $%s)' % varname p = subprocess.Popen(CMD, stdout=subprocess.PIPE, shell=True...
This code checks if a user has admin privileges in an OpenStack environment by querying Keystone for the user's role assignments. It retrieves the user's ID using OS_USERNAME, fetches their roles, and checks for a specific admin role ID. If found, it returns True; otherwise, False.
def is_admin(username): ks = get_keystone() userlogin_id = ks.users.list(name=get_var('OS_USERNAME')) userlogin_id = parsing(data=str(userlogin_id), var='id') # print('userlogin_id = ' + userlogin_id) role_assignments = ks.role_assignments.list(user=userlogin_id) is_admin = False if re.searc...
def get_keystone(): return ks3client.Client(session=get_sess()) def get_neutron(): return nt3client.Client(session=get_sess()) def parsing(data, var): if re.search(var, str(data)): out = data.strip().split(' ' + var + '=')[1] out = out.strip().split(',')[0] return out else: ...
This function lists OpenStack floating IPs with optional name filtering, retrieves associated project and network details, and prints formatted output including IP addresses, status, and metadata. It uses keystone and neutron clients, handles missing data gracefully, and applies color formatting for readability.
def floatingIPList(cari_name=''): print('\n') print(f.bold + fg.blue + '=====================' + f.reset) print(f.bold + fg.blue + 'List Floating IP' + f.reset) if cari_name != '': cari_name_ = fg.yellow + f.bold + '"' + cari_name + '"' + f.reset print('name = ' + cari_name_) print(...
def get_keystone(): return ks3client.Client(session=get_sess()) def get_var(varname): ''' MENGAMBIL VARENV DARI LUARM PYTHON ''' nf = open("rc.api3", "r") rc = nf.read() CMD = 'echo $(source ' + rc + '; echo $%s)' % varname p = subprocess.Popen(CMD, stdout=subprocess.PIPE, shell=True...
The code checks if a user is an admin by retrieving their Keystone user ID, listing their role assignments, and verifying the presence of a specific role ID ('19c6ed1d6fce4b38952193ab6b25dce9') in the assignments. It returns `True` if the role exists, indicating admin status.
def is_admin(username): ks = get_keystone() userlogin_id = ks.users.list(name=get_var('OS_USERNAME')) userlogin_id = parsing(data=str(userlogin_id), var='id') # print('userlogin_id = ' + userlogin_id) role_assignments = ks.role_assignments.list(user=userlogin_id) is_admin = False if re.searc...
def get_keystone(): return ks3client.Client(session=get_sess()) def get_neutron(): return nt3client.Client(session=get_sess()) def GetUserRCProjectID(): ks = get_keystone() pl = ks.projects.list(domain=get_var('OS_PROJECT_DOMAIN_NAME')) OS_USER_PROJECT_ID = '' for data in pl: # print(dat...
This function retrieves and lists subnet information from an OpenStack environment, optionally filtering by name or network ID. It formats output with headers, color coding, and structured data display when `printout=True`. If no filters are applied, it lists all subnets. When `printout=False`, it returns the count of ...
def subnetList(cari_name='', cari_network='', printout=True, header=True): if printout is True: if header is True: print('\n') print(f.bold + fg.blue + '=====================' + f.reset) print(f.bold + fg.blue + 'List Subnet.' + f.reset) if cari_name != '': ...
def get_keystone(): return ks3client.Client(session=get_sess()) def get_neutron(): return nt3client.Client(session=get_sess()) def GetUserRCProjectID(): ks = get_keystone() pl = ks.projects.list(domain=get_var('OS_PROJECT_DOMAIN_NAME')) OS_USER_PROJECT_ID = '' for data in pl: # print(dat...
The main task of the code is to list OpenStack routers with attributes (name, ID, external IP, network, project, status) using Keystone and Neutron APIs, applying optional name filters. It formats output with colored headers, highlights matching names, and displays detailed JSON data for matched routers.
def routerList(cari_name=''): print('\n') print(f.bold + fg.blue + '=====================' + f.reset) print(f.bold + fg.blue + 'List Router' + f.reset) if cari_name != '': cari_name_ = fg.yellow + f.bold + '"' + cari_name + '"' + f.reset print('name = ' + cari_name_) print(f.bold + ...
def get_keystone(): return ks3client.Client(session=get_sess()) def get_var(varname): ''' MENGAMBIL VARENV DARI LUARM PYTHON ''' nf = open("rc.api3", "r") rc = nf.read() CMD = 'echo $(source ' + rc + '; echo $%s)' % varname p = subprocess.Popen(CMD, stdout=subprocess.PIPE, shell=True...
The code lists users from an OpenStack keystone service, displaying their names, IDs, domains, projects, descriptions, and creators. It filters results by a search name if provided, uses color formatting for visual clarity, and handles admin vs. non-admin access to retrieve appropriate user data.
def userList(cari_name=''): print('\n') print(f.bold + fg.blue + '=====================' + f.reset) print(f.bold + fg.blue + 'List User' + f.reset) if cari_name != '': cari_name_ = fg.yellow + f.bold + '"' + cari_name + '"' + f.reset print('name = ' + cari_name_) print(f.bold + fg.bl...
def get_var(varname): ''' MENGAMBIL VARENV DARI LUARM PYTHON ''' nf = open("rc.api3", "r") rc = nf.read() CMD = 'echo $(source ' + rc + '; echo $%s)' % varname p = subprocess.Popen(CMD, stdout=subprocess.PIPE, shell=True, executable='/bin/bash') out_ = p.stdout.readlines()[0].strip()...
This function lists OpenStack projects, either filtered by domain or all projects, displaying details like name, ID, domain, description, and creator. It handles admin vs. non-admin users, retrieves project data via Keystone, formats output with colors and alignment, and prints the structured project list.
def projectList(domain=''): print('\n') print(f.bold + fg.blue + '=====================' + f.reset) print(f.bold + fg.blue + 'List Project' + f.reset) print(f.bold + fg.blue + '---------------------' + f.reset) print('PROJECT'.ljust(15, ' '), 'ID'.ljust(35, ' '), 'DOMAIN'.ljust(15, ' '), 'DESC.'.lju...
def get_var(varname): ''' MENGAMBIL VARENV DARI LUARM PYTHON ''' nf = open("rc.api3", "r") rc = nf.read() CMD = 'echo $(source ' + rc + '; echo $%s)' % varname p = subprocess.Popen(CMD, stdout=subprocess.PIPE, shell=True, executable='/bin/bash') out_ = p.stdout.readlines()[0].strip()...
The code lists OpenStack roles, displaying their names, IDs, and associated domains. If the user is an admin, it retrieves and displays roles across all domains; otherwise, it limits to the user's domain. The output uses colored formatting for clarity, with detailed role information printed in a structured table format...
def roleList(): print('\n') print(f.bold + fg.blue + '=====================' + f.reset) print(f.bold + fg.blue + 'List Role' + f.reset) print(f.bold + fg.blue + '---------------------' + f.reset) UserRC_domain_id = get_var('OS_PROJECT_DOMAIN_NAME') UserRC_username = get_var('OS_USERNAME') ks...
def get_nova(): return nv2client.Client(version='2.0', session=get_sess()) def get_var(varname): ''' MENGAMBIL VARENV DARI LUARM PYTHON ''' nf = open("rc.api3", "r") rc = nf.read() CMD = 'echo $(source ' + rc + '; echo $%s)' % varname p = subprocess.Popen(CMD, stdout=subprocess.PIPE,...
The function creates an OpenStack instance using parameters from a JSON string, including instance name, image, flavor, and network. It utilizes the Nova client to provision the server, assigns security groups and a key, and returns the instance ID if successful; otherwise, returns False on IndexError.
def createServer(json_str): # json_str = { # 'instance_name': '', # 'image': '', # 'flavor': '', # 'network': '' # } nv = get_nova() try: create_instance = nv.servers.create(name=json_str['instance_name'], image=json_str['image'], flavor=json_str['flavor'], nics=[...
def get_var(varname): ''' MENGAMBIL VARENV DARI LUARM PYTHON ''' nf = open("rc.api3", "r") rc = nf.read() CMD = 'echo $(source ' + rc + '; echo $%s)' % varname p = subprocess.Popen(CMD, stdout=subprocess.PIPE, shell=True, executable='/bin/bash') out_ = p.stdout.readlines()[0].strip()...
The code lists OpenStack users, filtering by name and domain based on admin status, and displays their details (name, ID, domain, project) in a formatted table with color highlighting.
def userList(name=''): print(f.bold + fg.blue + '=====================' + f.reset) print(f.bold + fg.blue + 'List User' + f.reset) print(f.bold + fg.blue + '---------------------' + f.reset) UserRC_domain_id = get_var('OS_PROJECT_DOMAIN_NAME') UserRC_username = get_var('OS_USERNAME') print('USER...
def get_var(varname): ''' MENGAMBIL VARENV DARI LUARM PYTHON ''' nf = open("rc.api3", "r") rc = nf.read() CMD = 'echo $(source ' + rc + '; echo $%s)' % varname p = subprocess.Popen(CMD, stdout=subprocess.PIPE, shell=True, executable='/bin/bash') out_ = p.stdout.readlines()[0].strip()...
This code lists OpenStack projects with their IDs and domains, filtering by domain if provided. It checks user admin status to determine project scope, formats output with headers, and prints project details in a structured table, using color for emphasis.
def projectList(domain=''): print(f.bold + fg.blue + '=====================' + f.reset) print(f.bold + fg.blue + 'List Project' + f.reset) print(f.bold + fg.blue + '---------------------' + f.reset) print('PROJECT'.ljust(15, ' '), 'ID'.ljust(35, ' '), 'DOMAIN'.ljust(35, ' ')) UserRC_username = get_v...
def get_var(varname): ''' MENGAMBIL VARENV DARI LUARM PYTHON ''' nf = open("rc.api3", "r") rc = nf.read() CMD = 'echo $(source ' + rc + '; echo $%s)' % varname p = subprocess.Popen(CMD, stdout=subprocess.PIPE, shell=True, executable='/bin/bash') out_ = p.stdout.readlines()[0].strip()...
The main task of the code is to list OpenStack roles with their IDs and associated domains, using color formatting for display. If the user is an admin, it lists all roles across all domains; otherwise, it lists roles specific to the user's domain. The output includes role names, IDs, and domain names, with structured ...
def roleList(): print(f.bold + fg.blue + '=====================' + f.reset) print(f.bold + fg.blue + 'List Role' + f.reset) print(f.bold + fg.blue + '---------------------' + f.reset) UserRC_domain_id = get_var('OS_PROJECT_DOMAIN_NAME') UserRC_username = get_var('OS_USERNAME') ks = get_keystone(...
def colorAlphaToString(self, colorAlpha): # print('colorAlphaToString received:') # print(colorAlpha) # colorStr = '#%02x%02x%02x' % color # print('colorStr = ' + colorStr) colorAlphaStr = str(colorAlpha[0]) + ',' + str(colorAlpha[1]) + ',' + str(colorAlpha[2]) + ',' + str(colorA...
The main task of the `readSettings` function is to **read and structure Blender's render and scene settings** into a nested dictionary (`settings`), differentiating between **Cycles** and **EEVEE** render engines. It captures extensive configuration details including render properties (sampling, light paths, performanc...
def readSettings(self, context, settings): print('Reading the settings...') # Add a file version to help protect against future changes to the file format settings['file_version'] = 1.0 # Are we using cycles or EEVEE? settings['render_props'] = {} settings['render_props'...
def Rules(self, iPos: Position, fPos: Position) -> int: # error checking if iPos.rank == fPos.rank and iPos.file == fPos.file: return 5 # attemting to move a piece to the same spot if self.grid[iPos.file][iPos.rank].color == self.grid[fPos.file][fPos.rank].color: return 6 # attemping to move...
The main task of the code is to validate and execute a chess piece move on a board, handling special cases like en passant, castling, and promotion. It checks move legality, updates the board state, and applies specific rules for each scenario, returning an error code if invalid or 0 on success.
def SmartMovePiece(self: Board, iPos: Position, fPos: Position, promoType: pieceType) -> int: # determine if move is legal errorcode = Rules(self, iPos, fPos) if errorcode != 0: return errorcode # error detected # en pesssanting scenario if CastleOrPromotionOrEnPessant(self, iPos, fPos) == 3...
def create_pairs (a): # Create local stores for use split_array = []; temp_array = []; for num, value in enumerate(a, start=1): temp_length = len(temp_array) if temp_length == 1: temp_array.append(value) split_array.append(temp_array) temp_array = [] elif len(split_array) * 2 == len(a) - 1: spli...
The function `merge_insertion_sort` sorts an array using a hybrid approach combining insertion sort and merge sort principles. It splits the array into pairs, sorts each pair, recursively sorts these pairs by their larger elements, and merges them into a final sorted sequence. If the array length is odd, it isolates th...
def merge_insertion_sort (A): # Print out Given Array, for clarity print("Starting Array:") print(A) # Determine if it's odd numbered... if so, take off a straggler hasStraggler = len(A) % 2 != 0 if hasStraggler: straggler = A.pop(len(A) -1) else: straggler = False # Then Split Array into Pai...
def stage(title, method="info"): """ Print stage title into log """ separator(method) getattr(logging, method)("### " + title) separator(method) def read_file(filename): """ Read text file and return its contents """ if not os.path.isfile(filename): fail("File not found: %s" % filename) ...
The main task of the code is to verify CodeChecker results by analyzing defect severities (e.g., CRITICAL, HIGH) from a parsed output file. It reads results, validates severity parameters, counts defects per severity, and fails if any disallowed severity-level defects are found, ensuring code quality compliance.
def check_results(): """ Check/verify CodeChecker results """ stage("CodeChecker result:") # Get results file and read it result_file = CODECHECKER_FILES + "/result.txt" logging.info("Find CodeChecker results in bazel-bin") logging.info(" all artifacts: %s/", CODECHECKER_FILES) logging....
def stage(title, method="info"): """ Print stage title into log """ separator(method) getattr(logging, method)("### " + title) separator(method) def execute(cmd, env=None, codes=None): """ Execute CodeChecker commands """ process = subprocess.Popen( cmd, env=env, shell=Tr...
The function `analyze()` executes the CodeChecker analysis tool to inspect code for defects. It sets environment variables, constructs a command with parameters like parallel jobs, skip files, compile commands, and output paths, then runs the analysis. It logs output, checks for failure indicators, and triggers an erro...
def analyze(): """ Run CodeChecker analyze command """ stage("CodeChecker analyze:") env = { "CC_ANALYZERS_FROM_PATH": "1", "PATH": "/bin:/usr/bin", } logging.debug("env: %s", str(env)) # FIXME: add analyze_extra_args? command = "%s analyze --jobs=%d --skip=%s %s --output=%s/...
def stage(title, method="info"): """ Print stage title into log """ separator(method) getattr(logging, method)("### " + title) separator(method) def execute(cmd, env=None, codes=None): """ Execute CodeChecker commands """ process = subprocess.Popen( cmd, env=env, shell=Tr...
The main task of the code is to execute the CodeChecker parse command to analyze code, then export the results into three formats: JSON (saved as result.json), HTML (saved as report/), and plain text (saved as result.txt), logging each step. The function orchestrates exporting analysis findings for different usage scen...
def parse(): """ Run CodeChecker parse commands """ stage("CodeChecker parse:") logging.info("CodeChecker parse -e json") codechecker_parse = CODECHECKER_PATH + " parse " + CODECHECKER_FILES + "/data " # Save results to JSON file command = codechecker_parse + "--export=json > " + CODECHECKER_FIL...
def stage(title, method="info"): """ Print stage title into log """ separator(method) getattr(logging, method)("### " + title) separator(method) def valid_parameter(parameter): """ Check if external parameter is defined and valid """ if parameter is None: return False elif parameter ...
The main task of the code is to execute the CodeChecker store command to upload analysis results to a specified online database. It validates the URL format, checks user permissions, constructs command parameters with dynamic tags, and executes the storage operation if all conditions are met, logging the process and ou...
def store(): """ Run CodeChecker store command """ stage("CodeChecker store:") username = getpass.getuser() logging.info(" URL: %s", str(STORE_URL)) logging.info("Valid users: %s", str(STORE_USERS)) logging.info(" Username: %s", username) logging.info(" Run name: %s", str(STORE_NA...
def prepare(): """ Prepare CodeChecker execution environment """ stage("CodeChecker files:") logging.info("Creating folder: %s", CODECHECKER_FILES) create_folder(CODECHECKER_FILES) def analyze(): """ Run CodeChecker analyze command """ stage("CodeChecker analyze:") env = { "CC_ANALYZ...
The code defines a function `run()` that executes the essential steps of the Bazel build process. It first prepares the build environment, analyzes the project structure, fixes output issues, and finally parses the results. These steps ensure a successful Bazel build by handling setup, validation, correction, and inter...
def run(): """ Perform all steps for "bazel build" phase """ prepare() analyze() fix_output() parse()
def setup(): """ Setup logging parameters for execution session """ if VERBOSITY == "INFO": log_level = logging.INFO elif VERBOSITY == "WARN": log_level = logging.WARN else: log_level = logging.DEBUG log_format = "[codechecker] %(levelname)5s: %(message)s" if log_file_na...
The main task of the code is to execute different modes ("Run" or "Test") based on the EXECUTION_MODE variable. It initializes setup and input data, then triggers either the run() or test() function accordingly. If the mode is invalid or an exception occurs, it logs the error and terminates with a failure message.
def main(): """ Main function """ setup() input_data() try: if EXECUTION_MODE == "Run": run() elif EXECUTION_MODE == "Test": test() else: fail("Wrong codechecker script mode: %s" % EXECUTION_MODE) except Exception as error: logging....
def input_nfa_process(self) -> None: processes = int(input('How many Processes in your nfa: ')) for process in range(processes): is_end = bool(int(input(f'Is q{process} final processing? (if yes put 1 if no put 0)'))) directions = int(input(f'How many Direction in your nfa q{proc...
The main task of the code is to convert a Non-Deterministic Finite Automaton (NFA) into a Deterministic Finite Automaton (DFA). It processes input NFA transitions, computes initial and next state movements, verifies DFA completeness, inserts missing states, and returns the final DFA transition matrix and state status m...
def main(self): self.input_nfa_process() self.get_q0_move() self.next_move() self.check_end_dfa() self.is_end() self.insert_none_dfa() return self.dfa_matrix, self.dfa_status_matrix
def handle_events(self): for action in self.event_handler.get_actions(): if action == Action.QUIT: self.handle_quit_game() elif action == Action.TOGGLE_PAUSE: self.toggle_pause() elif action in self.tetrimino_action_map: if acti...
This code runs a game loop that continuously handles events, updates the game state (if active and not paused), and renders the current game state. It maintains a consistent frame rate using pygame's clock, ensuring smooth gameplay while allowing for pausing and event processing.
def run(self) -> None: while self.running: self.handle_events() if not self.paused: if self.active_game: self.update_game_state() self.draw_game_state() pygame.time.Clock().tick(FPS)
def _test_connectivity(self, param): action_result = ActionResult() self.save_progress("Testing connectivity") ret_val = self._validate_connection(action_result) if phantom.is_fail(ret_val): return self.set_status_save_progress(phantom.APP_ERROR, "Connectivity test failed")...
The code defines a method `handle_action` that determines and executes the appropriate action based on the action identifier. It retrieves the action ID, checks its value, and calls corresponding private methods like `_test_connectivity`, `_create_ticket`, or `_update_ticket` to handle specific tasks. The method return...
def handle_action(self, param): action = self.get_action_identifier() ret_val = phantom.APP_SUCCESS if action == phantom.ACTION_ID_TEST_ASSET_CONNECTIVITY: ret_val = self._test_connectivity(param) elif action == self.ACTION_ID_CREATE_TICKET: ret_val = self._crea...
def best_approximate_match(self, image_a_source: np.ndarray, image_b_source: np.ndarray, level: int, pixel_q: tuple[int, int]) -> tuple[int, int]: """ It returns the coordinate of pixel p from image A that has t...
The function identifies the optimal pixel p in image A that matches pixel q in image B during synthesis. It computes an approximate match (p_app) and a coherence-based match (p_coh), then selects the better match by comparing their distances (d_app vs. d_coh) adjusted by pyramid level. If q is near image edges, it retu...
def best_match(self, image_a_source: np.ndarray, image_b_source: np.ndarray, source_s: np.ndarray, level: int, pixel_q: tuple[int, int]) -> tuple[int, int]: """ It finds the best match between pixel p from images A and A' and t...
def compute_gaussian_pyramids(self) -> None: """ Computes the Gaussian pyramids :return: None """ self.gaussian_pyramids_image_a_source.append(self.image_a_source) self.gaussian_pyramids_image_a_target.append(self.image_a_target) self.gaussian_pyramids_image_b_so...
The code synthesizes an image B' by learning the analogy between input images A and A' using Gaussian pyramids. It iteratively matches pixels across pyramid levels, transferring color values from A to B while preserving spatial relationships. The process involves grayscale conversion, multi-scale feature alignment, and...
def create_image_analogy(self) -> np.ndarray: """ It learns the analogy between A and A' and returns a synthesized image B' :return: The synthesized image """ self.compute_gaussian_pyramids() self.convert_images_to_gray_scale() for level in range(self.levels_gau...
def get_closest_node(self,lon, lat, from_node=0): # lon,lat = 31.347218, 30.058983 # 7154.87,8425.21 # 30.058983, 31.347218 # net = sumolib.net.readNet('myNet.net.xml') radius = 0.1 x, y = self.net.convertLonLat2XY(lon, lat) # x,y = 7154.87,842...
The code finds the shortest route from a starting location to a goal location using the A* algorithm, considering time constraints. It identifies the closest map nodes to the given coordinates, computes the optimal path, and returns navigational directions based on the calculated route.
def find_route(self,s_lat,s_lon, g_lat,g_lon,time): start_node = self.get_closest_node(s_lon, s_lat) goal_node = self.get_closest_node(g_lon, g_lat,from_node=1) shortest_path = self.a_star(start_node.getID() , goal_node.getID(),time) # print("Shortest path:", shortest_path) ret...
def getChatUnreadMessageCount(self, title): try: chat = self.getChat(title) count = 0 if self.isChatUnRead(title): count = chat.find_element_by_class_name( "_38M1B").get_attribute("aria-label").split(' ')[0] return int(count...
This code retrieves unread messages from a chat interface by first determining the unread count, opening the chat, parsing message elements, filtering duplicates, and returning the latest messages matching the unread count. It handles special message types, ensures uniqueness, and interacts with the web page using Sele...
def getUnreadMessages(self, title): unreadCount = self.getChatUnreadMessageCount(title) self.__openChat(title) unreadMessages = [] time.sleep(1) for i in self.driver.find_elements_by_css_selector( ".GDTQm.message-in.focusable-list-item"): data = self.g...
def reset(self): self.create_graph(self.graph_scheme) def breadth_first_search(self, src, target): pred = {src: None} path_s = [src] succ = {target: None} path_t = [target] while True: path = [] if len(path_s) <= len(path_t): for u...
This function computes the maximum flow from a source to a target node in a flow network using the Ford-Fulkerson method with BFS to find augmenting paths. It repeatedly identifies paths from source to target, augments flow along these paths, and accumulates the total flow until the specified cutoff is reached or no mo...
def max_flow(self, source, target, cutoff=float('inf')): self.reset() flow_value = 0 while flow_value < cutoff: v, pred, succ = self.breadth_first_search(source, target) if pred is None: break path = [v] u = v while u ...
def get_all_filenames(folder): file_list = [] for filename in os.listdir(folder): if 'abc' in filename: file_list.append("%s/%s" % (folder, filename)) return file_list def parse_file(filename, yes_to_all): lines_in_file = open(filename, 'r').readlines() song_head, song_body = fil...
The main task of the code is to convert ABC music notation files from a specified folder into a Folk-RNN-compatible format. It parses ABC files, tokenizes songs, filters duplicates, and writes processed data to an output file with optional metadata like titles, filenames, and token history tracking. The script uses com...
def main(): welcome_message = ''' #################################### # FolkRNN ABC parser # # Create a Folk-RNN file # # from a folder with ABC files # #################################### ''' print(welcome_message) parser = argparse.ArgumentParser() ...
def Create_InputsDict(self): """ Setup input of the form FORMAT InputsDict = {"KEYWORD": {"HELP":"Text to describe input", "optional":True/False, "vars": ...
The code reads a specified input file, processes its contents to generate input data structures (`InputsDict`), and initializes UI components (`searchctrl`, `propertygrid`) using the file's data. It handles file-opening errors with a try-except block, logging an error if the file cannot be accessed. The function sets u...
def read_filename(self, inputfilename): self.inputfilename = inputfilename print("Opening filename=", self.inputfilename) try: with open(inputfilename, 'r') as file: #Load new input file self.InputFileMod = swl.KeywordInputMod(inputfilename) ...
def InitUI(self): menubar = wx.MenuBar() fileMenu = wx.Menu() open = fileMenu.Append(wx.ID_OPEN, '&Open\tCtrl+O') save = fileMenu.Append(wx.ID_SAVE, '&Save\tCtrl+S') saveas = fileMenu.Append(wx.ID_SAVEAS, '&Save As...\tCtrl+Alt+S') setinitial = fileMenu.Append(wx.ID_...
(The main task of the code is to initialize a GUI application with tabs for molecular dynamics setup, run management, and result visualization using wxPython and matplotlib. It creates a window with a splitter layout for input controls and plots, loads input/restart files if provided, and sets up AUI notebook tabs for ...
def __init__(self, parent=None, inputfilename=None, restartfilename=None, executable="parallel_md.exe", width=800, height=600, title="Flowmol Input"): # begin wxGlade: MyFrame.__init__ wx.Frame.__init__(self, parent) self.width = width self.height = height self....
def _get_endpoint(entity: str, pipedrive_api_key: str, extra_params: Dict[str, Any] = None, munge_custom_fields: bool = True) -> Optional[Iterator[TDataItems]]: """ Generic method to retrieve endpoint data based on the required headers and params. Args: entity: the endpoint you want to call ...
This function generates DltResource objects for Pipedrive API endpoints, including entity fields, entities, activities, and transformer-based resources that reuse cached data. It ensures proper data dependency handling by ordering field resources before entities and using transformers like deals_participants and deals_...
def pipedrive_source(pipedrive_api_key: str = dlt.secrets.value) -> Sequence[DltResource]: """ Args: pipedrive_api_key: https://pipedrive.readme.io/docs/how-to-find-the-api-token Returns resources: activityFields dealFields deals deals_flow deals_participants ...
def _text_from_word_list(self,word_list): ''' Helper - copy from word list to a text string ''' text = '' for i in range(len(word_list)): text += word_list[i] if i<(len(word_list)-1): if word_list[i+1] != '.': text += ' ' return...
This method conditionally removes a selected word from a text if the resulting text is grammatically correct with high probability. It creates a modified word list without the selected word, checks grammaticality using a model, and retains the word if the grammar score is below 90%. If valid, it permanently deletes the...
def _drop_word(self): ''' Drop the selected word from a text if result will be grammatical ''' #Only proceed if words remain in list if len(self._word_list)==0: return #Build text without selected word drop_list = self._word_list.copy() drop_list.pop(self._wor...
def _embedding(self, text, openai=False): ''' Use LLM to return a vector encoding of text ''' if openai: return self._embedding_openai(text) else: return MODEL.encode(text) def _update_scores(self): ''' Calculate the game score ''' self._simple_score=((70-...
The main task of the code is to reset the environment by selecting a text passage (sequentially or randomly), initializing NLP processing, tokenization, and tracking variables for text simplification actions. It prepares the initial observation, scores, and agent state for a text simplification task, resetting counters...
def reset(self, sequential=False): super().reset() # Pick a sentence to simplify if sequential: try: self._start_text = copy.deepcopy(self.originals.iloc[self._item_number].original) #needs to be a copy self._item_number += 1 except: ...
def _drop_word(self): ''' Drop the selected word from a text if result will be grammatical ''' #Only proceed if words remain in list if len(self._word_list)==0: return #Build text without selected word drop_list = self._word_list.copy() drop_list.pop(self._wor...
This code processes an action in a text manipulation environment by updating the word cursor, applying transformations (e.g., dropping words, simplifying text), calculating rewards based on score changes, and returning the new observation, reward, termination status, and additional info. It handles four action types, t...
def step(self, action_code): action = self._action_to_keypress[action_code] terminate = False last_total_score = self._total_score if action == 'K': #'KEEP' - do nothing self._word_cursor += 1 cost = 0 elif action == 'D': #'DROP' - remove word ...
def create_presigned_url(bucket_name, object_name, expiration=3600): """Generate a presigned URL for accessing an S3 object Args: bucket_name: A string representing the name of the S3 bucket where the object is located. object_name: A string representing the key of the object to generate th...
The code performs inference on incoming data via a Flask server. It checks the request content type: if JSON, it processes the image reference, generates a pre-signed URL, downloads the image, and returns prediction results. For non-JSON types, it returns errors (400 for invalid JSON, 415 for unsupported formats). The ...
def inference(): """Performed an inference on incoming data. In this sample server, we take data as application/json, print it out to confirm that the server received it. """ # log content_type using logger logging.info(f"Flask request, {flask.request}") logging.info(f"content_type, {flask....
def parse_arguments(args=None): parser = ArgumentParser() parser.add_argument('--list', action='store_true', help='list the current display options') parser.add_argument('--set', help='set the current display settings') parser.add_argument('--target', help='specify the target terminal to interact with')...
The main task of the code is to handle command-line arguments for color-related operations. It parses input parameters and executes corresponding functions: listing colors, retrieving the current color, setting a default color, or applying a specified color. The function acts as a controller, routing user commands to a...
def main(): args = parse_arguments() if (args.list): colors_list() if (args.get): colors_get_current() if (args.default): colors_set_default() if (args.set): colors_set(args.set)
def read_data(filename): f = open(filename, 'r') p = re.compile(',') data = [] header = f.readline().strip() varnames = p.split(header) namehash = {} for l in f: example = [int(x) for x in p.split(l.strip())] x = example[0:-1] y = example[-1] data.append((x, y...
The code trains a logistic regression model using provided training data, saves the model parameters (weights and bias) to a file, and evaluates the model's accuracy on test data by predicting class probabilities and comparing them to true labels.
def main(argv): if (len(argv) != 5): print('Usage: lr.py <train> <test> <eta> <lambda> <model>') sys.exit(2) (train, varnames) = read_data(argv[0]) (test, testvarnames) = read_data(argv[1]) eta = float(argv[2]) lam = float(argv[3]) modelfile = argv[4] # Train model (w, b...
def registerInterfaces(self, intf: Union[Interface, Unit]): if hasattr(intf, "_interfaces") and intf._interfaces: parent = self._scope name = intf._name info = VcdVarScope(name, parent) self._scope = info for chIntf in intf._interfaces: ...
The function initializes signal handling for a unit by registering its interfaces, collecting new signals, recursively processing nested units, and temporarily updating the scope context to ensure proper signal registration and hierarchy management.
def initUnitSignals(self, unit): parentScope = self._scope self._scope = self.registerInterfaces(unit) for s in unit._ctx.signals: if s not in self.collectedWave: self.registerSignal(s) for u in unit._units: self.initUnitSignals(u) self._...