dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def _teardown_client(self): _log.info('Starting client teardown') self._kubectl(None, 'delete', 'pod/dns-perf-client') while True: code, _, _ = self._kubectl(None, 'get', 'pod', _client_podname) if code != 0: break time.sleep(1) _log.info('Waiting for client pod to terminate...
The main task of the code is to reset and configure a DNSPerf client pod on a specified node. It tears down the existing client, updates the YAML configuration with the target node, creates a new pod, waits for it to start and become ready for execution, then copies query files to the client pod. The process ensures th...
def _reset_client(self): self._teardown_client() self.dnsperf_yaml['spec']['nodeName'] = self.client_node self._create(self.dnsperf_yaml) while True: code, _, _ = self._kubectl(None, 'get', 'pod', _client_podname) if code == 0: break _log.info('Waiting for client pod to start ...
def _select_nodes(self): code, out, _ = self._kubectl(None, 'get', 'nodes', '-o', 'yaml') if code != 0: raise Exception('error gettings nodes: %d', code) nodes = [n['metadata']['name'] for n in yaml.load(out)['items'] if not ('unschedulable' in n['spec'] \ and n['spec'][...
The main task of the code is to execute performance tests by generating test cases, configuring server deployments, managing Kubernetes resources, and running each test scenario while handling exceptions. It ensures consistent environments by redeploying when parameters change, tears down resources post-tests, and logs...
def go(self): """ Run the performance tests. """ self._select_nodes() test_cases = self.test_params.generate(self.attributes) if len(test_cases) == 0: _log.warning('No test cases') return 0 try: self._ensure_out_dir(test_cases[0].run_id) self._reset_client() s...
def preprocess_signal(signal): num_samples = len(signal) # while number of samples is less than power of two # pad the signal with zeros at end to reach a length equal to power of two # the following condition is only zero for powers of two(consider bitwise representation) if num_samples & (num_samp...
This function computes the Fast Fourier Transform (FFT) of a signal in-place using an iterative approach. It first preprocesses the signal, applies bit-reversal permutation to the indices, and then iteratively performs butterfly operations. These operations use complex exponential scalers to combine signal components, ...
def in_place_fft(signal): signal = preprocess_signal(signal) num_samples = len(signal) # reverse the bits of the indices in the signal signal = bit_reverse(signal) # iterate over the table log(n) times, computing the values iterativelly # equivalent to starting from the base cases and building ...
def switch_state(self, state): self.state_lock.acquire() self.state = state self.time_entered_state = time.time() self.state_lock.release() self.put_info_text() def reload_bait(self): self.metin_window.activate() self.osk_window.reload_bait() time.sleep(ra...
This code implements an automated fishing bot that transitions through states (initializing, calibrating, casting, fishing, catching) to simulate gameplay. It activates a game window, monitors pixel data for fish movement, casts a rod, waits for catches, and restarts the cycle. Debug mode displays mouse positions. The ...
def run(self): while not self.stopped: if self.state == BotState.INITIALIZING: self.metin_window.activate() # self.respawn_if_dead() self.started = time.time() self.switch_state(BotState.CALIBRATION) if self.state == BotSt...
def get_query_response(client: OpenAI, message: str,) -> str: response = get_response_for_query(client, message, "user",) return response def update_msg_history(message: dict): import json msg_history = get_message_history() msg_history.append(message) with open("message_history.json", "w") as f...
The main task of the code is to handle user queries by generating responses via an OpenAI client, updating message history, detecting urgent queries, and notifying via email if urgency is detected, while allowing exit via "exit" command.
def main_agent(client: OpenAI): user_query = input("query: ") if user_query == "exit": print("Bye") return response = get_query_response(client, user_query) update_msg_history({"role": "assistant", "content": response}) query_is_urgent = query_convays_urgency(client, user_query) ...
def fill_list(center, win): ''' Creates the list for my animation ''' circle = Circle(center, 20) square = Square(Point(center.x-10, center.y-10), 20) circle.draw(win) square.draw(win) return [circle, square] def move_on_line(shapeList, dx, dy, repetitions, delay, win): """Animat...
The code creates an animation using a graphical window. It initializes points, moves them along lines and circular paths, draws dotted lines and an arc, and displays the result. The main task involves animating graphical elements along predefined paths and rendering shapes in a window.
def main(): win = GraphWin("My Animation", 400, 400) win.setBackground("white") win.yUp() my_list = fill_list(Point(100, 100), win) for i in range(10): move_on_line(my_list, 20, 0, 1, 0.1, win) move_on_circle(my_list, Point(200, 200), (PI / 64), 10, 0.3, win) for i in range(15): ...
def omega_matrix(a, x, height, width): l = height*width y = [] z = [] u = vector(2, 3, 5, 1) for i in range(math.ceil(l/16.0)): t = math.floor(numpy.dot(u, x)[0][0]) + 1 for j in range(t): x = a.dot(x) % 1 n = (numpy.floor(x * (2**32))).T y.append(x) z.append(vector(to_bytes(numpy.uint32(n), 4))...
The function `cypher_image` processes an input image through a series of transformations including padding, region division, shuffling using matrices and cat maps, and masking. It returns the encrypted image, mask, and original shape for potential decryption or analysis.
def cypher_image(image, a_matrix, a_vector, cat_map1, cat_map1_init, cat_map2, cat_map2_init, block_size, std_limit): omega, y = omega_matrix(a_matrix, a_vector, block_size, block_size) paddedImage, shape = imageutil.pad_image(image, block_size) mask = imageutil.divide_regions(paddedImage, block_size, std_limit) ...
def omega_matrix(a, x, height, width): l = height*width y = [] z = [] u = vector(2, 3, 5, 1) for i in range(math.ceil(l/16.0)): t = math.floor(numpy.dot(u, x)[0][0]) + 1 for j in range(t): x = a.dot(x) % 1 n = (numpy.floor(x * (2**32))).T y.append(x) z.append(vector(to_bytes(numpy.uint32(n), 4))...
The function deciphers an encrypted image by first unmasking it using a matrix and vector, then unshuffling the unmasked image with specified cat maps, and finally removing padding to reconstruct the original image shape. It processes the input image, mask, and cryptographic parameters to reverse encryption steps, yiel...
def decypher_image(image, mask, shape, a_matrix, a_vector, cat_map1, cat_map1_init, cat_map2, cat_map2_init, block_size): omega, y = omega_matrix(a_matrix, a_vector, block_size, block_size) unmasked_image = unmask_image(image.copy(), mask, omega, y) unshuffled_image = unshuffle_image(unmasked_image.copy(), mask, om...
def get_all_tables(self): self.conn.commit() cursor = self.conn.execute("SELECT name FROM sqlite_master WHERE " "type IN ('table','view') AND " "name NOT LIKE 'sqlite_%' ORDER BY 1;") table_tables = [] for row in curso...
The code generates a string representation of the 'projects' table from a database, excluding specific columns like 'project_location' and 'color'. It fetches data, constructs a DataFrame, replaces 'category_id' with category names via lookup, and formats the output with table headers and filtered columns.
def __str__(self): str_chunks = [] for table in self.get_all_tables(): if table not in ["projects"]: continue chunk = f"--- {table.capitalize()} ---" cols = self.get_table_cols(table) df_dict = {key: [] for key in cols} for row...
def entries_total_wordcount(entries): total = sum(entries_wordcount(entries)) return total def entries_period(entries, frm, to): def filter_by_date(entry, frm, to): if entry['date']: obj = entry_date_obj(entry['date']) return obj >= frm and obj <= to return Fals...
The code generates a journal report summarizing key statistics from a collection of entries, including total and monthly word counts, the longest entry, average word count and length, a random sentence, time since first entry, longest hiatus, and longest journaling streak.
def generate_report(entries): print("# Your journal report:") total_wordcount = entries_total_wordcount(entries) today = d.today() this_month_wordcount = entries_total_wordcount(entries_period(entries, d(today.year, today.month, 1), today)) print(f"You've written {total_wordcount} words on total; {t...
def randPair(s,e): return np.random.randint(s,e), np.random.randint(s,e) def validateBoard(self): valid = True player = self.board.components['Player'] goal = self.board.components['Goal'] wall = self.board.components['Wall'] pit = self.board.components['Pit'] all_p...
The main task of the code is to initialize static game components (Player, Goal, Pit, Wall) on a board with random positions for the Player and fixed positions for others, then validate the board layout. If invalid, it recursively rebuilds the static setup until valid.
def initGridStatic(self): #Setup static pieces self.board.components['Player'].pos = randPair(0,self.board.size) #Row, Column self.board.components['Goal'].pos = (3,0) self.board.components['Pit'].pos = (3,1) self.board.components['Wall'].pos = (3,2) if (not self...
def randPair(s,e): return np.random.randint(s,e), np.random.randint(s,e) def validateBoard(self): valid = True player = self.board.components['Player'] goal = self.board.components['Goal'] wall = self.board.components['Wall'] pit = self.board.components['Pit'] all_p...
The main task of the code is to randomly initialize positions for game components (Player, Goal, Pit, Wall) on a grid. It assigns each component a random coordinate using `randPair`, then checks board validity. If invalid, it recursively reinitializes the grid until a valid configuration is achieved, ensuring functiona...
def initGridRand(self): #height x width x depth (number of pieces) self.board.components['Player'].pos = randPair(0,self.board.size) self.board.components['Goal'].pos = randPair(0,self.board.size) self.board.components['Pit'].pos = randPair(0,self.board.size) self.board.component...
def initGridStatic(self): #Setup static pieces self.board.components['Player'].pos = randPair(0,self.board.size) #Row, Column self.board.components['Goal'].pos = (3,0) self.board.components['Pit'].pos = (3,1) self.board.components['Wall'].pos = (3,2) if (not self...
The code initializes a game grid by first setting up static components, then randomly placing the player on the board. It validates the board's configuration; if invalid, it recursively rebuilds the grid by reinitializing the player's position.
def initGridPlayer(self): #height x width x depth (number of pieces) self.initGridStatic() #place player self.board.components['Player'].pos = randPair(0,self.board.size) if (not self.validateBoard()): #print('Invalid grid. Rebuilding..') self.initGridPla...
def initGridStatic(self): #Setup static pieces self.board.components['Player'].pos = randPair(0,self.board.size) #Row, Column self.board.components['Goal'].pos = (3,0) self.board.components['Pit'].pos = (3,1) self.board.components['Wall'].pos = (3,2) if (not self...
Your return The code initializes a grid-based board game with a minimum size of 4, adding predefined pieces (Player, Goal, Pit, Wall) to specific positions. Depending on the `mode` parameter, it configures the board layout using static, player-defined, or random initialization methods to set up the game environment.
def __init__(self, size=4, mode='static'): if size >= 4: self.board = GridBoard(size=size) else: print("Minimum board size is 4. Initialized to size 4.") self.board = GridBoard(size=4) #Add pieces, positions will be updated later self.board.addPiece('...
def login(browser, user): logger.info("logging in for: " + user.its) time.sleep(5) username_input = browser.find_element(by=By.NAME, value="txtUserName") username_input.send_keys(user.its) pwd_input = browser.find_element(by=By.NAME, value="txtPassword") pwd_input.send_keys(user.pwd) login_b...
The code automates processing a list of miqaats on a website. It logs in, navigates to the miqaat section, processes each item in the list, and logs out. If no miqaats exist, it waits 30 seconds. Error handling ensures exceptions are logged.
def run(browser, data): try: if not data.miqaatList: logger.info("No miqaats to proccess") time.sleep(30) return browser.get('https://www.its52.com') login(browser, data.user) enter_miqaat(browser) process_all_miqaat(browser, data.miqaatLi...
def prepare_data(percent, train_x, train_y): num_of_examples = len(train_x) num_of_examples_for_learning = int(num_of_examples * percent) train_x_for_learn = train_x[:num_of_examples_for_learning] train_y_for_learn = train_y[:num_of_examples_for_learning] train_x_for_test = train_x[num_of_examples_f...
The code evaluates hyperparameters for a neural network by iterating through combinations of learning rate (eta), epochs, hidden layer sizes, and training/test data splits. It trains the model for each combination, classifies test data, and prints error percentages to assess performance. The goal is to identify optimal...
def check_values_for_hyper_params(train_x, train_y): number_of_pixels = 28*28 number_of_classes = 10 learn_percent = [0.9, 0.8, 0.7, 0.6] epochs_values = [10, 15, 20, 25] eta_values = [0.1, 0.01, 0.001, 0.0001] hidden_layer_size_values = [160, 140, 120, 100] for i in learn_percent: f...
def set_message(self, value): self._message = value return self._message def unbind_space_key(self): if self.space_key_bound: self.root.unbind('<space>', self.space_id) self.space_key_bound = False def check_if_clear_level(self): if "Boss" not in [monster.name for...
This function handles the conclusion of a battle by checking if the monster is defeated. It triggers level-up messages, key collection, or game over based on the hero's status, unbinds the space key, and determines if the level is cleared or if the monster retaliates.
def end_battle(self): if self.monster_to_fight.get_hp() == 0 and self.hero.just_got_key: self.set_message("Level up! You got the key!") self.unbind_space_key() elif self.monster_to_fight.get_hp() == 0 and self.hero.just_got_key is False: self.hero.level_up() ...
def testIterative(n): print("Iterative Method") x= [] t = [] for i in range(n+1): start = time.time() fib = f(i) end = time.time() print("Fibonacci value: {0} fibb sum is {2} Time taken : {1}".format(i,end-start, fib)) x.append(i) t.append(end-star...
The code's main task is to compare the performance of recursive and iterative Fibonacci algorithms by plotting their execution times against the number of terms. It allows users to either test a single Fibonacci term or generate a visual comparison of time complexity between the two methods for multiple terms.
def main(): usr = input("Quick test a value (q) or plot (p) multiple? ") if usr == 'p' or usr == 'P' : userIn = int(input("How many terms of the fibonacci sequence do you want to test: ")) x2, time2 = testIterative(userIn) x, timetaken= testRecursive(userIn) plt.plot(x, ...
def validate_interactive_quiz_submission(assessment_tool): if assessment_tool is None: raise InvalidRequestException(ASSOCIATED_TOOL_NOT_FOUND) if not isinstance(assessment_tool, InteractiveQuiz): raise InvalidRequestException(f'Assessment tool with id {assessment_tool.assessment_id} ' ...
The function handles the submission of interactive quiz answers by validating the assessment event, user participation, assessment tool, and submission attempt, then saving the quiz attempt. It retrieves necessary data, performs validations, and raises exceptions for invalid requests.
def submit_interactive_quiz_answers(request_data, user): try: event = utils.get_active_assessment_event_from_id(request_data.get('assessment-event-id')) assessee = utils.get_assessee_from_user(user) validate_user_participation(event, assessee) assessment_tool = \ event.ge...
def read_point_cloud_file(f_name): with open(f_name, 'r') as f: lines = f.readlines() points = [] for l in lines: points.append([float(token) for token in l.split()]) return np.array(points) def regress_process(X, points): beta = linear_regression(X, -1 * np.ones((X.s...
The code processes point cloud data from clear and cluttered tables and hallways, fitting planes using regression and RANSAC algorithms. It visualizes the results, calculates average distances, and evaluates how many points align with the fitted planes. For cluttered environments, it identifies the least cluttered plan...
def q4(): clear_table_points = read_point_cloud_file("data/clear_table.txt") plane_params, plane_points, other_points, distances = regress_process(clear_table_points, clear_table_points) ranges = get_ranges(clear_table_points) plot_planes_and_points("figures/clear_table.png", [plane_params], plane_point...
def laplacian_video(self,video_tensor,levels=3): tensor_list=[] for i in range(0,video_tensor.shape[0]): frame=video_tensor[i] pyr=self.build_laplacian_pyramid(frame,levels=levels) if i==0: for k in range(levels): tensor_list.append...
This code amplifies motion in a video by decomposing it into Laplacian pyramid levels, applying a bandpass filter to each level to enhance specific frequency ranges, amplifying the filtered signals, and reconstructing the modified video. The result is a motion-magnified video where subtle movements are emphasized for b...
def magnify_motion(self,video_tensor,fps,low=0.4,high=1.5,levels=3,amplification=30): lap_video_list=self.laplacian_video(video_tensor,levels=levels) filter_tensor_list=[] for i in range(levels): filter_tensor=self.butter_bandpass_filter(lap_video_list[i],low,high,fps) fi...
def drop_piece(self, piece): self.active_piece = Piece(piece) self.active_piece_pos = self.spawn_pos # if spawning on top of another piece, set game over if not self.can_fit(self.active_piece, self.active_piece_pos): self.is_over = True def handle_inputs(self): if se...
This function updates the game state by handling piece movement, locking, line clearing, scoring, and level progression. It checks for game over conditions, manages active pieces, processes player inputs, applies gravity, detects T-tricks, clears completed lines, calculates scores, and adjusts game speed based on the p...
def update_state(self): # check if game is over if self.is_over or self.reach_line_limit: return # drop new piece if none if self.active_piece is None: self.drop_piece(self.bag.grab_item()) # count frames self.frame_count += 1 # update stat...
def process_files(self): for filename in self.filenames: with open(filename, 'r') as file: self.process_data(file) def process_data(self, data): current_lines, tmp_text = 0, '' for line in data: line = line.rstrip().replace('"', '').split('\\n') ...
The code's main task is to sort data either from input files or standard input. If filenames are provided, it processes them; otherwise, it reads from stdin. After processing, it merges temporary files to produce the final sorted output.
def sort(self): if self.filenames: self.process_files() elif not sys.stdin.isatty(): self.process_data(sys.stdin.readlines()) self.merge_tmp_files()
def get_cocktails_that_have_given_ingredients(components: List[str]): cocktail_ids = {} for component in components: cocktails_from_component = cocktails_with_ingredient(component) for cocktail in cocktails_from_component: cocktail_ids[cocktail["idDrink"]] = cocktail["strDrink"] ...
The code determines which cocktails can be made using the provided ingredients by first identifying cocktails that contain some of the given ingredients, mapping each cocktail to its required ingredients, and then checking which of these cocktails can be fully made with the available ingredients.
def get_cocktails(ingredients): cocktails_that_contain_some_ingredients = ( get_cocktails_that_have_given_ingredients(ingredients) ) concktail2ingredient = get_cocktail2ingredients( cocktails_that_contain_some_ingredients ) cocktails = what_cocktail_can_i_make(concktail2ingredient,...
def deleteProj(self): """Delete a project """ try: projectRow = self.listWidget_ProjList.currentRow() # Grab Project Row projectName = self.listWidget_ProjList.takeItem(projectRow).text() # Get Project and remove del self.projects[projectName] # Delete proj...
This code sets up the user interface for a To-Do List application using PyQt. It creates and arranges UI elements like input fields, buttons (for adding/deleting projects/items), list widgets to display tasks, and a menu bar with a save action. The layout organizes components into a grid, connects buttons to methods (e...
def setupUi(self, MainWindow): MainWindow.setObjectName("ToDoList_App") MainWindow.resize(1050, 750) MainWindow.setMinimumSize(QtCore.QSize(1050, 750)) font = QtGui.QFont() font.setFamily("Fira Code") font.setPointSize(10) MainWindow.setFont(font) self.cen...
def preprocess(text): normalized = normalize(text) tokenized = tokenize(normalized) lemmatized = lemmatization(tokenized) without_stop_words = remove_stop_word(lemmatized) return without_stop_words def get_permuted_tree(redis_client): bin_tree = redis_client.get("permuted_tree") if bin_tree ...
The code performs a multi-strategy search: it processes queries with wildcards using a permuted tree, checks exact matches in a database, and applies fuzzy matching via Levenshtein distance for missing terms. It aggregates results, extracts URLs, and computes intersections of relevant documents across sub-queries, retu...
def search(index_db, redis_client, query): proccessed_query = preprocess(query) result_query = [] for q in proccessed_query: if "*" in q: tree = get_permuted_tree(redis_client) result_query += [search_tree(tree, q)] elif index_db.main.count_documents({"word": q}): ...
def preprocess(text): normalized = normalize(text) tokenized = tokenize(normalized) lemmatized = lemmatization(tokenized) without_stop_words = remove_stop_word(lemmatized) return without_stop_words def update_word(index_collection, redis_client, idx, title, word): if redis_client.exists(f"index:...
The function updates an index collection and Redis structures for text search. It processes text into unique words, maps each to its Soundex variant for phonetic matching, and updates a permuted tree for flexible querying. The permuted tree is modified with the text and saved, enhancing search capabilities for variatio...
def update_indexes(index_collection, redis_client, idx, title, text): words = set(preprocess(text)) for word in words: update_word(index_collection, redis_client, idx, title, word) s = to_soundex(word) redis_client.sadd(f"soundex:{s}", word) tree = get_permuted_tree(redis_client) ...
def get_file_path(file_type: str, required_cols: List[str], filename = None): """ input file report path and check for valid data """ valid_file = False while valid_file is False: print(f"Enter path for {file_type} file:") if filename is None: input_file = input() ...
The function `pull_clean_report_file` retrieves and processes maintenance log data, filtering records to include only those associated with zones and elevator numbers present in sensor alert data. It cleans the records, extracts relevant information, and returns a list of filtered `CleanRecord` objects along with the m...
def pull_clean_report_file(sensor_locations) -> Tuple[List[CleanRecord], datetime.datetime, datetime.datetime]: """ ask for maintenance log data file path process extract and cleaning records limiting records to zone and elevator numbers found in sensor alert data return list of records and min a...
def load_plugins(self): self._load_plugins_dynamically() def _execute_initial_command(self): self.command_handler.execute_command('menu') def _read_eval_print_loop(self): command_input = input(">>> ").strip() command_name, *args = command_input.split() self._execute_user_command(...
The code initializes by loading plugins and executing an initial command, then enters an infinite loop to continuously run a read-eval-print loop (REPL), allowing interactive command processing.
def start(self): self.load_plugins() self._execute_initial_command() while True: self._read_eval_print_loop()
def maxpool(self, x, kernel_size): p = np.floor((kernel_size - 1) / 2).astype(np.int32) p_x = tf.pad(x, [[0, 0], [p, p], [p, p], [0, 0]]) return slim.max_pool2d(p_x, kernel_size) def resblock(self, x, num_layers, num_blocks): out = x for i in range(num_blocks - 1): ou...
The code constructs a ResNet-50 encoder-decoder network for depth/disparity estimation. The encoder extracts hierarchical features via convolutional and residual blocks, while the decoder upsamples features using deconvolution/upconvolution, concatenating skip connections from the encoder. It generates multi-scale disp...
def build_resnet50(self): #set convenience functions conv = self.conv if self.params.use_deconv: upconv = self.deconv else: upconv = self.upconv with tf.variable_scope('encoder'): conv1 = conv(self.model_input, 64, 7, 2) # H/2 - 64D ...
def scale_pyramid(self, img, num_scales): scaled_imgs = [img] s = tf.shape(img) h = s[1] w = s[2] for i in range(num_scales - 1): ratio = 2 ** (i + 1) nh = h // ratio nw = w // ratio scaled_imgs.append(tf.image.resize_area(img, [nh,...
The code constructs a neural network model for stereo vision tasks, creating multi-scale input pyramids from left/right images. It conditionally concatenates inputs for stereo training, selects an encoder (VGG/ResNet50), and initializes model components based on training mode and configuration parameters, returning Non...
def build(self): with slim.arg_scope([slim.conv2d, slim.conv2d_transpose], activation_fn=tf.nn.elu): with tf.variable_scope('model', reuse=True): self.left_pyramid = self.scale_pyramid(self.left, 4) self.right_pyramid = self.scale_pyramid(self.right, 4) ...
def build(self): with slim.arg_scope([slim.conv2d, slim.conv2d_transpose], activation_fn=tf.nn.elu): with tf.variable_scope('model', reuse=True): self.left_pyramid = self.scale_pyramid(self.left, 4) self.right_pyramid = self.scale_pyramid(self.right, 4) ...
This code initializes a neural network model with parameters for training/testing, sets up model components (discriminator, fusion), defines input/output dimensions, and prepares for training by building model architecture, loss functions, and summaries. It configures batch size, image size, and training flags, then co...
def __init__(self, params, branch, mode, left, right, reuse_variables=None, model_index=0): self.params = params self.branch = branch self.mode = mode self.left = left self.right = right self.model_collection = ['model_' + str(model_index)] self.batch_size = para...
def connects_to_greenplum(): try: # Connect to an existing database global gp_connection gp_connection = psycopg2.connect(user="gpadmin", password="", host="10.4.8.131", port="5432", ...
The main task of the code is to process Bitcoin transactions in batches by fetching transaction data from a database, converting satoshi values to USD using historical exchange rates, updating the database with USD values, and managing Greenplum connections. It processes transactions in chunks, iterates through ranges,...
def main(): if not gp_connection or not gp_cursor: connects_to_greenplum() #load USD amounts into memory global date_usd_map date_usd_map = get_coindesk_usd_amounts(COINDESK_START, EXCHANGE_END_DATE) # iterate for total_txes entries total_txes = execute_sql_query("SELECT max(id) fr...
def connects_to_greenplum(): try: # Connect to an existing database global gp_connection gp_connection = psycopg2.connect(user="gpadmin", password="", host="10.4.8.131", port="5432", ...
The main task of the code is to convert Bitcoin transaction input and output values from Satoshi to USD using historical exchange rates, process data in chunks from a Greenplum database, update batches, and write results to CSV. It loads USD rates, iterates through transaction records, applies conversion, and manages d...
def main(): if not gp_connection or not gp_cursor: connects_to_greenplum() #load USD amounts into memory global date_usd_map date_usd_map = get_coindesk_usd_amounts(COINDESK_START, EXCHANGE_END_DATE) # iterate for input entries total_inputs = execute_sql_query("SELECT max(id) from ...
def __getUnigramMLE(self): N = self.corpus.N if N == 0: #if corpus size is 0 then something is wrong print("invalid corpus size") return; unigCount = self.__getUnigramCount() unigProb = dict() for elem in unigCount: unigProb[elem] = ((unigCount...
The code initializes a language model by setting up unigram and bigram probability distributions using Maximum Likelihood Estimation (MLE) and Laplace smoothing, leveraging a provided corpus. It stores corpus statistics, computes MLE probabilities, and applies Laplace smoothing for both unigrams and bigrams, enabling p...
def __init__(self, corpus): self.corpus = corpus #corpus type is corpusReader() self.N = corpus.N self.unigramMLE = self.__getUnigramMLE() self.bigramMLE = self.__getBigramMLE() self.unigramLaplace = self.__getUnigramLaplace() self.bigramLaplace = self.__getBigramLaplace(...
def get_ports(input_args: Namespace) -> Dict[str, Tuple[bool, int]]: """ Returns a map from an implementation to the host port its container port 53 should be mapped and whether that implementation should be tested. :param input_args: The input arguments """ implementations = {} implementat...
The function runs tests on DNS implementations by executing queries against containerized versions of the implementations, comparing their outputs. It logs test progress, timestamps, and errors, and saves discrepancies as JSON files. Containers are started based on input arguments, and tests are performed on zone files...
def run_tests(parent_directory_path: pathlib.Path, start: int, end: Optional[int], input_args: Namespace) -> None: """ Runs the tests in the parent directory path against all the implementations in the input arguments and compares their responses. If a difference in...
def set_window_size(self, x, y): self.setFixedSize(x, y) def initialize_window_stylesheet(self, window_stylesheet: dict): return self.__initialize(window_stylesheet) def __initialize_font_color(self, color_stylesheet): return self.__initialize(color_stylesheet) def __init_ui(self): self....
This code initializes a GUI window by setting its size, applying a background stylesheet, configuring font color and style, and calling a method to set up UI components. The class integrates with a main window, using a custom font and styling for a specific visual appearance.
def __init__(self, main: MainWindow): super().__init__() self.main = main self.set_window_size(700, 500) self.window_stylesheet = self.initialize_window_stylesheet({"background-color": "#361d32"}) self.font_color = self.__initialize_font_color({"color": "#f55951"}) self.f...
def look(self): if self.has_items(): sys.stdout.write(f"> {self.map[self.current_room]['name']}\n\n{self.map[self.current_room]['desc']}\n\nItems: {', '.join(self.map[self.current_room]['items'])}\n\nExits: {' '.join(self.map[self.current_room]['exits'].keys())}\n\n") else: sys.s...
The code runs a text-based adventure game where the player navigates rooms, collects items, and faces a boss. It checks for win/lose conditions based on inventory, processes user commands (e.g., move, pick up, drop), displays room details, and handles invalid inputs. The loop continues until the player quits or defeats...
def run(self): self.look() while(True): # winning and losing conditions if self.map[self.current_room]['name'] == "A boss room": if 'sword' in self.inventory and 'shield' in self.inventory: # win sys.stdout.write("You encountered a dragon and ...
def _generate_project_docs(self, output_format: str): """ Generates documentation for a Python project. Args: output_format (str): The format of the generated documentation. Supported formats are 'html' and 'markdown'. Returns: None """ try: ...
The code generates documentation from a project or module, converting content to HTML or Markdown format. It checks for input paths, processes content, applies templates if provided, and saves the output to a specified directory.
def generate_docs(self, output_path="docs_output", output_format="html"): """ Generates documentation based on the specified parameters. Args: output_path (str): The path to the directory where the generated documentation will be saved. Default is 'docs_output'. output_f...
def setupClients(self): con = self.DBconnection.cursor() con.execute("CREATE TABLE IF NOT EXISTS clients (id INT,client_name STRING, date DATE)") try: self.checkClients() except: raise ValueError("EE:Table clients could not be created!") def setupJobs...
The main task of the code is to create a database skeleton with tables for clients, jobs, and devices using SQLite. It connects to a database file, attempts to create each table, handles connection errors and potential setup errors, and returns a status indicating success (1) or failure (-1).
def createBlank(self,file): '''try to open/Create blank file''' print("=>Creating Database skeleton...") try: self.DBconnection = sqlite3.connect('BWO.db') except sqlite3.Error as E: print("EE:Database error: ",E) self.status = -1 ...
def setup(agent_config, network, service, sim_config, seed, episodes, weights, verbose, DATETIME, test, append_test, best, sim_seed, gen_scenario): """Overall setup for the rl variables""" if best: assert not (test or append_test or weights), "Cannot run 'best' with test, append_test, or weigh...
The code defines a CLI for training/testing reinforcement learning agents. It sets up configurations, executes training/testing via an agent helper, and saves results. Parameters include agent setup, simulation config, episodes, seeds, and testing options. The function handles both learning and evaluation phases, with ...
def cli(agent_config, network, service, sim_config, episodes, seed, test, weights, append_test, verbose, best, sim_seed, gen_scenario): """rlsp cli for learning and testing""" global logger # Setup agent helper class agent_helper = setup(agent_config, network, service, sim_config, seed, episode...
def setup_root(root: Path) -> None: if not root.exists(): root.mkdir() if any(root.iterdir()): if ConfirmPrompt( message=f"Target {root.name} is not empty, remove contents:", default=False, ).execute(): for i in root.iterdir(): if i.is_...
The main task of the code is to generate a project structure based on provided `ProjectInfo`, either in the current directory or a new directory named after the project. It confirms the directory choice, sets up the root path, creates necessary directories, and generates files according to the project configuration.
def main(info: ProjectInfo) -> None: current_dir: bool = ConfirmPrompt( message="Generate in current directory:", default=False ).execute() root = Path.cwd() if current_dir else Path.cwd() / info.name setup_root(root) generate_directories(info, root) generate_files(info, root)
def choose_random_starting_tile(self) -> Tile: row = choice(self.tiles) return choice(row) def add_neighbours_to_frontier(self, tile): for pos in tile.get_neighbours_position(): nx, ny = pos if 0 <= nx < self.w and 0 <= ny < self.h: tile = self.tiles[ny][n...
This code generates a maze by randomly selecting starting tiles, expanding the frontier of adjacent tiles, and connecting each newly added tile to a random neighbor until all tiles are included in the maze.
def generate_maze(self): tile = self.choose_random_starting_tile() self.maze.append(tile) self.add_neighbours_to_frontier(tile) while len(self.maze) < self.w*self.h: tile = self.choose_random_tile_from_frontier() self.maze.append(tile) self.add_neighbo...
def _ensure_cached_data(self, date, days, force_reload=False): offset_date = datetime.strptime(date, Arc2Core.DATE_FORMAT).date().toordinal() offset_today = datetime.now().date().toordinal() offset_upper = min(offset_date + days, offset_today) for day in range(offset_date, offset_upper)...
This function retrieves rainfall data for a specified location and date range by accessing cached data. It converts input coordinates and dates into indices, extracts the relevant data from the cache, and formats it into text for output.
def rainfall(self, latitude, longitude, date, days): self._ensure_cached_data(date, days) day_first = datetime.strptime(date, '%Y%m%d').date().toordinal() (lat, lng) = self._lat_long_to_pixel(latitude, longitude) idx = day_first - self.offset_start return self._data_to_txt(day_...
def MINIMAX_VALUE(GameObject,Gamestate): player = GameObject.PLAYER_TURN_DETECTOR(Gamestate) if GameObject.TERMINAL_TEST(Gamestate): return GameObject.UTILITY(Gamestate) elif player == 'MAX': value = -math.inf for action in GameObject.ACTIONS(Gamestate): value = max(value...
This function determines the optimal move for the minimizing player by evaluating all possible actions in the current game state using a specified minimax variant (standard, alpha-beta pruning, depth-limited, etc.). It iterates through each action, computes the resulting child node's minimax value, and selects the acti...
def HELPER_FOR_MIN_PLAYER_MOVE(GameObject,Gamestate,choice): val = math.inf for action in GameObject.ACTIONS(Gamestate): childNode = GameObject.RESULT(Gamestate,action) if choice == 1: minimax_val_child_node = MINIMAX_VALUE(GameObject,childNode) elif choice == 2: #min...
def Print_Text_On_Screen(screen,text_string,font_size,color,Vertical_Placement): font = pygame.font.Font('freesansbold.ttf', font_size) text = font.render(text_string,True,color) textRect = text.get_rect() textRect.center = (SCREEN_HORIZONTAL/2,Vertical_Placement) screen.blit(text,textRect) def Choose_Algorithm(s...
The main task of the code is to create a Tic Tac Toe game menu that displays options for selecting different algorithms, processes user input to initiate gameplay with the chosen algorithm, and allows exiting via the ESC key. It handles the main loop for rendering the menu, handling events, and transitioning to the gam...
def Game_TicTacToe(screen): running = True while running: screen.fill((255,0,0)) Print_Text_On_Screen(screen,"Welcome to Tic Tac Toe",25,(255,255,255),SCREEN_VERTICAL/5 -80) Choose_Algorithm(screen) Print_Text_On_Screen(screen,"Press ESCAPE: To Exit",20,(0,0,0),SCREEN_VERTICAL/5 + 300) for event in pyg...
def Print_Text_On_Screen(screen,text_string,font_size,color,Vertical_Placement): font = pygame.font.Font('freesansbold.ttf', font_size) text = font.render(text_string,True,color) textRect = text.get_rect() textRect.center = (SCREEN_HORIZONTAL/2,Vertical_Placement) screen.blit(text,textRect) def Choose_Algorithm(s...
The function `Game_OpenFieldTicTacToe` displays a menu screen for selecting algorithms in an Open Field Tic Tac Toe game. It shows warnings about performance for the first four algorithms and suggests using algorithm 5 (Experimental Minimax). The loop handles user input, allowing selection via number keys (1-5) to init...
def Game_OpenFieldTicTacToe(screen): running = True while running: screen.fill((255,0,0)) Print_Text_On_Screen(screen,"Welcome to Open Field Tic Tac Toe",25,(255,255,255),SCREEN_VERTICAL/5 - 80) Choose_Algorithm(screen) Print_Text_On_Screen(screen,"Press ESCAPE: To Exit",20,(0,0,0),SCREEN_VERTICAL/5 + 300)...
def MAX_MOVE(GameObject,Gamestate): # by HUMAN ---> called when the GameState has 'MAX' print('Game state is:') PRINT_GAME_STATE(Gamestate[0]) print('\nIts your turn:') print(' Legal actions:') i = 0 action_list = GameObject.ACTIONS(Gamestate) for action in action_list: print("{}). {...
The code implements a two-player game where a human (MAX) and an AI agent alternate turns. It initializes the game state, executes moves using MAX_MOVE for human input and GENERIC_GAME_PLAYING_AGENT for AI decisions, updates the state, and prints progress. The loop continues until a terminal state is reached, after whi...
def PlayGame(GameObject,choice): Gamestate = GameObject.initialState while(GameObject.TERMINAL_TEST(Gamestate) is False): if GameObject.PLAYER_TURN_DETECTOR(Gamestate) == 'MAX': action_by_max = MAX_MOVE(GameObject,Gamestate) # Move by Human NOTE:Here Gamestate indeed has 'MAX' ...
def Print_Text_On_Screen(screen,text_string,font_size,color,Vertical_Placement): font = pygame.font.Font('freesansbold.ttf', font_size) text = font.render(text_string,True,color) textRect = text.get_rect() textRect.center = (SCREEN_HORIZONTAL/2,Vertical_Placement) screen.blit(text,textRect) def Game_TicTacToe(scr...
This code initializes a Pygame window to display a game selection menu, showing options for TicTacToe and Open Field Tic Tac Toe. It handles user input via keyboard events, allowing users to launch selected games or exit using the ESC key. The loop continuously updates the screen with white background and colored text ...
def StartScreen(): pygame.init() screen = pygame.display.set_mode([600,600]) pygame.display.set_caption("Games") running = True while running: # Fill the background with white screen.fill((255, 255, 255)) Print_Text_On_Screen(screen,"Strategy Games",25,(0,255,0),SCREEN_VERTICAL/5) Print_Text_On_Scree...
def star_expression(self): self.current_values = [x for x in range(self.numeral_range.start, self.numeral_range.end+1)] def slash_expression(self,expression): values = expression.split("/") if len(values)!=2: raise Exception(f"Invalid slash expression: {expression}") ...
The code parses an expression by identifying its type (e.g., *, /, ,, -) and delegating to corresponding methods. If the expression is a numeral, it calls numeral_expression; otherwise, it treats it as a string. The function handles various expression formats by checking for specific characters and using try-except to ...
def parse(self, expression): if expression == "*": self.star_expression() elif expression.find("/")!=-1: self.slash_expression(expression) elif expression.find(",")!=-1: self.comma_expression(expression) elif expression.find("-")!=-1: self....
def CutOneLineTokens(sample): newList = [] str1 = "" inStringFlag = False for x in sample: #print(x) if x == '"': if inStringFlag == True: inStringFlag = False elif inStringFlag == False: inStringFlag = True if inStringFlag: str1 += x continue if x == "...
This function processes the next line of user input from a text box, tokenizes it, displays tokens in another box, parses them into outputs, highlights the current line, updates a counter, and shows an error if all lines are processed.
def gonextline(self): #self.populateTree() mytokens = [] #getting user input from txt box text = self.box1.get("1.0", "end") #putting it into a list lines = text.split('\n') if lines[-1] == '': lines[-1] = '\n' # removing last empty element if it exists # highlight previous line ...
def data_helper(params, mv_list, is_amp=False): total_df = pd.DataFrame() for idx, mv in enumerate(mv_list): df1 = pd.DataFrame() for param in params: if param.info['motion'] == mv: group = [param.info['BBS'] < 45] rms = list(np.nanmax(param.rms.data[...
The main task of the code is to evaluate movement modeling performance by selecting optimal features using RFECV, calculating classification metrics (e.g., Acc, AUC, F1), and storing results along with feature importance rankings for each movement type in MV_list. It processes train/test splits, applies feature selecti...
def movement_modeling_result(params, MV_list): mv_df = data_helper(params, MV_list) result_columns = ['MV', 'Acc', 'F', 'MCC', 'Sen', 'Spe', 'PPV', 'NPV', 'AUC', 'No. test'] result_df = pd.DataFrame(columns=result_columns) feature_list = ['RMS/R_TFL', 'RMS/R_QF', 'RMS/R_GC', 'RMS...
def data_helper(params, mv_list, is_amp=False): total_df = pd.DataFrame() for idx, mv in enumerate(mv_list): df1 = pd.DataFrame() for param in params: if param.info['motion'] == mv: group = [param.info['BBS'] < 45] rms = list(np.nanmax(param.rms.data[...
This function compares sensor performance metrics (Accuracy, F1, MCC, etc.) across different MV conditions using a random forest model. It processes each sensor-type/MV combination, trains/testes models, aggregates results into a dataframe, and generates a visualization plotting metric scores per sensor. The output inc...
def sensor_comparison_result(params, MV_list, is_MVC, title): mv_df = data_helper(params, MV_list) result_columns = ['MV', 'Sensor', 'Acc', 'F', 'MCC', 'Sen', 'Spe', 'PPV', 'NPV', 'AUC'] result_df = pd.DataFrame(columns=result_columns) for mv in tqdm(MV_list): for sensor in...
def start_HMM_display(S, expected_N, width=5000, height=5000, has_initial_state=True): '''Call this before calling show_next_time_step. S is the full set of states, including <S> and <E> special states, which must be at the beginning of S and end of S, respectively. However, these ...
The function generates a trellis diagram for a Hidden Markov Model (HMM) by visualizing states, transitions, and an observation sequence. It initializes the diagram with specified dimensions, iterates through time steps to display state transitions, and annotates each step with corresponding observations. The diagram i...
def show_entire_trellis(S, observation_sequence, width=1800, height=1000, has_initial_state=False): # Display all basic elements of a trellis diagram for a given HMM. # This includes nodes, edges, node labels (with state names), and an observation sequence. # The number of time steps shown depends on the ob...
def getCenterpoint(self): d = self.distance() a = d / 2 r = self.getRadius() h = math.sqrt(r * r - a * a) tempP = self.endpoint.substraction(self.startpoint).scalarMultiplication(a/d).addition(self.startpoint) c1 = Point2D((tempP.x + h * (self.endpoint.y - self.startpoin...
The code generates sample points along an arc between a start and end point on a circle. It calculates the center, start, and end angles, then interpolates points using trigonometric functions. Depending on the angle direction (clockwise/counter-clockwise), it computes coordinates for `steps` intervals, ensuring even s...
def sample(self, steps=2): cp = self.getCenterpoint() angle = self.centerAngle() # Start-angle dx_s = self.startpoint.x - cp.x dy_s = self.startpoint.y - cp.y t_start = self.angle(dx_s, dy_s) # End-angle dx_e = self.endpoint.x - cp.x dy_e = self....
def get_groupme_name(glob_vars): """ Get the groupme name from the global environment :param glob_vars: The global variable environment where the name is stored. :return: The name associated with the GroupMe bot. """ name = getattr(glob_vars, 'groupme_name', None) if name is None: in...
The main task of the code is to handle POST requests at the "/groupme" endpoint by detecting messages sent to a chat group, checking if they trigger a recognized command (e.g., ".ask"), and responding by sending a random question back to the group via the bot if conditions are met. It prevents the bot from reacting to ...
def post(self): """ Method to handle requests for POST /groupme to notify the bot when a message is sent to a chat that it is a part of. If the message is a recognized command, respond to the command and send the response back to the originating group. :return: "ok" text string, ...
def create_highlight_surface(self): """ A surface where we draw pin highlights. Gets completely redrawn on window resize. Gets partially redrawn when the user moves the mouse. """ allocation = self.get_allocation() # Create a separate surface for hi...
This method initializes a Cairo drawing surface for rendering SVG content on a widget. It calculates scaling ratios to fit the SVG within the widget's size, creates a background, renders the SVG, and sets up additional surfaces for highlighting pins, new wires, and connections. The task involves preparing the visual la...
def on_configure(self, widget, event): """ Initialise our surface where the actual drawing happens. When the draw event happens, we paint this surface to the actual widget. We have separate surfaces for highlighting pins, new wires, and existing conn...
def to_svg_coordinates(self, x, y): allocation = self.get_allocation() ratio_x = self.pin_manager.svg_handle.props.width / allocation.width ratio_y = self.pin_manager.svg_handle.props.height / allocation.height scale = max(ratio_x, ratio_y) return scale * x, scale * y def draw_...
This method handles button release events to manage pin connections in a diagram. It converts mouse coordinates to SVG coordinates, identifies the nearest pin, and checks proximity (≤5 units) to either create a new connection between pins or remove existing ones using the right mouse button. If a new wire start exists,...
def on_button_release(self, widget, event): svg_x, svg_y = self.to_svg_coordinates(event.x, event.y) nearest_pin = self.pin_manager.nearest_pin((svg_x, svg_y)) dist = 0 if nearest_pin: dist = math.sqrt((nearest_pin.x - svg_x)**2 + (nearest_pin.y - svg_y)**2) ...
def to_svg_coordinates(self, x, y): allocation = self.get_allocation() ratio_x = self.pin_manager.svg_handle.props.width / allocation.width ratio_y = self.pin_manager.svg_handle.props.height / allocation.height scale = max(ratio_x, ratio_y) return scale * x, scale * y def unhig...
This method handles mouse motion events to detect proximity to SVG pins, highlighting the nearest pin within 5 units and initiating wire drawing when the left mouse button is pressed. It converts mouse coordinates to SVG scale, checks for nearest pins, manages highlighting, and triggers wire drawing if a pin is selecte...
def on_motion_notify(self, widget, event): # Convert mouse x and y to coordinates relative to the original SVG size scaled_x, scaled_y = self.to_svg_coordinates(event.x, event.y) # Find the nearest pins close to the mouse nearest_pin = self.pin_manager.nearest_pin((scaled_x, scaled_y)) ...
def has_reached_end_state(self, graph_path: list, start: Graph, end: Graph) -> bool: latest_graph = graph_path[-1][0] reached_end_state = True if self.has_subgraph(latest_graph, end, include_edges_to_outsiders=True) else False if reached_end_state: self.save_graph_path(graph_path, s...
The code searches for a proof by applying transformation rules to graphs, expanding paths iteratively. It prunes redundant paths to avoid cycles, applies rules to swap subgraphs (a→b or b→a), and checks if any path reaches the end state. If a solution is found within 30 iterations, it saves the path. The main task is t...
def find_proof(self): start = self.start end = self.end rules = self.rules graph_paths = [[(copy.deepcopy(start), "-")]] count = 0 while not any(self.has_reached_end_state(graph_path, start, end) for graph_path in graph_paths) and count < 30: count += 1 ...
def find_bush(self): """ sort the bush by distance and assigned it to self.bushResult :return: True or False (boolean) """ if self.results: self.bushResult = self.ordered_bush_by_distance(self.bush_index) if self.bushResult: return True els...
The code manages a bot's state transitions to search for bushes, move toward them, hide, and attack enemies. It switches between states (INITIALIZING, SEARCHING, MOVING, HIDING, ATTACKING) based on conditions like bush detection, movement status, enemy proximity, and timers. The bot performs random movements when stuck...
def run(self): while not self.stopped: sleep(0.01) if self.state == BotState.INITIALIZING: # do no bot actions until the startup waiting period is complete if time() > self.timestamp + self.INITIALIZING_SECONDS: # start searching when t...
def login(self, role_id: str, secret_id: str) -> str: """ Login using an Approle. Returns the client token after successful login. """ url = urllib.parse.urljoin(self._vault_address, f"v1/auth/{self._approle_mount_path}/login") data = {"role_id": role_id, "secret_id": secret_id} resp = s...
The code rotates a secret ID using a specified strategy, checks its validity period, and returns rotation status. It logs in with provided credentials, retrieves secret metadata, calculates remaining validity time, and triggers rotation if needed. The result includes validity metrics, rotation flag, and potential error...
def rotate_secret_id(self, role_id: str, secret_id: str, role_name: str = None, rotation_strategy: SecretIdRotationStrategy = None) -> Dict: if not SecretIdRotationStrategy: rotation_strategy = ValidityPeriodRotationStrategy(DEFAULT_MIN_VALIDITY_PERIOD_PERCENT) self._vault_token = self.logi...
def get_mini_batches(self, X, y, batch_size): n = X.shape[1] mini_batches = list() for i in range(0, math.floor(n / batch_size)): mx = X[:, i * batch_size: (i + 1) * batch_size] my = y[:, i * batch_size: (i + 1) * batch_size] mini_batch = (mx, my) ...
The code trains a neural network using mini-batch gradient descent over multiple epochs. It shuffles data, splits it into mini-batches, performs forward and backward passes to compute gradients, then updates weights and biases (W1-W3, b1-b3) iteratively using the learning rate to minimize loss.
def train(self, X, y): # i = 0 for i in range(0, self.num_epochs): # j = 0 random = np.arange(len(X[1])) np.random.shuffle(random) X_shuffle = X[:, random] y_shuffle = y[:, random] mini_batches = self.get_mini_batches(X_shuffle, y_...
def _rCon(self, word, rcon) -> list: """ * Function XOR a given word with a given rcon """ result = hex(int(word[0], 16) ^ rcon) word[0] = result if len(result) == 4 else self._patchHex(result) return word def _subWord(self, word) -> list: """ * Function ...
This function generates AES subkeys from the original key through key expansion. It processes input key bytes, splits them into 4-byte words, and applies transformations like rotation, substitution, and XOR in a loop. The result is a list of subkeys used in AES rounds, with the number of subkeys depending on the key le...
def _getRoundKeys(self, key) -> list: """ * Functions performs key whitening/ key schedule.The key schedule takes the original * input key (of length 128, 192 or 256 bit) and derives the subkeys used in AES. * The number of subkeys is equal to the number rounds plus one, due to the key ...
def _divideIntoBlocks(self, plaintext) -> list: """ * Function performs the division of the input text into blocks of 128bit (16 bytes) * This function operates on two cases; Case 1: PLaintext in hex value Case 2: Plaintext in ascii characters """ #? Divide plaintext into block ...
This code decrypts data using AES by reversing encryption steps: it applies inverse operations (invSubBytes, invShiftRows, invMixColumns) with round keys in reverse order, starting from the final encryption round, then intermediate rounds, and finally the initial round, reassembling the plaintext from the processed sta...
def decrypt(self, state, key): """ * Function start the reverse encryption process. """ #? Starts with Final round of encryption state = self._divideIntoBlocks(state)[0] roundKeys = self._getRoundKeys(key) self._addRoundKey(roundKeys[self.Nr], state) #? For 12...
def _divideIntoBlocks(self, plaintext) -> list: """ * Function performs the division of the input text into blocks of 128bit (16 bytes) * This function operates on two cases; Case 1: PLaintext in hex value Case 2: Plaintext in ascii characters """ #? Divide plaintext into block ...
This code encrypts plaintext using a key via AES-like rounds. It validates key length, divides plaintext into blocks, expands the key, applies substitution, shifting, mixing, and round key addition across multiple rounds, then reassembles blocks into ciphertext.
def encrypt(self, plaintext, key) -> str: #? Cast input to str and checks key's length assert len(key) in (16, 24, 32, 48, 64), "Warning: Invalid key length." key = str(key) if type(key) == int else key plaintext = str(plaintext) if type(plaintext) == int else plaintext block...
def check_cpu(cpuString: str) -> list: print("{:=<158}".format("# PROCESSOR ")) try: print(f"CPU STRING: {cpuString}") cpuString = re.sub(r"(\(R\)|\s{2,}|@|\+|-|™|®|,|\d\.?\d{,2}[gm]hz)", " ", cpuString, re.IGNORECASE) print(f"CPU STRING: {cpuString}") matchingPhrases = [] ...
The code processes a dictionary of game objects, extracting and validating system requirements (CPU, GPU, memory, storage) using helper functions. It updates valid requirements in each game's data and compiles a new dictionary of games with non-empty CPU/GPU checks, returning it.
def walk_game_obj(gamesObj: dict) -> dict: outPutGames = {} for game in gamesObj.values(): systemSection = game["SYSTEM_REQUIREMENTS"] cpu = systemSection["PROCESSORS"] gpu = systemSection["GRAPHICS"] memory = systemSection["MEMORY"] storage = systemSection["STORAGE"] ...
def extract_links(htmlBuffer): encodedHTML = BS(htmlBuffer, 'lxml') print("[*] SERACHING FOR LINKS...") anchorElements = encodedHTML.find_all('a') print("=" * 100) for anchor in anchorElements: link = anchor['href'] print("[+] NEW LINK FOUND: {}".format(link)) EXTRACTED_LIN...
The main task of the code is to repeatedly send HTTP requests to a Steam API endpoint, extract HTML results from the JSON response, and process links iteratively. It handles errors during requests, increments a counter for pagination, and calls `crawl_links()` after completing all iterations.
def pull_links(): request_start = 0 for i in range(ITERATIONS): print("[*] STEAM REQUEST ITERATIONS: {}".format(i)) try: print("[*] SENDING REQUEST TO STEAM...") print("[i] REQUEST: {}".format(URL.format(request_start, COUNT))) steamResponse = R.get(URL.format...
def load_json_file(fileName: str) -> dict: try: json_obj = None fileParser = open(fileName, encoding="UTF-8", mode='r') json_obj = json.load(fileParser) return json_obj except Exception as E: print(f"FILE LOADING ERROR: {E}") def walk_game_obj(gamesObj: dict) -> dict: ...
The code loads a JSON file containing game data, connects to a MongoDB instance, selects a database and two collections (CPU and GPU), processes the game data using `walk_game_obj`, and exports the evaluated results to a new JSON file with "_evaluated" appended to the original filename.
def main(): fileName = input("FILE NAME: ") #fileName = "./data/games.json" gamesObj = load_json_file(fileName) HOST = "mongodb://localhost:27017" try: CLIENT = pymongo.MongoClient(HOST) except Exception as E: print(f"MONGO CONNECT ERROR: {E}") databases = CLIENT.list_datab...
def evaluate(expr): result = lldb.debugger.GetSelectedTarget().EvaluateExpression(expr) log(lambda : "evaluate: {} => {}".format(expr, result)) return result def _symbol_loaded_address(name, debugger = lldb.debugger): target = debugger.GetSelectedTarget() process = target.GetProcess() thread = p...
This function checks if a given value is a Kotlin String or an array by evaluating type information using hexadecimal addresses. It logs results and benchmarks performance, returning 1 for String instances, 2 for arrays, and 0 otherwise.
def is_string_or_array(value): start = time.monotonic() soa = evaluate("(int)IsInstance({0:#x}, {1:#x}) ? 1 : ((int)Konan_DebugIsArray({0:#x})) ? 2 : 0)" .format(value.unsigned, _symbol_loaded_address('kclass:kotlin.String'))).unsigned log(lambda: "is_string_or_array:{:#x}:{}".format(valu...
def host_llvm_target(): return "Native" def force_create_directory(parent, name) -> Path: build_path = parent / name print(f"Force-creating directory {build_path}") if build_path.exists(): shutil.rmtree(build_path) os.mkdir(build_path) return build_path def llvm_build_commands( i...
The function `build_distribution` performs a multistage build of LLVM (typically 1 or 2 stages) to generate a reproducible distribution. In a two-stage bootstrap process, stage 1 builds LLVM, which then compiles the source again in stage 2, ensuring environment independence. It creates temporary build directories, exec...
def build_distribution(args): """ Performs (probably multistage) build of LLVM and returns path to the final distribution. """ current_dir = Path().absolute() num_stages = args.num_stages bootstrap_path = args.stage0 intermediate_build_results = [] # Most likely, num_stages will be 1...
def _field_type(self, index): return evaluate("(int)Konan_DebugGetFieldType({:#x}, {})".format(self._valobj.unsigned, index)).unsigned def _field_address(self, index): return evaluate("(void *)Konan_DebugGetFieldAddress({:#x}, {})".format(self._valobj.unsigned, index)).unsigned def log(msg): if logg...
This function reads a value at a specified index by determining its data type and memory address, logs diagnostic information, and converts the value using a type-specific handler from the _TYPE_CONVERSION mapping.
def _read_value(self, index): value_type = self._field_type(index) address = self._field_address(index) log(lambda: "_read_value: [{}, type:{}, address:{:#x}]".format(index, value_type, address)) return _TYPE_CONVERSION[int(value_type)](self, self._valobj, address, str(self._field_name(i...
def log(msg): if logging: sys.stderr.write(msg()) sys.stderr.write('\n') exelog(msg) def is_string_or_array(value): start = time.monotonic() soa = evaluate("(int)IsInstance({0:#x}, {1:#x}) ? 1 : ((int)Konan_DebugIsArray({0:#x})) ? 2 : 0)" .format(value.unsigned, _symbo...
The function selects a provider based on the type of `lldb_val` (string, array, or object) using a factory pattern. It logs debug information, measures execution time, and returns an instance created by the appropriate factory method from `__FACTORY`, determined by checking if `lldb_val` is a string/array via `is_strin...
def select_provider(lldb_val, tip, internal_dict): start = time.monotonic() log(lambda : "select_provider: {:#x} name:{} tip:{:#x}".format(lldb_val.unsigned, lldb_val.name, tip)) soa = is_string_or_array(lldb_val) log(lambda : "select_provider: {:#x} : soa: {}".format(lldb_val.unsigned, soa)) ret = ...
def build_parser() -> argparse.ArgumentParser: parser = argparse.ArgumentParser(description="Build LLVM toochain for Kotlin/Native") # Output configuration. parser.add_argument("--install-path", type=str, default="llvm-distribution", required=False, help="Where final LLVM distributio...
The main task of the code is to build a distribution from an LLVM repository, handling temporary clones if no source is provided, creating archives with checksums, and cleaning up temporary files if specified. It parses arguments, sets up the environment, clones the repository if needed, builds the distribution, and op...
def main(): parser = build_parser() args = parser.parse_args() setup_environment(args) temporary_llvm_repo = None if args.llvm_src is None: temporary_llvm_repo = clone_llvm_repository(args.repo, args.branch, args.llvm_repo_destination) args.llvm_src = temporary_llvm_repo final_di...
def _read_value(self, index): value_type = self._field_type(index) address = self._field_address(index) log(lambda: "_read_value: [{}, type:{}, address:{:#x}]".format(index, value_type, address)) return _TYPE_CONVERSION[int(value_type)](self, self._valobj, address, str(self._field_name(i...
This function retrieves a value from a data structure at a given index. If the value exists, it returns either the direct value or the dereferenced value based on type information. If the value is None, it logs a debug message and returns None.
def _deref_or_obj_summary(self, index, internal_dict = {}): value = self._read_value(index) if not value: log(lambda : "_deref_or_obj_summary: value none, index:{}, type:{}".format(index, self._children[index].type())) return None return value.value if type_info(value) el...
def log(msg): if logging: sys.stderr.write(msg()) sys.stderr.write('\n') exelog(msg) def bench(start, msg): if bench_logging: print("{}: {}".format(msg(), time.monotonic() - start)) def type_info(value): """This method checks self-referencing of pointer of first member of TypeInf...
This function generates a summary string for a Kotlin object in LLDB by checking the object's type, retrieving type information, using a provider to format the value, and returning a shortened string representation for debugging purposes. It handles edge cases like null values and fallback representations.
def kotlin_object_type_summary(lldb_val, internal_dict = {}): """Hook that is run by lldb to display a Kotlin object.""" start = time.monotonic() log(lambda: "kotlin_object_type_summary({:#x}: {})".format(lldb_val.unsigned, lldb_val.type.name)) fallback = lldb_val.GetValue() if lldb_val.GetTypeName(...
def log(msg): if logging: sys.stderr.write(msg()) sys.stderr.write('\n') exelog(msg) def bench(start, msg): if bench_logging: print("{}: {}".format(msg(), time.monotonic() - start)) def type_info(value): """This method checks self-referencing of pointer of first member of TypeInf...
This code initializes a synthetic provider for a given value object (valobj) by determining its type and validity. It logs diagnostic information, benchmarks performance, and selects an appropriate provider (e.g., null, uninitialized, or custom) via `select_provider`, assigning it to `self._proxy` for further processin...
def __init__(self, valobj, internal_dict): start = time.monotonic() log(lambda : "KonanProxyTypeProvider:{:#x}, name: {}".format(valobj.unsigned, valobj.name)) if valobj.unsigned == 0: log(lambda : "KonanProxyTypeProvider:{:#x}, name: {} NULL syntectic {}".format(valobj.unsigned, valo...
def tm_wrapper(self, digit, the_type='T'): value_ = "" joiner = "" if the_type == 'T': # thousand value_ = self.THOUSAND_MILL[0] else: value_ = self.THOUSAND_MILL[1] joiner = self.LONA if digit > self.THOUS_MILL_ADD_JOIN_PT else "" digit_transl...
The code converts a numeric input into its English word representation by breaking it into millions, thousands, and remaining digits. It processes each segment using helper methods (`tm_wrapper`, `translation_engine`), applies connectors like "and" between non-zero segments, and combines them into a fluent textual form...
def processInput(self, digit): self.MILLION_DIGIT = digit // 1000000 self.THOUSAND_DIGIT = ((digit % 1000000) // 1000) self.OTHER_DIGIT = ((digit % 1000000) % 1000) million_exists = False thousands_exists = False MIL = "" TH = "" others = "" # ...
def generiraj_mine(self, xne, yne): ze_generirane_mine = [] for i in range(self.stevilo_min): x = random.randint(0, self.velikostx - 1) y = random.randint(0, self.velikosty - 1) while ((x, y) in ze_generirane_mine) or preveri_okoli(xne, yne, x, y): x...
This function handles a mouse click in a Minesweeper game by initializing a recursion table, generating mines on the first click, revealing cells, checking for mine hits, and ending the game if the player clicks a mine or wins.
def klik(self, x, y): if not self.konec: for i in range(self.velikosty): self.tabela_rekurzija.append([]) for j in range(self.velikostx): self.tabela_rekurzija[i].append(False) if self.prvic: self.prvic = False ...
def initialize_timers(self): """ Initialize the timers frame, time_left, wpm, and cpm labels. """ # Create timers frame self.timers_frame = CTkFrame(self, fg_color="transparent") self.timers_frame.pack() # Initialize time_left label and variable self.time...
This code initializes a GUI view for a word-based application, loading and shuffling words from a CSV file. It sets up a canvas for displaying words, an entry widget for user input, and timers for tracking progress. The view includes event bindings for dynamic resizing and input changes, along with a switch_view functi...
def __init__(self, parent, switch_view, *args, **kwargs): """ Initialize the MainView. Args: parent (Tk): The parent Tkinter window. switch_view (function): Function to switch to a different view. *args, **kwargs: Additional arguments for CTkFrame initializat...
def check_final_word(self, word_frame): """ Check and process the correctness of the final word typed by the user. Args: word_frame (tkinter.Frame): The current word frame. """ # Get the word entered by the user (without the last space) word_entered = self.entry_...
This code handles text input callbacks by managing a timer, validating entered letters against target words, and updating visual feedback (colors) for correct/incorrect letters. It advances to the next word on space input, scrolls content, and removes off-screen elements while tracking active word indices.
def entry_text_callback(self, var=None, index=None, mode=None): """ Handle the callback when there is a change in the entry text. Args: var: The StringVar object (default is None). index: The index value (default is None). mode: The mode value (default is Non...
def hash_graph(k, l, r, graph): """ Hash entire graph into a table of desired size using LSH. :param k: number of hash functions per table :param l: number of tables :param r: range of hash function :param graph: the graph to be hashed :return: A hash table that contains the hash values of t...
The main task of the code is to benchmark and compare the performance of a Locality-Sensitive Hashing (LSH) algorithm against a non-LSH approach for merging graph nodes. It evaluates merging efficiency (time and nodes merged) and similarity to the original graph using a distance metric. The tests are conducted on real-...
def run_tests(): ### ERDOS RENYI TEST print("REAL WORLD") g3 = read_graph.read_graph("USAir97.mtx") g = open("graph_out.txt", "w") g.write(str(g3)) #print(g3) # timeE2 = time.time() # print(str(timeE2 - timeE1)) ###FOR NON-LSH ALGORITHM g4 = copy.deepcopy(g3) ###ORIGINAL UNM...
def erdos_renyi(n, p): """ Generate a random Erdos-Renyi graph with n nodes and edge probability p. Arguments: n -- number of nodes p -- probability of an edge between any pair of nodes Returns: undirected random graph in G(n, p) """ g = {} ### Add n nodes to the graph for...
The code compares similarity scores of LSH and non-LSH methods during node-merging iterations on a graph. It generates an Erdos-Renyi graph, applies both methods to merge nodes while tracking similarity metrics after each merge, and returns a dictionary with merged node counts and corresponding similarity scores for bo...
def produce_time_series(): """ Compare the simlarity scores of the LSH vs non-LSH methods after each iteration of node-merging """ g3 = erdos_renyi(10000, 0.001) ###FOR NON-LSH ALGORITHM g4 = copy.deepcopy(g3) ###ORIGINAL UNMERGED GRAPH g5 = copy.deepcopy(g3) hg3, hf3 = hash_graph(...
def erdos_renyi(n, p): """ Generate a random Erdos-Renyi graph with n nodes and edge probability p. Arguments: n -- number of nodes p -- probability of an edge between any pair of nodes Returns: undirected random graph in G(n, p) """ g = {} ### Add n nodes to the graph for...
The function `produce_plot_data` generates comparative data for plotting the performance of LSH-based and non-LSH graph merging algorithms on Erdos-Renyi and clustered graphs. It measures nodes merged, execution time, and similarity differences across multiple trials, returning structured data for visualizing time effi...
def produce_plot_data(): """ Plot all desired data """ ###ERDOS RENYI GRAPH PLOTS er_data = [[[], [], []], [[], [], []]] for a in range(NUM_DATA_POINTS): print("a = " + str(a)) g3 = erdos_renyi(10000, 0.001) ###FOR NON-LSH ALGORITHM g4 = copy.deepcopy(g3) ...
def load_data(camera_path, object_path): camera_recording = load_rosbag(camera_path) object_poses = load_rosbag(object_path) return camera_recording, object_poses def load_pointclouds(path): pointclouds= ply.read_ply(path) return pointclouds def center_objects(data,marker_offset=[0, 0, -0.027]): ...
The code processes point cloud and camera data to generate a COCO-style dataset. It extracts object poses, creates 3D point cloud representations, computes transformations, and generates annotations with masks, bounding boxes, and camera intrinsics. The output is saved as a JSON file containing images, object metadata,...
def create_coco_style_data(images,plc_pths,length1,args): images_dic=[] annotation=[] models=[] C_stack=np.empty((4,4)) length=len(images) camera_recording, object_poses = load_data(args.camera_path, args.object_path) t=0 for plc_path in plc_pths: pos=plc_path.find('_pc_') ...
def load_data(camera_path, object_path): camera_recording = load_rosbag(camera_path) object_poses = load_rosbag(object_path) return camera_recording, object_poses def save_images_from_bag(camera_path,image_topic,path): bag = rosbag.Bag(camera_path, "r") bridge = CvBridge() count = 0 if not o...
The main task of the code is to process a ROS bag file by extracting RGB images and point cloud data, then generate COCO-style annotations. It loads data, saves RGB images from the bag, collects image and point cloud file paths, and creates a structured dataset with counts for further processing.
def process_rosbag(args): camera_recording, pt_clouds, = load_data(args.camera_path, args.object_path) #objects = center_camera(camera_recording, objects) #objects = generate_binary_masks(camera_intrinsics, objects) path=os.path.dirname(os.path.abspath(__file__)) save_images_from_bag(args....
def rela_to_uk_reloc(rela): # Offset and Sym. Name + Addend already have the link time address added offset = int(rela['Offset'], 16) - BASE_ADDR value = int(rela['Sym. Name + Addend'], 16) - BASE_ADDR # We cannot have a 64-bit PIE with 32-bit or 16-bit relocations, # so only 8 bytes per relocation...
The function processes dynamic relocations from an ELF file, converts them into UK relocations, gathers associated symbols, filters out relocations exceeding a specified memory offset, and returns the filtered list of UK relocations.
def build_uk_relocs(elf, rela_dyn_secs, max_r_mem_off): uk_relocs = [rela_to_uk_reloc(r) for r in rela_dyn_secs] uk_reloc_syms = get_nm_syms(elf, get_uk_reloc_sym_exp(r'data')) uk_reloc_syms += get_nm_syms(elf, get_uk_reloc_sym_exp(r'imm')) # Also gather all of the PTE uk_reloc's for use against reloca...
def get_nm_syms(elf, sym): nm_sym_exp = get_nm_sym_exp(sym) out = subprocess.check_output(["nm", elf]) _nm_syms = re.findall(nm_sym_exp, out.decode('ASCII'), re.MULTILINE) return [s for s in _nm_syms if x86_ignore_sym_substring not in s[1]] def get_shdrs(elf): sh_exp = get_shdr_exp() out = sub...
(The main task of the code is to process an ELF binary to generate a `.uk_reloc.bin` file containing structured relocation entries. It validates required ELF sections, extracts relocation data from `.rela.dyn`, ensures alignment with `.dynamic` metadata, and writes entries in a specific format with endianness support, ...
def main(): parser = argparse.ArgumentParser( description='Builds the .uk_reloc section off the .rela. and .symtab' 'ELF sections') parser.add_argument('elf', help='path to ELF binary to process') parser.add_argument('-b', '--big', action="store_true", hel...
def get_args(): parser = ArgumentParser() parser.add_argument("--corpus", required=True) parser.add_argument("--output_dir", "-o", required=True) return parser.parse_args() def documents_iterator(directory, add_fid): files = listdir(directory) for file in files: if not file.endswith(".js...
The main task of the code is to process a corpus of documents by iterating through subfolders, parsing their contents, and saving them as structured JSON files in an output directory. It reads input from command-line arguments, skips invalid subfolders, and converts document contents into a standardized format with IDs...
def main(): N = -1 args = get_args() root_path = args.corpus output_dir = args.output_dir os.makedirs(output_dir, exist_ok=True) subfolders = sorted(listdir(root_path), key=lambda k: int(k)) add_fid = 'task2' in args.corpus for subfolder in tqdm(subfolders, desc="Looping over each folder...
def is_list_img(v): return isinstance(v, list) and len(v) > 0 and isinstance(v[0], list) and len(v[0]) > 0 and (isinstance(v[0][0], list) or isinstance(v[0][0], tuple)) and len(v[0][0]) == 3 def list_to_html(arr, **kwargs): return ndarray_to_html(list_to_ndarray(arr), **kwargs) def is_ndarray_img(v): return isinstan...
This function converts image data (either a list of images or a NumPy ndarray) into HTML format with 'png' encoding. It checks the input type and uses corresponding conversion functions, returning None if the input isn't recognized as image data.
def if_img_convert_to_html(v): if is_list_img(v): return list_to_html(v, format='png') elif is_ndarray_img(v): return ndarray_to_html(v, format='png') else: return None
def load_code_lines(file_name): with open(file_name) as f: lines = f.readlines() strip_comments(lines) replace_empty_lines_with_noop(lines) return lines def compute_writes(lines): exception = None try: done = False while not done: try: code = "".join(lines) root = ast.parse(code) done = True ...
The main task of the code is to analyze a given code file by computing write operations and runtime data, handling exceptions during processing, and saving results (including return code, writes, and runtime data) into a JSON file named 'file.out'. If exceptions occur, they are raised after logging the error state.
def main(file): lines = load_code_lines(file) return_code = 0 run_time_data = {} (writes, exception) = compute_writes(lines) if exception != None: return_code = 1 else: (run_time_data, exception) = compute_runtime_data(lines) if (exception != None): return_code = 2 with open(file + ".out", "w") as o...
def is_loop_str(str): return re.search("(for|while).*:", str.strip()) != None def indent(str): return len(str) - len(str.lstrip()) def stmts_in_loop(self, lineno): result = [] curr_stmt = self.lines[lineno] loop_indent = indent(curr_stmt) for l in range(lineno+1, len(self.lines)): line = self.lines[l] i...
This function tracks active loops by checking if the current line is a loop. If a loop at the same line already exists in the active loops list, it increments the iteration count. Otherwise, it adds a new LoopInfo object to the list, including the frame, line number, and indentation. It then appends dummy environments ...
def record_loop_begin(self, frame, lineno): # for l in self.active_loops: # print("Active loop at line " + str(l.lineno) + ", iter " + str(l.iter)) curr_stmt = self.lines[lineno] if is_loop_str(curr_stmt): if len(self.active_loops) > 0 and self.active_loops[-1].lineno == lineno: self.active_loops[-1].it...
def remove_R(lineno): if isinstance(lineno, str): return int(lineno[1:]) else: return lineno def indent(str): return len(str) - len(str.lstrip()) def is_return_str(str): return re.search("return", str.strip()) != None def stmts_in_loop(self, lineno): result = [] curr_stmt = self.lines[lineno] loop_indent ...
This function handles the termination of a loop by adjusting iteration counts and updating loop data. It checks if the loop ends via a return or break, increments the loop's iteration counter, appends dummy environments to loop statements, and removes the loop from active tracking. It ensures proper cleanup and data re...
def record_loop_end(self, frame, lineno): curr_stmt = self.lines[lineno] if self.prev_env != None and len(self.active_loops) > 0 and self.active_loops[-1].frame is frame: prev_lineno = remove_R(self.prev_env["lineno"]) prev_stmt = self.lines[prev_lineno] loop_indent = self.active_loops[-1].indent curr_...
def is_list_img(v): return isinstance(v, list) and len(v) > 0 and isinstance(v[0], list) and len(v[0]) > 0 and (isinstance(v[0][0], list) or isinstance(v[0][0], tuple)) and len(v[0][0]) == 3 def list_to_html(arr, **kwargs): return ndarray_to_html(list_to_ndarray(arr), **kwargs) def is_ndarray_img(v): return isinstan...
The code converts image data (either a list or NumPy ndarray) to HTML with PNG format. It checks the input type: if it's a list of images, it uses `list_to_html`; if a NumPy array, it uses `ndarray_to_html`. If neither, it returns `None`.)
def if_img_convert_to_html(v): if is_list_img(v): return list_to_html(v, format='png') elif is_ndarray_img(v): return ndarray_to_html(v, format='png') else: return None
def add_loop_info(self, env): env["#"] = self.active_loops_iter_str() env["$"] = self.active_loops_id_str() def compute_repr(self, v): if isinstance(v, types.FunctionType): return None if isinstance(v, types.ModuleType): return None html = if_img_convert_to_html(v) if html == None: return repr(v) ...
This function records the current execution environment, including local variables, time, and line number, into a data structure. It limits recording to 100 frames, skips predefined variables, computes variable representations, and links consecutive environments. The data is stored for debugging/tracing purposes, with ...
def record_env(self, frame, lineno): if self.time >= 100: self.set_quit() return env = {} env["frame"] = frame env["time"] = self.time self.add_loop_info(env) self.time = self.time + 1 for k in frame.f_locals: if k != magic_var_name and (frame.f_code.co_name != "<module>" or not k in self.preexis...
def record_loop_end(self, frame, lineno): curr_stmt = self.lines[lineno] if self.prev_env != None and len(self.active_loops) > 0 and self.active_loops[-1].frame is frame: prev_lineno = remove_R(self.prev_env["lineno"]) prev_stmt = self.lines[prev_lineno] loop_indent = self.active_loops[-1].indent curr_...
Your return The code processes a stack frame to record loop boundaries and environment variables at specific line numbers. It skips list/dict comprehensions and non-"<string>" files. It tracks module-level variables, adjusts line numbers, and calls methods to log loop ends, environments, and loop beginnings for analy...
def user_line(self, frame): # print("user_line ============================================") # print(frame.f_code.co_name) # print(frame.f_code.co_names) # print(frame.f_code.co_filename) # print(frame.f_code.co_firstlineno) # print(dir(frame.f_code)) # print("lineno") # print(frame.f_lineno) # print...
def record_env(self, frame, lineno): if self.time >= 100: self.set_quit() return env = {} env["frame"] = frame env["time"] = self.time self.add_loop_info(env) self.time = self.time + 1 for k in frame.f_locals: if k != magic_var_name and (frame.f_code.co_name != "<module>" or not k in self.preexis...
The function `user_return` logs return values or exceptions from a function call, adjusting line numbers and recording environment data. It filters out list/dict comprehensions and non-string files, then stores computed representations of `rv` or formatted exceptions in a data structure. It also triggers a loop-end rec...
def user_return(self, frame, rv): # print("user_return ============================================") # print(frame.f_code.co_name) # print("lineno") # print(frame.f_lineno) # print(frame.__dir__()) # print("globals") # print(frame.f_globals) # print("locals") # print(frame.f_locals) if frame.f_cod...
def angle_btw(orientation: np.array, pos1: np.array, pos2: np.array): return int(acos(cos_btw(orientation, pos1, pos2)) * 180 / pi) def rotate(center: np.array, point: np.array, a): rot_matrix = np.array([[cos(a), -sin(a)], [sin(a), cos(a)]]) return rot_matrix.dot(point - center) + center def speed(agl, mod...
The code calculates a pod's movement strategy in a racing game by determining target coordinates and speed. It adjusts direction based on angle differences between the pod's velocity, position, and next checkpoint, applies boosts under specific lap conditions, and checks for collisions to trigger shields. The output gu...
def runner(self, infos: PodInfo): if infos.next_checkpoint_id != self.previous_check and not self.previous_check: self.lap += 1 if self.init and (infos.speed[0] or infos.speed[1]): # debug(str(infos.speed) + "m.s " + str(infos.pos) + " pos " + str(infos.next_check_pos) + " che...
def dist(x1, y1, x2=0, y2=0): try: _ = iter(x1) except TypeError: return ((x1 - x2) ** 2 + (y1 - y2) ** 2) ** .5 else: return ((x1[0] - y1[0]) ** 2 + (x1[1] - y1[1]) ** 2) ** .5 def magnitude(vector: np.array): return dist(0, 0, vector[0], vector[1]) def angle_btw(orientation: np...
The code determines a target for the pod by comparing enemy positions relative to checkpoints, adjusts movement direction based on speed and angle, and avoids collisions. It selects the closer enemy, calculates optimal rotation for alignment, and outputs target coordinates and speed or "SHIELD" if collision risk is det...
def fighter(self, infos: PodInfo): sensitivity = .01 tot0 = enemy_pod_info[0].next_checkpoint_id + enemies_infos[0].lap * checkpoint_count tot1 = enemy_pod_info[1].next_checkpoint_id + enemies_infos[1].lap * checkpoint_count if tot0 > tot1: self.locked_target = enemy_pod_in...
def read_state_file(): # read state file with smart_open.open(STATE_FILE_PATH, 'r') as f: return yaml.safe_load(f) def list_prefix(prefix: str): """ List all directories at the given prefix, e.g. a list of UUIDs. """ return wr.list_directories(prefix) def save_state_file(state: dict, last_modifi...
The code processes tasks from multiple queues to convert S3 prefixes to UUIDs, backup data, and manage state. It reads a state file, iterates through `list_queue` to generate UUIDs, pushes them to `task_queue`, and handles tasks like backup, state writing, and termination. It ensures all operations complete before savi...
def main(): """ Iterates the queue(s) for tasks and processes them. """ # get queue & read state file mb = MessageBroker() list_queue = mb.get_queue(QUEUE_NAME_LIST) # filled with top level S3 prefixes to be converted to UUIDs task_queue = mb.get_queue(QUEUE_NAME_TASK) # filled with UUIDs to check...