dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def shape(self): if len(self.bag) > 0: return self.bag.pop(0) else: self.bag = self.create_bag() return self.bag.pop(0) def __init__(self): self.bag = self.create_bag() self.current_block = TetrisBlock(5, 1, self.shape()) self.move_start_time =...
This function handles real-time keyboard and mouse inputs in a Tetris game. It processes arrow key presses for block movement/rotation, spacebar for hard drops, and 'C' for block holding/swapping. A 300ms delay prevents rapid inputs, while mouse clicks trigger game restarts. The code updates the current Tetris block's ...
def handle_input(self, event): keys = pygame.key.get_pressed() self.move_start_time = pygame.time.get_ticks() while not pygame.time.get_ticks() - self.move_start_time < 300: if keys[K_LEFT]: self.current_block.move_left() if keys[K_RIGHT]: ...
def check_collision(self, direction): check_left = dimensions[self.shape][0][self.rotation]+2 check_right = 10 - dimensions[self.shape][1][self.rotation] if direction == "v": if self.y >= 19: if self.shape != "I": self.y = 19 se...
This function moves a block down until it collides with the bottom or another block. It continuously checks for vertical collisions and block collisions, moving the block downward while no collision occurs. Once stopped, it writes the block's position, marks that the block has reached the bottom, and triggers the gener...
def hard_drop(self): while not self.check_collision("v") and not self.block_collision(): self.move_down() self.write_block() self.reached_bottom = True self.new_block = True
def move_down(self): if not self.check_collision("v") or not self.reached_bottom: if self.block_collision(): self.write_block() self.new_block = True else: for a in range(len(self.block_coords)): self.block_coords[a] = (...
This code updates an object's position by moving it in a specified direction after a set time interval, but only if the game is not over. It checks elapsed time using pygame's timer, triggers directional movement (down, right, or left), and resets the start time for future checks.
def update(self, time, direction="d"): if pygame.time.get_ticks() - self.start_time > time and not self.game_over: if direction == "d": self.move_down() elif direction == "r": self.move_right() elif direction == "l": self.move_l...
def handle_input(self, event): keys = pygame.key.get_pressed() self.move_start_time = pygame.time.get_ticks() while not pygame.time.get_ticks() - self.move_start_time < 300: if keys[K_LEFT]: self.current_block.move_left() if keys[K_RIGHT]: ...
This code runs a Tetris-like game loop using Pygame, handling user input, updating game state, rendering the board, blocks, and UI elements, checking for completed rows, and maintaining a 60 FPS frame rate. It continuously processes events, updates the current falling block, detects game over conditions, and redraws th...
def run(self): running = True while running: for event in pygame.event.get(): if event.type == QUIT: running = False self.handle_input(event) window.fill((0, 0, 0)) self.draw_board() self.draw_past_bloc...
def draw_title(data: List[Dict[str, str]]) -> str: for run_test in data: title = f'Test Runs for Plan {run_test["plan_id"]}:' title_line = f'{"─" * len(title)}' return f'{title}\n{title_line}\n\x00\n' def last_test_string(test: Dict[str, str]) -> str: end_connector = "└── " empty ...
The function generates a formatted help string for creating a TestRail plan JSON file. It reads input data from a JSON file, constructs a description with titles and test details, and appends run/test information with specific formatting for the last test in each run. The output includes structured text for TestRail pl...
def help_tr_create_plan_json() -> str: try: with ModuleDirFile(TR_PLAN_HELP_JSON, "r") as input_file: data = json.load(input_file) help_str = 'Create JSON help file for TestRail plan specified by option "--tr-plan-id"\n\x00\n' help_str = f'{help_str}{draw_title(data)}' ...
def get_testrail_keys(items): """Return Tuple of Pytest nodes and TestRail ids from pytests markers""" testcaseids = [] for item in items: if item.get_closest_marker(TESTRAIL_PREFIX): testcaseids.append( ( item, clean_test_ids( ...
The code modifies pytest test collection by filtering tests based on TestRail case IDs linked to a test plan or run. It creates JSON files for test plans/runs, skips tests not in the specified run, and generates a new test run if no existing one is provided, using parameters like project, suite, and milestone IDs.
def pytest_collection_modifyitems(self, session, config, items): items_with_tr_keys = get_testrail_keys(items) tr_keys = [case_id for item in items_with_tr_keys for case_id in item[1]] if self.create_extended_help: self.create_plans_json(session, config, items) if self.test...
def get_rgb_data(): # img = Image.open('shiba.jpg') # img_object = img.load() # img_width, img_height = img.size # pixel_values = list(img.getdata()) # uint8 contains numbers between 0 to 255, useful for colors rgb_data = list(img.getdata()) # print(rgb_data) # create image from a...
The code performs image recoloring using k-means clustering and nearest neighbor matching. It splits an image into training (left half) and test (right half) regions, clusters RGB data, then for each test pixel, identifies similar 3x3 patches in the training data to determine the majority color, reconstructing the righ...
def basic_agent(): rgb_data = get_rgb_data() gray_data = get_grayscale_data() clusters, centers = k_means(rgb_data) # convert dict to list centers_list = [] for key, value in centers.items(): temp = value centers_list.append(temp) print("centers: ", centers_list) recolo...
def get_rgb_data(): # img = Image.open('shiba.jpg') # img_object = img.load() # img_width, img_height = img.size # pixel_values = list(img.getdata()) # uint8 contains numbers between 0 to 255, useful for colors rgb_data = list(img.getdata()) # print(rgb_data) # create image from a...
The code performs image clustering using k-means on RGB data, splits the image into training and test sets, and processes the test set in parallel via six threads. Each thread uses the trained model (from the training set) to recolor the test data, combining results to produce a final output. The main task is paralleli...
def basic_agent_threaded(): rgb_data = get_rgb_data() gray_data = get_grayscale_data() clusters, centers = k_means(rgb_data) # convert dict to list centers_list = [] for key, value in centers.items(): temp = value centers_list.append(temp) print("centers: ", centers_list) ...
def create_psuedo_B(sizes, path_to_slits, slits_sorted, std_B=50): """ If you don't have an inverted magnetic field, create a psuedo-B from a sum over signed circular polarization of second 6302 wing - works fairly well for QS datasets, need to che...
The main task of the code is to align Hinode magnetic field data with CSAC slit data by performing an initial rough alignment and a final parameter optimization. It processes slit files, fetches HMI data, minimizes alignment parameters, checks convergence, visualizes results, and optionally saves HPC coordinates and fi...
def run(path_to_slits, hinode_B, bounds=None, path_to_sunpy='/Users/jamescrowley/sunpy/', plot=True, save_coords=False, save_params=False, verbose=True): """ Run: I want this to be the funciton which calls all the others to run the alignment, almos...
def setup_axes(self): axes = Axes(**self.axes_config) axes.center().to_edge(UP) y_label = axes.get_y_axis_label("\\text{Temperature}") y_label.to_edge(UP) axes.y_axis.label = y_label axes.y_axis.add(y_label) axes.y_axis.add_numbers(*self.y_labels) self.a...
This code defines a `construct` method that initializes and displays components of a visual simulation. It sets up coordinate axes, a graph, and a clock, then renders rods and an equilibration process. The primary task is to construct a dynamic visual scene, likely for educational or illustrative purposes, combining gr...
def construct(self): self.setup_axes() self.setup_graph() self.setup_clock() self.show_rods() self.show_equilibration()
def timeinsecs(self): reference_time = self.do_movingaverage()[0][0, 0] #print('Try to put the date as human reading', reference_time) axistoplot = [(x - reference_time) *1e-4 for x in self._getAxis()[0]] return axistoplot def _getAxis(self): xaxis = [item[self.IDxaxis] for item ...
This code generates a line plot comparing two data series over time. It plots the raw data from self._getAxis()[1] and a low-pass filtered version from self._butterlowfilter() against time in seconds. Axis labels are set using self.AXISNAMES_LST, then displays the plot.
def _dolinePlot(self): plt.plot(self.timeinsecs(),self._getAxis()[1]) plt.plot(self.timeinsecs(),self._butterlowfilter()) plt.xlabel(str(self.AXISNAMES_LST[0])) plt.ylabel(str(self.AXISNAMES_LST[1])) plt.show() return
def findHcools(self): values_filelst = [] for strings in self.dict_files().keys(): lst_numberStr = re.findall(r'[*+-]?\d+\.\d+', strings) values_filelst.append(float(lst_numberStr[0])) return values_filelst def _getAxis(self): xaxis = [item[self.IDxaxis] for item ...
The main task of the code is to generate a scatter plot visualizing two datasets against "Hcools [T]" on the x-axis. It plots self.findHcools() against self._getAxis()[1] and self._butterlowfilter() as two separate scatter series, labels the axes, and displays the plot. The function serves to compare or contrast the tw...
def _doscatterplot(self): plt.scatter(self.findHcools(), self._getAxis()[1]) plt.scatter(self.findHcools(), self._butterlowfilter()) plt.xlabel('Hcools [T]') plt.ylabel(self.AXISNAMES_LST[1]) plt.show() return
def handlecurrentchannel(i): currentpattern = FILESTUB.format("current", i) return handlechannel(currentpattern) def makemsg(status): if status == 1: return "no iio files found" elif status == 2: return "can't open iio file" elif status == 3: return "iio file is not csv" ...
The function `chart()` collects current and voltage data from multiple channels by iterating through each channel, retrieves values and history, checks for errors, and renders a chart template with aggregated data if successful. It initializes lists, processes each channel's status, and compiles readings for the templa...
def chart(): currenthistory = [] voltagehistory = [] current = [] voltage = [] val = [] history = [] for i in range(NUMCHANNELS): status, val, history = handlecurrentchannel(i) if status != 0: return render_template("waiting.html", msg=makemsg(status)) cu...
def handlecurrentchannel(i): currentpattern = FILESTUB.format("current", i) return handlechannel(currentpattern) def handlevoltagechannel(i): voltagepattern = FILESTUB.format("voltage", i) return handlechannel(voltagepattern) def makereadings(current, currenthistory, voltage, voltagehistory): readin...
The main task of the code is to read current and voltage data from multiple channels, check for errors during data retrieval, and compile the results into a JSON response. It iterates through each channel, retrieves current and voltage values along with their histories, validates the status, and aggregates the data. If...
def _refresh(): currenthistory = [] voltagehistory = [] current = [] voltage = [] val = [] history = [] for i in range(NUMCHANNELS): status, val, history = handlecurrentchannel(i) if status != 0: return jsonify(readings="error: {}".format(status)) current...
def get_sample_database(): """ Read sample feature vector from database """ global db_connection sample_vectors = [] if db_connection is None: res = set_db_connection() if not res: return None cur = db_connection.cursor() cur.execute('SELECT * FROM sampl...
The main task of the code is to compare input face feature vectors against a sample database, calculate similarity distances, identify the closest matching known faces (if above a threshold), and return candidate matches. If no match is found, it registers the face as unknown, adds it to the database, and returns the u...
def find_face(face_feature_vectors, min_simulation): """ Find the closest sample by comparing the feature vectors """ # Read sample database sample_vectors = get_sample_database() if sample_vectors is None: return GET_SAMPLE_VECTOR_ERR, None candidates = [] for vector_data in f...
def detect_faces(img): """ Detect the faces from the base image """ global model if model is None: load_model() if isinstance(img, str): if len(img) == 0: return None, None elif len(img) > 11 and img[0:11] == "data:image/": img = load_image(img) ...
The code processes an image to detect faces, extracts their features in batches, maps features to bounding boxes, and identifies candidate matches by comparing feature vectors against samples with a minimum distance threshold, returning results or errors accordingly.
def process_image(img, min_distance): """ Face recognition """ # Detect the faces from the image that is dedicated in the path or bytes try: base_img, faces = detect_faces(img) except: return FACE_DETECTION_ERR, None if len(faces) == 0: return NO_FACE_DETECTED_ERR, N...
def add_image(walls, image_data): scale, x, y, z, times = image_data thickness = 0.01 model0 = load_image(times[0][1]) ti = times[0][0] tf = times[-1][0] for i in range(len(model0)): start = ti - 1 + i / len(model0) end = tf + i / len(model0) positions = [] rot...
The main task of the code is to modify song data files by injecting predefined obstacles ("walls") and events into JSON structures. It reads each file, appends static wall/event data, truncates the modified JSON, and writes it back, while preserving original metadata via a file copy operation.
def main(): # NO Lights off events = [{"_time": 0, "_type": i, "_value": 0} for i in range(5)] walls = [] for model in MODELS: add_image(walls, model) add_main_title(walls) add_end_title(walls) walls.sort(key=lambda x: x["_time"]) # Prevent MM from overwriting info.dat sh...
def process_passport_lines(raw_file_input): blobs = re.compile(r'\n{2,}').split(raw_file_input) processed_blobs = [re.compile(r'\s+').split(blob) for blob in blobs] return [build_passport(blob) for blob in processed_blobs] def is_passport_valid_1(passport): for key in passport: if passport[key][...
The code reads passport data from 'input.txt', processes it into individual passports, validates each using two criteria (is_passport_valid_1 and is_passport_valid_2), and prints the total number of valid passports for each validation method.
def main(): with open('input.txt', 'r') as file: raw_passport_input = file.read() passports = process_passport_lines(raw_passport_input) print(sum(is_passport_valid_1(ppt) for ppt in passports)) print(sum(is_passport_valid_2(ppt) for ppt in passports))
def CheckExist(self, position): return 0 <= position[0] < self.height and 0 <= position[1] < self.width def CheckWumpus(self, position): # Check in KB, has Agent already known that room doesn't have wumpus if self.CheckExist(position) == False: return False if not self.wumpus...
This function determines if a given position in the Wumpus world is safe by checking if it contains a Wumpus, a pit, or is non-existent. If any of these conditions are true, the position is unsafe (returns False); otherwise, it is safe (returns True).
def CheckSafe(self, position): # Use resolution # For every x, y: Not Exist(x, y) Or Wumpus(x, y) Or PIT(x, y) Or Safe(x, y) From KB # Not Safe(position) if not self.CheckExist(position) or self.CheckWumpus(position) or self.CheckPIT(position): return False return Tru...
def CheckWumpus(self, position): # Check in KB, has Agent already known that room doesn't have wumpus if self.CheckExist(position) == False: return False if not self.wumpus[position[0]][position[1]]: return False # Use 4 first logic order in KB # For ever...
This function calculates the probability or risk value of a given position in a maze based on adjacent cells. If `model == 0`, it sums the presence of Wumpus in neighboring cells. If `model == 1`, it recursively determines the minimum probability by checking non-empty adjacent cells and their recursive probabilities, r...
def CalProbility(self, position, model): if model == 0: count = 0 for i in range(4): count += self.CheckWumpus((position[0] + self.direction[i][0], position[1] + self.direction[i][1])) return count else: count = 4 for i in range...
def CheckExist(self, position): return 0 <= position[0] < self.height and 0 <= position[1] < self.width def CheckWumpus(self, position): # Check in KB, has Agent already known that room doesn't have wumpus if self.CheckExist(position) == False: return False if not self.wumpus...
The code performs a BFS traversal to locate the Wumpus in a maze. It tracks visited positions, evaluates cell contents, and calculates a "price" for shooting based on depth and probability. When a Wumpus is detected, it updates the optimal goal position and returns the best starting point for shooting, prioritizing hig...
def FindWumpus(self): q = queue.Queue() q.put(self.pos) visited = set() visited.add(self.pos) count = [1, 0] level = 0 goal, wumpus_pos = self.pos, (-1, -1) price = -10**18 while not q.empty(): position = q.get() count[0] -=...
def FindPath(self): q = queue.Queue() q.put(self.pos) visited = set() visited.add(self.pos) count = [1, 0] level = 0 goal = self.pos deep = 10000 while not q.empty(): posititon = q.get() count[0] -= 1 for i in ra...
This method determines the next action for an agent in a maze by prioritizing: 1) executing remaining commands, 2) taking gold if present, 3) finding safe paths, 4) hunting wumpus to create new paths, and finally 5) climbing up if no other options exist. It manages movement commands, pathfinding, and wumpus interaction...
def GetActions(self): self.command.pop() # If still have command, just do it if len(self.command): return self.command[-1] if self.gold in self.maze[self.pos[0]][self.pos[1]]: self.command.append('TAKE GOLD') return self.command[-1] # Find the...
def preprocessing(old_quakes_df): """Collecting data from Geonet and finding out if there are any new earthquakes to add to the list.""" quake_df = import_data("quake?MMI=5") filtered_quake_df = \ extract_data(quake_df, 'properties.publicID','geometry.coordinates') updated_quakes_df = compa...
The main task of the code is to process earthquake data by reading a CSV file, preprocessing it to identify new entries, updating the dataset if new quakes are found, and generating a final ArcGIS-compatible CSV file. It checks for new data, resets indices, and collates results for output.
def main(): """The main function.""" old_quakes_df = pd.read_csv("list of quakes.csv") updated_quakes_df = preprocessing(old_quakes_df) if len(updated_quakes_df) == 0: print("There are no new quakes to add.") else: print("Please wait while the new data is collected and processed.") ...
def S(x): return 1.0/(1.0+np.exp(-x)) def extract_submatrices(WB): submatrices=[]; K=0 for i in range(0, len(layers)-1): # form relevant sub-matrix for layer N Nrow=layers[i+1]; Ncol=layers[i] # + 1 w=np.array(WB[K:K+Nrow*Ncol].reshape(Ncol,Nrow).T) # unpack /W K=K+Nrow*Ncol; # ...
The function evaluates a model (linear, logistic regression, or ANN) based on `model_type`. For linear/logistic models, it computes a weighted sum of inputs `x` and parameters `p`, applying a sigmoid function for logistic. For ANN, it processes `p` into submatrices and evaluates the neural network. The output depends o...
def model(x, p): if(model_type == "linear" or model_type == "logistic"): out = p[0] + np.matmul(x, p[1:].reshape(NFIT-1, 1)) if(model_type == "logistic"): out = S(out) return out if model_type == 'ANN': submatrices = extract_submatrices(p) return NN_eval(x, submatrices)
def transpose(self, mx): """Transpose a matrix, a list with lists""" # print("transpose",mx) mx_w, mx_h = len(mx[0]), len(mx) transResult = [[0] * mx_h for i in range(mx_w)] for a in range(mx_h): for b in range(mx_w): transResult[b][a] = mx[a][b] ...
The main task of the code is to move and merge cells in a grid based on the specified direction. It applies transformations like transposing or mirroring to align the grid for merging, processes rows to combine equal-value cells, then reverses transformations to restore the original orientation, returning the updated g...
def move_cells(self, dir): """Move all cells in the indicated direction and merge equally valued cells""" if dir not in self.dir_transp.keys(): return temp_sqrs = self.squares # in case of up or down, transpose if self.dir_transp[dir][0] == -1: temp_sqrs =...
def size(self, cid): direct_cluster_sizes = self._obj.loc[self._obj['cluster_id'] == cid]['cluster_size'].unique() if direct_cluster_sizes.any(): return max(direct_cluster_sizes) children = self.children(cid) return sum([self.size(child_id) for child_id in children]) def chi...
This code converts a node into a hierarchical dictionary representation, including its ID, size, and recursively its child nodes. It constructs a nested structure where each node contains its ID, size, and a list of child nodes processed similarly.
def to_dict(self, cid): node = { # 'name': '\n'.join(self.keywords(cid)), 'ID': int(cid), 'size': int(self.size(cid)) } children = self.children(cid) if children: node['children'] = [self.to_dict(child) for child in children] retur...
def verificareSahuriPinuri(self): pinuri = [] # sahuri = [] # inSah = False if self.MutareAlb: culoareOponent = 'n' culoareRege = 'a' regeRand = self.LocatieRegeAlb[0] regeCol = self.LocatieRegeAlb[1] else: culoareOpon...
The code validates possible chess moves by checking if the king is in check, filtering moves that leave the king in check, and determining checkmate or stalemate if no valid moves remain. It considers the type of attacking piece, generates safe squares for the king, and removes invalid moves. If multiple checks exist, ...
def MutariValide(self): mutari = [] self.inSah, self.pin, self.sahuri = self.verificareSahuriPinuri() if self.MutareAlb: randRege = self.LocatieRegeAlb[0] colRege = self.LocatieRegeAlb[1] else: randRege = self.LocatieRegeNegru[0] colRege =...
def EndRound(self,game_state): self.center_token = True self._DisplayState(game_state) self._InsertState("--------------End of round-------------",game_state) for i,plr_state in enumerate(game_state.agents): self._InsertState("Current score for Agent {}: {}".format(i,plr_stat...
This code processes a player's move in a game, updating the game state by handling actions like ending/start rounds, moving tokens to pattern/floor lines, managing the center token, and updating the factory. It applies movement logic, modifies the player's board, logs the action, and introduces a delay to control game ...
def ExcuteAction(self,player_id,move, game_state): if move == "ENDROUND": self.EndRound(game_state) elif move == "STARTROUND": self.StartRound(game_state) else: movement = move[2] #print(movement.num_to_pattern_line) if movement.num_to_...
def keep_card(window1): global CARDS_FLIPPED global CURR_PLAYER global CARDS global CARD_ORDER global NUM_CARDS_TAKEN user_input_box.delete('1.0', 'end') # player can keep the card (because they have the other 2 cards with the same value) if CARDS[CARD_ORDER[CARDS_FLIPPED[0]]][0] in PLAY...
This code creates a GUI window for a game decision after the first card flip, displaying instructions and three options: keeping the card, stealing another player's set, or proceeding to the next card. It initializes buttons linked to functions for each action, allowing the player to choose their next move.
def decision_after_first_card_flip(num): window1 = Toplevel(root, bd=20) window1.geometry("700x500") window1.title("Decision after 1st Card Flip") text_instructions = Text(window1, height=4, width=70, font=font_tuple) text_instructions.insert('end', "Do you wish to keep this card (if you have the ot...
def decision_after_first_card_flip(num): window1 = Toplevel(root, bd=20) window1.geometry("700x500") window1.title("Decision after 1st Card Flip") text_instructions = Text(window1, height=4, width=70, font=font_tuple) text_instructions.insert('end', "Do you wish to keep this card (if you have the ot...
This function handles card interactions in a matching game. It displays a card's face value, disables further clicks to prevent errors, and checks if flipped cards form a valid set. If the first card is clicked, it triggers a decision function. For the second card, it verifies a match; if successful, it awards points a...
def show_card_when_clicked(num): global buttons global CARD_ORDER global CARDS_FLIPPED global CURR_PLAYER global POINTS global NUM_CARDS_TAKEN # show the face value of the card buttons[num].config(image=card_images[CARD_ORDER[num]]) # prevent user from double-clicking a card or click...
def __get_koordinat_agen(self, no_lokasi): return (self.__lingkungan.get_lokasi()[no_lokasi - 1][0], self.__lingkungan.get_lokasi()[no_lokasi - 1][1]) def __cek_lokasi_bersih(self): flag = True for lokasi in self.__lingkungan.get_lokasi(): if lokasi[2] == 1: flag = Fa...
This code implements an agent's movement algorithm to navigate towards and clean the nearest dirty location in its environment. The agent continuously checks for dirty spots, calculates distances to the closest one, and moves in the required direction (up/down/left/right) to reach it. It repeats this process until the ...
def __alg_agen_cerdas(self): sec = 3 time.sleep(5) lokasi_kotor = [] target_terdekat = None while (True): koordinat_agen = self.__get_koordinat_agen(self.__no_lokasi_agen) x, y = koordinat_agen jarak_kotor_terdekat = float("inf") if...
def check_args(in_file_list,in_file,oligos,aligner,indel,mode,clean_up): def check_whitespaces(input): if os.path.exists(input): with open(input,"r") as file: for line in file: if re.search(" ",line.rstrip()): return "whitespace" ...
The main task of the code is to process sequencing data in different modes (demultiplex, consensus, all, consensus_batch) by validating inputs, converting file paths, and executing corresponding operations: demultiplexing samples using oligos, generating consensus sequences from reads, or handling batch processing. It ...
def main(_args): #Check possible errors in the supplied arguments check_args(_args.in_file_list,_args.in_file,_args.oligos,_args.aligner,_args.indel,_args.mode,_args.clean_up) # call function based on batch or single mode #Convert to full paths if _args.in_file: _args.in_file = convert_to_...
def heap_sort(heap): #heap of a single ward # Initializing the capacity of the heap. capacity = len(heap) # Sorting through all the patients in the heap according to the emergency number. for i in range(len(heap)): if heap[i]!=None: # Element is a patient and not an empty bed. # Col...
This function updates a patient's information in a heap structure. If the patient's ward remains unchanged, it locates and replaces their entry, then sorts the heap. If the ward changes, it removes the old entry and inserts the new one. The heap is returned with updated patient data, maintaining sorted order for each w...
def modify(heap,tup, old_Ward): # Collecting ward from patient tuple containing (Emergency Number, ward, key). ward=tup[1] # Collecting patient ID from patient tuple containing (Emergency Number, ward, key). key=tup[2] # Locating and updating the patient emergency Number from the heap. if old_...
def _open_file(self, file=None): if self.changes: yes = askyesno(title="Unsaved changes", message="There are unsaved changes in the current file. Do you " "want to open a new file anyway (changes are lost)?") if not yes: ...
This code initializes a GUI application for managing a list of questions, setting up a Tkinter window with keyboard shortcuts for file operations (open/save) and question navigation. It creates a dummy question, binds event handlers, and prepares for file interaction. The GUI elements are initialized via _init_setup(),...
def __init__(self, file=None): # always create one dummy question at startup so self._init_setup creates all # necessary GUI elements self.questions: list[Question] = [QuestionCreator.create_new_question()] self.cqi: int = 0 # current question index self.file = file self...
def createUs(self, state, action): errs = np.zeros(4) errs[0] = action[0] - state[11] errs[1] = action[1] - state[6] errs[2] = action[2] - state[7] errs[3] = 0 - state[8] u = np.zeros(4) bsZerr = self.zSet - state[11] u[0] = self.altController.updateContr...
The code executes one time step in a drone simulation environment by processing the RL agent's action, adjusting it via sigmoid activation and scaling, applying it to update the drone's state through numerical integration, checking termination conditions, calculating reward, and returning the next state, reward, done f...
def step(self, action): # Execute one time step within the environment #This is where we're accepting the action requirements from the RL agent #Right now since we're producing sigmoid outputs, we're modifying the inputs accordingly #Action[0] = z target (in meters? Currently unused) ...
def poly1305_key_generation(key, nonce): ctr = 0 block = chacha20_block(key, ctr, nonce) return block[0:32] def chacha20_encrypt(key, counter, nonce, plaintext): encrypted_message = b'' for j in range(0,math.floor(len(plaintext) / 64)): key_stream = chacha20_block(key, counter+j, nonce) ...
This function performs authenticated encryption using ChaCha20 and Poly1305. It generates a one-time key from the message key and nonce, encrypts plaintext with ChaCha20, combines authentication data with ciphertext, computes a Poly1305 tag, and returns encrypted data along with the authentication tag for secure commun...
def chacha20_aead_encrypt(ad, k_m, k_c, nonce, plaintext): #if the nonce is not 96 bits, it should be concatenating with a constant to become 96 bits #This code assume the nonce is 96 bits as specified in RFC8439 one_time_key = poly1305_key_generation(k_m, nonce) ciphertext = chacha20_encrypt(k_c, 1, n...
def poly1305_key_generation(key, nonce): ctr = 0 block = chacha20_block(key, ctr, nonce) return block[0:32] def chacha20_encrypt(key, counter, nonce, plaintext): encrypted_message = b'' for j in range(0,math.floor(len(plaintext) / 64)): key_stream = chacha20_block(key, counter+j, nonce) ...
The function decrypts ciphertext using ChaCha20 with key `k_c` and nonce, generating plaintext. It also creates a Poly1305 MAC tag using a one-time key derived from `k_m` and nonce, along with concatenated additional data (AD) and ciphertext. The result is a tuple containing the decrypted plaintext and the authenticati...
def chacha20_aead_decrypt(ad, k_m, k_c, nonce, ciphertext): one_time_key = poly1305_key_generation(k_m, nonce) plaintext = chacha20_encrypt(k_c, 1, nonce, ciphertext) mac_data = concatenate_mac_data(ad, ciphertext) tag = poly1305_mac(mac_data, one_time_key) return (plaintext, tag)
def poly1305_key_generation(key, nonce): ctr = 0 block = chacha20_block(key, ctr, nonce) return block[0:32] def concatenate_mac_data(ad, ciphertext): mac_data = ad + pad16(ad) mac_data += ciphertext + pad16(ciphertext) mac_data += convert_to_8_bytes_little_endian(len(ad)) mac_data += convert...
The function verifies a message using the Poly1305 message authentication code (MAC) algorithm. It generates a one-time key from the provided key material (k_m) and nonce, concatenates associated data (ad) with ciphertext, computes the MAC tag using the key, and returns the tag for verification.
def poly1305_verify_message(ad, k_m, nonce, ciphertext): one_time_key = poly1305_key_generation(k_m, nonce) mac_data = concatenate_mac_data(ad, ciphertext) tag = poly1305_mac(mac_data, one_time_key) return tag
def win(self): """ This method is to function the condition that the player won. """ x = 0 y = 0 path = "src/winner.gif" # pop up the winner.gif window self.draw_image(x=x, y=y, path=path) self.to_leaderboard(self.name) # after 2 seconds, end the o...
This method evaluates the player's guess by checking if they've won, lost, or should proceed to the next round. It uses the last guess to determine the result, triggers win/lose states if applicable, and advances the game round by resetting selections and incrementing the round count if the game continues.
def click_check_button(self): """ This method is to handle the action of clicking check button. If the players win, if will return a True. The check button has 3 situations. 1. Win: Call the function self.win(). 2. Loss: Call the function ...
def click_quit_button(self) -> None: """ This method is to handle the action of clicking the quit button. """ # pop up the quit.gif window x = 0 y = 0 path = "src/quitmsg.gif" self.draw_image(x=x, y=y, path=path) # after 2 seconds, close the screen...
This method processes user clicks to handle game interactions: it detects clicks on the quit button, adds/cancels color selections based on the number of selected colors (≤4 or exactly 4), and triggers actions like selecting colors, canceling choices, or checking selections. It uses coordinate checks to determine which...
def click(self, x: int, y: int) -> None: """ This method is to set the click's reaction Args: x (int): the x-coordinate of one clicking y (int): the y-coordinate of one clicking """ if ((( # click the quit button self.quit_button_coordinate['x'] - ...
def game_status(current_player): """ Checks if the current player has won the game or the game is a draw. Args: current_player (str): a string representing the current player which is either 'X' or 'O' Returns: bool: False if the current player has won the game or the game is a draw, T...
The function `play_game` manages a tic-tac-toe game loop, handling human and computer player turns. It processes mouse inputs for human moves, triggers AI moves with a delay, updates the game board, checks win/draw conditions, and renders the board using Pygame. The loop continues until the game ends or the user quits,...
def play_game(player1_type, player2_type, computer_delay=0): """ Handles the main game loop. Args: player1_type (str): A string representing the type of player 1 which is either 'human' or 'computer' player2_type (str): A string representing the type of player 2 which is either 'human' or '...
def read_lines(filename): #if windows #return open(filename, encoding="utf8").read().split('\n')[:-1] return open(filename, encoding="utf8").read().split('\n')[:-1] def filter_line(line, whitelist): return ''.join([ ch for ch in line if ch in whitelist ]) def filter_data(sequences, limit): filtered...
The main task of the code is to preprocess text data by reading, filtering, tokenizing, and saving question-answer pairs for machine learning. It applies lowercasing, removes non-alphanumeric characters, enforces length constraints, tokenizes into words/characters, and integrates pretrained embeddings (GloVe, Word2Vec)...
def process_data(): #set the random seed limit = { 'maxq' : 20, 'minq' : 0, 'maxa' : 20, 'mina' : 1 } print('\n>> Read lines from file') lines = read_lines(filename=FILENAME) # change to lower case (just for en) lines = [ line.lower(...
def generate_date(): current_time = datetime.utcnow().replace(second=0, microsecond=0) - timedelta(minutes=10) state = StateManager(connection_string=connection_string) past_time = state.get() # past_time = None if past_time is not None: logging.info("The last time point is: {}".format(past_...
The main task of the code is to authenticate with a server, retrieve event data (aggregated, raw, policy audits, and details) from multiple sets over a specified time period, categorize the events, and send them via a data collector API using `gen_chunks`. It handles authentication errors, logs processing steps, and ag...
def main(mytimer: func.TimerRequest) -> None: if mytimer.past_due: logging.info('The timer is past due!') logging.getLogger().setLevel(logging.INFO) logging.info('Starting program') start_time, end_time = generate_date() logging.info('Data processing. Period(UTC): {} - {}'.format(start_time,...
def process_data(data_file, label_file, pool): label, sample_num = load_label(label_file) data = load_sample(data_file, sample_num, pool) new_data=[] for i in range(len(data)): new_data.append(data[i].flatten()) idx = np.random.shuffle(np.arange(int(len(new_data)))) return np.squeeze(np....
The main task of the code is to train a model on incremental portions of a facial dataset, evaluate its test accuracy and training time for each portion, and visualize the results. It loads training/test data, divides the training data into 10 segments, trains the model iteratively on each segment, predicts labels, cal...
def main(): pool = 3 train = "../data/facedata/facedatatrain" train_label = "../data/facedata/facedatatrainlabels" test = "../data/facedata/facedatatest" test_label = "../data/facedata/facedatatestlabels" x_train, y_train = process_data(train, train_label, pool) x_test, y_test = process_data...
def process_data(data_file, label_file): label, sample_num = load_label(label_file) data = load_sample(data_file, sample_num) label = one_hot(label) new_data=[] for i in range(len(data)): new_data.append(data[i].flatten()) idx = np.random.shuffle(np.arange(int(len(new_data)))) return...
The code processes digit image data, trains a model incrementally on subsets of the training set, evaluates accuracy on the test set, records training time and test accuracy for each subset, and plots the results. It divides training data into 10 parts, trains on increasing portions, and measures performance metrics fo...
def main(): train = "../data/digitdata/trainingimages" train_label = "../data/digitdata/traininglabels" test = "../data/digitdata/testimages" test_label = "../data/digitdata/testlabels" x_train, y_train = process_data(train, train_label) x_test, y_test = process_data(test, test_label) amount...
def getLeader(i): if (parent[i] == i): return i else: parent[i] = getLeader(parent[i]) # stores the result in the parent list so that same parameter calls are faster return parent[i] def turnAroundPoint(screen,img,pointX,pointY,radius,degreeFromPoint,i): global resultingX,resultin...
This function manages fish movement and behavior on a screen, including turning, boundary collision handling, leader-follower dynamics, and predator attacks. It updates fish positions, rotates images, handles dead fish by displaying skeletons and removing them, and controls predator movement toward randomly selected ta...
def moveFish(screen): global fishImages,currentDegree,turnEnd,fishX,fishY,turnCentreX,turnCentreY,resultingX,resultingY,predatorX,predatorY global turning,turnDirection,degreeChanged,nextTurn,turnDegree,deltaX,deltaY,underAttack,lastAttack,fishToAttack,predatorDegree global fishAttacked,numberOfFish # ...
def getLeader(i): if (i >= numberOfFish): print(numberOfFish) for j in range(numberOfFish): print(fishDeathTime[j],end = " ") print() if (parent[i] == i): return i else: parent[i] = getLeader(parent[i]) # stores the result in the parent list so that sam...
The code simulates fish movement on a screen, handling turning, following leaders, and death animations. It manages predator attacks by chasing and killing target fish, updating positions, and removing dead fish. Fish rotate, move, and turn around points, while predators track targets, initiating attacks periodically. ...
def moveFish(screen): global fishImages,currentDegree,turnEnd,fishX,fishY,turnCentreX,turnCentreY,resultingX,resultingY,predatorX,predatorY global turning,turnDirection,degreeChanged,nextTurn,turnDegree,deltaX,deltaY,underAttack,lastAttack,fishToAttack,predatorDegree global fishAttacked,numberOfFish ...
def no_space(s: str) -> str: result = "" for i in s: if i != " ": result += i return result def solve(e: str,main: str,other: str,mode = 0): eq = no_space(e) + " " y = 0 n = 0 x = 0 fase = 1 for l in range(len(eq)): if eq[l] == main: g = floa...
The code solves a system of two algebraic equations derived from `line1` and `line2` to compute values for variables `x` and `y`. It processes the input strings to isolate and solve for `x` first, then constructs a new equation using the solved `x` to determine `y`, returning the pair `(x, y)`. The core task involves p...
def fv5(line1: str, line2: str) -> tuple: l1 = no_space(solve(line1,"y","x")) #print(l1) l2 = no_space(solve(line2,"y","x")) #print(l2) l1 = l1[2::] l2 = l2[2::] #print(l1) #print(l2) s = l1 + "=" + l2 x = solve(s,"x","y",1) #print(s) #print(x) s = "" l1 += " " ...
def get_pos(self, pos : str) -> list: result = [int(pos[1])-1,-1] for i in range(8): if pos[0] == self.__files[i]: result[1] = i return result def get_rook_move(self, pos : str or list, board : list = __board) -> list: pos = self.get_pos(pos) if type(pos) is s...
This function calculates all valid queen moves on a chessboard by combining rook-like straight-line moves and bishop-like diagonal moves. It accepts a position as a string or list, converts it to a standardized format, then merges results from rook and bishop movement functions to return all possible queen moves from t...
def get_queen_move(self, pos : str or list, board : list = __board) -> list: pos = self.get_pos(pos) if type(pos) is str else pos return self.get_rook_move(pos, board) + self.get_bishop_move(pos, board)
def get_pos(self, pos : str) -> list: result = [int(pos[1])-1,-1] for i in range(8): if pos[0] == self.__files[i]: result[1] = i return result def get_rook_move(self, pos : str or list, board : list = __board) -> list: pos = self.get_pos(pos) if type(pos) is s...
The function checks if a given position is under attack by counting opposing pieces (rook, bishop, knight, pawn) that can attack it, returning the count to determine if the king is in check.
def is_check(self, pos : str or list, king_color : str, board : list = __board) -> bool: pos = self.get_pos(pos) if type(pos) is str else pos colors = ['w','b'] index = colors.index(king_color) counter = 0 mylist = self.get_rook_move(pos, board) for i in mylist: ...
def is_legal_move(self, move : str, turn : str = __turn, board : list = __board) -> bool: colors = ['w','b'] index = colors.index(turn) if move == '0-0': #Finds short castling rank = 7 if index else 0 if board[rank][5] != '0' or board[rank][6] != '0': ...
This function executes a chess move if legal, handling special cases like castling (list of moves) and promotion (tuple with piece upgrade). It translates move notation, updates the board state via __play(), and returns True for valid moves, False otherwise.
def go_for(self, move : str, turn : str = __turn, board : list = __board) -> None: if self.is_legal_move(move, turn, board): move = self.translate_specials(move, turn) if type(move) is list: #Handles castling for i in move: self.__play(i, board) ...
def pos_to_str(self, pos : list) -> str: return self.__files[pos[1]] + str(pos[0] + 1) def get_king_move(self, pos : str or list, board : list = __board) -> list: pos = self.get_pos(pos) if type(pos) is str else pos result = [] temp_pos = list(pos) temp_pos[0] += 1 if s...
This function generates all legal moves for the current player's pieces on a chessboard. It iterates through each piece of the specified turn, determines valid moves based on piece type (king, queen, etc.), appends move strings to a list, then filters out illegal moves using is_legal_move(), returning the final list of...
def find_all_moves(self, turn : str = __turn, board : list = __board) -> list: moves = ["0-0", "0-0-0"] for i in range(8): for l in range(8): j = board[i][l] if j[0] != turn: continue pos = self.pos_to_str([i,l]) ...
def _process_manual_data(self, manual_data): """ Processes the manually labeled data for model training and evaluation by identifying neighbouring POIs and labeling them as either duplicates or not duplicates. :param manual_data: GeoDataFrame Contains the manually labeled da...
The main task of the code is to train and evaluate machine learning models (Gradient Boosting, Random Forest, XGBoost) for detecting duplicated POIs using manually labeled data, with class balancing, feature processing, and saving the best-performing model based on specified algorithm preferences.
def train_model(self): """ This function performs model training for identifying duplicated POIs between different data sources. """ # load manually labeled data print('Loading manually labeled data for model training...') manual_data = pd.read_csv(os.path.join(os...
def find_patches_hough(table_image, is_left: bool, show_intermediate_results=False) -> [Patch]: """ This function finds the 'X' in the table using the following steps: 1. split the image into the left or the right part 2. convert the image to grayscale 3. find the edges of the image using Canny (th...
The function detects the position of 'X' marks in a table from an image, comparing detected positions against ground truth coordinates. It uses either Hough transform or template matching to locate patches, classifies them, and calculates accuracy by averaging left and right side detection scores. The result is the ove...
def solve_image(image_path: str, gt_path: str, use_hough: bool = True, show_intermediate_results: bool = False) -> float: """ This function 'reads' the 'X' from the table and return the accuracy of detecting the correct position of 'X'. :param image_path. The path to the image that will be solved. :para...
def padding_util(order_max, acc): """Helper function returns number of nodes to pad at each boundary; defined by the width of FD stencils""" return int(math.ceil((acc + order_max)/2)+1) def ApplyFindiff(u, dx, d, acc): """ Takes dth derivative of data using the findiff module. :param u: 1D-data vec...
The function constructs a linear system matrix `Theta` for sparse regression using finite difference approximations of spatial and temporal derivatives from grid data `u`. It combines derivative terms (up to order `D`) with polynomial powers of `u` (up to order `P`), applies padding to mitigate edge effects, and includ...
def build_linear_system_FD(u, dt, dx, D=3, P=3, order_combinations=None, high_order_time_derivs=0, acc_space=8, acc_time=8): """ Constructs a linear system to use for sparse regression later. it used finite difference stencils from the findiff package. :param u: Grid data fro...
def initialize_policy_and_value_functions(self): self.policy = [] self.value = [] for i in range(len(self.BOARD)): # skip obstacles if self.BOARD[i] == 1: self.policy.append(None) self.value.append(None) continue ...
(Value iteration is a dynamic programming algorithm used to solve Markov Decision Processes (MDPs) by iteratively updating state values until convergence. The code initializes policy and value functions, then iteratively computes new values using maximum Q-values from available actions. It checks for convergence when t...
def value_iteration(self): # Initialize policy and value functions self.initialize_policy_and_value_functions() new_values = [0] * len(self.BOARD) # Value iteration loop iter = 0 start_time = time.time() while True: if iter % 5 == 0: ...
def initialize_policy_and_value_functions(self): self.policy = [] self.value = [] for i in range(len(self.BOARD)): # skip obstacles if self.BOARD[i] == 1: self.policy.append(None) self.value.append(None) continue ...
The code performs policy iteration in reinforcement learning by alternating between policy evaluation (computing value functions) and policy improvement (updating the policy). It iterates for a set number of steps, printing progress every 5 iterations, and terminates early if the policy stops changing. The function tra...
def policy_iteration(self): # Initialize policy and value functions self.initialize_policy_and_value_functions() # Policy iteration loop start_time = time.time() for i in range(self.ITERATIONS): if i%5 == 0: print(f"Policy Iteration {i}: values={self....
def get_Q(X, y): Q = np.outer(y, y) * (X.T @ X) return Q def get_f(Q): # - because the original problem is maximization problem. return lambda lamda: quadratic_form(lamda, None, None, Q) - np.sum(lamda) def get_h(y): return lambda lamda: lamda @ y def get_df(Q): return lambda l: df(l, Q) def get...
The code implements the Augmented Lagrangian method to solve a constrained optimization problem. It iteratively minimizes the augmented Lagrangian function using projected gradient descent, updates Lagrange multipliers and penalty parameters, and checks for convergence based on gradient norm tolerance. The goal is to f...
def augmented_lagrangian_method(X, y, lamda_0, mu_0, p0, C, beta, p_max, num_iter, tolerance, armijo_sigma, armijo_beta, armijo_a0): # initialize augmented lagrangian and it's derivative. Q = get_Q(X, y) f = get_f(Q) h = get_h(y) df = get_df(Q) lamda_k = lamda_0 ...
def is_namespace_created(self, **kwargs): return self.is_object_created("read_namespace", **kwargs) def create_namespace( self, labels: dict = None, annotations: dict = None ) -> client.V1Namespace: if self.is_namespace_created(): logger.info(f"namespace {self.namespace} exists...
The main task of the code is to initialize Kubernetes resources for a Calrissian job. It creates a namespace, defines roles and role bindings for pod and log management, provisions a persistent volume claim, and optionally sets up image pull secrets, service account patches, and resource quotas to ensure proper permiss...
def initialise(self): """Create the kubernetes resources to run a Calrissian job Arg: None Returns: None """ # create namespace if not self.is_namespace_created(): logger.info(f"create namespace {self.namespace}") self.cre...
def train(self, data, targets, lr, a): h, output = self.forward(data) deltaH, deltaO = self.backward(h, output, targets) self.updateWeights(deltaH, deltaO, data, h, lr, a) ## computing average mean square loss and accuracy self.loss.append(np.dot(output[0]-targets, output[0]-ta...
The code trains a model for a specified number of epochs using training data (idxTrain) and validates it on validation data (idxVal) each epoch. It visualizes the neural network's structure and optionally plots decision boundaries between two classes (classA and classB). The training process uses a learning rate (lr) a...
def train_epoch(self, idxTrain, idxVal, targets, data, classA, classB, epochs=100, lr=0.9, a=0): for epoch in range(epochs): self.train(data[:, idxTrain], targets[idxTrain], lr, a) self.validation(data[:, idxVal], targets[idxVal]) self.vizualize_nn(idxTrain, idxVal, targets, d...
def train(self, data, targets, lr, a): h, output = self.forward(data) deltaH, deltaO = self.backward(h, output, targets) self.updateWeights(deltaH, deltaO, data, h, lr, a) ## computing average mean square loss and accuracy self.loss.append(np.dot(output[0]-targets, output[0]-ta...
The main task of the code is to train a neural network model for a specified number of epochs using training and validation data subsets. It performs iterative training with a given learning rate and parameter 'a', validates the model after each epoch, and visualizes the final neural network structure. The function als...
def train_epoch(self, idxTrain, idxVal, targets, data, epochs=100, lr=0.9, a=0): for epoch in range(epochs): self.train(data[:, idxTrain], targets[idxTrain], lr, a) self.validation(data[:, idxVal], targets[idxVal]) self.vizualize_nn(idxTrain, idxVal, targets, data) # ...
def cov_to_corr(cov: np.array) -> np.array: std = np.sqrt(np.diag(cov)) corr = cov / np.outer(std, std) corr[corr < -1], corr[corr > 1] = -1, 1 # numerical error return corr def _get_PCA(self, matrix: np.array) -> (np.array): eigenvalues, eigenvectors = np.linalg.eigh(matrix) indices = ...
The code performs denoising of a covariance matrix using PCA and random matrix theory. It converts the covariance matrix to a correlation matrix, extracts eigenvalues/vectors, identifies significant eigenvalues via the max eigenvalue method, removes noise by retaining only relevant factors, and reconstructs a denoised ...
def transform(self, cov: np.array, n_observations: int) -> np.array: # q=T/N where T=sample length and N=number of variables q = n_observations / cov.shape[1] # get correlation matrix based on covariance matrix correlation_matrix = cov_to_corr(cov) # Get eigenvalues and e...
def _correlation_distance(self, corr: np.ndarray) -> np.ndarray: # A distance matrix based on correlation, where 0<=d[i,j]<=1 # This is a proper distance metric dist = np.sqrt((1. - corr) / 2.) for i in range(dist.shape[0]): dist[i, i] = 0. # diagonals should always be 0, bu...
The code computes Hierarchical Risk Parity (HRP) portfolio weights by clustering assets via correlation distances, sorting clusters, and allocating weights to balance risk. It converts covariance to correlation, calculates distances, performs hierarchical clustering, sorts clusters, and derives weights. It validates th...
def allocate(self, mu: np.array, cov: np.array) -> np.array: corr = cov_to_corr(cov) dist = self._correlation_distance(corr) link = sch.linkage(dist, 'single') # this step also calculates the Euclidean distance of 'dist' sorted_indices = self._quasi_diagonal_cluster_sequence(...
def get_category_urls(url): print(url) raw_html = get_url(url) html = BeautifulSoup(raw_html, 'html.parser') div_list = html.find_all("ul", class_="secLvMenu") category_list = [] for a in div_list[0].select('a'): category_list.append(a['href']) retur...
The code scrapes recipe data from a website by first extracting category URLs, then gathering recipe URLs from each category. It compiles recipe properties (e.g., ingredients, instructions) from each recipe URL into a pandas DataFrame for structured output.
def full_parse(url): category_list = get_category_urls(url) url_list = [] recipe_df = pd.DataFrame() for category in category_list: category_url = url + category recipe_urls = get_recipe_urls(category_url) print(recipe_urls) try: ...
def _read_file(self, filename): with open(filename, "r") as f: lines = f.readlines() f.close() if len(lines) < 2: # any file worth processing needs more than 1 line raise InvalidFile file_info = None if self._is_wp_file(lines): file_info =...
This code initializes an object by reading a file, converting its content into geographic points, optionally reversing perimeter paths based on specified passes, and converting the processed data into a designated output format, storing the resulting filename.
def __init__(self, filename=None, output_file_type=wp_file, num_reverse_passes=0, default_alt=DEFAULT_ALTITUDE): self.output_filename = None if filename is None: return if not path.exists(filename): raise...
def closing(img): se = np.ones(shape=(11,11), dtype=int) closed = img.dilate(se).erode(se) return closed def find_shapes(img): auximg = np.zeros((img.data.shape[0], img.data.shape[1]), int) lastimage = 2 for i in range(img.data.shape[0]): for j in range(img.data.shape[1]): if...
The code processes an image to count distinct shapes, distinguishing between those with and without holes. It applies morphological closing, identifies shapes, subtracts the original image to detect holes, and calculates the total shapes, shapes without holes, and shapes with holes using unique labels in the resulting ...
def count_shapes(img): print("starting image closing..") closed_img = closing(img) print("closing ended") print("starting shapes search") image_map = find_shapes(closed_img) print("shapes count ended") print("starting image subtraction") subtract = closed_img.subtract(img) print("ima...
def ID3(S, Attributes, Labels, depth, chooser, weCareAboutUnknowns, weights): allLabels, mostCommonLabel = GetTheDeets(S, weights) if len(list(allLabels.keys())) == 1: return Node({}, str(list(allLabels.keys())[0]), "") if len(Attributes) == 0 or depth < 1: return Node({}, mostCommonLabel, "...
This code implements the AdaBoost algorithm using decision trees as weak learners. It iteratively trains decision trees (via ID3), calculates their error, adjusts weights (D_t) based on performance, and combines hypotheses (hypotheses) with coefficients (alpha_t). The final hypothesis is a weighted sum of all weak lear...
def AdaBoost(S, Attributes, Labels, T, _D=None, _alpha=None, _h=None): if T == 1: D_t = [[0 for z in range(len(S.index))] for k in range(0, 501)] alpha_t = [0 for k in range(501)] D_t[0] = [1/len(S.index) for i in range(len(S.index))] hypotheses = [[] for k in range(501)] for...
def preprocess_data(self, posts): ''' Clean the data Params: Dataframe containing reddit posts Returns: Dataframe containing preprocessed reddit posts ''' posts['Body'] = posts['Body'].str.lower() posts = posts.drop(posts[posts.Body == '[deleted]'].index) ...
The code performs sentiment analysis on Reddit comments by checking for an existing CSV file of posts, generating one if absent, preprocessing text data, appending polarity scores, and filtering posts. It handles data retrieval, cleaning, sentiment scoring, and filtering to analyze game-related discussions.
def analysis(self): ''' Run sentiment analysis by preprocessing the data, appending polarity scores, and filtering posts Params: None Returns: None ''' # csv file exists if Path('data/posts.csv').is_file(): df = pd.read_csv('data/posts.csv') #...
def _parse_arg(self, arg): if arg > 0x7ff: return arg - 0x1000 return arg def _isqrt(self, num): if num <= 1: return num l = 1 r = num + 1 while (l != r - 1): m = (l + r) >> 1 if (m * m <= num): l = m else: r = m return l def _find_num_steps_circular(self, x, y, i, j, flags, r, is...
This function performs a circular arc movement from the current position to a target point (end_x, end_y), using a specified center (i, j). It calculates the arc's radius, determines the number of steps required, and iteratively executes each step in the correct direction (clockwise/counterclockwise) to trace the arc. ...
def _do_circular_mvt(self, arg1, arg2, arg3, arg4, flags, is_ccw): x = self._parse_arg(arg1) y = self._parse_arg(arg2) i = self._parse_arg(arg3) j = self._parse_arg(arg4) end_x = x end_y = y if not self._pos.absolute: end_x = self._pos.x + x end_y = self._pos.y + y center_x = self._pos.x + i c...
def whois(self): try: response=br.open("https://www.google.co.in") br.select_form(nr=0) br.form['q']=self.ques br.submit() src_code=br.response().read() answer=re.search(r'<span>(.*)',src_code) answer=answer.group()[:400] ...
This code performs a Google search using a query from 'self.ques', extracts the first answer from search results, cleans HTML tags, and sends the result to a recipient via 'self.send'. If no answer is found, it triggers 'self.whois()'. It handles exceptions and uses regex to parse dynamic content from the response.
def whatis(self): try: response=br.open("https://www.google.co.in") br.select_form(nr=0) br.form['q']=self.ques br.submit() src_code=br.response().read() spg=1 answer=re.search(r'"_sPg">(.*)',src_code) ...
def markAsDelivered(self, userID, threadID): data = {"message_ids[0]": threadID} data["thread_ids[%s][0]"%userID] = threadID r = self._post(DeliveredURL, data) return r.ok def markAsRead(self, userID): data = { "watermarkTimestamp": now(), "shouldSendReadR...
The code handles incoming messages by marking them as delivered/read, checking the sender's ID, and processing the message content. It triggers specific responses based on keywords like 'bye', 'who', or 'what', calling methods such as `trained()`, `whois()`, or `whatis()` to manage interactions. The goal is to provide ...
def on_message(self, mid, author_id, author_name, message, metadata): ''' subclass Client and override this method to add custom behavior on event ''' self.markAsDelivered(author_id, mid) self.markAsRead(author_id) if str(self.uid)!=str(author_id): p...
def update_nodes(self): len_node = len(self.nodes) for i in range(len_node): response = self.url_request('http://{node}/nodes'.format(node=list(self.nodes)[i])) if response != 0 and int(response['length']) > len_node: self.nodes = set() self.nodes ...
The main task of the code is to update the block by synchronizing nodes, resolving conflicts among them, and updating current vote records, ensuring consistency and accuracy in the system's state.
def update_block(self): self.update_nodes() self.resolve_conflicts() self.update_current_votes()
def new_grid(self,width,height): """ pre: an integer width and height are passed in post: makes self.grid a new unvisited grid, creates a random startpoint for algorithm, and visits the first neighboring squares to make them into walls. ...
The code generates a maze with specified width and height by creating a grid, constructing the maze structure, and printing it to the console. It initializes the grid, builds the maze logic, and outputs the result.
def new_maze(self,width=30, height=15): """ pre: an optional width and height is passed in post: generates a new maze and prints it to the console """ self.new_grid(width,height) self.make_maze() self.print_maze()
def load_input(): return open(INPUT_FILE, "r").read().strip().split("\n") def part_one(rules): bags = ['shiny gold'] outer_count = 0 while len(bags) > 0: bag = bags.pop(0) regex = r"contain.*" + bag containing_bags = [' '.join(rule.split()[:2]) for rule in rules if re.search(re...
The main task of the code is to execute two processing stages (`part_one` and `part_two`) using rules loaded from input. The `main()` function orchestrates this workflow by first retrieving the input rules via `load_input()` and then sequentially applying the two processing functions to analyze or transform the rules.
def main(): rules = load_input() part_one(rules) part_two(rules)
def load_input(): return open(INPUT_FILE, "r").read().strip() def part_one(ticket_info): validation = ticket_info.split("\n\n")[0] ranges = re.findall(r"\d+-\d+", validation) allowed = set() for allowed_range in ranges: allowed_range = allowed_range.split('-') allowed.update(range(in...
The code's main task is to process ticket information by executing two distinct functions, part_one and part_two, which likely perform separate analyses or validations on the loaded input data. The main function orchestrates this workflow by first loading the input and sequentially applying the two processing steps.
def main(): ticket_info = load_input() part_one(ticket_info) part_two(ticket_info)
def Vect(l): """ Creates a vector, represented by a matrix column """ return npmat.asmatrix(l).reshape((-1, 1)) def quaternion_mult(q1, q2): """ Returns the quaternion product of two quaternions represented by a 4 dimensional vector """ s1 = q1[0] v1 = q1[1:] s2 =...
This function updates an object's orientation by integrating total force/momentum into angular momentum, computing angular velocity using the inverse inertia matrix, updating the rotation quaternion via integration, normalizing it for numerical stability, and recalculating the rotation matrix from the updated quaternio...
def _update_orientation(self, total_force_moment, dt): """ Integrates the provided force momentum to change angular momentum, uses solid inertia to compute the angular speed and uses it to update the quaternion representing the object orientation """ ...
def _update_position(self, total_force, dt): """ Integrates velocity and position for a time step dt if the sum of every forces is provided """ total_force = Vect(total_force) self.center_velocity += dt * self.total_mass_inverse * total_force self.center_...
This code updates an object's position and orientation using applied forces and torques over a time step, then calculates its axis-aligned bounding box (AABB) for collision detection or spatial management.
def update(self, total_force, total_force_moment, dt): self._update_position(total_force, dt) self._update_orientation(total_force_moment, dt) self._compute_AABB()
def click_year(self, my_year: int): if len(str(my_year)) != 4: raise ValueError self.driver.implicitly_wait(20) self.driver.find_element_by_id('datepicker').click() self.click_to_years() self.driver.implicitly_wait(20) years = self.driver.find_elements_by_xpat...
The main task of the code is to set a specific date by sequentially clicking on the year, month, and day components. The function `click_date` takes `month`, `day`, and `year` as parameters and invokes three helper methods—`click_year`, `click_month`, and `click_day`—to navigate and select the specified date in a date-...
def click_date(self, *, month: int, day: int, year: int): self.click_year(year) self.click_month(month) self.click_day(day)
def check_fleet_edges(a_settings,aliens): for alien in aliens.sprites(): if alien.check_edges(): change_fleet_direction(a_settings, aliens) break def ship_hit(a_settings, stats, screen, ship, aliens, bullets): if stats.ships_left > 0: stats.ships_left -= 1 ...
This function updates alien movement, checks for collisions between the ship and aliens, and triggers responses to collisions or alien reaching the screen bottom. It first checks if aliens have hit screen edges, updates their positions, detects ship-alien collisions to trigger a "ship hit" response, and checks if any a...
def update_aliens(a_settings, ship, aliens, screen, bullets, stats): check_fleet_edges(a_settings, aliens) aliens.update() if pygame.sprite.spritecollideany(ship, aliens): print("Ship hit!!!") ship_hit(a_settings, stats, screen, ship, aliens, bullets) check_aliens_bottom(a_...
def create_df(dataset_dirname: str, files_list: List[str], labels: str): ''' prepare df with all data to make perfect to save in csv :param dataset_dirname: cifar10 or cifar100 :param files_list: list of batches :param labels: b'labels' or b'coarse_labels' :return: df to save to csv and array w...
The main task of the code is to process CIFAR-10 data by generating a DataFrame, writing it to a CSV file, saving associated images, and compressing label data into a ZIP archive for storage and distribution.
def load_cifar10(): ''' work on cifar10: creat csv, save images, save to zip :return:None ''' df, image_data = create_df(cnfg.cifar10, cnfg.files_list_cifar10, cnfg.label_head_cifar10) write_df_to_csv(df, newFile=True) save_images(df, image_data) save_cifar10_dict_labels_to_zip()
def update_cifar100_dict_labels_to_zip(labels_numbers_to_update:List[int]) : ''' if add another clases from cifar100 we must update file :param labels_numbers_to_update: label that we add to data :return: update labels ''' cifar100_labels_dict = create_cifar100_classes_dict() our_labels_name...
The main task of the code is to load and process CIFAR-100 dataset labels based on specified category numbers, filter corresponding image-data pairs, update a CSV file with selected labels, and save the processed images. It uses helper functions to transform labels, filter dataframes, and persist results, returning the...
def load_x_labels_from_cifar100(categorys_numbers: List[int]): ''' :param categorys_numbers: :return: ''' cifar100_source_labels=update_cifar100_dict_labels_to_zip(categorys_numbers) # print(cnfg.csv_path) old_csv = pd.DataFrame(pd.read_csv(r'C:\Users\1\Desktop\Efrat 2022\BOOTCAMP\PROJECT\c...
def _get_auth_code(self) -> int: return 401 def _get_error_code(self) -> int: return (next(iter(self.get_query_parameters().get('error_code') or []), None) or self._get_auth_code()) def _get_success_code(self) -> int: return (next(iter(self.get_query_parameters().get('success_cod...
This code handles HTTP authentication by validating credentials from the Authorization header. It checks for Basic auth format, verifies username/password presence based on configuration flags, and authorizes credentials. It returns appropriate HTTP status codes (auth error, generic error, or success) and includes a WW...
def send_head(self): req_auth_code: int = self._get_auth_code() req_error_code: int = self._get_error_code() req_result_code: int = self._get_success_code() auth_header: str = self.headers['Authorization'] if auth_header is None: req_result_code = req_auth_code ...
def prompt_for_cairo_file(self): """Prompt the user to select a Cairo file to run.""" self.setup_autocomplete() while True: self.filename_dot_cairo = input( "\n>>> Enter .cairo file name or press <TAB> for suggestions:\n\n" ) if self._is_cair...
The code compiles a Cairo file, executes it using a constructed command, creates a profiling directory, and optionally runs a profiling tool if specified. The main task involves compiling, executing, and profiling a Cairo program based on user arguments.
def run(self): self.prompt_for_cairo_file() print(f"Selected Cairo file: {self.filename_dot_cairo_path}") create_directory(f"{PROFILING_DIR}/{self.filename}") compiled_path = self.compile_cairo_file() run_command = self.construct_run_command(compiled_path) os.system(run_...
def get_resource_server_data(resource, stop=False): if not resource.url: return None url = f"https://{ACV_SERVER}{resource.url}" request = { 'url': url, 'headers': HEADERS, 'cert': CERT } if CA_FILE: request['verify'] = CA_FILE response = requests.get(**...
The main task of the code is to check the status of a resource via an API endpoint, update the resource's state (approved/rejected) based on the server response, handle retries for transient errors, and raise exceptions for invalid statuses or persistent failures. It uses HTTPS with certificate verification, processes ...
def get_request_status(resource, stop=False): url = f"https://{ACV_SERVER}{resource.status_url}" request = { 'url': url, 'headers': HEADERS, 'cert': CERT } if CA_FILE: request['verify'] = CA_FILE response = requests.get(**request) if response.ok: status ...
def load_vendors(j): vendors = [] taken_ids = [] for vendor in j["vendors"]: vid = vendor["id"] if vid in taken_ids: # We have already ingested a Vendor with this same id value raise ValueError(f"Vendor id({vid}) already used by previous Vendor. Unique id required for...
The main task of the code is to parse a metadata JSON file, generate Vendor and Person objects from it, and register these entities with a server and vendors respectively. The function reads the input file, loads vendor and person data, then calls registration functions to populate the system with the parsed informatio...
def create_resources(metadata_file=None): if not metadata_file: return with open(metadata_file) as f: metadata_json = json.load(f) # Create a list of Vendor from the JSON vendors = load_vendors(metadata_json) # Register the list of Vendor with server register_vendors(vendors) ...
def _verify_config(self, gitdir, fail_noid=True): # try loading all needed info from (git) config name = self.annex.getconfig('name') # get store url: self.ria_store_url = self.annex.getconfig('url') if self.ria_store_url: # support URL rewrite without talking to a Da...
This method prepares the annex environment by verifying configurations, selecting appropriate I/O (local or SSH), initializing storage paths, checking layout versions, and caching remote directory locations for data management. It ensures the system can access git repositories, validates connectivity, and sets up neces...
def prepare(self): # can we use self.annex.info() for sending user output to annex? self.can_notify = "INFO" in self.annex.protocol.extensions gitdir = self.annex.getgitdir() self.uuid = self.annex.getuuid() self._verify_config(gitdir) if self._local_io(): ...
def get_most_recent_date(): query = f'''SELECT MAX(date) FROM {STOCK_TABLE};''' cursor = connect_to_database() cursor.execute(query) for row in cursor: return str(row[0]) def connect_to_database(): error_message_list = [] try: config.user cursor = connect_helper(config.u...
The function retrieves the most recent stock close/open prices for specified company IDs from a database. It queries the latest date, extracts close/open values, prioritizing close prices, and supplements with open values if needed. If active_company_ids are provided, it ensures all listed companies are included by fet...
def get_current_value_dict(active_company_ids=None): most_recent_date = get_most_recent_date() cursor = connect_to_database() query = f'''SELECT {STOCK_TABLE}.company_id, {STOCK_TABLE}.close, {STOCK_TABLE}.open FROM {STOCK_TABLE} WHERE {STOCK_TABLE}.date = %s;''' cursor.execute(query, (most...
def connect_to_database(): error_message_list = [] try: config.user cursor = connect_helper(config.user, error_mesage_list) if cursor is not None: return cursor except AttributeError: for user in config.user_list: cursor = connect_helper(user, error_me...
The code retrieves stock company details from a database using a symbol, joins with sector and headquarters tables, fetches current value and all-time high data from dictionaries, compiles the information into a structured JSON format, and returns it.
def get_stock_summary(stock_symbol): query_args = [] query = f'''SELECT {COMPANY_TABLE}.id, {COMPANY_TABLE}.symbol, {COMPANY_TABLE}.full_name, {SECTOR_TABLE}.sector_name, {HEADQUARTERS_TABLE}.location, {COMPANY_TABLE}.date_first_added, {COMPANY_TABLE}.founded_year FROM {COMPANY_TABLE}, {SECTOR_TABLE}, {HEAD...
def connect_to_database(): error_message_list = [] try: config.user cursor = connect_helper(config.user, error_mesage_list) if cursor is not None: return cursor except AttributeError: for user in config.user_list: cursor = connect_helper(user, error_me...
This function searches for stock companies based on user-provided filters like search string, value ranges, and sector. It constructs a dynamic SQL query to fetch company data from joined tables, applies filters, retrieves additional financial data, and returns a JSON list of matching companies with details like symbol...
def search_stocks(): search_string = flask.request.args.get('search_string') current_value_min = flask.request.args.get('current_value_min') current_value_max = flask.request.args.get('current_value_max') all_time_high_min = flask.request.args.get('all_time_high_min') all_time_high_max = flask.reque...
def get_list(input, character): base_data = setup_data.load_data(input, character) return base_data def cross_validate(dataset): global classes backup_data = copy.copy(dataset) test_results = [] stats = [] backup_data = splitter(backup_data) for i in range(10): # iterate over all ten su...
The main task of the code is to perform 10-fold cross-validation on both untouched and scrambled datasets. It initializes 6 classes, retrieves data, copies it, and evaluates performance on the original data using `cross_validate`. Then, it prints results for scrambled data via `scrambled_cv`, likely testing model robus...
def driver(): global classes data = get_list('1', '?') classes = 6 unscrambled_data = copy.copy(data) print("Untouched Data:") cross_validate(unscrambled_data) # Does the ten fold cross validation print("Scrambled Data:") scrambled_cv(unscrambled_data)
def rolmean(dataset, hrw, fs): mov_avg = dataset.hart.rolling(window=int(hrw*fs)).mean() #Calculate moving average #Fill in mov_avg with the plain value where moving average function returns NaN, which is at the beginning of the signal avg_hr = (np.mean(dataset.hart)) mov_avg = [avg_hr if math.isnan(x...
The main task of the code is to process a heart rate dataset by analyzing peaks, calculating time-series metrics (e.g., RR intervals), determining optimal moving average parameters, detecting valid peaks, rejecting invalid peaks, and generating a heartbeat plot and frequency analysis via Fast Fourier Transform. The fun...
def process(dataset, hrw, fs): #Main function which calls the other functions rolmean(dataset, hrw, fs) valid_ma_perc = fit_peaks(dataset, fs) #Calculate the best-fit moving average percentage detect_peaks(dataset, valid_ma_perc, fs) calc_RR(dataset, fs) calc_ts_measures() plotter(dataset, "He...
def load_data(self,data): """ Load data from input and extract artifacts. """ if self.extract == True: data = self._extract_components(data) self.data = data[self.channels,:] def bank_of_filters(self): """ Filter each channel using narrow bandpass f...
This method processes input data through the Bakardjian System's modules: loading data, frequency filtering, energy variance analysis, Savitzky-Golay smoothing, channel integration, and normalization to prepare signals for classification or analysis.
def fit(self,data): """ This method performs all modules from Bakardjian System. """ ### 1. Firstly, load the data and extract components; those are modules 1. and 2. ### from original Bakardjian System self.load_data(data) ### 2. Secondly, filter the data on two...
def get_pad_tuple(padding, kernel): """Common code to get the pad option Parameters ---------- padding : int or str Padding size, or ['VALID', 'SAME'] kernel : tuple of int Conv kernel size Returns ------- pad_top : int Padding size on top pad_left : int ...
The code implements a depthwise 2D convolution operation using TVM, optimizing for performance through tiling, vectorization, and loop unrolling. It handles input padding, kernel packing (NCHWc format), and configures autotuning parameters for compute schedules. The function defines the computational graph, computes ou...
def conv2d_depthwise(N, H, W, CO, CI, KH, KW, strides, padding, groups): assert N == 1, "Only consider batch_size = 1 in this template" in_data = te.placeholder((N, CI, H, W), name="data") in_kernel = te.placeholder((CO, CI//groups, KH, KW), name="kernel") #conv = topi.nn.group_conv2d_nchw(data, kernel...
def getFile(bin): url = f'https://api.jsonbin.io/v3/b/{bin}' headers = { 'X-Master-Key': masterKey } return requests.get(url, json=None, headers=headers) def determineAnswer(): dateSeed = datetime.now().strftime("%m%d%Y%H%M%S") random.seed(int(dateSeed)) json_data = getFile(playersBin) players = json.loads(js...
The main task of the code is to update a JSON file with a new answer and incremented puzzle ID. It reads the current JSON data, generates a new answer using determineAnswer(), increments the puzzleId by 1, and writes the updated data back to the file. This likely automates daily puzzle tracking or answer logging.
def rolloverDay(): json_data = getFile(answerBin) todaysAnswer = json.loads(json_data.text) jsonString = {"answer": determineAnswer(), "puzzleId": todaysAnswer["record"]["puzzleId"] + 1} updateFile(answerBin, jsonString)
def search(node, value): left = value <= node.data right = value > node.data if left: # put the value on the left side of the AVL tree if node.left is None: return [node,True] elif node.left is not None: return search(node.left, value) if right: # put the v...
This code inserts a new node with the given value into a tree, maintaining balance by identifying and rebalancing any unbalanced nodes after insertion. It first places the node in the correct position, then iteratively checks and adjusts the tree's structure to ensure balance, updating parent-child relationships as nee...
def insert(tree, value): new_node = Node() new_node.data = value if tree.root is None: tree.root = new_node return else: node = tree.root position,left = search(node, value) if left: position.left = new_node else: position.right = new_node u...
def onlygui(self): print("Hi") def tcpreplay(self): if(self.edge_to_redraw != None): delLine = self.edge_to_redraw line = self.drawing_area.scene().addLine(delLine.line(),QPen(QColor(255, 255, 255),2)) self.edge_to_redraw = line self.drawing_area.scene().r...
The main task of the code is to process network packets based on specified modes. It initializes timing, sets the save path, filters packets if required, determines the packet count, and executes either GUI-only operations or mode-specific tasks like tcpreplay, Scapy processing, or network pinging, depending on command...
def updateNetwork(self): if(self.startTimining == 0): self.startTimining = time.time() self.savename = self.args.savepath if self.args.savepath != "" else "save.pcap" self.packets = self.packets if self.args.filter == "" else utils.filter_packets(self.packets,self.args.filter) ...
def send_packets_tcpreplay(packets, dict_source:dict, client,location,savename,save,maxRange,verbose,optimized=False): firstKey = str(list(dict_source.keys())[0]) if(save): client.containers.get(firstKey).exec_run("tcpdump -i eth0 -c " + str(maxRange)+" -w "+savename,detach=True) if(optimized): ...
The main task of the code is to send packets using different modes (tcpreplay, scapy, or pingnetwork) based on the provided arguments. It processes packet filtering, sets parameters like save path and verbosity, and delegates packet sending to mode-specific functions. The function also terminates containers after execu...
def send_packets_args(packets, dict_source, client, netname,location,args): #vars savename = args.savepath if args.savepath != "" else "/save.pcap" savename = args.savepath if args.savepath != "" else "save.pcap" save = True if args.dump == 1 else False args.listoflists = True if args.listoflists ==...
def init_sys_args(): parser = argparse.ArgumentParser() parser.add_argument("-p", "--pcap",type=str, help="pcap file to read") parser.add_argument("-d","--docker",type = int,help = "only generate the docker network without sending packets") parser.add_argument("-sp","--savepath",type = str,help = "name ...
The main task of the code is to process network traffic data from a pcap file, configure Docker networks and containers based on command-line arguments, and either launch a GUI interface or simulate packet transmission, depending on specified flags. It parses arguments, reads packet data, sets up Docker environments, a...
def main(): arg_parser = init_sys_args() args = arg_parser.parse_args() args = clean_args(args) location = get_path() if(args.onlygui == 1): init_only_gui(location,args) packets, dict_source = utils.read_pcap(args.pcap) # args.pcap,default = "fullTCP.pcap" client = ...
def hexTobinary(hexdigits): """ Converts Hexadecimal digits to Binary""" binarydigits = "" for hexdigit in hexdigits: binarydigits += bin(int(hexdigit,16))[2:].zfill(4) return binarydigits def generateKeys(key): """ Generates multiple keys from the initial 64 bit key""" round_keys = list...
The code implements the Data Encryption Standard (DES) algorithm to encrypt a given message using a provided key. It converts the key to binary, generates 16 round keys, applies an initial permutation to the message, splits it into halves, and iteratively applies the DES round function (F-function) with XOR operations....
def DES_encrypt(message, key): """ Takes in the message and key. Encrypts the message using the DES algorithm. Returns the encrypted message.""" key_bits = hexTobinary(key) roundkeys = generateKeys(key_bits) p_plaintext = apply_p(InitialPermutationList, message) L, R = splitInHalf(p_plaintext) f...
def hexTobinary(hexdigits): """ Converts Hexadecimal digits to Binary""" binarydigits = "" for hexdigit in hexdigits: binarydigits += bin(int(hexdigit,16))[2:].zfill(4) return binarydigits def generateKeys(key): """ Generates multiple keys from the initial 64 bit key""" round_keys = list...
The code decrypts a ciphertext using the DES algorithm by converting the key to bits, generating round keys, applying initial permutation, splitting the ciphertext into halves, performing 16 rounds of XOR operations with the f-function and round keys, recombining the halves, and applying the inverse permutation to retr...
def DES_decrypt(ciphertext, key): """ Takes in the ciphertext and key. Decrypts the ciphertext using the DES algorithm. Returns the decrypted message.""" key_bits = hexTobinary(key) roundkeys = generateKeys(key_bits) p_ciphertext = apply_p(InitialPermutationList, ciphertext) L, R = spliHalf(p_cipher...