dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def do_error(self, msg, code=500): raise HTTPError(code, msg) def _save_notebook(self, model, path): print("Save Notebook ") nb_contents = from_dict(model['content']) self.check_and_sign(nb_contents, path) file_contents = model["content"] self.fs.write(path, file_contents...
This function saves a file or directory model to a specified path, validating the model's type and content. It handles 'file', 'directory', and 'notebook' types, performing type-specific saving operations. Error checks ensure required fields exist, and exceptions trigger error responses. After saving, it retrieves the ...
def save(self, model, path): print("Save called") """Save a file or directory model to path. """ self.log.debug("MongoContents.GenericManager: save %s: '%s'", model, path) if "type" not in model: self.do_error("No model type provided", 400) if "content" not in...
def dir_exists(self, path): # Does a directory exist at the given path? self.log.debug("MongoContents.GenericManager.dir_exists: path('%s')", path) return self.fs.isdir(path) or self.fs.isdir(path.strip("/")) def increment_filename(self, filename, path='', insert=''): """Increment a file...
This function creates a new untitled file or directory in a specified path, handling type and extension parameters. It validates the directory exists, determines the appropriate default type (file/notebook/directory), generates a unique filename using an incrementing mechanism, and returns the result of creating the ne...
def new_untitled(self, path='', type='', ext=''): """Create a new untitled file or directory in path path must be a directory File extension can be specified. Use `new` to create files with a fully specified path (including filename). """ #path ...
def update_room(df,dfa): room_list=new_data.rooms_info(df) if str(dfa)=='None': dfa=pd.DataFrame(columns=['room_no','jan','feb','mar','apr','may','jun','jul','aug','sep','oct','nov', 'dec']) for i in range(len(room_list)): dfa.loc[i]=Hide([room_list[i], 0, 0, 0, 0, 0, 0, \ ...
The function processes room payment entries by distributing the paid amount across monthly service fees, updating the DataFrame `dfa` with the allocated fees, and ensuring the payment does not exceed the annual limit. It checks room existence, validates inputs, and modifies the DataFrame accordingly, returning the upda...
def fill(rooms,df,dfa): if len(df)==0: print('No room entries available') return dfa if len(dfa)==0: dfa=update_room(df,df1) room_id=input("Enter room number: ") if room_id in rooms: service_fee=int(input("Enter service fee: ")) amount=int(input("Enter am...
def update_room(df,dfa): room_list=new_data.rooms_info(df) if str(dfa)=='None': dfa=pd.DataFrame(columns=['room_no','jan','feb','mar','apr','may','jun','jul','aug','sep','oct','nov', 'dec']) for i in range(len(room_list)): dfa.loc[i]=Hide([room_list[i], 0, 0, 0, 0, 0, 0, \ ...
The main task of the code is to remove a specified room from a DataFrame by zeroing its monthly data entries, updating the DataFrame, and returning it. It prompts for a room number, checks its existence, modifies the corresponding row's values to zero, applies a 'Hide' function, and updates the DataFrame with the chang...
def remove(rooms,dfa): if len(dfa)==0: update_room(dfa) print(show(dfa).room_no.values.tolist()) room_id=input("Enter room number: ") if room_id in rooms: lst=[] df1=pd.DataFrame(columns=['room_no','jan','feb','mar','apr','may','jun','jul','aug','sep','oct','nov',...
def update_room(df,dfa): room_list=new_data.rooms_info(df) if str(dfa)=='None': dfa=pd.DataFrame(columns=['room_no','jan','feb','mar','apr','may','jun','jul','aug','sep','oct','nov', 'dec']) for i in range(len(room_list)): dfa.loc[i]=Hide([room_list[i], 0, 0, 0, 0, 0, 0, \ ...
The main task of the code is to manage a room data entry system through an interactive menu, allowing users to add/remove entries, view data, handle contributions, and save changes upon exiting. It processes user input, updates a DataFrame (`dfa`), sorts data, and maintains room records while handling edge cases like e...
def opt(rooms,df,dfm): global dfa if str(dfm)=="None": dfa=pd.DataFrame(columns=['room_no','jan','feb','mar','apr','may','jun','jul','aug','sep','oct','nov', 'dec']) else: dfa=dfm if len(df)==0: print('No entries avalible, first add new entries') return dfa ...
def Create_new_table_Artiste(self , artiste): # Create table to store songs and playlists self.cursor.execute(""" CREATE TABLE IF NOT EXISTS Art_or( id CHAR, name CHAR, ...
The code searches for artists matching user-provided keywords in their names or song titles, retrieving their details and song counts. It ranks matches by keyword relevance, displays up to 5 results at a time with pagination, and allows selecting an artist to view their songs.
def searchArtiste(self,keywords): # Searches for artists that match one or more keywords provided by the user. # Retrieves artists that have any of the keywords in their name or in the title of a song they have performed. # Each match returns the name, nationality, and number of songs performed ...
def clean_windows(Signal_Clean_Windows, SRate, MaxBadChannels = 0.2, PowerTolerances = [-3.5, 5], WindowLength = 1, WindowOverlap = 2/3, MaxDropoutFraction = 0.1, MinCleanFraction = 0.25, TruncateQuantile = [0.022, 0.6], StepSizes = [0.01, 0.01], ShapeRange = np.ara...
This function cleans an audio signal using Autoregressive Spectral Reconstruction (ASR), calibrating on a reference section (either user-provided clean windows or the full signal) to estimate parameters. It extrapolates the signal, processes it with ASR (using Riemannian geometry if enabled), and trims excess samples, ...
def clean_asr(Signal_Clean_ASR, SRate, Cutoff = 5, WindowLength = [], StepSize = [], MaxDimensions = 2/3, ReferenceMaxBadChannels = 0.075, ReferenceTolerances = [-3.5, 5.5], ReferenceWindowLength = 1, CleanWindows = False, UseGPU = False, UseRiemannian = True, MaxMem = []): ...
def find_conflict_free(self): # Helper functions def check_next_level(level): new_sets = set() for cf in level: extend_and_add_set(cf, new_sets) return new_sets def extend_and_add_set(cf, new_sets): for arg in set(self.args).difference(cf)...
The code's main task is to compute and return various types of extensions in an argumentation framework, including conflict-free, admissible, preferred, complete, grounded, and stable extensions. These extensions represent different semantic interpretations of acceptable argument subsets, ensuring consistency and valid...
def find_extentions(self): self.find_conflict_free() self.find_admissible() self.find_preferred() self.find_complete() self.find_grounded() self.find_stable()
def prop_turn(self, arg): print("------------------------PROPONENT'S ARGUMENT------------------------") print(f"({arg}): {self.af.args[arg]}\n") self.in_.add(arg) def opp_turn(self): self.find_valid_opp_arguments() self.last_opp_arg = self.get_and_validate_input() self.ou...
The main task of the code is to process a turn by updating the current object's property with the given argument, triggering the opponent's turn logic, and then selecting the next argument to return. This function manages a turn-based interaction, handling both the current action and the opponent's response before dete...
def turn(self, arg): self.prop_turn(arg) self.opp_turn() return self.select_arg()
def termination(self, arg): self.find_valid_opp_arguments() if len(self.in_.intersection(self.out)) > 0 or arg in self.out or arg is None: self.win = True return True elif len(self.valid) == 0 and len(self.in_) > 0: self.win = False return True ...
The main task of the code is to execute a game loop that repeatedly clears the screen, updates the game state via `self.turn(argument)`, and checks for termination conditions. If no initial argument is provided, it randomly selects one from `self.af.args`. The loop ends when `termination(argument)` returns True, after ...
def play(self, argument=None): argument = (choice(list(self.af.args)) if argument is None else argument) if len(self.af.args) > 0 else None while not self.termination(argument): os.system('cls' if system() == 'Windows' else 'clear') argument = self.turn(argume...
def realsense_setup(): pipeline = rs.pipeline() config = rs.config() config.enable_stream(rs.stream.depth, IMG_W, IMG_H, rs.format.z16, 30) config.enable_stream(rs.stream.color, IMG_W, IMG_H, rs.format.bgr8, 30) pipeline.start(config) return pipeline def yolo_model_load(): # Load YOLOv5 mod...
The code captures real-time depth and color data from a RealSense camera, processes images using YOLO models for object detection, combines results into a single visualization, and saves frames when triggered. It aligns depth and color streams, applies color mapping to depth data, and displays/dumps processed images fo...
def runner_realsense(): save_num = 6 pipeline = realsense_setup() model1,model2,model3 = yolo_model_load() align_to = rs.stream.color align = rs.align(align_to) while True: frames = pipeline.wait_for_frames() aligned_frames = align.process(frames) depth_frame = aligned...
def secho(s: str, fg=None) -> None: """Write text in tqdm with :func:`click.style`.""" tqdm.write(click.style(s, fg=fg)) def analyze_by_path(path: Union[str, Path], *, iri_filter: Optional[str] = None) -> AnalysisResults: """Analyze an ontology at a given IRI.""" path = Path(path).resolve() parse_re...
The code analyzes an ontology by accepting one input source (IRI, prefix, or file path), validating it, applying filters, and generating markdown output. It ensures only one input method is used, processes the ontology via `analyze_by_path`, `analyze_by_iri`, or `analyze_by_prefix`, and writes results to a file or outp...
def analyze( iri: Optional[str], prefix: Optional[str], path: Optional[Path], cache: bool, iri_filter: Optional[str], obo_filter: bool, ): """Analyze a given ontology.""" analysis_results: AnalysisResults if 1 != sum(arg is not None for arg in (iri, prefix, path)): secho("Ca...
def parse(self): """ Parse the file """ # load it loader = create_loader(self.fpath) doc_obj = loader.load() # parse it text = [item.page_content for item in doc_obj] metadata = [item.metadata for item in doc_obj] self.text = text ...
The code processes a document by parsing it, splitting it into chunks, generating embeddings for the chunks, and returning the processed object (self) as a dictionary.
def process(self): """ Process the document, returning a dictionary. """ self.parse() self.chunk() self.embed() return self
def parsed_text(text_input): # Removes stopwords from parsed text text = word_tokenize(text_input.text.lower()) new_text = [''.join(c for c in s if c not in string.punctuation) for s in text] new_text = [s for s in new_text if s] text_no_sw_list = [word for word in new_text if no...
The main task of the code is to recursively print structured information from nested sections, including section titles, most frequent words (excluding stop words), and hyperlinks. It increments a global counter for each section, processes text data, and formats output with indentation based on hierarchy level, handlin...
def print_page(sections, level=0): # Main function, prints all the information global number for section in sections: number += 1 text_no_sw_list = parsed_text(section) common_words = find_common_words(text_no_sw_list) souping = result(content_of_section(number)) ...
def trapezoidal(f, a, b, n): """Return the integral of a function using Trapezoidal method.""" x, y, h = setup_vars(f, a, b, n) result = y[0] + y[-1] result += 2 * sum(y[1:-1]) result *= h / 2.0 return result def setup_vars(f, a, b, n): x = sample_space(a, b, n) y = [f(xi) for xi in x] ...
This function numerically integrates a function `f` over the interval [a, b] using Simpson's method. It handles cases where the number of subintervals `n` is 1 (via trapezoidal rule), or greater than 1, splitting into Simpson's 3/8 rule for odd `n` and Simpson's 1/3 rule for even `n`, combining results for accuracy.
def simpson(f, a, b, n): """Return the integral of a function using Simpson method.""" result = 0 if n == 1: result = trapezoidal(f, a, b, n) elif n > 1: x, y, h = setup_vars(f, a, b, n) if is_odd(n): result = simpson38(f, y[:4], h) y = y[3:] if le...
def is_integral(dtype: torch.dtype) -> bool: # Skip complex/quantized types dtypes = [x for x in get_all_dtypes() if x not in get_all_complex_dtypes()] return dtype in dtypes and not dtype.is_floating_point def is_quantized(dtype: torch.dtype) -> bool: return dtype in (torch.quint8, torch.qint8, torch.q...
The function compares two tensors for equality, handling integral, boolean, and complex types with specified tolerances (rtol, atol) and NaN handling. It returns True if tensors match, or False with detailed debug info on discrepancies, including element counts, maximum differences, and their positions.
def _compare_tensors_internal( a: torch.Tensor, b: torch.Tensor, *, rtol, atol, equal_nan: Union[str, bool] ) -> _compare_return_type: assert equal_nan in {True, False, "relaxed"} debug_msg: Optional[str] # Integer (including bool) comparisons are identity comparisons # when rtol is zero and atol is...
def __selectColumns(dfs, columns): new_dfs = {} columns = ['id', 'td'] + columns + ['label'] # order matters for subject, df in dfs.items(): new_dfs[subject] = df[columns] return new_dfs def __calibrate(dfs): subjectsDataset = {} for subject, df in dfs.items(): calibrationFrame...
The code loads and preprocesses sensor data (e.g., yaw, pitch, roll) for machine learning, splitting it into training/validation/test sets. It supports two split modes: random sampling (classic) or subject-based splitting. Data undergoes calibration, interpolation, denoising, normalization, and optional flattening. The...
def loadData(subjects=shared.SUBJECTS, selectedColumns=['yaw', 'pitch', 'roll'], splitMode=shared.SPLIT_MODE_CLASSIC, validationRatio=0.2, testRatio=0.2, flatten=False, normalize=True, denoise_n=8): trainingX = None tr...
def reset_error_sum(self): self.E = 0 def get_pose(self): return self.cur_pose def generate_twist(self, isJustRotate=False): if not self.cur_pose: return None # Calculate required linear velocity v_x = 0.0 target_ang = 0.0 if isJustRotate == False: ...
The main task of the code is to control a robot's movement by generating and publishing twist commands for navigation or rotation. It continuously checks the robot's pose, evaluates tolerable error thresholds, and stops the robot when either no movement is needed or acceptable error limits are met, ensuring precise and...
def move(self, isJustRotate=False): # print(f"isJustRotate: {isJustRotate}") self.reset_error_sum() while rclpy.ok(): rclpy.spin_once(self) if self.get_pose() == None: turtle_sim_searcher.utils.pause(1) continue twist = self.gen...
def inc_dest_pos(self, x,y): self.dest.x += x self.dest.y += y def move(self, isJustRotate=False): # print(f"isJustRotate: {isJustRotate}") self.reset_error_sum() while rclpy.ok(): rclpy.spin_once(self) if self.get_pose() == None: turtle_si...
The code performs a grid search by alternately moving the robot horizontally and vertically, adjusting its angle and position incrementally. It checks boundaries to avoid exceeding a maximum length, toggling direction upon reaching limits. The robot pauses after each movement, ensuring systematic exploration of the env...
def grid_search(self): # print("grid_search") isRight = True while (True): angle_inc = M_2_PI len_inc = self.length wid_inc = self.width if not isRight: angle_inc = -angle_inc len_inc = -len_inc self.inc...
def get_instructions(): raw_data = ut.read_file_lines('input.txt') instructions = [item.split() for item in raw_data] print(instructions) return instructions def do_instr(instruction, display): operation = instruction[0] if operation == 'rect': dimensions = instruction[1].split('x') ...
The main task of the code is to process a series of instructions to manipulate a 6x50 grid display, starting with all cells unlit ('.'). It applies each instruction to update the grid, then visualizes the final state and counts the number of lit pixels. The function retrieves instructions, updates the display iterative...
def part_one(): instructions = get_instructions() height = 6 width = 50 display = [['.' for j in range(width)] for i in range(height)] # Do all instructions for instruction in instructions: display = do_instr(instruction, display) # Display the display show_display(display) ...
def start_new_lap(): global lap_start_time lap_start_time = time.time() def start_new_last_lap(): global last_lap_start_time last_lap_start_time = time.time() def update_timers(): if running: update_current_lap_timer() update_last_lap_timer() window.after(100, update_timers)
The function toggles the 'running' state of a timer, initiating a new lap, a final lap, and updating timer displays when activated, effectively starting or stopping the timer's operation.
def start_stop_timer(): global running if running: running = False else: running = True start_new_lap() start_new_last_lap() update_timers()
def assess_bets_quali(results: List[Results], race: Race): # first we transform data into more suitable structure results_transformed = transform_results(results) # scoring for each of the players in db for player in Player.objects.all(): playersbets = RaceBet.objects.filter(race=race, player=pl...
This code processes all races to assess betting outcomes for different race types (qualifying, sprint, and main race). It first deletes existing assessment data to prevent duplication, then evaluates each race's results, updates bet assessments, and marks events as assessed in the database.
def handle(self, *args, **options): # first, we delete all data about points to avoid duplication PlayerPoint.objects.all().delete() PlayerPointsTotal.objects.all().delete() EventAssessmentStatus.objects.all().delete() # we're assessing every race, every player, every racetype ...
def find_fibonacci_series(self, number): """This method is used to find the series of fibonacci for the given number. This method will be called recursively. :param number :type int """ if number == 0: return 2 elif number == 1: return 3 ...
This method validates the input number, processes Fibonacci series based on its value, and returns appropriate results or error messages for invalid inputs like floats, negatives, or non-integers.
def run(self): """This method is used to handle the logic""" return_code = '' if self.number.isdigit(): self.number = int(self.number) if self.number > 0 and self.number < 2: self.logger.info("Series is {}".format(self.find_fibonacci_series(self.number))...
def loadTestPredictions(f): test_predictions = pickle.load(open(f, 'rb')) # Retrieve task list from file name task_list = f.name.replace('_test_predictions.pkl', '').split('_TA') # Use '_TA' as delimiter so '_S9' strains don't break for idx, task in enumerate(task_list): if not task.startswith(...
This code calculates performance metrics (balanced accuracy, ROC AUC, sensitivity, specificity) and confidence intervals for machine learning models across different architectures (STL, uMTL, gMTL) using bootstrap resampling. It processes test predictions, groups results by task configurations, determines significance ...
def calculateResults(path_to_output): # STEP 1: PREPARE DIRECTORIES AND METRICS path_to_test_results = path_to_output / 'test_results' path_to_test_results.mkdir(exist_ok=True) path_to_test_predictions = path_to_output / 'test_predictions' test_predictions_dir = os.scandir(path_to_test_predictions)...
def trainNTaskNeuralNetworkFromDict(hyperparam_dict, train_dataloader, tasks, device): # Instatiate neural network with hyperparameter dict n_input = list(train_dataloader)[0][0].size(dim=1) model = NTaskNeuralNetworkFromDict(hyperparam_dict, n_input, tasks).to(device) # Define training parameters with...
This function trains a neural network using specified hyperparameters and training data, evaluates the model on test data to compute balanced accuracy (balacc) and ROC AUC (rocauc) metrics, logs these performance metrics, and saves the trained model along with hyperparameters to the specified output path.
def testFinalModel(hyperparam_dict, trainval_dataloader, test_dataloader_with_id, tasks, path_to_output, device): model = trainNTaskNeuralNetworkFromDict(hyperparam_dict, trainval_dataloader, tasks, device) balacc, rocauc = evaluateNeuralNetwork(model, test_dataloader_with_id, tasks, save_predictions=True, path...
def majority_label(y): """ Determines the majority label for a binary classification of 0 or 1 Returns 0 if the most common value of y is 0, otherwise return 1 """ zero_count = 0 one_count = 0 for v in y: if v == 0: zero_count += 1 else: one_count ...
The code implements the ID3 algorithm to construct a binary decision tree for classification. It recursively splits data using attribute-value pairs with maximum information gain, terminating when labels are pure, no attributes remain, or max depth is reached. The tree is represented as a nested dictionary, with nodes ...
def id3(x, y, attribute_value_pairs=None, depth=0, max_depth=5): """ Implements the classical ID3 algorithm given training data (x), training labels (y) and an array of attribute-value pairs to consider. This is a recursive algorithm that depends on three termination conditions 1. If the entire set ...
def majority_label(y): """ Determines the majority label for a binary classification of 0 or 1 Returns 0 if the most common value of y is 0, otherwise return 1 """ zero_count = 0 one_count = 0 for v in y: if v == 0: zero_count += 1 else: one_count ...
The code implements the ID3 algorithm to construct a binary decision tree from training data (x, y) by recursively selecting the attribute-value pair with the highest information gain. It terminates when labels are pure, no attributes remain, or max depth is reached, returning majority labels. The tree is represented a...
def id3(x, y, attribute_value_pairs=None, depth=0, max_depth=5): """ Implements the classical ID3 algorithm given training data (x), training labels (y) and an array of attribute-value pairs to consider. This is a recursive algorithm that depends on three termination conditions 1. If the entire set ...
def majority_label(y): """ Determines the majority label for a binary classification of 0 or 1 Returns 0 if the most common value of y is 0, otherwise return 1 """ zero_count = 0 one_count = 0 for v in y: if v == 0: zero_count += 1 else: one_count ...
This function implements a weighted ID3 algorithm for boosting, recursively building a decision tree by selecting the attribute-value pair with maximum information gain. It splits data into left (False) and right (True) branches based on the chosen feature, considering weighted examples. The tree is represented as a ne...
def id3_boosting(x, y, d, attribute_value_pairs=None, depth=0, max_depth=5): """ Implements the same ID3 algorithm as above, only modified to accept an input distribution of the weighted examples This is the Learn function which is called in the boosting algorithm Returns a decision tree represented as...
def id3_boosting(x, y, d, attribute_value_pairs=None, depth=0, max_depth=5): """ Implements the same ID3 algorithm as above, only modified to accept an input distribution of the weighted examples This is the Learn function which is called in the boosting algorithm Returns a decision tree represented as...
The code implements AdaBoost using ID3 decision trees as base learners. It iteratively trains weak hypotheses on weighted examples, computes their error and corresponding alpha coefficients, updates example weights based on prediction accuracy, and normalizes weights. The ensemble combines these hypotheses with alphas ...
def boosting(x, y, max_depth, num_stumps): """ Performs a AdaBoost algorithm on the ID3 learner, iterating up to num_stumps Returns an ensemble of hypotheses with their associated alphas, represented as a list of pairs, ie: [ (a_1, h_1), (a_2, h_2), … , (a_L, h_L) ] """ h_ens = [] # Initi...
def display_text_animation(rect, string, l): text = '' for i in range(len(string)): text += string[i] text_surface = fontREAObj.render(text, True, COLOR_ORANGE) text_rect = rect text_rect.center = (WINDOW_SIZE[0]/2+10, WINDOW_SIZE[0]/2-10+l) surface.blit(text_surface, tex...
The code creates a tutorial menu using pygameMenu, loads background images, displays language-specific tutorial text with animated line-by-line rendering, and handles mouse clicks to return to the main menu. It initializes a black rectangular box for text display, reads tutorial content from an English or Spanish file ...
def show_tutorial(): tutorial_menu = pygameMenu.Menu(surface, # main menu menu bgfun=settings_background, color_selected=COLOR_YELLOW, font=font_type_bold, font_color=COLOR_WHITE, font_size=16, fo...
def display_text_animation(rect, string, l): text = '' for i in range(len(string)): text += string[i] text_surface = fontREAObj.render(text, True, COLOR_ORANGE) text_rect = rect text_rect.center = (WINDOW_SIZE[0]/2+10, WINDOW_SIZE[0]/2-10+l) surface.blit(text_surface, tex...
This code creates a pygame menu with language-specific update content, displays animated text updates in a designated area, loads and positions menu images, and returns to the main menu on user click. It reads update lines from a file based on the set language, animates each line with spacing, and handles exit events t...
def update_menu(): update_m = pygameMenu.Menu(surface, # main menu menu bgfun=settings_background, color_selected=COLOR_YELLOW, font=font_type_bold, font_color=COLOR_WHITE, font_size=16, font_size...
def display_text_animation(rect, string, l): text = '' for i in range(len(string)): text += string[i] text_surface = fontREAObj.render(text, True, COLOR_ORANGE) text_rect = rect text_rect.center = (WINDOW_SIZE[0]/2+10, WINDOW_SIZE[0]/2-10+l) surface.blit(text_surface, tex...
The code creates a forum menu using pygame, displaying language-specific content (English/Spanish) with animated text. It loads background images, renders forum entries line-by-line with spacing, and exits to the main menu on mouse click. The menu uses custom styling, handles file input based on language settings, and ...
def forum_menu(): forum_m = pygameMenu.Menu(surface, # main menu menu bgfun=settings_background, color_selected=COLOR_YELLOW, font=font_type_bold, font_color=COLOR_WHITE, font_size=16, font_size_t...
def display_text_animation(rect, string, l): text = '' for i in range(len(string)): text += string[i] text_surface = fontREAObj.render(text, True, COLOR_ORANGE) text_rect = rect text_rect.center = (WINDOW_SIZE[0]/2+10, WINDOW_SIZE[0]/2-10+l) surface.blit(text_surface, tex...
The code creates an author credits menu using pygameMenu, loads images, displays language-specific credits text with animation, and handles mouse clicks to return to the main menu.
def author_menu(): credits_m = pygameMenu.Menu(surface, # main menu menu bgfun=settings_background, color_selected=COLOR_YELLOW, font=font_type_bold, font_color=COLOR_WHITE, font_size=16, font_siz...
def show_tutorial(): tutorial_menu = pygameMenu.Menu(surface, # main menu menu bgfun=settings_background, color_selected=COLOR_YELLOW, font=font_type_bold, font_color=COLOR_WHITE, font_size=16, fo...
This function detects mouse click events on menu options by checking collisions between the cursor and predefined rectangles. It triggers corresponding actions like starting the game, showing tutorials, or opening settings/config menus based on which menu item is clicked. The function uses Pygame's event handling and c...
def check_menu_events(howto_rect, play_rect, options_rect, update_rect, forum_rect, author_rect, cheats_rect, exit_rect, MENU_GAME_OPTIONS, MENU_GAME_LANG, MENU_GAME_LANG_EN, MENU_GAME_LANG_ES, MENU_GAME_FULLSCREEN, MENU_GAME_MUSIC, MENU_GAME_RETURN_SETTINGS): for event in pygame.event.get(): if event.type ...
def load_menu_translations(set_language): if set_language == "0": # English language_translation = "ENGLISH" else: # Spanish language_translation = "SPANISH" f = open(translations_menu, "r") translations = f.readlines() f.close() for lost in translations: lost = lost.repl...
The main task of the code is to render a game's main menu background, including localized text for options like Tutorial, Play, and Settings, while drawing buttons, a logo, version info, and white rectangles for layout. It prepares interactive elements and passes them to an event-checking function for user input handli...
def main_background(): surface.fill(COLOR_BLACK) # main menu background color MENU_GAME_TUTORIAL, MENU_GAME_PLAY, MENU_GAME_OPTIONS, MENU_GAME_UPDATE, MENU_GAME_FORUM, MENU_GAME_AUTHOR, MENU_GAME_CHEATS, MENU_GAME_EXIT, MENU_GAME_LANG, MENU_GAME_LANG_EN, MENU_GAME_LANG_ES, MENU_GAME_FULLSCREEN, MENU_GAME_MUSIC,...
def getConnection(): print("INSIDE GET CONNECTION") mydb = psycopg2.connect(user=DB_Uname, password=DB_password, host= DB_Id, database=DB_name,port=Port_no) # conn = psycopg2.connect(database = "sample_ts_db", user = "postgres", password = "password", host = "127.0.0.1", port = "5432") #print("mydb:",my...
The code handles TCP client connections by receiving data, parsing device information (MAC address, location), checking a database for existing entries, generating unique IDs if necessary, inserting new records, and sending responses back to the client.
def connect(Client): #Function to connect tcp client get data and send response back while True: # global timestr conn=getConnection() id=str(random.randint(100,UID)) #generate random number or Uid #print("id...",id) data=Client.recv(1024) #receive the data #pr...
def tally(target, guess): if len(target) != WORD_SIZE or len(guess) != WORD_SIZE: raise ValueError(target, guess, "Invalid guess") return [tallyforposition(i, target, guess) for i in range(len(target))] def determine_status(response, turns): return Status.WON if response == [Match.EXACT] * WORD_SIZ...
The code implements a guessing game loop where the player attempts to guess a target value. It reads guesses, evaluates their accuracy against the target, determines the game status (win/loss/continue), and updates the display with turn count, status, feedback, and messages. The loop terminates when the game status ind...
def play(target, readGuess, display): for turns in range(1, MAX_TRIES + 1): guess = readGuess() response = tally(target, guess) status = determine_status(response, turns) display(turns, status, response, create_message(turns, status, target)) if status != Status.IN_PROGRESS: ...
def current_rent(self): """ This function deals with requirement 1 of the test. :return: The first 5 items of the list sorted in ascending order by `Current Rent` are pretty printed to the console. """ csv_reader = self.make_csv_reader() try: ...
The code's main task is to aggregate and display multiple lease-related details by sequentially calling methods that output current rent, lease duration, total rent, masts per tenant, and lease start date, providing a comprehensive overview of rental data.
def all(self): self.current_rent() print('\n') self.lease_years() print('\n') self.total_rent() print('\n') self.masts_per_tenant() print('\n') self.lease_start_date()
def Tridiagonalize(mtrx) : # Ubah mtrx menjadi matriks tridiagonal # KAMUS LOKAL # ALGORITMA n = len(mtrx) m = np.array(mtrx,dtype=np.float64) Q = np.eye(n) if (n > 2) : for i in range(n-2) : HH = np.eye(n) HH[i+1:,i+1:] = HouseHolder(m[i+1:,i]) m...
This function computes eigenvalues and eigenvectors of a square matrix using QR decomposition with Wilkinson shifts. It tridiagonalizes the matrix, iteratively applies QR decomposition with shifts to converge eigenvalues, and accumulates orthogonal transformations to compute eigenvectors. The result is eigenvalues from...
def QREigenSendiri(mtrx) : # Menghitung nilai eigen dari matrik mtrx memakai QR decomposition. Prekondisi : mtrx adalah matriks persegi # Sumber : https://www.andreinc.net/2021/01/25/computing-eigenvalues-and-eigenvectors-using-qr-decomposition # https://mathoverflow.net/questions/258847/solved-how...
def MeanFace(imgVectorMatrix) : # Menghitung mean face dari matriks vektor gambar. # KAMUS LOKAL # ALGORITMA avgVector = np.zeros(len(imgVectorMatrix[0]), dtype=np.int64) count = 0 for i in range(len(imgVectorMatrix)) : avgVector += imgVectorMatrix[i] count += 1 for i in ran...
The function computes EigenFaces from a matrix of image vectors using specified methods (QRBuiltIn, QRSendiri, Rayleigh). It calculates the mean face, subtracts it from images, computes covariance, extracts eigenvalues/vectors, normalizes, selects significant eigenfaces (excluding small values), and generates coefficie...
def EigenFace(imgVectorMatrix, method) : # Melakukan kalkulasi eigenface terhadap matriks vektor baris gambar dan # mengembalikan hasilnya, matriks koefisien terhadap gambar, waktu eksekusi, dan mean face # sesuai metode eigen yang dipilih. # KAMUS LOKAL # ALGORITMA # Dataset kosong if ...
def __double_chebyshev(A: list, B: list) -> float: """ This function is for Q9 Computes the Chebyshev distance between two coordinate and multiply by 2. """ return __chebyshev(A, B) * 2 def __double_manhattan(A: list, B: list) -> float: """ This function is for Q9 Computes the Manhattan ...
The code defines a function `heuristics` that calculates the distance between two 2D coordinates (A and B) using a selected heuristic method. The method is determined by the `option` parameter, which specifies one of five distance metrics: Manhattan, Euclidean, Chebyshev, Double Manhattan, or Double Chebyshev. The func...
def heuristics(A: list, B: list, option: int=0): """ Computes the heuristic distance between two coordinate based on the option slected. Parameters: ---------- A : 2D coordinates of A as a list. B : 2D coordinates of B as a list. option : int 0 - Manhattan Distance (Default) ...
def update_lr(self): if self.total_steps < 1000: return if self.total_steps % 40000: # gradient clip # if self.config.gradient_clip > 0.1: # self.config.gradient_clip = 0.1 if self.config.ppo_ratio_clip > 0.1: self.config.ppo...
The main task of the code is to perform a training step in a Proximal Policy Optimization (PPO) algorithm. It collects trajectories using the current policy, computes advantages and returns via Generalized Advantage Estimation (GAE), updates the neural network with the collected data, tracks performance metrics, saves ...
def step(self): self.update_lr() if self.config.play_only: self.validate(False) return config = self.config memory_buffer = Storage(config.rollout_length) states = self.states self.network.eval() #save trajectories into memory buffer -...
def padding(self, message=None, salt=None): """ """ if len(message)>=(2**64): raise ValueError('for padding, message length needs to be less than 2**64') if salt is not None: message=salt+message bites=convertToBites(message) Length=len(bit...
This code initializes a SHA-256 hash processor by validating input message type, setting standard round constants (_K) and initial hash values. It handles optional origin hash input, applies padding/splitting to the message, processes data blocks, and computes the final hexadecimal SHA-256 hash string stored in self.sh...
def __init__(self, message, originHash=None, salt=None): if message is not None: if type(message) is not str: raise TypeError('%s() argument 1 must be string, not %s' % (self.__class__.__name__, type(message).__name__)) self._K = [0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe...
def k(self): ''' Returns the local condensed stiffness matrix ''' # Get the local stiffness matrix, partitioned as 4 submatrices in # preparation for static condensation k11, k12, k21, k22 = self.__k_Partition() # Calculate the condensed l...
The function computes and returns the local end force vector of a structural member by calculating the matrix product of the member's stiffness matrix (self.k()) and displacement vector (self.d()), then adding the member's initial force vector (self.fer()). This combines internal forces from deformation with pre-existi...
def f(self): ''' Returns the member's local end force vector ''' # Calculate and return the member's local end force vector return add(matmul(self.k(), self.d()), self.fer())
def L(self): iNode = self.iNode jNode = self.jNode return ((jNode.X-iNode.X)**2+(jNode.Y-iNode.Y)**2+(jNode.Z-iNode.Z)**2)**0.5 def f(self): ''' Returns the member's local end force vector ''' # Calculate and return the member's local end force vector ...
The main task of the code is to segment a structural member into continuous segments based on load discontinuities, calculate their stiffness and load properties, and initialize displacement/slope values. It processes point and distributed loads, updates segment forces and moments, and prepares the member for structura...
def SegmentMember(self): # Get the member's length and stiffness properties L = self.L() E = self.E A = self.A Iz = self.Iz Iy = self.Iy SegmentsZ = self.SegmentsZ SegmentsY = self.SegmentsY SegmentsX = self.SegmentsX # Cr...
def select_odrive(self): # try: path_list = [] path_list = self.find_tree_parents(self.treeView.selectedIndexes()[0], path_list) path_list.reverse() odrive_number = int(path_list[0][-1]) # print(path_list) # print(odrive_number) my_drive = self.my_drive_list[odrive_number] return my_drive def dele...
The main task of the code is to reboot an ODrive device by first stopping its associated controller window and worker process, handling potential exceptions during reboot and shutdown, clearing UI layout elements, and re-establishing the ODrive connection.
def odrive_reboot(self): my_drive = self.select_odrive() try: # self.deleteItems(self.button_layout) self.controller_window.odrive_stopped() self.controller_window.close() except: pass try: my_drive.reboot() except Exception as e: print("exception rebooting,: {}".format(e)) # print("did w...
def select_odrive(self): # try: path_list = [] path_list = self.find_tree_parents(self.treeView.selectedIndexes()[0], path_list) path_list.reverse() odrive_number = int(path_list[0][-1]) # print(path_list) # print(odrive_number) my_drive = self.my_drive_list[odrive_number] return my_drive def dele...
This code dynamically generates a UI layout by iterating through an ODrive's JSON data, adding UI elements for items without "members" keys, and inserting a spacer for flexible spacing. It clears existing layouts, populates rows with custom widgets, and ensures scalable UI structure for ODrive configuration or status d...
def setup_general(self): my_drive = self.select_odrive() row_index = 0 self.deleteItems(self.sb_layout) for item in my_drive._json_data: if "members" in item.keys(): pass else: item_layout = self.add_single_layout_line(item, my_drive) self.sb_layout.addLayout(item_layout,row_index,1,1,1) r...
def update_machine_state(self): current_state = self.my_drive.axis0.current_state if self.axis0_state != current_state: self.axis0_state = current_state # print("New state axis0: {}".format(self.axis0_state)) self.update_machine_state_color(current_state, 0) current_state = self.my_drive.axis1.current_s...
The main task of the code is to update machine status, controller mode, and perform error checks within a try block, while catching and printing any exceptions that occur during these operations.
def update_statuses(self): # pass # self.update_voltage() try: self.update_machine_state() self.update_controller_mode() self.error_checks() except Exception as e: print(e)
def select_odrive(self): # try: path_list = [] path_list = self.find_tree_parents(self.treeView.selectedIndexes()[0], path_list) path_list.reverse() odrive_number = int(path_list[0][-1]) # print(path_list) # print(odrive_number) my_drive = self.my_drive_list[odrive_number] return my_drive def dele...
This code dynamically generates a UI layout for configuring an ODrive device based on its JSON structure. It organizes parameters into sections like config, motor, controller, encoder, and GPIO using QGridLayouts, adding widgets and spacers to manage spacing. The layout is built by iterating through selected JSON data,...
def setup_config(self, tree_selection): my_drive = self.select_odrive() # print("setting up config") row_index = 0 col_index = 1 first_gpio = True first_config = True member_row_index = 0 config_row_index = 0 self.deleteItems(self.sb_layout) self.general_layout = QtWidgets.QGridLayout() self....
def select_odrive(self): # try: path_list = [] path_list = self.find_tree_parents(self.treeView.selectedIndexes()[0], path_list) path_list.reverse() odrive_number = int(path_list[0][-1]) # print(path_list) # print(odrive_number) my_drive = self.my_drive_list[odrive_number] return my_drive def find...
The main task of the code is to dynamically generate a configuration UI layout based on the selected ODrive hierarchy. It processes the selected path depth (1, 2, or 3 levels) to display general settings, member components, or detailed configurations in separate grid columns. The function deletes existing UI elements, ...
def setup_config_window(self): # print("setting up config") try: my_drive = self.select_odrive() except: return path_list = [] path_list = self.find_tree_parents(self.treeView.selectedIndexes()[0], path_list) # print("setting up config") row_index = 0 col_index = 1 first_gpio = True first_conf...
def deleteItems(self, del_layout): try: if del_layout.count() > 0: while del_layout.count(): item = del_layout.takeAt(0) widget = item.widget() if widget is not None: widget.deleteLater() else: self.deleteItems(item.layout()) except Exception as e: print("exception deleting...
The function handles tree item selection by initializing a settings dictionary, removing existing buttons from a layout, adding new action buttons, and setting up a configuration window. It responds to user selection in a tree view, updating the UI to reflect the chosen item's context, though some selection logic is co...
def tree_item_selected(self): self.changed_settings = {} # index = self.treeView.selectedIndexes()[0] # tree_selection = index.model().itemFromIndex(index).text() # print(tree_selection) try: self.deleteItems(self.button_layout) except: pass self.add_action_buttons() self.setup_config_window()
def convertXML(file): excerpt = "http://wordpress.org/export/1.2/excerpt/" content = "http://purl.org/rss/1.0/modules/content/" wfw = "http://wellformedweb.org/CommentAPI/" dc = "http://purl.org/dc/elements/1.1/" wp = "http://wordpress.org/export/1.2/" blogs_root = get_root(file) blog_lis...
The main task of the code is to convert XML data into markdown format and save it to a file. The `main()` function processes input XML by parsing it into a structured format, converts it to markdown using `to_markdown()`, writes the result to a file named 'content' via `save_md_to_file()`, and returns the processed blo...
def main(): blogs = convertXML(inp_xml) md_list = to_markdown(blogs) save_md_to_file(md_list, 'content') return blogs
def init(): global game, player, screen # init screen: lines, columns = get_terminal_size() lines -= 1 + 4 # to fit in cmd properly + score line matrix = [[SPACE_CHR * columns] for j in range(lines)] screen = Screen(lines, columns, matrix) # init game, enemies and player: game = Game(1,...
The main task of this code is to run a game loop that handles keyboard input, updates game state, renders the screen, and maintains a target FPS by introducing delays. It initializes resources, starts a keyboard thread, and continuously cycles through input handling, updates, rendering, and frame-rate control until the...
def main(): init() start_keyboard_thread() running = True while running: start = time.time() # input: keyboard_handler() # update: update() # show on screen: clear_screen() render() # delay: delay = FPS - (time.time() - star...
def _get_obs(self): if self.cheat: return self._get_cheat_obs() else: return self._get_default_obs() def get_velocity(self): # Relies on velocimeter being the first sensor # This is nasty but there really is no beter way than to know sensor offset return s...
This code executes a simulation step in a reinforcement learning environment, applying an action, updating the state, and returning observations, rewards, termination status, and auxiliary info. It tracks robot velocity, computes rewards, checks for a 60-second time limit, and optionally renders the environment.
def step(self, a): self.do_simulation(a, self.frame_skip) # Limit joint velocity to prevent clipping, but do not limit body speed # self.sim.data.qvel[3:] = np.clip(self.sim.data.qvel[3:], -1, 1) ob = self._get_obs() # Keep track of robot velocity during episode vel =...
def dist(self, p1, p2): (x1, y1), (x2, y2) = p1, p2 return math.sqrt((x2-x1)**2 + (y2-y1)**2) def peaks_perperson(self, ndnp, row, maxarr): #mv = ndnp[row][:] maxpositions = maxarr[row][:, np.r_[0:1]].ravel() #maxvalues = maxarr[row][:,1].ravel() return maxpositions def align_data(self, ndnp, pe...
This code processes biometric signal data by detecting peaks, aligning signals based on peak positions, slicing/resampling data between peaks, and exporting processed datasets. It reads CSV data, identifies peak locations, computes peak distances, aligns signals to their first peak, and either resamples data between pe...
def init(self): data = pd.read_csv(os.path.join('processed_data', 'filecgdata.csv')) npdata = np.asarray(data) personid = npdata[:,0] signals = npdata[:,np.r_[1:10000]] #1. detect peaks of signals np.apply_along_axis(self.peak_maxhelper, 1, signals) maxnp = np.asarray(self.maxs) ...
def version(bits): return int(bits[0:3], 2) def type_id(bits): return int(bits[3:6], 2) def is_operator_packet(bits): return not is_literal_packet(bits) def is_literal_packet(bits): return type_id(bits) == 4 def literal_packet_groups(bits): i = 6 while i < len(bits): last_group = bits[i]...
This code parses a binary packet structure, determining if it's a literal or operator packet. For literals, it extracts grouped binary values and computes their integer representation. For operators, it processes subpackets based on length type (total length or number of subpackets), recursively parsing nested packets ...
def __init__(self, bits, debug=False): if len(bits) < 6: self.terminal = True return self.terminal = False self.version = version(bits) self.type_id = type_id(bits) self.is_operator = is_operator_packet(bits) self.is_literal = is_litera...
def save_chosen_positions_to_db(self, positions_to_add, parsing_rules_dict, company): publish_datetime = timezone.now() for position_url in positions_to_add: position_dict = self.parse_position_page(position_url, parsing_rules_dict, company) if 'message' not in position_dict: # ...
This code processes form submissions to add new company positions, validates data, updates the database with new positions, cleans up ignore lists, archives old positions, and renders an admin form with parsed position data for review and submission.
def check_and_get_new_positions(self, request, pk): company = Company.objects.get(id=pk) positions_dict = {} position_dict = {} db_positions_to_archive = {} if request.method == 'POST': form = ParsingPositionsForm(request.POST) if form.is_valid(): ...
def parseInput(filepath: str): with open(filepath) as file: lines = file.readlines() return lines def solutionA(input): arr = generateArray(input) risk = [x[0]+1 for x in findLowPoints(arr)] print(sum(risk)) def solutionB(input): arr = generateArray(input) points = findLowPoints(arr)...
The main task of the code is to parse input data from 'input09', then execute two solutions (A and B) on the parsed input. SolutionA and SolutionB likely process the input to compute distinct results, though their specific logic is not shown. The code structure separates input handling from solution implementation.
def main(): input = parseInput('input09') #input = ['2199943210','3987894921','9856789892','8767896789','9899965678'] solutionA(input) solutionB(input)
def sort(dict): """Sort a dictionary based on values""" newDict = {} values = list(dict.values()) keys = list(dict.keys()) for i in range(len(values)): for j in range(i, len(values)): if(values[i] < values[j]): temp = values[i] values[i] = values[j...
The main task of the code is to generate and write coding statistics to a file named "statistics.txt". It calculates total hours/minutes, identifies the longest coding day, computes daily averages, and lists top languages/projects by time spent. The output includes formatted data on yearly totals, averages, and ranking...
def writeToStatistics(): """Write out statistics to a file called statistics.txt""" f = open("statistics.txt", "w") languages = sort(createLanguagesDict()) combined = combineFiles() projects = sort(getProjects()) time = getTotalTime(combined) hours = (minutesToHours(secondsToMinutes(time))) ...
def compute_updated_costs(n_images: int) -> None: """Each image costs in low resolution processing 85 tokens. Price per 1k tokens = 0.01 input. output = 0.03 per 1k tokens. we only have 10 output tokes """ p_per_input_token = 0.01 / 1_000 p_per_output_token = 0.03 / 1_000 token_per_image_triplet...
The main task of the code is to extract responses from a dataset using a language model. It loads image/concept data, initializes an OpenAI client, and processes prompts to generate responses based on specified parameters like maximum triplets, temperature, and output file paths. The core functionality revolves around ...
def main(args): compute_updated_costs(args.max_triplets) dataloader = create_dataloader( args.image_dir, args.train_fp, args.concepts_fp, args.non_unique_words_fp, args.image_size, args.seed, ) prompt_images = toml.load(args.prompt_images_fp) prompt_...
def get_path_of_directory_file_is_located_in(): directory = os.path.dirname(os.path.abspath(__file__)) return directory def generate_json_output(binsDirectory): output = { "date_last_updated": date.today().strftime("%m/%d/%Y"), "database_name": "torsions_z_score_database", "data": No...
The main task of the code is to generate a JSON file containing torsion angle z-score data from input bin files. It creates a designated output directory, clears any existing files, and writes the structured JSON data with proper formatting and encoding.
def main(): scriptDirectory = get_path_of_directory_file_is_located_in() binsDirectory = os.path.join(scriptDirectory, input_bins_relative_path) exportJSON = generate_json_output(binsDirectory) outputDirectoryPath = os.path.join(scriptDirectory, output_directory) if os.path.exists(outputDirectoryPa...
def _create_cells(self): for i in range(self._num_cols): col_cells = [] for j in range(self._num_rows): col_cells.append(Cell(self._win) ) self._cells.append(col_cells) ...
This code initializes a maze structure by setting up grid parameters, creating cells, breaking entrance/exit walls, and preparing for pathfinding via recursive wall-breaking and visited tracking.
def __init__( self, start, end, x1, y1, num_rows, num_cols, cell_size_x, cell_size_y, win=None ): self._cells = [] self._start = start self._end = end self._x1 = x1 self._y1 = y...
def setCallsMinMax(self): # set minimum and maximum for calls O(n) for call in self.calls.calls: # if the source is lower than the min floor then it cant be bigger than the max floor if call.source < self.callMinFloor: self.callMinFloor = call.source e...
The code initializes an elevator system by processing input calls to determine floor ranges, dividing the building into sectors, and sorting these sectors for efficient elevator assignment. It sets up parameters like minimum/maximum floors, sectors, and prepares for call distribution among elevators.
def __init__(self, numberOfElevators, calls): # receives a list of Calls.Calls self.calls = calls self.callMinFloor = 0 self.callMaxFloor = 0 self.numberOfElevators = numberOfElevators self.sector = [] self.setCallsMinMax() self.setSectors() self.S...
def determine_upsampling_split( self, target_image_size: tuple, max_edgelen: int, overlap: int = 64, enforce_min_size: bool = True, ) -> Tuple[List[np.ndarray]]: """ Returns pixel crop coordinates that cover an area of `target_image_size` in squares...
The code performs decoder optimization by fine-tuning the decoder's weights to minimize the mean squared error (MSE) between the decoded image and the unmasked regions of the reference image, while preserving the masked areas. It handles large images by splitting them into segments, optimizing each segment iteratively,...
def decoder_optimization( self, input_sample: torch.Tensor, reference_img: torch.Tensor, mask: torch.Tensor, n_decoder_opt_it: int = 75, background_preserve_weight: float = 100.0, learn_rate: float = 1e-4, reuse_last_cp: bool = False, max_edgelen: ...
def interpolate_img_mask(self, image, mask, width, height) -> Tuple[torch.Tensor]: """ Given image and mask and desired shape, this function interpolates the image and mask to the desired shape and returns both, as well as a version of the mask further downsampled x8 to be used in the latent s...
The function `multi_scale_generation` edits a masked region in an image using a diffusion model, starting at base resolution and progressively upscaling. It generates content based on a prompt, blends it with the original image, and applies optimizations for seamless integration. Key steps include initial diffusion, mu...
def multi_scale_generation( self, pil_img: Image, pil_mask: Image, prompt: str, margin: float = 1.0, decoder_optimization: bool = False, start_timestep: float = 1.0, upscaling_start_step: float = 0.35, grid_upscaling_start_step: float = 0.25, ...
def binary_array_generator(binary_array): for i in range(x_range*x_range):#Generate a N bit size binary array binary_array.append(str(bin(i)[2:])) for i in range(x_range*x_range):#Make every element of the array have the same lenght by inserting zeroes in front of it binary_array[i]=binary_a...
The code processes user inputs for packet and flit counts, generates binary data arrays, determines router coordinates, creates seeds for LFSR (Linear Feedback Shift Register), computes LFSR results, writes output to a file, and generates a graph for network simulation or routing analysis.
def pressedQPushButton(self): n_packets=int(self.lineEdit_1.text()) n_flits=int(self.lineEdit_2.text()) binary_array=[] binary_array_generator(binary_array) datapath_binary_array=[] datapath_selection(binary_array,datapath_binary_array) format_datapath(binary_ar...
def testSplit(node): bestInfo = 0 bestAttr = -1 for col in range(len(node.data[0]) - 1): info = splitEntropy(node.data, col) if info > bestInfo: bestInfo = info bestAttr = col return bestAttr def getCol(data): feature1 = [] feature2 = [] allFeatures = ...
The code implements the ID3 algorithm to build a decision tree recursively. It checks termination conditions (leaf node, empty data, or zero class counts) and splits the current node using the best attribute (testSplit). For each unique value of the split attribute, it filters data, creates child nodes, and recursively...
def ID3(node): if node.isLeaf: return elif node.rows == 0: return elif node.count[1] == 0 or node.count[2] == 0: return else: node.splitAttr = testSplit(node) for bin in np.unique(getCol(node.data)[3]): bin = int(bin) newData = [] ...
def discretize(allRows): # Sort into bins using sklearn discretizer = KBinsDiscretizer(n_bins=numBins, encode='ordinal', strategy='uniform') discretizer.fit(allRows) newRows = discretizer.transform(allRows) return newRows def ID3(node): if node.isLeaf: return elif n...
The code reads Pokémon statistics and legendary status data from CSV files, discretizes the statistics, combines them with the legendary labels, constructs a decision tree using the ID3 algorithm, and evaluates its accuracy on the dataset.
def main(): stats = [] legendary = [] # Get parent with open('pokemonStats.csv', 'r') as csvfile: reader = csv.reader(csvfile) next(reader) for row in reader: stats.append([int(i) for i in row]) with open('pokemonLegendary.csv', 'r') as csvfile: lege...
def getCol(data): feature1 = [] feature2 = [] allFeatures = [] target = [] for col in range(len(data[0])): for row in data: if col == 0: feature1.append(row[col]) elif col == 1: feature2.append(row[col]) else: ...
The code reads and processes data, discretizes features, constructs a decision tree using the ID3 algorithm, and evaluates its accuracy on the dataset.
def main(): parent = [] # Get parent for row in dataReader: parent.append(row) row[0] = int(row[0]) row[1] = int(row[1]) row[2] = int(row[2]) targets = getCol(parent)[2] data = discretize(parent) rowIt = 0 for row in data: row[len(row) - 1] = int(targ...
def get_modification_date(self, resource_name): if not self.use_in_memory_states: return self.prepare_modification_date(resource_name) try: return self.__modification_dates[resource_name] except KeyError: return self.prepare_modification_date(resource_name) d...
The function retrieves finished game data from a remote source if the local cache is outdated, updating the cache with fresh data when necessary, and returns the stored game data.
def get_finished_games(self, use_cache = False): if not use_cache: local_modification_date = self.get_modification_date(self.RESOURCE_FINISHED) modification_date = self.request_modification_date(self.RESOURCE_FINISHED_URI) if local_modification_date != modification_date: ...
def get_modification_date(self, resource_name): if not self.use_in_memory_states: return self.prepare_modification_date(resource_name) try: return self.__modification_dates[resource_name] except KeyError: return self.prepare_modification_date(resource_name) d...
The function retrieves and merges unfinished game data from two resources, updating local caches if remote data is newer. It fetches main game data and odds, compares modification dates, and merges them on 'id' to return a combined DataFrame.
def get_unfinished_games(self, use_cache = False): if not use_cache: local_modification_date = self.get_modification_date(self.RESOURCE_UNFINISHED) modification_date = self.request_modification_date(self.RESOURCE_UNFINISHED_URI) if local_modification_date != modification_dat...
def move(self, direction: int): """ Move the controllable beans horizontally. Args: direction (int): 1 or -1 (right or left, respectively) Returns: [int]: 0 for failed movement (blocked by other beans or field boundaries). 1 for successful m...
This function executes the movement or rotation of a controllable bean based on the current action (0-5). It processes actions like left/right movement, counter-clockwise/clockwise rotation, and hard dropping. Special handling occurs for action 5, which triggers a hard drop. After executing the action, it resets the ac...
def movement(self): """ Move the controllable bean according to the current action. Action | Effect 0 | Do nothing (for OpenAI Gym) 1 | Move bean left 2 | Move bean right 3 | Rotate counter-clockwise 4 | Rotate clockwise 5...
def dropcheck(self, bean): y = bean[0] x = bean[1] return ((y+1)>12) or (self.field[y+1,x]>0) def move_update(self, x1, y1, x2, y2): """ Update the field and display when the controlled beans move to positions (x1,y1) and (x2,y2). """ # Clear old pixels ...
The main task of the code is to move two hanging beans (bean1 and bean2) downward one space at a time until they can no longer drop, using a loop that checks drop feasibility with `dropcheck()`. It updates their positions, displays the changes, and stores their final coordinates in `dropped_yx`, then increments the pha...
def postdrop(self): """ Move any hanging beans down one space at a time. """ flag1 = True flag2 = True x1 = self.bean1[1] x2 = self.bean2[1] y1 = self.bean1[0] y2 = self.bean2[0] while flag1 or flag2: if flag1 and not self.dro...
def move(self, direction): # See what the hypothetical new coordinates would be y2 = self.bean2[0] x2 = self.bean2[1]+direction y1 = self.bean1[0] x1 = self.bean1[1]+direction if min([x1, x2]) < 0: return 0 if max([x1, x2]) > 5: return 0 ...
This code handles player input for movement and rotation of a game object. It processes keys 'a'/'d' for left/right movement, 'k'/'l' for counter-clockwise/clockwise rotation, and 'w' for hard drop. After executing actions, it resets the pressed key, updates the display, and increments the game phase.
def movement(self): # asd for movement, k to rotate counter, l to rotate clockwise if self.pressed_key == 'a': _ = self.move(-1) if self.pressed_key == 'd': _ = self.move(1) if self.pressed_key == 'k': _ = self.rotate(-1) if self.pressed_ke...
def get_state(): text = read_file(STATE_FILE) state = json.loads(text) ic(state) return state def get_person(name): people = get_people() for this in people: ic(this) if this['name'].lower() == name.lower(): return this print('not found') return None def ...
The main task of the code is to handle shift changes in a system by either specifying a person's name or using the current hour to determine the on-duty individual. It retrieves the current state, checks for a provided name or hour-based assignment, updates the on-duty person if valid, and notifies the user of the chan...
def change_shift(update, context): before = get_state() words = update.message.text.split() if len(words) > 1: name = words[1] on_duty = get_person(name) if on_duty == None: reply_text(update.message, f'The name {name} was not found') else: reply_text(...
def clone(board): #returns clone nboard = [] for row in board: nboard.append([x for x in row]) return nboard def horiz(board): #reflection about y-axis nboard = [] for row in board: nboard.append([x for x in reversed(row)]) return nboard def vert(board): #reflection about x-axis ...
The main task of the code is to check if any symmetry transformation of the input board exists in a predefined dictionary of states. It applies combinations of horizontal/vertical flips and transpositions, generating 8 possible transformations. If a transformed board matches a key in the `states` dictionary, it returns...
def lookup(board): for i in range(8): symboard = clone(board) if i%2 == 1: symboard = horiz(symboard) if (i//2)%2 == 1: symboard = vert(symboard) if i//4 == 1: if dim[0] == dim[1]: symboard = transp(symboard) else: ...
def legal(state, p, z=False): possible = set() failed = set() if min(state) == max(state) and z: for i in range(int((n + 1) / 2)): for j in range(int((m + 1) / 2)): possible.add(i * m + j) return possible for i in range(m * n): possible.add(i) for i in ran...
This code runs a two-player game where players take turns making moves on an m x n grid. It validates moves, updates the game state, alternates turns, and prints the board. The loop continues until no legal moves remain, at which point the current player is declared the loser.
def runGame(): print("---") state = [0] * m * n toMove = -1 a = legal(state, toMove) turns = 0 while a: want = input('Player ' + trans[toMove] + ' move: ') try: want = int(want) except ValueError: pass while want not in a: print...
def lookup(board): for i in range(8): symboard = clone(board) if i%2 == 1: symboard = horiz(symboard) if (i//2)%2 == 1: symboard = vert(symboard) if i//4 == 1: if dim[0] == dim[1]: symboard = transp(symboard) else: ...
The code determines if the current player can force a win in a game (likely similar to Reversi/Othello) by recursively exploring all valid moves, flipping pieces, and using memoization to track previously computed states. It checks for existing results in a lookup table, explores possible moves, and updates global coun...
def solve(board): # returns whether player to move wins if lookup(board) != None: global oldstate oldstate += 1 if oldstate%proginter == 0: print("oldstate: " + str(oldstate)) return lookup(board) winning = False for i in range(dim[0]): for j in range(dim[...
def setData(self): """ Fetches concours,filiers,matieres from the search form""" self.initVisit() self.concours = self.getSelectValues(self.selects["c"]) self.filieres = self.getSelectValues(self.selects["f"]) self.matieres = self.getSelectValues(self.selects["m"]) def fillinYear...
The code automates web scraping by initializing data, filling form fields (year, competition, field, subject), submitting a search, retrieving files, and capturing debug screenshots. The primary task is to extract data from a web form by simulating user interactions and handling the resulting file downloads.
def run(self): Spider = self.Spider # First of all, let's get all the needed data to start scrapping self.setData() ## DEBUG PURPOSES self.fillinYear("2017") self.selectOption(self.selects["c"],self.concours[4][1]) self.selectOption(self.selects["f"],self...
def print_new_session_header(self) -> None: """Print header and instructions for a new session""" self.f.center('', ["BOLD", "BLUE"], '*') self.f.center(' WELCOME TO IQ TESTER ', ["BOLD"], '*') self.f.center('', ["BOLD", "BLUE"], '*', end="\n\n") self.f.center("Start with any one...
This code manages a game session by displaying a main menu, allowing users to start new games, adjust settings, or quit. It initializes game instances, updates session statistics, handles settings changes, and ensures proper formatting and user feedback throughout the session.
def start(self) -> None: """Initiate and manage a new session of games""" self.print_new_session_header() # Infinite loop to keep playing until user quits selection_prompt = "Select a menu option" while True: self.main_menu() main_choice = self.f.prompt...
def print_new_game_header(self) -> None: """Print header rows for a new game""" self.f.center(" START NEW GAME ", fill_char="*", end="\n\n") self.f.center("Each letter in the board represents a peg in a hole.") def remove_one_peg(self) -> None: """Prompt user to choose one peg to remove ...
The code's main task is to manage a peg game by initializing the board, handling user inputs for removing pegs and making moves, checking for game over conditions, and processing valid jumps. It loops through gameplay, displays the board state, handles user choices (including quitting), and executes moves while returni...
def play(self) -> int: """Initiate and handle the game logic""" # Display New Game header self.print_new_game_header() # Print initial board self.b.print_board() # Prompt user to remove one peg self.remove_one_peg() # Gameplay loop while True: ...
def number_of_pegs(self) -> int: """Return the number of pegs remaining on the board""" # The number of pegs is just the number of keys in the PegsMap return len(self.peg_locations_map) def make_move(self, peg: Peg, jump: Jump) -> None: """ Update the board's state for the move ...
This function performs a depth-first search (DFS) to find the optimal solution in a peg solitaire puzzle by recursively exploring all possible move sequences. It tracks the minimum number of pegs remaining and the corresponding move list, updating them when a better solution is found. The algorithm backtracks after eac...
def dfs(moves_taken: List[Move] = []): # Base Case: There are no moves left if not self.moves_map: # Reference global optimal solution variables nonlocal optimal_result nonlocal optimal_moves # Compare result to optimal result ...
def get_random_key_and_iv(): return (get_random_bytes(16), get_random_bytes(16)) def pack(data, key, iv): return base64.b64encode(package_aes_key(key, iv) + encrypt_aes(data, key, iv)).decode('utf-8') def envelope(msg_id=12, data=b""): return message.Envelope(messageId=msg_id, message=data.SerializeToString...
This function securely transmits encrypted data via HTTP. It generates a random key/IV, encrypts an enveloped message containing msg_id and data, sends it as a cookie to a specified URL, then decrypts and extracts the response payload using the same key/IV. The core task is secure message transmission with symmetric en...
def wire(msg_id, data): print("[+] Sending messageId: {}".format(msg_id)) key, iv = get_random_key_and_iv() packed_msg = pack(envelope(msg_id, data), key, iv) r = requests.get(url=GATE_URL, cookies={"id":packed_msg}) return unenvelope(unpack(r.text, key, iv))
def wire(msg_id, data): print("[+] Sending messageId: {}".format(msg_id)) key, iv = get_random_key_and_iv() packed_msg = pack(envelope(msg_id, data), key, iv) r = requests.get(url=GATE_URL, cookies={"id":packed_msg}) return unenvelope(unpack(r.text, key, iv)) def shell_event(self): return me...
This function handles task execution based on `current_taskId`. If the task ID is 16, it generates a response using `shell_event()`; otherwise, it defaults to `knock_event()`. The response is parsed, a counter (`knock_id`) is incremented, and execution pauses for `call_delay` seconds to manage task timing.
def hander(self): if self.current_taskId == 16: wire_response = wire(17, self.shell_event()) else: wire_response = wire(15, self.knock_event()) # default is knock self.parse_response(wire_response) self.knock_id += 1 sleep(self.call_delay)
def get_partial_derivatives(I: np.ndarray, sigma: float) -> list: G = gauss(sigma) D = gaussdx(sigma) D = np.flip(D) G_T = G.reshape([G.shape[1], 1]) D_T = D.reshape([D.shape[1], 1]) I_x = cv2.filter2D(I, -1, G_T) I_x = cv2.filter2D(I_x, -1, D) I_y = cv2.filter2D(I, -1, G) I_y =...
The code computes and visualizes first and second-order image derivatives (I_x, I_y, I_xx, I_yy, I_xy) along with gradient magnitude and direction for a grayscale image. It loads an image, normalizes it, calculates derivatives using specified sigma, and displays all results in a grid with labeled titles.
def test_d(): sigma = 1 # I = imread_gray_cv2("images/museum.jpg", "float64") path = "images/museum.jpg" # assert os.path.exists(path) I = cv2.imread(path, cv2.IMREAD_GRAYSCALE) I = np.asarray(I) I = I.astype(np.float64) / 255 d = get_partial_derivatives(I, sigma) I_x = d[0] I_...
def parse_gpr(register_name, may_fail=False): gpr_str = ["ra", "rb"] register_name = register_name.lower() if register_name not in gpr_str: if may_fail: return -1 print("Unexpected word : {}".format(register_name), file=sys.stderr) print("Expected general purpouse registe...
This function translates assembly transfer instructions into machine code by parsing the destination register and source operand (register, address, or immediate value), determining the appropriate opcode and addressing mode, and emitting the corresponding bytes with relocation handling for addresses.
def inst_trans(line): line.pop(0) # mnemonic dest = parse_gpr(line.pop(0)) source_str = line.pop(0).lower() source_addr = -1 source = parse_register(source_str, True) if source == -1: source_addr = parse_address(source_str, True) if source_addr == -1: if source_str[...
def parse_address(address_str, may_fail=False): if address_str[0] != '[' or address_str[-1] != ']': if may_fail: return -1 print("Unexpected word : {}".format(address_str), file=sys.stderr) print("Expected address in brackets", file=sys.stderr) sys.exit(1) address_str...
This function encodes a store instruction (ST) into machine code. It processes the destination address (handling immediate values/symbolic labels) and source register, constructs the opcode with addressing mode flags, and emits the appropriate bytes along with relocation records for symbolic addresses.
def inst_st(line): line.pop(0) # mnemonic dest_addr = parse_address(line.pop(0)) source_register = parse_register(line.pop(0)) dest_flags = 0b00 if type(dest_addr) is tuple: dest_flags = 0b10 | dest_addr[1] emit_byte(0b10010000 | (dest_flags << 2) | source_register) if dest_flags ...
def zip(self): dbfile = self._get_dbfile("db") if dbfile: zip_filename = dbfile.filename.split(".")[0] + ".bz2" with open(f"data/db/{dbfile.filename}", "rb") as f_in: with bz2.BZ2File(f"data/zip/{zip_filename}", "wb") as f_out: f_out.writelin...
The main task of the code is to compress databases into a zip file, upload it to cloud storage (GCS) with a specific path, and retain only the latest three versions by removing older ones. If no zip file exists, it logs a warning.
def push(self): self.zip() path = "data/zip/" gcs = GCSConnection() dbfile = self._get_dbfile("zip") if dbfile: fname = dbfile.filename fsize = self._get_filesize(path, fname) print(f"db-mgr: Pushing '{fname}' [{fsize:.4f} Mb]...") ...
def _get_dbfile(self, ftype, filenames=None): """Gets latest or specific version as DBFile.""" v = self.args.version if v is None: return self._get_latest_dbfile(ftype, filenames) else: return self._get_version_dbfile(ftype, v) def unzip(self): zipfile = s...
The main task of the code is to download a specified database file from Google Cloud Storage (GCS) to a local directory ("data/zip/"), unzip it, and handle cases where no files are found by logging a warning. It retrieves filenames from GCS, identifies the target database file, downloads it if found, and triggers unzip...
def pull(self): path = "data/zip/" gcs = GCSConnection() source_names = gcs.get_filenames() dbfile = self._get_dbfile(self.comp_type, source_names) if dbfile: fname = dbfile.filename print(f"db-mgr: Pulling '{fname}'...") gcs.download(fnam...
def authUser(messageJSON): if (getID(messageJSON["ip"]) == 0): userIndex = addUser(messageJSON["ip"]) messageToTunnelJSON = json.dumps({ 'userId': userIndex, 'type': messageJSON["type"], 'body': messageJSON["body"] }, indent = 4) with open("proxy_tunnel/messag...
The function processes a message from a JSON file by checking its type and IP address. If the type is AUTH, it authenticates the user. For MSG type, it validates the IP's ID, routing to message tunneling if valid or triggering an error otherwise. For other types, it disconnects based on IP validation. Finally, it delet...
def receiveMessageUser(): if (os.path.exists("user_proxy/message.json")): with open("user_proxy/message.json", "r") as messageFile: messageJSON = json.loads(str(messageFile.read())) if (messageJSON["type"] == Type.AUTH.value): authUser(messageJSON) elif (m...
def check_events(self): for event in pygame.event.get(): if event.type==pygame.QUIT: sys.exit() def check_update_rains(self): self.update_rain() self.rains.update() self.check_rain() def update_screen(self): self.screen.fill(self.settings.bg_color) self.rains.draw(self.screen) pygame.display.flip()
The code defines a `run` method that continuously loops, checking for events, updating rain-related elements, and refreshing the screen to maintain real-time interaction or animation in a game or application.
def run(self): while True: self.check_events() self.check_update_rains() self.update_screen()
def _get_container(state, address): # Get the appropriate container type based on the address namespace = address[6:8] containers = { addresser.AGENT_PREFIX: AgentContainer, addresser.PROPERTY_PREFIX: (PropertyContainer if address[-4:] == '0000' ...
This function processes a proposal response (cancel, reject, accept) by validating the signer's authority, updating the proposal's status in the state, and ensuring only authorized agents perform actions. It retrieves the relevant proposal, checks conditions, modifies the status, and updates the state container.
def _answer_proposal(payload, signer, timestamp, state): record_id, receiving_agent, role, response = payload.record_id, payload.receiving_agent, payload.role, payload.response proposal_address = addresser.make_proposal_address( record_id, receiving_agent) proposal_container = _get_container(state,...
def api_request(request, url: str, data: dict = {}, params: dict = {}) -> requests.Response: token = get_token(request, get_user(request)) return requests.get(url, headers={'Authorization': f'Bearer {token}'}, data=data, params=params ...
The main task of the code is to fetch a user's Spotify playlists via the API, extract key details (name, URL, tracks, etc.), and update or create corresponding records in a database (PLAYLIST_DB) associated with the user. It handles errors by printing messages if the API request fails.
def update_playlist_id(request): url = 'https://api.spotify.com/v1/me/playlists' response = api_request(request, url, params = {'limit': 50}) status, error = error_info(response.status_code) if status: user = get_user(request) for item in response.json()['items']: PLAYLIST_...
def get_playlists(request) -> list: try: return PLAYLIST_DB.get_data( filters={'username_id': get_user(request)}, fields=('playlist_id',), as_list=True, flat=True ) except Exception as e: print(f'Error in Getting Playlist from DataBase : {e...
The function retrieves playlist IDs from a request, iterates through each playlist to fetch its track data, and stores/update track information in a database. It uses the playlist ID and user context to associate tracks with the correct playlist, ensuring data integrity by updating existing entries or creating new ones...
def store_playlists_data(request): pl_ids = get_playlists(request) for pl_num, pl_id in enumerate(pl_ids): tracks_data = store_playlists_tracks(request, playlist_id=pl_id) for track_data in tracks_data: TRACKS_DB.update_or_create( filters={ 'track...
def taboo_vals_rule(board, cell): """ Given a board an cell coordinates tuple. Returns a list of clauses specifying rules of what numbers should not be there. The return rule is a list of clauses where each clause is of the form [((cell, num), False)]. the rules imply that a the given cell must not be...
The function `get_empty_cell_rules` generates constraints for an empty cell on a board by combining three rules: prohibiting taboo values, ensuring the cell is filled at least once, and limiting it to at most one value. It aggregates these rules using `taboo_vals_rule`, `cell_must_be_filled_rule`, and `fill_cell_at_mos...
def get_empty_cell_rules(board, cell): """ Given a board and a cell return a general rule of all clauses that an empty cell alone must satisfy. It cannot be filled with some taboo values, it must be filled with at least once value and it must fille with at most one value at a time """ return taboo_v...
def get_cell(board, r, c): """ Given a board and r,c indices, return the val at the position in the board. >>> board = [ ... [1,2,3,4], ... [5,6,7,8], ... [9,10,11,12], ... [13,14,15,16] ... ] >>> [get_cell(board, r,c) for r in range(0,3) for c...
The function generates constraints for a Sudoku board by compiling rules for each cell. Existing cells enforce fixed values, while empty cells ensure valid placements (no duplicates in rows, columns, or 3x3 grids) and require at least one possible value. It combines these rules into a list for solving or validating the...
def get_all_cell_rules(n): """returns rules for every cell such that existing cells must maintain their values. Empty cells must be filled with at least one value, filled with at most one value, and must not be filled up with recurring row,column,grid values""" all_existing_cell...
def find_new_games(): new_games = scrape_matches() new_games.reverse() print("\nNew Games:",len(new_games)) for game in new_games: db.insert_game('raw', game) def match_details(): print("Getting missing matches") games = db.get_missing_matches() gameNum = 0 gamesTotal = len(games...
The main task of the code is to execute three functions sequentially: finding new games, fetching match details, and updating predicted matches. The `main()` function orchestrates these tasks with logging statements to indicate progress through each step, ensuring a structured workflow for processing game-related data.
def main(): print("Finding New Games...\n") find_new_games() print("Fetching Match Details...\n") match_details() print("Checking Finished Matches...\n") update_predicted_matches()
def print_menu(self, selected_row_idx): self.stdscr.clear() for idx, row in enumerate(self.menu): x = self.screen_width // 2 - len(row) // 2 y = self.screen_height // 2 - len(self.menu) // 2 + idx if idx == selected_row_idx: self.color_print(y, x, row,...
The code implements a curses-based menu-driven interface for encoding/decoding messages. It handles navigation, displays splash messages, confirms exit actions, and processes user input to either encode text (saving encrypted output) or decode pre-encoded files, displaying results with colored text formatting.
def main_loop(self, stdscr): # turn off cursor blinking curses.curs_set(0) # color scheme for selected row curses.init_pair(1, curses.COLOR_BLACK, curses.COLOR_WHITE) curses.init_pair(2, curses.COLOR_GREEN, curses.COLOR_BLACK) curses.init_pair(3, curses.COLOR_YELLOW, cur...
def privateChat(): global skype global PMFlag # PM messages statements_1 = ["hi", "hey", "good day", "hello", "yoo"] statements_2 = ["how are u", "how are you", "how are you doing?", "what's up?"] PM = MI.locateCenterOnScreen('images/skills/pm.png', confidence = 0.70, region = (730, 157, 50, 30...
This code automates battling specific game bosses using image recognition. It detects bosses via screenshots, triggers attacks/abilities, tracks battle stats (kills/losses), and manages game interactions like healing and post-battle actions. The loop continues until 20 battles or exit conditions are met, with resolutio...
def Boss(): privateChat() if screen_width != 800 and screen_height != 600: print("Invalid resolution. Only 800x600 is supported.\t") PlayerFlag = False battleOver = False numPlayers = 0 victory = False global Human global turns numBattles = 0 kills = 0 lo...
def privateChat(): global skype global PMFlag # PM messages statements_1 = ["hi", "hey", "good day", "hello", "yoo"] statements_2 = ["how are u", "how are you", "how are you doing?", "what's up?"] PM = MI.locateCenterOnScreen('images/skills/pm.png', confidence = 0.70, region = (730, 157, 50, 30...
The code automates gameplay in a game by detecting screen elements to initiate and manage battles, track stats (kills, losses), and execute pre-defined actions (clicks) during combat. It enforces a specific resolution, handles battle loops, and logs performance metrics while using image recognition to interact with the...
def Boss(): privateChat() if screen_width != 800 and screen_height != 600: print("Invalid resolution. Only 800x600 is supported.\t") PlayerFlag = False battleOver = False numPlayers = 0 victory = False global Human global turns numBattles = 0 kills = 0 lo...