dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def turn_motors_on(self) -> None: """ This method turns the robot motors on. """ self.request_mastership() self.motors_on() self.release_mastership() def start_RAPID(self, pp_to_reset: bool) -> None: """ The method resets the program pointer if necessary a...
The method initializes the robot, starts the RAPID program with an option to reset its pointer, waits for task completion via a synchronization variable, then stops the program and restores settings, ensuring coordinated execution between Python and RAPID.
def complete_instruction( self, reset_pp: bool = False, var: str = "ready_flag" ) -> None: """ This method sets up the robot, starts the RAPID program with a flag specifying if the program pointer needs to be reset and then it waits for the task completion. Finally, it stops ...
def helper_yn(question): choice = '' while choice.lower() not in ('y', 'n'): choice = input(question) if choice.lower() in ('y', 'n'): return choice #break else: print("") time.sleep(a) print("I'm sorry, I didn't understand tha...
The function `get_eliminated()` collects letters the user has eliminated from a word. It prompts the user to input these letters, validates the input, stores them in a list, and passes them to `get_known()` for further processing. If no letters are eliminated, it skips to `get_known()` directly.
def get_eliminated(): eliminated = [] print("First, let's address any letters you've eliminated.") print("") time.sleep(a) q_eliminated = "Have you eliminated any letters from the word? Y/N: " any_eliminated = helper_yn(q_eliminated) if any_eliminated.lower() == "y": print("...
def get_existing_listing(self, address: str) -> Optional[str]: """Check that listing exists in database. Assumes 'Address' is unique.""" response = requests.post( f"{self.database_url}/query", data=json.dumps( { "filter": { ...
The main task of the code is to add a new listing to the database or update an existing one if it already exists. It checks for an existing listing using the address, updates it if found, or creates a new entry otherwise, logging relevant information during the process.
def add_listing(self, listing: Listing): """ Adds a listing to the database. If the listing exists, updates that listing """ existing_listing = self.get_existing_listing(listing.features["address"]) if existing_listing: logger.info(f"Found existing listing with page i...
def reverseInOrder(root, player_list): if root: reverseInOrder(root.right, player_list) for i in root.players: player_list.append(i) reverseInOrder(root.left, player_list) return player_list def meanScore(player): sum = 0 for i in player.scores: sum+=i ret...
The main task of the code is to simulate a game round by updating player scores with random values, calculating their mean scores, and restructuring an AVL tree. It increments the round count, reverses the player order, assigns scores, and rebuilds the AVL tree by inserting players sequentially, effectively resetting t...
def round(self): ''' Here we simulate a game, we take which node by deleteind it, put it temporarily in a list, meanwhile we give to each player a score and we do the mean of it Input: - Output: - ''' players_list = [] #there we are going to put the players while...
def insertAVL(root, key): if not root: node = Node() node.players.append(key) return node elif key.score == root.players[0].score: root.players.append(key) return root elif key.score < root.players[0].score: root.left = insertAVL(root.left, key) else: ...
The main task of the code is to initialize a game database with 100 players, each starting with a score of 0, by inserting them into an AVL tree. It prints setup confirmation, pauses, and then triggers the competition and podium functions to proceed with the game.
def start(self): ''' This function is going to start our game by setting up the database with 100 players which initailly all of them are going to have score 0 Input: - Output: - ''' print("Now we are initialazing the database with 100 players. \nAll of them have ...
def assert_negative(data: int): """ General method to prevent negative values of integers. """ if data < 0: raise ValueError("Currently we do not support negative data values.") def assert_bits(data: int, num_bits: int): """ General method to prevent invalid number of bits. """ i...
The function converts an integer into a binary string of specified length, then constructs a vector of size 2^num_qubits where each element is (-1) raised to the corresponding bit value. It maps each bit of the binary representation to the vector's elements, returning the resulting array.
def get_vector_from_int(data: int, num_qubits: int) -> np.ndarray: """ This method returns the vector where each element is (-1)^b_i where b_i is the bit value at index i. Args: data: `int` representing data value (correspponding to input or weight vector) num_qubits: `int` represen...
def predict_img_seq(model, imgpath, respath): if not os.path.exists(respath): os.mkdir(respath) valid_transform = transforms.Compose([ transforms.Resize([resize_height, resize_width]), transforms.ToTensor() ]) files = os.listdir(imgpath) start = time.time() area_seq = []...
The main task of the code is to predict heart rate metrics from video data using a pre-trained model. It processes input video files, generates peak sequences and area data, calculates heart rate values, and saves results in a CSV file. The code handles both directory-based and TIFF image data, converting TIFFs to imag...
def main(): print("predict start now") modelpath = "./bestmodel_aug_100.pkl" data_path = "./video_data/2021010222" res_path = "./video_result" if not os.path.exists(res_path): os.mkdir(res_path) csv_name = os.path.join(res_path, "result.csv") csv_file = open(csv_name, 'w', encoding...
def _create_cells(self): cells = [] for r in range(self._num_rows): row = [] for c in range(self._num_cols): x1 = self._tl.x + self._cell_size_x * c y1 = self._tl.y + self._cell_size_y * r x2 = x1 + self._cell_size_x ...
This code initializes a maze generator by setting up grid parameters, creating cells, breaking walls recursively to form paths, and rendering the maze. It uses a seed for reproducibility, sets entrance/exit points, and draws the maze if a window is provided. The solve() method is called to attempt solving the generated...
def __init__(self, p1, num_rows, num_cols, cell_size_x, cell_size_y, window=None, seed=None): self._tl = p1 # Position of the top left point of the maze self._num_rows = num_rows self._num_cols = num_cols self._cell_size_x = cell_size_x self._cell_size_y = cell_size_y sel...
def semigradient_eps_greedy(env, s, w, eps): if np.random.random() > eps: # if random value > eps => Exploit the knowledge q_list = [] # create list of q-values for a in range(len(env.direction.keys())): # for each action calculate q_hat value q_value = q_hat(s, a, w) ...
The main task of the code is to implement the **Semi-Gradient SARSA algorithm** for training a reinforcement learning agent in a given environment. It initializes a weight vector, iterates over multiple episodes, and updates the weights using the SARSA update rule with an epsilon-greedy policy for action selection. The...
def SemiGradientSARSA(env, eps, alpha, E): w = np.full((8,), fill_value=float(-100)) # initialize weight vector # w = np.zeros((8,)) gamma = 0.9 # gamma value episode = 0 # initialize episode count steps_dict = {} # dictionary to store number of steps taken...
def eps_greedy(maze, s, w, eps): if np.random.random() > eps: # if random value > eps => Exploit the knowledge q_list = [] # create list of q-values for a in range(len(maze.direction.keys())): # for each action calculate q_hat value q_value = q_hat(s, a, w) q_list.a...
The code implements the SARSA algorithm for training an agent to navigate a maze using linear function approximation. It initializes a weight vector, runs for E episodes, and updates weights via TD learning with epsilon-greedy action selection. Each episode tracks steps taken and stores weight vectors, aiming to optimi...
def Sarsa(maze, eps, alpha, E): w = np.zeros((8,)) # initialize weight vector gamma = 0.9 # gamma value episode = 0 # initialize episode count steps_dict = {} # dictionary to store number of steps taken for each episode weights_dict = {} # dictionary to sto...
def _save_model(self, dst_dir, global_step = None): saver = tf.train.Saver() return saver.save(self.sess, os.path.join(dst_dir, 'model.ckpt'), global_step = global_step) def _plot(self, x, y, prediction, save = False, id = 0, dst_dir = None): x = x[0, ..., 0] y = y[0, ..., 0] pre...
The code trains a machine learning model by iterating over epochs, running sessions to compute training data, accumulating costs, and validating performance. It saves model checkpoints every 10 epochs, generates training/validation plots, and implements early stopping if validation error changes minimally for a specifi...
def train(self, dst_dir, model_dst_dir, training_plot_dst_dir, validation_plot_dst_dir, early_stop_epochs = 20): i = 0 samples = 0 epoch_cost = 0 lowest_validation_cost = np.inf early_stop_counter = 0 while True: if self.state['epoch'] >= self._num_epochs: ...
def make_volume_int(data): new_data = [] for note in data: note[3] = min(max(int(float(note[3]) * 100 + 0.5), 1), 100) new_data.append(note) return new_data def get_smart_note_placement(data): all_layers = get_all_layer_counts(data) layers = get_best_layers_with_preference_algorithm(...
This function converts musical data into the .nbs file format used by Minecraft Note Block Studio. It processes input data to adjust tempo, organize notes into layers, and writes structured metadata and note sequences to a file, ensuring compatibility with the ONBS format specifications.
def convert_to_nbs_file(data, metronome, is_original_order, filename, speed_fine_tune): metronome = noteblock_music_utility.get_metronome_info(data, metronome, False) tempo = int(160 * speed_fine_tune / metronome + 0.5) * 25 #rounding to multiplicate of 25 because ONBS can't be more precise and we don't tr...
def setup(): """Generates the Cryptosystem Parameters.""" G = EcGroup(nid=713) g = G.hash_to_point(b"g") h = G.hash_to_point(b"h") o = G.order() return (G, g, h, o) def keyGen(params): """ Generate a private / public key pair """ (G, g, h, o) = params priv = o.random() pub = pri...
This function tests the encryption and decryption process by encrypting a known string with generated keys, then decrypting it to verify it matches the original, ensuring the cryptographic functions work correctly.
def test_encrypt_decrip(): initial_string = 'supercalifragilisticexpialidocious' params = setup() keys = keyGen(params) cipher = encrypt_string(params, keys[1], initial_string) deciphered_text = decrypt_cipher(params, keys[0], cipher) assert initial_string == deciphered_text
def rectifying_affine_transforms(rpc1, rpc2, aoi, z=0, register_ground=True): """ Compute two affine transforms that rectify two images over a given AOI. Args: rpc1, rpc2 (rpc_model.RPCModel): two RPC camera models aoi (geojson.Polygon): area of interest Return: S1, S2 (2D arra...
The code rectifies two satellite images (file1, file2) with respect to a given area of interest (AOI), aligning them using RPC (Rational Polynomial Coefficients) and SIFT keypoint matching. It computes affine transformation matrices (S1, S2) for rectification, estimates horizontal disparity range (disp_min, disp_max), ...
def rectify_aoi(file1, file2, aoi, z=None, correct_pointing=True, register_ground=True, debug=False): """ Args: file1, file2 (strings): file paths or urls of two satellite images aoi (geojson.Polygon): area of interest z (float, optional): base altitude with respect to WG...
def _GrassDemFillDirTiles(self): ''' ''' srcComp = self.pp.srcCompL[0] dstComp = self.pp.dstCompL[0] if self.pp.process.parameters.asscript: today = mj_dt.Today() scriptFP = os.path.join('/Volumes',self.pp.dstPa...
The main task of the code is to initialize an object with provided parameters, configure verbosity settings, and route execution to specific GrassDEM processing methods based on the `processid` attribute. It directs the process to either `_GrassDemFillDirTiles`, `_GrassDemHydroDemTiles`, or `_GrassDemReInterpolateTiles...
def __init__(self, pp, session): ''' ''' self.session = session self.pp = pp self.verbose = self.pp.process.verbose self.session._SetVerbosity(self.verbose) # Direct to subprocess if self.pp.pro...
def addVegetableButtons(self, master): i=0 j=0 conn = sqlite3.connect(dbPath) cursor = conn.cursor() cursor.execute("""CREATE TABLE IF NOT EXISTS """+table1+""" (inventoryId TEXT, inventoryName TEXT, inventoryLink TEXT)""") cursor.execute("SELECT * FROM "+table1) ...
This code initializes a GUI frame for an inventory system, setting up navigation buttons, tabs for categorizing items (vegetables, meat, dairy), and scrollable sections to display inventory data. It configures the layout, integrates icons, and prepares to load item buttons dynamically. The "Continue" button transitions...
def __init__(self, master): ctk.CTkFrame.__init__(self, master) self.pack_propagate(0) self.configure(width=480, height=800, fg_color="black") self.inventoryDict = dict() self.vegetableButtonList =[] self.meatButtonList =[] self.dairyButtonList =[] b...
def count(self, value: bool) -> int: """Number of values in the BitArray of the given value. :param value: Value to count. """ assert isinstance(value, bool), check() # ---------- # Relies on padded values being False. count = sum(bit_count(d) for d in self._data...
The main task of the code is to return a random index of a specified boolean value within a BitArray. It first checks if the value exists, raises an error if absent, returns the sole index if unique, or selects a random occurrence from multiple matches using a provided random generator.
def random_index(self, value: bool, random: Random) -> int: """Return the index of any random value within the BitArray. :param value: Value to find. :param random: Random generator. """ assert isinstance(value, bool), check() assert isinstance(random, Random), check() ...
def EvalFunc(board: chess.Board, parentHash): curHash = Hash.getHash(board, parentHash) # get hash value of current board cachedVal = Hash.hasHash(curHash) # see if board is in the hash table global hit, miss if cachedVal is not None: # if board is in hash table hit = hit + 1 # update hits ...
The code implements the Minimax algorithm with alpha-beta pruning and memoization to evaluate board states in a game, recursively exploring possible moves to determine the optimal strategy. It caches evaluated board positions to avoid redundant computations, improving efficiency by pruning branches where the current pa...
def MiniMax(depth, isMax, board, alpha, beta, prevHash): global seen, hit seen += 1 # debugging - increase number of seen boards if depth == 0: # if search depth is reached return EvalFunc(board, prevHash) # return the value of the current board prevHash = Hash.getHash(board, prevHash) # g...
def GetOrderedMoves(board: chess.Board): def order(move): # returns estimate for move return GetEstimate(board, move) # sorts the legal moves by order given above, reverses so higher values are first moves = sorted(board.legal_moves, key=order, reverse=True) return moves def MiniMax(depth, isM...
The `MiniMaxRoot` function implements a minimax algorithm with alpha-beta pruning for a board game (likely chess). It evaluates all legal moves, recursively computes their values using `MiniMax`, and tracks the best moves based on alpha/beta bounds. If multiple moves yield the same evaluation, it selects one randomly. ...
def MiniMaxRoot(board, depth): global seen isMax = board.turn # white maximizing, black minimizing alpha = -math.inf # initialize alpha and beta beta = math.inf possible = [] # create empty list of possible moves hashVal = Hash.getHash(board) # get the hash value for this board moves = G...
def groupedGraphModification(self, title, disableUpdates=True): """ Get a GroupedGraphModification for this Graph. Args: title (str): the title of the macro command disableUpdates (bool): whether to disable graph updates Returns: GroupedGraphModification: th...
This function duplicates a specified node and all subsequent nodes in a graph, creating a mapping from original nodes to their duplicates. It preserves edge connections by recreating links between duplicated nodes and their corresponding sources, ensuring the graph structure remains consistent.
def duplicateNodesFromNode(self, fromNode): """ Duplicate 'fromNode' and all the following nodes towards graph's leaves. Args: fromNode (Node): the node to start the duplication from Returns: {Nodes: Node}: the source->duplicate nodes map """ src...
def _gen_answers(self, value): """Return Dictionary with Answers if value = 0, Points if value = 1""" _dict, x = {},0 while True: if self.trivia_dicts[value].get(f"question_{x}", False): _dict[f"question{x}"] = self.trivia_dicts[value][f"question_{x}"] ...
The code initializes a trivia drawing application by loading CSV data, generating answer keys and scoring entries, creating a drawing list, and launching a menu for data confirmation and drawing. It sets up game components like trivia questions, scoring, and entry management to facilitate the drawing process.
def __init__(self): """Initialize Trivia Drawing Class""" self.settings = Settings() self.trivia_dicts = mf.load_csv(self.settings.csvfilename) # Make Answer Key self.answers = self._gen_answers(0) self.points = self._gen_answers(1) # Make list of Entry Classes ...
def setRandomEnvironmentMagnitude(self): # self.TaskEnv = self.Environment[env] print(self.TaskEnv) min = self.TaskEnv['min_magnitude'] max = self.TaskEnv['max_magnitude'] self.TaskEnv['magnitude'] = random.uniform(min,max) def sampleAndEvaluateParticles(self): sampleInd ...
The main task of the code is to execute a particle filtering algorithm iteratively. It samples and evaluates particles, updates their weights based on performance, checks termination conditions, and optionally renders results in 3D. The loop continues until the end criteria are met, adjusting particles' weights to appr...
def runParticleFiltering(self): while not self.finished: self.setRandomEnvironmentMagnitude() self.sampleAndEvaluateParticles() self.calculateAverageParticlePerformance() self.updateParticleWeights() self.checkEndCriteria() if self.re...
def initilizeParticles(self): self.particles = [] self.performances = [] self.avgPerformances = [] self.weights = [] self.totalPerformance = 0 self.numberRuns = 0 self.clusterPoints = [] startPerf = self.CPFConfig['StartingPerformance'] numParti...
The main task of the code is to execute a particle filtering process across multiple enabled environments. It initializes particles, sets the environment task, runs particle filtering, calculates clusters and convex hulls, and finally returns a combined hull as the controller parameter set for each environment.
def run(self): print("CPF running") for env in self.Environment: enabled = self.Environment[env]['enabled'] == "True" if enabled: self.initilizeParticles() if self.render: self.render3D() self.setTaskEnv(env)...
def SQL(self): try: mydb = sql.connect( host = "localhost", user = "root", password = "", database = "ip_calc" ) print("Terkoneksi dengan MySQL!") return mydb except sql.Error: QMe...
This code creates a GUI application for managing student data and calculating index prestasi (GPA). It sets up input fields for student details, buttons to add/modify/delete records, and tables to display student lists, course grades, and GPA results. The interface uses PyQt with layouts, widgets, and database integrat...
def __init__(self): super().__init__() self.setWindowTitle("An Index Calculating #6") self.setGeometry(200, 200, 800, 600) self.mydb = self.SQL() #Mengatur Semua Widget berdasarkan GridLayout dan set Central Widget central_widget = QWidget() self.setCentralWidge...
def root(hrefAddition): tm = datetimeToStr(datetime.datetime.fromtimestamp(time.time())) return { "href": "{}"+hrefAddition, "getlastmodified": tm, "getetag": hrefAddition, "permissions": "RDNVCK", "id": hrefAddition, "size": 0, ...
The function `getProps` routes requests based on the provided `path` by returning different components: `root` for "/", `search` for "/Search", `searchMenu` for paths starting with "/Search/", and printing the path for other cases. It uses `hrefAddition` to modify hrefs when returning components, defaulting to an empty...
def getProps(self, path, hrefAddition = None): if len(path) == 0: path = "/" if path == "/": return root(hrefAddition if hrefAddition is not None else "") elif path == "/Search": return search(hrefAddition if hrefAddition is not None else "") elif path.startswith...
def generate(self, node): (wide, tall) = node.getSize() if (node.dir): # if the node im looking at is to be split horizontally line = int(random.randrange(0, wide) * 0.4 + wide * 0.3) # the line that will be used to split the cell left = Node.Node(node.tl, Point(node.tl.x + li...
The code generates a map of interconnected rooms, initializes an adjacency matrix, establishes predefined connections, assigns spawn points, keys, and gold rooms, creates random links, calculates distances from the spawn, and visualizes rooms with their distances. It structures a game environment with specific room typ...
def makeMap(self): self.generate(self.head) self.makeRoomList(self.head) self.rooms = self.head.childRooms numNodes = len(self.rooms) self.adjMatrix = np.zeros((numNodes,numNodes)) self.connectRooms(self.head.left.left, self.head.left.right, 1) self.connectRoo...
def unzip_stream(event): input_in_base64 = base64.b64decode(event['awslogs']['data']) #input_in_base64 = base64.b64decode(event) file_content = gzip.decompress(input_in_base64) return file_content def transform(logs_data): logs = json.loads(logs_data)['logEvents'] undesired_strings = ['DROP TA...
The main task of the code is to process incoming event data by unzipping it, transforming the content, extracting query statistics, and pushing these statistics to a database endpoint. The function returns a 200 OK response with a success message upon completion, or logs errors if exceptions occur during execution.
def lambda_handler(event, context): try: data = unzip_stream(event) response = transform(data) query_stats_tuple_list = get_query_stats_tuple_list_against(response) dump_query_stats_to("<db-endpoint>", query_stats_tuple_list) print("Data Pushed") return { ...
def load_image(self, path): return cv.imread(path) def find_img_onscreen(self, img, one=True): imga = img imgb = self.capture_screen() res = self.find_imga_in_imgb(imga, imgb, one) return res def click_on_last(self, rel="mid", t="left", times=1): self.click(self.last_x, self.last_y, rel, t, times)
The code loads an image from the specified path, searches for its occurrence on the screen, and if detected, performs a click action on the last found location. Its main task is to locate and interact with a specific image on the screen.
def findnclick_on(self, path): img = self.load_image(path) res = self.find_img_onscreen(img) if res: self.click_on_last()
def _create_placeholder(self): self.user_ph = tf.placeholder(tf.int32, [None], name="user") self.item_seq_ph = tf.placeholder(tf.int32, [None, self.seq_L], name="item_seq") self.item_pos_ph = tf.placeholder(tf.int32, [None, self.seq_T], name="item_pos") self.item_neg_ph = tf.placeholder(...
The main task of the code is to construct a computational graph for a machine learning model by initializing placeholders for input data, creating variables for model parameters, defining a loss function to measure prediction errors, and setting up an optimizer to minimize the loss during training.
def build_graph(self): self._create_placeholder() self._create_variable() self._create_loss() self._create_optimizer()
def full_date_to_short(full_date_str): """Converts a date string of the form yyyy-mm-dd to the form yymmdd.""" return full_date_str[2:].replace('-', '') def dst_conversion(date_str, event_time, timezone_conversion): """Returns an updated utc to local conversion number depending on the given date and time.""...
This function converts a detector's date and event time from UTC to local time by adjusting for timezone differences and daylight savings time (DST). It handles date rollover scenarios where the event time crosses midnight, either advancing or retreating the date as needed, then returns the adjusted local date and time...
def convert_to_local(full_date_str, event_time, timezone_conversion, is_dst): """Converts the detector date and event time to what they would actually be in local time.""" date_str = full_date_to_short(full_date_str) # Corrects the UTC conversion if we're in daylight savings time if is_dst: tim...
def is_valid_date(full_date_str): if len(full_date_str) != 10: return False valid = (full_date_str[0:4].isdigit() and full_date_str[5:7].isdigit() and full_date_str[8:].isdigit() and full_date_str[4] == '-' and full_date_str[7] == '-') return vali...
The function retrieves weather conditions at a specific event time by scraping data from Weather Underground. It adjusts for timezone and daylight savings, finds the closest recorded weather data, and evaluates conditions (e.g., rain, thunderstorms) to return a severity status code or descriptive string. If data is una...
def get_weather(full_date_str, event_time, station, timezone_conversion=0, is_dst=False, return_string=False): """Scrapes weather underground and returns the weather at the approximate time of an event. Parameters ---------- full_date_str : str The date to scrape weather for in the format yyyy-...
def get_path_by_key(dict_data, keyname,convert=False): all_path = list() routine_list = list() generate_dict_path("", dict_data, routine_list) for routine in routine_list: path_list = routine.split('/')[1:] if keyname in path_list: if check_list_key_illegal(path_list[-1]): ...
The function retrieves all values associated with a specified key in a nested dictionary structure by traversing paths obtained from `get_path_by_key`. It processes each path, handles both string and integer key access, and returns a list of dictionaries containing unique paths and corresponding values. If `convert=Tru...
def get_all_by_key(dict_data, keyname,convert=False): result_list = list() routine_list = get_path_by_key(dict_data, keyname) cache_last = [] for routine in routine_list: path_list = routine.split("/")[1:] dst_val = dict_data.copy() cache_routine = [''] for path in path_l...
def get_value_by_key(dict_data, keyname): result_list = list() routine_list = get_path_by_key(dict_data, keyname) for routine in routine_list: path_list = routine.split("/")[1:] dst_val = dict_data.copy() for path in path_list: if check_list_key_illegal(path): ...
The function searches for occurrences of a string in a dictionary's keys and values, aggregates all matching results, and returns a list of unique elements. If 'convert' is True, it transforms the elements using a path conversion function before deduplication.
def search_all_by_str(dict_data,search_str,convert=False): key_result = get_value_by_key(dict_data,search_str) value_result = get_key_by_value(dict_data,search_str) value_in_result = search_key_in_value(dict_data,search_str) combine_list = [element for i in [key_result,value_result,value_in_result] for ...
def create_options_menu(self): # create a menu bar menu_bar = tk.Menu(self.root) # create an options menu options_menu = tk.Menu(menu_bar, tearoff=0) # add a command to the options menu to open a panel for getting deals history options_menu.add_command( labe...
The code initializes a GUI application for visualizing trading data using MT5. It sets up tabs for different profit metrics, date selectors, a plot button, and a treeview for data display. The interface includes a notebook with multiple tabs, each linked to specific plots, and prepares components for filtering and disp...
def __init__(self, root: tk.Tk, mt5: MT5): self.root = root # the root window of the GUI self.mt5 = mt5 # the MT5 object for accessing the data self.tabs_list = [ "Sum Profit", "Mean Profit", "Reached Profit Goal", "Profit with Goal Status", ...
def move(self, delta_x): if not self.gameover: new_x = self.stone_x + delta_x if new_x < 0: new_x = 0 if new_x > COLS - len(self.stone[0]): new_x = COLS - len(self.stone[0]) if not check_collision(self.board, self.stone, (new_x, self.stone_y)): self.stone_x = new_x def center_msg(self, msg): ...
This code runs a Tetris-like game loop, handling user inputs (arrow keys, space, etc.) to control piece movement and rotation, rendering the game board, score, and next piece. It includes AI-related displays for heuristic evaluations if enabled, updates the screen at a fixed FPS, and processes game events like dropping...
def run(self): key_actions = { 'ESCAPE': sys.exit, 'LEFT': lambda: self.move(-1), 'RIGHT': lambda: self.move(+1), 'DOWN': self.drop, 'UP': self.rotate_stone, 'SPACE': self.start_game, 'RETURN': self.insta_drop, 'p': self.ai_toggle_instant_play, } clock = pygame.time.Clock() while True...
def estimate_frames(self): return math.ceil(self.get_svg_height() / self.advance_px) + 1 def get_frame_rect(self, frame_no): """Calculate the rectangle for the given frame number.""" return self.RECT.shift_down(frame_no * self.advance_px) def export_area(rect, source, png): x1, y1 = rect.top...
The main task of the code is to generate a cached image of the entire content by exporting a PNG file covering all frames, then return either the file path (for PNG caching) or the image data in memory (for MEMORY caching), ensuring full scrollable content is preserved without rounding errors.
def cache(self, tmpdir): # we have to cache the full image + some extra # to fully scroll away the contents. n_frames = self.estimate_frames() last_rect = self.get_frame_rect(n_frames - 1) # 0 indexing full_height = last_rect.y2 + 1 # to prevent any rounding errors full...
def validate_input(self): assert self.svg.exists() def create_outpath_if_required(self): if not self.outpath.exists(): os.makedirs(self.outpath.resolve()) def cache(self, tmpdir): # we have to cache the full image + some extra # to fully scroll away the contents. n_fr...
The code renders animated frames from an SVG source, exporting each frame as a PNG file. It validates input, manages caching, creates output directories, estimates total frames, and iteratively exports each frame with progress tracking.
def render(self): self.validate_input() self.create_outpath_if_required() source = self.cache(tempfile.TemporaryDirectory()) if self.caching else self.svg estimated_frames = self.estimate_frames() for current_frame in range(estimated_frames): print(f"Rendering Frame...
def getValidity(self): # print("Getting Validity") return len(self.pm0_1)>=1; def getAverageAll(self): if(len(self.pc0_1)>0): self.pc0_1Avg = statistics.mean(self.pc0_1) self.pc0_3Avg = statistics.mean(self.pc0_3) self.pc0_5Avg = statistics...
The main task of the code is to update the object's state when valid by calculating averages, processing time data, generating a CSV file, and clearing all data. It checks validity first, executes data processing steps if valid, and always ends by clearing data, while a commented-out line suggests a potential state tog...
def changeStateV2(self): if self.getValidity(): # print("Is Valid") self.getAverageAll() self.getTimeV2() self.doCSV() # self.evenState = not(self.evenState) self.clearAll()
def superReader(nodeID,sensorID): if sensorID == "BME280": floatSum = 3 elif sensorID == "BME680": floatSum = 4 elif sensorID == "GPGGALR": floatSum = 6 elif sensorID == "WIMDA": floatSum = 12 elif sensorID == "YXXDR": floatSum = 4 e...
The function prepares and processes climate data for a specific node by merging sensor data (climateSensor, WIMDA, YXXDR, GPGGALR), cropping GPS coordinates to a defined region, removing GPS columns, filtering by a start date, and saving intermediate/results as pickle files for further analysis.
def climateDataPrep(nodeData,nodeID,climateSensor,WIMDA,YXXDR,mergedPklsFolder): dataCropDate = datetime.datetime.strptime(nodeData['climateSensorBegin'], '%Y-%m-%d') print("Reading Data for Node: " + nodeID) GPGGALR = superReader(nodeID,"GPGGALR") climateSensor = superReader(nodeID,climateSens...
def getDataSuperReader(nodeID,sensorID,beginDate): print("Reading Data for Node : " + nodeID) print("Sensor ID : " + sensorID) print("Begin Date : " + beginDate) startDate = datetime.datetime.strptime(beginDate, '%Y-%m-%d') mintsData = superReaderV...
This function prepares and processes climate data by merging sensor data (climate, GPS) with external datasets (WIMDA, YXXDR), crops GPS coordinates within specified bounds, and saves processed data as pickle files. It handles empty data cases by logging errors.
def climateDataPrepV2(nodeData,nodeID,WIMDA,YXXDR): climateData = getDataSuperReader(nodeID,nodeData['climateSensor'],nodeData['climateSensorBegin']) gpsData = getDataSuperReader(nodeID,nodeData['gpsSensor'],nodeData['gpsSensorBegin']) mintsData = merger([climateData, WIMDA,YXXDR, gpsData]) if l...
def read_from_scene(self, scene_filename): """Reads a scene from a csv file into a list of event commands.""" # Clear the old event script if self.current_events_script: self.current_events_script.clear() unparsed_event_list = [] # Open the scene file and write it i...
The method determines the next event by checking the current event's `next_ID`. If it points to a "scene", it loads the corresponding CSV file. If `next_ID` is "return", it reverts to the last marked event. Otherwise, it retrieves the event directly using the `next_ID` value.
def get_next_event(self): """Reads the next event from the current event and loads it.""" if "scene" in self.current_event.commands: self.read_from_scene("scenes/" + self.current_event.next_ID + ".csv") elif self.current_event.next_ID == "return": self.return_to_last_mark...
def handleUniqueIDRequest(self, request, conn, addr): print("Creating unique ID....") # Get response. Set question set, game_id, and name. response = self.gm.getUniqueID() question_set = self.gm.getQuestions(5) game_id = response['data'][0]['uniqueID'] name = request['dat...
This code processes incoming requests by routing them to specific handler methods based on their type, such as handling unique IDs, question sets, join requests, chat messages, start commands, answer checks, and score retrieval. It delegates each request type to the corresponding method for further processing.
def processRequest(self, request, conn, addr): if request['type'] == "uniqueID": self.handleUniqueIDRequest(request, conn, addr) elif request['type'] == "question_set": self.handleQuestionSetRequest(request, conn) elif request['type'] == "join_request": self.h...
def getQuestionSet(self): "Requests uniqueID from server" request = {'type': 'question_set', 'game_id': self.game_id} print("Requesting question set: QUIZ") self.network_handler.sendRequest(request) time.sleep(.3) def createUI(self): '''Creates label, question, answer ch...
The code initializes and manages a quiz scene loop, setting up UI elements, handling events, updating game state, and rendering visuals. It starts a timer, processes user inputs, transitions between scenes (e.g., "quit" or "results"), and maintains the loop until the scene ends.
def sceneLoop(self): self.network_handler.setCallbackResponse(self.handleResponse) self.running = True self.getQuestionSet() print("creating UI quiz") self.createUI() self.updateAnswers() # Initial answer selection self.updateQuestion() # Places initial question ...
def CSV_converter(CSV_converter, channel): _, ext = os.path.splitext(CSV_converter) # extracting filename extension to open the file. if ext in [".xls",".xlsx"]: #for Excel qc = pd.read_excel(CSV_converter) elif ext == '.csv': #for CSV qc = pd.read_csv(CSV_converter) elif ext == '.tsv':...
The main task of the code is to process NMR data from a CSV file, predict molecular properties (fingerprint, molecular weight, class, glycosylation) using a machine learning model, search a database for top candidate matches, and save results (table, predicted fingerprint, and HSQC spectra image) for analysis and visua...
def search_CSV(input_nmr_filename, DB, index_super, model, channel, output_table, output_nmr_image, output_pred_fingerprint, mw=None, top_candidates=20): # i = CSV file name mat = CSV_converter(input_nmr_filename,channel) # Searching the molecules and drawing the HSQC spectra image with classificaiton results. ...
def load_db(db_folder="."): db_path = os.path.join(db_folder, 'DB_010621_SM3.json') db_df = pd.read_json(db_path) #loading DB DB = np.array(db_df) with open(os.path.join(db_folder, 'superclass.json'),'r') as r: index_super = json.load(r) return DB, index_super def load_models(models_fold...
The code processes input CSV data using either of two preloaded models (model_1ch or model_2ch) based on the specified channel (1 or 2), searches a database (DB) for matches, and generates output files including a table, NMR images, and predicted fingerprints. It accepts molecular weight as an optional parameter to ref...
def main(): DB, index_super = load_db() model_1ch, model_2ch = load_models() parser = argparse.ArgumentParser(description='SMART Embedding') parser.add_argument('input_csv', help='input_csv') parser.add_argument('output_table', help='output_table') parser.add_argument('output_nmr_image', help='...
def buy(self): print("What do you want to buy? 1 - espresso, 2 - latte, 3 - cappuccino, back - to main menu:") self.order = input() if self.order == "1": return self.espresso() elif self.order == "2": return self.latte() elif self.order == "3": ...
The code processes user commands for a coffee machine system, continuously prompting for actions like 'buy', 'fill', 'take', 'remaining', or 'exit'. It executes corresponding methods based on input and terminates when 'exit' is selected.
def action(self): while True: print("Write action (buy, fill, take, remaining, exit):") self.option = input() if self.option == "buy": self.buy() elif self.option == "fill": self.fill() elif self.option == "take": ...
def _build_iteration_indexes(data_len, num_iterations, verbose=False, random_generator=None): iterations = np.arange(num_iterations) % data_len if random_generator: random_generator.shuffle(iterations) if verbose: return _wrap_index__in_verbose(iterations) el...
The code trains a Self-Organizing Map (SOM) by iteratively updating neuron weights using input data samples. It tracks quantization error at specified intervals, appends these errors to an array, and returns them. If verbose, it prints the final quantization error. The training uses random iteration indices, updates th...
def Train(self, data, num_iteration, step_len, verbose): """Trains the SOM. data : np.array Data matrix (sample numbers, feature numbers). num_iteration : Maximum number of iterations. """ start_num = num_iteration[0] end_num = num_iteration[1] random_...
def __initLoggingVariables(self): self.trainLoss=0 self.trainGridAccuracy=0 self.batchCount=0 def __prepareIOTrainTensors(self, batch): tensorInput, tensorOutput = self.__getIOTensorFromBatch(batch) return tensorInput, tensorOutput.view(-1) def __logInformation(self, pred1, pred...
The code trains a neural network model by iterating over epochs and batches. For each batch, it computes predictions, applies a loss function on masked input elements, performs backpropagation, and updates the model. It logs training metrics and evaluates/saves the model after each epoch.
def train(self): for self.epoch in range(self.parameters.maxEpochs): self.__initLoggingVariables() for self.batchIndex, batch in enumerate(self.trainDataLoader): self.optimizer.zero_grad() tensorInput, tensorOutput = self.__prepareIOTrainTensors(batch) ...
def _read(self, reformat: bool = None) -> str: """Read from frotz interpreter process.""" reformat = self.reformat_spacing if reformat is None else reformat output = b"" while True: rlist, _, _ = select.select([self.frotz.stdout], [], [], 1) if self.frotz.stdout i...
This code initializes a Frotz-based interactive fiction game interpreter by launching the specified interpreter executable with configuration flags, reading and processing the game's introductory text, handling potential blorb/zcode file warnings, and loading a saved game state if available. It ensures proper setup and...
def _init_frotz(self, interpreter: str) -> None: self.frotz = subprocess.Popen( # noqa ( interpreter, "-m", "-R", "/dev/null", "-Z0", f"-w{self.screen_width}", self.story_file, ...
def __choose(self, request): # check if any freeMemory left if self.__freeMem.size > 0: # store the outcome as we want to print the freeMem after keepOutcome = self.__allocate(request) print(f"# FREE MAIN MEMORY #\n{self.__freeMem}\n{self.__endString}") # ...
This code processes a queue of memory management requests by iterating through each entry and handling allocation/replacement, deallocation, or write operations based on the request type, using corresponding methods to manage memory efficiently.
def run(self): """ Run the management system. """ # print that the system is running print(f"# RUNNING MEMORY MANGEMENT SYSTEM #\n{self.__endString}") # for each in the queue for request in self.__requests: # if the request is allocation/replacement ...
def generate_algorithm(root_value): alg = [] current_index = 0 for ga_i in range(m+1): if ga_i == 0: # Root Node root_c = NR_COMPS * bitarray('1') rho_min = 0 if root_value[0] == 0: rho_min = 1 root_node = Node(current_index...
The function checks algorithms generated from a root component for validity. It repeatedly validates the algorithm, returning it if valid or proceeding to the next variant if invalid, with conditional logic involving `critical_words` and debug logging.
def check_alg_for_root_comp(root_comp): global critical_words alg = generate_algorithm(root_comp) if DEBUG: print("({}) Starting checking of algorithms with root value {}".format(strftime("%Y-%m-%d %H:%M:%S", gmtime()), ...
def merge_attributes(in_list, simplify=False): """ Merge like attributes from a list of objects This function checks the attributes of each element of in_list against each of the attributes in in_list[0]. In cases where the attribute is different in one or more elements of in_list, the function rep...
The main task of the code is to download GRIB files for specified forecast hours and dates using Herbie, then convert them into a well-structured xarray dataset with merged attributes and time dimensions. It handles multiple dates by recursively processing each, merging global and layer attributes, and concatenating da...
def get_nbm( dates, vnames_toget={}, fhr=list(range(0, 23+1)), fxx=1, product='co', simplify=True ): """ Download/open a GRIB file (or list of them) using Herbie This function uses Herbie's bulk_download to get GRIBS for a range of of forecast release hours on a given day, then ...
def _loadSourceFiles(self): sys.path.extend(self.sourceDirs) def _scanTestDirectory(self): testFileMapper ={} for dirname, subdirList, fileList in os.walk(self.testDir): testFileNames =[] log('Scanning directory :' +dirname ) for filename in fileList: if filena...
The main task of the code is to scan test directories, map them to their respective test files, add each directory to the Python path, and execute the identified test files. This involves loading source files, discovering test files, modifying the system path for module resolution, and running the tests.
def scanAndExecuteTests(self): self._loadSourceFiles() testFileMapper = self._scanTestDirectory() for directory in testFileMapper.keys(): testfilenames = testFileMapper[directory] sys.path.append(directory) self._loadAndExecuteFiles(testfilenames)
def total_force_Z_dir_sls(self): """ Calculates the total axial force at serviceability limit states of 1.0gk + 1.0qk + 1.0wk. The foundation loads are converted to kN and added to the total axial loads from permanent,imposed and wind loads. Returns ------- float ...
This function calculates the base pressures at four corners of a pad foundation under serviceability limit state (SLS) by combining total vertical force with eccentricities in X and Y directions. It computes four corner pressures (q1–q4) using adjusted formulas based on foundation dimensions and eccentricity ratios, th...
def pad_base_pressures_sls(self): """ Calculates the pad foundation pressures at the four corners of the foundation using the serviceability limit state combination. Returns ------- q1 : float base pressure at sls located at the bottom left corner of the pad ...
def total_force_Z_dir_uls(self): """ Calculates the total axial force at ultimate limit states of 1.35gk + 1.5qk + 0wk The foundation loads are converted to kN and added to the total axial loads from permanent,imposed and wind loads. Returns ------- float sum...
This function calculates the base pressures at the four corners of a pad foundation using the ultimate limit state (ULS) combination. It computes four values (q1 to q4) representing the pressure at each corner (bottom-left, top-left, bottom-right, top-right) in kN/m². The calculation uses the total vertical force, ecce...
def pad_base_pressures_uls(self): """ Calculates the pad foundation pressures at the four corners of the foundation using the ultimate limit state combination. Returns ------- q1 : float base pressure at sls located at the bottom left corner of the pad founda...
def make_loaders(self): ''' Initializes three dataloaders: training, validation. ''' # the batch size for the dataloaders is defined as (seq_len * batch_size) / target_window batch_size =self.param_vals.get('batch_size', 64) num_workers = self.param_vals.get('num_workers...
The main task of the code is to perform model training over multiple epochs, processing training and validation batches to compute losses, evaluation metrics, and statistical correlations (e.g., Spearman's). It tracks training/validation performance, visualizes metrics, and periodically saves the model if enabled. The ...
def train(self, debug): ''' Main training loop ''' print('began training') for epoch in range(self.param_vals.get('num_epochs', 10)): self.model.train() self.tr_epoch_df = pd.DataFrame() train_loader, val_loader, _ = self.make_loaders() ...
def calcular_media(self): return sum(self.datos) / len(self.datos) def calcular_Z(self): media = self.calcular_media() acumulado = norm.cdf(media) posicion = norm.ppf(acumulado) return posicion def Superior(self): inferior=(0.5)-(((self.calcular_Z()*self.a)/2)/(math.sqrt(...
This method prints statistical data, calculates and displays the mean and Z-score, outputs upper and lower limits, and determines if a hypothesis is accepted based on whether the hypothesis values fall within these limits.
def toString(self): print(self.datos) print("la media de los datos es {:.2f}".format(self.calcular_media())," al mismo tiempo que Z se encuentra en " "{:.2f}".format(self.calcular_Z())," al mismo tiempo sabemos que el limite superior es {:.4f}".format(self.Superior()),"" "y el inferior e...
def __accept_and_handle_connection(self): session_socket, session_addr = self.master_socket.accept() self.handle_connection(session_socket, session_addr) def find_session(self, *, fd: socket.socket = None, id_: str = None, idx: int = None) -> [Session, None]: """ Looking for session in `...
This code sets up a network server using a socket, listens for incoming connections, and manages sessions. It uses `select.select` to monitor sockets for read/write events, handles data reception, decodes and prints session output, and manages session lifecycle (creation, termination). A background thread runs the inte...
def main(self): Printer.info(f"Listening: {self.master_host}:{self.master_port}") if self.allow_duplicate_sessions: Printer.warning("Session duplicating enabled") self.master_socket.bind((self.master_host, self.master_port)) self.master_socket.listen(0x10) self.inpu...
def __start_service(self): #does the service exists ? command = "status $"+self.serviceName result = self.__execute_in_tacl(command) if "(Process does not exist)" not in str(result): data = self.__handle_error("Service exists") return data ...
The main task of the code is to handle service requests based on the `action` attribute. If `action` is "start", it initiates a service; if "stop", it terminates a service; otherwise, it returns an error for invalid actions. The method acts as a dispatcher, routing requests to private methods `__start_service()`, `__st...
def serve_request(self): if self.action == "start": return self.__start_service(); elif self.action == "stop": return self.__stop_service(); else: return self.__handle_error("Invalid value for action.")
def _get_current_date_as_str(type_of_format: int = 0) -> str: """ Functionality to get a datetime.now() as a string in needed format :param type_of_format: int type of format to return :return: str datetime.now() in needed format """ now = datetime.now() if type_...
This function verifies if the current screen state matches the expected state by comparing images. It waits up to a specified timeout, checks for differences, and raises an assertion error or logs a message if discrepancies are found. The method captures screenshots, compares them, and handles verification outcomes bas...
def verify_screen(self, expected: str, hard_assert: bool = True, timeout: int = 2) -> None: """ Screen state verification functionality :param expected: str Screen state name :param hard_assert: bool raise AssertionError or just display a error message :param timeout: int wait f...
def translate_push_pop_command(static_label, cmd, seg, val): res = None match cmd: case PushPop.pop: res = translate_pop_command(static_label, seg, val) case PushPop.push: res = translate_push_command(static_label, seg, val) case _: raise Exception(f"U...
The function `translate_command` translates a given command into assembly code by routing it to specific helper functions based on its type. It uses pattern matching to identify the command type (e.g., `PushPopCommand`, `OpCommand`, `BranchCommand`, `FunctionCommand`), invokes the corresponding translation function wit...
def translate_command(static_label, command, label_gen): res = None match command: case PushPopCommand(cmd, seg, val): res = translate_push_pop_command(static_label, cmd, seg, val) case OpCommand(op): res = translate_op_command(op, label_gen) case BranchCommand(cm...
def add_transaction_to_block(self, block): # Get the transaction with highest fee by block_limitation self.pending_transactions.sort(key=lambda x: x.fee, reverse=True) #Sort the transaction value form descending order (reverse=True) by comparing with transaction.fee (key=lambda x: x.fee) if len(self...
The main task of the code is to implement a proof-of-work mining process for a blockchain. It generates a new block with transactions, validates its hash against the difficulty requirement by incrementing a nonce, stores the block in a database, and appends it to the chain if valid. The process includes timestamping, c...
def mine_block(self, miner): #Mining process aka proof of work algorithm start = time.process_time() #Recording the start time last_block = self.chain[-1] #[-1] is last item of an array in here it means the last block of the chain. new_block = Block(last_block.index + 1, last_block.hash, se...
def generate_address(self): #Generate public and private key, the public key will be the user address and the key will save as pkcs1 format public, private = rsa.newkeys(512) public_key = public.save_pkcs1() private_key = private.save_pkcs1() return self.get_address_from_public(publi...
The main task of the code is to generate a miner's public and private keys, store them in a text file, initialize a blockchain with a genesis block if no sufficient arguments are provided, and continuously mine blocks while adjusting mining difficulty in an infinite loop.
def start(self): #self.mysql_block_table() #self.mysql_transaction_table() address, private = self.generate_address() #generate the address by generate_address() function print(f"Miner address: {address}") print(" ") print(f"Miner private: {private}") #...
def get_balance(self, account): #Function to get the balance of an account current_balance = 0 for block in self.chain: # Check miner reward miner = False if block.miner == account: #If block miner is same as the account name, the reward will ...
This function handles incoming network messages from connected clients by parsing requests, executing corresponding actions (e.g., balance checks, transaction processing, blockchain synchronization), and sending appropriate responses. It processes "get_balance", "transaction", "clone_blockchain", "broadcast_block", "br...
def receive_socket_message(self, connection, address): #Check user request for further action with connection: print(f'Connected by: {address}') address_concat = address[0]+":"+str(address[1]) while True: message = b"" while True: ...
def setup(runType): pwn.context.clear(arch = 'amd64') config = { 'runType': runType } if runType == "Debug": config['host'] = '127.0.0.1' config['port'] = 3006 config['special_char'] = b'\xc8' config['parm'] = 25 config['pad'] = b'' elif runType == "Test": ...
The main task of the code is to configure a system by initializing parameters, extract a primary value, modify the configuration with this value, execute a loop-breaking process to obtain critical data, and then prepare and launch an attack using the derived data and modified configuration. The code orchestrates setup,...
def main(): config = setup("Go for it") #config = setup("Test") #config = setup("Debug") val = getFirstValue(config) config['garbage'] = val s, d = breakInLoop(config) config['s'] = s setupAttack(config, d) attack(config, d)
def advance(self): c = self.src[self.current] self.current += 1 return c def add_token(self, token_type, literal=None, val=None): val = self.src[self.start: self.current] if val is None else val self.values.append(Token(token_type, literal, val, self.line)) def match(self, char):...
The code scans input characters to generate tokens, handling punctuation, operators, comments, strings, numbers, and identifiers. It checks for multi-character tokens (e.g., `!=`, `==`), skips comments with `/`, processes strings via `self.string()`, and identifies numbers/identifiers. Whitespace is ignored, while unre...
def scan(self): c = self.advance() if c == '(': self.add_token(TokenType.LEFT_PAREN) elif c == ')': self.add_token(TokenType.RIGHT_PAREN) elif c == '{': self.add_token(TokenType.LEFT_BRACE) elif c == '}': self.add_token(TokenType.R...
def check(self, token_type): if self.is_end(): return False return self.peek().type == token_type def advance(self): if not self.is_end(): self.current += 1 return self.previous() def peek(self): return self.tokens[self.current]
The main task of the code is to consume a token of a specified type. If the current token matches `token_type`, it advances the parser; otherwise, it raises a `LoxError` with the provided message and the line number of the current token, indicating a syntax error.
def consume(self, token_type, msg): if self.check(token_type): return self.advance() raise LoxError(msg + " at line: {}".format(self.peek().line))
def find_three_meld(hand): #all three melds for i in range(len(hand)): for j in range(i + 1, len(hand)): for k in range(j + 1, len(hand)): meld = [hand[i], hand[j], hand[k]] if is_meld(meld): return meld return [] def remove(meld, han...
The function `find_melds` aims to identify and remove possible melds (three-of-a-kind or four-of-a-kind card combinations) from a given hand in a game like Gin Rummy. It iteratively checks for three-card and four-card melds, removes them from the hand, and returns the remaining cards after processing. The code attempts...
def find_melds(hand): #there are possible melds: (4, 4), (3, 3, 4), (3, 3), (3), (4), (4, 3), () #further, for each of these (except empty) there are could be multiple options. #check out https://stackoverflow.com/questions/62707039/gin-rummy-algorithm-for-determining-optimal-melding melds = [] ...
def find_melds(hand): #there are possible melds: (4, 4), (3, 3, 4), (3, 3), (3), (4), (4, 3), () #further, for each of these (except empty) there are could be multiple options. #check out https://stackoverflow.com/questions/62707039/gin-rummy-algorithm-for-determining-optimal-melding melds = [] ...
The code simulates a turn-based card game between two players: one using random strategies and the other using a greedy approach. It processes their turns, including drawing cards, discarding, checking for "gin" (winning with an empty hand), and "knocking" (ending the game if deadwood points are below a threshold). Poi...
def greedy_vs_random(player_one_hand, player_two_hand, deck, discard_pile, max_deadwood, points): #player one is random #player two is greedy rand.seed(a=None,version=2) while (deck.qsize() > 3): # print('iter') #random goes first #draw card from either discard or deck #l...
def pointc(x: bytes) -> Point: P = lift_x(x[1:33]) if x[0] == 2: return P elif x[0] == 3: return point_negate(P) assert False def key_agg_internal(pubkeys: List[bytes]) -> Point: u = len(pubkeys) Q = infinity for i in range(u): a_i = key_agg_coeff(pubkeys, pubkeys[i])...
This function generates a Schnorr signature using a secret nonce, secret key, aggregated nonce, and public keys for a given message. It computes elliptic curve points, adjusts keys based on parity checks, hashes the challenge, and derives the signature component 's' via modular arithmetic, returning the resulting signa...
def sign(secnonce: bytes, sk: bytes, aggnonce: bytes, pubkeys: List[bytes], msg: bytes) -> bytes: R = pointc(aggnonce) assert not is_infinite(R) Q = key_agg_internal(pubkeys) k_ = int_from_bytes(secnonce) assert 0 < k_ < n k = k_ if has_even_y(R) else n - k_ d_ = int_from_bytes(sk) asser...
def pointc(x: bytes) -> Point: P = lift_x(x[1:33]) if x[0] == 2: return P elif x[0] == 3: return point_negate(P) assert False def key_agg_internal(pubkeys: List[bytes]) -> Point: u = len(pubkeys) Q = infinity for i in range(u): a_i = key_agg_coeff(pubkeys, pubkeys[i])...
This function verifies a Schnorr signature using aggregated public keys and nonces. It checks if the scalar multiplication of the elliptic curve generator by the signature scalar equals the sum of the nonce point and the product of the public key, message hash, and aggregation coefficient. The verification ensures the ...
def partial_sig_verify_internal(psig: bytes, pubnonce: bytes, aggnonce: bytes, pubkeys: List[bytes], pk: bytes, msg: bytes) -> bool: s = int_from_bytes(psig) assert s < n R = pointc(aggnonce) Q = key_agg_internal(pubkeys) R__ = pointc(pubnonce) R_ = R__ if has_even_y(R) else point_negate(R__) ...
def nonce_gen() -> Tuple[bytes, bytes]: k = 1 + secrets.randbelow(n - 2) R = point_mul(G, k) pubnonce = cbytes(R) secnonce = bytes_from_int(k) return secnonce, pubnonce def nonce_agg(pubnonces: List[bytes]) -> bytes: R = infinity for pubnonce in pubnonces: R = point_add(R, pointc(pub...
This code tests a partial signature scheme's correctness by generating random keys, nonces, and messages, then verifying that a partial signature is valid for the correct signer and message, but invalid for incorrect signer indices or altered messages.
def test_sign_and_verify_random(iters): for i in range(iters): sk_1 = secrets.token_bytes(32) sk_2 = secrets.token_bytes(32) pk_1 = bytes_from_point(point_mul(G, int_from_bytes(sk_1))) pk_2 = bytes_from_point(point_mul(G, int_from_bytes(sk_2))) pubkeys = [pk_1, pk_2] ...
def Linv(self,M): with torch.no_grad(): N=M.shape[0] k=int(0.5*N*(N-1)) # l=0 w=torch.zeros(k,device=self.device) ##in the triu_indices try changing the 1 to 0/-1/2 for other ## ascpect of result on how you want the diagonal to be included indices=torch.triu...
The code trains the RWL-GNN model's two-stage process by computing a graph Laplacian from the adjacency matrix, initializing learnable weights via its inverse, optimizing these weights with specified optimizers, and returning the learned adjacency matrix after pre-training epochs.
def fit(self, features, adj): """Train RWL-GNN: Two-Stage. Parameters ---------- features : node features adj : the adjacency matrix. The format could be torch.tensor or scipy matrix labels : node labels idx_train : ...
def Linv(self,M): with torch.no_grad(): N=M.shape[0] k=int(0.5*N*(N-1)) # l=0 w=torch.zeros(k,device=self.device) ##in the triu_indices try changing the 1 to 0/-1/2 for other ## ascpect of result on how you want the diagonal to be included indices=torch.triu...
The code trains a RWL-GNN model for node classification by jointly optimizing graph structure (via Laplacian regularization) and model parameters. It initializes optimizers, processes the adjacency matrix to compute graph Laplacians, and alternates between optimizing the graph structure (using a custom optimizer) and t...
def fit(self, features, adj, labels, idx_train, idx_val): """Train RWL-GNN. Parameters ---------- features : node features adj : the adjacency matrix. The format could be torch.tensor or scipy matrix labels : node labels idx_tra...
def mkObstacles(d, n): ''' Randomly lay out obstacles with so they are at least 2 and a bit bot diameters away from any wall or other obstacle. ''' obstacles = [] rad = d.conf['arenaSize'] * d.conf['obstacleRadius'] / 100.0 for i in range(n): overlaps = True attempts = 0 ...
This code sets up and runs a networked robot battle server, handling configuration via command-line arguments, game state management, bot interactions, and timing control. It initializes server settings, processes game steps at fixed intervals, manages bot connections, and maintains game rules for a specified number of...
def main(): global d # d is global so quit() can access it. d = SrvData() random.seed() parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('-ip', metavar='Server_IP', dest='serverIP', type=nbipc.argParseCheckIPFormat, ...
def apply_mask(img_src, mask_src): with Image.open(img_src) as img, Image.open(mask_src) as mask: mask_pixels = mask.load() mask_pixels[0, mask.size[1] - 1] = mask_pixels[1, mask.size[1] - 1] img = img.convert("RGBA") mask = mask.convert("1") img.paste(0, mask=mask) r...
The main task of the code is to extract and decompress game assets, apply masks to generate sprites, organize resources into designated directories, process animation data from JSON files, and copy necessary files (sounds, icons, animations) into a "res" folder for further use. It also handles file renaming, layer extr...
def main(): if not path.isdir(path.join(os.getcwd(), "extracted")): extract_n_decompress.main() pathlib.Path(SPRITES_DEST_DIR).mkdir(parents=True, exist_ok=True) pathlib.Path(SOUNDS_DEST_DIR).mkdir(parents=True, exist_ok=True) # apply masks for i in range(527): mask_src = os.path.j...
def feistel_decrypt_with_keys_ecb(cipher, key, function_logic): return feistel_decrypt(cipher, key, function_logic) def feistel_decrypt_with_keys_cbc(cipher, keys, function_logic, init_vector): result = [] previous_ciphertext = init_vector for block in cipher: decrypted_block = block[:] ...
The code decrypts a cipher using a Feistel network with a custom function logic, handling multiple modes (ECB, CBC, CFB, CRT, ???). It applies the decryption algorithm to the provided cipher pairs, key, and initialization vector, outputting the decrypted text. The function logic combines XOR and bitwise operations, whi...
def main(): # the function_logic is the same as the one used in the encryption script function_logic = lambda m, key: (m ^ key) & ((key // 16) | m) # the cipher pairs cipher = [[72, 16], [83, 17], [89, 23], [65, 16], [77, 8], [82, 0], [78, 5], [80, 7], [91, 27], [92, 29], [71, 13], [75, 10], [...
def tooSmall(): messagebox.showwarning("Password is too short","The password entered isn't strong enough!") def namesEntered(): fname=Fore.get() sname=Sur.get() cGroup=classGroup.get() if fname == "" or sname == "" or cGroup == "": errorMsg() else: ...
The code validates if two password inputs match and checks their length. If they match and are longer than 7 characters, it proceeds to the next step (namesEntered()); otherwise, it triggers an error for short passwords (tooSmall()) or mismatched passwords (passMatchError()).
def checkPassword(): p1=Pass.get() p2=confirmPass.get() if p1 == p2: print("Matching") passw=len(p1) if passw<=7: tooSmall() else: namesEntered() else: passMatchError()
def errorMsg(): messagebox.showwarning("Invalid Details","Fill in the information correctly") def checkPassword(): p1=Pass.get() p2=confirmPass.get() if p1 == p2: print("Matching") passw=len(p1) if passw<=7: tooSmall() else:...
The main task of the code is to validate a username input by checking if it is non-empty and not already present in the 'Users' table of a SQLite database. If valid, it proceeds to check the password; otherwise, it triggers an error message for empty input or a taken username.
def checkUsername(): Username=User.get() ##Gets the username from the entry widget if Username == "": errorMsg() ##Runs an error messagebox else: db_conn = sqlite3.connect('Coursework.db') ##Connects to the database with db_conn: ...
def usage(exit_code=0): progname = os.path.basename(sys.argv[0]) print(f'''Usage: {progname} [-a ALPHABET -c CORES -l LENGTH -p PATH -s HASHES] -a ALPHABET Alphabet to use in permutations -c CORES CPU Cores to use -l LENGTH Length of permutations -p PREFIX Prefix for all permutations ...
The main task of the code is to crack or smash hash values by generating potential passwords based on command-line arguments (e.g., alphabet, length, cores, prefix). It loads hash data from a file, uses multi-threading if specified, and outputs matched passwords. The core functionality involves parsing inputs, processi...
def main(): arguments = sys.argv[1:] alphabet = ALPHABET cores = 1 hashes_path = 'hashes.txt' length = 1 prefix = '' # TODO: Parse command line arguments while arguments: argument = arguments.pop(0) if argument == '-h': usage() ...
def get_legal_moves(board, player): """ Helper function to get a list of index 2-tuples that are valid moves for the current player. :param board: The current board state, a 2d-list :param player: The current player to place the next piece, 0 = black, 1 = white """ board_width, board_height = le...
The function `get_move` handles player turns in a game, printing the current player's turn, checking for legal moves, and updating the board. If no legal moves exist, it returns the board unchanged. For the human player, it prompts for input; for the computer, it calculates a move and updates the board accordingly.
def get_move(board, current_player): """ Helper function to pass the game between players. :param board: The current board state, a 2d-List :param current_player: Player to go next, 0 = black, 1 = white """ print('It is', NAME_LIST[current_player] + '\'s turn.') legal_moves = get_legal_moves...
def get_move(board, current_player): """ Helper function to pass the game between players. :param board: The current board state, a 2d-List :param current_player: Player to go next, 0 = black, 1 = white """ print('It is', NAME_LIST[current_player] + '\'s turn.') legal_moves = get_legal_moves...
The main task of the code is to simulate a turn-based game on a board, alternating between two players (BLACK and WHITE). It repeatedly gets moves for each player, checks if the board state meets a terminal condition (e.g., win/loss/draw), and breaks the loop when such a condition is met. Finally, it concludes the game...
def main(): board = parse_board(BOARD) while True: board = get_move(board, current_player=BLACK) if check_board(board): break board = get_move(board, current_player=WHITE) if check_board(board): break conclude_game(board)
def peek(self): if self.position + 1 >= len(self.code): return EOF return self.code[self.position + 1] def eat(self): if self.position + 1 >= len(self.code): self.error("EOF", self.stderr) return EOF self.position += 1 return self.ch() def slot...
This code processes output by converting it to integer, float, character, or ASCII value based on the next character. If "&" follows, it writes to a specified file handle; otherwise, it prints to stdout.
def print(self): output = self.w next = self.peek() if next == "i": self.eat() output = int(float(output)) if next == "f": self.eat() output = float(output) elif next == "c": self.eat() output = chr(output) ...
def peek(self): if self.position + 1 >= len(self.code): return EOF return self.code[self.position + 1] def eat(self): if self.position + 1 >= len(self.code): self.error("EOF", self.stderr) return EOF self.position += 1 return self.ch() def slot...
This code reads input either from a file handle (if the input starts with "&<...") or from standard input. It checks for "&" and "<" to determine the source, reads content into `self.w`, and handles errors if the handle is invalid. If no "&" is found, it reads a line from `stdin` and strips the newline.
def read(self): if self.peek() == "&": self.eat() if self.peek() == "<": self.eat() file_handle = self.slots[self.slot()] else: file_handle = self.w try: self.w = file_handle.read() exce...
def peek(self): if self.position + 1 >= len(self.code): return EOF return self.code[self.position + 1] def string(self): """ Parse a string literal """ if DEBUG: debug(self) s = "" while 1: if self.peek() == "\\": ...
This code parses either a string or a number from the input based on the next character. If the next character is a single quote, it skips the quote and reads a string; otherwise, it reads a number. The parsed value is then assigned to the instance variable `self.w` for further processing.
def data(self): if self.peek() == "'": self.position += 1 # Skip ' value = self.string() else: value = self.number() self.w = value
def peek(self): if self.position + 1 >= len(self.code): return EOF return self.code[self.position + 1] def string(self): """ Parse a string literal """ if DEBUG: debug(self) s = "" while 1: if self.peek() == "\\": ...
The main task of the code is to parse and accumulate values from input. It checks the next character: if it's a quote, it reads a string; if it's '<', it retrieves a slot value; otherwise, it parses a number. The parsed value is then added to the instance variable `self.w` for accumulation.
def plus(self): if self.peek() == "'": self.position += 1 # Skip ' val = self.string() elif self.peek() == "<": self.position += 1 val = self.slots[self.slot()] else: val = self.number() self.w += val
def error(self, msg, stderr): stderr.write(msg + '\n') self._has_errored = True # Make embedded Qualm not break if __name__ == '__main__': sys.exit(-1) def peek(self): if self.position + 1 >= len(self.code): return EOF return self.code[self.posit...
This function determines the index of an item in `self.w` based on the next input token. It handles strings (if quoted), numeric values, or slots, and assigns the result to `self.w`. If encountering `$`, it sets `self.w` to its length and exits. Errors occur if `self.w` is not iterable or invalid input is provided.
def indexof(self): if not hasattr(self.w, "index"): self.error("self.w is not iterable", self.stderr) next = self.peek() if next == "'": self.eat() item = self.string() elif next == "$": self.eat() self.w = len(self.w) ...
def peek(self): if self.position + 1 >= len(self.code): return EOF return self.code[self.position + 1] def eat(self): if self.position + 1 >= len(self.code): self.error("EOF", self.stderr) return EOF self.position += 1 return self.ch() def slot...
This function parses and returns an integer value, either from a slot reference (if the next token is "<") or directly from a number. It checks the current token, consumes it if it's a slot marker, and retrieves the corresponding slot value or number as an integer.
def slot_or_number(self): if self.peek() == "<": self.eat() return int(self.slots[self.slot()]) else: return int(self.number())
def peek(self): if self.position + 1 >= len(self.code): return EOF return self.code[self.position + 1] def string(self): """ Parse a string literal """ if DEBUG: debug(self) s = "" while 1: if self.peek() == "\\": ...
This code parses and evaluates a conditional expression of the form `<expr> <op> <expr>`, handling numeric, string, and variable expressions. It identifies operands (left/right) based on input type, processes relational operators (==, !=, <=, >=), and returns the boolean result of the comparison.
def condition(self): """ <expr> <op> <expr> """ ch = self.peek() if ch in ".,ws<v": self.position += 1 self.operators[ch]() left = self.w elif self.peek() == "'": self.position += 1 # Skip ' left = self.string(...
def peek(self): if self.position + 1 >= len(self.code): return EOF return self.code[self.position + 1] def eat(self): if self.position + 1 >= len(self.code): self.error("EOF", self.stderr) return EOF self.position += 1 return self.ch() def slot...
The code implements an `at` method to either set or retrieve values in a data structure (`self.w`). If an equals sign (`=`) is encountered, it assigns a key-value pair, parsing the key with `slot_or_number`, expecting a comma, and then reading a string (if quoted) or another value. If no `=` is found, it retrieves the ...
def at(self): # Set at if self.peek() == "=": self.eat() at = self.slot_or_number() if self.eat() != ",": self.error(f"Expected `,` at {self.position}", self.stderr) if self.peek() == "'": self.eat() value ...
def get_dataloader_train_impute(series, masks, batch_size=4, train_split=0.7, valid_split=0.9, len_dataset=100, path_save=''): ...
The main task of the code is to train a CSDI (Conditional Score-based Diffusion for Imputation) model for time series imputation. It processes input data (`series`, `masks`), configures hyperparameters (e.g., diffusion layers, learning rate, masking strategy), splits data into training/validation/test sets, initializes...
def train(self, series, masks, k_segments_or_k_misssing, train_split = 0.7, valid_split = 0.2, epochs = 200, samples_generate = 10, path_save = "", batch_size = 16, lr = 1.0e-3, ...
def set_current_sprite_state(self): self.motion = self.get_sprite_state() if self.last_state == '_'.join([self.motion, self.direction, self.look]): return self.motion = self.get_sprite_state() if self.look == 'down' and self.motion == 'staying': self.polar_star.up...
The code updates an entity's position, manages interaction states, handles invincibility/damage timers, updates bullets, and animates sprites by cycling through frames with sound effects when running.
def update(self, maap, enemies): self.set_current_sprite_state() self.updatex(maap) self.updatey(maap) self.interacting = True if self.motion == 'staying' and self.look == 'down' else False # TODO: test interacting if self.invincible: self.invincible_time += 1 ...
def move(self, direction): if self.not_in_wall(): self.x += MOVEMENT_SPEED * DIR_OFFSETS[direction][0] if self.x >= 920: self.x = 919 elif self.x <= 60: self.x = 62 if self.not_in_wall(): self.y += MOVEMENT_SPEED * DIR_OFFSE...
This code updates a game object's position and jumping mechanics. It moves the object, applies gravity during jumps, detects platform collisions to reset jump state, and handles falling when leaving a platform. The method manages vertical movement, jump physics, and platform interactions to simulate realistic movement ...
def update(self, delta): print(self.jump_charge) self.move(self.direction) if self.is_jump: self.y += self.vy self.vy += GRAVITY new_p = self.find_touching_platform() if new_p: self.vy = 0 self.jump_count = ...
def get(self, game, row, col): """returns a specific cell""" return(game["grid"][row][col]) def get_neighbours(self, game, row, col): neighbour_indexes = [(-1, -1), (0, -1), (1, 0), (1, 1), (0, 1), (-1, 0)] neighbours = [] for x, y in neighbour_indexes: # identify all neighbours...
The function counts the number of consecutive cells in three potential winning directions for a given cell in a game board, adjusting for double-counting of the current cell. It evaluates neighbors in six directions, calculates continuation lengths, and combines opposing directions to determine total consecutive rows f...
def count_cont_rows(self, game, row, col): """count win directions for a given cell""" cell = self.get(game, row, col) neighbours = self.get_neighbours(game, row, col) cont_rows = [0, 0, 0, 0, 0, 0] win_directions = [0, 0, 0] for i, nb in enumerate(neighbours): ...
def get_player(self, game): return game["turn"] % 2 def is_legal(self, game, row, col): # this should be a GameLogic method """check if a specific cell can be occupied""" real_neighbours = [i for i in self.get_neighbours(game, row, col) if (i != None)] occupied_neighbours = sum([1 if i[...
This function updates the owner of a game cell at specified coordinates if the move is legal. It assigns the current player's ownership, checks for a win condition, sets the winner if applicable, advances to the next turn, and returns True for valid moves or False otherwise.
def update_owner(self, game, row, col): player = self.get_player(game) if self.is_legal(game, row, col): self.get(game, row, col)["owner"] = self.get_player(game) if self.is_win_condition(game): game["winner"] = player self.next_turn(game) ...
def _get_vertical_animation_transition(self): """Returns the animation transition for based on whether we will vertically expand or retract.""" will_expand = not self._expanded_vertical if will_expand: if self.transition_expand_y: return self.transition_expand...
This method animates the vertical size hint (size_hint_y) of a widget to either its minimum or maximum allowed value, if vertical resizing is enabled. It validates the target y_hint, cancels existing animations, selects an animation transition/duration, and triggers either a standard or special-case animation to smooth...
def _animate_height_hint(self, y_hint, *_args): """If we are allowed to resize vertically, and if the y_hint is one of the values min_y_hint or max_y_hint, then we perform the needed animation to animate to that value of y_hint. This will call self._resolve_size_hint_xy if the current si...
def elitism_selection(self, size): """Select the top #size individuals to be parents.""" population = sorted( self.population, key=lambda individual: individual.fitness, reverse=True ) return population[:size] def roulette_wheel_selection(self, size): selection = [] ...
The main task of the code is to evolve a population in a genetic algorithm by calculating average fitness, selecting parents via elitism and roulette wheel selection, generating children through crossover and mutation, and updating the population. It also tracks generations, saves progress periodically, and updates the...
def evolve(self): """The main procss of Genetic Algorithm.""" sum_fitness = 0 for individual in self.population: individual.get_fitness(self.opp_individual.genes) sum_fitness += individual.fitness self.avg_fitness = sum_fitness / len(self.population) # Se...
def _infer_dim_if_1d(arr, dim): """Helper function to get dim name of 1D arrays.""" if dim is None: if arr.ndim == 1: dim = arr.dims[0] else: raise ValueError("Dimension must be specified if array isn't 1D.") return dim def detrend(arr, dim=None, order=1): """Subt...
The main task of the code is to compute a detrended standardized anomaly time series by first standardizing the input array (centering and scaling) and then applying detrending to remove trends, using specified dimension and polynomial order. This process isolates anomalies by eliminating both trends and scaling variat...
def dt_std_anom(arr, dim=None, order=1): """Detrended standardized anomaly timeseries.""" dim = _infer_dim_if_1d(arr, dim) return detrend(standardize(arr, dim), dim=dim, order=order)
def _get_date_x(self, date: datetime.date) -> float: return (date - self.config.start) / \ (self.config.end - self.config.start) * \ self.width + self.Xmin def _get_track_y(self, track_num: int) -> float: return (1 - (self.caption_padding + self.track_height * track_num)) * \ ...
This function draws a timeline event as a colored rectangle with text, positioning it based on date ranges and track assignments. It calculates coordinates for the event's start/end dates and track position, then renders a box with the event name, using track-specific colors.
def _draw_event_period(self, event: Event) -> Tuple[Rectangle, Text]: start, end = event.time.date_intersection(self.config.start, self.config.end) track_num = self.tracks.index(event.get_track()) color = self.track_colors[track_num] lef...
def _get_date_x(self, date: datetime.date) -> float: return (date - self.config.start) / \ (self.config.end - self.config.start) * \ self.width + self.Xmin def _draw_date_impl(self, text: str, x: float, text_y_offset: float = 0.05, ymin: float = None, ymax: float ...
This function draws grid lines and date labels on a plot, placing them at regular intervals (defaulting to every 7 days or a power-of-two multiple). It adjusts for specified weekdays, calculates positions dynamically, and ensures labels remain within the plot's x-axis bounds by removing out-of-range text.
def draw_grid(self, weekday: int = None, period: int = None) -> None: if weekday is None: weekday = getattr(self.config, "weekday", 0) if period is None: period = (self.config.end - self.config.start).days // 28 period = (2 ** (period.bit_length() - 1)) * 7 ...