dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def _initialGen(self, minVal, maxVal): self.generation = [] # Creates a chromosome for the entire population size for i in range(self.populationSize): initial = [] for j in range(self.chromeSize): newVal = random.random() newVal *= maxVal -...
This code initializes a genetic algorithm with parameters like population size, chromosome size, and value ranges. It sets up the best solution tracker, initializes the first generation, and prepares to evolve through generations using methods like _initialGen, _addBestOfRun, and _generateGens for optimization tasks.
def __init__(self, numGens, popSize, chromeSize, minVal, maxVal, randomSeed, isMaxFitness = True): self.numGens = numGens self.populationSize = popSize self.chromeSize = chromeSize self.isMaxFitness = isMaxFitness random.seed(randomSeed) self.bestOfRun = ...
def _selectProportNewGen(prevGen, lengths, minVal, maxVal, isMaxFit): indices = range(len(prevGen)) # Get a list of all fitness values and convert to percents # Reverse fitness values if attempting to minimize fitness fitnessVals = _getFitnessValues(prevGen, lengths, minVal, maxVal) if not isMaxFit:...
This function generates a new generation in a genetic algorithm by selecting individuals based on the specified selection method (proportional, binary tournament, or linear ranking), followed by crossover and mutation operations to introduce genetic diversity. The parameters determine fitness maximization, individual l...
def _generateNewGen(prevGen, isMaxFitness, lengths, pointCross, probC, probM, minVal, maxVal, selChoice): if selChoice is 0: _selectProportNewGen(prevGen, lengths, minVal, maxVal, isMaxFitness) elif selChoice is 1: _selectBinTourNewGen(prevGen, lengths, minVal, maxVal, isMaxFitness) else: ...
def _initialGen(self): self.generation = [] # Creates a chromosome for the entire population size for n in range(self.populationSize): initial = 0 tempSize = self.bitLength # Randomly flags bits in length of chromosome while tempSize > 0: ...
This code initializes a genetic algorithm for the knapsack problem, setting parameters like population size, crossover/mutation rates, and bit-length. It seeds randomness, initializes the population, tracks the best solution of the run, validates the crossover point, and prepares to generate new generations. The main t...
def __init__(self, knapsack, numGens, bitLength, popSize, pointCross, probCross, probMut, randomSeed): self.numGens = numGens self.bitLength = bitLength self.populationSize = popSize self.pointCross = bitLength - pointCross self.probCross = probCross self.probMut = probMu...
def _initialGen(popSize, chromoSize, minVal, maxVal): initGen = [] #Creates a chromosome for the entire population size for n in range(popSize): xVals = [] #Selects random values inside given range for each element #in the chromosome for i in range(chromoSize): xV...
The function `singleRun` executes a genetic algorithm for a specified number of generations (`numGens`), tracking fitness data and best solutions at each generation. It initializes a population, iteratively generates new generations, and periodically logs high/low fitness values, average fitness, and corresponding indi...
def singleRun(storeRun, numGens = 50): isMaxFitness = storeRun.getIsMaxFitness() cell = _initialGen(numGens, 3, -1.0, 5.0) fitData = _getFitnessData(cell) storeRun.addGenResults(0, fitData['High Fit'], cell[fitData['High Fit Index']], fitData['Low Fit'], cell[fitData['Low Fit ...
def _initialGen(popSize, chromoSize): initGen = [] # Creates a chromosome for the entire population size for n in range(popSize): initial = 0 tempSize = chromoSize # Randomly flags bits in length of chromosome while tempSize > 0: tempSize = tempSize - 1 ...
This function executes a single run of a genetic algorithm, initializing a population, evaluating fitness, and iteratively generating new generations through crossover and mutation. It tracks and stores the best and worst individuals (fitness values and their corresponding genomes) at each generation in the provided st...
def singleRun(storeRun, numGens, vectorLengths, pointCross, probCross, probMut, minVal, maxVal, selChoice): isMaxFitness = storeRun.getIsMaxFitness() cell = _initialGen(30, sum(vectorLengths)) fitData = _getFitnessData(cell, vectorLengths, minVal, maxVal) storeRun.addBestOfRun(fitData['Hi...
def _receive_packet(self): raw_data, address = self.server.recvfrom(TRANSMISSION_SIZE) raw_data = verify_checksum(raw_data.decode("utf-8")) if raw_data is None: return None msg = raw_data[HEADER_SIZE:].rstrip() msg = msg[:(len(msg)-SEP_SIZE)] data = { "address": address, "flags": raw_data[0:FLAG_SI...
This function processes incoming packets by checking their flags and connection status. It validates packets against active connections or listening state, initiates handshakes for SYN packets, and routes data/ACK packets through appropriate handlers based on connection progression. It enforces connection state consist...
def _sort_incoming_packets(self): data = self._receive_packet() if (data is None) or (data.get("address") not in self.active_conns and not self.listening): return if data.get("address") in self.active_conns: conn_info = self.active_conns.get(data.get("address")) flags = data.get("flags") if conn_info...
def _sort_incoming_packets(self): data = self._receive_packet() if (data is None) or (data.get("address") not in self.active_conns and not self.listening): return if data.get("address") in self.active_conns: conn_info = self.active_conns.get(data.get("address")) flags = data.get("flags") if conn_info...
This function maintains a server loop to handle incoming packets, process data requests, format and send outgoing data with acknowledgment checks, and clear inactive connections. It continuously monitors for incoming data, sorts packets, processes requests, formats outgoing data, sends packets, checks for acknowledgmen...
def _start_server(self): while True: # check if packet incoming ready_sockets, _, _ = select([self.server], [], [], 0) # process incoming packet if len(ready_sockets) != 0: self._sort_incoming_packets() # process data requests if len(self.data_requests) != 0 or len(self.data_requests_r) != 0: ...
def noOfChar(essay): count=0 for i in essayToWords(essay): for j in i: count=count+len(j) return count def noOfWords(essay): count=0 for i in essayToWords(essay): count=count+len(i) return count def noOfSentence(essay): return len(essayToWords(essay)) def avgWordL...
The main task of the code is to extract and combine multiple text features (character count, word count, sentence count, average word length, misspelling check, and part-of-speech tags) from an essay into a single NumPy array for analysis or machine learning purposes.
def addAdditionalFeatures(essay,words): arr = [] arr.append(noOfChar(essay)) arr.append(noOfWords(essay)) arr.append(noOfSentence(essay)) arr.append(avgWordLength(essay)) arr.append(checkMisspell(essay,words)) pos = np.asarray(count_pos(essay)) arr = np.asarray(arr) combined = np.co...
def check_if_both_alive(self): if self.player.current_health > 0 and self.monster.current_health > 0: return True else: return False def battle_screen(self): self.set_title_component(title=f"{self.player.name} vs {self.monster.name}") self.characters_screen() ...
The main task of the code is to manage a turn-based battle between a player and a monster. It resets the battle state, repeatedly displays the battle screen, validates player input, processes attacks, and checks health status. The loop continues until either the player or monster is defeated, triggering a game-over scr...
def battle(self): self.player.battle_reset() while self.check_if_both_alive(): self.battle_screen() player_choice = input("Choose a move.\n>>> ") if not self.validate_option(choice=player_choice): print(self.center_text("Not a valid choice.")) ...
def get_all_nodes_features(self): node_feature_names = self.get_nodes_feature_names() node_features = dict() for feature_name in node_feature_names: node_features[feature_name] = list() for _, features in self.DG.nodes(data=True): for feature_name, feature_value ...
The code identifies repetitive features in node data by retrieving all node features, extracting repetitive ones, computing their frequencies, creating filters based on these frequencies, and returning the filters. Edge-related code is commented out, focusing solely on node feature analysis.
def identify_repetitive_features(self): nodes_features = self.get_all_nodes_features() nodes_repetitive_features = self.get_repetitive_features( nodes_features) node_repeatetie_feature_frequencies = self.compute_repetitive_features_frequencies( nodes_repetitive_features) ...
def is_primal(pb): """ Detecte si la base est primale-realisable """ return is_positive(pb.b) def probleme_auxiliaire(pb): """ Cherche une base primale realisable d'un probleme Cherche une base primale realisable en resolvant le probleme auxiliaire au probleme donne. Le probleme auxiliaire est caracterise par:...
The function `resoudre` solves a linear programming problem using the simplex method. It first constructs an initial feasible basis using slack variables, then checks if the basis is primal or dual feasible. If not, it invokes an auxiliary problem to find a primal feasible basis. The problem is converted into tableau f...
def resoudre(pb): """ Trouve une premiere base realisable puis resoud le probleme avec le simplexe Calcule une premiere base realisable, par defaut composee des variables d'ecart, puis verifie si cette base est primale ou duale realisable. Si c'est le cas, appelle le simplexe directement, sinon appelle la fonctio...
def SubkeyPermute(KEY, verbose): permuteKEY =[57, 49, 41, 33, 25, 17, 9, 1, 58, 50, 42, 34, 26, 18, 10, 2, 59, 51, 43, 35, 27, 19, 11, 3, 60, 52, 44, 36, 63, 55, 47, 39, 31, 23, 15, 7, 62, 54, 46, 38, 30, 22, 14, 6, 61, 53, 45, 37, 29, 21, 13, 5, 28, 20, 12, 4] output = [] for i in range(0, len(permuteKEY)...
This code implements the Data Encryption Standard (DES) algorithm. It generates 16 subkeys from the input key through permutations and left shifts, then applies 16 rounds of DES block cipher operations on the plaintext. The process involves initial permutation, iterative encryption rounds using subkeys, and final permu...
def main(): #Variable used to store the round of the Cipher global round round = 1 #Begins the actual script KEY = input("Enter the KEY : ") PT = input("Enter the Plaintext : ") verbose = input("Enter a 1 or a 0 :") verbose = int(verbose) KEY = SubkeyPermute(KEY, verbose) #The K...
def distance_point_coordinates(self, p1_coordinates, p2_coordinates): return distance.euclidean(p1_coordinates, p2_coordinates) def spatio_temporal_center(self, sequence): cx_num = 0 cy_num = 0 den = 0 for sequence_index, point_index in enumerate(sequence): (x,y) = se...
The main task of the code is to determine if two sequences meet spatial and temporal criteria. It checks if the distance between their spatio-temporal centers is ≤ 2×self.eps and if the time gap between seq1's end and seq2's start is < self.minMov, returning True when both conditions are satisfied.
def criterion1(seq1, seq2): return self.distance_point_coordinates(self.spatio_temporal_center(seq1),self.spatio_temporal_center(seq2)) <= 2 * self.eps and \ self.time_diff(seq1[-1], seq2[0]) < self.minMov
def time_diff(self, point_index_1, point_index_2): return self.time_diff_str(self.point_timestamp(self.traj_points[point_index_1]), self.point_timestamp(self.traj_points[point_index_2])) def get_next_point_index(self, sequence, sequence_index): if sequence_index == len(sequence) - 1: if sequ...
The main task of the code is to compute a weighted average distance between each point in the input sequence and the spatio-temporal center of the sequence. It calculates the weighted sum (num) of these distances multiplied by time intervals between consecutive points, divides it by the total time (den), and returns th...
def centered_distance(self, sequence): num = 0 den = 0 for sequence_index, point_index in enumerate(sequence): time_diff = self.time_diff(point_index, self.get_next_point_index(sequence, sequence_index)) num += self.distance_point_coordinates(self.point_coordinates(self.t...
def distance(self, point_index_1, point_index_2): return self.distance_point_coordinates(self.point_coordinates(self.traj_points[point_index_1]), self.point_coordinates(self.traj_points[point_index_2])) def is_core_sequence(self, sequence, tau=None): if not tau: tau = self.tau return...
This function calculates the minimum distance $ r $ for a given point to form a core sequence within a specified epsilon sequence. It iterates through sorted distances between the point and its neighbors, checking if a core sequence exists at each distance. If valid, it returns the smallest such $ r $; otherwise, retur...
def core_distance(self, eps_seq, point_index): r = 0 if len(eps_seq) > 1: point_eps_seq_index = eps_seq.index(point_index) distances = [self.distance(point_index, pi) for i, pi in enumerate(eps_seq) if i != point_eps_seq_index] distances.sort() print(f"fin...
def j_star_candidate(self, i): j=i+1 while(j < len(self.traj_points)): if self.time_in_sec(j) >= self.time_in_sec(i) + self.stay_duration_delta: break j+=1 return j def deameter(self, i, j): return max(self.all_distances(i, j)) def max_j_deameter(s...
The main task of the code is to extract stays from a trajectory by identifying clusters of consecutive points within a specified roaming distance. It iterates through trajectory points, determines candidate end indices (j_star) for each stay, checks if the cluster's diameter exceeds the allowed distance, and if not, re...
def extract_stays(self): stays = [] i=0 while(i< len(self.traj_points)-1): print(f"point: {i}") j_star = self.j_star_candidate(i) if self.deameter(i, j_star) > self.roaming_distance_delta: i+=1 else: j_star = self.ma...
def eps_sequence(self, point_index, eps = None): if not eps: eps = self.eps eps_sequence_forward = [] i = point_index + 1 while(i < len(self.traj_points) and self.distance(i, point_index) <= eps): eps_sequence_forward.append(i) i+=1 eps_sequenc...
This function computes reachability distances for trajectory points by identifying core sequences. For undefined distances, it calculates the core distance of the sequence and updates each point's reachability distance as the maximum of the core distance and pairwise distances within the sequence.
def compute_reachability_distances(self): for _, point_index, _, _ in self.traj_points: if self.reachability_distances[point_index] == self.undefined: print(f"point: {point_index}/{len(self.traj_points)}") eps_seq = self.eps_sequence(point_index) if(se...
def _append_history(self, role, content): """ Append a new message to the chat history. This function adds a new message to the chat history with the specified role and content. Args: role (str): The role of the message sender, e.g., "user" or "assistant". conten...
The main task of the code is to send a user message along with chat history to a language model, receive the model's response, append both the query and response to the history for context tracking, and return the response. It handles default prompts when no input is provided and adjusts history length to manage payloa...
def send_receive_message(self, user_query=""): """ Send a single message using history as payload and append the response to the history. This function sends the full history as payload, receives the response from the language model, and appends the response to the chat history. The his...
def checkInsideRange(q, p): # Function to check whether q are within the range of p cart_q = spher2cart(q) cart_p = spher2cart(p) # Get [x', y', z'] of point q coef = np.dot(cart_p, cart_p) / np.dot(cart_p, cart_q) posInPlane = coef * cart_q # Get the v1 and v2 (where cart_q = v1*e_theta +...
This code computes a performance value based on the spatial relationship between two spherical-coordinate vectors q and p. It uses either Perf0 or Perf1 depending on whether checkInsideRange confirms the vectors lie within a specified range, enabling context-dependent performance calculation.
def Perf(q, p): # q and p is a vector in spherical coordinate if checkInsideRange(q, p): return Perf0(q, p) else: return Perf1(q, p)
def checkInsideRange(q, p): # Function to check whether q are within the range of p cart_q = spher2cart(q) cart_p = spher2cart(p) # Get [x', y', z'] of point q coef = np.dot(cart_p, cart_p) / np.dot(cart_p, cart_q) posInPlane = coef * cart_q # Get the v1 and v2 (where cart_q = v1*e_theta +...
The function `PPerf` determines whether points `q` and `p` lie within a specified range using `checkInsideRange`. If true, it computes performance via `Perf0`; otherwise, it uses `Perf1`. Both methods accept parameters `thetap` and `phip` for additional configuration, returning the calculated performance result based o...
def PPerf(q, p, thetap=False, phip=False): if checkInsideRange(q, p): return Perf0(q, p, True, thetap, phip) else: return Perf1(q, p, True, thetap, phip)
def spher2cart(points): """theta phi to x y z""" z = np.cos(points[0]) y = np.sin(points[0]) * np.sin(points[1]) x = np.sin(points[0]) * np.cos(points[1]) result = np.array([x, y, z]) * radius return result def cart2spher(points): """x y z to theta phi""" rho = np.sqrt(points[0] ** 2 + p...
This function computes line integrals using Monte Carlo methods for each camera position, calculating average values (ave_l), arc lengths (length), and a parameter (k). It samples points along four paths (up/down/left/right) on a sphere, computes partial derivatives, and integrates using random samples. The results dep...
def calcLineIntegral(N, p, isTheta): """ Parameters ---------- u : random numbers from 0-1, len = N v : random numbers from 0.5-1, len = N N : length of random numbers. Number of Monte Carlo sampling points p : each value represents a angle of joint. cam_num*2...
def spher2cart(points): """theta phi to x y z""" z = np.cos(points[0]) y = np.sin(points[0]) * np.sin(points[1]) x = np.sin(points[0]) * np.cos(points[1]) result = np.array([x, y, z]) * radius return result def Perf(q, p): # q and p is a vector in spherical coordinate if checkInsideRange...
The function computes the minimum angular distance between points in `p` and `q`, identifies the closest point in `p` to `q`, calculates a performance metric using this closest point, and multiplies it by a phi value derived from `q`'s Cartesian coordinates to return a result.
def H_multiprocess(p, q): min_pq = 2 * pi min_i = -1 # Find the nearest points of P length = len(p) for i in range(length): p_cart = spher2cart(p[i]) q_cart = spher2cart(q) dis = acos(np.dot(p_cart, q_cart) / np.dot(p_cart, p_cart)) if dis < min_pq: min_pq...
def Perf(q, p): # q and p is a vector in spherical coordinate if checkInsideRange(q, p): return Perf0(q, p) else: return Perf1(q, p) def spher2cart(points): """theta phi to x y z""" z = np.cos(points[0]) y = np.sin(points[0]) * np.sin(points[1]) x = np.sin(points[0]) * np.cos...
The function H_multiprocess_T calculates the maximum performance value (maxPerf) from a list of parameters p and q, converts q from spherical to Cartesian coordinates, computes a phi value based on this conversion, and returns the product of maxPerf and phi. Its main task is to determine the highest performance metric ...
def H_multiprocess_T(p, q): # Find the maximum of Perf length = len(p) maxPerf = 0.0 for i in range(length): perf = Perf(q, p[i]) # print("In H_multiprocess_T, No", i, "th value is: ", perf) if perf >= maxPerf: maxPerf = perf # Compute phi and return result q...
def spher2cart(points): """theta phi to x y z""" z = np.cos(points[0]) y = np.sin(points[0]) * np.sin(points[1]) x = np.sin(points[0]) * np.cos(points[1]) result = np.array([x, y, z]) * radius return result def PPerf(q, p, thetap=False, phip=False): if checkInsideRange(q, p): return ...
The code computes a Monte Carlo surface integral by evaluating the nearest neighbor of a spherical point $(x_\theta, x_\phi)$ in a dataset $p$, converting coordinates to Cartesian space, calculating angular distance, and applying functions $PPerf$ and $\phi$. It returns a computed term (involving $PPerf$ and $\phi$) an...
def integral_surface(p, x_theta, x_phi, theta): """ Calculating a specific Monte Carlo point surface integral (point : [x_theta, x_phi]). theta is true for theta, and is false for phi """ q_sphere = np.array([x_theta, x_phi]) q_cart = spher2cart(q_sphere) # Find the nearest points of P m...
def loadImagePaths(self): scene_ids = [] for scene_id in os.listdir(ROOT_FOLDER): annotation_filename = ROOT_FOLDER + scene_id + '/annotation/floorplan.txt' exists1 = os.path.exists(annotation_filename) filename_glob = ROOT_FOLDER + scene_id + '/' + 'dataset/mesh/*.ob...
The main task of the code is to initialize a TFRecord writer for training/test data by loading image paths, filtering them based on the task (train/test), and writing each image as a TFRecord example. It sets parameters like input channels, point count, and label maps, then iterates through filtered image paths to gene...
def __init__(self, options): #super(RecordWriterTango, self).__init__() self.dataPath = 'data/' self.stopped=False self.split = options.task self.imagePaths = self.loadImagePaths() self.numImages = len(self.imagePaths) self.numPoints = options.numPoints s...
def build_graph(options, input_dict): branches_options = set(options.branches) simple_option = set(['0', '6', '7']) if (simple_option | branches_options) == simple_option: return build_graph_pointnet(options, input_dict) if options.branches == '4': return build_graph_image(options, inp...
The code trains a neural network model using TensorFlow, handling multiple datasets (e.g., Syn, Tango, ScanNet) based on the 'hybrid' option. It constructs data iterators, defines the model graph, computes loss, and uses Adam optimization. The training loop runs for specified iterations, logs losses, validates on a sep...
def train(options): if not os.path.exists(options.checkpoint_dir): os.system("mkdir -p %s"%options.checkpoint_dir) pass if not os.path.exists(options.test_dir): os.system("mkdir -p %s"%options.test_dir) pass if not os.path.exists(options.log_dir): os.system("mkdir -p ...
def build_graph(options, input_dict): branches_options = set(options.branches) simple_option = set(['0', '6', '7']) if (simple_option | branches_options) == simple_option: return build_graph_pointnet(options, input_dict) if options.branches == '4': return build_graph_image(options, inp...
The code evaluates a neural network model on multiple datasets (Syn, Tango, ScanNet, etc.), computing metrics like precision, recall, and IOU for corners, icons, and rooms. It loads pre-trained weights, processes batches of data, compares predictions with ground truth, accumulates statistics, and optionally caches resu...
def test(options): if not os.path.exists(options.test_dir): os.system("mkdir -p %s"%options.test_dir) pass if options.useCache == 1 and os.path.exists(options.test_dir + '/network_numbers.npy'): numbers = np.load(options.test_dir + '/network_numbers.npy')[()] print([(k, v[0] / v...
def string_to_hex(string): return "".join([to_hex_string(c) for c in string]) def caesar(plaintext, rot=13): ans = "" # iterate over the given text for i in range(len(plaintext)): ch = plaintext[i] ord_ch = ord(ch) # check if space is there then simply add space if ord_c...
The function attempts to find a matching encoded pattern by comparing pairs of encoded strings against an encoded guess. It iterates over all string pairs, checks possible offsets, and uses decrypt_attempt to test if the encoded guess aligns with substrings of both strings at the same offset, printing results for analy...
def take_a_guess(encoded_strings, string_guess): encoded_guess = string_to_hex(caesar(string_guess)) length = len(encoded_guess) for [enc1, enc2] in combinations(encoded_strings, 2): offset = 0 while offset + length <= len(enc1) and offset + length <= len(enc2): attempt = decry...
def menu_list_window(name = None, price=None, ingredient=None, tags=None, meal_type=None): #Filter the menu based on the user's search criteria menu1.filter_menu(name, price, ingredient, meal_type, tags) #Create the search bar search = [sg.Button('Filter', button_color=('#D9A88F', '#B06660'), key='filt'...
The main task of the code is to manage a menu list interface where users can navigate, search, filter, add meals, and view meal details. It handles user interactions like closing the window, returning to previous screens, applying filters, clearing searches, and opening meal-specific details, dynamically updating the U...
def run_menu_list_wind(): #create menu list window menu_list_wind = menu_list_window() #start looping to wait for user input while True: #read user input from the menu list window event, values = menu_list_wind.read() #if user closes window, exit program if event == sg.W...
def solve_captcha(self, solve): captcha = '' tries = 0 while len(captcha) != 2: self.driver.get("https://control.unet.edu.ve/sec/inicioNuevo.php") container = self.driver.find_element_by_id("iseg") # image_src = container.find_element_by_tag_name("img").get_attribute('src') image_tes = contain...
This code automates accessing academic information by solving a CAPTCHA, navigating a menu if on the 'adm_usuarios/menuppal.php' route, opening academic records, and retrieving grades. It handles user interaction with a web interface to extract academic data.
def open(self, solve=True): self.solve_captcha(solve) if self.route == 'adm_usuarios/menuppal.php': self.select_menu('pregrado', 'class', 'subOpcion') self.open_informacion_academica() self.get_notas()
def enter_config_mode(self): self._config_mode = True self.send_command('CG') def set_loopback(self, loopback: bool): self._send_config_command('CAN_MODE', 1 if loopback else 0) def set_can_baudrate(self, bitrate): self._send_config_command("CAN_BAUD", bitrate) def enter_running_mode(sel...
This code initializes a serial communication interface by configuring a serial port, setting baud rates, and entering device modes. It validates the input channel, splits baudrate if needed, opens the serial connection, applies delays, and configures CAN settings before transitioning to running mode. The super class is...
def __init__(self, channel, ttyBaudrate=9600, bitrate=None, btr=None, sleep_after_open=_SLEEP_AFTER_SERIAL_OPEN, rtscts=False, **kwargs): """ :param str channel: port of underlying serial or usb device (e.g. /dev/ttyUSB0, COM8, ...) Must not be e...
def readable(self, image): """ Checks that are there pieces of head return = True or False """ sit, _, __ = self.detect(image, part_name= 'all') return sit def get_mean_multiple(self, image): """ returns mean of coordinates """ _, __, ey...
This function calculates the gesfacexp_score by analyzing a video against a reference image. It processes each frame to evaluate eye, lip, and eyebrow movements, accumulates scores, and computes an average. The result is a dictionary containing individual and total scores for facial expression analysis at a specified f...
def gesfacexp_score(self, reference_image, video_path, fps = 5): """ Calculates gesfacexp_score @param reference_image = first taken image @param video_path = selected video's path @param fps = frame per second @return dict format gesfacexp_score = [eye_gesfac_s...
def log(msg): xbmc.log("### [%s] - %s" % (__scriptname__,msg,),level=xbmc.LOGDEBUG ) def get_libname(platformstr): if platformstr == "osx": return "libboblight-osx.0.dylib" elif platformstr == "ios": return "libboblight-ios.0.dylib" elif platformstr == "tvos": return "libboblight-tvos.0.dylib" eli...
The main task of the code is to download and extract the libboblight library for a specified platform. It constructs a URL based on the platform, downloads the ZIP file, extracts it to a designated directory, and removes the ZIP afterward. If an error occurs and notifications are allowed, it displays a user notificatio...
def tools_downloadLibBoblight(platformstr,allowNotify): log("boblight: try to fetch libboblight") libname = get_libname(platformstr) destdir = get_download_path(platformstr) url = "%s/%s/%s.zip" % (__libbaseurl__, platformstr, libname) dest = os.path.join( destdir, libname) try: DownloaderClass(url, des...
def read_exp_flux(self,flux_name='exp_flux_data.csv'): """ Read in experimental V, and CNao dependent flux data """ df = pd.read_csv(flux_name) vmps = df['V in mV'] return vmps,df def calc_pump_states_concentrations(self,temp,v,concentrations,all_k_params,don2,init_st...
The main task of the code is to calculate the normalized deviation between a model's predicted flux values and a reference experimental flux dataset. It computes the squared average deviation of flux values across different parameter sets and concentrations, normalizes this by the reference flux's variance, and returns...
def calc_flux_dev_from_ref(self,all_k_params,don2,fraction,cnos=[1.5,50,100,150],concentrations=[9999, 50, 5.4, 140, 9.8, 0.05,1.833],\ init_states_conc = np.array([0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]),temp=310.0): """ calculating deviation of flux for a ...
def read_exp_qslow_na(self,fname='exp_qslow_na.csv'): df = pd.read_csv(fname) vmps = df['V in mV'] return vmps,df def calc_pump_states_concentrations(self,temp,v,concentrations,all_k_params,don2,init_states_conc,fraction,time=np.linspace(0.0,0.5,10000)): """ calculate steady s...
The code calculates the normalized deviation between modeled and experimental slow charge movement in external Na+ binding. It iterates through voltage protocols, computes state concentrations at holding/variable voltages, calculates theoretical charge values, compares them to experimental data, and returns the normali...
def calc_qslow_na_dev_from_ref(self,all_k_params,don2,fraction,cnos=[50,100,200,400],concentrations=[9999,0,0,0,0,0,0],\ init_states_conc=np.array([0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]),holding_v=-40.0,temp=298.0): """ calculating deviation of slow cha...
def read_exp_qslow_k(self,fname='exp_qslow_k.csv'): df = pd.read_csv(fname) vmps = df['V in mV'] return vmps,df def calc_pump_states_concentrations(self,temp,v,concentrations,all_k_params,don2,init_states_conc,fraction,time=np.linspace(0.0,0.5,10000)): """ calculate steady sta...
The function calculates the normalized deviation of slow charge movement in external K+ binding from experimental reference data. It iterates over specified K+ concentrations, computes theoretical charge values at different voltages, compares them to experimental data, and returns the normalized squared deviation avera...
def calc_qslow_k_dev_from_ref(self,all_k_params,don2,fraction,ckos=[1,2,4,8],concentrations=[0,0,999,0,0,0,25.0],\ init_states_conc=np.array([0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0]),holding_v=0.0,temp=298.0): """ calculating deviation of slow charge move...
def calc_energy_dev_from_ref(self,all_k_params,don2,vs=range(-120,80,20),cnos=[1.5,50,100,150],concentrations=[9999, 50, 5.4, 140, 9.8, 0.05,1.833],temp=310.0): """ calculating deviation of cycle energy for a given parameter set concentrations take the format of cno,cni,cko,cki,catp,cadp...
This function performs Monte Carlo sampling to optimize parameters (guessed_ks, guessed_delta) by minimizing deviations in energy, flux, and slow charges. It iteratively proposes new parameters, calculates total deviation, and accepts/rejects them using a probabilistic criterion based on temperature factor (tfactor). R...
def monte_carlo_cycles(self,total_steps,tolerance,guessed_ks,guessed_delta,fraction,log_csv_name,tfactor=0.1): """ To run MC sampling """ ## calculate error use the guessed ks and gating charges energy_dev = self.calc_energy_dev_from_ref(guessed_ks,guessed_delta) flux...
def update_history(self, lookback=2880): """ Parameters ---------- lookback : int, default=2880 Lookback period in minutes, where default is two days Returns ------- None """ for asset in self.tradable_assets: ...
This code runs a live trading strategy by periodically checking tradable assets, calculating order quantities based on account cash and price history, applying stop-loss/take-profit levels, and executing buy orders when signals are triggered, while logging trades and managing risk parameters like volatility and minimum...
def run(self, min_tp_sl=0, percent_acc_to_trade=0.9, update_lookback=50, interval=0): """Runs the live trader. Parameters ---------- None Returns ------- None """ last_min = datetime.now().minute while True: if self.M...
def get_labeled_data(labels,pred): """Get labeles Returns: Labels """ return labels[labels!=0],pred[labels!=0] def RI(labels,pred): """ Funtion that returns the rand index. The Rand index measure the similarity between the clusters. Returns: Rand_index """ TP,TN,FP,FN = confu...
This function evaluates clustering algorithms (KMeans, DBSCAN, etc.) by varying parameters (k or ε) across a specified range. For each parameter value, it computes clustering results and calculates performance metrics—Silhouette Score, Rand Index, F1 Score, Precision, Recall, and Adjusted Rand Index—using labeled data....
def method_performance(features, labels,range_values,method): """ Function that returns all the metrics for Kmeans and DBSCAN algorithms (or others) varying the k clusters and eps. Parameters: features - Array with the selected final features. labels: Actual labels from the biologists r...
def extract_features(data): pca = PCA(n_components=6) x_pca = pca.fit_transform(data) print('Shape of data after PCA:', x_pca.shape) tsne = TSNE(n_components=6, method='exact') x_tsne = tsne.fit_transform(data) print('Shape of data after TSNE:', x_tsne.shape) isomap = Isomap(n_componen...
The main task is to process image data by extracting and selecting features, then apply clustering algorithms (KMeans, DBSCAN, Agglomerative) with parameter tuning (k, ε, n) to group data, evaluate performance via metrics, and generate HTML reports comparing clustering results against true labels.
def main(): data = images_as_matrix() features_already_extracted = True # toggle this to false to extract features # 1. Feature extraction using 3 different methods each extracting 6 features for total of 18 features if not features_already_extracted: extracted_features = extract_features(data...
def isProximityQuery(self, __term): if(__term[0] == '/'): return (True) return (False) def proximityQuery(self, __firstTerm, __secondTerm, __distance): totalDocuments = [] i = 0 j = 0 while(i < len(__firstTerm[1]) and j < len(__secondTerm[1])): if (__firstTerm[1][i] == __secondTer...
The code processes a query by tokenizing it, then handling either a proximity query (if detected) or combining terms with logical operators. It classifies terms and operators, iteratively applying two-term queries to filter documents, ultimately returning the matched documents.
def executeQuery(self, __query): parsedQuery = nltk.word_tokenize(__query) documents = [] if (len(parsedQuery) == 3 and self.isProximityQuery(parsedQuery[2])): documents = self.proximityQuery((parsedQuery[0], self.singleTermQuery(parsedQuery[0])),(parsedQuery[1], self.singleTermQuery(parsedQuery[1]))...
def _has_parse_errors( config: dict, ignore_errors_keywords: List[str] | None = None, ) -> bool: """Check whether parsed config has errors. Sometimes projects use `include` directives without real files presence in the repo (these files are added as nginx defaults during installation) - https:/...
This function checks if an Nginx configuration file contains "wide" `try_files` directives (e.g., using `$uri` or `$uri/`), which may indicate insecure or overly broad routing. It parses the config, identifies `try_files` and `location` blocks, validates against custom/excluded paths, and returns `True` if no invalid d...
def _nginx_valid( filename: str, custom_deny_locations: List[str] | None = None, extra_deny_locations: List[str] | None = None, ignore_errors_keywords: List[str] | None = None, ) -> bool: """Check whether file with `filename` contains wide nginx configuration. Search for wide range of files in ...
def ratio_ORFlength_hcds(fastas): diff_ORFlength_encoding = [] header = ['#'] + ['diff_ORFlength'] diff_ORFlength_encoding.append(header) for i in fastas: name, seq = i[0], re.sub('-', '', i[1]) code = [name] l = (len(seq)) / 162.6482 ##note code.append(l) diff_...
The function `extracted_features` processes DNA and protein sequences to generate combined features based on the specified model (species and CDS/non-CDS). It loads model-specific data (Excel/CSV files), computes DNA features using 3-mer statistics and ORF length ratios, extracts protein features, concatenates them, an...
def extracted_features(dna_seq, protein_seq, model): if model == 'H.sapiens-CDS': c_m = pd.read_excel('./files/6mermean.xlsx', sheet_name=0, nrows=1, header=None) nc_m = pd.read_excel('./files/6mermean.xlsx', sheet_name=0, skiprows=1, header=None) Tc = pd.read_csv('./files/human_cds_train_fr...
def __CreatePredicate(self, f, bAllParameters, lActionParameters) -> ParametrizedPredicate: if type(f) is Fluent: if (not bAllParameters) and (lActionParameters is None or len(lActionParameters) == 0): pp = GroundedPredicate(f.name) else: pp = Parametrized...
The code creates a problem object by initializing known predicates from true initial values, adding hidden constraints (OR and ONEOF), combining goals into an AND formula, simplifying it, and setting it as the problem's goal.
def createProblem(self, problem, domain): p = Problem(problem.name, domain) for f, v in problem.initial_values.items(): if v.is_true(): gp = self.__CreatePredicate(f, False, None) p.AddKnown(gp) for c in problem.or_constraints: cf = self....
def build_tree(train, max_depth, min_size): root_node = get_split(train) split(root_node, max_depth, min_size, 1) return root_node def print_tree(node, depth=0): if isinstance(node, dict): print('%s[X%d < %.3f]' % (depth * ' ', (node['column_index'] + 1), node['split_value'])) print_tree...
The code builds a decision tree from a given dataset using the `build_tree` function with parameters 3 and 3, prints the tree structure, and predicts labels for each data point using the `predict` function, outputting the predicted results.
def main(): dataset = [[2.771244718, 1.784783929, 0], [1.728571309, 1.169761413, 0], [3.678319846, 2.81281357, 0], [3.961043357, 2.61995032, 0], [2.999208922, 2.209014212, 0], [7.497545867, 3.162953546, 1], [9.00220326, 3.3390...
def get_matrix(data): users = data["user_id"] questions = data["question_id"] cij_lst = data["is_correct"] answer_matrix = np.zeros((542, 1774)) data_matrix = np.zeros((542, 1774)) for i in range(len(users)): u_id = users[i] q_id = questions[i] cij = cij_lst[i] an...
This code performs hyperparameter tuning for an Item Response Theory (IRT) model by iterating over learning rates and iterations. It evaluates model performance on validation and test data, plots training likelihood and validation accuracy curves, and visualizes the probability of correct responses against theta parame...
def main(): train_data = load_train_csv("../data") val_data = load_valid_csv("../data") test_data = load_public_test_csv("../data") answer_matrix, data_matrix = get_matrix(train_data) # Using the same hyperparameter as before # theta, beta, c, alpha, val_acclst, train_llh = irt(train_data, val_d...
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}...
The code performs hyperparameter tuning for an Item Response Theory (IRT) model using training, validation, and test data. It evaluates model accuracy and negative log-likelihood across learning rates and iterations, selects optimal hyperparameters based on validation performance, and visualizes training/validation met...
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") iterations = [200] lr = [0.01] # iterations_lst = list(range(iter...
def create_gitignore(path, options): # Create .gitignore from gitignore.io options += ",jetbrains,visualstudio,eclipse" gitignore_content = requests.get(f"https://www.toptal.com/developers/gitignore/api/{options}").text create_text_file(path, ".gitignore", gitignore_content) def initialize_git_repo(path...
The main task of the code is to process form data to generate a project scaffold. It collects configuration details from multiple forms, creates directory structures, generates template files (e.g., Dockerfiles, docker-compose.yml), initializes language-specific code examples, packages the project into a ZIP archive, a...
def process_data(request, form_classes): # Get data from forms data = {} # Get data from single field forms single_fields = ['project_name', 'programming_language', 'generate_code_examples', 'nats', 'memcached', 'redis', 'prometheus', 'clickhouse', 'elasticsearch', 'mailhog'] fo...
def rotate(pts, R): # rotate the points - pts using R res = [] for pt in pts: res.append(np.dot(R, pt)) return res def find_corresponding_points(p, norm_pts_rot, foe): # compute the epipolar line between p and foe # run over all norm_pts_rot and find the one closest to the epipolar line ...
This function calculates 3D points from 2D correspondences by rotating previous points, matching them to current points using a focus of expansion (foe), computing depth (Z) with a given translation (tZ), and constructing 3D coordinates. It returns corresponding indices, 3D points, and validity flags for each computed ...
def calc_3D_data(norm_prev_pts, norm_curr_pts, R, foe, tZ): norm_rot_pts = rotate(norm_prev_pts, R) pts_3D = [] corresponding_ind = [] validVec = [] for p_curr in norm_curr_pts: corresponding_p_ind, corresponding_p_rot = find_corresponding_points(p_curr, norm_rot_pts, foe) Z = calc_d...
def get_simulated_lane_location(self, pose): """ Returns a simulated measurement of a projection of the robots location on to the nearest lane line """ projection = self.get_expected_lane_location(pose) # TODO: Add noise to the projection return projection def get_lane_lo...
This function updates a robot's location estimate by adjusting its current pose based on the difference between expected and measured lane positions. It calculates a correction vector from the discrepancy, applies it to the current pose, and publishes the adjusted position as a PoseWithCovarianceStamped message, mainta...
def update_location(self, msg): """ Publishes message to particle filter to add in a sample with given location estimate Params: Odometry Publishes PoseWithCovarianceStamped of new location estimate """ pose = msg.pose.pose if self.simulation: measured...
def ask_value(message: str) -> int: print(message) while True: try: a = int(input('a = ')) if a == 0: print("'a' can't be zero, please try again") else: break except ValueError: print('Only integer number is allowed,...
The main task of the code is to solve a quadratic equation by obtaining coefficients (a, b, c) via `ask_value`, computing solutions with `solv_square`, and drawing a line with `line()`. It handles keyboard interruptions gracefully by notifying the user if the program is interrupted mid-execution.
def main() -> None: try: (a,b,c) = ask_value(msg) solv_square(a,b,c) line() except KeyboardInterrupt: print('\nProgramm was interrupted!')
def get_string(m): user_input = input(m) user_input = user_input.upper() user_input = user_input.strip() return user_input def menu_pizza(p): for x in p: output = "{}: ${}".format(x[0], x[1]) print(output) return def get_customer_details(o, c, d, l): for x in o: outpu...
The code implements a pizza order management system, allowing users to view menus, add/remove pizzas, adjust quantities, review orders, and exit. It maintains customer details, tracks costs, and handles delivery/pick-up options through a menu-driven interface.
def main(): customer_list = [] cost = 0 pizza_list = [ ["Cheese", 5], ["Pepperoni", 5], ["Hawaiian", 10], ["Meatlovers", 5] ] order_list = [ ["M", "Menu"], ["G", "get customer details"], ["N", "add pizza to order"], ["D", "delete piz...
def select_info_by_phrase(self, phrase): """ Query scraped info by phrase :param phrase: phrase for search :return: scraped info {phrase, title, price, page_size} """ self.create_connection() try: cur = self.conn.cursor() except Error as e: ...
This code inserts scraped product data into a database table if the phrase doesn't already exist, returning the count of added products. It checks for existing entries, establishes a database connection, executes an INSERT statement with parameters from the scrapInfo object, and commits the transaction.
def add_scrape_info(self, scrapInfo): """ Add scraped data into info table {id, phrase, title, price, page_size} @return: count of added products. """ add_cnt = 0 print("my step") if self.select_info_by_phrase(scrapInfo.phrase) is not None: pri...
def ping_all_peers(): """ args -> None This pings all peers and checks if they are alive or dead and removes the dead ones and stores the alive ones """ new_peers = [] peers = read_peers() for i in peers: if requests.post(i[0] + "ping", timeout=1.5).text == network_owner: new_...
The main task of the code is to synchronize peer information by fetching the latest peer list from a designated node, updating local storage with this data, and ensuring all peers (except the original) include the original node in their lists. This function is triggered when a node connects to the main node, facilitati...
def get_peers(): """ args -> None This is run when started and the node contacts the main node (my node) and I send back a list of all peers to the node. for all repls except the one referred to as the original, the repl shall contain peers that HAVE TO HAVE the original in it """ ping_all_peers() ...
def read_block_latest_db(): block = Blockchain.objects.latest('pub_date') return { 'transactions': json.loads(block.transactions), 'index': block.index, 'timestamp': float(block.timestamp), 'hash': block.hash, 'nonce': block.nonce, 'owner': block.owner } def w...
The function handles post-mining tasks by validating the block's index against the latest database entry. If valid, it updates the block with current transactions and nonce, saves it to the database, resets transaction list, broadcasts the block, and initializes a new block entry with incremented index, timestamp, owne...
def new_block_mined(self, nonce, index): """ steps after mining is completed successfully, such as looking at whether the block is outdated or not """ if read_block_latest_db()['index'] == index: block = read_block_latest_db() block['transactions'] = self.current_transact...
def read_block_latest_db(): block = Blockchain.objects.latest('pub_date') return { 'transactions': json.loads(block.transactions), 'index': block.index, 'timestamp': float(block.timestamp), 'hash': block.hash, 'nonce': block.nonce, 'owner': block.owner } def g...
The code performs Proof of Work mining by incrementing a counter to find a nonce that makes the block's hash meet the required difficulty level, then records the mined block with the valid nonce.
def mine(self): """ mining a block let people crash everything at this point idc. """ counter = 0 block = read_block_latest_db() hash = block['hash'] zero_string = generate_zero_string(self.difficulty) mined = False print( "MINING RN. Dont try ...
def start(): newline() sys.stdout.write(body_color) def package_name(): # If 'src' is a symlink, use base name of the symlink target if os.path.islink('src') and os.path.isdir('src/.'): return os.path.basename(os.readlink('src')) # Use script name as basis import inspect script_fil...
The function `test` executes either a test suite or a package's main module based on the `main` flag. If `main=True`, it retrieves the package name and optional arguments from a file, then runs the package's `__main__.py` using `python -m`. If `main=False`, it runs `pytest` to execute the test suite. The function also ...
def test(c, main=False): """ Run the test suite. Usage: test [--main] Options : --main Execute <package>/__main__.py and not the test suite """ start() if main: # '-m' requires <package>/__main__.py # package = slurp('package-name.txt').strip() ...
def start(): newline() sys.stdout.write(body_color) def format(c, top='src'): """ Run autopep8 on all .py files below 'src'. CHANGED: Run google's python formatter on all .py files below 'src'. Ideally 'src' is a symlink to your package source directory and tests are located at src/tests (...
This function cleans up build/test artifacts by removing directories like 'build', 'dist', and egg files, along with bytecode (.pyc/.pyo) files unless disabled. It also deletes 'docs/_build' if specified, matches custom patterns via --extra, and recursively removes __pycache__ and .pytest_cache directories, plus tempor...
def clean(c, docs=False, no_bytecode=True, extra=None): """ Cleanup build & test artifacts. Usage: clean [options] Options : --no-bytecode Retain .pyc and .pyo byte code files. --docs Also remove 'docs/_build'. --extra <p> Also remove files matching pattern <p>. ""...
def create_simulator(lattice, screen): ref_part = lattice.get_reference_particle() # We're only going to propagate a small number of particles # each at a different momentum to determine their tunes so I # don't really need the grid stuff. macro_particles = len(get_dpop_offsets()) print("Numb...
The code simulates particle beam propagation through a lattice for a specified number of turns using parallel computing. It configures RF cavities, sets open longitudinal boundaries, initializes parallel communication, registers diagnostics, and propagates the simulation. Key tasks include lattice setup, boundary condi...
def run_rr(lattice, turns): screen = synergia.utils.parallel_utils.Logger(0, synergia.utils.parallel_utils.LoggerV.DEBUG) sim = create_simulator(lattice, screen) # turn off RF and set open longitudinal boundary conditions # before propagating the particles rr_setup.setup_rf_cavities(lattice, 0, ...
def get_commits_period(from_date, to_date, gitdir): cmd = ['git', '--git-dir=' + gitdir, 'rev-list', '--since="{}"'.format(from_date.strftime('%Y-%m-%d')), '--before="{}"'.format(to_date.strftime('%Y-%m-%d')), '--all', '--no-merges'] return check_output(cm...
The code calculates code activity metrics across specified dates in a Git repository. It retrieves commits between `from_date` and `to_date`, categorizes each commit (e.g., 'New Work', 'Refactoring'), and sums their code changes (via `get_diff_count`). The result is a dictionary mapping activity types to their total co...
def get_counts_period(from_date, to_date, gitdir): commits = get_commits_period(from_date, to_date, gitdir) activity = {'New Work': 0, 'Refactoring': 0, 'Helping Others': 0, 'Code Churn': 0, 'Other': 0} for commit in commits: c_type, _ ...
def Card7hand(player,table): playerandtable = [] for c in player.hand: playerandtable.append(c) for c in table.communitycards: playerandtable.append(c) return playerandtable def CheckSF(tobechecked): sf = False high = int a = CheckF(tobechecked) if a[0]: flushlis...
The code evaluates a poker hand's strength by checking for specific combinations (e.g., straight flush, quads, full house) in descending order of priority. It assigns a score based on the hand's rank and card values, returning both the score and the hand's name (e.g., "Straight Flush"). If no higher-ranking hand is fou...
def Eval(player,table): #probably a better way to do this mash = Card7hand(player,table) score = 0 result = "" sf = CheckSF(mash) if sf[0]: score += 80000000000 score += sf[1] result = "Straight Flush" if score == 0: q = CheckQuads(mash) if q[0]: ...
def log(self, *args, **kwargs): if self.local_rank == 0: if not self.mute: #print(*args) self.console.print(*args, **kwargs) if self.log_ptr: print(*args, file=self.log_ptr) def prepare_data(self, data): if isinstance(data, list):...
The main task of this code is to perform one epoch of training for a neural network model using a data loader. It initializes training parameters, handles distributed training setup, computes loss via a training step, performs backpropagation with mixed precision, updates model weights, tracks metrics, and logs progres...
def train_one_epoch_svr(self, loader): self.log(f"==> Start Training Epoch {self.epoch}, lr={self.optimizer.param_groups[0]['lr']:.6f} ...") total_loss = 0 if self.local_rank == 0: for metric in self.metrics: metric.clear() self.model.train() # upda...
def log(self, *args, **kwargs): if self.local_rank == 0: if not self.mute: #print(*args) self.console.print(*args, **kwargs) if self.log_ptr: print(*args, file=self.log_ptr) def prepare_data(self, data): if isinstance(data, list):...
This code trains a neural network model for one epoch, handling distributed training, mixed precision, metrics tracking, and learning rate scheduling. It processes batches, computes loss, performs backpropagation, updates model parameters, and logs metrics like loss and learning rate. The training includes SMPL body pa...
def train_one_epoch(self, loader): self.log(f"==> Start Training Epoch {self.epoch}, lr={self.optimizer.param_groups[0]['lr']:.6f} ...") total_loss = 0 if self.local_rank == 0: for metric in self.metrics: metric.clear() self.model.train() # update g...
def log(self, *args, **kwargs): if self.local_rank == 0: if not self.mute: #print(*args) self.console.print(*args, **kwargs) if self.log_ptr: print(*args, file=self.log_ptr) def prepare_data(self, data): if isinstance(data, list):...
This function evaluates a model for one epoch on a validation dataset, computes loss, updates metrics, saves validation images, and handles distributed training. It processes data batches, precomputes KNN fields for each frame, runs evaluation steps with mixed precision, aggregates results across GPUs, and logs metrics...
def evaluate_one_epoch_svr(self, loader): self.log(f"++> Evaluate at epoch {self.epoch} ...") total_loss = 0 if self.local_rank == 0: for metric in self.metrics: metric.clear() self.model.eval() if self.local_rank == 0: pbar = tqdm.tqdm(...
def log(self, *args, **kwargs): if self.local_rank == 0: if not self.mute: #print(*args) self.console.print(*args, **kwargs) if self.log_ptr: print(*args, file=self.log_ptr) def prepare_data(self, data): if isinstance(data, list):...
The code evaluates a model on a validation dataset for one epoch. It computes loss, aggregates predictions/truths across GPUs, updates metrics, and saves validation images. The model is set to evaluation mode, and EMA (if enabled) is handled. Loss and metrics are logged, with results stored for tracking performance. (1...
def evaluate_one_epoch(self, loader): self.log(f"++> Evaluate at epoch {self.epoch} ...") total_loss = 0 if self.local_rank == 0: for metric in self.metrics: metric.clear() self.model.eval() if self.local_rank == 0: pbar = tqdm.tqdm(tota...
def log(self, *args, **kwargs): if self.local_rank == 0: if not self.mute: #print(*args) self.console.print(*args, **kwargs) if self.log_ptr: print(*args, file=self.log_ptr) def prepare_data(self, data): if isinstance(data, list):...
The code performs a test evaluation of a neural network model on a given dataset. It processes input data in batches, generates RGB and depth predictions using the model, and saves these outputs as PNG images. Additionally, it compiles the results into video files (RGB and depth) for visualization. The test runs in eva...
def test(self, loader, save_path=None): if save_path is None: save_path = os.path.join(self.workspace, 'results') else: save_path = os.path.join(self.workspace, save_path) os.makedirs(save_path, exist_ok=True) self.log(f"==> Start Test, save results to ...
def train_one_epoch_svr(self, loader): self.log(f"==> Start Training Epoch {self.epoch}, lr={self.optimizer.param_groups[0]['lr']:.6f} ...") total_loss = 0 if self.local_rank == 0: for metric in self.metrics: metric.clear() self.model.train() # upda...
The code trains a Support Vector Regression (SVR) model using provided data loaders, performing epochs up to `max_epochs`. It logs training progress with TensorBoard if enabled, saves full checkpoints at regular intervals, evaluates model performance on validation data periodically, and stores the best model checkpoint...
def train(self, train_loader, valid_loader, max_epochs): if self.use_tensorboardX and self.local_rank == 0: self.writer = tensorboardX.SummaryWriter(os.path.join(self.workspace, "run", self.name)) for epoch in range(self.epoch, max_epochs + 1): self.epoch = epoch ...
def _input( self ): vertex_count, edge_count = map(int, input("Enter n, m: ").split()) graph = FlowGraph(vertex_count) # graph.print_graph() for _ in range(edge_count): u, v, lower_bound, capacity = map(int, input("Enter (u, v, l, c): ").split()) graph.add_edge(u ...
This code initializes a flow network solver by reading input data, computes a circulation (flow) in the network using the find_Circulation method, and writes the resulting flow values and flow paths. The core task is solving a maximum flow/circulation problem in a directed graph with capacities, typical in network flow...
def __init__( self ): graph, n, m = self._input() flow, flows = self.find_Circulation(graph, n, m) self.write(flow, flows)
def actual_state(self): print ("check actual state") current_state = "3" conn = upnp() try: with time_limit(self.timeout_val): resp = conn.sendSOAP(str(self.ip_address) +':'+self.port, 'urn:Belkin:service:basicevent:1','http://'+ str(self.ip_address) + ':'+sel...
This code updates a device's state (on/off) to match its target state by checking the current state. If discrepancies exist, it triggers the on() or off() method based on the target state, then resets the target state to -1 upon success. It also includes commented database query logic for fetching device details, sugge...
def apply(self): current_state = self.actual_state() print("Apply {} ({} == {})".format(self.name,self.state,current_state)) #self.cur.execute("SELECT `room_id`, `state`, `target_state`, `last_on`, `last_off`, `modified` FROM `WeMoLights` WHERE `mac_address` = '{}' LIMIT 1".format(self....
def actual_state(self): print ("check actual state") current_state = "3" conn = upnp() try: with time_limit(self.timeout_val): resp = conn.sendSOAP(str(self.ip_address) +':'+self.port, 'urn:Belkin:service:basicevent:1','http://'+ str(self.ip_address) + ':'+sel...
The main task of the code is to monitor and synchronize the system's actual state with a target state. It checks if the current state matches the target state, corrects discrepancies by setting the state to the target, and handles error states by attempting to find a port. The process concludes by saving the updated st...
def observe(self): self.state = self.actual_state() # if error state find port and try again... if(self.state == "2"): if(self.findPort()): self.state = self.actual_state() # if target state != actual state try to set state to target state if(int(self....
def train_classifier(self, classifier, iteration, epoch, best_metrics_valid=0.0, losses_train=None, losses_valid=None, segmenter=None ...
This function trains and validates a neural network model (either a classifier, segmenter, or both in a joint setup) based on the specified experiment type. It iterates through epochs, updating model parameters, tracking training/validation losses/metrics, and adjusting loss weights (e.g., binary/multi-class segmentati...
def train_experiment( self, iteration, max_epoch, epoch, segmenter=None, losses_train_seg=None, losses_valid_seg=None, best_metrics_valid_seg=None, binary_seg_weight=0, multi_seg_weight=1, ...
def user_input(self): self.velocity_x = 0 self.velocity_y = 0 # check for key presses keys = pygame.key.get_pressed() if keys[pygame.K_w]: self.velocity_y = -self.speed if keys[pygame.K_a]: self.velocity_x = -self.speed if keys[pygame.K_s...
The code's main task is to handle a game entity's update loop by processing user input, movement, aiming, ammo pickup, and ammo counter updates. It also decrements the shooting cooldown timer each tick if active, preparing the entity to shoot again after a delay.
def update(self): self.user_input() self.move() self.aim() self.ammo_pickup() self.ammo_counter() # reduce time before next shot each tick if self.shoot_cooldown > 0: self.shoot_cooldown -= 1
def getHorizontalMatrix(s): return s.split("\n") def getVerticalMatrix(s): return transposeMatrix(getHorizontalMatrix(s)) def findLineOfReflextion(m, smudge): for i in range(0, len(m) - 1): reflection = checkReflection(m, i, smudge) if reflection != (-1, -1): return reflection ...
The code calculates the sum of horizontal and vertical reflection line positions from matrices generated for each input item. Horizontal reflections contribute (position + 1) × 100 to the total, while vertical reflections add (position + 1). The function returns the aggregated sum of these values.
def partOne(input): hs = 0 vs = 0 for item in input: hm = getHorizontalMatrix(item) vm = getVerticalMatrix(item) hr = findLineOfReflextion(hm, 0) vr = findLineOfReflextion(vm, 0) if hr != (-1, -1): hs += (hr[0] + 1) * 100 if vr != (-1, -1): ...
def getHorizontalMatrix(s): return s.split("\n") def getVerticalMatrix(s): return transposeMatrix(getHorizontalMatrix(s)) def findLineOfReflextion(m, smudge): for i in range(0, len(m) - 1): reflection = checkReflection(m, i, smudge) if reflection != (-1, -1): return reflection ...
The code calculates a score based on reflection lines in horizontal and vertical matrices derived from input items. For each item, it computes horizontal (hm) and vertical (vm) matrices, finds their reflection lines, and accumulates scores: horizontal reflections contribute (position + 1) × 100, vertical reflections ad...
def partTwo(input): hs = 0 vs = 0 for item in input: hm = getHorizontalMatrix(item) vm = getVerticalMatrix(item) hr = findLineOfReflextion(hm, 1) vr = findLineOfReflextion(vm, 1) if hr != (-1, -1): hs += (hr[0] + 1) * 100 if vr != (-1, -1): ...
def draw_ec11_cutout(dxf, item): draw_rect_cutout(dxf, item, (12, 12)) def draw_oled_cutout(dxf, item): draw_rect_cutout(dxf, item, (19.05*2, 14)) def draw_mx_horiz_stab_cutout(dxf, item, s): center_x, center_y = get_center(item) dxf.add_polyline_2d([(u+center_x, v+center_y) for (u, v) in get_stabilizer_shape(s)]) ...
This function determines the appropriate cutout type to draw in a DXF file based on the item's label and dimensions. It uses conditional checks to select between specific cutout functions like `draw_ec11_cutout`, `draw_oled_cutout`, or `draw_mx_*_stab_cutout`, with parameters adjusted according to item size, ensuring a...
def draw_item(dxf, item): # draw_rect_cutout(dxf, item, (u_to_mm(item['w']), u_to_mm(item['h']))) if item['label'] == 'X7': draw_ec11_cutout(dxf, item) elif item['label'] == 'OLED': draw_oled_cutout(dxf, item) elif item['w'] == 6.25: draw_mx_horiz_stab_cutout(dxf, item, 50) elif item['w'] >= 2: draw_mx_hor...
def draw_outline(dxf, dimensions): w, h = dimensions dxf.add_line(u_to_coords(0, -0.5), u_to_coords(w, -0.5)) dxf.add_line(u_to_coords(w+0.5, 0), u_to_coords(w+0.5, h)) dxf.add_line(u_to_coords(w, h+0.5), u_to_coords(0, h+0.5)) dxf.add_line(u_to_coords(-0.5, h), u_to_coords(-0.5, 0)) dxf.add_arc(u_to_coords(w, 0)...
The code generates two DXF files (plate and back) with specified dimensions. It draws outlines, outer screws, and layout items on the plate file, while the back file includes outlines, outer screws, and inner screws. The function facilitates creating 2D designs for plates and backs, likely for manufacturing or engineer...
def generate_dxf(layout, plate_filename, back_filename): dimensions = (22.5, 7.5) with r12writer(plate_filename) as dxf: draw_outline(dxf, dimensions) draw_outer_screws(dxf, dimensions) for item in layout: draw_item(dxf, item) with r12writer(back_filename) as dxf: draw_outline(dxf, dimensions) draw_ou...
def get_layout_raw(filename): with open(filename, encoding='utf-8') as f: raw = json.load(f) return raw def parse_layout_data(raw): result = [] meta = None if not isinstance(raw[0], list): meta, *raw = raw y = 0 for row in raw: x = 0 w = 1 h = 1 for item in row: if isinstance(item, str): la...
The main task of the code is to process an input file, parse its layout data, and generate two DXF files (plate and back) based on the parsed layout. The function reads raw data from `infile`, converts it into a structured layout, and exports the results to `outfile_plate` and `outfile_back`, logging the input-output m...
def main(infile, outfile_plate, outfile_back): raw = get_layout_raw(infile) layout = parse_layout_data(raw) generate_dxf(layout, outfile_plate, outfile_back) print(f'{infile} => {outfile_plate}') print(f'{infile} => {outfile_back}')
def upload_cert(domain, acme_install_dir): """https://cloud.tencent.com/document/product/400/9078""" cert_dir = os.path.expanduser(os.path.join(acme_install_dir, domain)) params = { "alias": "%s.%s.%s" % ( domain, datetime.utcnow().strftime("%Y%m%d"), int(time.time())), "Action":...
The code automates renewing a Tencent CDN HTTPS certificate by uploading a new certificate, configuring it for the domain, and deleting all existing certificates except the newly uploaded one.
def main(): domain = os.getenv("DOMAIN") cert_id = upload_cert(domain, os.getenv("ACME_INSTALL_DIR")) config_cdn_cert(cert_id, "www.%s" % domain) cert_ids = list_cert_ids() cert_ids.remove(cert_id) for cert_id in cert_ids: delete_cert(cert_id) print("Renew tencent cdn https cert ...
def var(n, v=None): """ shortcut for setting a variable """ return Gvars['tpl'].var(n, v) def set_stack_vars(): a = '' for m in Gvars['stacks']['messages']: a += f'<p class="message">{m}</p>\n' var('MESSAGES', a) a = '' for m in Gvars['stacks']['errors']: a += f'<p class="err...
The main task of the code is to render an HTML page by combining header, content, and footer templates. It loads specified template files from a directory, injects variables like page title and version, and outputs the concatenated HTML content. The function handles I/O errors during file access and exits after renderi...
def page(pagename, title=''): """ display a page from html template """ tl = Gvars['tpl'] htmldir = Gvars['config']['htmlDir'] file_ext = Gvars['template_ext'] var('pageTitle', title) var('VERSION', Gvars['VERSION']) set_stack_vars() for p in ('header', pagename, 'footer'): try: ...
def connect(): try: db = BWDB(dbms='sqlite', database='./data/jurl.db') print(f"BWDB version {db.version()}") print(f"dbms is {db.dbms}") except BWErr as err: db = None print(f"Error: {err}") exit(1) GLOBALS['db'] = db return db def do_menu(): while T...
The main task of the code is to create a database table 'jurl' for storing short and target URLs if it doesn't exist, then enter a loop to handle user interactions through a menu system. The code connects to a database, checks for the table's existence, creates it if needed, and processes user responses to either quit ...
def main(): connect() db = GLOBALS['db'] # create table if not exists create_table_statement = ''' CREATE TABLE IF NOT EXISTS jurl ( id integer PRIMARY KEY, shortURL VARCHAR(32) UNIQUE NOT NULL, targetURL VARCHAR(128) NOT NULL ) ''' try: ...
def set_form_vars(**kwargs): s = kwargs.get('shortURL', '') t = kwargs.get('targetURL', '') row_id = kwargs.get('id', '') var('shortURL', s) var('targetURL', t) var('id', row_id) var('SELF', Gvars['linkback']) def hidden(n, v): Gvars['stacks']['hiddens'].append([n, v]) def page(pagename,...
The main task of the code is to load a specific database record using an ID from request variables, populate a form with that record's data, set hidden fields for update operations, and render an "Edit this short URL" page for modifying the entry.
def edit(): db = Gvars['db'] row_id = Gvars['vars'].getfirst('id') rec = db.make_dict_row(db.get_row(row_id)) set_form_vars(**rec) hidden('a', 'update') hidden('id', row_id) hidden('sURL', rec['shortURL']) page('edit', 'Edit this short URL')
def set_form_vars(**kwargs): s = kwargs.get('shortURL', '') t = kwargs.get('targetURL', '') row_id = kwargs.get('id', '') var('shortURL', s) var('targetURL', t) var('id', row_id) var('SELF', Gvars['linkback']) def hidden(n, v): Gvars['stacks']['hiddens'].append([n, v]) def page(pagename,...
This function prepares a confirmation page for deleting a short URL. It retrieves the record using an ID, sets hidden form fields for deletion action, and displays a confirmation message.
def delete_confirm(): db = Gvars['db'] row_id = Gvars['vars'].getfirst('id') rec = db.make_dict_row(db.get_row(row_id)) set_form_vars(**rec) hidden('a', 'delete_do') hidden('id', row_id) hidden('shortURL', rec['shortURL']) page('delconfirm', 'Delete this short URL?')
def message(*m_list, **kwargs): stackmessage('messages', *m_list, **kwargs) def list_pagebar(pageno, numpages): """ return the html for the pager line """ prevlink = '<span class="n">&lt;&lt;</span>' nextlink = '<span class="n">&gt;&gt;</span>' linkback = Gvars['linkback'] if pageno > 0: ...
The main task of the code is to display paginated database records with navigation controls. It calculates total records, determines current page number via user input, retrieves limited records per page, generates a pagination bar, and assembles the content with records and navigation links for display.
def listrecs(): """ display the database content """ db = Gvars['db'] v = Gvars['vars'] sql_limit = int(Gvars['config'].get('sql_limit', 25)) # how many records do we have? count = db.count_rows() message(f"There are {count or 'no'} records in the database. Add some more!") # how many ...
def var(n, v=None): """ shortcut for setting a variable """ return Gvars['tpl'].var(n, v) def listrecs(): """ display the database content """ db = Gvars['db'] v = Gvars['vars'] sql_limit = int(Gvars['config'].get('sql_limit', 25)) # how many records do we have? count = db.count_rows() ...
The main task of the code is to manage the main page of a URL shortening application. It temporarily disables displaying unknown entries, processes target and short URLs, restores original settings, and prepares the interface for entering a new short URL. The function handles variable storage, UI state adjustments, and...
def main_page(): # save values unkflag = Gvars['tpl'].flags['showUnknowns'] Gvars['tpl'].flags['showUnknowns'] = False target_url = var('targetURL') short_url = var('shortURL') Gvars['tpl'].flags['showUnknowns'] = unkflag listrecs() if target_url is not None: var('targetURL', t...
def main_page(): # save values unkflag = Gvars['tpl'].flags['showUnknowns'] Gvars['tpl'].flags['showUnknowns'] = False target_url = var('targetURL') short_url = var('shortURL') Gvars['tpl'].flags['showUnknowns'] = unkflag listrecs() if target_url is not None: var('targetURL', t...
This code handles adding a short URL entry by retrieving form data, validating inputs, and inserting records into a database. It checks for existing 'shortURL' and 'targetURL' parameters, generates short URLs if needed, and handles duplicate errors. The function updates form variables, displays messages, and renders th...
def add(): db = Gvars['db'] v = Gvars['vars'] cgi = Gvars['cgi'] if 'shortURL' in v: short_url = v.getfirst('shortURL') else: short_url = '' if 'targetURL' in v: target_url = v.getfirst('targetURL') else: target_url = '' main_page() rec = dict( ...
def add(): db = Gvars['db'] v = Gvars['vars'] cgi = Gvars['cgi'] if 'shortURL' in v: short_url = v.getfirst('shortURL') else: short_url = '' if 'targetURL' in v: target_url = v.getfirst('targetURL') else: target_url = '' main_page() rec = dict( ...
The main task of the code is to dispatch operations based on the value of variable 'a' from Gvars. It routes to functions like add(), edit(), delete_confirm(), update(), or delete_do() depending on 'a's value, with conditional checks for cancellation or specific parameters. Errors are handled for invalid inputs, and ma...
def dispatch(): v = Gvars['vars'] a = v.getfirst('a') if a == 'add': add() elif a == 'edit_del': if 'edit' in v: edit() elif 'delete' in v: delete_confirm() else: error("invalid edit_del") elif a == 'update': if 'cancel' in ...
def get_hist_nbpixel_vs_grayintensity(tiff_data, output_path=None): """ For a given list of images in np.array format, return a histogram of the number of pixels per gray intensity of each of the given arrays. Parameters ---------- tiff_data : np.array 2D or 3D np.array. output_path...
The function `cv_report` generates components of a CV report from a TIFF image, including ROI-marked images, microscopy metadata, intensity histograms, and pixel intensity dataframes. If an `output_dir` is specified, it saves these elements as files (e.g., PNGs and CSVs) in the directory. Otherwise, it returns a list c...
def cv_report( tiff_path, output_dir=None, microscope_type="NA", wavelength="NA", NA="NA", sampling_rate="NA", pinhole="NA" ): """ Generate the different componenent of the cv report and stock them in a list. If output_dir specified, it sav...
def getRequest(self, url): ''' Performs an HTTP get request. ''' req = urllib2.Request(url) req.add_header('User-Agent', 'Mozilla/5.0' '(Windows; U; Windows NT 6.1; en-GB; rv:1.9.2.8) ' 'Gecko/20100722 Firefox/3.6.8') response = urllib2.urlopen(req) ...
This code extracts and displays event data from the SC2Casts "browse" page by parsing HTML links containing '/event' in their href. It uses a regex to identify event links, filters them based on the 'allEvents' flag (showing all or top events), and iterates through the results to add each event as a category with its n...
def browseEvents(self, params, allEvents): '''Extracts and displays all/top events from the main "browse" page of the SC2Casts site.''' get = params.get link = self.getRequest(get(NavigationConstants.URL)) soup = self.getSoup(link) allEventsMarker = soup.find('span', text='All Ev...
def getRequest(self, url): ''' Performs an HTTP get request. ''' req = urllib2.Request(url) req.add_header('User-Agent', 'Mozilla/5.0' '(Windows; U; Windows NT 6.1; en-GB; rv:1.9.2.8) ' 'Gecko/20100722 Firefox/3.6.8') response = urllib2.urlopen(req) ...
The code extracts and displays casters from SC2Casts' "browse" page by parsing HTML, identifying links with '/caster' paths, and adding them as categories. It uses `allCasters` to determine whether to list all casters or only top ones, adjusting the link traversal direction accordingly.
def browseCasters(self, params, allCasters): '''Extracts and displays all/top casters from the main "browse" page of the SC2Casts site.''' get = params.get link = self.getRequest(get(NavigationConstants.URL)) soup = self.getSoup(link) allCastersMarker = soup.find('span', ...
def getRequest(self, url): ''' Performs an HTTP get request. ''' req = urllib2.Request(url) req.add_header('User-Agent', 'Mozilla/5.0' '(Windows; U; Windows NT 6.1; en-GB; rv:1.9.2.8) ' 'Gecko/20100722 Firefox/3.6.8') response = urllib2.urlopen(req) ...
This code extracts and displays a list of players (either all or top) from the SC2Casts website's browse page by parsing HTML links containing '/player' paths. It uses BeautifulSoup to navigate the page, filters relevant links based on the 'allPlayers' flag, and adds each player as a category with their name, cast URL,...
def browsePlayers(self, params, allPlayers): '''Extracts and displays all/top players from the main "browse" page of the SC2Casts site.''' get = params.get link = self.getRequest(get(NavigationConstants.URL)) soup = self.getSoup(link) allPlayersMarker = soup.find('a', tex...
def getCastsURL(self, path): return self.SC2CASTS_URL + path def getRequest(self, url): ''' Performs an HTTP get request. ''' req = urllib2.Request(url) req.add_header('User-Agent', 'Mozilla/5.0' '(Windows; U; Windows NT 6.1; en-GB; rv:1.9.2.8) ' 'Gecko/20...
The main task of the `showTitles` method is to retrieve and display a list of SC2 series (games between players) from the SC2Casts website, dynamically adapting to user searches, filters, or navigation choices. It parses HTML content, applies user-defined settings (e.g., colors, date display, spoiler options), and gene...
def showTitles(self, params = {}): ''' This method shows a list of series, i.e., each list entry generated by this method represents a series (which can be any number of games) between two SC2 players (or more if it is a 2v2 for example). This method is the central piece of cod...
def setWatched(self, url): ''' Sets the watched marker for a series to TRUE. ''' if self.checkWatched(url): return conn = self.getDBConn() if conn is not None: c = conn.cursor() urlList = (url,) c.execute('INSERT INTO watched VALUES (?)', u...
The code extracts and displays SC2 series videos (or "video" entries) from YouTube/Twitch embeds, marks them as watched if enabled, and optionally adds dummy videos to avoid spoilers. It processes iframe sources, generates list entries/queue items based on the 'play' flag, and notifies users when adding to the queue.
def showGames(self, params, play): ''' Extracts and displays a number of games from a SC2 series. (Actually "games" is misleading because often more than one games is included in one of the list items. A more precise description would be "video".) ''' get = para...
def getRequest(self, url): ''' Performs an HTTP get request. ''' req = urllib2.Request(url) req.add_header('User-Agent', 'Mozilla/5.0' '(Windows; U; Windows NT 6.1; en-GB; rv:1.9.2.8) ' 'Gecko/20100722 Firefox/3.6.8') response = urllib2.urlopen(req) ...
This code extracts and displays event rounds (e.g., Semi Final, Final) from a sports event webpage. It identifies the current round via an HTML element, adds it as a category, then uses regex to find all other rounds linked via JavaScript. For each round, it constructs URLs and adds them as categories for navigation, e...
def browseEventRounds(self, params = {}): '''Extracts and displays the event rounds (e.g. Semi Final, Final, etc.) of a particular event.''' get = params.get url = get('url') link = self.getRequest(url) soup = self.getSoup(link) currentRound = soup.find('a', id='selected'...
def getRequest(self, url): ''' Performs an HTTP get request. ''' req = urllib2.Request(url) req.add_header('User-Agent', 'Mozilla/5.0' '(Windows; U; Windows NT 6.1; en-GB; rv:1.9.2.8) ' 'Gecko/20100722 Firefox/3.6.8') response = urllib2.urlopen(req) ...
The main task of the code is to retrieve and display a list of series associated with a specific player, identified by their position (first or second party) in a matchup. It extracts player-specific URLs from a given webpage, constructs navigation parameters, and triggers the display of titles linked to that player us...
def findPlayer(self, url, playerNo): ''' Displays a lists of series of a player. The player is identified by the id of the (most probably) currently inspected series and their number (first or second party in the matchup). ''' link = self.getRequest(url) soup = ...
def sendMove(self,data): move_flag = 2 data1 = data.encode() connectionSocket.send(data1) gameBoard.lastuser = gameBoard.username1 self.setMove(data,move_flag) def check_win(self): win_flag = gameBoard.isGameFinished() if ((win_flag == 1) or (win_flag == 2)): ...
The main task of the code is to handle a player's move in a turn-based game. It checks if the selected button (btn1) is available (marked by '-'), sends the move data ('1') to the game, checks for a win, and if no win occurs, waits for the opponent's move. If the button is already occupied, it alerts the player with an...
def choose1(self): gameChar = self.btn1['text'] if gameChar == '-': data = '1' self.sendMove(data) if_win = self.check_win() if not if_win: self.recieveMove() else: tkinter.messagebox.showinfo("Error: Invalid Move", "I...
def sendMove(self,data): move_flag = 2 data1 = data.encode() connectionSocket.send(data1) gameBoard.lastuser = gameBoard.username1 self.setMove(data,move_flag) def check_win(self): win_flag = gameBoard.isGameFinished() if ((win_flag == 1) or (win_flag == 2)): ...
The main task of the code is to handle a player's move in a turn-based game. It checks if the selected button (btn2) is empty ('-'), sends the move data '2' if valid, checks for a win, and proceeds to receive the opponent's move if the game isn't won. If the button is occupied, it shows an error message for invalid mov...
def choose2(self): gameChar = self.btn2['text'] if gameChar == '-': data = '2' self.sendMove(data) if_win = self.check_win() if not if_win: self.recieveMove() else: tkinter.messagebox.showinfo("Error: Invalid Move", ...
def sendMove(self,data): move_flag = 2 data1 = data.encode() connectionSocket.send(data1) gameBoard.lastuser = gameBoard.username1 self.setMove(data,move_flag) def check_win(self): win_flag = gameBoard.isGameFinished() if ((win_flag == 1) or (win_flag == 2)): ...
The function `choose3` handles a player's move on a game board by checking if the third position (btn3) is empty ('-'). If so, it sends the move '3', checks for a win, and if no win occurs, waits for the next move. If the position is occupied, it displays an error message for invalid moves.
def choose3(self): gameChar = self.btn3['text'] if gameChar == '-': data = '3' self.sendMove(data) if_win = self.check_win() if not if_win: self.recieveMove() else: tkinter.messagebox.showinfo("Error: Invalid Move", ...
def sendMove(self,data): move_flag = 2 data1 = data.encode() connectionSocket.send(data1) gameBoard.lastuser = gameBoard.username1 self.setMove(data,move_flag) def check_win(self): win_flag = gameBoard.isGameFinished() if ((win_flag == 1) or (win_flag == 2)): ...
The main task of the code is to handle a player's move selection on a game board. When the fourth button (btn4) is chosen, it checks if the cell is empty ('-'). If so, it sends the move '4', checks for a win, and if no win occurs, waits for the opponent's move. If the cell is occupied, it displays an error message proh...
def choose4(self): gameChar = self.btn4['text'] if gameChar == '-': data = '4' self.sendMove(data) if_win = self.check_win() if not if_win: self.recieveMove() else: tkinter.messagebox.showinfo("Error: Invalid Move", ...
def sendMove(self,data): move_flag = 2 data1 = data.encode() connectionSocket.send(data1) gameBoard.lastuser = gameBoard.username1 self.setMove(data,move_flag) def check_win(self): win_flag = gameBoard.isGameFinished() if ((win_flag == 1) or (win_flag == 2)): ...
The main task of the code is to handle a move selection in a game. It checks if the button labeled '5' is available (marked by '-'). If available, it sends the move '5', checks for a win, and awaits the next move if no win occurs. If the button is already occupied, it displays an error message prompting the user to try...
def choose5(self): gameChar = self.btn5['text'] if gameChar == '-': data = '5' self.sendMove(data) if_win = self.check_win() if not if_win: self.recieveMove() else: tkinter.messagebox.showinfo("Error: Invalid Move", ...
def sendMove(self,data): move_flag = 2 data1 = data.encode() connectionSocket.send(data1) gameBoard.lastuser = gameBoard.username1 self.setMove(data,move_flag) def check_win(self): win_flag = gameBoard.isGameFinished() if ((win_flag == 1) or (win_flag == 2)): ...
The function `choose6` handles a player's move selection in a game by checking if the sixth position (btn6) is available (marked with '-'). If available, it sends the move '6', checks for a win, and waits for the next move if the game isn't won. If the position is already occupied, it displays an error message to promp...
def choose6(self): gameChar = self.btn6['text'] if gameChar == '-': data = '6' self.sendMove(data) if_win = self.check_win() if not if_win: self.recieveMove() else: tkinter.messagebox.showinfo("Error: Invalid Move", ...