dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def init_game(verbose): current_deck = build_deck() computer_hand = [] player_hand = [] # Intial draw - 2 cards for player draw_results = draw_cards(2, current_deck, player_hand, 'Player', verbose) player_hand = draw_results['hand'] current_deck = draw_results['deck'] # Intial draw - 2...
The code simulates a turn-based card game where the player and computer (dealer) alternately draw cards. The game checks for win/loss conditions (e.g., busting or reaching 21) after each move. The player chooses to "hit" or "stand," and the dealer automatically draws cards. The loop continues until the game ends, displ...
def game(): # Init stuff game_over = False game_rounds = 0 initial_game = init_game(True) current_deck = initial_game['deck'] computer_hand = initial_game['computer_hand'] player_hand = initial_game['player_hand'] game_over_results = is_game_over(computer_hand, player_hand, True) ga...
def parse_data(vin): headers = get_auth() DECODE_URL = 'http://api.carmd.com/v3.0/decode?vin=' IMAGE_URL = 'http://api.carmd.com/v3.0/image?vin=' decoder = requests.get(DECODE_URL + vin, headers=headers).json() message = decoder['message'] data = decoder['data'] if data is not None and mess...
The code validates a 17-character VIN input, retrieves vehicle data using a parser, and stores the results in a database. It creates a dataframe, saves query data to a SQL file, loads the dataset, and visualizes car data by year. If the VIN is invalid or data retrieval fails, it alerts the user. The core tasks involve ...
def main(): vin = '' while(len(vin) != 17): vin = input("Enter a Vehicle Identification Number: ") if(len(vin) != 17): print('Please enter a valid VIN') # print vehicle info to user decoder = parse_data(vin) database_name = 'vindecoder' filename = 'vin-queries.sql' ...
def preprocess_text(text,stop_words): if pd.isna(text)==True: return '' # Tokenize sentence text = re.sub(r'[-_/]',' ',text) tokens = word_tokenize(text) # Remove stopwords filtered_tokens = [token for token in tokens if token.lower() not in stop_words] # Lowercasing ...
This function processes a query phrase to retrieve and rank relevant items using TF-IDF. It handles quoted phrases by splitting them into words, performing single-word or phrase searches on inverted indices, and combining results. It then applies TF-IDF ranking via `rank_retrieve`, filters common elements from quoted p...
def phrase_tfidf(phrase,info_inverted_index,review_inverted_index,info_length,review_length,stop_words): # Regular expression pattern to match a phrase search query pattern = r'"[^"]+"' if bool(re.match(pattern,phrase))==True: # Find all matches of the pattern in the query string matches = r...
def preprocess_text(text,stop_words): if pd.isna(text)==True: return '' # Tokenize sentence text = re.sub(r'[-_/]',' ',text) tokens = word_tokenize(text) # Remove stopwords filtered_tokens = [token for token in tokens if token.lower() not in stop_words] # Lowercasing ...
This function processes a search query using boolean operators and proximity phrases, combining TF-IDF and proximity search results from inverted indexes. It handles logical operators (AND, OR, NOT), resolves proximity phrases (#distance{term1,term2}), and evaluates the query against universal sets to return relevant d...
def allsearch(query,universal_set,info_inverted_index,review_inverted_index,info_length,review_length,stop_words): boolean_word = ['AND NOT', 'OR NOT','AND','OR','NOT'] query = query.replace('NOT NOT','') query = query.replace('(','') query = query.replace(')','') split_query = re.split(r'\b(AND NOT...
def is_connected(self): """ Determine if a Proximity device is conntected to the system.. :return: True if the device is connected, otherwise False. :rtype: bool """ return qwiic_i2c.isDeviceConnected(self.address) def get_id(self): """ R...
The main task of the code is to initialize the Proximity module by checking I2C connection, verifying the sensor ID, and configuring parameters like LED current, IR duty cycle, integration time, and resolution. It enables smart persistence, activates proximity and ambient light sensing, and returns True on successful i...
def begin(self): """ Initialize the operation of the Proximity module :return: Returns true of the initializtion was successful, otherwise False. :rtype: bool """ # //Check connection if not self.is_connected(): return False # I2C comm f...
def setup_damage_types(): """Sets up radio-buttons for the different damage types""" for damage_type, damage_type_full_name in damage_types.items(): _ = document["damage_type"] <= html.INPUT( type="radio", id=f"damage_type_{damage_type}", name="damage_type", ...
The main task of the code is to initialize a UI-based application for managing armor and damage calculations. It sets up data structures for damage types, armor selections, body parts, and ignored armor types, binds click and input events to update dynamic elements like damage values, sliders, and mirrored selections, ...
def setup(): print("In setup") setup_damage_types() setup_armor_selection() setup_body_parts() setup_ignored_armor_types() restore_from_local_storage() for part in [ "body_part", "armor_selection", "damage_type", "ignored_armor_types", ]: document[...
def initialize(self): """Goes to math url for selected grade""" url = self.create_url() self.driver.get(url) def get_links(self): """Returns list of links for worksheets""" category_links = self.get_category_links() topic_links = self.get_topic_links(category_links) ...
The code's main task is to collect web links (WS links) and save associated files. It initializes resources, retrieves links via `get_links()`, saves the files using `save_files()`, and finally quits the browser driver to release resources. The method automates downloading files from specified web sources by handling i...
def download(self): """Collects WS links and saves files""" self.initialize() links = self.get_links() self.save_files(links) self.driver.quit()
def is_json(myjson): """ Return True if source string is valid json """ jsontype = 0 try: json_object = json.loads(myjson) del json_object jsontype = 1 # Return Type of JSON except: pass try: json_object = json.loads(myjson.decode("utf-8")) del json_o...
The main task of the code is to receive UDP packets, decode JSON payloads, process weather event data based on packet type, handle errors, and return structured results including event type, serial number, and JSON data with error handling. It processes packets like 'obs_st', 'device_status', and others, handling excep...
def get_event(self): wf_type = False wf_serial = None wf_json = { "error": "Failure in Receiving/Decoding Packet", "value": "" } data = "{}".encode() try: data, addr = self.tempest.recvfrom(self.buffersize) if is_json(data.d...
def add(total): global player_total x = random.choice(l) player.append(x) if (player_total > 21 and 11 in player): i = player.index(11) player[i] = 1 player_total -= 10 return x print("your cards are : ", player, "your total is :",...
The function allows a player to choose to add a card or pass in a game. If adding a card causes the total to exceed 21, it converts an Ace (11) to 1 to adjust the score. If the adjusted total still exceeds 21, the game ends with a loss message. Otherwise, the loop continues for further choices. Passing ends the turn, l...
def choose(): choice = input("ADD CARD(y) OR PASS(n) :") if (choice == 'y'): global player_total player_total += add(player_total) if (player_total > 21 and 11 in player): i = player.index(11) player[i] = 1 player_total...
def createSymmetry(id, minst, initialRotation = None, overFlow = None, padding = None, finalRotation = None, resizingPercent = None): # Getting the image and label result,label = getImageArray(id,minst) # Initial rotation if initialRotation is None: initialRotation = random.randrange(360) ...
This function generates an image containing a symmetric digit (from MNIST) and randomly placed asymmetric digits, ensuring they fit within a specified size. It uses packing algorithms to arrange elements without overlap, adjusts symmetry parameters based on positioning, and returns the final image along with updated sy...
def getRandomDigitsWithSymmetry(id, mnist, size, initialRotation = None, overFlow = None, padding = None, finalRotation = None, resizingPercent = None): # Elements for while loop possible = True squareSizes = [] elements = [] # Adding symmetry and placing it in the first place of the list symme...
def getRandomDigitsWithSymmetry(id, mnist, size, initialRotation = None, overFlow = None, padding = None, finalRotation = None, resizingPercent = None): # Elements for while loop possible = True squareSizes = [] elements = [] # Adding symmetry and placing it in the first place of the list symme...
The function generates an image combining a digit with symmetry and a background (smooth noise or wood texture), returning the image and metadata dictionaries. It handles digit generation, background creation, and merges them, allowing customizable parameters for symmetry, background type, and visual effects.
def getLocalSymmetry(shape, mnist, idx = None, initialRotation = None, overFlow = None, padding = None, finalRotation = None, resizingPercent = None, backgroundType = None, darknessBackground = None, xPeriod = None, yPeriod = None, turbPower = None, turbSize = None, offsetX = N...
def title_parse(self): """ Parses through the titles for each respective page and populates the ID as its key and name as its value Also populates an internal titles dictionary that will be used in Page Rank to map the title of a document to its respective ID :param self ...
The code parses an XML document, initializes dictionaries to store titles, words, links, and PageRank data, and prepares for text analysis and ranking. It sets up structures for title extraction, word frequency tracking, internal link mapping, and PageRank computation, enabling tasks like document analysis or search al...
def __init__(self, xml: str): self.tree = et.parse(xml) self.root = self.tree.getroot() # titles_dict self.title_dict = {} # words_dict self.words_dict = {} # links_dict (maps all the links that a given document has) self.links_dict = {} # interna...
def is_train_test_file_exists(self) -> bool: """ It checks if the training and testing files are present in the specified path :return: The return value is a boolean value. """ try: logging.info( 'Checking if Training And Testing File is Available!!!!?...
This method validates data by checking the existence of train/test files, verifying dataset schema, and detecting data drift. It returns a DataValidationArtifact with validation results if successful, or logs/raises exceptions on errors.
def initiate_data_validation(self) -> DataValidationArtifact: """ It checks if the train and test files exist, validates the schema of the dataset, and checks if there is any data drift :return: DataValidationArtifact """ try: self.is_train_test_file_exists() ...
def setupWindow(self): self.rootWindow = tkinter.Tk() self.rootWindow.title('Admin Creator GUI') self.rootWindow.geometry('350x530') self.rootWindow.configure(background=Constants().windowBackgroundColor) self.rootWindow.resizable(False, False) def setupHeader(self): self...
This code initializes a GUI window for an admin creator, setting up form fields (first name, last name, email, password) with default values, linking to a controller, and launching the main event loop to display the interface. It prepares the window structure, binds variables, and ensures the GUI remains active for use...
def __init__(self, controller : AdminCreatorWindowController): self.controller = controller self.setupWindow() self.rootWindow.update() self.firstNameTextVar = tkinter.StringVar() self.lastNameTextVar = tkinter.StringVar() self.lastNameTextVar.set('Admin') self....
def __get_current_deal_orders_by_symbol(self, symbol: str) -> List[Order]: orders = self.binance_client.get_all_orders_by_symbol(symbol) filtered_orders = [ord for ord in orders if (ord.is_new_or_filled_order() and ord.is_buy_order())] sorted_filtered_orders = self.__sort_orders_by_timestamp(fil...
The main task of the code is to reevaluate the current deal orders for a specific trading symbol, update the safety order value, and determine if rebalancing of quote assets is required. It logs orders, checks safety order status, calculates next order values, updates asset data, and sends Telegram notifications for re...
def __reevaluate_symbol(self, symbol, order_event: Order = None): current_deal_orders = self.__get_current_deal_orders_by_symbol(symbol) if order_event is not None: current_deal_orders = self.__upsert_order_to_orders(order_event, current_deal_orders) self.__log_orders(current_deal_or...
def display_player_names(): win = pygame.display.set_mode((1000, 668)) win.blit(background, (0, 0)) win.blit(player_name, (450, 630)) win.blit(player_teammate, (400, 20)) win.blit(computer, (10, 300)) win.blit(comp_team_mate, (970, 220)) def card_assignment_for_players(x_limit, no_comp, no_compt...
The function initializes a game by checking if neither the player nor the computer has selected a trump card. If true, it displays player names, assigns cards using specified parameters, and determines the trumps. This sets up the game state for subsequent actions.
def initialize_game(): if player_trump_selected is False and comp_trump_selected is False: display_player_names() card_assignment_for_players(920, 13, 13, 13, 390, 390, 590) determine_trumps()
def have_suits(hand, s): for i in hand: if i.suit == s: return True return False def check_least_high_card(c, hand): n = 0 for s in suits: for m in range(13): if c.suit == s and c.value == values[n]: for k in range(13): for i in...
The function determines the computer's teammate's card play in a round-based game, evaluating suits, trump status, and hand availability to select a valid card. It checks conditions on played cards, uses comparison and selection logic, and triggers `comp_tm_set_play` with calculated parameters for positioning and card ...
def comp_tm_play(rnd, ply_tm_card_pos): x_limit = 920 - (75 * rnd) cards = 13 - rnd card_pos = 390 - (20 * rnd) rnd -= 1 c_pos = len(comp_played_hands) p_pos = len(player_played_hands) ct_pos = len(comp_teammate_played_hands) pt_pos = len(player_teammate_played_hands) if ct_pos == rn...
def have_suits(hand, s): for i in hand: if i.suit == s: return True return False def check_least_high_card(c, hand): n = 0 for s in suits: for m in range(13): if c.suit == s and c.value == values[n]: for k in range(13): for i in...
The function determines the appropriate card for the player's teammate to play in a card game round, based on current game state (played cards, suits, trumps). It evaluates conditions to select the lowest/highest valid card from the teammate's hand or trumps, adjusting position/parameters via multiple nested conditiona...
def player_tm_play(rnd, ply_tm_card_pos): x_limit = 920 - (75 * rnd) cards = 13 - rnd card_pos = 390 - (20 * rnd) rnd -= 1 c_pos = len(comp_played_hands) p_pos = len(player_played_hands) ct_pos = len(comp_teammate_played_hands) pt_pos = len(player_teammate_played_hands) if pt_pos == ...
def clear_all_decks(): player_deck_clear() comp_deck_clear() comp_tm_deck_clear() player_tm_deck_clear() play_area_clear() def comp_set_play(played_trumps, card, a, b, c, d, e, f, g): global comp_round_done if played_trumps is False: match_cards(card, 430, 300) comp_played_ha...
The function `comp_play` determines the computer's card play in a turn-based game, selecting a card from its hand based on the current round, played cards, and game rules. It prioritizes following suit, uses trumps if necessary, and positions the card visually. The logic checks teammates' and opponents' played cards to...
def comp_play(first_play, rnd, ply_tm_card_pos): global comp_round_done x_limit = 920 - (75 * rnd) cards = 13 - rnd card_pos = 390 - (20 * rnd) rnd -= 1 c_pos = len(comp_played_hands) p_pos = len(player_played_hands) ct_pos = len(comp_teammate_played_hands) pt_pos = len(player_teamma...
def comp_play(first_play, rnd, ply_tm_card_pos): global comp_round_done x_limit = 920 - (75 * rnd) cards = 13 - rnd card_pos = 390 - (20 * rnd) rnd -= 1 c_pos = len(comp_played_hands) p_pos = len(player_played_hands) ct_pos = len(comp_teammate_played_hands) pt_pos = len(player_teamma...
The code manages a game round by handling player and computer turns, updating positions, checking for round completion, and determining the winner based on specific conditions. It adjusts game parameters per round, triggers actions like card plays, and updates the game state, ensuring proper flow until all rounds are c...
def play_round(rnd): global round_status, winner x_limit = 920 - (75 * rnd) turn = 14 - rnd c1 = 14 - rnd c2 = 14 - rnd c3 = 14 - rnd c1_pos = 410 - (20 * rnd) c2_pos = 410 - (20 * rnd) c3_pos = 610 - (20 * rnd) if comp_trump_selected and comp_round_done is False and winner is No...
def trump_list(): global trump_list_chosen if player_trump_selected or comp_trump_selected: for i in computer_hand: if i.suit == trump: comp_trumps.append(i) computer_hand.remove(i) for j in computer_teammate_hand: if j.suit == trump: ...
The function `start_play()` sequentially initiates and manages 13 rounds of a game. It checks if the trump list is set, then progresses through each round (1–13), ensuring each starts only after the prior round is completed. Once all rounds are finished, it clears the play area and displays the winner screen.
def start_play(): global all_rounds_done if trump_list_chosen is False: trump_list() if round_status['round1'] is False: play_round(1) start_new_round() for i in range(2, 13): if round_status['round' + str(i)] is False and round_status['round' + str(i - 1)]: p...
def display_analysis_of_nontrivial_mapping(self, s): sys.stdout.write(s) def levenshtein(s1, s2): ''' Calculates the Levenshtein distance between two strings. This implementation is from: http://en.wikibooks.org/wiki/Algorithm_implementation/Strings/Levenshtein_distance#Python released u...
This function analyzes mappings between original and normalized taxonomic names. It checks for exact matches, case-insensitive matches, synonym matches, and potential typos using Levenshtein distance. If no match is found, it queries user input and logs classifications (SYNONYM, TYPO, etc.) to files for diagnosis. The ...
def analyze_mapping(self, original, normalized, ott_id): if normalized == original: self.norm_logger.num_exact_matches += 1 return if normalized.lower() == original.lower(): self.norm_logger.num_case_i_matches += 1 return name_list = self.taxonomy...
def make_key(): determinant = 0 C = None while True: cipher = input("Input 4 letter cipher: ") C = stringmatrix(cipher) determinant = C[0][0] * C[1][1] - C[0][1] * C[1][0] determinant = determinant % 26 inverse_element = inverse(determinant) if inverse_element...
The code decrypts a matrix-based ciphertext using a Hill cipher by computing the inverse of the encryption key matrix, applying modular arithmetic, and converting numerical results back to characters. It processes pairs of encrypted values, applies the inverse matrix transformation, and trims trailing "0" characters to...
def decryption(encryptionmatrix): C = make_key() determinant = C[0][0] * C[1][1] - C[0][1] * C[1][0] determinant = determinant % 26 multiplicative_inverse = inverse(determinant) C_inverse = C C_inverse[0][0], C_inverse[1][1] = C_inverse[1, 1], C_inverse[0, 0] C[0][1] *= -1 C[1][0] *= -1 ...
def org_valid(org_data): if type(org_data)==dict: if 'name' in org_data: pass else: return FieldError({'organisation "name"'}) if 'address' in org_data: result = adr_valid('organisation',org_data['address']) print(result) return res...
This function validates the structure of the input data `rec_data`, ensuring the presence of a "person" dictionary with required fields (`firstName`, `lastName`, `email`). It also checks for optional "organisation" and "address" components, returning validation results or specific error messages for missing fields, typ...
def validation(rec_data): if "person" in rec_data: if type(rec_data["person"])==dict: if rec_data["person"].keys() >= {"firstName","lastName","email"}: if "organisation" in rec_data: result=org_valid(rec_data["organisation"]) if type(result...
def _get_dependencies(smth): if isinstance(smth, type): return inspect.getfullargspec(smth.__init__).args[1:] elif inspect.isfunction(smth): return inspect.getfullargspec(smth).args def _create_singleton(self, smth, name): if isinstance(smth, type): self._sing...
This method initializes an object by injecting dependencies from a source. It selects a default name if none is provided, skips if the object already exists, retrieves the source, checks for validity, recursively initializes dependencies, and creates a singleton instance using the source and name.
def _init(self, name=None): if name is None: name = list(self._sources.keys())[0] if name in self._objects: return source = self._sources.get(name) if source is None: raise PynjectorContextException(f"Couldn't inject `{name}`: no source for init") ...
def _init_svg(self):#only called in init self.svg_bytes = bytearray(ET.tostring(self.tree.getroot()).decode(), encoding='utf-8') self.load(self.svg_bytes) self.renderer().setAspectRatioMode(Qt.KeepAspectRatio) self.show() def _get_ids_from_svg(self): self.ids = [each.attrib['id']...
The main task of the code is to initialize SVG elements, extract IDs, configure hover styles, set initial transformations, reload SVG data, store initial styles in `style_box`, and initialize a list to track clicked shapes. This prepares the SVG for rendering and interaction handling.
def _init_actions(self): self._init_svg() self._get_ids_from_svg() self._set_style_model_when_hovered() self._set_init_transform() self.reload_svg() self.style_box = self._get_init_styles() self.last_clicked_shapes_id= []
def _get_element_with_id(self, id): eles = [each for each in self.tree.getroot().iter("*") if 'id' in each.attrib and each.attrib['id']==id] if len(eles)!=0: return eles[0] else: return None def _get_updated_style_attrib(self, style_str, modifier): #style_str is ;...
This function updates an XML element's attributes based on a provided dictionary. It locates the element using a hierarchical shape ID, applies attribute-value pairs from the dictionary, with special handling for 'style' (via a helper method) and 'text' (direct text content update). If the element exists, modifications...
def update_xml_tree(self, shape_id, modifier_dict = {}): #shape_id should be a string segments seperated by / representing the #modifier_dict hold the attribute as keys and the updated attribute values as the values #note the spetial attribute of 'text' means modifying the text of the node, ...
def calculate_sum(a): result = 0 for x in a: result = result + x return result def calculate_mean(a): num_elements = len(a) if(num_elements > 0): return calculate_sum(a)/num_elements def calculate_variance(a): #sample variance mean = calculate_mean(a) num_elements = len(a) ...
The code processes user input for x and y values, calculates statistical measures (sum, mean, variance, standard deviation), formats results, and renders them in a table on a web page. It validates numeric inputs, stores data in lists, computes statistics if at least two data points exist, and passes formatted values t...
def index(): sum_of_x = 0 sum_of_y = 0 mean_of_x = 0 mean_of_y = 0 variance_of_x = 0 variance_of_y = 0 standard_deviation_of_x = 0 stardard_deviation_of_y = 0 num_x_data = 0 num_y_data = 0 table_values = [] if(request.method == 'POST'): x_received = request.form['...
def generateMaze(self, current: node.Node): # getting neighbours current.changeState(2) self._freePositions.append(current.getCoordinates()) neighbours = self.getNeighbours(current) random.shuffle(neighbours) for neighbor in neighbours: if isinstance(neighbor....
This code initializes a maze structure with specified dimensions, ghost count, and dot distribution. It generates a maze, breaks walls, spawns dots, and extends the maze layout. The class manages game elements like walls, dots, ghosts, and pacmans, setting up a simulation environment with configurable parameters for ma...
def __init__(self, m: int = 35, n: int = 35, ghostsAmount = 0, numberOfDots: int = 1000000000000, numberOfBroken = 20, setSeed: bool = False, seed: int = 100): if setSeed: random.seed(seed) self.m = m self.n = n self.trueM = m self.trueN = n * 2 + 1 self.ghost...
def get_csv_delimeter(self): return self.csv_delimeter def get_export_rows(self, queryset): exporter = self.get_exporter(queryset) yield exporter.row_labels yield from exporter.rows def get_export_filename(self, queryset): return self.export_file_name
This code generates a CSV file from a queryset by streaming rows, sets the appropriate content type and filename for download, and returns an HTTP response for the user to download the CSV data.
def download_csv(self, queryset): pseudo_buffer = Echo() writer = csv.writer(pseudo_buffer, delimiter=self.get_csv_delimeter(), dialect='excel') response = StreamingHttpResponse((writer.writerow(row) for row in self.get_export_rows(queryset)), content_typ...
def get_download_format(self, *args): download_format = self.request.GET.get('export') if download_format in ['csv', 'xlsx', 'pdf', 'docx','json']: return download_format return None def get_export_objects(self): return [] def get_export_object(self): return {} def do...
The main task of the code is to export objects in specified formats (CSV, JSON, XLSX, PDF, DOCX) based on the action ('list' or 'retrieve') and download format. It retrieves the appropriate objects, selects the export format, and returns the corresponding downloaded file. If no format is specified, it returns None.
def export_objects(self): download_format = self.get_download_format() if download_format: if self.action == 'list': objects = self.get_export_objects() elif self.action == 'retrieve': objects = [self.get_export_object()] else: ...
def Str_List(amount): """Returns the string format, a list containing the digits, and the length of the number""" num_str = ''.join(str(amount).split(',')) num_list = [] [num_list.append(int(i)) for i in num_str] length = len(num_list) return num_str, num_list, length def hundreds(amount): ...
This function converts numbers into their English word representation, handling 4- and 5-digit values by splitting them into thousands and hundreds components. It uses helper functions to process each part, appending "Thousand" when needed, and returns formatted strings like "X Thousand Y" or "X Thousand" based on non-...
def Thousand(amount): """Converts four and five digit numbeRs""" num_str, num_list, length = Str_List(amount) if amount == 0: return if length <= 3: return hundreds(amount) if length == 4: if hundreds(int(''.join(num_str[-3:]))): return ( ' '.join(...
def Str_List(amount): """Returns the string format, a list containing the digits, and the length of the number""" num_str = ''.join(str(amount).split(',')) num_list = [] [num_list.append(int(i)) for i in num_str] length = len(num_list) return num_str, num_list, length def Thousand(amount): ...
This function converts a six-digit number into its word representation using the Indian numbering system, handling values in "Lakh" (100,000) and "Thousand" (1,000) units. It splits the number into parts, recursively processes smaller units, and combines them with appropriate terms like 'Lakh' and 'Thousand' for proper...
def Lakh(amount): """Converts six digit numbeRs""" num_str, num_list, length = Str_List(amount) if amount == 0: return if length <= 5: return Thousand(amount) if Thousand(int(''.join(num_str[-5:]))): return ( ' '.join(( single_double(num_list[0]), 'Lakh', ...
def info(msg=""): print(" %s" % msg) def zip_ignored_file(fname): for i in zip_ignored: if fname.find(i) != -1: return True def copy_sols(source_filename, source_abs_filename, dest_filename): if FileKinds.is_supported_ext(source_filename): info("Stripping jupman tags from %...
The main task of the code is to recursively copy files from a source directory to a destination directory, maintaining folder structure. It handles three file types: exercises (copied directly), tests (with '_solution' replaced by '_exercise'), and solutions (conditionally copied based on the flag). It creates necessar...
def copy_code(source_dir, dest_dir, copy_test=True, copy_solutions=False): info(" Copying exercises %s \n from %s \n to %s" % ('and solutions' if copy_solutions else '', source_dir, dest_dir)) # creating folders for dirpath, dirnames, filenames in os.walk(source_dir): struct...
def fatal(msg, ex=None): """ Prints error and exits (halts program execution immediatly) """ if ex == None: exMsg = "" else: exMsg = " \n " + repr(ex) info("\n\n FATAL ERROR! %s%s\n\n" % (msg,exMsg)) exit(1) def info(msg=""): print(" %s" % msg) def delete_tree(path, path...
The code zips contents of a specified folder into an output directory, cleaning and copying files, then archives them with given prefixes/suffixes while excluding certain paths using patterns.
def zip_folders(folder, prefix='', suffix=''): global exercise_common_files source_folders = glob.glob(folder + "/*/") if folder.startswith('..'): fatal("BAD FOLDER TO ZIP ! IT STARTS WITH '..'") if len(folder.strip()) == 0: fatal("BAD FOLDER TO ZIP ! BLANK STRING") build_jupm...
def getSlopeIntervals(self, step): maxSlope = self.getBiggestSlope() range_ = self.getRange() return list(np.arange(maxSlope - range_, maxSlope + range_, step)) def getInterceptIntervals(self, step): multCoefficient = 10 lowEndIntercept = -multCoefficient*(max(self.data.iloc[:...
This code performs manual linear regression by iterating through possible slope and intercept values in specified ranges, calculating the total mean squared error (MSE) for each combination, and selecting the parameters that yield the lowest MSE. It updates the model's slope, intercept, and minimum error accordingly.
def manualRegression(self, step): lowestMSE = float("inf") optimalSlope = 0 optimalIntercept = 0 slopeRange = self.getSlopeIntervals(step) interceptRange = self.getInterceptIntervals(step) for m in slopeRange: for b in interceptRange: ...
def remove_weird_parts(parts): """ Removes parts from the given list that are not present in the part_data. Replaces certain old part IDs with their corresponding new part IDs. Returns the updated list of parts and any error messages encountered. """ # Set to store unknown part IDs unknown_p...
This function calculates a ship's center of mass, center of thrust, and speed across eight directions using input data. It processes ship parts, removes anomalies, computes physics properties, generates an output image, and outputs results including error messages and directional mappings.
def com(input_filename, output_filename,args): """ Calculate the center of mass, center of thrust, and speed of a ship. Args: input_filename (str): The filename of the ship data. output_filename (str): The filename of the output image. args (dict, optional): Additional arguments. De...
def extract_imports(self, node: ast.Module) -> List[ImportSignature]: imports = [] for item in node.body: if isinstance(item, (ast.Import, ast.ImportFrom)): if isinstance(item, ast.Import): for alias in item.names: imports.append(Im...
The code extracts import statements, functions, and classes from provided Python code using AST parsing. It identifies dependencies by combining imported names and defined names, filtering out standard library modules. The result is a structured `ModuleSignature` containing imports, function details, and class definiti...
def extract_code_info(self, code: str) -> ModuleSignature: tree = ast.parse(code) imports = self.extract_imports(tree) import_names = {imp.name for imp in imports} | {spec.name for imp in imports for spec in imp.specified} functions = [ self.extract_function_info(item) ...
def analyze_file(self) -> ModuleSignature: with open(self.file_path, "r", encoding="utf-8") as file: code = file.read() return self.extract_code_info(code) def extract_code_info(self, code: str) -> ModuleSignature: tree = ast.parse(code) imports = self.extract_imports(tree) ...
This code initializes an object by analyzing either a file path or provided code to extract a signature, script name, and module name. It sets attributes based on input: if a file path is given, it analyzes the file; if code is provided, it extracts info from the code. The object stores these details for further proces...
def __init__(self, file_path: str | None, code: str | None = None): self.file_path = file_path if file_path is not None: self.signature = self.analyze_file() elif code is not None: self.signature = self.extract_code_info(code) self.name = self.extract_script_name(...
def _start_ftps_connection(self): self._ftp = ftps = ftplib.FTP_TLS(host=self._hostname, user=self._username, passwd=self._password) self._make_nested_dir(self._path) self._ftp.cwd(self._path) self._logger.debug("Initialized FTPS connection") ...
The code uploads files from a queue to an FTP server, logging progress and errors. It continuously retrieves files, uploads them, optionally deletes local copies, and handles termination by checking for a termination symbol. If an error occurs, it logs details and requeues the file for retry.
def upload_files(self): self._logger.info("Worker started") self._start_ftps_connection() while True: item = self._upload_queue.get() if item == self._termination_symbol: if self._upload_queue.empty(): return else: ...
def visualise(brd): global count count += 1 row, column = -1, -1 for i in range(len(brd)): for j in range(len(brd[i])): if brd[i][j] == 0: row, column = i, j break if row != -1: break if row == -1: ...
The main task of the code is to visualize and update a game board's state by clearing the screen, redrawing the board layout, displaying the number of recursive steps taken, and updating the background color if specified. It uses turtle graphics to render the board, track progress, and signal completion via the 'done' ...
def step(): global done visualise(board) scn.clear() move(220, -280, test_pen) # test_pen.write("By Akshit", align="center", font=("Cooper Black", 11, "normal")) layout(pos_x, pos_y,colchange) if colchange:scn.bgcolor('black') my_board(board, pos_x, pos_y,colchange) test_pen.color("...
def bruteHelper(integer_1, integer_2, signal, digits): b = bruteForce(integer_1, integer_2) b.initializeValues() b.isZero() if b.zero == True: print("Brute force multiplication result: ", "0") else: b.bruteForceMultiply() b.rePosition() b.isZero2() if b.zero2 ...
The main task of the code is to allow users to choose between brute force or divide-and-conquer algorithms for multiplying large integers. It processes user-input integers, executes the selected algorithm, and generates test cases of varying sizes (1000–10000 digits). It then runs both algorithms on these test cases, r...
def main(): choice = input('Enter B/b for brute force or D/d for divide and conquer: ') if choice == 'B' or choice == 'b': integer_1 = input("Enter first big integer: ") integer_2 = input("Enter second big integer: ") bruteHelper(integer_1, integer_2, True, None) print("") ...
def bird_a(): print("You raise your hands in surrender and start to explain the quest you were sent on and " "how Dae pointed you in this direction looking for someone.\n" "The person seems to recognize Dae's name, they drop some of their defensive posture.\n" "'Dae, as in a rabbit per...
The code defines a function `crow_y()` that presents a narrative scenario in a text-based game, describing a player's encounter with a Sudo-Dragon and a mysterious bird-human hybrid. It prompts the user with three choices (A, B, C) to determine the next action, branching to different functions (`bird_a()`, `bird_b()`, ...
def crow_y(): print("You decide to go and check up on what Crow is doing.\n" "When you find Crow you see her looking at another Sudo-Dragon.\n" "This one is green with orange on its spikes and horns.\n" "It doesnt seem aggressive, but more confused than anything.\n" "You call...
def bird_a(): print("You raise your hands in surrender and start to explain the quest you were sent on and " "how Dae pointed you in this direction looking for someone.\n" "The person seems to recognize Dae's name, they drop some of their defensive posture.\n" "'Dae, as in a rabbit per...
This code presents a narrative scenario in a text-based game where the player must choose a response to a confrontation with a bird-human hybrid character. The function displays story text, pauses, and prompts the user to select an option (A, B, or C), then directs execution to corresponding functions based on the inpu...
def crow_n(): print("You decide not to investigate why Crow is growling.\n" "Eventually Crow comes running into the clearing and hot on her tail is another Sudo-Dragon.\n" "This one is green with orange on its spikes and horns.\n" "While you are trying ot figure out what to do Crow run...
def read(file = 'test.txt'): f = open(file, 'rb') return f.read() def pad(message): newmsg = "" k = 0 if type(message) is bytes: # 0000 0000 - formato pakeitimas i bitus for byte in message: newmsg += '{0:08b}'.format(byte) return pad(newmsg) else: new...
The main task of the code is to process a file's content by reading it, padding the data, parsing it, hashing it, and printing the final hash value. If no filename is provided as a command-line argument, it prompts the user to input one. The code relies on functions `read`, `pad`, `parse`, and `hash` to transform the d...
def main(): if len(sys.argv) == 1: print('Iveskite failo pavadinima') return x = read(sys.argv[1]) x = pad(x) x = parse(x) x = hash(x) print(x)
def read(file = 'test.txt'): f = open(file, 'rb') return f.read() def pad(message): newmsg = "" k = 0 if type(message) is bytes: # 0000 0000 - formato pakeitimas i bitus for byte in message: newmsg += '{0:08b}'.format(byte) return pad(newmsg) else: ...
The main task of the code is to read a file's content from the command line, process it through padding, parsing, and hashing operations, then output the resulting hash. If no filename is provided, it prompts the user to input one. The script relies on external functions `read`, `pad`, `parse`, and `hash` for processin...
def main(): if len(sys.argv) == 1: print('Iveskite failo pavadinima') return message = read(sys.argv[1]) x = pad(message) x = parse(x) x = hash(x) print(x)
def read(file = 'test.txt'): f = open(file, 'rb') return f.read() def pad(message): newmsg = "" k = 0 if type(message) is bytes: # 0000 0000 - formato pakeitimas i bitus for byte in message: newmsg += '{0:08b}'.format(byte) return pad(newmsg) else: ...
The code processes a file's content by padding, parsing, and hashing it. It reads the input file, applies padding, parses the data, computes a hash, and prints the result. The main task is to transform the file's content through these steps and output the final hash value.
def main(): if len(sys.argv) == 1: print('Iveskite failo pavadinima') return message = read(sys.argv[1]) x = pad(message) x = parse(x) x = hash(x) print(x)
def iter_leaves(sons, c): for cc in sons[c]: if cc in sons: yield from iter_leaves(sons, cc) else: yield cc def bootstrap(m, ori_Y, cl_method='ward', metric='euclidean', n=1000, p=0.9): size = len(m) ori_sons = dict((float(c), (i, j)) for c, (i, j, d, l) in enumerate(...
This function generates a dendrogram plot from a linkage matrix (Y) using matplotlib. It allows cutting the dendrogram at a specified threshold (cut_score) to form clusters, assigns colors to clusters, and returns the leaf order and cluster labels. The plot visualizes hierarchical clustering with customized styling, in...
def dendrogram(Y, axe=None, cut=None, cut_score='CH', matrix=None, method=None, metric=None, max_clusters=100): if not axe: plt.figure(figsize=(12, 3)) axe = plt.subplot(111) dmax = max(i[2] for i in Y) size = len(Y) + 1 sons = dict((float(c), (i, j)) for c, (i, j, d, l) i...
def get_pauli_list(ham_name,measure_list): input_file = open(ham_name) pauli_list= [[] for _ in range(4)] # Z, X, Y,full ##read Hamiltonian from the file for lines in input_file: A = lines.split()[0] B = lines.split()[1][1:-1] pauli_list[-1].append([A, float(B)]) ...
The code simulates quantum algorithms (VQE/VQD) for a given Hamiltonian, generating Pauli strings from a defined Hamiltonian matrix. It sets up quantum circuits with 4 qubits, prepares measurement configurations, and executes optimization via SPSA to find optimal parameters. The function returns simulation results, inc...
def sim_one(flag_vqe=1,Udet=1.8,tc=0.05): Nq=4 # number of qubits of Ansatz ### generate Pauli string according to Hamiltonian qml_jw,f_jw,qml_bk,f_bk, Hmatrix,Hbasis,H1body,H2body=getH(Ez1=1.,Ez2=0.9, Udet=Udet, tc=tc, U0=2.) write_pauli_string(...
def print_board(board): output = "" for row in range(MAX_HEIGHT -1, -1, -1): output += " " for column in range(len(board)): try: output += board[column][row] except IndexError: output += '-' if column != len(board) - 1: ...
The code implements a Connect 4 game where two players take turns dropping pieces into columns. It checks for a winning condition after each move, alternates turns, and declares a winner or draw once the maximum turns are reached.
def run(): board = [ [], [], [], [], [], [], [], # ['o', 'o', 'o',], # ['x', 'o', 'x'], # ['o', 'x'], # ['x'], ] p1_turn = True print("Welcome to connect 4! Player 1 goes first.") turn_counter = 0 while...
def move_up(self): snake = self.get_snake_position() snake_head_row = snake[0]["row"] + 1 if snake_head_row > self.row_count - 1: snake_head_row = 0 self.update_snake_cells(snake_head_row, snake[0]["col"]) def move_down(self): snake = self.get_snake_position() ...
This code updates an object's movement state by checking if enough time has passed (delta_time) since the last update. If so, it resets the timer and triggers directional movement methods (move_up/down/left/right) based on active key presses. The purpose is to control movement frequency and synchronize actions with a f...
def on_update(self, delta_time: float = 1/60): self.time_since_update += delta_time if self.time_since_update > self.time_between_moves: self.time_since_update = 0 if self.up: self.move_up() if self.down: self.move_down() ...
def _check_state(self): if self.dev == None: logger.warning('EV2300 not ready, call prepare() first') raise AssertionError('EV2300 not ready') def _check_arguments(self, device_address, register_address): if not (0 <= device_address <= 127): raise ValueError('Device a...
The main task of the code is to read a 16-bit word from a specified SMBus device register by constructing a request packet with device address, register address, and CRC checksum, sending it via `_request()`, and unpacking the 2-byte response into a signed integer.
def smbus_read_word(self, device_address, register_address): self._check_state() self._check_arguments(device_address, register_address) self.buffer[0] = 10 # total bytes except first self.buffer[1] = 0xAA; self.buffer[2] = self.READ_WORD self.buffer[3:6] = array('B', [0...
def _check_state(self): if self.dev == None: logger.warning('EV2300 not ready, call prepare() first') raise AssertionError('EV2300 not ready') def _check_arguments(self, device_address, register_address): if not (0 <= device_address <= 127): raise ValueError('Device a...
This function writes a 16-bit word to a specified SMBus device register by constructing a formatted data packet with error checking, CRC calculation, and command execution. It validates inputs, prepares a buffer with device/register addresses, the 16-bit word, and a CRC checksum, then sends the command via the bus.
def smbus_write_word(self, device_address, register_address, word): self._check_state() self._check_arguments(device_address, register_address) if not (0 <= word <= 0xFFFF): raise ValueError('word not in range 0-FFFF', word) self.buffer[0] = 12 # total bytes except first ...
def _check_state(self): if self.dev == None: logger.warning('EV2300 not ready, call prepare() first') raise AssertionError('EV2300 not ready') def _check_arguments(self, device_address, register_address): if not (0 <= device_address <= 127): raise ValueError('Device a...
This function reads a block of data from a specified SMBus device and block address by constructing a command packet with CRC, sending it via `_request()`, and returning the received data from the response. It validates inputs, prepares a buffer with protocol-specific formatting, and handles error checks.
def smbus_read_block(self, device_address, block_address): self._check_state() self._check_arguments(device_address, block_address) self.buffer[0] = 10 # total bytes except first self.buffer[1] = 0xAA; self.buffer[2] = self.READ_BLOCK self.buffer[3:6] = array('B', [0]) *...
def _check_state(self): if self.dev == None: logger.warning('EV2300 not ready, call prepare() first') raise AssertionError('EV2300 not ready') def _check_arguments(self, device_address, register_address): if not (0 <= device_address <= 127): raise ValueError('Device a...
The main task of the code is to construct and send an SMBus write-block command packet. It validates input parameters, formats a data buffer with device address, block address, payload, CRC checksum, and control bytes, then transmits the packet to write a block of data to a specified SMBus device.
def smbus_write_block(self, device_address, block_address, block): self._check_state() self._check_arguments(device_address, block_address) if not (0 <= len(block) <= 52): raise ValueError('Block length not in range (0-52)', len(block)) self.buffer[0] = 10+len(block)+1 # tot...
def _check_state(self): if self.dev == None: logger.warning('EV2300 not ready, call prepare() first') raise AssertionError('EV2300 not ready') def _calculate_crc(self, slice): crc = crc8.crc8() crc.update(slice.tostring()) digest = array('B') digest.fromst...
The main task of the code is to construct and send an SMBus command packet to a specified device. It validates the command range, assembles a buffer with predefined headers, device address, command byte, CRC checksum, and trailing bytes, then transmits the formatted data via a write request. The function ensures proper...
def smbus_command(self, device_address, command): self._check_state() if not (0 <= command <= 0xff): raise ValueError('Command number not in range 0-255', command) self.buffer[0] = 10 # total bytes except first self.buffer[1] = 0xAA; self.buffer[2] = self.COMMAND ...
def get_time_ms(): # https://www.python.org/dev/peps/pep-0418/#time-monotonic return int(round(monotonic() * 1000)) def get_log(self): # Add temperature temperature_dict = self.get_temperature() self.add_to_battery_dict(temperature_dict, "Temperature") # Add voltage ...
The main task of the code is to monitor and log data at regular intervals (every 250ms) into a specified file. It ensures the target file is empty before starting, queries data periodically using `get_log()`, and writes timestamps/log data to the file via `write_log()`. The loop runs indefinitely, maintaining a fixed l...
def create_monitor(self, file_str): # Prepare log file log_path = Path(file_str) # Create file if it doesn't exist' log_path.touch() # Prepare file, it needs to be empty f = log_path.open(mode='w+') content = f.readlines() if content: self.lo...
def prepare_csv(self): data_file = Path(DATA_FILE) if not data_file.exists(): data_file.touch() with data_file.open() as f: file_content = f.readlines() if not len(file_content) == 0: self.battery_dict_ready = True self.HEADER...
The main task of the code is to continuously process battery data from a CSV file by resetting dictionaries, preparing data, generating summaries, logging key metrics (voltages, temperatures, SOH, cycle count), and writing results to a file. It creates a quick report, displays real-time battery status, and waits for us...
def create_summary(self): # TODO: change file handling to csv for all below methods while True: # Reset dicts self.battery_dict = dict() self.quick_report = dict() # Get existing data from battery_data.csv self.prepare_csv() # Get...
def reduce_conditions(condition_1, condition_2 = None, condition_3 = None, condition_4 = None, condition_5 = None): submitted_conditions = [condition_1, condition_2, condition_3, condition_4, condition_5] reduced_conditions = [] for condition in submitted_conditions: if condition != None: ...
The function processes five input conditions by trimming whitespace if non-empty, reduces them using `reduce_conditions`, fetches data and adjacency info via `get_stats`, generates a graph with `generate_my_graph`, and returns the figure. Its main task is to dynamically update a visual graph based on user-provided inpu...
def update_my_graph(input_condition1, input_condition2, input_condition3, input_condition4, input_condition5): input_cond1 = None input_cond2 = None input_cond3 = None input_cond4 = None input_cond5 = None if len(input_condition1) > 0: input_cond1 = input_condition1.strip() if len(in...
def is_1d(array): if isinstance(array, (KeysView, ValuesView)): array = np.array(list(array)) else: array = np.array(array) if len(array)==array.size: return True return False def get_color(cmap, color, ncharts, n_bars)->list: if not isinstance(cmap, list): cmap = [cm...
This function generates a bar chart from input data, handling both single and multi-dataset scenarios with customizable orientation, colors, labels, and grouping. It processes input values, prepares axes, and renders bars with options for sorting, limiting bars, and displaying labels, returning the matplotlib Axes obje...
def bar_chart( values, labels=None, orient:str = 'h', sort:bool = False, max_bars:int = None, errors = None, color=None, cmap: Union[str, List[str]] = None, rotation:int = 0, bar_labels: Union[list, np.ndarray] = None, bar_label_kws...
def build_widgets(self): # ~~ DENOISE WIDGETS ~~ self.denoise_mot_label = QLabel("Select .mot mocap source files") self.denoise_hind_mot_path = QLineEdit() self.configure_filepath_widgets(self.denoise_hind_mot_path, "Browse hindlimb motfile...") self.denoise_fore_mot_path = QLine...
This code initializes a GUI window for 'Komodo Tools', setting window properties, default search paths, and global variables for denoising, file import, and loop controls. It constructs UI components, layouts, and connects interactive elements to enable tool functionality like noise reduction, animation import, and loo...
def __init__(self, parent=None): super(KomodoToolsUI, self).__init__(parent) self.setWindowFlags(Qt.Window) self.setObjectName('KomodoTools_uniqueId') self.setWindowTitle('Komodo Tools') self.setGeometry(50, 50, 800, 800) # ~~ GLOBAL CLASS VARS ~~ self.default_se...
def get_rpm_package_name(self): """ returns the package name according to the info provided in the source file. """ split_index = ' : ' package_details = {} package_details_query = run(['rpm', '-qpi', self.source_path]) rows = package_details_query.aggr_st...
This method removes an existing RPM package by checking its installation status, logging the removal process, and using the 'rpm' command with sudo to uninstall it without executing scripts.
def remove_existing_rpm_package(self): """ removes any version that satisfies the package name of the given source path. """ package_name = self.get_rpm_package_name() if self._is_package_installed(package_name): ctx.logger.info('Removing existing package sour...
def _get_rollback_properties_dir(self, service_name): return os.path.join(self.BASE_PROPERTIES_PATH, service_name, self.ROLLBACK_NODE_PROPS_DIR_NAME) def _get_properties_dir(self, service_name): return os.path.join(self.BASE_PROPERTIES_PATH, ...
The main task of the code is to archive previous node properties for rollback purposes after a service installation completes. It moves the existing properties file to an archive directory, logs the action, and replaces it with new properties. This ensures rollback capability while updating service configurations.
def archive_properties(self, service_name): """ Archive previously used node properties. These properties will be used for rollback purposes. This method should be called ONLY once it's been determined that the node installation has ended and the service is up. :param service_nam...
def _get_rollback_resources_dir(self, service_name): return os.path.join(self.BASE_RESOURCES_PATH, service_name, self.RESOURCES_ROLLBACK_DIR_NAME) def mkdir(dir): if os.path.isdir(dir): return ctx.logger.info('Creating Directory: {0}'.forma...
The code archives resources for a specified service by moving files from the service's resource directory to a rollback directory. It separates files based on a prefix, relocating those without the prefix to the rollback directory and renaming/moving those with the prefix to the original directory without the prefix, l...
def archive_resources(self, service_name): rollback_dir = self._get_rollback_resources_dir(service_name) mkdir(rollback_dir) service_archive_path = self._get_resources_dir(service_name) # nodes will not always use blueprint resources i.e. java/python if is_upgrade and os.path.is...
def get_file_name_from_url(url): try: return url.split('/')[-1] except: # in case of irregular url. precaution. # note that urlparse is deprecated in Python 3 from urlparse import urlparse disassembled = urlparse(url) return os.path.basename(disassembled.path) def...
This function downloads a resource from a given source URL, checks if it already exists in a specified directory, and if not, downloads it. It then moves the file to a designated local path, logging the process for tracking. The main task is to ensure the resource is available locally, either by reusing an existing cop...
def _download_source_resource(source, local_resource_path): filename = get_file_name_from_url(source) if filename in os.listdir(CLOUDIFY_SOURCES_PATH): tmp_path = os.path.join(CLOUDIFY_SOURCES_PATH, filename) ctx.logger.info( 'Source found at: {0}, will use it ins...
def error_exit(message): ctx.logger.error(message) sys.exit(1) def sudo_write_to_file(contents, destination): fd, path = tempfile.mkstemp() os.close(fd) with open(path, 'w') as f: f.write(contents) return move(path, destination) def chmod(mode, path): ctx.logger.info('chmoding {0}: {...
The code deploys SSL certificates to a specified destination, validating their type (private/public) by checking header lines. It sets appropriate file permissions (440 for private, 444 for public) and ownership (root/group) to secure access. The function logs deployment details and ensures certificates are stored safe...
def deploy_ssl_certificate(private_or_public, destination, group, cert): # Root owner, with permissions set below, # allow anyone to read a public cert, # and allow the owner to read a private cert, but not change it, # mitigating risk in the event of the associated service being vulnerable. ownersh...
def get_selinux_state(): return subprocess.check_output('getenforce').rstrip('\n\r') def sudo(command, retries=0, globx=False, ignore_failures=False): if isinstance(command, str): command = shlex.split(command) command.insert(0, 'sudo') return run(command=command, globx=globx, retries=retries, ...
This function checks if SELinux is in enforcing mode. If so, it switches it to permissive mode for the current session and updates the system-wide configuration file to ensure the change persists after reboots. If SELinux is not enforcing, it logs that no action is needed.
def set_selinux_permissive(): """This sets SELinux to permissive mode both for the current session and systemwide. """ ctx.logger.info('Checking whether SELinux in enforced...') if 'Enforcing' == get_selinux_state(): ctx.logger.info('SELinux is enforcing, setting permissive state...') ...
def get_file_name_from_url(url): try: return url.split('/')[-1] except: # in case of irregular url. precaution. # note that urlparse is deprecated in Python 3 from urlparse import urlparse disassembled = urlparse(url) return os.path.basename(disassembled.path) def...
This function installs a package using yum, handling sources like URLs, local paths, or default repos. It checks if the package is already installed; if not, it downloads the RPM (if needed) and installs it, ensuring no conflicting versions remain. The function supports single-package installations, avoiding redundant ...
def yum_install(source, service_name): """Installs a package using yum. yum supports installing from URL, path and the default yum repo configured within your image. you can specify one of the following: [yum install -y] mylocalfile.rpm [yum install -y] mypackagename If the source is a pac...
def move(source, destination): sudo(['mv', source, destination]) def chown(user, group, path): ctx.logger.info('chowning {0} by {1}:{2}...'.format(path, user, group)) sudo(['chown', '-R', '{0}:{1}'.format(user, group), path]) def deploy_blueprint_resource(source, destination, service_name, ...
(The code deploys a logrotate configuration for a specified service by creating or overriding a logrotate config file in `/etc/logrotate.d`, ensuring proper permissions and ownership. It also sets up an hourly cron job for logrotate if not already present, moving the daily cron entry to hourly. The function prioritizes...
def logrotate(service): """Deploys a logrotate config for a service. Note that this is not idempotent in the sense that if a logrotate file is already copied to /etc/logrotate.d, it will copy it again and override it. This is done as such so that if a service deploys its own logrotate configuration...
def _get_install_resources_json(self, service_name): return self._get_resources_json(service_name, False) def _get_resource_file_path(self, service_name, resource_name, upgrade): base_service_res_dir = self._get_resources_dir(service_name) if upgrade: upgrade_resource_name = self.UPG...
This function handles downloading or copying user resources during an upgrade or initial setup. If an existing resource exists, it reuses and copies it to the destination. If not, it downloads the resource, either rendering it with context or directly downloading based on the 'render' flag.
def _download_user_resource(self, source, dest, resource_name, service_name, render=True, load_ctx=True): if is_upgrade: install_props = self._get_install_resources_json(service_name) existing_resource_path = install_props.get(resource_name, '') ...
def _load_ctx_properties(self, service_name): node_props = ctx.node.properties.get_all() if is_upgrade: # Use existing property configuration during upgrade use_existing = node_props.get('use_existing_on_upgrade') if use_existing: install_props_path = ...
The code creates a local copy of node properties for deployment, enabling reuse during upgrades/rollbacks. It loads context properties, checks for upgrade context to manage rollback archives, writes properties to a file if specified, and returns the node properties dictionary.
def create(self, service_name, write_to_file=True): """ a Factory used to create a local copy of the node properties used upon deployment. This copy will allows to later reuse the properties for upgrade/rollback purposes. The node ctx properties will be set according to the node ...
def _get_resource_file_path(self, service_name, resource_name, upgrade): base_service_res_dir = self._get_resources_dir(service_name) if upgrade: upgrade_resource_name = self.UPGRADE_RESOURCE_PREFIX + \ resource_name dest_file_path = os.path.j...
The main task of the code is to create a local copy of a resource from a source URL, handling different rendering and download scenarios (user-defined, source-only, or rendered), and updating a resources.json file to track the local path. This enables reuse of the resource for deployment, upgrades, or rollbacks by main...
def create(self, source, destination, service_name, user_resource=False, source_resource=False, render=True, load_ctx=True): """ a Factory used to create a local copy of a resource upon deployment. This copy allows to later reuse the resource for upgrade/rollback purposes....
def count_X(blocks): count = 0 for i in [z for y in blocks for x in y for z in x]: if i == 1: count += 1 return count def count_O(blocks): count = 0 for i in [z for y in blocks for x in y for z in x]: if i == -1: count += 1 return count def blocksO(blocks)...
The code selects the optimal move in a game, likely Ultimate Tic-Tac-Toe, by evaluating valid moves based on the current state. For player 1, it prioritizes specific positions, symmetry, and local board logic, while for other players, it uses a minimax algorithm with depth adjustment. The function balances heuristic ch...
def select_move(cur_state, remain_time): valid_moves = cur_state.get_valid_moves blocks = cur_state.blocks n = len(valid_moves) if n == 0: return None if cur_state.player_to_move == 1: if count_X(blocks) == 0 and count_O(blocks) == 0: return UltimateTTT_Move(4, 1, 1, 1) ...
def _check_for_tx(self, id, channel): # Calculate noise at receiver noise_interference_w = 10**(self.NOISE_FLOOR / 10.0) for i,tx in enumerate(self.active): if i == id: continue if tx['tx'] == None or tx['channel'] != channel: # Ignore things not transmitting or on different channel continue ...
The code manages packet reception from stations by handling SENSE and DATA messages. It checks channel activity, tracks transmissions, detects collisions, and acknowledges received packets. The loop continues until all stations have sent the required number of packets, ensuring complete data collection before stopping.
def run(self): # Loop until we have enough packets from each station. while True: # Wait until we have a "packet" to receive from some station. # Note: packets are actually two queue messages: a START and a DONE # message. msg = self.recv_queue.get() # print('AP: {} sent {}({})'.format(msg['id'], ms...
def generate_dataframe_censusData_dataWithGender(tableID, state, location_list, grp_lst, grp_dict, yr=2019, lvl='cousubs'): """ Census Data Contains gender categories ('Male', 'Female') i.e., 'B01001' - age group, 'C24010' - occupation list of available data (2019ver., acs5) is in https://api.census.gov/data/2...
The function `generate_dataframe_census` processes U.S. Census Bureau data to generate cleaned, structured data frames based on specified parameters like data type (`age`, `work`, `race`, etc.), state, location lists, and grouping rules. It routes requests to specialized helper functions (e.g., `B01001` for age data, `...
def generate_dataframe_census(dataType, state, location_list, grp_lst, grp_dict, yr=2019, lvl='cousubs', joint_race_lst=None, joint_race_dict=None, i_interest=21): """ This function will return complete data frame(s) after cleaning up, instead of returning raw census data. If raw data is required, use getDataUsin...
def logger(message=''): """ Send a message to a specific log file. @param message (optional) - message to include in the log. """ currTime = datetime.datetime.now() # timestampString = f"[{currTime.strftime("%Y-%m-%d %H:%M:%S %z")}]" # UTC offset does not display timestampString = f"[{currTi...
The main task of the code is to execute a backup process using user preferences, log progress and statistics, handle errors, and record total files, directories, sizes, and execution time. It initializes a log file, reads configuration paths, performs the backup, computes size metrics in bytes, MB, and GB, and logs res...
def main(): """ Only method to be called. """ open('backup.log','w').close() logger('MAIN METHOD STARTING') start = time.time() # conduct backup procedure logger('Reading preferences file') usrPrefs = readPreferences('preferences.txt') originalPath = Path(usrPrefs.get('orig...
def clean(self): self.points.clear() self.points_x.clear() self.points_y.clear() def add_point(self, xc, yc, x, y): self.points.append(Point(xc + x, yc + y)) self.points.append(Point(xc - x, yc + y)) self.points.append(Point(xc + x, yc - y)) self.points.append(Poi...
This code implements the midpoint circle algorithm to draw a circle on a graphics context 'g'. It calculates pixel positions iteratively using decision parameter 'pk', updating coordinates (x,y) to plot points in the first octant, then symmetrically mirroring them. The loop increments x, adjusts y based on 'pk' values,...
def draw(self, g): self.clean() x, y = 0, self.radius pk = 3 - 2 * self.radius self.add_point(self.center.x, self.center.y, x, y) self.draw_circle(g, self.center.x, self.center.y, x, y) while x <= y: x += 1 if pk <= 0: pk = pk + 4...
def _active_update(self, action): if action in self.techs.keys(): self._handle_tech(action) elif action in self.units.keys(): self._handle_unit(action) elif action in ['repair', 'stop_repair']: self.base.set_repair(action == 'repair') def _tech_count_down(self...
The `faction_step` method updates the faction's state by processing active actions, decrementing tech/unit cooldowns, managing unit movement and health, repairing the base, updating gold resources, and preparing rendering data if enabled. It orchestrates real-time game mechanics like countdowns, repairs, and resource c...
def faction_step(self, action): # - active update self._active_update(action) # - passive update # === count down for techs self._tech_count_down() # === count down for units self._unit_count_down() # === units movement # === units health ...
def separate(img): return img[:len(img) // 3], img[len(img) // 3:2 * (len(img) // 3)], img[2 * (len(img) // 3):3 * (len(img) // 3)] def prokudin_gorskii(target, source, other_channel, source_color, scale=0.2): res_x_shift, res_y_shift = 0, 0 past_y_shift, past_x_shift = 0, 0 if np.min(target.shape) > 40...
The main task of the code is to align the color channels of an image using the Prokudin-Gorskii method. It separates the input image into red, green, and blue channels, calculates horizontal and vertical shifts for each channel relative to the others, prints the shifts, and returns the aligned image as unsigned 8-bit i...
def register(img): b, g, r = separate(img) print("channel green:") x_shift, y_shift, g = prokudin_gorskii(r, g, b, 'g') print("Shift in direction of x:", x_shift, ", Shift in direction of y:", y_shift) print("channel blue:") x_shift, y_shift, b = prokudin_gorskii(r, b, g, 'b') print("Shift i...
def is_player_pulling(self): pressed_key = pg.key.get_pressed() if pressed_key[pg.K_LCTRL]: return True else: return False def determine_direction_coordinates(self, direction, pawn: Pawn): x = pawn.x y = pawn.y match direction: ...
The main task of the code is to move the player in a specified direction, checking if the target square is empty and within bounds. If not, it recursively moves obstructing pawns if they are movable. If pulling is enabled, it moves the opposite-direction pawn recursively. The player's position is updated, and the board...
def move_player(self, direction): """ Move the player in the direction given. Only empty squares can be moved into and if the player moves into a wall, the walls are moved recursively :param direction: the direction based on keyboard presses """ move_player = Fal...
def is_answered(self, pos: Tuple[int, int]): return self.board[pos[0]][pos[1]] != 0 def update_possible_vals(self, input: int, i: int, j: int): # same row and column for k in range(9): self.possible_vals[i][k].discard(input) self.possible_vals[k][j].discard(input) ...
This code solves a Sudoku puzzle by iteratively identifying cells with only one possible value in rows, columns, or 3x3 blocks, updating the board, and recursively solving until completion or backtracking if no valid moves remain.
def solve(self): if self.unanswered_count == 0: return True for i in range(9): for j in range(9): if not self.is_answered((i, j)) and len(self.possible_vals[i][j]) == 0: return False ExcaliburSudoku.step_count += 1 start = tim...
def is_answered(self, pos: Tuple[int, int]): return self.board[pos[0]][pos[1]] != 0 def update_possible_vals(self, input: int, i: int, j: int): # same row and column for k in range(9): self.possible_vals[i][k].discard(input) self.possible_vals[k][j].discard(input) ...
This function solves a Sudoku puzzle visually by applying constraint propagation and backtracking. It identifies cells with only one possible value, fills them, and updates the board step-by-step. If stuck, it tries backtracking with copies of the board, recursively solving until completion or failure, notifying the ca...
def visual_solve(self, on_update): if self.unanswered_count == 0: return True for i in range(9): for j in range(9): if not self.is_answered((i, j)) and len(self.possible_vals[i][j]) == 0: return False ExcaliburSudoku.step_count += 1 ...
def get_new_sudoku(): ExcaliburSudoku.step_count = 0 filename = None while not filename: filename = askfile() sudoku = ExcaliburSudoku.from_json(filename) return sudoku def create_cells(): cells = [[] for _ in range(9)] # Set attributes for for first RectCell row = 0 col = 0...
This code implements a playable Sudoku game using Pygame, featuring a reset button to generate new puzzles and a solve button to visualize step-by-step solutions. It handles user input, dynamically updates the board and buttons, and displays interactive elements like hover effects and step counts. The core tasks includ...
def play(): sudoku = get_new_sudoku() cells = create_cells() active_cell = None solve_rect = pygame.Rect( buffer, height-button_height - button_border*2 - buffer, button_width + button_border*2, button_height + button_border*2 ) while True: for event in ...
def ConvertImageToGrayscale(image): return cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) def PILToCV2(image): array = numpy.array(image) return cv2.cvtColor(array, cv2.COLOR_RGB2BGR) def GetThresholdImage(self, img): _, threshold = cv2.threshold(img, self.thresholdValue, 255, cv2.THRESH_BINARY...
The code processes an image to measure diameters using contour detection, applying grayscale conversion, thresholding, and contour drawing based on the specified processing type. It returns the processed image and measurement readings, optionally saving intermediate results.
def ProcessImage(self, imageToProcess, numberOfMeasurements, borderOffset, pixelsPerMM, threshold, imageProcessingType, writeImages = False): pt.StartTimer() self.thresholdValue = threshold self.imageToProcess = imageToProcess self.imageProcessingType = imageProcessingType self....
def save_highscore(): if check_file(DEFAULT_HIGHSCORE_PATH): if r["Game Mode"] == "Classic": if r["Digestion"] == 0: if r["Score"] > r["Highscore File"]["Highscore"]["Classic"]["Normal Digestion"]: r["Highscore"]["Classic"]["Normal Digestio...
The code resets game state by saving high scores, initializing scores/levels, and configuring game elements. It sets up a maze or field based on the "Game Mode" (Mazy/Lengthy), positions the snake and food, and handles errors during maze initialization.
def default(): save_highscore() r["Background"].reset_scroll_speed() r["Score"] = 0 r["Field Score"] = 0 r["Field Levels Cleared"] = 0 if r["Game Mode"] == "Mazy": r["Maze"] = EwSafeRectWallMaze(0, 0, r["Screen Width"], r["Screen Height"], r["Element Size"],...
def draw_main_score(var): w = r["Screen Width"]-16 h = r["Screen Height"]-16 x = 16 y = 16 if r["Score Counter Value Chooser"]["value"] == "Decimal": EwTransformedFont(x, y, w, h, r["FONT"], str( var), (0, 25, 0), 255, False, r["Font Quality"]).draw()...
The main task of the code is to execute a snake game loop by adjusting game speed via FPS settings, rendering the background/grid, displaying scores, managing snake life based on game mode, updating snake/food visuals, and handling exit/pause actions. It dynamically adapts visuals and mechanics based on user-selected o...
def exec_game(): app.fill_background(BLACK) r["Background"].draw() # Option-depended code: if r["Game Speed Value Chooser"]["value"] == "Huge Cells": app.set_fps(2) elif r["Game Speed Value Chooser"]["value"] == "Lame": app.set_fps(5) elif r["Ga...
def CheckLegality(self,direction): return DisplayAbstraction.CheckLegalityAbsolute(self.board,self.shape,direction) def Move(self, direction): #print(direction) self.board = DisplayAbstraction.MoveAbsolute(self.board,direction,self.shape) def Rotate(self, move=False): #print(self.current...
This code handles keypress events to control movement and rotation in a game or application. It checks specific scancodes (keys) like Down, Right, Left, Up, Space, and 'c', triggering actions like moving, rotating, moving to the end, or swapping, with legality checks for directional movements.
def Keypress(self, event): if event['scancode'] == 81 and self.CheckLegality("Down"): # Down self.Move("Down") elif event['scancode'] == 79 and self.CheckLegality("Right"): # Right self.Move("Right") elif event['scancode'] == 80 and self.CheckLegality("Left"): # Left ...
def SpawnATetronome(self): if len(self.spawnBag) == 0: self.spawnBag = [i for i in range(7)] self.spawnBag.append(random.randint(0, 6)) random.shuffle(self.spawnBag) self.currentTetronome = self.spawnBag.pop(0) #print(f"Spanning {self.currentTetronome}") ...
This code runs a Tetris game loop, handling user input, AI-controlled moves, and block movement. It spawns initial blocks, updates game state at set intervals, and renders the display while maintaining a specified tick rate.
def run(self): self.SpawnATetronome() # spawn first block counter = 0 while (True): for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() elif event.type == pygame.KEYDOWN: ...
def reset(self, start_square=UL_SQUARE): """ Method to initialize an episode (start our Jetbot at some random location and establish our goal square) """ if start_square not in self.squares: raise Exception(f'Error: start square at {start_square} is not inside the map') ...
The code performs one-shot navigation using a Q-table model to guide an agent through an environment. It initializes the environment at a specified start square, observes the initial state, and repeatedly selects actions based on the model's predictions. The process continues until the agent reaches a goal or incurs a ...
def navigate(self, model, start_square=UL_SQUARE): """ Method to perform a one-shot given a Q-table ("model") """ self.reset(start_square) state = self.observe_state() while True: action = model.predict(state=state) state, reward, status = self.s...
def wake_up(self) -> None: """ This command is used to wake up the sensor from the idle mode. The sensor will return to the measurement mode. """ print("Waking up") self._send_command(SCD4x_WAKE_UP, 50) def self_test(self) -> None: """ This command triggers a self...
The code initializes an SCD41 sensor via I2C, setting up data buffers, configuring the I2C bus address, and performing initial setup tasks like waking the sensor, optional self-testing, and stopping periodic measurements to prepare for controlled data acquisition.
def __init__(self, bus: I2C, do_self_test: bool = False): self._message_buffer = bytearray(18) self._command_buffer = bytearray(2) self._crc_buffer = bytearray(2) self.bus: I2C = bus self.address = SCD41_ADDRESS self._temperature = None self._humidity = None ...
def _should_stop_prematurely(self) -> bool: if self.completion_timeout is None: return False elapsed = time.time() - self.start_time stop = elapsed >= self.completion_timeout if stop: self.log_info(f"Call id {self.call_id} should stop prematurely. Elapsed {elapsed:.1f}s") return stop de...
This function handles a streamed request with retry logic, processes each event in the stream, manages exceptions by logging errors, and returns the accumulated generation output. It initializes a GenerationOutput, tracks execution time, trims content, invokes a callback on completion, and sets the provider's execution...
def _streamed_request_with_retry(self) -> t.Optional[GenerationOutput]: if self._should_stop_prematurely(): return gen_events = self._provider_stream(func=self._streamed_request_with_retry) self.full_generation_output = GenerationOutput() start = time.time() last_event = time.time() try...
def log_info(self, msg): if self.verbose: self.logger.info(msg) def _should_stop_prematurely(self) -> bool: if self.completion_timeout is None: return False elapsed = time.time() - self.start_time stop = elapsed >= self.completion_timeout if stop: self.log_info(f"Call id {self.cal...
This code implements a streaming generator that processes events from a provider, handles each step of the generation process, yields partial results incrementally, and manages potential interruptions or exceptions. It logs start/end events, checks for early termination, and streams content via `yield` while maintainin...
def generator(self): self.log_info(f"Start generator call id `{self.call_id}` (provider={self.provider_name}, llm={self.llm})") if self._should_stop_prematurely(): return gen_events = self._provider_stream(func=self.generator) self.full_generation_output = GenerationOutput() try: start...
def on_init(self): pygame.init() self.game_display = pygame.display.set_mode((self.width,self.height)) self.running = True #other variables such as mass, charge, spring constant, etc can go here for i in range(self.numberOfParticles): #randomi...
The code executes a game loop by initializing resources, processing events, updating game logic, rendering visuals, and cleaning up upon termination. It runs continuously while `self.running` is True, handling user input and maintaining the game state until explicitly stopped.
def on_execute(self): if self.on_init() == False: self.running = False while( self.running ): for event in pygame.event.get(): self.on_event(event) self.on_loop() self.on_render() self.on_cleanup()
def __correct_settings(self): self.__choose_board() self.__choose_names() self.__choose_symbols() while True: self.__clear_screen() self.__show_menu("player") input_player_p = int(input("Choose an option: ")) if input_player_p == 1: ...
This method handles a player vs. player game mode by managing the game loop, alternating turns between two players, displaying the board, checking for game completion, and handling restarts or resets based on user input. It alternates player positions, updates the board with symbols, and provides options to replay or e...
def __play_vs(self, game_mode): if game_mode == "player" and self.__correct_settings(): self.__players.append(self.__p2) while True: self.__clear_screen() print(f"----- Player vs Player -----\n") self.__board.display() self....
def __clear_screen(self): os.system("cls") if os.name == "nt" else os.system("clear") def __show_menu(self, option): if option == "main": print("\n[ Tictactoe's Menu ]\n") print(" 1) Player vs Player") print(" 2) Player vs CPU") print(" 3) Show match...
This code runs a game menu loop, displaying options to play against a player, CPU, or exit. It validates user input, handles errors, and executes corresponding game modes while keeping the interface interactive.
def start(self): while True: try: self.__clear_screen() self.__show_menu("main") option = int(input("Choose an option: ")) if option == 1: self.__play_vs("player") elif option == 2: ...
def import_csv(path, remove_first_list = False): """ Returns: ------- None. """ data = list() file = read_csv(path,header=None) for i in range(len(file.columns)): data.append(file[i].tolist()) del file # Remove first item in each column (column name) if rem...
The main task of the code is to process CSV files by adding derived data columns such as Energy (hc/lambda), Mean Intensity, and background-corrected intensity. It also applies discontinuity removal, computes true spectra, and exports modified data. The process involves importing data, applying mathematical transformat...
def __main__(PATH): """ Creates new data columns in each csv file. Creates Energy column (hc/lambda) from column 0 Creates Mean Intensity column from n next columns """ import_path = PATH export_path = 'D:\\MPhys_data_modified' isExist = os.path.exists(export_path) if not i...
def _compute_unrolled_model(self, input, target, eta, network_optimizer): # unrolled_model is a model whose "w" is changed to "w-eta·Grad(w)L_train" # this updates the weights of teacher, and don't update its architecture loss = self.model._loss(input, target) theta = _concat(self.model....
This code computes gradients for the model's architecture parameters by unrolling optimization steps. It updates the student model's weights using validation loss, calculates implicit gradients via the outer-layer optimization problem, and applies them to the teacher model's architecture parameters, keeping the teacher...
def step1(self, input_train, target_train, input_valid, target_valid, input_unlabeled, eta, network_optimizer, student_optimizer, unrolled): self.optimizer.zero_grad() # this updates the architecture via the second term of the outer layer's optimization problem unrolled_model = se...
def isCloseDown(self): if self.prev is not None: return not self.isCloseUp() else: return None def isLowerHigh(self): return not self.isHigherHigh() def isLowerLow(self): return not self.isHigherLow()
The code defines a method `isDown` that checks if three conditions—`isCloseDown`, `isLowerHigh`, and `isLowerLow`—are all true, likely to determine if a stock or asset is in a downward trend based on its closing price, high, and low values.
def isDown(self): return self.isCloseDown() and self.isLowerHigh() and self.isLowerLow()
def management_menu(user_id): while True: manager_menu = input( """Please choose from the following menue options: (1) Create a User (2) Create a Compotency (3) Create an Assessment (4) Create an Assessment Result set (5) View Users (...
The code authenticates a user by verifying their email and password against a database. It retrieves the hashed password, user type, and ID, then checks the input password using bcrypt. If valid, it redirects to management or view user menus based on user type; otherwise, it recursively prompts for login again.
def login(): print("Welcome to Mitchells Capstone Please Proceed with Login.") user_email = input("Enter email address:") user_password = input("Enter password:") hashed_password, user_type, user_id = cursor.execute( "SELECT password, user_type, user_id FROM USER WHERE email = ?", (user_email,)...
def build_default_header(self, kong_render_setup_generatorWindow): # Setting up the default PXO header self.centralwidget = QtWidgets.QWidget(kong_render_setup_generatorWindow) self.centralwidget.setObjectName("centralwidget") self.verticalLayout = QtWidgets.QVBoxLayout(self.centralwidge...
The code defines the user interface (UI) for a rendering setup generator window. It sets up a grid layout with input fields for shader selection, asset name, category, file prefix, and background, along with buttons to load shaders and build rendering layers. The UI includes labels, text fields, and tool buttons organi...
def setupUi(self, kong_render_setup_generatorWindow): kong_render_setup_generatorWindow.setObjectName("kong_render_setup_generatorWindow") kong_render_setup_generatorWindow.resize(600, 300) self.build_default_header(kong_render_setup_generatorWindow) self.build_help() # Tool ...