dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def reverse(film_motor, folder=None): want_to_reverse = 'not y, n, or empty' while not want_to_reverse.lower() in ('y', 'n', ''): want_to_reverse = input("Do you want to reverse [y/n] (Default 'n'): ") if want_to_reverse.lower() in ('n', ''): pass elif want_to_reverse.lower() == 'y'...
The main task of the code is to initialize and control two DRV8825 stepper motors (film and take-up) for a mechanical system, configure their microstepping modes, adjust motor delays, execute a reverse operation, load user settings, and run a user interface. It includes error handling and cleanup procedures to stop mot...
def main(): film_motor = DRV8825(step_angle=1.8 ,dir_pin=13, step_pin=19, enable_pin=12, mode_pins=(16, 17, 20)) takeup_motor = DRV8825(step_angle=1.8 ,dir_pin=24, step_pin=18, enable_pin=4, mode_pins=(21, 22, 27)) # Setup with camera controls film_motor.SetMicroStep('softward','fullstep') takeup_m...
def store_public_key(sender_public_key: str): """ Store the public key of the sender in the keys dictionary. Return True if the key already exists in the dictionary, False otherwise. """ global keys client_username, _, key = sender_public_key.partition(':') key = key.encode() key = seria...
The main task of the code is to receive and process messages from a server using a socket, display them in a curses-based window, and handle different message types such as joining/leaving rooms, public key exchange, and decrypted simple messages. It creates a dedicated message display area, parses incoming JSON data, ...
def receive_messages(sock, stdscr): """ Receive and process messages from the server. """ global finished, receiver_win # Create the receiver window receiver_win = stdscr.subwin(receiver_max_row, curses.COLS, 0, 0) receiver_win.bkgd(' ', green_on_black) # Set background color receiver_...
def init_model(config, checkpoint, device='cuda:0'): """Initialize a model from config file, which could be a 3D detector or a 3D segmentor. Args: config (str or :obj:`mmcv.Config`): Config file path or the config object. checkpoint (str, optional): Checkpoint path. If left as N...
The main task of the code is to perform 3D object detection inference on LiDAR point cloud data using a pretrained deep learning model. It processes both sample and sweep PCD files, extracts bounding boxes and labels for each scan, and stores the results in a structured dictionary format. The output is saved as a pickl...
def generate_inference_data(config_file, pretrained_network, root_directory_for_pcd_path,inference_out_path): model = init_model(config_file, pretrained_network) lidar_inference_result = {} lidar_inference_result['file_name']=[] lidar_inference_result['bboxes']=[] lidar_inference_result['labels']=[]...
def parse_args(): parser = argparse.ArgumentParser(description='MMDet test (and eval) a model') parser.add_argument('--config', help='test config file path') parser.add_argument('--checkpoint', help='checkpoint file') parser.add_argument('--out_dir', help='output result file in pickle format') parse...
The main task of the code is to perform 3D object detection on LiDAR point cloud data using a pre-trained model. It processes multiple `.pcd.bin` files from a specified directory, runs inference to extract 3D bounding boxes and labels, organizes results in a structured dictionary, and saves the output as a pickle file ...
def main(): args = parse_args() model = init_model(args.config, args.checkpoint) print lidar_inference_result = {} lidar_inference_result['file_name']=[] lidar_inference_result['bboxes']=[] lidar_inference_result['labels']=[] #notice the order would be reversed after the glob.glob functi...
def __load_table__(self, table_name) -> dict: """ Loads a table. """ with open(osp.join(self.table_root, '{}.json'.format(table_name))) as f: table = json.load(f) return table def load_lidarseg_cat_name_mapping(self): """ Create mapping from class index to class name, and vic...
This code initializes a NuScenes dataset loader by loading version-specific tables (e.g., categories, instances, annotations), creating reverse indexes for efficient lookups, and setting up data structures like colormap and MapMask. It also handles optional lidar segmentation/panoptic data, validates file consistency, ...
def __init__(self, version: str = 'v1.0-mini', dataroot: str = '/data/sets/nuscenes', verbose: bool = True, map_resolution: float = 0.1): """ Loads database and creates reverse indexes and shortcuts. :param version: Version to l...
def get(self, table_name: str, token: str) -> dict: """ Returns a record from table in constant runtime. :param table_name: Table name. :param token: Token of the record. :return: Table record. See README.md for record details for each table. """ assert table_name...
The main task of the code is to retrieve sample data and its associated annotations, transforming the annotations into the sensor's coordinate system (or ego vehicle frame) based on parameters, and returning the data path, transformed bounding boxes, and camera intrinsic matrix. It handles visibility checks for camera ...
def get_sample_data(self, sample_data_token: str, box_vis_level: BoxVisibility = BoxVisibility.ANY, selected_anntokens: List[str] = None, use_flat_vehicle_coordinates: bool = False) -> \ Tuple[str, List[Box], np.array]: """ ...
def malaria(): ## the structure of this object is [[path to infected images], [path to normal images], [path to unfected test images], [path to normal test images]]. The int after is the desired output from the model. malaria_folders = [['/root/Documents/workspace/ai/FINAL_PROJ/malaria/cell-images-for-detecting-mal...
The main task of the code is to initialize and execute three distinct model-building processes by sequentially calling the `malaria()`, `pmna()`, and `cancer()` functions within the `main()` function, likely for separate analytical or predictive modeling tasks related to malaria, PMNA (possibly a dataset or condition),...
def main(): ## start the three different models building malaria() pmna() cancer()
def is_ccinc(pdg_list): if 13 in pdg_list or -13 in pdg_list: return True return False def is_event_contained(event): if not is_muon_tagged(event): return False if not is_hadronic_contained(event): return False return True def get_neutrino_4mom(groo_event): ## Loop over ...
The main task of the code is to analyze particle physics simulation data to study the containment efficiency of charged current inclusive (CC-INC) events. It processes multiple ROOT files, calculates Q² values for true and reconstructed events, and evaluates pion energy reconstruction accuracy. Histograms track Q² dist...
def test_containment(infilelist): ## Get the file(s) edep_tree = ROOT.TChain("EDepSimEvents") groo_tree = ROOT.TChain("DetSimPassThru/gRooTracker") ## Loop over the file list and add them to the chain for file in infilelist: ## Allow for escaped wildcards in the input... for f in g...
def clear_screen(): os.system("cls" if os.name == "nt" else "clear") def display_product(): clear_screen() table_product = [] with open("UAS-SEM1/kasir/Data-product.txt", "r+") as file_produk: products = file_produk.readlines() products = [x.strip("\n") for x in products] w...
The main task of the code is to process a customer transaction by collecting product selections, updating product stock quantities, generating an invoice with itemized costs, and handling errors. It reads product data, allows users to input buyer details and selected items, adjusts inventory, and prepares an invoice (c...
def main_transaction(): clear_screen() update_produk = [] invoice = [] produk_pilihan = [] with open("UAS-SEM1/kasir/Data-product.txt", "r+") as file_produk: products = file_produk.readlines() products = [x.strip("\n") for x in products] while True: display_pro...
def tampilkan_buku(): print("\n") print("Daftar buku di perpustakaan Kelompok 1") daftar_buku.clear() # Membuat table untuk keperluan menggunakan "tabulate", # data dibawah ini dijadikan sebagai header. table_buku = [ ["ID", "Judul Buku", "Pengarang", "Jmlh. Halaman", "Stok buku"] ]...
The code defines a 'welcome' function that displays a library management system menu, allowing users to view books, add books, borrow books, return books, or exit. It loops until the user selects option 5, validates input, and calls corresponding functions while handling errors.
def welcome(): while True: print("\n") print("+====================================================+") print("| SELAMAT DATANG DI PERPUSTAKAAN KELOMPOK 1 |") print("+----------------------------------------------------+") print("| 1 - Untuk menampilkan daftar buku ...
def main_transaction(): clear_screen() update_produk = [] invoice = [] produk_pilihan = [] with open("UAS-SEM1/kasir/Data-product.txt", "r+") as file_produk: products = file_produk.readlines() products = [x.strip("\n") for x in products] while True: display_pro...
The main task of the code is to display a menu-driven interface for a gadget store cashier application, allowing users to select options for transactions, product management, or logout. It loops until logout is chosen, validates input, handles errors, and directs to corresponding functions like transaction, display, ad...
def welcome(): while True: print("\n") print("+========================================+") print("| Kelompok 1 - Gadget Store Cashier App |") print("+----------------------------------------+") print("| 1 - Main Transaction |") print("| 2 - Display ...
def _split_coprus(self, text: str) -> typing.List[str]: """Splits corpus -- a collection of documents stored in one .txt file, as a text delimited with special chars -- into a list of documents.""" return re.split(self.DOCUMENT_SEPARATOR, text) def _parse_document(self, document: str) -> JSON: ...
The main task of the code is to parse a text-based corpus into a semi-structured JSON format by splitting the input text into documents, parsing each document into structured data, filtering out empty results, and flattening the parsed fields into a list of JSON objects for output.
def parse(self, text: str) -> typing.List[JSON]: """Parses .txt export into semi-structure format.""" data = [] documents = self._split_coprus(text) for document in documents: parsed_document = self._parse_document(document) if len(parsed_document) != 0: ...
def single_qubit_gate(self): ''' Returns general single qubit gate in noise free regime ''' #X-gate > theta = np.pi theta = self.theta phi = self.phi U = np.array( [[np.cos(theta/2), - 1J * np.sin(theta/2) * np.exp(-1J * phi)], [- 1J * np...
The function constructs a modified quantum gate by combining a single-qubit gate with exponentials of determinant and stochastic matrix components. If `ev=1`, it uses `single_qubit_gate()` with `__det_part_s()` and `__stoch_part_s()`. If `ev=0`, it uses `single_qubit_gate_rest()` with `__det_part_1()` and `__stoch_part...
def __modify_gate_s(self, ev = 0): if ev == 1: U = self.single_qubit_gate() result = U @ scipy.linalg.expm(self.__det_part_s()) @ scipy.linalg.expm(self.__stoch_part_s()) #result = U @ scipy.linalg.expm(self.__stoch_part_s()) if ev == 0: U = self.single_...
def single_qubit_gate_ryd_ham(self): omega = self.omega delta = self.delta H = np.array([[0, omega/2, 0, 0], [omega/2, -delta, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]) return H def __det_part_r(self, ham): ...
This function simulates the time evolution of a single qubit quantum state under a sequence of single-qubit gates. It calculates probability distributions (p0, p1, pd) at each step by applying modified unitary gates derived from a Hamiltonian. The initial state ψ₀ is evolved through N gate applications, with results st...
def singlequbit_single_run(self, psi_0, N): ''' The actual run function. psi_0 > has to be for single qubit N > number of single qubit gates. ''' results_p0 = np.zeros([N]) results_p1 = np.zeros([N]) results_pd = np.zeros([N]) re...
def two_qubit_gate_rest(self): U = np.diag([1,1,1,1]) return U def __det_part_d(self): ''' Deterministic part calculation. ''' eps_1_ctr = np.sqrt(self.__get_lams(1,1)) eps_2_ctr = np.sqrt(self.__get_lams(2,1)) eps_1_trg = np.sqrt(self.__...
The function `modify_gate_d` constructs a quantum gate by combining a selected two-qubit gate (either `two_qubit_gate_rest` or `two_qubit_gate`) with matrix exponentials of determinant and stochastic components. It returns a list containing the resulting composite matrix and a temporary component from the stochastic pa...
def modify_gate_d(self, ev = 1): if ev == 0: U = self.two_qubit_gate_rest() result = U @ scipy.linalg.expm(self.__det_part_d()) @ scipy.linalg.expm(self.__stoch_part_d()[0]) tmp = self.__stoch_part_d()[1] if ev == 1: U = self.two_qubi...
def single_qubit_gate_ryd(self): o_p, t, d, o, gam1, gam2, gamr = sp.symbols('o_p, t, d, o, gam1, gam2, gamr', real = True) x1, x2 = sp.symbols('x1, x2') U = sp.Matrix(([sp.exp(1J*d*t/2)*(sp.cos(o_p/2*t) - 1J*d/o_p*sp.sin(o_p/2*t)), sp.exp(1J*d*t/2)*(-1J*o*x1/o_p*sp.sin(o_p/2*t...
The code simulates the application of multiple single-qubit gates (N gates) on an initial quantum state (psi_0), calculating the probability of the resulting state after each gate. It uses symbolic computation and numerical evaluation to generate gate matrices, applies them iteratively to the state, and averages result...
def singlegate_runs(self, psi_0, N, shots, params): ''' The actual run function. psi_0 > has to be for single qubit N > number of single qubit gates. ''' K_array = self.K_array results_st1 = np.zeros([N, shots]) o_p, t, d...
def single_qubit_gate_ryd(self): o_p, t, d, o, gam1, gam2, gamr = sp.symbols('o_p, t, d, o, gam1, gam2, gamr', real = True) x1, x2 = sp.symbols('x1, x2') U = sp.Matrix(([sp.exp(1J*d*t/2)*(sp.cos(o_p/2*t) - 1J*d/o_p*sp.sin(o_p/2*t)), sp.exp(1J*d*t/2)*(-1J*o*x1/o_p*sp.sin(o_p/2*t...
The function `singlequbit_single_run` simulates the time evolution of a two-qubit quantum state under a sequence of single-qubit gates, calculating the probabilities of specific measurement outcomes (p0, p1, pd) at each step. It initializes result arrays, constructs unitary and stochastic matrices from parameters, appl...
def singlequbit_single_run(self, psi_0, N, params): ''' The actual run function. psi_0 > has to be for two qubit N > number of two qubit gates. ''' K_array = self.K_array results_p0 = np.zeros([N]) results_p1 = np.zeros([N]) resu...
def get_posts_from_database(self): posts_list = posting.get_all_posts() if posts_list is not None: routing.flush_posts() for post in posts_list: if ("image_name" in post) and ("image_path" in post) and ("username" in post): routing.create_route...
This function parses HTTP request headers and content, extracts method, URI, and headers, handles content-length overflow, decodes text content, processes cookies, and routes requests. It specifically handles GET (WebSocket key extraction), POST (multipart/form-data parsing with upload handling), and returns 404 for PU...
def get_headers(self, received_data): decoded_data = received_data.split(b'\r\n\r\n', 1) content = decoded_data[1] data_types = decoded_data[0].decode().split(' ', 2) request_method = data_types[0] request_uri = data_types[1] http_content = data_types[2].split('\r\n', 1) ...
def get_dialog_train_set_path(path): return os.path.join(path, 'chat') def get_dialog_dev_set_path(path): return os.path.join(path, 'chat_test') def create_vocabulary(vocabulary_path, data_path, max_vocabulary_size, tokenizer=None, normalize_digits=True): if not gfile.Exists(vocabulary...
The function prepares dialog dataset by generating a vocabulary file and converting text data into token IDs for both training and development sets, returning the paths to these processed files and the vocabulary.
def prepare_dialog_data(data_dir, vocabulary_size): train_path = get_dialog_train_set_path(data_dir) dev_path = get_dialog_dev_set_path(data_dir) vocab_path = os.path.join(data_dir, "vocab%d.in" % vocabulary_size) create_vocabulary(vocab_path, train_path+".in", vocabulary_size) train_ids_path = tr...
def init_gradients(layers_dim, m): grads = { "dW": [], "db": [], } for l in range(len(layers_dim) - 1): grads["dW"].append(np.zeros((layers_dim[l+1], layers_dim[l]))) grads["db"].append(np.zeros((layers_dim[l+1], 1))) return grads def full_forward_prop(X, params, layers_d...
This function trains a neural network using gradient descent by performing forward and backward propagation over multiple iterations. It updates model parameters, computes loss, tracks training progress, and optionally prints loss values. The process involves initializing gradients, iterating through epochs, calculatin...
def train_model(X, Y, params, layers_dim, activations, alpha, n_iters, step_save, verbose=None): L = len(layers_dim) - 2 m = X.shape[1] errors = { "iters": [], "losses": [] } grads = init_gradients(layers_dim, m) for iter in range(0, int(n_iters)): params["Z"], params["A"...
def get_item_name(item_id): global item_data if item_data is None: item_data = download_item_data() item_name = None if item_data and str(item_id) in item_data['data']: item_name = item_data['data'][str(item_id)]['name'] return item_name def get_item_url(item_id): global item...
This function processes game item events to update a player's build order and final build list. It handles ITEM_PURCHASED by adding items to both lists, removes items for ITEM_SOLD/DESTROYED, and processes undo events. The core task is tracking item acquisitions and modifications in a game context through event-driven ...
def process_item_events(event, build_order, final_build): if 'itemId' not in event: return item_name = get_item_name(event['itemId']) item_icon_url = get_item_url(event['itemId']) purchase_time = event['timestamp'] if event['type'] == 'ITEM_PURCHASED': final_build.append([item_name...
def find_participant_id(match, summoner_name): for participant in match['info']['participants']: if participant['summonerName'].lower() == summoner_name.lower(): return participant['participantId'] return None def get_gold_lead_15(timeline, participant_id): for frame in timeline['info'][...
The main task of the code is to retrieve detailed match statistics for a specific summoner, including gold lead at 15 minutes, item build orders, runes, team champions, and game timestamp, using a provided match ID and summoner name. It fetches data from the API, identifies the summoner's participant ID, and extracts r...
def get_match_details(match_id, summoner_name): ''' This function retrieves the details of a specific match for a given summoner. Args: match_id (int): The ID of the match to retrieve details for. summoner_name (str): The name of the summoner whose match details are to be retrieved. ...
def find_point_for_secret_line(secret, points): """ This function finds a point from the points list that shares at least one coordinate with the secret point (geheimnis). Args: geheimnis: The secret point, as a list of coordinates. points: A list of available points, each represented a...
The function implements a threshold encryption scheme in projective space over a finite field. It generates a secret point, constructs a secret line, identifies intersecting hyperplanes, and selects splitters in general position. The process requires a prime field order and dimension >1, returning secret line points an...
def t_threshold_encrypt(dimension, order): """ This function implements the threshold scheme encryption. It generates a random secret point in a projective space and finds another point on the same line. It then generates all hyperplanes in the space and finds those that intersect the secret line. F...
def generateSubKeys(self, key256): """ Function that creates subkeys needed for encryption from initial value of given key Parameters: key256 (int): Given key Returns: keys (list) : List of integer values of subkeys to be used for encryption c_...
The function encrypts plaintext (PT) using the Kuznyechik algorithm with a given key. It generates subkeys and constants, applies 9 rounds of transformations (L, S, X) on PT with subkeys, followed by a final transformation. It returns lists of constants, subkeys, and intermediate PT values for visualization during encr...
def encryptKuznyechik(self, PT, key): """ Function that encrypts given input with given key using Kuznyechik algorithm Parameters: PT (int): Plain text repsented as int value key (int): Key to be used for encryption represented as int value Returns: c_list (list) : Lis...
def generateSubKeys(self, key256): """ Function that creates subkeys needed for encryption from initial value of given key Parameters: key256 (int): Given key Returns: keys (list) : List of integer values of subkeys to be used for encryption c_...
The function decrypts the input ciphertext (CT) using the Kuznyechik algorithm with the provided key. It generates subkeys, applies inverse operations (S_inverse, L_inverse) and XOR (X) in 9 rounds, storing intermediate results in OT_list. The final step applies the first subkey's XOR, returning all round outputs as a ...
def decryptKuznyechik(self, CT, key): """ Function that encrypts given input with given key using Kuznyechik algorithm Parameters: CT (int): Cipher text repsented as int value key (int): Key to be used for decryption represented as int value Returns: OT_list (list) : L...
def _createBookTab(self): self.tabs.addTab(self.order_tab,"Book a trip") self.accountInfo = self._getAccountInfo() conn = psycopg2.connect(database="postgres", user="arshegor", password="", ...
This code initializes a UserWindow GUI with a vertical layout and multiple tabs (Account, Order, Logout) using PyQt. It sets up a tabbed interface by creating and adding three QWidget tabs to a QTabWidget, which is then added to the layout. The login parameter is stored for later use, and private methods (_createBookTa...
def __init__(self, login): super(UserWindow, self).__init__() self.login = login self.vbox = QVBoxLayout(self) # Initialize tab screen self.tabs = QTabWidget() self.account_tab = QWidget() self.order_tab = QWidget() self.logout_tab = QWidget() ...
def _create_drivers_salaries_tab(self): self.tabs.addTab(self.drivers_salaries_tab, "Drivers salaries") self.vboxDriversS = QVBoxLayout() self.updateDriversSalariesButton = QPushButton("Update") self.driversSalariesTable = QTableWidget() self.driversSalariesTable.setColumnCoun...
This code initializes a GUI window for an accountant application, creating a vertical layout with multiple tabs (drivers' salaries, workers' salaries, workers management, and logout) to manage payroll and user data, using PyQt/PySide framework
def __init__(self, login): super(AccountantWindow, self).__init__() self.login = login self.vbox = QVBoxLayout(self) # Initialize tab screen self.tabs = QTabWidget() self.drivers_salaries_tab = QWidget() self.workers_salaries_tab = QWidget() self.worker...
def _create_books_tab(self): self.tabs.addTab(self.order_tab, "Orders") self.vboxOrders = QVBoxLayout() self.updateButton = QPushButton("Update") self.ordersTable = QTableWidget() self.ordersTable.setColumnCount(13) self.ordersTable.setHorizontalHeaderLabels(...
The main task of the code is to initialize a GUI window with multiple tabs for managing drivers, orders, cars, users, and logout functionality. It sets up a vertical layout containing a QTabWidget with several QWidget-based tabs, each initialized via private methods like _create_driver_tab and _create_users_tab, provid...
def __init__(self, login): super(ManagerWindow, self).__init__() self.login = login self.vbox = QVBoxLayout(self) # Initialize tab screen self.tabs = QTabWidget() self.driver_tab = QWidget() self.order_tab = QWidget() self.cars_tab = QWidget() s...
def findExplodePair(node): if node == None: return None left = findExplodePair(node["left"]) if left: return left right = findExplodePair(node["right"]) if right: return right if node["depth"] >= 4 and not isLeaf(node): return node return None def explode(pair...
The main task of the code is to recursively reduce a tree structure by either exploding pairs or splitting leaves until no further reductions are possible, ensuring the tree is simplified according to defined rules.
def reduce(tree): reduced = False if findExplodePair(tree) != None: reduced = True explode(findExplodePair(tree)) elif findSplitLeaf(tree) != None: reduced = True split(findSplitLeaf(tree)) if reduced: reduce(tree)
def get_player_a(self): """ Purpose: To return the first Player object. :return: Player A object """ return self._player_a def get_player_b(self): """ Purpose: To return the second Player object. :return: Player B object """ return self._pl...
The main task of the code is to determine if a specified player has any legal moves available on the board by checking their marbles. It identifies the player's color based on their name, then uses a recursive method to examine the board. It returns `True` if at least one legal move exists, and `False` if no moves are ...
def legal_moves_available(self, playername): """ Purpose: This method checks all of the player's marbles on the board, to see if a player has no legal moves available. :return: True if a moves is available False if a player has no moves available on the board. ""...
def crearPoblacion(): poblacionArboles = [crearIndividuo() for i in range(cantidadIndividuos)] return poblacionArboles def seleccion(poblacionArboles): fitnessRate = [(fitness(arbol), arbol) for arbol in poblacionArboles] fitnessRate = [arbol[1] for arbol in sorted(fitnessRate, reverse=True)] selecc...
The code executes a genetic algorithm to evolve a population over multiple generations. It iteratively selects, reproduces, and mutates individuals to optimize parameters like thickness, angles, and decay rates. After evolution, it prints the final optimized values and displays a target tree image using OpenCV.
def runAlgoGenetico(): poblacion = crearPoblacion() for i in range(cantidadGeneraciones): print('________________________________') print('GENERACION: ', i) print('GROSOR: ', poblacion) seleccionados = seleccion(poblacion) poblacion = reproduccion(poblacion, selecciona...
def get_col_n_list(self, MDell_feat, LDell_feat, GW_feat, DC_feat): #Mtn dell MDell_predict= [] MDell_col = MDell_feat.columns #lil Dell LDell_predict = [] LDell_col = LDell_feat.columns #GW GW_predict = [] GW_col = GW_feat.columns #GW ...
The main task of the code is to predict values for multiple water system components (Mountain Dell, Little Dell, GW, DC) under different climate scenarios (Low, Average, High) using pre-trained XGBoost models. It dynamically updates feature dataframes during prediction, applies physical constraints to outputs, and gene...
def WSM_Predict(self): #Set up the target labels #Mountain Dell self.MDell = 'Mtn_Dell_Percent_Full' self.MDell_Pred = self.MDell+'_Pred' self.MDell_Pred_Low = self.MDell_Pred+'_Low' self.MDell_Pred_Hig = self.MDell_Pred+'_Hig' self.MDell_Initial = self.MDell+'...
def HistoricalAnalysis(self): print('Calculating historical water system component means to create baseline for comparison with prediction') targets = ['SLCDPU_GW', 'Mtn_Dell_Percent_Full', 'LittleDell_Percent_Full','SLCDPU_DC_Water_Use'] pbar = ProgressBar() for comp...
The main task of the code is to use trained XGBoost models to predict values for four water systems (Mountain Dell, Little Dell, GW, DC) by iteratively feeding predicted values back into input features. It applies physical constraints (e.g., non-negative values, maximum limits), computes 5-day rolling averages, and pre...
def WSM_Predict(self): #Set up the target labels #Mountain Dell self.MDell = 'Mtn_Dell_Percent_Full' self.MDell_Pred = self.MDell+'_Pred' self.MDell_Pred_Rol = self.MDell_Pred+'_Rolling' self.MDell_Initial = self.MDell+'_Initial' #Little Dell self.LDel...
def ride_receive_wait(self): while True: if self.ride_receive(): break def debug(s): if DYALOGJUPYTERKERNELDEBUG: writeln(s) def ride_receive(self): data = b'' rcv = False while True: try: head = self.recv_all(8) ...
This function establishes a TCP connection to a Dyalog server with timeout handling, performs handshake authentication, and sends initialization commands (Identify, Connect, etc.) to configure the session. It manages socket retries, handles data queues, and sets connection status upon successful handshake completion.
def dyalog_ride_connect(self): timeout = time.time() + RIDE_INIT_CONNECT_TIME_OUT while True: self.dyalogTCP = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.dyalogTCP.settimeout(TCP_TIMEOUT) time.sleep(0.5) # solves an issue with connecting to 17.0 on Linu...
def execute_line(self, line): self.ride_send(["Execute", {"trace": 0, "text": line}]) def ride_receive_wait(self): while True: if self.ride_receive(): break def out_error(self, s): _content = { 'output_type': 'stream', 'name': 'stderr', # stdi...
This code defines an APL function or namespace by processing input lines, handling syntax errors, and returning error messages. It constructs a function string, executes it in an APL environment, checks for errors using signal codes, and outputs error details if present.
def define_function(self, lines): self.execute_line("⎕SE.Dyalog.ipyFn←''\n") for line in lines: quoted = "'" + line.replace("'", "''") + "'" self.execute_line("⎕SE.Dyalog.ipyFn,←⊂," + quoted + "\n") self.ride_receive_wait() dq.clear() if re.match('^\\s...
def ride_send(self, d): json_str = 'XXXXRIDE' + json.dumps(d, separators=(',', ':')) # json, fix all \r and \n. They should be escaped appropriately for JSON json_str = json_str.replace('\n', '\\n') json_str = json_str.replace('\r', '\\r') _data = bytearray(str.encode(json_str)...
The code executes APL code in a Jupyter notebook environment, handling commands like `%suspend`, defining functions with `∇`/`:namespace`, and interacting with a Dyalog APL interpreter (RIDE). It processes input line-by-line, manages execution states, handles errors, and outputs results or HTML. The function also suppo...
def do_execute(self, code, silent, store_history=True, user_expressions=None, allow_stdin=True): global SUSPEND code = code.strip() if not silent: if self.connected: lines = code.split('\n') match = re.search('^%suspend\s+(\w+)$',li...
def extract_json(self, file): """ returns the keys and values in a json file Parameters ---------- json_file: str Path to the json_file """ data, columns = self._default_path_is_set(file, "_load_json") return da...
The main task of the code is to match and combine related records from JSON, XML, and CSV data sources by comparing common attributes like first name, last name, sex, and age, then returning a 2D list of matched record triplets.
def map_records_dep(self) -> list: ''' map_records iterates through multiple data sources and attempts to match related records using columns that hold values common to all sources like firstname, sex and age; it then returns a 2-dimensional list containing objec...
def phyobj(self, xk, a, pk): return self.fobj(xk + np.multiply(a, pk)) def dphyobj(self, xk, a, pk): h = 10 ** (-16) return (self.phyobj(xk, a + h, pk) - self.phyobj(xk, a, pk)) / h def zoom(self, a_low, a_high, xk, pk): phy_0 = self.phyobj(xk, 0, pk) dphy_0 = self.dphyobj(xk, 0,...
This code performs a line search to find an optimal step size $ a_1 $ satisfying sufficient decrease and curvature conditions. It iteratively checks if the function value at $ a_1 $ meets the criteria using $ \text{phyobj} $ and $ \text{dphyobj} $. If not, it adjusts $ a_1 $ and uses the zoom function for bracketing. T...
def line_search(self, xk, a1, pk, a_max): a0 = 0 i = 1 while True: phy_a1 = self.phyobj(xk, a1, pk) phy_0 = self.phyobj(xk, 0, pk) dphy_0 = self.dphyobj(xk, 0, pk) if phy_a1 > phy_0 + self.c1 * a1 * dphy_0 or (phy_a1 >= self.phyobj(xk, a0, pk) and...
def _get_raw_and_expected_mag_data(self, grav, mag): # pylint: disable=invalid-name,too-many-locals """ Rotate a set of mag readings so that the effects of roll has been removed and calculate the average mag vector, then rotate this vector back to where it should be... :param gra...
This function performs a quick non-linear calibration for magnetometers using a least squares method, adjusting parameters for Y-axis rotations to compensate for non-linear device responses. It requires pre-run ellipsoid and axis calibration, returns calibration accuracy in degrees, and uses 1, 3, or 5 parameters per a...
def fit_non_linear_quick(self, data, param_count: int = 3): # pylint: disable=invalid-name,too-many-locals """ Compensate for devices which do not have a linear response between the magnetic or gravity field and their output. It is recommended to use a ``param_count`` of either 1...
def get_meetings_list(): meeting_list = [] # 0.1.2 # meeting_list_temp = wait_for_element(driver, # "div[class*='calendar-multi-day-renderer__cardHolder']", 30, 'css') meeting_list_temp = wait_for_element(driver, '//*[@id=...
(The function continuously monitors a list of meetings, checking if they should be joined based on status. It repeatedly searches for unprocessed meetings, evaluates join eligibility, and initiates joining if required, with 30-second intervals between checks. Errors are logged, and the process persists indefinitely unt...
def wait_for_meeting(_driver): get_meetings_list() format_meeting_details() meeting_list = get_list_from_json() while True: try: # print('Meeting list: found') # print('Meeting list: formatted') # print('Meeting list: retrieved') if meeting_list: ...
def Conv2dLearnableParameters(layer_tuple): """ Parameters ---------- layer_tuple : (layer object, input_shape, output_shape) with - input_shape = (batch_size,C_in,x_in,y_in) - output_shape = (batch_size,C_out,x_out,y_out) Returns: the number of learnable parameters: #weight + ...
The function `AnalyzeConv2d` analyzes a PyTorch `Conv2d` layer by extracting and compiling multiple metrics into a list. It verifies the layer type, collects structural details (in/out channels, kernel sizes), learnable parameters, weight/bias vanishing coefficients, entropy, MACC (multiply-accumulate operations), and ...
def AnalyzeConv2d(layer_tuple): """ Parameters ---------- layer : torch.nn.modules.conv.Conv2d """ assert ( layer_tuple[0]._get_name() == "Conv2d" ), f"Layer must be a Conv2d but received {layer_tuple[0]}" indicators = [layer_tuple[0]._get_name()] indicators.append(layer_tu...
def ConvTranspose2dLearnableParameters(layer): """ Parameters ---------- layer_tuple : (layer object, input_shape, output_shape) with - input_shape = (batch_size,C_in,x_in,y_in) - output_shape = (batch_size,C_out,x_out,y_out) Returns: the number of learnable parameters: #weight...
The main task of the code is to extract and return a list of analytical indicators for a `ConvTranspose2d` layer. These include layer type, input/output dimensions, parameters, vanishing coefficients, entropy values, and computational metrics like MACC and KB32, providing a comprehensive characterization of the layer's...
def AnalyzeConvTranspose2d(layer_tuple): assert ( layer_tuple[0]._get_name() == "ConvTranspose2d" ), f"Layer must be a ConvTranspose2d by received {layer_tuple[0]}" indicators = [layer_tuple[0]._get_name()] # number of input channels indicators.append(layer_tuple[1][0]) # input shape ...
def initialize_weights(layers, units_per_layer, inputs, ouput): network = [] layer = [] network.append([]) if layers == 2: for i in range(len(ouput)): temp = [] for j in range(len(inputs)): temp.append(np.random.uniform(-0.5, 0.5)) layer.appe...
This code trains a multi-layer neural network using backpropagation on provided training and testing datasets. It normalizes input data, initializes weights/biases, performs forward and backward propagation with sigmoid activation, updates parameters iteratively, and evaluates the model on test data using one-hot encod...
def neural_network(): training_path = sys.argv[1] testing_path = sys.argv[2] layers = int(sys.argv[3]) units_per_layer = int(sys.argv[4]) rounds = int(sys.argv[5]) learning_rate = 1 if not os.path.exists(training_path): print('Invalid File Training File Path') exit() tr...
def costumes_available(costumedata): print("----------------------------------------------------------------------------------------------") print() print("S.No", "\t", "Costume Name", "\t", "Brand", "\t\t", "Price", "Quantity") print() print("-------------------------------------------------...
The function `costume_returned()` manages returning costumes by validating serial numbers, checking quantities, updating inventory, and generating return invoices. It loops to allow multiple returns, collects user input, and processes each return with file updates and bill generation. The process continues until the us...
def costume_returned(): cart = [ ] continueLoop = True while continueLoop == True: costumes_available(costumedata) Sign = sno_valid_return(costumedata) Total_Quant = quantity_valid_return(costumedata, Sign) fileUpdate(costumedata) double...
def zero_quantity(costumedata): Total_Quant = 0 # initially quantity is zero for Sign in range(len(costumedata)): Sign = Sign + 1 Total_Quant += int(costumedata[Sign] [3]) return Total_Quant def bill_generate(cart, costumedata, rentdays, INVOICE): print() Date = Rent_Dat...
The main task of the code is to manage costume rental operations by allowing users to select items, check stock availability, update inventory, and generate rental bills. It includes handling out-of-stock scenarios, validating user inputs, maintaining a shopping cart, and providing options to continue renting or finali...
def costumerent(): #costume rent garna ko lagi banako function continueloop = True cart = [ ] while continueloop == True: Quantity = zero_quantity(costumedata) INVOICE = "RENT" if Quantity == 0: if len(cart) == 0: print("we are out of stock") ...
def get_latest_transcript(): import os, glob path = "src/python_back/transcripts/*" list_of_files = list_of_files = glob.glob(path) latest_file = max(list_of_files, key=os.path.getctime) return latest_file def get_latest_summary(): import os, glob path = "src/python_back/summaries/*" li...
The main task of the code is to process a transcript and summary text by extracting content, performing NLP analysis, and storing structured data using the `populate` function. It reads files, cleans text, generates NLP results, and saves resources in a database, with optional customization via parameters.
def main(name=None, dataBase=None): path = get_latest_transcript() s_path = get_latest_summary() txt = '' with open(path, "r") as f: lines = f.readlines() for line in lines: line = line.strip() if len(line[34:]) != 0: txt += line[34:] + '. ' ...
def search(self, label: int) -> Node: """ Searches a node in the tree >>> t = BinarySearchTree() >>> t.put(8) >>> t.put(10) >>> node = t.search(8) >>> assert node.label == 8 >>> node = t.search(3) Traceback (most recent call last): .....
This method removes a node with the specified label from a binary search tree. It handles three cases: nodes with two children (replaced by the in-order successor), nodes with one child (replaced by that child), and leaf nodes (removed). Parent pointers are updated, and an exception is raised if the node doesn't exist.
def remove(self, label: int) -> None: """ Removes a node in the tree >>> t = BinarySearchTree() >>> t.put(8) >>> t.put(10) >>> t.remove(8) >>> assert t.root.label == 10 >>> t.remove(3) Traceback (most recent call last): ... Ex...
def xy_to_idx(x_coord, y_coord, xds, outproj="EPSG:4326", inproj="EPSG:4326"): """ Given a x coord and y coord value will find the in index of the xds which that xy coord pix is in. Defaults to longitude lattitude values """ from pyproj import Proj, transform import numpy as np inproj = Proj(inproj) ...
The function processes a cluster of anomalies by creating a FireModel instance in a Django database. It extracts key data from a dataset, including location, timestamps, and radiance values, converts anomalies into binary formats, generates an image snapshot, retrieves graph data, and initializes a fire model with thes...
def cluster_to_FireModel(cluster, diff_xds_path, area): """ Parameters ---------- cluster : np.array numpy array containing a list of anomalies of form (lon, lat, timestamp) will add the anomalies to a newly created FireModel diff_xds_path : str Path to diff_xds that we just...
def clearOutput(): outputFil = open("output.txt", 'w') outputFil.write("") outputFil.close() def checkInputFileExists(): try: inputFil = open('input.txt', 'r') inputFil.close() except IOError: generateInputFil() print("input.txt file missing. New file generated.") ...
The main task of the code is to process student programming assignments by running predefined test cases on each Python file in the "assignments/" directory. It renames files, validates inputs, executes tests for each input set, compiles results with student names, and writes the aggregated output to a file, excluding ...
def main(): util.renameAssignmentFiles() clearOutput() checkInputFileExists() inputList = processInput() output = getOutputHeader() assignmentNames = os.listdir("assignments/") assignmentNames.sort() for fil in assignmentNames: if fil.endswith(".py") and not fil == INIT_FILE_N...
def check_sites(sites, max_sites): """Validate the specified site ids. We require that sites are: 1) Within the boundaries of available sites in the tree sequence 2) Sorted 3) Non-repeating Raises an exception if any error is found. :param sites: 1d array of sites to validate. :param...
The function `two_locus_count_stat` computes a two-locus statistic (e.g., linkage disequilibrium) for specified sites and sample sets in a tree sequence. It validates inputs, prepares site indices, and applies summary and normalization functions to calculate the statistic. The result is a 3D NumPy array of LD values ac...
def two_locus_count_stat( ts, summary_func, norm_func, polarised, sites=None, sample_sets=None, ): """Outer wrapper for two site general stat functionality. Perform some input validation, get the site index and allele state, then compute the LD matrix. TODO: implement mode switching...
def get_corpus(name="brown"): return nltk.corpus.__getattr__(name) def build_vocab(questions, V=10000): #token_feed = (canonicalize_word(w) for w in sentence.split() for sentence in questions) #token_feed = (canonicalize_word(w) for sentence in questions for w in sentence.split()) #print (token_feed) ...
The code loads a specified corpus, splits it into training and test sets, builds a vocabulary of up to V words, converts sentences to numerical IDs using the vocabulary, and returns the vocabulary along with the processed training and test data for machine learning tasks like language modeling or NLP experiments.
def load_corpus(name, split=0.8, V=10000, shuffle=0): """Load a named corpus and split train/test along sentences.""" corpus = get_corpus(name) vocab = build_vocab(corpus, V) train_sentences, test_sentences = get_train_test_sents(corpus, split, shuffle) train_ids = preprocess_sentences(train_sentenc...
def extract_unicode_blocks(text): blocks = set() for line in text.splitlines(): line = line.strip() for chunk in re.split("|".join(map(re.escape, fs)), line): norm = unicodedata.normalize('NFKC', chunk.strip()) chunk = re.sub(r"(^[^\w]+)|([^\w]+$)", "", chunk) ...
The code translates text blocks in a file using a specified translator, caching previously translated chunks to avoid redundant work. It processes batches of untranslated blocks, replaces them with translated content, and writes the updated text back to the file, optimizing for efficiency and handling edge cases like p...
def translate_file(path, translator, translated_chunks): try: d = from_path(path) file_contents = str(d.best()) blocks_in_file = extract_unicode_blocks(file_contents) blocks_to_translate = [b for b in blocks_in_file if b not in translated_chunks] if len(blocks_in_file) - len(...
def encoder(inputs): output = encoder_block(inputs, num_filters=64) output = encoder_block(output, num_filters=128) output = encoder_block(output, num_filters=256) output = encoder_block(output, num_filters=512) return output def feature_concatenation_model(low_light, reference): global_average_...
The code defines a neural network model for image enhancement. It takes a low-light image and a reference image as inputs, encodes both to extract features, concatenates these features, and decodes them to generate an enhanced output image. The model leverages the reference image to guide the enhancement of the low-lig...
def model(): low_light_image = Input(shape=(128, 128, 3)) reference_image = Input(shape=(128, 128, 3)) feature_map_low_light_image = encoder(low_light_image) feature_map_reference_image = encoder(reference_image) reconstructed_image = feature_concatenation_model(feature_map_low_light_image, featur...
def equation2(self, user_id) -> dict[int, float]: # ok rt = self.equation1(user_id) user_ratings = self.ratings.get_ratings(user_id) user_ratings_ratings = [rating.rating for rating in user_ratings] r_mu = sum(user_ratings_ratings)/len(user_ratings_ratings) wt ...
The function computes a normalized value using the absolute value from equation2, the variance of a rating vector, and a rated indicator. It returns the minimum of 2 and the ratio of the absolute value to the variance divided by the square root of the rated count, ensuring a bounded output.
def equation6(self, user_id, tag_id) -> float: wt_abs = abs(self.equation2(user_id).get(tag_id, 0)) Rt = self.rt_vec(user_id).get(tag_id, []) sigma_t = self.variance(Rt) it = self.it_rated( user_id, tag_id) if sigma_t == 0 or it ==0: return 0 ...
def equation5(self, user_ids: np.array, tag_ids: np.array) -> np.array: # OK i = self.i_rated(user_ids) it = self.it_rated( user_ids, tag_ids) return min([ it/i , (i-it)/ i ]) def equation6(self, user_id, tag_id) -> float: wt_abs = abs(self.equation2(user_...
This function calculates a combined value 'U' by multiplying three components: covariance (cov) from equation5, significance (sig) from equation6, and the absolute value of weights (wt_abs) derived from equation2. It returns the product of these three factors as a NumPy array, representing the importance of tags for gi...
def equation4(self, user_ids: np.array, tag_ids: np.array) -> np.array: # U = cov * sig * |wt| # importance of the tags # OK # time_eq4_1= time.time() cov = self.equation5(user_ids, tag_ids) sig = self.equation6(user_ids, tag_ids) wt_abs = abs(self.equation2(use...
def encode_src(self, text: str, append_eos=True): tensor = self.model.src_dict.encode_line( ' '.join(self.src_spm.encode(self.src_pipeline.encode(text), out_type=str)), add_if_not_exist=False, append_eos=append_eos ).long() return tensor def surprisal(self, ...
This function performs beam search decoding on input text, generating multiple translations (beam_size) per input. It returns structured outputs including translations, surprisal (negative log probabilities), lengths, and conditional entropy (if requested). The implementation uses a pre-trained model, processes each be...
def beam_search(self, src, beam_size=1, compute_entropies=False): """ :param text: a sentence (str) or a list of sentences (each a string) :param beam_size: :param compute_entropies: this will compute the entropy of each conditional due to limitations of hub_utils, this does...
def encode_src(self, text: str, append_eos=True): tensor = self.model.src_dict.encode_line( ' '.join(self.src_spm.encode(self.src_pipeline.encode(text), out_type=str)), add_if_not_exist=False, append_eos=append_eos ).long() return tensor def surprisal(self, ...
The function performs ancestral sampling to generate multiple translations (num_samples) from a source text (src) using a pre-trained model. It returns a dictionary (or list of dicts) containing generated outputs, surprisal values (-log probabilities), token lengths, and conditional entropies (if requested). Entropy co...
def ancestral_sampling(self, src: str, num_samples=1, compute_entropies=False): """ :param text: a sentence (str) or a list of sentences (each a string) :param num_samples: :param compute_entropies: this will compute the entropy of each conditional due to limitations of hub_...
def _check_model(self, best=True): model_fn = self.mdl_fn_best if best else self.mdl_fn_final return os.path.exists(model_fn) def _load_model(self, best=True): model_fn = self.mdl_fn_best if best else self.mdl_fn_final self.mdl.load_state_dict(tc.load(model_fn)) return model_fn d...
The code trains a model using provided data loaders. It loads an existing model if specified, otherwise initiates training across multiple epochs. Each epoch includes training, validation, and optional test evaluations. The process manages model checkpoints, early stopping, and final evaluation, ensuring iterative opti...
def train(self, ld_tr, ld_val, ld_test=None): ## load a model if not self.params.rerun and self._check_model(best=False): if self.params.load_final: self._load_model(best=False) else: self._load_model(best=True) return ...
def _compute_error_permissive_VC(self, eps, delta, n): g = geb_VC(delta, n) error_per = eps - g return round(error_per*n) if error_per >= 0.0 else None def _compute_error_permissive_direct(self, eps, delta, n): k_min = 0 k_max = n bnd_min = half_line_bound_upto_k(n, k...
The main task of the code is to construct a prediction set by computing a permissive error bound based on specified parameters (n, ε, δ) and bound type (VC, direct, or iw_finite). It loads a pre-trained model, calculates the optimal threshold $ T_{\text{opt}} $ to ensure coverage guarantees, updates the model with this...
def train(self, ld): n, eps, delta = self.mdl.n.item(), self.mdl.eps.item(), self.mdl.delta.item() print(f"## construct a prediction set: n = {n}, eps = {eps:.2e}, delta = {delta:.2e}") ## load a model if not self.params.rerun and self._check_model(best=False): if self.param...
def is_numeric_feature(self): feature_type = self.data[self.x].dtype if feature_type in ['int64', 'int32', 'float64', 'float32']: return True else: return False def categorical_binning(self): tmp_df = pd.DataFrame(self.data[self.x].value_counts()) tmp...
This function bins a feature by first checking if it's numeric. If not, it applies categorical binning. For numeric features, it creates a summary, generates initial bins, combines them using p-values, and finally produces a Weight of Evidence (WOE) table from the bins.
def bin_feature(self): self.is_numeric_feature() if not self.is_numeric_feature(): bins = self.categorical_binning() else: summary_df = self.create_summary() initial_bins = self.create_initial_bins(summary_df) bins = self.combine_bins_based_on_pva...
def efficient_is_under_check(self): #c will the color marker for the piece. This variable will be used in Python f strings below #obtain row and column of the king if self.white_to_move == True: c = "w" king_row = self.position_of_white_king[0] king_column = s...
This function generates valid castling moves for a king at (row, column) if the king is not currently in check. It checks for both kingside (ks) and queenside (qs) castling possibilities based on the current player's turn and available castling rights, then calls corresponding helper methods to populate the possible_mo...
def obtainCastleMoves(self, row, column, possible_moves, piece_color): #first we have to check if the king in (row, column) is currently under check. If the king is under check, then we cannot do anything if self.efficient_is_under_check(): return #now to check whet...
def obtain_all_possible_moves(self): possible_moves = [] for row in range(len(self.board)): for column in range(len(self.board[row])): piece = self.board[row][column] color_of_piece = piece[0] type_of_piece = piece[1] if (color...
The function generates valid chess moves by simulating each possible move, checking if it leaves the king in check, and removing invalid moves. It handles castling, en passant, and determines checkmate/stalemate by analyzing the resulting positions after each move simulation. Temporary variables preserve game state dur...
def obtain_valid_moves(self): print("Printing current_castling_possibility:") print(f"wks:{self.current_castling_possibility.wks} bks:{self.current_castling_possibility.bks} wqs:{self.current_castling_possibility.wqs} bqs{self.current_castling_possibility.bqs}") print("Printing the castling Log...
def train_step(model, device, criterion, optimizer, train_loader): model.train() train_loss = [] for j, (xb, yb, lb, *args) in (pbar := tqdm.tqdm(enumerate(train_loader), leave=False, total=len(train_loader), dynamic_ncols=True)): xb = xb.to(device).float() yb = yb.to(device).float() ...
This function trains a machine learning model over multiple epochs using specified loss functions and optimizers, with early stopping based on validation loss and optional model saving. It tracks training and validation losses, evaluates the model periodically, and terminates training if early stopping conditions are m...
def train_model(model, device, criterion, optimizer, n_epochs, train_loader, dev_loader, evaluate_cycle=5, early_stop=True, save_current=True, evaluate_fun=vrf_evaluate_model_singlehead, evaluate_fun_params={}, early_stop_params={}, save_current_params={}): train_losses, dev_losses =...
def word_count(nltk_text): """ Count frequency of word by type """ text_collocations_list = text_collocations(nltk_text) tagged = nltk.pos_tag(nltk_text) tag_fd = nltk.FreqDist(word for (word, tag) in tagged if tag in ('JJ', 'JJR', 'JJS')) common_word = tag_fd.most_common() return com...
The code processes a CSV file containing mental health-related questions and responses by converting text to lowercase, combining question literals with responses, tokenizing words, and analyzing common words, bigrams, and trigrams. It generates word counts, collocation tables, and word clouds, saving results in specif...
def main(): input_file = '../github/colectica_api/RCNIC_covid_lable.csv' df_input = pd.read_csv(input_file, sep='\t') # lower case df_input = df_input.astype(str).apply(lambda x: x.str.lower()) # combine question literal with response df_input['words'] = df_input['QuestionLiteral'] + df_input['...
def brick_fall(self): for brick in self.state[-2]: if brick.strength: return True print() # for brick in self.state[-1]: # if brick.strength: # self.player.lives = 0 # return True new_state = [] ...
This code updates the game state by moving bricks, checking collisions, updating UFO elements, handling power-ups, and redrawing game objects. It manages brick falling intervals, game over conditions, rainbow brick colors, ball movement, paddle lasers, and player visuals. The method returns False if bricks fall or the ...
def update(self): # Moving the bricks down before the update if time.time() - self.last_tick >= BRICK_FALL_TIME: if self.brick_fall(): return False if self.game_over(): return False # Change the rainbow brick colors self.rainbow_u...
def movement(self): sin_a = math.sin(self.angle) cos_a = math.cos(self.angle) dx, dy = 0, 0 self.player_speed = PLAYER_SPEED * self.game.delta_time speed_sin = self.player_speed * sin_a speed_cos = self.player_speed * cos_a keys = pygame.key.get_pressed() ...
The main task of the code is to update the game state by handling movement, mouse control, hand correction, and win condition checks.
def update(self): #self.draw() self.movement() self.mouse_control() self.quick_fix_the_hand() self.win()
def parse_args(): parser = argparse.ArgumentParser() parser.add_argument("feed") return parser.parse_args() def fetch_feed(url): return requests.get(url).content.decode("utf-8") def convert_feed(original): feed_attrs = dict( title="FEMA Daily Operations Briefings", id=BASE_ID, ...
The code fetches an RSS feed, parses it using feedparser, converts the parsed data, and outputs the converted RSS feed in a pretty-printed format to standard output.
def main(): args = parse_args() feed_content = fetch_feed(args.feed) original = feedparser.parse(feed_content) converted = convert_feed(original) converted.rss_file(sys.stdout.buffer, pretty=True)
def conv2d(input_tensor, filters, kernel_size, strides, act=None, padding='SAME', w_init=None, b_init=None, name=None): return tl.layers.Conv2d(input_tensor, n_filter=filters, filter_size=kernel_size, strides=strides, act=act, padding=padding, W_init=w_init, b_init=b_init, name=name) def bn(input_tensor, is_train, ...
This function constructs a ResNet variant with customizable depth and cardinality for image classification. It processes input tensors through stacked convolutional blocks (with identity shortcuts) and global average pooling, outputting a 100-class classification layer. The architecture follows standard ResNet patterns...
def get_resnet(input_tensor, block, is_training, reuse, cardinality, kernel_initializer=None): # 3, 4, 16, 3 with tf.variable_scope('scope', reuse=reuse): x = tl.layers.InputLayer(input_tensor, name='inputs') x = conv2d(x, 64, (3,3), strides=(1,1), padding='SAME', w_init=kernel_initializer, name='face_conv1_1/3x3...
def _check_duration(self, config:dict, activity:Activity, record:Record) -> bool: duration = record.stop - activity.first_record.start too_short, too_long = _in_duration_window(duration, config) if too_long: self.stop_search = True if too_short or too_long: return...
This function checks if a record matches the last rule in a step by verifying date alignment, duration constraints, continuity requirements, and intermittent conditions. It returns False and stops the search if conditions fail, otherwise returns True after all checks.
def _match_last_rule(self, record:Record, activity:Activity) -> bool: last_rule = self.step['last'] # Check conditions that will stop the search if they are not satisfied matched = record.date == activity.date if matched and (duration := last_rule.get('duration', {})): matc...
def transactionCheck(self): """ Check if the program can procede with the transacton Check if we have an access code Check if the default account is set """ self.is_authorized() self.is_account_set() def refresh_token(self, **kwargs): """ ...
The main task of the code is to refresh the account status by validating the account, renewing the token, fetching updated account data from the server using specified fields, and updating the local account object with the retrieved information. It returns 1 on success or 0 on failure.
def refresh_account( self, options=['positions'], params={} ): """ Refresh the account status """ self.transactionCheck() self.refresh_token() if not self.account.account_id: raise ValueError("account_id not defined") pa...
def transactionCheck(self): """ Check if the program can procede with the transacton Check if we have an access code Check if the default account is set """ self.is_authorized() self.is_account_set() def refresh_token(self, **kwargs): """ ...
The main task of the code is to refresh order statuses by performing a transaction check, refreshing the authentication token, retrieving all orders via the all_orders() method, and updating the self.orders attribute with the fetched data if successful. The function returns 1 for success or 0 for failure, based on the ...
def refresh_orders(self): """ Refreshes status of the orders and stores results in the self.orders class """ self.transactionCheck() self.refresh_token() status, r = self.all_orders() if status: self.orders.update(r.json()) return...
def create_connection(db_file): conn = None try: conn = sql.connect(db_file) return conn except Exception as e: print(e) return conn def tableExists(cs, tableCreation): cs.execute("CREATE TABLE IF NOT EXISTS " +tableCreation+";") def getBookingsByDoctors(database, doctorID): ...
The main task of the code is to check if a booking with the same date and doctorID already exists in the database. If not, it inserts a new booking record with provided details (doctorID, userID, serviceID, date) into the 'bookings' table and returns a JSON response indicating success or failure.
def postBooking(database,bookingInfo): db = create_connection(database) if db is not None: cs = db.cursor() tableExists(cs, "bookings(date TEXT, doctorID INTEGER, userID INTEGER, serviceID INTEGER, bookingID INTEGER PRIMARY KEY)" ) bookings = json.loads(getBookingsByDoctors(database,book...
def compute_bidder_shading(knots_bidder, coeffs_bidder_shading): def this_function(x): return np.dot(coeffs_bidder_shading, np.append([1.0, x], [max(0.0, x - knot) for knot in knots_bidder])) return this_function def compute_v_value_after_shading(knots_bidder, coeffs_bid...
This function computes the gradient of a bidder's payoff with respect to coefficients in a piecewise linear spline shading function, using first-order basis functions. It evaluates contributions from opponent density/CDF, bidder's virtual value, and basis function derivatives, returning a vector of gradient values for ...
def compute_objective_vector_first_order_splines(density_opponents, cdf_opponents, knots_bidder, coeffs_bidder_shading, density_bidder, cdf_bidder, ...
def compute_v_value_after_shading(knots_bidder, coeffs_bidder_shading, bidder_pdf, bidder_cdf): """ implements the differential equation results we had a long time ago... note that we replace the subderivative at the knots by a value of the subderivative... :param knots_bidder: :param coeffs_bidder_...
The code performs multiple gradient ascent steps to optimize a bidder's shading function coefficients, aiming to maximize revenue. It iteratively updates the coefficients using gradient steps, recalculates reserve prices and virtual values, and tracks revenue and constraints. The process continues for a specified numbe...
def perform_multiple_gradient_ascent_steps(density_opponents, cdf_opponents, knots_bidder, coeffs_bidder_shading, density_bidder, cdf_bidder, ...
def tcp_read(self, sock): lengthbuf = self._recvall(sock, 4) length, = struct.unpack('!I', lengthbuf) data = self._recvall(sock, length) message = pickle.loads(data) self.outputs.append(sock) return message def para_list_handler(self,socket,data): # decode data ...
This code uses I/O multiplexing with `select.select` to monitor multiple sockets, handling incoming data based on message flags (INIT, PARA, FINAL) by triggering specific handlers, managing connections, and sending responses. It processes readable sockets for data reception, determines actions via flags, and handles wr...
def run(self, timeout=30): while self.inputs: #print("Waiting events!") readable, writable, exceptional = select.select(self.inputs, self.outputs, self.inputs, timeout) if not (readable or writable or exceptional): print("Time out ! ") break ...
def succesors(state,moves): return [move(state,m) for m in moves] def seen(state,openN,closeN): allN = openN+closeN for s in allN: if compareStates(state,s): return True return False def isfial(state): return compareStates(state,final_state)
This code implements a search algorithm by expanding the current node (first), checking if it's the goal, and adding unvisited successors to the exploration list. It removes the current node from freeNodes, marks it as closed, generates new states, filters out already seen nodes, and updates exploration count. If the g...
def inc(self): first = self.freeNodes.pop(0) self.show = first self.closedNondes.append(first) generated = succesors(first,moves) generated = [i for i in generated if not seen(i,self.freeNodes, self.closedNondes)] if isfial(first): self.sucess = True ...
def get_existing_teams(): vars = _get_env_vars() org = vars.get("org") all_teams = [] teams = _gh_api_call('get', f"/orgs/{org}/teams", params={'per_page': 100}) all_teams.extend(teams) return all_teams def get_members_of_team(slug): vars = _get_env_vars() org = vars.get("org...
The code gathers team information (name, description, members, repositories, slug, privacy) into a structured dictionary, using team slugs as keys. If no team names are provided, it fetches existing teams. It processes each team's data, combining details from multiple functions into a unified format for output.
def get_teams_data(team_names): if None == team_names: team_names = get_existing_teams() teams_data = {} for team in team_names: t = {} t['0_name'] = team.get('name') t['1_description'] = team.get('description') t.update(get_members_of_team(team.get('slug'))) ...
def prepare_test_plan(workspace, testplan_dest, result_dest): new_testplan = '' with open(testplan_dest, 'r') as src_jmx: source_lines = src_jmx.readlines() closing = source_lines.pop(-1) closing = source_lines.pop(-1) + closing if "<hashTree/>" in source_lines[-1]: s...
The main task of the code is to initiate a JMeter test execution by setting up directories, configuring remote JMeter instances via SSH, applying project-specific parameters, running the test plan, capturing logs/results, and storing test metadata in the database. It handles both local and remote execution, manages pro...
def start_test(request, project_id): response = [] project = Project.objects.get(id=project_id) pid = 0 start_time = 0 display_name = "" test_id = 0 if request.method == 'POST': # Create dir for new test: last_test_id = 0 if Test.objects.filter(project_id=project_id)....
def spellCheck(self, sentence): """ This method takes a sentence and corrects any spelling mistakes based on closest known word Parameters: sentence (str): a sentence of user input Returns: corrected (str): a spell corrected sentence """ corrected ...
The code's main task is to handle user interaction by continuously receiving input, correcting spelling, predicting user intent, generating appropriate responses, and invoking a shop-finding function. It operates in a loop, processing each input to determine intent via `predictResponse`, formulating a reply with `getRe...
def run(self): """ This methods receives user input, and uses the predictResponse methods to determine what the user's intention is, then uses the getResponse methods to determine an ideal response to return. """ print("Welcome, we are here to help you with your computer issues....
def initialize(self, windowSize, sampleRate): self.windowSize = windowSize self.sampleRate = sampleRate for _ in range(0, self.windowSize): self.weights.append(0.0) self.window.append(0.0) print(f"LMS with DeviceId: {self.deviceId} initialized!") def process_v...
The code processes incoming device data by validating the device ID and handling message types ("INIT", "DATA", "STOP"). It initializes parameters, processes sensor values, or stops threads based on the message, ensuring data is correctly routed to appropriate methods for further handling.
def process_data(self,data): id = int(data[0]) if id != self.deviceId: print(f"Device Id mismatch! Expected: {self.deviceId} but received: {id}") # data has following elements: [id,msgId,....] # msgId = "INIT": [id,"INIT",windowSize,sampleRate] # msgId = "DATA": [id,"...
def declarations(astnode, hm=None): if hm is None: hm = {} if isinstance(astnode, ast.Module): for b in astnode.body: declarations(b, hm) elif isinstance(astnode, ast.FunctionDef): #hm[astnode.name + '__return__'] = translate_to_z3_name(astnode.returns.id) for a i...
This code initializes a function analysis tool by parsing arbitrary code to extract variable declarations and function arguments, setting up Z3 solver for constraint solving, and preparing to process control flow paths using provided CFG data. It stores function entry/exit points, initializes solver, and triggers proce...
def __init__(self, arbitary_code, function_names, index, py_cfg, **kwargs): self.fn_name = function_names[index] self.function_names = function_names self.py_cfg = py_cfg self.fnenter, self.fnexit = self.py_cfg.functions[self.fn_name] # a dictionary of used variables; ex. {'a':...
def get_path_to_root(self): path = [] n = self while n: path.append(n) n = n.parent # print(list(reversed(path))) return list(reversed(path)) def to_single_assignment_predicates(path): env = {} new_path = [] completed_path = False for i, no...
The code's main task is to generate a string representation of an object's path to its root, converting the path into single-assignment form (SSA) and joining the resulting predicates with commas. It retrieves the path using `get_path_to_root()`, transforms it via `to_single_assignment_predicates()`, and formats each p...
def __str__(self): path = self.get_path_to_root() ssa_path = to_single_assignment_predicates(path) return ', '.join([to_src(p) for p in ssa_path])
def extract_constraints(self, path): result = [] generated_path, completed = to_single_assignment_predicates(path) if not completed: return [] for p in generated_path: # if (isinstance(p, ast.AnnAssign) and p.target.id in {'exit', 'return'}): if p: ...
The code solves path constraints using Z3, extracting variables, checking satisfiability, and returning solutions. It defines symbolic variables, enforces constraints, and if satisfied, records variable values. It then adds a negated constraint to exclude the found solution, returning the variable mappings. Your return
def solve_path_constraint(self, path): # re-initializing does not seem problematic. # a = z3.Int('a').get_id() remains the same. constraints = self.extract_constraints(path) identifiers = [c for i in constraints for c in used_identifiers(i)] # <- changes with_types = identifiers...
def extract_constraints(self, path): result = [] generated_path, completed = to_single_assignment_predicates(path) if not completed: return [] for p in generated_path: # if (isinstance(p, ast.AnnAssign) and p.target.id in {'exit', 'return'}): if p: ...
The code checks if a set of constraints extracted from a path can be satisfied using the Z3 SMT solver. It processes constraints from `p.get_path_to_root()`, defines symbolic variables with their types, adds the constraints to the solver, and returns `True` if the solver finds a satisfying assignment (`z3.sat`), otherw...
def can_be_satisfied(self, p): s2 = self.extract_constraints(p.get_path_to_root()) # if any(fn_name in s2 for fn_name in self.function_names): # print("asdasdasdsadas") # print(s2) s = z3.Solver() identifiers = [c for i in s2 for c in used_identifiers(i)] with...
def cluster(self, X, y, iterations=100, batch_size=1024, verbose=False): """Cluster contexts in X for same output event y. Parameters ---------- X : torch.Tensor of shape=(n_samples, seq_length) Input context to cluster. y : torch.Tensor of shape...
The main task of the code is to fit an `Interpreter` by clustering input data (`X`, `y`) and assigning cluster scores based on individual sample scores (`scores`). It clusters data, distributes scores to clusters using a specified strategy (`max`, `min`, or `avg`), and sets the computed scores. The method returns the u...
def fit(self, X, y, scores, iterations = 100, batch_size = 1024, strategy = "max", NO_SCORE = -1, verbose = False, ): """Fit the Interpreter by performing clustering and assigning scores. ...
def get_state(self): #mapping all vehicles into an array state = np.zeros(self.agent.nb_states) #get all vehicles to define current state for veh_id in traci.vehicle.getIDList(): lane_id = traci.vehicle.getLaneID(veh_id) #get distance from traffic light ...
The code simulates a traffic control scenario using SUMO, where an agent selects actions (e.g., traffic light settings) based on the current state and an exploration rate (epsilon). It executes steps, calculates rewards (reduction in waiting time), and stores experiences in memory for training. If in training mode, it ...
def run(self, epsilon): traci.start(self.sumo) total_reward = 0 total_waiting_time = 0 total_waiting_length = 0 step = 0 last_state = self.get_state() last_total_waiting = 0 while step < self.max_steps: action = self.agent.select_action(last_...
def process_instrument_list(config_path = "C:\\Python\\daq\\config\\"): """ Reads in an instrument list from the configuration file directory and creates a dictionary with instrument names as keys and instrument config file paths as values Args: config_path (str): path to configuration file dir...
The main task of the code is to process command-line arguments for an instrument name, load its configuration, redirect output to log files, and initiate logging (stream or standard) based on the instrument's configuration. It checks if the instrument is supported, creates necessary directories, and manages logger stat...
def main(): """ Main function to run program. Takes in command line arguments and calls functions """ import argparse #Parse command line arguments parser = argparse.ArgumentParser(description='Data Writing Settings') parser.add_argument('-I', '--instrument_name', type=str, help='Name ...
def process_instrument_list(config_path = "C:\\Python\\daq\\config\\"): """ Reads in an instrument list from the configuration file directory and creates a dictionary with instrument names as keys and instrument config file paths as values Args: config_path (str): path to configuration file dir...
The main task of the code is to allow users to configure instrument enable/disable states in JAQFactory. It processes instrument configurations, displays current states, accepts user commands to modify instrument status, updates configurations, and displays final enabled states before exiting. The code handles error lo...
def main(): """ Main function to run program. Takes in command line arguments and calls functions """ #Specify an error log file error_log_file = "C:\\Python\\daq\\logs\\_initialize_logger_error.txt" sys.stderr = open(error_log_file, 'w') #Create dictionary with configuration file loca...
def mlp_head(self, feat): rgb_1, rgb_2, frame_1, frame_2, res_1, res_2 = torch.unbind(feat, dim=1) rgb_v1 = self.fv(rgb_1) rgb_v2 = self.fv(rgb_2) frame_v1 = self.fs(frame_1) frame_v2 = self.fs(frame_2) res_v1 = self.fd(res_1) res_v2 = self.fd(res_2) fea...
The code computes a decoupled probability distribution from input features, splits it into static and dynamic components, calculates entropy losses against a queue, and performs self-reconstruction and local matching tasks. It returns the probability, losses, entropies, reconstructions, and local matches for both stati...
def decouple_prob(self, feat, maps, use_queue): ''' feat b x n x 512 maps b x n x 512 x t x h x w prob b x n x 400 attribute b x n x 200 ''' logit = self.mlp_head(feat) logit = F.normalize(logit, dim=-1) # prob = self.prototype(logit) prob ...
def fail(message, code=1): log_error(message) sys.exit(code) def resolve(base_path, spec_path): if spec_path is None: return None if not os.path.isabs(spec_path): spec_path = os.path.join(base_path, spec_path) return spec_path def transcribe_many(path_pairs): pbar = create_progre...
The main task of the code is to transcribe audio files into text logs (.tlog) using the specified source file or catalog. It validates input/output paths, checks for existing files/directories, and handles overwriting via the --force flag. If a catalog (.catalog) is provided, it processes multiple entries, ensuring sou...
def main(_): if not FLAGS.src: fail('You have to specify which file or catalog to transcribe via the --src flag.') src_path = os.path.abspath(FLAGS.src) if not os.path.isfile(src_path): fail('Path in --src not existing') if src_path.endswith('.catalog'): if FLAGS.dst: ...
def kfolds(n, k=3, shuffle=True): ''' Generate indices to fold a training set into k subsets and yield the subsets. :param n: The number of samples in the tensors. :param k: The number of folds to generate. Must be greater than 1. :param shuffle: Whether to shuffle the order of each fold. :yield...
The function performs k-fold cross-validation by splitting the dataset into k folds, training a model on each training subset, evaluating it on the corresponding test subset, and computing the average accuracy and loss across all folds. It uses parameters like the number of folds and shuffling to control the process, r...
def kfolds_train(X, y, params): ''' Perform training with k-folds cross-validation. :param X: The training inputs. :param y: The training targets. :param params: The model parameters for creating a model. :param num_batches: The maximum number of batches or None. :returns: A tuple of the ave...
def _check_veto(db: Session, poll_id: int): """Sets veto on books with 1 or less votes in primary poll.""" objs = ( db.query(Book) .filter(Choice.book_id == Book.id) .filter(Choice.poll_id == poll_id) .filter(Choice.votes <= 1) .all() ) for obj in objs: ob...
The function finalizes a poll by marking it as completed, then creates a secondary poll if it was primary or updates the current book otherwise, handling veto checks and state transitions in a database session.
def complete_poll(db: Session, poll_id: int): """Finalizes the given poll and either creates the secondary poll or updates the current book to be read.""" obj = db.query(Poll).filter(Poll.id == poll_id).first() obj.finished = True db.commit() if obj.primary: _check_veto(db, poll_id) ...
def Upload(fileName, connection): fileSize = connection.recv(CHUNK) fileSize = fileSize.decode(FORMAT) frame = connection.recv(CHUNK) data = b"" bytesReceived = 0 with open(f"./ServerFiles/" + fileName, "wb") as f: while len(frame) == CHUNK: #data += frame f.writ...
This function handles client commands by routing them to appropriate helper functions, managing client connections, and processing file operations (UPLOAD/DOWNLOAD/DIR/DELETE) or specific scenarios (2_1/2_2/2_3). It initializes clients, processes incoming data, and terminates connections on DISCONNECT commands.
def HandleClient(connection, checkConnection): # initalize the client and give the client an ID global numClients, clients, client1, client2 print("Client Connected\n") if numClients == 2: client1 = clients[1] client2 = clients[2] while True: # wait for the client to send a...
def compute_sample_max_distribution(pdf, n_evidence): if n_evidence < 1: raise ValueError('n_evidence must be greater than 0') cdf = np.cumsum(pdf) sample_max_distribution = n_evidence * cdf ** (n_evidence - 1) * pdf return sample_max_distribution / np.sum(sample_max_distribution) def compute_s...
This code generates a prior distribution over a specified domain by combining multiple Beta distributions with Dirichlet weights. It normalizes the combined distribution, then computes lower and upper bounds using filtering and sampling methods. The function returns the normalized prior distribution along with its calc...
def generate_prior(seed, domain, beta_weights=[2,10]): np.random.seed(seed) bin_size = domain[1] - domain[0] # Create prior distribution of parameter value first_prior = beta(np.random.randint(beta_weights[0], beta_weights[1]), np.random.randint(beta_weights[0], beta_weights[1])) second_prior = be...
def simple_query_filter(domain, function, current_value, logistic_k, higher=True, pdf=True): # The filter is a logistic function, centered around current_value with a certain steepness (logistic_k) # and direction (higher). # https://en.wikipedia.org/wiki/Logistic_function dom = np.linspace(0, 1, domai...
The code calculates the expected reduction in entropy after a query by computing weighted average entropies of posterior distributions. For 1D/2D functions, it filters posteriors (higher/lower/fine ranges), computes their probabilities via numerical integration, normalizes, validates as a probability distribution, and ...
def compute_expected_reduction_in_entropy(domain, function, query_value): if len(function.shape) == 1: posterior_higher = simple_query_filter(domain, function, query_value, 50.0, True) posterior_lower = simple_query_filter(domain, function, query_value, 50.0, False) probs = np.zeros(2) ...
def simple_query_filter(domain, function, current_value, logistic_k, higher=True, pdf=True): # The filter is a logistic function, centered around current_value with a certain steepness (logistic_k) # and direction (higher). # https://en.wikipedia.org/wiki/Logistic_function dom = np.linspace(0, 1, domai...
The code computes the expected reduction in divergence (using JS or KL) between a posterior distribution and a prior, given a query value. It handles 1D and 2D functions by generating posterior distributions (higher, lower, or fine-grained) via filtering, calculating their probabilities via numerical integration, and w...
def compute_expected_reduction_in_divergence(domain, function, query_value, method='js'): if method == 'js': chosen_method = js_divergence_categorical elif method == 'kl': chosen_method = kl_divergence_categorical else: print('Unknown divergence method. Known methods: Jensen-Shannon ...
def entropy_categorical(categorical_pdf): if len(categorical_pdf.shape) > 1: categorical_pdf = categorical_pdf.flatten() is_true_categorical_pdf(categorical_pdf) entropy = np.sum([-value*np.log2(value) for value in categorical_pdf if not(value < np.finfo(categorical_pdf.dtype)...
The code selects the most informative query from a domain by evaluating expected reduction in entropy (ERE) for both max and min distributions. It calculates ERE for each value, compares entropy differences, and chooses the index with minimal reduction. If safe, it uses a safety-aware selection; otherwise, it picks the...
def choose_query(self): timer = CodeTimer() with timer: n = self.domain.shape[0] ere_max = np.zeros(n) ere_min = np.zeros(n) entropy_max_prior = entropy_categorical(self.max_distribution) entropy_min_prior = entropy_categorical(self.min_distri...
def entropy_categorical(categorical_pdf): if len(categorical_pdf.shape) > 1: categorical_pdf = categorical_pdf.flatten() is_true_categorical_pdf(categorical_pdf) entropy = np.sum([-value*np.log2(value) for value in categorical_pdf if not(value < np.finfo(categorical_pdf.dtype)...
The main task of the code is to select the next query by computing the expected reduction in entropy (ERE) for each domain value, combining results from min/max distributions, and choosing the value with the minimum ERE adjustment. It returns either the selected query or detailed profiling data, including ERE values, e...
def choose_query(self): timer = CodeTimer() with timer: n = self.domain.shape[0] ere_sum = np.zeros(n) entropy_sum_prior = entropy_categorical(self.min_distribution) + entropy_categorical(self.max_distribution) for j, value in enumerate(self.domain): ...
def entropy_categorical(categorical_pdf): if len(categorical_pdf.shape) > 1: categorical_pdf = categorical_pdf.flatten() is_true_categorical_pdf(categorical_pdf) entropy = np.sum([-value*np.log2(value) for value in categorical_pdf if not(value < np.finfo(categorical_pdf.dtype)...
This function selects the next query by computing the expected reduction in entropy (EVE) for each domain value, then choosing the value with the minimum EVE. If 'safe' is enabled, it uses a safety-aware selection; otherwise, it uses standard minimization. It returns the selected query or a profiling dictionary contain...
def choose_query(self): timer = CodeTimer() with timer: n = self.domain.shape[0] ere_values = np.zeros(n) entropy_prior = entropy_categorical(self.range_distribution) for j, value in enumerate(self.domain): ere_values[j] = compute_expected...
def checkidx(self, boards, tkn): if (boards, tkn) in self.movesCache: return self.movesCache[(boards, tkn)] idxs = {} board = [list(boards[i:i + 8]) for i in range(0, 64, 8)] for idx in self.holePos: idxSet = set() if boards[idx] != '.': continue x = i...
The code determines the best move in a board game (likely Othello/Reversi) by prioritizing corner/edge positions, then using alphabeta pruning for deeper analysis. It identifies empty cells, filters valid moves, selects from corners/edges if available, removes corners otherwise, and applies alphabeta with varying depth...
def final_code(self, board, tkn, best_move): bm = 0 for idx, i in enumerate(board): if i == '.': self.holePos.add(idx) moves = self.checkidx(board, tkn) listOfMoves = list(moves.keys()) edges = self.analyze_edges(board, listOfMoves, tkn) ...