dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def safe_call(f, args, suppress_stdout=True, stdin=None): # Suppress stdout and/or get stdin from string if suppress_stdout: devnull = open(os.devnull, 'w') old_stdout = sys.stdout sys.stdout = devnull if stdin != None: old_stdin = sys.stdin sys.stdin = StringIO(stdin...
This function tests if a given function `f` returns the expected value `exp` when called with arguments `args` and optional input `stdin`. It uses `safe_call` to execute `f`, compares the result to `exp`, and prints colored failure/success messages. Auxiliary arguments are logged, and it returns 1 for success or 0 for ...
def test(f, args, exp, stdin=None): success, ret = safe_call(f, args, stdin=stdin) if not success: return 0 if ret != exp: p_fail(f"Returned {Colors.BLUE}{repr(ret)}{Colors.END} ({type(ret)})" + f" instead of {Colors.BLUE}{repr(exp)}{Colors.END} ({type(exp)})") retval = 0 els...
def __check_key(key: Any) -> None: if key is None: raise TypeError("None is not a valid HKEY in this context") if not isinstance(key, int) and not isinstance(key, PyHKEY): raise TypeError("The object is not a PyHKEY object") if isinstance(key, int): if key >= 2**64: raise...
The main task of the code is to create or open a registry key (including nested subkeys) with specified access rights, returning a handle to the key. It validates inputs, ensures proper parameters (e.g., non-null sub_key, correct key type), and raises exceptions for invalid cases. The function supports creating parent ...
def CreateKeyEx(key: Handle, sub_key: str, reserved: int = 0, access: int = KEY_WRITE) -> PyHKEY: # noqa """ Creates or opens the specified key, returning a handle object with access as passed in the parameter The sub_key can contain a directory structure like r'Software\\xxx\\yyy' - all the parents to yy...
def __check_key(key: Any) -> None: if key is None: raise TypeError("None is not a valid HKEY in this context") if not isinstance(key, int) and not isinstance(key, PyHKEY): raise TypeError("The object is not a PyHKEY object") if isinstance(key, int): if key >= 2**64: raise...
The main task of the `DeleteKeyEx` function is to delete a specified registry key (and its values) using the Windows API `RegDeleteKeyEx`, exclusively for 64-bit systems. It ensures the key being deleted has no subkeys and validates parameters like the key handle, subkey name, access rights, and reserved values. The fu...
def DeleteKeyEx(key: Handle, sub_key: str, access: int = KEY_WOW64_64KEY, reserved: int = 0) -> None: # noqa """ Deletes the specified key. This method can not delete keys with subkeys. If the method succeeds, the entire key, including all of its values, is removed. the function does NOT accept named p...
def __check_key(key: Any) -> None: if key is None: raise TypeError("None is not a valid HKEY in this context") if not isinstance(key, int) and not isinstance(key, PyHKEY): raise TypeError("The object is not a PyHKEY object") if isinstance(key, int): if key >= 2**64: raise...
The function `OpenKey` opens a specified Windows registry key (or subkey) using an existing handle or predefined HKEY constant, returning a new `PyHKEY` handle. It validates parameters like access rights, reserved values, and subkey names, raising exceptions for invalid inputs. The function supports error handling for ...
def OpenKey(key: Handle, sub_key: Union[str, None], reserved: int = 0, access: int = KEY_READ) -> PyHKEY: # noqa """ Opens the specified key, the result is a new handle to the specified key. one of the few functions of winreg that accepts named parameters Parameter --------- key: an...
def __check_key(key: Any) -> None: if key is None: raise TypeError("None is not a valid HKEY in this context") if not isinstance(key, int) and not isinstance(key, PyHKEY): raise TypeError("The object is not a PyHKEY object") if isinstance(key, int): if key >= 2**64: raise...
Your return The function `QueryValue` retrieves the default (unnamed) value of a Windows registry key as a string. It accesses the first value with a NULL name, returning an empty string if the value is unset or invalid. The function validates inputs, handles exceptions (e.g., invalid data types, handles), and ensure...
def QueryValue(key: Handle, sub_key: Union[str, None]) -> str: # noqa """ Retrieves the unnamed value (the default value*) for a key, as string. * Remark : this is the Value what is shown in Regedit as "(Standard)" or "(Default)" it is usually not set. Nethertheless, even if the value is not set, Quer...
def __check_key(key: Any) -> None: if key is None: raise TypeError("None is not a valid HKEY in this context") if not isinstance(key, int) and not isinstance(key, PyHKEY): raise TypeError("The object is not a PyHKEY object") if isinstance(key, int): if key >= 2**64: raise...
The main task of the `SetValue` function is to associate a string value with a specified registry key, acting as the default value shown in Regedit as "(Standard)" or "(Default)". It creates the key if it does not exist, enforces the use of `REG_SZ` (string) type, and validates parameters rigorously. The function ensur...
def SetValue(key: Handle, sub_key: Union[str, None], type: int, value: str) -> None: # noqa """ Associates a value with a specified key. (the Default Value* of the Key, usually not set) * Remark : this is the Value what is shown in Regedit as "(Standard)" or "(Default)" it is usually not set. Netherth...
def scrape_house_links(self, page_count): p1 = 'https://www.zillow.com/homes/95630_rb/?searchQueryState=%7B%22pagination%22%3A%7B%22currentPage%22%3A' p2 = '%7D%2C"usersSearchTerm"%3A"95630"%2C"mapBounds"%3A%7B"west"%3A-122.23061173828125%2C"east"%3A-120.071798261718' \ '75%2C"south"%3A38.0...
The main task of the code is to scrape home data from links by extracting key details like bed/bath/living area, additional home facts, and school information. It processes each link to gather structured data, filters relevant school labels (K-5, 6-8, 9-12), appends corresponding values, and stores the results in `self...
def scrape_home_data(self): if self.isScraping: self.scrape_house_links(20) else: self.read_home_links_list() # Add Checks: if bed/bath not there pop it. add label checks to match for link in self.homeLinks: soup = self.create_home_soup(link) ...
def gen_header_class(cls): return f"""class {cls.__name__}({', '.join(s.__name__ for s in cls.__bases__)}):""" def get_attributs(cls): attributs = [] for attribut in cls.__dict__ : if (isinstance(cls.__dict__[attribut],Attribute)): attributs.append(attribut) return attributs def gen_...
The main task of the code is to generate a class definition in Python by combining a header and body. It checks if the class has attributes: if yes, it appends generated body code; if not, it adds a `pass` statement. The result is a formatted string representing the class code.
def gen_code_class(cls): res = gen_header_class(cls) + "\n" + "\n" if len(get_attributs(cls))>0 : res += gen_body(cls) else : res += "\t" "pass" + "\n" + "\n" return res
def grab_organizations(self, delete=False): print("\n\nLOADING ORGANIZATIONS", datetime.datetime.now()) if delete: Organization.objects.all().delete() Post.objects.all().delete() print("deleted all organizations and posts") # first grab city council root ...
This code handles command-line data synchronization tasks by connecting to a database, parsing options like 'update_since' and 'endpoint', and triggering specific data retrieval methods (grab_organizations, grab_bills, etc.) based on the endpoint. It supports selective updates or full data loading, with optional deleti...
def handle(self, *args, **options): db_conn = settings.DATABASES['default'] self.db_conn_kwargs = { 'database': db_conn['NAME'], 'user': db_conn['USER'], 'password': db_conn['PASSWORD'], 'host': db_conn['HOST'], 'port': db_conn['PORT'], ...
def get_videos_by_playlist_id(playlist_id, page_token=None): playlist_items_json = get_playlist_items(playlist_id, page_token=page_token) playlist_items_items = playlist_items_json["items"] if ("nextPageToken" in playlist_items_json): token = playlist_items_json["nextPageToken"] next_page_it...
The function retrieves YouTube playlist data, extracts video information, and writes each video's details to a database, using the 'is_classic' flag to influence storage. It processes the playlist in steps: fetching items, converting to structured data, and batch-saving to the database with progress indicators.
def write_playlist_to_db(playlist_id, is_classic=False): print("Retrieving information from YouTube...") playlist_items = get_videos_by_playlist_id(playlist_id) print("Done!") print("Converting to item list") video_info = get_video_information_from_item_list(playlist_items) print("Done!") pr...
def _create_next_page_url_to_format(request): request_url =request.build_absolute_uri() if "page" in request.GET: before_page, after_page = request_url.split("page=") before_page += "page=" after_page = after_page.lstrip('123456789') return before_page + "%d" + after_page eli...
The code handles paginated artist data retrieval by processing request parameters for max items per page and page number. It constructs a JSON response with the current page's artists, total results count, and navigation links (next/previous page URLs) using Django's Paginator. The result includes artist details format...
def artists(request): params = request.GET.copy() max = 50 format_for_page = _create_next_page_url_to_format(request) if "max" in params: max = int(params.pop("max")[0]) page = 1 if "page" in params: page = int(params.pop("page")[0]) artists_obj = {"status": "success", "arti...
def place(board, counter, x, y): board = [row[:x] + counter + row[x+1:] if row_number == y else row for row_number, row in enumerate(board)] return board def pretty_print_board(board): print('---+---+---\n'.join(' %s \n' % ' | '.join(r) for r in board)) def win_for(board, counter): three = counter*3 ...
This code implements a Tic-Tac-Toe game where the user plays as "o" against a computer opponent as "x". The game initializes a 3x3 board, lets the computer make a random first move, then alternates turns with the user inputting coordinates. It validates moves, checks for wins/draws after each turn, and uses a best_move...
def play(): user_counter = "o" computer_counter = 'x' print('You are "o"s') board = [' '*3]*3 #board is represented as below # [' ', ' ', ' '] # [' ', ' ', ' '] # [' ', ' ', ' '] moves = 0 board = place(board, 'x', randint(0, 2), randint(0, 2)) ...
def decrease_width(params: Parameters, num_pixels): img = params.image.copy() # copiaza imaginea originala for i in range(num_pixels): print('Eliminam drumul vertical numarul %i dintr-un total de %d.' % (i + 1, num_pixels)) # calculeaza energia dupa ecuatia (1) din articol E = compute_...
The main task of the code is to resize or modify an image based on a specified option in the parameters. It handles four operations: reducing width, reducing height, amplifying content, or removing an object. The function uses different helper functions depending on the selected option and returns the modified image. I...
def resize_image(params: Parameters): if params.resize_option == 'micsoreazaLatime': # redimensioneaza imaginea pe latime resized_image = decrease_width(params, params.num_pixels_width) return resized_image elif params.resize_option == 'micsoreazaInaltime': resized_image = decre...
def _check_buffers(self): """ Check validity of buffers See: manual section "Limits of pre trigger, post trigger, memory size" """ pretrigger = self.data_memory_size() - self.posttrigger_memory_size() if pretrigger > 2**13: raise Exception('value of SPC_PRETRIGGER is...
This function acquires voltage data using hardware-triggered block averaging, configuring pre/post-trigger memory, setting averaging parameters, and returning interleaved voltage arrays across multiple channels. It handles both single and multi-average acquisitions, converts raw data to volts, and manages hardware trig...
def blockavg_hardware_trigger_acquisition(self, mV_range, nr_averages=10, verbose=0, post_trigger=None): """ Acquire data using block averaging and hardware triggering To read out multiple channels, use `initialize_channels`. This methods updates the...
def _channel_mask(self, channels=range(4)): """ Return mask for specified channels Args: channels (list): list of channel indices Returns: cx (int): channel mask """ cx = 0 for c in channels: cx += getattr(pyspcm, f'CHANNEL{c}') ...
The function reads data from a specified channel by enabling all channels, performing a single acquisition, and returning the average value of the specified channel's data.
def _read_channel(self, channel, memsize=None): """ Helper function to read out a channel Before a channel is measured all channels are enabled to ensure we can read out channels without the overhead of changing channels. """ if memsize is None: memsize = self._channe...
def inference(self, x): self.forward(x) return self.output def backward(self, batch_x, batch_y, batch_a): m = batch_x.shape[0] dZ2 = batch_a - batch_y self.wb2.dW = np.dot(self.A1.T, dZ2) / m self.wb2.dB = np.sum(dZ2, axis=0, keepdims=True) / m dA1 = np.dot(dZ2, s...
This method trains a neural network by iterating over epochs and batches, performing forward/backward passes, updating parameters, and periodically checking for early stopping based on error/loss. It uses a custom reader for data loading, adjusts batch size dynamically, and breaks training if CheckErrorAndLoss triggers...
def train(self, reader, checkpoint): self.loss_history = TrainingHistory() self.loss_func = LossFunction(self.params.net_type) if self.params.batch_size == -1: self.params.batch_size = reader.num_train max_iteration = math.ceil(reader.num_train / self.params.batch_size) ...
def wait_for_keypress(key_list:list): continueRoutine = True while continueRoutine: theseKeys = event.getKeys(keyList=key_list) if len(theseKeys) > 0: # at least one key was pressed # a response ends the routine continueRoutine = False def run_block(n_trials, blo...
The main task of the code is to guide participants through practice trials for three types of YES/NO questions (self-descriptive, descriptive of a friend, and semantic positivity) by providing instructions, testing response buttons, and running practice trials with finger-based responses. It ensures participants unders...
def run_practice(): instruct_text.setText(f'The 3 types of YES or NO questions you will see will be:\ \n\n1) Does a word describe you?\ \n\n2) Does a word describe {expInfo["friend_name"]} (who you mentioned earlier)?\ \n\n3) Is a word positive?') instruct_text.draw() win.flip() wait_for_keypress(key_li...
def is_lobby(self): return self.current_score() is None and self.player_state() == 'running' def is_game_over(self): return self.player_state() == 'paused' def player_state(self): player_dict = self.parse_style(self.player_elem.get_attribute('style')) return player_dict['animation-play-s...
The main task of the code is to initialize a game by continuously checking for specific states: if the game is in a lobby, it exits the loop; if the game is over, it logs the state, presses the space key, and pauses before restarting. This loop ensures the game transitions properly from initial states to active play.
def init_game(self): while True: # break on init image if self.is_lobby(): logger.info('init_game: while is_lobby') break # break on init image if self.is_game_over(): logger.info('init_game: while is_game_over ({})...
def press_space(self): action_chains = ActionChains(self.driver) action_chains.send_keys(Keys.SPACE) action_chains.perform() def grab_frame(self): # wait for next frame to grab self.wait_next_frame() # grab frame as bytes and convert them to image frame = Image....
This code processes a movement action (pressing a button or doing nothing) in a game environment, captures the resulting game state, calculates a reward, checks if the game is over, and returns these values as a tuple for reinforcement learning purposes.
def move(self, move): if move == 1: # press button self.press_space() elif move == 0: # do nothing pass next_state = self.grab_frame() reward = self.reward() done = self.is_game_over() return next_state, reward, done
def is_game_over(self): return self.player_state() == 'paused' def init_game(self): while True: # break on init image if self.is_lobby(): logger.info('init_game: while is_lobby') break # break on init image if self.is_game_...
The code initializes the game until it's no longer over, skips the lobby by pressing space repeatedly, records the start time, captures the first frame, and returns it.
def start_game(self): while self.is_game_over(): self.init_game() while self.is_lobby(): self.press_space() # self.started = time.time() frame = self.grab_frame() self.frames.append(frame) return frame
def imdecode_image(image_file): return cv2.imdecode( np.frombuffer(image_file.read(), np.uint8), cv2.IMREAD_UNCHANGED ) def recognize_fruit_by_cv_image(cv_image): freshness_percentage = freshness_percentage_by_cv_image(cv_image) return { # TODO: change freshness_level to freshnes...
The code processes an uploaded fruit image via POST request, decodes it using OpenCV, recognizes the fruit, extracts freshness level/percentage, encodes the image to base64 for display, and renders a template showing freshness percentage, corresponding label, and price. If not POST, it renders the template with hidden ...
def detects(): if request.method == "POST": cv_image = imdecode_image(request.files["image"]) fruit_information = recognize_fruit_by_cv_image(cv_image) # TODO: change freshness_level to freshness_percentage freshness_percentage = fruit_information["freshness_level"] # show s...
def _analyze_title(self, doc): """ Validate the title Args: doc: Beautful Soup Object Returns: earned/warn: Returns if the Document Title fall among the prerequisties set """ self.title = t = u"" if doc.title: self.title = t = d...
The code's main task is to analyze a webpage's HTML for optimization by evaluating elements like title, description, URL structure, anchors, images, headings, keywords, and word count. It uses BeautifulSoup to parse the HTML, performs per-page analysis via helper methods, and generates a report using the `_render()` me...
def report(self): ''' Analyzes and verified the Optimizations on the Page. ''' soup = bs4.BeautifulSoup(self.html, "html.parser") # per page analysis self._analyze_title(soup) self._analyze_description(soup) self._analyze_url_structure(soup) self....
def new_node(tag, text = None, children = None): if children == None: children = [] return { "tag": tag, "text": text, "children": children } def compile_if_is_keyword_in(self, parent, keywords): if self.is_keyword_in(keywords=keywords): self.compile_keyword(parent) else: raise SyntaxErr...
This function parses a variable declaration, creating a 'varDec' node in the parsed tree. It generates a unique ID, adds the node as a child to the parent, checks for the 'VAR' keyword, compiles the variable type, and processes the variable name list, structuring the AST with appropriate hierarchical relationships.
def compile_var_dec(self, parent): var_dec_id = gen_uuid4() self.parsed_tree[var_dec_id] = new_node(tag="varDec") self.parsed_tree[parent]["children"].append(var_dec_id) self.compile_if_is_keyword_in(parent=var_dec_id, keywords={Keyword.VAR}) self.__advance_and_do_compil...
def new_node(tag, text = None, children = None): if children == None: children = [] return { "tag": tag, "text": text, "children": children } def compile_if_is_keyword_in(self, parent, keywords): if self.is_keyword_in(keywords=keywords): self.compile_keyword(parent) else: raise SyntaxErr...
This code parses a 'do' statement in a programming language, creating a node in the parsed tree. It handles method calls with or without parentheses, processes identifiers, symbols, and expression lists, and ensures proper syntax by checking for required tokens like '(', ')', and ';'. The function advances through toke...
def compile_do(self, parent): do_statement_id = gen_uuid4() self.parsed_tree[do_statement_id] = new_node(tag="doStatement") self.parsed_tree[parent]["children"].append(do_statement_id) self.compile_if_is_keyword_in(parent=do_statement_id, keywords={Keyword.DO}) self.__advance_an...
def new_node(tag, text = None, children = None): if children == None: children = [] return { "tag": tag, "text": text, "children": children } def compile_static_field(self, parent): if self.is_keyword_in(keywords={Keyword.STATIC, Keyword.FIELD}): self.compile_keyword(parent) else: raise ...
This function parses a class variable declaration, creating a new AST node for "classVarDec", appending it to the parent node, and compiling its components (static field, type, and variable names) by advancing through the token stream and constructing the corresponding tree structure.
def compile_class_var_dec(self, parent): class_var_dec_root_id = gen_uuid4() self.parsed_tree[class_var_dec_root_id] = new_node(tag="classVarDec") self.parsed_tree[parent]["children"].append(class_var_dec_root_id) self.compile_static_field(parent=class_var_dec_root_id) self.__adv...
def new_node(tag, text = None, children = None): if children == None: children = [] return { "tag": tag, "text": text, "children": children } def is_keyword_in(self, keywords): if self.tokenizer.token_type() != TokenType.KEYWORD: return False if self.tokenizer.keyword() not in keywords: ...
This function compiles a parameter list by creating a "parameterList" node in the AST, appending it to the parent node, then parsing parameters consisting of type and variable name pairs separated by commas. It processes each parameter by compiling the type, variable name, and comma symbols, iterating until no more tok...
def compile_parameter_list(self, parent): parameter_list_id = gen_uuid4() self.parsed_tree[parameter_list_id] = new_node(tag="parameterList") self.parsed_tree[parent]["children"].append(parameter_list_id) if self.is_keyword_in(keywords={Keyword.INT, Keyword.CHAR, Keyword.BOOLEAN}): ...
def new_node(tag, text = None, children = None): if children == None: children = [] return { "tag": tag, "text": text, "children": children } def compile_if_is_keyword_in(self, parent, keywords): if self.is_keyword_in(keywords=keywords): self.compile_keyword(parent) else: raise SyntaxErr...
This code parses a 'let' statement in a programming language, building a parse tree node for variable declarations. It handles both simple assignments (var = expr) and array element assignments (var[index] = expr), validating syntax symbols and advancing through tokens. The function creates a 'letStatement' node, attac...
def compile_let(self, parent): let_statement_id = gen_uuid4() self.parsed_tree[let_statement_id] = new_node(tag="letStatement") self.parsed_tree[parent]["children"].append(let_statement_id) self.compile_if_is_keyword_in(parent=let_statement_id, keywords={Keyword.LET}) self.__adv...
def new_node(tag, text = None, children = None): if children == None: children = [] return { "tag": tag, "text": text, "children": children } def compile_if_is_keyword_in(self, parent, keywords): if self.is_keyword_in(keywords=keywords): self.compile_keyword(parent) else: raise SyntaxErr...
This function parses an 'if' statement in a compiler, constructing an abstract syntax tree (AST) node for the statement. It checks for the 'if' keyword, processes the condition in parentheses, compiles the expression, and adds the statement block. It also handles an optional 'else' clause by checking for the keyword an...
def compile_if(self, parent): if_statement_id = gen_uuid4() self.parsed_tree[if_statement_id] = new_node(tag="ifStatement") self.parsed_tree[parent]["children"].append(if_statement_id) self.compile_if_is_keyword_in(parent=if_statement_id, keywords={Keyword.IF}) self.__advance_an...
def new_node(tag, text = None, children = None): if children == None: children = [] return { "tag": tag, "text": text, "children": children } def compile_if_is_keyword_in(self, parent, keywords): if self.is_keyword_in(keywords=keywords): self.compile_keyword(parent) else: raise SyntaxErr...
This code compiles a while loop statement into an abstract syntax tree (AST). It creates a "whileStatement" node, validates syntax elements (while keyword, parentheses, braces), compiles the condition expression, and processes the loop body statements. The function builds a hierarchical tree structure representing the ...
def compile_while(self, parent): while_statement_id = gen_uuid4() self.parsed_tree[while_statement_id] = new_node(tag="whileStatement") self.parsed_tree[parent]["children"].append(while_statement_id) self.compile_if_is_keyword_in(parent=while_statement_id, keywords={Keyword.WHILE}) ...
def new_node(tag, text = None, children = None): if children == None: children = [] return { "tag": tag, "text": text, "children": children } def compile_if_is_keyword_in(self, parent, keywords): if self.is_keyword_in(keywords=keywords): self.compile_keyword(parent) else: raise SyntaxErr...
This code compiles a subroutine declaration by creating a subtree node, adding it to the parent, and sequentially parsing its components: type, name, parameters, and body. It uses helper methods to advance through tokens and compile each part, ensuring proper structure in the parsed tree.
def compile_subroutine(self, parent): subroutine_root_id = gen_uuid4() self.parsed_tree[subroutine_root_id] = new_node(tag="subroutineDec") self.parsed_tree[parent]["children"].append(subroutine_root_id) self.compile_if_is_keyword_in(parent=subroutine_root_id, keywords={Keyword.CONSTRUCT...
def compile_var_name(self, parent): self.compile_if_is_identifier(parent) def is_symbol_in(self, symbols): if self.tokenizer.token_type() != TokenType.SYMBOL: return False if self.tokenizer.symbol() not in symbols: return False return True def compile_symbol(self, parent): symbol...
This function compiles a list of variable names by iterating through tokens. It first compiles the initial variable name, then repeatedly processes commas to add subsequent variables, compiling each new name. The loop terminates when a semicolon is encountered, at which point the symbol is compiled and the process stop...
def compile_var_name_list(self, parent): self.compile_var_name(parent=parent) while (self.tokenizer.has_more_tokens()): self.tokenizer.advance() if self.is_symbol_in({","}): self.compile_symbol(parent=parent) self.__advance_and_do_compile(self.comp...
def new_node(tag, text = None, children = None): if children == None: children = [] return { "tag": tag, "text": text, "children": children } def is_possibly_term(self): return self.tokenizer.token_type() == TokenType.INT_CONST or \ self.tokenizer.token_type() == TokenType.STRING...
This function parses an expression by creating a new expression node in the parsed tree, appending it to the parent node, then iteratively compiling terms and operators until a non-operator symbol is encountered, building the expression structure with children nodes for terms and operators.
def compile_expression(self, parent): expression_id = gen_uuid4() self.parsed_tree[expression_id] = new_node(tag="expression") self.parsed_tree[parent]["children"].append(expression_id) while self.is_possibly_term(): self.compile_term(parent=expression_id) if sel...
def new_node(tag, text = None, children = None): if children == None: children = [] return { "tag": tag, "text": text, "children": children } def __advance_and_do_compile(self, compile_function, parent = None, keywords = None, symbols = None): if (self.tokenizer.has_more_tokens()): s...
This method compiles a class declaration by building a parse tree. It initializes a root node, processes the class keyword, name, and opening brace, then iterates through tokens to compile class variables (static/field) and subroutines (constructor/function/method). The loop ends when encountering a closing brace, ensu...
def compile_class(self): class_root_id = "root" self.root_id = class_root_id self.parsed_tree[class_root_id] = new_node(tag="class") self.__advance_and_do_compile(self.compile_class_keyword, parent=class_root_id) self.__advance_and_do_compile(self.compile_class_name, parent=class...
def new_node(tag, text = None, children = None): if children == None: children = [] return { "tag": tag, "text": text, "children": children } def compile_if_is_keyword_in(self, parent, keywords): if self.is_keyword_in(keywords=keywords): self.compile_keyword(parent) else: raise SyntaxErr...
The code parses a return statement in a programming language, creating a syntax tree node for it. It checks for the 'return' keyword, processes an optional expression, and ensures a semicolon is present, adding corresponding nodes to the parsed tree structure.
def compile_return(self, parent): return_statement_id = gen_uuid4() self.parsed_tree[return_statement_id] = new_node(tag="returnStatement") self.parsed_tree[parent]["children"].append(return_statement_id) self.compile_if_is_keyword_in(parent=return_statement_id, keywords={Keyword.RETURN...
def new_node(tag, text = None, children = None): if children == None: children = [] return { "tag": tag, "text": text, "children": children } def is_possibly_term(self): return self.tokenizer.token_type() == TokenType.INT_CONST or \ self.tokenizer.token_type() == TokenType.STRING...
This function compiles a list of expressions into a parse tree. It creates an "expressionList" node, adds it to the parent, then iteratively compiles expressions and commas until a non-term is encountered. Each expression is added as a child, with commas handled as separators. The loop stops when no more terms can be p...
def compile_expression_list(self, parent): expression_list_id = gen_uuid4() self.parsed_tree[expression_list_id] = new_node(tag="expressionList") self.parsed_tree[parent]["children"].append(expression_list_id) while self.is_possibly_term(): self.compile_expression(parent=exp...
def new_node(tag, text = None, children = None): if children == None: children = [] return { "tag": tag, "text": text, "children": children } def is_keyword_in(self, keywords): if self.tokenizer.token_type() != TokenType.KEYWORD: return False if self.tokenizer.keyword() not in keywords: ...
The function `compile_statements` parses a sequence of statements by creating a "statements" node in a parse tree, then iteratively processes each statement based on encountered keywords (e.g., LET, IF, WHILE). It appends child nodes to the "statements" node, delegates compilation to specific methods (e.g., `compile_le...
def compile_statements(self, parent): statements_id = gen_uuid4() self.parsed_tree[statements_id] = new_node(tag="statements") self.parsed_tree[parent]["children"].append(statements_id) while (self.is_keyword_in(keywords={Keyword.LET, Keyword.IF, Keyword.WHILE, Keyword.DO, Keyword.RETUR...
def get_subject(self, doc, verb): return self.get_children(doc, verb, [nsubj, csubj, agent]) def get_children(self, doc, word, relations): children = [] for token in doc: append = False for relation in relations: if token.dep == relation: ...
This code recursively parses a document to extract and structure verbs along with their syntactic dependencies, including subjects, objects, and modifiers, while avoiding redundant processing of auxiliary verbs. It constructs a hierarchical representation of verbs and their relationships, returning parsed components if...
def rec_parser(self, doc, used_verbs = []): verbs = [] if len(doc) == 1: return doc[0] for token in doc: if token.pos == VERB and token.dep not in [auxpass, aux] and token not in used_verbs: used_verbs.append(token) verbs.append(( ...
def get_buttom(browser, *args): try: button = browser.find_element_by_css_selector('.tCibT.qq7_A.z4xUb.w5S7h') if button is not None: browser.execute_script("window.scrollTo(0, document.body.scrollHeight);") time.sleep(0.5) button.click() time.sleep(1)...
The main task of the code is to automate scrolling through a dynamically loading webpage using Selenium, capture photo URLs encountered during scrolling, and store them in a JSON file. It initializes a Firefox browser, navigates to the given URL, scrolls to the bottom repeatedly until no new content loads, handles pote...
def main(http_url_page, dir_path, dir_path_img, *args): """A method for scrolling the page.""" # Specify the full path to geckodriver.exe for Windows options = Options() options.headless = False driver = Firefox(options=options, executable_path=r'.\geckodriver.exe') driver.get(http_url_pag...
def tokenize_lines(plain_text): """ tokenize_lines -Accepts the lyrics of a song as a string and partitions the string into a list of lines. :param plain_text: The string containing song lyrics read from plaintext or HTML. :return tokenized_lines: A list of lines composed of the provided string delimina...
The main task of the code is to perform Grapheme-to-Phoneme (G2P) transcriptions using CMUDict, processing song metadata and ASCII lyrics. It tokenizes text, generates ARPABET phonetic transcriptions, logs failed conversions, and saves results as JSON files in a specified directory. The function optionally downloads NL...
def main(download_new_corpus, storage_dir): """ main -Performs Grapheme to Phoneme (G2P) Transcriptions by: 1. Reading ASCII plaintext files 2. Downloading new corpora for use by NLTK (if neccessary) 3. Encoding metadata such as (song name, artist name, album, g2p accuracy, etc...) in JSON form ...
def distToPathSegment(nk, p): kp0 = UTM_path[nk % len(UTM_path)] kp1 = UTM_path[(nk+1) % len(UTM_path)] return distToSegment(p, kp0, kp1) def closestPathSegmentMidpoint(nk, p): kp0 = UTM_path[nk % len(UTM_path)] kp1 = UTM_path[(nk+1) % len(UTM_path)] return midPointSegment(p, kp0, kp1) def dist2...
This function calculates the cross-track error (CTE), distance to the next waypoint, and current lap distance for a given point `p` relative to a predefined path. It identifies the closest path segment, computes the CTE using the segment's perpendicular distance and orientation, determines the distance to the subsequen...
def NearestWayPointCTEandDistance(p): distance_to_waypoint = 1000.0 k=0 for i in range(len(UTM_path)): distance = distToPathSegment(i, p) if distance < distance_to_waypoint: distance_to_waypoint = distance k=i # get closest midpoint midp = closestPathSegment...
def _add_ecc_and_interleave(self, datacodeword): numOfBlocks = _NUM_ERROR_CORRECTION_BLOCKS[1][5] # ECC lev M va ver 5 blockECClen = _ECC_CODEWORDS_PER_BLOCK[1][5] rawCodeWords = self._get_Num_Raw_Data_Modules(5)//8 numshortblocks = numOfBlocks - (rawCodeWords % numOfBlocks) shor...
This code initializes a QR code generator by setting up parameters like version, error correction level, and data. It processes data codewords, constructs a 2D matrix for the QR image, applies error correction, draws functional patterns, masks the data, and generates the final QR image. The main task is to create a QR ...
def __init__(self, version, ecclvl, datacodeword, mask): self._version = version self._size = self._version * 4 + 17 # 2.1.2 tao bo ma sua loi # buoc 1 chon mua sua loi self._errcorlvl = ecclvl # buoc 2 tao thong diep da thuc n = 8 datacodewords = [dataco...
def validateConfig(self): if ( self._config_file == None ): raise Exception("Main Configuration files are not set...\n set variable CONFIG_FILE to config file path") self._api_key = os.getenv('GENAI_API_KEY') if ( self._api_key == None ): raise Exception("GenAI A...
The code defines a method `fw` that performs three main tasks: validates the configuration, processes data, and generates output. It sequentially calls `validateConfig()` to check configuration validity, `process()` to handle data transformation, and `generate()` to create the final output or files. The method ensures ...
def fw(self): self.validateConfig() self.process() self.generate()
def validateConfig(self): if ( self._config_file == None ): raise Exception("Main Configuration files are not set...\n set variable CONFIG_FILE to config file path") self._api_key = os.getenv('GENAI_API_KEY') if ( self._api_key == None ): raise Exception("GenAI A...
The code's main task is to configure and prepare a target object by first validating its configuration, then processing it, and finally applying decorators to enhance or modify its behavior, ensuring it meets required specifications for subsequent operations.
def targetSetup(self): self.validateConfig() self.process() self.decorate()
def run_test_fund(self): # if deployment did not already happen do it now if not self.dao_addr: self.run_test_deploy() else: print( "WARNING: Running the funding scenario with a pre-deployed " "DAO contract. Closing time is {} which is appr...
The main task of the code is to simulate a DAO proposal test by generating a random proposal with specified parameters, creating a JavaScript file to execute the proposal, running the test script, and verifying outcomes like vote counts, proposal status, and deposit returns against expected results. It ensures the prop...
def run_test_proposal(self): if not self.token_amounts: # run the funding scenario first self.run_test_fund() debate_secs = 20 minamount = 2 # is determined by the total costs + one time costs amount = random.randint(minamount, sum(self.token_amounts)) v...
def run_test_proposal(self): if not self.token_amounts: # run the funding scenario first self.run_test_fund() debate_secs = 20 minamount = 2 # is determined by the total costs + one time costs amount = random.randint(minamount, sum(self.token_amounts)) v...
The main task of the code is to execute a rewards test scenario by creating a JavaScript file with parameters like DAO contract details, reward amounts, and debate duration. It runs the test script, evaluates outcomes (e.g., DAO balances), and stores results. If no proposal ID exists, it first runs a proposal test. The...
def run_test_rewards(self): if not self.prop_id: # run the proposal scenario first self.run_test_proposal() debate_secs = 15 self.create_js_file( 'rewards', { "dao_abi": self.dao_abi, "dao_address": self.dao_addr, ...
def run_test_rewards(self): if not self.prop_id: # run the proposal scenario first self.run_test_proposal() debate_secs = 15 self.create_js_file( 'rewards', { "dao_abi": self.dao_abi, "dao_address": self.dao_addr, ...
This code prepares a test scenario for a DAO split by generating votes, creating a JavaScript configuration file with parameters like debating period and gas, and executing the script. It returns the generated votes and script output for testing.
def prepare_test_split(self, split_gas): if self.prop_id != 2: # run the rewards scenario first self.run_test_rewards() debate_secs = 15 votes = create_votes_array( self.token_amounts, not self.args.proposal_fail ) self.create_js_f...
def to_tableau(c, A, b): xb = [eq + [x] for eq, x in zip(A, b)] z = c + [0] return xb + [z] def can_be_improved_for_dual(tableau): rhs_entries = [row[-1] for row in tableau[:-1]] return any([entry < 0 for entry in rhs_entries]) def print_table(tableau): n_var = len(tableau[0]) var = ["x{0}"....
The code implements the **dual simplex algorithm** to solve a linear programming problem. It converts the input coefficients (`c`, `A`, `b`) into a tableau, iteratively improves the solution by selecting pivot positions, and performs pivoting steps until no further improvements are possible. The algorithm checks for op...
def dual_simplex(c, A, b): tableau = to_tableau(c, A, b) it = 0 while can_be_improved_for_dual(tableau): print("\n\nIteration: ", it) print_table(tableau) it += 1 pivot_position = get_pivot_position_for_dual(tableau) tableau = pivot_step(tableau, pivot_position) ...
def north_west_corner(sources, dest, costs): temp_source = sources.copy() temp_dest = dest.copy() n_source, n_dests = costs.shape assigned = np.zeros(costs.shape) while find_north_west_corner(temp_source, temp_dest): x, y = find_north_west_corner(temp_source, temp_dest) min_cost = m...
The code implements the Modified Distribution (MODI) method for solving transportation problems. It initializes with the northwest corner rule, calculates dual variables (U, V), and iteratively improves the solution by identifying entering variables via penalty matrices, adjusting allocations through closed loops, and ...
def Modi_method(sources, dest, costs): assigned = north_west_corner(sources, dest, costs) print("Initial Assigned Values:\n", assigned) print("Initial Cost:", get_cost(costs, assigned)) U, V = find_uv_values(sources, dest, costs, assigned) print("Initial U Values:", U) print("Initial V Values:"...
def read_ref_from_file(self): with open(self.reference, 'r') as f: self.ref_name = f.readline() #reference genome self.ref = f.readline().strip()[1:] self.ref_length = len(self.ref) def read_total_reads_and_bases(self): with open(self.summary_path+"basecalled/count.cs...
The main task of the code is to aggregate statistical data from a file by sequentially reading reference information, total reads/bases, barcode summaries, and mapped read statistics. This method orchestrates four sub-processes to compile comprehensive sequencing data metrics for analysis or reporting.
def read_stats(self): self.read_ref_from_file() self.read_total_reads_and_bases() self.read_barcode_summary() self.read_mapped_reads()
def write_list(f, values): string_list = [str(v) for v in values] f.write('{}\n'.format(OUTPUT_SEPARATOR.join(string_list))) def determine_column_positions(raw_lines): global input_separator global column_position column_position = {} # read the column names from the raw file to figure out their...
The main task of the code is to process multiple input files by determining their column positions, then aggregate and write the processed data into a single output file with specified columns. It creates the output directory if needed, reads input files, identifies column positions, and writes results to the output fi...
def open_files(data_path, output_path): global column_position output_dir = os.path.dirname(output_path) pathlib.Path(output_dir).mkdir(parents=True, exist_ok=True) filenames = glob.glob(data_path) with open(output_path, "w") as output_file: write_list(output_file, OUTPUT_COLUMNS) fo...
def get_statement(soup): return concat_contents(soup.find('div', 'header').next_sibling.contents) def get_content(soup, _class=''): element = soup.find('div', _class) if not element: return None tags = element.contents tags.pop(0) return concat_contents(tags) def get_sample_tests(souped_...
The code parses an HTML problem page to extract structured information, including the problem title, statement, input/output specifications, sample tests, and notes, returning them as a dictionary.
def parse_problem(raw_problem_page): soup = bs4.BeautifulSoup(raw_problem_page, "html.parser") problem = { "title": soup.find('div', 'title').string, # "timeLimit": split_limit(soup.find('div', 'time-limit').contents[1].string), # "memoryLimit": split_limit(soup.find('div', 'memory-limit...
def _validate_word(self, word) -> None: if not word: raise ValueError('Invalid None value for response') if len(word) != self.word_length: raise ValueError('Invalid string length for response') def make_attempt_with_input(self) -> None: self.make_attempt(input('Please inp...
This method simulates a solo Wordle game by validating an answer, converting it to uppercase, and allowing a specified number of attempts. For each attempt, it processes user input, checks the guess against the answer, and returns True if solved within attempts; otherwise, returns False.
def play_wordle_alone_with_answer(self, answer): self._validate_word(answer) answer = answer.upper() for attempt in range(self.num_attempts): self.make_attempt_with_input() self.get_automated_attempt_response(answer) if self.is_solved(): return...
def make_attempt_with_input(self) -> None: self.make_attempt(input('Please input a word attempt!\n')) def get_user_attempt_response(self) -> str: response = input('Please input the response to the last attempt with not contained = X, ' 'misplaced = ?, and correct = O. Example fo...
This method simulates a solo Wordle game without revealing the answer. It iterates up to self.num_attempts, prompting user guesses, checking responses, and verifying if the puzzle is solved after each attempt. If solved within attempts, it returns True; otherwise, returns False after exhausting all tries.
def play_wordle_alone_without_answer(self): for attempt in range(self.num_attempts): self.make_attempt_with_input() self.get_user_attempt_response() if self.is_solved(): return True return False
def create_letter_position_freq_dict(words): freq_dict = {} for word in words: for i in range(len(word)): key = get_letter_position_freq_dict_key(word, i) freq_dict[key] = freq_dict.get(key, 0) + 1 return freq_dict def get_best_freq_score_word(self, freq_dict: dict) -> str: ...
The main task of the code is to solve a Wordle game by iteratively selecting the best word based on letter frequency analysis, attempting it, and filtering remaining possible words according to feedback. It returns True if the word is solved within the allowed attempts, otherwise False. The algorithm uses frequency dic...
def solve(self, answer=None) -> bool: wordle = Wordle(self.word_length, self.num_attempts) possible_words = self.filtered_words_by_length # Taking most expensive parts of what's in this loop, # the time complexity of WordleSolver.solve is O(num_words*word_length*num_attempts) fo...
def _get_headers(self): print(self.session_token_info) access_token = self.session_token_info['access_token'] headers = {"Authorization": f"Bearer {access_token}"} return headers def _get_track_uri_if_found(self, track_data, name, artists_names): track_name = track_data["name"] ...
This function searches Spotify for a track by name, artist(s), and album, returning the track's URI if found. It constructs a query with the given parameters, sends a GET request to Spotify's API, and checks the response. If no match is found, it retries without lowercasing the album name.
def search_track_and_with_album(self, name, artists_names, album_name): headers = self._get_headers() artists_query = "".join([f"artist:{artist}" for artist in artists_names]) url = f"{self.SPOTIFY_API_BASE_URL}search?q={name}_{artists_query}album:{album_name.lower()}&type=track&offset=0&limit=5...
def _get_headers(self): print(self.session_token_info) access_token = self.session_token_info['access_token'] headers = {"Authorization": f"Bearer {access_token}"} return headers def _get_track_uri_if_found(self, track_data, name, artists_names): track_name = track_data["name"] ...
This function searches Spotify for a track by combining the provided track name and artist names into a query, using the Spotify API. It returns the track URI if found; otherwise, it delegates to another method that includes the album name in the search.
def search_track_with_name_separator(self, name, artists_names, album_name): headers = self._get_headers() artists_query = "".join([f"artist:{artist}" for artist in artists_names]) url = f"{self.SPOTIFY_API_BASE_URL}search?q={name}_{artists_query}&type=track&offset=0&limit=5" response = ...
def _get_headers(self): print(self.session_token_info) access_token = self.session_token_info['access_token'] headers = {"Authorization": f"Bearer {access_token}"} return headers def _get_track_uri_if_found(self, track_data, name, artists_names): track_name = track_data["name"] ...
This function searches Spotify for tracks matching a given name and artists, returning the first matching track's URI. If no match is found, it falls back to an alternative search method.
def search_track(self, name, artists_names, album_name=None): headers = self._get_headers() artists_query = "".join([f"artist:{artist}" for artist in artists_names]) url = f"{self.SPOTIFY_API_BASE_URL}search?q={name}{artists_query}&type=track&offset=0&limit=5" response = requests.get(ur...
def get_path(event): app_id = event["queryStringParameters"]['appId'] logger.info(f'** AppId: {app_id}') stage = event["queryStringParameters"]['stage'] logger.info(f'** Stage: {stage}') path = f'/{app_id}/{stage}/' if 'x-path-override' in event['headers']: path = event['headers']['x...
The code processes incoming events by parsing JSON data, extracting key-value pairs and tags, then updating AWS SSM parameters with the parsed data and associated tags. It logs event details, handles parsing via two methods based on headers, and returns a success or error response.
def handler(event, context): logger.info('** Incoming event!') logger.info(f'Event:\n{event}') try: # init path = get_path(event) keyValueDict = {} data = json.loads(event['body']) logger.info('** Parsing json data **') if 'x-kv-block-parser' in event['he...
def parse_event(event): app_id = event['queryStringParameters']['appId'] logger.info(f'AppId: {app_id}') stage = event['queryStringParameters']['stage'] logger.info(f'Stage: {stage}') if 'x-path-override' in event['headers']: path = event['headers']['x-path-override'] else: pa...
The code processes an incoming event by parsing its parameters and returning them in a JSON response. If parsing fails, it returns a 500 error. The handler logs the event, extracts path parameters, validates them, and constructs a structured response. The main task is to parse and return event parameters while handling...
def handler(event, context): logger.info('Incoming event!') logger.info(f'Event:\n{event}') try: path = parse_event(event) naked_params = get_params(path) params = parse_params(path, naked_params) response = { 'statusCode': 200, 'body': params, ...
def get_config(): if production: filename = source_dir / 'config.prod.yml' else: filename = source_dir / 'config.yml' return read_yml(filename) def service_relocate_paths(service, base_dir): service_relocate_build_path(service, base_dir) service_relocate_volumes_path(service, base_d...
The function generates a Docker Compose YAML file by copying an existing configuration, updating service paths, and adding new services from task directories. It ensures the 'services' section exists, processes each task directory to create services, and writes the final configuration to the specified file.
def create_compose_yml(filename): compose = deepcopy(get_config()['compose']) if 'services' not in compose: compose['services'] = {} services = compose['services'] for service in services.values(): service_relocate_paths(service, source_dir) for path in (source_dir / 'tasks').iterd...
def compose_yml_filename(): return source_dir / '.generated/docker-compose.yml' def ensure_path_parents(path): path.parent.mkdir(parents=True, exist_ok=True) def create_compose_yml(filename): compose = deepcopy(get_config()['compose']) if 'services' not in compose: compose['services'] = {} s...
This code ensures the creation of a Docker Compose YAML file by generating its filename, verifying the existence of required directory paths, and then creating the YAML file itself. The main task is to guarantee the proper setup and generation of a Docker Compose configuration file.
def ensure_compose_yml(): yml = compose_yml_filename() ensure_path_parents(yml) create_compose_yml(yml)
def ensure_compose_yml(): yml = compose_yml_filename() ensure_path_parents(yml) create_compose_yml(yml) def compose_yml_filename(): return source_dir / '.generated/docker-compose.yml' def ensure_docker_is_running(): from subprocess import check_call if is_docker_running(): return c...
The function initializes Docker Compose by ensuring the presence of a `docker-compose.yml` file and verifying Docker is running. It then creates and returns a `DockerCompose` object with the specified YAML file and project name, enabling container orchestration and management via Docker Compose commands.
def docker_compose(): from docker_composer import DockerCompose ensure_compose_yml() file = [str(compose_yml_filename())] ensure_docker_is_running() return DockerCompose(file=file, project_name=project_name)
def mtFileClassification(input_file, model_name, model_type, plot_results=False, gt_file=""): ''' This function performs mid-term classification of an audio stream. Towards this end, supervised knowledge is used, i.e. a pre-trained classifier. ARGUMENTS: - input_file: ...
The code evaluates the performance of a classification or segmentation model on audio files in a directory by processing each .wav file, comparing predictions against ground truth .segments files, aggregating accuracy, confusion matrices, and metrics (recall, precision, F1) across all files, then printing average/media...
def evaluateSegmentationClassificationDir(dir_name, model_name, method_name): flags_all = numpy.array([]) classes_all = [] accuracies = [] for i, f in enumerate(glob.glob(dir_name + os.sep + '*.wav')): # for each WAV file wav_file = f print(wav_file) gt_file = f.r...
def initiate_hm(HMS, n_days = 7, n_staff = 11): harmonymemory = [] for i in range(HMS): harmony = generate_random_staff_planning(n_days = n_days, n_staff = n_staff) hourly_planning = staffplanning_to_hourlyplanning(harmony) score = cost(hourly_planning, hourlystaff_needed) harmon...
This function implements a Harmony Search algorithm to optimize staff scheduling, minimizing cost while meeting hourly staff requirements. It iteratively generates and evaluates schedules using parameters like HMCR (harmony memory consideration rate) and PAR (pitch adjustment rate), updating the harmony memory with bet...
def harmony_search(hourlystaff_needed, HMS = 20, HMCR = 0.9,PARMIN = 0.0,PARMAX = 1.0,NI = 1000): bw1 = 6 bw2 = 3 ucb = 0 ucw = 0 ngh = 4 fcb = 10 fcw = 10 n_days = 5 n_staff = 11 hm = initiate_hm(HMS, n_days, n_staff) hm = sorted(hm, key=itemgetter('score')) for iteratio...
def create_parent_generation(n_parents, n_days = 7, n_staff = 11): parents = [] for i in range(n_parents): parent = generate_random_staff_planning(n_days = n_days, n_staff = n_staff) parents.append(parent) return parents def select_acceptable(parent_gen): parent_gen = [parent for parent ...
The code implements a genetic algorithm to optimize staff scheduling. It iteratively generates, selects, combines, and mutates parent generations to evolve toward an optimal schedule meeting specified hourly staff requirements, returning the best solution after a given number of iterations.
def gen_algo(hourlystaff_needed, n_iterations): generation_size = 500 parent_gen = create_parent_generation(n_parents=generation_size, n_days=5, n_staff=11) for it in range(n_iterations): parent_gen = select_acceptable(parent_gen) parent_gen = select_best(parent_gen, hourlystaff_needed, n_b...
def retrieveAllAirQualityData(zone, start_date, end_date, debug): stationCodes = retrieveStationCodes(zone, debug) listForHarmonisation = [] for item in stationCodes: listForHarmonisation.append(retrieveAirQualityDataWithStationCode(item, start_date, end_date, debug)) return listForHarmonis...
The main task of the code is to parse command-line arguments to configure parameters for retrieving and processing air quality data. It retrieves data for a specified time range and location, consolidates it, then saves the output as CSV, Orion JSON, or PostgreSQL format based on the selected mode. Debug mode prints co...
def main(argv): optlist, args = getopt.getopt(argv, '', ['start=', 'end=', 'zone=', 'host=', 'port=', 'mode=', 'output-file=', 'schema=', 'debug=', 'username=', 'password=', 'table=', 'baseurl=',]) now=datetime.datetime.now() yesterday=now-datetime.timedelta(days=1) yearago=yesterday-datetime.timedelta...
def extractStationCodes(source): stationCodes=[] startDT={} endDT={} print('Checking for site codes & date ranges') for i in source.index: datarow=source.loc[i,:] site=datarow['SiteCode'] dt=datarow['MeasurementDate'] fdt=formatAsNGSIDate(dt) if site is not...
The main task of the code is to process data from a source DataFrame, authenticate with Fiware using provided credentials, manage token refreshes (every 500 requests), and store records in Fiware while checking against existing entities to avoid duplication. It extracts station codes and date ranges, caches existing Fi...
def mainLoop(fiwareAuthBaseURL, fiwareBaseURL, fiwareService, fiwareServicePath, fiwareUser, fiwarePassword, source): useCount=0 token=None stationCodes, startDT, endDT=extractStationCodes(source) cache=listExistingEntities(fiwareAuthBaseURL, fiwareUser, fiwarePassword, fiwareBaseURL, fi...
def enter(lines, x, y, relX, relY, scrolly): # create new lines if needed lineRemainder = lines[relY][x:] lines.insert(relY, lines[relY][:x]) x = 0 # Indent if there is tab if (tabCount := countTabSpaces(lines[relY])) > 0: lines[relY+1] = TAB_SPACE * tabCount + lineRemainder x +=...
This function processes user input in a text editor interface, updating cursor position (x, y), scroll offsets (scrollx, scrolly), and text content (lines) based on key presses. It handles navigation (arrow keys), editing (backspace, enter), clipboard operations (Ctrl+C/V), and screen resizing. The function returns upd...
def HandleInput(scr, key, lines, x, y, scrollx, scrolly, relX, relY, renderUpdate): global quit if key == curses.KEY_RESIZE: print(curses.LINES-1, curses.COLS-1) scr.clear() scr.refresh() if key == input.LEFT: x -= 1 if x <= 0 and scrollx > 0: scrollx -= ...
def renderLineNumbers(scr, color): for i in range(0, MAX_FILE_LENGTH): s = str(i).rjust(LINE_NUM_WIDTH-LINE_NUM_PAD, ' ') scr.addstr(i, 0, f'{s}|', color) def initNavMenu(nav_win, nav_bgcolor) -> nav.NavBar: # Set up navbar buttons fileBtn = nav.DropDownButton("File", ProcessNavActions) ...
The code creates a text editor using the curses library, featuring syntax highlighting, line numbers, scroll bars, navigation tabs, and mouse input handling. It loads files, renders content dynamically, and manages user interactions for editing and navigation within a terminal-based interface.
def main(stdscr): ######## # Config ######## bkgd = curses.COLOR_BLACK curses.init_pair(100, curses.COLOR_WHITE, curses.COLOR_BLACK) COL_DEFAULT = curses.color_pair(100) curses.init_pair(101, curses.COLOR_WHITE, 235) COL_OFFDARK = curses.color_pair(101) curses.init_pair(102, 245, cur...
def clear_freestyle_edges(obj: bpy.types.Object) -> None: """ Clears all the FreeStyle edges of the object. :param obj: the object :return: nothing """ bpy.ops.object.mode_set(mode="EDIT") select_all_edges(obj) bpy.ops.mesh.mark_freestyle_edge(clear=True) def init_object(obj: bpy.types.O...
The function creates and modifies a 3D object in Blender by duplicating a shape, applying transformations, bisecting geometry, cleaning vertices, adjusting origins, and positioning it relative to the camera, returning the processed object for further use.
def create_answer(shape_name: str, original_co, original_no, rotation, diff: Tuple[float, float, float] = (0, 0, 0), ratio_value: float = 2.0): try: bpy.ops.object.mode_set(mode="OBJECT") except RuntimeError: ...
def remove_punctuation(path_general,dir1): '''function that will remove any spaces in the target folder name input: path to general folder, name of images folder e.g 'images' ''' print('remove_punctuation') path=path_general+'/'+dir1 for filename in sorted(os.listdir(path)): if filename=...
The main task of the code is to check the number of image target folders in specified directories. If there are 30 or more, it processes FITS images through a series of steps (e.g., renaming, combining, filtering) and moves processed files to a "finished_images" folder. If fewer than 30 folders exist, it alerts the use...
def fold_check(path_general): '''function to check how many image target folders there are in the 'images' folder and run the image-processing functions if there are >30. function will move original fits images to the 'finished_images' folder after completion. input: path to general folder ''' p...
def get_init_state_front(self) -> QSet: tmp = self.non_dominated_sets(self.initial_state) tmp.shrink(self.policies) return tmp def gather_data(self): front = self.get_init_state_front() self.output_file.write(json.dumps([s.tolist() for s in front.set]) + '\n') found_poin...
This code runs an agent through multiple episodes in an environment, interacting with it by taking actions, updating rewards and data structures, and rendering if interactive. It optimizes by skipping episodes where initial conditions are already met, tracks rewards periodically, and terminates episodes based on done f...
def run(self): """ Core loop, runs the agent on the environment for a number of episode. """ episode = 0 while episode < self.num_episodes: done = False obs = self.env.reset() timestep = 0 self.initial_state = obs if sel...
def check_id_db(client): user = client.recv(1024).decode("utf-8") print(user,"user") passs = client.recv(1024).decode("utf-8") print(passs) if read(user, passs) is not None: print(read(user, passs),"read") return "frontPage",user return "a","" def check_user(client): if len(read(a = client....
The main task of the code is to handle a client connection in a chat or social network application. It authenticates users via login/create operations, manages user sessions, and processes client requests such as retrieving friends, finding users, sending notifications, and managing friend interactions (add/cancel/mess...
def handle_connection(client): print("asd") stop = False what = "not" login = "" while not stop: try: while what != "frontPage" and what!="": print("asdasd1") what = client.recv(1024).decode("utf-8") print(type(what), what) if what == "Login": ...
def parse_prefix(fd: BinaryIO, json_encodable: bool) -> dict[str, Any]: ret: dict[str, Any] = { 'magic': fd.read(5), 'version': byte(fd), 'size': le_uint4(fd), 'targets': byte(fd) } if ret['magic'] != b'DfuSe' or ret['version'] != 1: error('Invalid/unexpected constan...
The main task of the code is to parse a binary file into three structured components: 'prefix', 'images', and 'suffix'. It reads the prefix and suffix data, positions the file pointer to parse images based on the prefix's targets, and returns these parsed elements as a dictionary. The `json_encodable` parameter ensures...
def parse(fd: BinaryIO, json_encodable: bool = True) -> dict: prefix = parse_prefix(fd, json_encodable) suffix = parse_suffix(fd, json_encodable) fd.seek(prefix_len, 0) images = parse_images(fd, prefix['targets'], json_encodable) return { 'prefix': prefix, 'images': images, ...
def generate_output_folder(ic_path): random_ic_image = get_random_image(ic_path) image = cv2.imread(random_ic_image) new_image = image.copy() gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) binary = cv2.threshold(gray, 100, 255, cv2.THRESH_OTSU)[1] inverted_binary = ~binary contours = cv2.fin...
The code processes medical images by extracting brain slices from thresholded files, organizing them into folders, separating color and black regions, performing clustering, detecting boundaries, and managing directory structures, while handling exceptions to ensure clean execution.
def main(): try: path = os.getcwd() images_dir_path = path + "/" + 'Images' if os.path.exists(images_dir_path): shutil.rmtree(images_dir_path) ic_path = path + '/testPatient/test_Data/' generate_output_folder(ic_path) pth = path +'/output' generate...
def lost_message(self, message: Message, time: int): message.state = MessageState.LOST self.lost_messages_output.process_input(message, time) def message_processing_complete(self) -> bool: """Returns True if the currently processed message is complete. Return False if there are no messa...
This function processes an incoming message by checking server state (on/off), simulating message loss during server downtime or queue fullness, appending valid messages to the queue, and setting service duration. It returns True if the message is lost or successfully added, with debug logging enabled.
def process_input(self, message: Message, time: int) -> bool: # If the server is off, simulate message loss if self.state is OnOffServerState.OFF: loss_instance = np.random.uniform(0, 1) if loss_instance > self.loss_propability: self.lost_message(message, time) ...
def empty(self) -> bool: return len(self.messages) == 0 def message_processing_complete(self) -> bool: """Returns True if the currently processed message is complete. Return False if there are no messages to process """ if self.empty() or self.message_service_length is None: ...
This method processes completed messages from a queue when the server is active, outputs them, cleans up expired messages, increments effectuated work if active, and toggles server state between on/off using an exponential distribution for state flip intervals.
def tick(self, time: int, delta: int): processing_completed_messages = True # Process all completed messages from the queue while ( processing_completed_messages and self.state == OnOffServerState.ON and not self.empty() ): if self.message...
def wall_constraints(self): """ Author Jacob Adds wall constraints by ensuring that no blocks are assigned to walls """ for wall in self.walls: x_pos = wall[0] y_pos = wall[1] filled = [] pos = x_pos + y_pos * self.board_wid...
The code's main task is to solve a constraint programming problem by applying wall, target, and piece constraints, then using the CP-SAT solver to find a feasible or optimal solution within 90 seconds. If successful, it returns active variables (marked as 1) and additional content; otherwise, it returns the solver's st...
def get_solution(self): """ Performs the sequence of calls necessary to get a Solution returns solution if solving successful, otherwise return status """ self.wall_constraints() self.target_constraints() self.piece_constraints() solver = cp_model.CpSolve...
def calibrate_analytical(self): # !!! self.x_axis_nm is as input px-x-axis.... # ToDo: rename input array into px_array self.x_axis_nm[:] = self.calibration_parameter[0] * (self.x_axis_nm[:] + self.calibration_parameter[-1]) for counter, value in enumerate(self.x_axis_nm): # ...
The main task of the code is to process and visualize data by calibrating analytical parameters, converting wavelength arrays from nanometers to electron volts, and generating a plot of the results in electron volts. This workflow likely supports spectral analysis or energy-based data interpretation.
def main(self): self.calibrate_analytical() self.convert_array_nm_to_eV() self.plot_result_ev()
def separate_by_class(data): separated = dict() for i in range(len(data)): vector = data[i] class_value = vector[-1] if (class_value not in separated): separated[class_value] = list() separated[class_value].append(vector) return separated def stat_continuous(conti...
This code implements a Naive Bayes classifier. It calculates class probabilities from the training set, separates features into categorical and continuous types, computes statistics (mean, standard deviation) for continuous features, and predicts test set labels using these probabilities and feature distributions.
def algorithm(train_set, test_set): separated = separate_by_class(train_set) prob_by_class = dict() # P(class) cnt = 0 for label, data in separated.items(): prob_by_class[label] = len(data) cnt += len(data) for label in prob_by_class: prob_by_class[label] /= float(cnt) ...
def separate_by_class(data): separated = dict() for i in range(len(data)): vector = data[i] class_value = vector[-1] if (class_value not in separated): separated[class_value] = list() separated[class_value].append(vector) return separated def stat_continuous(conti...
The code implements a Naive Bayes classifier. It calculates class probabilities from the training set, separates features into categorical/continuous types, computes statistical parameters for continuous features, and predicts test set labels using these statistics and prior probabilities. The main task is to classify ...
def algorithm(train_set, test_set): separated = separate_by_class(train_set) prob_by_class = dict() cnt = 0 for label, data in separated.items(): prob_by_class[label] = len(data) cnt += len(data) for label in prob_by_class: prob_by_class[label] /= float(cnt) categorica...
def cross_validation_split(data, n_folds): dataset_split = list() dataset_copy = list(data) fold_size = int(len(data) / n_folds) for _ in range(n_folds): fold = list() while len(fold) < fold_size: index = randrange(len(dataset_copy)) fold.append(dataset_copy.pop(i...
The code performs k-fold cross-validation on a dataset. It splits the data into 'n_folds' subsets, iteratively uses one subset as the test set and the rest as training data, trains a model, predicts outcomes, calculates accuracy against actual values, and collects accuracy scores for each fold. The function returns a l...
def evaluate(data, n_folds): folds = cross_validation_split(data, n_folds) scores = [] for fold in folds: train_set = list(folds) train_set.remove(fold) train_set = sum(train_set, []) test_set = list() for row in fold: row_copy = list(row) test...
def user_throw(): """ Throws user's dices :return sum of 2 dices: """ user_dice1 = check_input() user_dice2 = check_input() user_result = randint(0, user_dice1) + randint(0, user_dice2) return user_result def computer_throw(): """ Throws computer's dices :return sum of 2 dic...
The code defines a turn-based game where a user and computer accumulate points by repeatedly adding values from their respective functions. The loop continues until either player reaches or exceeds 2001 points, after which the winner is determined based on higher points. The game tracks and displays scores, announcing ...
def game(): """The main body of the program""" points_user = 0 points_computer = 0 points_user += user_throw() points_computer += computer_throw() while points_user < 2001 and points_computer < 2001: print(f'User points: {points_user} | Computer points: {points_computer}') poin...
def failure_response(message, code = 400): return json.dumps({"error": message}), code def verify_session_token(request): """ helper function that verifies if a session token is valid and grants access to protected endpoints """ success, session_token = extract_token(request) if not success: ...
This function updates an item's description, found status, and bounty based on provided data, ensuring the requesting user is the item's owner via session token verification. It validates input completeness, updates the database, and returns a success response with the modified item data or error messages for invalid c...
def update_item(item_id): """ updates an item given item id; cannot edit user or location (protected endpoint) """ item = Item.query.filter_by(id = item_id).first() if item is None: return failure_response("Item does not exist!", 404) success, user = verify_session_token(request) ...
def infusion_time(self, dose): if dose < 1000: return 1 elif dose <1500: return 2 else: return 3 def change_in_concentration_after_dose(self, dose): ti = self.infusion_time(dose) delta_c = ((dose*(1-math.exp(-self.ke*ti)))/(ti*self.ke*self.vol...
The code generates time points and corresponding drug concentrations over a specified period, considering infusion intervals and dose effects. It calculates concentrations at each time step, adjusting for additive levels after each dose, and returns a dictionary mapping time points to concentrations for plotting.
def generate_plots_to_graph(self, dose, interval, hours_to_graph): time_hours = [] concentrations = [] for i in range(hours_to_graph): time_hours.append(i) sorted_hours = sorted(time_hours) counter = 0 final_hours = sorted_hours.copy() infusion...
def and_gate(self, input_a, input_b): """ And Gate: Output is True when both inputs are true a b output | 0 | 0 | 0 | | 0 | 1 | 0 | | 1 | 0 | 0 | | 1 | 1 | 1 | :param input_a: :param input_b: :return: """ if input_b...
The code implements an XOR gate by combining the outputs of an OR gate and a NAND gate using an AND gate, producing a result that is True only when exactly one of the inputs is True, adhering to the XOR truth table.
def xor_gate(self, input_a, input_b): """ Xor Gate: (Exclusive Or Gate) - Only True when a single input is True a b output | 0 | 0 | 0 | | 0 | 1 | 1 | | 1 | 0 | 1 | | 1 | 1 | 0 | :param input_a: :param input_b: :return: """ ...
def find_vandermonde(self): return np.vander(self.inputs) def invert_vandermonde(self): self.find_vandermonde() return np.linalg.inv(self.find_vandermonde()) def find_coefficients(self): self.invert_vandermonde() self.coeffs = np.matmul(self.invert_vandermonde(), self.outputs) ...
The code's main task is to generate a string representation of an object's coefficients by first computing the Vandermonde matrix, inverting it, determining the coefficients, and then returning them as a formatted string.
def __repr__(self): self.find_vandermonde() self.invert_vandermonde() self.find_coefficients() return f'{self.coeffs}'
def find_vandermonde(self): return np.vander(self.inputs) def invert_vandermonde(self): self.find_vandermonde() return np.linalg.inv(self.find_vandermonde()) def find_coefficients(self): self.invert_vandermonde() self.coeffs = np.matmul(self.invert_vandermonde...
The code's main task is to compute and return the polynomial coefficients by constructing a Vandermonde matrix, inverting it, and solving for coefficients, ultimately outputting them as a string representation of the object.
def __repr__(self): self.find_vandermonde() self.invert_vandermonde() self.find_coefficients() return f'{self.coeffs}'
def deduplicate_data(self, data: pd.DataFrame ) -> pd.DataFrame: deduped_data = data.drop_duplicates(subset=self.key_columns) return deduped_data def load_upsert(self, data: pd.DataFrame ) -> bool: """ Database upsert function for loading Domain API results. ...
The code's main task is to load deduplicated data into a database table using a mode-specific strategy: upsert, chunked upsert, incremental update, or full overwrite, logging the operation and returning a success status.
def load(self, data: pd.DataFrame ) -> bool: data = self.deduplicate_data(data) if (self.mode == "upsert"): logging.info(f"Performing conventional upsert into table {self.target_table}") success = self.load_upsert(data) elif (self.mode == "upsert_ch...
def _global_matrix(self, l: int, m: int, n: int): """This a 3D matrix Mijk(0 <= i <= l-1, 0 <= j <= m-1, 0<= k<= n-1). is used to store the material attributes of all the global background elements. It will store elements such as Mijk=1,2,3. Meaning that the grid element (i, j, k...
This code initializes a 3D concrete specimen grid, generates polyhedral aggregates with specified size ranges, and attempts to place them without overlaps (intrusions) by randomly translating aggregates up to 500 times. It uses probability-based aggregate sizing, sorts aggregates by surface area for packing efficiency,...
def __init__(self, L, W, H, dmin, dmax, number): # initialization of the global background grid # the global background grid of concrete specimen. # let's take unit in mm. # L (length) # W (width) # H (height) of the concrete specimen. self.L = L...
def _global_matrix(self, l: int, m: int, n: int): """This a 3D matrix Mijk(0 <= i <= l-1, 0 <= j <= m-1, 0<= k<= n-1). is used to store the material attributes of all the global background elements. It will store elements such as Mijk=1,2,3. Meaning that the grid element (i, j, k...
This code initializes a 3D mesh for aggregate placement, generates polyhedral aggregates with size-based probabilities, sorts them by size, and iteratively translates each aggregate to random positions while checking for spatial intrusions, ensuring non-overlapping placement through repeated translation attempts.
def __init__(self, L, W, H, dmin, dmax, number): self.L = L self.W = W self.H = H self.dmin = dmin self.dmax = dmax self.number = number # mesh size self.e = (1/5)*self.dmin # number of elements along x, y, z ...
def checking_castle(self, target_x, target_y): if (target_x, target_y) in [(0, 0), (7, 0), (0, 7), (7, 7)]: if self.selected_figure.symbol == 'k' and not self.kings_already_move[Constants.FIG_WHITE]: return True if self.selected_figure.symbol == 'K' and not self.kings_al...
This code moves a selected chess piece to a target position, adjusting coordinates for board orientation, handling castling, updating the board state, clearing the previous position, and performing post-move actions like pawn promotion, evaluation, and king movement tracking.
def move(self, target_x, target_y): # switch x, y if board is reserved if not self.white_on_top: target_x = 7 - target_x target_y = 7 - target_y if self.checking_castle(target_x, target_y): self.castle(target_x, target_y) else: old_x: int...
def show_parameters(self, state): vs.ShowItem(self.dialog, self.kWidgetID_imageGroup, state) vs.ShowItem(self.dialog, self.kWidgetID_withImageLabel, state) vs.ShowItem(self.dialog, self.kWidgetID_withImageSelector, state) vs.ShowItem(self.dialog, self.kWidgetID_withImage, state) ...
This callback function handles VectorWorks dialog events by updating settings based on user interactions. It initializes dialog fields, updates parameters from input changes, enables/disables UI elements conditionally, validates import settings, and controls the import button's state. It manages file selection, image/f...
def dialog_handler_cb(self, item, data) -> None: """ Handles dialog events This is a call-back function invoked by VectorWorks whenever there is a change in the state od the dialog box. Changes in the dialog fields will be reflected in the `self.settings` object. :param item: The ID of...
def cur_op(self): op_str = self.cur_op_str() return int(op_str[-2:]) def add(self): arg1 = self.arg_get(1) arg2 = self.arg_get(2) self.arg_set(3, arg1 + arg2) self.cur += 4 def multiply(self): arg1 = self.arg_get(1) arg2 = self.arg_get(2) self.arg_...
The code processes a sequence of operations (op) in a loop, executing methods like add, multiply, input/output, and conditional jumps until encountering op 99 (halt), then returning collected outputs.
def process(self, inputs): outputs = [] while True: op = self.cur_op() if op == 1: self.add() elif op == 2: self.multiply() elif op == 3: self.input(inputs) elif op == 4: self.outp...
def bayesian_search(self, embeddings, space, max_evals=100): trials = Trials() objective = partial(self.search_objective, embeddings=embeddings) logger.info( f'Finding optimal clustering configuration with {max_evals} maximum evaluations') best_trial = fmin( objec...
The code processes text data by generating embeddings, clustering them using Bayesian optimization or a fixed configuration, and saving results including cluster summaries, run metadata, and embeddings to specified directories. It handles caching, configuration tuning, and output organization for analysis.
def run(self, output, run_id, message_id_tag='message_id'): output_root = output or os.getcwd() if os.path.isdir(os.path.join(output_root, 'data', run_id)): raise FileExistsError(os.path.isdir( os.path.join(output_root, 'data', run_id))) # self._df = self._data_loade...
def _validateJson(self, json_map): self._validateRooms(json_map) def _createGraph(self, map): for room in map['rooms']: neighbours = self._getRoomNeighbours(room) self.graph[room['id']] = neighbours object_list = self._getRoomObjects(room) self.objects[ro...
The main task of the code is to load a JSON file, validate its structure, construct a graph from the data, and ensure the graph's validity. It raises an InvalidMaze exception if the JSON is malformed.
def fromFile(self, json_filename): try: with open(json_filename) as json_file: json_map = json.loads(json_file.read()) self._validateJson(json_map) self._createGraph(json_map) self._validateGraph() except json.decoder.JSONDecode...
def cat_bed(files, control, subdir, warn): """ Concatenate compressed or uncompressed files into subsampled.0.bed. :param files: Files to concatenate. :type files: str :param control: Control files to concatenate. :type control: str or None :param subdir: Path to the subsample directory. ...
The code executes a chromTools pipeline to process genomic data, concatenating input files, calculating total reads, subsampling using multiprocessing, binarizing data, and generating benchmarks and visualizations for analysis.
def run(options): """ The function pipeline for chromTools complete. :param options: Command line options. :type options: Namespace object. """ start_time, options.start_time = time.time(), time.time() timestr = time.strftime("%Y%m%d-%H%M%S") benchmark(options.outdir, f"N={len(options....
def Darknet(name=None): x = inputs = Input([None, None, 3]) x = DarknetConv(x, 32, 3) x = DarknetBlock(x, 64, 1) x = DarknetBlock(x, 128, 2) x = x_36 = DarknetBlock(x, 256, 8) x = x_61 = DarknetBlock(x, 512, 8) x = DarknetBlock(x, 1024, 4) return tf.keras.Model(inputs, (x_36, x_61, x), n...
The code defines a YOLOv3 object detection model. It processes input images through a Darknet backbone, generating three feature maps. These are refined via YoloConv layers, producing box predictions. Lambda layers apply YOLO-specific box generation and non-max suppression (NMS) to output final bounding boxes. The mode...
def YoloV3(size=None, channels=3, anchors=yolo_anchors, masks=yolo_anchor_masks, classes=80): x = inputs = Input([size, size, channels], name='input') x_36, x_61, x = Darknet(name='yolo_darknet')(x) x = YoloConv(512, name='yolo_conv_0')(x) output_0 = YoloOutput(512, len(masks[0]), classes,...
def _convert_proposal_field_report_to_pandas_dataframe(self): """In the API response for the Curriculog Proposal Field Report, the response nests the fields for a proposal under a list called 'fields'. This function loops over those the api_responses and the nested fields to create a pandas dataframe with a col...
The main task of the code is to analyze self.api_responses by converting proposal data into a Pandas DataFrame, merging additional API responses (user and proposal lists), transforming college names, and exporting the consolidated data as a TSV file named 'concatenated_dataframe.tsv'. The result is a unified DataFrame ...
def concatenate_proposals (self): """Analyzes self.api_responses to form a single Pandas dataframe. Stores the dataframe as concatenated_dataframe.""" ##Create and store the primary dataframe 'concatenated_proposals' self._convert_proposal_field_report_to_pandas_dataframe() ##Merge the ...
def get_column_names_needing_comments(self): """Loops over a list of fields to determine which should have a comment. Excel columns which should have comments are stored as column_names_needing_comments.""" ### Map over fields, returning field_name column_names = [] for field in self.fi...
The code creates an Excel workbook named 'output_TIMESTAMP.xlsx' containing a main sheet with processed data and additional sheets for specified dataframes. It processes rows to set comments, embedded URLs, and formats impact cells, then deletes unnecessary columns. Additional sheets are added, and the workbook is save...
def create_workbook(self): """Creates an output Excel workbook titled 'output_TIMESTAMP'.xlsx TIMESTAMP is the current timestamp when the output Excel workbook is being generated. The first sheet titled "Main" is the concatenated_rows. Additional sheets correspond to additional_rows , with the sheets having na...