dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def _initcolor(self, r, g, b): if not hasattr(self, "nccolori"): self.nccolori = 24 self.nccolori += 1 self.log( f"Initializing color {self.nccolori} as r {r}, g {g}, b {b}", 8 ) curses.init_color(self.nccolori, r, g, b) return self.nccolori def lo...
The main task of the code is to validate and initialize color configurations and color pairs. It processes color values from the configuration, ensuring they are valid hex strings, converts them to scaled integers, and stores them in a dictionary. Then, it initializes color pairs by resolving foreground/background colo...
def init_cpairs(self): # Initialize colors colors = dict(self.config.colors) for c in colors: if ( len(colors[c]) != 7 or not colors[c].startswith("#") or not colors[c].lower().strip("bxbethav3gg99btw8s6h693ngtrj7ao2") == "#" ...
def draw_header(self): self.wins.header.clear() header_text = f"{self.metainfo['pkgname']} v{self.metainfo['version']}" header_text = header_text[: curses.COLS - 1].center(curses.COLS - 1) if not hasattr(self.flags, "header"): self.flags.header = True self.log(f"D...
The main task of the code is to handle user input in a curses-based interface by processing keypresses, managing escape sequences, updating the UI (header/footer), and responding to input events like resizing, Enter, Backspace, or transmitting characters, while logging unrecognized inputs and breaking loops on specific...
def run(self): curses.update_lines_cols() footer_buffer = "" multichar_escape_reader_chars_left = 0 multichar_escape_reader_chars_buffer = "" while True: self.draw_header() self.draw_footer(footer_buffer) self.pobj.draw() self.wins....
def init_windows(self): self.wins.center = curses.newwin(curses.LINES - 2, curses.COLS, 1, 0) self.wins.header = curses.newwin(1, curses.COLS, 0, 0) self.wins.footer = curses.newwin(1, curses.COLS, curses.LINES - 1, 0) if hasattr(self, "pobj"): self.pobj.setWin(self.wins.cent...
This code initializes a curses-based application by setting up windows, logging, and color pairs. It configures the screen, initializes a logger, loads metadata, sets up processing objects, and prepares color pairs for display. The main task is to prepare the environment for a terminal-based interface with logging and ...
def __init__( self, stdscr: _curses.window, logfile, metainfo, pobj, log_verbosity=1, dev=False, ): self.wininfo = (curses.LINES, curses.COLS) self.stdscr = stdscr self.wins = GenericObject() self.init_windows() self.p...
def get_image_sources_and_reorder_stream_names(self): self.stream_names.clear() image_sources = [] for stream in self.stream_scheduling: stream_name = streamid_to_name(stream[self.current_block]) image_sources.append(STREAM_DICT[stream_name]["image_source"]) s...
The function retrieves images from specified sources by preparing requests with defined quality and pixel formats, sending them to an image client, and handling timeouts by resetting the client after five consecutive failures. It returns the image response or raises exceptions for other errors.
def get_images_from_spot(self): image_sources = self.get_image_sources_and_reorder_stream_names() self.update_current_block() requests = [ build_image_request(source, quality_percent=self.jpg_quality, pixel_format=self.pixel_format) # image_format=jpeg for source in imag...
def avg_rating_deviation(self,grouped_df,Candidate_Groups,final_df): no_of_reviews=0 total_num_reviews=[] average_rating_product = collections.defaultdict(list) average_rating_product_group = collections.defaultdict(list) Review_tightness=[] ...
The main task of the code is to compute and combine multiple features (e.g., group deviation, burst ratio, content similarity) to evaluate candidate groups, calculate a suspicious score, sort groups by this score, and return the sorted results alongside predictions. It processes group data, applies statistical and simi...
def compute_features(self): for i in self.Candidate_Groups: self.Candidate_Groups[i] = list(map(int, self.Candidate_Groups[i])) final_df=pd.DataFrame(columns=['Groups']) for i in self.Candidate_Groups: final_df.loc[i,'Groups']...
def info2(self, msg, sleep_time=None, end=''): if sleep_time is None: sleep_time = self.sleep_time msg = self.str_color(msg, style=86) print(msg, flush=True, end='\n' + end) time.sleep(sleep_time) def color_from_type(self, v): v_color = '' if type(v) in self.type_colors: v_color = s...
This code allows users to modify a selected parameter's value, displaying its details (description, allowed types, etc.), validating input, and handling static vs. live parameters differently. It either applies changes immediately (live) or requires confirmation/reboot (static), with feedback on validity and value upda...
def change_parameter(self, choice): while True: chosen_key = list(self.params)[choice] param_info = self.op_params.fork_params[chosen_key] old_value = self.params[chosen_key] if not param_info.static: self.info2('Chosen parameter: {}{} (live!)'.format(chosen_key, COLORS.BASE(207)), ...
def update_lane_bounds(self): # todo: run this at half the rate of lane_speed # todo 2: add dPoly offsetting to lane bounds here as well, from group_tracks lane_width = self.sm['pathPlan'].laneWidth if isinstance(lane_width, float) and lane_width > 1: self.lane_width = min(lane_width, 4.5) # LanePla...
The code continuously processes real-time car data (speed, steering angle, path planning) to update lane speed control logic, checks for button inputs, maintains a fixed update rate (LANE_SPEED_RATE), and sends status updates. It ensures timely execution by sleeping if not lagging, otherwise logging delays.
def start(self): while True: # this loop can take up 0.049_ seconds without lagging t_start = sec_since_boot() self.sm.update(0) if self.sm.updated['laneSpeedButton']: self.button_updated = True self.v_ego = self.sm['carState'].vEgo self.steer_angle = self.sm['carState'].stee...
def info(self, msg, sleep_time=None, end=''): if sleep_time is None: sleep_time = self.sleep_time msg = self.str_color(msg, style='info') print(msg, flush=True, end='\n' + end) time.sleep(sleep_time) def color_from_type(self, v): v_color = '' if type(v) in self.type_colors: v_color ...
This code runs a loop to display and allow user editing of parameters, either live-tunable or static. It formats parameters with colors, truncates long values, and handles user input for editing, toggling live mode, or exiting. The loop updates parameter values and display dynamically based on user choices and live_tun...
def run_loop(self): while True: if not self.live_tuning: self.info('Here are all your parameters:', sleep_time=0) self.info('(non-static params update while driving)', end='\n', sleep_time=0) else: self.info('Here are your live parameters:', sleep_time=0) self.info('(chan...
def success(self, msg, sleep_time=None, end=''): if sleep_time is None: sleep_time = self.sleep_time msg = self.str_color(msg, style='success') print(msg, flush=True, end='\n' + end) time.sleep(sleep_time) def prompt(self, msg, end=''): msg = self.str_color(msg, style='prompt') print(msg,...
This code initializes the command line editor by checking if a username is set. If not, it prompts the user to provide a Discord username for crash debugging, with options to accept, decline, or skip future prompts. If a username is provided, it stores it for future use. Finally, it welcomes the user and launches the m...
def run_init(self): if self.username is None: self.success('\nWelcome to the {}opParams{} command line editor!'.format(COLORS.CYAN, COLORS.SUCCESS), sleep_time=0) self.prompt('Would you like to add your Discord username for easier crash debugging for the fork owner?') self.prompt('Your username is...
def average_slope_intercept(self, lines): left_lines = [] right_lines = [] if lines is None: return None, None for line in lines: for x1, y1, x2, y2 in line: if x1 == x2: continue slope = (y2 - y1) / (x2 - x1)...
This code processes an input image to detect lane lines, calculates the vehicle's steering angle based on lane position, smooths the angle using a buffer, and controls the car's front wheels. It returns the processed image with lane markings and center offset visualization.
def follow_path(self, image): thresholded_img_future = self.executor.submit(self.preprocess_image, image) thresholded_img = thresholded_img_future.result() lines_future = self.executor.submit(self.detect_lines, thresholded_img) lines = lines_future.result() left_lane, right_lane...
def add_respondent(rsp_info, sess_type, country, lang, pnum, spoc, rcr_name=None): # project_templates - dict of all time zones, and pc equivalents rsp_name = rsp_info["rsp_name"] invite_name = rsp_info["invite_name"] display_name = rsp_info["display_name"] rsp_date = datetime.strptime(rsp_info["dat...
The main task of the code is to process respondent records from JSON files, performing actions like adding, deleting, or rescheduling respondents based on their "row_color" (yellow, red, green), while collecting any errors encountered during these operations. It maps dates to project numbers, uses session details from ...
def gridmaster(master_num): with open("./json_templates/rsp_combo_details.json", "r") as file: data = json.load(file) rsps = data["grid_rsps"] with open("./json_templates/project_details.json", "r") as file: details = json.load(file) session_type = details["session-type"] ...
def createMenuBar(self): menuBar = self.menuBar() self.setMenuBar(menuBar) #create menu using QMenu fileMenu = QMenu("&File", self) self.openaction = QAction("open", self) self.openaction.setShortcut("Ctrl+O") self.undoaction = QAction("undo", self) self....
This code initializes a MainWindow for an image editor application by setting up the window title, menu bar, action connections, image display area, and UI layout. It creates a progress bar and arranges the image window, top control group, and progress bar using a grid layout. The central widget is set to a container w...
def __init__(self, parent=None): super(MainWindow, self).__init__(parent) self.setWindowTitle("Image Editor") self.createMenuBar() self.connectActions() self.createImageWindow() self.createTopGroup() self.pbar = QProgressBar(self) self.pbar.setGeomet...
def get_bintarget(x, y, target): y_bin = np.zeros([target.size, y.size], np.int8) for i in range(y_bin.shape[0]): y_bin[i] = list(map(lambda x: 1 if x == target[i] else 0, y)) return y_bin def set_errorepoch(error, epoch, x, weight, y_bin, target): for i in range(target.size): error[epoch][i] = loss_log(get_vec...
This function trains a neural network using batch gradient descent to minimize error between predicted and target outputs. It initializes random weights, iterates over epochs, updates weights based on calculated deltas, and stops early if error falls below a threshold. The network shuffles data each epoch and adjusts w...
def learning_nn(x, y, target, epochs, alpha, batch, eborder): weight = np.random.random(x.shape[1] + target.size - 1) delta = np.zeros(weight.size, np.float32) error = np.zeros([epochs, target.size], np.float32) y_bin = get_bintarget(x, y, target) cursor = 0 for epoch in range(epochs): set_errorepoch(error, epo...
def check_argv(argv): argv_len = len(argv) if not argv_len: print("\033[31mNeed input train dataset\033[37m") exit() if argv_len > 2: print("\033[31mToo many arguments\033[37m") exit() if (argv_len == 2 and argv[1] != '-g') and\ (argv_len == 2 and argv[1] != '-graph'): print("\033[31mUnknown key\033[37m...
The code trains a neural network using input data, preprocesses features, saves model weights, and optionally visualizes results. It reads data, normalizes features, trains the network with specified parameters, stores weights in a dump file, and generates a graph comparing original and processed data if enabled.
def main(argv): source, graph = check_argv(argv) print('reading data...') target, x, y = read_data(source) if graph: x_origin = x.copy() print('learning nn...') x_minmax, x = prepare_features(x) epochs = 300 alpha = 0.01 batch = 500 eborder = 0.12 weight = learning_nn(x, y, target, epochs, alpha, bat...
def advance(self) -> str: c: str = self.source[self.current] self.current+=1 return c def _addToken(self, tokenType: TokenType): self.addToken(tokenType, None) def match(self, expected: str) -> bool: if (self.isAtEnd()): return False if (self.source[self.curre...
This function scans a single character from the input, identifies its corresponding token type (e.g., parentheses, operators, symbols), and adds it to the token list. It handles multi-character tokens like '!=' and '>=', processes comments with '/', manages strings, numbers, identifiers, and skips whitespace. Unexpecte...
def scanToken(self) -> None: char: str = self.advance() if (char == "("): self._addToken(TokenType.LEFT_PAREN) elif (char == ")"): self._addToken(TokenType.RIGHT_PAREN) elif (char == "{"): self._addToken(TokenType.LEFT_BRACE) elif (char == "}"): self._addToken(TokenType.RIGHT_BR...
def select_piece(self, row, col): is_edge = self.game_controller.is_edge_piece(row, col) is_empty = self.game_controller.is_empty_piece(row, col) can_rechoose = self.game_controller.can_rechoose_piece(row, col) if is_edge and (is_empty or can_rechoose): self.undo_button.confi...
This code handles button clicks in a game, allowing a player to select a piece or make a move. If the current player is AI, it triggers the AI's move, updates the game state, displays changes, and checks for game over. The function manages both user and AI interactions, ensuring proper game flow and UI updates.
def on_button_click(self, row, col): if not self.is_choosing: self.select_piece(row, col) else: self.choose_position(row, col) if isinstance(self.game_controller.current_player, AIPlayer): ai_move = self.game_controller.get_ai_move() ...
def line_array(x): upper, lower = [], [] for y in range(5, len(x) - 5): s_a, s_p = strtline(y, x) e_a, e_p = endline(y, x) if s_a >= 7 and s_p >= 5: upper.append(y) if e_a >= 5 and e_p >= 7: lower.append(y) return upper, lower def refine_array(array_up...
This code performs image segmentation on an input image to detect and isolate characters. It resizes the image, applies adaptive thresholding, removes noise via morphological operations, identifies lines, and segments individual characters using contour detection. The process includes line refinement, average letter wi...
def image_segmentation(filepath): print("\n........Program Initiated.......\n") # src_img = cv2.imread(filepath, cv2.IMREAD_GRAYSCALE) src_img = cv2.imread("input.png", -1)[:, :, 3] if len(set(src_img.flatten())) == 1: src_img = cv2.imread("input.png", -1)[:, :, 0] orig_height, orig_width = ...
def check(self, first_name, last_name, email): self.check_empty(first_name, "first name") self.check_empty(last_name, "last name") self.check_empty(email, "email") self.check_email(email) def add_phones(self, phones): for p in phones: self.phones.append(Phone(p)) def ...
The code initializes a Person object by validating and assigning attributes like first name, last name, year of birth, and email. It processes phone numbers via add_phones(), handles address formatting with add_address(), and generates a unique ID through id_increment(). The main task is to create a structured person i...
def __init__(self, first_name, last_name, year_of_birth, email, address, phones): """the init function to initialize the person object""" self.check(first_name, last_name, email) self._first_name = first_name self._last_name = last_name self._year_of_birth = year_of_birth ...
def checkout_java_acc(force): """ Check out the Java API Compliance Checker. If 'force' is true, will re-download even if the directory exists. """ acc_dir = get_java_acc_dir() if os.path.exists(acc_dir): logging.info("Java ACC is already downloaded.") if not force: return logging.info("Fo...
The main task of the code is to run a Java API Compliance Checker by parsing command-line arguments, configuring JAR filters, managing project builds, and executing compatibility checks between specified source and destination Git revisions. It handles dependencies, directory setup, build processes, and applies include...
def main(): """Main function.""" logging.basicConfig(level=logging.INFO) parser = argparse.ArgumentParser( description="Run Java API Compliance Checker.") parser.add_argument("-f", "--force-download", action="store_true", help="Download dependencies (i.e. Java J...
def red_color(): print(Fore.RED) def choose_disaster_option(): spaceship.current_disaster = random.choice(disaster_list) # solar flare disaster scenario if spaceship.current_disaster == 'solar_flare': red_color() slowprint('Disaster: Solar Flare') white_color() fastprint...
This function clears the console, displays a spaceship graphic, applies red color formatting, presents disaster options to the user, and transitions to a new planet scene, likely part of a text-based game or simulation handling space disaster scenarios.
def disaster_scene(): os.system('cls') print(spaceship) print('---------------------------') red_color() choose_disaster_option() new_planet_scene()
def blue_color(): print(Fore.BLUE) def green_color(): print(Fore.GREEN) def white_color(): print(Fore.WHITE) def try_probes(): if planet.unlocked == True: planet_scene() if spaceship.scientific_probes <= 0: playsound('no_more_probes_left.mp3') planet_scene() elif spaceshi...
The code presents a menu for a spaceship simulation, allowing the user to choose between sending a probe, attempting a landing, or continuing exploration. It clears the screen, displays game elements (spaceship, planet), and uses color formatting for visual feedback. Based on user input, it triggers corresponding actio...
def make_choice(self): os.system('cls') print(spaceship) print('--------------------------') print(planet) blue_color() print('1 to send probe') print('2 to attempt landing') print('3 to keep searching') green_color() self.answer = input('T...
def at_const_V(V, dat_abc, dat_eos): dat = dat_eos nd = dat.shape[0] entropies = dat[:,0] energies = np.empty(nd) for i in range(nd): E0 = dat[i,1] B0 = dat[i,2] BP = dat[i,3] V0 = dat[i,4] energies[i] = func_UV(V, E0,B0,BP,V0) [a,b,c] = fit_US(entropies,e...
The code calculates thermodynamic potentials and properties (volume, entropy, pressure, temperature, internal energy, Helmholtz free energy, enthalpy, Gibbs free energy) using given temperature, volume, and material data. It first derives constants [a,b,c], computes entropy S, then evaluates all potentials via the pote...
def potential_A(T, V, dat_abc, dat_eos): [a, b, c] = at_const_V(V,dat_abc,dat_eos) S = func_ST(T, a, c) [V, S, p, T, U, A, H, G] = potential_U(S, V, dat_abc,dat_eos) return [V, S, p, T, U, A, H, G]
def at_const_S(S, dat_abc, dat_eos): dat = dat_abc nd = dat.shape[0] volumes = dat[:,0] energies = np.empty(nd) for i in range(nd): a = dat[i,1] b = dat[i,2] c = dat[i,3] energies[i] = func_US(S,a,b,c) [E0, B0, BP, V0] = fit_UV(volumes, energies, dat_eos) retu...
The code calculates thermodynamic properties (volume, temperature, internal energy, etc.) at given entropy $ S $ and pressure $ p $ using material parameters. It first determines reference values $ E0, B0, BP, V0 $, computes volume $ V $ via $ func\_Vp $, then derives all thermodynamic quantities through $ potential\_U...
def potential_H(S, p, dat_abc, dat_eos): [E0,B0,BP,V0] = at_const_S(S,dat_abc,dat_eos) V = func_Vp(p,B0,BP,V0,dat_abc) [V, S, p, T, U, A, H, G] = potential_U(S, V,dat_abc,dat_eos) return [V, S, p, T, U, A, H, G]
def potential_H(S, p, dat_abc, dat_eos): [E0,B0,BP,V0] = at_const_S(S,dat_abc,dat_eos) V = func_Vp(p,B0,BP,V0,dat_abc) [V, S, p, T, U, A, H, G] = potential_U(S, V,dat_abc,dat_eos) return [V, S, p, T, U, A, H, G] def fit_US(entropies, energies, dat_abc): guess_abc = dat_abc[0,1:] popt, pcov = cur...
The code calculates thermodynamic potentials (enthalpy, Gibbs free energy, etc.) by iterating through entropy data, fitting parameters to enthalpy values, and computing final properties using the fitted model. It returns all derived thermodynamic variables after processing input data and pressure.
def potential_G(T, p, dat_abc, dat_eos): temperature = T pressure = p nd = dat_eos.shape[0] entropies = dat_eos[:,0] enthalpies = np.empty(nd) for i in range(nd): [V,S,p,T,U,A,H,G] = potential_H(entropies[i],pressure,dat_abc,dat_eos) enthalpies[i] = H [a,b,c] = fit_US(entropi...
def getPlayerID(linkTag): r = requests.get(address + linkTag["href"]) soup = BeautifulSoup(r.text, "html.parser") subtitle = soup.find("div", {"class": "subtitle"}) profile = subtitle.find("a") playerID = cutProfilePath(profile["href"]) return playerID def getSeries(stat): return stat[len("s...
The main task of the code is to parse a match webpage by extracting player IDs and game series data. It fetches the webpage, identifies two players via HTML links, retrieves JavaScript-embedded statistics using regex, processes them into structured game objects, and returns player IDs along with the parsed game data.
def parseMatchPage(path): games = [] r = requests.get(path) # players soup = BeautifulSoup(r.text, "html.parser") p1 = soup.find("a", {"id": "lnk1"}) id1 = getPlayerID(p1) p2 = soup.find("a", {"id": "lnk3"}) # why lnk3 :/ id2 = getPlayerID(p2) # scores stats = re.findall(regex, r...
def parse_instructions(data): return [ (d.split(' ')[0], int(d.split(' ')[1])) for d in data.splitlines() ] def solution_1(instructions): head = Rope((0, 0)) tail = Rope((0, 0)) knots = [head, tail] for inst in instructions: for _ in range(inst[1]): knots = m...
(The code processes input data by parsing it into instructions, then applies two distinct solutions to these instructions, returning both results.)
def solution(data): instructions = parse_instructions(data) sol_1 = solution_1(instructions) sol_2 = solution_2(instructions) return sol_1, sol_2
def vni_vxi(atoms, bonds, edges): vni, _ = mask_atoms_by_degree(atoms,edges,bonds = bonds) summed_bond_features = np.sum(bonds, axis=-2) vxi = np.concatenate([atoms, summed_bond_features], axis=-1) return vni, vxi def stage_creator(model_params, layer, conv=True): """ Returns a set of stage I or...
The code trains a multistage autoencoder for molecular data, iteratively building layers with two stages: Stage I uses graph convolutions to encode SMILES into node/edge features, while Stage II generates molecular fingerprints from these encodings. Each layer adds complexity, saving encoder weights. The model learns h...
def multistage_autoenc(smiles_x, num_layers, params, train_params): # Create empty lists for outputs #val_losses = [] # X_atom, X_bond, X_edge = tensorise_smiles(smiles_x[:2], max_degree=5, max_atoms=60) print('Processing SMILES...') #X, val = train_test_split(smiles_x, test_size=train_params["valid...
def add_data_to_plot(ax): rhs_col, lhs_col = "tab:blue", "red" plot_lhs_data(ax, lhs_col) plot_rhs_data(ax, rhs_col) def set_xy_lables(ax, xlabel, ylabel): xlim, ylim = ax.get_xlim()[1], ax.get_ylim()[1] ax.annotate(xlabel, xy=(xlim * 0.0, ylim * -0.3), annotation_clip=False, fontsize='35', ha='cent...
The code generates a plot with customized axes, labels, and data, saving it as 'predictions.png'. It creates a figure with specific dimensions, sets axis limits, adds data, and applies styling (labels, ticks, grid) based on the 'simple' flag, then exports the plot.
def plot(): x_len = 10.0 fig = plt.figure(figsize=(x_len/2.0 , x_len / 2.0)) ax = fig.add_subplot(111, xlim=(-1, 1), ylim=(0, 1)) add_data_to_plot(ax) xlab, ylab = r"$\chi_{\rm{eff}}$", r"$q$" simple = True if simple: set_xy_lables(ax, xlab, ylab) remove_axes_splines(ax) ...
def assign(self, orderId, startTimeSlot): if not self.isFeasableToAssignOrderToStartAtTimeslot(orderId, startTimeSlot): return False for j in range(self.orders[orderId].length): self.schedule[orderId][startTimeSlot + j] = 1 self.updateFitness() return True def getRating(sel...
The code generates feasible assignments for a given order by iterating through possible start times, checking validity via `assign()`, and collecting valid `Assignment` objects with calculated fitness and ratings.
def findFeasibleAssignments(self, orderId): feasibleAssignments = [] order = self.orders[orderId] min_start = max((order.min_deliver - order.length), 0) for j in range(min_start, order.max_deliver - order.length +1): feasible = self.assign(orderId, j) if not feasi...
def set_doc_styles(doc): # text set_style(doc, 'Default Paragraph Font', type="character", italic=False) set_style(doc, 'Normal', indent=0.5, space_after = 6) # date set_style(doc, 'Heading 1', bold=True, alignment = WD_ALIGN_PARAGRAPH.CENTER) # topic set_style(doc, 'Heading 2', bold=True) ...
The code generates a Word document report by iterating through specified topics, updating status labels during processing, and saving the report with a date-stamped filename in a 'reports' directory. It creates the directory if missing and returns the file path.
def generate_report(status_label, root, topics, pages, num_days): doc = Document() set_doc_styles(doc) heading = doc.add_heading(date.today().strftime("%B %d, %Y"), 1) for topic in topics.keys(): result = update_status(root, status_label, f"Searching for topic: {topic}...") result = t...
def unquote_bool_values(input_string): """ Change in eggPlant 21.2.0 - bool values inside a list get quoted [false, true] --> ["False", "True"] """ s = input_string.replace('"True"', 'True') s = s.replace('"False"', 'False') log.debug(f"Removed double quotes around possible bool values in the li...
The function `auto_convert` attempts to convert a string into a Python data type, primarily for processing eggPlant result strings. It handles lists by converting "True"/"False" to booleans, removing '@' symbols before quotes, and using `ast.literal_eval` for parsing. If parsing fails, it quotes non-digital values and ...
def auto_convert(s): """ Tries to convert the input value into one of Python data types. This function is designed specially for converting eggPlant result strings in the 'RunWithNewResults' mode. Values of a list get special processing: - String values "True" and "False" are converted into boolean...
def getWeather(res): print(res, 'res from lambda\n') if res[0] == 'err': return {'err': "sorry didnt understand you, please try another location"} try: req = requests.get( f"http://api.openweathermap.org/data/2.5/forecast?lat={res[1]}&lon={res[0]}&appid={os.getenv('WEATHER_APP_AP...
The code processes chatbot interactions by retrieving user messages and chat data, checking for specific actions (weather, crypto, riddle) in the chat. It handles these actions by fetching coordinates, crypto prices, or validating riddle answers, updating the chat state, and returning formatted responses. If no action ...
def chatbot(): # print(msg) msg = request.args.get('msg') user_id = request.args.get('user_id') chat_id = request.args.get('chat_id') # check to see if theres a type in the chat data chat = chats_db.find_one({"_id": ObjectId(chat_id)}) # print('\n chat:', chat) if chat['typeAction'] != ...
def compute_sliced_distance(self, X, Y, weights=None, projections=None, num_projections=1000, r=1, device='cuda', proj_out=False): if proj_out: X_projections, Y_projections, directions = self.slice.get_slice(X, Y, projections=projections, num_projections=num_projections, r=r, device=device, proj_out...
The code computes a distance metric between two datasets `X` and `Y` based on the `self.ftype` parameter, which determines the method: sliced, max-sliced, max-sliced-eig, or distributional-sliced. It delegates to specialized helper functions (`compute_sliced_distance`, etc.) to calculate the distance using projections,...
def compute(self, X, Y, weights=None, projections=None, num_projections=100, r=1, f=None, f_op=None, lam=1, iter=100, device='cuda', proj_out=False): if self.ftype == 'sliced': d = self.compute_sliced_distance(X, Y, weights=weights, projections=projections, num_projections=num_projections, r=r, devi...
def find_e(board): # go through each row and column for r in range(9): for c in range(9): # find the interested space, if 0 then it is empty space = board[r][c] if space == 0: return (r, c) return None def valid(board, num, pos: tuple): r, c = pos[0], pos[1] ess_spac = find_spaces(board, r, c) if n...
This function solves a Sudoku puzzle using backtracking. It recursively finds empty cells, tries valid numbers (1-9), and checks constraints. If a number is valid, it places it and continues solving. If no solution exists, it backtracks by resetting the cell. The process repeats until the board is fully solved or all p...
def solve_sodoku(board: list[list]): find = find_e(board) if not find: return True else: r, c = find for inp in range(1, 10): tandf = valid(board, inp, (r, c)) if tandf: board[r][c] = inp if solve_sodoku(board): return True board[r][c] = 0 return False
def cbz_path(series, volume, chapter, directory): fname = '_'.join([series, volume, chapter]) + '.cbz' return os.path.join(directory, fname) def download_chapter(series, volume, chapter, directory): url = url_from_chapter(series, volume, chapter) + '1.html' tree = html.parse(url) pages = pages_in_ch...
The function `download_volume` downloads chapters from a specified series and volume, checks if a CBZ file for each chapter already exists in the given directory, and if not, downloads the chapter's pages, stores them in a temporary directory, and creates a ZIP archive (CBZ file) for the chapter.
def download_volume(series, volume, chapters, directory): for chapter in chapters: chapter = chapter['number'] with tempfile.TemporaryDirectory() as tmpdir: print('Downloading chapter ', chapter) print(series, volume, chapter, tmpdir) cbz_p = cbz_path(series, volu...
def series_from_url(url): return re.search(r'http:\/\/mangafox\.me\/manga\/(\w+)\/?.*' , url).group(1) def volumes_from_url(url): '''url = http://mangafox.me/manga/binbougami_ga/''' tree = html.parse(url) sid_ = sid(tree) volume_script = script_from_sid(sid_) return volumes_...
The code's main task is to download all volumes of a series from a given URL into a specified directory. It retrieves the series data and volume list from the URL, then iterates through each volume, printing its name and triggering the download process using `download_volume` with the series, volume title, and volume-s...
def download_series(url, directory): series = series_from_url(url) volumes = volumes_from_url(url) for volume in volumes: print('Downloading volume ', volume) download_volume(series, volume, volumes[volume], directory)
def permute(x, perm_table): y = BitString() for n in perm_table: y += x[n-1:n] return y def splitToN(x, n): """ Splits a bitstring x into n pieces of equal len Returns a tuple of n pieces """ l = x.len return tuple(x[(l*i//n):(l*(i+1)//n)] for i in range(n)) def transform(C, ...
This code implements the Data Encryption Standard (DES) algorithm for encrypting or decrypting a 64-bit input using a 64-bit key. It applies initial permutation, splits the input/key into halves, generates 16 subkeys via permutation and rotation, processes data through 16 Feistel rounds with round functions, and applie...
def des(x, k, enc=True): """ des function @param x BitString length=64: input (Plaintext if enc==True else Ciphertext) @param k BitString length=64: 64-bit Key @param enc bool: True if encrypt mode; False if decrypt mode @return y BitString """ # initial permutation of...
def _view_helper_markdown(self): display_fields = self._get_display_fields(note=self.NOTE) target, error, meta = self._markdown_to_html(self.NOTE.source) display_fields['target'] = target display_fields['editable'] = (self.NOTE.owner==self.HANDLER.USER ...
This function determines if a user can view a note based on access level and note ownership/public status. If allowed, it generates formatted display data using markdown, splits content into slides if needed, selects the appropriate HTML template (view, slides, or page), and renders the note with the correct layout and...
def render_view(self): '''Show the formatted version of the current note''' allow_viewing = False if self.HANDLER.ACCESS_LEVEL == 'user': if self.NOTE.owner == self.HANDLER.USER: allow_viewing = True # Allow viewing of user's own notes elif self.NOTE.publi...
def evaluate(self, input): assert len(input) == self.input_length, "The length of the introduced input array does not coincide with the inut length declared when creating the Network object" self.a_vectors[0] = input for i in range(self.n_layers): self.z_vectors[i] = self.W_matrices...
The code trains a neural network by iterating through training examples, computing errors between network outputs and target outputs using a specified error function, and performing backpropagation with scaled errors. It aggregates errors, applies gradients, resets them, and returns the mean squared error (MSE) and sta...
def train(self, training_examples, target_outputs, error_factor = 2, error_function = difference, training_it = None): self.training_it = training_it n_training_examples = len(training_examples) errors = np.array([None] * n_training_examples) for i in range(n_training_examples): ...
def compute_low_rt60(self): #compute low RT60 value low_freq_range = self.find_target_frequency("low") low_data, low_t = self.frequency_check("low") low_rt60_values = np.random.rand(10) return low_rt60_values def compute_mid_rt60(self): #compute mid RT60 value mid_freq_range = ...
The code computes the combined RT60 value by summing the low, mid, and high frequency RT60 components calculated by separate methods, returning their aggregate as a single RT60 metric.
def compute_combined_rt60(self): #add RT60 values combined_rt60_values = self.compute_low_rt60()+self.compute_mid_rt60()+self.compute_high_rt60() return combined_rt60_values
def DINetEncoder(img_rows=480, img_cols=640,train_bn=None, weight_file=None): inputimage = Input(shape=(img_rows, img_cols,3)) base_model = M_ResNet50nob(input_tensor=inputimage, train_bn=train_bn) # # for layer in base_model.layers: # layer.trainable = False x5 = base_model.output x5 ...
This code defines a dual-decoder neural network model (DINetvisual2o) for image processing. It uses an encoder (DINetEncoder) to extract features from input images, then two decoders (DINetDecoder and DINetDecodernoas) to generate output predictions. The model returns two outputs, likely for parallel tasks like reconst...
def DINetvisual2o(img_rows=480, img_cols=640, train_bn=False): inputimage = Input(shape=(img_rows, img_cols,3)) # for layer in base_model.layers: # layer.trainable = False x,b1,b2,b3 = DINetEncoder(img_rows, img_cols)(inputimage) # for layer in DINetEncoder.layers: # layer.trainable =...
def decode_place_input(self, command): command = command.split(',') # check if the command has the correct number of arguments if len(command) != 3: logging.error("Invalid command length: expected 4 arguments, received " + str(len(command)) + " arguments") elif command[0].isd...
The code processes commands to control a robot. It handles "PLACE" to position the robot, and if already placed, executes "MOVE", "LEFT", "RIGHT", or "REPORT" commands. It validates inputs, logs errors for invalid commands or when the robot is not placed.
def handle_command(self, command): if command[0] == "PLACE": # if command can be decoded into x, y, and f variables, place the robot if self.decode_place_input(command[1]) != None: x, y, f = self.decode_place_input(command[1]) self.place(x, y, f) ...
def game_at(self, x: int, y: int) -> str: if 0 <= x < len(self._game[0]) and 0 <= y < len(self._game): return self._game[y][x] return OUT_OF_BOUNDS def play_at(self, x: int, y: int): self._game[y][x] = BLACK def flag_at(self, x: int, y: int): self._game[y][x] = CIRCLE def setStatus(...
This method handles a click event on a game board by determining the cell's state at (x,y). If the cell is an integer, it triggers a play action; if BLACK, it flags the cell; if CIRCLE, it updates the game state. If 'save' is True, it records the current state for undo functionality. Finally, it updates the status disp...
def click(self, x, y, save): if isinstance(self.game_at(x, y),int): self.play_at(x,y) elif self.game_at(x, y) == BLACK: self.flag_at(x,y) elif self.game_at(x, y) == CIRCLE: self._game[y][x] = self._values[y][x] if save: self._undo.save(self._game) self.setStatus()
def mousePos(self, audio): x, y = g2d.mouse_position() if 0 < x < CANVAS_DIM and 0 < y < CANVAS_DIM: g2d.play_audio(self.getAudio(audio)) return (int(x // (CANVAS_DIM/self._game.numRowsCols())), int(y // (CANVAS_DIM/self._game.numRowsCols()))) return -1, -1 def saveStatus...
The code handles keyboard events to control game actions: left-click triggers mouse-based clicks, help-click enables a circle/Black feature, ESC saves status, UNDO reverts moves, AI initiates next moves, and FINISH resolves graphics. It maps key presses to specific game interactions, managing user input for gameplay, u...
def keyControl(self): if g2d.key_pressed(LEFTCLICK): x, y = self.mousePos("black") if x >= 0: self._game.click(x, y, True) elif g2d.key_pressed(HELPCLICK): self._game.circleAndBlack(True) elif g2d.key_pressed(ESC): self.saveStatus() ...
def drawTitle(self): g2d.clear_canvas() g2d.set_color(COLOR_BG) g2d.fill_rect((0,0,self._w, self._h)) g2d.set_color(COLOR_TITLE) g2d.draw_text_centered(HITORI, (self._w/2, self._w/6), SIZE1*5/2) g2d.draw_line((20, self._w/6 + SIZE1), (self._w-20, self._w/6 + SIZE1)) def m...
This method renders the menu interface by checking the current state (e.g., main menu, levels, rules) and drawing corresponding elements. It uses mouse input for zoom/interaction effects and ensures the title and copyright are displayed. Conditional logic directs which menu-specific functions to call, such as mouse zoo...
def drawMenu(self): self.drawTitle() if self._menu: self.mouseZoom(g2d.mouse_position()[1], self._w, MAIN_MENU) elif self._levels: self.mouseZoomLvls(g2d.mouse_position(), self._w, LVL_MENU) elif self._command: self.drawRules(g2d.mouse_position(), self._w, COMMAND_MENU) ...
def keyControl(self): if g2d.key_pressed(LEFTCLICK): x, y = self.mousePos("black") if x >= 0: self._game.click(x, y, True) elif g2d.key_pressed(HELPCLICK): self._game.circleAndBlack(True) elif g2d.key_pressed(ESC): self.saveStatus() ...
The code's main task is to manage game state transitions: it draws the menu if active, handles key controls and button updates during gameplay, and triggers a win sequence by deleting a continue file, playing a victory sound, and displaying a winning board when the game ends.
def tick(self): if self._menu.getMenuOn(): self._menu.drawMenu() elif not self._game.getStatus(): self.keyControl() self.update_buttons(True) else: File.deleteContinue(File) g2d.play_audio(self.getAudio("win")) self.winningBoard()
def code_to_tok(self, path): codes = [] a = 0 for filename in glob.glob(path): if a % 1000 == 0: print(filename) a += 1 if a > 25000: break with open(filename, 'r') as f: raw_code = f.read() ...
The code generates a dataset of code snippet pairs: one correct and one with intentional typos. It reads code from a file, tokenizes it, introduces typos to create incorrect versions, converts both to strings, and pairs them. The result is a zipped tuple of (correct_code, incorrect_code) pairs for training models to de...
def create_dataset(self, path): # path : path to spa-eng.txt file # num_examples : Limit the total number of training example for faster training (set num_examples = len(lines) to use full data) #lines = io.open(path, encoding='UTF-8').read().strip().split('\n') #word_pairs = [[self.prep...
def load_vectors(infile): # Input lines look like: # R75,D30,R83,U83,L12,D49,R71,U7,L72 # U62,R66,U55,R34,D71,R55,D58,R83 # Read them in and convert them into [x, y] vectors # - U = [0, 1] # - D = [0, -1] # - R = [1, 0] # - L = [-1, 0] vecs = [] with open(infile, 'r') as f: ...
The code reads two vector lines from a file, converts them into points, finds their intersection, calculates distances between intersecting points, sorts these distances, and prints the second smallest distance as the "shortest".
def main(infile): line1, line2 = load_vectors(infile) # print("Line 1:", line1) # print("Line 2:", line2) points1 = vecs_to_points(line1) points2 = vecs_to_points(line2) # print("points1:", points1) # print("points2:", points2) intersection = intersect(points1, points2) distances ...
def jisotonic5_updown(values: np.array, weights: Union[np.array, None]): N = len(values) values_reversed = values[::-1] if weights is not None: weights_reversed = weights[::-1] else: weights_reversed = None B1, MSE1 = jisotonic5(values, weights) B2, MSE2 = jisotonic5(values_rever...
The code computes a cutpoint in sorted samples by fitting a unimodal density model, identifying a critical range via a dip score, and applying residual analysis to locate a significant dip in the data, returning the dip score and cutpoint.
def isocut6_slow(samples: np.array): N = len(samples) X = np.sort(samples) spacings = X[1:] - X[:(N - 1)] multiplicities = np.ones((N-1,)) if np.min(spacings) == 0: raise Exception('Spacings are not allowed to be zero') log_densities = np.log(multiplicities / spacings) # Unimod...
def jisotonic5_updown(values: np.array, weights: Union[np.array, None]): N = len(values) values_reversed = values[::-1] if weights is not None: weights_reversed = weights[::-1] else: weights_reversed = None B1, MSE1 = jisotonic5(values, weights) B2, MSE2 = jisotonic5(values_rever...
The code performs a unimodal test on sorted samples by subsampling, estimating density using isotonic regression, computing a dip score to detect multimodality, and determining a cutpoint within a critical range. It returns the dip score and the identified cutpoint to assess data distribution characteristics.
def isocut5_slow(samples: np.array): N = len(samples) samples_sorted = np.sort(samples) ############################################## # SUBSAMPLING # num_bins is sqrt(N/2) * factor num_bins_factor = 1 num_bins = int(np.ceil(np.sqrt(N * 1.0 / 2) * num_bins_factor)) num_bins_1 = int(np....
def vpp_vports_config(self): if 'vports' in self.vpp_json_cfg: for key, val in self.vpp_json_cfg['vports'].items(): self.vpp_vports_conf = self.vpp_vports_conf + 'create host-interface name {}\n'.format(key) def vpp_dpdk_config(self): disable_dpdk = True if 'dpdk' in...
The main task of the code is to apply configuration changes to VPP by generating and writing port, DPDK, and environment configurations to specific files, saving JSON config data, logging changes, and resetting the system, returning True upon successful execution.
def commit(self): """ Write configuration change to VPP. :return: True if change was applied successfully, False otherwise """ self.vpp_vports_config() self.vpp_dpdk_config() self.vpp_env_config() self.render_vpp_config() with open(VPP_CONFIG_JSO...
def generate_food(self): while True: x = random.randint(0, (CANVAS_WIDTH - GRID_SIZE) // GRID_SIZE) * GRID_SIZE y = random.randint(0, (CANVAS_HEIGHT - GRID_SIZE) // GRID_SIZE) * GRID_SIZE if (x, y) not in self.snake: return x, y def update_score(self): ...
The main task of the code is to reset the game state by initializing the snake's position, direction, food location, score, delay, and game over status, while binding keys and updating the display to prepare for a new game session.
def reset(self): self.direction = 'Right' self.snake = [(100, 100), (80, 100), (60, 100)] self.food = self.generate_food() self.score = 0 self.update_score() self.delay = DELAY[self.level_var.get()] self.game_over = False self.bind_keys() self.upda...
def single_frequency(text: str) -> dict: """Finds the frequencies of single letters in text. Args: text (str): String text. Returns: Letter frequencies. """ freq = {} if not text: # check that there is text raise EmptyText for char in text: # for each character ...
The function `decrypt_puzzle` decrypts a Cryptoquote puzzle by analyzing letter, bigram, and trigram frequencies from both the encrypted text and a training text. It calculates single-letter and n-gram (bigram/trigram) frequencies, normalizes them to match the encrypted text's length, and uses these to infer a substitu...
def decrypt_puzzle(crypto: str, train_text: str) -> str: """Decrypts a Cryptoquote puzzle. Args: crypto (str): Encrypted puzzle string. train_text (str): Filename for training text. Returns: The decrypted puzzle string. """ train_freq = single_frequency(train_text) # get ...
def load_rating(args): print('reading rating file ...') # reading rating file rating_file = '../data/' + args.dataset + '/ratings_final' if os.path.exists(rating_file + '.npy'): rating_np = np.load(rating_file + '.npy') else: rating_np = np.loadtxt(rating_file + '.txt', dtype=np.int...
The main task of the code is to load training, evaluation, and test datasets from user ratings, retrieve knowledge graph (KG) entities and relations, and construct a ripple set representing user interaction triplets from the KG. It returns these components for downstream tasks like recommendation modeling, integrating ...
def load_data(args): train_data, eval_data, test_data, user_history_dict = load_rating(args) n_entity, n_relation, kg = load_kg(args) ripple_set = get_user_triplet_set(args, kg, user_history_dict) return train_data, eval_data, test_data, n_entity, n_relation, ripple_set
def draw_point(canvas: tk.Canvas, rep, **kwargs): cx, cy = computed_coordinates(*rep) kwargs['fill'] = (*root.winfo_rgb(kwargs.pop('color', 'black')), 192) kwargs['outline'] = "" w = floor(kwargs['width']) return create_transparent_point(canvas, [(cx - w, cy - w), (cx + w, cy + w)], **kwargs) def dr...
This function draws geometric entities (point, segment, polygon) on a canvas based on the input type 't', applies default color and width settings, and appends the resulting graphical objects to a global 'entities' list for tracking. It raises an error for unsupported entity types.
def draw_entity(canvas: tk.Canvas, t, rep, **kwargs): global entities kwargs['width'] = floor(zoom/10) kwargs.setdefault('color', default_colors[t]) if t == 'point': entities.append(draw_point(canvas, rep, **kwargs)) elif t == 'segment': entities.append(draw_segment(canvas, rep, **kw...
def handle_mouse_move(cvs, clicked): def callback(event): global mouse_x, mouse_y, cam_x, cam_y, entities dx = (mouse_x - event.x) dy = (mouse_y - event.y) if clicked: cam_x += dx cam_y -= dy for e in entities: cvs.move(e, -dx, -dy)...
The code creates a GUI to visualize log data using Tkinter, enabling navigation (left/right keys), zoom (up/down arrows), and mouse interactions (scroll, drag) on a canvas. It initializes the window, sets up event bindings for user controls, and renders the log's current frame.
def visualize(log): global _log, font, cvs, root _log = log root = tk.Tk() root.title('Wizer') font = tkfont.Font( root=root, family="Mono", size=-font_height, weight=tkfont.BOLD, slant=tkfont.ROMAN, ) cvs = tk.Canvas( root, background...
def read_data_parallel(self, nthreads=8): """Read data in parallel chunks (good for SSD disks)""" fid = h5py.File(self.args.file_name, 'r') # read dark and flat, binning dark = fid['exchange/data_dark'][:].astype('float32') flat = fid['exchange/data_white'][:].astype('float32')...
This function performs GPU-based 3D reconstruction of large datasets by processing data in parallel chunks. It loads data, applies parallel processing in z-axis (sinograms) and theta-axis (projections), then reconstructs in chunks to manage memory. Steps include data reading, z-axis chunk processing, theta-axis chunk p...
def recon_steps(self): """GPU reconstruction by loading a full dataset in memory and processing by steps """ log.info('Step 1. Reading data.') data, dark, flat = self.read_data_parallel() log.info('Step 2. Processing by chunks in z.') data = self.proc_sino_parallel(data, dark, f...
def read_data_parallel(self, nthreads=8): """Read data in parallel chunks (good for SSD disks)""" fid = h5py.File(self.args.file_name, 'r') # read dark and flat, binning dark = fid['exchange/data_dark'][:].astype('float32') flat = fid['exchange/data_white'][:].astype('float32')...
This code performs GPU-based tomographic reconstruction by processing data in parallel chunks along z and theta axes, varying the center of rotation, and saving reconstructed slices as TIFF files using multithreading to avoid conflicts.
def recon_steps_try(self): """GPU reconstruction by loading a full dataset in memory and processing by steps """ log.info('Step 1. Reading data.') data, dark, flat = self.read_data_parallel() log.info('Step 2. Processing by chunks in z.') data = self.proc_sino_parallel(data, da...
def read_data_parallel(self, nthreads=8): """Read data in parallel chunks (good for SSD disks)""" fid = h5py.File(self.args.file_name, 'r') # read dark and flat, binning dark = fid['exchange/data_dark'][:].astype('float32') flat = fid['exchange/data_white'][:].astype('float32')...
The main task of the code is to perform GPU-based tomographic reconstruction by loading a dataset in memory, processing it in chunks along z and theta axes, and reconstructing a specific slice for multiple phi angles. It saves the results as TIFF files using parallel threads, handling angular shifts and output director...
def recon_steps_try_phi(self): """GPU reconstruction by loading a full dataset in memory and processing by steps """ log.info('Step 1. Reading data.') data, dark, flat = self.read_data_parallel() log.info('Step 2. Processing by chunks in z.') data = self.proc_sino_parallel(data...
def init_matrix(file): nb_lines = 0 nb_columns = 0 for line in file: nb_lines += 1 file.seek(0) for line in file.readlines(): line = line.strip() for char in line: nb_columns += 1 break return np.empty((nb_lines, nb_columns,)) def create_matrix(file, mat): file.seek(0) for ix_line,...
The code processes input data from 'input.txt' to compute two results: (1) the product of gamma and epsilon rates for part 1, and (2) the product of oxygen and CO2 rates for part 2. It reads the input, initializes and creates matrices, calculates the required rates, and prints both results.
def main(): src_dir = Path(__file__).parent with open(src_dir / 'input.txt', 'r') as file: mat = init_matrix(file) create_matrix(file, mat) gamma_rate, epsilon_rate = part1(mat) print(f'Result part 1 : {gamma_rate * epsilon_rate}') oxygen_rate, CO2_rate = part2(mat) ...
def create_matrices_from_input(file): file.readline() boards = [] cur_board = [] for line in file: if line in ['\n', '\r\n']: boards.append(cur_board) cur_board=[] else: cur_board.append([int(x) for x in line.strip('\n').split()]) matrices = [] ...
The code processes a Bingo game by reading input numbers and Bingo matrices from a file, then executes two tasks: part1 and part2, likely to determine winning boards for the first and last calls respectively.
def main(): src_dir = pathlib.Path(__file__).parent with open(src_dir / 'input.txt', 'r') as file: bingo_input = [int(x) for x in file.readline().strip('\n').split(',')] matrices = create_matrices_from_input(file) part1(bingo_input, matrices) part2(bingo_input, matrices)
def draw_axes(self, color): pygame.draw.line(self.screen, color, (0, self.height/2-self.viewpoint[1]), (self.width, self.height/2-self.viewpoint[1]),3) #x-axis pygame.draw.line(self.screen, color, (self.width/2-self.viewpoint[0], 0), (self.width/2-self.viewpoint[0], self.height),3) #y-axis ...
The code refreshes a graphical display by updating the screen with axes, graphs (if specified), and a cursor based on input data. It handles user exit events, applies scaling, and maintains a 60 FPS frame rate while redrawing elements.
def refresh(self, function_data, scale): function_string = function_data[0] const = (function_data[1], function_data[2], function_data[3], function_data[4]) self.scale = scale self.screen.fill(self.background_color) for event in py...
def caller_finfo(offset=2) -> inspect_.FrameInfo: currframe = inspect_.currentframe() outer = inspect_.getouterframes(currframe) frameinfo = outer[offset] return frameinfo def varinfo(arg_idx=0, value="__UNSET__", offset_or_frameinfo: Union[int, inspect_.FrameInfo] = 2, ...
The main task of the code is to pretty-print function arguments with contextual information (variable names, filenames, function names) using the `rich` library, supporting customizable offset and display options for debugging purposes.
def print_patch(*args, **kwargs): """Keyword args support `offset = 2`, `with_filename = True`, `with_fnname = True`""" formatted_args = [] caller_frameinfo = caller_finfo(offset=kwargs.pop('offset', 2)) with_filename = kwargs.pop('with_filename', True) with_fnname = kwargs.pop('...
def val_one_step(self, batch_x, batch_y): c = self.config with torch.cuda.amp.autocast(enabled=c.autocast): with torch.no_grad(): model_y = self.model(batch_x) loss = self.loss(model_y, batch_y) res = { 'val_loss': loss, ...
This function performs one training epoch for a machine learning model, including optional validation, metric logging, learning rate scheduling, and checkpoint saving. It processes training data, updates model parameters, validates if a validation iterator is provided, tracks metrics with TensorBoard, saves the best mo...
def train_one_epoch(self, train_data_iter, val_data_iter=None): c = self.config if val_data_iter is not None: log.info('Validating.') self.model.train(False) to_merge = {} for _batch_x, _batch_y in val_data_iter: batch_x, batch_y = _batch_...
def get_id_prefix(title): match_obj = re.match(r'#\d+', title) id = match_obj.group().strip('#') return id def extract_num_prefix(title): match_obj = re.match(r'#\d+', title) title_extracted = title[match_obj.end():].strip() return title_extracted def create_task_list(lines, level, status_id, us...
The function `create_us` parses a line from input to generate a User Story (US) dictionary. It extracts the US title, ID, milestone, status, tags, and point information, processes role assignments, and creates a task list from specified lines. The output is a structured dictionary representing the US with its attribute...
def create_us(lines, line_num, line_num_next, milestone, us_status, tags, commit_line, task_status, point_dict, role_dict, level_task): us = defaultdict() # Exclude '#' prefix from the us title us['title'] = lines[line_num].strip('#').strip() if us['title'].startswith('#'): us['id'] = get_id_p...
def calc_min_level(lines): min_level = float('inf') for line in lines: if not line.startswith('#'): continue level = re.match(r'#+', line).end() min_level = min(min_level, level) return min_level def get_line_num_of_commit_line(lines): for line_num, line in enumerate(...
The function `create_us_list` generates a list of user stories (US) from input text using project-specific configurations. It processes text lines to determine user story and task levels, retrieves status, tags, and milestones from the project, and constructs user stories with associated metadata. Each user story is cr...
def create_us_list(text, project, status_name, tag_name, milestone_name): lines = text.splitlines() level_us = calc_min_level(lines) level_task = level_us + 1 commit_line = get_line_num_of_commit_line(lines) # TODO: Error handling us_status = project.us_statuses.get(name=status_name) tags =...
def _glob(filepattern): return glob.glob(filepattern) def _compute_scores(target_filenames, prediction_filenames, scorer, delimiter): """Computes aggregates scores across the given target and prediction files. Args: target_filenames: List of filenames from which to read target lines. prediction_filenames...
This function computes scores between target and prediction texts using a scorer, aggregates them if an aggregator is provided, and writes the results to a CSV file. It processes files matching given patterns, handles per-example or aggregated scores, and uses a delimiter to split records.
def compute_scores_and_write_to_csv(target_filepattern, prediction_filepattern, output_filename, scorer, aggregator, delimiter="\n"): """R...
def isIgnored(path): for i in IGNORE: if re.search(i, path): return True return False def markdownmeta(path): with open(path, "r") as f: md = f.read() metadata = {} portions = md.split("---\n") if len(portions) < 3: return None if md.startswith("---"): ...
The function recursively scans a directory for markdown files, parses their metadata using markdownmeta, and stores the results in a dictionary (`notes`) with normalized keys. It also collects links from the files into a list (`links`), ignoring hidden files and directories. The function handles subdirectories, normali...
def scanNotesDir(path, notes, links): for n in os.listdir(path): if not isIgnored(n): if os.path.isdir(os.path.join(path, n)): scanNotesDir(os.path.join(path, n), notes, links) else: if not n.startswith(".") and n.endswith('.md'): k...
def scanNotesDir(path, notes, links): for n in os.listdir(path): if not isIgnored(n): if os.path.isdir(os.path.join(path, n)): scanNotesDir(os.path.join(path, n), notes, links) else: if not n.startswith(".") and n.endswith('.md'): k...
The main task of the code is to scan a directory specified by `path`, organize notes into a structured dictionary, generate a link index from found links, and enhance this index with tags derived from the notes. It returns both the processed notes and the enriched link index for further use in indexing or retrieval sys...
def scanNotes(path): notes = {} links = [] scanNotesDir(path, notes, links) balanceIndex(notes) linkIndex = {"index" : genLinkIndex(links), "links" : links} extendLinkIndexWithTags(linkIndex, notes) return notes, linkIndex
def getProfileLogLikelihood(self): return -0.5*(log(self.detR)+self.n+self.n*log(2.0*pi*self.processVariance)) def getRndCorr(self): return np.power(10*np.ones(self.s),np.random.random(self.s,)*log10(self.MAX_CORR*100.0)-2) def createRMatrix(self): self.R = np.zeros((self.n, self.n)) sel...
This function iteratively estimates the Maximum Likelihood Estimate (MLE) for a correlation matrix by randomly initializing parameters, checking matrix conditioning, updating solutions via local MLE optimization, and stopping when convergence criteria (e.g., gradient magnitude < 0.01, iteration limits, or replicate sta...
def estimateRandomMLE(self): self.solutions = [] bestCorr = np.array(self.d) bestLL = self.getProfileLogLikelihood() done = False iters = 0 replicates = 0 while not done: # get a random location to start self.d = self.get...
def resetCorrelationModel(self): self.d = np.zeros((self.s)) for i in range(self.s): self.d[i]=self.p/float(self.n) self.createRMatrix() def createTrendModelForm(self): # allocate space to specify a full second-order model # with cross terms self.trendModel=np...
This function optimizes a statistical model by iteratively removing non-essential trend components to minimize the corrected AIC (AICc). It initializes correlation and trend models, calculates test statistics for parameters, removes the least significant parameter (based on t-statistics), updates the model, and repeats...
def createOptModel(self): # number of model parameters self.q = self.s + self.numTrendParams + 1 # set initial values for the correlation model self.resetCorrelationModel() # set up the initial trend model self.createTrendModelForm() # Update the trend model infor...
def setScale(self): self.max=np.array(self.X.max(axis=0)) self.min=np.array(self.X.min(axis=0)) def scaleData(self): temp=(self.X[0]-self.min)/(self.max-self.min) for row in self.X[1:]: temp=np.append(temp,(row-self.min)/(self.max-self.min), axis=0) self.scaledX=np.ar...
This code initializes a statistical model for spatial or regression analysis by setting up input data, trend models, spatial dimensions, and correlation structures. It configures parameters for optimal model fitting, checks for MLE convergence, and prepares for parameter estimation. The class handles input scaling, mod...
def __init__(self, XIn, yIn, KSIn = None,TMIn = None, SMIn= None, dIn = None): self.X=np.mat(XIn) self.y=yIn[:] # the number of input dimensions # print self.X self.p=np.size(self.X,1) # print 'number of dimensions: ',self.p # the number of observations se...
def _pad_array(self, array, padding_size): """ pad array with padding_size zeros """ return np.append(array, np.zeros(padding_size)) def _fast_DFT(self, sequence, w_n=None): """ compute the discrete fourier transform of the given sequence """ if sequence.size == 1: return np....
The function `_fast_polynomials_multiplication` computes the coefficients of the product of two polynomials using Fast Fourier Transform (FFT). It pads the input polynomials to avoid circular convolution, applies FFT to both, multiplies the transformed arrays element-wise, performs an inverse FFT to obtain the product ...
def _fast_polynomials_multiplication(self, poly_1, poly_2): """ compute the coefficients of the product of the given polynomials """ poly_1_padded = self._pad_array(poly_1, poly_2.size - 1) poly_1_FFT = self._fast_DFT(poly_1_padded) poly_2_padded = self._pad_array(poly_2, poly_1.size - 1...
def get_last_shape(): global last_drawn_shape try: return last_drawn_shape except: return def get_last_side(): global sides try: return sides.pop() except: return 40 def get_last_color(): global last_color return last_color def undo_steps(num, abso=False): if not abso: num = 2*num + 1 global turtle...
The main task of the code is to scale up the last drawn rectangle by a random factor (1.01–2.99) while retaining its original color, effectively replacing it with a larger version. It first checks if the last shape was a rectangle, retrieves its dimensions and color, undoes the last 10 steps (likely removing the origin...
def increase_rectangle(): if get_last_shape()==4: length = get_last_side() breadth = get_last_side() color = get_last_color() undo_steps(10, abso=True) factor = random.uniform(1.01,2.99) draw_rectangle(color, length* factor, breadth* factor)
def get_last_shape(): global last_drawn_shape try: return last_drawn_shape except: return def get_last_side(): global sides try: return sides.pop() except: return 40 def undo_steps(num, abso=False): if not abso: num = 2*num + 1 global turtle for __ in range(num): turtle.undo() def draw_circle(radi...
The main task of the code is to check if the last drawn shape is a circle. If true, it retrieves the circle's radius, undoes the last four drawing steps, and redraws a larger circle with a radius increased by a random factor between 1 and 3 using the turtle graphics module.
def increase_circle(): if get_last_shape()==1: radius = get_last_side() undo_steps(4, abso=True) global turtle draw_circle(radius * random.uniform(1,3))
def exit(): print("exiting") sys.exit(0) def save(): ##turtle.mainloop() # print("Saving") # global data # logging.warning(f'Fun li before popping: {data}') # start() # logging.warning(f'After start') # # print("Saving") # # turtle.mainloop() # global turtle # logging.w...
The function `generate_events` continuously monitors keyboard inputs. It exits on 'Ctrl+Shift+E', saves data and logs a warning on 'Ctrl+Shift+S', sends data to a server on 'Ctrl+Shift+P', and yields keyboard events otherwise. It uses global variables and external functions (`save`, `send_to_server`) for actions, relyi...
def generate_events(): while True: if keyboard.is_pressed('ctrl+shift+e'): exit() elif keyboard.is_pressed('ctrl+shift+s'): global data save() logging.warning("returned") elif keyboard.is_pressed('ctrl+shift+p'): send_to_server() ...
def build_res_atten_unet_2d(input_shape, filter_num=8): merge_axis = -1 # Feature maps are concatenated along last axis (for tf backend) data = Input(shape=input_shape) conv1 = Conv2D(filter_num * 4, 3, padding='same')(data) conv1 = BatchNormalization()(conv1) conv1 = Activation('relu')(conv1) ...
The code defines a function `get_net` that returns different 2D/3D Residual Attention UNet models based on the input `algorithm` string, selecting appropriate architectures (e.g., liver or brain tumor variants) and filter numbers. It acts as a factory to instantiate specific neural network configurations for medical im...
def get_net(inp_shape, algorithm): if algorithm == 'liver_att_resunet_2d': return build_res_atten_unet_2d(inp_shape, filter_num=4) elif algorithm == 'liver_att_resunet_3d' or algorithm == 'liver_tumor_att_resunet_3d': return build_res_atten_unet_3d(inp_shape) elif algorithm == 'brain_tumor_...
def display_message(self, message): messagebox.showinfo("Message.", message) def display_menu(self): self.display_message("Calculator Menu\n" "1. Add\n" "2. Subtract\n" "3. Multiply\n" "4....
The main task of the code is to provide a menu-driven calculator that allows users to perform basic arithmetic operations (addition, subtraction, multiplication, division, exponentiation) by selecting options from a displayed menu. It repeatedly prompts for input, executes the chosen operation using a calculator instan...
def perform_calculation(self): self.display_message("Welcome to the Calculator.") self.display_menu() calculator = NewCalculator() while True: try: choice = self.get_menu_choice() if choice == 1: int1 = self.get_integer_in...
def show(self,square,board): for spot in generate.moves(square[2], board): self.add_marker(spot) def sync(self,board): self.current_board = board self.clear_widgets() for square, piece in enumerate(board.piece_arr): self.add_piece(piece,board.color_arr[square],squ...
This method handles a touch-up event to move a game piece. It checks if the touch is within bounds and if the game hasn't ended. It calculates the target square, validates the move, updates the board, and triggers a promotion dialog if needed.
def on_touch_up(self,touch): if self.current_board.winner != -1 or not self.collide_point(*touch.pos): return xpos = touch.pos[0]-self.pos[0] ypos = touch.pos[1]-self.pos[1] self.up_square = (presets.square_pos(xpos,ypos,self.width)) if self.up_square == self.down_squ...
def quiz(bass_mode = True): strings = "EADG" if bass_mode else "EADGBE" max_fret = 20 while True: random_string = random.choice(strings) random_fret = random.randint(0, max_fret) test_note = get_note_at_fret(random_string, random_fret) print("What is the note at fret {} on th...
The code defines a menu function that prompts the user to choose between a quiz, mode test, or note finder. It validates input (Q, M, N) and executes the corresponding function. If invalid input is given, it loops until a valid choice is made. Finally, it prints "Goodbye!" after processing the selection.
def menu(): print("Would you like to do the (Q)uiz, (M)ode test, or (N)ote Finder?") while (choice := input(": ").upper()) not in "QNM" and choice != "": print("That is not an option") if choice == "Q": quiz(False) elif choice == "M": mode_quiz() elif choice == "N": ...
def logLikelihood(nsame, ntrs, ntrv, v, k): same, trs, trv = transitionProbs(v, k) try: loglike = math.log(0.25)*(nsame + ntrs + ntrv) + math.log(same)*nsame + math.log(trs)*ntrs + math.log(trv)*ntrv except ValueError: sys.exit('math domain error in logLikelihood(%d, %d, %d, %.5f, %.5f)' % (...
This function performs Markov Chain Monte Carlo (MCMC) sampling to estimate parameters `edgelen` and `kappa` by iteratively updating their values. It initializes parameters, runs a burn-in phase to stabilize the chain, then generates samples while thinning them to reduce autocorrelation. Each sample includes iteration ...
def MCMC(): global sample, lnL0, lnPv0, lnPk0, edgelen, kappa print(' Using %d iterations (thinning by %d)' % (niters, thinby)) edgelen = starting_edgelen kappa = starting_kappa vsample = [] ksample = [] lnL0 = logLikelihood(nsame, ntrs, ntrv, edgelen, kappa) lnPv0 = logPriorV(edgelen) ...
def updatev(beta, tune): global edgelen, lnL0, lnPv0, vaccepts, vupdates, deltav v0 = edgelen v = (v0 - deltav/2.0) + random.random()*deltav if v < 0.0: v = -v lnL1 = logLikelihood(nsame, ntrs, ntrv, v, kappa) lnPv1 = logPriorV(v) logratio = beta*((lnL1 + lnPv1) - (lnL0 + lnPv0)) ...
The code computes the log marginal likelihood using steppingstone sampling. It calculates reference distributions for edge lengths and kappas (if applicable) from sample data, then iterates through power posteriors, adapting parameters and sampling. It accumulates log-likelihood contributions, adjusts for reference dis...
def SS(): global ss_kappa_alpha, ss_kappa_beta, ss_v_alpha, ss_v_beta, vaccepts, vupdates, kaccepts, kupdates, edgelen, kappa inv_alpha = 1.0/ssalpha beta_k = [math.pow(float(k)/nstones, inv_alpha) for k in range(nstones+1)] print(' Using %d stone%s, %d iterations/stone (thinning by %d)' % (nston...
def calcLogTransformedStandardizedKernel(stdlogv, stdlogk): v,k = detransform(stdlogv, stdlogk) logkernel = logLikelihood(nsame, ntrs, ntrv, v, k) logkernel += logPriorV(v) if not do_jc: logkernel += logPriorK(k) logv = math.log(v) transformed_logkernel = logkernel + logv + logdetsqrtS ...
The function generates a 2D grid of values (zz) based on specified parameters and plot type, calculating h using different kernel functions (e.g., log-transformed, untransformed, multivariate normal). It creates xx and yy ranges for edgelen and kappa values, computes h for each pair, normalizes with log_norm_const, and...
def createZArray(nincr, linear_scale, log_norm_const, vmin, vmax, kmin, kmax, plot_type, fn = None): dv = (vmax - vmin)/nincr dk = (kmax - kmin)/nincr xx = [] yy = [] zz = [] zzmin = None zzmax = None if fn is not None: zfile = open(fn, 'w') xx = [(vmin + dv*j) for j in...
def logLikelihood(nsame, ntrs, ntrv, v, k): same, trs, trv = transitionProbs(v, k) try: loglike = math.log(0.25)*(nsame + ntrs + ntrv) + math.log(same)*nsame + math.log(trs)*ntrs + math.log(trv)*ntrv except ValueError: sys.exit('math domain error in logLikelihood(%d, %d, %d, %.5f, %.5f)' % (...
The code performs MCMC simulations for phylogenetic parameter estimation using either the Jukes-Cantor or Kimura model. It reads existing samples if available, otherwise simulates data, runs MCMC to estimate edge length and (optionally) kappa, and outputs statistics like mean, mode, variance, and effective sample size....
def doSimulationMCMC(): global sample, rnseed, nsamples, T global nsame, ntrs, ntrv global lnL0, lnPv0, lnPk0 global edgelen, vaccepts, vupdates, deltav global kappa, kaccepts, kupdates, deltak if do_jc: print('Using Jukes-Cantor (1969) model (estimating edge length only)') else...
def get_encryption_key() -> bytes: """ Generate the encryption key from the settings found in Chrome Safe Storage It uses the PBKDF2 key derivation function to create a 16-byte key. """ # Default values used by both Chrome and Chromium in OSX and Linux salt = b'saltysalt' length = 16 # O...
The main task of the code is to decrypt Chrome browser cookies stored in a specified path using an encryption key. It retrieves the encryption key, identifies the user's Chrome cookies file, reads and decrypts the encrypted cookies, then prints the decrypted cookie data. The process involves environment variable checks...
def main(): encryption_key = get_encryption_key() user_name = os.environ.get('USERNAME') or os.environ.get('USER') chrome_cookies_path = f'/home/{user_name}/.config/google-chrome/Default/Cookies' encrypted_cookies = get_encrypted_cookies(chrome_cookies_path) decrypted_cookies = decrypt_cookies(encry...
def check_keydown_events(event, ai_settings, screen, ship, bullets): # Respone to press key if event.key == pygame.K_RIGHT: # Move ship to right ship.moving_right = True elif event.key == pygame.K_LEFT: # Move ship to left ship.moving_left = True elif event.key == pygame....
The main task of the code is to handle user input events in a game, including keyboard presses (movement/shooting), mouse clicks (starting the game), and quit actions. It processes each event type (QUIT, KEYDOWN, KEYUP, MOUSEBUTTONDOWN) and delegates actions to specialized functions like check_keydown_events, check_key...
def check_events(ai_settings, screen, stats, sb, play_button, ship, aliens, bullets): # Respone to keyboard and mouse event for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.KEYDOWN: check_keydown_events(e...
def check_fleet_edges(ai_settings, aliens): # Take action when alien reach edge for alien in aliens.sprites(): if alien.check_edges(): change_fleet_direction(ai_settings, aliens) break def ship_hit(ai_settings, stats, sb, screen, ship, aliens, bullets): # Respone to aliens hi...
The function updates alien positions, checks for ship-alien collisions, and detects if aliens reach the bottom. It triggers responses like handling ship hits and game-over conditions when collisions or bottom-reach events occur.
def update_aliens(ai_settings, stats, screen, sb, ship, aliens, bullets): # Update all aliens' position check_fleet_edges(ai_settings, aliens) aliens.update() # Detect wether alien is hit with ship if pygame.sprite.spritecollideany(ship, aliens): ship_hit(ai_settings, stats, sb, screen, shi...
def get_topic_page_count(topic): ua = pyuser_agent.UA() headers = { 'User-Agent': ua.random, 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8', 'Accept-Language': 'en-US,en;q=0.5', 'Accept-Encoding': 'gzip, deflate, br', 'Co...
The code processes a given topic by retrieving listing counts, building project data with Redis caching, collecting contributor information, and generating a report. It logs findings, limits project processing to 5 pages (TODO), and compiles results into a spreadsheet. The main task is to generate a structured report o...
def project_task(topic): pages_f, pages = get_topic_page_count(topic) mes = 'Total Listings Found ' + str(pages_f) + '; Pages ' + str(pages) logger.info(mes) # build projects and add to redis cache get_all_projects(pages, topic) # TODO: LIMIT TO 5 PAGES AT A TIME # get contributors and add pr...
def markdown_to_text(self, md_text="", tab_length=4): """ Args: md_text (bytes, str): Markdown text in the form of bytes tab_length (int, optional): Description Returns: plain_text (list): Converted Markdown into plain text """ if not md_text...
The main task of the code is to convert text (extracted from markdown) into speech using Google TTS API, saving each segment as an MP3 file in a temporary directory. It optionally deletes these files post-processing if cleanup is enabled. The text is split into lines, each converted to audio, logged, and stored with se...
def text_to_speech(self, cleanup=False): """Generate speech from text using Google TTS API Args: cleanup (bool, False): Delete MP3 files after playing. """ text_from_markdown = self.markdown_to_text() splitted_words = self.splits_words(text_from_markdown) se...
def _f(self, x): try: f = self.dbf(x) except Exception as e: print(f'The decision boundary function could not be evaluated over the x values supplied owing to error: {e}') # cap the result by boundaries, requires conversion to array first f = np.array(f) ...
The code calculates the shortest Euclidean distance from a point P to the nearest point on a boundary, identifies this closest boundary point, and optionally normalizes the distance relative to the maximum boundary distance. It returns the closest boundary point, computed distance, and normalized metrics (if enabled) i...
def execute(self) -> DistanceOutput: print(f'Finding nearest distance to point P: {self.p}') # find the closest point on the boundary to the point p closest_boundary_point_to_p = minimize_scalar(self.__objective, bounds=self.bounds.x_tuple, method='bounded') self.boundary_point = [clos...
def parse_file(file_name): with open(file_name, 'r') as f: return np.array([[int(c) for c in line.strip()] for line in f]) def solution1(arr): return sum(map(lambda x: x+1, arr[(arr < np.vstack((np.full((1, arr.shape[1]), 10), arr[:-1]))) & (arr < np.vstack((arr[1:], np.full((1, arr.shape[1]), 10)))) & ...
The code processes input data from 'input.txt', computes two solutions, and prints results. First, it parses the input file into an array. Then, it calculates `solution1` and prints its output. Next, it identifies lowpoint indices, converts them into a NumPy array, and uses them in `solution2` to compute a second resul...
def main(): arr = parse_file('input.txt') print('Final Solution 1:', solution1(arr)) lowpoints = np.array(list(zip(*get_lowpoint_indices(arr)))) print('Final Solution 2:', solution2(arr, lowpoints))
def load_maze(): fn = sys.argv[1] if os.path.exists(fn): print("Maze file exists!\n") print("Filename: {}".format(os.path.basename(fn))) with open(sys.argv[1], 'r') as f: content = f.read() print(content) print('\nProcess Maze to 2D numpy array...') lines = [] with op...
The code executes value iteration, policy iteration, and optimistic policy iteration algorithms on two grid environments (g1, g2) with varying gamma values, generates heatmaps to visualize optimal policies and value functions, and compares algorithm runtimes and performance through additional analysis functions.
def main(): load_maze() # value iteration folder = 'plots/' name = 'value_iter_g1_'+str(gamma) print(name+': ') V, pi = value_iteration(g1) heat_map(folder+name, V, pi) print('------------------------------------') name = 'value_iter_g2_'+str(gamma) print(name+': ') V, pi =...
def get_expected_events_with_dict(self, wf_dict): """ Get number of expected events of a workflow. """ if 'FilterEfficiency' in wf_dict: filter_eff = float(wf_dict['FilterEfficiency']) elif 'Task1' in wf_dict and 'FilterEfficiency' in wf_dict['Task1']: fil...
The main task of this code is to retrieve and process workflow data from the RequestManager (ReqMgr2) by fetching a workflow dictionary from a CouchDB endpoint, extracting key attributes like events, lumis, campaigns, and requests, structuring the data into a standardized dictionary format, and returning it with releva...
def get_new_dict_from_reqmgr2(self, workflow_name): """ Get workflow dictionary from RequestManager. """ url = f'/couchdb/reqmgr_workload_cache/{workflow_name}' wf_dict = make_cmsweb_request(url) expected_events = self.get_expected_events_with_dict(wf_dict) expect...
def get_new_dict_from_reqmgr2(self, workflow_name): """ Get workflow dictionary from RequestManager. """ url = f'/couchdb/reqmgr_workload_cache/{workflow_name}' wf_dict = make_cmsweb_request(url) expected_events = self.get_expected_events_with_dict(wf_dict) expect...
This function updates or creates a workflow entry in the database by fetching data from RequestManager. It compares the new workflow dictionary with the existing one (or initializes a new entry if none exists). If changes are detected, it updates the database, logs the action, and triggers external processes based on `...
def update_one(self, workflow_name, trigger_prod=False, trigger_dev=False): """ Action to update one workflow's dictionary from RequestManager. If no such workflow exist in database, new one will be created. """ self.logger.info('Updating %s', workflow_name) update_start ...
def get_new_history_entry(self, wf_dict): """ Form a new history entry dictionary for given workflow. """ include_lumisections: bool = self.lumis_should_be_retrieved(wf_dict) self.logger.info('Getting a new entry - Lumisections to be included: %s', include_lumisections) o...
This function updates the event count for a specified workflow by retrieving the workflow, adding a new history entry, and updating the database if changes occur. If successful, it logs the update time and triggers external processes based on flags. If the workflow isn't found or no changes are made, it logs warnings o...
def recalculate_one(self, workflow_name, trigger_prod=False, trigger_dev=False): """ Action to update event count for workflow. """ recalc_start = time.time() self.logger.info('Updating event count for %s', workflow_name) workflow = self.database.get_workflow(workflow_nam...
def get_list_of_changed_workflows(self): """ Get list of workflows that changed in RequestManager since last update. """ last_seq = self.database.get_setting('last_reqmgr_sequence', 0) url = f'/couchdb/reqmgr_workload_cache/_changes?since={last_seq}' self.logger.info('Get...
This function updates workflows that have changed since the last update, deletes obsolete workflows, handles previously crashed workflows, recalculates event counts for related workflows, and logs progress and errors. It ensures data consistency by tracking changes, managing exceptions, and updating database timestamps...
def perform_update_new(self, trigger_prod=False, trigger_dev=False): """ Perform update for all workflows that changed since last update and recalculate events for files that changed since last update """ update_start = time.time() changed_workflows, deleted_workflows, la...
def catcher(s, stop=True): try: yield except stopit.utils.TimeoutException: raise except Exception: awesome_error(s, exc_info=True) if stop: raise Abort() def awesome_info(msg, **kwargs): awesome_log(logging.INFO, msg, **kwargs) def awesome_warning(msg, **kwar...
The code loads an ELF and debug binary using angr, extracts function symbols from the debug binary, generates a control flow graph (CFG) for the ELF, checks if symbols exist in the CFG, and attempts to decompile each function with error handling, logging success/failure and code quality warnings.
def doit_raw(pkg_name, elf_path, dbg_path): with catcher(f"ELF_OPEN_FAIL: elf={elf_path} pkg={pkg_name}"): elf = angr.Project(elf_path, auto_load_libs=False) awesome_info(f"ELF_OPEN_SUCCESS: elf={elf_path} pkg={pkg_name}") with catcher(f"DBG_OPEN_FAIL: dbg={dbg_path} pkg={pkg_name}"): d...
def single_connection(self, client): try: # _logger.info(f' {client.name} connection...') if len(client.queue_receive) > 0: msg = client.queue_receive.pop(0) if msg.header == Header.AUTO_UPLOAD: if client.name == 'Local Client': ...
The main task of the code is to manage bidirectional communication between two clients (local and remote) by continuously checking their connection status and message queues. It forwards messages between clients, handles specific `AUTO_UPLOAD` headers to save or send screenshots, and maintains a loop with a 0.1-second ...
def run(self): while True: if self.local_client.connected and not self.remote_client.connected: self.single_connection(self.local_client) if self.remote_client.connected and not self.local_client.connected: self.single_connection(self.remote_client) ...
def find_element(self, element, locator, locator_type=By.XPATH, page=None, timeout=10, condition_func=EC.presence_of_element_located, condition_other_args=tuple()): """Find an element, then return it or None. If timeout is less than or requal zero, then just find. ...
This code automates paraphrasing text using OpenAI's chat interface by logging in with provided credentials, handling CAPTCHA verification, and iterating through database entries to generate paraphrased responses, which are then saved to the database. It includes session management, popup interactions, and conversation...
def work(self,UserEmail,UserPassword): self.driver.get('https://chat.openai.com/chat') while True: time.sleep(3) capacity = self.find_element('High capacity','//*[@id="__next"]/div[1]/div/div/div[1]/div[1]',timeout=2) if capacity: if 'capacity...
def get_closest_waypoint_idx(self): x = self.pose.pose.position.x y = self.pose.pose.position.y closest_idx = self.waypoint_tree.query([x, y], 1)[1] #Check if closest is ahead or behind vehicle closest_coord = self.waypoints_2d[closest_idx] prev_coord = self.waypoints_2...
The code continuously monitors the robot's pose relative to a predefined path, calculates the cross-track error (deviation from the path), and publishes this error along with relevant waypoints at 50 Hz. It operates until ROS shutdown, ensuring real-time path-following feedback.
def loop(self): rate = rospy.Rate(50) while not rospy.is_shutdown(): if self.pose and self.base_waypoints and self.waypoint_tree: # Get closest waypoint closest_waypoint_idx = self.get_closest_waypoint_idx() self.publish_cross_track_error(clos...