dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def update_depth(self, gs): """function to make the computer smarter if theres room for it""" values = {'P': 1, 'Q': 9, 'R': 5, 'N': 3, 'B': 3, '-': 0, 'K': 3} total_value = 0 for row in range(8): for column in range(8): total_value += values[gs.board[row][col...
The code determines the best move using a minimax algorithm by evaluating possible game states, updating influence matrices, and selecting the highest-rated move from legal options. It adjusts depth if a checkmate is detected and returns the optimal move as an Engine.Move object.
def make_best_move(self, gs): # TODO if you can castle force it self.update_depth(gs) if len(gs.moves_log) > 30 and self.matrixes_updated == False: self.update_matrix() gs_copy = copy.deepcopy(gs) gs_small = SmallGs(None, 1) self.min_max_gamestate(gs_copy, gs_...
def FC(x, units, activations, bn, bn_decay, is_training, use_bias=True): if isinstance(units, int): units = [units] activations = [activations] elif isinstance(units, tuple): units = list(units) activations = list(activations) assert type(units) == list for num_unit, acti...
This code implements a spatiotemporal GAN (WeaGAN) for processing input data X with embedded temporal (TE), spatial (SE), and weather (WE) features. It applies feedforward layers, spatiotemporal attention blocks (STWAttBlock), and self-attention (STWSelfAttention) to encode/decode features, generating a final output th...
def WeaGAN(X, TE, SE, WE, P, Q, T, L, K, d, bn, bn_decay, is_training): D = K * d # input X = tf.expand_dims(X, axis=-1) X = FC( X, units=[D, D], activations=[tf.nn.relu, None], bn=bn, bn_decay=bn_decay, is_training=is_training) # STE, STWE STE,STWE,WE,TWE,SWE = STWEmbedding(SE,...
def get_line_number(raw_input): """ Return line if the line given exist, is a number, and non-negative, else None. """ try: input_parts = raw_input.split() command = input_parts[0] option = input_parts[1] line_number = input_parts[2] line_number = int(line_number)...
The function validates if a given line number is within the valid range of a file's lines. It retrieves the line number from input, checks if it's within the file's length, and returns it if valid. If invalid, it prints an error message and returns None.
def get_line_number_in_range(raw_input): """ Return the line if its within the file lines length. """ line_number = get_line_number(raw_input) if not line_number: return None if not is_line_number_in_range(line_number): print(f"Line number must be in range of 1 to {get_file...
def get_line_number(raw_input): """ Return line if the line given exist, is a number, and non-negative, else None. """ try: input_parts = raw_input.split() command = input_parts[0] option = input_parts[1] line_number = input_parts[2] line_number = int(line_number)...
The function `process_write_command` validates and processes a "write" command by parsing input, extracting the command, option, line number, and content. It checks if the line number and content exist, then executes either `write_line` or `write_end` based on the option's alias. Invalid options trigger an error messag...
def process_write_command(raw_input): """ validate incomming inputs for the write command. """ input_parts = raw_input.split() command = input_parts[0] option = input_parts[1] line_number = get_line_number(raw_input) if not line_number: return None content = get_content(raw...
def read_line(line_number): file_lines = get_file_content(current_open_file) line_content = file_lines[line_number - 1].rstrip('\n') # generate a right-justified line number. line_number = microfilesys_rjust(str(line_number), 4) print(f"{line_number}| {line_content}") def get_line_number_in_range(...
This function processes 'read', 'clear', and 'remove' commands by determining if the input specifies a specific line or all lines. It validates input format, executes corresponding actions (e.g., reading/clearing/removing lines or all content), and returns None or displays errors for invalid inputs.
def process_common_command(command, raw_input): """ A generic function to handle read, clear, and remove command. """ common_command_handler = { "read": { "line": lambda: read_line(get_line_number_in_range(raw_input)), "all": lambda: read_all() }, "clear":...
def get_file_length(file_name): """ Return the line length of the file. """ return len(get_file_content(file_name)) def display_help(): print( f"""Syntax: create <file> Create a file in the current directory. open <file> O...
This code defines a program's main loop for a file management system, handling user input validation and mode switching between file manager (FM_MODE) and file editor (FE_MODE). It processes commands like create/open/delete files in FM_MODE and read/write/clear/remove operations in FE_MODE, with error handling for inva...
def start(): """ Starting point of the program, handles the basic input validation. """ current_file_mode = FM_MODE current_file = None global current_open_file print(f"microfilesys.py {version} {updated}\nEnter 'help' for help and 'quit' to quit.\n") while True: try: ...
def find_sci_cam_scale(image_file): # width from the imag file img = cv2.imread(image_file) image_width = img.shape[1] # Width from the config file config_file = os.environ["ASTROBEE_CONFIG_DIR"] + "/cameras.config" with open(config_file, "r") as file: text = file.read() m = re...
The function textures a 3D mesh using camera images, handling distortion correction for real data or simulated data. It processes image lists, adjusts crop windows, undistorts images (if not simulated), creates camera parameters, and runs texturing algorithms to generate a textured mesh, returning it or handling errors...
def texture_mesh(src_path, exec_path, cam_type, crop_win_map, mesh, args): if args.simulated_data and cam_type == "nav_cam": print("Texturing nav_cam is not supported with simulated data.") return "None" dist_image_list = os.path.join(args.output_dir, cam_type + "_index.txt") with open(dist...
def panoOrientations(panMin, panMax, tiltMin, tiltMax, hFov, vFov, overlap, preTilt): """ Return image center coordinates that cover the specified pan and tilt ranges, with the specified @overlap. Special complete wrap-around behavior is triggered when the pan range is exactly -180 .. 180. The @preTilt ...
The main task of the code is to execute and validate a pano orientation configuration test case. It prints a test label, generates a pano object using `panoOrientations` with given config parameters, visualizes the result with `printPano`, and verifies correctness via `checkPano` with the same config. This implements a...
def testCase(label, config): print(label, end=": ") pano = panoOrientations(**config) printPano(pano) checkPano(pano, **config)
def mean(my_list): # This is the defintion in the head. i = 0 my_sum = 0 for number in my_list: my_sum = my_sum + my_list[i] i+=1 mu = my_sum / i print('mean = ' + str(mu)) return mu def sd(my_list): j = 0 sigma = 0 my_sumsd = 0 mu = mean(my_list) f...
The code calculates the mean, standard deviation, and normal distribution of a list, generates a graph, checks for normality and skewness, then returns the mean, standard deviation, and normal distribution result as a tuple.
def stats(my_list): mu = mean(my_list) std = sd(my_list) dist = norm(my_list) graph(my_list) is_norm(my_list) is_skew(my_list) return (mu, std, dist)
def display_hand(hand): for letter in hand.keys(): for j in range(hand[letter]): print(letter, end=' ') print() def calculate_handlen(hand): letter_count = 0 for key in hand.keys(): letter_count += hand[key] return letter_count def update_hand(hand, word): word ...
The main task of the code is to allow a player to input valid words using the letters in their hand, calculate the score for each valid word, update the hand after each play, and track the total score until the hand is exhausted or the player quits. It validates words against a word list, updates the hand state, and re...
def play_hand(hand, word_list): x="" score=0 while 1==1: print() print("Current hand: ", end="") display_hand(hand) x=input("Enter word, or !! to quit: ") if x == "!!": print("Thank you for playing.") break elif calculate_h...
def _handle_yara_scan(self, param) -> RetVal: """ Look up all files in self.state_dir found in provided yara_path, defaulting to all files in self.state_dir, something we may or may not want depending on the source that was downloaded. scan_dir is the target of our yara search. ...
This code handles different actions based on the action identifier by routing requests to specific methods like YARA scanning, listing sources, or connectivity tests, then returns the result of the executed action.
def handle_action(self, param: Dict[str, Any]) -> RetVal: ret_val = APP_SUCCESS action_id = self.get_action_identifier() self.debug_print("action_id ", action_id) if action_id == "yara_scan": ret_val = self._handle_yara_scan(param) if action_id == "list_yara_source...
def checkForDuplicates(self): '''Go through the master vocab file and check for duplicate words (in english)''' data = self.readVocabFile(self.masterfile) newdata = [] temp = [] for line in data: word = line.split("::")[0] if word not in temp: ...
The code's main task is to initialize vocabulary file paths, check for duplicates in the master and vocab files, merge their contents, and fix the vocab files to ensure consistency. It processes text files to maintain a clean, duplicate-free vocabulary list, likely for NLP tasks like tokenization or model training.
def __init__(self): self.masterfile = "Vocab/vocab_master.txt" self.vocabfile = "Vocab/vocab.txt" self.checkForDuplicates() self.mergeFiles() self.fixVocabFiles()
def on_init(self): pygame.init() pygame.display.set_caption("WFD") self.window = pygame.display.set_mode(self.window_size, pygame.RESIZABLE) self._running = True #self.generate_map() self.load_map() self.initialize_map_objs() self.find_path() def o...
This code initializes and runs a game loop for a grid-based application (likely a tower defense game), handling initialization, rendering a grid of rectangles, processing events, updating game elements (enemies, towers), and maintaining the game state. It continuously redraws the grid, manages game logic, and displays ...
def on_execute(self): if self.on_init() == False: self._running = False background_color = (0,0,0) self.window.fill(background_color) rect_size = self.rect_size for i in range(self.grid_size): x_coord = (self.grid_padding * (i+1) + (rect_size * i...
def generate_map(self): for i in range(self.grid_size): if i not in self.grid.keys(): i_coord = (self.grid_padding * (i + 1) + (self.rect_size * i)) self.grid[i] = {} for j in range(self.grid_size): j_coord = (self.grid_padding * (j + 1) + ...
This code defines a game loop that initializes and manages a game environment, including map generation, enemy spawning, tower attacks, and rendering. It handles event processing, updates game state (enemy movement, health checks), renders visuals, tracks frame rates, and maintains the game loop until termination. The ...
def loop(self): self.running = True self.generate_map() self.load_map() self.solve_map() self.calculate_pixel_path() self.spawn_enemy() last_hit = pygame.time.get_ticks() self.locate_towers() while self.running: time = pygame.time.g...
def populate_names(): #name of the video is loaded global moves_60,moves_90,moves_120; m_60=10 m_90=22 m_120=28 str_60="60_" str_90="90_" str_120="120_" for i in range(1,m_60+1,1): name=str_60+str(i)+".mov" seq = VideoFileClip(name); moves_60[name]=seq.duration ...
The main task of the code is to process an input song file by trimming its duration based on beat timings, generate a synchronized dance video by concatenating preselected video clips according to a combination index derived from the song's rhythm, and output the final video with the modified audio, while providing fee...
def main2(song_file_in): populate_names() # load_data() global beats_f beats_f = dynamic_temp(song_file_in) sound = AudioSegment.from_file(song_file_in, format=formate_song) x = len(sound) a = x x = x - beats_f[0][0] * 1000 sound = sound[-x:] if len(sound)/1000 >120: so...
def getOptions(): print("1. Explore") print("2. Inventory") print("3. Town") print("4. Exit") val = input("") return int(val) def exploreLogic(): for i in range(1, 10): print(str(i) + "0% ...") time.sleep(0.1) determineFoundItem() def printInventory(): print("==Inve...
The main task of the code is to run a text-based game loop that repeatedly displays options to the user, processes their selection (e.g., exploring, viewing inventory, or exiting), and executes corresponding functions until the user chooses to exit.
def main(): print("This is a text based game") while True: selected = getOptions() if selected == 1: exploreLogic() elif selected == 2: printInventory() continue elif selected == 3: continue elif selected == 4: ...
def inference(self, x): bs = x.shape[0] # Backbone network feat = self.backbone(x) # Neck network feat = self.neck(feat) # Detection head cls_feat, reg_feat = self.head(feat) # Prediction layer obj_pred = self.obj_pred(reg_feat) cls_pred...
The main task of the code is to perform forward propagation through a detection model, processing input features via backbone, neck, and head networks to generate objectness, classification, and regression predictions. It reshapes outputs, decodes bounding boxes using anchors, and returns structured predictions includi...
def forward(self, x): if not self.trainable: return self.inference(x) else: bs = x.shape[0] # Backbone network feat = self.backbone(x) # Neck network feat = self.neck(feat) # Detection head cls_feat, reg_fe...
def load_configs(): ''' This function loads the configs from default.config into the local configs. ''' config_path = get_config_path() config_dict = {} float_regex = re.compile("[0-9]+\.[0-9]+") int_regex = re.compile("[0-9]+") bool_regex = re.compile("True|False") with open(config_...
The main task of the code is to execute a dynamic-taxes process by loading configurations, preparing script arguments, checking a "noexec" flag to determine if execution should be skipped, and running the script if allowed. It serves as a capsule for orchestrating the execution flow with conditional control based on in...
def main(): ''' This function is a capsule for an execution of dynamic-taxes ''' configs_unset = load_configs() args = prepare_script({"configs_unset" : configs_unset}) if "noexec" in args: if args["noexec"]: return exec_script(args)
def separative_power(feed, countercurrent_to_feed, cut): a_p, a_w = a_factors(feed, countercurrent_to_feed, cut) z_p = rectifier_length(countercurrent_to_feed, cut) factor11 = 0.5 * DELTA_M * VELOCITY**2 / GAS_CONSTANT / TEMPERATURE factor12 = 1 - R1_R2**2 line1 = 0.5 * feed * cut * (1-cut) * facto...
The main task of the code is to plot the relationship between feed rate and separative work units (SWU) and the stage separation factor for different values of $ k $. It generates two subplots: one showing SWU as a function of feed rate (in mg/s) and another showing the separation factor, each with lines corresponding ...
def plot(): feed = np.linspace(1, 30, 50)*1e-6 # kg s^-1 f_opt = np.array([10e-6, 4e-6]) # optimum feed rate F*, kg s^-1 k = np.array([2.31, 3.94]) fs = ps.set_size(subplots=(1, 2), higher=True) fig, ax = plt.subplots(1, 2, figsize=fs) for i, (kk, ff) in enumerate(zip(k, f_opt)): ...
def reactor_cycles(irradiation_time, verbose=False): """Get the (int) number of expected reactor cycles in one simulation""" # Note the integer division! n_cycles = ((SIM_DUR - enrichment_reactorgrade()) // (irradiation_time + REFUELLING_TIME)) if verbose: print(f'Irradiat...
The main task of the code is to execute a series of calculations for a nuclear reactor simulation cycle, computing expected values related to plutonium, enriched uranium, and reprocessed uranium based on input parameters like burnup and irradiation time. It orchestrates multiple sub-functions to model reactor behavior,...
def get_expectations(fname, irradiation_time, burnup, verbose=True): """Run all the calculations for one simulation""" print(f"Expected values for a cycle with burnup {burnup} and " + f"irradiation time {irradiation_time}:\n") reactor_cycles(irradiation_time, verbose=True) natU_to_repU_...
def calculate_concentrations(self, n_e=None, n_s=None): """ Calculate the concentrations in all streams (feed, product and tails) for the given enrichment parameters. Following E. von Halle, see [2]. """ n_e = self.n_e if n_e is None else n_e n_s = self.n_s if n_s...
The function `calculate_staging` determines the optimal number of enriching (`n_e`) and stripping (`n_s`) stages to meet target concentrations using scipy's optimization. It minimizes a root-finding equation involving concentration differences, rounds results to integers, and validates solutions. It handles process-spe...
def calculate_staging(self, return_OptimizeResult=False): """ Calculate the staging by finding the root of sqrt((self.xp[3]-self.user_xp)**2 / self.user_xp**2 + (self.xt[3]-self.user_xt)**2 / self.user_xt**2) using scipy's optimize.minimize function. Round...
def check_data_purity(data): if len(np.unique(data[:, -1]))!=1:#if label column has more than 1 value return False else: return True def classify_data(data): labels=data[:, -1]#retreive label column data unique,count=np.unique(labels, return_counts=True)#set of unique label values and th...
This function recursively builds a decision tree by splitting data based on the best feature-value pair, handling base cases for purity, depth limits, and minimum samples. It constructs a tree structure as a dictionary, where each node represents a decision question, and branches lead to classifications or further spli...
def decision_tree_algorithm(df, counter=0, min_samples=1, max_depth=7): #data preparations if counter==0: global COLUMN_HEADERS #global to access COLUMN_HEADERS=df.columns data=df.values #numpy array if first iteration else: data=df #later iterations #base case ...
def read_data(class1, class2): data_class1 = pd.read_csv(class1) data_class2 = pd.read_csv(class2) data = data_class1.append(data_class2) return data def normalize(df): norm_df = (df-df.min())/(df.max()-df.min()) return norm_df def split_data(data, value): split = calculate_split(len(data), ...
The code evaluates a k-Nearest Neighbors (k-NN) classifier's accuracy for varying k-values (10 down to 1) on a normalized dataset. It loads and preprocesses data, splits it into training and test sets, shuffles data using a provided seed, and iteratively tests each k-value. For each k, it predicts test labels, calculat...
def main(seed_val): data = read_data(url0, url1) data = normalize(data) data = data.to_numpy() # List of good seed values: 2, 4, 11, 12 np.random.seed(seed_val) np.random.shuffle(data) train, test = split_data(data, 0.10) print_test_split(test) neighbors = 10 while neighbors!=1: count = 0 ...
def modifying_chapter1(number_of_stage, user_answer, skillset): if user_answer == "1": skillset = modify_statpoint("Team spirit", 1, 1, skillset) elif user_answer == "2": skillset = modify_statpoint("Team spirit", -1, -1, skillset) return skillset def modifying_chapter2(number_of_stage, user...
This code modifies a 'skillset' based on the 'user_answer' and current 'number_of_stage' by routing to stage-specific functions (modifying_chapter1-5), then returns the updated skillset.
def modifying(number_of_stage, user_answer, skillset): if number_of_stage == 1: modifying_chapter1(number_of_stage, user_answer, skillset) elif number_of_stage == 2: modifying_chapter2(number_of_stage, user_answer, skillset) elif number_of_stage == 3: modifying_chapter3(number_of_s...
def analyze_continuous(self, dataframe): """ Pipeline for continuous features. :param dataframe: pandas.DataFrame :return: dict (scheme for continuous features) """ continuous_woes_scheme = dict() for feature in dataframe: if feature == 'target': ...
This function generates a scheme for input variables using a scikit-learn interface. It creates a continuous or categorical analysis plan based on the 'is_continuous' flag, processes data with target variables, and stores the scheme in self.scheme. The method returns the instance with the generated scheme, handling bot...
def fit(self, X: pd.DataFrame, y=None): """ Creates a scheme for passed variables, Scikit-Learn interface :param X: pd.Dataframe, independent variables :param y: pd.Series, dependent variables :return: dict, scheme """ dataframe = X.copy(deep=True) self.sc...
def _save_chat(self, c, d): chat_dict = self._get_defaults_dict( source=c, keys={ 'title': 'title', 'username': 'title', }, existing={ 'type': c['type'], 'updated_':d, ...
This method processes incoming Telegram messages by saving chat/member data, identifying message type/chat context, and delegating to specialized handlers for text messages, new group members, and member exits. It uses telepot's glance() for message analysis and routes events to _on_chat_message_text(), _on_join_a_grou...
def on_message(self, msg): chat = self._save_chat(msg['chat'], msg['date']) member = self._save_member(msg['from'], msg['date']) content_type, chat_type, chat_id = telepot.glance(msg) print('\n\n--- [ %s ] ---\n' % content_type, chat_type, chat_id) pprint(msg) if conte...
def get_bytes_from_file(file_path): with open(file_path, "rb") as image_file: file_bytes = image_file.read() return file_bytes def get_titan_image_insertion_request_body(prompt_content, input_image_bytes, insertion_position, insertion_dimensions): original_image = get_image_from_bytes(input_image_b...
The main task of the code is to generate an image using Amazon's Titan Image Generator model via AWS Bedrock. It initializes an AWS session, configures a Bedrock client, uses a default image if none is provided, constructs a request body with text/image insertion parameters, invokes the model, and returns the generated...
def get_image_from_model(prompt_content, image_bytes, mask_prompt=None, negative_prompt=None, insertion_position=None, insertion_dimensions=None): session = boto3.Session( profile_name=os.environ.get("BWB_PROFILE_NAME") ) #sets the profile name to use for AWS credentials bedrock = session.clien...
def find(self, a: EClassId) -> EClassId: return self.U.find(a) def lookup(self, n: ENode) -> Optional[EClassId]: if self.lookup_compression: canon_n = self.canonicalize(n) a = self.H.get(canon_n, None) if a is None: return None elif (canon_...
The function `equiv` determines if two objects `x` and `y` are equivalent based on their types. For `EClassId` instances, it checks if their `find` results match. For `ENode` instances, it compares their `lookup` values. For `Term` instances, it verifies if their `represents` outputs are non-None and equal. If none of ...
def equiv(self, x, y) -> bool: if type(x) == type(y) == EClassId: return self.find(x) == self.find(y) elif isinstance(x, ENode) and isinstance(y, ENode): return self.lookup(x) == self.lookup(y) elif isinstance(x, Term) and isinstance(y, Term): a = self.represe...
def click_on_element(self, locator=None, index=None): """Generic function for clicking elements. (Range index version)""" click_result = False try: WebDriverWait(self.selenium, self._timeout).until( EC.presence_of_element_located(locator) ) Web...
The main task of the code is to verify if clicking a specified link opens a new browser tab and loads a page containing a required string in its URL. It returns True if both conditions are met, otherwise False. The function handles tab switching, URL validation, and ensures the result is printed regardless of outcome.
def check_new_page( self, np_link_locator=None, required_string=None, index=None ): """Check if the Linked Page opens up in a New Tab""" check_result = False try: time.sleep(0.5) self.click_on_element(np_link_locator, index) self.selenium.switc...
def wait_it_out(cls, seconds=1.0): time.sleep(seconds) return True def click_on_element(self, locator=None, index=None): """Generic function for clicking elements. (Range index version)""" click_result = False try: WebDriverWait(self.selenium, self._timeout).until( ...
The function checks if clicking a link opens the same page in the current tab by verifying the URL contains a specified string. It clicks the element, switches to the current window, waits, checks the URL, and returns a boolean result. If the URL contains the required string, it confirms the link works in the same tab.
def check_same_page_link_works( self, sp_link_locator=None, required_string="https://masaischool.com", index=None, ): """Check if the Linked Page opens up in the Same Tab""" check_result = False try: self.wait_it_out(3) ...
def wait_it_out(cls, seconds=1.0): time.sleep(seconds) return True def click_on_element(self, locator=None, index=None): """Generic function for clicking elements. (Range index version)""" click_result = False try: WebDriverWait(self.selenium, self._timeout).until( ...
This function verifies if a specified link opens a new tab with a URL containing a required string. It clicks the link, switches to the new tab, checks for the expected URL content, and restores the original tab if successful.
def check_new_page_link_works( self, np_link_locator=None, required_string=None, index=None ): """Check if the Linked Page opens up in a New Tab""" check_result = False try: self.wait_it_out(0.5) self.click_on_element(np_link_locator, index) se...
def check_page_element(self, locator=_LOCATOR, timeout=None): """Check to see if given WebElement is in place, present and visible""" check_result = False try: if timeout is None: timeout = self._timeout WebDriverWait(self.selenium, timeout).until( ...
This function scrolls a specified web element into view using JavaScript, adjusts the scroll position by a given value, and handles element selection by index or random choice if unspecified. It ensures the element is visible and positions the scroll accordingly.
def scroll_into_view(self, locator, index=0, scroll_val=150): self.check_page_element(locator, timeout=25) self.wait_it_out(1) elem = self.selenium.find_elements(*locator) if index is None: index = self.select_random_index(locator) self.selenium.execute_script( ...
def select_random_index(self, card_locator=_FOCUS_TAG_LOCATOR): card_list = self.get_page_elements(card_locator) self.wait_it_out(1) card_count = len(card_list) if card_count > 1: index = randint(0, card_count - 1) else: index = 0 return index def ...
The function `check_new_window_link_works` verifies if a specified link opens a new window and loads content containing a required string. It clicks the link, switches to the new window, checks the URL for the target string, and returns `True` if successful. If the check fails or an error occurs, it returns `False`. Th...
def check_new_window_link_works( self, nw_link_locator=None, required_string="masaischool", index=None ): """Check if the Linked Page opens up in a New window""" check_result = False try: # assert self.is_current_page time.sleep(0.5) if index is No...
def locate_files(path, mode=0): os.chdir(path) for file in os.listdir(path): if file.startswith(".") or file.endswith(".ms"): continue f_abspath = os.path.abspath(file) if mode == 0: tree_cloner(f_abspath) if is_dir(f_abspath): # print("Found DIR : " + f...
This function locks files in a specified directory by renaming each file with a generated code suffix, writing the code to a clone path, and changing the directory back to its parent after processing.
def lock(path): os.chdir(path) for file in locate_files(path): f_abspath = os.path.abspath(file) code = code_gen() os.rename(f_abspath, "{0}.ms".format(code)) with open(get_clone_path(f_abspath), "w") as c_file: c_file.write(str(code)) print("File [{0}] Locke...
def f_state_config(): if os.path.exists("SAFE"): return "Online" elif os.path.exists("MS_hidden-00978687##afd"): return "Offline" else: return "nil" def clear(): f_stat = f_state_config() if f_stat == "Online": rmtree(Safe_root) elif f_stat == "Offline": o...
The code verifies a user-entered password against a stored password from a file, selecting the file based on system state (Online/Offline). If incorrect, it displays an error; if correct, it either unlocks a folder (mode 0) or exits the program (mode 1), then initializes data and closes the password window. If unconfig...
def check_pass(): pass1 = pass_ent.get() f_stat = f_state_config() c_pass_root = "" if f_stat == "Online": c_pass_root = Pass_root2 elif f_stat == "Offline": c_pass_root = Pass_root elif f_stat == "nil": pass_lbl2.config(text="Program U...
def f_state_config(): if os.path.exists("SAFE"): return "Online" elif os.path.exists("MS_hidden-00978687##afd"): return "Offline" else: return "nil" def req_pass(mode=0, window=None): def check_pass(): pass1 = pass_ent.get() f_stat = f_state_config() c_pas...
The function `p()` checks the system state using `f_state_config()` and performs actions based on the result: locking the folder if "Online", unlocking with a password request if "Offline", or initializing setup with a default password if "nil". It also triggers `data_init()` for initialization.
def p(): f_stat = f_state_config() if f_stat == "Online": folder_lock() print("You Locked the Folder") elif f_stat == "Offline": req_pass(mode=0) print("You Unlocked the folder") elif f_stat == "nil": setup() messagebox.showinfo("Master_Safe", "You success...
def f_state_config(): if os.path.exists("SAFE"): return "Online" elif os.path.exists("MS_hidden-00978687##afd"): return "Offline" else: return "nil" def get_single(): filename = filedialog.askopenfilename(initialdir=Clone_root, title="Select A File To Open") return filename d...
The code checks the system state via f_state_config(). If "Online", it retrieves and unlocks a file; if "Offline", it warns the user; if unconfigured ("nil"), it shows an error. Finally, it initializes data with data_init().
def r(): f_stat = f_state_config() if f_stat == "Online": file = get_single() unlock_single(os.path.abspath(file)) elif f_stat == "Offline": messagebox.showwarning("Master_Safe", "[SAFE] folder is Offline") elif f_stat == "nil": messagebox.showerror("Master_Safe", "Progra...
def display_welcome(self): print("Welcome to Rock, Paper, Scissors, Lizard, Spock!") player2 = int(input("Will the second player be a human [Press 1] or [Press 2] to play the AI?")) if player2 == 1: self.player2 = Human(3, "Human", "Human 2") if player2 == 2: pass...
The main task of the code is to execute a game流程 by first displaying a welcome message, then initiating gameplay, and finally showing the winners. The `run_game` method orchestrates these steps sequentially: welcoming players, facilitating game play, and announcing winners, ensuring a complete game experience from star...
def run_game(self): self.display_welcome() self.play_game() self.display_winners()
def unary(self): print("UNARY") # Optional unary +/- if self.checkToken(TOKEN.PLUS) or self.checkToken(TOKEN.MINUS): print (self.curToken.type.name) self.nextToken() self.primary() def checkToken(self, kind): return kind == self.curToken.type def ...
The main task of the code is to parse a "term" in an expression, handling multiplication/division operators. It starts with a unary expression, then processes zero or more *// operators followed by additional unary expressions. The loop iterates over operators, prints their type for debugging, and advances the tokenize...
def term(self): print("TERM") self.unary() # Can have 0 or more *// and expressions. while self.checkToken(TOKEN.ASTERISK) or self.checkToken(TOKEN.SLASH): print ("Operator- "+self.curToken.type.name) self.nextToken() self.unary()
def term(self): print("TERM") self.unary() # Can have 0 or more *// and expressions. while self.checkToken(TOKEN.ASTERISK) or self.checkToken(TOKEN.SLASH): print ("Operator- "+self.curToken.type.name) self.nextToken() self.unary() def checkToken(self,...
This code parses an arithmetic expression by first handling a term, then repeatedly processing '+' or '-' operators followed by additional terms, allowing for multiple terms connected by additive operators.
def expression(self): print("EXPRESSION") self.term() # Can have 0 or more +/- and expressions. while self.checkToken(TOKEN.PLUS) or self.checkToken(TOKEN.MINUS): print ("Operator- "+self.curToken.type.name) self.nextToken() self.term()
def expression(self): print("EXPRESSION") self.term() # Can have 0 or more +/- and expressions. while self.checkToken(TOKEN.PLUS) or self.checkToken(TOKEN.MINUS): print ("Operator- "+self.curToken.type.name) self.nextToken() self.term() def isComparis...
The code parses a comparison expression by first evaluating an expression, then checking for at least one comparison operator followed by another expression. It continues processing additional comparison operators and expressions in a loop, aborting if a required operator is missing. The task ensures valid comparison s...
def comparison(self): print("COMPARISON") self.expression() # Must be at least one comparison operator and another expression. if self.isComparisonOperator(): print ("Comparison Operator- "+self.curToken.type.name) self.nextToken() self.expression() ...
def checkToken(self, kind): return kind == self.curToken.type def nextToken(self): self.curToken = self.peekToken self.peekToken = self.lexer.getToken() def expression(self): print("EXPRESSION") self.term() # Can have 0 or more +/- and expressions. while self.che...
This code parses and processes different types of statements in a programming language, such as PRINT, LET (variable assignment), IF-THEN-ENDIF, WHILE-REPEAT-ENDWHILE, and INPUT. It checks for valid tokens, handles variable declarations, evaluates expressions, and manages control flow structures. The function also vali...
def statement(self): # "PRINT" (expression | string) if self.checkToken(TOKEN.PRINT): print("STATEMENT-PRINT") self.nextToken() if self.checkToken(TOKEN.STRING): self.nextToken() else: self.expression() ...
def __str__(self): return f"{self.type}-{self.nr}" def debug(self): cellinfo = "\n".join([c.__repr__() for c in self.cells]) return f"{self.__str__()}: {cellinfo}" def remaining_cells(self): return [c for c in self.cells if c.value == 0] def values(self): return [c.value for c in...
This code solves a puzzle by eliminating invalid options from remaining cells, identifies groups of cells (islands) with shared constraints, and removes options not applicable to non-island cells. It iteratively narrows possibilities to find cells with single valid options, aiding in solving the puzzle efficiently.
def solve(self): Verbosity.verbose( 3, f"solving {self.__str__()} ({Cell.progress})") Verbosity.verbose(4, self.debug()) rcells = self.remaining_cells() if (len(rcells) == 0): return for cell in rcells: for value in self.values(): ...
def _check_keydown_events(self,event): """Respond to keypresses""" if event.key == pygame.K_RIGHT: self.ship.moving_right = True elif event.key == pygame.K_LEFT: self.ship.moving_left = True elif event.key == pygame.K_q: sys.exit() elif event.k...
This method handles user input events in a Pygame application by iterating through event queue. It exits the game on window close, delegates key presses to _check_keydown_events and key releases to _check_keyup_events, and checks mouse clicks to detect play button interactions via _check_play_button with mouse position...
def _check_events(self): """Respond to keypress and mouse events""" for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.KEYDOWN: self._check_keydown_events(event) elif event.type == pygame...
def _check_fleet_edges(self): """Respond appropriatley if any alien have reached an edge""" for alien in self.aliens.sprites(): if alien.check_edges(): self._change_fleet_direction() break def _ship_hit(self): """Respon to ship being hit by an alien"""...
This method updates alien positions, checks for collisions with the player's ship, and detects if aliens reach the screen bottom, triggering responses like collision handling or game state changes.
def _update_aliens(self): """Check if the fleet is at an edge, then update position""" self._check_fleet_edges() self.aliens.update() #Look for alien-ship collision if pygame.sprite.spritecollideany(self.ship, self.aliens): print("Ship Hit!!!") self._ship_...
def _check_events(self): """Respond to keypress and mouse events""" for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.KEYDOWN: self._check_keydown_events(event) elif event.type == pygame...
The code runs the game's main loop, continuously checking for events, updating game elements (ship, bullets, aliens) when active, rendering the screen, and maintaining a 60 FPS frame rate to ensure smooth gameplay.
def run_game(self): """Start the main loop for the game""" while True: self._check_events() if self.game_active: self.ship.update() self.bullets.update() self._update_bullets() self._update_aliens() self....
def majorVote(node): labels = node.data[:,-1] y,count = np.unique(labels,return_counts=True) results = y[count==count.max()] if len(results) > 1: results = np.sort(results) vote = results[-1] else: vote = results[0] node.val = vote def mutualInfo(data,X): return entro...
This code constructs a decision tree up to a specified maximum depth using a decision stump approach. It selects the attribute with the highest mutual information for splitting, recursively builds left and right subtrees, and prints the tree structure with label counts at each node.
def decisionStump(node,maxdepth,label,header): if node.depth == int(maxdepth): majorVote(node) return else: maxInfo = 0 splitAtt = -1 for i in range(len(node.data[0])-1): mI = mutualInfo(node.data,i) if mI > maxInfo: maxI...
def decisionStump(node,maxdepth,label,header): if node.depth == int(maxdepth): majorVote(node) return else: maxInfo = 0 splitAtt = -1 for i in range(len(node.data[0])-1): mI = mutualInfo(node.data,i) if mI > maxInfo: maxI...
This function builds a decision tree from training data, evaluates its performance on the training set, and saves the error metric. It reads input data, constructs a decision tree with a specified maximum depth, predicts class labels, calculates classification error, and writes the error to a metrics file. The root nod...
def decisionTree(traininput,maxdepth,trainoutput,metricsoutput): with open(traininput, newline='\n') as f: reader = csv.reader(f, delimiter='\t') header = next(reader) data = np.zeros((0,len(header))) for row in reader: data = np.vstack((data,row)) root = Node(data) ...
def weight_variable(name, shape, stddev): """weight_variable generates a weight variable of a given shape.""" #1/sqrt(x) initial = tf.truncated_normal_initializer(stddev=tf.rsqrt(stddev)) return _variable_with_weight_decay(name, shape, initial, wd=0.0004) def bias_variable(name, shape): """bias_variable generates ...
The code defines a neural network training function that processes both original images and optical flow data using a CNN architecture inspired by NVIDIA's autonomous driving model. It splits input images into original and optical flow components, applies convolutional and fully connected layers to each, computes a com...
def train(): graph = tf.Graph() with graph.as_default(): global_step = tf.Variable(0, name='global_step', trainable=False) im, la = pre.get_val() images, labels = pre.read_opt_data(im, la, BATCH_SIZE, NUM_SAMPLES, True) #split images into original and optical flow images_ori, images_opt = tf.split(images...
def weight_variable(name, shape, stddev): """weight_variable generates a weight variable of a given shape.""" #1/sqrt(x) initial = tf.truncated_normal_initializer(stddev=tf.rsqrt(stddev)) return _variable_with_weight_decay(name, shape, initial, wd=0.0004) def bias_variable(name, shape): """bias_variable generates ...
This function evaluates a convolutional neural network (CNN) model on test data, computes prediction accuracy, and logs results. It constructs a CNN with multiple convolutional layers, max-pooling, and fully connected layers, applies a tan⁻¹ transformation to outputs, restores a pre-trained model checkpoint, and calcul...
def test(): graph = tf.Graph() with graph.as_default(): global_step = tf.Variable(0, name='global_step', trainable=False) im, la = pre.get_test() images, labels = pre.read_data(im, la, BATCH_SIZE, NUM_SAMPLES, False) # First convolutional layer W_conv1 = weight_variable('conv_weights_1', [5, 5, 3, 24], ...
def get_stage(l): prefix = l[0] if prefix=='*': return get_file_related_info(l) elif prefix=="-": if l[:2] == "--": return get_file_related_info(l) else: return Status.is_del elif prefix==' ': return Status.is_content elif prefix=='!': ...
The function parses a diff result (from difflib.context_diff) into structured containers, separating 'before' and 'after' content. It processes lines to identify sections, line ranges, and content changes, assigning them to respective containers. It handles blank lines, section boundaries, and content additions/deletio...
def parse_diff_content(g, fromfile="", tofile=""): ''' Analyze the diff result (get by difflib.context_diff) to the custom container. ''' before_content = Content(before=True, title=fromfile) after_content = Content(before=False, title=tofile) holden_content = before_content for l in g: ...
def set_color(): ''' 0:black, 1:red, 2:green, 3:yellow, 4:blue, 5:magenta, 6:cyan, and 7:white curses.init_pair(index, font_color, background) color should use this style: curses.COLOR_XXXX, ex. curses.COLOR_WHITE ''' os.environ["TERM"] = "xterm-256color" curses.start_color() default = c...
This function creates a curses-based text editor with split windows for viewing two files. It initializes screen elements, handles keyboard input for cursor navigation (arrows/h,j,k,l), updates displayed text dynamically, and manages window resizing. The main task is providing an interactive file viewer with synchroniz...
def get_win(stdscr, fromfile, tofile): screen = curses.initscr() screen.border(0) curses.echo() set_color() half_width, winl, winr, cursor, status, bufl, bufr = initialize(stdscr, fromfile, tofile) control_win = winr.curses_win while True: stdscr.erase() update_text(winr, b...
def colorWipe(self, strip, color, wait_ms=50): """Wipe color across display a pixel at a time.""" color = self.LED_TYPR(self.ORDER, color) for i in range(self.strip.numPixels()): self.strip.setPixelColor(i, color) self.strip.show() time.sleep(wait_ms / 1000.0)...
The code defines a method `ledMode` that controls LED strip effects based on the input mode. It cycles through predefined color patterns (e.g., red, green, blue wipes; rainbow, theater chase) in an infinite loop until an invalid mode triggers a break, resetting the LEDs to off.
def ledMode(self, n): self.mode = n while True: if self.mode == "1": self.colorWipe(self.strip, Color(255, 0, 0)) # Red wipe self.colorWipe(self.strip, Color(0, 255, 0)) # Green wipe self.colorWipe(self.strip, Color(0, 0, 255)) # Blue wipe ...
def score(x): if np.any((1 - x) == 0.): raise ValueError('Probs==1 -> -ln(1-x) is invalid') return -np.log(1 - x) def adjust(truth_score): truth_score_df = pd.DataFrame(data=truth_score, columns=['score']) truth_score_df.reset_index(inplace=True) # adjust truth_score_df = truth_score_d...
The code computes a truth score for each (object_id, value) pair by aggregating trust scores from sources, adjusting the aggregated scores, and converting them to probabilities using a dampening factor.
def compute_truth(trust, c_df, dampening_factor): trust_score = score(trust) truth_score = c_df.groupby( ['object_id', 'value']).apply(lambda x: np.sum(trust_score[x.source_id])) truth_score = adjust(truth_score) truth = to_prob(truth_score, dampening_factor) return truth
def compute_truth(trust, c_df, dampening_factor): trust_score = score(trust) truth_score = c_df.groupby( ['object_id', 'value']).apply(lambda x: np.sum(trust_score[x.source_id])) truth_score = adjust(truth_score) truth = to_prob(truth_score, dampening_factor) return truth def comput...
The code implements the TruthFinder algorithm for truth discovery, iteratively adjusting source reliabilities and fact confidences until convergence. It initializes source trustworthiness, computes fact confidences using a dampening factor, updates source trust based on fact confidences, and repeats until cosine simila...
def truthfinder(claims, imp_func=imp, initial_trust=0.9, similarity_threshold=(1 - 1e-05), dampening_factor=0.3, verbose=False): """ performs truth discovery using truthfinder TruthFinder works as follows 1. Initialize all...
def levenshtein(a: str, b: str) -> int: """ Computes the Levenshtein distance: the number of insertions, deletions or substitutions required to transform a -> b. Uses the Wagner-Fischer dynamic programming algorithm. Parameters: a: First string b: Second string Returns:...
This function calculates the distance between two strings using a specified method. It acts as a wrapper, routing the input to corresponding algorithms like Levenshtein, Hamming, or LCS based on the 'method' parameter. The valid methods include various string distance metrics, and it returns the computed distance or ra...
def distance(a: str, b: str, method: str): """ Wrapper function for calculating the distance of two strings using a given method. Parameters: a: First string b: Second string c: Distance metric, one of: ['levenshtein', 'normalized_levenshtein', 'levenshtein_recurisve'...
def choose_initial_centroids(self): added = 0 while added != self.nr_clusters: j = randrange(0,len(self.data)) if self.data[j] not in self.centroids: self.centroids.append(self.data[j]) added = added + 1 def reassign_clusters(self): self.cl...
This function performs K-means clustering by iteratively reassigning data points to clusters and recalculating centroids until convergence. It initializes centroids, tracks previous centroid states, and updates clusters in a loop until centroids stabilize. The process continues until the centroids no longer change betw...
def do_kmeans(self): sys.stderr.write('Choosing centroids.'+'\n') self.choose_initial_centroids() self.prev_centroids = [] self.clusters = [] # list of lists of relations name sys.stderr.write('Starting kmeans loop...'+'\n') while self.centroids != self.prev_centroids: ...
def _soup(self, url: str, type_: str = 'lxml'): return BeautifulSoup(self._get(url).content, type_) def _select_one(soup, selector, boolean=False, pretty=False, image=False, numeric=False, link=False): element = soup.select_one(selector) if pretty: return element.prettify() if eleme...
The main task of the code is to recursively parse product data from multiple web pages, extract key details (title, price, image, etc.), handle duplicate entries, and aggregate results into a dictionary. It uses HTML parsing, pagination, and duplicate checks to collect product information efficiently while avoiding red...
def _parse_products(self, link, parameters, page=1, result=dict()): products = self._soup(f"{self.link}{link}{parameters['PAGE']}{page}").select(parameters['PRODUCT_URL']) if not products: return result for product in products: product_link = product.get('href') ...
def _soup(self, url: str, type_: str = 'lxml'): return BeautifulSoup(self._get(url).content, type_) def _select_one(soup, selector, boolean=False, pretty=False, image=False, numeric=False, link=False): element = soup.select_one(selector) if pretty: return element.prettify() if eleme...
The code parses product types from a webpage, extracting titles and URLs, then organizes them into a dictionary with URLs as keys and associated product data. If no types are found, it defaults to the sub-category title and original link.
def _parse_types(self, link, sub_category_title, parameters): result = dict() type_page = self._soup(f"{self.link}{link}") types = type_page.select(parameters['TYPE_BLOCK']) for type_ in types: type_title = self._select_one(type_, parameters['TYPE_TITLE']) type_...
def _soup(self, url: str, type_: str = 'lxml'): return BeautifulSoup(self._get(url).content, type_) def _select_one(soup, selector, boolean=False, pretty=False, image=False, numeric=False, link=False): element = soup.select_one(selector) if pretty: return element.prettify() if eleme...
The main task of the code is to parse sub-categories from a given link, extract their titles and URLs, and build a structured dictionary (`result`) containing nested data. It uses CSS selectors to identify sub-category blocks, iterates through them, and populates the dictionary with parsed titles, URLs, and further par...
def _parse_sub_categories(self, link, category_title, parameters): result = dict() sub_category_page = self._soup(f"{self.link}{link}") sub_categories = sub_category_page.select(parameters['SUB_CATEGORY_BLOCK']) for sub_category in sub_categories: sub_category_title = self....
def _soup(self, url: str, type_: str = 'lxml'): return BeautifulSoup(self._get(url).content, type_) def _select_one(soup, selector, boolean=False, pretty=False, image=False, numeric=False, link=False): element = soup.select_one(selector) if pretty: return element.prettify() if eleme...
The code parses categories from a webpage using BeautifulSoup, extracts URLs and titles, and recursively processes subcategories/products. It structures data into a nested dictionary with category URLs as keys, storing titles and parsed subcategory/product details. The function returns this organized data structure.
def _parse_categories(self, parameters): category_page = self._soup(self.link) categories = category_page.select(parameters['CATEGORY_BLOCK']) data = dict() for category in categories: category_url = self._select_one(category, parameters['CATEGORY_URL'], link=True) ...
def __firstNumericCharacter(self, instruction): for i in range(len(instruction)): if instruction[i].isnumeric(): return i return None def valid(self, instructions): for instruction in instructions: instruction_name = self.__extract_name(instruction) if instruction_name not in self._operations: re...
The method `new_operation` defines a new operation by validating the input name (no numeric start, no apostrophes) and subinstructions, then stores them in a dictionary. It clears recent operations to ensure undo functionality works correctly and triggers a reset.
def new_operation(self, name, subinstructions): self._recent_operations.clear() #have to clear else undo no longer works anymore assert self.__firstNumericCharacter(name) == None assert "'" not in name assert self.valid(subinstructions) self._operations[name] = subinstructions self.reset()
def __extract_name(self, instruction): if "'" in instruction: return instruction[:instruction.index("'")] if instruction[-1].isnumeric(): return instruction[:self.__firstNumericCharacter(instruction)] return instruction def _extractNumber(self, instruction): index = self.__firstNumericCharacter(inst...
This code recursively expands complex instructions into fundamental operations by breaking down composite instructions into their subcomponents, applying multiplicity (repetition) and inversion logic based on instruction formatting, and returning the fully expanded list of fundamental operations.
def expand(self, instruction): instruction_name = self.__extract_name(instruction) if instruction_name in self._fundamental_operations: return [instruction] subinstructions = self._operations[instruction_name] expanded_subinstructions = [] for subinstruction in subinstructions: expanded_subinstruc...
def valid(self, instructions): for instruction in instructions: instruction_name = self.__extract_name(instruction) if instruction_name not in self._operations: return False return True def __extract_name(self, instruction): if "'" in instruction: return instruction[:instruction.index("'")] if i...
This code processes and executes a series of operations (instructions) by validating, expanding derived operations, and optionally saving them for undo functionality. It handles input as a string or list, normalizes it, checks validity, and executes fundamental or expanded derived operations, returning the instance aft...
def execute(self, instructions, saving_instructions = True): assert isinstance(instructions, str) or isinstance(instructions, list) if isinstance(instructions, str): instructions = instructions.replace(" ","") instructions = instructions.split(",") #turns into a list automatically if no commas found assert ...
def loadMB(input_folder): left_filelist = glob.glob(input_folder + '/im0.png') right_filelist = glob.glob(input_folder + '/im1.png') disp_filelist = glob.glob(input_folder + '/disp0GT.pfm') left_filelist = sorted(left_filelist) right_filelist = sorted(right_filelist) disp_filelist = so...
The code trains a neural network model (branch and simB) using a custom hinge loss on stereo vision datasets (MB, Kitti2012/15, ETH). It processes batches of image pairs, computes similarity scores, and updates model parameters via Adam optimization. After each epoch, it evaluates performance, saves weights if the aver...
def train(branch, simB,lr, input_folder, nr_epochs, nr_batches,batch_size, patch_size, dataset, out_folder,save_weights, save_folder_branch, save_folder_simb, model_name): params = list(branch.parameters()) + list(simB.parameters()) if(dataset == 'MB'): left_list, right_list, gt_list = loadMB(input...
def createNW(chan,n_conv): class UpdateInconsNW(nn.Module): def __init__(self,img_ch=chan): super(UpdateInconsNW,self).__init__() self.softmax = nn.Softmax(dim=1) self.act = nn.ReLU() self.Conv1 = nn.Conv2d(img_ch, n...
The code reads configuration parameters for training a neural network model, including patch size, epochs, batch size, and dataset paths. It loads displacement, ground truth, and image data lists, prepares a network architecture, computes class weights, and initiates training using the specified settings. The main task...
def main(): config = configparser.ConfigParser() config.read(sys.argv[1]) patch_size = int(config['PARAM']['patch_size']) nr_epochs = int(config['PARAM']['nr_epochs']) batch_size = int(config['PARAM']['batch_size']) model_name = config['PARAM']['model_name'] s_range = int(config[...
def get_column_message_context(self): return self.work_sheet.column_dimensions[self.get_column_letter_message_context()] def get_column_message_id(self): return self.work_sheet.column_dimensions[self.get_column_letter_message_id()] def get_columns_indices_comments(self) -> List[int]: indices = [...
The code applies styles to an Excel worksheet by setting column widths for message contexts, IDs, comments, and translations; freezing panes for visibility; and applying a regular font to columns. It also enables sheet protection if specified, ensuring structured formatting for data export or display.
def apply_style(self): # NOTE: Because we are using optimized mode we must set these before writing anything # https://openpyxl.readthedocs.io/en/stable/optimized.html # Reference: https://automatetheboringstuff.com/chapter12/ # Lock if self.lock_sheet: self.work_she...
def get_column_names(self): columns = [] if self.has_message_context: columns.append(ColumnHeaders.message_context) columns.append(ColumnHeaders.message_id) # Headers if CommentType.REFERENCES in self.comment_types or CommentType.ALL in self.comment_types: ...
This code initializes an Excel workbook for exporting translation data from .po files, setting up formatting parameters, worksheet structure, and preparing to write translation entries with specified column widths, text wrapping, and styling rules. It handles both source and target language content, comments, and metad...
def __init__( self, po_files: List[PortableObjectFile], comment_types: List[CommentType], output_file_path: Path, width_message_context: int = 20, width_message_id: int = 80, width_message_translation: int = 80, width_commen...
def get_arg(self): ''' gets size of images, paths etc. in a namespace arg. ''' # image shape HEIGHT, WIDTH, DEPTH = 96, 96, 3 # size of a single image in bytes IMG_SIZE = HEIGHT * WIDTH * DEPTH # path to the directory with the data path_root_dir = ...
The code tests the 'shuffle_at_scales' function by applying image shuffling at specified scales (None and 1) on a dataset, then visualizing the result. It reads images from a given path, applies the shuffle operation, and plots a single image to verify correctness. The test ensures proper handling of scaling parameters...
def test_shuffle_scale1(self,scale=1): print('run unit test - shuffle') arg = self.get_arg() images = read_all_images(arg.DATA_PATH) scales = [None, 1] images = shuffle_at_scales(scales,images) plot_a_single_image(3,images)
def get_arg(self): ''' gets size of images, paths etc. in a namespace arg. ''' # image shape HEIGHT, WIDTH, DEPTH = 96, 96, 3 # size of a single image in bytes IMG_SIZE = HEIGHT * WIDTH * DEPTH # path to the directory with the data path_root_dir = ...
The code tests the 'shuffle_at_scales' function by reading images from a specified path, applying shuffling at scales [None, 0, 1], and plotting a single image to validate the operation. It verifies correct handling of different scale parameters during image shuffling.
def test_shuffle_scale2(self,scale=1): print('run unit test - shuffle') arg = self.get_arg() images = read_all_images(arg.DATA_PATH) scales = [None, 0, 1] images = shuffle_at_scales(scales,images) plot_a_single_image(3,images)
def get_arg(self): ''' gets size of images, paths etc. in a namespace arg. ''' # image shape HEIGHT, WIDTH, DEPTH = 96, 96, 3 # size of a single image in bytes IMG_SIZE = HEIGHT * WIDTH * DEPTH # path to the directory with the data path_root_dir = ...
The code tests the 'shuffle_at_scales' function by applying specified scale values (including None and 0) to a set of images, then visualizing the shuffled result. It reads images from a data path, processes them with the given scales, and plots a single image to verify correct shuffling behavior.
def test_shuffle_scale3(self,scale=1): print('run unit test - shuffle') arg = self.get_arg() images = read_all_images(arg.DATA_PATH) scales = [None, 0, 0, 1] images = shuffle_at_scales(scales,images) plot_a_single_image(3,images)
def get_arg(self): ''' gets size of images, paths etc. in a namespace arg. ''' # image shape HEIGHT, WIDTH, DEPTH = 96, 96, 3 # size of a single image in bytes IMG_SIZE = HEIGHT * WIDTH * DEPTH # path to the directory with the data path_root_dir = ...
The code tests the 'shuffle_at_scales' function by applying predefined scale parameters (including None and 0) to a set of images, shuffling them, and plotting a single image for validation. It verifies correct handling of scale values during image shuffling, ensuring the function works as intended across edge cases li...
def test_shuffle_scale4(self,scale=1): print('run unit test - shuffle') arg = self.get_arg() images = read_all_images(arg.DATA_PATH) scales = [None, 0, 0, 0, 1] images = shuffle_at_scales(scales,images) plot_a_single_image(3,images)
def get_arg(self): ''' gets size of images, paths etc. in a namespace arg. ''' # image shape HEIGHT, WIDTH, DEPTH = 96, 96, 3 # size of a single image in bytes IMG_SIZE = HEIGHT * WIDTH * DEPTH # path to the directory with the data path_root_dir = ...
The code tests the 'shuffle_at_scales' function by reading images, applying shuffling with specified scale parameters (including None and 0), and plotting a single image to verify the shuffle operation's correctness at different scales.
def test_shuffle_scale5(self,scale=1): print('run unit test - shuffle') arg = self.get_arg() images = read_all_images(arg.DATA_PATH) scales = [None, 0, 0, 0, 0, 1] images = shuffle_at_scales(scales,images) plot_a_single_image(3,images)
def is_done(self) -> bool: """ Returns: bool: True if the state machine reached the last phase. Otherwise False. """ if self._event >= len(self._events_dt): return True else: return False def pause(self) -> None: """Pauses the state mac...
The code computes target joint positions for a robotic arm's articulation controller based on picking/placing positions, current joint states, and end-effector parameters. It handles event-driven phases like gripper opening/closing, trajectory interpolation, and orientation control, returning an ArticulationAction to e...
def forward( self, picking_position: np.ndarray, placing_position: np.ndarray, current_joint_positions: np.ndarray, end_effector_offset: typing.Optional[np.ndarray] = None, end_effector_orientation: typing.Optional[np.ndarray] = None, ) -> ArticulationAction: ...
def __load_buckets(self, section_name): """ Loads the schedule objects into their corresponding array buckets. Returns the resulting bucket """ section = self.entries[section_name] buckets = [[] for _ in range(len(Excella.DAYS))] # Access subjects for subject...
The code's main task is to draw a schedule block in a worksheet by loading section data, drawing metadata, railings, and schedules, then returning the updated offset for subsequent elements.
def __draw(self, worksheet, offset, section, officers): """ Draws a schedule block given a section and its officers """ buckets = self.__load_buckets(section) curr_offset = offset # Draw metadata curr_offset = self.__draw_metadata( worksheet, curr...
def __log(self, msg): """ Simple logging """ print(f"[3xc311a]: {msg}") def __set_columns(self, worksheet): """ Set the column styles """ if not self.has_set_columns: # Set column widths start = Excella.SCHED_BLOCK_COLUMN_ST...
This code initiates a spreadsheet drawing cycle by creating a worksheet, applying column styles, and rendering officer schedules from a JSON file. It reads officer data, iterates through sections/officers, and uses the __draw method to position content in the worksheet while updating cell offsets. The process logs prog...
def begin(self): """ Begins drawing cycle """ self.__log("Beginning drawing cycle...") # Set column stylings worksheet = self.workbook.add_worksheet() self.__set_columns(worksheet) # Begin drawing offset = Excella.HORIZONTAL_CELL_OFFSET ...
def update_vertical_lines(self): start_index= -int(self.V_NB_LINES/2) +1 for i in range(start_index, start_index+self.V_NB_LINES): line_x= self.get_line_x_from_index(i) x1, y1= self.transform(line_x, 0) x2, y2= self.transform(line_x, self.height) self.ve...
This function updates game elements (vertical/horizontal lines, tiles, ship) and manages scrolling mechanics, score tracking, and collision detection. It adjusts vertical/horizontal offsets based on time and speed, increments score when tiles pass, checks for ship collisions, and triggers game-over state with visual/au...
def update(self, dt): time_factor = dt*60 self.update_vertical_lines() self.update_horizontal_lines() self.update_tiles() self.update_ship() if not self.state_game_over and self.state_game_has_started: speed_y= self.SPEED* self.height/100 self.cu...
def create_dir(dir: str): if not os.path.exists(dir): os.makedirs(dir) def read_segments_from_seattle_data(): print(f"Reading segments from Seattle data {SEATTLE_STREET_CSV_PREPARED}") df = pd.read_csv(SEATTLE_STREET_CSV_PREPARED) for _, entry in df.iterrows(): street_name = entry["NAME"...
The main task of the code is to generate validation data by processing OpenStreetMap (OSM) data and Seattle-specific street segments. It creates directories, loads nodes/edges from OSM files, assigns segments to edges, generates a quality map with origin coordinates, and produces 10 sample data points for validation. T...
def generate_validation_data(file: str): create_dir(OSM_DIR) read_segments_from_seattle_data() load_nodes_and_edges_from_osm(file) assign_segments_to_edges() origin_lat, origin_lon = generate_quality_map() generate_samples(origin_lat, origin_lon, 10)
def Tag_Extractor(SENTENCEs, POSTAGs, CAPs, models, tokenizer, LM_model, LM_corpus, device, multi_head, multi_head_two=None): hiddens = [None, None, None] for model in models: if isinstance(model, (MIMO_LSTM, MIMO_LSTM_TF, MIMO_BERT_LSTM, MIMO_BERT_LSTM_TF)): LM_SENTENCEs = [] LM_hidden = LM_model.init_hidden...
The function `_evaluation` evaluates machine learning models on a dataset by predicting fact and condition labels from text data. It processes inputs in batches, extracts predictions using `Tag_Extractor`, and optionally generates tuples via `Tuple_Extractor`. Predictions are validated against ground-truth labels (`OUT...
def _evaluation(models, dataCenter, data, threshold_fact, threshold_cond, write_prediction=False, device=torch.device("cuda"), tokenizer=None, LM_model=None, LM_corpus=None, mimo_extractor_fact=None, mimo_extractor_cond=None, pretrain=False, multi_head=None, multi_head_two=None): raw_SENTENCEs, raw_POSTAGs, raw_CAPs,...
def _evaluation(models, dataCenter, data, threshold_fact, threshold_cond, write_prediction=False, device=torch.device("cuda"), tokenizer=None, LM_model=None, LM_corpus=None, mimo_extractor_fact=None, mimo_extractor_cond=None, pretrain=False, multi_head=None, multi_head_two=None): raw_SENTENCEs, raw_POSTAGs, raw_CAPs,...
The code evaluates multiple machine learning models on a dataset, performing cross-validation by splitting data into `num_pass` parts. It computes metrics like macro F1 score and standard deviation for validation and test sets, tracks the best model based on F1, saves predictions and model weights if improvements are f...
def evaluation(models, file_name, dataCenter, threshold_fact, threshold_cond, max_f1, max_std, out_model_name, num_pass, just_eval, write_prediction=False, file_name2=None, just_PR=False, tokenizer=None, LM_model=None, LM_corpus=None, mimo_extractor_fact=None, mimo_extractor_cond=None, pretrain=False, multi_head=None, ...
def Tag_Extractor(SENTENCEs, POSTAGs, CAPs, models, tokenizer, LM_model, LM_corpus, device, multi_head, multi_head_two=None): hiddens = [None, None, None] for model in models: if isinstance(model, (MIMO_LSTM, MIMO_LSTM_TF, MIMO_BERT_LSTM, MIMO_BERT_LSTM_TF)): LM_SENTENCEs = [] LM_hidden = LM_model.init_hidden...
This function trains a multi-model system with configurable heads for tasks like tagging and tuple extraction. It handles pretraining, semi-supervised learning, and batched data processing, optimizing parameters via SGD with gradient clipping. It computes weighted loss for fact/condition tags, manages model updates bas...
def apply_model(models, batch_size, dataCenter, device, weight_classes_fact=None, weight_classes_condition=None, LM_model=None, LM_corpus=None, tokenizer=None, mimo_extractor_fact=None, mimo_extractor_cond=None, pretrain=False, multi_head=None, multi_head_two=None, is_semi=False, eval_pack=[]): if is_semi: out_file...
def get_lines(filename): with open(filename, "r") as f: return [line.strip("\n") for line in f.readlines()] def move_crates(crates, moves): for move in moves: _, crates = execute_move(move, crates) return crates def parse_lines(lines): crates = defaultdict(lambda: []) moves = [] ...
The code processes a file's lines to parse crate positions and movement instructions, simulates moving crates according to those instructions, and returns the top crates from each stack as a string.
def get_part_1(filename): lines = get_lines(filename) crates = move_crates(*parse_lines(lines)) return get_top_crates(crates)
def monkeys_be_throwing_things_around( monkey_specifications, rounds=20, divider_override=None ): for monkey_round in range(rounds): for active_monkey in monkey_specifications: for item_worry in active_monkey["item_worries"]: # inspect new_item_worry = act...
The main task of the code is to read monkey specifications from a file, simulate monkeys throwing items around, and compute the resulting "monkey business" metric based on their final status. It processes input data, models interactions, and returns a calculated value representing the monkeys' activity after the simula...
def get_part_1(filename): monkey_status_after_throwing_around = monkeys_be_throwing_things_around( get_monkey_specifications(filename) ) return get_monkey_business(monkey_status_after_throwing_around)
def get_monkey_specifications(filename): with open(filename, "r") as f: monkey_lines = [line.strip("\n") for line in f.readlines()] monkey_specifications = [] for monkey_index in range(0, len(monkey_lines), 7): monkey_specifications.append( get_monkey_specification(monkey_lines[m...
The main task of the code is to compute the "monkey business" value after simulating 10,000 rounds of monkeys throwing items to each other. It calculates a divisor as the product of all monkeys' test operands, uses this to avoid large numbers during simulations, and returns the final monkey business score based on insp...
def get_part_2(filename): monkey_specifications = get_monkey_specifications(filename) monkey_divider = functools.reduce(operator.mul, [monkey["test_operand"] for monkey in monkey_specifications]) # we override dividing by the product of all test operands - this won't change the test results monkey_statu...
def process_beacons_data(self, beacon_data): point = [float(beacon_data.get("x")), float(beacon_data.get("y"))] mac_address = beacon_data.get("beacon") areas = self.get_beacon_facility(mac_address) area_id = next(area.get("idArea") for area in areas if self.is_inside_area(area.get("verti...
The main task of the code is to process beacon data by iterating through each beacon, handling exceptions, collecting valid processed rows, cleaning the data, and posting the cleaned positions. It ensures error resilience by skipping faulty beacons and only transmitting valid, cleaned data when available.
def proccess_areas(self): rows = [] for beacon in self.beacons_data: try: row = self.process_beacons_data(beacon) if row is not None: rows.append(row) except Exception as e: continue if len(rows) > 0: ...
def create_wordsearch(self): self.wordsearch = [[" " for _ in range(self.cols)] for _ in range(self.rows)] for word in self.words: placed = False while not placed: direction = random.choice(["horizontal", "vertical", "diagonal"]) if direction == "...
The main task of the code is to initialize a new word search game by selecting a random "boss word," resetting tracking variables, generating and displaying a word search puzzle, displaying the target word to find, and scheduling periodic shuffling of the puzzle every 3 minutes to add challenge.
def start_new_game(self): self.boss_word = random.choice(self.words) self.found_words = [] self.words_found_text.delete("1.0", tk.END) self.create_wordsearch() self.draw_wordsearch() self.riddle_label.config(text=f"Find the boss word: {self.boss_word}") self.resta...
def create_widgets(self): self.canvas = tk.Canvas(self, width=480, height=480) self.canvas.pack() self.riddle_label = tk.Label(self, text=f"Find the boss word: {self.boss_word}") self.riddle_label.pack() self.entry_label = tk.Label(self, text="Enter boss word:") self.en...
This code initializes a Word Search Game GUI with a 16x16 grid, sets up a list of programming language words, randomly selects a "boss" word, configures timers for game mechanics, and starts the game by creating widgets, generating the puzzle board, and initiating periodic shuffling after 3 minutes.
def __init__(self, *args, **kwargs): tk.Tk.__init__(self, *args, **kwargs) self.title("Word Search Game") self.geometry("500x550") self.rows = 16 self.cols = 16 self.words = ["PYTHON", "JAVA", "CPLUSPLUS", "RUBY", "HTML"] self.boss_word = random.choice(self.word...
def get_element(osm_file, tags=('node', 'way', 'relation')): """Yield element if it is the right type of tag""" context = ET.iterparse(osm_file, events=('start', 'end')) _, root = next(context) for event, elem in context: if event == 'end' and elem.tag in tags: yield elem ...
The code processes XML data from a file, validating elements if specified, and writes structured data into separate CSV files for nodes, ways, and their associated tags/nodes, using Unicode handling for proper character encoding.
def process_map(file_in, validate): """Iteratively process each XML element and write to csv(s)""" ''' encoding = 'utf8' has been addedd ''' with codecs.open(NODES_PATH, 'w', encoding='utf8') as nodes_file, \ codecs.open(NODE_TAGS_PATH, 'w', encoding='utf8') as nodes_tags_file, \ ...
def extractIdFromSample(self, sample): sampleHash = self._calcHash(sample) return sampleHash def extractMetricSpecFromMetric(self, metric): tokens = self.splitMetric(metric) for token in tokens: entries = self.splitToken(token) entriesDict = self.convertEntriesToD...
The code converts input rows into a structured list of dictionaries with specified fields ("id", "metricspec", "responsetime", "successrate"). It skips the first row (header), extracts relevant data from each subsequent row using helper methods, and returns the new field names along with the transformed data.
def convertRows(self, rows): converted = [] newFieldNames = ["id", "metricspec", "responsetime", "successrate"] effectiveRows = rows[1:] for row in effectiveRows: newRow = {} sample = row[0] sampleId = self.extractIdFromSample(sample)...
def prepareSimExpResultsOf(sampleSpaceFile, simExpStoreFile, strategyLabel): responseTimes = [] rewards = [] time = [] with open(sampleSpaceFile) as csv_file: sampleSpace = csv.reader(csv_file, delimiter=csvDelimiter) for eachRow in sampleSpace: if eachRow[0].startswith('Poi...
The main task of the code is to aggregate simulation results from three strategies (non-adaptive, 0.1-step, 0.2-step) into a unified dataset and visualize their response times and accumulated rewards using line plots. It prepares individual results, combines them, and generates comparative visualizations to analyze per...
def visualizeSimExpResults(): nonAdaptiveStrategyResults = prepareSimExpResultsOf(sampleSpaceNonAdaptiveStrategy, simExpStoreNonAdaptiveStrategy, "Non-adaptive") #lineplotResponseTimes(nonAdaptiveStrategyResults) oneStepStrategyResults = prepareSimExpResultsOf(sampleSpaceOneStepStrategy, simExpStoreOneStep...
def create_dictionary(self): seat_dictionary = {} for line in self.get_lines(): row = line[0:7] column = line[7:10] if row in seat_dictionary: seat_dictionary[row]["count"] += 1 seat_dictionary[row]["columns"].append(column) ...
The code's main task is to identify and return the seat ID of a missing seat by first creating a seat dictionary, validating it to find missing seats, and then retrieving the seat ID from the missing seats list.
def find_seat_id(self): seat_dictionary = self.create_dictionary() missing_seats = self.validate_seats(seat_dictionary) return self.get_seat_id(missing_seats)
def get_user_id(): reader = open("user_id.txt", "r") global user_id user_id = reader.read(); reader.close() return user_id def get_document_data(): db = firestore.client() doc_ref = db.collection(u'settings').document(user_id) doc = doc_ref.get() if doc.exists: global wait_s...
The code's main task is to monitor a button press and time-based updates to control a display and motor system. It retrieves user data, tracks time intervals, updates the display periodically, adjusts update times daily, and ensures motor resets on exit or interruption, handling both user input and scheduled tasks.
def main(): global user_id, next_update_time, end_time, start_time user_id = get_user_id() get_document_data() print("Start time/End time:\n", start_time,"\n" ,end_time) print("next update:",next_update_time.time()) try: while True: if GPIO.input(button_pin) == GPIO...
def move_to_line(new_line): global current_train_line num_step = train_line_diff(current_train_line, new_line) print("steps: " + str(num_step)) current_train_line = new_line; step(num_step, full_rotation//36+1, train_pins) GPIO.output(train_pins, (0,0,0,0)) def move_to_direction(direction): ...
The code updates a train's status by moving it to a specified line, setting its direction, and determining the duration of movement in minutes.
def update_train(new_line, direction, minutes): move_to_line(new_line) move_to_direction(direction) move_numbers(minutes)
def move_to_line(new_line): global current_train_line num_step = train_line_diff(current_train_line, new_line) print("steps: " + str(num_step)) current_train_line = new_line; step(num_step, full_rotation//36+1, train_pins) GPIO.output(train_pins, (0,0,0,0)) def move_to_direction(direction): ...
The main task of the code is to control a car's movement by positioning it on the "CAR" line, setting its direction to 2, and then moving it based on the specified number of minutes.
def update_car(minutes): move_to_line("CAR") move_to_direction(2) move_numbers(minutes)
def move_to_line(new_line): global current_train_line num_step = train_line_diff(current_train_line, new_line) print("steps: " + str(num_step)) current_train_line = new_line; step(num_step, full_rotation//36+1, train_pins) GPIO.output(train_pins, (0,0,0,0)) def move_to_direction(direction): ...
The main task of the code is to reset system parameters by moving to line "A", setting the default direction (downtown), and initializing numerical values to zero, likely preparing the environment for a fresh simulation or operation cycle.
def reset_all(): move_to_line("A") move_to_direction(0) #default is downtown move_numbers(0)
def draw_circle(cX, cY, rad, color=True): x,y = rad, 0 decisionOver2 = 1 - x # Decision criterion divided by 2 evaluated at x=r, y=0 while(y <= x): draw_pixel( x + cX, y + cY, color) #Octant 1 draw_pixel(-x + cX, y + cY, color) #Octant 4 draw_pixel( y + cX, x + cY, color) #Octan...
The main task of the code is to draw an obstacle with layered circular and arc elements. It draws two concentric circles, a star, and a series of arcs increasing in radius to form a shaded or 3D effect. The `cam_x` adjustment suggests camera-relative positioning, while the `angle` parameter controls arc orientation. Th...
def draw_obstacle(x,y): global angle draw_circle(x-cam_x, y,radius+16, False) draw_circle(x-cam_x, y,radius+22, False) draw_star(x-cam_x, y, False) i = 16 while(i <= 21): i+=1 draw_arc(x-cam_x, y,radius+i,angle,angle+90, False)
def option(self, tag, value=None): option = self.options[tag] if value is not None: # print(f"`{tag}` = `{value}`") option.value = value if option.callback is not None: option.callback(value) return option.value def restart_render_thread(self):...
This code initializes a simulation environment by processing a track image, loading car configurations, generating MJCF files for MuJoCo physics simulations, and setting up visualization parameters. It handles track validation, image processing, metadata loading, model configuration, and platform-specific adjustments f...
def stage(self, track=None): if track is None: if self.track is None: raise RuntimeError("stage must be called with a track first") else: self.track = track if self.option("cars_path") is not None: cars_path = os.path.join(self.template_dir, "c...
def partition(graph, boxes, arr, left, right): pivot = arr[left] i, j = left + 1, right while True: # consider even or odd length lists while i <= j and arr[i] <= pivot: i += 1 while i <= j and arr[j] >= pivot: j -= 1 if i <= j: arr[j], arr[i] = a...
This function implements the quicksort algorithm on an array, recursively sorting subarrays by partitioning around a pivot element. It integrates visualization through the 'draw_boxes_and_read' call, likely updating a graphical representation of the sorting process. The parameters 'graph' and 'boxes' suggest interactio...
def quick_sort(graph, boxes, arr, left, right): if left >= right: return p = partition(graph, boxes, arr, left, right) draw_boxes_and_read(graph, boxes, arr, 100) quick_sort(graph, boxes, arr, left, p - 1) quick_sort(graph, boxes, arr, p + 1, right)
def initialize_NN(layers): weights = [] biases = [] num_layers = len(layers) for l in range(0,num_layers-1): W = xavier_init(size=[layers[l], layers[l+1]]) b = tf.Variable(tf.zeros([1,layers[l+1]], dtype=tf.float32), dtype=tf.float32) weights.append(W) biases.append(b) ...
This function initializes a neural network for PDE identification, setting up placeholders, network layers, prediction graphs, and optimizers. It prepares the model to minimize losses between predicted and actual solutions, using Adam and L-BFGS-B optimizers for training. The code structures data inputs, neural network...
def idn_init(self, t, x, u, u_layers, pde_layers): # Training Data for Identification self.t = t self.x = x self.u = u # Layers for Identification self.u_layers = u_layers self.pde_layers = pde_layers # Initialize NNs for Identification ...
def initialize_NN(layers): weights = [] biases = [] num_layers = len(layers) for l in range(0,num_layers-1): W = xavier_init(size=[layers[l], layers[l+1]]) b = tf.Variable(tf.zeros([1,layers[l+1]], dtype=tf.float32), dtype=tf.float32) weights.append(W) biases.append(b) ...
The code initializes a physics-informed neural network (PINN) for solving PDEs. It sets up training data for initial/boundary conditions and collocation points, defines neural network layers, and constructs placeholders for TensorFlow inputs. The function computes predictions for the solution and its derivatives, formu...
def sol_init(self, x0, u0, tb, X_f, layers): # Training Data for Solution X0 = np.concatenate((0*x0, x0), 1) # (0, x0) X_lb = np.concatenate((tb, 0*tb + self.lb_sol[1]), 1) # (tb, lb[1]) X_ub = np.concatenate((tb, 0*tb + self.ub_sol[1]), 1) # (tb, ub[1]) self.X_f...