dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def process_inputs(self, **kwargs): """Process the user inputs.""" return { "multi_select": bool(kwargs.get("multi_select", False)), "filter": kwargs.get("filter", ""), "disable_nbsp": kwargs.get('disable_nbsp', False) } def setup(self, **kwargs): """...
The main task of the code is to generate an HTML file by processing inputs, writing its header and body, then copying the generated HTML content to the clipboard. It handles platform-specific clipboard operations (Windows vs. others) and notifies the user upon completion.
def run(self, **kwargs): """Run command.""" inputs = self.process_inputs(**kwargs) self.setup(**inputs) html_file = ".html" with OpenHtml(html_file) as html: self.write_header(html) self.write_body(html) # Set clipboard html.see...
def get_empty_xml(): return pkgutil.get_data(__package__, 'empty.xml') def xml_make_table(data): obj = ET.Element('dia:object', attrib={ 'type': 'Database - Table', 'version': '0', 'id': 'O{}'.format(data['id']), }) attr = ET.SubElement(obj, 'dia:attribute', attrib={'name': 'met...
The function generates a Dia XML diagram by combining tables and relationships into an XML structure. It parses an empty XML template, appends table and relation elements (with optional bezier curves), and returns the encoded XML string for a Dia diagram.
def dia_xml(tables, rels, bezier=False): dom = ET.fromstring(get_empty_xml()) layer = dom.find('dia:layer', namespaces=XML_NAMESPACES) for t in tables: layer.append(xml_make_table(t)) for r in rels: layer.append(xml_make_relation(r, bezier=bezier)) return ( u'<?xml version=...
def rewrite_page_title(soup): title = soup.find("title") if not title: return title.string.replace_with(trademarkify_text(title.string)) def rewrite_links(soup): server_url = f"http://{HOST}:{PORT}" for link in soup("a"): if isinstance(link.contents[0], str): link.string...
The main task of the code is to process and modify HTML content by applying a series of rewrite functions to specific elements like page titles, links, scores, descriptions, comments, and footer search fields, ultimately returning the transformed HTML as a string.
def trademarkify_page_html(html): soup = BeautifulSoup(html, "html.parser") rewrite_page_title(soup) rewrite_links(soup) rewrite_scores(soup) rewrite_post_description(soup) rewrite_post_comments(soup) rewrite_footer_search(soup) trademarkified_html = str(soup) return trademarkified_h...
def calc_pic_diff(self, frame1, frame2, conv_to_gray=True): if conv_to_gray == True: frame1 = cv2.cvtColor(frame1, cv2.COLOR_BGR2GRAY) frame2 = cv2.cvtColor(frame2, cv2.COLOR_BGR2GRAY) diff_gray = cv2.absdiff(frame1, frame2) blur = cv2.GaussianBlur(diff_gray, (5, 5), 0) ...
This function detects motion in video streams or files by comparing consecutive frames, identifying moving objects via contours, and optionally visualizing or saving detected movements. It supports input from cameras or video files, allows frame resizing, contour drawing, and saving cropped images of moving objects. Th...
def motion_detection(self, camera_stream=False, vcap_url=None, stream_from_file=False, video_file=None, movie_show=False, resize_tuple=None, draw_contours=False, save_moving_objects=False, motion_max_count=3000): ...
def calc_pic_diff(self, frame1, frame2, conv_to_gray=True): if conv_to_gray == True: frame1 = cv2.cvtColor(frame1, cv2.COLOR_BGR2GRAY) frame2 = cv2.cvtColor(frame2, cv2.COLOR_BGR2GRAY) diff_gray = cv2.absdiff(frame1, frame2) blur = cv2.GaussianBlur(diff_gray, (5, 5), 0) ...
This function detects motion in video input (camera stream or file), identifies moving objects via frame difference and contour analysis, labels detected movements, and saves labeled images. It processes frames, checks for motion thresholds, draws contours, verifies intersections, and optionally displays video or saves...
def motion_detection_and_labeling(self, camera_stream=False, vcap_url=None, stream_from_file=False, video_file=None, movie_show=False, resize_tuple=None, draw_contours=False, save_labels=True, skip_frames=3, ...
def has_keypoint(self): if self.keypoint_roi_pool is None: return False if self.keypoint_head is None: return False if self.keypoint_predictor is None: return False return True def select_training_samples(self, proposals...
The main task of this code is to perform the forward pass of a Faster R-CNN-like object detection model. It processes input features and proposals to generate class logits, box regression parameters, and detection scores. During training, it computes classification, regression, and scoring losses. In inference, it appl...
def forward(self, features, # type: Dict[str, Tensor] proposals, # type: List[Tensor] image_shapes, # type: List[Tuple[int, int]] targets=None, # type: Optional[List[Dict[str, Tensor]]] class_logits_loss=True, nm...
def optimal_weights(n_points, er, cov): """ -> list of weights to run the optimizer on to minimize the vol """ target_rs = np.linspace(er.min(), er.max(), n_points) weights = [minimize_vol(target_return, er, cov) for target_return in target_rs ] return weights def portfolio_return(weights, retu...
This function plots the efficient frontier for multiple assets using optimal weights, returns, and volatilities. It optionally displays the equal-weight portfolio, global minimum variance portfolio, and capital market line (CML) based on input flags. The plot visualizes risk-return trade-offs across asset allocations, ...
def plot_ef(n_points, er, cov, style = ".-", show_cml=False, riskfree_rate=0, show_ew=False, show_gmv=False): """ Plots the n-asset efficient frontier """ weights = optimal_weights(n_points, er, cov) rets = [portfolio_return(w, er) for w in weights] vols = [portfolio_vol(w, cov) for w in w...
def parse(puzzle_input: str)->list[Passport]: """Parse input""" rawRecords = [i.replace('\n', ' ') for i in puzzle_input.split('\n\n')] records = [] for rawRecord in rawRecords: birthYear=re.search(r'byr:(\S+)', rawRecord) issueYear=re.search(r'iyr:(\S+)', rawRecord) expirationYe...
The code solves a puzzle by parsing the input data, then computing two solutions using separate functions (`part1` and `part2`). It returns both solutions as a tuple. The main task is to process the input, split into two parts for distinct problem-solving steps, and combine their results. Your return
def solve(puzzle_input): """Solve the puzzle for the given input""" data = parse(puzzle_input) solution1 = part1(data) solution2 = part2(data) return solution1, solution2
def fill_alignment_matrix(query, reference): """ Creates the alignment matrix. """ M = len(query) N = len(reference) alignment_matrix = np.zeros(shape=(M+1, N+1)) for i in range(1, M+1): for j in range(1, N+1): alignment_score, movement = next_movement(alignment_matr...
The code implements the Smith-Waterman algorithm for sequence alignment, aligning a query sequence with a reference sequence. It constructs an alignment matrix, performs traceback to determine optimal alignments, and returns the aligned sequences. If enabled, it prints the original sequences, alignment matrix, aligned ...
def smith_waterman(query, reference, verbose=True): """ main function """ total_start = time.perf_counter() matrix_start = time.perf_counter() alignment_matrix = fill_alignment_matrix(query, reference) # compute alignment matrix matrix_end = time.perf_counter() traceback_start = ti...
def fill_alignment_matrix_mpi(query, reference): M = len(query) N = len(reference) # alignment_matrix = np.zeros(shape=(M+1, N+1)) # calculate how many times each processor needs to run iters = N // (size - 1) leftovers = N % (size - 1) if rank != 0 and rank <= N: # some proces...
The `smith_waterman` function performs sequence alignment using the Smith-Waterman algorithm with MPI parallelization. It computes an alignment matrix (`fill_alignment_matrix_mpi`), identifies optimal local alignments via traceback, and outputs aligned sequences, matrix visualization, and timing metrics (matrix creatio...
def smith_waterman(query, reference, verbose=True): """ main function """ if rank == 0: total_start = time.perf_counter() matrix_start = time.perf_counter() alignment_matrix = fill_alignment_matrix_mpi(query, reference) # compute alignment matrix if rank == 0: ...
def fill_alignment_matrix_mpi(query, reference): M = len(query) N = len(reference) cols_per_proc = N // (size - 1) leftovers = N % (size - 1) if rank != 0 and rank <= N: if rank <= leftovers: cols_per_proc += 1 end_ref_i = rank * cols_per_proc else: ...
The function `smith_waterman` performs sequence alignment using the Smith-Waterman algorithm, leveraging MPI for parallel computation. It constructs an alignment matrix to identify optimal local alignments between a query and reference sequence. If rank 0 (master process), it executes traceback to extract aligned seque...
def smith_waterman(query, reference, verbose=True): """ main function """ if rank == 0: total_start = time.perf_counter() matrix_start = time.perf_counter() alignment_matrix = fill_alignment_matrix_mpi(query, reference) # compute alignment matrix if rank == 0: matr...
def load_story(filenames): stories = [] for filename in filenames: with open(filename) as fp: story = fp.read() if filename.endswith('.ftxt'): story = remove_single_newlines(story) stories.append(story) return '\n'.join(stories) def load_wikipedia(...
The code trains a Markov model on a story input (from text file or Wikipedia), tokenizes the input, builds transition probabilities between states, saves the model as JSON, then generates and prints a new story by sampling from the model's learned patterns with punctuation-aware spacing and timing.
def main(args): model = MarkovModel() if args.mode == 'txt': story = load_story(args.txt) elif args.mode == 'wikipedia': story = load_wikipedia(100) else: raise ValueError("invalid mode {}".format(args.mode)) tokens = list(tqdm(tokenize_story(story), desc="tokenizing")) ...
def composeMenuView(): sectionPair = initReactionString("pairs") view = { "type": "modal", "callback_id": "menuView-modal", "notify_on_close": True, "title": { "type": "plain_text", "text": "Snolloween Noise Machine", "emoji": True }, "close": { "type": "pla...
This function handles a command by logging input data, acknowledging receipt, opening a Slack modal interface via the API, creating a user, and initializing their view settings with generated IDs and hashes. It uses logging for debugging and interacts with Slack's client to manage user interfaces and data setup.
def handle_command(body, ack, client, logger): logger.info(body) ack() res = client.views_open( trigger_id=body["trigger_id"], view= composeMenuView() ) createUser(body["user_id"]) userInitView(body["user_id"], "menu_view", res["view"]["id"], res["view"]["hash"]) ...
def stringValidate_add(string): #check string against regex for add match = re.findall("(:{1}\w+:{1})(\s+)([\w\-]+)(\.mp3)", string) if match: return match[0] else: return "" def errorCheck_add(input): #check capture against error cases, return error message if error if input == "": return "Erro...
This function processes a form submission by validating user input, handling errors, and updating a database and UI if valid. It extracts input from a Slack view, validates it with `stringValidate_add`, checks for errors, and returns error messages if invalid. On success, it updates the database with `dbAddPair` and re...
def addView_submission(ack, body, client, logger): logger.info(body["view"]["state"]["values"]) input = body["view"]["state"]["values"]["input-block"]["addPair-action"]["value"] match = stringValidate_add(input) print(match) error = errorCheck_add(match) if error: myError = {} ...
def stringValidate_removal(string): #check string against regex for removal match = re.search("(^:{1}\w+:{1}$)", string) if match: return match.group() else: return "" def errorCheck_removal(input): #check capture against error cases, return error message if error if input == "": return "Error: ...
This function handles the removal of a pair from a menu view. It validates user input, checks for errors, and if valid, updates the database and refreshes the menu view. If errors occur, it returns error messages.
def removeView_submission(ack, body, client, logger): #logger.info(body["view"]["state"]["values"]) input = body["view"]["state"]["values"]["input-block"]["removePair-action"]["value"] print(input) match = stringValidate_removal(input) print(match) error = errorCheck_removal(match) if e...
def composeMenuView(): sectionPair = initReactionString("pairs") view = { "type": "modal", "callback_id": "menuView-modal", "notify_on_close": True, "title": { "type": "plain_text", "text": "Snolloween Noise Machine", "emoji": True }, "close": { "type": "pla...
This function handles a home button interaction by logging request details, acknowledging the action, opening a menu view via Slack's API, creating a user entry, initializing view state data, and logging the response. It manages UI navigation and user session setup for a Slack application.
def homeButton_handler(ack, client, body, logger): logger.info(body) ack() res = client.views_open( trigger_id=body["trigger_id"], view= composeMenuView() ) createUser(body["view"]["id"]) userInitView(body["view"]["id"], "menu_view", res["view"]["id"], res["view"]["hash...
def _draw_game_window(self): self.alpha_button self.settings.hangman_picts self._update_screen() def _update_screen(self): #Update the images on the screen and glip to the new screen self.screen.fill(self.settings.bg_colour) #Draw the play button self.al...
The code defines a game loop that continuously draws the game window, updates the screen, and checks for events in an infinite loop, maintaining the game's runtime and responsiveness.
def run_game(self): #start the main loop of the game while True: self._draw_game_window() self._update_screen() self._check_events()
def add_emas(df, parameters): emasrc = parameters['EMA']['emasrc'] ema1 = parameters['EMA']['ema1'] ema2 = parameters['EMA']['ema2'] ema3 = parameters['EMA']['ema3'] col1 = 'ema'+str(ema1) col2 = 'ema'+str(ema2) col3 = 'ema'+str(ema3) df[col1] = df[emasrc].ewm(span=ema1, adjust=False).m...
The code's main task is to enrich a DataFrame with technical indicators by adding Exponential Moving Averages (EMA), Stochastic RSI, and Average True Range (ATR) using specified parameters. It sequentially applies three functions to update the DataFrame and returns the modified data, likely for financial analysis or tr...
def get_indicators(df, parameters): df = add_emas(df, parameters) df = add_stochRSI(df, parameters) df = add_atr(df, parameters) return df
def get_ohlc(ohlc_call): url = 'https://chartdata.sfox.com/candlesticks' pair = ohlc_call['ticker'] + "usd" period = ohlc_call['period'] startTime = ohlc_call['startStamp'] endTime = ohlc_call['endStamp'] url = "{}?endTime={}&pair={}&period={}&startTime={}".format(url, endTime, pair, period, st...
The main task of the code is to retrieve OHLC data using `get_ohlc`, generate technical indicators with `get_indicators` based on parameters, and output the last six rows of the resulting DataFrame to a CSV file via `write_directory_output`. The function then returns without further processing.
def main(parameters, ohlc_call): ohlc = get_ohlc(ohlc_call) df = get_indicators(ohlc, parameters) write_directory_output('print',df[-6:], 'df2csv') return
def initialize_board(): # Create a 3x3 array of space characters board = [ [' ', ' ', ' '], [' ', ' ', ' '], [' ', ' ', ' '] ] return board def print_board(board): row1 = "| {} | {} | {} |".format(board[0][0], board[0][1], board[0][2]) row2 = "| {} | {} | {} |".format(boa...
The code implements a Tic-Tac-Toe game where Player 'X' (human) plays against an AI using the minimax algorithm. It initializes the board, alternates turns, updates the board state, and checks for game termination. The AI (Player 'O') selects optimal moves via minimax with a depth of 3. The game concludes by declaring ...
def main(): board = initialize_board() print_board(board) while (not game_is_over(board)): # Player X goes first board = player_move(board, "X") print_board(board) if game_is_over(board): break # Player O goes next move = minimax(board,3,False)[1] make_move(board, move, "O...
def drawBackground(data): data.canvas.create_rectangle(0,0,data.width,data.width,fill="#000000",width=0) pass def drawBoard(data): drawWheel(data) pass def drawButtonDistrict(data): data.canvas.create_rectangle(0,data.width+2,data.width,data.height,fill="#000000",width=0) def drawStepCounter(data): ...
The main task of the code is to render a canvas by drawing its background, board, button area, and step counter using the provided data.
def drawCanvas(data): # draw the background drawBackground(data) # draw the board drawBoard(data) # draw button district drawButtonDistrict(data) # draw step counter drawStepCounter(data)
def prepare_body_headers_with_data(request): request_messages = request.json["messages"] # Set query type query_type = "simple" if AZURE_SEARCH_QUERY_TYPE: query_type = AZURE_SEARCH_QUERY_TYPE elif AZURE_SEARCH_USE_SEMANTIC_SEARCH.lower() == "true" and AZURE_SEARCH_SEMANTIC_SEARCH_CONFIG: ...
This function handles a conversation request by preparing headers and payload, constructing an Azure OpenAI endpoint, and either sending a synchronous POST request or initiating a streaming response based on the `SHOULD_STREAM` flag. It incorporates history metadata into the response and returns results in NDJSON forma...
def conversation_with_data(request_body): body, headers = prepare_body_headers_with_data(request) base_url = AZURE_OPENAI_ENDPOINT if AZURE_OPENAI_ENDPOINT else f"https://{AZURE_OPENAI_RESOURCE}.openai.azure.com/" endpoint = f"{base_url}openai/deployments/{AZURE_OPENAI_MODEL}/extensions/chat/completions?api...
def _handle_test_connectivity(self, param): self.save_progress("In action handler for: {0}".format(self.get_action_identifier())) # Add an action result object to self (BaseConnector) to represent the action for this param action_result = self.add_action_result(ActionResult(dict(param))) ...
This code determines the action to execute based on the action identifier, delegates to the corresponding handler method, and returns the result. It routes requests for tasks like testing connectivity, retrieving job details, submitting files/URLs, or listing jobs to their respective processing functions.
def handle_action(self, param): ret_val = phantom.APP_SUCCESS # Get the action that we are supposed to execute for this App Run action_id = self.get_action_identifier() self.debug_print("action_id", self.get_action_identifier()) if action_id == "test_connectivity": ...
def create_placeholders(img_size, n_c): # input X and y X = tf.placeholder(shape=[None, img_size, img_size, n_c], dtype=tf.float32) y = tf.placeholder(shape=[None], dtype=tf.int64) # placeholder for mask mask_with_labels = tf.placeholder_with_default(False, shape=()) return X, y, mask_with_labels def ...
This function trains a CapsNet model using TensorFlow on given data, performing forward propagation, computing loss, and backpropagation via Adam optimizer. It uses mini-batch training, validates after each epoch, and saves the best model checkpoint based on validation loss. The model includes reconstruction loss, accu...
def model(X_train, y_train, X_val, y_val, parameters, n_epochs = 10, batch_size = 50, img_size=(28,28,1), restore_checkpoint=True): tf.reset_default_graph() m = X_train.shape[0] m_val = X_val.shape[0] best_loss_val = np.infty checkpoint_path = "./checkpoints" # Cr...
def is_main_process(): return get_rank() == 0 def perplexity(model: torch.nn.Module, device: torch.device, data: np.ndarray, list_steps_val: List[int], step: int, list_losses_val: List[torch.Tensor], list_ppl_val: List[t...
The code trains a machine learning model using distributed training, with validation, gradient accumulation, learning rate scheduling, and logging. It processes training data in batches, performs forward/backward passes, clips gradients, updates weights, and evaluates perplexity periodically. Metrics like loss, learnin...
def train(device: torch.device, model: nn.Module, optimizer: Any, train_data: np.ndarray, val_data: np.ndarray, world_size: int, step_init: int = 0, num_tokens_init: int = 0, q_init: int = 0) -> None: """ Train a machine learning model. Parameters: device (torch.dev...
def load_questions(self, filename): questions = [] with open(filename, "r") as file: reader = csv.reader(file) for row in reader: question = { "text": row[0], "options": row[1:5], "correct_answer": int(ro...
This code initializes a GUI-based quiz system by setting up a window, loading questions from a CSV file, creating interface components (question label and answer buttons), and starting the quiz by displaying the first question.
def __init__(self, root): self.root = root self.root.title("Quiz System") self.root.geometry("600x400") # Create variables to store the current question and user's score self.current_question = 0 self.score = 0 # Load questions from the CSV file self.que...
def parse_message(self, received_msg): parts = received_msg.split(' ') prefix = None user = None channel = None text = None text_command = None text_args = None irc_command = None irc_args = None tags = None if parts[0].startswith...
This function processes incoming IRC messages by parsing them, logging details if verbose, triggering event handlers, responding to PING commands with PONG, and executing custom/template commands for PRIVMSG based on user permissions and command type.
def handle_message(self, received_msg): if len(received_msg) == 0: return message = self.parse_message(received_msg) if self.verbose: print(f'> ({message.irc_command} {message.irc_args}) @{message.user}: {message.text}') if 'on_message' in self.event_handlers: ...
def send_command(self, command): if self.verbose and 'PASS' not in command: print(f'< {command}') self.irc.send((command + '\r\n').encode()) def send_privmsg(self, channel, text): if text.startswith('/'): return self.send_command(f'PRIVMSG #{channel} :{text}') def...
The code connects to an IRC server using SSL, authenticates with an OAuth token, sets the username, requests capabilities, joins specified channels, sends initial greetings, and initiates a loop to handle incoming messages.
def connect(self): self.irc = ssl.wrap_socket(socket.socket()) self.irc.connect((self.irc_server, self.irc_port)) self.send_command(f'PASS {self.oauth_token}') self.send_command(f'NICK {self.username}') if len(self.caps) > 0: self.send_command(f'CAP REQ {" ".join(self...
def inverse_convert(self, x, y=None): """Converts screen coordinates to simulation coordinates""" if isinstance(x, list): return [self.convert(e[0], e[1]) for e in x] if isinstance(x, tuple): return self.convert(*x) return ( int(-self.offset[0] + (x - ...
The code draws the x and y axes on a coordinate system by converting coordinates using `inverse_convert` and `convert` methods. It draws two lines: one vertical from the top to bottom of the canvas and one horizontal from left to right, using the specified color. The function maps screen coordinates to the coordinate s...
def draw_axes(self, color=(100, 100, 100)): x_start, y_start = self.inverse_convert(0, 0) x_end, y_end = self.inverse_convert(self.width, self.height) self.line( self.convert((0, y_start)), self.convert((0, y_end)), color ) self.line( ...
def inverse_convert(self, x, y=None): """Converts screen coordinates to simulation coordinates""" if isinstance(x, list): return [self.convert(e[0], e[1]) for e in x] if isinstance(x, tuple): return self.convert(*x) return ( int(-self.offset[0] + (x - ...
The code draws a grid of horizontal and vertical lines on a surface, spaced at intervals defined by the 'unit' parameter. It calculates the necessary lines based on the converted coordinates of the surface's boundaries, then iterates to draw each line using the specified color. The grid covers the entire area defined b...
def draw_grid(self, unit=50, color=(150,150,150)): x_start, y_start = self.inverse_convert(0, 0) x_end, y_end = self.inverse_convert(self.width, self.height) n_x = int(x_start / unit) n_y = int(y_start / unit) m_x = int(x_end / unit)+1 m_y = int(y_end / unit)+1 ...
def background(self, r, g, b): """Fills screen with one color.""" self.screen.fill((r, g, b)) def draw_roads(self): for road in self.sim.roads: # Draw road background self.rotated_box( road.start, (road.length, 3.7), cos=roa...
The code's main task is to render a visual scene by drawing the background, roads, vehicles, traffic signals, and status information. It fills the background with a specified color, draws road networks, vehicle positions, traffic signals, and overlays status details, creating a comprehensive visual representation of a ...
def draw(self): # Fill background self.background(*self.bg_color) # Major and minor grid and axes # self.draw_grid(10, (220,220,220)) # self.draw_grid(100, (200,200,200)) # self.draw_axes() self.draw_roads() self.draw_vehicles() self.draw_signals...
def addSelection(self, doc_name, obj_name, sub, selected_point=None, as_is=False): """ Add the selected sub-element (face) of the part to the Reference list. Prevent selection in other document. """ if not self.checkBlockMeshLink(obj_name): return if FreeCADGui.activ...
This method handles face selection changes in a GUI. When a face item is checked, it adds the selection to the document; when unchecked, it removes the corresponding reference from the list. It then rebuilds the reference list and schedules a recomputation to update the model accordingly.
def faceListItemChanged(self, item): #NO-if item is beeing checked, add selection, otherwise -remove item from reference(if not empty) object_name = self.solidsNames[self.form.shapeComboBox.currentIndex()] if object_name != 'None': face_name = item.text() if item...
def rebuildReferenceList(self): self.form.listReferences.clear() items = [] remove_refs = [] for ref in self.References: try: idx = self.solidsNames.index(ref[0]) except ValueError: # If solid doesn't exist anymore remove_refs.appe...
This code initializes a UI for selecting and managing geometric references (faces, edges, vertices) of a 3D object in FreeCAD. It sets up selection modes, populates UI elements with available solids, connects interaction buttons, and configures toggle options between standard and solid selection modes. The widget allow...
def __init__(self, parent_widget, obj, allow_face_sel, allow_solid_sel, allow_point_sel=False, allow_edge_sel=False): #NO-define widget parameters self.parent_widget = parent_widget self.form = FreeCADGui.PySideUic.loadUi(path_to_faceselection_wizard_ui, self.parent_widget) ...
def _query_tasks(db: sqlite3.Connection) -> pa.Table: db.create_function("task_yaml_to_label", 1, build_task_yaml_to_label()) db.create_function("comment_yaml_to_text", 1, comment_yaml_to_text) db.create_function( "format_dynamic_annotation_field_value", 5, format_dynamic_annotation_...
This function retrieves specific database tables as PyArrow tables based on a query identifier. It uses the provided SQLite connection and a 'query_slug' to determine which internal query function to execute, returning results for 'tasks', 'conversations', or defaulting to 'items'. It raises errors if queries fail, ens...
def query_database(db: sqlite3.Connection, query_slug: str) -> pa.Table: """Return a table; raise sqlite3.ProgrammingError if queries fail.""" if query_slug == "tasks": return _query_tasks(db) elif query_slug == "conversations": return _query_conversations(db) else: return _query...
def _open_sqlite3_lz4_file(db_lz4_path: Path) -> ContextManager[sqlite3.Connection]: with tempfile.NamedTemporaryFile(mode="wb") as tf: with lz4.frame.open(db_lz4_path) as lz4_file: while True: try: block = lz4_file.read1() except Exception: ...
This function builds an Arrow table from a compressed SQLite database file. It opens the LZ4-compressed SQLite file, validates its integrity, executes a query defined by `query_slug`, and returns the resulting Arrow table. If a programming error occurs during querying, it returns `None` along with an error message prom...
def _build_arrow_table(db_lz4_path: Path, query_slug: str) -> pa.Table: """Main logic. Used by render() and by command-line script.""" with _open_sqlite3_lz4_file(db_lz4_path) as db: validate_database(db) # raises sqlite3.DatabaseError try: arrow_table = query_database(db, query_sl...
def insert(self, item, _height: Union[int, None] = None) -> None: height = self.__gen_height(_height) head = self.head tail = self.tail before = head.height if before < height: tail.height = height + 1 head.height = height for i in range(before, h...
The main task of the code is to update a data structure by either inserting or deleting an item based on the 'insertion' flag, then set the 'timestamp' attribute to the provided value or the head hash if unspecified. This function manages state changes and timestamp tracking within the object.
def update(self, insertion: bool, item, timestamp: Union[bytes, None] = None, height: Union[int, None] = None)\ -> None: if insertion: self.insert(item, height) else: self.delete(item) if timestamp is None: timestamp = self.__head_hash() s...
def parse_pages(self): """Extract objects in pdf pages, and populate them in a nested list Raises: PDFTextExtractionNotAllowed: given pdf is not allowed to be parsed """ fp = open(self.resume_file, 'rb') # Create a PDF parser object associated with the file object. ...
The main task of the code is to parse structured data from web pages, split and extract key sections like experience and education details, then save the processed data into JSON files and Excel spreadsheets for backup and organized storage.
def _parse_and_save(self): self.parse_pages() self.split() self.parse_main_panel() self.parse_exp() self.parse_edu() self.backup_json() self.backup_exp_edu_to_excel()
def parse_pages(self): """Extract objects in pdf pages, and populate them in a nested list Raises: PDFTextExtractionNotAllowed: given pdf is not allowed to be parsed """ fp = open(self.resume_file, 'rb') # Create a PDF parser object associated with the file object. ...
The main task of the code is to parse structured data by sequentially extracting content from pages, splitting sections, and isolating key information such as main panels, experience, and education details. It orchestrates data segmentation and extraction for structured output processing.
def _parse(self): self.parse_pages() self.split() self.parse_main_panel() self.parse_exp() self.parse_edu()
def count_single(n): add = 0 if (n == 9): add += 4 elif (n == 8): add += 5 elif (n == 7): add += 5 elif (n == 6): add += 3 elif (n == 5): add += 4 elif (n == 4): add += 4 elif (n == 3): add += 5 elif (n == 2): add += 3 ...
The main task of the code is to calculate the total number of letters in the English words for numbers from 1 to a given limit, using different helper functions for single-digit, teen, double-digit, and triple-digit numbers, with special handling for 1000.
def countem(limit): count = 0 for i in range(1, limit + 1): if (i < 10): count += count_single(i) elif (i < 20): count += count_teen(i) elif (i < 100): count += count_double(i) elif (i < 1000): count += count_triple(i) elif ...
def key_gen(x, y): prime_list = [] for n in range(x, y): isPrime = True for num in range(2, n): if n % num == 0: isPrime = False if isPrime: prime_list.append(n) randomPrime1 = random.choice(prime_list) randomPrime2 = random.choice(prime_l...
This function generates an RSA key pair by selecting two prime numbers, computing their product (n) and Euler's totient (phi), choosing a public exponent (e) coprime to phi, and calculating the private exponent (d) using modular inverse. It returns the public key (e, n) and private key (d, n) for encryption/decryption.
def crypt_keygen(): p,q = key_gen(2,100) n = p * q phi = (p-1) * (q-1) #Choose an integer e such that e and phi(n) are coprime e = random.randrange(1, phi) #Use Euclid's Algorithm to verify that e and phi(n) are comprime g = gcd(e, phi) while g != 1: e = random.randrange(1, phi) ...
def crypt_keygen(): p,q = key_gen(2,100) n = p * q phi = (p-1) * (q-1) #Choose an integer e such that e and phi(n) are coprime e = random.randrange(1, phi) #Use Euclid's Algorithm to verify that e and phi(n) are comprime g = gcd(e, phi) while g != 1: e = random.randrange(1, phi) ...
The code demonstrates RSA encryption and decryption by generating a public-private key pair, encrypting a message with the private key, decrypting it with the public key, and returning both the encrypted and decrypted results.
def rsa(message): public, private = crypt_keygen() encrypted_message = encrypt(private, message) decrypted_message = decrypt(public, encrypted_message) return encrypted_message, decrypted_message
def createRoot(self): self._content.grid(column=0, row=0, columnspan=8, rowspan=3, sticky=('EWNS')) self._root.title('Platform of Attacks Simulation') self._root.tk.call('wm', 'iconphoto', self._root._w, Tk.PhotoImage(file='View/Resources/Pictures/Logo ensicaen.png')) ...
The code initializes a GUI component by setting up a Tkinter window, creating frames and widgets (labels, buttons, combo boxes), linking them to a presenter, and arranging the layout. It prepares the interface for user interaction, including dynamic file selection via a combo box, and ensures widgets are resizable for ...
def __init__(self, presenter): self._presenter = presenter self._root = Tk.Tk() self._content = ttk.Frame(self._root) self.createRoot() self.createLabelWidgets() self.createButtonWidget() self.createComboBoxAttack() self.updateFileComboBox([]) self...
def update(env): with cd("{}repo.git".format(get_deploy_path(env))): run("git pull") def build(env, version): environment_path = get_deploy_path(env) code_path = get_code_path(env, version) run("mkdir {}".format(code_path)) with cd(code_path): run("cp -R {}repo.git/webapp/* .".format(environment_path...
The code deploys an application by generating a timestamp-based version token, updating the environment, building the application and static assets with this version, then switching the environment to use the new deployment.
def deploy(env): VERSION_TOKEN = datetime.now().strftime("%Y%m%d-%H%M%S-%f")[:-3] update(env) build(env, VERSION_TOKEN) build_statics(env, VERSION_TOKEN) switch(env, VERSION_TOKEN)
def add_user(): # Grab updated version of user list, useful if adding multiple in a row users_check() if user == "admin": with open("user.txt", "a") as newuser: while True: new_username = input("Enter a new username: ") # Check if the username already exi...
This code defines a menu-driven interface for a task management system. It allows users to register new users, add tasks, view all tasks, or view their assigned tasks. Admin users have additional options to view statistics and generate reports. The menu loops until the user selects 'e' to exit, handling input validatio...
def menu(): while True: # Menu if user is not set to admin if user != "admin": menu = input( f"""Please select one of the following options: r - Register a new user a - Add a new task va - View all tasks vm - View tasks currents assigned t...
def spawn_food(self) -> None: body_as_tuples = [tuple(e) for e in self.snake.body] open_squares = [ (x, y) for x in range(self.size) for y in range(self.size) if (x, y) not in body_as_tuples ] self.food = np.array(random.choice(open_squares)) def is_in_bounds(self, pos: NDArray) ...
The main task of the code is to move a snake in a specified direction, update its position, check for food collisions, manage body length, detect game-over conditions (intersection or out-of-bounds), and return a reward value. The reward is -0.05 for each step, 1 for eating food, or -1 if the snake dies. The function a...
def step(self, turn: Dir) -> int: """Take a step in a direction. Returns a reward based on the outcome.""" reward = -0.05 head = self.snake.body[0] self.snake.direction = turn t = turn.value self.snake.body.insert( 0, np.array((head[0] + (t & 1) * (2 - t), head[1] + ((t + 1) & 1) * ...
def cum_fit_prob(generation, Distance, X, Y, DRAW): prob = population_fitness(generation, Distance, X, Y, DRAW) cum = 0 cum_prob = [] for i in range(len(prob)): cum += prob[i] cum_prob.append(cum) return cum_prob def select(cum_prob): ran = random.random() if ran < cum_prob[0...
The function generates the next generation in an evolutionary algorithm by selecting parents via cumulative fitness probabilities, performing crossover (if probabilistically triggered) and mutation on offspring, then appending the resulting children to form the new generation.
def next_generation(generation, Distance, X, Y, DRAW, P_mutate, P_crossover, ): new_generation = [] cum_prob = cum_fit_prob(generation, Distance, X, Y, DRAW) for i in range(int(len(generation) / 2)): parentA_index = select(cum_prob) parentB_index = select(cum_prob) if random.random()...
def getData(filename): Distance = np.loadtxt(filename) return Distance def generate_population(city_number, population_size): generation = [] individual = [] for i in range(city_number): individual.append(i) for i in range(population_size): for j in range(20): index_1...
This code implements a genetic algorithm to solve a traveling salesman problem (TSP). It loads distance data, computes city coordinates, initializes a population, and iteratively evolves solutions through selection, crossover (80% chance), and mutation (10% chance). After iterations, it outputs the best route and total...
def genetic_algorithm(datasource, DRAW): Distance = getData(datasource) X, Y = compute_coordinates(Distance) city_num = len(Distance) generation = generate_population(city_num, POPULATION) for i in range(ITERATION): generation = next_generation(generation, Distance, X, Y, DRAW, P_mutate=0.1,...
def forward(self, seconds=0): self.set_motors(1, 0, 1, 0) if seconds > 0: time.sleep(seconds) self.stop() def left(self, seconds=0): self.set_motors(0, 1, 1, 0) if seconds > 0: time.sleep(seconds) self.stop() def right(self, seconds=0): ...
This code simulates a sequence of directional movements (forward, left, right, reverse, stop) with user input prompts for each action, testing a system's response to commands. It pauses at each step, waits for confirmation, then ends the test with a final input.
def test(self): input("forward") self.forward(2) input("left") self.left(2) input("right") self.right(2) input("reverse") self.reverse(2) input("stop") self.stop() input("End of test")
def __resize_frame_resolution(self, frame: np.ndarray, max_width: int, max_height: int) -> np.ndarray: """ Resizes the frame to fit within the specified maximum width and height while maintaining the aspect ratio. Args: frame (`np.ndarray`): The input frame. max_...
The main task of the code is to detect faces in a given image frame using a pre-processing resize step and RetinaFace detection. It returns a specified face (by index) as a Face namedtuple containing detected keypoints and embeddings, or all faces if the index is negative. The function handles edge cases like empty fra...
def extract_faces(self, frame: np.ndarray, index: int = 0): """ Extracts faces from a given frame and returns the face at the specified index. Args: frame (`np.ndarray`): The input image frame. index (`int`, optional): The index of the face to return. Defaults to...
def multi_scale_aug(self, image, label=None, rand_scale=1, rand_crop=True): long_size = np.int(self.base_size * rand_scale + 0.5) if label is not None: image, label = self.image_resize(image, long_size, label) if rand_crop: image, label = self.rand_cr...
This function performs data augmentation on an image and label by applying multi-scale resizing, center cropping, flipping, and label downsampling. It transforms inputs, transposes image channels, and adjusts label resolution if needed, preparing data for model training.
def gen_sample(self, image, label, multi_scale=True, is_flip=True, center_crop_test=False): if multi_scale: rand_scale = 0.5 + random.randint(0, self.scale_factor) / 10.0 image, label = self.multi_scale_aug(image, label, r...
def get_default_config_path() -> str: entries = get_bootctl_entries() defaults = [x for x in entries if x.is_default] if len(defaults) != 1: raise LifeboatError('Could not determine the default entry from bootctl') return defaults[0].path def get_bootctl_entries() -> list[Config]: entries = ...
The main task of the code is to manage lifeboat backups for a default configuration. It validates input parameters, locates the default config, ensures it has required metadata, checks for existing backups, and deletes the oldest lifeboats if exceeding the max limit. Finally, it creates a new lifeboat backup for the de...
def main(*, default_sort_key: str, default_version: str, max_lifeboats: int, default_config_path: Optional[str]): if max_lifeboats < 1: raise LifeboatError(f'max_lifeboats{max_lifeboats} must be > 1') if not default_config_path: default_config_path = get_default_config_path() configs = get_...
def read_csv(self, csv_path): data = read_binary(csv_path) for str in data.split('\r\n'): if not str: continue self.csv_list.append([str[:9], str[10:]]) def read_lub(self, lub_path): self.lub_data = read_binary(lub_path) def actual_work(self): for csv in self.csv_list: if len(csv[1]) == 0: continue ...
The code's main task is to replace data in a LUB file using information from a CSV file. It reads both files, processes the data through `actual_work()`, saves the modified LUB data as a binary file at `out_path`, and displays the results.
def replace(self, lub_path, csv_path, out_path): self.read_csv(csv_path) self.read_lub(lub_path) self.actual_work() save_binary(out_path, self.lub_data) self.show_result()
def read_binary(path): with open(path, "rb") as f: return f.read() return False def parse_data(self, data): global header header = LuaHeader(data) if not header.valid_sign(): raise ValueError('Invalid LUB Signature') if not header.valid_version(): raise ValueError('Invalid LUB Version') fu...
The code's main task is to parse binary data from a specified file path using a FileReader, process the data with `parse_data`, save the results as a CSV file via `save_csv`, and display the parsed outcomes with `show_result`, enabling data conversion and visualization from binary format.
def parse(self, path): bin = read_binary(path) reader = FileReader(bin) self.parse_data(reader) self.save_csv(path) self.show_result()
def train_KF_self_training(args, config, train_features, dev_features, dev_rels, test_features, n_splits): global crest_probs splits = n_splits trains, devs = get_train_dev_split(train_features, args.n_splits) merged_train = [] #dev_file = os.path.join(args.data_dir, args.dev_file) #dev_data ...
This function performs multi-round K-fold self-training for a model, iteratively updating training data, reinitializing the model, fine-tuning it, and saving checkpoints. Each round updates features using self-training, evaluates the model on the dev set, and stores results with parameters in filenames. It runs for spe...
def Multi_Round_KF_self_training(args, model, config, train_features, dev_features, dev_rels, test_features, n_splits, n_rounds): for i in range(args.start_round, args.start_round + n_rounds): train_features = train_KF_self_training(args, config, train_features, dev_features, dev_rels, test_features, n_sp...
def get_random_mask(train_features, drop_prob, device): new_features = [] device= torch.device('cpu') for feat_id, old_feature in enumerate(train_features): #if feat_id==100: feature = deepcopy(old_feature) if type(feature['labels']) == list: neg_labels = np.array(feature...
The main task of the code is to train and evaluate a document relation extraction model (DocRE) using self-training with K-fold cross-validation. It leverages pre-trained PubMedBERT for biomedical text, processes annotated data (train/dev/test), and supports pseudo-labeling, confidence-based label dropping, and multi-r...
def main(): parser = argparse.ArgumentParser() parser.add_argument("--data_dir", default="./dataset/cdr", type=str) parser.add_argument("--transformer_type", default="bert", type=str) parser.add_argument("--cache_dir", default="cache", type=str) parser.add_argument("--model_name_or_path", default="...
def DISinter(D1, D2, alpha=0.43, d0=8, sig=1.5): D1 = np.array(D1) D2 = np.array(D2) dists = np.linalg.norm(D1[:, np.newaxis] - D2, axis=2) probs = contact_prob(dists, d0, sig) s = np.sum(probs) s *= 1 / ((len(D1) * len(D2)) ** alpha) return s def DISintra(D, indices = None, beta = 0.95, ...
The code processes a list of fragments by iteratively splitting them based on proximity between points (distance < 8). It uses `DISinter` and `DISintra` to evaluate fragment compatibility, splitting fragments if the minimum inter-fragment distance is less than half the intra-fragment distance. The `top_down_algo` recur...
def contact_map_algo(original_frags): frags = [original_frags.copy()] frag_ind= [tuple([(0,len(original_frags))])] s = 0 while True: flag = 0 new_frags = [] new_frag_ind = [] for frag,ind in zip(frags,frag_ind): DIS2 = {} for position1 in range(30,...
def build_vocab(self, list_data): list_data=self.clean_text(list_data) vocab={} for j in (list_data): for jj in (j): if jj not in (vocab): vocab[jj]=1 else: vocab[jj]+=1 vocab_a=sorted(vocab...
The code prepares training, validation, and test datasets for a transformer model by loading English and German sentence pairs, building vocabulary mappings, converting sentences to index sequences, and generating matrix representations for each dataset split. It structures the data into vocabulary lists, sentence inde...
def prepare_data(self): self.Data=CN() self.Data.val=CN() self.Data.test=CN() self.Data.train=CN() en=[data.split() for data in open("numpy-transformer-master/dataset/val.en", 'r', encoding='utf-8')] de=[data.split() for data in open("numpy-transformer-master/dataset/val...
def _init_embeddings(self, user_item, user_feature=None, item_feature=None): """""" # initialize the factors self.is_features_ = ( False if (user_feature is None) and (item_feature is None) else True ) item_sparse = True if self.loss in {'sgns'...
This code trains a recommendation model using user-item interactions and optional features. It initializes embeddings, prepares data loaders, performs stochastic gradient descent with validation checks, and updates model parameters to minimize a specified loss function. The training loop includes forward passes, loss c...
def fit(self, user_item, user_feature=None, item_feature=None, valid_user_item=None, feature_sparse=False, batch_sz=512, n_tests=1000, topk=100, valid_callback=None, verbose=False, keep_best=False, n_jobs=4): """""" # set some variables feats = {} do_v...
def hashKey(self, key, ip=False, port=None): try: hashedKey = 5381 for x in key: hashedKey = (( hashedKey << 5) + hashedKey) + ord(x) a = hashedKey & 0xFFFFFFFF key0 = None key1 = None try: key0 = int(key[0])...
The code adds a new node to a ring structure by hashing its IP to determine placement. It checks if the current node is responsible using the finger table. If so, it updates the finger table, adjusts range boundaries, and sets predecessor/successor pointers. For multiple nodes, it propagates updates; for a single node,...
def addToRing(self, details, msg): # Hash the given IP to find the position hashedIP = self.hashKey(details[1], True, details[2]) highRange = hashedIP # Check if this node is my responsibility if self.consultFingerTable(highRange,msg): # Add the node to our...
def hashKey(self, key, ip=False, port=None): try: hashedKey = 5381 for x in key: hashedKey = (( hashedKey << 5) + hashedKey) + ord(x) a = hashedKey & 0xFFFFFFFF key0 = None key1 = None try: key0 = int(key[0])...
The code handles insert operations from user input or inter-process messages. It checks if the hashed key falls within the node's range, updates the local hash table if so, and forwards the insert request to the next node if not. For process-originated inserts, it updates the table, sends a copy to the next node, and r...
def performInsert(self, userStream=None, processStream=None): # Command to insert came from user if userStream: args = userStream.rstrip().split() if len(args) != 3: print('Usage: $ insert [key] [value]') return False key = args[1] ...
def hashKey(self, key, ip=False, port=None): try: hashedKey = 5381 for x in key: hashedKey = (( hashedKey << 5) + hashedKey) + ord(x) a = hashedKey & 0xFFFFFFFF key0 = None key1 = None try: key0 = int(key[0])...
The code performs a lookup operation by checking if a key exists in the local hash table. If found, it returns the value with 'success' status; otherwise, it forwards the request. It handles both user-initiated lookups and inter-process communication, sending acknowledgment messages with results when applicable.
def performLookup(self, userStream=None, processStream=None): # Perform lookup has a little bit of different semantics since you can either return the looked up value in the function or wait for it from another process. # Perform lookup will always return a dictionary with a key called 'status'. If sta...
def hashKey(self, key, ip=False, port=None): try: hashedKey = 5381 for x in key: hashedKey = (( hashedKey << 5) + hashedKey) + ord(x) a = hashedKey & 0xFFFFFFFF key0 = None key1 = None try: key0 = int(key[0])...
The main task of the code is to handle the removal of a key from a distributed hash table. It processes removal commands from both user input and inter-process messages, checks if the key exists locally, updates the hash table if present, and propagates the removal request to the next node if needed. It also sends ackn...
def performRemove(self, userStream=None, processStream=None): # Command to remove came from user if userStream: args = userStream.rstrip().split() if len(args) != 2: print('Usage: $ remove [key]') return False key = args[1] ...
def send_msg(self, msg, dest_args): # Check if message is not a dictionary if not type(msg) is dict: return {'status': 'failure', 'message': 'message sent to function was not a dictionary'} # Check if dest args is not specified if not dest_args: return {'status'...
The main task of the code is to handle a process crash in a distributed system by updating local pointers (next/prev) and range in the finger table, then forwarding recovery instructions or routing the message to the appropriate node based on adjacency and hash calculations. It processes 'toForward' commands to adjust ...
def performFindProcess(self, processArgs): # processArgs is a json message with this structure: # method: findProcess # prev/next: [position, ipAddress, port] --> should be the arguments of a process that crashed # from: [position, ipAddress, port] # toForward: [...
def sendUpdatePrev(self, prev_args, dest_args): msg = {'method': 'updatePrev', 'prev': prev_args, 'from': [self.highRange, self.ipAddress, self.port]} ret_msg = self.send_msg(msg, dest_args) if ret_msg['status'] == 'failure': return False return True def sendUpdateRange(self,...
The code's main task is to handle cleanup during program exit by notifying adjacent nodes in a distributed system, resetting range values, and propagating stored data to the ring structure before finalizing termination.
def __del__(self): print('\nExiting program...') # Alert the next node if self.next and self.next[1] != self.ipAddress: self.sendUpdatePrev(self.prev, self.next) self.sendUpdateRange(-1, self.lowRange, self.next) # Alert the previous node if self.prev a...
def sendUpdatePrev(self, prev_args, dest_args): msg = {'method': 'updatePrev', 'prev': prev_args, 'from': [self.highRange, self.ipAddress, self.port]} ret_msg = self.send_msg(msg, dest_args) if ret_msg['status'] == 'failure': return False return True def handleCrash(self, cra...
The main task of the code is to perform a sanity check on a node's position in a ring structure by verifying connectivity with neighboring nodes. It sends dummy updates to both the next and previous nodes. If either fails to respond, it triggers a crash handling routine for the respective neighbor, ensuring the node's ...
def sanityCheck(self): # Return if no other node in ring if not self.prev or not self.next or (self.prev[1] == self.ipAddress and self.prev[2] == self.port) or (self.next[1] == self.ipAddress and self.next[2] == self.port): return # Sending dummy update previous to next pre...
def performRemove(self, userStream=None, processStream=None): # Command to remove came from user if userStream: args = userStream.rstrip().split() if len(args) != 2: print('Usage: $ remove [key]') return False key = args[1] ...
The code processes incoming messages to manage a distributed hash table's ring structure, handling node joins, rebalancing after crashes, data insertion/removal, and inter-node communication. It executes commands like saving/removing data, updating pointers, propagating rebalances, and acknowledging operations to maint...
def parseStream(self, stream, msg_length): # Check if we have encountered a malformed stream if msg_length != len(str(stream)): return False # If method not in stream, just return if 'method' not in stream: return False # Command to store hashta...
def usage(self): print('\nP2PHashTable Usage:') print(' Insert [key] [value]') print(' Lookup [key]') print(' Remove [key]') print(' Exit/Ctrl-c to quit\n') def sanityCheck(self): # Return if no other node in ring if not self.prev or not self.next or (self.pr...
The main task of the code is to handle incoming network connections, user input, and inter-process messages using a socket-based system. It listens for commands (insert, lookup, remove), processes JSON messages from connected clients, maintains message counts, performs periodic sanity checks, updates a name server, and...
def readMessages(self): # Set variable for user input self.stdinDesc = sys.stdin.fileno() # Initialize listening variables print(f"Listening on Port {self.sock.getsockname()[1]}") self.usage() self.sock.settimeout(60) listen_list = [self.sock, se...
def hashKey(self, key, ip=False, port=None): try: hashedKey = 5381 for x in key: hashedKey = (( hashedKey << 5) + hashedKey) + ord(x) a = hashedKey & 0xFFFFFFFF key0 = None key1 = None try: key0 = int(key[0])...
The main task of the code is to initialize a P2P node by creating a listening socket, determining its position on a distributed ring network via hashing, setting initial neighbor references, marking itself as part of the ring, notifying a name server, and starting to listen for incoming messages. This establishes the n...
def startP2P(self): # Start listening socket and get port port = 0 self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.bind((self.ipAddress,port)) self.sock.listen() self.port = self.sock.getsockname()[1] # Hash IP Address + p...
def vector_square(vector, current_pos): return [current_pos[0]+vector[0], current_pos[1]+vector[1]] def is_piece(coord): piece_to_move = piece_on_square(coord) if piece_to_move == ' ' or piece_to_move == '#': return False else: return True def is_opponent_coords(start_coord, end_coord):...
The function generates a list of valid squares a piece can move to along a given vector direction, starting from the current position. It adds each valid square to the list until the movement goes out of bounds or encounters a piece. If an opponent's piece is encountered, it is included in the list before stopping.
def vector_path(vector, current_pos): start_coord = current_pos current_pos = vector_square(vector, current_pos) squares = [] while current_pos[0] >0 and current_pos[0] < 9 and current_pos[1]<9 and current_pos[1]>0 and is_piece(current_pos)==False: squares.append(current_pos) current_pos...
def vector_checked_square(vector, current_pos): square = [current_pos[0]+vector[0], current_pos[1]+vector[1]] if square[0]>0 and square[0] <9 and square[1]>0 and square[1]<9 and (is_opponent_coords(current_pos, square) == True or is_piece(square)==False): return [square] return [] def is_piece(coord...
The function calculates all squares a pawn can move to and attack, based on its starting position and color. It checks standard pawn moves (1 or 2 squares forward for initial moves) and adds attacked squares via `attacked_pawn_squares`. Color determines direction: white moves upward, black downward. The result combines...
def pawn_squares(start_coord, color): start_row = start_coord[1] start_col = start_coord[0] squares = [] if color == 'white': squares += vector_checked_square([0,1], start_coord) if start_row == 2 and is_piece([start_col, 3]) == False: # checking the path of a pawn squares +...
def piece_on_square(coord): piece = chess_board_funcs.chess_board()[8-coord[1]][coord[0]-1] return piece def rook_squares(start_coord): squares = [] squares += vector_path([1,0], start_coord) squares += vector_path([-1,0], start_coord) squares += vector_path([0,1], start_coord) squares += v...
The code identifies all squares under attack by pieces of a specified color on a chessboard. It iterates through each square, checks the piece present, and appends the squares attacked by that piece using corresponding functions. Duplicates are removed before returning the list of attacked squares.
def all_attacked_squares(color): attacked_squares = [] if color == 'white': for end_row in range(1,9): for end_col in range(1,9): piece = piece_on_square([end_col, end_row]) if piece == '♖': attacked_squares += rook_squares([end_col, end_ro...
def get_or_create_raw_data_dir(): """Return the path of the raw data dir.""" raw_data_dir = os.environ.get( "FOOBAR_RAW_DATA_DIR", os.path.join(get_root_data_dir(), "raw") ) dir_path = os.path.expanduser(raw_data_dir) if not os.path.exists(dir_path): os.makedirs(dir_path) retu...
The function `load_kaggle_data` downloads a specified Kaggle dataset to a local directory if it is not already present, either as a single file or a zipped collection. It then loads the data into a pandas DataFrame, allowing customization via parameters like `chunksize`, `usecols`, and `unzip`. The function ensures dat...
def load_kaggle_data( local_fname, dataset, unzip, single_file=False, download_if_missing=True, force=False, chunksize=None, usecols=None, ): """Load a dataset from kaggle.""" data_dir = get_or_create_raw_data_dir() file_path = os.path.join(data_dir, local_fname) if not...
def get_begin_time(self, unit): """ count begin time :param unit """ # set integrate value: year-month-day-0-0-0-0 if unit == UnitType.day.value: self.begin = (self.end - pd.DateOffset(days=1) ).replace(hour=0, minute=0, second=0, mi...
This code initializes a report object with store ID, report type, and time unit. It sets creation time, calculates start/end time ranges, fetches store data from the database, generates a report URL, adjusts timezone, and saves the report to the SQL database.
def __init__(self, stID, rtype, timeunit): """ Report :param stID: store ID :param timeunit :param rtype: type of report """ self.ID = None # DB created automatically; get while saved it into DB self.storeID = stID self.reportType = rtype ...
def create_display_to_data_map(tokens_data): return create_field_to_data_map(tokens_data, 'display') def create_chain_denom_to_data_map(tokens_data): return create_field_to_data_map(tokens_data, 'denom') def create_pool_data_maps(pool_data): """ Creates and returns pool data dictionaries for testing. ...
The main task of the code is to initialize shared test data during pytest session setup. On the master node, it fetches token/pool data, creates reference maps, and stores them in a shared state file. Worker nodes read this preloaded data for deterministic testing. The code ensures synchronized access to shared state v...
def pytest_sessionstart(session): """ This hook is called after the Session object has been created and before performing collection and entering the run test loop. This is where we perform the setup tasks for the tests. If the code is running on the master node, we fetch all the data (see data_ser...
def wr(self, reg, dat): self.setReg(DS1302_REG_WP, 0) self.setReg(reg, dat) self.setReg(DS1302_REG_WP, 0x80) def DecToHex(self, dat): return (dat//10) * 16 + (dat%10) def HexToDec(self, dat): return (dat//16) * 10 + (dat%16) def getReg(self, reg): self.cs.value = True ...
The main task of the code is to handle reading and writing the seconds register of a DS1302 RTC chip. If a `second` value is provided, it writes the value (modulo 60) to the register in hexadecimal format. If no value is provided, it reads the register, converts it from hexadecimal to decimal, and returns the seconds v...
def Second(self, second=None): if second: self.wr(DS1302_REG_SECOND, self.DecToHex(second%60)) else: return self.HexToDec(self.getReg(DS1302_REG_SECOND+1))%60
def wr(self, reg, dat): self.setReg(DS1302_REG_WP, 0) self.setReg(reg, dat) self.setReg(DS1302_REG_WP, 0x80) def DecToHex(self, dat): return (dat//10) * 16 + (dat%10) def HexToDec(self, dat): return (dat//16) * 10 + (dat%16) def getReg(self, reg): self.cs.value = True ...
This code sets or retrieves the minute value from a DS1302 real-time clock. If a minute is provided, it writes the value (after validating 0-59) to the minute register in hexadecimal. If no minute is given, it reads the register, converts it from hexadecimal to decimal, and returns the current minute value.
def Minute(self, minute=None): if minute: self.wr(DS1302_REG_MINUTE, self.DecToHex(minute%60)) else: return self.HexToDec(self.getReg(DS1302_REG_MINUTE+1))
def HexToDec(self, dat): return (dat//16) * 10 + (dat%16) def getReg(self, reg): self.cs.value = True self.write_byte(reg) t = self.read_byte() self.cs.value = False return t def wr(self, reg, dat): self.setReg(DS1302_REG_WP, 0) self.setReg(reg, dat) ...
This code handles reading and writing the hour value for a DS1302 real-time clock. If no hour is provided, it retrieves the current hour from the register by converting hexadecimal to decimal. If an hour is specified, it writes the value to the register after converting decimal to hexadecimal and ensuring it stays with...
def Hour(self, hour=None): if not hour: return self.HexToDec(self.getReg(DS1302_REG_HOUR+1)) else: self.wr(DS1302_REG_HOUR, self.DecToHex(hour%24))
def HexToDec(self, dat): return (dat//16) * 10 + (dat%16) def getReg(self, reg): self.cs.value = True self.write_byte(reg) t = self.read_byte() self.cs.value = False return t def wr(self, reg, dat): self.setReg(DS1302_REG_WP, 0) self.setReg(reg, dat) ...
This code reads or writes the weekday value from/to a DS1302 real-time clock chip. If no weekday is provided, it returns the current weekday (0-6) by converting hexadecimal register data to decimal. If a weekday is specified, it writes the value (0-7) to the register after converting it to hexadecimal, ensuring valid i...
def Weekday(self, weekday=None): if not weekday: return self.HexToDec(self.getReg(DS1302_REG_WEEKDAY+1)) else: self.wr(DS1302_REG_WEEKDAY, self.DecToHex(weekday%8))
def HexToDec(self, dat): return (dat//16) * 10 + (dat%16) def getReg(self, reg): self.cs.value = True self.write_byte(reg) t = self.read_byte() self.cs.value = False return t def wr(self, reg, dat): self.setReg(DS1302_REG_WP, 0) self.setReg(reg, dat) ...
This method gets or sets the day value from a DS1302 RTC chip. If no day is provided, it reads the current day from register DS1302_REG_DAY+1, converts it from hex to decimal, and returns it. If a day is provided, it writes the day value (mod 32) to DS1302_REG_DAY after converting it to hex. The function handles both r...
def Day(self, day=None): if not day: return self.HexToDec(self.getReg(DS1302_REG_DAY+1)) else: self.wr(DS1302_REG_DAY, self.DecToHex(day%32))
def HexToDec(self, dat): return (dat//16) * 10 + (dat%16) def getReg(self, reg): self.cs.value = True self.write_byte(reg) t = self.read_byte() self.cs.value = False return t def wr(self, reg, dat): self.setReg(DS1302_REG_WP, 0) self.setReg(reg, dat) ...
This code interacts with a DS1302 RTC chip to either retrieve or set the current month. If no month is provided, it reads the month from the RTC's register (converted from hex to decimal). If a month is provided, it writes the month to the register after converting it to hex, ensuring values are within 1-12 via modulo ...
def Month(self, month=None): if not month: return self.HexToDec(self.getReg(DS1302_REG_MONTH+1)) else: self.wr(DS1302_REG_MONTH, self.DecToHex(month%13))
def HexToDec(self, dat): return (dat//16) * 10 + (dat%16) def getReg(self, reg): self.cs.value = True self.write_byte(reg) t = self.read_byte() self.cs.value = False return t def wr(self, reg, dat): self.setReg(DS1302_REG_WP, 0) self.setReg(reg, dat) ...
The code handles reading and writing the year value from/to a DS1302 RTC chip. If no year is provided, it reads the year from the device's register, converts it from hexadecimal to decimal, and adds 2000 to form the full year (e.g., 00 → 2000). If a year is provided, it converts the last two digits of the year to hexad...
def Year(self, year=None): if not year: return self.HexToDec(self.getReg(DS1302_REG_YEAR+1)) + 2000 else: self.wr(DS1302_REG_YEAR, self.DecToHex(year%100))
def Year(self, year=None): if not year: return self.HexToDec(self.getReg(DS1302_REG_YEAR+1)) + 2000 else: self.wr(DS1302_REG_YEAR, self.DecToHex(year%100)) def Month(self, month=None): if not month: return self.HexToDec(self.getReg(DS1302_REG_MONTH+1)) ...
This method handles date-time data by either returning current date/time components [year, month, day, weekday, hour, minute, second] when no input is provided, or setting these components using a 7-element list input. It acts as a getter when no argument is passed, and a setter when a list is provided to update the ob...
def DateTime(self, dat=None): if not dat: return [self.Year(), self.Month(), self.Day(), self.Weekday(), self.Hour(), self.Minute(), self.Second()] else: self.Year(dat[0]) self.Month(dat[1]) self.Day(dat[2]) self.Weekday(dat[3]) sel...
def join_bytes(self, data: list) -> bytes: """Converts byte array into byte sequence""" return b''.join(data) def authenticate_packet(self, data: bytes) -> str: decrypted_msg = self.decrypt_data(data) decrypted_msg = decrypted_msg.decode() if decrypted_msg.startswith(self.flag_be...
The main task of the code is to authenticate a command packet by joining its byte components, then process the packet if authentication succeeds. It combines `cmd_bits` into data, verifies authenticity via `authenticate_packet`, and triggers `process_packets` with the validated result if authentication is successful.
def get_command_response(self): data = self.join_bytes(self.cmd_bits) val = self.authenticate_packet(data) if val: self.process_packets(val)
def process_yaml(self) -> None: with open('config.yaml', 'r') as f: config = yaml.safe_load(f) self.target_ip = config['attacker']['target'] self.recv_port = config['attacker']['recv_port'] self.send_port = config['attacker']['send_port'] self.file_port = config['sha...
The main task of the code is to initialize a process by parsing YAML configurations, creating a thread for concurrent execution, and retrieving input data. The `start` method sequentially calls `process_yaml` to handle configuration files, `create_thread` to set up threading, and `get_input` to collect necessary data, ...
def start(self) -> None: self.process_yaml() self.create_thread() self.get_input()
def get_file_path(folder_name: str, file_name: str = None) -> str: return join(dirname(abspath(__file__)), f'{folder_name}{"/" + file_name if file_name else ""}') def create_connector_definition(connector_dict: dict, logger: Logger) -> ConnectorSettings: connector_settings = ConnectorSettings() connector_se...
The main task of the code is to periodically execute configurable connectors by running their associated scripts, monitor their execution, log outputs/errors, and write results to designated output folders. It reads global configurations, checks interval timers and output statuses to determine when to trigger each conn...
def main(): logger = Logger().get_logger() # Open global configs file input_file = get_file_path(RESOURCES_FOLDER, CONFIG_FILE_NAME) with open(input_file) as f: input_data = load(f) # Parse each record as a ConnectorSettings and append to a list connectors_settings = [create_connector_d...
def fetch_challenges(self, order: Order): order.CHALLENGES = {} for a in order.authorizations: protected = { "alg": "ES256", "kid": self.KID, "nonce": self.NONCE, "url": a } r = post(url=a, data=self.gene...
The main task of the code is to complete an order by fetching and verifying domain challenges, generating a Certificate Signing Request (CSR), issuing a certificate, and downloading it. It iterates through orders, processes each domain's challenges, validates them, creates a CSR with relevant domains, submits it to iss...
def complete_order(self): for order in self.ORDERS: self.fetch_challenges(order) for domain, challenges in order.CHALLENGES.items(): self.verify_challenges( order=order, domain=domain, challenges=challenges) domains = list(order.CHALLENGES.keys...
def _most_common_label(self, y): """ Find the most common label in the target values. Args: y (numpy.ndarray): The target values. Returns: any: The most common label. """ counter = Counter(y) value = counter.most_common(1)[0][0] r...
The function recursively builds a decision tree by selecting random features, finding the optimal split, and creating child nodes until stopping criteria (max depth, single class, or insufficient samples) are met, returning a node with the best split parameters and child subtrees.
def _grow_tree(self, X, y, depth=0): """ Recursively grow the decision tree. Args: X (numpy.ndarray): The data features. y (numpy.ndarray): The target values. depth (int, optional): The current depth of the node. Returns: Node: The root n...
def audio_eda(file): # load audio file with Librosa signal, sample_rate = load_audio_sample(file) # WAVEFORM # display waveform st.write("Use librosa.waveplot to diplay the [waveform](https://pudding.cool/2018/02/waveforms/) of the uploaded file. ", "The blue line is the data we're gra...
The code provides an interactive Streamlit app for audio data analysis, enabling users to upload audio files for exploratory data analysis (EDA), apply augmentation techniques (e.g., noise addition, pitch shift), or compare two audio files via spectral analysis or Dynamic Time Warping (DTW). It guides users through upl...
def audio_data_app(): st.write("Welcome to the DQW for Audio data analysis. ", "As unstructured data, audio input analysis for ", "AI models is of crucial importance. This dashboard ", "offers visualisation of descriptive statistics of a ", "audio input file uploaded...
def upload_file(): demo = st.sidebar.checkbox('Use demo data', value=False, help='Using the adult dataset') if demo: data = pd.read_csv('demo_data/tabular_demo.csv') return(data) else: data = st.sidebar.file_uploader("Upload dataset", type="csv") ...
The main task of the code is to create a structured data analysis application that allows users to perform exploratory data analysis (EDA), preprocessing, and comparison of datasets using tools like pandas-profiling, PyCaret, Sweetviz, and table-evaluator. It provides a user interface for uploading data, selecting anal...
def structured_data_app(): # the very necessary reference expander intro_text = """ Welcome to the DQW for structured data analysis. Structured data analysis is an important step in AI model development or Data Analysis. This app offers visualisation of descriptive statistics of a csv in...
def logAndPrint(msgMethodType,msg): #current_datetime=datetime.datetime.now()#.today().strftime('%Y-%h-%d') message=str(current_datetime)+"|"+msg print(message) msgMethodType(message) def scaleTiming(time,speed): ##speed range 1-255 (units=?) ##speed=0 is stopped maxSpeed=100 minSpeed=1 ...
This function detects when a motor reaches the home position. If conditions indicate it has arrived, it stops the motor, reverses direction, updates position to 0, and logs completion. If not, it logs continued movement toward another destination. It handles motor direction, timing, and position tracking during homing.
def printHomeDetected(GPIO_Home): global curPos,lastDir if debug: logAndPrint(logging.info,"Home logged") if curDest==0 and curDir==-1 and curPos!=0: #global counter2 lastDir=curDir #logAndPrint(logging.info,"printHomeDetected "+str(counter2)+" "+str(lastDir)) #c...
def logAndPrint(msgMethodType,msg): #current_datetime=datetime.datetime.now()#.today().strftime('%Y-%h-%d') message=str(current_datetime)+"|"+msg print(message) msgMethodType(message) def motorStop(): global curDir #print ("Slow down...") #for i in reversed(range(motorSpeed)): #if cu...
This function handles dump detection logic in a motor control system. When a dump is detected (curDest=1, curDir=1), it updates the current position, stops the motor, logs the event, initiates a countdown, then returns home. If not at the dump, it logs the decision to proceed home. Debug logging is enabled when 'debug'...
def printDumpDetected(GPIO_Dump): global curPos,lastDir #logAndPrint(logging.info,str(sflag)) if debug: logAndPrint(logging.info,"Dump logged") if curDest==1 and curDir==1 and curPos!=1: #global counter curPos=1 lastDir=curDir #logAndPrint(logging.info,"print...
def titleScreen(): #Title Screen logAndPrint(logging.info,"---------------------------------") logAndPrint(logging.info,"-"+prog_name+" "+str(prog_version)+" -") logAndPrint(logging.info,"-Date:"+current_datetime.today().strftime('%Y-%h-%d')+" -") logAndPrint(logging.info,"-----------...
The main task of the code is to control a robot's operation cycles based on scheduled intervals, moving it to a designated dump location while tracking cycle counts and logging status updates. It checks real-time conditions, manages emergency stops, updates next run times, and terminates after reaching the maximum cycl...
def main(ipaddress): titleScreen() #main print("Running Main") global curPos,lastDir,flag,curDest,curDir,cycle_num_max,cycle_count,next_run_datetime,current_datetime while (flag): #logAndPrint(logging.info,"Next run date/time:"+str(next_run_datetime)) current_datetime=datetime.d...
def camera_capture(self): self.__cap = cv2.VideoCapture(0) self.__frames_numbers = 1 self.__play = not self.__play self.show_frame() def pause_movie(self): if self.__cap.isOpened(): self.__cap.release() else: self.camera_capture() if self....
The main task of the code is to build a graphical user interface (GUI) with panels, buttons, and visual elements for video/image processing controls. It creates a frame layout with a white board area, progress bar, and control buttons (camera, pause, load image, select video, play, stop). It also includes an algorithm ...
def _build_widget(self, parent: ttk.Frame=None, setup: dict=dict): if parent is None : self.master.geometry('1000x1000') self.main_panel = Frame(self.master) self.main_panel.place(relx = 0.1 , rely=0.1 , relwidth=0.8 , relheight=0.8) else : self.main_panel...
def permutations(tile): return [ tile, rotate90(tile), rotate90(rotate90(tile)), rotate90(rotate90(rotate90(tile))), flipVertical(tile), rotate90(flipVertical(tile)), flipHorizontal(tile), rotate90(flipHorizontal(tile)), ] def cell_has_sea_monster(...
The code searches for a sea monster pattern in an image by checking all permutations of the image. It iterates over possible positions, verifies if a sea monster exists at each location using `cell_has_sea_monster`, and marks it with `add_sea_monster`. The function returns the permutation where a sea monster was matche...
def find_sea_monsters(image): perms = permutations(image) y_range = len(image) - len(SEA_MONSTER) x_range = len(image[0]) - len(SEA_MONSTER[0]) for perm in perms: for y in range(y_range): for x in range(x_range): if cell_has_sea_monster(perm, x, y): ...
def params(self, num) -> List[int]: params = [] for i in range(1, num + 1): param = self.memory[self.pc + i] mode = self.current_instruction_str()[-2 - i] if mode == "0": params.append(self.memory[param]) if mode == "1": p...
The code adds two values retrieved from parameters, stores their sum at a specified memory address, and increments the program counter by 4 to proceed to the next instruction.
def add(self): a, b = self.params(2) self.set(self.memory_address(3), a + b) self.pc += 4
def params(self, num) -> List[int]: params = [] for i in range(1, num + 1): param = self.memory[self.pc + i] mode = self.current_instruction_str()[-2 - i] if mode == "0": params.append(self.memory[param]) if mode == "1": p...
The code multiplies two parameters retrieved from memory, stores the result at memory address 3, and increments the program counter by 4 to proceed to the next instruction.
def mul(self): a, b = self.params(2) self.set(self.memory_address(3), a * b) self.pc += 4
def params(self, num) -> List[int]: params = [] for i in range(1, num + 1): param = self.memory[self.pc + i] mode = self.current_instruction_str()[-2 - i] if mode == "0": params.append(self.memory[param]) if mode == "1": p...
The code implements a 'less than' comparison operation by retrieving two parameters, comparing them, storing 1 if the first is less than the second or 0 otherwise in memory address 3, then incrementing the program counter by 4 to proceed to the next instruction.
def less_than(self): a, b = self.params(2) self.set(self.memory_address(3), 1 if a < b else 0) self.pc += 4
def params(self, num) -> List[int]: params = [] for i in range(1, num + 1): param = self.memory[self.pc + i] mode = self.current_instruction_str()[-2 - i] if mode == "0": params.append(self.memory[param]) if mode == "1": p...
The function compares two values retrieved from parameters, stores 1 in memory address 3 if they are equal or 0 otherwise, then increments the program counter by 4 to proceed to the next instruction.
def equals(self): a, b = self.params(2) self.set(self.memory_address(3), 1 if a == b else 0) self.pc += 4
def current_instruction(self): return self.memory[self.pc] def add(self): a, b = self.params(2) self.set(self.memory_address(3), a + b) self.pc += 4 def mul(self): a, b = self.params(2) self.set(self.memory_address(3), a * b) self.pc += 4 def set_input(self): ...
This code executes a sequence of instructions defined by opcodes until encountering opcode 99 (halt). It processes each opcode by performing corresponding operations like addition, multiplication, input/output handling, conditional jumps, comparisons, and base setting. The loop terminates when reaching opcode 99, setti...
def run(self): while self.current_instruction() != 99: opcode = self.current_instruction() % 100 if opcode == 1: self.add() elif opcode == 2: self.mul() elif opcode == 3: self.set_input() elif opcode == ...
def _CalculateAllGroups(self): """Calculates all the existing groups at each division """ if self._dTotalGroups: return tAnzsic06Unique = tuple(self._dfIndustrial[self._s_ANZSIC06_CODE_COLUMN].unique()) for sRow in tAnzsic06Unique: tGroups = re.findall(sel...
The main task of the code is to replace the "Industry_code_ANZSIC06" column in a dataset with specified "Groups" and "ExcludedGroups" columns, ensuring the operation is performed only once. It calculates all groups, replaces the relevant columns using provided names, saves the updated data to a designated path, and mar...
def PopulateGroups(self, sGroupsColumnName: str = "Groups", sExcludedGroupsColumnName: str = "ExcludedGroups"): """Task1 - replaces “Industry_code_ANZSIC06” column with the designated groups and excluded groups columns :param sGroupsColumnName: The groups column name :param sExcludedGroupsColum...