dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def delay(n, T, k): return n*T + Z_inv(1-T, k) def beta_and_p(delay, T, k): p = delay//T return Z_der(delay-p*T, k), p def Z(theta, k): a, c, b = _get_parameters(k) t = -np.tanh(k*theta+b) return (t+a)/c
The main task of the code is to generate a plot of a system's behavior using calculated parameters. It computes delay (d), beta (β), and p values from inputs T, k, n, then visualizes the system's dynamics via the Z(theta, k) function over specified steps, displaying the results with a title containing the computed para...
def plot(T, k, n, steps=50): d = delay(n, T, k) beta, p = beta_and_p(d, T, k) plot_system(lambda theta: Z(theta, k), d, steps=steps, title=fr"$\tau={d}, k={k}, \beta={beta}, p={p}$")
def major_class(data,attributes,target): freq={} index=attributes.index(target) for t in data: if t[index] in freq: freq[t[index]]+=1 else: freq[t[index]]=1 m=0 major="" for key in freq.keys(): if freq[key]>m: m=freq[key] ma...
This code constructs a decision tree recursively by selecting the best attribute to split the data, creating subtrees for each possible value of the attribute, and using majority class labels as leaf nodes when no further splits are possible or all instances share the same target class.
def build_tree(data,attributes,target): vals=[record[attributes.index(target)]for record in data] default=major_class(data,attributes,target) if not data or (len(attributes)-1)<=0: return default elif vals.count(vals[0])==len(vals): return vals[0] else: best=attr_choose(data,...
def update_nombre_y_path(self,nombre_proyecto,carpeta): '''Actualiza el nombre de proyecto y su carpeta''' self.configuracion.nombre_proyecto = nombre_proyecto self.configuracion.path_proyecto = carpeta def get_plugins_obligatorios(self): '''Retorna todos los plugins obligatorios configu...
This code initializes an object with project name, directory, and main path, validates inputs, sets up required plugins, and configures the main plugin. It checks for valid project names, assigns default paths if missing, and prepares plugin lists for use.
def __init__(self, *args): ''' arg0 : nombre_proyecto, arg1 : carpeta, arg2 : path_principal ''' nombre_proyecto, carpeta = args[0],args[1] path_principal = args[2] if len(args)>2 and is_dir(args[2]) else None super().__init__(path_principal) ...
def generate_population(N): pop = [] for i in range(N): c1 = random.randint(0,100) c2 = random.randint(0,100) c3 = random.randint(0,100) pop.append([c1,c2,c3]) return pop def fitness(pop, num_sims): fit_list = [] for ls in pop: b = board() player = GAPlayer(b, ls[0], ls[1], ls[2]) ...
The code implements a genetic algorithm to optimize a set of weights over multiple generations. It initializes a population, evaluates fitness through simulations, iteratively evolves the population via selection and mutation, and returns the best-performing weight configuration after specified generations.
def genetic_algorithm(num_gens, N, num_sims): pop = generate_population(N) fit_list = fitness(pop, num_sims) for i in range(num_gens): pop = next_generation(pop, fit_list) fit_list = fitness(pop, num_sims) max_fitness = max(fit_list) max_ind = fit_list.index(max_fitness) weights = pop[max_ind] pri...
def get_corners(img): lines = lsd(img) corners = [] if lines is not None: lines = lines.squeeze().astype(np.int32).tolist() horizontal_lines_canvas = np.zeros(img.shape, dtype=np.uint8) vertical_lines_canvas = np.zeros(img.shape, dtype=np.uint8) for line in lines: ...
The main task of the code is to detect and return the largest valid rectangular contour from an image, either by identifying corners and validating quadrilaterals or using standard contour detection. It processes the input image through grayscale conversion, blurring, edge detection, and morphological operations, then ...
def get_contour(rescaled_image): MORPH = 9 CANNY = 84 IM_HEIGHT, IM_WIDTH, _ = rescaled_image.shape gray = cv2.cvtColor(rescaled_image, cv2.COLOR_BGR2GRAY) gray = cv2.GaussianBlur(gray, (7, 7), 0) kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (MORPH, MORPH)) dilated = cv2.morphologyE...
def standard_transform_y_inv(stats, x): return x[:,:28]*stats['ytrain_std']+stats['ytrain_mean'] def standard_transform_x_inv(stats, x): return x*stats['xtrain_std']+stats['xtrain_mean'] def get_scores(true, pred, X_test, stats): r2= r2_score(true, pred) r2_log = r2_score(np.log(np.abs(true)+1e-8), np...
The main task of the code is to evaluate a machine learning model's performance on test data by calculating validation scores (R², RMSE, Mass RMSE, Negative fraction). It applies inverse transformations to standardized predictions and test data, then computes metrics using the `get_scores` function, returning these sco...
def get_val_scores(model, X_test, y_test, epoch, stats, args): mse = 0 r2 = 0 mass = 0 neg = 0 model.eval() pred = model(torch.Tensor(X_test).to(device)) pred = pred.cpu().detach().numpy() #scale back pred = standard_transform_y_inv(stats, pred) y_test = standard_transform_y...
def get_classes(signs): y_signs = np.ones((signs.shape[0],28)) y_signs[:,0] = -1 y_signs[signs[:,0]<0.5,1] = -1 y_signs[signs[:,1]<0.5,2] = -1 y_signs[signs[:,2]<0.5,3] = -1 y_signs[:,4] = 1 y_signs[signs[:,3]<0.5,5] = -1 y_signs[signs[:,4]<0.5,6] = -1 y_signs[:,7] = 1 y_signs[:,...
The function generates a model evaluation report by predicting test data, applying inverse scaling transformations, handling classification/correction tasks, calculating scores, and saving results along with arguments. It processes predictions, adjusts for scaling methods (z/log), applies corrections if needed, compute...
def create_report(model, X_test, y_test, stats, args): #predict pred = model(torch.Tensor(X_test).to(device)) pred = pred.cpu().detach().numpy() #scale back if args.model == 'classification': classes = get_classes(pred) np.save('./data/classes.npy',classes) scores = get_class...
def model_step(model, train_data, optimizer, epoch, args): running_loss = 0 for x, y in train_data: x = x.to(device) optimizer.zero_grad() model.to(device) output = model(x) y = y.to(device) loss = get_loss(output, y, args) loss.backward() optimize...
This function trains a neural network model using provided training and test data, employing early stopping to prevent overfitting. It iterates over epochs, updating the model with optimizer, evaluating validation loss, and optionally recording metrics like R², MSE, and mass balance. The best model is saved based on va...
def train_model(model, train_data, test_data, optimizer, input_dim, output_dim, X_test, y_test, stats, args): best = 1e20 patience = 0 print('GPU available:', torch.cuda.is_available()) is_stop = False if args.save_val_scores: val_r2 = [] val_mse = [] val_mass = [] va...
def heapSort(arr): n = len(arr) # Build a maxheap. for i in range(n, -1, -1): heapify(arr, n, i) # One by one extract elements for i in range(n - 1, 0, -1): arr[i], arr[0] = arr[0], arr[i] # swap heapify(arr, i, 0) def evaluation(colorVal, graphVal): # this is the c...
This code implements a hill climbing algorithm for graph coloring. It iteratively explores adjacent states by modifying node colors, evaluates their validity (score), and selects the best improvement using heap sort. The algorithm tracks memory usage, exploration steps, and visits, returning these metrics upon finding ...
def hillClimbingSimple(colorHill, graphHill, nodeNum): queue = [] answerQueue = [] extendSize = 0 visitSize = 1 # here i measure the real size of each algorithm in bytes storage = 0 # here I must generate all adjacent states that one situation has # in this kind of problems (graph colori...
def parse_args(): ap = argparse.ArgumentParser() """ Data saving arguments """ # plot name argument ap.add_argument("-p", "--plot_name", default="deep_history_plot", help="The name you wish to save the history plot under") # report ...
The main task of the code is to perform classification using specified parameters (epochs, embed_size, batch_size), ensure reproducibility via a fixed random seed, generate a report and training history, save the report to a text file, plot the history, and print the report.
def main(): # parse arguments args = parse_args() # get parameters report_name = args["report_name"] epochs = args["epochs"] embed_size = args["embed_size"] batch_size = args["batch_size"] plot_name = args["plot_name"] # fix random seed for reproducibility seed = 42 np.random...
def get_previous_sensor_data(device_id, timestamp): """ get the last recorded data point for a given device unique ID Args: device_id: String containing the unique ID of the IoT device timestamp: IoT rule writes directly to the database so we need to ensure we ignore messages with...
This function checks if a two-week summary entry is needed for an IoT device by comparing the current event's timestamp with the last recorded data point. If the new data falls in the next hour, it retrieves the last hour's data, calculates averages, and stores the summary in the two-week table for long-term tracking.
def two_week_update_check(device_id, event): """ check if two week table entry is required get the last recorded data point for this device unique ID if the new message occurred in the next hour: get all data for the last hour for this device unique ID create a summary an...
def get_page(self,url): self.page = webdriver.Chrome(executable_path=self.chromedriver_path, chrome_options=self.chrome_options) try: self.page.get(url) except: time.sleep(60) self.get_page(url) def pageges_list_builder(self) -> None: page_body = Beaut...
This code downloads all chapters of a manga by scrolling through a webpage to load chapter links, collecting them, and then downloading the associated images.
def download_all_from_page(self): url=f'https://mangalib.me/{self.manga_name}?section=chapters' self.get_page(url) i=1 while True: start_len=len(self.page_links) self.page.execute_script(f"window.scrollTo(0, document.documentElement.clientHeight*{i})") ...
def write_output(msg, end='\n'): print(str(msg), end=end, flush=True) def print_feeding_indicator(): global indicator_bool indicator = "\\" if indicator_bool else "/" write_output('=', end="") indicator_bool = not indicator_bool def write_to_file(text, command_audio_buffer): def write(text, com...
This function processes streaming audio data by buffering and converting it to text via STT, emitting real-time results, handling sample tagging logic, sending user input to a bot for response generation, converting bot responses to speech via TTS, and emitting both text and audio outputs through WebSocket. It manages ...
def handle_stream_audio(data): global stt_res_buffer stt_res_buffer = None global command_audio_buffer global session_audio_buffer if len(command_audio_buffer) == 0: write_output("recieving first stream of audio command") data = bytes(data) command_audio_buffer += data sessi...
def _split_docstring(value): headers = {} current_header = '' current_lines = [] lines = value.split('\n') index = 0 while index < len(lines): if index + 1 < len(lines) and len(lines[index + 1].strip(' ')) > 0 and \ len(lines[index + 1].strip(' ').strip('-')) == 0: ...
The code reads a JSON metadata file, validates and updates class definitions by checking their docstrings, and writes the updated metadata back to the file. It skips specific modules, ensures classes exist, verifies docstrings, splits headers, and updates schema descriptions/parameters accordingly.
def _metadata(): json_file = os.path.join(os.path.dirname(__file__), '../source/sklearn-metadata.json') with open(json_file, 'r', encoding='utf-8') as file: json_root = json.loads(file.read()) for schema in json_root: name = schema['name'] skip_modules = [ 'lightgbm.', ...
def _threads(address=None): threads = [ _ for _ in threading.enumerate() if isinstance(_, HTTPServerThread) and _.alive() ] if address is not None: address = _make_address(address) threads = [ _ for _ in threads if address[0] == _.address[0] ] if address[1]: threads = [ _ for...
The main task of the code is to wait for all model server threads to exit by continuously checking the thread count, and upon console exit or interruption, it logs a message and stops the servers.
def wait(): '''Wait for console exit and stop all model servers.''' try: while len(_threads()) > 0: time.sleep(0.1) except (KeyboardInterrupt, SystemExit): _log(True, '\n') stop()
def _log(condition, message): if condition: sys.stdout.write(message) sys.stdout.flush() def _make_address(address): if address is None or isinstance(address, int): port = address address = ('localhost', port) if isinstance(address, tuple) and len(address) == 2: host ...
The function `serve` starts a server to serve a machine learning model from a file or data buffer, determining the model format automatically. It binds to a specified address, launches a web browser if requested, and returns the server address. The function handles file validation, data type detection, and initializes ...
def serve(file, data, address=None, browse=False, verbosity=1): '''Start serving model from file or data buffer at address and open in web browser. Args: file (string): Model file to serve. Required to detect format. data (bytes): Model data to serve. None will load data from file. addr...
def dog_detector(self, img_path): prediction = self.ResNet50_predict_labels(img_path) return ((prediction <= 268) & (prediction >= 151)) def predict_dog_breed(self, filepath): tensor = path_to_tensor(filepath) feature = self.extract_Resnet50(tensor) dog_breed = np.argmax(self.mod...
This function identifies if an image contains a dog or human, predicts the dog breed using a model, and returns a message specifying the breed if a dog is detected, or a human-like breed if a face is detected, else an error message.
def predict_dog_breed_from_image(self, filename): if self.dog_detector(filename): dog_breed = self.predict_dog_breed(filename) message = 'This dog breed is %s'%dog_breed elif self.face_detector(filename): dog_breed = self.predict_dog_breed(filename) messag...
def get_next_query(): """Get the next query we want to run""" # Connect to the database history_df = get_table_psql('search_history', SEARCH_METADATA) # If the search_history is empty, return a default query, chicken if len(history_df) == 0: return [None, None, 'Chicken', None, 'https://a...
The code queries the Edamam API using parameters from XCOM, processes the response, logs search details to PostgreSQL, saves raw JSON data, converts results to a DataFrame, uploads it to a PostgreSQL table, and exports the data as a CSV file for storage and analysis.
def edamam_request(ti): """Connect to edamam API, run query, and save raw data to postgres DB """ # Initialize Variables dag_path = os.getcwd() host = 'https://api.edamam.com/' recipe_base = 'api/recipes/v2' url = host + recipe_base # Xcom Pulls query = get_next_query() search...
def _authorize(self) -> None: if self._country_code == 'be-nl': self.authorize_telenet() elif self._country_code == 'gb': self.authorize_gb() else: self._authorize_default() def _obtain_mqtt_token_gb(self): _logger.debug("Obtain Virgin GB mqtt token......
The code's main task is to establish a connection to an API by authorizing the user, obtaining an MQTT token (with country-specific handling for "gb"), initializing an MQTT client, registering customer and device information, and connecting to the MQTT broker. This prepares the system for IoT device communication and d...
def connect(self) -> None: _logger.debug("Connect to API") self._authorize() if self._country_code == "gb": self._obtain_mqtt_token_gb() else: self._obtain_mqtt_token() self._mqttClient = LGHorizonMqttClient(self._auth, self._country_settings, self._on_mqt...
def graph_scene(self): self.number_plane = NumberPlane( x_range=[-10, 10, 1], y_range=[-10, 10, 1], background_line_style={ "stroke_color": BLACK, "stroke_width": 1, "stroke_opacity": 0.4 }) self.number_plane...
The code constructs and animates visual comparisons of negative autoregulation vs. simple regulatory systems. It calculates stable protein states using bisection, generates graphs for varying parameters (beta = 1,3), and overlays annotated projections. Key tasks include plotting regulatory dynamics, labeling stable sta...
def construct(self): self.beta_vary = [1,3] #network = self.simple_regulation() #self.play(network.animate.scale(0.5),network.animate.move_to(2*LEFT+2*UP)) self.graph_scene() #self.simple_graph() self.play(Create(self.neg_axes),Create(self.neg_labels), C...
def generate_test_features(headlines, bodies): overlap = gen_or_load_feats(word_overlap_features, headlines, bodies, "fnc_1_baseline/features/overlap.competition.npy") refuting = gen_or_load_feats(refuting_features, headlines, bodies, "fnc_1_baseline/features/refuting.competition.npy") polarity = gen_or_loa...
The code evaluates a model's predictions on a test dataset by generating features, filtering correctly predicted examples (agree/disagree/discuss), modifying their body text while preserving the original stance, and analyzing the number of deletions made during transformation. Results are saved as CSV files with statis...
def main(): # Load test data test_dataset = DataSet(name="competition_test", path="fnc_1_baseline/fnc-1") headlines, bodies, body_ids, y = [],[],[],[] transformed_examples = [] for stance in test_dataset.stances: y.append(LABELS.index(stance['Stance'])) headlines.append(stance['Head...
def check_input_data(x_coord, y_coord, Chain, Sales): # check whether all lists have the same length lists = [x_coord, y_coord, Chain, Sales] if not all(len(l) == len(lists[0]) for l in lists): raise ValueError( "Not all lists that define the shops data have the same length" ) de...
The code's main task is to simulate shopping flow using the hyman_model by processing input coordinates, population data, and sales information. It creates population and shop dataframes, runs the model with parameters like empirical shopping distance and tolerance, then saves the resulting flow data as a pickle file i...
def main(x_coord, y_coord, Chain, Sales): check_input_data(x_coord, y_coord, Chain, Sales) df_population = create_population_df(population_per_cell) df_shops = create_shops_df(df_population, x_coord, y_coord, Chain, Sales) flow = hyman_model( empirical_mean_shopping_distance, tolerance, df_popul...
def read_dictionary(): """ This function reads file "dictionary.txt" stored in FILE and appends words in each line into a Python list """ global dict with open(FILE, 'r') as f: for line in f: word = line.split() word_s = word[0].strip() dict.append(word_s) def rows(): global row1, row2, row3, row4 #c...
The main task of the code is to search for a word in a dictionary by first reading the dictionary data, processing rows, building row structures, and finally executing a word search function. The code orchestrates these steps to locate a target word within the processed data.
def main(): """ TODO: """ read_dictionary() rows() build_rows() find_word()
def make_matrix(self): theta0, theta1, theta2, theta3, r0, r1, r2, r3, alpha0, alpha1, alpha2, alpha3, d0, d1, d2, d3 = symbols('theta0 theta1 theta2 theta3 r0 r1 r2 r3 alpha0 alpha1 alpha2 alpha3 d0 d1 d2 d3') rs = [0,0,3.5,3] alphas = np.deg2rad([-90,-90,-90,0]) ds = [2.5, 0, 0,0] matrix0 = (self.dh_matr...
The code processes two image messages by converting them to OpenCV images, computes forward kinematics matrices, estimates joint angles using control logic, and publishes the estimated joint angles for a robotic arm. It handles image data to drive robotic motion control, with commented-out sections suggesting additiona...
def callback(self, data1, data2): try: self.cv_image1 = self.bridge.imgmsg_to_cv2(data1, "bgr8") self.cv_image2 = self.bridge.imgmsg_to_cv2(data2, "bgr8") except CvBridgeError as e: print(e) if (self.fkmatrix == Matrix([0])): self.fkmatrix,self.fkjacobian, self.symThetas = self.make_matrix() jo...
def wilkinsonMu(A): d = (A[-2, -2] + A[-1, -1])/2 t = np.sqrt(d**2 + A[-1, -2]**2) mu = A[-1, -1] + d - sign(d) * t return mu def doubleShift(A): a = A[-2, -2] b = A[-2, -1] c = A[-1, -2] d = A[-1, -1] trace = a + d det = a*d - b*c eig1 = trace/2 + np.sqrt(trace**2 / 4-det) eig2 = trace/2 - np.sqrt(trace**2...
The code performs QR iteration to compute eigenvalues of a matrix by iteratively transforming it into an upper triangular form. It uses Hessenberg decomposition and applies shifts (Wilkinson, bottom-right, or double-shift) to accelerate convergence. Each iteration involves QR decomposition, updating the matrix, and che...
def qr_iter(A, muType='wilk', tol=1.e-5, maxIter=1000, verbose=False): n,m = A.shape Q = np.empty((n,m)) R = np.empty((n,m)) Ak = sLA.hessenberg(A).astype('cfloat') err = 1 i = 0 doubShiftCounter = 0 mu1 = 0 mu2 = 0 for i in range(maxIter): if muType == 'wilk': mu = wilkinsonMu(Ak) if muType == '...
def vocabulary(self, n=None): n = self.n if n is None else n v = set() for ngram in self.traverse(size=n): v.add("_".join(ngram[:n])) v = sorted(list(v)) return v def traverse(self, node=None, sequence=None, size=None): sequence = sequence if sequence else [] ...
The code trains a language model by calculating n-gram probabilities using Laplace smoothing. It initializes parameters for smoothing and logging, computes adjusted probabilities for each n-gram by adding a smoothing value to counts, and updates their probabilities. If smoothing is enabled, it adjusts probabilities usi...
def train(self, logs=False, smoothing=False): print("Start training {}".format(self)) self.logs = logs self.smoothing = smoothing v = len(self.vocabulary(n=1)) if self.smoothing else 0 a = 1 if self.smoothing else 0 self.error.probability = (a / v) if (smoothing and log...
def warning(msg): """Prints the supplied warning message. :param msg: A short message :type msg: ``String`` """ message('WARNING: %s' % msg) def sendmail(msg): """Sends the MIMETest message to the mailgun account. :param msg: The message to send :type msg: ``MIMEText`` :return: Tru...
The code sends a warning email upon the first probe failure, notifying recipients that a monitored location is at risk due to a non-zero 'count' payload. It uses a template with project, location, threshold, and period variables to inform recipients of potential service suspension after consecutive failures. The email ...
def email_warning(): """Sends an email, driven by the first probe failure. This email delivers a warning that the first probe attempt has failed. Another email will come when the probe fails a second time. """ # Do nothing if no recipients if not RECIPIENTS: warning('Skipping warning em...
def warning(msg): """Prints the supplied warning message. :param msg: A short message :type msg: ``String`` """ message('WARNING: %s' % msg) def sendmail(msg): """Sends the MIMETest message to the mailgun account. :param msg: The message to send :type msg: ``MIMEText`` :return: Tru...
The main task of the code is to send an automated recovery email通知 when a system issue is resolved. It informs recipients that a previous 'AT RISK' status has been resolved to 'SAFE', resets the error count, and schedules the security probe to restart after a specified period. The email includes dynamic project-specifi...
def email_recovery(): """Sends an email, driven a recovery from an initial failure. This email delivers a message saying that the previous warning has now cleared. At this point the error failure count will have been reset. """ # Do nothing if no recipients if not RECIPIENTS: warnin...
def warning(msg): """Prints the supplied warning message. :param msg: A short message :type msg: ``String`` """ message('WARNING: %s' % msg) def sendmail(msg): """Sends the MIMETest message to the mailgun account. :param msg: The message to send :type msg: ``MIMEText`` :return: Tru...
The main task of the code is to send an automated email warning when a security probe failure triggers service suspension. It notifies recipients about prolonged "AT RISK" status, specifies the affected service location, threshold, and monitoring interval, and mandates investigation to resolve the issue or revert to a ...
def email_suspension(): """Sends an email, driven by the final probe failure. This email delivers a warning that the final security probe attempt has failed and the probed service is being shutdown. """ # Do nothing if no recipients if not RECIPIENTS: warning('Skipping suspension email ...
def warning(msg): """Prints the supplied warning message. :param msg: A short message :type msg: ``String`` """ message('WARNING: %s' % msg) def sendmail(msg): """Sends the MIMETest message to the mailgun account. :param msg: The message to send :type msg: ``MIMEText`` :return: Tru...
The function sends an email alert when a service suspension fails, warning that the service may remain active and vulnerable. It checks for recipients, constructs a formatted message with project-specific details, and logs success or failure after attempting to send the email via sendmail.
def email_suspension_failure(): """Sends an email, driven by the failure to suspend the service. This email delivers a warning that the suspension of the probed service failed and there is a possibility that it is still running and vulnerable. """ # Do nothing if no recipients if not RECIPI...
def matchDateRangeLimit(dateStr, start_date=None, end_date=None): if start_date is not None or end_date is not None: date = parser.parse(dateStr) return ((start_date is not None and date < start_date) or (end_date is not None and date > end_date)) == False return True def distr...
This function updates team and member statistics for a sprint based on issue data. It increments committed issues, tracks resolved issues, adds story points to committed/completed metrics, and distributes trophies. It also handles bug fixes, test plans, and new features by updating relevant counters and calling `handle...
def accumulatePrimaryIssueStatForSprint(issue_data, team_stat, member_stat_dict, start_date=None, end_date=None, develop...
def get_average_penalty(self): linear_penalty = 0 exp_penalty = 0 threshold = 5 for student_courses in self.raw_student_data: for i in range(len(student_courses)): for j in range(i+1,len(student_courses)): day1 = self.assignments[student_co...
The code refines a solution using a Kempe chain method to minimize a penalty (conflict measure) in graph coloring. It iterates over epochs, switching colors along a random Kempe chain, and reverts changes if the penalty increases or invalid nodes arise. The penalty type (linear/exponential) is selected via `penalty_idx...
def refine_solution_kempe_chain(self,verbose = 1, epochs=1000, penalty_idx = 1): '''penalty_idx = 0 for linear, 1 for exponential''' for epoch in range(epochs): penalty_before = self.get_average_penalty()[penalty_idx] kempe_chain = self._get_random_kempe_tree() ...
def get_weather_forecast(self): print("Getting weather forecast") #Update weather forecast end_point = "https://api.openweathermap.org/data/2.5/onecall" params = { "lat": 51.454768, "lon": -2.596210, "appid": "", "exclude": "current,minutel...
The code initializes a weather display, attempts to fetch weather data using `get_weather_forecast()`, handles errors by populating placeholder data with missing icons, and updates the UI. It schedules a periodic display update every 1000ms using `after()` to ensure continuous weather information presentation.
def generate_weather_display(self): #Initialise weather display self.weather_view = 1 self.multi_view_start = 0 try: print("Trying to get weather data") self.get_weather_forecast() print(f"Weather data") except Exception as e: pri...
def get_date(): now = dt.datetime.now() todays_date = [(now.strftime('%d')), (now.strftime('%m'))] return todays_date def read_birthday_data(): birthday_data = pd.read_csv("birthdays.csv") return birthday_data def check_birthdays(birthday_data, todays_date): email_list = [] for row in birthd...
The code runs an infinite loop that checks for birthdays daily, generates emails for individuals whose birthdays match the current date, and pauses for 24 hours before repeating. It retrieves the current date, reads birthday data, identifies matching entries, creates emails for them, and sleeps for a day to avoid redun...
def start_loop(): while True: todays_date = get_date() birthday_data = read_birthday_data() email_list = check_birthdays(birthday_data, todays_date) for item in email_list: Generate_Email(item) print("Sleeping...") time.sleep(60*60*24)
def create_bar_code(sn): """Create a barcode from a number""" return barcode.get("code128", serial_num_2_barcode(sn), writer=ImageWriter()) def serial_num_2_barcode(sn): return pad_serial_num(sn) def get_bc_filename(sn): """generate a name for a barcode file""" suffix = "BC" return sn + suffix d...
This function generates and prints QR or barcode labels based on input parameters. It creates a barcode or QR code image, confirms printing with the user, executes the print command multiple times, then deletes the generated image file.
def print_it(serial, count, label_type): """ A serial number, how many to print and QR or Bar code. Then loop through an os.system call to print. """ print(serial, count, label_type) fn = None if label_type == "Bar Code": code = create_bar_code(serial_num_2_barcode(serial)...
def unconfigure_ip_address(netbox_interface_object, ip_address, address_family): """ Primary function to remove an address from an interface. Depending on the address family, call the appropriate function to unconfigure the v4 or v6 address. :param netbox_interface_object: pynetbox interface object...
This function handles IP address configuration changes via webhooks by determining if an IP address is newly created, updated, or deleted. It configures, unconfigures, or updates the IP on non-management network interfaces based on the event type, using NetBox API data to identify affected interfaces and perform necess...
def manage_interface_ip_address(): """ Function for the Webhook listener at the IPAM configuration path. When an IPAM webhook is received, obtain the IP address and address family from the payload data. If there is an assigned interface for the IP address, determine if it's a new address, an existi...
def init_imap_folder_structure(config, imap): for folder in [config.folders.ACCEPTED_FOLDER, config.folders.PUBLISHED_FOLDER]: logger.debug('Checking if folder "%s" exists.', folder) if not imap.folder_exists(folder): logger.info('Creating IMAP folder "%s"', folder) imap.crea...
This code connects to an IMAP server using provided credentials, initializes folder structure, selects an accepted folder, and either enters an idle mode for real-time updates or a polling mode to check for new emails at specified intervals, depending on the 'mode' parameter.
def run(config, mode, poll_interval): logger.debug('Connecting to IMAP account at %s', config.imap.IMAP_HOST) with IMAPClient(config.imap.IMAP_HOST) as imap: logger.debug('Login to IMAP with user %s', config.imap.IMAP_USER) imap.login(config.imap.IMAP_USER, config.imap.IMAP_PWD) init_ima...
def createDataFrame(fileData): dataFrame = pd.read_csv(fileData, sep= " " , header= None, names= ["Type", "Stability","NumBodies" , "NumLines" , "NumCircles"]) return dataFrame def unstableConfigurations( dataFrame ): df = dataFrame[dataFrame["Stability"] == "unstable"] return [df, df.shape[0]] def Regi...
The function processes a dataset to identify and analyze unstable configurations, calculates their proportion relative to the total data size, and registers statistical information based on the number of bodies, lines, and circles in the dataset.
def generateSeparateData(): #os.chdir('./') #print(os.listdir()) fileData = '../data/linear_no_23' originalDataFrame = createDataFrame(fileData) totalSize = originalDataFrame.shape[0] print(originalDataFrame.tail()) print("total data = ", totalSize) dfUnstable ,numberUnstableConfigur...
def readData(nameFile): position = np.array([]) file = open('../data/'+nameFile) lines = file.readlines() numOfBodies = len(lines[:-1]) position = np.zeros((numOfBodies,2), dtype=object) index = 0 for line in lines[:-1]: x1,x2 = line.split() position[index] = np.array([float(...
This code integrates the equations of motion for a multi-body gravitational system using a Hamiltonian approach. It reads initial conditions from a file, computes initial momenta, and numerically integrates the system over time using a high-precision solver. The process records positions, momenta, and energy values at ...
def IntegrationProcess(file): global masses x, masses , numOfBodies= readData(file) #print(x) setNumOfLines(file) #print('number of bodies = ', numOfBodies, 'and number of lines = ', numLines) y = setInitialMomenta(x,masses) initialCondition = np.append(x,y,0).reshape(4*numOfBodies...
def _system_is_idle_status(self): if not self._idle_start_time: self._idle_start_time = time() self._update_query_size(0) sleep(self._idle_sleep_time) def _update_query_size(self, current_size: Optional[int] = None): if not current_size: current_size = self.inpu...
The code processes video frames from an input queue, managing system idle states, tracking k-values over time, and outputting processed frames with boundary boxes. It continuously checks if processing should continue, updates query size, adjusts k-values dynamically, and logs idle durations. Each frame is retrieved, pr...
def start_processing(self, is_running_getter: IsRunningGetter): execution_start_time = time() while True: if not is_running_getter(): break if self.input_queue.is_empty(): self._system_is_idle_status() continue # syst...
def _set_attributes(root): global g_attributes_func global g_attributes for key in g_attributes: g_attributes_func[key](root, g_attributes[key]) def _init_ttk_styles(): style = ttk.Style() style.configure('Content.TFrame', background=g_attributes['background']) style.configure('Label.TLa...
The main task of the code is to initialize a GUI application's views by setting attributes, configuring ttk styles, creating menus, and setting up the main view using the provided root widget. This function orchestrates the setup of essential UI components for a Tkinter-based application.
def _init_views(root): _set_attributes(root) _init_ttk_styles() _init_menus(root) _init_main_view(root) pass
def forward_pass(X, parameters, activation, num_hidden): A = {} # To prevent broadcasting when a single input vector is given if X.ndim == 1: X = X[:, np.newaxis] # Initializing the pre-activation to inputs H = {"h0":X} for l in range(1, num_hidden + 2): Wl = parameters["W" ...
The code evaluates a neural network's performance on training and validation datasets by computing accuracy, error rates, and loss. It performs forward passes to generate predictions, calculates accuracy and error (100 - accuracy) for both sets, and computes cross-entropy or squared loss based on the specified loss fun...
def measure_performance(X, Y, X_val, Y_val, params, activation_func, num_hidden, loss): # Performing forward pass on training set Yhat, _, _ = forward_pass(X, params, activation_func, num_hidden) train_acc = find_accuracy(Yhat, Y) train_err = 100 - train_acc if loss == "ce": train_loss = (cr...
def createnetwork(num_hidden, activation_func, sizes, inputsize = 784, outputsize = 10): # Appending the first element(number of inputs=784) and the last element(number of of outputs=10) to sizes array. # Sizes is a list representing the number of units in each layer. sizes = [inputsize] + sizes sizes =...
(The main task of the code is to implement the Adam optimizer for training a neural network on given data, using specified activation and loss functions. It initializes network parameters, performs forward and backward passes, updates weights via Adam's momentum and variance correction, tracks training/validation perfo...
def adam(X, Y, X_val, Y_val, activation_func, loss_func, eta, num_epochs, num_hidden, sizes, batch_size, path_save_dir, inputsize = 784, outputsize = 10, beta1 = 0.9, beta2 = 0.999, eps = 1e-8, anneal = True, pretrain = False, state = 0): print("Adam optimizer is being used.") step_data = {} epoch_data = [...
def createnetwork(num_hidden, activation_func, sizes, inputsize = 784, outputsize = 10): # Appending the first element(number of inputs=784) and the last element(number of of outputs=10) to sizes array. # Sizes is a list representing the number of units in each layer. sizes = [inputsize] + sizes sizes =...
This function implements momentum gradient descent for training a neural network. It initializes or loads network parameters, computes gradients via backpropagation, applies momentum updates to parameters, and performs learning rate annealing if validation loss stagnates. The training tracks performance metrics per epo...
def mgd(X, Y, X_val, Y_val, activation_func, loss_func, eta, gamma, num_epochs, num_hidden, sizes, batch_size, path_save_dir, inputsize = 784, outputsize = 10, anneal = True, pretrain = False, state = 0): print("momentum gradient descent") step_data = {} epoch_data = [] if pretrain == False: p...
def createnetwork(num_hidden, activation_func, sizes, inputsize = 784, outputsize = 10): # Appending the first element(number of inputs=784) and the last element(number of of outputs=10) to sizes array. # Sizes is a list representing the number of units in each layer. sizes = [inputsize] + sizes sizes =...
The code implements mini-batch stochastic gradient descent (SGD) for training a neural network, with options for pretraining, learning rate annealing, and performance tracking. It initializes or loads network parameters, performs forward/backward passes, accumulates gradients over mini-batches, updates weights, and eva...
def sgd(X, Y, X_val, Y_val, activation_func, loss_func, eta, num_epochs, num_hidden, sizes, batch_size, path_save_dir, inputsize = 784, outputsize = 10, anneal = True, pretrain = False, state = 0): print("Gradient decent with minibatch is used.") step_data = {} epoch_data = [] if pretrain == False...
def createnetwork(num_hidden, activation_func, sizes, inputsize = 784, outputsize = 10): # Appending the first element(number of inputs=784) and the last element(number of of outputs=10) to sizes array. # Sizes is a list representing the number of units in each layer. sizes = [inputsize] + sizes sizes =...
This function implements Nesterov Accelerated Gradient (NAG) optimization for training a neural network. It processes training data in batches, computes gradients via forward/backward passes, updates parameters using momentum with gamma decay, and optionally applies learning rate annealing if validation loss stagnates....
def nag(X, Y, X_val, Y_val, activation_func, loss_func, eta, gamma, num_epochs, num_hidden, sizes, batch_size, path_save_dir, inputsize = 784, outputsize = 10, anneal = True, pretrain = False, state = 0): print("NAG") step_data = {} epoch_data = [] if pretrain == False: params = createnetwork(...
def init_data(path_train, path_val, path_test): data, X, y = read_data(path_train) Y = (convert_to_onehot(y, 10)).T X = (X.T/255) pca = PCA(n_components=50) pca.fit(X) X = pca.transform(X) X = X.T print(np.shape(X), np.shape(y), np.shape(data)) data, X_val, y_val = read_data(pa...
The function `run_model` trains a neural network using specified hyperparameters (learning rate, optimizer, network structure) and generates test predictions. It loads training/validation/test data (or just test data in testing mode), trains the model with chosen optimization algorithms (SGD, momentum, Adam, NAG), save...
def run_model(eta, gamma, num_hidden, sizes, activation_func, loss_func, optim, batch_size, num_epochs, path_save_dir, path_expt_dir, path_train, path_val, path_test, anneal, state): # Reading data if testing == False: X, Y, X_val, Y_val, X_test, indices = init_data(path_train, path_val, path_test) elif tes...
def nameerror(name,FUNCTION): global model_name if model_name == name: return else: print("Error 1: Model ",name, " NOT Found in ",FUNCTION) exit() def spim(word, model,words_list1,words_list2): nameerror(model,"chatbot.model_run") closest_index = -1 closest_distance = ...
The function `model_load` dispatches input processing based on the `modeltype` parameter by calling specific model-handling functions (e.g., `spim`, `spimx`, `rasv`, `codewriter`). It uses global variables `words_list1`, `words_list2`, and `model_name`, converts input to lowercase, and delegates tasks to corresponding ...
def model_load(modeltype,input, model): global words_list1 global words_list2 global model_name input = input.lower() nameerror(model,"chatbot.model_load()") if modeltype == "spim": return spim(input,model,words_list1,words_list2) elif modeltype == "spimx": return spimx(input...
def get_best_guess(self): """ Gets the ideal guess(es) based on letter frequency of remaining words. Returns- ideal_guesses: a list of ideal guesses. """ most_common_letters = self.most_common_letters() # Get most common letters copy_list = self.copy() ...
The main task of the code is to handle a single turn in a Wordle game by obtaining the player's guess, validating it against letter status feedback (correct position, wrong position, wrong letter), and updating the game state if valid. It ensures the guess meets constraints, checks for a solved game, and uses best-gues...
def play_turn(self): """ Plays a full turn of Wordle. Requires the user to input the guess and status of each letter in correct order. """ player_guess = 'NONE' right_letter_right_position = 'NONE' right_letter_wrong_position = 'NONE' wrong_letter = 'N...
def continents_extraction(self, file_path=continents_file_name): data = pd.read_csv(file_path, delimiter=',') data = data.replace({np.nan: None}) data = data.to_numpy() columns = get_columns_without_id(self.connection, disasters_stage_db, country_table) self.write_data_to_databas...
The code extracts geographical data (continents, earthquakes, volcanoes, tsunamis) and their effects (damage, people, houses) from specified files into tables, initializing disaster impact analysis.
def initial_extraction(self): self.continents_extraction() self.earthquakes_extraction() self.volcanos_extraction() self.tsunami_extraction_initial() self.effect_extraction(damage_description_file_name, damage_description_table) self.effect_extraction(people_description_f...
def connect_server(): """ Create Database if it doesn't exist :return: engine """ # gives default value if the credential is absent db_user = db_parameter.get('DATABASE_USER', 'root') db_password = db_parameter.get('DATABASE_PASSWORD', 'pass') db_port = db_parameter.get('DATABASE_PORT', ...
The function updates a MySQL database by creating it if necessary, then inserting job and company data from provided lists while handling duplicates. It uses SQLAlchemy to define tables, inserts companies with industries, and adds jobs with conditions and job types, reporting new entries and duplicates.
def update_mysql_db(job_list, company_list): """ Create Database if it doesn't exist and update the database with the information from job_list and company_list :param job_list: list of dictionaries with job attributes :param company_list: list of dictionaries with company attributes :return: ""...
def _load_data(self): """Load instrumental pols and uvdist/time/freq data, converting to MHz, s, and mJy.""" # Import instrumental polarisations and time/frequency/uvdist arrays with h5py.File(self.ds_path, "r") as f: self._validate(f) # Read uvdist, time, frequency, a...
This code initializes an object by loading data, determining scan intervals, stacking scans, generating Stokes parameters, and setting time/frequency ranges and resolutions. It configures time labels, processes data dimensions, and calculates temporal and spectral resolutions for subsequent analysis.
def __post_init__(self): self._timelabel = "Phase" if self.fold else f"Time ({self.tunit})" self._load_data() self.avg_scan_dt, scan_start_idx, scan_end_idx = self._get_scan_intervals() self._stack_cal_scans(scan_start_idx, scan_end_idx) self._make_stokes() self.tmin =...
def ecb(self, stringBlocks, keyBlock, encrypt): resultBlocks = [] for block in stringBlocks: resultBlocks.append(self.feistel(block, keyBlock, encrypt)) return resultBlocks def cbc(self, stringBlocks, keyBlock, encrypt): key = Helper.convertBinary64ToString([keyBlock...
The code's main task is to execute encryption or decryption using specified modes (ECB, CBC, or Counter) based on the 'mode' parameter. It processes data with the provided initial value, key, and encryption flag, then stores the result in 'self.result' for further use.
def execute(self, mode, encrypt=True): if mode == "ecb": result = self.ecb(self.initial, self.key, encrypt) elif mode == "cbc": result = self.cbc(self.initial, self.key, encrypt) elif mode == "counter": result = self.counter(self.initial, self.key, encrypt) ...
def dN( tN: float, N: NDArray[np.float32], a: NDArray[np.float32], R: NDArray[np.float32], d: float = 6e-5, ) -> NDArray[np.float32]: """Rate of change of population growth. Args: tN: time lam: species' growth rate N: current population a: internal energy (ATP) concentra...
The function `forward_euler` numerically solves three coupled ordinary differential equations (ODEs) using the forward Euler method. It approximates the solutions for population growth (`u_N`), ribosome fraction (`u_r`), and ATP production (`u_a`) over time `t` from 0 to `T` with `N` steps. The method iteratively updat...
def forward_euler( dN: Callable[[float, float, float, float], float], dr: Callable[[float, float, float], float], da: Callable[[float, float, float], float], u0: float, T: float, N: int, ) -> tuple[ NDArray[np.float32], NDArray[np.float32], NDArray[np.float32], NDArray[np.float32] ]: """...
def insert_elements(set_size): elm_count = 0 while(elm_count < set_size): print("Enter element no. ", elm_count+1, end = " ") elm = input() set_a.append(elm) elm_count+=1 def fill_size(): for i in range(0, len(set_a)): inds_p.append(i) def determine_elements_per_chunk...
The main task of the code is to partition a set of elements into chunks based on user-defined size, measure the execution time of this partitioning process, and output the resulting partitions. It begins by taking input for the total number of elements, processes them through functions to determine chunk distributions,...
def main(): set_size = input("Enter total number of elements: ") insert_elements(int(set_size)) start = time.time() fill_size() for i in inds_p: determine_elements_per_chunk(0, i, i) print_partitions() end = time.time() print(end - start)
def food_menu(): print("\t WELCOME THIS IS OUR FOOD MENU") print("\t Choose from the following code") for i in range(len(menu)): print("["+str(i+1)+"]",menu[i], end = "...................................") print(price[i]) def user_response_state(response_type_initial = [0], typ...
The code implements a food ordering system where users select items and quantities, add them to a cart, confirm the order, calculate total cost, and process payment. It uses loops for input validation, updates the cart, and ensures confirmation before finalizing the transaction.
def main_menu(): confirmation_key = False food_order = [0,0,0,0,0,0,0] total_cost = 0 transaction_state = 0 while not confirmation_key: os.system("cls") confirmation_key = False food_type = [0] food_type_state = 0 food_quantity = [0] food_quantity_stat...
def openSession(session): print("Opening Session ", session) tp.send(bytearray([0x10, session])) tp.recv() def VSEC_level3_unlock(): seed = getSeed() SendKey() def TesterPresent(): tp.send(bytearray([0x3E])) #tp.send(bytearray([0x3E, 0x80])) # Silent #tp.send(bytearray([0x3E, 0x00])) # N...
The main task of the code is to initialize a communication session with a vehicle's ECU, perform security access by unlocking VSEC level 3 and level 1, and send TesterPresent commands to establish or maintain communication, likely for diagnostic or programming purposes.
def main(): openSession(0x03) VSEC_level3_unlock() openSession(0x02) TesterPresent() VSEC_level1_unlock() TesterPresent()
def equal(self): equal = self.prob.split('=') z =(equal[0]) if self.is_number(z) == True: return z else: try: z= (equal[1]) return z except: return '' def addd(self): add = self.eq[0].split('+') ...
This code evaluates a mathematical expression by concatenating results from multiple methods (equal(), addd(), minus(), divide(), multiply()) into a string. It constructs an equation using self.eq[1] and parts from evall_str(), evaluates it with Python's eval(), and prints the result as 'x = [value]'.
def evall(self): y = "" + self.equal() + self.addd()+self.minus()+self.divide() +self.multiply() + "" solved = '('+self.eq[1] + self.evall_str()[0] + self.evall_str()[1] + self.evall_str()[2] + self.evall_str()[3] o = eval(solved) print('x = '+str(o))
def multiply(self): mult = self.eq[0].split('*') z =mult[0] return z def divide(self): divides = self.eq[0].split('/') z = divides[0] if self.is_number(z) == True: return z else: try: z= (divides[1]) return z...
The code parses a mathematical equation by splitting it into parts, processes multiplication, division, addition, and subtraction operations, checks equality, and evaluates the expression for validation or computation.
def __init__(self , equation): self.prob=equation self.eq = self.prob.split('=') self.multiply() self.divide() self.addd() self.minus() self.equal() self.evall_str() self.evall()
def romanbound(a,b, m,n): return min(romanbound1(a,b, m,n), romanbound1(b,a, n,m)) def packlimit(a,b, m): """Return the "packing limit" for n given a,b and m.""" if (t := packable_simplices(a,b, m)) != None: exact = (b-1)*comb(m,a) == t*(a+1) else: t = 0 exact = True return (...
The function computes lower and upper bounds for Zarankiewicz's problem (maximum edges in a bipartite graph without a K_{a,b} subgraph) using a combination of theoretical bounds (e.g., Roman's bound) and empirical data from files. It adjusts parameters for symmetry, checks precomputed bounds, and merges them to return ...
def zbounds(a,b, m,n): """Return bounds for Zarankiewicz's function at the given arguments.""" if a > m or b > n: return [m*n, m*n] if m-a > n-b: return zbounds(b,a, n,m) rbound = romanbound(a,b, m,n) lbs = [0] if packlimit(a,b, m) <= n: lbs.append(rbound) # Roman's bound...
def __command_up_key(self): with self.write_lock: if self.history_tail_index > 0: self.history_tail_index -= 1 self.update_input_buffer(self.history[self.history_tail_index]) def __command_down_key(self): with self.write_lock: if len(self.history) ...
This code handles keyboard stroke events by mapping specific key inputs (UP, DOWN, LEFT, RIGHT, DELETE) to corresponding command methods, using a read lock for thread safety. Unrecognized keys are logged with their UTF-8 encoded representation.
def handle_stroke(self, char): with self.buffer_lock.for_read(): if char == key.UP: # up self.__command_up_key() elif char == key.DOWN: # bottom self.__command_down_key() elif char == key.LEFT: # left self.__command_left_key(...
def __write_input(self, append=''): with self.write_lock: self.__clear_input() with self.buffer_lock.for_read(): self.last_line = self.label_colored + self.read_buffer + append sys.stdout.write(self.last_line) self.__move_cursor(self.last_l...
This function processes input characters in a thread, handling special keys (delete, interrupt), updating a buffer and cursor position, and managing input interruption. It reads characters, modifies the buffer for deletions, handles line feeds, and clears input on interruptions, while skipping control characters and ha...
def thread_read(self): self.__write_input() try: while True: try: char = readkey() except KeyboardInterrupt: with self.buffer_lock.for_read(): self.read_interrupted_buffer = self.read_buffer ...
def id(n): arr = np.array([[0] * n for _ in range(n)]) for i in range(n): arr[i][i] = 1 return arr def t_adjoint(t): r = t[0:3, 0:3] p = t[0:3, 3] p_m = lp_cross(p) bot_left = np.dot(p_m, r) top_right = np.array([[0] * 3 for _ in range(3)]) top = np.concatenate((r, top_right)...
The function `calc_body_j` computes the body Jacobian matrix for a robotic chain using the product of exponentials formulation. It processes joint parameters in reverse order, applying adjoint transformations and SE(3) exponential maps to calculate Jacobian entries. Each iteration updates the transformation matrix and ...
def calc_body_j(thetas, bs): curr_t = id(4) jacobian_tp = [] for b, theta in zip(reversed(bs), reversed(thetas)): curr_transform = t_adjoint(curr_t) jacobian_tp.append(np.dot(curr_transform, b)) curr_t = np.dot(curr_t, se3_exp(b, -1 * theta)) return trap_arr(list(reversed(jacob...
def id(n): arr = np.array([[0] * n for _ in range(n)]) for i in range(n): arr[i][i] = 1 return arr def t_adjoint(t): r = t[0:3, 0:3] p = t[0:3, 3] p_m = lp_cross(p) bot_left = np.dot(p_m, r) top_right = np.array([[0] * 3 for _ in range(3)]) top = np.concatenate((r, top_right)...
The code computes the space Jacobian matrix for a kinematic chain using screw theory. It iterates through joint axes (ss) and joint variables (thetas), applying the adjoint transformation of the current spatial transform to each joint's screw axis, then updating the transform using the exponential map. The resulting Ja...
def calc_space_j(thetas, ss): curr_t = id(4) jacobian_tp = [] for b, theta in zip(ss, thetas): curr_transform = t_adjoint(curr_t) jacobian_tp.append(np.dot(curr_transform, b)) curr_t = np.dot(curr_t, se3_exp(b, theta)) return trap_arr(jacobian_tp)
def update_train_params(self): self.batch_size = self.batch_sizes[self.restart_idx] self.learning_rate = self.learning_rates[self.restart_idx] self.beta1_decay = self.beta1_decays[self.restart_idx] self.early_stopping_steps = self.patiences[self.restart_idx] def init_logging(self, log_di...
This code initializes a machine learning trainer with configurable hyperparameters, including batch sizes, learning rates, optimizer settings, and validation parameters. It sets up TensorFlow graph/session, logging, checkpoints, and handles multiple training restarts with patience-based early stopping. The trainer supp...
def __init__( self, reader=None, batch_sizes=[128], num_training_steps=20000, learning_rates=[.01], beta1_decays=[.99], optimizer='adam', grad_clip=5, regularization_constant=0.0, keep_prob=1.0, patiences=[3000], warm_start_...
def chartInput(): while True: try: print("\nChart Types") print("------------") print("1. Bar") print("2. Line\n") chartType = int(input("Please Enter a Chart Type (1, 2): ")) if isChartCorrect(chartType): print("Enter a...
The function collects user inputs for stock data visualization parameters—ticker symbol, chart type, time series, dates, and intraday interval—and returns them as a tuple for further processing.
def userPrompt(): tickerSymbol = input("Please Enter a Stock Ticker Symbol: ").upper() chartType = chartInput() chartTimeSeries = timeSeriesInput() if chartTimeSeries == 1: intradayInterval = intradayIntervalInput() else: intradayInterval = "" startDate = dateInputStart() ...
def isConverge(M, L, S, M_F, threshold): """Decide whether to stop the while loop in main algorithm Args: M (numpy.narray): M matrix L (numpy.narray): L matrix S (numpy.narray): S matrix M_F (float): the 2-norm of origin matrix M threshold (float): the threshold for deci...
This function performs Robust Principal Component Analysis (RPCA) on images from a specified folder, decomposing each image matrix into low-rank (L) and sparse (S) components. It uses parameters miu and lam for optimization, with defaults calculated if specified. The algorithm iterates until convergence, then saves L, ...
def getRPCACompressedImage( miu, lam, folder_name="0000045", default_miu=True, default_lam=True ): """The main algorithm of RPCA Args: miu (float): miu parameter in algorithm lam (float): lambda parameter in algorithm folder_name (str, optional): The choosen folder.Defaults to "0000...
def build_edges(): global edges edges = {} for n1, (_, adjacents, _, _) in enumerate(graph): for n2 in adjacents: eid = edge_id(n1, n2) if eid not in edges: edges[eid] = [(n1, n2), grey] def draw_graph(): global graph, screen, edges screen.fill((0, 0...
This code implements a Breadth-First Search (BFS) algorithm visualization using Pygame. It initializes a graph, draws nodes/edges, and animates BFS traversal by updating node colors (grey → white → yellow → blue for visited nodes, red for discovered nodes) while highlighting traversal paths. The BFS processes nodes fro...
def run(): global screen, edges, clock for element in graph: element.extend([grey, black]) build_edges() pygame.init() clock = pygame.time.Clock() screen = pygame.display.set_mode((display_width, display_height)) draw_graph() update() pygame.time.delay(2000) # BFS algo...
def TPS_generate(source,target): P = np.append(source,np.ones([source.shape[0],1]),axis=1) P_Trans = P.T Z = np.zeros([3,3]) K = np.zeros([source.shape[0],source.shape[0]]) for p in range(source.shape[0]): K[p] = [U(np.linalg.norm((-source[p]+source[i]),ord =2)+sys.float_info.epsilon) for i ...
The function performs image swapping using TPS (Thin Plate Spline) warping to align source image points with target points, generates a mask for blending, warps the source image, and applies Poisson blending via OpenCV's seamlessClone to integrate the warped image into the target, returning the blended result.
def swap(img_source,img_target,points1,points2): weights_x,K = TPS_generate(points1,points2[:,0]) weights_y,K = TPS_generate(points1,points2[:,1]) # plt.imshow(K) w, h = img_target.shape[:2] # ## Mask for blending mask = mask_from_points((w, h), points2) # plt.imshow(mask) # mask.shape ...
def getQueryResult(query, fetchOne=False, fetchTop=0): con = getConnection() cur = con.cursor() cur.execute(query) if fetchOne: return cur.fetchone() if fetchTop: return cur.fetchmany(fetchTop) else: return cur.fetchall() def getPersonType(p_id): query = "SELECT P_TYPE FROM {}.PERSON WHERE P_ID = {}".form...
This function retrieves student and interviewer information for a given event by querying RSVP records, categorizing individuals by type (student or interviewer), and returning their interests in separate dictionaries.
def getPeopleFromEvent(event_id): query = 'SELECT P_ID FROM {0}.RSVP WHERE E_ID = {1}'.format(instance_name, event_id) result = getQueryResult(query) print ("HERE") students = dict() interviewers = dict() for item in result: # print (item) p_type = getPersonType(item[0]) if p_type == 1: st...
def Loss(self, points, features0, features1, Yobs): start=time.time() tau, Xp = self.network.out(points, features0, features1) dtau = self.gradient(tau, Xp) end=time.time() D = Xp[:,self.dim:]-Xp[:,:self.dim] T0 = torch.einsum('ij,ij->i',...
This code trains a neural network for a specific task, using a weighted random sampler and adaptive learning rate adjustments. It initializes the network, optimizer, and dataset, then iteratively trains the model over epochs. The training includes loss computation, gradient updates, and state restoration if the loss ra...
def train(self): self.network = NN(self.Params['Device'],self.dim,self.Params['DataPath']) self.network.apply(self.network.init_weights) self.network.to(self.Params['Device']) self.optimizer = torch.optim.AdamW( self.network.parameters(), lr=self.Params['Training'][...
def _open_dict(self): self.__write_indent() self._file.write('{') self.__indent_level += 1 self.__is_collection_empty.append(True) self._open_containers.append('dict') self._fsync() def _write_dict_item(self, key, value): # Write key. self._write_dict_key...
This method initializes a JSON structure by writing boilerplate data, including the results version, test name, options (excluding 'env' and 'name'), and environment variables. It ensures no None values are included, then opens a 'tests' dictionary for subsequent test entries.
def _initialize(self, metadata): """ Write boilerplate json code This writes all of the json except the actual tests. Arguments: options -- any values to be put in the options dictionary, must be a dict-like object name -- the name of the test env -- ...
def update_scoreboard(self): # Update the combined score label for both players self.score_label.config(text=f'X: {self.scores["X"]} O: {self.scores["O"]}') def reset_game(self): for row in self.buttons: for button in row: button.configure(text='') self.game ...
This function determines the game outcome (win/draw), updates the winner's score, displays the result, and prompts the user to play again or return to the menu.
def display_winner(self, winner): if winner == 'draw': result = 'The game ended in a draw!' else: result = f'Player {winner} wins!' self.scores[winner] += 1 # Update the score for the winning player # Update the scores on the scoreboard self.update_s...
def get_file(file): with open(file) as read_file: data = json.load(read_file) return data def get_sources(data): source = {} count = 0 for item in data['sources']: source[item['source']] = item['rssurl'] count += 1 return source, count def get_feed(sources): feed ...
The main task of the code is to identify new articles from a source feed, compare them with existing local data, and insert the newly detected articles into a database. It retrieves feed data, extracts article details, determines which articles are not yet stored locally, and writes them to the database using `put_item...
def add_new_articles(): file = get_file(sourceFile) values, threads = get_sources(file) feed = get_feed(values) keys, newer, update = extract_articles(feed) have = compare(keys) should_update = list(newer - have) print("Compare local and exisiting") print("%s articles that need to be up...
def countNucFrequency(self): return dict(collections.Counter(self.seq)) def calculate_gc_content(self): """Calculate the GC content of a DNA sequence""" return round((self.seq.count('C') + self.seq.count('G')) / len(self.seq) * 100) def show_rna_transcription(self): """Show RNA transcrip...
The code defines a method `show_seq_info` that returns a formatted string containing detailed information about a biological sequence. Depending on whether the sequence type is "DNA" or not, it displays attributes like label, sequence, type, length, validity, nucleotide frequency, GC content, transcription, reverse com...
def show_seq_info(self): if self.seq_type == "DNA": return f"[Label]: {self.label}\n[Sequence]: {self.seq}\n[Type]: {self.seq_type}\n[Length]: {len(self.seq)}\n[Is Valid]: {self.is_valid}\n[Nucleotide Frequency]: {self.countNucFrequency()}\n[GC Content]: {self.calculate_gc_content()}%\n[Transcriptio...
def _conv2d_impl(self, input_layer, num_channels_in, filters, kernel_size, strides, padding, kernel_initializer): if self.use_tf_layers: return conv_layers.conv2d(input_layer, filters, kernel_size, strides, padding, self.channel_pos, ...
This function constructs a 2D convolutional layer with customizable parameters like kernel size, stride, padding mode (including ResNet-specific handling), activation function, and batch normalization. It initializes weights, applies padding, performs convolution, adds biases (if not normalized), applies activation, an...
def conv(self, num_out_channels, k_height, k_width, d_height=1, d_width=1, mode='SAME', input_layer=None, num_channels_in=None, use_batch_norm=None, stddev=None, activation='relu', bias=0....
def _separable_conv2d_impl(self, input_layer, num_channels_in, num_channels_out, channel_multiplier, kernel_size, strides, padding, kernel_initializer): if self.use_tf_layers: # TODo: add tf layers for separable_conv2d print('error') assert(False) # return conv_layers.conv...
This function constructs a separable convolutional layer with customizable parameters (e.g., kernel size, strides, padding modes) for deep neural networks. It supports ResNet-style padding, batch normalization, and activation functions (ReLU, ReLU6, etc.), updating the model's top layer and output size. The implementat...
def separable_conv(self, num_out_channels, channel_multiplier, k_height, k_width, d_height=1, d_width=1, mode='SAME', input_layer=None, num_channels_in=None, use_batch_norm=None, stddev=None, ...
def conv(self, num_out_channels, k_height, k_width, d_height=1, d_width=1, mode='SAME', input_layer=None, num_channels_in=None, use_batch_norm=None, stddev=None, activation='relu', bias=0....
The main task of the code is to construct an inception module by processing multiple parallel columns of neural network layers (convolutional, pooling, or shared). It dynamically creates unique layer names, applies specified operations to each column, stores intermediate outputs, and concatenates the final outputs of a...
def inception_module(self, name, cols, input_layer=None, in_size=None): if input_layer is None: input_layer = self.top_layer if in_size is None: in_size = self.top_size name += str(self.counts[name]) self.counts[name] += 1 with tf.variable_scope(name): col_layers = [] col_lay...
def open_url(self, url): """Open the specified url and wait until page source is fully loaded.""" self.get('%s%s' % (self.live_server_url, url)) self._wait_for_page_source() def type_in(self, selector, text): elem = self.find(selector) elem.clear() elem.send_keys(text) de...
The code automates user login by navigating to the login page, inputting the provided username and password into the respective form fields, and submitting the login form. This function is likely part of a test script to simulate authentication in a web application, such as a Django project, using browser automation to...
def authorize(self, username, password): self.open_url(reverse('login')) self.type_in("#id_username", username) self.type_in("#id_password", password) self.click("#login-form [type='submit']")
def process_audio_files(directory): features = [] labels = [] for filename in os.listdir(directory): if filename.endswith('.wav'): audio_path = os.path.join(directory, filename) feature = extract_spectrogram_features(audio_path) features.append(feature) ...
The main task of the code is to train a neural network model on audio data from multiple files. It processes audio features, normalizes and pads/truncates spectrograms to uniform length, splits data into training/test sets, converts labels to categorical format, defines and compiles a model, trains it using generators,...
def train_model_on_multiple_files(directory, batch_size=32): features, labels = process_audio_files(directory) features_train, features_test, labels_train, labels_test = train_test_split(features, labels, test_size=0.2, random_state=42) # Get the length of the shortest time sequence in your data min_le...
def __writeRegister(self, register, value): self.spi.xfer([register | 0x80, value]) def SetLoRaFrequency(self, Frequency): """Sets the frequency in MHz.""" self.__setMode(RF98_MODE_STANDBY) self.__setMode(RF98_MODE_SLEEP) self.__writeRegister(REG_OPMODE, 0x80); #self.__setMode(RF98_MODE_SLEEP) self.__setM...
This code initializes a LoRa radio module for the PITS Zero board, configuring parameters like channel, frequency, and mode. It sets up hardware (DIO0 pin, SPI), configures LoRa settings (frequency, power), and prepares non-blocking transmission with callback support. The class handles image/data packet tracking and en...
def __init__(self, Channel=0, Frequency=434.250, Mode=1, DIO0=0): """ This library provides access to one LoRa (Long Range Radio) module on the PITS Zero board or the add-on board for the PITS+ board. The LoRa object is **non-blocking**. The calling code can either poll to find out when the transmission has comp...
def display_table(): print(table[0] + " | " + table[1] + " | " + table[2]) print(table[3] + " | " + table[4] + " | " + table[5]) print(table[6] + " | " + table[7] + " | " + table[8]) def handle_turn(): print("Position Given:") # Chooses Random Board Position position = random.randint(0, 8)...
The code defines a function `play_game()` that initializes a game by displaying a table, then enters a loop to handle player turns and check if the game is over. The loop continues as long as `continueplay` is true, processing each turn and evaluating game-ending conditions until the game concludes.
def play_game(): display_table() while continueplay: handle_turn() check_if_game_over()
def runDark(self): """ Collect one dark. """ darkPlan = self.darkCollection() self.runScan(darkPlan) def setPowerOutput(self, x): """ give percentage output (0-100) """ caput('XF:28ID1-ES{LS336:1-Out:3}Out:Man-SP', x) def singleScan(self): """ Sing...
This code processes a series of predefined scans by iterating through them, updating their status in a configuration dictionary, executing specific scan operations based on their type (e.g., dark scans, sleep, power settings, single scans, time scans), and handling interruptions to allow user-controlled continuation or...
def runInput(self): """ run an input file. """ for scan in list(range(self.totalScans))[self.currentScan:]: self.SE28IdConfig['scans_completed'][str(scan)] = ['unstarted', 'incomplete'] for scan in list(range(self.totalScans))[self.currentScan:]: self.SE28...
def liberties(self, x, y): scratch = self.scratch_board() self.flood(scratch, self.grid[x][y], x, y) n = 0 for i in range(5): for j in range(5): if self.grid[i][j] == 0 and self.group_border(scratch, i, j): n += 1 return n def scrat...
The main task of the code is to capture stones on a game board by checking if a group at position (x, y) has no liberties. If so, it uses a temporary "scratch" board to identify connected stones of the same color via a flood fill, then replaces those captured stones with the current player's move (`to_move`) in the mai...
def capture(self, x, y): if self.liberties(x, y) > 0: return scratch = self.scratch_board() self.flood(scratch, self.grid[x][y], x, y) for i in range(5): for j in range(5): if scratch[i][j]: self.grid[i][j] = self.to_move
def process_phase_2a(input_date, input_str): """Custom function to run phase 2a of the PDF scrapping""" date_list = [input_date, input_date + datetime.timedelta(days=1)] date_list_re_pattern = convert_date_list_to_re_pattern(date_list) date_list_re_search = re.search(date_list_re_pattern, input_str) ...
The main task of the code is to process phases 2, 3, and 4 of PDF content scraping by iterating through dates and content, updating an output dictionary with processed data, and returning the structured results. It handles date-based iterations, content transformation, and dictionary aggregation for structured storage.
def process_phase_2_to_4(input_str): """Custom function to run phase 2, 3 and 4 of the PDF scrapping""" date = datetime.date(2022, 11, 24) in_memory_date = None in_memory_content = None output_dict = {} while process_phase_2a(date, input_str): date_str, date, content = process_phase_2a(d...
def xab(x, a, b, G, H, P, Q): """ Pollard Step :param x: :param a: :param b: :return: """ sub = x % 3 # Subsets if sub == 0: x = x*G % P a = (a+1) % Q if sub == 1: x = x * H % P b = (b + 1) % Q if sub == 2: x = x*x % P a = a*...
The function implements Pollard's Rho algorithm to compute the discrete logarithm of $ H $ with base $ G $ modulo prime $ P $. It uses a cyclic subgroup of order $ Q = (P-1)/2 $, simulating a tortoise-and-hare (Floyd's cycle-finding) approach by iterating operations on $ x $ and $ X $, tracking exponents $ a, b $ and $...
def pollard(G, H, P): # P: prime # H: # G: generator Q = (P - 1) / 2 # sub group x = G*H a = 1 b = 1 X = x A = int(a) B = int(b) # Do not use range() here. It makes the algorithm amazingly slow. for i in range(1, P): # Who needs pass-by reference when you ha...
def _check_parameters(self): if not isinstance(self.n_clusters, int): raise TypeError if self.n_clusters <= 0: raise ValueError(f"n_clusters should be > 0, got {self.n_clusters} instead.") if not isinstance(self.m, int): raise TypeError if self.m <= 0...
This code performs Fuzzy C-Means clustering on input data `X`. It validates parameters, initializes centroids randomly (or with provided `init`), iteratively updates cluster centroids and membership matrix via `_cmeans0` until convergence (change < `tol` or max iterations reached), computes objective function history, ...
def fit(self, X, init=None): X = self._validate_data(X, dtype=[np.float64, np.float32]) self._check_parameters() self._check_data(X) random_state = check_random_state(self.random_state) data = X.T if init is None: n = data.shape[1] u0 = random_st...
def _check_data(self, X): if X.shape[0] < self.n_clusters: raise ValueError( f"n_samples={X.shape[0]} should be >= n_clusters={self.n_clusters}." ) def normalize_columns(columns): """ Normalize columns of matrix. Parameters ---------- columns : 2d arr...
This code performs fuzzy c-means clustering on input data X, iteratively updating fuzzy membership degrees until convergence or max iterations. It initializes centroids, computes membership updates via _cmeans_transform0, checks stopping criteria using tolerance, and returns final fuzzy labels with their transposed ori...
def transform(self, X, init=None, max_iter=None, random_state=None): X = self._validate_data(X, dtype=[np.float64, np.float32]) self._check_data(X) data = X.T if max_iter is None: max_iter = self.max_iter if random_state is None: random_state = self.rando...
def initStateMatrix(self, plaintext): state = [] while plaintext: state.append(plaintext[:2]) plaintext = plaintext[2:] return state def keyAddition(self, state, key): stateString = '' keyString = '' newState = [] for...
This function performs one round of AES encryption by initializing the state matrix from plaintext, applying key addition, byte substitution, shift rows, mix columns, generating a round key via key scheduling, and final key addition, returning the transformed state matrix.
def encryptOneRound(self, plaintext, key): # For encrypting one round # Initialize state matrix from given plaintext state = self.initStateMatrix(plaintext) # Perform key addition/round key state = self.keyAddition(state, key) # Perform byte substitution state ...
def keyAddition(self, state, key): stateString = '' keyString = '' newState = [] for byte in state: stateString += byte for word in key: keyString += word stateString = self.xor( stateString, keyString).zfill(len(stateString)) ...
This code implements AES encryption according to FIPS-197 standards, verifying each round's state against predefined test vectors. It initializes a plaintext/key pair, performs 10 rounds of AES transformations (SubBytes, ShiftRows, MixColumns, KeyAddition), and checks intermediate states and final ciphertext against ex...
def encryptFIPS197(self): # Check array contains expected values after each round with the given plaintext/key # input from the FIPS-197 document. For each round, an assertion is made that check[round] == state. # If there are no assertion errors, the test is passed. check = [ ...
def initStateMatrix(self, plaintext): state = [] while plaintext: state.append(plaintext[:2]) plaintext = plaintext[2:] return state def keyAddition(self, state, key): stateString = '' keyString = '' newState = [] for...
This code implements a 10-round AES-like encryption algorithm. It initializes a state matrix from plaintext, applies key addition, and iterates through substitution, shift rows, and mix columns (except final round). Each round updates the state with key scheduling, logging transformations in tables. The final encrypted...
def encrypt(self, plaintext, key): # ENCRYPTS TEN ROUNDS TableText = "" state = self.initStateMatrix(plaintext) self.Table.append(f"|{plaintext}| | | |{' '.join(state)}|") # Initial Key Addition Layer state = self.keyAddition(state, key) for round in ran...
def loop_count(divide, row): loop = row / divide remaining = row % divide return loop, remaining def thread_execute(divide, is_random, loop, remaining, table): executor = ThreadPoolExecutor(10) for i in range(int(loop)): executor.submit(bulk_insert_execute, table, divide, is_random) if r...
This function performs bulk insertion into a MySQL table. If the row count exceeds 10,000, it divides the data into chunks and uses multithreading for parallel insertion; otherwise, it executes a single bulk insert. It measures and prints the total execution time, optimizing performance for large datasets through paral...
def bulk_insert_mysql(table, row, is_random): start = time.time() divide = 10000 if row > divide: loop, remaining = loop_count(divide, row) thread_execute(divide, is_random, loop, remaining, table) else: bulk_insert_execute(table, row, is_random) end = time.time() - start ...
def generate_plot_dict(): return {'x': [], 'y' : []} def rand_edge_count(n): max = int((n*(n + 1)) / 2) return random.randint(0, max) def MIS(G): nodes = [i for i in range(G.number_of_nodes())] max_set = [] for i in get_power_set(nodes): if is_ind_set(i, G) and len(i) > len(max_set): ...
The code compares the sizes of Maximum Independent Sets (MIS), Minimum Vertex Covers (MVC), and their complements across random graphs of varying sizes. It runs multiple trials, computes averages, and plots the cardinalities of these sets against graph size, verifying that the complement of an MIS is a valid MVC.
def len_comp_MIS(max_nodes,trials, skip): len_of_comp_of_mis = generate_plot_dict() len_of_mvc = generate_plot_dict() len_of_mis = generate_plot_dict() for n in range(0, max_nodes, skip): avg_mis = 0 avg_mvc = 0 for _ in range(trials): G = create_random_graph...
def generate_plot_dict(): return {'x': [], 'y' : []} def rand_edge_count(n): max = int((n*(n + 1)) / 2) return random.randint(0, max) def MVC(G): #minimum vertex cover nodes = [i for i in range(G.number_of_nodes())] min_cover = nodes for i in get_power_set(nodes): if is_vertex_cover(i, ...
The code compares the average sizes of Maximum Independent Sets (MIS) and Minimum Vertex Covers (MVC) in random graphs of varying sizes. It generates plots showing how these set cardinalities scale with graph size, verifying that the complement of an MVC is an MIS. The function runs multiple trials for each graph size,...
def len_comp_MVC(max_nodes,trials, skip): len_of_comp_of_mvc = generate_plot_dict() len_of_mvc = generate_plot_dict() len_of_mis = generate_plot_dict() for n in range(0, max_nodes, skip): avg_mis = 0 avg_mvc = 0 for _ in range(trials): G = create_random_graph...
def generate_plot_dict(): return {'x': [], 'y' : []} def rand_edge_count(n): max = int((n*(n + 1)) / 2) return random.randint(0, max) def sum_of_MIS_MVC(G): return len_MIS(G) + len_MVC(G)
This function tests and visualizes the average size of Maximum Independent Sets (MIS) and Minimum Vertex Covers (MVC) in random graphs. It iterates through graph sizes (0 to max_nodes), runs multiple trials for each size, computes MIS/MVC averages, and plots them against graph size. The plot compares MIS/MVC sizes with...
def size_of_MIS_MVC_test(max_nodes,trail_count, skip): mis_mvc = generate_plot_dict() g = generate_plot_dict() for n in range(0, max_nodes, skip): sum = 0 for _ in range(trail_count): G = create_random_graph(n, rand_edge_count(n)) sum += sum_of_MIS_MVC(G) ...
def resetAllRooms(self): self.roomDict = {} self.rooms = set() self.occupiedRooms = set() self.emptyRooms = set() self.roomCoordinates = set() self.allPlayers = {} Player.resetAllPlayerRooms() self.spawnRoom = Room("Spawn Area") self.addRoomConne...
The code generates a network of connected rooms using a queue-based approach. It initializes with a seed for randomness, creates rooms iteratively by connecting new rooms to existing ones in random eligible directions, and enqueues eligible rooms for further expansion. The process continues until the room limit is reac...
def generateRooms(self, seed=time.time()): self.resetAllRooms() random.seed(seed) print("seed: ", seed) self.seed = seed roomQueue = Queue() roomQueue.enqueue(self.spawnRoom) while len(self.rooms) < self.roomLimit: if len(roomQueue) == 0: ...
def distance (q1, q2): """ Returns the distance between two configurations. You may want to look at the getRobotPlacement function in utils.py that returns the OBB for a given configuration """ distance = math.sqrt((q1[0] - q2[0])*(q1[0] - q2[0])+(q1[1] - q2[1])*(q1[1] - q2[1])) retu...
This code constructs a probabilistic roadmap (PRM) for robot navigation by generating collision-free vertices within specified bounds, connecting nearby vertices to form paths, and saving the roadmap. It samples random points, avoids collisions, ensures vertex diversity, and builds a graph for motion planning in clutte...
def build_roadmap(q_range, robot_dim, scene_obstacles): global obstacles, robot_width, robot_height, robot_radius obstacles = scene_obstacles # setting the global obstacle variable x_limit = q_range[0] # the range of x-positions for the robot y_limit = q_range[1] # the range of y-positions for the ro...
def gen_def(self, node): if node in self.json["defs"]: parent = self.cfg.get_any_parents(node) children = self.cfg.get_any_children(node) rhs = self.cfg.get_op_hands(children[0])[1] if rhs in self.json["sources"]: return set([node]) if...
This code performs data-flow analysis on a control flow graph (CFG) to compute propagation of definitions. It iteratively calculates OUT sets for each node using gen_def and kill_def operations, updating values until no changes occur. Finally, it collects sink nodes' OUT sets and returns them along with a sink-specific...
def poss_t_def(self, cfg: CFG): self.cfg = cfg self.nodeset = self.cfg.get_node_ids() self.index = self.cfg.get_root() IN = [set() for i in range(len(self.nodeset))] self.OUT = [set() for i in range(len(self.nodeset))] old_out = [set() for i in range(len(self.nodeset))] ...
def check_num_of_arguments(sum_of_argument): """ :param sum_of_argument: int :return: True if sum of argument == 2 """ global full_path, source, destination result = "True" if sum_of_argument > 2: full_path = sys.argv[ZERO] source = sys.argv[ONE] destination = sys.arg...
The code processes arithmetic expressions from a file, validating script arguments and file existence. It reads expressions line-by-line, computes results, and writes them to a destination file, ensuring each expression is on a separate line. Error handling and assertions are included for integrity checks.
def main(): """ main function :return: non """ sum_of_argument = len(sys.argv) script_integrity = check_num_of_arguments(sum_of_argument) if script_integrity == "True": dir_path = full_path.rfind('/') files_exist = check_if_files_exist(os.listdir(full_path[0:dir_path])) ...
def get_abs_root_path() -> str: """Returns the absolute path of the root dir of this repository. Throws an error if the current path does not end in /docs/source. """ current_abs_path: str = os.getcwd() assert_abs_path_ends_in_docs_source(current_abs_path=current_abs_path) abs_root_path: str = ...
The function generates Sphinx-compatible .rst documentation files for all Python files in a project's 'src' and 'test' directories, automatically creating them in an 'autogen' folder and returning their filepaths. It processes source and test code separately, ensuring modular documentation integration for Sphinx builds...
def generate_rst_per_code_file( *, extension: str, ) -> List[str]: """Generates a parameterised .rst file for each .py file of the project, to automatically include its documentation in Sphinx. Returns rst filepaths. """ abs_root_path: str = get_abs_root_path() abs_src_py_paths: List[s...