dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def eh_labirinto (maze): #Verifica se o maze e um tuplo if not isinstance(maze,tuple): return False #Verifica se o maze tem o numero minimo de tuplos if len(maze)<3: return False for tuplo in range(len(maze)): #Verifica se os elementos do maze sao tuplos if not isinstance(maze[...
The function validates inputs and returns a tuple of valid adjacent positions from all elements in 'conj' (excluding 'posicao'), filtering out walls and duplicates to determine objective positions in a maze.
def obter_objetivos(maze,conj,posicao): if not (eh_labirinto(maze)==True and eh_posicao(posicao)==True and eh_conj_posicoes(conj)==True and eh_mapa_valido(maze,conj)==True and (posicao in conj)==True): raise ValueError("obter_objetivos: algum dos argumentos e invalido") objetivo_adjacentes=() o...
def cria_unidade(p,v,f,cad): ''' cria_unidade: posicao x N x N x str -> unidade cria_unidade(p,v,f,str) recebe uma posicao p, dois valores inteiros maiores que 0 correspondentes a vida e a forca da unidade, e uma cadeia de caracteres nao vazia correspondente ao exercito da unidade e devolve a unidade correspon...
The function `simula_batalha` simulates a battle between two armies based on a configuration file, returning the winner or "EMPATE" for a tie. It reads unit data, positions, and map details from the input string, initializes the battlefield, and processes turns until one army is defeated or the map stabilizes. In verbo...
def simula_batalha(cad,b): ''' simula_batalha: str x booleano -> str Funcao principal que permite simular uma batalha completa, recebe uma cadeia de caracteres e um valor booleano e devolve o nome do exercito ganhador.Em caso de empate, a funcao deve devolver a cadeia de caracteres 'EMPATE'. A cadeia de caract...
def eh_labirinto (maze): #Verifica se o maze e um tuplo if not isinstance(maze,tuple): return False #Verifica se o maze tem o numero minimo de tuplos if len(maze)<3: return False for tuplo in range(len(maze)): #Verifica se os elementos do maze sao tuplos if not isinstance(maze[...
The function `obter_caminho` finds the shortest path from a given position to any objective in a maze using breadth-first search. It validates inputs, explores adjacent positions, tracks visited nodes, and returns the path if an objective is reached. If no path exists or inputs are invalid, it raises an error or return...
def obter_caminho(maze,conj,posicao): if not (eh_labirinto(maze)==True and eh_posicao(posicao)==True and eh_conj_posicoes(conj)==True and eh_mapa_valido(maze,conj)==True and (posicao in conj)==True): raise ValueError("obter_caminho: algum dos argumentos e invalido") lista_exploracao=[(posicao,())] ...
def _get_file_name_by_url(self, url: str) -> str: """Get the file name by URL. Arguments: url (str) -- The specified URL. Returns: str """ file_name = url.replace(self._base_url, '') or 'index' return f"{file_name.strip('/')}.html" def _prepare_p...
The main task of the code is to save a BeautifulSoup-parsed webpage content to a specified file path. It generates a filename from the URL, constructs the full file path, prepares the page content, creates necessary directories, and writes the content to a file. If an error occurs during saving, it catches the exceptio...
def _save_page(self, url: str, page: BeautifulSoup) -> None: """Save the page Arguments: url (str) -- The specified URL. page (BeautifulSoup) -- The page. """ file_name = self._get_file_name_by_url(url) file_full_path = join_path(self._export_base_path, f...
def get_page(self, url: str) -> BeautifulSoup: """The get specified page Arguments: url (str) Returns: BeautifulSoup """ headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0' ...
This function crawls a website by recursively extracting links from pages, adding them to a sitemap while respecting a maximum depth limit. It avoids revisiting URLs and handles exceptions silently. The process stops when the depth exceeds the allowed maximum or errors occur during page retrieval.
def _crawl(self, url: str, current_depth: int = 0) -> None: """Crawl the URL. Arguments: url (str) -- The site URL. current_depth (int) -- The current crawling depth (default 0). Raises: Exception """ if current_depth > MAX_ALOWED_DEP...
def _fresh_dir(self, full_path: str) -> None: """Remove the specified path. Arguments: full_path (str) -- The full path to remove. """ self._rmdir(full_path) self._mkdir(full_path) def _save_page(self, url: str, page: BeautifulSoup) -> None: """Save the page ...
The main task of the code is to export a sitemap by first preparing a fresh directory, then iterating through each link-page pair in the sitemap to save pages individually, followed by a cooldown period between exports to manage resource usage or avoid overloading the system.
def _export(self) -> None: """Export the sitemap. """ self._fresh_dir(self._export_base_path) for _link, _page in self._sitemap.items(): self._save_page(_link, _page) self._cooldown()
def __construct_payload(self, content, data_format=None, action=None, record=None, typee=None, report_id=None, instrument=None, date_range_begin=None, date_range_end=None, filter_logic=None): """ Construct the payload with specified content and data_format :param cont...
The method checks the validity of the URL and token by making an API call to retrieve metadata and the REDCap version. It constructs a payload, sends a request, and raises errors for invalid status codes (501 for URL, 403 for token). If valid, it stores the metadata and REDCap version from the response.
def __check_configuration(self): """ Check the URL and token are valid with API calls to obtain metadata and REDCAP version :return: None (raises redcapy.RedCapError if the configuration is not OK) """ content = keywords.CONTENT_METADATA data_format = keywords.FORMAT_JSON...
def deltaSecDateTime(strTm1, strTm2): ep1 = strDateTimeUTCToEpoch(strTm1) ep2 = strDateTimeUTCToEpoch(strTm2) return (ep2 - ep1) def storeGatewayJson(base_dir, access_rights, strDateTime, device, gateway, strExt, gtw_data): # divide string date-time strDate = getStrDate(strDateTime) strTime = ge...
The main task of the code is to process incoming MQTT data by parsing JSON payloads, filtering out unnecessary fields, handling gateway metadata, and storing cleaned data for device acquisitions. It validates device IDs, cleans JSON structure, adjusts gateway timestamps, and saves processed data to files for further us...
def process_mqtt_string(mqttData): # https://stackoverflow.com/questions/7472839/python-readline-from-a-string json_data = io.StringIO(mqttData) # ------------------------------------------------------- line = json_data.readline() svMqtt.update(line) # print(line) if (not line): ret...
def mapData(UtcStartTime, UtcEndTime, fullPathReport, deviceID): gcm = gc.collect() print('---[{}] GC Unreachable objects: [{}] Remaining Garbage: [{}]'.format(inspect.currentframe().f_code.co_name, gcm, gc.garbage)) # ------------------------------------------ # convert UtcStartTime, UtcEndTime in str...
The main task of the code is to generate HTML reports for a specified device's data across different time intervals (24h, 10d, 20d, 30d, all) and create specialized reports (time-RSSI, SNR, spreading factor). It also archives device data into a ZIP file, including JSON files from the device directory and its subdirecto...
def FormHtmlReportDevice(deviceID): gcm = gc.collect() print('---[{}] GC Unreachable objects: [{}] Remaining Garbage: [{}]'.format(inspect.currentframe().f_code.co_name, gcm, gc.garbage)) #---------------------- # check if exist a subdirectory deviceID inside gtw PathDeviceGtw = config.PathGtwDir +...
def collect_input_files(antismash_dir: pathlib.Path, rgi_dir: pathlib.Path): input_files = [] antismash_files = list(antismash_dir.glob("*region*.gbk")) genome_name = antismash_dir.parent.stem if len(antismash_files) == 0: print("No BGCs were found for " + genome_name + " !!!") for antismash...
The main task of the code is to predict functions for Bacterial Genome Clusters (BGCs) by processing input files from antiSMASH and RGI directories. It loads machine learning classifiers and training data, then iterates over each BGC to generate predictions. Results are aggregated into a DataFrame and saved as a CSV fi...
def main( antismash_dir: pathlib.Path, rgi_dir: pathlib.Path, data_dir: pathlib.Path, output_dir: pathlib.Path, no_SSN: bool, classifier_list: List[str], antismash_version: int, rgi_version: int, ) -> None: data = [] # Step 1: Get antismash and rgi files input_files = collect...
def get_random_position_vector_from_random_start(self): x_steps, y_steps, z_steps = map(SimulationRunner.get_random_step_vector, repeat(self, 3)) xyz_steps = zip(x_steps, y_steps, z_steps) current_position = self.get_random_point() position_vector = [current_position] for step in...
The main task of the code is to visualize a 3D particle trajectory using a colormap, adjusting axis limits and tick labels based on the path's range. If enabled, it scales the plot to a container size, adding sedimentation path lines and annotations. It prints particle properties like radius, density, sedimentation/dif...
def visualize_single_run(self, scale_to_container_size=True): position_vector = self.get_random_position_vector_from_random_start() fig = plt.figure() ax = fig.add_subplot(111, projection='3d') coords = list(zip(*position_vector)) lines = convert_to_colormap_lines(plt.get_cmap('j...
def output(string): print(string) sys.stdout.flush() def is_int(cmd): for character in cmd: if character not in "0123456789": return False return True def ennemy_play(x, y): modify_board(x, y, '2') def find_tile(player): global BOARD global SIZE global BOARDSCORE ...
This function processes a command to move to specified coordinates, validates input arguments, and executes game actions. It splits the command to extract coordinates, checks if they are integers, and triggers enemy movement and tile positioning logic. Errors are reported for invalid formats or types, ensuring only val...
def turn_cmd(cmd): tmp = cmd.split(' ') tmp = tmp[1].split(',') if len(tmp) == 2: x = tmp[0] y = tmp[1].rstrip("\r\n") if len(tmp) != 2: output("ERROR - unsupported size") elif not is_int(x) or not is_int(y): output("ERROR - wrong argument type") else: e...
def get_line(): return sys.stdin.readline() def output(string): print(string) sys.stdout.flush() def is_int(cmd): for character in cmd: if character not in "0123456789": return False return True def create_empty_board(x, y): global BOARD BOARD = [] line = "" for ...
The function processes a command string containing board instructions, validates each line's format, modifies a 20x20 board based on valid commands, and determines a play position by finding the '1' tile. It handles errors, skips "BOARD" markers, and executes the play action with coordinates derived from the processed ...
def board_cmd(cmd): test = False temp = cmd.split('\n') tmp = cmd while temp[0] != "DONE": temp = get_line() tmp = "".join((tmp, temp)) temp = temp.split('\n') tmp = tmp.split('\n') failure = 0 for elm in tmp: elm.strip("\r\n") if elm == "BOARD": ...
def traj_sim(x0, ulist): # tsteps = ulist.shape[0] x_traj = np.zeros((tsteps + 1, 3)) x_traj[0, :] = x0 xt = copy.deepcopy(x0) for t in range(tsteps): xt_new = step(xt, ulist[t]) x_traj[t + 1] = copy.deepcopy(xt_new) xt = copy.deepcopy(xt_new) ...
The main task of the code is to compute the descent direction for the control input in an Iterative Linear Quadratic Regulator (iLQR) algorithm. It simulates the system dynamics, computes linearized dynamics and cost gradients, solves a boundary value problem to obtain adjoint variables, and derives the optimal control...
def ilqr_iter(x0, u_traj): """ :param x0: initial state of the system :param u_traj: current estimation of the optimal control trajectory :return: the descent direction for the control """ # forward simulate the state trajectory x_traj = traj_sim(x0, u_traj) ...
def traj_sim(x0, ulist): # tsteps = ulist.shape[0] x_traj = np.zeros((tsteps + 1, x0.shape[0])) x_traj[0, :] = x0 xt = copy.deepcopy(x0) for t in range(tsteps): xt_new = step(xt, ulist[t]) x_traj[t + 1] = copy.deepcopy(xt_new) xt = copy.deepcop...
The code computes the descent direction for control in an Iterative Linear Quadratic Regulator (iLQR) algorithm. It simulates the state trajectory, calculates cost terms, and solves a boundary value problem (BVP) for the state and costate variables using `solve_bvp`. The solution provides the optimal control adjustment...
def ilqr_iter(x0, u_traj): """ :param x0: initial state of the system :param u_traj: current estimation of the optimal control trajectory :return: the descent direction for the control """ # forward simulate the state trajectory x_traj = traj_sim(x0, u_traj) ...
def seek(self, target_pos): # Move towards target position desired_vel = (target_pos - self.pos).normalise() * self.max_speed if (target_pos - self.pos).length() < 5: return -self.vel return desired_vel - self.vel def arrive(self, target_pos, speed): ''' this behaviou...
This method calculates and returns the steering acceleration vector based on the agent's current mode, such as seeking, arriving at a target with varying speeds, fleeing, following a path, or wandering. It selects the appropriate behavior, computes the acceleration, stores it in self.acceleration, and returns the resul...
def calculate(self, delta): # reset the steering force mode = self.mode if mode == 'seek': accel = self.seek(self.world.target) elif mode == 'arrive_slow': accel = self.arrive(self.world.target, 'slow') elif mode == 'arrive_normal': accel = sel...
def setDefaultFolders(self): self.defaultFiledialogOpenLocation = os.path.join( os.path.expanduser("~"), "Documents", ) self.defaultSaveFolder = os.path.join( os.path.expanduser("~"), "Documents", "PDFHandeler", ) self.d...
The main task of this code is to initialize a GUI window by loading a UI file, setting window properties, initializing dictionaries to manage PDF data, connecting list view interactions to event handlers, and configuring default directories and button connections for a PDF management application.
def __init__(self): super(MainWindow, self).__init__() uic.loadUi("./ui/mainUi.ui", self) self.resize(1650, 800) self.setWindowIcon(QtGui.QIcon("./resources/icon.ico")) self.pdfs = {} self.compressedPdfs = {} self.mergedPdfs = {} self.pdfListView.itemC...
def change_level(self, new_level=None): self.find_new_level = False if new_level is not None and self.locked_levels[new_level] == False: self.level = new_level else: self.level = self._get_next_level() self._write_to_pipe('changelevel#' + str(self.level)) ...
This code handles a single step in a reinforcement learning environment, managing level transitions, reward calculation, and episode tracking. It updates observations, adjusts rewards based on episode progress, logs level and score information, and triggers level unlocks upon episode completion. The function returns th...
def _step(self, action): # Changing level if self.find_new_level: self.change_level() obs, step_reward, is_finished, info = NesEnv._step(self, action) reward, self.total_reward = self._calculate_reward(self._get_episode_reward(), self.total_reward) # First step() aft...
def prob_c(self, given): if given == 'a': return self.prob_a() elif given == 'b': return self.prob_b() else: return None def prob_c_gm(self, given, initial_m): if given == 'a': return self.prob_a_gm(initial_m) elif given == 'b': ...
This code computes posterior probabilities for each initial_m using Bayes' theorem, updating self.m_probability by calculating [P(given|initial_m) * P(initial_m)] / P(given), where final_val represents P(given). It iterates through all initial_m values in self.given_m, applying the formula to determine the conditional ...
def p_m_prob(self, given): final_val = self.prob_c(given) for initial_m in self.given_m: val_a = self.prob_c_gm(given, initial_m) * self.prob_p_m(initial_m) / final_val self.m_probability[self.given_m == initial_m] = val_a
def evalBoard(self, player: int, board: list = None) -> float: if board is None: board = self.board score = 0 for y, row in enumerate(board): for x, p in enumerate(row): if p == PLAYER1: score += 1 + (7 - y) / 7 elif p =...
This code implements a turn-based board game where two players alternate moves. It handles legal move validation, user input for piece/move selection, win/loss conditions (elimination of all pieces), and draw detection (no legal moves for both players). The game tracks evaluation history, enforces turn order, and manag...
def playGame(self) -> None: self.playing = True evalhist = [] turn_count = 0 nlm = 0 while self.playing: p = None avail_moves = 1 if self.turn == PLAYER1: evalhist.append(self.evalBoard(self.turn)) turn_count += ...
def decodeBoard(self, encoding: str, letters: str = "aAbBn"): newboard = [] piece_dict = {0: PLAYER1, 1: 2 * PLAYER1, 2: PLAYER2, 3: 2 * PLAYER2, 4: 0} if len(encoding) == 16: for y in range(8): row = [] for x in range(8): if y % 2 ...
The function generates all possible board states after a player's legal moves by decoding the input board, simulating each move, and encoding the resulting states into a dictionary with moves as keys.
def getPossBoards(self, encodedboard: str, player: int) -> dict: defboard = self.decodeBoard(encodedboard) newboards = {} p = None avail_moves = 1 lm = self.legalMoves(player, defboard, p) for piece in lm: for direction in lm[piece]: simboard =...
def read_metafile(meta_path): try: with open(meta_path, 'r') as file: hash = file.read() return hash except FileNotFoundError: return None def get_digest(file_path='./process_image.py'): h = hashlib.sha256() with open(file_path, 'rb') as file: while True: ...
The function processes an image by checking a cache (via hash) to avoid reprocessing. If cached, it returns a preprocessed PNG; otherwise, it reads the image, applies transformations (cropping, text addition), saves the hash for future use, and returns the modified image.
def process_image(imagePath, number): meta_path = imagePath.replace('.jpg', '.hash').replace('images', 'output') hash = read_metafile(meta_path) if hash == get_digest(): print("Using cache", meta_path) output_file = imagePath.replace("images", "output").replace('jpg', 'png') return ...
def reset(self): self.count = 0 self.H_set, self.H_tilda = self.state_space() H_set = self.H_set[:, :, self.count] H_tilda = self.H_tilda[:, :, self.count] s_actor = np.zeros((self.K*self.M, 2)) for i in range(self.M): for j in range(self.K): s...
The main task of the code is to run a test phase for a DQN-based agent over 100 episodes. It initializes the environment, interacts with it by predicting actions and collecting rewards, calculates the average reward per episode, and logs performance metrics. The function returns a list of average rewards across episode...
def test(self, sess): max_episode = 100 self.Ns = int(5e2+1) self.sess = sess tf.compat.v1.global_variables_initializer().run() st = time.time() reward_hist = list() for k in range(1, max_episode+1): reward_dqn_list = list() s_actor, s_c_...
def verifyTx(self, tx: Transaction) -> bool: # verify a Tx """ 1. Ensure the transaction is not already on the blockchain (included in an existing valid block) 2. Ensure the transaction is validly structured """ return self.__verifyTxNotOnBlockchain(tx) and self.__verify...
This function generates an invalid block for testing by either corrupting the previous hash or proof-of-work (POW) value. It verifies the transaction's validity, computes a nonce to meet mining difficulty, and constructs a Block object with intentional invalidity. The block is then added to the blockchain tree with adj...
def mineInvalidBlock(self, tx: Transaction, isInvalidPrevHash = False, isInvalidPOW = False) -> None: """ This function is only used for testing. mine a new invalid block with the tx, either prev_hash or pow is invalid """ if not isInvalidPrevHash and not isInvalidPOW: ...
def verifyTx(self, tx: Transaction) -> bool: # verify a Tx """ 1. Ensure the transaction is not already on the blockchain (included in an existing valid block) 2. Ensure the transaction is validly structured """ return self.__verifyTxNotOnBlockchain(tx) and self.__verify...
The code mines a new block by validating the transaction, finding a nonce through proof-of-work to meet the difficulty target, creating a new block with the transaction and computed hash, and updating the blockchain structure with the new block and its node in the tree.
def mineBlock(self, tx: Transaction) -> None: # mine a new block with the tx # tx not valid if not self.verifyTx(tx): # because this transaction is already in the ledger if not self.__verifyTxNotOnBlockchain(tx): log.error("Node " + self.id + " :" + "Tx Verificat...
def __verifyBlockPrevHash(self, prevBlock: Block, newBlock: Block) -> bool: prevEncode = prevBlock.toString().encode('utf-8') prevHash = sha256(prevEncode).hexdigest() __flag = prevHash == newBlock.prev return __flag def __verifyTxNotOnBlockchain(self, tx: Transaction) -> bool: #...
This method processes incoming blocks from a queue, verifies their validity by checking previous hashes, transaction uniqueness, and block integrity, and appends valid blocks to the ledger as part of a blockchain. It ensures blocks are correctly linked to the longest chain and logs errors for invalid blocks.
def receiveBroadcastBlock(self) -> None: if self.receivedBlockQueue.empty(): return else: while not self.receivedBlockQueue.empty(): newBlock = self.receivedBlockQueue.get() for blockTreeNode in self.ledger: if self.__verifyBloc...
def get_cnv_sample( fp: str ) -> str: return fp.split("/")[-1].split(".purple.")[0] def compute_copy_loss_burden( df: pd.DataFrame ) -> int: # number of genes with copy number change df_sex = df[df['chromosome'].isin(['X','Y'])] df_non_sex = df[df['chromosome'].isin([str(i) for i in range(23)])] sex_ch...
The function processes a CNV data file to extract and compute genetic features, returning a dictionary containing the sample ID, copy number loss burden, and region-based features derived from the input data.
def get_cnv_gene_features( fp: str ) -> dict: print( "Get CNV gene features: " + get_cnv_sample(fp)) df = pd.read_csv( fp, sep = "\t") features = {'sampleId' : get_cnv_sample(fp)} features.update({'cnv_copy_loss_burden': compute_copy_loss_burden(df)}) features.update( get_cnv_region_features(df...
def read_vcf(vcf_path: str) -> pd.DataFrame: names = get_vcf_col_names(vcf_path) return pd.read_csv(vcf_path, compression='gzip', comment='#', chunksize=10000, delim_whitespace=True, header=None, names=names).read() def get_metadata_df(vcf: pd.DataFrame) -> pd.DataFrame: return vcf[["#CHROM", "POS", "ID", "...
The code processes a VCF file by reading its data, extracting metadata and info fields, combining them into a DataFrame, filtering entries that pass quality checks, and adding mutation type annotations, ultimately returning a structured DataFrame with filtered and annotated variant data.
def get_quick_vcf(vcf_path: str) -> pd.DataFrame: vcf = read_vcf(vcf_path) metadata = get_metadata_df( vcf) info = get_info_df( vcf ) together = metadata.join(info) clean_df = filter_PASS( together ) return add_mutation_type( clean_df )
def get_sample( fp: str ) -> str: return fp.split("/")[-1].split(".purple.")[0] def get_sample_features( sample: str, df: pd.DataFrame, genes: list) -> dict: sample_features = { 'sampleId' : sample } sample_features.update( get_TMB_cts(df) ) sample_features.update( get_gene_mts(df, genes) ) return s...
The main task of the code is to extract somatic mutation features from a VCF file for specified genes. It retrieves the sample name from the VCF path, loads variant data via `get_quick_vcf`, and processes these to generate a dictionary of features using `get_sample_features`, focusing on somatic alterations in the give...
def get_somatic_features(vcf_path: str, genes: list) -> dict: print("Get somatic features for: " + get_sample(vcf_path)) return get_sample_features( sample=get_sample(vcf_path), df=get_quick_vcf(vcf_path), genes = genes)
def create_default_config(self): # This configuration dictionary is saved in pex.json. return { u"pex_status": u"enabled", # enabled or disabled changed by PEX UI u"auto_configure": 1, u"demo_mode": 0, u"default_ic_type": u'mcp23017', # Used by autoconfi...
The main task of the code is to load, validate, and configure a PEX system's settings from a JSON file. It handles missing or invalid files by creating default configurations, validates the loaded config, applies demo mode or auto-configuration settings, calculates device counts, and sets system status based on configu...
def load_config(self): pex_config = {} try: with open(u"./data/pex_config.json", u"r") as f: pex_config = json.load(f) # Read the pex_config from file except IOError: # If file does not exist create file using defaults. print("PEX: No config file found. ...
def handleIf(self, node, indent): if_code = "\n" + self.get_indent(indent) + "if" if node.get("BooleanStatement"): if_code += " " + self.handle_binary_expression(node["BooleanStatement"]) + ":" if node.get("IfBlock"): if_code += "\n" + self.get_indent(indent+2) + self.ha...
This function traverses an abstract syntax tree (AST) recursively, processing each node to generate formatted code. It handles specific node types like IfStatement, ExpressionStatement, VariableDeclaration, and PrintStatement by appending processed code to `self.code`, using indentation. It skips non-type keys and recu...
def walk_ast(node, indent): if node is None: return try: print(node['type']) except: pass if node["type"] == "IfStatement": self.code += str(self.handleIf(node, indent)) return ...
def _parse(f): lines = [l for l in [x.strip() for x in f.readlines()]] input = {} for l in lines: bag, contents = l.split('contain') bag_name = bag.split(' bags')[0].replace(' ', '-') input[bag_name] = {} if 'no other bags' in contents: continue contents...
The code defines a function `run` that processes an input `f`. It first parses `f` using `_parse`, then computes two results by applying `_star1` and `_star2` to the parsed input. The function returns a tuple containing both computed results. The main task is to parse the input and generate two derived outputs. Your re...
def run(f): input = _parse(f) return (_star1(input), _star2(input))
def handle_empty_line(self, buffer: str, report_count: int) -> bool: if report_count == self.max_report_delimiter_count and buffer.strip(): self.publish_parsed_report(buffer) return True elif report_count == 0 and buffer.strip(): self.publish_parsed_event(buffer) ...
The main task of the code is to continuously read and process incoming serial data until a shutdown flag is set. It handles data lines by decoding and parsing them, managing empty lines, and publishing parsed reports or events. The function also manages exceptions related to serial communication, decoding errors, and u...
def process_incoming_data(self, shutdown_flag: threading.Event) -> None: buffer = "" report_count = 0 if self.ser is None: raise ValueError("Serial port is not initialized") try: while not shutdown_flag.is_set(): if self.ser.in_waiting > 0: ...
def open_serial_port(self) -> None: try: if self.ser is None: self.init_serial_port() if not self.ser.is_open: self.ser.open() self.queue.is_serial_connected = True self.logger.debug("Serial connected") ...
This function continuously listens to a serial port, processing incoming data while handling connection errors, decoding issues, and unexpected exceptions. It attempts reconnection on serial failures, resets buffers for decoding errors, and implements exponential backoff for unexpected errors. The loop terminates upon ...
def listening_to_serial(self, shutdown_flag: threading.Event) -> None: max_delay = 60 delay = 1 while not shutdown_flag.is_set(): try: self.open_serial_port() self.process_incoming_data(shutdown_flag) except (serial.SerialException, seri...
def host_add_file_from_client(sock, n, data): # First download the file from the client fsize = int(data[data.find(ETX) + len(ETX):data.find(EOT)]) fname = data[CCLEN:data.find(ETX)] print("Getting %s of size %d from %s" % (fname, fsize, str(sock.getpeername()))) truepath = n.fp + fname f = ope...
The main task of the code is to listen for incoming data from a client socket, process commands related to file management (add, delete, update), and handle disconnections. It receives file operations from clients, updates a master file list, and broadcasts changes to other nodes while maintaining active connections in...
def host_listen(name, n, sock): global sock_list while True: time.sleep(5) try: data = sock.recv(BUFFER_SIZE).decode(ENCODING) except socket.timeout: print("Time out in host_listen with: %s" % str(sock.getpeername())) if data: print(data) ...
def client_node(n): # creates the client socket and connects, then returns the socket s = socket.socket() s.connect((n.host, n.port)) print("Connected to %s" % str(s.getpeername())) return s def pop(msg='Something went wrong'): sg.popup('Error:', msg) def client_clear_folder(): # clears the folder...
The code creates a login GUI for connecting to a host or hosting a new connection. It takes IP/port inputs, allows client connection via 'Connect to host' (launching a client node with threading), or hosting via 'Host new connection' (starting a host node). Error handling includes retrying the login window on connectio...
def login_window(): # the main login window sg.theme('Default1') layout = [ [sg.Text('Host IP:'), sg.InputText("192.168.2.151", key='ip', size=(30, 1))], # TODO get rid of the default text [sg.Text('Host Port:'), sg.InputText("8000", key='port', size=(20, 1))], [sg.Button('Conn...
def get_file_names(): files = os.listdir(get_working_directory()) if len(files) == 0: files.append(' ') return files def get_filepath(name): return os.path.join(get_working_directory(), name) def get_mod_time(filepath): fileStatsObj = os.stat(filepath) return fileStatsObj.st_mtime
The code scans files by retrieving their names, modification times, and paths, creating File objects and returning them as a list.
def scan(): list = [] names = get_file_names() for name in names: path = get_filepath(name) mod = get_mod_time(path) list.append(file.File(name, mod, path)) return list
def _reset(self): self.__init__(self.rows, self.cols) def _moveBox(self, row, col): if (row, col) in self.boxes: dx, dy = row - self.player_pos[0], col - self.player_pos[1] nr, nc = dx + row, dy + col if (nr, nc) in self.boxes or not (self.rows - 1 > nr > 0 < nc < sel...
The code handles player movement in a grid-based game, checking if the move is valid. It updates the player's position, attempts to move boxes if encountered, and returns True if all boxes are moved successfully, otherwise False.
def play(self, move): if move == 'r': self._reset() if move not in self.moves: return nr, nc = self.moves[move] nr += self.player_pos[0] nc += self.player_pos[1] if self.rows - 1 > nr > 0 < nc < self.cols - 1: if (nr, nc) in self.boxe...
def initial_population(self): population = [] for _ in range(population_size): configuration = [] angle = pi / 2 for i in range(robot_number): x = base_station[0] + start_radius * cos(angle) y = base_station[1] + start_radius * sin(angl...
This code initializes a simulation environment for a robot navigation or pathfinding system. It sets up a collision map, Pygame display, tracks visited areas, initializes robot configurations, loads a WFC-generated map, counts open spaces, and starts the simulation loop. The main tasks include environment setup, collis...
def __init__(self): self.collision_array = np.zeros((background_resolution, background_resolution), dtype=bool) self.collision_surface = None self.open_space = 0 self.screen = pg.display.set_mode([background_resolution, background_resolution]) self.visited = set() self.vi...
def initial_population(self): population = [] for _ in range(robot_number): angle = pi / 2 x = base_station[0] + start_radius * cos(angle) y = base_station[1] + start_radius * sin(angle) angle += 2 * pi / robot_number population.append(Robot(x...
This code initializes a simulation environment for robot navigation, setting up collision/visited grids, a base station, and Pygame display. It loads a WFC-generated map, counts open space, and starts the main simulation loop to manage robot movement and environment interaction.
def __init__(self): self.running = True self.fps = 30 self.collision_array = np.zeros((background_resolution, background_resolution), dtype=bool) self.collision_surface = None self.visited_array = np.zeros((background_resolution, background_resolution), dtype=bool) self.v...
def fetch_and_save_file(self, path, save_to_fn=None): fileinfo = self.get_endpoint('list', path) if fileinfo.status_code not in [200, 207]: logger.error("error: %s", fileinfo.text) raise StorageException(fileinfo.text) fileinfo = fileinfo.json()[0] filesi...
The function fetches and saves files or directories recursively. If `recursive=False`, it processes a single file. If `recursive=True`, it iterates through directory entries, saving files and recursively handling subdirectories by creating directories and calling itself, ensuring all files and nested directories under ...
def fetch_and_save_file_or_dir(self, path, recursive=False): if not recursive: return self.fetch_and_save_file(path) else: for entry in self.list_dir(path): if entry['href'] != path: if entry['type'] == 'file': logger.in...
def load_Dataset(self, path): fn = os.path.join(os.path.dirname(__file__), 'brestcancer.csv') self.df_breastCancer = pd.read_csv(fn,delimiter=";",encoding = "ISO-8859-1") self.df_breastCancer = self.df_breastCancer.drop_duplicates() self.df_breastCancer = self.df_breastCancer.drop(column...
The code initializes a machine learning pipeline by loading a dataset, preprocessing it (normalizing features, selecting columns), splitting data into training/test sets, generating models (likely decision trees or k-NN), evaluating performance, storing results in a table, saving model files, and constructing a binary ...
def __init__(self, path, max_depth, test_size, n_neighbors): self.path = path self.max_depth = max_depth self.test_size = test_size self.n_neighbors = n_neighbors self.load_Dataset(path) self.generate_plots() self.get_min_and_max_values() self.add_columns_...
def get_3_points(image): points_coord = [] higth, width, ch = image.shape points_coord.append([(higth*2)/3, width/2]) points_coord.append([(higth*2)/3, (width * 2)/7]) points_coord.append([(higth*2)/3, (width * 5)/7]) return points_coord def process_image(img): img = cv2.medianBlur(img,5) ...
The main task of the code is to continuously capture and process screen regions to extract specific point data and color values from images, then process this data in real-time. It includes pausing/resuming functionality via the 'T' key, image processing with OpenCV, and handling user input. The loop runs until manuall...
def main(): paused = False while not paused: #image_org = cv2.imread(file_paths[0]) image_org = grab_screen(region=(0,30,1250,750)) #speed, speed_img = get_speed(image_org) points = get_3_points(image_org) image = process_image(image_org) point_colour_value, image...
def fun(onto): dicto = {} classes = list(onto.classes()) subs = [list(ont.subclasses()) for ont in classes if len(list(ont.subclasses())) > 0] indivs = list(onto.individuals()) str_classes = [str(ont).split('.')[1] for ont in classes] str_indivs = [str(ont).split('.')[1] for ont in indivs] f...
The code processes a user request by correcting its spelling, searching for matching entities in an ontology, and returning either a 'no match' message or a processed result based on the found entity, using a web template for response.
def home(request): myrequest=request.POST.get('requestrisk') myrequest=str(myrequest) diction_entities = fun(onto) myrequest = spell_it_right(myrequest) entities = [] entities.extend(classes) entities.extend(indivs) entities = fix_entities(entities) entity = find_entity(myrequest, ...
def _build_z_matrix(self): """Build a Z-matrix for the system.""" import networkx as nx # Build a graph representing the topology. graph = nx.Graph() graph.add_nodes_from(self.universe.atoms) graph.add_edges_from(self.universe.bonds) if not nx.is_connected(graph...
The code initializes a generative model for molecular configurations using Masked Autoregressive Flows (MAF). It constructs a Z-matrix from a molecular system, builds a MAF flow with specified layers, and incorporates coordinate transformations to reduce dimensions by fixing translational/rotational degrees of freedom....
def __init__( self, universe, n_maf_layers=6, n_maf_layers_ic=0, **kwargs ): super().__init__() # Determine a Z-matrix for the molecule. self.universe = universe self.z_matrix = self._build_z_matrix() # Build the M...
def getKeyValue(key, string): vraceni = re.search(key + "([-0-9.]*)", string).group(1) return float(vraceni) def update_XYE_coordinates(self, line): self.past_X = self.current_X self.past_Y = self.current_Y if ("X" in line): self.current_X = round(self.baseSizes["X"] ...
This function parses G1 movement commands from a line of G-code, extracting parameters like feed rate (F) and coordinates (X, Y, Z, E). It generates byte-encoded commands based on the axes present, appending them to a queue. It also handles smart acceleration logic, deciding whether to start, maintain, or end accelerat...
def parseG1_new(self, line): if "F" in line: F_value = self.getKeyValue("F", line) F_value = int(F_value) vraceni = bytearray() vraceni.extend((2).to_bytes(self.byteSizes["command"], byteorder='big')) vraceni.extend(F_value.to_bytes(self.byteSizes["F"...
def getKeyValue(key, string): vraceni = re.search(key + "([-0-9.]*)", string).group(1) return float(vraceni) def parseG1_new(self, line): if "F" in line: F_value = self.getKeyValue("F", line) F_value = int(F_value) vraceni = bytearray() vraceni.ex...
This function parses a line of G-code or similar commands by checking its starting character. If the line is invalid or starts with a comment/semicolon, it returns False. For 'G' commands, it identifies the command value and calls specific parsing methods (e.g., parseG1_new, parseNoArg). For 'M' commands, it checks if ...
def parseLine(self, line): if not line: return False elif line[0] == ";": return False elif line[0] == "\n": return False elif line[0] == "G": value = int(self.getKeyValue("G", line)) if value == 1: self.parseG1_...
def load_session_data(self): self.load_cookie() if "sessionId" in self.cookie: sessionId = self.cookie["sessionId"].value self.sessionData = gSessionStore.getSessionData(sessionId) if self.sessionData == None: sessionId = gSessionStore.createSession() ...
This method handles HTTP DELETE requests by determining the resource and identifier from the URL path. If the resource is 'fighters' and an identifier is present, it deletes the corresponding fighter member. Otherwise, it returns a 404 Not Found response.
def do_DELETE(self): self.load_session_data() path_parts = self.path.split("/") resource = path_parts[1] if len(path_parts) > 2: identifier = path_parts[2] else: identifier = None if resource == "fighters" and identifier != None: self....
def load_session_data(self): self.load_cookie() if "sessionId" in self.cookie: sessionId = self.cookie["sessionId"].value self.sessionData = gSessionStore.getSessionData(sessionId) if self.sessionData == None: sessionId = gSessionStore.createSession() ...
This code handles PUT requests to update fighter member data. It extracts the resource name and identifier from the URL path, checks if the resource is "fighters" with a valid identifier, and calls handleFighterUpdateMember if so. Otherwise, it returns a not-found response.
def do_PUT(self): self.load_session_data() path_parts = self.path.split("/") resource = path_parts[1] if len(path_parts) > 2: identifier = path_parts[2] else: identifier = None if resource == "fighters" and identifier != None: self.han...
def load_session_data(self): self.load_cookie() if "sessionId" in self.cookie: sessionId = self.cookie["sessionId"].value self.sessionData = gSessionStore.getSessionData(sessionId) if self.sessionData == None: sessionId = gSessionStore.createSession() ...
The code defines a `do_POST` method that handles HTTP POST requests by routing them based on the request path. It loads session data, then directs the request to specific handlers for creating fighters, users, or sessions. If the path doesn't match any known route, it triggers a "not found" response. The method central...
def do_POST(self): self.load_session_data() if self.path == "/fighters": self.handleFighterCreate() elif self.path == "/users": self.handleUserCreate() elif self.path == "/sessions": self.handleSessionCreate() else: self.handleNotFo...
def load_session_data(self): self.load_cookie() if "sessionId" in self.cookie: sessionId = self.cookie["sessionId"].value self.sessionData = gSessionStore.getSessionData(sessionId) if self.sessionData == None: sessionId = gSessionStore.createSession() ...
This code handles HTTP GET requests by parsing the URL path to determine the resource and identifier, then routing the request to the appropriate handler method for retrieving fighter data or returning a not-found response.
def do_GET(self): self.load_session_data() path_parts = self.path.split("/") resource = path_parts[1] if len(path_parts) > 2: identifier = path_parts[2] else: identifier = None if resource == "fighters" and identifier == None: self.han...
def calc_dist(pos1, pos2): return abs(pos1[0] - pos2[0]) + abs(pos1[1] - pos2[1]) def calc_nearby_fruits(state, location): score = 0 for key, value in state.fruits.items(): if calc_dist(location, key) <= 3: score += value*0.1 return score def find_longest_route(state, isMe): max ...
The code calculates a heuristic value for a game state by evaluating fruit values, adjusting for distance from the player/rival, incorporating nearby fruits, and weighting route lengths. It prioritizes maximizing high-value fruit acquisition while penalizing long routes, with adjustments based on whether it's the playe...
def heuristic_calc(state, isMe): heuristic = 0 max_fruit = -100000000 for key, value in state.fruits.items(): if isMe is True: location = state.my_location else: location = state.rival_location real_value = state.fruits[key] - 0.1 * value * (calc_dist(key, loc...
def heuristic_calc(self, state, isMe): heuristic = 0 max_fruit = -100000000 for key, value in state.fruits.items(): if isMe is True: location = state.my_location else: location = state.rival_location real_value = state.fruits[ke...
This function calculates a heuristic value for a given move in a game state. Depending on the heuristic_type (0 or 1), it either evaluates the current state directly or applies the move first before evaluation. It uses two distinct heuristic calculation methods: heuristic_calc for type 0 and heuristic_calc_light for ty...
def get_heuristic_for_move(self, state, move, agent, heuristic_type): if heuristic_type == 0: return self.heuristic_calc(state, agent) if heuristic_type == 1: return self.heuristic_calc_light(self.preform_move(state, move, agent))
def heuristic_calc(state, isMe): heuristic = 0 max_fruit = -100000000 for key, value in state.fruits.items(): if isMe is True: location = state.my_location else: location = state.rival_location real_value = state.fruits[key] - 0.1 * value * (calc_dist(key, loc...
The function `get_heuristic_for_move` computes a heuristic value for a given state and move based on the specified `heuristic_type`. If `heuristic_type` is 0, it directly calculates the heuristic using the current state. If 1, it applies the move to the state first via `preform_move`, then computes the heuristic on the...
def get_heuristic_for_move(state, move, agent, heuristic_type): if heuristic_type == 0: return heuristic_calc(state, agent) if heuristic_type == 1: return heuristic_calc_light(preform_move(state, move, agent))
def can_I_move(board, pos): num_steps_available = 0 for d in get_directions(): i = pos[0] + d[0] j = pos[1] + d[1] # check legal move if 0 <= i < len(board) and 0 <= j < len(board[0]) and (board[i][j] not in [-1, 1, 2]): # print(num_steps_available, '^^^^^^^^^^^^^^^^...
The code implements the Alpha-Beta pruning algorithm for game tree search, evaluating moves with heuristic-based utility functions. It alternates between maximizing (player's turn) and minimizing (opponent's turn) nodes, recursively exploring valid moves while considering fruit collection, board state updates, and dept...
def search(self, state, depth, maximizing_player, alpha=ALPHA_VALUE_INIT, beta=BETA_VALUE_INIT, heuristic_type=0): """Start the AlphaBeta algorithm. :param state: The state to start from. :param depth: The maximum allowed depth for the algorithm. :param maximizing_player: Whether this is...
def can_I_move(board, pos): num_steps_available = 0 for d in get_directions(): i = pos[0] + d[0] j = pos[1] + d[1] # check legal move if 0 <= i < len(board) and 0 <= j < len(board[0]) and (board[i][j] not in [-1, 1, 2]): # print(num_steps_available, '^^^^^^^^^^^^^^^^...
The code implements the MiniMax algorithm to determine the optimal move for a player in a game, evaluating possible states recursively. It alternates between maximizing and minimizing players, considering heuristic values when depth is exhausted. The function returns the best score and direction for the current player,...
def search(self, state: State, depth, maximizing_player, heuristic_type=0): """Start the MiniMax algorithm. :param state: The state to start from. :param depth: The maximum allowed depth for the algorithm. :param maximizing_player: Whether this is a max node (True) or a min node (False)....
def usage(): print("setup/managing script for awccc") print("without arguments: create a config file if not present") print("-u | username [string]") print("-c | copy config preset [int]") print("-d | delete ['cache'/'list'/'users'/'config'/'program'/]") print("-f | force (no confirmation)") ...
The main task of the code is to parse command-line arguments for managing user data operations, such as deleting cache/config/script files or creating a user with optional presets. It validates inputs, checks for conflicting flags, and executes deletion or creation actions based on provided options like username, prese...
def main(): arg_list = sys.argv[1:] opts = "u:c:d:fh" username = "" preset = -1 delete = "" force = False try: # parsing args args, _ = getopt.getopt(arg_list, opts) # checking each for curr_arg, curr_val in args: if curr_arg == "-h": ...
def open_file(file): """Return a text file as a set.""" try: with open(file) as file: content = set(file.read().split()) return content except FileNotFoundError: return [] def map_letters(corpus, amount): """Finds all possible suffixes following an existing combin...
The main task of the code is to generate 10 unique new words of a user-specified length (4–18 characters) using a corpus of existing words. It validates user input, loads forbidden prefixes, maps letter patterns from the corpus, and constructs new words while avoiding forbidden prefixes. The result is displayed as a li...
def main(): """Lets user create new words of a chosen length.""" print("\nWelcome to the wonderous word generator!") choice = None while not choice: choice = input( "Please specify how long the new word should be (between 4-18): " ) if not choice.isdigit(): ...
def creating_task(): while True: new_task=input('\n'"Do you want to add a new task? yes or no: ") new_task=new_task.lower() if new_task=="no": task_listing() break elif new_task=="yes": new_name=input('\n'"What is the name of the task? ") new_description=input("Briefly describe the task. ") new...
The main task of the code is to orchestrate a data processing workflow by sequentially executing functions: creating a task, handling access choices, filtering data, sorting it, and generating statistics. Each function contributes to processing or analyzing data, culminating in structured output or insights.
def main(): creating_task() access_choice() filtering() sorting() statistics()
def SVM_window(): ELkiller(); frame_creator(); label_creator("SVM", [.5,.3]) #function that assigns the selected choice to the global variable kernel def kernelmenu_callback(choice): global kernel kernel = choice def Submit(): if "kernel" not in globals(): tkinter.messagebox.sho...
The function `back_fun()` deletes the `ELalgo.model` attribute if it exists, then routes to different algorithm-specific windows (SVM, KNN, logistic regression, decision tree) based on the value of `alg`, ensuring error-free model cleanup before initiating the selected algorithm's interface.
def back_fun(): try: del ELalgo.model except AttributeError: pass if alg=="s": SVM_window() elif alg=="knn": KNN_window() elif alg=="lor": ELalgo_selector() elif alg=="t": decision_tree_window(...
def send(self, type: ambilight_pb2.MessageType, to_client: Tuple[str, int]=ALL_CLIENTS, payload: bytes=b"") -> bool: message = ambilight_pb2.Message() message.type = type message.sender = ambilight_pb2.Sender.SERVER message.sequence_number = self.sequence_number if type == ambilight_pb2.MessageType...
The code broadcasts discovery messages periodically and listens for client responses. It handles CONFIG messages by registering clients and sending acknowledgments, and processes HEARTBEAT messages to update client last-seen timestamps. It manages client data using a thread-safe dictionary and handles socket errors, en...
def discovery_broadcast(self): while True: message = ambilight_pb2.Message() print("Sending discovery message") try: self.send(ambilight_pb2.MessageType.DISCOVERY, (self.UDP_BROADCAST_IP, self.UDP_BROADCAST_PORT)) except (socket.timeout): print("Discovery socket send timeout...
def get_next_input(min_count, max_count): global inputs global next_input_index if next_input_index < len(inputs): next_input = inputs[next_input_index] next_input_index += 1 else: next_input = generate_new_input(min_count, max_count) inputs.append(next_input) ne...
This function runs test rounds for a player by sending input values (count, amount) to their program, verifying outputs against expectations, and tracking correctness. It handles timeouts, errors, and terminates when the program ends or a timeout occurs, updating the player's performance metrics accordingly.
def run_rounds_for_player(player, min_count, max_count): player.start_program() while True: next_input = get_next_input(min_count, max_count) try: if not player.program.isalive(): print(f"P{player.index} no longer alive") continue print_nex...
def print_duel_info(players, min_count, max_count, timeout): print(f"min count per coin type: {min_count:,}") print(f"max count per coin type: {max_count:,}") print(f"timeout per player: {timeout:,} s") print() print_player_info(players) def reset_inputs(): global next_input_index next_inpu...
The main task of the code is to manage a competitive duel between players, where each player completes a specified number of rounds (between min_count and max_count) under a time limit. It initializes duel parameters, executes rounds for each player with timeout enforcement, tracks results, and returns the updated play...
def run_duel(players, min_count, max_count, timeout): print_duel_info(players, min_count, max_count, timeout) for player in players: reset_inputs() with timer.Timer(timeout): run_rounds_for_player(player, min_count, max_count) print_duel_results(players) return players
def getweight(mat): count = 0; for i in range(4): for j in range(4): if(mat[i][j] != 4*i + j + 1): count+=1 return count def Find16(mat): for i in range(4): for j in range(4): if(mat[i][j] == 16): return i,j def AddBranch(mat,path,i...
The code solves a sliding puzzle (e.g., 15-puzzle) using a priority-based search algorithm. It explores possible moves (up/down/left/right) from the current state, tracks the path to reach the solution, and stops when a zero-weight state is found. It returns the optimal path and the count of expanded nodes during the s...
def solve(mat): global dict global q global Current_Node dict = {} q = PriorityQueue() Expanded_Nodes = 0 root = Node(mat,["none"]) q.put((0, root)) while not q.empty(): Current_Node = q.get()[1] Expanded_Nodes +=1 mat = Current_Node.data...
def separator_3(): for item in '\n', '-' * 100, '\n': print(item) def separator_1(): print('-' * 100) def encrypt_ui(interface_selection): file_bytes_list = [] key_list = [] user_file_filename_list = [] try: if int(interface_selection) == 1: print(pyfiglet.figlet_fo...
The code displays a menu for encryption/decryption options (message/file) and routes user input to corresponding functions. It uses pyfiglet for a stylized title, separators for visual structure, and handles input validation to redirect to encrypt_ui or decrypt_ui with specific parameters, exiting on option 0 or retryi...
def interface(): separator_3() print(pyfiglet.figlet_format('BX-CRYPT', font='cybermedium')) separator_1() print('\n', '\n', 'ENCRYPTION OPTIONS: ', '\n', '\n', '1) ENCRYPT A MESSAGE 2) DECRYPT A MESSAGE', '\n', '\n', '3) ENCRYPT A FILE 4) DECRYPT A FILE', '\n', '\n', '0) EX...
def separator(): for item in '\n', '-' * 100, '\n': print(item) def encrypt_message(): message_list = [] key_list = [] encrypted_message_list = [] semantic_encryption_list = [] print(pyfiglet.figlet_format('ENTER MESSAGE TO ENCRYPT: ', font='cybermedium')) separator() message ...
The code defines an interface function that displays a menu for encryption/decryption options (message/file) and handles user input to route to corresponding functions like encrypt_message or decrypt_file. It includes error handling for invalid inputs, prompting retries with numerical keys.
def interface(): separator() print(pyfiglet.figlet_format('BX-CRYPT', font='cybermedium')) print('-' * 100) print() print() print('ENCRYPTION OPTIONS: ') print() print('1) ENCRYPT A MESSAGE 2) DECRYPT A MESSAGE') print() print('3) ENCRYPT A FILE 4) DECRYPT A F...
def sep(): for item in '\n', '-' * 100, '\n': print(item) def encrypt_message(): encrypted_msg = [] b64_encrypted_msg = [] print(pyfiglet.figlet_format('ENTER MESSAGE TO ENCRYPT:', font='cybermedium')) sep() in_msg = input() sep() in_key = input('ENTER KEY: ') key = in_key ...
The main task of the code is to display a menu-driven encryption tool interface, offering options for symmetric and asymmetric key encryption/decryption of messages and files, key generation, and exit. It captures user input to trigger corresponding functions like encrypt_message, decrypt_file, or exit, with placeholde...
def interface(): print('-' * 100) print(pyfiglet.figlet_format('B-CRYPTO-TOOL', font='cybermedium')) print('-' * 100 + '\n\n') print('SYMMETRICAL KEY ENCRYPTION OPTIONS:\n') print('1) ENCRYPT A MESSAGE 2) DECRYPT A MESSAGE\n') print('3) ENCRYPT A FILE 4) DECRYPT A FILE') s...
def get_color(piece_type): rep = hex(ord(piece_type)) if int(rep,16) < 0x265A: return 1 else: return 0 def get_piece_at_position(self, x, y): for piece in self.blackPieces: if piece.x==x and piece.y==y: return piece for piece in self.whitePieces: ...
This function generates all valid moves for the current player's pieces in a chess game, handling pawn movements (including en passant and promotions), knight jumps, bishop and rook diagonals/straights, queen's combined movements, and king's adjacent moves (including castling). It filters out self-check moves and retur...
def generate_all_moves(self, check=True): start = time.perf_counter() all_moves = [] pieces =[] if self.turnNum%2==1: pieces = self.whitePieces else: pieces = self.blackPieces for piece in pieces: #White Pawn Case ...
def is_terminal(self): return self.outcome[0] def generate_all_moves(self, check=True): start = time.perf_counter() all_moves = [] pieces =[] if self.turnNum%2==1: pieces = self.whitePieces else: pieces = self.blackPieces for piece...
This function generates all possible successor states of the current game state by first checking if the state is terminal (returning an empty list if so), then generating all valid moves, and creating a list of new states using each move. It returns the list of successor states.
def generate_all_successor_states(self): if self.is_terminal(): return [] moves= self.generate_all_moves(True) states = [self.generateSuccessor(move) for move in moves] return states
def ensureInitialStateIsClean(): bpy.ops.object.select_all(action='DESELECT') bpy.context.view_layer.objects.active = None # ensure we're not in 'edit mode' for mesh in bpy.data.meshes: if mesh.is_editmode == True: print("mesh ", mesh, "is in edit mode", file=sys.stderr) assert(mesh.is_editmode...
The code converts selected mesh and font objects in Blender to mesh data, cleans up unused meshes, applies transformations, and exports the result as a compressed file containing materials and mesh data.
def run(): # Isolate ourselves from the current obj/edit mode # and the current selection. ensureInitialStateIsClean() makeStandalone() bpy.ops.object.select_by_type(type='MESH') if len(bpy.context.selected_objects) > 0: bpy.context.view_layer.objects.active = bpy.context.selected_objects[0] bpy....
def add_edge_padding(x, filter_size): assert filter_size % 2 == 1 if filter_size == 1: return x a = (filter_size - 1) // 2 # width padding size pad = tf.pad( tf.zeros_like(x[:, :, :1]) - 1, [[0, 0], [a, a], [0, 0]] ) + 1 x = tf.pad(x, [[0, 0], [a, a], ...
This function performs a 1D convolution operation on input tensor `x` with configurable parameters like filter size, stride, and padding. It includes optional weight normalization, activation normalization, and edge padding adjustments. The function returns the transformed tensor after applying the convolution and norm...
def conv1d(name, x, n_out, filter_size=3, stride=1, padding="SAME", do_weightnorm=False, do_actnorm=True, edge_bias=True): with tf.variable_scope(name): if edge_bias and padding == "SAME": x = add_edge_padding(x, filter_size) padding = 'VALID' n_in = int(x.get_sha...
def funcs(file: ParsedGenFile) -> str: out: str = "" if len(file.functions) == 0: return out out += banner("function signature typedefs") out += func_typedefs(file.functions, lambda func, is_native: func_sig_name(file, func.name, is_native)) out += banner(file.libname()) out += f"class {...
The code generates Dart code from parsed files, including imports, banners, and structural elements (functions, enums, classes). It uses a type lookup table to process each file, concatenating generated content into a single output string for FFI-related bindings. Your return
def codegen(files: list[ParsedGenFile]) -> str: out = "" out += \ """// for native types & basic FFI functionality import 'dart:ffi'; // for string utils import 'package:ffi/ffi.dart'; // for @mustCallSuper import 'package:meta/meta.dart'; """ global lookup lookup = TypeLookup(files) for file in ...
def get_structure_name(self, structure_type: str, structure_decl: str) -> str: return structure_decl[len(structure_type) + 1:][:-2].strip() def strip_all(strings: list[str]) -> list[str]: return list(map( lambda string: string.strip(), strings )) def error(self, msg: str, line: str = '',...
This function parses a class definition from a list of strings, extracting its name, methods, and annotations. It processes each line, handling annotations, method definitions (checking for invalid parameters like 'struct_ptr'), and unsupported fields. It validates the class structure and returns a CodegenClass object ...
def parse_class(self, class_: list[str], annotations: list[CodegenAnnotation]) -> CodegenClass: name = self.get_structure_name("class", class_[0]) contents = class_[1:-1] out = CodegenClass(name, [], [], annotations) # lots of possibilities!! # - whitespace, clear annotations...
def get_part(self, contents: list[str], i: int): try: close_bracket_idx = contents[i:].index("}\n") except ValueError: # could be one at the end of the file with no newline after try: close_bracket_idx = contents[i:].index('}') except Value...
This code parses a source file into structured data by reading lines, identifying enums, classes, and functions, handling annotations, and validating them. It skips comments, processes code blocks, collects annotations, and returns a ParsedGenFile object with parsed elements and warnings.
def parse(self) -> ParsedGenFile: contents: list[str] with open(self.fname, "rt") as fh: contents = fh.readlines() out = ParsedGenFile( self.fname, [], [], [], [] ) skip = 0 annotations: list[CodegenAnnotation] = [] fo...
def calc_distance(point1, point2): sum_result = 0 dim1 = point1.split(",") dim2 = point2.split(",") for i in range(1, len(dim1)): temp = (float(dim1[i]) - float(dim2[i])) temp *= temp sum_result += temp return math.sqrt(sum_result) def insert_in_array(array, element): if...
The code performs k-nearest neighbors classification by calculating distances between a new point and all data points in the array, storing these with their corresponding points, then determining the predicted class and confidence through a polling mechanism on the nearest neighbors.
def predict_class(array, new_point): shortest_n = [] for data_point in array: distance = calc_distance(new_point, data_point) element = { "d": distance, "point": data_point } insert_in_array(shortest_n, element) predicted_class, confidence = take_poll...
def empty_at(pt): temp = pt.split(",") for i in range(len(temp)): if len(temp[i]) == 0: return i return -1 def find_min_max(all_data): min_max_array = [] for i in range(len(all_data[0].split(","))): element = { "min": 9999999, "max": -9999999 ...
The code generates synthetic data points by varying a specific feature (pt) in small increments, predicts class labels and confidence scores using a model, and plots the results to visualize how predictions change with feature variations. It iterates over a feature's min-max range, creates interpolated values, evaluate...
def partial_point(all_data, pt): x_values = [] y_values = [] y_values_2 = [] x = empty_at(pt) prog = 10 mul = 1 min_max_array = find_min_max(all_data) if x == 2: prog = 1 mul = 10 for i in range(min_max_array[x]["min"], min_max_array[x]["max"]): for j in ra...
def get_threshold(self): return self.thresholds def quote_rate(self, source_currency, target_currency): url = f"https://transferwise.com/gb/currency-converter/{target_currency}-to-{source_currency}-rate" while True: resp = requests.get(url, headers={'User-Agent': 'Mozilla/5.0'}) ...
This code monitors currency exchange rates, triggers automated money transfers when thresholds are met, and dynamically adjusts thresholds to continue monitoring. It displays real-time rates, countdowns, and threshold alerts for user tracking.
def start(self): print("AutoWise Refresh Rate: 1m\n") rate_index = 0 while True: # upper_threshold = currency.get_threshold()[0] user_threshold = self.get_threshold()[1] # lower_threshold = currency.get_threshold...
def buildNetwork(self, inputSpec, outputSpec): inputRect = MakeRect(inputSpec[1][0], inputSpec[1][1], inputSpec[1][2], inputSpec[1][3]) outputRect = MakeRect(outputSpec[1][0], outputSpec[1][1], outputSpec[1][2], outputSpec[1][3]) self.nodePos = [] self.nodeSize = [] nodeSurface ...
This code visualizes neural network weights by drawing lines between connected nodes, with colors determined by weight values via sigmoid and bilinear interpolation. It highlights specific nodes with red circles, rendering the weight visualization on a Pygame surface.
def glowWeights(self, l, weights): nodeSurface = self.buildNetwork(self.drawingConfig[0], self.drawingConfig[1]) matrix = self.network.weights[l].tolist() for item in weights: w = matrix[item[0]][item[1]] color = biLinearInterpolation(self.weightColorSpace[0], self.weight...
def drawNetwork(self): nodeSurface = self.buildNetwork(self.drawingConfig[0], self.drawingConfig[1]) self.drawWeights(self.screen, self.weightColorSpace) self.screen.blit(nodeSurface, (0,0)) def drawWeightMatrix(self, matrix, space): xPos = space[0] + 8 yPos = space[1] lo...
The code's main task is to visualize a neural network system by drawing its structure, weight matrix, and activation vectors in specified regions of a canvas. It calls `drawNetwork()` to render the network, `drawWeightMatrix()` to plot the second layer's weights in a defined rectangle, and `drawVector()` to display the...
def drawSystem(self): self.drawNetwork() self.drawWeightMatrix(self.network.weights[1], MakeRect(self.width, self.height, (0.3, 0.9), (0.52, 1.0))) self.drawVector(self.network.activations[1], MakeRect(self.width, self.height, (0.95, 1.0), (0.52, 1.0)))
def find_first_star(line): return star_pattern.search(line).span()[0] def check_line(alist, i, star_index): #assigning left and right indices, checking if against edge if star_index != 0: first_index = star_index - 1 else: first_index = star_index if star_index < (len(alist[i]) - 1)...
The code processes each line in 'alist' to find star patterns, calculates products from pairs identified by 'check_line', accumulates their sum, and prints the result.
def part2(): sum = 0 i = 0 for i in range(len(alist)): line = alist[i] while star_pattern.search(line) != None: star_index = find_first_star(line) result = check_line(alist, i, star_index) if len(result) == 2: sum += (result[0] * result[...
def _find_all_solutions(self, puzzle: list, unknowns: list, unfilled: list) -> list: assert len(unknowns) == len(unfilled) solutions = [] # Generate permutations and select feasible solutions for sequence in permutations(unfilled): valid = True ...
This code solves a Sudoku puzzle using logical deduction and backtracking. It iteratively identifies cells with unique possible values based on row, column, and grid constraints. If no progress is made, it performs backtracking by testing possible values in cells with the fewest options, recursively solving sub-problem...
def solve(self, puzzle: list, show_progress: bool = False) -> list: board = [[int(puzzle[row][col]) for col in range(9)] for row in range(9)] # Find solutions with solid evidence while True: step = 0 # Detect each row, column and grid position...
def rand_hash() -> bytes32: # TODO: address hint errors and remove ignores # error: Incompatible return value type (got "bytes", expected "bytes32") [return-value] return rand_bytes(32) def rand_g1() -> G1Element: sk = AugSchemeMPL.key_gen(rand_bytes(96)) return sk.get_g1() def rand_bytes(num...
This function generates a synthetic blockchain FullBlock using randomized components, including ProofOfSpace, RewardChainBlock, Foliage, and TransactionsInfo. It constructs mock data for blockchain elements like VDF proofs, coins, and cryptographic hashes, assembling them into a FullBlock object for testing or simulati...
def rand_full_block() -> FullBlock: proof_of_space = ProofOfSpace( rand_hash(), rand_g1(), None, rand_g1(), uint8(0), rand_bytes(8 * 32), ) reward_chain_block = RewardChainBlock( uint128(1), uint32(2), uint128(3), uint8(4), ...
def display(): display_line = "-" display_content = "|" for n in range(table_size): display_line = display_line + " - -" print(display_line) for n in range(table_size): display_content = table[n] display_content = str(display_content) display_content = display_content...
The code's main task is to prompt the user for replay confirmation after a game, validate input, and either restart the game (via 'Y') or exit (via 'N'). It handles empty inputs and invalid commands by looping until a valid choice is made, ensuring user interaction is properly managed before proceeding.
def replay(): global table_size table_size display() replay_confirmation = input("Do you wish to replay? (Y/N)").upper() if len(replay_confirmation) == 0: print("No input entered!") replay() elif replay_confirmation[0] == "Y": restarter() elif replay_confirmation[0...
def set_parameters(self, parameters): parameters = np.array(parameters) total_params = reduce(lambda a,b: a*b, np.array(parameters).shape) expected_params = self.dim_in * self.dim_h + self.dim_h**2 + self.dim_h * self.num_classes assert total_params == expected_params, ...
This code trains a neural network by updating its parameters (w_xh, w_hh, w_hy) using gradient descent over multiple epochs. It computes gradients of the loss with respect to these parameters, applies the learning rate to adjust weights, and evaluates the model's loss and accuracy after each epoch. The function returns...
def fit(self, parameters, config=None, epochs=3): """ Set the model parameters with parameters, """ self.set_parameters(parameters) get_grad = autograd.grad(self.get_loss, argnum=(2,3,4)) x, y = get_data(split=self.split) ...
def initialise_game(SnakePart, x_grid_size, y_grid_size): snake = [ SnakePart(x_grid_size//2, y_grid_size//2, "h"), SnakePart(x_grid_size//2, y_grid_size//2 + 1, "t") ] x_food, y_food = generate_food(snake, x_grid_size, y_grid_size) inertia = 0 return snake, inertia, x_food, y_food def gen_and_output_...
The code defines a main function for a snake game, initializing grid size, handling game loop, movement, collision detection, and win/loss conditions. It adjusts grid size to defaults if too small, manages snake movement, food generation, and checks game states (win, overlap, out-of-bounds) to terminate the loop with a...
def main(x_grid_size=grid_size_def, y_grid_size=grid_size_def): if x_grid_size <=min_grid_size and y_grid_size <= min_grid_size: x_grid_size = grid_size_def y_grid_size = grid_size_def print(f"Grid size too small, defaulting to {x_grid_size}x{y_grid_size}") SnakePart = namedtuple("SnakePart", "x y type"...
def valid_input(self, start, to): valid_pos = self.valid_pos(start, to) if valid_pos: valid_pos = self.is_piece(start) if valid_pos: valid_turn = self.correct_turn(start) if not valid_pos: self.error = f"Invalid Move: {start} to {to} \nInvalid...
This method executes a chess move by validating input, updating the board state, handling special moves like castling and promotion, and updating game logs. It checks for move validity, updates piece positions, tracks move history, and detects checkmate. If valid, it updates the board visualization, counter, and logs t...
def move(self, start, to): # TODO : ghost board? -theres some redundancy in updating the logic board and visual board # MAYBE ADD IN THE BOARD START TO VARIABLES AS CLASS ATTRIBUTES AND UPDATE THEM HERE WHEN ITS VALID? # THAT WAY WE DONT HAVE TO CONSTANTLY PASS IN VARIABLES FOR METHODS ...
def x_diff(self, start, to): """ Returns the difference between start and end x positions given two position pairs Can be negative """ x1 = letters.index(start[0]) x2 = letters.index(to[0]) return x2 - x1 def enemy_king(self, board): return [value ...
This code checks if any enemy piece can block the line of sight between the current position and the enemy king, returning True if a blocking move is possible. It calculates direction vectors, iterates along the path, and tests enemy pieces' ability to move to potential blocking positions, crucial for determining legal...
def block(self, board, to): # Find the diagonal / line from checking piece to king # Done via if board[to].get_name() not in ['N', 'K']: x_diff = self.x_diff(to, self.enemy_king(board).pos()) y_diff = self.y_diff(to, self.enemy_king(board).pos()) i, j = self....
def enemy_king(self, board): return [value for value in self.enemy_pieces(board) if value.get_name() == 'K'][0] def escape(self, board): vector =[ [-1, 1], [0, 1], [1, 1], [-1, 0], [1, 0], [-1,-1], [0,-1], [1,-1] ] ...
This function checks if the current player is in checkmate by verifying if the enemy king's move to position 'to' is valid. If valid, it returns whether the player cannot escape, capture, or block the enemy king, indicating checkmate. Otherwise, it returns False.
def mate(self, board, to): if board[to].is_valid_move(board, to, self.enemy_king(board).pos()): return not (self.escape(board) or self.capture(board, to) or self.block(board, to)) return False
def getValidMoves(board, tile): # Returns a list of [x,y] lists of valid moves for the given player on the given board. validMoves = [] for x in range(8): for y in range(8): if isValidMove(board, tile, x, y) != False: validMoves.append([x, y]) return validMoves def i...
The function determines the computer's optimal move by prioritizing corner positions if available, otherwise selecting the move that yields the highest score by simulating each valid move and evaluating the resulting board state.
def getComputerMove(board, computerTile): # Given a board and the computer's tile, determine where to # move and return that move as a [x, y] list. possibleMoves = getValidMoves(board, computerTile) # randomize the order of the possible moves random.shuffle(possibleMoves) # always go for a cor...
def getNewBoard(): # Blanks out the board it is passed, except for the original starting position. board = {} for x in range(8): for y in range(8): board[(x, y)] = ' ' # Starting pieces: board[(3, 3)] = 'X' board[(3, 4)] = 'O' board[(4, 3)] = 'O' board[(4, 4)] = 'X' ...
The main task of the code is to run a turn-based game where a player and computer alternately place tiles on a board, following valid moves until no moves remain. It initializes the game, handles player input, executes computer moves, checks for game-ending conditions, and displays the final board and score.
def main(): # Reset the board and game. mainBoard = getNewBoard() playerTile, computerTile = enterPlayerTile() isPlayersTurn = True while True: if getValidMoves(mainBoard, 'X') == [] and getValidMoves(mainBoard, 'O') == []: break # Neither player can move, so quit. if i...
def file_to_dict(file): """Dump json file to dict variable""" with open(file) as f: return json.load(f) def get_meshes_by_armature(arm): """Return list of mesh objects that has armature modifier pointing to armature object arm""" res = [] for ob in [ob for ob in bpy.data.objects if ob.type =...
The code merges and renames vertex groups (VGs) from an input armature to a destination armature using a provided data dictionary. It loads input data, identifies meshes linked to the input armature, updates bone mappings, merges overlapping VGs, renames remaining VGs, and updates armature modifiers to the destination ...
def transfer_weights_from_dict(input_data, input_arm, dest_arm): """Merge and rename vertex groups basing on input dictionary or json file""" # Get input data if isinstance(input_data, str): data = file_to_dict(input_data) else: data = input_data # Get only meshes which have armature...
def sort_data_by_class(self): if self.x is None: print('Firstly you have to separate x and y') return False z = [(x, y) for y, x in sorted(zip(self.y, self.x), key=lambda pair: pair[0])] self.x = np.array(z[0][0]) self.y = np.array(z[0][1]) for i in range...
This function splits a dataset into training and test sets with equal class distribution. It first sorts data by class if needed, splits data per class, shuffles each class, then allocates a proportion (1-test_size) to training and the rest to testing. The result is four arrays: training and test features (x) and label...
def get_training_test_set_in_equal_portion(self, test_size=0.2, is_data_sorted=True): if not is_data_sorted: self.sort_data_by_class() classes_length = self.get_classes_length() x = np.split(self.x, classes_length) y = np.split(self.y, classes_length) training_x = n...
def get_all_edges(): author_to_file_paths = get_author_to_file_paths() module_nodes = get_all_module_nodes() contributor_nodes = get_all_contributor_nodes() # TODO: add num files changed in a module edges = [] def num_files_changed_in_this_module(changed_file_paths, module_name): counter...
The function `get_data_for_vis` retrieves and organizes data for visualization by collecting all edges, nodes, and categorizing nodes into contributors and modules. It returns module nodes, contributor nodes, and edges to enable graph or network visualization, likely for analyzing relationships or structures between co...
def get_data_for_vis(): # Edges all_edges = get_all_edges() # Nodes all_nodes = get_all_nodes() contributor_nodes = get_all_contributor_nodes() module_nodes = get_all_module_nodes() return module_nodes, contributor_nodes, all_edges
def _print_prompts(self): prompts = { "client_system_prompt": self.client_bot.system_prompt, "counsellor_system_prompt": self.counsellor_bot.system_prompt, "evaluator_system_prompt": self.eval_bot.system_prompt if self.eval_bot else None, } ...
This code manages a structured dialogue between a client, counsellor, and evaluator, alternating turns to generate responses using OpenAI models. It tracks conversation progress, monitors price/turn limits, and uses an end classifier to determine termination. The loop transitions between states ("counsellor," "client,"...
def converse( self, client_openai_obj, counsellor_openai_obj, evaluator_openai_obj, end_classifier_openai_obj, ): counsellor_turn = None client_turn = None running_counts = {} self._print_prompts() try: while self.state != ...
def menu_view(self): menu_objects = [] star = Star(10**13, (self.screen_size[0]/2, self.screen_size[1]/2), (0, 0), 15, [255, 255, 0]) planet = Planet(5*10**9, (500, 500), (0, 1), 5, self.fps, [0, 0, 255], self.inputs["trails"]) font = pygame.font.Font(None, 100) title = font.ren...
The code manages application views by continuously checking the `self.views` dictionary. It runs an infinite loop, displaying the `menu_view`, `game_view`, or `edit_view` based on which key in `self.views` is set to `True`. The initial state shows the menu, and transitions between views depend on updating the correspon...
def run(self): self.views = {"menu": True, "game": False, "edit": False} while True: if self.views["menu"] == True: self.menu_view() elif self.views["game"] == True: self.game_view() elif self.views["edit"] == True: self...
def Allocate(self): # Retrieve Data From TextBox process_entry = self.SegmentTextBox.toPlainText().split('\n') process_name = "P" + str(self.current_process_name) process_data = {} print("Process Entry:", process_entry) for segment in process_entry: if segment...
This code sets up a graphical user interface (GUI) for a "Processes" application. It creates UI elements like radio buttons for memory allocation algorithms (First Fit, Best Fit, Worst Fit), a text box for inputting process segments, buttons to allocate/deallocate processes, and a combo box to select processes. The int...
def setupUi(self, Processes): Processes.setObjectName("Processes") Processes.resize(513, 473) self.label = QtWidgets.QLabel(Processes) self.label.setGeometry(QtCore.QRect(40, 50, 201, 21)) self.label.setObjectName("label") self.radioGroup = QtWidgets.QGroupBox(Processes) ...
def _state(self, action: str, token_dict: dict = None) -> bool: """Sets the session state for the Client Library. ### Arguments ---- action : str Defines what action to take when determining the state. Either `load` or `save`. token_dict : dict, optional...
The main task of the code is to authenticate a user by first attempting silent SSO login. If unsuccessful, it redirects the user to an authorization URL, waits for the user to paste the authentication redirect URL, extracts the code, retrieves an access token, and finally establishes a GraphSession for the authenticate...
def login(self) -> None: """Logs the user into the session.""" # Load the State. self._state(action="load") # Try a Silent SSO First. if self._silent_sso(): # Set the Session. self.graph_session = GraphSession(client=self) return True ...
def read_next_token(self): self.current_token_idx += 1 if self.current_token_idx < len(self.token_list): self.current_token = self.token_list[self.current_token_idx] def syntax_condition(self): # BOOL if self.current_token in grammar.boolean: return self.current_...
This code parses an 'if' statement by checking the condition, validating braces, and handling nested structures. It reads tokens, verifies syntax, and processes code blocks with error handling for mismatched brackets or invalid tokens.
def syntax_if(self): self.read_next_token() # read condition condition = self.syntax_condition() # read ( self.read_next_token() if self.current_token != "{": self.syntax_error("expected {") return self.read_next_token() ...
def read_next_token(self): self.current_token_idx += 1 if self.current_token_idx < len(self.token_list): self.current_token = self.token_list[self.current_token_idx] def syntax_if(self): self.read_next_token() # read condition condition = self.syntax_condition() ...
The main task of the code is to process a list of tokens in a loop, handling syntax elements like "if", "var", and "fmt.Println" by invoking corresponding methods, skipping dividers, and raising errors for unexpected tokens until all tokens are processed.
def mainloop(self) : while self.current_token_idx < len(self.token_list): if self.current_token == "\n": self.read_next_token() elif self.current_token == "if": self.syntax_if() elif self.current_token == "var": self.syntax_var() elif self.current_token == "fmt.Pr...
def sexpr_to_str(l): return str(l).replace('[', '(').replace(']', ')').replace(',', '').replace('\'', '') def interp(exp, env_id=BASE_ENV_ID): if isinstance(exp, numbers.Number): return exp elif isinstance(exp, str): return lookup_value(exp, globalenv[env_id]) elif isinstance(exp, list):...
The code defines an `interpret` function that processes an input expression by parsing it, evaluating the parsed expression using an interpreter, and converting the result into a string representation for output.
def interpret(exp): return sexpr_to_str(interp(parse(exp)))