dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def updateClassFromDB(self): queryData = list(self.queryDB()) for i, x in enumerate(queryData): if x is None: x = '' queryData[i] = x if type(x) != int: if '\n' in x: queryData[i] = tuple(x.split('\n')) ...
This method downloads a work item based on the host platform (AO3, TTH, FFN) by calling specific download functions. It updates the class from the database, saves the downloaded work, marks it as saved ('1' or '0'), converts data to a dictionary, processes tuple values into strings, and updates the database with the pr...
def downloadWorkViaModules(self, downloadFormat='HTML'): self.updateClassFromDB() if self.host == host_ao3: workDownloaded = downloadWorkFromID_ao3(self.work_id, self.title, downloadFormat) elif self.host == host_tth: workDownloaded = downloadWorkFromID_tth(self.work_id...
def updateClassFromDB(self): queryData = list(self.queryDB()) for i, x in enumerate(queryData): if x is None: x = '' queryData[i] = x if type(x) != int: if '\n' in x: queryData[i] = tuple(x.split('\n')) ...
This method fetches metadata for a work from different hosts (AO3, TTH, FFN) using the work ID, updates class attributes with the retrieved data, and syncs the processed information to the database. It checks the host, retrieves metadata, assigns relevant fields (title, authors, tags, etc.) while preserving defaults if...
def getMetadataViaModules(self): if self.host == host_ao3: workData = fetchMetadataFromID_ao3(self.work_id) elif self.host == host_tth: workData = fetchMetadataFromID_tth(self.work_id) elif self.host == host_ffn: workData = fetchMetadataFromID_ffn(self.work_i...
def setUpDatabase(db_name): '''This function takes in the name of the database, makes a connection to server using name given, and returns cur and conn as the cursor and connection variable to allow database access.''' path = os.path.dirname(os.path.abspath(__file__)) conn = sqlite3.connect(pat...
The code's main task is to populate a database with U.S. state COVID-19 data in batches of 25 rows, using two state lists. It checks the current table length to determine which states and data (December or March) to fetch. After accumulating 100 rows, it calculates percentage changes and writes these results to a CSV f...
def main(): '''Main includes two state abbreviation lists with 25 states in each. It calls covid_table_length() and uses the results to determine what set of data to collect, storing 25 rows each time until CovidData is populated with 100 rows. Then calculates and populates PercentChange, and writes calcula...
def _setup_keys(self, tmpdirname): if self.ed25519_priv_key: print("Creating temporary signing key file") self.ed25519_priv_key_file = os.path.join(tmpdirname, "ed25519_priv_key") with open(self.ed25519_priv_key_file, "w") as keyfile: keyfile.write(self.ed2551...
The main task of the code is to build multiple configurations using temporary directories and encryption/signing keys from environment variables. It iterates through each test configuration, sets up temporary paths, executes the build process, checks for errors, and exits with a non-zero return code if any build fails....
def build_all(self): with tempfile.TemporaryDirectory( dir=args.build_dir, prefix="tmpbuild_" ) as tmpdirname: # Run through each test and see if it fails or not returncode = 0 # Create temporary files with encryption/signing keys from # envir...
def init(task_list): hyperperiod = header.computeHyperperiod(task_list) for task in task_list: task.jobs_in_hyper_period = hyperperiod/task.period; for jobnum in range(0,int(task.jobs_in_hyper_period)): job = header.Job(ex_time=task.ex_time, arr_time = (jobnum*task.period), abs_deadline = ((jobnum*task.period)...
The main task of the code is to initialize and sort a task set, create a multi-core processor, check if tasks can fit on the processor (feasibility), and prepare for offset tuning. It returns the status of the feasibility check, determining if the task set can be scheduled on the given number of cores.
def main(task_set,number_of_cores): init(task_set) sortTask(task_set) processor = header.Processor(num_cores = number_of_cores) status = jobFit(processor, task_set) prepareForOffsetTuning(task_set,processor) return status
def update_prev_rect(self): self.prev_rect.x = self.rect.x self.prev_rect.y = self.rect.y def add_to_position(self, x, y): self.set_position(self.rect.x + x, self.rect.y + y) def apply_env_speeds(self): total_speed = {'x': 0, 'y': 0} for speed in self.env_speeds.values(): ...
This code updates an object's position and state in a game loop by applying movement, gravity, collision handling, and animations, while managing invincibility and rope interactions.
def update(self): self.update_prev_rect() self.add_to_position(self.speed['x'], self.speed['y']) self.apply_env_speeds() self.apply_gravity() self.handle_hit_platforms() self.decrement_invicible_counter() self.handle_hit_enemy() self.update_rope_offset() ...
def convert(f,struct_fmt,keys=None,as_list=False): struct_len = struct.calcsize(struct_fmt) if not type(f) is bytes: data = f.read(struct_len) else: data = f if len(data) > struct_len: data = data[:struct_len] if len(data) < struct_len: retur...
This function reads an object from a file by determining its type via a shape code, then parsing specific data using corresponding read functions. It constructs a dictionary with object details, adds text and type fields, and returns it. If parsing fails, it returns None.
def ReadObject(f): ret = convert(f, '<2b', as_list=True) #object if ret is None: return None shape,typ = ret if shape == POLYGON: dic = ReadPolygon(f) elif shape == ELLIPSE: dic = ReadEllipse(f) elif shape == CIRCLE: dic = ReadCircle(f) elif shape == POLYLINE...
def convert(f,struct_fmt,keys=None,as_list=False): struct_len = struct.calcsize(struct_fmt) if not type(f) is bytes: data = f.read(struct_len) else: data = f if len(data) > struct_len: data = data[:struct_len] if len(data) < struct_len: retur...
The main task of the code is to parse a binary MLD file, extracting layer data (including objects, names, and metadata), additional sections like images and configurations, and returning structured information in a dictionary. It reads layer-specific objects, handles corrupted data gracefully, and supports debugging ou...
def ReadMLDFile(fn, debug=False): f = open(fn,'rb') ret = convert(f,'<4s2i',['magic','version','nlayers']) if debug: print('Version=%d - nlayers=%d' % (ret['version'],ret['nlayers'])) for layer_index in range(ret['nlayers']): layer_pos = f.seek(0,1) #In some cases, the buffer size giv...
def word_choice(input): output = [] check = False for i in range(len(input['markup'])): error = input['markup'][i] check = False if error['type'] == 'word choice': # Check if we see this error before, update the error_count for item in output: ...
The main task of the code is to analyze a dataset for three types of errors: word choice, punctuation, and spelling. It processes essays to detect and aggregate error frequencies, merges duplicate entries, and prints the top 10 common word choice errors, top 5 punctuation errors, and a percentage of spelling errors com...
def main(): # Running sample of our function on the dataset. Geting some of the result and stat # To get the full result and all the statictis please refer to Similar Errors.ipynb # Running Word choice error detection on dataset # And print out top 10 common error # Tuple of set ...
def encoder_forward(self, inputs): _, hidden_outputs = self.encoder(inputs) latent_repr = self._get_latent_repr(hidden_outputs) # latent_repr: (batch, latent_space_size) return latent_repr, hidden_outputs def classify_forward(self, inputs, latent_repr): # Creating fake represen...
The code performs forward pass of a neural network, encoding inputs into latent representations, decoding them to reconstruct inputs, classifying using latent features, and computing clustering loss. It returns latent representations, reconstructed inputs, classification outputs, and clustering loss for training and in...
def forward(self, inputs, should_update_f=False): # inputs of shape (Batch, Time Steps, Single step size) latent_repr, _ = self.encoder_forward(inputs) # For decoding we also need a time-step dimension (which is 1) # reconstructed_inputs will have the same shape as the inputs de...
def save_file(a): global open_status_name global file_location global file_name global saved_file if open_status_name: text_file = open(open_status_name, 'w') text_file.write(my_text.get(1.0, 'end-1c')) text_file.close() status_bar.config(text=f'Saved: {file_location ...
This function opens a file in a text editor, checks for unsaved changes, reads the selected file's content, and displays it while updating UI elements like the status bar and window title. It handles file path parsing, saves the file if prompted, and applies syntax highlighting.
def open_file(a): global file_name global file_location global saved_file global file_type global file_name_path if my_text.get(1.0, 'end-1c') != "": if saved_file: pass else: answer = tkinter.messagebox.askyesno(title="Warning", message="Do you want to sa...
def compile(a): global file_location global file_type global file_name global file_name_path global saved_file global process compile_output = "" result = "" if (file_name == "fn") and (file_name_path == "fnp") and (file_type == "ft") and (file_location == "fl"): saved_fi...
This code initializes and executes a debugging process for C/C++ programs. It compiles the source file using g++/gcc, sets breakpoints via GDB, runs the program, captures output, highlights the first breakpoint in the UI, and enables debug menu options. The function checks if the file is saved, compiles it, and manages...
def start_debug(a): global file_type global file_name global file_location global saved_file global process global breakpoint_list global debug_output global last_breakpoint error = "" output = "" bp_location = [] if len(breakpoint_list) == 0: compile(a) r...
def caesar_cipher(text, shift): result = "" for char in text: if char.isalpha(): is_upper = char.isupper() char = char.lower() shifted_char = chr(((ord(char) - ord('a') + shift) % 26) + ord('a')) if is_upper: shifted_char = shifted_char.upp...
This code provides an interactive menu-driven program for encrypting or decrypting text using various classical ciphers (Caesar, Vigenère, Polyalphabet, Hill, Playfair, Affine). It repeatedly prompts the user to select a cipher, input text, and required parameters, then applies the chosen cipher function to process the...
def main(): while True: print("Pilih cipher yang ingin Anda gunakan:") print("1. Caesar Cipher") print("2. Vigenere Cipher") print("3. Polyalphabet Cipher") print("4. Hill Cipher") print("5. Playfair Cipher") print("6. Affine Cipher") print("7. Keluar"...
def produce_json(self) -> None: """ Method which is dedicated to produce config json file with the Input: Basic values Output: json file was created """ for v, key in zip([json_name, json_name_translate], [json_keys_default, json_keys_translate]): value_name ...
The main task of the code is to process image files in a folder based on command-line arguments, performing actions like analysis, file updates, deletion, or observation. It dynamically selects files, applies specified operations, and optionally deletes processed files if required. The method handles input/output opera...
def main_usage(self) -> None: """ Main method which is dedicated to work with Input: inserted arguments Output: program finished worked """ if self.argparse.update: os.remove(os.path.join(self.folder_config, json_name)) self.produce_json() ...
def reset_game(self): """ resets the game by initializing a new Board and AlphaBeta instance. """ # Display current wins and losses self.leaderboard.display_leaderboard() # Wait for a short time before resetting pygame.time.wait(2000) self.board = Board() ...
This code manages a Connect 4 game's main loop, handling player/AI moves, event inputs (ESC/SPACE), win/draw checks, sound effects, and UI updates. It uses alpha-beta pruning for AI decisions, displays results, and resets the game state upon completion or user exit.
def run(self): """this handles the game logic""" # initialize game sounds Sounds.stop() Sounds.game_music() # draws a border to now show background image pygame.draw.rect(self.screen, connect_4.rgbcolors.light_blue, (0,0, self.width, self.board.square_size)) whi...
def _cvx_learn(self, Seq, **opt_args): noGroup = opt_args['noGroup'] Reg = self.regParam ## convert everying to numpy format T = len(Seq) Seq = Seq.numpy() groupLevel = self.groupLevel.numpy() A = self.A.numpy() gamma = self.ga...
The code's main task is to learn model parameters by solving a convex optimization problem using either CVXPY (for convex programming) or gradient-based L-BFGS optimization with random restarts. It converts input data to tensors, handles multiple random initializations, and selects the solution with the highest likelih...
def learn(self, Seq, optimizer='lbfgs', **opt_args): if not isinstance(Seq, torch.Tensor): Seq = torch.vstack([torch.tensor(item, dtype=DTYPE) for item in Seq]) ### formulate the learning problem as a convex programming ### and use off-the-shelf solver (we use CVXPY) to lear...
def checkLiveImage(self): if self.liveimageCheckBox.isChecked(): self.timerLiveImage.start(int(1000 / 60)) else: self.timerLiveImage.stop() self.liveImageFunction() def settingsNotFoundError(self): msgBox = QMessageBox() msgBox.setWindowTitle('Error') ...
(The main task of the code is to load user settings from a pickle file, update the application's UI elements and internal state with these settings, configure hotkeys, and initialize the application's behavior based on previously saved configurations. It handles exceptions for file errors and invalid settings, ensuring...
def loadSettings(self): try: with open('settings.pkl', 'rb') as f: [self.split_image_directory, self.similarity_threshold, self.fps_limit, self.split_key, self.reset_key, self.skip_split_key, self.undo_split_key, self.x, self.y, self.width, self.hei...
def rotate(left, factor): brake() if left: left_motor.duty_cycle_sp = - DEFAULT_DUTY_CYCLE * factor right_motor.duty_cycle_sp = DEFAULT_DUTY_CYCLE * factor else: left_motor.duty_cycle_sp = DEFAULT_DUTY_CYCLE * factor right_motor.duty_cycle_sp = - DEFAULT_DUTY_CYCLE * factor ...
The code's main task is to control a robot's movement and response to environmental stimuli. It continuously checks sensors for borders, obstacles, and enemy presence, adjusting rotation and direction accordingly. If a border is detected, the robot turns around. If an enemy is spotted, it attacks; otherwise, it searche...
def run_loop(): left = True turn_speed = 1 rotate(left, turn_speed) time.sleep(0.8) while True: # time.sleep(DEFAULT_SLEEP_TIMEOUT_IN_SEC) if DEBUG: print('----------------------------') print('color value: %s' % str(color_sensor.value())) print('u...
def set_speed(speed): for m in motors: m.speed_sp = speed def forward(): for m in motors: speed = m.speed_sp if speed < 0: m.speed_sp = speed * -1 m.run_forever() def run_loop(): # game loop (endless loop) while True: time.sleep(DEFAULT_SLEEP_TIMEOUT...
The code's main task is to control a robot by setting its speed, moving forward, and executing a loop. It handles clean shutdowns (via KeyboardInterrupt/SystemExit) and errors by calling a teardown function to release resources, ensuring graceful termination while logging exceptions.
def main(): print('Run robot, run!') set_speed(DEFAULT_SPEED) forward() try: run_loop() # doing a cleanup action just before program ends # handle ctr+c and system exit except (KeyboardInterrupt, SystemExit): teardown() raise # handle exceptions except Exc...
def set_speed(speed, duty_cycle): for m in motors: m.speed_sp = speed m.duty_cycle_sp = duty_cycle def forward(): for m in motors: # m.speed_sp = -500 m.duty_cycle_sp = DEFAULT_DUTY_CYCLE m.run_forever() def run_loop(): left = True # game loop (endless loop) w...
The main task of the code is to initialize hardware settings (speed and duty cycle), move forward, execute a loop, and handle shutdowns or errors gracefully. It sets default parameters, runs operations in a loop, ensures cleanup via `teardown()` on exit signals (Ctrl+C or SystemExit), and catches unexpected errors to p...
def main(): set_speed(DEFAULT_SPEED, DEFAULT_DUTY_CYCLE) forward() try: run_loop() # doing a cleanup action just before program ends # handle ctr+c and system exit except (KeyboardInterrupt, SystemExit): teardown() raise # handle exceptions except Exception as ...
def set_speed(speed, duty_cycle): for m in motors: m.speed_sp = speed m.duty_cycle_sp = duty_cycle def run_loop(): left = True turn_speed = 1 rotate(left, turn_speed) time.sleep(0.8) while True: # time.sleep(DEFAULT_SLEEP_TIMEOUT_IN_SEC) if DEBUG: prin...
The code initializes a system by announcing readiness, waits for a button press, sets default speed parameters, executes a main loop, and ensures cleanup on exit or errors through exception handling.
def main(): print('I am ready. Please start me!') sound.speak('I am ready. Please press any button!') # Wait for any key while True: if DEBUG: print('ready') if button.any(): break set_speed(DEFAULT_SPEED, DEFAULT_DUTY_CYCLE) # Main loop try: ...
def get_collection_title( collection: dict ) -> str: """ Get the title from the given collection collection: dict The collection to evaluate returns str """ return f"# {collection['info']['name']} #" def get_collection_table_of_contents( collection: dict ) -> List[str]: """...
The function generates markdown content from a collection dictionary by appending the collection title, a GitHub credit link (if enabled), a table of contents, and parsed items. It then joins these elements, replaces escaped brackets, and substitutes variables using the collection data to produce the final markdown str...
def get_markdown_from_collection( collection: dict, credit_repository=True, ) -> str: """ Generate/extract the markdown content from the collection's dict collection : dict The parsed collection's content returns str """ markdown = [] markdown.append(get_collection_title(c...
def get_args_parser() -> argparse.ArgumentParser: """ Initializes the parser @source=https://stackoverflow.com/questions/40001892/reading-named-command-arguments returns argparse.ArgumentParser """ parser = argparse.ArgumentParser() parser.add_argument('--collection', help=""" The Pos...
The main task of the code is to initialize a workflow that parses command-line arguments, retrieves content from a specified collection, converts it into markdown format, and saves the resulting markdown to a designated destination.
def main() -> None: """ Initializes the workflow returns None """ args = get_args_parser().parse_args() collection = get_collection_content(args.collection) markdown = get_markdown_from_collection(collection) # print(markdown) success = save_mardown(markdown, destination=args.dest...
def construct_tree1(line_index, file_arr, d, players, curr = None): if curr == None: curr = Node(file_arr[line_index]) i = line_index if curr.node_type == 'p': curr_player = int(curr.player)-1 if curr.info_set not in players[curr_player].information_set_sizes: players[curr_player]....
This code converts an extensive-form game (EFG) from a file into a normal-form game (NFG) representation. It parses the EFG structure, constructs a game tree, computes strategy profiles for each player, and outputs the payoffs in a standardized NFG format with player names, strategy counts, and payoff arrays.
def efg_NFG(file_name): file_arr = [] with open (file_name, 'r') as f: for x in f: file_arr.append(x) first = EFG_first(file_arr[0]) numPlayers = len(first.player_names) players = [] for i in range (numPlayers): temp = Player() players.append(temp) ...
def construct_tree(line_index, file_arr, d, players, done, curr = None): if curr == None: curr = Node(file_arr[line_index]) i = line_index if curr.node_type == 'p': curr_player = int(curr.player)-1 curr_depth = d if curr_depth in players[curr_player].info_sets: if curr.info_s...
The code converts an Extensive Form Game (EFG) file into Normal Form Game (NFG) format. It reads the input file, parses game structure (players, information sets), constructs a game tree, computes strategy profiles via Cartesian products, evaluates payoffs using DFS traversal, and formats results into NFG syntax with p...
def efg_NFG(filename): file_arr = [] with open (filename, 'r') as f: for x in f: file_arr.append(x) first = EFG_first(file_arr[0]) numPlayers = len(first.player_names) players = [] for i in range (numPlayers): temp = Player() players.append(temp) ...
def install_all_stack(self): self.install_nodejs() self.install_npm() self.install_nvm() self.install_php() self.install_php_compose() self.install_rbenv() self.install_docker() self.install_docker_compose() def install_nodejs(self): colorprint.pri...
The code's main task is to install selected development tools (e.g., Node.js, PHP, Docker) based on user input. It checks if 'ALL' is selected to install full packages or handles individual choices via a loop, invoking specific installation methods. It also issues warnings about potential conflicts or manual steps requ...
def install(self): colorprint.print_success("[+] Starting Installations") stacks = inquirer.prompt(self.install_choices) if 'ALL' in stacks['Tech']: colorprint.print_success("[+] You Have Selected ALL Option") colorprint.print_success("[+] Installing FULL-PACKAGES") ...
def conv_layer(net, filters = 32, kernel_size = 3, strides = 1, with_relu = True): """ Conv2D layer with batch norm and optional ReLU (default is applied) """ net = layers.Conv2D(filters, kernel_size=kernel_size, strides=strides, activation=None, padding='SAME', k...
This code defines a feed-forward transformation network for image processing, using convolutional layers to extract features, residual blocks for deeper learning, and transposed convolutions to upscale the image. The network transforms input images into outputs with adjusted color ranges via tanh activation, likely for...
def transform_net(): """ feed forward transformation network """ inputs = tf.keras.Input((256, 256, 3)) x = conv_layer(inputs, 32, 9, 1) x = conv_layer(x, 64, 3, 2) x = conv_layer(x, 128, 3, 2) x = residual_layer(x, 128, 3) x = residual_layer(x, 128, 3) x = residual_layer(x, 128,...
def ErrorHandler(self,Error_code,Error_msg): with open(f'resource/html/Error_Form.html','r',encoding='UTF-8') as TextFile: Response_file=TextFile.read() Response_file=Response_file.format(Error_code,Error_msg).encode('utf-8') self.log(f"[ Handle Error ] ==> Code : \033[35m{Error_...
This code updates a user's account information (name, email, birthdate, and password) using provided data, ensuring the user is authenticated via a session. If the password is changed, it logs the user out to enforce the new credentials. The updated data is saved to the database, and a confirmation HTML page is returne...
def UpdateAccount_Handler(self,newUserInfo=None,session=None): if session is None: return self.ErrorHandler('403 Forbidden', 'Warning! You are attempting to post without logging in. If you wish to make a post, please proceed with the login.') DataBase=self.getDatabase(session.UserInfo['DataB...
def HandleTextFileRequest(self,textflie='/html/Index.html'): with open(f'resource{textflie}','r',encoding='UTF-8') as TextFile: Response_file=TextFile.read().encode('UTF-8') return '200 OK',Response_file def verifySessionCookie(self,RequestData:list): for data in RequestData: ...
This code processes POST requests by parsing JSON data, routing requests to specific handlers (e.g., Register, Login, Logout) based on the 'Form' field, managing session validation, and constructing HTTP responses with headers and cookies. It centralizes request handling, session management, and response preparation fo...
def HandlePOSTRequest(self, Request): JsonData = parse.unquote(Request[1].decode()) DictPostData = json.loads(JsonData) Form = DictPostData['Form'] Response = self.HandleTextFileRequest() is_valid_cookie, sessionid, session = self.verifySessionCookie(Request[0]) # try: ...
def HandleGETRequest(self, Request): result = parse.unquote(Request[0]).split(' ')[1].replace('\\', '/') is_valid_cookie, sessionid, session = self.verifySessionCookie(Request) try: temporaryResponse = self.HandleTextFileRequest() if any(extension in result for extension...
This code handles HTTP requests in a separate thread. It spawns a thread for each client connection, processes the request (GET/POST), generates a response, and cleans up resources. The thread executes the request, checks the method type, sends the appropriate response, and terminates the thread after completion.
def HandleRequestThread(self, client_socket, client_address): socket_and_address = [(client_socket,), client_address] thread_name, thread = self.http.AssignUserThread(socket_and_address) thread.start() thread.join() Request=thread.result first_line = thread.result[0] ...
def my_get_paths(data_dir, ext): """Get filepath from data_dir""" path_list = [] for p in os.listdir(data_dir): class_folder = os.path.join(data_dir, p) if os.path.isdir(class_folder): for pp in os.listdir(class_folder): file_path = os.path.join(class_folder, pp) ...
The main task of the code is to generate face embeddings using a pre-trained facenet model on a set of images. It configures GPU settings, loads image paths, runs forward passes in batches to compute embeddings, and saves the results to a CSV file with timestamps. The process involves TensorFlow graph management, model...
def main(args): os.environ['CUDA_VISIBLE_DEVICES'] = str(args.gpu) with tf.Graph().as_default(): gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=args.gpu_memory_fraction) config = tf.ConfigProto(gpu_options=gpu_options, log_device_placement=False) with tf.Session(config=con...
def writeTree(): ''' Write a tree object from the current index file. ''' for entry in readIndex(): # entry.mode = 33277, {:o} o => octal # '{:o} {}'.format(entry.mode, entry.path) => '100775 demo.py' modePath = '{:o} {}'.format(entry.mode, entry.path).encode('utf-8') treeEntry =...
The main task of the code is to create a Git commit object using the current index (tree), parent commit (if exists), author information, and the provided message. It constructs the commit metadata, hashes the data to generate a SHA1 identifier, updates the master branch reference to point to this new commit, and retur...
def commit(message): ''' Commit, using the index file and given message, return: sha1 of commit object. ''' treeHash = writeTree() parent = getLocalMasterHash() # 'corsair <blctl@example.com>' author = 'Annoymous' email = 'atiex@example.com' try: author = '{} <{}>'.format( ...
def readIndex(): ''' Read index file, return list of IndexEntry object. ''' try: data = readFile(os.path.join(baseName, 'index')) except FileNotFoundError: return [] # calculate checksum leaving the last 20 bytes(checksum itself). # data[0:20], left included, right not. checkSu...
(This function generates and prints the unified diff between Git index (staging area) files and their corresponding working tree files for changed paths. It reads index entries, retrieves blob objects from Git's object database, compares content with working files, and outputs differences using difflib's unified_diff f...
def diff(): ''' Show diff between index and working tree. ''' ''' entries_by_path = {e.path: e for e in read_index()} = {'indexcat.py': IndexEntry(..., ..., path='indexcat.py'), 'main.cpp': IndexEntry(..., ..., path='main.cpp')} ''' # type(entries_by_path) = <class 'dict'>, convert to Ke...
def read_file(filename): """ Reads the information from the specified file and builds a new word_data dictionary with the data found in the file. Returns the newly created dictionary. Input: filename (str): name of the file holding professor review data >>> read_file('data/small-one....
This code processes command line arguments to either search for words in a file or print all words. It reads a data file, checks for a '-search' flag with a target word, and outputs matching words or the full list based on the input parameters.
def main(): # (This function is provided for you) import sys args = sys.argv[1:] if len(args) == 0: return # Two command line forms # 1. data_file # 2. -search target data_file # Assume no search, so filename to read # is the first argument filename = args[0] # Che...
def create_vars(self, N, lb, ub, tag='X_'): n = lb.size w, lbw, ubw = [], [], [] X = [] for ii in range(N): Xn = MX.sym(tag+str(ii), n) X += [Xn] w += [Xn] lbw += lb.tolist() ubw += ub.tolist() return w, lbw, ...
This function initializes and structures an optimization problem for motion planning by unrolling a sequence of operators into decision variables (states and controls), constraints, and cost terms. It iterates over each plan segment to generate variables, adds dynamics constraints, initial conditions, and integrates gr...
def unroll_plan(self): self.cost = 0. self.X, self.U = [], [] self.Xg = [] self.w, self.lbw, self.ubw = [], [], [] self.g, self.lbg, self.ubg = [], [], [] # Create decision variables for free-flyer # for operator in self.plan: # w_loc, lbw_loc, ubw_l...
def _run_rotatevol(self, rotation): """Rotates mrc volume """ markermrc = os.path.join(self._get_marker_dir(), self._markermrc) tmp_mrc = os.path.join(self._get_marker_dir(), 'tmp.mrc') cmd = ('rotatevol -angles ' + str(rotation) + ',0,0 ' + markermrc + ' ' + tmp_m...
The function generates a tilt series by rotating a 3D volume and associated markers based on the input rotation angle, then processes projections, clips MRC files, updates marker positions, and converts points to models for tomographic reconstruction.
def _generate_tilt_series(self, rotation, rotationdir): """Generates tilt series for rotation passed in """ self._workdir = rotationdir # rotate marker mrc file and 3Dmarkers.txt file if math.fabs(rotation) > 0.001: self._run_rotatevol(rotation) self._run...
def _get_common_markers_filter(self, dirlist): mlist = [] for path in dirlist: logger.debug('Loading markers from ' + path) self._workdir = path two_d_txt = os.path.join(self._get_tracking_dir(), TiltSeriesCreator.TWO_D_MARKERS_ALL...
This function processes each directory in dirlist to filter and save common 2D markers, generating marker files and .fid files for tilt series. It removes unique markers, writes filtered common markers to a file, and executes alignment operations before consolidating results into a shared directory.
def _generate_common_marker_files(self, dirlist): """For each rotation eliminate missing tracks and write out a new marker file and .fid file for each rotationdir """ filt = self._get_common_markers_filter(dirlist) for path in dirlist: logger.debug('Saving common ...
def get_nodes_and_labels(network_string): """ Map the root position of nodes and labels to the node / label text. e.g. map_nodes_and_labels(" n1--(label1)--n2 ") -> { Point(2, 0): "n1", Point(6, 0): "(label1)", Point(16, 0): "n2", } """ nodes = ...
The code converts an ASCII network diagram into a NetworkX graph by parsing the input string to extract nodes, their labels, and edges, then constructing the graph using these elements.
def graph_from_ascii(network_string): """ Produces a networkx graph, based on an ascii drawing of a network """ nodes, labels = get_nodes_and_labels(network_string) edges = get_edges(network_string, nodes, labels) return build_networkx_graph(nodes, edges)
def remove_div(div: Tag, soup: BeautifulSoup): len_content = 0 child = None for c in div.contents: if isinstance(c, NavigableString) and len(c.text.strip(" \n")) == 0: continue len_content += 1 if child is None: child = c if len_content < 1: div.de...
This function processes a PatchNote's HTML content by removing images, unnecessary spans, and adjusting divs/paragraphs. It standardizes formatting, replaces specific styles with lists, converts bold tags to strong, and extracts headings. The cleaned HTML element is returned after restructuring and cleanup.
def get_html(patch_note: PatchNote) -> PageElement: if patch_note.content is None: raise FormattingException(f"Patch note {patch_note} does not have any content") soup = BeautifulSoup(patch_note.content.replace(" ", " "), "html.parser") # .replace(" ", " ") # soup2 = BeautifulSoup(patch_note.conten...
def find_all_patch_notes_urls(base_url: str, max_index: int, min_index: int = 1, cache=True) -> List[PatchNote]: patch_notes = [] for i in range(min_index, max_index + 1): logger.info("Loading patch note urls %s/%s", i, max_index) index = f"_{i}" if i == 1: index = "" ...
The function downloads new patch notes from specified URLs up to a given page limit. It iterates through pages, checks for missing notes, collects and downloads them if found, then updates the cache. The process stops early if a page has no new notes.
def download_new_patch_notes(base_url: str, stop_at=4) -> None: logger.info("Loading missing patch notes") new_notes = [] for i in range(1, stop_at + 1): patch_notes = find_all_patch_notes_urls(base_url=base_url, max_index=i, min_index=i, cache=False) if not has_missing_notes(patch_notes): ...
def load_level_map(): global MAP MAP = [] for i in range(len(LEVEL_MAP)): MAP.append( [] ) for j in range(len(LEVEL_MAP[i])): MAP[i].append(LEVEL_MAP[i][j]) def render_game_map(): # render the map global coords, firstcycle if not firstcycle: c = getcoords() ...
The code initializes a text-based game using the curses library, allowing a player to navigate a grid with WASD keys, toggle cell states with 'E', and simulate actions with 'F'. It manages game rendering, input handling, and state updates in a loop until the player quits with 'Q', cleaning up the terminal interface upo...
def main(): global selector_y, selector_x, X, O, end load_level_map() stdscr = curses.initscr() curses.noecho() curses.cbreak() curses.curs_set(0) curses.start_color() curses.keypad(stdscr, True) curses.init_pair(1, curses.COLOR_CYAN, curses.COLOR_BLACK) curses.init_pair(2, curse...
def resetScreen(): clearScreen() showLogo() def background(): clearScreen() showLogo() print( " The TC Lab API is an application programming interface utilizing the Flask\n" "framework. This open source technology allowed TC technology to react to various\n" "activities ...
The code provides a menu-driven interface for server management and user information, allowing users to choose actions like starting/stopping the server, updating, clearing data, or viewing user details. It loops until the user selects "Quit" (option 6), invoking corresponding functions for each choice and pausing for ...
def help(): running = True while running: resetScreen() background() print("\nFor more information choose one of the following.") print("1) Starting the server ") print("2) Updating the server ") print("3) Stoping the server ") print("4) Clearing the...
def clearScreen(): if name == 'nt': _ = system('cls') else: _ = system('clear') def showLogo(): print(logo) def help(): running = True while running: resetScreen() background() print("\nFor more information choose one of the following.") prin...
The code defines a menu-driven interface that displays options for Background, Utilities, Help, and Quit. It loops until the user selects 'Quit' (option 4), calling respective functions for other choices. The menu clears the screen, shows a logo, and processes user input to navigate functionalities.
def menu(): running = True while running: clearScreen() showLogo() print ("1) Background ") print ("2) Utilities ") print ("3) Help ") print ("4) Quit ") choice = input("\nChoose: ") if choice == '4': return 0 elif choice ...
def __new_empty_tile(self): result = "" for row in range(0, self.tile_size): result += "⭕"*self.tile_size if row < self.tile_size - 1: result += "\n" return result def __can_continue_generating_pixels(self, written_pixels, iteration): return writte...
The code generates tiles by iteratively adding random pixels, validating configurations, and ensuring Hamming distances between tiles meet a threshold. It returns a valid tile if criteria are satisfied, otherwise returns None after exhausting iterations.
def __generation_loop(self, all_tiles): written_pixels = 1 tile = self.__new_empty_tile() iteration = 0 while self.__can_continue_generating_pixels(written_pixels, iteration): new_pixel_x = random.randint(1, self.tile_size - 1) new_pixel_y = random.randint(1, self...
def _create_usage_list(dimensions: dict, timestamp: datetime, config: Config): """Create the usage list used with the batchEventUsage API""" usage = [] try: resource_uri = os.environ['EXTENSION_RESOURCE_ID'] plan_id = os.environ['PLAN_ID'] except KeyError: # if not present, it i...
The function processes metered billing by sending usage data to Microsoft's Marketplace API, handling retries on errors, and returning a status dictionary indicating success or failure for each dimension. It constructs a usage list from input dimensions, sends a POST request with retries, logs errors if failures occur,...
def meter_billing( config: Config, dimensions: dict, timestamp: datetime, dry_run: bool ): """ Process a metered billing based on the dimensions provided If a single dimension is provided the meter_usage API is used for the metering. If there is an error the metering is attempted 3 ...
def processed_lines(self) -> Iterator[str]: """ Lines we see may be: 1. Comments or empty -> ignore 2. start with push/pop -> memory instruction 3. an arithmetic instruction """ for line in self.input_lines: line = line.strip() if len(line)...
The code compiles processed lines into a string, appends infinite loop instructions, adds jump logic if needed, and writes the final output to a file.
def compile(self): out = "\n".join(line for line in self.processed_lines()) out += self.compile_infinite_loop_instruction() if self.jump_counter: out += self.compile_true_false_jumps() self.output_filepath.write_text(out)
def applog(message,status): try: if status=="e": f.write(format_time() + " -0000 ERROR " + str(message)+"\n") elif status=="s": f.write(format_time() + " -0000 SUCCESS " + str(message)+"\n") elif status=="n": f.write(format_time() + " -0000 INF...
The code initializes an application by declaring global variables, setting directory paths, reading configuration files, and establishing a MongoDB connection, while logging progress and handling potential errors.
def INIT(): try: applog(" - INIT() -- Started","n") applog(" - INIT() -- Declaring Global Variables","n") global bin_dir global project_dir global var_dir global lib_dir global conf_dir global log_dir global app_log_file global config_f...
def detect(self, img_path): """ @brief This function pass the image path to the model and calculate bounding boxes for each object @param img_path (String): path of input image """ self.block_list.clear() # Detection model self.results = MODEL(img_path) self....
The code initializes an image detection system by loading an input image and configuring model parameters. It provides a user interface to select detection methods: re-detecting the full image, detecting regions of interest (ROI), or manual detection. The core task is to enable flexible object detection with options fo...
def __init__(self, img_path): """ @brief Class constructor @param img_path (String): path of input image """ MODEL.conf = CONFIDENCE MODEL.multi_label = False # MODEL.iou = 0.5 self.block_list = [] self.detect(img_path) # Let user choose...
def is_monitor_mode(): os.system("iwconfig > ./os/iwconfig") with open("./os/iwconfig", "r") as f: text = f.read() return True if "Mode:Monitor" in text else False def get_mac_frame_details_from_buffer(buf): frame_details = init_frame_details() header_radiotap = buf[:56] header_frame_con...
This function processes a pcap file to extract network frame details. It checks if monitor mode is enabled, then iterates through each packet in the file. For each packet, it appends either MAC or Ethernet frame details (based on monitor mode) to a list, which is returned as the result.
def get_all_frame_details(): is_monitor = is_monitor_mode() frame_details = [] for len, time, buf in rpcap("./os/pcap.pcap"): if is_monitor: frame_details.append(get_mac_frame_details_from_buffer(buf)) else: frame_details.append(get_ethernet_frame_details_from_buffer(...
def signed_in(): global SIGNED_IN return SIGNED_IN def log(type, assistant_sid, task_sid, date, time_start, time): with open('log_file.csv', 'a') as file: file.write(f'{type},{assistant_sid},{task_sid},{date},{time_start},{time}\n') def get_task_actions(assistant_sid, task_name): tasks = client....
The main task of the code is to create a query for an autopilot assistant if the user is signed in. It retrieves parameters from the request, checks if the assistant's model is built, creates the query, validates task actions, and returns a JSON response with results or an error if the model isn't built. If the user is...
def create_query(request): if signed_in(): assistant_sid = request.POST['assistantSid'] query_string = request.POST['queryString'] tasks_limit = request.POST.get('taskLimit', False) if tasks_limit == 'true': tasks_limit = None time_start = datetime.now() t...
def signed_in(): global SIGNED_IN return SIGNED_IN def log(type, assistant_sid, task_sid, date, time_start, time): with open('log_file.csv', 'a') as file: file.write(f'{type},{assistant_sid},{task_sid},{date},{time_start},{time}\n') def get_task_actions(assistant_sid, task_name): tasks = client....
The code handles a request to retrieve task actions in a simulator. It checks if the user is signed in, logs the action with timestamps, and returns JSON data containing task actions if authenticated. If not signed in, it redirects to the homepage with a "Sign In" alert.
def get_task_actions_simulator(request): if signed_in(): assistant_sid = request.POST['assistantSid'] time_start = datetime.now() ts = time.time() log('Redirected to Task in Simulator', assistant_sid, '', datetime.now().strftime('%d/%m/%Y'), time_start.strftime('%H:%M:%S'), round(tim...
def splitBarcodes(self): lvl1BarcodeAliases = {} for name,bc in self.demuxJson["samples"][self.sampleName]["barcodes"].items(): lvl1BarcodeAliases[bc['sequence']] = name libDirJSON = GeneralUtils.readJSON(self.libDir, preserveDictOrder=True) barcodeInfo = libDirJSON['barcod...
The main task of the code is to generate a comprehensive HTML report by processing input data files, splitting barcodes, calculating statistics, and constructing multiple report pages (summary, cells, barcodes, fragments, peaks). It compiles accumulated statistics into a TSV file and assembles all pages into a unified ...
def build(self): (df, cellStats) = CalculationUtils.getStatsAsDataframes(self.sampleSpecificFilePaths['filterDfPath'], self.sampleSpecificFilePaths['cellStatsPath'], self.sampleThresholds) self.unfilteredCells = df self.cellStats = cellStats self.splitBarcodes() self.getSpeci...
def _filter_blank(i): for s in i: if s.strip(): yield s def parse_media_range(range): """Parse a media-range into its component parts. Carves up a media range and returns a tuple of the (type, subtype, params) where 'params' is a dictionary of all the parameters for the media range. For example, t...
The function `best_match` identifies the highest-quality (`q`) mime-type from a list of supported types that best matches the media ranges specified in an HTTP Accept header. It parses the header, evaluates each supported mime-type against the ranges using fitness and quality scores, sorts candidates by these metrics, ...
def best_match(supported, header): """Return mime-type with the highest quality ('q') from list of candidates. Takes a list of supported mime-types and finds the best match for all the media-ranges listed in header. The value of header must be a string that conforms to the format of the HTTP Accept: header. Th...
def character_count(self, data): char_freq = dict() for each_char in data: if each_char in char_freq: char_freq[each_char]+=1 else: char_freq[each_char]=1 return char_freq def make_heap(self, freq_char_data): for each_char in freq_c...
The code implements Huffman encoding by first counting character frequencies, building a priority queue (heap), merging nodes to form a Huffman tree, generating binary codes for each character, and finally encoding the input data into a compressed binary string using these codes.
def huffman_encoding(self, data): # step1 freq_data = self.character_count(data) #step2 self.make_heap(freq_data) #step3 self.merge_nodes() #step4 - making codes self.make_codes() #step5 encoded_text= self.get_encoded_text(data)...
def get_file_list(vkey, format_string =source_format): search_path = format_string.format(vkey) print("searching for files", search_path) for f in glob(search_path): yield f def reduce_file(f): """ reduce accross chunks on other categorical columns. capture statistics for Moments M0+ bec...
The main task of the code is to process files associated with a given key. If `skip_to_combine` is False, it generates atoms by reducing individual files listed under the key. If no files exist, it exits early. Regardless of the flag, it combines the processed data using a combiner function, finalizing the task with a ...
def process(key, skip_to_combine=False): if skip_to_combine == False: print("generating atoms for",key) l = list(get_file_list(key)) if len(l) ==0: print("there are no files to process when matching", key) return for f in l: reduce_file(f) print("") ...
def _goal_reached(self): if self._target_fn is None: return False return self._target_fn(self._state) def get_valid_actions(self, state=None, force_rebuild=False): if state is None: if self._valid_actions and not force_rebuild: return copy.deepcopy(self._...
The `step` method processes an action (a molecular modification) in an environment, updates the current state, checks termination conditions (max steps or goal reached), validates the action, records the path if enabled, and returns the new state, reward, and termination status to guide reinforcement learning training.
def step(self, action): """Take an action Argument ----------- - action. Chem.RWMol. The molecule after taking this action Return - result. Result object. * state. The molecule reached after taking the action. * ...
def _genVar(varName, numVars, enumFormat = None): # example call: Acc = _genVar("acc", 166, "A"); # Tap = _genVar("tap", 168) if enumFormat == None: varNames = [] for i in range(0,numVars): varNames.append("{}{}".format(varName, i)) return varNames if e...
This code initializes a class to process digital filter coefficients, generating hardware description code for a finite impulse response (FIR) filter. It reads coefficients from a file, sets up variables for accumulators, taps, and buffers, and generates code for multiplication and accumulation operations. The class ha...
def __init__(self, numTaps, coeffsFile , outFile , bitWidth = None): #coeffsFile is the path to .txt file of the coefficient values generated by matlab self.coeffsFile = coeffsFile self.outFile = outFile self.numTaps = numTaps self.varNames = ["acc", "tap", "buff"] self.A...
def dateStr(dt): return dt.strftime('%d%b%y').upper() def shortCall(strike, units, pUSD, pBTC=None, currentBTC = None, feeRate = 0.0004): if pBTC == None: optionPrice = pUSD else: optionPrice = pBTC * currentBTC FEE = units * feeRate * currentBTC profit = pd.Series(SPOT_PRICE_RANG...
This function implements a bearish vertical call spread strategy by selling a call at strike price sk1 and buying a call at strike price sk2. It calculates the profit/loss profile, determines max profit/loss, computes probability of profit, and returns strategy parameters including strike prices, bid/ask prices, and ri...
def callVert_Z(sk1, sk2, bUnits, spot, expiry, useDeribit=True, charts = False): print('=== CALL VERTICAL Z BEAR ===') if useDeribit: ask, bid, delta = deribitOptionsData(dateStr(expiry), sk1, 'C') pBTC1 = bid ask, bid, delta = deribitOptionsData(dateStr(expiry), sk2, 'C') pBTC2 ...
def dateStr(dt): return dt.strftime('%d%b%y').upper() def shortPut(strike, units, pUSD, pBTC=None, currentBTC=None, feeRate = 0.0004): if pBTC == None: optionPrice = pUSD else: optionPrice = pBTC * currentBTC FEE = units * feeRate * currentBTC profit = pd.Series(SPOT_PRICE_RANGE) ...
This function evaluates a bear put vertical spread strategy by calculating potential profit/loss, determining trade viability, and returning key metrics like max profit/loss, probability of profit, and pseudo expected return. It retrieves option prices, checks trade feasibility, and outputs structured trade details wit...
def putVert_Z(sk1, sk2, bUnits, spot, expiry, useDeribit=True, charts = False): print('=== PUT VERTICAL Z BEAR ===') if useDeribit: ask, bid, delta = deribitOptionsData(dateStr(expiry), sk1, 'P') pBTC1 = bid ask, bid, delta = deribitOptionsData(dateStr(expiry), sk2, 'P') pBTC2 = ...
def dateStr(dt): return dt.strftime('%d%b%y').upper() def longCall(strike, units, pUSD, pBTC=None, currentBTC=None, feeRate = 0.0004): if pBTC == None: optionPrice = pUSD else: optionPrice = pBTC * currentBTC FEE = units * feeRate * currentBTC profit = pd.Series(SPOT_PRICE_RANGE) ...
The function calculates the payoff and risk/reward metrics for a bull call vertical spread strategy. It retrieves option prices (ask for long call, bid for short call) at two strike prices, computes the combined profit/loss profile, determines max profit/loss, identifies the breakeven point, and estimates the probabili...
def callVert_S(sk1, sk2, bUnits, spot, expiry, useDeribit=True, charts = False): print('=== CALL VERTICAL S BULL ===') if useDeribit: ask, bid, delta = deribitOptionsData(dateStr(expiry), sk1, 'C') pBTC1 = ask ask, bid, delta = deribitOptionsData(dateStr(expiry), sk2, 'C') pBTC2...
def dateStr(dt): return dt.strftime('%d%b%y').upper() def longPut(strike, units, pUSD, pBTC=None, currentBTC=None, feeRate = 0.0004): if pBTC == None: optionPrice = pUSD else: optionPrice = pBTC * currentBTC FEE = units * feeRate * currentBTC profit = pd.Series(SPOT_PRICE_RANGE) ...
The function `putVert_S` evaluates a **bull put vertical spread** strategy by calculating potential profits/losses, probability of success, and pseudo expected returns. It fetches put option prices (ask for sk1, bid for sk2), computes profit/loss scenarios, identifies break-even points, and assesses risk/reward. If the...
def putVert_S(sk1, sk2, bUnits, spot, expiry, useDeribit=True, charts = False): print('=== PUT VERTICAL S BULL ===') if useDeribit: ask, bid, delta = deribitOptionsData(dateStr(expiry), sk1, 'P') pBTC1 = ask ask, bid, delta = deribitOptionsData(dateStr(expiry), sk2, 'P') pBTC2 =...
def dateStr(dt): return dt.strftime('%d%b%y').upper() def longCall(strike, units, pUSD, pBTC=None, currentBTC=None, feeRate = 0.0004): if pBTC == None: optionPrice = pUSD else: optionPrice = pBTC * currentBTC FEE = units * feeRate * currentBTC profit = pd.Series(SPOT_PRICE_RANGE) ...
The code calculates a condor options trading strategy's profit/loss profile using four strike prices (sk1–sk4) and given parameters (spot price, expiry). It retrieves bid/ask prices for calls, computes max profit/loss, assesses win/loss scenarios, and calculates probability of profit and pseudo expected return. If char...
def condor(sk1, sk2, sk3, sk4, bUnits, spot, expiry, useDeribit=True, charts = False): print('=== CONDOR ===') if useDeribit: ask, bid, delta = deribitOptionsData(dateStr(expiry), sk1, 'C') pBTC1 = ask ask, bid, delta = deribitOptionsData(dateStr(expiry), sk2, 'C') pBTC2 = ask ...
def dateStr(dt): return dt.strftime('%d%b%y').upper() def callVert_S(sk1, sk2, bUnits, spot, expiry, useDeribit=True, charts = False): print('=== CALL VERTICAL S BULL ===') if useDeribit: ask, bid, delta = deribitOptionsData(dateStr(expiry), sk1, 'C') pBTC1 = ask ask, bid, delta = ...
The function generates vertical call/put spreads (S/Z types) for given dates and strike spacings, using Deribit or Okex data. It iterates through strike pairs, calculates spread results with `callVert_S/Z`/`putVert_S/Z` functions, and collects non-None outputs into a list. The task involves strategy evaluation for opti...
def getVerts(spot, dates, useDeribit=True, bUnits = 0.5, S = True, Call = True): results = [] if Call: if S: print('****** CALL VERTICAL - S ******') else: print('****** CALL VERTICAL - Z ******') else: if S: print('****** PUT VERTICAL - S ******'...
def dateStr(dt): return dt.strftime('%d%b%y').upper() def longCall(strike, units, pUSD, pBTC=None, currentBTC=None, feeRate = 0.0004): if pBTC == None: optionPrice = pUSD else: optionPrice = pBTC * currentBTC FEE = units * feeRate * currentBTC profit = pd.Series(SPOT_PRICE_RANGE) ...
The function `rodnoc` analyzes an inverse condor options strategy by calculating profit/loss scenarios for selling calls at two lower strikes (sk1, sk2) and buying calls at two higher strikes (sk3, sk4). It retrieves bid/ask prices for options using Deribit or another data source, computes max profit/loss, and evaluate...
def rodnoc(sk1, sk2, sk3, sk4, bUnits, spot, expiry, useDeribit=True, charts = False): print('=== INVERSE CONDOR ===') if useDeribit: ask, bid, delta = deribitOptionsData(dateStr(expiry), sk1, 'C') pBTC1 = bid ask, bid, delta = deribitOptionsData(dateStr(expiry), sk2, 'C') pBTC2 ...
def dateStr(dt): return dt.strftime('%d%b%y').upper() def longCall(strike, units, pUSD, pBTC=None, currentBTC=None, feeRate = 0.0004): if pBTC == None: optionPrice = pUSD else: optionPrice = pBTC * currentBTC FEE = units * feeRate * currentBTC profit = pd.Series(SPOT_PRICE_RANGE) ...
The code evaluates a **straddle options strategy** by calculating potential **maximum profit**, **maximum loss**, and **profit probability** based on given strike prices (sk1, sk2), spot price, and expiry. It fetches call/put option prices (via Deribit or custom data), computes profit/loss scenarios across spot price r...
def straddle(sk1, sk2, bUnits, spot, expiry, useDeribit=True, charts = False): if useDeribit: ask, bid, delta = deribitOptionsData(dateStr(expiry), sk1, 'C') pBTC1 = ask ask, bid, delta = deribitOptionsData(dateStr(expiry), sk2, 'P') pBTC2 = ask else: ask, bid, delta = ...
def dateStr(dt): return dt.strftime('%d%b%y').upper() def rodnoc(sk1, sk2, sk3, sk4, bUnits, spot, expiry, useDeribit=True, charts = False): print('=== INVERSE CONDOR ===') if useDeribit: ask, bid, delta = deribitOptionsData(dateStr(expiry), sk1, 'C') pBTC1 = bid ask, bid, delta = d...
The function `getCondors` generates condor or inverse condor options strategies for given dates and strike ranges. It iterates through strike spacings, constructs butterfly or condor spreads using specified parameters, and collects results from `condor`/`rodnoc` functions. The output is a list of strategy results, with...
def getCondors(spot, dates, useDeribit = True, bUnits = 0.5, butterfly = False, inverse = False): results = [] if inverse: print('****** INVERSE CONDOR ******') else: print('****** CONDOR ******') if useDeribit: spacingRange = [6,8,12] else: spacingRange = [4,6] for d in date...
def file2list(self): with open(self.fname) as f: self.slist = f.readlines() def extractall(self): self.tupletable = [] for i,line in enumerate(self.slist): tds = self.line2tds(line) if tds: tags = ('Issue', 'B_1', 'B_1 fgx', 'B_5', 'B_5 fgx') ...
This code defines a method 'fixture' that processes data by converting a file into a list, extracting all data, calculating ticket-related metrics, and performing an analysis. The main task is to prepare and analyze data from files, likely for ticket management or similar systems, by sequentially executing these operat...
def fixture(self): self.file2list() self.extractall() self.calctickets() self.analysis()
def load_data(filename): """ Load shopping data from a CSV file `filename` and convert into a list of evidence lists and a list of labels. Return a tuple (evidence, labels). evidence should be a list of lists, where each list contains the following values, in order: - Administrative, an int...
The code's main task is to train a machine learning model on shopping data, evaluate its performance, and print results. It loads data from a spreadsheet, splits it into training and test sets, trains a model, makes predictions, calculates accuracy metrics (sensitivity and specificity), and outputs correct/incorrect co...
def main(): # Check command-line arguments if len(sys.argv) != 2: sys.exit("Usage: python shopping.py data") # Load data from spreadsheet and split into train and test sets evidence, labels = load_data(sys.argv[1]) X_train, X_test, y_train, y_test = train_test_split( evidence, labe...
def predict_by_all_memories(self, x, y): if len(self.STM_X) >= self.k: STM_dist = self.getMetricDistances(x, self.STM_X, self.STM_y) STM_idx = libNearestNeighbor.nArgMin(self.k, STM_dist) STM_pred = self._predict(STM_dist, STM_idx, self.STM_y) else: STM_p...
The function performs incremental learning by updating short-term memory (STM) and long-term memory (LTM) with new data, adapts the model, enforces memory size limits, calculates prediction errors for different components (Model, STM, LTM, CM), tracks memory sizes, and returns predicted values. It manages online learni...
def _partial_fit(self, x, y): self.y.append(y) y_pred = self.predict_by_all_memories(x, y) self.STM_X.append(x) self.STM_y.append(y) self.trainStepCount += 1 self._adaptSTM() self._cleanLTM(x, y) self._enforceMaxLTMSize() self._enforceMaxSTMSiz...
def __calculate_size(size: float) -> float: """ This function calculate with size of object the quantity Args: :param(float) size: size of object in cm Returns: :return(float): quantity for gripper """ size_ = SizeOfMedicines.calculate_approach(s...
This function closes a gripper to detect objects by monitoring motor current during closure. It uses cap/body size parameters to set approach thresholds, analyzes current deviations, and verifies object presence. If detected, it triggers a confirmation thread. Returns detection status, calculated max/min approach dista...
def close_tool(self, cap_size: float = 0, body_size: float = 0) -> tuple[bool, float, float, float]: """ This function close the gripper and try detected object Args: :param(float, optional) cap_size: size for cap of object in cm. Defaults to 0. :param(float, optional) b...
def File_dialog(self): self.file_name = filedialog.askopenfilename(initialdir="/", title="Select A File", filetypes=(("xlsx files", "*.xlsx"),("csv files","*.csv"),("All Files", "."))) self.label_file["text"] = sel...
The main task of the code is to create a GUI application using Tkinter that displays CSV data in a Treeview widget, includes file browsing and loading functionality, and provides buttons for data visualization and calculation. It sets up frames, labels, scrollbars, and interactive buttons to manage and process CSV data...
def main(self): # frame for Treeview self.frame1 = tk.LabelFrame(self.root, text='CSV Data') self.frame1.place(height=250, width=500) # label self.label_file = ttk.Label(text='No File Selected') self.label_file.place(rely=0, relx=0) # Treeview widget self....
def command_read_file(self, filename: str) -> None: """Read a file into a dictionary. :precondition: the file exit. :post-condition: File read into the dictionary. @complexity: Best O(n*m) and worst O(n*m), n is the no of words in the file, m is the no of char in the word Raises...
The code defines a `menu` method that displays a command menu for interacting with a hash table. It allows users to read a file, add, find, or delete words, or exit. Based on user input, it calls corresponding methods like `command_read_file` or `command_delete_word`. The method recursively invokes itself to maintain t...
def menu(self) -> None: """ Print the menu of commands :complexity: O(1) in best case, O(n*m) in worst case """ line1 = "1. Read File" line2 = "2. Add Word" line3 = "3. Find Word" line4 = "4. Delete Word" line5 = "5. Exit" print(line1, line2, line3...
def clear_custom_cookie(): dom = get_wvs_settings_dom() custom_cookie = dom.getElementsByTagName("CustomCookies") if not custom_cookie: CustomCookieNode = dom.createElement("CustomCookies") CustomCookieNodeParent = dom.getElementsByTagName("ScanSettings")[0] CustomCookieNodeParent.ap...
The function `set_custom_cookie_main` initializes and configures custom cookies by parsing XML data to extract cookie URL, string, and enable status. It clears existing custom and default cookies before setting new custom cookie attributes using the parsed values.
def set_custom_cookie_main(): xmlParse = XmlParse() cookie_list = xmlParse.get_cookie() cookie_url = cookie_list[0] cookie_string = cookie_list[1] cookie_enable = cookie_list[2] clear_custom_cookie() #init customCookies clear_cookie() #init cookie set_custom_co...
def __save_file(self, directory, content): """ Utility function to save a gzipped HTML file :param directory: directory of the file :param content: content of the file """ with gzip.open(f"{directory}.gz", "wb") as fp: fp.write(content) def __get_documents_in...
This function scrapes documents from search pages by iterating through terms, handling pagination, errors, and retries. It extracts document metadata, retrieves full text, and saves HTML/data as specified. It supports resuming scraping, skipping existing files, and outputs structured document dictionaries with Eurovoc ...
def __get_documents_search( self, search_term, terms=[], log_errors=True, save_html=False, save_data=False, directory="./", max_retries=10, sleep_time=0, n=0, mode="year", resume_params=None, skip_existing=True, ...
def check_defined(reference, reference_name): if not reference: raise Exception('Error: ', reference_name, 'is not defined') return reference def get_configuration_item(invoking_event): check_defined(invoking_event, 'invoking_event') if is_oversized_changed_notification(invoking_event['messageTy...
This code processes an AWS Config event to check compliance of a resource. It extracts configuration details, determines applicability, invokes a compliance check, and reports results to AWS Config via put_evaluations. The function returns the compliance status after handling the event and updating the evaluation state...
def handler_wrapper(event, context): check_defined(event, 'event') invoking_event = json.loads(event['invokingEvent']) rule_parameters = {} if 'ruleParameters' in event: rule_parameters = json.loads(event['ruleParameters']) configuration_item = get_configuration_item(...
def remove_url(text): url = re.compile(r'https?://\S+|www\.\S+') return url.sub(r'', text) def remove_emoji(text): emoji_pattern = re.compile( '[' u'\U0001F600-\U0001F64F' # emoticons u'\U0001F300-\U0001F5FF' # symbols & pictographs u'\U0001F680-\U0001F6FF' # transport & m...
The code preprocesses text data by removing URLs, emojis, HTML tags, and cleaning the text, followed by stemming to normalize words, returning the processed text for further analysis or modeling.
def preprocess_data(text): text = remove_url(text) text = remove_emoji(text) text = remove_html(text) text = clean_text(text) text = stemming(text) return text
def get_client(options, client_type): us_east_1_clients = ['acm', 'route53domains'] session = boto3.Session(profile_name=options['aws_profile_name']) if client_type in us_east_1_clients: client = session.client(client_type, region_name='us-east-1') else: client = session.client(client_ty...
The main task of the code is to upload non-hidden files from a specified 'dist' directory to an S3 bucket, using different handlers for HTML, JS, CSS files, while ignoring images and hidden files. It recursively processes files, trims the 'dist' path prefix, and uses an S3 client for uploads.
def send_it(options, client=None): if client == None: client = get_client(options, 's3') for filename in glob.glob(f'{options["dist"]}/**', recursive=True): if not filename.startswith('.'): if not os.path.isdir(filename): destname = filename[len(options['dist'])+1:] ...
def get_nav_pages(files, options): nav_pages = [] for fileset in files: fileset_pages = [] if isinstance(fileset['src'], str): fileset_pages.append(fileset['src']) elif isinstance(fileset['src'], list): current_pages = GlobLoader.concat_paths(fileset['src']) ...
The function `build_pageset` generates pages by combining global and pageset-specific configurations. It initializes a Jinja2 template environment, injects options like `production`, `analytics_id`, and `recaptcha_sitekey` into each page's data, and constructs pages using `build_page`, ensuring navigation pages are inc...
def build_pageset(pageset, options): '''Logic for building pages.''' if 'nav' in pageset['options']: nav_pages = get_nav_pages(pageset['files'], options) pages = get_pages(pageset['files'], options) j2_env = get_j2_env(pageset) for page in pages: # global options if 'produ...
def get_client(options, client_type): us_east_1_clients = ['acm', 'route53domains'] session = boto3.Session(profile_name=options['aws_profile_name']) if client_type in us_east_1_clients: client = session.client(client_type, region_name='us-east-1') else: client = session.client(client_ty...
The function creates a CloudFront CDN distribution for an S3 bucket by retrieving the bucket's region, configuring the distribution with an Origin Access Identity, ACM certificate, and S3 endpoint, then creating and returning the distribution's ARN.
def create_cdn_distribution(options): s3_client = get_client(options, 's3') response = s3_client.get_bucket_location(Bucket=options['s3_bucket']) zone = response['LocationConstraint'] if not zone: zone = 'us-east-1' endpoint = f'{options["s3_bucket"]}.s3.{zone}.amazonaws.com' cf_client ...
def initial_guess(self, x0, y0, image): gauss_now = Gaussian() gauss_now.theta = 0.1 gauss_now.amp = image[x0][y0] gauss_now.x0 = where(image == gauss_now.amp)[0][0] gauss_now.y0 = where(image == gauss_now.amp)[1][0] a_nominator = image[gauss_now.x0 + 1][gauss_now.y0] + i...
The main task of the code is to model a quasar image using Gaussian functions by iteratively fitting Gaussian components to the input image. It identifies peaks, generates initial Gaussian guesses, refines them via least-squares optimization, subtracts the modeled components from the image, and computes the analytical ...
def process(self, image): """ Model a quasar image with gaussian functions. :param image: np.array of image data :return: org - original input image, mdl - modelled image, anl - analytical fourier transform of modelled image """ logger = logging.getLogger('QuasarModelLog'...
def _add_dns_lookups(self, node, calls): """ Internal function to add DNS lookups to the graph. :param node: The node name for the calls. :param calls: A pandas.DataFrame of process calls. :returns: Nothing. """ dnslookups = calls[calls['api'] == 'gethostbyname...
The main task of the code is to add network-related data to a graph structure by processing DNS, domain, and process call information from a JSON report. It converts network data into structured DataFrames, iterates through process nodes, and calls helper functions to add DNS lookups, socket activity, internet traffic,...
def _add_network_activity(self): """ Internal function that adds network data to the graph. Assumes processes have already been plotted. :returns: Nothin. """ self.domains =\ pandas.DataFrame(self.jsonreportdata['network']['domains']) self.dns =\ ...
def _add_all_processes(self): """ Internal function to add processess from JSON report process tree. :returns: Nothing. """ self._processtree = self.jsonreportdata['behavior']['processtree'] self._processes = self.jsonreportdata['behavior']['processes'] ...
This class initializes an object to parse and visualize data from a Cuckoo JSON report. It reads the report from a file or dictionary, allows customization of plotted activities (network, file operations, registry changes), and sets up a graph to represent these activities. Path filters and data loading are handled, wi...
def __init__(self, jsonreportfile=None, jsonreportdict=None, plotnetwork=True, plotfiles=True, plotfilecreates=True, plotfiledeletes=True, plotfilemoves=True, plotfilecopies=True, plot...
def validate_team(self, team: int) -> None: if (team not in [0,1]): raise ValueError("Invalid team. Valid values are 0 or 1.") def battle_is_over(self) -> bool: if self.ticks_left == 0: return True # check remaining tanks of each team, if either one is zero, return True ...
This function checks if a specified team has won a battle by verifying if the battle is over, the team still has tanks remaining, and the opposing team has no tanks left. It returns True if all conditions are met, otherwise False.
def win(self, team: int) -> bool: self.validate_team(team) other_team: int = 1 if team == 0 else 0 if (self.battle_is_over() and self.remaining_tanks(team) > 0 and self.remaining_tanks(other_team) == 0): return True else: return False
def compute_state_from_tank_state(battle: Battle, team: int, player: int, player_state: TankState) -> State: # I am realizing too late that this will not scale for more than one enemy lol in_light_cover, in_heavy_cover, ready_to_shoot, moving, possible_target, enemy_moving, enemy_light_cover = False, False, Fa...
The code implements Q-learning to train an agent for a 1v1 battle against a specified enemy strategy (greedy or random). It simulates battles, updates Q-values based on rewards and future state values, and stores the learned policy in a dictionary. If a pre-trained model is provided, it loads the weights instead. The f...
def q_learn_1v1(enemy_strategy: str, num_simulations: int = 1000, epsilon: float = 0.1, discount: float = 0.4, l_rate: float = 0.3, trained_filename: Union[str,None] = None) -> Policy: # exploration value EPSILON = epsilon DISCOUNT_FACTOR = discount INITIAL_LEARNING_RATE = l_rate # if pickled_we...
def _read_relations(self, file): id2rel, rel2id = {}, {} with open(file) as f: for index, line in enumerate(f): rel = line.strip() id2rel[index] = rel rel2id[rel] = index return id2rel, rel2id def _read_data(self, file, save_data_path):...
The code initializes a model configuration, sets up a tokenizer (BERT/RoBERTa) with special tokens based on the specified pattern, loads training/validation/test data, processes relation clusters, and shuffles task order for training. It also configures prompt tokens, relation mappings, and prepares data structures for...
def __init__(self, config=None, seed=None): self.config = config self.max_length = self.config.max_length self.task_length = self.config.task_length self.unused_tokens = ['[unused0]', '[unused1]', '[unused2]', '[unused3]'] self.unused_token = '[unused0]' if self.config.mo...
def get_donos(self): per_page = 100 # max results per page. # This is checking if the cache file exists, if it doesn't it creates it. Then it opens the file in # read and write mode. if not os.path.exists(self.cache): open(self.cache, "w") f = open(self.cach...
The code retrieves donations, filters them by a user-specified date, sums their values, formats the total to two decimal places, and returns a dictionary containing the total donation amount and count. It also ranks members based on donations.
def get_total(self) -> dict: """ It gets the latest donations from the API, adds them to the cache, and then sums up the donations from the date specified by the user Returns: A dictionary with the total money collected from donations and the number of donations. ...
def dumpClass(self, classInfo: ClassNode): plantUmlList = list() for relation in classInfo.relations: if relation.relationship == InheritanceEnum.DEPENDED: plantUmlList.append(classInfo.name + " .....> " + relation.name) if relation.relationship == InheritanceEnu...
This code generates a PlantUML class diagram from provided class information. It constructs a PlantUML script by adding class/interface definitions, extends it with dumped class details, removes duplicates, writes the result to a .puml file, generates a PNG image, and prints the class info.
def drawUml(self, classInfo: ClassNode): plantUmlList = list() plantUmlList.append("@startuml") ''' if classInfo.isInterface: plantUmlList.append("interface " + classInfo.name) else: plantUmlList.append("class " + classInfo.name) ''' plant...
def initialize(s,d,file_name): global qtables, q_tbl_cnt, src_node, des_node, weights,edges, graph # loading graph - json file with open('../graphs/'+file_name+'.json','r') as f: graph = json.load(f) # edges in graph edges = graph['edges'] # extracting the weights of the edges weig...
The main task of the code is to analyze the performance of a Q-learning algorithm in a graph-based system by evaluating how the number of iterations required to find a path between two nodes changes as the number of nodes increases. It also examines the impact of removing edges on iteration counts, generating trends an...
def main(): global qtables # learning rate # itr_lr = [] # for k in range(1,9): # alpha = k * 0.1 nodes = [] mean = [] q_ini = [] threshold = 0.3 for num_nodes in range(9, 100, 1): if num_nodes % 10 == 0: print("Iteration " + str(num_nodes)) nodes....
def convert_official_weights(ckpt_dir, use_custom_cuda): g_clone = load_generator(g_params=None, is_g_clone=True, ckpt_dir=None, custom_cuda=use_custom_cuda) # restore official ones to current implementation official_checkpoint = tf.train.latest_checkpoint('./official-pretrained') official_vars = tf.tr...
The main task of the code is to convert official model weights into CUDA and reference (ref) versions, test their generators, and validate consistency by performing cross-inference between the two versions. It first saves official weights as CUDA/ref formats, tests each, then infers CUDA weights using the ref model and...
def main(): allow_memory_growth() ckpt_dir_base = './official-converted' # phase 1-1: save official weights as cuda version use_custom_cuda = True ckpt_dir = os.path.join(ckpt_dir_base, 'cuda') if use_custom_cuda else os.path.join(ckpt_dir_base, 'ref') convert_official_weights(ckpt_dir, use_cu...
def find_paths(self, label1: str, label2: str): start_node = self.nodes.get(label1) end_node = self.nodes.get(label2) del_link = None self.res = [] path = [label1] for k in self.lines: if self.lines.get(k).get_in_service() == 0: del_link = k ...
The code generates a DataFrame containing latency, noise power, and signal-to-noise ratio metrics for all possible paths between distinct nodes in a network. It iterates through node pairs, constructs path strings, calculates signal properties via probing, and compiles results into a pandas DataFrame indexed by path na...
def create_data_frame(self): names = [] latency = [] noise = [] ratio = [] for a in self.nodes: for b in self.nodes: if a is not b: paths = self.find_paths(a, b) for path1 in paths: tmp = ...
def find_paths(self, label1: str, label2: str): start_node = self.nodes.get(label1) end_node = self.nodes.get(label2) del_link = None self.res = [] path = [label1] for k in self.lines: if self.lines.get(k).get_in_service() == 0: del_link = k ...
This function simulates network traffic recovery after a link failure. It creates a new network, applies failure scenarios, recalculates paths, adjusts transceivers using a specified strategy, and reallocates connection bit rates to match the updated traffic matrix capacity, ensuring connections adhere to remaining ban...
def traffic_recovery(self,strategy, cut=0, label=None): #failure & label used in case of removal of most congested link self.logger.reset_index() old_logger = self.logger # for recovery -> create new network and stream connections from logger, copy results into new network n = Ne...
def noise_generation(self, sig_info: signal_information.Signal_information): # OLD NOISE DEFINITION # noise = 1e-9 * sig_info.get_signal_power() * self.length # LAB8 NOISE DEFINITION noise = self.ase_generation() + self.nli_generation(self.number_of_channels, sig_info.get_signal_po...
The code propagates a lightpath signal by increasing its noise power and latency, setting the signal's channel state to 0, and passing it to the next node in the network.
def propagate(self, sig: lightpath.Lightpath): sig.noise_power_increase(self.noise_generation(sig)) sig.latency_increase(self.latency_generation(sig)) node1 = self.successive.get(self.label[1]) self.set_state(sig.get_channel(), 0) node1.propagate(sig)
def find_best_snr(self, a: str, b: str): """OLD VERSION(no route_space) best_path = None best_ratio = None for index, row in self.weighted_paths.iterrows(): # print(row["Signal to noise ratio"]) if index[0] is a and index[-1] is b: if best_ratio is...
The code processes each connection in the list to determine optimal lightpath routes based on the specified metric (SNR or Latency). It calculates signal parameters, propagates the lightpath, updates network resources, and sets connection attributes like bit rate, latency, and SNR.
def stream(self, connection_list: list[connection.Connection], label="Latency"): for elem in connection_list: if label == "SNR": path, channel = self.find_best_snr(elem.get_input(), elem.get_output()) # print(path) if path is None: ...
def instruction_fetch(pc): #returns the instruction at the pc return instruct_memory[pc] def print_string(start_address): # print the string given the starting address address = start_address address=(address//4)*4 offset=start_address%4 output="" if offset ==1: a=int(data_mem[address][...
Your return The code simulates a pipelined MIPS processor, executing instructions through five stages: fetch, decode, execute, memory access, and write-back. It handles control signals, ALU operations, memory reads/writes, and syscalls for I/O (e.g., printing values, reading input). The processor tracks clock cycles,...
def mips_processor(): pc=0x400000 clock=0 while pc<=max(instruct_memory.keys()): for i in control_signals.keys(): control_signals[i]=0 #instruction fetch instruction=instruction_fetch((pc)) clock+=1 if instruction != "00000000000000000000000000001100": # s...
def get_max(state_name): """ Parameter: state Returns a dictionary containing with information about the max temperature in a state for 2016 """ return get_max_min(state_name, 'max') def get_min(state_name): """ Parameter: state Returns a dictionary containing with information about...
The main task of the code is to aggregate weather data (max, min, mean temperatures, rainy/snowy days) for a specified state and return it as a JSON-formatted string. It calls five helper functions to retrieve individual metrics, compiles them into a list, and serializes the list using `json.dumps` for structured data ...
def get_all_state(state_name): """ returns json dump with max,min,mean,rain index, and snow index for state """ main_list = [get_max(state_name), get_min(state_name), get_mean(state_name), get_rainy_days(state_name), get_snowy_days(sta...
def get_max(state_name): """ Parameter: state Returns a dictionary containing with information about the max temperature in a state for 2016 """ return get_max_min(state_name, 'max') def get_min(state_name): """ Parameter: state Returns a dictionary containing with information about...
The function `compare_states` takes two state names as input, retrieves specific weather statistics (max, min, mean temperatures, rainy/snowy days) for each using helper functions, and returns these values in a JSON-formatted list. It aggregates data for both states and serializes the result as a JSON string for output...
def compare_states(state_name1, state_name2): """ returns json dump with information for both states in query """ compare = [get_max(state_name1), get_max(state_name2), get_min(state_name1), get_min(state_name2), get_mean(state_name1), get_mean(state_name2), ...
def get_max_city(state_name, city_name): """ returns max temp for city """ return get_min_max_city(state_name, city_name, 'max') def get_min_city(state_name, city_name): """ returns min temp in city for 2016 """ return get_min_max_city(state_name, city_name, 'min') def get_mean_city(sta...
The function `get_all_city` retrieves maximum temperature, minimum temperature, mean temperature, rainy days index, and snowy days index for a specified city and state. It aggregates these values into a list and returns them as a JSON-formatted string.
def get_all_city(state_name, city_name): """ returns json dump with max,min,mean,rain index, and snow index for state """ city_list = [get_max_city(state_name, city_name), get_min_city(state_name, city_name), get_mean_city(state_name, city_name), get_ra...
def get_max_city(state_name, city_name): """ returns max temp for city """ return get_min_max_city(state_name, city_name, 'max') def get_min_city(state_name, city_name): """ returns min temp in city for 2016 """ return get_min_max_city(state_name, city_name, 'min') def get_mean_city(sta...
The function compares two cities by retrieving and compiling statistical data (max, min, mean temperatures, rainy/snowy days) for each, then returns the results as a JSON-formatted list.
def compare_cities(state_name1, city_name1, state_name2, city_name2): """ returns json dump with information for both cities in query """ city_compare = [get_max_city(state_name1, city_name1), get_max_city(state_name2, city_name2), get_min_city(state_name1, city_n...
def get_csv_lang(filename, encoding=None): """Get the language of the export. (de/en)""" if not encoding: encoding="iso-8859-1" # default content = "" with open(filename, encoding=encoding) as file: content = file.read() lines = content.split("\n") if "Transactions" in lines[0]...
This function reads a bank CSV file using a specified encoding (default: ISO-8859-1), detects the language, filters rows with valid dates and non-empty amount fields, decodes transactions, and returns a list of processed transactions. It skips invalid rows and outbound transactions without amounts.
def read_transactions(filename, encoding=None): """Read bank .csv""" if not encoding: encoding="iso-8859-1" # default lang = get_csv_lang(filename, encoding) transactions = [] with open(filename, encoding=encoding) as file: reader = csv.reader(file, delimiter=";") for row i...
def get_member(conn, member_id): """Get a members by id from the database""" qry = """ SELECT * FROM members WHERE id = ? """ cur = conn.cursor() cur.execute(qry, [member_id]) res = cur.fetchone() return decode_member(dict_row(res, cur)) def encode_decimal(value):...
The main task of the code is to update a member's account balance and last payment date in the database based on a transaction. It checks if the transaction date is older than the member's last payment, issues a warning if so, and updates the member's record with the transaction amount and date. The function encodes da...
def add_payment(conn, transaction): """Add payment to member""" member = get_member(conn, transaction["member_id"]) if transaction["date"] < member["last_payment"]: print("WARNING: last_payment for member is more recent.") payment_date = member["last_payment"] qry = """ UPDATE m...