dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def load_config(path): """ Loades the configuration file """ with open(path, 'rb') as handle: return json.loads(handle.read().decode('utf-8')) def load_image(config): """ Loads the original image """ return Image.open(config['original_image']) def sample_colors(config, image): ...
The main task of the code is to process an image using a configuration file. It loads the configuration, reads an image, samples colors, determines optimal base and alpha values, prepares stencils, and composites the stencil with the base image. The workflow involves image analysis, parameter optimization, and layer co...
def main(): """ Main function of the application """ if len(sys.argv) < 2: print(f'Usage: {sys.argv[0]} CONFIG_FILE_PATH') sys.exit(1) config = load_config(sys.argv[1]) image = load_image(config) sample_colors(config, image) best_base, best_alpha = best_base_and_alpha(con...
def _finiteField(self,alpha,M,show=False): flag=True finite=[] i=0 while(flag): out=np.mod(alpha**i,M) if(i>0 and out==1): flag=False if(flag): finite.append(out) i+=1 if(i>16): break if(show): for i in range(len(finite)): print(str(alpha)+"^"+str(i)+"(mod"+str(M)+")="+str(fi...
This code initializes a class for number-theoretic transforms (NTT) over a finite field. It sets up parameters like modulus (mod), primitive root (alpha), finite field structure (_F), field size (_N), modular inverse (_Ninv), and precomputes addition/multiplication tables. It also generates transformation tables (_nttT...
def __init__(self,mod,alpha,show=False): self._M=mod self._alpha=alpha self._F=self._finiteField(alpha,mod,show) self._N=len(self._F) self._Ninv=self._modularInverse(self._N,mod) self._addTable,self._mulTable=self._createCalsTable(mod) self._nttTable,self._inttTable=self._createTransTable(self._F,self._Ni...
def find_character(game_state, color): target = {} for character in game_state["characters"]: if character["color"] == color: target = character break return target def get_score(game_state): score = game_state["position_carlotta"] suspects = [] fantom = find_char...
This function generates a new game solution by capturing character data, appending it to a solution list with depth and score, and conditionally processing it via `do_turn_characters` if depth is 2, otherwise adding it to a tree structure for further analysis.
def new_move(game_state, tree, solutions, color, power_action): depth = len(game_state["active character_cards"]) info = find_character(game_state, color) data = { "color": info["color"], "suspect": info["suspect"], "position": info["position"], "power": info["power"], ...
def find_character_pos(game_state, position): targets = [] for character in game_state["characters"]: if character["position"] == position: targets.append(character) return targets def new_positions(game_state, color, initial_pos, distance): possible_positions = [] if color == "p...
The function `move_character` generates possible new positions for a game character based on the number of characters in its current room, updates the game state for each new position, and triggers further processing via `new_move` to explore solutions in a tree structure, considering movement constraints and power par...
def move_character(game_state, character, tree, solutions, power): color = character["color"] position = character["position"] distance = len(find_character_pos(game_state, position)) # character can move no. X of steps from room with X people inside for pos in new_positions(game_state, color, posit...
def find_character_pos(game_state, position): targets = [] for character in game_state["characters"]: if character["position"] == position: targets.append(character) return targets def new_positions(game_state, color, initial_pos, distance): possible_positions = [] if color == "p...
The function `move_blue` generates all valid moves for a character (Madame Giry) by calculating possible positions based on the number of people in the current room, updating the game state with these moves, and exploring new block configurations. It iterates through potential positions, modifies the game state, and re...
def move_blue(game_state, character, tree, solutions): # Madame Giry can change block color = character["color"] position = character["position"] distance = len(find_character_pos(game_state, position)) # character can move no. X of steps from room with X people inside for pos in new_positions(game...
def find_character_pos(game_state, position): targets = [] for character in game_state["characters"]: if character["position"] == position: targets.append(character) return targets def new_positions(game_state, color, initial_pos, distance): possible_positions = [] if color == "p...
This function generates all possible game states resulting from moving a character (Joseph Buquet) in a shadow room puzzle. It calculates potential new positions, updates the game state for each, and iterates through shadow room configurations, creating new game states by modifying the shadow room position. Each valid ...
def move_grey(game_state, character, tree, solutions): # Joseph Buquet can move shadow room color = character["color"] position = character["position"] distance = len(find_character_pos(game_state, position)) for pos in new_positions(game_state, color, position, distance): t_game_state_2 = cop...
def find_character_pos(game_state, position): targets = [] for character in game_state["characters"]: if character["position"] == position: targets.append(character) return targets def new_positions(game_state, color, initial_pos, distance): possible_positions = [] if color == "p...
This function generates all possible moves for a black character (Christine Daae) in a game by iterating through new positions, applying movement updates with or without power, removing the character, and adding resulting states to a solution tree. It explores movement options, power effects, and state transitions to b...
def move_black(game_state, character, tree, solutions): # Christine Daae can attract others color = character["color"] position = character["position"] distance = len(find_character_pos(game_state, position)) for pos in new_positions(game_state, color, position, distance): for power in range(2)...
def select_character(self, question, data: list, game_state): if (len(data) == 1): self.selected_color = data[0]["color"] return 0 index = next((index for (index, d) in enumerate(data) if d["color"] == "red"), None) self.do_we_separate(game_state) if (index != Non...
The function `analyze_question` determines the appropriate action based on the question type. It randomly selects an index from data, then routes processing to specific methods for "select" (character/position), "activate" (color), or default "ask_for_color_power" logic, returning the computed index for game state upda...
def analyze_question(self, question, data, game_state): arrayQuestionsType = question['question type'].split() index = random.randint(0, len(data)-1) if (arrayQuestionsType[0] == "select"): if (arrayQuestionsType[1] == "character"): index = self.select_character(quest...
def _determine_modulus(states): diffs = [s1 - s0 for s0, s1 in zip(states, states[1:])] zeroes = [t2*t0 - t1*t1 for t0, t1, t2 in zip(diffs, diffs[1:], diffs[2:])] modulus = abs(reduce(gcd, zeroes)) return modulus def _determine_multiplier(states, modulus): multiplier = (states[2] - states[1]) * mod...
The code determines the parameters (modulus $ m $, multiplier $ a $, and increment $ c $) of a Linear Congruential Generator (LCG) pseudorandom number generator. It accepts a list of integer states generated by the LCG, validates the input, and computes each parameter using helper functions. The main task is to reverse...
def determine_lcg_parameters(states): assert type(states) == list and len(states) >= 5 for i in states: assert type(i) == int m = _determine_modulus(states) a = _determine_multiplier(states, m) c = _determine_increment(states, m, a) return (m, a, c)
def gen_keys(n): w = [randint(1, 10)] multiplier = randint(2, 4) for i in range(n-1): w.append(randint(sum(w)+1, multiplier * sum(w))) q = randint(sum(w), multiplier * sum(w)) r = randint(1, q-1) while gcd(q, r) != 1: r = randint(1, q-1) B = [(i * r) % q for i in ...
The code tests an encryption/decryption process by generating keys, encrypting a message, decrypting it, and verifying if the decrypted message matches the original. If they differ, it prints an error and displays the keys.
def test(msg): B, w, q, r = gen_keys(8) ct = encrypt_text(msg, B) print(f'Encrypted msg: {ct}') pt = decrypt_text(ct, w, r, q) print(f'Decrypted msg: {pt}') if pt != msg: print(f'Initial message ({msg}) is not equal to decrypted message ({pt})!') print(f'B: {B}') print(f'...
def Forward(self,row): X = np.array(row).reshape(self.InputLayerSize, 1) Zs = [] for LayerWeights in self.LayersWeight: X = self.GetNeuronOutput(LayerWeights, X) Zs.append(X) return Zs def EncodeProb(self,Probabilties): Label = [] mx = max(Probab...
This function calculates model accuracy by comparing predicted and actual labels, generates a confusion matrix, and visualizes it. It iterates through input data, performs forward passes, encodes predicted classes, updates accuracy count, and increments confusion matrix entries. Finally, it computes accuracy percentage...
def CaclulateAccuracy(self,X,Y): Ans = 0 OutPutClasses = [] CoffMat = np.zeros((self.OutputLayerSize,self.OutputLayerSize)) for indx, row in X.iterrows(): Output = self.Forward(row) OutputLayer = Output[len(Output) - 1] OutputClass = self.EncodeProb(O...
def Forward(self,row): X = np.array(row).reshape(self.InputLayerSize, 1) Zs = [] for LayerWeights in self.LayersWeight: X = self.GetNeuronOutput(LayerWeights, X) Zs.append(X) return Zs def Backward(self,index,Zs): Grident = [] DesiredOutput = s...
The main task of the code is to train a neural network by iterating over epochs, performing forward and backward propagation for each training sample, updating weights based on calculated gradients, and finally evaluating the model's accuracy on the training data.
def Train(self): for i in range(self.Epochs): for indx, row in self.x_train.iterrows(): Zs = self.Forward(row) self.Gridents = self.Backward(indx,Zs) X = np.array(row).reshape((self.InputLayerSize,1)) Zs.insert(0,X) self...
def next_token(): global current_line token = lexer.get_token() current_line = lexer.lineno return token def handle_opc(opc): global last_opc opc_modes = OPC_TABLE.get(opc) if opc_modes == None: error("Unknown Opcode") last_opc = opc if opc_modes[IMP] != -1: write_byt...
This function processes tokens sequentially, handling each by checking if it matches an opcode in OPC_TABLE, or using pattern-based handlers in TOKEN_HANDLERS. If no match is found, it raises a syntax error. The loop continues until the end of input is reached.
def first_pass(): token = next_token() while token != lexer.eof: if OPC_TABLE.get(token.upper()) != None: handle_opc(token.upper()) else: token_handled = False for pattern, handle in TOKEN_HANDLERS: if pattern.match(token): ...
def run_simulation(theta_i, omega_i, driving_force, time_step, total_time): #creating a list to the total time with incriment of the timestep times = np.arange(0., total_time, time_step) #initializing the list of values theta_list = [theta_i] omega_list = [omega_i] #each value in the time array for tim...
The function computes the Poincaré map of a dynamic system by simulating its behavior over time, extracting angles at intervals corresponding to the driving force period, and adjusting these angles to the [-π, π] interval to analyze periodicity and stability.
def poincare_angle(initial_angle, initial_speed, driving_force, time_step, final_time): data = run_simulation(initial_angle, initial_speed, driving_force , time_step , final_time) #Get all the angles idx = get_poincare(data[-1]) #Get the indices of the time after each driving period periodic_angle_list = angle_sh...
def sanitise_start_angle(self, start_angle, narrow_range_sanitise = False): start_angle %= 2 * pi if start_angle < 0: start_angle += 2 * pi involute_start_angle = start_angle - self._base_to_pitch_angle # constrain value to be within +90 degree quadrant if narrow_ran...
The main task of the code is to generate coordinates for a wheel by rotating a single tooth shape around a circle. It initializes empty arrays, calculates evenly spaced angles, creates a base tooth shape, then iteratively rotates and appends its coordinates to form a full wheel with multiple teeth. The function returns...
def create_wheel(self, start_angle = 0): start_angle = self.sanitise_start_angle(start_angle, False) x_coords = empty(0) y_coords = empty(0) start_angles = linspace(start_angle, start_angle + 2*pi, self._number_of_teeth) x_coords_tooth, y_coords_tooth = self.create_single_tooth(s...
def load_popular_wordlist(word_length) -> list: wordlist = os.path.join(cfg.paths.data, cfg.files.popular_word_list) with open(wordlist, 'r') as file: word_dict = load(file) return word_dict[str(word_length)] def load_dictionary_wordset(word_length) -> set: wordset = os.path.join(cfg.paths.data,...
The code implements a Wordle game with customizable parameters. It loads word lists, generates a secret word (or uses a provided one), processes user guesses with validation, tracks attempts, and displays results. It also outputs the command used to start the game, including seed, word length, and max attempts.
def main(word_length: int, max_attempts: int, seed: str, secret_word: str) -> str: popular_word_list = load_popular_wordlist(word_length) dictionary_wordset = load_dictionary_wordset(word_length) seed_int = decode_num(seed) if seed is not None else random.randint(0, cfg.params.seed_max) random.seed(see...
def DenseUNet(nb_dense_block=4, growth_rate=48, reduction=0.0, dropout_rate=0.0, weight_decay=1e-4, weights_path=None): """Instantiate the DenseNet 161 architecture, # Arguments nb_dense_block: number of dense blocks to add to end growth_rate: number of filters to add per dense block...
The main task of the code is to train a DenseUNet model for image segmentation using a custom dataset. It loads data, compiles the model with SGD optimizer, sets up callbacks for saving weights, and trains the model for 6000 epochs using a generator. The model is preloaded with weights and optimized for tasks like tumo...
def train_and_predict(): print('-' * 30) print('Creating and compiling model...') print('-' * 30) model = DenseUNet(reduction=0.5, weights_path='./result_train_dense167_fast/model/weights365.04-0.02.hdf5') sgd = SGD(lr=1e-3, momentum=0.9, nesterov=True) model.compile(optimizer=sgd, loss=[weight...
def get_problem_folder(self, year, day): """ Returns folder path for given problem """ return os.path.join(self.get_year_folder(year), f'problem-{day}') def get_problem_file(self, year, day): return os.path.join(self.get_problem_folder(year, day), 'solution.py') def get_template_file(): ...
This function creates a directory structure for a coding problem based on the given year and day. It checks if the problem folder exists, creating it if necessary, then ensures a problem file exists by copying a template file into the folder if the file is missing.
def create_problem_template(self, year, day): problem_folder = self.get_problem_folder(year, day) if not os.path.exists(problem_folder): os.makedirs(problem_folder) problem_file = self.get_problem_file(year, day) if not os.path.isfile(problem_file): shutil.copy...
def _update_input(self): for i in range(0,self.num_events): if not self.ev_controllable[i]: # Check only the UCEs if self._input_read(i): self.input_buffer.append(i) self.last_events[i] = 1 def _make_transition(self, ev): num_transition...
The main task of the code is to process uncontrollable events by clearing the input buffer, updating inputs, and applying state transitions for each event. It then checks for the next controllable event, executing its transition if available. The function manages event-driven state changes in a system, prioritizing unc...
def run_step(self): self.input_buffer = [] # Clear buffer self._update_input() # Get all uncontrollable events uce = self.input_buffer # Apply all the uncontrollable events while uce: event = uce.pop(0) self._make_transition(event) s...
def _rm_pnp(S: Set[FrozenSet[Proposition]], p_list: List[Proposition]) -> Set[FrozenSet[Proposition]]: """Removes clauses that contain p and its complement from S""" S_prime = set() for clause in S: has = False for p in p_list: if _has_pnp(clause, p): has = True ...
The code implements the DPLL algorithm for propositional logic proof, iteratively eliminating propositions by resolving clauses. It maintains a set of clauses (S), computes parent sets (T) and resolvents (U) for each proposition, then updates S by replacing T with U. If print_steps is True, it logs each transformation ...
def prove(self, print_steps: bool = False) -> None: """Runs DPP""" S = self._clauses T = None U = None elimed = set() if print_steps: step_num = 1 for p in self._props: print("Eliminating ", p.name, ":") DPP._print(S...
def _generate_training_examples_md(self, training_data: "TrainingData") -> Text: """Generates markdown training examples.""" import rasa.nlu.training_data.util as rasa_nlu_training_data_utils training_examples = OrderedDict() # Sort by intent while keeping basic intent order f...
The code's main task is to convert a TrainingData object into a markdown-formatted string by concatenating sections generated from its components: training examples, synonyms, regex patterns, and lookup tables. The method `dumps` aggregates these parts using helper functions and returns the combined markdown text, faci...
def dumps(self, training_data: "TrainingData") -> Text: """Transforms a TrainingData object into a markdown string.""" md = "" md += self._generate_training_examples_md(training_data) md += self._generate_synonyms_md(training_data) md += self._generate_regex_features_md(training...
def parse_training_example(self, example: Text) -> "Message": """Extract entities and synonyms, and convert to plain text.""" from rasa.nlu.training_data import Message entities = self._find_entities_in_training_example(example) plain_text = re.sub( entity_regex, lambda m: m...
This function parses a markdown list item line into appropriate data structures based on the current section type. It uses regex to extract the item, then routes it to intent training examples, synonyms, regex patterns, or lookup tables, appending or adding them to respective lists/dictionaries.
def _parse_item(self, line: Text) -> None: """Parses an md list item line based on the current section type.""" match = re.match(item_regex, line) if match: item = match.group(1) if self.current_section == INTENT: parsed = self.parse_training_example(item)...
def __init__(self) -> None: self.current_title = None self.current_section = None self.training_examples = [] self.entity_synonyms = {} self.regex_features = [] self.lookup_tables = [] self._deprecated_synonym_format_was_used = False def _strip_comments(text: Tex...
(The code parses a markdown string into a `TrainingData` object by processing each line to identify section headers, parse training examples, handle synonyms, and load files. It checks for deprecated synonym formats, issues warnings if detected, and returns a structured `TrainingData` instance containing examples, syno...
def reads(self, s: Text, **kwargs: Any) -> "TrainingData": """Read markdown string and create TrainingData object""" from rasa.nlu.training_data import TrainingData self.__init__() s = self._strip_comments(s) for line in s.splitlines(): line = line.strip() ...
def __multicall_market_data(self, market_index: int): calls = [ self.multicall_instance.create_call( self.config_storage_instance, "marketConfigs", [market_index] ), self.multicall_instance.create_call( self.perp_storage_instance, "markets", [m...
The function retrieves and calculates financial details of a trading position, including PnL, funding fees, and borrowing costs, using market data, TVL, and timestamp information. It returns position size, average entry price, and adjusted fees in normalized units (e30) for a specified account and market.
def get_position_info(self, account: str, sub_account_id: int, market_index: int): market_data = self.__multicall_market_data(market_index) tvl = self.__get_hlp_tvl() position = self.__get_position(account, sub_account_id, market_index) position_reserved_value = position["reserve_value_...
def __check_sub_account_id_param(self, sub_account_id): if sub_account_id not in range(0, 256): raise Exception("Invalid sub account id") def __create_order_batch(self, account: str, sub_account_id: int, orders): (cmds, datas) = self.__prepare_batch_input(orders) return self.limit_tr...
This function creates a market order for a specified sub-account, defining parameters like market index, trade direction (buy/sell), size, and reduce-only status. It converts the size to Wei using tether, sets trigger/acceptable prices, and generates a transaction. The function returns the transaction hash and parsed o...
def create_market_order( self, sub_account_id: int, market_index: int, buy: bool, size: float, reduce_only: bool, tp_token: str = ADDRESS_ZERO, ): """ Post a market order :param sub_account_id: requied :type sub_account_id: int...
def __add_slippage(self, value: float): return decimal.Decimal(value) * (BPS + 25) / BPS def __sub_slippage(self, value: float): return decimal.Decimal(value) * (BPS - 25) / BPS def __create_order_batch(self, account: str, sub_account_id: int, orders): (cmds, datas) = self.__prepare_batch_input(...
The function creates a trigger order by preparing an order dictionary with parameters like market, size, price, and execution details, then submits it via a batch order creation method. It returns the transaction hash and parsed order arguments from the blockchain event logs.
def create_trigger_order( self, sub_account_id: int, market_index: int, buy: bool, size: float, trigger_price: float, trigger_above_threshold: bool, reduce_only: bool, tp_token: str = ADDRESS_ZERO, ): """ Post a trigger order ...
def __add_slippage(self, value: float): return decimal.Decimal(value) * (BPS + 25) / BPS def __sub_slippage(self, value: float): return decimal.Decimal(value) * (BPS - 25) / BPS def __create_order_batch(self, account: str, sub_account_id: int, orders): (cmds, datas) = self.__prepare_batch_input(...
This function updates a trigger order by adjusting parameters like size, trigger price, and slippage, then constructs a transaction to execute the update. It returns the transaction hash and parsed order details from the blockchain event.
def update_trigger_order( self, sub_account_id: int, order_index: int, buy: bool, size: float, trigger_price: float, trigger_above_threshold: bool, reduce_only: bool, tp_token: str = ADDRESS_ZERO, ): """ Update a trigger order ...
def query_jql(self, script, params=None, format='json'): """Query the Mixpanel JQL API https://mixpanel.com/help/reference/jql/api-reference#api/access :param script: String containing a JQL script to run :param params: Optional dict that will be made available to the script as the par...
The function executes a JQL query to retrieve a JSON array of user profiles, then applies a Mixpanel People update operation to those profiles using a customizable `update_value` function. It optionally creates a backup of all profiles before execution and returns the count of profiles modified.
def jql_operation(self, jql_script, people_operation, update_value=lambda x: x['value'], jql_params=None, ignore_alias=False, backup=True, backup_file=None): """Perform a JQL query to return a JSON array of objects that can then be used to dynamically construct People updates v...
def noise_cleaning(x_raw, y_raw): # data filtering goes here return x_raw, y_raw def Remove_hysteresis(x, y): print("to be completed") return x, y def get_fit(x, y): g = [0.6, -14, 80, 5 * (10 ** 10), 1000, -0.5] # intial guess b = ((-3, -np.inf, -np.inf, 0, 0, -3), (3, np.inf, np.inf, np.inf, ...
The main task of the code is to process raw data by cleaning noise, optionally removing hysteresis based on the input flag, and then performing a fitting operation on the cleaned data. It returns the result of this fitting process.
def fit_sweep(x_raw, y_raw, hysteresis): x, y = noise_cleaning(x_raw, y_raw) if (hysteresis): x, y = Remove_hysteresis(x, y) return get_fit(x, y)
def Packet_test(): # test to see if UDIP_packets is loaded #if UDIP_packets == []: if len(UDIP_packets) == 0: Load_data() def find_closest(time, array): # returns index in array that is closest to the given time n = len(array) if (time < UDIP_packets[array[0]].tInitial): return 0...
The function `Plot_sweep` plots probe current versus sweep voltage for three ADC channels (low, mid, high gain) from either dense or full data packets. It loads data, determines the correct packet index based on input parameters, extracts voltage and current data, and generates a figure with three subplots. Optional fi...
def Plot_sweep(time=None, index=None, isDense=False, fit=False, hysteresis=False): Packet_test() # load data only if needed if (time != None) or (index != None): try: if isDense: if index == None: # ind = find_closest(time, ind_medium) ...
def parse_cli_args(): parser = argparse.ArgumentParser( description='A nagios check that can pass/fail based on the size of' \ ' the contents of a directory.', epilog='Warn and crit can be either a single value (trigger if over) ' \ 'or a range in the form value:value and will tr...
The main task of the code is to calculate and display the size of a specified directory. It parses command-line arguments to determine the target directory, computes the total size of that directory's contents, and then outputs the result to the user. The function orchestrates three key steps: argument parsing, directo...
def main(): args = parse_cli_args() dir_size = find_dir_size(args) output_response(args, dir_size)
def load_predictions( dataset_name: str, sample_idx: int, model_name: str ) -> Dict[str, np.ndarray]: """ Load the pre-computed predictions Args: dataset_name: the name of the dataset to consider sample_idx: the sample index inside the dataset to consider model_name: the name o...
(The code evaluates a machine learning model on a dataset using configurable parameters. It initializes a dataset and model via Hydra, creates directories for storing metrics, iterates through samples (with optional limits), loads predictions, computes per-sample metrics, and aggregates results. The task focuses on per...
def run(cfg: omegaconf.DictConfig): seed_everything(0) dataset = EvalDataset(cfg["dataset"]) model = hydra.utils.instantiate(cfg.model) assert model.name, "The model must have a name!" assert dataset.name, "The dataset must have a name!" global_metrics_path = ( PROJECT_ROOT / "evaluat...
def simulationStart(self): # osi_template_source.start(self.start) return True def simulationInit(self): return True def preStep(self, time, nexttime): # global osi_viewer # view = osi_template_source.generateSensorView(time, self.step, nexttime) view = self.generateSenso...
The code runs a simulation by initializing it, iterating from a start time to a stop time in incremental steps, executing pre-step actions at each interval, and finally stopping the simulation. It returns True upon completion.
def runSimulation(self): self.simulationStart() self.simulationInit() time = self.start while (time < self.stop): next_ = time + self.step self.preStep(time, next_) #sleep(step) time = next_ self.simulationStop() return True
def waiting_for_dropoff(self): # time.sleep(2) self.get_logger().info("Waiting for can to drop") while not self.weight_placed: rclpy.spin_once(self) # time.sleep(0.5) self.get_logger().info('Can has been dropped') time.sleep(0.5) def move_back(self, dist_l...
The main task of the code is to navigate the robot back to the docking station after completing drop-off and pickup operations. It ensures proper execution order by checking laser scan data availability, moves backward to avoid obstacles, waits for pickup confirmation, and then moves forward to dock. The function coord...
def table1(self): if self.laser_range.size != 0: #This line to ensure movef_front will run first, before rotatebot as scan message has delay to be received self.waiting_for_dropoff() self.move_back(distance_to_stop) self.waiting_for_pickup() #Return back to docki...
def waiting_for_dropoff(self): # time.sleep(2) self.get_logger().info("Waiting for can to drop") while not self.weight_placed: rclpy.spin_once(self) # time.sleep(0.5) self.get_logger().info('Can has been dropped') time.sleep(0.5) def move_back(self, dist_l...
This function navigates a robot to a table for drop-off/pickup, then returns to a docking station. It checks for laser data, moves back from a bucket, rotates right, aligns with the left wall, waits for pickup, then moves forward, rotates left, and docks. The sequence ensures proper positioning for object handling and ...
def table2(self): if self.laser_range.size != 0: #This line to ensure move_front will run first, before rotatebot as scan message has delay to be received self.waiting_for_dropoff() self.move_back(distance_to_stop) #distance from bucket 1 self.rotatebot(90, right) ...
def waiting_for_dropoff(self): # time.sleep(2) self.get_logger().info("Waiting for can to drop") while not self.weight_placed: rclpy.spin_once(self) # time.sleep(0.5) self.get_logger().info('Can has been dropped') time.sleep(0.5) def move_back(self, dist_l...
The main task of the code is to navigate a robot around a table by moving backward, rotating 90 degrees right, moving backward again, waiting for a drop-off, then returning to a docking station by moving forward, rotating left, and docking, ensuring proper sequence and timing with laser data checks.
def table3(self): if self.laser_range.size != 0: #This line to ensure move_front will run first, before rotatebot as scan message has delay to be received self.waiting_for_dropoff() self.move_back(0.5) self.rotatebot(90, right) self.move_back(1.15) se...
def waiting_for_dropoff(self): # time.sleep(2) self.get_logger().info("Waiting for can to drop") while not self.weight_placed: rclpy.spin_once(self) # time.sleep(0.5) self.get_logger().info('Can has been dropped') time.sleep(0.5) def move_back(self, dist_l...
The code navigates a robot to perform a drop-off and pick-up task, then returns to a docking station. It ensures scan data is received before moving, backs up, rotates 90° right, waits for pickup, then moves forward, rotates left, and docks. Key actions include movement, rotation, and waiting for signals to coordinate ...
def table4(self): if self.laser_range.size != 0: #This line to ensure move_front will run first, before rotatebot as scan message has delay to be received self.waiting_for_dropoff() self.move_back(0.55) self.rotatebot(90, right) self.move_back(0.42) s...
def waiting_for_dropoff(self): # time.sleep(2) self.get_logger().info("Waiting for can to drop") while not self.weight_placed: rclpy.spin_once(self) # time.sleep(0.5) self.get_logger().info('Can has been dropped') time.sleep(0.5) def move_back(self, dist_l...
The main task of the code is to navigate a robot to drop off an item, reposition to pick up another item, and return to a docking station. It involves precise movements (forward/backward, rotations) and waits for drop-off/pick-up events, ensuring the robot aligns correctly using laser scan data before executing maneuve...
def table5(self): if self.laser_range.size != 0: #This line to ensure move_front will run first, before rotatebot as scan message has delay to be received self.waiting_for_dropoff() self.move_back(1.50) self.rotatebot(90, right) self.move_back(0.45) s...
def get_preprocessing(data): """ :param data: json object heaving headlines :return: data frames, and inverted index for further process """ clean_data = [go_clean(i) for i in data] inverted_index = get_inverted_index(list(clean_data)) return clean_data, inverted_index def get_sents_vector(...
The code performs hierarchical clustering on Twitter data to group similar tweets. It processes input articles, extracts tweet content and queries, preprocesses text, generates word vectors using a word2vec model, computes similarity scores, and clusters tweets into groups. It returns clustered data with labels, counts...
def get_twitter_clusters(objects, model, prev_data): ''' Fn to get twitter clusters :param objects: list of articles :param model: word2vec model :param prev_data: prev data list :return: clustered data ''' tweet_objs = [tweet_obj for article in objects for tweet_obj in article['art...
def get_preprocessing(data): """ :param data: json object heaving headlines :return: data frames, and inverted index for further process """ clean_data = [go_clean(i) for i in data] inverted_index = get_inverted_index(list(clean_data)) return clean_data, inverted_index def get_sents_vector(...
The function clusters news articles into groups using hierarchical clustering based on semantic similarity from a word2vec model. It processes article chunks, generates vectors, computes similarity scores, and forms clusters. If prior cluster data exists, it merges new clusters with previous ones; otherwise, it returns...
def get_news_clusters(objects, model, prev_data): ''' Fn to get news clusters :param objects: list of articles :param model: word2vec model :param prev_data: prev data list :return: clustered data ''' chunks = [[get_relevant_chunks(obj['query'], article['content'], article.get('_id', ''...
def day11_part1(): password = list(get_input_as_string(INPUT)) while not check_password_security(password): incremente(password) return "".join(password) def incremente(old_password, place = -1): char_to_incremente = old_password[place] if char_to_incremente == 'z': old_password[plac...
The main task of the code is to generate a secure password by incrementing an initial password from `day11_part1()` until it meets security criteria checked by `check_password_security()`. The password is iteratively incremented using `incremente()` until valid, then returned as a string.
def day11_part2(): password = list(day11_part1()) password = incremente(password) while not check_password_security(password): incremente(password) return "".join(password)
def getTreePoss(forestRange_x, forestRange_y, nTrees, algo="uniform", seed=1234): if algo.lower()=="uniform": np.random.seed(seed) treePoss = np.random.uniform(size=[nTrees,2]) else: raise NotImplementedError assert treePoss.shape[0]==nTrees treePoss[:, 0] *= (forestRange_x[1] ...
The main task of the code is to simulate a forest impulse response (IR) by modeling sound propagation through a forest environment. It computes direct and reflected paths (including floor reflections and first-order tree scattering), applies cylindrical scattering filters, air absorption, and source directivity. The ge...
def simulateForestIR( nTrees, posSrc, micPoss, fs, sigLen_in_samples=None, forestRange_x=None, forestRange_y=None, reflectionCoef=2.0, treeRadiationExponent=0.7, applyCylindricalScatteringFilter=1, applyAirAbsorption=1, maxDist=20000.0, maxReflOrder=1, seed=1234, floorReflectionCoef=0.8, ntaps_t...
def build_rect (pt1, pt2, width): # arctan2 (y, x) line_angle = np.arctan2(pt2.y - pt1.y, pt2.x - pt1.x) angle1 = line_angle + np.pi/2 angle2 = line_angle - np.pi/2 rect_pt1 = Point_2D(pt1.x + width/2.0*np.cos(angle1), pt1.y + width/2.0*np.sin(angle1)) rect_pt2 = Point_2D(pt1.x + width/2.0*np.co...
The function extracts connected skeleton chains from a binary mask by smoothing the mask, performing skeletonization, extracting contours, pruning overlapping segments, and merging remaining chains into a continuous path using optimization techniques. It returns ordered chains representing the structured skeleton of th...
def extract_connected_skeleton (visualize_process, mask, img_scale=10, seg_length=3, max_curvature=30): # note: mask is one channel # smooth image im = Image.fromarray(mask) smoothed_im = im.filter(ImageFilter.ModeFilter(size=15)) mask = np.array(smoothed_im) # resize if necessary for better skel...
def register(pts, M, mu=0, max_iter=10): # initial guess X = pts.copy() Y = np.vstack((np.arange(0, 0.1, (0.1/M)), np.zeros(M), np.zeros(M))).T if len(pts[0]) == 2: Y = np.vstack((np.arange(0, 0.1, (0.1/M)), np.zeros(M))).T s = 1 N = len(pts) D = len(pts[0]) def get_estimates (...
The code processes RGB and depth images to detect and track blue-colored objects (e.g., ropes) using point cloud registration. It initializes object models from the first frame by segmenting contours and fitting splines, then continuously tracks them using CPD-LLE alignment. The tracked nodes are projected onto the RGB...
def callback (rgb, depth, pc): global saved global initialized global init_nodes global nodes global cur_time global sigma2 global num_of_dlos proj_matrix = np.array([[918.359130859375, 0.0, 645.8908081054688, 0.0], \ [ 0.0, 916.26586...
def Convex_hull(a, n): a = sort(a, n) p1 = a[0] p2 = a[n - 1] up = [] down = [] su = 1 sd = 1 up.append(p1) down.append(p1) for i in range(1, n): if (i == n - 1 or cw(p1, a[i], p2)): while (su >= 2 and cw(up[su - 2], up[su - 1], a[i]) == 0): up...
The code computes a polygonal path by finding points along lines parallel to the convex hull's diameter, spaced by distance `d`. It first constructs the convex hull of input points, identifies the diameter endpoints, and generates lines offset by `d` in both directions. For each offset line, it appends intersection poi...
def solve(a, n, d): a, n = Convex_hull(a, n) pt1, pt2 = findmax(a, n) aa, b, c = makeline(pt1, pt2) k = math.sqrt(aa * aa + b * b) * d; fl = 1 j = 0 ans = [] ans.append(pt1) ans.append(pt2) sa = 2 while (fl == 1): j = j - 1 ass, sz1 = check(a, n, aa, b, c + ...
def Convex_hull(self, a, n): a = self.sort(a, n) p1 = a[0] p2 = a[n - 1] up = [] down = [] su = 1 sd = 1 up.append(p1) down.append(p1) for i in range(1, n): if (i == n - 1 or self.cw(p1, a[i], p2)): while (su >= ...
The code constructs a polygonal path by extending from a convex hull's edge. It first identifies two extreme points (pt1, pt2) and defines a line. Using this line, it iteratively adds points along both directions (negative and positive offsets) by checking intersections and ordering them based on vector angles (cosine ...
def solve(self): a, n = self.Convex_hull(self.mas, self.nn) d = self.dd pt1, pt2 = self.findmax(a, n) aa, b, c = self.makeline(pt1, pt2) k = math.sqrt(aa * aa + b * b) * d; fl = 1 j = 0 ans = [] ans.append(pt1) ans.append(pt2) sa ...
def get_local_time_zone(request): local_time_zone = None for key, value in request.headers.items(): if key == "Tz" and value: local_time_zone = pytz.timezone(value) return local_time_zone def date_range(start_date, end_date, user_id, device_serial_no, date_values, time_zone, environment=...
This function processes POST requests to retrieve session data based on user input parameters like dates, device serial number, and environment. It filters sessions using these criteria, defaults to the user's latest session if no dates are provided, and returns structured session data in date_values.
def session_list(request): if request.method == 'POST': # try: date_values = [] user_id = get_member_id(request) device_serial_no = request.data.get('device_serial_no', None) start_date = request.data.get('start_date', None) end_date = request.data.get('end_date', Non...
def get_local_time_zone(request): local_time_zone = None for key, value in request.headers.items(): if key == "Tz" and value: local_time_zone = pytz.timezone(value) return local_time_zone def date_range(start_date, end_date, user_id, device_serial_no, date_values, time_zone, environment=...
The function retrieves session history data for graph visualization based on user input parameters like device ID, date ranges, and environment. It handles cases with or without specified dates, defaults to a 7-day range if no dates are provided, and formats the data into a structured response for graph rendering.
def get_session_detail_history_for_graph(request): if request.method == 'POST': try: date_values = [] user_id = get_member_id(request) device_serial_no = request.data.get('device_serial_no', None) start_date = request.data.get('start_date', None) e...
def chaikin_money_flow(dataframe, n=20, fillna=False) -> Series: """Chaikin Money Flow (CMF) It measures the amount of Money Flow Volume over a specific period. http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:chaikin_money_flow_cmf Args: dataframe(pandas.Dataframe): d...
This function enriches a DataFrame with multiple technical analysis (TA) indicators like RSI, MACD, EMA, Bollinger Bands, and divergence metrics for trading strategies. It emphasizes performance efficiency by advising users to limit indicator usage. The DataFrame is populated with momentum, volatility, and trend indica...
def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: """ Adds several different TA indicators to the given DataFrame Performance Note: For the best performance be frugal on the number of indicators you are using. Let uncomment only the indicator you are usin...
def H(X): ''' calculate mutual entropy from observation of ramdom variable ''' return calculate_ent_from_observation(X) def H2(X, Y): ''' calculat Joint entropy of two ramdom variables ''' return calculate_ent_from_observation(list(zip(X, Y))) def H3(X, Y, Z): ''' calculat Jo...
This function calculates the mutual information among three random variables X, Y, and Z using their individual entropies H(X), H(Y), H(Z), pairwise joint entropies H2(X,Y), H2(Y,Z), H2(X,Z), and the triple joint entropy H3(X,Y,Z). It combines these terms to quantify the shared information among all three variables acc...
def calculate_mi_of_ramdom_variables(X, Y, Z): return H(X) + H(Y) + H(Z) - H2(X, Y) - H2(Y, Z) - H2(X, Z) + H3(X, Y, Z)
def cal_mi(data, clu, k): """ Calculate the distance between centroids and sample points. :param data: Set of sample points :param clu: Set of centroids :param k: Number of classes :return: Distance matrix between centroids and sample points """ dis = [] for i in range(len(data)): ...
The function `classfy_mi` iteratively updates centroids in a clustering algorithm. It calculates new centroids (`clunew`) from input data and cluster assignments (`clusterRes`), computes the error (`err`) between new and old centroids, and returns the error, updated centroids, number of classes (`k`), and cluster resul...
def classfy_mi(data, clu, k): """ Update centroids iteratively. :param data: Set of sample points :param clu: Set of centroids :param k: Number of classes :return: Error and new centroids """ clulist = cal_mi(data, clu, k) clusterRes = divide(data, clulist) clunew = center(data, ...
def climb(self, heading): print("Climb") while self.flight.speed < 100: self.set_pitch_heading(90, heading) self.vessel_control.autostage() self.vessel_control.adjust_throttle_twr(1.7) def pitch_maneuver(self, heading): print("Pitch Maneuver") for x in...
The code performs a series of orbital ascent maneuvers to reach a specified target orbit altitude. It executes climb, pitch, and multiple injection phases, then checks if the achieved apoapsis altitude meets 95% of the target. If successful, it returns True; otherwise, it finalizes the process and returns False.
def ascend(self, target_orbit_alt, heading): print(" Ascending To:") print(" Heading = " + str(heading)) print(" Target Orbit Altitude = " + str(target_orbit_alt) + "m") self.climb(heading) self.pitch_maneuver(heading) self.initial_injection(heading) self...
def set_pitch_heading(self, pitch, heading): self.engage_autopilot_if_not_engaged() self.vessel.auto_pilot.target_pitch_and_heading(pitch, heading) def autostage(self): self.activate_or_decouple_engines_and_fairings() self.decouple_fuel_tanks() def adjust_throttle_twr(self, twr): ...
This code simulates a spacecraft's ascent phase. It initializes liftoff with the vehicle's name, then enters a loop to maintain a vertical pitch (90 degrees) and specified heading until reaching 100 units of speed. During ascent, it automatically stages propulsion systems and adjusts throttle/thrust-to-weight ratio (TW...
def ascent(self): heading = self.params['heading'] print(f"---------------- Liftoff of the {self.params['name']} ----------------") while self.flight.speed < 100: self.set_pitch_heading(90, heading) self.autostage() self.adjust_throttle_twr(1.7)
def activate_current_stage_engines(self): # loop through all parts in current stage for part in self.get_current_stage_parts(): # if part is engine and engine can activate or restart if part.engine is not None and part.engine.can_restart: # activate the engine ...
This method activates both the current and next stage engines of a rocket and jettisons the protective fairing, typically part of a multi-stage rocket's ascent sequence to transition between propulsion phases and reduce mass for efficient flight.
def activate_or_decouple_engines_and_fairings(self): self.activate_current_stage_engines() self.activate_next_stage_engines() self.jettison_fairing()
def comms_state(self): self._log.debug('Comms State') # If swarm, all agents communicate if not self._swarm: self._log.debug('Collaboration not enabled') return # Each agent pings for agent in self._agents: agent.ping(self._ag...
The code advances the simulation by one turn. It logs the current turn, updates agent states through communication, decision-making, and action phases, updates results, and increments the turn counter.
def turn(self): """ Method to step the simulation forward one turn return: None """ # Log the turn self._log.info(f'Turn: {self._turns}') # Update the agents self.comms_state() self.decide_state() self.action_state() # Update result...
def compute_loss(self, sparse_mat, low_rank_mat, features, labels): """ Compute the MSE loss for the linear regression task. :param sparse_mat: The sparse matrix. :param low_rank_mat: The low rank matrix. :param features: The features. :param labels: The labels. :...
The main task of the code is to optimize a low-rank and sparse matrix using projected gradient descent (PGD) under L1 and nuclear norm constraints. It iteratively updates the matrices with gradient steps, projects them back into feasible regions defined by the radii, computes validation losses, and returns the optimiza...
def projected_gradient_descent(self, step_size, radius_sparse, radius_low_rank, n_iter, low_rank_mat, sparse_mat, features_train, labels_train, features_val, labels_val): """ Optimize using projected gradient descent. :param step_size: The gamma of gradient des...
def get_file_list(path: str, search_term: str): """ Returns a list of files that matches search term within the directory provided. Args: path (str): directory in which to search search_term (str): search term Returns: files (list of str): list of files ...
The main task of the code is to load images and their corresponding density maps from a directory, split them into sub-images of a specified resolution, filter out sub-images without eggs to optimize training, normalize the data, and return the processed sub-images, their density maps (or egg counts in end-to-end mode)...
def process_load_data_dir(e2e: bool = False, directory: str = './egg_photos/originals', resolution: str = "256"): """ Given directory, loads images (X) and their corresponding density maps (Y), splits them into sub-images of defined resolution, filters out sub-images with no eggs in them to speed up tra...
def vec_by_selection(train_, test_, min_d_, max_f_, selection): if selection == TFIDF: return vectorize.create_vec_tfidf(train_, test_, min_d_, max_f_) def classify_by_selection(train_v, test_v, train_l, n, met, k_clstrs, selection, r=0.2): if selection == KNClassifier: predicted_, k_nbrs = try_...
The code performs stratified cross-validation on a dataset, splitting it into training and test sets while preserving class distribution. It applies feature selection (vec_by_selection) and classification (classify_by_selection) using parameters like max_, met_, c_, and s_. Accuracy is calculated for each fold, aggrega...
def stratified_test(max_, met_, c_, s_, file): res = [[], []] features, labels = df_utils.get_features_and_labels(df) skf = StratifiedKFold(n_splits=2, shuffle=True) for train_index, test_index in skf.split(features, labels): train_, test_ = features[train_index], features[test_index] tr...
def split_path(self, path, **kwargs): """Normalise OCI path string into bucket and key. Parameters ---------- path : string Input path, like `oci://mybucket@mynamespace/path/to/file` Examples -------- >>> split_path("oci://mybucket@mynamespace/path/to/...
This function retrieves and formats directory listings from an OCI bucket. It constructs the full path, queries OCI's list_objects API with specified parameters, processes results to distinguish files/directories, caches the formatted data, and returns it. The function handles caching, error translation, and metadata f...
def _lsdir(self, path: str, refresh: bool = False, **kwargs): bucket, namespace, key = self.split_path(path) path = _build_full_path(bucket=bucket, namespace=namespace, key=key, **kwargs) full_bucket_name = _build_full_path(bucket=bucket, namespace=namespace) prefix = key + "/" if key el...
def split_path(self, path, **kwargs): """Normalise OCI path string into bucket and key. Parameters ---------- path : string Input path, like `oci://mybucket@mynamespace/path/to/file` Examples -------- >>> split_path("oci://mybucket@mynamespace/path/to/...
This method lists files in a specified bucket or directories, using cached data by default unless `refresh=True`. It splits the input path into bucket/namespace components and delegates to `_lsbuckets` for bucket listings or `_lsdir` for directory listings, enabling efficient file/directory navigation with optional cac...
def _ls(self, path: str, refresh: bool = False, **kwargs): """List files in given bucket, or list of buckets. Listing is cached unless `refresh=True`. Parameters ---------- path : string/bytes location at which to list files refresh : bool (=False) ...
def split_path(self, path, **kwargs): """Normalise OCI path string into bucket and key. Parameters ---------- path : string Input path, like `oci://mybucket@mynamespace/path/to/file` Examples -------- >>> split_path("oci://mybucket@mynamespace/path/to/...
The main task of the code is to create an empty file or truncate an existing file in Oracle Cloud Infrastructure (OCI) storage. If `truncate` is True, it deletes the existing file and replaces it with an empty one. If `data` is provided, it writes that content to the file. The function validates inputs, checks for unsu...
def touch(self, path: str, truncate: bool = True, data=None, **kwargs): """Create empty file or truncate Parameters ---------- path : string/bytes location at which to list files truncate : bool (=True) if True, delete the existing file, replace with empt...
def split_path(self, path, **kwargs): """Normalise OCI path string into bucket and key. Parameters ---------- path : string Input path, like `oci://mybucket@mynamespace/path/to/file` Examples -------- >>> split_path("oci://mybucket@mynamespace/path/to/...
The function `copy_basic` copies a file between Oracle Cloud Infrastructure (OCI) storage locations using the OCI SDK. It takes source (`path1`) and destination (`path2`) URIs, along with optional parameters like `destination_region` and encryption keys. It splits paths into components, constructs destination details, ...
def copy_basic(self, path1, path2, destination_region=None, **kwargs): """Copy file between locations on OCI Not allowed where the origin is >50GB Parameters ---------- path1 : str URI of source data path2 : str URI of destination data de...
def split_path(self, path, **kwargs): """Normalise OCI path string into bucket and key. Parameters ---------- path : string Input path, like `oci://mybucket@mynamespace/path/to/file` Examples -------- >>> split_path("oci://mybucket@mynamespace/path/to/...
This code retrieves metadata for a file, directory, bucket, or namespace from Oracle Cloud Infrastructure (OCI) based on the provided path. It uses OCI API calls like `head_object`, `list_objects`, and `head_bucket` to fetch details such as size, type, modification time, and storage tier. The function handles 404 error...
def info(self, path, **kwargs): """Get metadata about a file from a head or list call. Parameters ---------- path : str URI of the directory/file kwargs : dict additional args for OCI """ bucket, namespace, key = self.split_path(path) ...
def _strip_protocol(cls, path): if isinstance(path, list): return [cls._strip_protocol(p) for p in path] path = stringify_path(path) stripped_path = super()._strip_protocol(path) if stripped_path == cls.root_marker and "@" in path: return "@" + path.rstrip("/").sp...
This method creates a bucket or directory in Oracle Cloud Infrastructure (OCI), handling nested directory creation if `create_parents` is True. It uses the provided `compartment_id` or defaults to the auth compartment. If the bucket doesn't exist, it creates it via OCI's API, logs details, and invalidates caches. It ca...
def mkdir( self, path: str, create_parents: bool = True, compartment_id: str = None, **kwargs, ): """Make a new bucket or folder Parameters ---------- path : str URI of the directory create_parents : bool (=True) ...
def split_path(self, path, **kwargs): """Normalise OCI path string into bucket and key. Parameters ---------- path : string Input path, like `oci://mybucket@mynamespace/path/to/file` Examples -------- >>> split_path("oci://mybucket@mynamespace/path/to/...
This method deletes multiple keys in a single bucket using OCI, validating they belong to the same bucket and namespace. It invalidates the cache for each key's parent path, then attempts deletion via OCI's delete_object API, translating and re-raising any service errors encountered during the process.
def bulk_delete(self, pathlist, **kwargs): """ Remove multiple keys with one call Parameters ---------- pathlist : listof strings The keys to remove, must all be in the same bucket. """ if not pathlist: return bucket_namespace = {se...
def split_path(self, path, **kwargs): """Normalise OCI path string into bucket and key. Parameters ---------- path : string Input path, like `oci://mybucket@mynamespace/path/to/file` Examples -------- >>> split_path("oci://mybucket@mynamespace/path/to/...
The `ls` method lists files in a specified directory, returning filenames or detailed metadata based on the `detail` parameter. It handles empty results by checking the parent directory, filters non-directory items, and uses caching unless `refresh` is True. The path is parsed into bucket, namespace, and key components...
def ls(self, path: str, detail: bool = False, refresh: bool = False, **kwargs): """List single "directory" with or without details Parameters ---------- path : string/bytes location at which to list files detail : bool (=False) if True, each list item is ...
def _strip_protocol(cls, path): if isinstance(path, list): return [cls._strip_protocol(p) for p in path] path = stringify_path(path) stripped_path = super()._strip_protocol(path) if stripped_path == cls.root_marker and "@" in path: return "@" + path.rstrip("/").sp...
This method copies files between locations on Oracle Cloud Infrastructure (OCI) by invoking a basic copy operation. It checks the source file's size, and if it exceeds 50 GB, it raises a NotImplementedError. The function handles URIs for source and destination paths, with optional region specification for the destinati...
def copy(self, path1, path2, destination_region=None, **kwargs): """Copy file between locations on OCI Parameters ---------- path1 : str URI of source data path2 : str URI of destination data destination_region : str the region you wan...
def split_path(self, path, **kwargs): """Normalise OCI path string into bucket and key. Parameters ---------- path : string Input path, like `oci://mybucket@mynamespace/path/to/file` Examples -------- >>> split_path("oci://mybucket@mynamespace/path/to/...
The code removes an empty directory by checking if it's empty using `ls(path)`, then deleting the corresponding bucket via OCI if empty. It handles errors, invalidates cache entries for the path and namespace, and ensures the directory is empty before deletion.
def rmdir(self, path, **kwargs): bucket, namespace, key = self.split_path(path) key = key.rstrip("/") path = _build_full_path(bucket=bucket, namespace=namespace, key=key, **kwargs) if self.ls(path): raise OSError("Directory is not empty") if not key: try: ...
def exists(file): if not os.path.exists(file): # print("'{}' does not exist.".format(file)) print("No existing file: ", file) return False return True def generate_diff_result(old_class_profile, new_class_profile): diff_result = [] for name in old_class_profile['class_method']: ...
The code compares classes between two APKs by reading class pairs from a file, checking if corresponding .smali files exist in specified directories, and generating diffs for pairs with similarity exceeding a threshold. It counts existing and total class files, printing results for qualifying pairs.
def class_compare(): os_path1 = temp1 os_path2 = temp2 class_pair_file_name = "./class_pair/classPairOutput_{}.txt".format(apk_name) file = open(class_pair_file_name) lines = file.readlines() file.close() existing_file_count = 0 total_class_count = 0 for line in lines: total...
def exists(file): if not os.path.exists(file): # print("'{}' does not exist.".format(file)) print("No existing file: ", file) return False return True def folder_exists(path, clean=False): if clean and os.path.exists(path): shutil.rmtree(path) os.makedirs(path) def get_ap...
The main task of the code is to decompile two APK files using apktool, organize their extracted contents into temporary directories, and prepare them for comparison. It parses command-line arguments for input APKs, output paths, and options like cleanup or using Meld for visual comparison. The code ensures directories ...
def apk_parse(): global temp1, temp2, apk_name print("") print("\t\t\t apktool") print("") parser = argparse.ArgumentParser(description='Diff two versions of an APK file.') parser.add_argument('apk1', metavar='apk1', help='Location of the first APK.') parser.add_argument('apk2', metavar='ap...
def exists(file): if not os.path.exists(file): # print("'{}' does not exist.".format(file)) print("No existing file: ", file) return False return True def reader(file): f = open(file, 'r', encoding='utf8', errors='ignore') data = f.read() f.close() return data def prepro...
This code compares classes between two APKs by reading pairs from a file, checking if corresponding .smali files exist in specified paths, and generating diffs if similarity exceeds a threshold. It counts valid file pairs and outputs comparison results, filtering differences for analysis.
def class_compare(): os_path1 = temp1 os_path2 = temp2 # fileName = "classPairOutput_" + apkName + ".txt" fileName = "classPairOutput_{}.txt".format(apk_name) # fileName = "classPairOutput_{}.txt".format('hope') file = open(fileName) lines = file.readlines() left_class = "" right_cl...
def exists(file): if not os.path.exists(file): # print("'{}' does not exist.".format(file)) print("No existing file: ", file) return False return True def folderExists(path, clean=False): if clean and os.path.exists(path): shutil.rmtree(path) os.makedirs(path) def get_apk...
This code parses command-line arguments to compare two APK files by decompiling them into smali code using apktool, organizing extracted files into temporary directories, and preparing them for difference analysis. It handles input validation, directory setup, and provides options for cleanup, visual comparison via mel...
def apk_parse(): global temp1, temp2, apk_name print("") print("\t\t\t apktool") print("") parser = argparse.ArgumentParser(description='Diff two versions of an APK file.') parser.add_argument('apk1', metavar='apk1', help='Location of the first APK.') parser.add_argument('apk2', metavar='ap...
def exists(file): if not os.path.isfile(file): print(format("'{}' does not exist.".format(file), bcolors.FAIL)) exit(0) def folderExists(path, clean=False): if clean and os.path.exists(path): shutil.rmtree(path) os.makedirs(path) def getPackageName(filepath): a = apk.APK(filepath...
The main task of the code is to compare two APK files by decompiling them into smali code, analyzing differences in their structure and content, and optionally outputting results, cleaning up temporary files, or using a visual diff tool (meld). It parses command-line arguments for APK paths, output location, and flags ...
def main(): print("") print("\t\t\t apktool") print("") parser = argparse.ArgumentParser(description='Diff two versions of an APK file.') parser.add_argument('apk1', metavar='apk1', help='Location of the first APK.') parser.add_argument('apk2', metavar='apk2', help='Location of the second APK.'...
def get_conn_string(db_name: Optional[str] = None) -> str: # everything but dbname should be the same, since we are using the admin user for everything host = os.getenv("HOST", "localhost") port = os.getenv("PORT", "5432") user = os.getenv("USERNAME", "postgres") password = os.getenv("PASSWORD", "po...
This function initializes database structures by creating databases, roles, and users based on input parameters. It uses SQLAlchemy to connect to a database, creates a database if specified, generates roles for each component, constructs usernames for partners, creates users, and assigns roles. The process ensures prop...
def pre_table_initialization( stage: Stage, components: list[Component], partner_names: list[Partner], create_dbs: bool = True ) -> None: engine = create_engine(get_conn_string()) with engine.connect() as conn: if create_dbs: create_database(conn, db_name=stage) for component in...
def _filter_empty_spots(self,table): full_list = [] for i in table: if i!=[]: full_list.append(i) return full_list def _make_hash_table(self,new_size): return [[] for i in range(new_size)] def _resizinghash(self,key,val,table,iterations_table,iterations): ...
The main task of the code is to resize a hash table by creating a new table of specified size, rehashing existing key-value pairs into the new structure, and updating internal state variables. It filters out empty spots from the original table, constructs new hash tables, iterates through remaining items, and transfers...
def _resize(self,new_size,table): items = self._filter_empty_spots(table) new_hash_table = self._make_hash_table(new_size) new_iterations = self._make_hash_table(new_size) for i,content in enumerate(items): keys = content[0][0] vals = content[0][1] sel...
def hash_key(self,key): return hash(key)%self.size def _resize(self,new_size,table): items = self._filter_empty_spots(table) new_hash_table = self._make_hash_table(new_size) new_iterations = self._make_hash_table(new_size) for i,content in enumerate(items): keys = con...
This function inserts or updates a key-value pair in a hash table. It checks if the key exists in the target bucket; if found, it updates the value. If not, it resizes the table if the load factor exceeds 0.67, then either rehashes the entry or appends it to the bucket, updating iteration counts and the element count.
def set_val(self,key,val): hash_key = self.hash_key(key) bucket = self.table[hash_key] iters = self.iterations[hash_key] iterations = 0 load_factor = self.n/self.size found_key = False for idx,content in enumerate(bucket): record_key,record_val = conte...
def fileTest(file, image = False): if isinstance(file, list): return [fileTest(f, image = image) for f in file] if file == 'exit': exit() try: if image: Image.open(file) else: open(file, 'r') except: writeToLog("Could not find file " + file...
The main task of the code is to validate a list of image file paths. It checks if any file in the list is invalid using `fileTest()`. If invalid files are found, it prompts the user to correct each invalid path through input, using `inferPath()` to update the list. The loop continues until all files are valid or the us...
def confirmImages(images): if False in fileTest(images): for i in range(len(images)): while not fileTest(images[i], image = True): print("Image file \"" + images[i] + "\" could not be opened, please speficy a correct image file.") images[i] = inferPath(input()) ...
def confirmImages(images): if False in fileTest(images): for i in range(len(images)): while not fileTest(images[i], image = True): print("Image file \"" + images[i] + "\" could not be opened, please speficy a correct image file.") images[i] = inferPath(input()) ...
The function prompts the user to specify image paths, processes them using `inferPath` and `confirmImages`, checks if the input signals an exit, and returns the confirmed image paths or exits if instructed.
def promptImages(): print("Please specify the images to be processed.") ans = confirmImages(inferPath(input().split(" "))) if ans == [inferPath('exit')]: exit() return ans
def split_data(x, y): n = y.shape[1] batch_split = np.random.permutation(n) split_pt = (80 * n) // 100 training_split = batch_split[0:split_pt] validation_split = batch_split[split_pt:] training_x = x[:, training_split] training_y = y[:, training_split] valid_x = x[:, validation_split] ...
The function performs a grid search over specified hyperparameters (layers, hidden units, batch size, learning rate, epochs, regularization) to find the combination yielding the highest test accuracy. It iterates through all hyperparameter combinations, trains a model for each, evaluates on the test set, and tracks the...
def findbesthyperparameters(X_tr, ytr, X_te, yte): # trajectory_dict = {} ############ Best Hyper Parameters ############## n_layer_list = [3] n_hidden_list = [75] batch_size_list = [16] learning_rate_list = [0.1] epochs_list = [40] reg_list = [0] ############# Used Hyper Parameter L...
def clear_board(self): """ Clears the board variable that keeps track of each cell state """ self.board = np.zeros((self.board_y_size, self.board_x_size)) def is_valid_board(self): """ Checks that the board is valid as is :return boolean: True if the board is valid, False otherwi...
The main task of the code is to generate a solvable binairo board by randomly placing initial values, validating the board, and ensuring a solution exists. It iteratively creates boards until one is solvable, then adjusts the number of starting positions to match the desired difficulty. The function returns the positio...
def create_solvable_board(self): """ Finds the positions and states to fill in to create a solvable binairo board :return positions: A list of positions to be filled in to create a solvable board """ # Initialize conditions and counters can_be_solved = False counter = 0 ...
def parse_config(buf): global ind0, ind1, stack, menu_id is_choice = buf[0].strip() == 'choice' is_menu = buf[0].startswith('menu') or is_choice is_nonconfig_menu = buf[0].startswith('menu ') or is_choice key = None if is_nonconfig_menu else buf[0].split()[1].strip() title = buf[0][len('menu '):...
This code parses a Kconfig file, recursively handling included files, nested menu/choice blocks, and conditional logic. It collects config blocks, processes 'if/endif' conditions, and returns a list of parsed configuration items.
def load_kconfig(file): global ind0, ind1, stack, path, menu_id, if_stack r = [] config_buf = [] with open(path + file) as f: for line in f: if config_buf: if not (line.startswith('\t') or line.startswith(' ')): r += [parse_config(config_buf)] ...
def loadFiles(): path = "searchAlgorithm/" with open(path+"word_dict.dict", "rb") as f: wordDict = pickle.load(f) #get dimension dimension = 0 for i in wordDict.items(): if i[1] > dimension: dimension = i[1] f.close() print("word dict load...
The main task of the code is to search for a valid pathway connecting a drug to an adverse drug reaction (ADR) using iterative deepening depth-first search (IDDFS) within a limited depth (7). It loads biological data, filters valid paths, and saves results as JSON if found. If no valid path exists, it returns -1.
def webAppSearch(drug, adr, path): limitedDepth = 7 matrix, wordDict, wordDictInv, gotermDict, dimension = loadFiles() searchProblem = FindDrugToAdr(drug, adr, matrix, wordDict, wordDictInv, dimension) nodeList = IDDFS(searchProblem, limitedDepth) filteredList = [] for n in nodeList: if ...
def load_image(self, index): image = cv2.imread(self.filenames[index]) h, w = image.shape[:2] r = self.input_size / max(h, w) if r != 1: resample = cv2.INTER_LINEAR if (self.augment or r > 1) else cv2.INTER_AREA image = cv2.resize(image, dsize=(int(w * r), int(h * r)), interpolation=resa...
This function generates a mosaic image by combining four randomly selected images into a 2x2 grid. It adjusts the positions and scales of the input images, transforms their corresponding labels, and applies random perspective augmentation. The result is a single augmented image and its associated labels, used for train...
def load_mosaic(self, index): label4 = [] image4 = numpy.full((self.input_size * 2, self.input_size * 2, 3), 0, dtype=numpy.uint8) y1a, y2a, x1a, x2a, y1b, y2b, x1b, x2b = (None, None, None, None, None, None, None, None) xc = int(random.uniform(self.input_size // 2, 2 * self.input_size - self.input_siz...
def nested_data(self, attribute): with open('computer_info.json', 'r') as read: data = json.load(read) info = data[attribute] if(attribute == 'Open Ports'): self.display_open_ports(info) elif(attribute == 'Updates'): self.display_updates(info) ...
This code initializes a GUI interface for displaying system scan information, organizing data into labeled sections with interactive buttons. It sets up frames for headers, attribute details, and nested data display, including buttons to show descriptions and retrieve specific system data like firewall status, IP addre...
def __init__(self, parent, controller): Frame.__init__(self, parent) self.controller = controller self.header = StringVar() self.header.set('Attribute') self.information = StringVar() self.information.set('Information about the attribute will be displayed here') ...
def delta_sq(mu, mu_j, sigma_j_sq, n_j): """Calculates the quantity delta squared as given in the Glicko paper.""" e_term = E(mu, mu_j, sigma_j_sq) to_sum = n_j * g(sigma_j_sq) ** 2 * e_term * (1 - e_term) return (q ** 2 * np.sum(to_sum)) ** (-1) def g(sigma_sq): """Calculates the quantity g as g...
This function updates a player's rating parameters by incorporating contest outcomes against multiple opponents. It calculates a new mean and variance using prior beliefs (mu, sigma_sq) and opponent data (mu_j, sigma_j_sq, n_j, s_jk). Key steps include computing discrepancies, summing weighted outcome differences, and ...
def calculate_new_rating(mu, sigma_sq, mu_j, sigma_j_sq, n_j, s_jk): """Calculates the updated mean and variance for the player. mu: Prior mean. A single number. sigma_sq: Prior variance. A single number. mu_j: The means of the m opponents faced in the rating period -- an array of shape [m,]. ...
def update_time_passage(ratings, period_to_period_variance): """Adds the variance from the passage of time.""" for cur_player in ratings: ratings[cur_player] = ( ratings[cur_player][0], ratings[cur_player][1] + period_to_period_variance, ) return ratings def calcula...
The code calculates Glicko ratings for players based on match outcomes across periods, updating ratings over time while tracking discrepancies. It initializes player ratings, iterates through periods, updates ratings using match results, and accumulates discrepancies. The output includes a rating history (pre-update ra...
def calculate_ratings( winners, losers, periods, prior_variance, period_to_period_variance ): """Calculates Glicko ratings. Args: winners: The array of winners for each of N contests, of shape [N,]. losers: The array of losers for each of N contests, of shape [N,]. periods: The period each matc...
def _send_versions(self, relation): self._sdi.send_versions(relation) def _send_auto_data(self, relation): if self.auto_data and self.is_available(relation): self.wrap(relation, self.auto_data) def is_ready(self, relation: Relation = None): """Checks whether the given relation, or an...
The main task of the code is to handle a relation event by sending version and auto data, then emitting 'ready', 'available', or 'failed' signals based on the relation's status checks. It processes the event by first transmitting necessary data and then triggering appropriate state-specific callbacks to notify observer...
def _handle_relation(self, event): self._send_versions(event.relation) self._send_auto_data(event.relation) if self.is_ready(event.relation): self.on.ready.emit(event.relation) elif self.is_available(event.relation): self.on.available.emit(event.relation) ...
def forward_encoder(self, x, building_mask, min_samples, max_samples, pre_sampled=False): if pre_sampled: mask = (x[:, 1:] == 1) mask = self.patchify(mask).squeeze(-1) x = x[:,:1] # embed patches x = self.patch_embed(x) # append pos embed w/o cls tok...
The code processes input images and building masks through an encoder-decoder architecture. It handles both regular and pre-sampled data, ensuring batch size constraints for pre-sampled maps. The encoder generates latent representations and masks, while the decoder predicts outputs. For pre-sampled data, it replaces pr...
def forward(self, imgs, building_mask, min_samples, max_samples, pre_sampled=False): # Because pre-sampled maps have different numbers of samples (even when binned by % sampled), the # _MAE sub-model can only accept batches of size 1 on pre-sampled maps. if pre_sampled: if imgs.shape...
def get_fact_confirm() -> pd.DataFrame: df_confirm = __load_csv_data(file_name=COVID_DATA_JHU_CONFIRM) df_confirm = etl_covid_data_jhu(df_confirm, total_col_label='confirm', trans_col_label='new_confirm') return df_confirm def get_fact_death() -> pd.DataFrame: df_death = __load_csv_data(file_name=COVID_...
The function `get_fact_jhu_full` merges confirmed cases, deaths, and recoveries dataframes on 'location' and 'date', calculates active cases, merges country metadata (economy, income group), and returns a sorted DataFrame with combined COVID-19 statistics and geographical attributes.
def get_fact_jhu_full() -> pd.DataFrame: df_confirm = get_fact_confirm() df_death = get_fact_death() df_recover = get_fact_recover() df_full = pd.merge(df_confirm, df_death[['location', 'date', 'death', 'new_death']], how='inner', on=['location', 'date']) df_full = pd.merge(d...
def getValidLocations(board): validLocations = [] for col in range(COL_COUNT): if isNotFull(board, col): validLocations.append(col) return validLocations def gameIsOver(board): return (winningMove(board, player) or winningMove(board, bot) or len(getValidLocations(board))==0) def...
This code implements the Minimax algorithm with Alpha-Beta pruning for a two-player game (e.g., Connect Four). It evaluates the best move by recursively exploring all possible game states, maximizing the score for the AI player and minimizing it for the opponent. The function checks terminal states, assigns scores base...
def minimax(board, depth, alpha, beta, maximizingPlayer): valid_locations = getValidLocations(board) is_terminal = gameIsOver(board) if depth == 0 or is_terminal: if is_terminal: if winningMove(board, bot): return (None, 100000000000000) elif winningMove(board, player): return (None, -10000000000000)...
def minimax(board, depth, alpha, beta, maximizingPlayer): valid_locations = getValidLocations(board) is_terminal = gameIsOver(board) if depth == 0 or is_terminal: if is_terminal: if winningMove(board, bot): return (None, 100000000000000) elif winningMove(board, player): return (None, -10000000000000)...
The main task of the code is to determine the optimal move for the bot using the minimax algorithm, place its mark on the board, check for a winning condition, and return. It selects the best column via minimax, updates the board with the bot's piece, prints the board state, and announces a win if the move results in a...
def compMove(): bestCol = minimax(board, 5, -math.inf, math.inf, False)[0] #places mark in the column r = getNextOpenRow(board, bestCol) dropMark(board, r, bestCol, bot) printBoard(board) print() if winningMove(board, bot): printBoard(board) print("Bot ...
def get_calendar_api(): # pragma: no cover """ Get an object which allows you to consume the Google Calendar API. You do not need to worry about what this function exactly does, nor create test cases for it. """ creds = None # The file token.pickle stores the user's access and refresh tokens, a...
The main task of the code is to provide a menu-driven interface for interacting with a calendar system, allowing users to view past/future events, search events by date or keyword, delete events, and handle input validation, with a loop that continues until the user chooses to exit.
def main(): primary_calendar = Calendar(get_calendar_api()) # time_now = datetime.datetime.utcnow().isoformat() + 'Z' # 'Z' indicates UTC time # primary_calendar.get_upcoming_events(time_now, 3) choice = get_choice() while choice != 6: if choice == 1: print("Enter number of ...
def insert_series(): series = [] n = int(input("Enter the number of elements in the series: ")) for i in range(n): element = int(input(f"Enter element {i + 1}: ")) series.append(element) return series def minimum(series): return min(series) def maximum(series): return max(series)...
This code implements a menu-driven basic statistics calculator. It allows users to input a numerical series and compute statistics like min, max, sum, mean, product, geometric mean, standard deviation, or generate a full report. The loop repeatedly displays options until the user chooses to quit.
def main(): series = [] while True: print("\nBASIC STATISTICS CALCULATOR:") print("1.- Insert Series") print("2.- Minimum") print("3.- Maximum") print("4.- Sum") print("5.- Arithmetic Mean") print("6.- Product") print("7.- Geometric Mean") ...
def get_input_type(self, user_input): if isinstance(user_input, pddf): return 'pandas' elif isinstance(user_input, psdf): return 'pyspark' else: raise ValueError("Only pandas or pyspark dataframes allowed as input!") def check_if_exists(self, table_name): ...
This function appends data from a DataFrame to a Kusto table, handling both pandas and non-pandas inputs. It checks if the target table exists: if so, it maps pandas data types to Kusto schema and writes data using Spark; if not, it creates the table via write_table. Authentication details and cluster/database paramete...
def write_append_table(self, data_frame, table_name, folder='KustoPyTables'): # Get the datatype of the input dataframe input_datatype = self.get_input_type(data_frame) # Check if table really exists table_exists, response = self.check_if_exists(table_name) if table_exists: ...
def make_word_list(res_tag, res_pos, token): word_list = [] # encoded word list stored for s in range(1, len(token) - 1): # Do not count the CLS and SEP if res_tag[s] != 'O': # Add word to word list word = replace_decoded_token_string_to_word(decode(token[s])) # ...
The code processes input parameters `res_tag`, `res_pos`, and `token` to generate structured JSON output. It first creates a list of words using `make_word_list`, filters relevant words with `filter_words`, and converts the result into a JSON format via `return_phrase_json`, ultimately returning this structured data.
def predict_output(res_tag, res_pos, token): word_list = make_word_list(res_tag, res_pos, token) word_json_result = filter_words(word_list) json_result = return_phrase_json(word_json_result) return json_result
def onSelect(self,event): #calling the event is the self.lstList1 widget varList = event.widget select = varList.curselection()[0] value = varList.get(select) conn = sqlite3.connect('phonebook.db') with conn: cursor = conn.cursor() cursor.execute("...
The code defines a `load_gui` method that creates a Tkinter GUI for data entry and management. It sets up labels, entry fields, a listbox with scrollbar, and buttons for submitting/deleting records. The interface allows users to input personal details, view entries in a list, and interact with a database via `create_db...
def load_gui(self): self.lbl_fname = tk.Label(self.master,text='First Name:') self.lbl_fname.grid(row=0,column=0,padx=(27,0),pady=(10,0),sticky=N+W) self.lbl_lname = tk.Label(self.master,text='Last Name:') self.lbl_lname.grid(row=2,column=0,padx=(27,0),pady=(10,0),sticky=N+W) sel...
def save_info(self): info = {} info["description"] = self.long_memory.description info["schedule"] = self.short_memory.schedule with open(os.path.join(self._out_folder, "info.json"), "w") as f: json.dump(info, fp=f) def _decompose(self): self.short_memory.cur_activi...
The code executes a scheduling process by decomposing events, recognizing activities, updating short-term memory, and iterating until the schedule ends. It saves activity data, checks for new events, updates time, and terminates when reaching the end time or encountering schedule completion.
def _run_schedule(self): self.save_info() ## decompose the first event self._decompose() while True: ## Recognize if the planning activity is reasonable reg_success, reg_activity, sensor_summary = self._recognize_activity() self.s...
def _create_range_schedule(self,start_date,start_time) -> Schedule: for try_idx in range(self._retry_times): try: _schedule = self._create_range_schedule_chat( start_date=start_date, start_time=start_time, ) asse...
The code plans and executes a schedule over a specified time period. It initializes date/time parameters, validates the start time format, sets memory variables for simulation, generates schedules for each day, runs them, and saves results. The function returns True if the schedule execution completes successfully, han...
def plan( self, days:int=1, start_time:str="00:00", end_time:str="23:59", base_date:datetime=datetime.strptime("02-01-2024", '%m-%d-%Y') ): try: start_time_dt = datetime.strptime(start_time, "%H:%M") del(start_tim...
def __checkForQuit(self): """ Checking for quit event, from the close button """ #Same as passing a parameter ## for event in pygame.event.get(): ## if event.type == pygame.QUIT: for event in pygame.eve...
This code implements a main game loop that handles user input, checks for game over conditions, restarts the game upon user interaction, updates the game state, and renders the board and UI elements. It processes mouse events to detect tile clicks, manages game state transitions, plays background and game over music, a...
def control(self): """ 1.Main game loop - a big while to check for quit 2.For loop to receive events 3.Check for quit all the time, the 4.For loop looking for specific quit event is in __checkForQuit 5.Mouse up and game is ...
def init(): """ Initialize the black screen with tile, font and screen size """ global SCREEN, CGBACKGROUND, TILELOGO #initialize pygame - call the constructor pygame.init() os.environ["SDL_VIDEO_CENTERED"] = "1" #set the font font = pygame.font.Font('freesansbold.ttf', 20...
The main task of the code is to create a game loop that continuously redraws the board, handles mouse events for tile interaction, and highlights the clicked tile. It initializes the game, processes user input (including quitting via ESC or window close), updates the display to reflect changes, and maintains real-time ...
def main(): """ The controller """ #Call init - has draw board with tiles - has initial update of screen init() ###################################WHILE STARTS################################# #continuously monitor while True: boolMouseCicked = False ###################...