dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def readProblemType(line, lineIndex): if lineIsEmpty(line): lineIndex += 1 return 0, lineIndex if line.startswith("max"): return 1, lineIndex elif line.startswith("min"): return -1, lineIndex else: print("\nMaxmin check = False") print("Syntax Error. Wrong...
The code parses an optimization problem from a file, extracting the objective function coefficients (`c`), constraint matrix (`A`), right-hand side values (`b`), equality constraints (`Eqin`), problem type (max/min), and variable names. It reads the file line-by-line, identifies the problem type, processes the objectiv...
def parse(filename): file = None maxmin = 0 Eqin = [] A = [] b = [] c = [] Variables = [] # a list of the problem variable names e.g. x1, x2, x3, ... or x, y, z, w, ... print("Parsing...") try: file = open(filename, "r") lines = file.readlines() except FileNotF...
def parse(filename): file = None maxmin = 0 Eqin = [] A = [] b = [] c = [] Variables = [] # a list of the problem variable names e.g. x1, x2, x3, ... or x, y, z, w, ... print("Parsing...") try: file = open(filename, "r") lines = file.readlines() except FileNotF...
The code converts a primal linear programming problem into its dual form by parsing input data, computing dual parameters (including matrix inversion and sign changes), and saving the dual problem in a new file.
def convert(filename): #input cPrimal, APrimal, bPrimal, maxminPrimal, eqinPrimal, variablesPrimal = parse(filename) variablesEqinPrimal = len(cPrimal)*[1] print(2*"\n" + "Primal LP:") print("A = " + str(APrimal)) print("c = " + str(cPrimal)) print("b = " + str(bPrimal)) print("maxmin =...
def set_forward_hover(self, forward_touching): if (forward_touching and (not self.forward_hover)): self.forward_hover = True hover_image = games.load_image('images/hovered-button.png') self.responder.forward_button.set_image(hover_image) elif ((not forward_touching) a...
This function checks if forward and backward buttons are touched by sprites with ID 0, then updates hover/select states and tickers accordingly. It iterates through overlapping sprites on each button, sets internal flags based on contact, and triggers UI updates to reflect interaction states.
def update_steps(self): forward_touching = False backward_touching = False if (self.responder.forward_button): for item in self.responder.forward_button.overlapping_sprites: if (item.id == 0): forward_touching = True break ...
def handle_A(self): if (self.left_index == self.left_size): self.state = 2 if (self.steps): self.tt = 'Search For Ways To Augment Paths' self.sA = '' self.sB = '' self.sC = '' else: self.title_tex...
The code processes a sequence of states by repeatedly calling specific methods (handle_A, handle_B, handle_C, or handle_E) based on the current state value (1, 2, 3, or 5). The loop continues until the state reaches 4, at which point it executes handle_D. The primary task is to transition through predefined states and ...
def generate_steps(self): while (not (self.state == 4)): if (self.state == 1): self.handle_A() elif (self.state == 2): self.handle_B() elif (self.state == 3): self.handle_C() elif (self.state == 5): s...
def update_steps(self): forward_touching = False backward_touching = False if (self.responder.forward_button): for item in self.responder.forward_button.overlapping_sprites: if (item.id == 0): forward_touching = True break ...
This code updates game states by toggling pause/play functionality via mouse interaction and spacebar input, managing button visuals, a ticker counter for state transitions, and conditionally executing state-specific handlers (handle_A to handle_E) based on the current state.
def update(self): if (self.steps): self.update_steps() else: mouse_touching = False if (self.responder.pause_button): for item in self.responder.pause_button.overlapping_sprites: if (item.id == 0): mouse_touc...
def extract_timestamp(line, date_string): timestamp_pattern = r'^([0-9]{2}:[0-9]{2}:[0-9]{2}) ' match = re.match(timestamp_pattern, line) if match is None: return None time_string = match.group(1) return date_string + " " + time_string def extract_nickname(line): message_pattern = r'^[^ ...
This code processes a file to insert new messages into a database, checking existing entries to avoid duplicates. It extracts timestamps, user IDs, and message content from each line, logs progress, and updates the database with new records while tracking added messages and collected user IDs.
def process_file(filename, short_name, channel, user_ids): logger.debug('Processing file %s, channel #%s' % (short_name, channel['name'])) match = re.match(filename_pattern, short_name) date_string = match.group(1) cur = conn.cursor() cur.execute("SELECT COALESCE(MAX(line), 0) FROM message where s...
def manhattan_distance(state, goal_state): """ Calculate Manhattan distance heuristic between current state and goal state. """ distance = 0 for i in range(len(state)): for j in range(len(state[0])): if state[i][j] != goal_state[i][j] and state[i][j] != 0: value =...
The code implements the A* algorithm to find the shortest path from a start state to a goal state. It uses a priority queue (open_set) and a closed set to track explored nodes, prioritizing nodes based on their combined cost (g) and heuristic (h) values. When the goal is reached, it reconstructs the path via parent poi...
def a_star(start_state, goal_state): """ A* algorithm to find the shortest path from start_state to goal_state. """ start_node = Node(start_state, None, 0, manhattan_distance(start_state, goal_state)) open_set = [start_node] closed_set = set() while open_set: current_node = heapq.he...
def writeToLog(self,message): logfile = None if exists("amazonatozlog.txt"): logfile = open("amazonatozlog.txt","a") else: logfile = open("amazonatozlog.txt","w") log = "[{}]{}\n".format(datetime.now().strftime("%d/%m/%Y %H:%M:%S"),message) print(log) ...
The code initializes a bot handler for Amazon AtoZ, sets up Telegram command/message handlers, automates login via a web driver, retrieves a work ID, updates URLs, saves cookies, and prepares to fetch opportunities. It waits for a /start command to trigger login, then configures the system to access opportunity data.
def __init__(self,username,password,updater): self.username = username self.password = password amazonatoz.updater = updater self.chatID = "" startHandler = CommandHandler('start',amazonatoz.start) otpHandler = MessageHandler(Filters.text &(~Filters.command),amazonatoz.o...
def load_json_config(file_path): with open(file_path) as f: data = json.load(f) return data def generate_github_repository_block(repo_config): # Main attributes repo_block = f"""resource "github_repository" "{repo_config["name"]}" {{ name = "{repo_config["name"]}" description = "{repo...
The function parses a JSON configuration file, converts dictionaries to lists if necessary, and generates Terraform configuration blocks for GitHub repositories, branches, default branch settings, and branch protections. It concatenates these blocks into a single string for output.
def parse_json_config(file_path): data = load_json_config(file_path) # Wrap in list if data is a dictionary if isinstance(data, dict): data = [data] main_tf_content = "" for repo_config in data: # Generate blocks for each resource repo_block = generate_github_repository_block...
def get_class(node: ClassDef) -> SourceClass: """ Generates a source class based on the input node. :param node: The input node. :return: A source class. """ source_class: SourceClass = SourceClass() source_class.name = node.name source_class.bases = [base.name for base in node.bases if...
The main task of the code is to parse a Python source file into a structured `SourceFile` object, extracting classes, functions, variables, and import statements while respecting parameters like root path, known modules, and external dependency inclusion. It uses AST parsing to generate a representation of the module's...
def get_module_info( root: str, file_path: str, known_modules: list[str], with_external_dependencies: bool = False ) -> SourceFile: """ Generates a source file based on the provided file path. :param root: The root path of the analysis. :param file_path: The file path fo...
def get_education_age(self): high_school_terms = ['high school', '12', 'XII', 'secondary school'] bachelors_terms = ['bachelor', 'bachelors', 'btech', 'b.tech', 'bcom', 'b.com'] masters_terms = ['master', 'masters', 'mtech', 'mba', 'm.b.a'] data = self.load_data() educatio...
The main task of the code is to predict a person's age by prioritizing three data sources: education, work experience, and certifications. It retrieves age estimates from each source sequentially, returning the first non-null value found. If all sources fail to provide an age, it returns None, indicating no valid age p...
def predict_age(self): age_from_education = self.get_education_age() age_from_experience = self.get_experience_age() age_from_certifications = self.get_certifications_age() if age_from_education: return age_from_education elif age_from_experience: ...
def __get_initial_condition(self): """ Solve the p-Laplacian equation return: the solution of -div(|\nabla u|^{p-2}\nabla u)=f \in \Omega """ u=TrialFunction(self.V) v=TestFunction(self.V) a= dot(grad(u),grad(v))*dx L=self.f*v*dx u=Function(self.V)...
The code implements an iterative optimization algorithm to minimize an objective function. It performs gradient descent with line search, updating variables `u` and `theta` via projections. Key tasks include computing gradient norms, tracking iterations, objective values, and step sizes, while terminating when the grad...
def solve(self): """ Solve the problem. Return the functions evaluations, the length steps and the norma of the gradient. """ ts=[] dFs=[] Fs=[] mus=[] u=self.__get_initial_condition() theta=Function(self.Theta) mu,theta=self.__get...
def move(x,y) : write('\033[{};{}H'.format(y,x)) def write(o) : sys.stdout.write(str(o)) sys.stdout.flush() def random_color() : return '#{}'.format(''.join(random.choices(hex_chars,k=6)))
The code generates a dynamic, colorful terminal animation by randomly placing colored spaces across the screen. It creates all possible (x, y) positions in the terminal, shuffles them, then iterates through each, moving the cursor, writing a space with a random background color, and adding a brief delay to create a vis...
def dazzle() : term = TerminalInfo() positions = list(product(range(term.width),range(term.height))) random.shuffle(positions) for x,y in positions : move(x,y) write(bg256(random_color(),' ')) sleep(0.001)
def rect(x1,y1,x2,y2,color) : term = TerminalInfo() positions = list( product( range(max(0,x1),min(x2,term.width)), range(max(0,y1),min(y2,term.height)) ) ) for x,y in positions : move(x,y) write(bg256(color,' ')) def move(x,y) : ...
The code defines a `banner()` function to draw a stylized terminal banner. It calculates terminal dimensions, draws a black rectangle, and writes two skewed, shadowed text lines ("terminal" and "quest") at specific vertical positions using a predefined color. The banner likely serves as a header or visual element in a ...
def banner() : term = TerminalInfo() voffset = 4 rect(0,int(term.height/voffset-2),term.width,int(term.height/voffset+26),'#000') move(0,int(term.height/voffset)) write(text.Text(' terminal',skew=5,shadow=True,color=banner_color)) move(0,int(term.height/voffset+12)) write(text.Text(' ques...
def clear() : write('\033[2J') def move(x,y) : write('\033[{};{}H'.format(y,x)) def type_text(text,speed=0.03) : variance = 1 for c in str(text) : write(c) jitter_speed = speed*((1-variance/2)+random.random()*variance)**2 sleep(jitter_speed) def set_echo_and_icanon(flag) : if...
The main task of the code is to display a celebratory message sequence in green text with varying speeds, simulate a reward "dazzle" effect, and promote a sequel game "Terminal Temple" with a URL. It clears the terminal, positions text, manages terminal settings, and displays closing credits with delays between each st...
def fini(): clear() move(0,0) sleep(3) type_text(green("oh hey"),speed=0.1) sleep(3) type_text(green("\n\nyou did it"),speed=0.1) sleep(3) type_text(green("\n\nthat was fun"),speed=0.08) sleep(3) type_text(green("\n\nthanks for playing"),speed=0.08) sleep(3) type_text(g...
def getRateX(self): return ((self.readShortFromRegister(RA_GYRO_XOUT_H, 2)) / GYRO_SENSITIVITY) - self.centerX def getRateY(self): return ((self.readShortFromRegister(RA_GYRO_YOUT_H, 2))/GYRO_SENSITIVITY) - self.centerY def getRateZ(self): return ((self.readShortFromRegister(RA_G...
The code calibrates the ITG3200 sensor by collecting acceleration rate samples over a specified time, averaging the X, Y, Z values, and storing them as the sensor's baseline "center" values for later use in calculations.
def calibrate(self, time=10.0, samples=100): """ Calibrate Watch out, this will actually pause the robot :param samples: The amount of samples to take :param time: The time to calibrate :return: """ gathered = 0 calX = 0 calY = 0 c...
def getRateX(self): return ((self.readShortFromRegister(RA_GYRO_XOUT_H, 2)) / GYRO_SENSITIVITY) - self.centerX def getRateY(self): return ((self.readShortFromRegister(RA_GYRO_YOUT_H, 2))/GYRO_SENSITIVITY) - self.centerY def getRateZ(self): return ((self.readShortFromRegister(RA_G...
This method updates the object's orientation angles (X, Y, Z) by multiplying the angular rates (getRateX/Y/Z) with the time delta (dt converted from milliseconds to seconds), accumulating the result into self.angleX/Y/Z. It applies a time-step correction to simulate rotational motion over time.
def update(self, dt=50): """ :param dt: Delta time in milliseconds :return: """ # TODO: Filter out data? Use accel? real_dt = dt/1000 # Turn ms into seconds self.angleX += self.getRateX() * real_dt self.angleY += self.getRateY() * real_dt self...
def getRateX(self): return ((self.readShortFromRegister(RA_GYRO_XOUT_H, 2)) / GYRO_SENSITIVITY) - self.centerX def getRateY(self): return ((self.readShortFromRegister(RA_GYRO_YOUT_H, 2))/GYRO_SENSITIVITY) - self.centerY def getRateZ(self): return ((self.readShortFromRegister(RA_G...
The code defines a method `getRate` that returns the rate value for a specified axis (X, Y, or Z) by delegating to corresponding private methods `getRateX`, `getRateY`, or `getRateZ`. Its main task is to route the axis-specific rate calculation request to the appropriate method based on the input parameter.
def getRate(self, axis): if axis == Axis.X: return self.getRateX() if axis == Axis.Y: return self.getRateY() if axis == Axis.Z: return self.getRateZ()
def getPIDSourceType(self): return self.pidSourceType def getRate(self, axis): if axis == Axis.X: return self.getRateX() if axis == Axis.Y: return self.getRateY() if axis == Axis.Z: return self.getRateZ() def getAngle(self, axis): if axis == Ax...
The main task of the code is to retrieve either the rate or angle value based on the PID source type. If the source type is "kRate," it returns the rate using `getRate`; otherwise, it returns the angle using `getAngle` for the specified PID axis.
def pidGet(self): if self.getPIDSourceType() == PIDSource.PIDSourceType.kRate: return self.getRate(self.pidAxis) else: return self.getAngle(self.pidAxis)
def testConnection(self): return self.getDeviceID() == 0b110100 def setFullScaleRange(self, range): self.writeBits(RA_DLPF_FS, DF_FS_SEL_BIT, DF_FS_SEL_LENGTH, range) def setSleepEnabled(self, enabled): self.writeBit(RA_PWR_MGM, PWR_SLEEP_BIT, enabled) def setStandByXEnabled(self, enabled): ...
The code initializes the ITG3200 gyroscope by checking I2C addressing and connection validity, applying configuration settings (full-scale range, power modes, clock source, interrupts), and enabling the device if successful. Errors trigger warnings and disable the device.
def init(self): if self.i2c.addressOnly(): wpilib.DriverStation.reportError("Could not address ITG3200", False) self.enabled = False # return False if not self.testConnection(): wpilib.DriverStation.reportError("Could not connect to ITG3200", False) ...
def displayInformation(self): ''' Displays information in the lower interface of simulation window. ''' self.informativeText_1 = Text(Point(0, -105), 'Click anywhere inside the habitat to spawn a new organism.') self.informativeText_1.setSize(20) self.informativeText_1.draw(self.window) self.plantExamp...
The code runs a simulation by displaying initial information, waiting for user input, spawning organisms, and executing a loop to update the simulation for a predefined number of ticks. After completion, it pauses briefly and terminates all remaining organisms.
def runSim(self): ''' Runs the simulation from start to finish. ''' self.displayInformation() self.waitForClick() self.spawnOrganisms() self.keepRunning = True for i in range(gameTicks): self.update() time.sleep(2) # destroy all remaining organisms for organism in self.organisms: organi...
def getClickedSquareCoordinates(self, pos): x_index = math.floor(pos[0]/self.getFieldSize()) y_index = math.floor(pos[1]/self.getFieldSize()) return [x_index, y_index] def deselectAllPieces(self): for i in self.board: for j in i: if j is None: ...
This method handles mouse clicks on a board game interface. It identifies the clicked square, logs the action, deselects all pieces, and either moves a selected piece to a valid position or triggers actions on clicked game elements. If no piece is clicked, it checks for valid moves; if a piece is clicked, it selects it...
def handleClick(self, pos): clickedCoordinates = self.getClickedSquareCoordinates(pos) clicked_x, clicked_y = clickedCoordinates clickedThing = self.board[clicked_y][clicked_x] logging.debug("Click registered at " + str(clicked_x) + "," + str(clicked_y) + ": object " + str(clickedThing))...
def apply_filters(self, node, filters, filter_params): """ given filters and a node, return True if node satisfies all filters """ satisfy = True for filter, filter_param in zip(filters, filter_params): satisfy = satisfy and getattr(self, filter)(node, **filter_param)...
This code applies filters to identify nodes in a graph, binds parameters to these nodes, transforms them using specified logic, and updates the graph's edges to reflect changes. It iterates through nodes, applies filters, binds parameters, stores transformed results, and updates the abstracted graph structure with modi...
def apply(self, filters, filter_params, transformation, transformation_params): """ perform a full operation on the abstracted graph 1. apply filters to get a list of nodes to transform 2. apply param binding to the filtered nodes to retrieve parameters for the transformation 3. ...
def kineFactor_GE_GM( ratio_err, particle, flavor, mEff, p_fin, Q, L, mpi_info ): finalMomentaNum = ratio_err.shape[ 0 ] QNum = ratio_err.shape[ 1 ] ratioNum = ratio_err.shape[ -1 ] binNum = len( mEff ) if p_fin.shape[ 0 ] != finalMomentaNum: error_template = "Error ...
The function `kineFactor` selects and computes a kinematic factor based on the specified `formFactor` parameter. It routes input parameters like `ratio_err`, `mEff`, `p_fin`, `Q`, `L`, and `mpi_info` to corresponding helper functions (e.g., `kineFactor_GE_GM`, `kineFactor_BT10`) tailored to different form factor models...
def kineFactor( ratio_err, formFactor, particle, flavor, mEff, p_fin, Q, L, mpi_info ): if formFactor == "GE_GM": kineFactor = kineFactor_GE_GM( ratio_err, particle, flavor, mEff, p_fin, Q, L, mpi_info ) eli...
def pgn_iter(games_file): buffer_size = 1024 * 1024 cursor = 0 bookmark = 0 headers, moves = None, None needle = re.compile(r"\n\n") with open(games_file, "r") as f: haystack = f.read(buffer_size) while haystack: for match in re.finditer(needle, haystack): ...
The main task of the code is to process chess games from a file, extract key positions (opening, middlegame, endgame) with metadata (ELO, move validity, time control, etc.), and save them into separate JSONL files. It randomly samples games, walks through moves to identify phase transitions, and stores positions in a s...
def main(games_file): """ Notes: open games_file get first game load into python-chess Walk the game move by move Index key moments - note the ply when the game transitions to middlegame and to endgame Add to "position" database - No ply 0, 1, or 2 ...
def augment_classical_residual_stream(classical_residual_stream): #takes an n_ctx-by-d_model matrix, adds a row of 0s to the bottom, and a square identity matrix to the right #resulting matrix is (n_ctx+1)-by-(d_model+n_ctx+1) matrix n_ctx=classical_residual_stream.shape[0] d_model=classical_residual_st...
The main task of the code is to create and apply an attention head that applies the SiLU activation function to a specific channel of the residual stream. It constructs query/key (W_QK) and output/value (W_OV) weight matrices tailored for the given channel, processes an augmented residual stream through an attention me...
def SiLU_head_on_one_channel(classical_residual_stream, channel_to_focus, Omega=1000): # creates and applies an attention head which will apply SiLU to one dimension of the residual stream n_ctx=classical_residual_stream.shape[0] d_model=classical_residual_stream.shape[1] augmented_residual_stream=augme...
def augment_classical_residual_stream(classical_residual_stream): #takes an n_ctx-by-d_model matrix, adds a row of 0s to the bottom, and a square identity matrix to the right #resulting matrix is (n_ctx+1)-by-(d_model+n_ctx+1) matrix n_ctx=classical_residual_stream.shape[0] d_model=classical_residual_st...
The function applies a linear transformation with attention mechanisms to an augmented residual stream. It constructs augmented matrices (W_QK_augmented, W_OV_augmented) using the input weight matrix and a scaling factor (Ω). The augmented residual stream undergoes an attention head operation with these matrices, and t...
def linear_transformation_with_augmentation(classical_residual_stream, weight_matrix, Omega=1000): # augments a residual stream to implement the weight matrix n_ctx=classical_residual_stream.shape[0] d_model=classical_residual_stream.shape[1] augmented_residual_stream=augment_classical_residual_stream(...
def augment_classical_residual_stream(classical_residual_stream): #takes an n_ctx-by-d_model matrix, adds a row of 0s to the bottom, and a square identity matrix to the right #resulting matrix is (n_ctx+1)-by-(d_model+n_ctx+1) matrix n_ctx=classical_residual_stream.shape[0] d_model=classical_residual_st...
This function implements an augmented attention mechanism by modifying a residual stream and weight matrices. It augments the residual stream, constructs a context vector attention matrix, extends the weight matrices with this context, computes an attention head, and returns the sum of the augmented residual stream and...
def normal_attention_with_augmentation(classical_residual_stream, W_QK_classical, W_OV_classical, Omega=1000): # augments a residual stream and the W_QK and W_OV matrices to produce the same result as if there was no augmentation n_ctx=classical_residual_stream.shape[0] augmented_residual_stream=augment_cla...
def augment_classical_residual_stream(classical_residual_stream, zero_out_identity_matrix=False): # pads out a matrix by adding a row of 0s to the bottom, and a square identity matrix to the right # resulting matrix is (n_ctx+1)-by-(d_model+n_ctx+1) matrix # inputs: # - classical_residual_stream - the...
The function applies a linear transformation to a residual stream using an augmented attention mechanism. It enhances the input residual stream, constructs specialized weight matrices (W_QK and W_OV) with a scaling factor Omega, computes an attention head output, and returns the sum of the augmented residual stream and...
def linear_transformation_with_augmentation(classical_residual_stream, weight_matrix, Omega=1000): # augments a residual stream to implement the weight matrix n_ctx=classical_residual_stream.shape[0] d_model=classical_residual_stream.shape[1] augmented_residual_stream=augment_classical_residual_stream(...
def augment_classical_residual_stream(classical_residual_stream, zero_out_identity_matrix=False): # pads out a matrix by adding a row of 0s to the bottom, and a square identity matrix to the right # resulting matrix is (n_ctx+1)-by-(d_model+n_ctx+1) matrix # inputs: # - classical_residual_stream - the...
This function computes an attention mechanism with data and matrix augmentation. It augments the residual stream and weight matrices (W_QK, W_OV) to simulate non-augmented behavior. The context vector attention is constructed using Omega and matrix operations, then combined with original matrices. The augmented inputs ...
def normal_attention_with_augmentation(classical_residual_stream, W_QK_classical, W_OV_classical, Omega=1000): # augments a residual stream and the W_QK and W_OV matrices to produce the same result as if there was no augmentation n_ctx=classical_residual_stream.shape[0] augmented_residual_stream=augment_cla...
def augment_classical_residual_stream(classical_residual_stream, zero_out_identity_matrix=False): # pads out a matrix by adding a row of 0s to the bottom, and a square identity matrix to the right # resulting matrix is (n_ctx+1)-by-(d_model+n_ctx+1) matrix # inputs: # - classical_residual_stream - the...
This function applies an attention head to a residual stream, using SiLU activation on one hidden dimension. It constructs query-key (W_QK) and output-value (W_OV) matrices from given weights, augments the residual stream, and computes the attention head's output. The process transforms the input through a modified fee...
def FFN_on_one_hidden_dimension(classical_residual_stream, W_1, W_2, hidden_dimension, Omega=1000): # creates and applies an attention head which will apply SiLU to one dimension of the residual stream n_ctx=classical_residual_stream.shape[0] d_model=classical_residual_stream.shape[1] augmented_residual...
def normal_attention_with_augmentation(classical_residual_stream, W_QK_classical, W_OV_classical, Omega=1000): # augments a residual stream and the W_QK and W_OV matrices to produce the same result as if there was no augmentation n_ctx=classical_residual_stream.shape[0] augmented_residual_stream=augment_cla...
The function `test_augmented_attention` compares two implementations of an attention head in a transformer model. It computes attention outputs using a direct method (with residual stream and attention head) and an augmented method (with an additional vector). It checks if their results match within a specified error t...
def test_augmented_attention(test_residual_stream, test_W_QK, test_W_OV, Omega=1000, error_tolerance=10**-10): # compares result of an attention head implemented: # - directly (as in a normal transformer) # - directly (with the additional vector) # parameters: # - test_residual_stream - an n_c...
def normal_attention_with_augmentation(classical_residual_stream, W_QK_classical, W_OV_classical, Omega=1000): # augments a residual stream and the W_QK and W_OV matrices to produce the same result as if there was no augmentation n_ctx=classical_residual_stream.shape[0] augmented_residual_stream=augment_cla...
The function compares two attention implementation methods: (1) a standard attention head with augmentation and (2) a direct residual stream augmentation approach. It calculates outputs using both methods, computes the maximum absolute difference between results, and checks if the error stays below a threshold. If so, ...
def test_augmented_attention(test_residual_stream, test_W_QK, test_W_OV, Omega=1000, error_tolerance=10**-10): # compares result of an attention head implemented: # - directly (as in a normal transformer) # - directly (with the additional vector) # parameters: # - test_residual_stream - an n_c...
def FFN_on_all_hidden_dimensions(classical_residual_stream, W_1, W_2, Omega=1000): # creates and applies attention heads which apply an FFN parameterized by W_1 and W_2 # returns the total head output (to be added to the residual stream) total_head_output=sum([FFN_on_one_hidden_dimension(classical_residual_...
The main task of the code is to verify the equivalence of two Feed-Forward Network (FFN) implementations—attention-based and direct—by comparing their outputs on a residual stream. It computes both results, checks their maximum absolute difference, and prints a success message if the error is below a tolerance threshol...
def test_FFN(test_residual_stream, W_1, W_2, Omega=1000, error_tolerance=10**-10): # compares result of applying an FFN: # - directly # - with attention heads # parameters: # - test_residual_stream - an n_ctx-by-d_model array # - Omega - the large number that overwhelms softmaxes # ...
def choice_back_door(): print("Try to open the back door.") print("It creaks open...") print("Do you:") print("1. You enter the house.") print("2. Give up and go home \n") choice = input("Choose: ") if choice == '1': choice_enter_house() elif choice == '2': choice_go_home() ...
The main task of the code is to present the user with choices after encountering a locked front door, directing them to check the back door or give up, while handling invalid inputs by recursively prompting for a valid choice.
def choice_front_door(): print("Try the front door.") print("It's locked.") print("Do you:") print("1. Check around back") print("2. Give up and go home \n") choice = input("Choose: ") if choice == '1': choice_back_door() elif choice == '2': choice_go_home() else: ...
def choice_front_door(): print("Try the front door.") print("It's locked.") print("Do you:") print("1. Check around back") print("2. Give up and go home \n") choice = input("Choose: ") if choice == '1': choice_back_door() elif choice == '2': choice_go_home() else: ...
The main task of the code is to display a text-based game menu offering options to interact with a spooky house scenario. It prompts the user to choose between attempting the front door, sneaking around back, going home, or quitting. Based on input, it calls corresponding functions (e.g., choice_front_door()), handles ...
def main_menu(): print("Main Menu") print("You're in front of a spooky old house...") print("Do you:") print("1. Try the front door") print("2. Sneak around back") print("3. Forget it and go home") print("4. [Quit] \n") choice = input("Choose: ") if choice == '1': choice_fron...
def __create_base_files(graph, id): n = graph.number_of_nodes() m = graph.number_of_edges() edgelists = nx.generate_edgelist(graph, data=False) paths = __get_paths(id) os.makedirs(paths['folder'], exist_ok=True) with open(paths['data'], 'w') as f: f.write(f'{n} {m}\n') f.write...
The function `get_clique_counts` computes the number of cliques of varying sizes (from 3 to the total number of nodes) in a given graph. It initializes necessary files, iterates through potential clique sizes, uses a helper function to count cliques for each size, stops early if no cliques are found, cleans up temporar...
def get_clique_counts(graph, id="graph"): # Create base files __create_base_files(graph, id) n = graph.number_of_nodes() clique_counts = {} for k in range(3, n+1): clique_counts[k] = __get_k_clique_count(id, k) if clique_counts[k] == 0: break __cleanup(id) ...
def __create_base_files(graph, id): n = graph.number_of_nodes() m = graph.number_of_edges() edgelists = nx.generate_edgelist(graph, data=False) paths = __get_paths(id) os.makedirs(paths['folder'], exist_ok=True) with open(paths['data'], 'w') as f: f.write(f'{n} {m}\n') f.write...
The main task of the code is to count the number of k-cliques in a given graph. It creates temporary files for processing, computes the clique count using a helper function, and cleans up resources afterward. The function returns the total count of k-clique subgraphs in the input graph.
def get_k_clique_count(graph, k, id="graph"): # Create base files __create_base_files(graph, id) count = __get_k_clique_count(id, k) __cleanup(id) return count
def traj_segment_generator(agents, env, horizon, num, comm_weight, explo_iters, deviation, stochastic, num_options, seed): ### Initialize basic data start=time.time() t = 0 comm_weight = comm_weight timer = 0.1 glob_count = 0 glob_count_thresh = -1 # Initialize current states print(...
The code implements a multi-agent Proximal Policy Optimization (PPO) algorithm to train policies in a reinforcement learning environment. It optimizes policies using clipped surrogate objectives, entropy regularization, and advantage estimation. The training involves collecting trajectories, updating policies via Adam ...
def learn(env, policy_func, *, timesteps_per_batch, # timesteps per actor per update clip_param, entcoeff, # clipping parameter epsilon, entropy coeff optim_epochs, optim_stepsize, optim_batchsize, # optimization hypers gamma, lam, # advantage estimation comm_weight...
def fitness(self,genome,genome_reduced=False, background_genome=None): """Fitness function used to evaluate genomes. Arguments: genome -- genome sequence to be evaluated (String) Keyword arguments: genome_reduced -- whether the genome given is reduced (Boolean) backgrou...
The code maps and evaluates mutations around given seed genomes by calculating their fitness, reducing genome complexity, and recursively exploring neighboring mutations. It builds a mutation network stored in `self.mutation_network`, using seed genomes as starting points for landscape analysis. The process initializes...
def map(self,seed_genomes): """Maps and evaluates relevant mutations given object parameters Saves result in self.mutation_network property. Arguments: seed_genomes -- genome or list of genomes used as background for mutations (String or list of Strings) """ ...
def generate_constraint(model, cells, constraint) -> ExpressionBase: return sum(model.cells[cell] for cell in cells) == sum(constraint) def row(idx, COLS) -> List[Cell]: return [(idx, col) for col in range(COLS)] def col(idx, ROWS) -> List[Cell]: return [(row, idx) for row in range(ROWS)] def gen_disj( ...
The code solves a logic puzzle by maximizing the number of filled cells in a grid, adhering to given row and column constraints. It uses Pyomo to define a binary optimization model, where each cell is a binary variable. Constraints are generated for each row and column to satisfy the provided rules. Disjunctions repres...
def solve_puzzle(row_constraints, col_constraints) -> Iterator[Cell]: # row_constraints = load_input("Row constraints: ") # col_constraints = load_input("Col constraints: ") ROWS = len(row_constraints) COLS = len(col_constraints) index_list = [ (i, j) for i in range(len(row_constraints)) f...
def BuildBaseModel(self, vars): model = cp_model.CpModel() self.InitializeModel(model, vars) # Make sure that every ride has at least one group. for r in range(0, self.params.num_rides): bools = [] for k in vars.group_active: if k[0] == r: bools.append(vars.group_active[k]...
The code optimizes group sizes and pairings for rides using a constraint programming model. It first builds a base model, optimizes group numbers and participant/leader counts, logs results, then uses these as hints to optimize pairings. Finally, it generates rosters based on the optimized groupings, ensuring constrain...
def Solve(self): print('Optimizing group size...') vars = Vars() model = self.BuildBaseModel(vars) self.OptimizeGroupSize(model, vars) print(model.ModelStats()) printer = Printer(vars, self.riders) solver = cp_model.CpSolver() solver.parameters.log_search_progress = True solver.para...
def find_closest_date_file(target_date, sentinel2_list): """ Find the file in the directory with the date closest to the target date. """ closest_file = None min_diff = float('inf') for file in sentinel2_list: # Extracting the date from the file name (assuming YYYYMMDD format after seco...
The code processes tower retrieval data (DHR, BHR, TOC_R) by upscaling them using Sentinel-2 satellite data. It identifies relevant files, calculates cloud ratios, matches dates, applies corrections, and generates output CSVs with uncertainties. The process involves iterating through tower data, finding closest Sentine...
def main(): tower_retrieval_dir = '../ReferenceMeasurements/OUTPUT_dhr_bhr_tocr' sentinel2_dir = '/gws/nopw/j04/gbov/ruis/gbov/Sentinel2' OUTPUT_dir = './OUTPUT' cloud_ratio_threshold = 0.2 os.makedirs(OUTPUT_dir, exist_ok=True) upscale_filelist = [] for file in os.listdir(tower_retrieval...
def read_station_information_file(self, station_information_file): hams = [] # will be a list of dicts infile = open(station_information_file, 'r') infile.readline() # skip the header line 1 infile.readline() # skip the header line 2 for line in infile: line = sel...
This code initializes a database for ham radio station reports. If `recreate_database` is True, it backs up the existing database, reads station locations, fetches data from a Google Sheet, creates a new database, and populates it with reports. Otherwise, it connects to an existing database. It then loads station data ...
def __init__(self, report_database_filename, station_locations_filename=None, spreadsheet_id=None, range_name=None, google_key=None, recreate_database=False): """ :param str report_database_filename: SQL file created ...
def compute_capacities(settings, df): #chosen_node_set = ALL_NODE_SET chosen_node_set = settings.chosen_node_set nodes_without_units = {n.split(" ")[0] for n in chosen_node_set} CapacityData(df).set_chosen_node_set(nodes_without_units).compute() def tier_training_set(settings, satSetDF): tiering_metr...
The function performs a SAT analysis on training and test datasets by computing capacities, SW bias, clustering training data, matching test codelets to clusters, calculating SI-based metrics, and generating statistics. It returns cluster info, matched test codelets, summary statistics, and tiering results, with option...
def do_sat_analysis(optimal_data_df, testSetDF, settings=SatAnalysisSettings()): compute_capacities(settings, optimal_data_df) # If SI Analysis is disabled # Creating an empty Dataframe with column names only SI_SAT_NODES and SI_CLUSTER_NAME if settings.disable: testSetDF[NonMetricName.SI_CLUSTER...
def compute_capacities(settings, df): #chosen_node_set = ALL_NODE_SET chosen_node_set = settings.chosen_node_set nodes_without_units = {n.split(" ")[0] for n in chosen_node_set} CapacityData(df).set_chosen_node_set(nodes_without_units).compute() def tier_training_set(settings, satSetDF): tiering_metr...
The code processes a training dataset to determine optimal tiering thresholds for system analysis. It computes capacities, clusters data based on metrics, merges threshold information, generates range values, and expands metrics into individual rows. Finally, it prepares data for visualization, computes capacities agai...
def tiering_only(args): NUM_POINTS=3 SMALL = np.finfo(float).eps * 100 SMALL = 0.001 training_set_csv = args.training_csv_file chosen_node_set = ALL_NODE_SET settings = SatAnalysisSettings(satThreshold=float(args.sat_threshold), cuSatThreshold=float(args.cu_sat_threshold), chosen_node_set=chosen...
def irt(data, val_data, lr, iterations): """ Train IRT model. You may optionally replace the function arguments to receive a matrix. :param data: A dictionary {user_id: list, question_id: list, is_correct: list} :param val_data: A dictionary {user_id: list, question_id: list, is_correct: list}...
Your return The code trains an IRT model using training data, tunes learning rate (0.01) and iterations (50), and evaluates validation/test accuracy. It plots training/validation log-likelihoods over iterations, then visualizes probability curves for top 3 questions against theta values. The main tasks are: (1) IRT mod...
def main(): train_data = load_train_csv("../data") # You may optionally use the sparse matrix. sparse_matrix = load_train_sparse("../data") val_data = load_valid_csv("../data") test_data = load_public_test_csv("../data") ##################################################################### ...
def get_index(node): return pow(7, node[0]) * pow(5, node[1]) def transition(old, new, jugs): #Get the amount of water from old state/node for first Jug a = old[0] #Get the amount of water from old state/node for second Jug b = old[1] #Get the amount of water from new state/node for first J...
This code implements a search algorithm (BFS or DFS) to solve a water jug problem, finding a sequence of moves to reach a target amount. It explores states using a queue, tracks visited nodes, and prints the solution path if achievable, otherwise indicating failure.
def search(starting_node, jugs, goal_amount, check_dict, is_breadth): if is_breadth: print("Implementing BFS...") else: print("Implementing DFS...") goal = [] accomplished = False q = collections.deque() q.appendleft(starting_node) while len(q) != 0: p...
def check_centers(x0, y0, z0, centers, r): for i in range(len(centers)): if too_close(x0, y0, z0, centers[i], r): return True return False def add_virtual_particle(s, vtype, sys_topology, x, y, z, rpid): vpid = len(s.part) s.part.add(id=vpid, type=vtype, pos=[x, y, z]) s.part[vpi...
The code generates ring-like filament structures by placing particles and virtual particles in circular arrangements. It ensures non-overlapping positions, connects virtual particles with bonds to form rings, and returns the system topology containing all particles and bonds.
def generateRings(s, ext_params, particle_params, bond): fn, fl = ext_params.fn, ext_params.fl mom = particle_params.mom rtype, vtype = particle_params.rtype, particle_params.vtype sys_topology = SysTopology([], [], [], []) R = bond_length / (2 * sin(pi / fl)) dTheta = 2 * pi / fl radius = ...
def is_move(category): return category in {'move.b', 'move.w', 'move.l'} def disassemble_move(bits, data, offset): category = OPCODE_CATEGORIES[bits[0:4]] total_added = 2 # dst: reg|mode dst_op, added = operand(category[-1], bits[7:10], bits[4:7], data, offset) total_added += added # src: m...
This function disassembles a 16-bit instruction from given data starting at a specified offset, categorizes it by opcode, and generates an abstract syntax tree (AST) representation of the instruction using helper functions for different operation types like moves, arithmetic, branches, and bit operations, returning str...
def _disassemble(data, offset): bits = "{0:016b}".format(struct.unpack(">H", data[offset:offset+2])[0]) # first step categorize by looking at bits 15-12 opcode = bits[0:4] category = OPCODE_CATEGORIES[opcode] if is_move(category): instr = disassemble_move(bits, data, offset) elif catego...
def compute_force(self): self.F_f.fill(0) for i in self.F_f: self.F_f[i] -= self.mass * self.gravity dt = self.dt self.F_f[0] += self.mass * self.manipulate_acc[None] for i in range(self.NE): xx, yy = self.e2v[i] base_len = self.l_i[i] ...
This code defines a `step` method that selects and executes a specific numerical integration technique based on the input string `s`. It dispatches to `compute_force` and method-specific steps like `step_explicit`, `step_symplectic`, etc., to update the system's state. The function handles four integration schemes: exp...
def step(self, s): if s == "explicit": self.compute_force() self.step_explicit() elif s == "symplectic": self.compute_force() self.step_symplectic() elif s == "midpoint": self.compute_force() self.step_midpoint_pos() ...
def learn_from_pos(self): actual_components = self.perceives() self.kb[4-self.r, self.c-1][S] = ("S" if "S" in actual_components else "~S") self.kb[4-self.r, self.c-1][B] = ("B" if "B" in actual_components else "~B") self.kb[4-self.r, self.c-1][P] = ("P" if "P" in actua...
The main task of the code is for the `GoldDigger` agent to navigate a grid-based environment, avoiding walls and pits, to locate the gold ('G'). It tracks the path taken, adjusts the score by adding 1000 upon finding gold, and subtracts the path length from the score. The agent uses a knowledge base to identify safe ad...
def find_gold(self): path = [] gold = False while not gold: print(f"GoldDigger is on: {self.r}, {self.c}") self.learn_from_pos() path.append([self.r, self.c]) next_xy = [] if 'G' in self.perceives(): gold = True ...
def clean_text(self): return list( map(lambda w: self.clean_w(w), self.corpus) ) def count_match(self): match = map(lambda w: {a: w.count(a) for a in w}, self.corpus) return {uuid: a for uuid, a in zip(self.uuids, match)} def transform_tf(self): _ret = { d...
The code processes a text corpus by cleaning the text, calculating term frequencies (TF), inverse document frequencies (IDF), and generating TF-IDF values for each document. It initializes attributes for UUIDs, cleaned corpus, word matches, TF, IDF, and final TF-IDF vectors, enabling text analysis tasks like informatio...
def __init__(self, corpus: dict): self.uuids, self.corpus = corpus.keys(), list(corpus.values()) self.corpus = self.clean_text() self.words_match = self.count_match() self.tfreq = self.transform_tf() self.idf = self.transform_idf() self.val_tfidf = self.transform_tfidf()
def find_by_key(data, target): for key, value in data.items(): if isinstance(value, dict): find_by_key(value, target) elif key == target: return value return 'NOT_FOUND' def name_resources(file_name, file_json): # Check for: # FHIRVersion key in json ...
This function processes an HTTP request to import FHIR resources from a Google Cloud Storage JSON file into a FHIR store. It decodes the request, validates the JSON file, extracts resource type, constructs API payloads, creates necessary FHIR datasets/stores if missing, and imports the FHIR data using the Healthcare AP...
def fhir_to_fhirstore(request): """Responds to any HTTP request. Args: request (flask.Request): HTTP request object. Returns: The response text or any set of values that can be turned into a Response object using `make_response <http://flask.pocoo.org/docs/1.0/api/#flask.Flas...
def createMesh(): triangulos = [] triangulos.append([8,1,9,'R']) triangulos.append([2,1,9,'R']) triangulos.append([10,3,9,'R']) triangulos.append([2,3,9,'R']) triangulos.append([5,1,4,'R']) triangulos.append([2,1,4,'R']) triangulos.append([2,3,4,'R']) triangulos.append([13,3,4,'...
The code solves a finite element problem by assembling a stiffness matrix (K) and applying boundary conditions (via K_front and H). It computes the displacement vector X by solving the linear system K*X = g, where g is derived from force vector B and boundary adjustments. The function returns the computed solution vect...
def finiteElements(f,h): mesh = createMesh() K,K_front = createCoeffMatrix(mesh) B,H = vectorBH(mesh,h,f) #H = np.asarray([0,-1,-1,-1,-1,0,1,1,1,1]) g=B-K_front.dot(H) X = np.linalg.solve(K, g) return X
def get_conda_bin(module): conda_bin = find_executable('conda') if not conda_bin: for path in POTENTIAL_CONDA_PATHS: if os.path.isfile(os.path.join(path, 'conda')): conda_bin = os.path.join(path, 'conda') if not conda_bin: module.fail_json(msg="Could not find co...
This Ansible module manages Conda package installations/upgrades/removals. It accepts parameters like package names, upgrade flags, environments, and channels. The module normalizes state values (present/absent), checks for conda availability, and executes install/upgrade operations based on input. It supports check mo...
def main(): module = AnsibleModule( argument_spec=dict( name=dict(aliases=['pkg', 'package']), upgrade = dict(default=False, type='bool'), channels = dict(default=False, type='list', required=False), environment = dict(default=False, type='str', required=False...
def update(G, color_map, pos, algorithm, t): fig = generateFigure(G, color_map, pos) plt.savefig("%s_%d.eps"%(algorithm,t), dpi=300, bbox_inches='tight') raw_data, size= getRawData(fig) drawFig(raw_data,size) pygame.display.update() clock.tick(fps) pygame.time.delay(time_delay) def searc...
This code executes a specified pathfinding algorithm (BFS, DFS, UCS, Greedy, A*) on a grid, visualizes the search process through graph updates and animations, and highlights the found path. It reads input data, initializes a graph structure, runs the chosen algorithm to determine visited nodes and the optimal path, th...
def run(input, algorithm, delay): global time_delay time_delay=delay matrix, start, end=readMatrix(input) G, pos, color_map=initialize(matrix) t = 1 update(G, pos, color_map, algorithm, t) if algorithm == 'bfs': visited, path = BFS(matrix, start, end) elif algorithm == 'dfs': ...
def getOrdersByDate(deliveryDate): try: sqlcursor = mysqldb.cursor() query = f"SELECT * FROM orders o, users u WHERE o.userId=u.id AND o.deliveryDate=\'{deliveryDate}\'" sqlcursor.execute(query) result = sqlcursor.fetchall() return result except Exception as e: print(e) finally: sqlcursor.close() def ...
The main task of the code is to process orders by delivery date, group them by city, compute optimal delivery routes using warehouse locations and distance matrices, and store routing results in a database. It decodes input data, maps orders and warehouses, calculates shortest paths for each city, and inserts route det...
def routeOrders(ch, method, properties, body): req_body = json.loads(body.decode('utf-8')) deliveryDate = req_body['deliveryDate'] ######## Testing variables ######## # deliveryDate = body['deliveryDate'] # cities = body['cities'] # orders = getOrdersByDateAndCity(deliveryDate, cities) # print(len(orders)) ####...
def restart_driver(): global browser try: browser.quit() except Exception as e: print(f"Error closing the driver: {e}") options = webdriver.ChromeOptions() chrome_prefs = {} chrome_prefs["profile.default_content_settings"] = {"images": 2} chrome_prefs["profile.managed_defaul...
This function scrapes Glassdoor reviews for companies stored in a MongoDB database. It retrieves company data, updates their status to 'active', scrapes reviews using dynamic URLs, saves results in directories, and implements random delays to avoid detection. The process iterates for a specified number of companies, co...
def scrapeGlassdoor(number_to_scrape): # base_url = "https://www.glassdoor.com.au/Reviews/Apple-Reviews-E1138_P{}.htm?filter.iso3Language=eng" # browser = None restart_driver() uri = "mongodb+srv://yzha0058:yzha0058@yzhamongo.0wrgmhr.mongodb.net/?retryWrites=true&w=majority" # Create a new client ...
def connect_glassdoor(self): '''connect to job searched page''' self.driver.get(self.url) def use_full_searched(self): '''this function must be used before loading the crawler function''' amount_descript = self.driver.find_element(By.XPATH,self.num_header_selector).text ...
The main task of the code is to scrape job position data from Glassdoor by connecting to the platform, performing a full search if enabled, navigating through pages, loading position details, and storing the collected data for further processing or analysis.
def main(self): self.connect_glassdoor() if self.if_full_search: self.use_full_searched() logging.debug('searched all position result') self.click_next_turn() self.load_positions() return self.stor_data
def check_update(): p=open("version.txt","r") v=p.read() r=requests.get("https://raw.githubusercontent.com/alpha-hexor/animeflix/main/version.txt").text.strip("\n") if v!=r: #update is required update() def clear(): os.system('cls' if os.name == 'nt' else 'clear') def colored_print(m...
The main task of the code is to provide an anime streaming/downloading interface. It allows users to search for anime, select episodes, and choose between streaming or downloading. It supports resuming from previous sessions via log files and includes update functionality. The script handles user input for navigation, ...
def main(): if len(sys.argv) == 1: check_update() clear() print(logo) name = input("[*]Enter anime name: ") animes,anime_links =search_anime(name) for i in range(len(animes)): colored_print("["+str(i+1)+"] "+animes[i]) #take input from us...
def get_config_variable(config_path, variable_name): try: with open(CONFIG_PATH, 'r') as file: config_content = file.read() config_namespace = {} exec(config_content, {}, config_namespace) config_variable = config_namespace.get(variable_name) except Exception as e: ...
The main task of the code is to determine which method to use for finding wanted movies based on a configuration variable 'match_type'. If 'match_type' is "1" or unset, it uses a string-based search; if "2", it uses a fuzzy search. The function acts as a dispatcher to select between two different movie search strategie...
def find_wanted_movies(movies_dir): match_type = get_config_variable(CONFIG_PATH, 'match_type') if match_type == "1" or match_type == None: find_wanted_movies_string(movies_dir) elif match_type == "2": find_wanted_movies_fuzzy(movies_dir)
def GetSeriesList(): m3u_url = get_config_variable(CONFIG_PATH, 'url') scheme, rest = m3u_url.split('://') domain_with_port, _ = rest.split('/get.php') username, password = extract_credentials_from_url(m3u_url) api_url = f"{scheme}://{domain_with_port}/player_api.php?username={username}&password={pa...
The main task of the code is to update or download series data by matching directory names in a specified directory path with series entries retrieved from an API. It iterates through directories, checks for name matches with API-series data, and triggers a download if a match is found, logging warnings for unmatched d...
def update_series_directory(series_dir): # Retrieve the list of series from the API series_list = GetSeriesList() # Loop through all directories within series_dir for root, dirs, files in os.walk(series_dir): for dir_name in dirs: # Find a matching series by name mat...
def get_config_variable(config_path, variable_name): try: with open(CONFIG_PATH, 'r') as file: config_content = file.read() config_namespace = {} exec(config_content, {}, config_namespace) config_variable = config_namespace.get(variable_name) except Exception as e: ...
The function `find_wanted_series_fuzzy` searches for series in a list (`wanted_series`) using fuzzy matching (via `fuzz.token_set_ratio`) against a database of series (`series_list`). It identifies the best match based on similarity (≥75%) and year, prioritizing recent releases. If a match is found, it downloads the se...
def find_wanted_series_fuzzy(series_dir): wanted_series = get_config_variable(CONFIG_PATH, 'wanted_series') overwrite_series = int(get_config_variable(CONFIG_PATH, 'overwrite_series')) current_year = datetime.now().year similarity_threshold = 75 if wanted_series is None: wanted_series = [] ...
def get_config_variable(config_path, variable_name): try: with open(CONFIG_PATH, 'r') as file: config_content = file.read() config_namespace = {} exec(config_content, {}, config_namespace) config_variable = config_namespace.get(variable_name) except Exception as e: ...
The function identifies series from a config file that match the names of wanted series via substring checks against an API's series list. It downloads matching series, removes successfully found entries from the wanted list, and updates the config.
def find_wanted_series_string(series_dir): wanted_series = get_config_variable(CONFIG_PATH, 'wanted_series') found_match = False if wanted_series == None: wanted_series = [] m3u_url = get_config_variable(CONFIG_PATH, 'url') # Extract credentials and base URL from m3u_url username, ...
def get_config_variable(config_path, variable_name): try: with open(CONFIG_PATH, 'r') as file: config_content = file.read() config_namespace = {} exec(config_content, {}, config_namespace) config_variable = config_namespace.get(variable_name) except Exception as e: ...
The function `find_wanted_series` determines the matching method for identifying wanted series based on a configuration variable `match_type`. If `match_type` is "1" or unspecified, it uses exact string matching via `find_wanted_series_string`. If "2", it employs fuzzy matching via `find_wanted_series_fuzzy`, enabling ...
def find_wanted_series(series_dir): match_type = get_config_variable(CONFIG_PATH, 'match_type') if match_type == "1" or match_type == None: find_wanted_series_string(series_dir) elif match_type == "2": find_wanted_series_fuzzy(series_dir)
def get_config_variable(config_path, variable_name): try: with open(CONFIG_PATH, 'r') as file: config_content = file.read() config_namespace = {} exec(config_content, {}, config_namespace) config_variable = config_namespace.get(variable_name) except Exception as e: ...
The main task of the code is to schedule the download of Video-on-Demand (VOD) content by updating directory structures for series and movies, then identifying and processing "wanted" (missing or required) items in each. It retrieves configuration paths, synchronizes directories, and flags content needing download, lik...
def scheduled_vod_download(): series_dir = get_config_variable(CONFIG_PATH, 'series_dir') update_series_directory(series_dir) find_wanted_series(series_dir) movies_dir = get_config_variable(CONFIG_PATH, 'movies_dir') update_movies_directory(movies_dir) find_wanted_movies(movies_dir)
def scan_to_close( remaining_text: str, open_char: str = "(", close_char: str = ")", skip_comments: bool = False, debug: bool = False, ) -> str: needed_to_close: int = 1 i: int = 0 while needed_to_close > 0 and (i + len(close_char) - 1) < len(remaining_text): if remaining_text[i ...
The code parses and formats SQL queries by normalizing whitespace, handling comments, and reindenting clauses. It sanitizes input text, processes parentheses and substatements, detects SQL keywords (e.g., SELECT, FROM), and restructures expressions with proper indentation and line breaks. The function aims to improve r...
def parse( # noqa: C901 text: str, line_length=100, debug: bool = True, indent=" " * 4, starting_indent: str = "", ) -> str: # select_block = re.search('$|\n|\s+SELECT\n|\s+', 'SELECT ') # join_block = None # tail_blocks = None # re.match('\s*(?P<select>SELECT)\s*(?P<expressions>.*?...
def test_scan_to_close() -> None: assert scan_to_close("a)") == "a" assert scan_to_close("(a))") == "(a)" import unittest unittest.TestCase().assertRaises(RuntimeError, scan_to_close, "(a)") assert scan_to_close("(z(x(a)1)2)3)") == "(z(x(a)1)2)3" def test_detect_substatement_type() -> None: det...
The code defines a test function that executes four unit tests for a parser or code analysis tool: scanning to close, detecting substatement types, indenting case statements, and parsing. Its main task is to validate the correctness of these functionalities through automated testing.
def test(): test_scan_to_close() test_detect_substatement_type() test_indent_case_statement() test_parse()
def get_random_zip_code(): return random.choice(search.by_city_and_state(city=None, state=None, returns=42724)).zipcode def scrape_car_data(page_number, selected_zip): url = f"https://www.cars.com/shopping/results/?page={page_number}&zip={selected_zip}" headers = {'User-Agent': ua.random} try: ...
The main task of the code is to scrape car data from multiple ZIP codes with pagination, using tqdm for progress visualization. It randomly selects ZIP codes, scrapes pages within each ZIP, collects car data with random delays, and batch-inserts the results into a database. The process logs progress and ensures data is...
def main(): all_car_data = [] # Wrap the outer loop with tqdm for ZIP code progress visualization for selected_zip in tqdm(range(NUM_ZIP_CODES), desc="ZIP Codes Progress"): selected_zip = get_random_zip_code() logging.info(f"Scraping data for ZIP code: {selected_zip}") # Wrap the i...
def write_debug(tag, message): timestamp = dt.datetime.now().strftime("%x-%X") with open('orion5_server_log.txt', 'a') as log: log.write('{:s}-{:s}: {:s}\n'.format(tag, timestamp, message)) def process(self, data): if data == 'p': if self.orion.serial is not None and self.orion.seria...
This code continuously receives data from a socket, parses it using a custom protocol (splitting by '$' and '&'), processes valid messages, tracks timeouts, and terminates the connection if timeouts exceed a threshold or errors occur. It maintains the connection while self.connected is True, handles data buffering, and...
def run(self): try: read_buffer = '' while self.connected: data = '' ready = select.select([self.socket], [], [], 1) if ready[0]: data = self.socket.recv(1024).decode() # print('{} - {}'.format(self...
def move_to_position(orion, joints, threshold=10.0): """ move to a position defined by a list of joint angles [turret, shoulder, elbow, wrist, claw] returns current position after move """ # wait until we arrive at position while not arrived(joints, orion.getAllJointsPosition(), threshold)...
The code automates a robotic arm to pick up and place blocks at specified angles. It iterates through locations, moves to a waiting position, plays an audio cue, waits for an emergency stop signal, closes the claw to grab a block, and then moves the block to the designated putdown position. The process involves precise...
def feedme(orion, locations): for putdown_theta in locations: print(f'feedme - putdown: {putdown_theta}') # goto waiting position wait_for_block_pos = [last_gap, 90.0, 180.0, 180.0, CLAW_OPENED] move_to_position(orion, wait_for_block_pos, 5.0) # play 'feed me' soundbyte ...
def find_equivalent(comp, relevant): """ This function takes a compartment and replaces all of its relevant progeny (NOT including the compartment itself) with a single equiavent compartment. The relevance of progeny depends on its Strahler number: a compartmmet is deemed relevant if its...
This code constructs an EquivalentTree by simplifying the original RawTree structure. It merges compartments based on Strahler number thresholds, creating a simplified trunk with equivalent compartments. The process combines spiny and smooth branches, maps original components to new ones, and generates equivalent spiny...
def __init__(self, RawTree_object, thresh): """ To create an EquivelentTree with simplified architecture, this method needs the original tree in form of the RawTree object, and the threshold Strahler number for simplification. """ raw_tree=RawTree_object.tree...
def get_region_order(self, team, seed_num, region_name_to_num): order = list() if seed_num < 5: for site in region_rankings[team]: order.append(region_name_to_num[site]) else: #construct list of possible sites possible_sites = list() ...
The main task of the code is to construct a tournament bracket by assigning teams to regions and seeds based on their auto/at-large bids, adhering to placement rules. It handles edge cases like play-in games, switches teams if necessary, and assigns regional and first-weekend sites according to rankings, ensuring valid...
def build_bracket(self): self.regions = [dict(), dict(), dict(), dict()] region_num_to_name = dict() region_name_to_num = dict() self.first_weekend_num_to_name = [dict(), dict(), dict(), dict()] self.first_weekend_name_to_num = dict() auto_count = 0 at_large_count...
def generate(): global indexes while(len(indexes)<5): x=random.randint(0,9) if x in indexes: continue else: indexes.append(x) def startquiz(): global lblquestion,r1,r2,r3,r4 lblquestion=Label(root,text=questions[indexes[0]],font=("times new roman", 16, "bold"),background="#888888") lblquestion.place(x=...
This function handles the initiation of a quiz application by destroying initial UI elements, generating quiz content, starting the quiz, and initiating a countdown. It then launches two parallel processes: one for the game logic and another for the countdown timer, ensuring concurrent execution of quiz and timing func...
def startbtnprs(): labelimage.destroy() labeltext.destroy() btnStart.destroy() lblinstructions.destroy() lblRules.destroy() generate() startquiz() countDown() try: root.destroy() except: time.sleep(0.0001) process1 = multiprocessing.Process(target=startgame) process2 = multiprocessing.Process(target=co...
def write_log(payload): # takes an input dictionary and writes it to cloud logging - but only after checking if we want to log or not if use_cloud_logging: logger.log_struct(payload) else: return def get_subreddits(): subreddit_list = [] with open(input_list, "r") as file: da...
(The code retrieves stickied posts from multiple subreddits, logs the process, and saves the data into CSV files. It initializes logging, iterates through a list of subreddits, sets up CSV outputs for each, fetches stickied posts, and logs completion. The main task involves automated data collection and storage of Redd...
def main(): write_log( { "message": "** get_stickies.py | Retrieving Stickied Posts **", "severity": "NOTICE", "target-metadata": "stickies" }) subreddit_list = get_subreddits() for sub in subreddit_list: output = csv_setup(sub) get_s...
def resizeImg(self, dimension='30x30',path="X_train"): size = dimension.strip().split("x") listImg = os.listdir(self.X_train) imgList = [] for imgPath in listImg: img = cv2.imread(f'{self.X_train}/{imgPath}') img = cv2.resize(img, (int(size[0]), int(size[1]))) ...
This function performs image augmentation by applying various transformations (resizing, rotation, noise addition, flipping, blurring, translation) to images in a specified directory. It generates modified images based on input parameters and compiles them into a list for further processing or analysis.
def dataAugmentation(self, directory, parent_dir, resize='0', rotate=[90,180,270], scale=[1, 1.5, 1], noiseAmt=0.2, noiseSaltvsPepper=0.004,transformavalue=[0.09,0.43,0.56,0.85,0.99,0.32,0.32,0.99], flip=[0,1], kernel=(5,5), translation=[[1, 0, 25], [0, 1, 50]]): ...
def nine_lines(): three_lines() three_lines() three_lines() def three_lines(): new_line() new_line() new_line() def new_line(): print('.')
The main task of the code is to simulate clearing the screen by printing a sequence of lines. It calls `nine_lines()` and `three_lines()` twice in a loop, then adds one final line via `new_line()`, generating 24 lines total to create a blank screen effect in environments without direct screen-clearing commands.
def clear_screen(): print('Calling clear_screen()') i = 1 while(i <= 2): nine_lines() three_lines() i += 1 new_line()
def add_border(board): board[0] = np.ones((board.shape[0])) board[-1] = np.ones((board.shape[0])) board[:, 0] = np.ones((1, board.shape[0])) board[:, -1] = np.ones((1, board.shape[0])) return board def add_exit_left(board): board[board.shape[0] // 2, 0] = 2 return board def add_exit_right(bo...
The code generates a square grid (board) of specified size, initializes it with zeros, adds a border, exits on both sides, a middle wall, and pedestrians, then prints and returns the modified board for simulation or visualization purposes.
def generate_board_2(size): board = np.zeros((size, size), dtype=np.uint8) board = add_border(board) board = add_exit_left(board) board = add_exit_right(board) add_middle_wall_2(board) board = add_pedestrians(board) print(board) return board
def add_border(board): board[0] = np.ones((board.shape[0])) board[-1] = np.ones((board.shape[0])) board[:, 0] = np.ones((1, board.shape[0])) board[:, -1] = np.ones((1, board.shape[0])) return board def add_dormitory(board): # horizontal board[board.shape[0] // 4, :] = np.ones((board.shape[0]...
The main task of the code is to generate a square board (grid) of a specified size for a simulation or game. It initializes an empty board, adds a border, optionally adds exits (commented out), places a dormitory, populates pedestrians, prints the board, and returns it. The function constructs a structured environment ...
def generate_board_3(size): board = np.zeros((size, size), dtype=np.uint8) board = add_border(board) # board = add_exit_left(board) # board = add_exit_right(board) add_dormitory(board) board = add_pedestrians(board) print(board) return board
def _scrape_date_range(self, start_year, end_year=None, verbose=1): """ Scrape data from a given ``start_year`` to a given ``end_year``. A directory path can be given as ``save_to`` in order to save the tables ...
The code scrapes data from `start_year` to `end_year`, merges newly scraped data with existing datasets (if fully loaded), removes duplicates, and saves the updated data to `self.directory`. It handles five data types: races, circuits, results, drivers, and constructors, ensuring consistency by either appending new ent...
def scrape(self, start_year, end_year=None): """ Scrape from start_year to end_year. Combine currently loaded data and save to ``self.directory``. """ (new_races, new_circuits, new_results, new_drivers, new_constructors) = self._scrape_date_range...
def _all_data_loaded(self): return ( (not self.races is None) & (not self.circuits is None) & (not self.results is None) & (not self.drivers is None) & (not self.constructors is None) ) def _get_race_id(self, data): """ Creates...
The code updates the most recent Formula 1 season data by fetching the latest race results from an API. If data isn't already loaded, it prompts to use `.scrape()`. It checks if the latest race ID exists in the existing dataset; if not, it scrapes the latest season data and removes duplicates from the races DataFrame t...
def update( self, last_results_url='http://ergast.com/api/f1/current/last/results.json' ): """Update and save data to the most recent season.""" if not self._all_data_loaded(): return 'No data loaded. Use `.scrape()` instead.' r = reques...
def _init_from_data(self): """ Creates feature dictionaries from scratch in cases where training data is provided """ # extract features if self.method == 'bow': self.build_dictionaries() self.extract_features(self.train_data) # update max values only ...
This code initializes a Corpus class to process text data, supporting either bag-of-words (bow) or embeddings (emb) methods. It validates inputs, sets training/test data, initializes feature mappings (names, types, locations, menus), and loads or creates feature dictionaries. It handles feature toggles, normalization, ...
def __init__(self, train_data: list = None, test_data: list = None, exclude_feats: list = None, load_mapping: str = None, method: str = 'bow'): # current version of Corpus for tracking compatibility with external feature mappin...
def short_weiertrass(a, b, x, p): y_2 = (x*x*x + a*x + b) % p return tonelli_shanks(p, y_2) def twisted_edwards(a, b, x, p): y_2 = ((1-a*x*x)/(1-b*x*x)) fract = find_frac(y_2) denom_inv = mod_inverse(fract.denominator, p) y_2 = (fract.numerator * denom_inv) % p return tonelli_shanks(p, y_2) ...
This function determines the type of elliptic curve based on the 'type_curve' parameter and delegates validation to the corresponding method (short Weierstrass, twisted Edwards, or Montgomery). It returns the result of the specific curve check or None for invalid types.
def check_curve(type_curve, a, b, x, p): if type_curve == 1: return short_weiertrass(a, b, x, p) elif type_curve == 2: return twisted_edwards(a, b, x, p) elif type_curve == 3: return montgomery(a, b, x, p) else: return None
def short_weiertrass(a, b, x, p): y_2 = (x * x * x + a * x + b) % p return tonelli_shanks(p, y_2) def twisted_edwards(a, b, x, p): y_2 = ((1 - a * x * x) * mod_inverse(1 - b * x * x, p)) % p fract = find_frac(y_2) denom_inv = mod_inverse(fract.denominator, p) y_2 = (fract.numerator * denom_inv) ...
The function `check_curve` determines the type of elliptic curve (short Weierstrass, twisted Edwards, or Montgomery) based on the input `type_curve` and delegates validation of the curve parameters `a`, `b`, `x`, and `p` to the corresponding specialized function. It returns the result of the validation or `None` if the...
def check_curve(type_curve, a, b, x, p): if type_curve == 1: return short_weiertrass(a, b, x, p) elif type_curve == 2: return twisted_edwards(a, b, x, p) elif type_curve == 3: return montgomery(a, b, x, p) else: print("Invalid curve type") return None
def print_board(board): for row in board: print(' | '.join(row)) print('-' * 9) def get_player_move(board): while True: row = int(input("Enter the row (0-2): ")) col = int(input("Enter the column (0-2): ")) if board[row][col] == ' ': return row, col e...
The code implements a tic-tac-toe game where a human player ('X') competes against a computer ('O'). It initializes a 3x3 board, alternates turns, updates the board with moves, checks for a winner or tie after each move, and declares the result when the game ends.
def play_game(): board = [[' ', ' ', ' '], [' ', ' ', ' '], [' ', ' ', ' ']] current_player = 'X' while True: print_board(board) if current_player == 'X': row, col = get_player_move(board) board[row][col] = current_player else: print("Computer's ...
def find_best_move(board, heuristic, *args, **kwargs): min_pct = 0.05 before = heuristic(board, board.turn) moves = [] table = get_moves_table(board, min_moves=0) pass_pct = [ k for k in table.keys() if table[k][0] > min_pct or table[k][1] > 100_000 ] if len(pass_pct) >= 3: ...
The code builds a game tree by exploring chess positions using a specified heuristic, pruning branches based on ply depth and a prune factor. It generates best moves iteratively, tracks terminal states, and outputs PGN-formatted game variations from these states, logging depth statistics and move sequences during the s...
def build(heuristic, color, max_ply=MAX_PLY, prune_factor=20, find_best_move=find_best_move): best_moves = {} q = collections.deque() terminal = [] ply = 0 if color == chess.WHITE: board = chess.Board() best = find_best_move(board, heuristic, color) logging.info("q: %d, ply...
def driving(mode): #sends packet to arduino bus.write_byte(duino_address,mode) time.sleep(0.5) #requests to get packet back from arduino readNum() def calibrate(): #use this function to correlate N,S,E,W with +/- X and Y print("Calibrating") # Need to make transformation matrix # Dri...
The code navigates a rover through predefined waypoints by adjusting heading and position incrementally. It calculates target headings, aligns the rover, and moves toward each waypoint, checking proximity to confirm arrival. The process repeats for all waypoints, ensuring precise movement to each target location before...
def dm3(): #goalX, goalX2, goalX3, goalY, goalY2, goalY3): ###Changed to no inputs driving(0) calibrate() print("Drive Mode 3") ## Insert code here to read in MM waypoints ## Set waypoint coords into usable format, such as arrays x_points = [0,0,0] #[goalX, goalX2, goalX3] ###Set to zeros for ...
def convert_byte_stdin(length_byte): return convert_byte(sys.stdin.readlines(), length_byte) def print_hex(ver, length_byte, prefix): # insert length byte if need if length_byte: ver = bytes([len(ver)]).decode('utf-8') + ver # convert string to hex format, and split each byte by space if (pr...
The main task of the code is to convert version data between byte format and hex strings, handling input from files or stdin. It processes command-line arguments to determine conversion mode (revert/prefix), input source (file/stdin), and formatting options, then outputs the processed version data accordingly.
def main(): parser = argparse.ArgumentParser( description="IPMID return version bytes data file") parser.add_argument( 'file', default='', nargs='?', help='the IPMID oem version command return version byte data' ) parser.add_argument( '-s', '--stdin', dest='stdin', actio...
def set_default_values(self, win) -> None: """ Sets the default values for each knob on the UI: (Attack, Decay, Sustain, Release, Volume, Pitch) Sets the default wave selection Args: win: The UI window object where default values are to be set. """ # attac...
The main task of the code is to load a graphical user interface (GUI) from a specified UI file using QUiLoader, create a QWidget window populated with the UI elements, and initialize it with default values, control connections, wave selection logic, and key handlers to prepare the interface for interaction.
def load_ui(self) -> QWidget: """ Loads the graphical user interface (GUI) window and its elements from a designated UI file. Utilizes the QUiLoader to load the UI window and its components from the specified file path. Returns the generated GUI window after loading. Returns: ...
def remove_unnecessary_elements(root): work = root.find('work') if work is not None: root.remove(work) identification = root.find('identification') if identification is not None: root.remove(identification) defaults = root.find('defaults') if defaults is not None: root.re...
The code processes a MusicXML file by removing unnecessary elements, attributes, and text, then splits the cleaned file into smaller files containing 4 bars each, returning the list of generated files.
def processFile(fileName, fileCategory, folderName, outputFolderName, logAsCSV): # Load the file using ElementTree musicXmlFile = f'{path}/{folderName}/{fileName}' tree = ET.parse(musicXmlFile) root = tree.getroot() # Preprocess the file as a whole remove_unnecessary_elements(root) remove_wi...
def selectFilesForTesting(): with open(f'{path}/initialFilesDatabase.csv', 'r') as file: reader = csv.reader(file) print("Splitting files into training/testing...") classificationToListOfFiles = dict() testingFiles = [] for row in reader: if row[1] in classificati...
The main task of the code is to preprocess training data by splitting files into smaller segments, managing directory contents, and preparing structured data for further processing. It excludes testing files, processes remaining files into chunks, samples if necessary, updates the processed files database, and stores p...
def PREPROCESS_DATA(): testingFiles = selectFilesForTesting() # Delete all files in FILES_AFTER_PROCESSING to prepare for new processed data for filename in os.listdir(f'{path}/FILES_AFTER_PROCESSING'): filePath = os.path.join(f'{path}/FILES_AFTER_PROCESSING', filename) if os.path.isfile(fil...
def prepareAttributes(self,result): self.classMap={} for elementKey in result.keys(): element=result[elementKey] if element["kind"]=='Entity': self.classMap[elementKey]={} for elementKey in result.keys(): element=result[elementKey] ...
This code generates a UML class diagram from an SMW ask query result by preparing attributes, introducing diagram elements, generating class structures, configuring skin parameters, and finalizing output. The main task is to transform structured query data into a visual UML representation through sequential diagram gen...
def generate(self,result): """ generate a UML class diagram from the given SMW ask query result""" self.prepareAttributes(result) self.intro() self.genClasses(result) self.getSkinParams() self.outro()
def play(): print('Entering manual playback') _VARS['window']['Stop'].Update(disabled=False) _VARS['window']['Play'].Update(disabled=True) _VARS['window']['Play-USB'].Update(disabled=True) _VARS['window']['Play-Random'].Update(disabled=True) _VARS['window']['Set'].Update(disabled=False) _VAR...
The main task of the code is to initiate random playback of a sine wave with randomized pitch values, disable specific GUI controls during playback, and handle user interactions like stopping the playback or adjusting volume. It creates a sine wave stream, enables the Stop button, disables other controls, and enters a ...
def play_random(): print('Entering random playback') _VARS['window']['Stop'].Update(disabled=False) _VARS['window']['Play'].Update(disabled=True) _VARS['window']['Play-USB'].Update(disabled=True) _VARS['window']['Play-Random'].Update(disabled=True) _VARS['window']['Exit'].Update(disabled=True) ...
def play(): print('Entering manual playback') _VARS['window']['Stop'].Update(disabled=False) _VARS['window']['Play'].Update(disabled=True) _VARS['window']['Play-USB'].Update(disabled=True) _VARS['window']['Play-Random'].Update(disabled=True) _VARS['window']['Set'].Update(disabled=False) _VAR...
The main task of the code is to initiate USB-based audio playback by configuring GUI controls, initializing a sine wave stream, and dynamically adjusting the pitch based on real-time USB input values. The function disables specific buttons during playback, processes incoming serial data to scale pitch values, and allow...
def play_usb(serial_port): print('Entering USB playback') _VARS['window']['Stop'].Update(disabled=False) _VARS['window']['Play'].Update(disabled=True) _VARS['window']['Play-USB'].Update(disabled=True) _VARS['window']['Play-Random'].Update(disabled=True) _VARS['window']['Set'].Update(disabled=Tru...
def sending_proceed(self): for name, p in self.client_pos.items(): if p[0]!=0: self.client_sockets.get(name).send(("$proceed "+str(p[0])+" "+str(p[1])).encode()) self.client_pos[name]=(0,None) def findBySocet(self, so): for k, v in self.client_sockets.items():...
This function listens for client messages, processes commands like broadcasting, adding clients, sending private messages, listing users/files, and handling disconnections. It uses threads for file transfers and manages client sockets, ensuring messages are routed correctly and connections are maintained or terminated ...
def clientListen(self, cl, cAddr): while True: self.sending_proceed() try: msg = cl.recv(1024).decode() print(msg) source = self.findBySocet(cl) first_word = msg.split()[0] msg = msg.replace(first_word+"...
def geting_info(self): global name while True: info = input().strip() try: if info.split()[0] =="connect" and info.split()[1] is not None: name = info.split()[1] break except Exception as e: pr...
The main task of the code is to connect to a server using specified host and port, initiate a background thread to listen for client messages, and send data. It retrieves server info, establishes a connection, spawns a daemon thread for message handling, and triggers data transmission.
def join_to_server(self): self.geting_info() host = server_IP port = server_PORT self.connect_to_server(host, port) # creating new thread for each client messages th1 = threading.Thread(target=self.messagesListener, ) # make the thread run until the main threa...
def clear_screen(): #Cross platform screen clearing if name == 'nt': #Clear screen for windows _ = system('cls') else: #Clear screen for unix _ = system('clear') def Auto_LogCheck(): #Sets log interval to 0 seconds if there is only one test global Auto_LogCount global Auto_LogInterval_Counter ...
The main task of the code is to configure and initiate automated data logging by collecting user inputs (duration, count, interval), initializing global variables, calculating total runtime, recording session metadata to a file, and triggering the logging process via `Auto_DLS_Start()` while managing timer counters for...
def Auto_DLS_PreStart(): #Need to set variables first - could use lists instead global window global Auto_LogCount global Auto_LogTime global Auto_LogInterval global Auto_LogTime_counter global Auto_LogInterval_Counter global Auto_LogCount_save #Saving log count for times around the sun global Auto_dls_temp #T...
def clear_screen(): #Cross platform screen clearing if name == 'nt': #Clear screen for windows _ = system('cls') else: #Clear screen for unix _ = system('clear') def Auto_DLS_PreStart(): #Need to set variables first - could use lists instead global window global Auto_LogCount global Auto_Log...
The MainStart function presents a menu for a data logging application, offering options to initiate data logging sessions, access automated logging, view live sensor data, or exit. It processes user input to trigger corresponding functions like Start_DLS, Auto_DLS_PreStart, or Start_man_DLS, or terminates the program. ...
def MainStart(): clear_screen() print('Welcome to RIGS') print ('Today is', current_date_time, " | ", b_ver) print('----------------------------------------------') print('1. Start Data Logging')#Run data logging session print("2. Automated data logging") #Live Data From Sensors print("3. Live Sensor Data") #Liv...
def setup_user(username, ssh_key): commands = [ f'adduser --disabled-password --gecos "" --shell /usr/bin/zsh {username}', f'usermod -a -G adm,dialout,cdrom,sudo,audio,video,plugdev,games,users,input,netdev,gpio,i2c,spi {username}', ] for cmd in commands: subprocess.run(cmd.split())...
The main task of the code is to set up a user with an SSH key, secure SSH configuration, enable the SSH service, and remove a Pi-related component. It automates system setup for SSH access and cleanup of a Raspberry Pi environment.
def main(): setup_user( 'nazarewk', 'ssh-rsa AAAAB3NzaC1yc2EAAAABJQAAAYEAvM4y0G5vZ2OYlSeGn2w7y/s+VZMzhGGb9rlUkDtWtwvsE2TWlApFyHggn6qObmQ5DUOu0Mhy6l/ojylyp2Q/C7FMoQWkeBorLKvxf8KFE1lJktCXCxJyptDn8kkNi6Fxszig/flrp5lSWWjDCafyVeyFhvMo22fblzjPOG//wu0+RnOLn9eiWC2CUvJjG11AH+AxWI4UMXY93gq5K1YVLd3EmhI/L1ITAoY...