dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def checkMissing(param): if param is None: raise ValueError(f"Missing required '{param[0]}' parameter") def checkType(param, check): if not isinstance(check, type): if check[0] is LIST_TYPES: result = isinstance(param[1], LIST_TYPES) if not np.all(result): ...
This function validates and configures parameters for a clustering model, ensuring inputs meet requirements for K (number of clusters), data structure (FDataBasis/dict), absence of NaNs/infs, consistency between 'known' labels and data dimensions, initialization methods (vector/mini-em/kmeans), model selection criteria...
def _T_hddc_control(params): K = ('K',params['K']) checkMissing(K) checkType(K, (INT_TYPES)) checkRange(K, lower=1) data = ('data', params['data']) checkMissing(data) checkType(data, (skfda.FDataBasis, dict)) if isinstance(data[1], skfda.FDataBasis): checkType(('data', data[1]...
def _T_funhddt_init(fdobj, Wlist, K, t, nux, model, threshold, method, noise_ctrl, com_dim, d_max, d_set): #univariate case if(type(fdobj) == skfda.FDataBasis): x = fdobj.coefficients else: #Multivariate if len(fdobj) > 1: x = fdobj[0].coefficients.copy() ...
The code performs clustering/classification on functional data using a HDDC (Hybrid Dynamic Dimensional Clustering) model. It initializes cluster memberships via methods like k-means or random, iteratively optimizes parameters via E-M steps, enforces dimensional constraints, and computes model selection criteria (BIC/I...
def _T_funhddc_main1(fdobj, wlist, K, dfstart, dfupdate, dfconstr, model, itermax, threshold, method, eps, init, init_vector, mini_nb, min_individuals, noise_ctrl, com_dim, kmeans_control, d_max, d_set, known): np.seterr(all='ignore') modelName...
def get_H(n): """Sample H from the Gaussian unitary ensemble, GUE(N). N = 2**n, where n is the number of pairs shared by Alice and Bob (W in equation 4).""" # sampling a GUE (beta=2) matrix of size (2^n)x(2^n) H = GaussianEnsemble(beta=2, n=2**n).matrix #H = H/np.linalg.norm(H) return H def prepare_tfd(n, H...
The code checks the correctness of the TFD (Thermal Field Dynamics) state for beta=0 by comparing the computed TFD state with a theoretically derived reference state. It constructs the reference state using Bell states, tensor products, and transpositions, then verifies agreement via absolute difference sums. Additiona...
def check_tfd_for_beta_0(): """# check tfd for beta = 0""" n = 4 beta = 0 H = get_H(n) tfd = prepare_tfd(n, H, beta) bell = prepare_bell() tfd_correct = bell for i in range(n-1): tfd_correct = np.kron(tfd_correct , bell) tfd_correct = tfd_correct.reshape((2*n)*[2]) if n%...
def apply_unitaries(state, n, H, t): """Apply unitary evolution operators. """ U = sp.linalg.expm(1j*t*H) U_conj = np.conj(U) new_shape = (2*n)*[2] U_conj = U_conj.reshape(*new_shape) transposition = [n-1-i for i in range(n)] + [2*n-1-i for i in range(n)] U_conj = U_conj.transpose(transposition) U_co...
The code calculates the probabilities of successful postselection and entanglement swap in a quantum system. It evolves the initial state `psi_swap` using the Hamiltonian `H` over time `t`, applies a projection to postselect on a desired state, computes the postselection probability as the squared norm of the projected...
def find_probs(n, H, psi_swap, t): """Find probability of successful postselection and entanglement swap, for given Hamiltonian H, the state after the swap, and the evolution time t.""" psi = psi_swap.copy() psi = apply_unitaries(psi, n, H, t) psi = apply_proj(psi, n) prob_postselection = np.linalg.norm(psi...
def get_H(n): """Sample H from the Gaussian unitary ensemble, GUE(N). N = 2**n, where n is the number of pairs shared by Alice and Bob (W in equation 4).""" # sampling a GUE (beta=2) matrix of size (2^n)x(2^n) H = GaussianEnsemble(beta=2, n=2**n).matrix #H = H/np.linalg.norm(H) return H def experiment(n, H,...
The code simulates and visualizes the time evolution of swap probabilities in a TFD state under a given Hamiltonian and inverse temperature beta. It computes probabilities over a time range, plots them, and compares them to a theoretical prediction line, displaying the results for analysis.
def run_experiment(n, beta): """Runs the above -- @param n: The number of pairs in the TFD state. @param beta: 1/T """ print(f'Running experiment with n={n}, beta={beta}') H = get_H(n) tmax = 2 ts = np.linspace(0, tmax, 100) probs_swap = experiment(n, H, beta, ts) pred = find_pre...
def get_H(n): """Sample H from the Gaussian unitary ensemble, GUE(N). N = 2**n, where n is the number of pairs shared by Alice and Bob (W in equation 4).""" # sampling a GUE (beta=2) matrix of size (2^n)x(2^n) H = GaussianEnsemble(beta=2, n=2**n).matrix #H = H/np.linalg.norm(H) return H def experiment(n, H,...
The code runs an experiment simulating probability dynamics over time (ts) for given parameters n and beta (set to 1). It calculates probabilities (probs_swap) using the experiment function, compares them to a prediction (pred) from find_prediction, and visualizes the results with a plot showing time-evolving probabili...
def run_experiment_2(n, beta): print(f'Running experiment_2 with n={n}, beta={beta}') H = get_H(n) beta = 1 tmax = 2*beta ts = np.linspace(0, tmax, 100) probs_swap = experiment(n, H, beta, ts) pred = find_prediction(n, H, beta) plt.plot(ts, np.array(probs_swap)) plt.hlines(pred, 0, t...
def _init_global_step(self): self.global_step = training_util.get_or_create_global_step() self._training_ops.update({ 'increment_global_step': training_util._increment_global_step(1) }) def _init_placeholders(self): """Create input placeholders for the SAC algorithm. ...
The main task of the code is to initialize and configure the model's training components by setting up placeholders, global step, and operations for actor-critic updates, behavior cloning, and Q-target calculations. It organizes training operations into a dictionary for subsequent execution, essential for reinforcement...
def _build(self): self._training_ops = {} self._init_global_step() self._init_placeholders() self._init_actor_update() self._init_critic_update() self._init_bc_update() self._init_Q_target_no_entropy()
def _init_training(self): self._update_target(tau=1.0) def _pretrain_bc(self, batch_size=256, n_epochs=50, max_logging=2000, holdout_ratio=0.1): """ Pretrain the policy using behaviour cloning on the dataset """ progress = Progress(n_epochs) env_samples = self._pool.return_all_s...
The main task of the code is to perform 1R2R offline reinforcement learning (RL) training by iterating through epochs, collecting data via model rollouts, training the policy and critic networks, evaluating performance, and logging diagnostics. It includes behavior cloning pretraining, model updates, and periodic evalu...
def _train(self): """Return a generator that performs 1R2R offline RL training. """ training_environment = self._training_environment evaluation_environment = self._evaluation_environment policy = self._policy pool = self._pool model_metrics = {} if not s...
def SK_thresholds(M, N = 1, d = 1, p = 0.0013499): Nd = N * d #Statistical moments moment_1 = 1 moment_2 = float(( 2*(M**2) * Nd * (1 + Nd) )) / ( (M - 1) * (6 + 5*M*Nd + (M**2)*(Nd**2)) ) moment_3 = float(( 8*(M**3)*Nd * (1 + Nd) * (-2 + Nd * (-5 + M * (4+Nd))) )) / ( ((M-1)**2) * (2+M*Nd) *(3+M*Nd...
The code simulates RF signal detection using modulation schemes (BPSK, ASK, BFSK, QPSK), generating signals, applying filters, and analyzing power spectra. It computes thresholds for detection, applies multiscale analysis, flags RFI, and visualizes results (spectra, dB plots, scatter plots) to assess detection accuracy...
def simulate(encode,Nchan,SK_m,fs,cc_sig,cc_tone,cc_fsk_space,sym_rate,bits_per_sym,num_SK,SKsigma,ms0,ms1,ask_bias,dc,dcper,wincut,newdata,newdc,Iplot,spect_lbl,sdb_lbl,ssplt_lbl,msplt_lbl,num): #do the thing print('hello?') #INPUTS: #Nchan=256 #SK_m=512 global y #global num #PFB taps...
def loadPretrained(filePath): """Opens a `.vec` file and returns word2index and wordVectors (KeyedVectors) holding the word embedding vectors""" wordVectors = KeyedVectors.load_word2vec_format(filePath) vectorSize = wordVectors.vector_size # This assigns [0, 0, ..., 0] to SOS, EOS, and PAD, and ...
The main task of the code is to train and evaluate a Recurrent Neural Network (RNN) model for sequence modeling using pre-trained word2vec embeddings on a product review dataset. It loads data, configures a GPU, initializes an RNN with fixed embeddings, trains it for 40 epochs, and evaluates performance on training and...
def main(): ON_COLAB = False embedfile = "embeddings/all-lower-89k-300d.vec" trainfile = "data/prime-pantry-lower-200k-train.csv" testfile = "data/prime-pantry-lower-40k-test.csv" if ON_COLAB: embedpath = "/content/drive/Shareddrives/DLFinalProject/" + embedfile else: emb...
def generate_visibility_nodes(self, start_x, start_y, goal_x, goal_y, obstacles): # add start and goal as nodes nodes = [DijkstraSearch.Node(start_x, start_y), DijkstraSearch.Node(goal_x, goal_y, 0, None)] # add vertexes in configuration space...
The code performs path planning using a visibility graph approach. It generates nodes around obstacles, constructs a roadmap, and applies Dijkstra's algorithm to find the shortest path from a start to a goal point. The method returns the coordinates of the planned path, optionally visualizing the roadmap if plotting is...
def planning(self, start_x, start_y, goal_x, goal_y, obstacles): nodes = self.generate_visibility_nodes(start_x, start_y, goal_x, goal_y, obstacles) road_map_info = self.generate_road_map_info(nodes, obstacles) if self.do_plot: self.p...
def turn_binary(img): image_raw = cv.cvtColor(img, cv.COLOR_BGR2GRAY) kernel = np.array([[0., 1., 0.], [1., 1., 1.], [0., 1., 0.]], np.uint8) image = normalize_image(image_raw) image_g_blur = cv.GaussianBlur(image, (5, 5), 0) image_sharpened = cv.addWeighted(image, 1.2, image_g_blur, 1 , 0) thre...
This code processes cropped Sudoku images to extract and save digit information. It handles two tasks: Task1 uses binary thresholding and grid division to extract patches, while other tasks apply color filtering, morphological operations, and specialized patch extraction. The result is written to a text file, with meth...
def process_cropped_sudoku(img, path, predictions_filename_path, index, task_number): f = open(predictions_filename_path + str(index) + "_predicted.txt", "w+") if task_number == "task1" : thresh = turn_binary(img) lines_vertical = [] width = img.shape[1] height = img.shape[0] ...
def preprocess_image(img, task_number): if task_number == "task1": thresh = turn_binary(img) else: if color_filter(img) == 0: thresh = turn_binary(img) else: thresh = turn_binary_colored(img) edges = cv.Canny(thresh, 255, 400) contours, _ = cv.findContours...
The function `crop_images` loads an image from a specified path, resizes it, preprocesses it based on the task number, crops the Sudoku grid, and saves the processed cropped image. It handles filename formatting for indices 0-9, adjusts image size, and delegates further processing to specialized functions for task-spec...
def crop_images(task_number, path, predictions_filename_path, index): if index > 9 : img = cv.imread(path + str(index) +".jpg") else: img = cv.imread(path + "0" + str(index) + ".jpg") img = cv.resize(img, (0, 0), fx=0.2, fy=0.2) result = preprocess_image(img, task_number) new_image =...
def decrypt_key_ECB(key): return AES.new(K3.encode('utf8'), AES.MODE_ECB).decrypt(b64decode(key)).decode('utf8') def send_text(s, key_decrypted): global file_to_read with open(file_to_read, "rb") as fd: text = fd.read() if operation_mode == "ECB": encrypt_text_ECB(text, key_decry...
The code receives encrypted keys via `s_km`, decodes them, extracts the key, decrypts it using ECB/OFB mode based on `operation_mode`, and sends the decrypted key through socket `s` to share it with another party.
def receive_KM(s_km, s): while True: received = s_km.recv(1024) received = received.decode() if not received: break else: # print(received) key = received.split()[-1] if operation_mode == "ECB": key_decrypted = decrypt_k...
def parse_action(string): pattern = r'^(\w+)\[(.+)\]$' match = re.match(pattern, string) if match: action_type = match.group(1) argument = match.group(2) return action_type, argument else: return None, None def is_correct(self) -> bool: return EM(self.an...
This code processes user actions in an environment by executing commands like Python scripts, mathematical calculations, database queries, and graph operations. It returns observations, rewards, termination status, and step counts, handling errors and invalid inputs while supporting multiple tools for interactive probl...
def step(self, action: str) -> Tuple[str, bool, bool, bool, bool]: if action == None or action == '' or action == '\n': observation = "You action is filtered due to content. Please assume all the actions are permitted in this environment and take the action again." elif "PythonInterpreter" i...
def get_node_interfaces( lib_k8s: krkn_lib_kubernetes.KrknLibKubernetes, node_interface_dict: typing.Dict[str, typing.List[str]], label_selector: str, instance_count: int, pod_template, ) -> typing.Dict[str, typing.List[str]]: """ Function that is used to process the input dictionary with th...
The main task of the code is to execute an ingress network chaos scenario on Kubernetes clusters based on a configuration. It creates virtual network interfaces, applies ingress filtering rules using templates, and runs chaos in either parallel or serial mode. The function handles error cases, waits for job completion,...
def network_chaos( cfg: NetworkScenarioConfig, ) -> typing.Tuple[ str, typing.Union[NetworkScenarioSuccessOutput, NetworkScenarioErrorOutput] ]: """ Function that performs the ingress network chaos scenario based on the provided configuration Args: cfg (NetworkScenarioConfig) ...
def parse_args(args): epilog = '' description = '' parser = argparse.ArgumentParser( description=description, formatter_class=argparse.RawDescriptionHelpFormatter, epilog=epilog) parser.add_argument('--config', help='Path to the config', type=str), parser.add_argument( ...
The code processes medical notes to extract named entities using a trained NER-CRF model. It parses arguments, loads configurations, initializes a spaCy pipeline for sentence splitting, processes input data, loads a pre-trained NER model, and applies it to annotated documents, saving results to a specified output path.
def main(args=None): if args is None: args = sys.argv[1:] args = parse_args(args) config = load_config(args.config) nlp = spacy.load('en_core_web_sm', disable=[ 'tagger', 'parser', 'ner', 'lemmatizer']) nlp.add_pipe("sentencizer") documents = process_data(args.no...
def parse_args(args): epilog = '' description = '' parser = argparse.ArgumentParser( description=description, formatter_class=argparse.RawDescriptionHelpFormatter, epilog=epilog) parser.add_argument('--config', help='Path to the config', type=str), parser.add_argument('--eval...
The main task of the code is to evaluate a Named Entity Recognition (NER) model using a pre-trained CRF architecture. It loads configuration settings, spaCy's English NLP model, evaluation data, and a saved NER checkpoint. The processed evaluation documents are then analyzed with the loaded model, outputting results to...
def main(args=None): if args is None: args = sys.argv[1:] args = parse_args(args) config = load_config(args.config) nlp = spacy.load("en_core_web_sm") evaluation_documents = get_evaluation_documents(args.eval_data) ner_model = NER_CRF.load_from_checkpoint(config['checkpoint'], ...
def has_processed(symbol): with DatabaseManager() as db: rows = db.read_data(symbol) if not rows: return False symbol, tested_at = rows[0] tested_at = datetime.strptime(tested_at, '%Y-%m-%d %H:%M:%S.%f') return (datetime.now() - tested_at).days < 365 def is_volat...
The code evaluates if a stock is a "strong buy" by checking volatility, return on equity (ROE), and debt ratios. It skips processed symbols, logs results if verbose, and returns a dictionary with key metrics (ROE, volatility, 52-week range, exchange) only if all criteria are met; otherwise, it returns None.
def test_strong_buy(symbol, verbose): if has_processed(symbol): logging.info(f"{symbol} has already been processed") return None # Return None if already processed else: with DatabaseManager() as db: db.insert_data(symbol, datetime.now()) ticker = Ticker(symbol)...
def train_one_epoch(self, loader): self.log(f"==> Start Training {self.workspace} Epoch {self.epoch}, lr={self.optimizer.param_groups[0]['lr']:.6f} ...") total_loss = 0 if self.local_rank == 0 and self.report_metric_at_train: for metric in self.metrics: metric.clear(...
The main task of the code is to train a model using the provided train_loader and valid_loader for a specified number of epochs. It performs training, validation, and checkpoint saving at regular intervals, logs training duration, and supports TensorBoard logging if enabled. The function ensures a text prompt is provid...
def train(self, train_loader, valid_loader, max_epochs): assert self.text_z is not None, 'Training must provide a text prompt!' if self.use_tensorboardX and self.local_rank == 0: self.writer = tensorboardX.SummaryWriter(os.path.join(self.workspace, "run", self.name)) start...
def _forward_batch(self, q): # Batch of questions tokens = [self.get_tokens(q[i]) for i in range(len(q))] ids = [self.tokens_to_id(tokens[i]) for i in range(len(q))] embeddings = [self.embedding(id_) for id_ in ids] outputs = [self.gru(embedings.unsqueeze(0))[0] for embed...
The code processes input text (q) by converting it to token embeddings, feeding them through a GRU neural network, and returning the final hidden state as a contextualized representation of the input sequence. It handles both single strings and numpy arrays, with batch processing enabled for array inputs.
def forward(self, q): if isinstance(q,np.ndarray): return self._forward_batch(q) tokens = self.get_tokens(q) ids = self.tokens_to_id(tokens) embeddings = self.embedding(ids) outputs, _ = self.gru(embeddings.unsqueeze(1)) return outputs[-1].squeeze(0)
def convertSymbol2ID(self, find: list[str]) -> dict[str: str] | set: res = {'error': False} # make all string lower and remove all empty string (including '\n' '\t' ' ') find = [x.lower() for x in find if x.replace(' ', '') != ''] checkSet = set(find) # check if items in find ...
This method retrieves cryptocurrency prices from CoinGecko by converting input symbols to IDs, making an API request with those IDs, and mapping the returned JSON data to original symbols. It returns a dictionary of prices, along with sets of symbols that failed conversion or price retrieval, and logs warnings for miss...
def getPriceOf(self, find: list[str]) -> dict[str, float]: path = 'simple/price' id, missingCryptoFromConvert = self.convertSymbol2ID(find=find) id = self.deleteControlItem(id) priceToReturn = dict() checkSet = set(id.keys()) param = { 'ids': ','.join(id.value...
def map_digits_using_segments_count(digits_str): res = [] for i in range(10): digit_map = [] for digit_str in digits_str: if len(digit_str) == DIGITS_SEGMENTS_COUNTS[i]: digit_map.append(digit_str) res.append(digit_map) return res def only_in_first(first, ...
The main task of the code is to map seven-segment display characters (a-g) to their corresponding power-of-two values by analyzing segment patterns in the input digits string. It identifies each segment through elimination and comparison of unique segment counts in known digits (e.g., 1, 4, 7), then assigns each segmen...
def mapping_segment(digits_str): digits_map = map_digits_using_segments_count(digits_str) a = only_in_first(digits_map[7][0], digits_map[1][0])[0] digits_map = remove_char(digits_map, a) f = digits_map[1][0][0] digits_map = remove_char(digits_map, f) c = digits_map[1][0][0] digits_map = r...
def get_area_data(self, key): self.open_area(key) area = self.main_area.read(self.area_size * 20) area = area.split(sep='\n') return area[:-1] def find_in_area(self, array, K): self.number_of_comparisons = 0 N = len(array) k = int(math.log2(N)) i = 2 ** k ...
The code searches for a key in a primary area; if not found and the primary area is full, it checks an overflow area. It returns the first match or None if neither area contains the key.
def find(self, key): area = self.get_area_data(key) main_area_search = self.find_in_area(area, key) if main_area_search != None: return main_area_search elif self.occupancy(area) >= self.area_size: area = self.get_area_data('overflow') overflow_area_se...
def create_line(self, key, data): return self.num_to_len_5(key) + ',' + self.str_to_len_n(data, 13) def get_area_data(self, key): self.open_area(key) area = self.main_area.read(self.area_size * 20) area = area.split(sep='\n') return area[:-1] def occupancy(self, area): k ...
This code adds a key-data pair to a storage system. It creates a new entry, checks if the target area has space or already contains the key, and inserts the entry there. If the area is full, it adds the entry to an overflow area. The function returns 'added' upon successful insertion.
def add(self, key, data): new_line = self.create_line(key, data) area = self.get_area_data(key) if self.occupancy(area) < self.area_size or self.find_in_area(area, key) != None: area = self.add_line(area, new_line) self.write_area(key, area) else: ar...
def get_area_data(self, key): self.open_area(key) area = self.main_area.read(self.area_size * 20) area = area.split(sep='\n') return area[:-1] def occupancy(self, area): k = 0 for line in area: if int(line[:5]) == 0: return k k += 1...
This code removes a specified key from a data structure by checking its presence in the primary area or overflow area. If found, it removes the key, updates the area, and returns 'removed'; otherwise, it returns -1.
def remove(self, key): area = self.get_area_data(key) if self.occupancy(area) < self.area_size or self.find_in_area(area, key) != None: if self.find_in_area(area, key) == None: return -1 area = self.remove_in_area(key, area) self.write_area(key, area)...
def createDir(directories,dir): index=getIndex(directories,dir) if index[0]==True: return False#exists else: tmp=index[1] for d in index[0]: tmp[d]={} tmp=tmp[d] return True def removeDir(directories,dir): index=getParentIndex(directories,dir) if i...
The code handles user commands to manage a directory structure. It creates, removes, or renames directories based on input, updating the global 'directories' variable or returning status messages like "Directory exists" or "Directory does not exist" depending on operation success.
def userInput(command): global directories if command=='create': dir=input() if createDir(directories,dir): return (directories) else: return('Directory exists') elif command=='remove': dir=input() if removeDir(directories,dir): ret...
def clear_canvas(self): """Remove all objects from the canvas.""" for id in self.canvas.find_all(): self.canvas.delete(id) self.elements.clear() def init_game_objects(self): """Initial objects on the game canvas.""" # draw buildings before gorillas self.bui...
The `init_game` method initializes game elements by setting the canvas background, clearing the canvas, creating game objects, binding mouse click events, initializing the control panel, and designating the next player to take a turn. It prepares the game environment for interaction and gameplay.
def init_game(self): """This method is called by the superclass (GameApp) constructor to initialize game elements. """ self.canvas['bg'] = config.CANVAS_COLOR self.clear_canvas() self.init_game_objects() # handle mouse clicks (not actually used now) self.p...
def game_over(self, winner_index: int): """Update scores and ask to play again.""" score = self.scores[winner_index] score.set(score.get()+1) winner = self.players[winner_index] msg = f"{winner} wins!\n\nPlay again?" newgame = messagebox.askyesno("Game Over", msg) ...
The main task of the code is to handle an explosion event in a game. It updates the explosion and player states, checks if the explosion has finished, and if so, records the explosion, checks for collisions with a monkey, determines a winner, ends the game, and restarts it if a monkey is hit. If not, it transitions to ...
def exploding(self): """An explosion is occurring.""" self.explosion.update() # give player a chance to update his image, if necessary self.player.update() if self.explosion.is_exploding(): return # done exploding, change the state self.craters.append(...
def getDeviceHeader(): global deviceHeader authHeaders = {"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8"} userName = input("Concert username[iotpadminuser]: ") or "iotpadminuser" password = getpass.getpass("Password for {0}: ".format(userName)) try: print("authURL: {0}".format(config.aut...
The code initializes an MQTT client to connect to AWS IoT, processes user input for LED/Switch sensor control, and publishes JSON-formatted device status updates to an AWS IoT topic. It handles sensor value retrieval, user interface options for message display/control, and maintains a loop for continuous device state m...
def main(): global LED_SensorType global Switch_Sensor_Type global do_publish global curr_Display_Switch global curr_Mess_Display getDeviceHeader() #LED_SensorType = getSensorTypeID("LED") #Switch_Sensor_Type = getSensorTypeID("Switch") curr_Display_Switch = getSnapshotSensorValue(deviceId,"Switch") cu...
def browse(self,id): self.file,_ = QtGui.QFileDialog.getOpenFileName(self, 'choose the image', os.getenv('HOME') ,"Images (*.png *.xpm *.jpg)" ) if self.file == "": logger.info("no file has been chosen to be open") pass #error when upload img1 before img2 #set...
This function connects GUI elements to their respective functions in a PyQt application. It links menu actions to methods like newwindow() and browse(), connects combo box selections to Fourier transform handling functions (choose_FT(), mixer(), update_mode()), sets default selections, and attaches slider updates to sl...
def connect_func(self): self.actionNew_Window.triggered.connect(self.newwindow) self.actionImage1.triggered.connect(lambda: self.browse(0)) self.actionImage2.triggered.connect(lambda: self.browse(1)) logger.info("open buttons are connected to their functions successfully") ...
def get_post_nat_ip(self): ip_post_nat_text = self.get_xml_text('IP_Address') return ip_post_nat_text, int(ipaddress.ip_address(ip_post_nat_text)) def get_post_nat_port(self): port_post_nat_text = self.get_xml_text('Port') return int(port_post_nat_text) def get_nat_log_file_paths(self): ...
The code scans NAT logs for entries matching a specific time, post-NAT IP, and port by executing grep commands on log files. It retrieves relevant log lines, processes them, and returns the results as a list.
def scan_nat_logs(self): ip_post_nat, ip_post_nat_decimal = self.get_post_nat_ip() port_post_nat = self.get_post_nat_port() files_to_scan = self.get_nat_log_file_paths() # Create command used to scan nat logs # for file in files_to_scan: tail = ntpath.basenam...
def get_local_time_stamp(self): # Local timezone as eastern local_tz = pytz.timezone("America/New_York") # Get utc time from infringement xml utc_text = self.get_xml_text('TimeStamp') # Create datetime object from utc time stamp received in xml utc_dt = datetime.strptim...
The code initializes a class to process XML and NAT logs by setting timestamps, scanning NAT logs, extracting IP/port information, validating IP addresses, and raising exceptions if invalid IPs are detected.
def __init__(self, xml_file_path, nat_log_folder_path): self.end_time = datetime.now() self.start_time = datetime.now() self.xml_file_path = xml_file_path self.xml_data = '0' self.nat_log_folder_path = nat_log_folder_path self.exact_local_time, self.local_dt = self.get_lo...
def extract_query(sample_path): # Read the content of the file with open(sample_path, 'r',encoding='utf-8', errors='ignore') as file: content = file.read() # Extract the sentence between <q> and </q> tags start_tag = '<q>' end_tag = '</q>' # Use regular expressions to find the content ...
The function generates a summary and snippet from a document by extracting key sentences using a Markov chain model. It processes input text, builds a sentence relationship graph via word sets, computes sentence scores, selects top-ranked sentences, and returns a summary string and a snippet of the top three sentences ...
def summarize_and_evaluate(sample_no,test_type,use_ext_only = False): sample_path = cons.document_root + "/" + test_type + "/" + sample_no + ".txt" input_query = extract_query(sample_path) input_doc = extract_doc(sample_path) input_summary = extract_summary(sample_path) # Get the list of sentences a...
def clean_expired_talks(self): if len(self.talks) <= 0: return None talk_keys = self.talks.keys() for user_id in talk_keys: # get expired time expired_time = datetime.datetime.strptime(self.talks[user_id]['expired'], "%Y-%m-%d %H:%M:%S") ...
The main task of the code is to process active user interactions (talks) by checking for completed polls or queries, retrieving selected options, and triggering corresponding response functions. It handles special selections like quitting or returning to the root menu, executes predefined functions based on poll result...
def check_talks(self): """ look each talk and reply the answers """ # remove expired talk self.clean_expired_talks() # if len(self.talks) > 0: # check polls # call the response function if poll was voted talking_user_ids = list(self.talks.keys())...
def clean_expired_talks(self): if len(self.talks) <= 0: return None talk_keys = self.talks.keys() for user_id in talk_keys: # get expired time expired_time = datetime.datetime.strptime(self.talks[user_id]['expired'], "%Y-%m-%d %H:%M:%S") ...
This function manages user interactions by either continuing existing talks (handling polls or queries) or initiating a new conversation. It cleans expired talks, checks for active user sessions, executes appropriate actions (e.g., quitting polls, calling response functions), and starts fresh talks with introductions w...
def start_talk(self, user, mention): """ if there are no continue talk, just start a new talk if there is a talk for the current user, just do something depends on the action """ # remove expired talk self.clean_expired_talks() # get user id user_id = us...
def fix_rotation(img): img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) img_edges = cv2.Canny(img_gray, 100, 100, apertureSize=3) lines = cv2.HoughLinesP(img_edges, 1, math.pi / 180.0, 100, minLineLength=100, maxLineGap=5) angles = [] for [[x1, y1, x2, y2]] in lines: # cv2.line(img, (x1, y1...
The main task of the code is to process an input image through a series of transformations: resizing, rotation alignment, skew correction, artifact removal, and border extension. It saves the original, processed, and bordered versions of the image, adjusts DPI, and conditionally exits or saves results. The function ser...
def master_image_processor(image_name, path): # packages all pyImageProcess funcs in one general use-case call # edge cases will be passed through another tunnel image = cv2.imread(path, 1) image = cv2.resize(image, (0, 0), fx=0.25, fy=0.25) # detects angle of the image and aligns it upwards at 90d...
def get_route(ori_str, des_str,routing, alpha, obs, con): """ Geocodes the origin and destination, then returns the route. Main documentation is in the stream_route docstring. """ g1 = geocoder.osm(ori_str + " Brighton, MA") g2 = geocoder.osm(des_str + " Brighton, MA") p1 = (g1.json['lng'], g1.json['lat...
The function `get_fig` retrieves a route from a database based on origin/destination addresses, routing method (`short`, `slope`, `balance`), penalty factor `alpha`, and obstacle avoidance (`obs`). It connects to the database, fetches the route using `get_route`, generates map-drawing lines with `make_lines`, and retur...
def get_fig(ori_str, des_str, routing, alpha, obs): """ This is the point of this file. This function ocnnects to the database, gets a route from ori_str to des_str according to the routing method/alpha/obs, and returns the lines to draw. Arguments: ori_str, des_str -- strings of street addresses ...
def _load_students_and_create_instances(self, file_path): """ This method loads the students from the given file_path and creates an instance of the Student class for record read from the file. At the end, it calls the __init_scores_board to create the initial empty scores board for all ...
The main task of the code is to generate a specified number of student data entries, save them to a JSON file, create Student class instances, automatically assign 3 magic items to each student, and optionally display their weapons. It includes user input validation, data generation, file handling, object instantiation...
def init_students(self,file_path='./configuration/students_list.json'): """ It starts generating the given number of students' data to persit to a JSON file. Secondly, it loads the content of the file and for each student's data it creates an instance of the Student class. After ...
def test1(): with open("data/data7test", "r") as file: bags = outermost_bags("shiny gold", file) print(f"Test1 : {len(bags)} {len(bags) == 4}") def part1(): with open("data/data7", "r") as file: bags = outermost_bags("shiny gold", file) print(f"Part 1 : {len(bags)} {bags}") def t...
The main task of the code is to execute a sequence of test and part functions related to "Day 7" of a coding challenge or project. It prints a header, runs test1(), part1(), test2(), test2_2(), part2(), and separates sections with a delimiter, likely organizing and executing tasks for a structured coding problem.
def day7(): print("Day 7 \n") test1() part1() test2() test2_2() part2() print("----------------------\n")
def test(): with open("data/data6test", "r") as file: yes = count_answer(file) print(f"Test: {yes} {yes == 11}") def test2(): with open("data/data6test", "r") as file: yes = count_answer_2(file) print(f"Test2: {yes} {yes == 6}") def part1(): with open("data/data6", "r") as fi...
The main task of the code is to execute a sequence of functions (test(), test2(), part1(), part2()) under the "Day 6" label, likely for testing or demonstration purposes, with print statements separating sections.
def day6(): print("Day 6 \n") test() test2() part1() part2() print("----------------------\n")
def main_window(): ptr = omUI.MQtUtil.mainWindow() try: maya_window = wrapInstance(long(ptr), QtWidgets.QMainWindow) except: maya_window = wrapInstance(int(ptr), QtWidgets.QMainWindow) #Fixed bug in python 3 return maya_window def my_ui(self): # -- Setting window -- # se...
This code initializes a UI component for an application, setting up widgets, layouts, buttons, and image handling variables. It prepares the interface for importing FBX files, including sliders, search fields, folder paths, and image scaling parameters. The `my_ui()` method is called to finalize UI setup, while comment...
def __init__(self, parent=None): super(Import_Fbx, self).__init__(main_window()) self.centralwidgets = None self.vbox_layout = None self.project_tab = None self.main_tab = None self.child_tab_vertical_layout = None self.scroll_area = None self.scrollAreaWi...
def literal(self, s): if not s: return if not self.in_literal: self.indent() self.file_out.write('yield """') self.in_literal = True self.file_out.write(s.replace('"', '\\"')) def close_literal(self): if self.in_literal: self.fi...
This code parses a line by identifying and processing elements starting with a specific character. It separates literals, statements (STMNT), and expressions (EXPR), handling each type with dedicated methods. The loop processes the line incrementally, trimming processed sections and continuing until the line is fully p...
def parse_line(self, l): while l: start = l.find(self.START_CHAR) if start == -1: self.literal(l) return self.literal(l[:start]) self.close_literal() sel = l[start + 1] #print("*%s=%s=" % (sel, EXPR)) ...
def header(self): self.file_out.write("# Autogenerated file\n") def parse_line(self, l): while l: start = l.find(self.START_CHAR) if start == -1: self.literal(l) return self.literal(l[:start]) self.close_literal() ...
The code compiles input data by generating a header, parsing each line of the input file, closing literal structures, and returning the compiled sequence. It processes the file line-by-line using helper methods to build and finalize the output.
def compile(self): self.header() for l in self.file_in: self.parse_line(l) self.close_literal() return self.seq
def export_pattern(self, export_dir): patname = self.pat_name_cb.SelectedItem existing_pats = DB.FilteredElementCollector(revit.doc)\ .OfClass(DB.FillPatternElement)\ .ToElements() fillpats = [x.GetFillPattern() for x in existing_pats] ...
The code's main task is to export a pattern either directly if `self._export_only` is set, or by verifying a name, selecting a domain, and creating a new pattern with specified export settings. It handles user input for directories and domains, triggers pattern creation or export, and closes the interface afterward.
def export_pat(self, sender, args): if self._export_only: self.Close() export_dir = forms.pick_folder() if export_dir: self.export_pattern(export_dir) elif self.verify_name(): self.Hide() domain = self.pick_domain() ...
def verify_name(self): if not self.pat_name: forms.alert('Type a name for the pattern first') return False elif not re.search('[a-zA-Z0-9]', self.pat_name): forms.alert('Pattern name must have at least ' 'one character or digit') re...
The function verifies the name, hides the object, selects a domain, creates a pattern if a valid domain is found, and then closes.
def make_pattern(self, sender, args): if self.verify_name(): self.Hide() domain = self.pick_domain() if domain: self.create_pattern(domain) self.Close()
def create_command(cmd: MonCommand, cmd_data: List = []) -> Command: return Command(cmd, cmd_data) def send_command(command: Command) -> None: log_sending(command) get_socket().sendall(command.blob) def await_response() -> None: """Receive data from the socket, parse it and put responses on the global R...
This function sends a command and waits for its response. It creates a command from the input, sends it, retrieves the request ID, and in a blocking loop, waits for the corresponding response. Once received, it returns the response associated with the request ID, handling cases where the response is not yet available.
def roundtrip_command(cmd: MonCommand, cmd_data: List=[], blocking=True) -> MonResponse: command = create_command(cmd, cmd_data) send_command(command) request_id = command.get_request_id() while blocking: try: await_response() return pop_response(request_id) excep...
def consume_word_token(input_tokens: List[str], default_or_none: None, name: str = '<address>') -> int: if input_tokens: token = input_tokens.pop(0) ok, value = parse_token(token, WORD_PAT, int_16) if ok: return value else: raise SyntaxError(f'Invalid token "{...
This function parses input tokens to determine memory addresses, reads memory data from the specified range, and updates the global PROMPT_ADDR for subsequent operations. It consumes address tokens, validates ranges, retrieves memory contents, and prints the result while advancing the prompt address pointer.
def parse_cmd_m(input_tokens: List[str]) -> None: global PROMPT_ADDR first = PROMPT_ADDR last = PROMPT_ADDR + MEMDUMP_DEFAULT_BYTES - 1 first = consume_word_token(input_tokens, first, '<first-address>') last = consume_lastaddr_token(input_tokens, first + MEMDUMP_DEFAULT_BYTES - 1, '<last-address>', ...
def consume_string_token(input_tokens: List[str], default_or_none: None, name: str='<string>') -> str: if input_tokens: token = input_tokens.pop(0) if token.startswith('"') and token.endswith('"'): return token[1:-1] return token if default_or_none is None: raise Synt...
The main task of the code is to parse command-line input tokens to extract a filename, memory address range, and load address, then read memory data from the specified range, save it to the given file with metadata, and print a confirmation message containing the filename and address details.
def parse_cmd_s(input_tokens: List[str]) -> None: filename = consume_string_token(input_tokens, None, '<filename>') first = consume_word_token(input_tokens, None, '<first-address>') last = consume_lastaddr_token(input_tokens, None, '<last-address>', first, '<first-address>') load = consume_word_token(in...
def consume_word_token(input_tokens: List[str], default_or_none: None, name: str = '<address>') -> int: if input_tokens: token = input_tokens.pop(0) ok, value = parse_token(token, WORD_PAT, int_16) if ok: return value else: raise SyntaxError(f'Invalid token "{...
The function parses hexadecimal tokens from input into byte data, writes them to memory starting at a specified address, and updates the global PROMPT_ADDR to the end of the written data for sequential memory operations.
def parse_cmd_wm(input_tokens: List[str]) -> None: global PROMPT_ADDR first = consume_word_token(input_tokens, None, '<address>') cmd_data = [] for t in input_tokens: if len(t) > 2: cmd_data.append(np.uint16(int(t,base=16)&0xffff)) else: cmd_data.append(int(t,base...
def consume_string_token(input_tokens: List[str], default_or_none: None, name: str='<string>') -> str: if input_tokens: token = input_tokens.pop(0) if token.startswith('"') and token.endswith('"'): return token[1:-1] return token if default_or_none is None: raise Synt...
The main task of the code is to load a file into memory at a specified address. It parses input tokens to extract the filename and load address, loads the file's contents, writes them to memory starting at the specified address, and prints a confirmation message with the loaded file's name and memory range.
def parse_cmd_l(input_tokens: List[str]) -> None: filename = consume_string_token(input_tokens, None, '<filename>') load_addr = consume_word_token(input_tokens, 0, '<load-address>') load_addr, body = load_file(filename, load_addr=load_addr) write_memory(load_addr, body) print(f'Loaded "{os.path.spli...
def monitor_exit(): return roundtrip_command(MonCommand.exit) def response_pending() -> bool: readable, writable, errored = select.select([get_socket()],[],[], 0) return get_socket() in readable def await_response() -> None: """Receive data from the socket, parse it and put responses on the global RESPO...
The function resumes the emulator, waits for debugger events with an optional timeout, and handles user interruptions (Ctrl-C) or timeouts by clearing the response queue and exiting, ensuring responsive debugging control.
def wait_for_debugger_event(timeout: Union[float,None] = None): """Resume the emulator and wait for a debugger event. A timeout may be specified, but the user can also break and pause the emulator by pressing Ctrl-C """ target_time = time.time() + timeout if timeout else 0 global RESPONSE_QUEUE...
def consume_word_token(input_tokens: List[str], default_or_none: None, name: str = '<address>') -> int: if input_tokens: token = input_tokens.pop(0) ok, value = parse_token(token, WORD_PAT, int_16) if ok: return value else: raise SyntaxError(f'Invalid token "{...
The function `parse_cmd_g` parses an address token from input, sets the program counter (PC) to that address if valid, and exits the monitor. It uses a global `BREAK_ADDR` for validation, consuming the token and updating registers before terminating the monitoring process.
def parse_cmd_g(input_tokens: List[str]) -> None: global BREAK_ADDR addr = consume_word_token(input_tokens, BREAK_ADDR, '<address>') if addr != BREAK_ADDR: set_registers({"PC": addr}) monitor_exit()
def consume_word_token(input_tokens: List[str], default_or_none: None, name: str = '<address>') -> int: if input_tokens: token = input_tokens.pop(0) ok, value = parse_token(token, WORD_PAT, int_16) if ok: return value else: raise SyntaxError(f'Invalid token "{...
The function `parse_cmd_break` parses input tokens to set a breakpoint, extracting the first and last addresses, a condition, and invoking `set_breakpoint` with these parameters and the given mode.
def parse_cmd_break(input_tokens: List[str], mode: BreakPointMode): first_addr = consume_word_token(input_tokens, None, '<address>') last_addr = consume_lastaddr_token(input_tokens, first_addr, "<last-address>", first_addr, "<first-address") condition = consume_string_token(input_tokens, '', "<condition>") ...
def preprocess(data): return pd.DataFrame({'sepal length': data[0], 'sepal width': data[1], 'petal length': data[2], 'petal width': data[3], 'class': data[4]}) def kmeans(df, k): # performs k-means randindices = random.sample(range(0, df.shape[0]), k) kcenters = [] # list of centers updated at each iterat...
The code performs Principal Component Analysis (PCA) on the Iris dataset to reduce dimensionality, then applies k-means clustering for k=2 to 8. It calculates Normalized Mutual Information (NMI) to evaluate clustering quality, identifying the optimal k with maximum NMI. The process includes data preprocessing, feature ...
def main(): classmap = { # maps each class to a particular integer 'Iris-setosa': 0, 'Iris-versicolor': 1, 'Iris-virginica': 2 } data = pd.read_csv('iris.data',header=None) data = preprocess(data) df = data.drop('class', axis=1) features = ['sepal length', 'sepal width',...
def is_csv_file(filepath: Path): """ This function checks whether the filename provided is a valid file and whether it is of the required csv format. :param filepath: R2D2 get output csv path :return: Valid file path """ if filepath.is_file(): if file...
The main task of the code is to initialize a CSV data viewer application. It checks command-line arguments to load CSV data, loads a UI from a .ui file, sets up settings, restores sessions, configures buttons/menus, and starts the GUI if valid data is provided. If no data is loaded, it opens a file browser to select a ...
def __init__(self, parent=None): super(Showcsv, self).__init__(parent) logging.info(START) logging.info(f"CSV data viewer version - {VERSION}") # Check if correct argument number provided if len(sys.argv) == 1: self.dataIn = None elif len(sys.argv) == 2: ...
def is_train_test_file_exists(self)->bool: try: logging.info("Checking if training and test file is available") is_train_file_exist=False is_test_file_exist=False train_file_path=self.data_ingestion_artifact.train_file_path test_file_path=self.data_in...
The main task of the code is to perform data validation by checking the existence of train/test files, validating the dataset schema, and detecting data drift. It then creates a `DataValidationArtifact` with configuration paths, marks validation as successful, logs the artifact, and returns it. Exceptions are handled b...
def initiate_data_validation(self)->DataValidationArtifact: try: self.is_train_test_file_exists() self.validate_dataset_schema() self.is_data_drift_found() data_validation_artifact=DataValidationArtifact( schema_file_path=self....
def __get_available_actions(self) -> str: """Get a string to inject into the prompt telling the agent what actions it can take.""" actions = "\n".join( ["- " + action.to_string() for action in self.actions_available] ) return actions def __get_actions_taken(self) -> s...
The code runs an agent to achieve a specified objective by iteratively generating prompts, processing AI completions as JSON, executing actions, and handling errors. It formats prompts with context, available actions, and memory, then decodes the AI's response. If valid, it processes the action, updates the agent's sta...
def run(self): """Runs the agent.""" action = None steps = 0 while action is not DONE_FUNCTION and steps < self.max_steps: # Format the prompt and get a completion prompt = AGENT_PROMPT.format( objective=self.objective, actions=sel...
def attribute_split_probability(self): probability = np.zeros(self.data.shape[1]) if self.data_name in ["ids2017_2","ids2017_3","ids2017_4","ids2017_5","ids2017_6","ids2017_7","ids2017_8"]: important_idx = [10, 62, 3, 12, 18, 23, 0, 72, 69, 25, 65, 29, 43, 66, 7, 36, 45, 51] rati...
This code implements an iterative anomaly detection system using Isolation Forests. It trains on streaming data, computes anomaly scores, evaluates performance (ROC, PR), dynamically queries data based on distribution changes via KL divergence, updates model weights using pseudo-labels, and returns average evaluation m...
def run(self, train_size, iter): stream = DataStream(self.data, self.label) self.attr_prob = self.attribute_split_probability() roc_all = [] f1_all = [] pr_all = [] self.batch = 0 print("Begin Trainning and Testing-----------") start_time = time.time() ...
def get_dict(): return nc.cmudict.dict() def create_single_Line(model, num, corpus): #gotta clean this all up.... while True: originalText = model.make_sentence() if originalText: text = copy_text(originalText) while text and ' ' in text and text != ' ': ...
The code generates a poem by splitting a model-generated text into lines that match specified syllable counts. It uses a corpus for syllable checks, iteratively finding substrings with the required syllables, and returns the structured poem as a string.
def create_Poem(model, lines, corpus=None): start = 0 poem_return = [] if corpus is None: corpus = get_dict() poem = create_single_Line(model, sum(lines), corpus) words = poem.split(' ') for line in lines: found = False for i in range(start, len(words)+1): ...
def _process_arp(self, pkt): """ Updates ARP cache upon receiving ARP packets, only if the packet is not spoofed. """ try: if pkt.op == 2 and pkt.hwsrc != self._host_state.host_mac: self._host_state.set_ip_mac_mapping(pkt.psrc, pkt.hwsrc) exc...
The function processes network packets by checking for ARP, DHCP, and SYN-ACK responses, filtering traffic based on MAC OUIs, host IP, and gateway IP. It handles DNS, TCP/UDP protocols, and routes packets to appropriate processing methods like _process_arp, _process_dhcp, or _process_tcp_udp_flow, while ignoring irrele...
def _process_packet_helper(self, pkt): if sc.ARP in pkt: return self._process_arp(pkt) if sc.DHCP in pkt: return self._process_dhcp(pkt) # SYN-ACK response to SYN scans if sc.TCP in pkt and pkt[sc.TCP].flags == 'SA' and sc.IP in pkt: tcp_layer = pkt...
def display_home_page(): print("Welcome to Book My Property!") print("Please select an option:") print("1. Buy") print("2. Sell") print("3. Rent") def get_user_choice(): while True: try: choice = int(input("Enter your choice (1/2/3): ")) return choice exce...
This code implements a menu navigation system using stacks. It allows users to select options (Buy/Sell/Rent) which push corresponding submenu labels onto a stack. The '0' choice navigates back by popping from the stack, managing hierarchical menu transitions. The loop continues until the user exits from the main menu.
def main(): menu_stack = [] # To keep track of the main menu submenu_stack = [] # To keep track of the sub-menus user_choice = -1 while user_choice != 0: display_home_page() user_choice = get_user_choice() if user_choice == 1: buy_options() submenu_sta...
def pair_addr(child, addr): print("Pairing " + addr) child.sendline('pair ' + addr) def lcd_clear_lines(lcd): lcd.lcd_display_string(''.center(20), 2) lcd.lcd_display_string(''.center(20), 3) lcd.lcd_display_string(''.center(20), 4) lcd_refresh_wifi_status(lcd) def get_pin(kp, lcd): lcd.lcd_...
The function `pair_ble` automates Bluetooth pairing with a device at address `addr`, using `bluetoothctl` via `pexpect`. It handles passkey input through a keypad/LCD or direct input, retries up to 5 times on failure, and authenticates via a REST API upon success. If pairing fails, it displays an error on an LCD and re...
def pair_ble(addr, kp=None, lcd=None): print("Initializing pairing process...") child = pexpect.spawn('bluetoothctl') global locked # Uncomment to enable debug output child.logfile = sys.stdout.buffer child.expect('Agent registered', timeout=5) #child.sendline('default-agent') #child.e...
def lcd_clear_lines(lcd): lcd.lcd_display_string(''.center(20), 2) lcd.lcd_display_string(''.center(20), 3) lcd.lcd_display_string(''.center(20), 4) lcd_refresh_wifi_status(lcd) def lcd_refresh_wifi_status(lcd): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) try: s.connect(('10.255...
The function assigns an NFC tag to a child by reading the tag's UID, sending it to a REST API, and updating an LCD display with status messages. It handles user input for cancellation, checks for tag availability, and provides feedback on success or errors, such as tag reuse or API issues.
def assign_nfc(kp, lcd, nfc): global locked locked = False global allow_nfc allow_nfc = False t = time.time() lcd_clear_lines(lcd) lcd.lcd_display_string('ASSIGN NFC Tag'.center(20), 1) lcd_refresh_wifi_status(lcd) lcd.lcd_display_string('* back'.ljust(10)+'ok #'.rjust(10), 4) ...
def lcd_clear_lines(lcd): lcd.lcd_display_string(''.center(20), 2) lcd.lcd_display_string(''.center(20), 3) lcd.lcd_display_string(''.center(20), 4) lcd_refresh_wifi_status(lcd) def lcd_refresh_wifi_status(lcd): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) try: s.connect(('10.255...
The main task of the code is to unassign an NFC tag from a child's bracelet via an API, using an LCD for user feedback. It reads an NFC UID, calls a delete endpoint, and displays success/error messages. The process includes autolock handling, user input checks, and LCD updates to guide users through unassigning the tag...
def delete_nfc(kp, lcd, nfc): global locked locked = False global allow_nfc allow_nfc = False t = time.time() lcd_clear_lines(lcd) lcd.lcd_display_string('Unassign NFC Tag'.center(20), 1) lcd_refresh_wifi_status(lcd) while not locked: identifier = get_child_id(kp, lcd, n...
def get_child_id(kp, lcd, nfc): lcd.lcd_display_string('Student ID'.center(20), 2) lcd.lcd_display_string('_ _ _ _ _ _'.center(20), 3) global locked global read_nfc child_number = [] t = time.time() read_nfc = False success = False global allow_nfc if allow_nfc: lcd.lcd...
The code measures a child's weight using a scale, identifies the child via NFC or username, timestamps the measurement, and uploads the data to the OCARIOT platform. It handles success/failure scenarios, displays prompts on an LCD, and requires confirmation via a '#' key. If upload fails, data is saved locally. The pro...
def run_scale(kp, lcd, nfc): # 1 username, 2 tag identifier = get_child_id(kp, lcd, nfc) global locked if locked: return child_id = identifier[1] type = identifier[0] lcd_clear_lines(lcd) th = AnimateMessageThread(lcd, 'Starting Scale') while not scale_REST_API.reset_scal...
def lcd_home(lcd): lcd.lcd_display_string(''.center(19), 1) lcd.lcd_display_string('LOCKED'.center(20), 2) lcd.lcd_display_string(''.center(20), 3) # lcd.lcd_display_string(chr(0).center(20), 4) lcd.lcd_display_string(''.ljust(10)+'unlock #'.rjust(10), 4) lcd_refresh_wifi_status(lcd) def get_dig...
The code manages a scale interface requiring PIN-based unlocking, handling shutdown, NFC tag association, data uploads, and network settings. When unlocked, it continuously measures weights, captures student IDs, and uploads data to the OCARIOT platform. It includes backlight control, idle timeout, and signal handling ...
def run_scale_interface(kp, lcd, nfc): while True: lcd_home(lcd) global locked, ble_pair_jar global backlight_on global allow_nfc t = time.time() if locked: if ble_pair_jar is not None: ble_pair_jar.send_signal(signal.SIGINT) ...
def read_float(self, f) -> float: return struct.unpack("f", f.read(4))[0] def bound_check(self, x: float, y: float, z: float) -> bool: # Order: [xmin, xmax, ymin, ymax, zmin, zmax] if ( (x < self.bounds[0]) or (x > self.bounds[1]) or (y < self.bounds[2]) ...
This function decodes a GM_SOBJ file by parsing object data, extracting position, rotation, and scale values, applying bound checks, converting Euler angles to quaternions, and storing transformed data in a dictionary. It reads the file, identifies objects via regex, processes their properties, trims filenames, and acc...
def decode_gm_sobj(self, gm_sobj_path: str) -> None: f = open(gm_sobj_path, "rb") data = f.read().decode("latin-1") gm_regex = re.compile("cAssetBasicSetObject") for i in gm_regex.finditer(data): offset = i.start() f.seek(offset + 25) x = self.read_...
def thumb_state(self): angles = [ angle_at(*self.marks[[0,1,2],]), angle_at(*self.marks[[1,2,3],]), angle_at(*self.marks[[2,3,4],]), ] if (is_same_side( *self.marks[[0,5,9,4]] )): return CLOSED elif (np.min(angles) > BEND_THRESHOLD): ...
The code aggregates the states of five fingers (thumb, index, middle, ring, pinky) by calling their respective state methods and concatenates them into a single string, returning the combined result.
def get_state(self): t=self.thumb_state() i=self.index_state() m=self.middle_state() r=self.ring_state() p=self.pinky_state() return f"{t}{i}{m}{r}{p}"
def get_function_name(func_node): if 'id' in func_node.keys(): return func_node['id'] elif 'attr' in func_node.keys(): function_name = func_node['attr'] func_node = func_node['value'] while True: if 'attr' in func_node.keys(): function_name = func_node...
This function performs taint analysis on an AST to track data flow and identify potential security vulnerabilities. It propagates taint information through control structures (While, If), assignments, function calls, and expressions. It marks variables as tainted if they originate from sources, checks for sinks or sani...
def propagate_flow(node, implicit=''): # Flow information through an While node if node['ast_type'] == 'While': tainted_left = propagate_flow(node['test']['left']) for obj in node['test']['comparators']: tainted_comparator = propagate_flow(obj) if tainted_left[0]: ...
def read_program(program_name): with open(program_name, 'rb') as data_file: return json.loads(data_file.read()) def process_patterns(patterns): for vulnerability in patterns: present_vuln = '' for i, vuln in enumerate(PATTERNS): if vulnerability['vulnerability'] in vuln['vuln...
The main task of the code is to analyze Python code for vulnerabilities by reading an AST from a JSON file, loading vulnerability patterns, processing these patterns, propagating information flow through the AST, and printing/saving detected vulnerabilities. It identifies security risks by matching code structures agai...
def main(): # read json object of an AST of python code ast = read_program(sys.argv[1]) # read json object of patterns to identify vulnerabilities patterns = read_program(sys.argv[2]) # instantiates PATTERNS and SOURCES process_patterns(patterns) # check how information flows in code for...
def read_input_data(self,file_nm): data = pd.read_csv(file_nm, sep=" ", header=None) return data def break_index_value(self,data): break_index=0 for i in data[0]: if i[0:6]=='000110': break_index_value=i return break_index,break_index_value ...
This code simulates a file by reading input data, splitting it into instructions and register values, converting register values to decimal, categorizing instructions with addresses, formatting disassembly data, saving it to a text file, and running a simulation with the processed data and registers.
def SimulateFile(self,file_nm,strt_addr): data=self.read_input_data(file_nm) break_index,break_index_value=self.break_index_value(data) instructions_data=data[0][0:break_index+1] register_values=data[break_index+1:][0] register_decimal_values = [self.convert_complement_on_two_int...
def _recover_origin_data(dists, eta): dists **= 2 n_samples = dists.shape[0] B = _cal_B(dists, n_samples) eigen_val, eigen_vector = _do_svd(B, eta) X = _cal_X(dists, eigen_val, eigen_vector, n_samples) return X def _sampling(data): n_samples = data.shape[0] km = KMeans(n_clusters=int(np...
This function generates embeddings by first reconstructing original data from input distances using a learned parameter (eta), sampling control points from this reconstructed data, and then projecting these control points onto the original data through a real projection method to obtain final embeddings.
def fit_transform_cntp_free(self, dists, labels=None): origin_data = _recover_origin_data(dists, self.eta) control_points = _sampling(origin_data) embeddings = self.real_project(control_points, origin_data) return embeddings
def _cal_new_data_probability(self, dists): conditional_P = search_prob(dists**2, perplexity=self.desired_perplexity) self.condition_P = np.concatenate([self.condition_P, conditional_P], axis=0) return conditional_P def _initialize_new_data_embedding(self, high_prob, new_knn_indices): ca...
The function incrementally embeds a new data point into the existing latent space by computing its nearest neighbors, calculating probabilities based on distances, initializing an embedding, and optimizing it using neighbor indices and probabilities. It returns the optimized embedding for the new data.
def _incremental_embedding(self, new_data): new_data = np.reshape(new_data, (1, -1)) knn_indices, knn_dists, dists = self._cal_new_data_kNN(new_data, include_self=False) knn_indices = knn_indices.squeeze() new_data_prob = self._cal_new_data_probability(knn_dists.astype(np.float32, copy...
def _find_clusters(self, data, knn_indices): dimension_pw_, main_components = CustomizedLPCA().fit_transform_pw(data, knn_indices) n_samples = data.shape[0] idx = 1 labels = np.ones(n_samples) * -1 unlabeled_num = n_samples cluster_indices = [] unsigned_indices = ...
The function performs initial training by constructing a kNN graph from training data, clustering data points, generating local embeddings, and transforming them into global embeddings if multiple clusters exist. It returns processed embeddings after applying Euclidean transformation or using direct local embeddings, d...
def _first_train(self, train_data): self.initial_train_num = train_data.shape[0] knn_indices, knn_dists = compute_knn_graph(train_data, None, self.n_neighbors, None) self.knn_manager.add_new_kNN(knn_indices, knn_dists) self.cluster_indices = self._find_clusters(train_data, knn_indices) ...
def setup_camera(robot: cozmo.robot.Robot): robot.camera.image_stream_enabled = True robot.say_text("Camera Setup").wait_for_completed() robot.say_text("Click on Control C when it's done").wait_for_completed() sleep(2) while 1: try: do_photo(robot, "setup.png") except Key...
The code enables Cozmo's camera, captures a barcode image, reads its value, converts it to a carbon value, and inspects the carbon level. If no valid barcode is detected, it alerts the user. The process involves image capture, barcode decoding, data conversion, and robotic feedback.
def main(robot: cozmo.robot.Robot): robot.camera.image_stream_enabled = True # setup the barcode infront the robot setup_camera(robot) # take the photo do_photo(robot, path()) robot.say_text("I read the barcode").wait_for_completed() value = read_barcode(path()) if value == 0: r...
def get_compile_command(c_source: str, compile_target: str): command_template = COMPILE_COMMAND_TEMPLATES[compile_target] source_part = "-I %s -I %s %s %s -o %s" % ( os.path.join(POLYBENCHC_PATH, 'utilities'), os.path.dirname(c_source), os.path.join(POLYBENCHC_PATH, 'utilities', 'polyben...
The main task of the code is to compile a C source file using a generated command, then compress all resulting binary files into gzip archives with maximum compression (level 9). It retrieves the compilation command, executes it, locates the output binaries, and sequentially copies each binary's contents into a compres...
def compile_c_source(c_source: str, compile_target: str): command = get_compile_command(c_source, compile_target) print(command) os.system(command) bins = get_all_binary_paths_by_source(c_source, compile_target) for bin in bins: with open(bin, 'rb') as f_in, gzip.open(get_gzip_path_by_binary...
def get_args(): parser = argparse.ArgumentParser(description="jScope file creator.") parser.add_argument('--shot', default=0, type=int, help='specify shot number') parser.add_argument('--start', default=0, type=int, help='Which shot num to start at.') pars...
The main task of the code is to retrieve and process data based on the specified type ("mds" or "blob") using command-line arguments. It initializes global settings, parses input parameters, and calls corresponding data-fetching functions (`get_mdsplus_data` or `get_blob_data`) to handle different data formats, storing...
def main(): args = get_args() global _dprint _dprint = args.dprint #uuts = os.walk("/home/dt100/TREES/") # uut_dirs = [item[0] for item in os.walk("/home/dt100/TREES/")][1:] # uut_list = [item.split("/")[-1] for item in uut_dirs] if args.type == "mds": data, uut_list = get_mdsplus_d...
def get_args(): parser = argparse.ArgumentParser(description="jScope file creator.") parser.add_argument('--shot', default=0, type=int, help='specify shot number') parser.add_argument('--start', default=0, type=int, help='Which shot num to start at.') pars...
The main task of the code is to process and compare MDSPlus data across multiple "shots" (test cases) for units under test (UUTs). It iterates through a specified range of shot numbers, retrieves data for each shot using `get_mdsplus_data`, and compares the data against a threshold (`args.th`) via `compare_data`. The s...
def main(): args = get_args() global _dprint _dprint = args.dprint #uuts = os.walk("/home/dt100/TREES/") uut_dirs = [item[0] for item in os.walk("/home/dt100/TREES/")][1:] uut_list = [item.split("/")[-1] for item in uut_dirs] for shot in range(args.start, args.stop + 1): # shot =...
def log_message(message='', debug_only=False): if (verbose and not debug_only) or (debug and debug_only): print('[LOG]: %r' % message) def generate_action_map(metadata, folder): action_map = {} for d in metadata: action_map[d['SourceFile']] = generate_path(d, folder) return action_map de...
The function processes a list of files by reading their metadata using ExifTool, generating a mapping of files to destination directories based on the metadata, and then attempting to move each file to its designated location. It logs errors during the move operation but continues processing other files. If no files ar...
def handle_files(files): if not files: return with exiftool.ExifTool() as et: log_message('Reading metadata for %r' % files) metadata = et.get_metadata_batch(files) move_map = generate_action_map(metadata, dest_dir) for file, destination in move_map.items(): try: ...
def get_impute_null_transforms_for_dataset(data, add_flag=True): ''' Returns a list of dicts describing imputations for the columns of the dataset provided. Categorical variables recieve a mode imputaton, while numerical columns recieve a median imputation. Parameters ---------- data: p...
The function generates a sequence of data transformation steps for a dataset, including imputation of missing values, capping/flooring of extreme values, and one-hot encoding of categorical variables. It applies these transformations in sequence and returns a combined list of transformation specifications for later use...
def get_standard_transforms_for_dataset(dataset): ''' Returns a list of dicts representing imputation, cap, floor, onehot, and ihs transforms. The list of dicts is used by apply_transforms to apply each transform to a dataset. ''' data = dataset.copy() null_transforms = get_impute_null...
def rolmean(dataset, hrw, fs): mov_avg = dataset['hart'].rolling(int(hrw*fs)).mean() avg_hr = (np.mean(dataset.hart)) mov_avg = [avg_hr if math.isnan(x) else x for x in mov_avg] mov_avg = [x*1.2 for x in mov_avg] dataset['hart_rollingmean'] = mov_avg def detect_peaks(dataset): window = [] pe...
The main task of the code is to process a physiological signal dataset to calculate heart rate (BPM) by first applying a rolling mean to smooth the data, detecting peaks in the signal, and then computing the BPM from these peaks. The function uses a specified window size (hrw) and sample rate (fs) for accurate analysis...
def process(dataset, hrw, fs): #Remember; hrw was the one-sided window size (we used 0.75) and fs was the sample rate (file is recorded at 100Hz) rolmean(dataset, hrw, fs) detect_peaks(dataset) #calc_RR(dataset, fs) calc_bpm()
def line_length(self): return np.sum(np.abs(np.diff(self.data))) def spectral_alpha_power(self): return np.sum(np.power(get_alpha_band(self.data, self.freq), 2)) def spectral_beta_power(self): return np.sum(np.power(get_beta_band(self.data, self.freq), 2)) def spectral_gamma_power(self): return np.sum(n...
The main task of the code is to compute four features from the data: line length, alpha-band spectral power, beta-band spectral power, and gamma-band spectral power. These features are calculated by calling respective methods and returned as a list. The function serves to extract time-domain (line length) and frequency...
def get_features(self): """Calculates line length and alpha/beta/gamma spectral power of data as features""" return [ self.line_length(), self.spectral_alpha_power(), self.spectral_beta_power(), self.spectral_gamma_power(), ]
def _calculate_yahtzee_bonus(self): """Adds Yahtzee bonus to Player's total score when earned. Yahtzee bonus is earned by rolling more than one Yahtzee in a single game and is worth 100 points. """ if (self.scorecard[11][0] == 50 and self._sorted_dice[0] == self....
This method rolls specified dice based on the to_roll list, updates game state attributes, and recalculates theoretical scorecard values while enforcing input validation and game rules. It checks for valid input types, lengths, binary values, and ensures all dice are rolled on the first turn. Dice are rerolled for posi...
def roll(self, to_roll): """Rolls dice specified by the to_roll list, updates related class attributes, and calculates the theoretical scorecard values. Args: to_roll (list): A list of length 5 containing binary values where 0 indicates the die in that position shoul...
def _calculate_yahtzee_bonus(self): """Adds Yahtzee bonus to Player's total score when earned. Yahtzee bonus is earned by rolling more than one Yahtzee in a single game and is worth 100 points. """ if (self.scorecard[11][0] == 50 and self._sorted_dice[0] == self....
The function `debug_roll` rolls specified dice based on the `to_roll` list, updates class attributes like dice values and remaining rolls, and computes theoretical scorecard values. It validates inputs, ensuring `to_roll` is a binary list of length 5, and raises errors for invalid states (e.g., no rolls left). After up...
def debug_roll(self, to_roll, dice): """Rolls dice specified by the to_roll list, updates related class attributes, and calculates the theoretical scorecard values. Args: to_roll (list): A list of length 5 containing binary values where 0 indicates the die in that po...
def ruleBase(node: HydroPrimitive, candidates: typing.List[HydroPrimitive], params: HydrologyParameters): #filling """Rule 1 from Table 1 in Genevaux et al :param node: The node to expand :type node: HydroPrimitive :param candidates: The set of candidate nodes :type candidates: list[HydroPrimitive]...
The function `alpha` determines the expansion rule for a hydrological node based on its priority and probabilistic thresholds. If the node's priority is 1, it applies the base rule (`ruleBase`). For other priorities, it uses a random value to select between three rules: `rulePa` (if within `params.Pa`), `rulePc` (if wi...
def alpha(node: HydroPrimitive, candidates: typing.List[HydroPrimitive], params: HydrologyParameters): # alpha, as in the expansion rules in Table 1 """Alpha node expansion rule :param node: The node to expand :type node: HydroPrimitive :param candidates: The set of candidate nodes :type ca...
def get_info(url: str, headers: dict): """ Scrapes webpage and returns dom elements :return: Dom elements """ global r try: s = requests.Session() r = s.get(url, headers=headers) soup = BeautifulSoup(r.content, 'html.parser') empty_page = soup.find("div", {"class...
This code continuously monitors product availability for a given search key by polling a URL, comparing newly retrieved products with existing stock data stored in a global dictionary, and notifying Discord of changes. It runs in an infinite loop with a delay, updating the stock state and triggering notifications only ...
def monitor(search_key: str, start: bool): global instock while True: try: # Setup dictionary for instock instock.setdefault(search_key, []) # Returns all new products retrieve_products = get_info(build_url(search_key.upper()), used_arc_headers) ...
def _is_msg_clear(self): # is user in whitelist for _x in list(self.users_whitelist.find()): try: if str(_x['key']).lower() in str(self.message.from_user).lower(): return True except Exception as exc: print(exc) # is us...
This method processes group messages by deleting videos, handling unverified users (checking spam, saving messages, sending CAPTCHA/welcome messages), and forwarding verified messages for further processing. It ensures moderation via message deletion, spam checks, and user verification workflows in group chats.
def check_group_msg(self): if 'group' in self.message.chat.type and \ self.new_message.message is not None and \ not self._is_msg_clear(): # is video in the msg if self._is_video: self.bot.delete_message( chat_id=self.g...
def get_action(message): _is_document = False menu_option = None if message['message'] is not None: menu_option = message['message']['text'] _is_document = message['message']['document'] is not None if 'mp4' in str(message['message']['document']): ...
The code processes incoming messages by extracting user data, message content, and group information, verifying user status, and executing actions based on message text. It handles user verification, retrieves balance details, checks for username changes, and processes commands while logging exceptions.
def processing_messages(self, new_messages): for self.new_message in new_messages: try: time.sleep(0.5) self.message = self.new_message.message \ if self.new_message.message is not None \ else self.new_message.callback_query.mes...
def update_balance(self): """ Update user's balance using transactions history """ print("Handle TXs") response = self.wallet_api.get_txs_list() for _tx in response['result']: try: if _tx['status'] == 1: self.check_hun...
The code initializes a bot with a wallet API, connects to MongoDB to manage multiple collections (e.g., users, captcha, transactions), schedules periodic tasks (balance updates, captcha processing), and processes incoming messages in a loop. It sets up data structures for user tracking, notifications, and pending opera...
def __init__(self, wallet_api): # INIT self.bot = Bot(bot_token) self.wallet_api = wallet_api # Beam Butler Initialization client = MongoClient(connectionString) db = client.get_default_database() self.col_captcha = db['captcha'] self.col_commands_history ...
def minimum_queens(self): """Returns a list of queens that could be moved to the minimum conflict locations. Returns a list of pairs ((i1, j1), (i2, j2)), where the first parameter represents the queen location, and the second parameter represents a location that the queen could...
The function `random_minimal_successor` updates the board by selecting a random minimal move from possible positions that reduce conflicts. It retrieves potential moves using `minimum_queens()`, checks the current conflict count via `conflicts()`, and if conflicts exist, randomly picks a move from the minimal options. ...
def random_minimal_successor(self): """Updates the board with a random minimal successor. """ possible_moves = self.minimum_queens() heuristic = self.conflicts() if heuristic != 0: queen, next_move = random.choice(possible_moves) i1, j1 = queen ...
def adjust_learning_rate(optimizer, epoch, args): """Decay the learning rate based on schedule""" lr = args.lr if args.cos: # cosine lr schedule lr *= 0.5 * (1. + math.cos(math.pi * epoch / args.epochs)) else: # stepwise lr schedule for milestone in args.schedule: lr *= 0.1...
The code trains a deep learning model for age estimation and face verification/identification using distributed computing. It loads a pre-trained age estimation model, initializes optimizers, prepares multi-dataset loaders (FGNET, CACD_VS, CALFW, MORPH2), and performs training with mixed-precision scaling. The model is...
def main_worker(gpu, ngpus_per_node, args): args.gpu = gpu if args.gpu is not None: print("Use GPU: {} for training".format(args.gpu)) if args.distributed: if args.dist_url == "env://" and args.rank == -1: args.rank = int(os.environ["RANK"]) if args.multiprocessing_dist...
def getPrime(n): # this function returns random n-bit prime number p such that (p-1)/2 is also prime p = None while p is None: temp = random.randrange((1<<(n-1))+1, (1<<(n)), 2) if isPrime(temp): p = temp return p def isPrime(n): # low-level primality testing using first N(16...
This code generates a safe prime $ p $ (where $ p-1 $ is twice a prime) and a primitive root $ g $ modulo $ p $, commonly used in cryptographic protocols like Diffie-Hellman. It first finds $ p $ by checking if $ 2 \times \text{prime}(n-1) + 1 $ is prime, then selects $ g $ such that $ g^{(p-1)/2} \mod p \neq 1 $, ensu...
def get_g_p(n): p = None while p is None: temp = getPrime(n-1) if isPrime(2*temp+1): p = 2*temp+1 g = None while g is None: temp = random.randint(2, p-1) if modExpo(temp, (p-1)//2, p) != 1: g = temp return g, p
def getBlankPosition(board): # Return the x and y of board coordinates of the blank space. for x in range(BOARDWIDTH): for y in range(BOARDHEIGHT): if board[x][y] == 0: return (x, y) def drawBoard(board, message): DISPLAYSURF.fill(BGCOLOR) if message: textSurf...
This function animates a tile sliding in the specified direction on a game board by incrementally redrawing the tile's movement over a blank space, creating a smooth visual transition. It calculates the target position based on the direction, prepares a base surface, and updates the display in steps controlled by the a...
def slideAnimation(board, direction, message, animationSpeed): # Note: This function does not check if the move is valid. blankx, blanky = getBlankPosition(board) if direction == DOWN: movex = blankx movey = blanky + 1 elif direction == UP: movex = blankx movey = blanky ...
def makeText(text, color, bgcolor, top, left): # create the Surface and Rect objects for some text. textSurf = BASICFONT.render(text, True, color, bgcolor) textRect = textSurf.get_rect() textRect.topleft = (top, left) return (textSurf, textRect) def to_matrix(l, n): X = [l[i:i+n] for i in range(0, ...
The code implements a sliding puzzle game with a graphical interface using Pygame, allowing users to solve the puzzle via DFS, BFS, or A* algorithms. It initializes the game window, handles user interactions (reset, algorithm selection), and animates the solution steps by moving tiles according to the chosen algorithm'...
def main(): global FPSCLOCK, DISPLAYSURF, BASICFONT, RESET_SURF, RESET_RECT, NEW_SURF, NEW_RECT, NEW2_SURF, NEW2_RECT, SOLVE_SURF, SOLVE_RECT pygame.init() FPSCLOCK = pygame.time.Clock() DISPLAYSURF = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT)) pygame.display.set_caption('Slide Puzzle') ...
def fetch_table_data(table): data = [] for line in table.get_children(): rows = [] for value in table.item(line)['values']: rows.append(value) data.append(rows) return data def delete_whole(table, total_labels): for lines in table.get_children(): table.delete(...
This function deletes a selected row from a table after user confirmation, updates the table data, renumbers remaining rows, and refreshes associated labels. It fetches current data, removes the row, updates indices, reinserts data, and synchronizes UI elements with the modified dataset.
def delete(event, table, total_labels): ans = messagebox.askyesno("Confirmation Dialogue", "Do you want to Delete?") if ans: row = table.focus() table.delete(row) table.update() data = fetch_table_data(table) delete_whole(table, total_labels) for i in range(len(da...
def replace_tree(tree, variable, value): if type(tree) == Input: if tree.a == variable: return value return tree elif type(tree) == Add: left = replace_tree(tree.a, variable, value) right = replace_tree(tree.b, variable, value) return Add(left, right) elif...
The code recursively explores possible variable assignments in a tree structure to find a valid solution path. It starts with initial values (4-9), then iterates through subsequent variables (1-9), optimizing the tree at each step. If a tree configuration leads to failure (no valid option for 0), it avoids reprocessing...
def find_solution(tree, variable=None, value=None, path=[], known_fail=set()): if variable is None: for new_value in range(4, 10): ret = find_solution(tree, 0, new_value, [new_value]) if ret is not None: return [new_value] + ret return None print("\n" + (...
def try_num(s): try: return int(s) except ValueError: return s def combine_instructions(instructions): i = 0 while i < len(instructions): inst = instructions[i] next_inst = None if i+1 >= len(instructions) else instructions[i+1] # Transformations # MulIns...
This code reads input instructions, parses them into operation objects (like AddInst, MulInst), combines these instructions, and then decomposes them into an abstract syntax tree (AST) for output. It processes each line, identifies operations and arguments, constructs instruction objects, and generates a structured AST...
def main(): input_i = 0 instructions = [] for line in sys.stdin: op, args_str = line.strip().split(" ", 1) args = args_str.split(" ") if op == "inp": instructions.append(InpInst(args[0], input_i)) input_i += 1 elif op == "add": instructions...
def check_win(): player1_win = (True, "AI Wins") player2_win = (True, "Player Wins") no_win = (False, "Nobody Yet") board = st.session_state.connect # Horizontal for i in range(NROWS): for j in range(NCOLS-4 + 1): seq = board[i, j:(j+4)] if is_win(seq, 1): ...
This function updates a game board by placing a player's token in the specified column, checks for a win, then places the enemy's token in a chosen column and checks for a win again, managing game progression and end conditions.
def update_board(col): row = NROWS - 1 while st.session_state.connect[row, col]: row -= 1 if row < 0: break st.session_state.connect[row, col] = -1 win_check = check_win() if win_check[0]: end_game(win_check) return enemy_action = enemy_play() ro...
def loadFile(self) : fname = QtGui.QFileDialog.getOpenFileName( self, 'choose the signal', os.getenv('HOME') ,"wav(*.wav)" ) self.path = fname[0] if self.path =="" : return self.flag = True self.fs , self.data = wavfile.read(self.path) self.data =np.array...
The main task of the code is to initialize a GUI window by setting up UI components (graphics views, sliders, buttons) and connecting their events to methods for functionalities like spectrogram display, zooming, scrolling, sound playback, and file operations. It configures sliders to update visualizations, links menu ...
def __init__(self, *args, **kwargs): super(MainWindow, self).__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) self.Input_Updated_Channel = [self.ui.graphicsView,self.ui.graphicsView_2] self.sliders_vector =[self.ui.verticalSlider, self.ui.verticalSlider_2 ,self.ui.vert...