dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def isEqual(u,v, eps_scalar = 1e-2, eps_angle = 5.): ''' returns whether u and v are **ALMOST** equal. - eps: if u,v are scalars, then eps is the absolute difference - eps_angle: IN DEGREES, max angle between vectors (n-dim, n>1) for them to be equal. ''' try: return abs( angle_between(u...
The code implements waypoint following for an autonomous agent by adjusting altitude, heading, and groundspeed to navigate toward predefined waypoints. It checks if the current waypoint's altitude is reached, calculates the desired heading and speed toward the next waypoint, and updates the vehicle's orientation and ve...
def callback_wp(data): ''' Waypoint following TODO: make sure command is meant for this agent #TODO : extend "==" to "almost equal", same for "!=" : heading & vel ''' global vehicle, agent try: if agent.clear_wp and agent.action.cmd == "wp": # check if next waypoint reach...
def get_mobile_prepaid_data(browser, url): page = goto_page(browser, url) time.sleep(5) logging.info(f"Extracting mobile prepaid data from: {url}") mobile_prepaid_data = extract_prepaid_data(page, url) page.close() return mobile_prepaid_data def get_mobile_subscription_data(browser, url): ...
The main task of the code is to aggregate mobile prepaid, subscription, and internet plan data from specified URLs using a browser, compile them into a unified product list, validate the data with a Pydantic model, and return the structured result as a dictionary. Error handling logs validation issues and raises an Air...
def get_products(browser, url): try: prepaid_data = get_mobile_prepaid_data(browser, url['mobile_prepaid']) mobile_subscription_data = get_mobile_subscription_data(browser, url['mobile_subscription']) internet_subscription_data = get_internet_subscription_data(browser, url['internet_subscri...
def get_products(browser, url): try: prepaid_data = get_mobile_prepaid_data(browser, url['mobile_prepaid']) mobile_subscription_data = get_mobile_subscription_data(browser, url['mobile_subscription']) internet_subscription_data = get_internet_subscription_data(browser, url['internet_subscri...
The code scrapes product data from a website (URL) using Playwright, processes combo advantages, generates product packs, and saves results as JSON files. It logs execution details, handles errors, and records start/end times.
def mobileviking_scraper(): with sync_playwright() as pw: start_time = time.strftime("%Y-%m-%d %H:%M:%S") start_time_seconds = time.time() error_details = 'no error' log_file_name = 'test.log' log_file_path = f"logs/{log_file_name}" log_format = '%(asctime)s [%(lev...
def __write_irq_handlers(self, fp): for i in range(self.__nv): if self.__vt[i] is None: fp.write(self.__irq_spurious_entry(i) + '\n') else: fp.write('/* ISR: {} implemented in app. */\n'.format(i)) def __write_shared_handlers(self, fp): fp.write("e...
The function writes source code to a file, including a header and conditional interrupt handler sections based on internal flags and configuration. It writes IRQ handlers if `self.__vt` is true, skips further processing if `self.__swt` is false, and writes shared interrupt handlers if configured, followed by standard I...
def write_source(self, fp): fp.write(self.source_header) if self.__vt: self.__write_irq_handlers(fp) if not self.__swt: return if self.__config.check_shared_interrupts(): self.__write_shared_handlers(fp) self.__write_isr_handlers(fp)
def _setup_tqdms(self, training): idx = 0 if training else 1 t = tqdm(total=self.iters_per_epoch[idx], leave=True, dynamic_ncols=True) t.clear() self.tqdms[idx] = t def do_epoch(self, epoch_id, training): idx = 0 if training else 1 iters_per_epoch = self.iters_per_epoch[i...
The code trains a machine learning model over multiple epochs, adjusting the learning rate and logging progress. It alternates between training and testing phases periodically, runs training/test epochs, logs results, and saves checkpoints. The scheduler updates after each epoch, ensuring structured training with evalu...
def train(self): for epoch_id in range(self.num_epochs): lrs = self.scheduler.get_last_lr()[0] self.logger.info(f'Epoch: {epoch_id}/{self.num_epochs} lr: {lrs:.5f}') if (epoch_id + 1) % self.test_period == 0 or \ epoch_id == self.num_epochs - 1: ...
def linear_search(A, query_index, num_neighbors): #TODO distances = np.sum(np.abs(A - A[query_index]), axis=1) distances[query_index] = 1e6 return list(np.argpartition(-distances, -num_neighbors)[-num_neighbors:]) def lsh_setup(A, k = 24, L = 10): functions = create_functions(k = k, L = L) hashe...
The code compares the time efficiency of linear search and Locality-Sensitive Hashing (LSH) for nearest neighbor queries. It benchmarks both methods on a dataset `A` by performing searches for 10 query points (`query_indexes`). The linear search directly finds neighbors, while LSH uses precomputed hash functions (`lsh_...
def problem4_1(A): num_neighbors = 3 query_indexes = [100 * j for j in range(1, 11)] start = time.time() linear_neighbors = list(map(lambda query_index: linear_search(A, query_index, num_neighbors), query_indexes)) end = time.time() print('Time linear search: ' + str(end - start)) L = 10 ...
def linear_search(A, query_index, num_neighbors): #TODO distances = np.sum(np.abs(A - A[query_index]), axis=1) distances[query_index] = 1e6 return list(np.argpartition(-distances, -num_neighbors)[-num_neighbors:]) def lsh_setup(A, k = 24, L = 10): functions = create_functions(k = k, L = L) hashe...
The code evaluates the performance of Locality-Sensitive Hashing (LSH) for approximate nearest neighbor search by comparing error rates against a linear search. It varies parameters L (hash table size) and k (number of hash functions), computes errors for different query indexes, and plots error trends against L and k ...
def problem4_2(A): num_neighbors = 3 query_indexes = [100 * j for j in range(1, 11)] start = time.time() linear_neighbors = list(map(lambda query_index: linear_search(A, query_index, num_neighbors), query_indexes)) end = time.time() print('Time linear search: ' + str(end - start)) Ls = np.ar...
def _concept_cavs(self, bottleneck: str, bottleneck_model: tf.keras.Model, concept: str, activations: np.ndarray, randoms: Optional[List] = None, ow: bool = True) -> List: """Calculates CAVs of a concept versus all the random counterparts. @param bottleneck: Bottleneck layer name....
This method computes and saves Concept Activation Vectors (CAVs) for discovered concepts against random concepts in all bottleneck layers. It calculates classification accuracies of linear boundaries orthogonal to CAVs, loads concept images from memory or disk, filters out low-accuracy concepts, and returns a structure...
def cavs(self, min_acc: float = 0., ow: bool = False, in_memory: bool = True, concept_dir: str = '') -> Dict: """This method calculates and saves CAVs for all the discovered concepts versus all random concepts in all the bottleneck layers. @param min_acc: Delete discovered concept if average cl...
def dfs(visited, graph, node): if node not in visited: visited.add(node) for neighbour in graph[node]: dfs(visited, graph, neighbour) return visited def rch(root, graph, nodes=None): reach = set() if nodes==None: for node in graph.keys(): visited = set()...
This code recursively generates all valid graphs by adding edges from the list `ug` while ensuring reachability constraints. It uses depth-first search (dfs) to determine reachable nodes and checks conditions to avoid cycles. If an edge doesn't violate reachability rules, it adds the edge and recurses, appending valid ...
def generate(ug, t, i1, j): #copies needed for recursion tg=copy.deepcopy(t) tg1=copy.deepcopy(t) #set of reachable nodes form i1 R = dfs(set(), t, i1) #nodes less than i1 that reach i1 nn = list(range(1, i1, 1)) B = rch(i1, t, nn) #recursion base ...
def checkQuit(self): for input in pygame.event.get(): if (input.type == pygame.QUIT): pygame.quit() quit() def AIMove(self, action): if (np.array_equal(action, [1, 0, 0])): if (self.currentDirection != 0): self.AIDirection = self.cu...
The main task of the code is to control an AI agent's movement in a snake game, process game state updates, check collision/termination conditions, and return game status (True/False), current score, and reward. It increments iteration count, applies the action, updates snake position, checks for collisions or excessiv...
def AIControl(self, action): self.checkQuit() self.iteration += 1 self.reward = 0 self.AIMove(action) self.snake.insert(0, self.head) if (self.checkCollision()): return True, self.score, -10 if (self.iteration > 50*len(self.snake)): return ...
def print_help(): print(__doc__.strip()) def query_sqlite_file(scriptfile, *args, **kwargs): """ Run a script of SQL commands on a sqlite database in the specified file (or in memory if sqlfilename is None). """ cmds = read_sqlfile(scriptfile) return query_sqlite(cmds, *args, **kwargs) def q...
This code parses command-line arguments to execute SQL queries on SQLite databases or CSV files. It handles flags for version display, help, input/output files, and script execution. Depending on input type (file or CSV), it runs queries, processes results, and outputs them to a file or stdout. The core task is executi...
def main(): optlist, arglist = getopt.getopt(sys.argv[1:], "i:u:o:f:Vhs") flags = dict(optlist) if '-V' in flags: print(VERSION) sys.exit(0) if len(arglist) == 0 or '-h' in flags: print_help() sys.exit(0) outfile = flags.get('-o', None) usefile = flags.get('-u'...
def __plot_config(self): self.plot_opts = { 'connect': 'all', 'fftMode': False, 'logMode': [False, False], 'alphaHint': 1.0, 'alphaMode': False, 'pen': (255, 0, 0), 'shadowPen': None, 'fillLevel': None, ...
The code initializes a GUI application window for temperature monitoring/control, setting up database connections, thermocouple inputs, PID control, and plotting. It loads a UI layout, configures plot settings, initializes timers, reads parameters from a database, applies styling, and prepares for real-time data visual...
def __init__(self, db, tc, io, pid): super(ApplicationWindow, self).__init__() self.db = db self.tc = tc # Thermocouple self.io = io self.pid = pid self.temperature_data = [] # list of tempeatures to be plotted self.setAttribute(QtCore.Qt.WA_DeleteOnClose) ...
def setUp(self) -> None: self.driver = webdriver.Remote(appium_server_url, capabilities) self.wait = WebDriverWait(self.driver, 10) time.sleep(3) def click_on_btn(self, btn_name): button = self.select_one(btn_name) self.wait.until(EC.element_to_be_clickable(button)) self....
The main task of the code is to scrape hotel price data from a website by automating the selection of hotels and dates, then storing the results in a dictionary. It iterates through hotel names and check-in dates, navigates the site using selenium, extracts price information, and handles exceptions during the process. ...
def get_prices(self, hotel_data) -> dict: self.setUp() dict_data = {}.items() for hotel_name, dates_list in hotel_data.items(): # dict_data[hotel_name] = {} self.click_on_btn("Search") self.click_on_btn("Where to?") self.click_on_btn("Where to?")...
def read_csv(filepath, encoding="utf-8", newline="", delimiter=","): """ Reads a CSV file, parsing row values per the provided delimiter. Returns a list of lists, wherein each nested list represents a single row from the input file. WARN: If a byte order mark (BOM) is encountered at the beginning of th...
The code processes a CSV file containing coral reef data, standardizing "CORAL_FAMILY" entries using a classification lookup JSON. It cleans and replaces family names with standardized values, then writes the updated data to a new CSV file. The task involves data cleaning, taxonomy lookup, and reformatting coral family...
def main(): """ Program entry point. Orchestrates workflow. Parameters: None Returns: None """ # filepath = Path(__file__).parent.resolve().joinpath("coral_bleaching.csv") filepath = Path("coral_bleaching.csv").resolve() data = read_csv(filepath) headers = data[0] ...
def read_csv(filepath, encoding="utf-8", newline="", delimiter=","): """ Reads a CSV file, parsing row values per the provided delimiter. Returns a list of lists, wherein each nested list represents a single row from the input file. WARN: If a byte order mark (BOM) is encountered at the beginning of th...
This code processes coral reef data by reading a CSV file, cleaning coral family and species names using predefined substrings, classifying entries with a JSON lookup, inserting a new 'CORAL_GENUS' column, and writing the cleaned data to a new CSV file.
def main(): """ Program entry point. Orchestrates workflow. Parameters: None Returns: None """ # filepath = Path(__file__).parent.resolve().joinpath("coral_bleaching.csv") filepath = Path("coral_bleaching.csv").resolve() data = read_csv(filepath) headers = data[0] ...
def generate_real_samples(dataset, n_batch, patch_shape, jitter=True, labels=True): """ generate pair of image and labels with 'true' labels for discriminator dataset: image/label pairs n_batch: number of patches in each batch patch_shape: size of patchGAN output jitter: add random jitter and c...
The function `summarise_performance` evaluates a trained generator model by generating synthetic images from input labels and comparing them to real images. It processes real and generated samples, scales pixel values, and visualizes triplets (real labels, generated images, real images) in a grid. It saves the visualiz...
def summarise_performance(step, g_model, dataset, labels=False, n_samples=3, savepath='.'): # https://machinelearningmastery.com/how-to-implement-pix2pix-gan-models-from-scratch-with-keras/ """ generates synthetic image from generator, compares to true image and saves images and model step: model step ...
def createWindow(self): self.window = tk.Tk() self.window.geometry('312x324') self.window.resizable(0, 0) # this prevents from resizing the window self.window.title('Calculator') def createFrames(self): self.input_text = tk.StringVar() # creating a frame for the ...
The code initializes a GUI application by setting up a window, frames for layout, and buttons. It initializes an empty expression string to store input/calculation data, then calls methods to create the window, organize frames, and add interactive buttons, forming the foundation of a calculator or similar interface.
def __init__(self): self.expression = '' self.createWindow() self.createFrames() self.createButtons()
def xml_ns(arg): """Returns the full URL of an XML namespaced tag""" return QName(xml_namespace, arg).text def parse_master_cmp(self, input_file): doc = etree.parse(input_file) for elem in doc.getroot(): if elem.tag.lower() == xml_ns("preferences"): self.parse_preferences(elem) elif elem...
This code initializes a class to process CMP files, handling zip/non-zip inputs. It parses XML to identify a master CMP file, loads it, and processes variables/dialogs by substituting placeholders. The main task is to set up document metadata, parse component data, and prepare dynamic content for rendering or further p...
def __init__(self, input_name): self.metadata = {} self.setup_info = {} self.page_map: dict[str, PageNode] = {} self.dialogs: dict[str, dict] = {} self.variable_map: dict[str, Variable] = {} # HotDoc specific things that might be useful self.preferences = {} self.code_blocks = {} se...
def parse_text(text_elem): text = text_elem.text for html_elem in text_elem: if html_elem.tag.lower() == "p": text += parse_paragraph(html_elem) elif html_elem.tag.lower() == "ul": for list_item in html_elem: text += f"* {parse_inline(list_item)}\n" text += "\n" elif html_elem....
This code initializes a class instance to parse and store attributes from an XML/element node, including text, help content, buttons, fields, and metadata like name, type, and coordinates. It processes child elements to populate corresponding properties, using helper methods for complex elements like buttons and fields...
def __init__(self, page_elem): self.parent = None # need to update this later self.text = None self.learn = None self.help = None self.helpimage = None self.buttons = [] self.fields = [] self.children_names = set() self.codeafter = None self.codebefore = None self.name = pag...
def makeCoarse(x): """Make coarse, i.e. chop off anything after the colon Args: x (str): input string Returns: str: input truncated from colon onwards """ if ":" in x: return x[: x.index(":")] return x def linearize_mindl(sentence): """Linearize a dependency tree to...
The function `orderSentence` linearizes a sentence based on a grammar model using dependency-head directionality and distance weights. It processes each word, categorizes dependencies, and orders them according to the specified model (e.g., reversing order, sorting by frequency, or minimizing dependency length). For no...
def orderSentence(sentence, model, dhWeights, distanceWeights, freqs=None, debug=False): """Linearize a sentence under a given grammar, parametrized by the given dependency-head directionality weights and distance weights Args: sentence (List[Dict[str->str]]): list of dicts mapping field names to v...
def get_angle(vec): return np.arctan2(vec[1], vec[0]) def compute_reward(self, achieved_goal: object, desired_goal: object, info: Mapping[str, Any]) -> float: achieved = np.linalg.norm(achieved_goal - desired_goal) < self.unwrapped.object_size return 0 if achieved else -1 def _get_obs(self): ...
The code implements a reinforcement learning environment step function. It applies an action to adjust an object's angular velocity, updates the environment state using physics simulation, computes a reward based on proximity to a target, checks if the task is completed (when reward is zero), and returns the new observ...
def step(self, action: float) -> Tuple[ObsType, float, bool, bool, dict]: angle_diff = float(action * self.max_angular_velocity) angle = get_angle(self.object.linearVelocity) self.object.linearVelocity = np.cos(angle + angle_diff) * self.speed, np.sin(angle + angle_diff) * self.speed se...
def train_file(): print("TRAIN FILE") print("----------") print("1. Add a train") print("2. Delete a train") print("3. Display all trains") print() sub_opt = int(input("Select any one option: ")) print() if sub_opt == 1: add_train() elif sub_opt ...
The code implements a menu-driven system for managing train ticket operations. It allows users to train files, book tickets (with steps for selecting trains, days, and user info), cancel tickets, generate reports, or exit. The program handles user input validation, loops for repeated actions, and provides navigation ba...
def menu(): cont = True while(cont == True): print("WELCOME USER!!") print("-------------") print() print("1. Train file") print("2. Book a ticket") print("3. Cancel a ticket") print("4. Report") print("5. Quit")...
def _update_link_and_column_volume(column_pool, links, iter_num, reduce_path_vol = True): if not iter_num: return for link in links: if not link.length: break link.reset_period_flow_vol() for k, cv in column_pool.items(): # k= (at, tau, oz_id, dz_id) ta...
(The main task of the code is to perform Path/Column-based User Equilibrium (UE) traffic assignment using column generation and iterative optimization. It generates columns (paths) through multiple iterations, updates link travel times and column volumes, and optimizes the column pool to achieve equilibrium. The functi...
def perform_column_generation(column_gen_num, column_update_num, ui): """ perform network assignment using the selected assignment mode WARNING ------- Only Path/Column-based User Equilibrium (UE) is implemented in Python. If you need other assignment modes or dynamic traffic assignment (DTA), ...
def parseoptions(): parser = OptionParser() parser.add_option("-t", "--target", dest="target", help="Target SpamTitan URL to attack. E.g.: https://spamtitan.com/", default=None) parser.add_option("-m", "--method", dest="method", help="Exploit number: (1) CVE-2020-1169...
The main task of the code is to exploit specific CVE vulnerabilities (1-4) in a target system by authenticating with provided credentials, then initiating reverse shell attacks or file reading based on the selected method. It validates inputs, handles authentication, spawns threads for exploitation, and launches a reve...
def main(): (options,arguments) = parseoptions() quiet = options.quiet target = options.target ip = options.ip port = options.port user = options.user password = options.password shellurl = options.shellurl method = int(options.method) rfile = options.filtetoread # Sanit...
def run_cmd(cmd: str) -> Tuple[str, str]: logger.debug("cmd: %s", cmd) p = subprocess.Popen(cmd.split(" "), stdout=subprocess.PIPE, stderr=subprocess.PIPE) out_, err_ = p.communicate() out = out_.decode("utf-8").strip() err = err_.decode("utf-8").strip() logger.debug("cmd out: %s", out) logg...
The function generates GitHub release notes by formatting diffs between consecutive Git tags in a specified range. If `create` is True, it creates releases on GitHub for each tag; otherwise, it prints the formatted diffs. It identifies the tag range using `prior_tag` and `release_tag`, calculates the number of releases...
def create_releases(repo_name: str, prior_tag: str, release_tag: str, create: bool, percentage: str): commits, _ = run_cmd(f"{GIT_EXE} rev-list HEAD") # last will be first # need this to compare the very first tag initial_commit = commits.splitlines()[-1] tags = [initial_commit] git_tags, _ = r...
def _strip_url(www): """Used to parse the query string of the URL and create a dictionary of parameter names and values.""" # Parse the URL parsed_url = urlparse(www) # Extract query parameters query_params = parse_qs(parsed_url.query) # Get the values of xkraj and xnumnuts xkraj_val...
The function downloads a webpage, extracts specific data (ID, name, titles), processes it into a DataFrame, saves the structured data to a CSV file in a designated directory, and ensures the output file is created with the provided name.
def dwn_main_webpage(www, output_file): """Raise for status www page and start up process to find ID, name, titles and data. After collecting data prepare lists to merge.""" while True: task = requests.get(www) task.raise_for_status() # Assuming _strip_url is defined somewhere ...
def hunger(self): #to get his food to decrease every second (not realistic but yeah) self.HUNGEREVENT = pygame.USEREVENT + 1 pygame.time.set_timer(self.HUNGEREVENT, 1000) self.all_sprites.update() pygame.display.flip() def reproduce(self): #well realistically again not po...
The code's main task is to execute the game's core loop, managing gameplay mechanics like hunger, reproduction, and scoring. It initializes the game state, processes events, updates game logic, and renders visuals at a consistent frame rate (FPS), maintaining the loop until 'self.playing' is set to False. Delta time ca...
def run(self): #main algorithm running the game self.playing = True self.hunger() self.reproduce() self.scorelol() while self.playing: self.dt = self.clock.tick(FPS) / 1000 self.events() self.draw() self.update()
def _get_header_order(self): order_dict = self._get_header_order_dict() order_ls = [None for _ in range(len(order_dict.items()))] for tag, order in order_dict.items(): order_ls[order - 1] = tag return order_ls def get_header_labels_dict(self): label_dict = {} ...
The function `get_header_info` compiles metadata for table columns, including labels, hyperlink status, and numeric type, into an ordered dictionary. This data supports UI features like search, sorting, and table rendering by providing structured column information.
def get_header_info(self): ''' Return specific info about the columns, which is required for the search and sort functions and the tables appearance. ''' headers = self._get_header_order() labels = self.get_header_labels_dict() is_hyperlink = self._get_header_att...
def prewitt_edge_detector(img): # define prewitt x and y kernels prewitt_x = [ [-1, 0, 1], [-1, 0, 1], [-1, 0, 1] ] prewitt_y = [ [1, 1, 1], [0, 0, 0], [-1, -1, -1] ] return detect_edges(img, prewitt_x, prewitt_y) def sobel_edge_detector(img): ...
The code generates line art from an input image using specified edge detection (Prewitt, Sobel, or Scharr) and recolors edges with given foreground and background colors. It applies the chosen edge detector to extract edges, then maps those edges to the specified colors to produce stylized line art.
def make_line_art(img, kernel_type, fg_color, bg_color): if kernel_type == 'Prewitt': edge_img = prewitt_edge_detector(img) elif kernel_type == 'Sobel': edge_img = sobel_edge_detector(img) else: edge_img = scharr_edge_detector(img) line_art = recolor_image(edge_img, fg_color, bg...
def generateAlist(team, pathToDict, prefix): a_list = [] for a in list(team.keys()): aID = findID(a, pathToDict, prefix) a_list.append(aID) sort_nicely(a_list) return a_list def generateSlist(team, pathToDict, prefix): s_list = set() # s_list = [] for a in team.keys(): for i in range(len(team[a])): #...
The function `generateASMlists` generates three lists (a_list, s_list, m_list) by calling `generateAlist`, `generateSlist`, and `generateMlist` with specified prefixes and parameters, then returns them collectively.
def generateASMlists(team, pathToDict, a_prefix, s_prefix, m_prefix): a_list = generateAlist(team, pathToDict, a_prefix) s_list = generateSlist(team, pathToDict, s_prefix) m_list = generateMlist(team, pathToDict, m_prefix) return a_list, s_list, m_list
def init_allStates(num_a, num_s, teamTime,teamTimeID,relation_as, row_prefix, col_prefix, a_list, s_list, pathToDict): ''' find all possible combinations for initial timestep returns list of as_matrix arrays ''' # actionDict = action2str(num_a, num_s, teamTime,teamTimeID,relation_as, row_prefix, col...
The code generates an initial transition rule for a system with multiple agents and states. It constructs a string representing the transition from time `t=0` to `t+1`, incorporating probabilities, agent actions, state updates, and agent counts. The function calculates probabilities for each state, normalizes them, and...
def initTransition(numASM, teamTime,teamTimeID, allStates, allStates_dict, relation_as, prefixList, a_list, s_list, probDict, pathToDict): ''' [initial] t = 0 -> p1: (a1_s1 = 1) & (a2_s1 = 1) & (t' = t+1) + ... ''' num_a, num_s, num_m = numASM row_prefix, col_prefix, m_prefix =...
def allStates_asm(numASM, relation_as,relation_ms_no, allStates, probDict): '''given all a_s states and m states, generate a nested dictionary {state a_s:{state m: probability}}''' num_a, num_s, num_m = numASM allStates_dict = {} measZero_dict = measZero_all(numASM, relation_ms_no, allStates, probDict) ...
The function `allStates_next2str` generates a formatted string representing probabilistic next states in a system, combining agent-sensor (a_s) and machine (m) states. It uses a dictionary of states and their probabilities, iterating through each state to construct lines like `"0.3: (a1_s1' = 0) & ... & (m1' = 0)"`, ag...
def allStates_next2str(numASM, a_list, s_list, relation_as,relation_ms_no, row_prefix, col_prefix, teamTimeID, probDict): ''' Generates entire string for next states (the stuff after the arrow ->) Example: 0.3: (a1_s1' = 0) & (a1_s2' = 0) & (a1_s3' = 0) & (a2_s1' = 0) & (a2_s2' = 0) & (a2_s3' = 1) & (m1' =...
def probConstants(probDict): ''' create string that looks like: const double P1 = 0.9; const double P2 = 0.8; const double P3 = 0.7; ''' probStr = '' for p in list(probDict.keys()): probStr += 'const double ' + p + ' = ' + str(probDict[p][0]) + '; \n' return probStr def timeCon...
The function constructs a Markov Decision Process (MDP) module by integrating agent-sensor/measurement-sensor relationships, initial states, and transition probabilities. It combines constants, state definitions, and action-time logic into a PRISM-compatible model, using input parameters to define relationships, probab...
def constructKGModule(actions, timeDict, allStates_dict, numASM, prefixList, a_list, s_list, teamTime, relation_as, relation_ms,probDict,pathToDict,missionLength): num_a, num_s, num_m = numASM row_prefix, col_prefix, m_prefix = prefixList # add comment about relationship matrices comments = "// agent-s...
def get_last_state(): try: global last_state_data with open("last_state.json", 'r') as file: last_state_data = json.load(file) return last_state_data['last_category'], last_state_data['last_asin'] except: return "Electrical Goods", None def get_excel_file_path(main_ca...
The main task of the code is to automate extracting product data from Amazon.de using Selenium, processing ASINs from an Excel file, and saving extracted information into a workbook. It navigates product pages, handles cookies, waits for elements, logs errors, and sends the results via email, while managing workbook op...
def main(driver): category, last_asin = get_last_state() try: excel_file_path = get_excel_file_path(category) if excel_file_path: try: asins = load_excel_workbook(last_asin, excel_file_path) workbook, worksheet, row_index, excel_...
def scatter_sum(src: torch.Tensor, index: torch.Tensor, dim: int = -1, out: Optional[torch.Tensor] = None, dim_size: Optional[int] = None) -> torch.Tensor: index = broadcast(index, src, dim) if out is None: size = list(src.size()) if dim_size is not None: ...
The function `scatter` distributes values from the source tensor `src` into the output tensor `out` at indices specified by `index` along the given dimension `dim`, applying a reduction operation (e.g., sum, mean, min, max). It aggregates values from `src` into `out` based on `index`, with `dim_size` defining the outpu...
def scatter(src: torch.Tensor, index: torch.Tensor, dim: int = -1, out: Optional[torch.Tensor] = None, dim_size: Optional[int] = None, reduce: str = "sum") -> torch.Tensor: r""" | .. image:: https://raw.githubusercontent.com/rusty1s/pytorch_scatter/ master/docs/source/_f...
def containsIterative(array: List[Comparable], value: Comparable) -> bool: min = 0 max = len(array)-1 while min <= max: middle = (min + max) // 2 if array[middle] < value: min = middle + 1 elif array[middle] > value: max = middle - 1 else: ...
The main task of the code is to test three functions—containsIterative, containsRecursive, and firstIndexOf—using assertions. It verifies if these functions correctly identify element presence (True/False) or locate the first occurrence index in arrays, using both integer and string test cases. The code ensures the fun...
def main(): integerTestArray = [1, 3, 5, 7, 9] assert containsIterative(integerTestArray, 4) == False assert containsIterative(integerTestArray, 7) == True assert containsRecursive(integerTestArray, 0) == False assert containsRecursive(integerTestArray, 9) == True stringTestArray = ["cat", "ca...
def get_scan_stats(filepath, map_grid=None): n_stats = len(stats_list) try: with h5py.File(filepath, mode="r") as my_file: pass except: print(f"CANNOT OPEN CORRUPT OR NON-EXISTING FILE: {filepath}") with h5py.File(filepath, mode="r") as my_file: tod_ind = np.array(my_...
The function processes observational data by generating a map grid, reading scan data from HDF5 files, computing power spectra, and compiling statistical results into a structured array for further analysis. It initializes parameters based on input metadata, constructs spatial grids, extracts scan statistics, calculate...
def get_obsid_data(obsid_info): scans = obsid_info.scans fieldname = obsid_info.field l2_path = obsid_info.l2_path ## set up map grid info = patch_info[fieldname] if fieldname == "NCP": field_centre = [0, 0] else: field_centre = np.array(info[:2]).astype(float) map_r...
def _check_version(version): version = Version(version.lstrip('v')) if version not in Spec('>=0.4.11'): raise ValueError("py-solc-x does not support solc versions <0.4.11") return "v" + str(version) def _get_platform(): if sys.platform.startswith('linux'): return "linux" if sys.platf...
The function installs a specified version of the Solidity compiler (solc) for different operating systems (Linux, macOS, Windows), verifies the installation by checking the binary's version, sets the active solc version if not already defined, and outputs the installation path and success message.
def install_solc(version, allow_osx=False): version = _check_version(version) platform = _get_platform() if platform == 'linux': _install_solc_linux(version) elif platform == 'darwin': _install_solc_osx(version, allow_osx) elif platform == 'win32': _install_solc_windows(versi...
def _select_pragma_version(pragma_string, version_list): comparator_set_range = pragma_string.replace(" ", "").split('||') comparator_regex = re.compile(r"(([<>]?=?|\^)\d+\.\d+\.\d+)+") version = None for comparator_set in comparator_set_range: spec = Spec(*(i[0] for i in comparator_regex.finda...
This function identifies a compatible Solidity compiler version based on a given pragma string, installs it if specified, and returns the selected version.
def install_solc_pragma(pragma_string, install=True): version = _select_pragma_version( pragma_string, [Version(i[1:]) for i in get_available_solc_versions()] ) if not version: raise ValueError("Compatible solc version does not exist") if install: install_solc(version) ...
def _select_pragma_version(pragma_string, version_list): comparator_set_range = pragma_string.replace(" ", "").split('||') comparator_regex = re.compile(r"(([<>]?=?|\^)\d+\.\d+\.\d+)+") version = None for comparator_set in comparator_set_range: spec = Spec(*(i[0] for i in comparator_regex.finda...
This function sets the Solidity compiler version based on a pragma string, checks for installed compatibility, raises an error if no match is found, updates a global version variable, and optionally prints the version or alerts about newer available versions.
def set_solc_version_pragma(pragma_string, silent=False, check_new=False): version = _select_pragma_version( pragma_string, [Version(i[1:]) for i in get_installed_solc_versions()] ) if not version: raise SolcNotInstalled( "No compatible solc version installed. " + ...
def _normalize_path(self, path, prefix): if not path.startswith(os.path.sep): path = os.path.join(os.path.sep, path) normpath = os.path.normpath(path) return os.path.join(prefix, normpath[1:]) def get_jail_path(self): self.match_jail() return self.jpath def tempfile(s...
This function transfers a local file to a remote jail by normalizing the destination path, using a temporary file to store the transferred data via the parent class's put_file method, then copying the temporary file to the specified remote path within the jail.
def put_file(self, in_path, out_path): ''' transfer a file from local to remote jail ''' out_path = self._normalize_path(out_path, self.get_jail_path()) with self.tempfile() as tmp: super(Connection, self).put_file(in_path, tmp) self._copy_file(tmp, out_path)
def _normalize_path(self, path, prefix): if not path.startswith(os.path.sep): path = os.path.join(os.path.sep, path) normpath = os.path.normpath(path) return os.path.join(prefix, normpath[1:]) def get_jail_path(self): self.match_jail() return self.jpath def tempfile(s...
The code fetches a file from a remote location to a local path by normalizing the input path, copying the file to a temporary location, and then transferring it to the specified output path using the parent class's fetch_file method.
def fetch_file(self, in_path, out_path): ''' fetch a file from remote to local ''' in_path = self._normalize_path(in_path, self.get_jail_path()) with self.tempfile() as tmp: self._copy_file(in_path, tmp) super(Connection, self).fetch_file(tmp, out_path)
def _strip_sleep(self, cmd): # Get the command without sleep cmd = cmd.split(' && sleep 0', 1)[0] # Add back trailing quote cmd = '%s%s' % (cmd, "'") return cmd def _strip_sudo(self, executable, cmd): words = shlex.split(cmd) while words[0] == executable or words[...
The code executes a command within a jail environment, handling sudo and sleep flags. It constructs the command with the specified executable, strips unnecessary parts, and appends jail-specific connectors. If sudo is involved, it uses a plugin to build the command. Finally, it delegates execution to the parent class's...
def exec_command(self, cmd, in_data=None, executable='/bin/sh', sudoable=True): ''' run a command in the jail ''' slpcmd = False if '&& sleep 0' in cmd: slpcmd = True cmd = self._strip_sleep(cmd) if 'sudo' in cmd: cmd = self._strip_sudo(executable, c...
def is_legal_move(self, column, state): """ Checks if a move (column) is a legal move. """ for i in range(6): if state[i][column] == ' ': return True return False def game_is_over(self, state): """ Checks if the game is over by checking...
This function implements the minimax algorithm with optional alpha-beta pruning to determine the optimal move for the current player in a game. It evaluates all legal moves recursively, considering the game state and depth, and returns the best move along with its associated value. Alpha-beta pruning optimizes the sear...
def minimax(self, depth, state, curr_player, use_alpha_beta, alpha=-float('inf'), beta=float('inf')): """ Implements the minimax algorithm with optional alpha-beta pruning to find the best move and its associated value. Returns the best move (as a column number) and the associated value. ...
def get_coords(root): coords = [] objects = root.findall('.//object') for object_ in objects: x_min = int(object_.find('bndbox').find('xmin').text) y_min = int(object_.find('bndbox').find('ymin').text) x_max = int(object_.find('bndbox').find('xmax').text) y_max = int(object_....
The code performs image and XML annotation augmentation by rotating and translating images, saving modified images and corresponding XML files with new names. It handles original, rotated (in two directions), and translated (four directions) versions, updating coordinates in XMLs. Bounding boxes are optionally saved in...
def perform_augmentation(images_folder, xmls_folder, im_dest_folder, xmls_dest_folder, rot=True, trans=True, bounded_folder=None): xmls_list = os.listdir(xmls_folder) total = len(xmls_list) log('xmls list acquired') stroke_width = 2 upper_limit = 50 lower_limit = 20 angle_min = 1 ang...
def partieSuperieur(A: Coordonne): penup() goto(A.abcisse, A.ordonne) pendown() forward(901) A.abcisse = 451 debutRec = Coordonne(xcor(), ycor()) left(90) forward(55) left(90) countTwo = 271 forward(countTwo) A.abcisse = (450/5)*2-1 # tick = 0 left(90) ...
The code's main task is to draw a structured figure using Turtle graphics, starting with a roof, creating left and right ears (possibly decorative elements), positioning a tableau, saving a starting point, drawing door bars, returning to the origin, and constructing left/right window sections and a base rectangle to fo...
def principal(): partieSuperieur(Coordonne(A.abcisse, A.ordonne)) creerOreilleGauche(A) tableau(Coordonne(xcor(), ycor())) pointDepart = Coordonne(xcor(), ycor()) creerOreilleDroit(Coordonne(xcor(), ycor())) barresPortes(Coordonne(xcor(), ycor())) penup() goto(pointDepart.abcisse, pointD...
def reconnect_with_peers(self): self.arrNodes = [] for i in self.nodes_outbound: self.disconnect_with_node(i) self.join_p2p() def peers_validators(self): peersValidators = [] for node in self.nodes_outbound: if (node.host == '127.0.0.1' and node.p...
This function processes incoming node messages to handle blockchain synchronization. It checks for specific data patterns like node lists, blockchain hashes, and download requests. If three identical blockchain hashes are received, it triggers a blockchain download. It also reconnects to peers if validation fails, ensu...
def node_message(self, node, data): #print("node_message (" + str(self.port) + ") from " + str(node.port) + ": " + str(data)) if (node.host == '127.0.0.1') and (node.port == 9000): if 'nodes:' in data[:6]: #try: nodesArray = ast.literal_eval(data[6:]) ...
def augmentedMatrix(A, b): augmentedMatrix = [] Acopy = valueMatrix(A) for i in range(len(Acopy)): Acopy[i].append(b[i]) augmentedMatrix.append(Acopy[i]) return augmentedMatrix def printMatrix(Matrix): for row in Matrix: print(row) def gaussianPartialPivoting(AbParam, n, p...
The main task of the code is to solve a system of linear equations using Gaussian elimination with partial pivoting. It constructs an augmented matrix from a given coefficient matrix `A` and vector `b`, then applies Gaussian substitution with partial pivoting to compute the solution vector `x`. The code prints the orig...
def main(): A = [ [2, -1, 0, 3], [1, 0.5, 3, 8], [0, 13, -2, 11], [14, 5, -2, 3] ] b = [1, 1, 1, 1] Ab = augmentedMatrix(A, b) print("Matrix A: ") printMatrix(A) print("Vector b: ") printMatrix(b) print("Matrix Ab: ") printMatrix(Ab) print...
def objective_func_board(self, state, player): res = 0 for i in range(self.bSize): for j in range(self.bSize): if state[i][j] == player: res -= self.objective_func(state, player, (i, j)) elif state[i][j] != 0: res += sel...
This function performs a local search decision-making process to select between an initial state and a randomized state based on their objective values. It checks if the initial state is not a winning state, enforces a time limit, and recursively applies local search if the randomized state's objective is worse. The go...
def local_search_decision(self, init_state, randomed_state, player, s): decided_state = [[0 for i in range(self.bSize)] for j in range(self.bSize)] init_obj = self.objective_func_board(init_state, player) rand_obj = self.objective_func_board(randomed_state, player) print(1) ...
def init_args(): ''' initializes arguments from command line ''' kwvars = util.d({}) parser = argparse.ArgumentParser(description='manages backups') parser.add_argument('--test',action='store_true',default=False,\ help="run in test mode, prints result to terminal") parser.add_arg...
(The main task of the code is to execute a backup process by initializing arguments, configuration, and logging, then triggering the backup operation via `make_backup()`. It starts by printing a backup initiation message and sequentially prepares necessary parameters and settings before performing the backup.)
def main(): ''' do the thing ''' print("starting backup...") kwvars = init_args() kwvars.config = init_config() init_log(kwvars) kwvars = make_backup(kwvars)
def get_boundaries(arr: np.array, reduction: float) -> np.array: """Retrieves the boundaries given a reduction size""" unique = np.unique(arr.copy()) x = unique[:-1] y = unique[1:] boundary = (x + y) / 2 return boundary[::reduction] def info_gain(s_all: np.array, bound) -> float: """Calcul...
The function identifies the optimal feature and threshold to split data for a decision tree, maximizing information gain. It iterates through features (excluding the label column), evaluates potential splits using `get_boundaries`, calculates information gain with `info_gain`, and stores the best split parameters—featu...
def find_split(data: np.array, reduction: float) -> dict: """Find best place to split data.""" top_gain = 0 split = {} for col in range(0, data.shape[1] - 1): # don't include last col: label col for boundary in get_boundaries(data[:, col], reduction): temp_gain = info_gain(data[:, [...
def find_split(data: np.array, reduction: float) -> dict: """Find best place to split data.""" top_gain = 0 split = {} for col in range(0, data.shape[1] - 1): # don't include last col: label col for boundary in get_boundaries(data[:, col], reduction): temp_gain = info_gain(data[:, [...
The function recursively constructs a decision tree by splitting data based on information gain, stopping when reaching max_depth or encountering uniform labels. It creates left/right branches, recursively processes subsets of data, and combines results into a nested dictionary structure representing the tree.
def tree_learn( data: np.array, depth: int, tree: dict, max_depth: int, reduction: float ) -> dict: """Creates a decision tree based on a set of data and a max_depth parameter data : data to parse depth : keeps track of depth of decision tree tree : dictionnary of dictionnaries : this is the decisio...
def _create_temp_dir_for_sftp_files(self, temp_path: str) -> None: if not os.path.exists(temp_path): try: os.makedirs(temp_path) except OSError: raise Exception( "Creation of the directory %s failed" % temp_path) def authenticate_to_sft...
The code fetches XML reports from an SFTP server, downloads files with a specific prefix, parses their content, saves parsed data with an optional requisition ID, and deletes files in production environments. It uses a temporary directory for storage, handles exceptions during file operations, and closes the SFTP conne...
def fetch_reports(self, requisition_id: Optional[str] = None) -> None: ''' Fetches report from SFTP server Parameters: requisition_id -> str (Optional) Returns: None ''' local_root_dir = os.path.join(self.base_dir, 'labportalen', 'sample_report') ...
def create_limit_alltimeframe_orders(self): atrs = {} last_crypto_price = float(self.redis_tick_data.get(self.pair).decode()) last_krypton_price = self.krypton.get_last_price(self.pair) redis = self.redis_atr for time_frame in ALL_TIMEFRAMES: atrs[time_frame] = float(...
This code creates a limit order with adjusted price and volume based on market conditions. It checks order book depth, compares crypto/krypton prices, applies noise, adjusts order side and price if needed, calculates volume based on pair type, adds randomness, and places the order via krypton's API.
def create_limit_tick_timeframe_order(self,side): try: if self.redis_orders.get_len_buy_order() or self.redis_orders.get_len_sell_order() < MINIMUM_ORDER_IN_ORDER_BOOK/2: self.create_limit_alltimeframe_orders() except: self.create_limit_alltimeframe_orders() ...
def create_limit_alltimeframe_orders(self): atrs = {} last_crypto_price = float(self.redis_tick_data.get(self.pair).decode()) last_krypton_price = self.krypton.get_last_price(self.pair) redis = self.redis_atr for time_frame in ALL_TIMEFRAMES: atrs[time_frame] = float(...
The function creates a market order opposite to the nearest existing order (buy/sell flip) using its price and quantity, then generates a limit order for the tick timeframe.
def create_market_order(self): self.create_limit_alltimeframe_orders() nearest_order_id = self.get_nearest_order_id() nearest_order = json.loads(self.redis_orders.get(nearest_order_id).decode()) price = nearest_order["price"] quantity = nearest_order["amount"] krypton_ord...
def create_limit_alltimeframe_orders(self): atrs = {} last_crypto_price = float(self.redis_tick_data.get(self.pair).decode()) last_krypton_price = self.krypton.get_last_price(self.pair) redis = self.redis_atr for time_frame in ALL_TIMEFRAMES: atrs[time_frame] = float(...
The code's main task is to manage trading orders by canceling existing ones, creating limit orders across all timeframes, and continuously monitoring to cancel outlier orders while placing new market orders in an infinite loop. This ensures dynamic order adjustment and real-time trade execution.
def run(self): self.krypton.cancel_all_orders() # can be uncomment or comment self.create_limit_alltimeframe_orders() while True: self.cancel_outlier_orders() self.create_market_order()
def step1(subfolder): for topic_name in topic_names: try: df = pd.read_csv(os.path.join(folder_path, subfolder, topic_name + ".csv")) if topic_name == 'imu-data': # remove noise from acceleration try: df['linear_acceleration.x_filtered'] = lowpass_...
The code processes CSV files in specified subfolders by filtering relevant files, applying a sequence of data processing steps (step1-step4), and saving the results. It skips subfolders with no matching files.
def process_csv(): for subfolder in subfolders: print(f'\n[Processing] {subfolder}') temp = os.listdir(os.path.join(folder_path,subfolder)) temp = [i.split('.')[0] for i in temp] temp = [i for i in topic_names if i in temp] # print(temp) if temp != []: mer...
def _get_session_stimulus(self, data_set): """ Args: data_set: (map) Subset of alldat Returns: stims[nTrials x 3] bias: constant with ones stim_left: contrast level for the right stimulus. stim_right: con...
The code processes session data by extracting and structuring specific features (stimulus, response, contrast difference, spike rates, trial types) from valid sessions into a dictionary array. It computes delta contrast, retrieves spike data for two regions, calculates firing rates, and assigns trial types for each ses...
def select_data(self, data): valid_session_data = data[self.valid_sessions_idx] output_data = np.zeros(self.n_valid_sessions, dtype=object) for session_idx in range(self.n_valid_sessions): session_data = valid_session_data[session_idx] outpu...
def chat_init(db: DatabaseManager, cookie_manager: CookieManager) -> Set[Union[dict, ThreadManager]]: user = db.get_user(st.session_state["username"]) thread_id = "" # Create thread if one doesn't exist. try: if not user["threads"]: thread_id = create_thread(st.secrets["openai"]["ap...
The code manages a chat session by initializing a user and thread, displaying chat history, and prompting user input while tracking usage via a markdown display.
def chat(db: DatabaseManager, cookie_manager: CookieManager): user, thread = chat_init(db, cookie_manager) display_chat_history() user_prompt(db, cookie_manager, user, thread) st.markdown(f"Current Usage:`{user["usage"]}`")
def get_indication(): file_type = client_socket.recv(BUFFER_SIZE).decode() client_socket.send(ACCEPT.encode()) return file_type def insert_new_folder(folder_path, client_socket): #file transfer sequence print('getting file') file_data = client_socket.recv(BUFFER_SIZE).decode() client_socket....
This function processes client updates by receiving and handling file operations (create, delete, move) based on received data. It iterates 'size' times, communicates with the client via sockets, updates connected users, and performs file system operations like creating directories, making files, or moving/deleting the...
def get_updates_protocol(size): try: index = int(size) except: return 0 #iterations on update notes for x in range(index): print('new update') update = client_socket.recv(BUFFER_SIZE).decode() print('got update') client_socket.send(ACCEPT.encode()) ...
def get_indication(): file_type = s.recv(BUFFER_SIZE).decode() s.send(ACCEPT.encode()) return file_type def insert_new_folder(folder_path, client_socket): #file transfer sequence print('stuck 1') file_data = client_socket.recv(BUFFER_SIZE).decode() client_socket.send(ACCEPT.encode()) whi...
This function processes file system updates over a network by receiving update data (created/moved/deleted files/folders), applying changes to the local file system, and sending acknowledgment responses. It handles folder creation, file operations, and error recovery via socket communication.
def get_updates_protocol(size): try: index = int(size) except: return 0 for x in range(index): print('new update stuck 1') update = s.recv(BUFFER_SIZE).decode() s.send(ACCEPT.encode()) update_info = update.split(',') #update type can be c-created m...
def api_challenge(self): head = {"user-agent": f"Instagram 172.16.31.10.000 Android"} req = requests.get(f"https://i.instagram.com/api/v1{self.path}", headers=head, cookies=self.coo) #print(req.text, req.status_code) if "phone_number" in req.json()["step_data"]: try: ...
This code authenticates an Instagram user via API by sending login credentials, handles 2FA challenges by prompting user input, and stores session cookies upon successful login.
def api_login(self): head = {"user-agent": f"Instagram 172.16.31.10.000 Android"} data = { "jazoest": "22452", "phone_id": self.loginuuid, "enc_password": f"#PWD_INSTAGRAM:0:0:{self.password}", "username": self.username, "guid": self.loginuuid,...
def web_challenge(self): head = { 'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9', 'accept-encoding': 'gzip, deflate, br', 'accept-language': 'en-US,en;q=0.9', "...
This code performs Instagram web login using session cookies and CSRF token, sends POST request with username/password, handles login success by storing session ID, and manages 2FA challenges by prompting user input for security verification steps.
def web_login(self): self.web_head = { "accept": "*/*", "accept-encoding": "gzip, deflate, br", "accept-language": "en-US,en;q=0.9", "content-length": "267", "content-type": "application/x-www-form-urlencoded", "cookie": "ig_did=089749...
def random_proxy(self): prox = random.choice(proxies) return {"https": f"{my_proxy}{prox}", "http": f"{my_proxy}{prox}"} def claimed(self, sessionid, attempts, rs): self.username_claimed = True open(f"{target}.txt", "a").write(f"\nusername: {target}\nsessionid: {sessionid}\nattempts: {at...
This code sends a POST request to Instagram's API to set a username using a session ID, checks the response for status/conditions, and triggers actions like claiming a username, incrementing counters, or handling errors such as existing usernames, login requirements, or rate limits.
def set_username(self, sessionid): head = { "user-agent": f"Instagram 172.16.31.10.000 Android", "cookie": f"sessionid={sessionid}" } req = self.reqs.post("https://i.instagram.com/api/v1/accounts/set_username/", headers=head, data=self.data, proxies=self.random_proxy()) ...
def grab_proxies(self): req = requests.get("https://api.proxyscrape.com/v2/?request=getproxies&protocol=socks4&timeout=10000&country=all&ssl=all&anonymity=all") #print(req.text, req.status_code) if req.status_code==200: open("proxies.txt", "w").write(f"") for x in req.tex...
This code initializes a class to handle user login and session management in different modes. It configures proxies, authenticates via API/web, manages session IDs, generates usernames, validates inputs, and stores session data. The 'mode' parameter determines login type (normal vs. two-session), with proxy settings an...
def __init__(self, mode): self.done, self.error, self.set, self.next_check, self.run, self.username_changed = 0, 0, 0, 10, True, False self.sessions = [] self.users = [] self.loginuuid = str(uuid.uuid4()) self.reqs = requests.Session() if mode=="0": if s.setti...
def run_process(self): '''Moves the next process from ready to running. Sets the time that the process will be preempted at.''' self.admit_processes() if not self.unfinished_processes: # Returns as there are no processes left to run return if self.number_ready_pro...
This function manages process scheduling by checking if the current running process has completed, handling preemption based on priority or time limits, and transitioning processes between running, ready, blocked, and finished states while ensuring a new process is initiated when needed.
def check_running_process(self): '''Checks to see if currently running process (`self.running_process[0]` is complete). If so moves that process to `self.finished_processes` and moves new process into `self.running_process`''' # Runs a process if none are currently running if len(self.running_pr...
def minimax(self, board: list, depth: int, alpha: int, beta: int, maximizingPlayer: bool) -> tuple: valid_columns = self.get_valid_columns(board) terminal = self.is_terminal(board) if depth == 0 or terminal: if terminal: if self.validate_winning_move...
The main task of the code is to determine the AI's optimal move using the minimax algorithm on a game board. It selects a column for placement, validates the move, and updates the game state. If the minimax result is invalid, it randomly chooses a valid column. The function also prints the selected column and score, th...
def ai_move(self, board: list): if not globals.game_over: (column, score) = self.minimax(board, gb.GAME_BOARD_ROWS - 1, self.NEG_INFINITY,self.INFINITY, True) # If the game board is not full. valid_columns = self.get_valid_columns(board) if len(va...
def structure_check(value: str, test_string: str='') -> bool: """ Check if value contains the name of a structure in TITLES. """ for key, list_pseudonyms in conf.TITLES.items(): for title_value in list_pseudonyms: if title_value.casefold() in value.casefold(): if conf.DEBUG: print(f'title_value is: {t...
This function extracts data from an Excel sheet by locating a cell matching a given string value, adjusting column positions based on context (e.g., structure headers), and returning the corresponding cell's value. It handles edge cases like duplicate entries, structure constraints, and special formatting rules, priori...
def data_extractor(cell_container: list, sheet, value: str, fraction: int): """ This is THE function to retrieve data given a string value to match. The data is extracted via coordinates rather than directly from cell_container for the purposes of clarity to the user. """ column_shift = fraction cell_of_interest =...
def fermatTest(n): for i in range (0,20): r=random.randint(2,n-2) if pow(r,n-1,n)!=1: return False return True def nextPrime(lastPrime): global index global length global primes if(primes[-2]>=lastPrime): if primes[index]==lastPrime: index+=1 ...
This function decomposes a number `n` into its prime factors by checking divisibility starting from 2. If no factors are found up to √n, it assumes `n` is prime. It uses a Fermat primality test under specific conditions to handle large numbers, adding all identified prime factors to a global set `locatedPrimes`. The ma...
def numPrime(n): if(n<2): return global locatedPrimes prime=2 count=0 tested=False while prime<n**0.5+1: if((not tested) and count>10000 and count>n**0.3): if(fermatTest(n)): return 1 else: tested=True if(n%prime==0)...
def get_file_name(self): if self.model == "normal": file_name = "output/eval_" + self.v + "_" + self.n + "_" + self.d + ".txt" else: file_name = "output/eval_myModel_" + self.v + "_" + self.n + "_" + self.d + ".txt" # May have to change that name later return file_name ...
The main task of the code is to generate an evaluation file by appending calculated metrics—accuracy, precision, recall, F1 scores, and macro/weighted F1—to an existing file. It retrieves the file name, reads associated trace data, checks the file's existence, and writes the metrics in a formatted string. The method en...
def create_evaluation_file(self): file_name = self.get_file_name() self.read_affilated_trace_file() if os.path.exists(file_name): message = str(self.accuracy) + "\n" + self.convert_lang_dict_to_str( self.precision_dict) + "\n" + self.convert_lang_dict_to_str(self.reca...
def get_spot_balance(): to_ret = {} params = "timestamp=" + str(get_server_time()) resp = make_request("https://api.binance.com/api/v3/account?" + params + "&signature=" + generate_signature(params), api_binance=True) spot = loads(resp['response']) spot_list = [] for coin in spot["balances"]: ...
The main task of the code is to initialize configurations, clear a file for order data, retrieve current spot balance, fetch open orders using the balance, and obtain historical order data from Binance, likely for tracking or managing trading activities.
def main(): Config() f = open("binance/order-wallet.txt", "w") f.write("") f.close() balance = get_spot_balance() get_open_orders(balance) get_order_history()
def get_order_history(): total_sell = 0 total_buy = 0 total_comm = 0 type_order = "" params = "timestamp=" + str(get_server_time()) + "&symbol=" + Config.settings['binance']['symbol'] resp = make_request("https://api.binance.com/api/v3/myTrades?" + params + "&signature=" + generate_signature(par...
The main task of the code is to monitor Binance trading orders, log execution details (last order type, gain, fees), and automatically place new limit orders (BUY/SELL) based on open order status and predefined config settings. It uses Binance API requests with timestamp/signature validation, looping with set intervals...
def main(): basicConfig( filename=None, # "bot.log", format="%(asctime)s|%(levelname)s|%(filename)s:%(lineno)s|%(message)s", level=INFO) Config() quantity = str(Config.settings['binance']['quantity']) count = 0 while True: type_order, gain, tot_comm = get_order_histo...
def find_order(typology, symbol, price, quantity): to_ret = { 'order_open': False, 'order_id': 0 } query_string = "timestamp=" + str(get_server_time()) resp = make_request("https://api.binance.com/api/v3/openOrders?" + query_string + "&signature=" + generate_signature(query_string)) ...
This function performs order operations on Binance via API: checking for existing orders, inserting new limit orders with signatures, and deleting orders. It handles 'check', 'insert', and 'delete' operations, validates orders, constructs signed requests, and exits with status codes. Error handling ensures exceptions t...
def do_action(operation, typology, symbol, price, quantity): try: Config() if operation == 'check': if find_order(typology, symbol, price, quantity)['order_open']: info("ORDER FOUND") exit(1) else: info("ORDER NOT FOUND") ...
def train(train_epoch_state: TrainEpochState, train_epoch_spec: TrainEpochSpec): model = train_epoch_state.model dataloader = train_epoch_state.train_dataloader loss = train_epoch_spec.loss optimizer = train_epoch_state.optimizer device = train_epoch_spec.device_id model.train() for i, (in...
(The main task of the code is to perform a multi-epoch training loop for a machine learning model, validating after each epoch, serializing training state, visualizing progress periodically, and saving results as a pickle file. It initializes training configurations, iterates through epochs, executes training/validatio...
def do_training(train_run: TrainRun, state: TrainEpochState, device_id): next_visualization = time.time() train_epoch_spec = TrainEpochSpec( loss=train_run.train_config.loss, device_id=device_id, ) factories = Factories(model_factory=ModelFactory(), data_factory=DataFactory()) seria...
def check_song_with_delay(mode, user, thread): song = user.sp.currently_playing() if song and song['item']: intro_left = 30000 - song['progress_ms'] if intro_left > 0: delay = intro_left else: remaining = song['item']['duration_ms'] - song['progress_ms'] ...
This code monitors for song changes in a user's music session, updates state tracking, handles playback mode logic (curate vs. normal), and triggers actions for listeners. It polls for song changes, determines next tracks based on queue status, plays/synchronizes songs, and manages controller activity. If the song chan...
def run(self, user, current_song_id): if user.hasActivePoller: return False user.hasActivePoller = True user.pollingThread = str(self.thread.ident) user.save() try: song_changed = polling.poll( # Won't work if user is a listener! ...
def make_dir_out(self): self.make_dir(self.dir_out) def list_input_files(self): return os.listdir(self.dir_in) def audio_to_txt(self): path = os.path.join(self.dir_in, self.filename) path = subtitles.check_path(path) path_wav = subtitles.audio_to_wav(path) sound = AudioSe...
The main task of the code is to convert audio and video files from the input directory into text subtitles. It processes supported formats (e.g., .mp3, .wav, .mp4) by calling `audio_to_txt()` or `video_to_txt()`, handles errors silently, and deletes the `__pycache__` directory afterward.
def subs_for_dir(self): # convert all audio files in /in/ to text print('Please wait! Files are converting to subtitles:') self.make_dir_out() files = self.list_input_files() for index, cur_file in enumerate(files, start=0): print(cur_file) try: se...
def _tile(self, row, col): if self._onBoard(row, col): return self._tiles[col + self._numRows * row] return None def _getHint(self, row, col): hint = 0 for c in (col - 1, col, col + 1): for r in (row - 1, row, row + 1): t = self._tile(r, c) ...
The code initializes a game board by resetting all tiles, placing mines randomly, calculating hints for non-mine tiles based on adjacent mines, and activating the playing state. It first clears existing mines and hints, then distributes the specified number of mines across the grid, ensuring no overlaps. Finally, it co...
def setBoard(self): for t in self._tiles: t.setHasMine(False) t.setHint(-1) # Place the mines. mines = self._nMines; self._remaining = self._numRows * self._numCols - mines while mines > 0: col = random.randint(0, self._numCols - 1) ...
def find_vehicle_infraction(self): """ The goal of this function is to find a vehicle to perform an infraction. Argument : None Returns: None """ position = random.choice([0, 1, 2, 3]) direction = ["right", "down", "left", "up"] # We choose a random dir...
The main task of the code is to initialize a simulation window using Pygame, set up an infinite loop for real-time updates, handle events like vehicle/pedestrian infractions, manage traffic light changes, spawn vehicles, and render dynamic elements such as vehicles, pedestrians, and infraction alerts on the screen.
def main_screen(self): """ The goal of this function is to set the window of the program, the initial screen and the infinite loop of the simulation. Argument : None Returns: None """ # The size of the window is settled screenWidth = 859 screenHeight = 70...
def up_managers(managers: Dict[str, IPvAnyAddress]) -> Union[str, None]: result = None for name, address in managers.items(): result = up_manager(name, address) if result == None: return None node = list(managers.keys())[0] ip_address = managers[node] registry_result = u...
This function controls Docker swarm initialization and termination. It validates swarm options, then either brings up a swarm (starting managers/workers) or tears it down (stopping nodes). It handles errors during node operations and logs success/failure states, ensuring proper swarm management via SSH-accessible Docke...
def swarm_control( cluster_config: ClusterConfig, swarm_up: bool = False, swarm_down: bool = False, ) -> None: try: swarm_opts = SwarmOpts(swarm_up=swarm_up, swarm_down=swarm_down) except ValidationError as err: logger.error(f"invalid swarm option configuration: {err}") retur...
def min_max(self, g: GraphAlgo): global min_x, min_y, max_x, max_y min_x = min(list(g.Graph.listNode.values()), key=lambda n: n.pos[0]).pos[0] min_y = min(list(g.Graph.listNode.values()), key=lambda n: n.pos[1]).pos[1] max_x = max(list(g.Graph.listNode.values()), key=lambda n: n.pos[0])....
This code defines a 'display' method that initializes a game loop using Pygame. It handles user input (QUIT events, button clicks), fetches game data (Pokemons, Agents), renders the game screen with images and graphical elements, updates the display at 60 FPS, and executes an algorithm while the client is running. The ...
def display(self,g:GraphAlgo=None): button.fun = self.client.stop_connection self.min_max(g) try: while self.client.is_running() == 'true': pokemons = self.client.get_pokemons() pokemons_obj = self.algo.json_pokemons(pokemons) agent = self.algo.json_A...
def insert_action(): st.header("Insert Actions") st.write("Choose one table to insert from:") st.markdown("<p style='color:red'><strong>If you would like to select a different table, please deselect your current selection first.</strong></p>", unsafe_allow_html=True) buttons = ["Suppliers", "Pr...
This code creates a Streamlit web app allowing users to select CRUD operations (Insert, Update, Delete, Search). It displays an ERD image, manages session state to reset button states upon action changes, and routes to corresponding functions based on user selection, ensuring a dynamic and responsive interface for data...
def main(): st.title("End-User Web Application") st.image('frontend/ERD.png') # Prompt user for action choice action_choice = st.radio("Select an action to perform:", ["Insert", "Update", "Delete", "Search"], index=None) # Reset all button states when action_choice changes if st.sessio...
def update_query_values(self, query, table_name): """ Update values in an INSERT or UPDATE SQL query based on the column data types from the schema. :param query: The original SQL query. :param table_name: The table name to fetch schema details for. :return: The updated SQL quer...
The code's main task is to insert records into a hashed database by determining the appropriate database index based on the supplier name's hash or order ID parity. It processes SQL `INSERT` queries for different tables (`suppliers`, `products`, `order_details`, `orders`), extracts relevant data (e.g., supplier name, b...
def insert(self, query): """ Insert record into hashed database after hashing supplier name. """ # Getting table name match = re.search(r"INSERT INTO\s+([a-zA-Z0-9_]+)", query, re.IGNORECASE) if match: table_name = match.group(1) else: prin...
def parse_cfr_string(s,verbose=False): try: title = s.split()[0] for part in re.search(r'CFR(.*?(?P<part>(_|\d+|\b[IVXCL]+\b)))+',s,re.IGNORECASE).captures('part'): yield (title,part) except Exception: if verbose: print('Warning: Failed to parse CFR string "%s"' % s) ...
The function builds a mapping from XML part elements to CFR (title, part) tuples by analyzing document structure. It handles single/multiple CFR references and part elements, using "List of Subjects" tables and headers to resolve ambiguities. When conflicts arise between lstsub and header data, warnings are issued if v...
def build_part_cfr_map(root,verbose=False): """ Build a mapping from part elements to CFR (title,part) tuples. If document has one CFR reference an one part element then mapping is trivial. If document has multiple CFR references and/or multiple part elements, *try* to infer correct CFR for each par...
def build_part_cfr_map(root,verbose=False): """ Build a mapping from part elements to CFR (title,part) tuples. If document has one CFR reference an one part element then mapping is trivial. If document has multiple CFR references and/or multiple part elements, *try* to infer correct CFR for each par...
This function parses an XML tree representing regulatory text into a structured pandas DataFrame. It extracts paragraphs, headers, CFR metadata (titles, parts, sections), footnotes, and text content, handling formatting inconsistencies. It identifies legal content, splits paragraphs by newlines if requested, and applie...
def parse_reg_xml_tree(tree,nlp=None,extract_numbering=True,verbose=False, split_paragraphs=True): root = tree.getroot() part_cfr_map = build_part_cfr_map(root,verbose) paragraphs = [] header = [] part_element = None # Need to track part elements because they are not hiera...
def database_creater(zipcode, time_range): # makes databases for current forecast (time range from 0-14 days) # does not have hour intervals but could add them if necessdary (right now chooses one hour of the day) data_location = pd.DataFrame() # creates empty DataFrame data_current = pd.DataFrame() ...
The main task of the code is to create a weather information program that takes a user's zipcode, retrieves weather data for a specified date, allows date changes, and updates a database with formatted data. It includes a loop for user decisions: viewing data, adjusting dates, or exiting. The code interacts with databa...
def main(): print("\nWelcome to Whenever Weather!!!\n") zipcode = input("Please enter your zipcode: ") print() date = current_date porf = 0 # TO-DO: format output text with data wanted to display database_creater(zipcode, 1) while True: # FIX-ME: format for question? ...
def __create_optimizer(self): rho = self.volfrac * np.ones(self.num_elem) x = rho xmin = np.ones_like(rho) * self.rho_min xmax = np.ones_like(rho) # add theta variable if self.dim == '2D' or self.dim == '3D_layer' or self.dim == '3D_free': ...
This code performs optimization iterations using MAPDL, handling connection failures by restarting MAPDL, checking convergence based on stress change tolerance, updating the optimization state, and post-processing results including printability and greyness scores. It runs up to max_iter iterations, evaluates final res...
def run(self): try: self.mma except AttributeError: self.__create_optimizer() t0 = time.time() self.mapdl = pymapdl.launch_mapdl(jobname=self.jobname, run_location=self.res_dir.absolute(), override=True, start_timeout=200) self.mapdl.resume(fname=self.inputfile.abso...
def unfocus_edit(self): self._edit_type = None self.contents['footer'] = (self.footer_widget, None) self.set_focus('body') self.messagebox.set_text('') self.editbox.set_mask(None) def copy_by_key(self, key): if key in self._parsed_password: copy_text = self._p...
This method handles keypress events to perform actions like editing, deleting, searching, or toggling features based on key bindings. It checks the key's associated action, manages focus states, and triggers corresponding operations (e.g., confirm, cancel, copy, delete) or passes input to the focused widget. Special ca...
def keypress(self, size, key): logging.debug("ui keypress: {} {}".format(key, size)) action = config.keybindings.get(key) if action == 'cancel': self.unfocus_edit() elif self._edit_type == "copy": self.unfocus_edit() self.copy_by_key(key) elif ...
def next_color(self): if(len(self.move_list) % 2 == 0 ): return COLORS['white'] else: return COLORS['black'] def color_of_piece(cls, piece): return PIECES_COLOR[piece] def is_move_valid(self, srcx, srcy, dstx, dsty, prom_piece): if(not self.is_move_inbounds(srcx, ...
This function checks if any valid move exists for the current player by iterating through all pieces of the next color on an 8x8 board. It identifies pawns reaching promotion ranks, assigns promotion pieces (queen for pawns), and tests all possible moves using `is_move_valid()`. If any valid move is found, it returns `...
def is_move_available(self): color = self.next_color() for y1 in range(8): for x1 in range(8): piece = self.board.readfield(x1, y1) if(color == self.color_of_piece(piece)): if(piece == PIECES['wPw'] and y1 == self.board.RANKS['7']): ...
def _get_rivm(self, subdir: str = "rivm", subset: str = "aantallen_gemeente_per_dag"): """ Collects data from the RIVM, with an optional subset Parameters -------------- subdir : str Subdirectory for data storage, default "rivm" subset : str Option...
This method retrieves data from specified datasets (e.g., "rivm", "stocks", etc.) by delegating to private methods. If "all" is specified, it aggregates data from all available datasets into a dictionary of DataFrames. Parameters are passed to underlying methods, returning a single DataFrame or list of DataFrames based...
def get(self, dataset: str = None, *args, **kwargs): """ Collects data from dataset, passing arguments to hidden methods Parameters -------------- dataset : str Dataset name, either: - "rivm" - "stocks" - "jhu" - "weathe...
def get_delay_block(tick_delay, use_observer=False) -> blocks.BlockData: if use_observer and tick_delay == 1: return blocks.get_observer(facing="west") else: return blocks.get_repeater(facing="west", delay=tick_delay) def place_walkway(nbt_s: NBTStructure, anchor_pos: Vector, option: str) -> Non...
The function generates an NBT structure for a Minecraft walkway synchronized with a musical score. It places redstone components, delay blocks, and instrument blocks according to the song's timing (TPS), tileable width, and walkway style. The structure progresses horizontally, embedding chords at specified intervals wh...
def generate_simplest_walkway_nbt_structure( song_path: str, instruments: list[blocks.InstrumentBlock], song_tps: int = 10, tileable_width: int = 7, walkway_option: str = None, ) -> NBTStructure: if song_tps == 10: tick_delay = 1 elif song_tps == 5: tick_delay = 2 else: ...
def get_delay_block(tick_delay, use_observer=False) -> blocks.BlockData: if use_observer and tick_delay == 1: return blocks.get_observer(facing="west") else: return blocks.get_repeater(facing="west", delay=tick_delay) def place_walkway(nbt_s: NBTStructure, anchor_pos: Vector, option: str) -> Non...
The function generates NBT structures representing segments of a song using redstone and delay blocks, placing walkways and chord patterns based on tempo (song_tps) and segment length. It constructs tileable Minecraft structures by iterating through song ticks, appending completed segments to a list when the segment le...
def generate_simplest_segments( song_path: str, instruments: "list[blocks.InstrumentBlock]", song_tps: int = 10, tileable_width: int = 7, segment_length: int = 32, walkway_option: str = None, ) -> "list[NBTStructure]": if song_tps == 10: tick_delay = 1 elif song_tps == 5: ...
def determine_channel_counts(total_channels: int) -> tuple[int, int]: max_channels_per_side = 30 channel_count_1 = total_channels channel_count_2 = 0 if channel_count_1 > max_channels_per_side * 2: raise ValueError( "Max channel count is %i but %i were parsed from song." ...
The function generates an NBT structure representing a musical wall with sequencers, arranging channels into two layers. It builds the primary structure with instruments and channels, adds a listening zone with flooring and lighting, and optionally creates a secondary structure behind the first if additional channels e...
def generate_wall_song_nbt_structure( instruments: list[blocks.InstrumentBlock], channels: list[Channel], tickchannels: list[TickChannels], max_height: int = 384, ) -> NBTStructure: channel_count_1, channel_count_2 = determine_channel_counts(len(channels)) ordered_channels = reorder_channels(cha...
def get_best_candidate(self): """Get the best prompt using the score as the decider. Returns: dict[str, Any]: Dictionary of prompt and score with the highest score in the self.pop list. """ return sorted(self.pop, key = lambda x: x["score"], reverse = True)[0] de...
The main task of the code is to perform a crossover operation in a genetic algorithm. It generates a new population by selecting the best prompt, then randomly pairing other prompts to create offspring through crossover. The function returns a list of new prompt dictionaries, combining the best candidate with newly gen...
def crossover(self): """Crossover function for selecting two prompts and crossing them over at a random point. Returns: list[dict[str, Any]]: New list of prompt dictionaries generated through crossing over. """ best_prompt = self.get_best_candid...
def get_sentences(self, prompt, remove_tags = False): """Get cleaned sentences from a prompt. Either removing or keeping tags as specified. Args: prompt (str): Prompt in string format. remove_tags (bool, optional): Whether to keep tags in sentences. Defaults to False. ...
The code selects a sentence index from a prompt for mutation, using random selection if no history exists, or a bandit algorithm combining historical scores and encoded sentence features to prioritize high-scoring sentences with a probability-based trade-off between exploration and exploitation.
def select_sentence(self, prompt) -> int: """Selects a sentence to be mutated. Args: prompt (str): Prompt in string format. Returns: int: Index of selected sentence. """ sentences_orig = self.get_sentences(prompt) sentences = self.get_se...
def evaluate_fitness(self, prompt: str, df = None): """Attempts to evaluate the fitness of a prompt using the fitness function. Args: prompt (str): Prompt in string format. df (_type_, optional): _description_. Defaults to None. Raises: ValueError: Provided ...
This function tunes prompts using an evolutionary algorithm. It initializes a population, iteratively performs crossover, selects prompts, mutates them, evaluates fitness, and updates the population to optimize prompt quality. The mutator is adjusted based on score changes, aiming to improve prompts through generations...
def tune_prompt(self): """Tune the prompts. """ self.init_score = self.evaluate_fitness(self.init_prompt["prompt"]) self.init_population() self.evaluate_population(self.pop) for i in range(self.num_iter): print("iteration:", i) new_pop = s...
def select_sentence(self, prompt) -> int: """Selects a sentence to be mutated. Args: prompt (str): Prompt in string format. Returns: int: Index of selected sentence. """ sentences_orig = self.get_sentences(prompt) sentences = self.get_se...
The code mutates a given prompt by selecting a sentence, replacing it with a mutated version, and rejoining the sentences. It identifies if the selected sentence starts with "Question: " or "Answer: ", preserving these prefixes during mutation. The result is a modified prompt with the altered sentence, maintaining orig...
def get_mutated_prompt(self, prompt) -> str: """Mutates a given prompt and returns it. Args: prompt (str): Prompt in string format Returns: str: Mutated prompt in string format. """ select_index = self.select_sentence(prompt) mutated_sen...
def get_centroid(coords): x, y, w, h = coords[0], coords[1], coords[2], coords[3] x_center = int((x + (x + w)) / 2) y_center = int((y + y + h) / 2) return x_center, y_center def marge_columns(row_data, MERGE_THRESH=30): for k in range(len(row_data)): row = row_data[k] need_marge = Tr...
The code processes OCR output to structure table data by clustering text elements based on coordinates, sorting clusters by x-position, aligning text into rows/columns, merging columns, and organizing final data into a 2D array for structured table representation.
def process_table_data(table, output): min_conf = .75 ''' commenting for paddle exp 307-326 ''' coords=[] ocrText=[] for i in range(0, len(output)): x = int(output[i][0][0][0]) y = int(output[i][0][0][1]) w = int(output[i][0][2][0] - x) h = int(output[i][0][...
def get_vh_lines_mask(img): logging.info("############################") logging.info(img.shape) img_height, img_width, channel = img.shape blockGryImg = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) thresh, img_bin = cv2.threshold(blockGryImg, 128, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU) img_bin_inv...
The main task of the code is to extract structured data from a table in an image using OCR (via `paddelExtract`) and line detection (via `get_vh_lines_mask`). It processes the table, converts the output to JSON/Excel formats, and saves the results. The function returns the transposed processed data array `arr.T` for fu...
def get_extracted_data(table,img_path):# options = "--psm 6" print("len(table)",len(table)) vh_lines_mask, vertical_lines_mask, horizontal_lines_mask = get_vh_lines_mask(table) vh_lines, rmvh_lines = get_vh_lines(table, vh_lines_mask) image_cv = cv2.imread(img_path) output = paddelExtract(img_p...
def transpose(self): # read file contents as homogenous list items li = self.enlist() rows = len(li) cols = len(li[0]) lii = [] i = 0 while i < cols: arr = list() j = 0 while j < rows: e = li[j][i] ...
The main task of the code is to format and display structured data in a tabular format with aligned columns. It calculates column widths based on content length, constructs a table body with padded entries, creates a header/footer using dashes, and prints the formatted table with pipes and proper spacing.
def tabulate(self): # display file content in relational format li = self.transpose() li = self.serialize(li) padx = list() for e in li: maxlen = 0 for ee in e: strlen = len(ee) maxlen = strlen if strlen > maxlen else maxlen...
def put_text_with_space_line(text, x, y, dy): """ :param text: text to write on canvas :param x: x location to start write the text :param y: y location to start write the text :param dy: the diff between line of text in pixels :return: write the text on canvas """ y0 = y for i, line...
The main task of the code is to visualize the steps of a Rubik's cube solution by drawing each move's effect on the cube's faces in a GUI. It uses a dictionary of side colors, generates solution steps via an external API, and renders each move with labeled arrows, color updates, and step numbering to demonstrate the so...
def draw_solution(dict_side_colors=None): """ :param dict_side_colors: dictionary of all colors of each side in cube :return: draw steps of solution """ global front_side_points, up_side_points, right_side_points, canvas root = Tk() root.title('Solution') ico = Image.open('image.jpg') ...