dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def _kmeans_plus_plus(self): """ Initialize the centroids with KMeans++ initialization. Returns: numpy array: The initialized centroids. """ # initialize the centroids with KMeans++ initialization centroids = [self.X[np.random.randint(self.n_samples)]] ...
The code's main task is to predict cluster labels for input data using a KMeans++ initialized clustering model. It assigns each sample to the nearest centroid after optimizing cluster positions, returning the cluster indices as labels for classification.
def predict(self, X): self.X = X self.n_samples, self.n_features = X.shape # initialize with KMeans++ initialization self.centroids = self._kmeans_plus_plus() # optimize clusters self._optimize_clusters() # classify samples as the index of their clusters ...
def build_encoder(self): """The encoder. Bidirectional LSTM. Similar architecture as in: "Listen, Attend and Spell" https://arxiv.org/pdf/1508.01211.pdf """ with tf.variable_scope("encoder"): # Pyramidal bidirectional LSTM(s) inputs = self.audios ...
This method constructs a sequence-to-sequence model with encoder-decoder architecture. It builds the encoder, decoder, computes training loss, configures learning rate (cyclic or exponential decay), applies Adam optimizer with gradient clipping, and sets up inference outputs. The core tasks include model construction, ...
def add_seq2seq(self): """Creates the sequence to sequence architecture.""" with tf.variable_scope('dynamic_seq2seq', dtype=tf.float32): # Encoder encoder_outputs, encoder_state = self.build_encoder() # Decoder logits, sample_id, final_context_state = sel...
def add_placeholders(self): self.audios = tf.placeholder(tf.float32, shape=[None, None, 494]) self.audio_sequence_lengths = tf.placeholder(tf.int32, shape=[None], ...
The main task of the code is to construct a TensorFlow graph for a sequence-to-sequence model by adding placeholders, embeddings, lookup operations, and the seq2seq architecture, then initializing a model saver and confirming graph completion with a print statement.
def build_graph(self): self.add_placeholders() self.add_embeddings() self.add_lookup_ops() self.add_seq2seq() self.saver = tf.train.Saver() print('Graph built.')
def PrintMenu(self): print('Select the Calculation: ') print('1. Factorial') print('2. Exponential') print('3. Exponential of X') def GetInput(self): sw_input = True while sw_input: try: selection = int(input('Select: ')) sw_inp...
The code initializes an object by printing a menu, capturing user input, and creating a selector instance based on the input to handle user choices.
def __init__(self): self.PrintMenu() input = self.GetInput() self.Selector(input)
def store_by_hash(obj_list): '''returns a dict where the objects are stored by their full_id_hash. drops duplicates.''' result_dict = {} for obj in obj_list: full_id_hash = get_hash(obj) if full_id_hash in list(result_dict.keys()): result_dict[full_id_hash] = get_most_recent(obj,...
The code generates an enumeration comparison report in Excel format by organizing acquisition lists, interferogram configurations, and interferogram data into structured sheets. It validates input enumeration strings, compares date pairs, and saves the report along with metadata, ensuring a systematic analysis of SAR d...
def generate(product_id, aoi, track, acq_lists, ifg_cfgs, ifgs, audit_trail, enumeration_string): '''generates an enumeration comparison report for the given aoi & track''' # unique tracks based on acquisition list if os.path.exists(product_id): shutil.rmtree(product_id) os.mkdir(product_id) ...
def store_by_id(obj_list): """returns a dict where the objects are stored by their object id""" result_dict = {} for obj in obj_list: obj_id = obj.get('_source', {}).get('id', False) if obj_id: result_dict[obj_id] = obj return result_dict def store_by_slc_id(obj_list): ""...
The code generates an HTML report comparing SLC and acquisition data for a given AOI and track. It identifies missing SLCs, checks product status, and structures results into tables. If no data is found, it returns an empty string. The report includes sections for missing SLCs and product status, formatted with HTML ta...
def generate(product_id, aoi, track, acqs, slcs, acq_lists, ifg_cfgs, ifgs, audit_trail, aoi_tracks): """generates an enumeration comparison report for the given aoi & track""" acq_dct = store_by_id(acqs) acq_map_dct = store_by_slc_id(acqs) slc_dct = store_by_id(slcs) acq_list_dct = store_by_hash(ac...
def load_context(): '''loads the context file into a dict''' try: context_file = '_context.json' with open(context_file, 'r') as fin: context = json.load(fin) return context except: raise Exception('unable to parse _context.json from work directory') def get_aoi(a...
The main task of the code is to query relevant products for each track, filter them based on audit trail hashes, and generate reports. It loads context, validates inputs, retrieves AOI data, sorts acquisition lists by track, checks audit trails, filters products using allowed hashes, and creates timestamped product IDs...
def main(): ''' Queries for relevant products & builds the report by track. ''' ctx = load_context() aoi_id = ctx.get('aoi_id', False) aoi_index = ctx.get('aoi_index', False) if aoi_id is False or aoi_index is False: raise Exception('invalid inputs of aoi_id: {}, aoi_index: {}'.forma...
def get_aoi(aoi_id, index): 'retrieves the AOI from ES' grq_ip = app.conf['GRQ_ES_URL'].replace(':9200', '').replace('http://', 'https://') grq_url = '{0}/es/{1}/_search'.format(grq_ip, index) es_query = { "query": { "bool": { "must": [ {"term": {"...
The code generates an HTML report for Area of Interest (AOI) tracking by querying product data, organizing it by track, and compiling two tables per track. It validates inputs, retrieves AOI details, filters products using audit trails and hashes, and constructs HTML segments for each track, combining them into a final...
def generate_aoi_track_report(aoi_idx, aoi_id): """ Queries for relevant products & builds the report by track. :param aoi_idx, str, ES index for AOI's :param aoi_id: area of interest id in elasticsearch, ex. AOI_monitoring_hawaiian_chain_tn124_hawaii :return: str, html with consisting of 2 <table>'...
def ensure_category_present(platforms, root, category_list): ''' Ensures the category folder exists, by making it if it doesn't Note: category_list will someday be a list. for now it is the name of a single category ''' for platform in platforms: plat_root = get_platform_root(platform, root)...
The main task of the code is to rename a sample by prompting users for old and new names/categories, creating new directories, copying files with name replacements, deleting old folders if empty, and updating the csproj file to reflect the changes.
def rename_sample_main(full_directory): # Ask for the name of the old sample old_name = input("Please enter the name of the old sample, as it appears in the file system: ") # Ask for the category of the old sample old_cat = input("Please enter the category of the old sample, as it appears in the file s...
def ensure_category_present(platforms, root, category_list): ''' Ensures the category folder exists, by making it if it doesn't Note: category_list will someday be a list. for now it is the name of a single category ''' for platform in platforms: plat_root = get_platform_root(platform, root)...
The main task of the code is to rename a sample by moving its files from an old category/name to a new category/name. It ensures the new category exists, creates a new directory, copies and renames files, deletes the old directory, and updates project files. The function handles input parsing, directory management, fil...
def rename_sample_alt(full_directory, command): # Ask for full details if (command == None): command = input("Enter the old and new category and name in format old_cat,old_name-new_cat,new_name: ") old, new = command.split("-") old_cat, old_name = old.split(",") old_cat, old_name = old_cat.s...
def get_unfriendly_sample_name(friendly_name): ''' Return the unfriendly equivalent to the given friendly name ''' unfriendly_name = [] last_space = False # last character was a space, capitalize next for character in friendly_name: if character not in [' ', ',', '(', ')', '\n', '\t', '-...
This code creates a new sample project by collecting user inputs for sample details, generating necessary file structures, and replacing placeholders in template files with dynamic data like names, categories, and configuration settings.
def new_sample_main(full_directory): print(full_directory) # Ask for the name of the sample friendly_name = input("Enter the friendly name of the sample: ") sample_name = input("Enter the 'unfriendly' (space-free) type name of the sample (or blank to autogenerate): ") if (sample_name == ""): ...
def rename_sample_main(full_directory): # Ask for the name of the old sample old_name = input("Please enter the name of the old sample, as it appears in the file system: ") # Ask for the category of the old sample old_cat = input("Please enter the category of the old sample, as it appears in the file s...
The main task of the code is to process command-line arguments to determine whether to rename existing samples, create new samples, or rename samples via a one-line entry. It validates input parameters, checks the operation mode (rename, new, or copy), and delegates tasks to corresponding functions like `rename_sample_...
def main(): # Ask if the user wants to rename a sample or copy if len(sys.argv) < 3: print("Usage: samplegen.py /path/to/samples/directory -[mode] (note: dir should end with 'src')") print("Mode is -[r]ename to rename a sample (guided), -[n]ew to create new, -c to rename (one-line-entry)") ...
def get_num_available_workers(self): """Get num available workers.""" available = 0 for key in self.worker_threads: if self.worker_threads[key]["state"] == "ready": available = available + 1 return available def find_ready_worker(self): """Return pid o...
The code groups input files into partitions, distributes them to worker processes for sorting, manages job assignments, and prepares the environment for subsequent processing phases by updating directories and monitoring worker completion.
def group(self, message_dict): """Group files and make directories.""" num_workers = self.get_num_available_workers() file_partitions = [[] for _ in range(num_workers)] home_dir_tmp = pathlib.Path.cwd() / "tmp" job_dir = home_dir_tmp / "job-{}".format(str(message_dict["job_id"]...
def mapreduce(self, message_dict, job_type): """Reduce and map execution.""" # num_workers is number required in job, not total num of workers num_workers = ( message_dict["num_mappers"] if job_type == "map" else message_dict["num_reducers"] ) ...
The code executes a MapReduce task by initializing server status, performing a map phase, grouping data, executing a reduce phase, finalizing the task, and stopping the server.
def execute_task(self, message_dict): """Execute task.""" # begin job execution self.server_running = True self.mapreduce(message_dict, "map") self.group(message_dict) # pdb.set_trace() self.mapreduce(message_dict, "reduce") wrap_up(message_dict) s...
def login(self): """ Logs into PollEv. :raises LoginError: if login failed. """ if self.login_type.lower() == 'uw': success = self._uw_login() else: success = self._pollev_login() if not success: raise LoginError("Your username...
The code's main task is to continuously monitor for new polls on a host by logging in, retrieving a token, and looping to check for new polls. If a poll is detected, it waits a specified time before answering it, logging responses. If no poll is found, it waits and retries periodically, handling login errors and value ...
def run(self): """Runs the script.""" try: self.login() token = self.get_firehose_token() except (LoginError, ValueError) as e: logger.error(e) return while self.alive(): poll_id = self.get_new_poll_id(token) if po...
def create_header(): ua = UserAgent() return {'User-Agent': str(ua.chrome)} def get_mapping_list(): ret_val = [] ret_val.append(('abaddon', 'Abaddon')) ret_val.append(('alchemist', 'Alchemist')) ret_val.append(('ancient-apparition', 'Ancient Apparition')) ret_val.append(('anti-mage', 'Anti-M...
The main task of the code is to scrape hero information from a website by iterating through a list of hero URL fragments and names. It uses a header for requests, tracks progress with a counter, and prints status updates. Each hero's data is scraped using the `scrape_hero_info` function, with a 3-second delay between r...
def main(): header = create_header() all_heroes = get_mapping_list() counter = 0 print('Starting to scrape...\n') for hero_element in all_heroes: url_fragment, hero_name = hero_element print('Working on: %s' %(hero_name)) scrape_hero_info(url_fragment, hero_name,header) ...
def play_buttons(): global spectroCheckBox,Apply col1,col2=st.sidebar.columns([1,2]) with col2: spectroCheckBox=st.checkbox('Spectrogram') st.checkbox('signal time') if col1.button("Play"): control_music("play") if col1.button("Pause"): ...
The main task of the code is to create a Streamlit interface for audio signal analysis, displaying original and modified signals via spectrograms, with playback controls, adjustable sliders, and an "Apply" function to process modifications. It splits the UI into columns for real-time visualization of input and output s...
def sound_mode(): play_buttons() leftUpColumns,rightUpColumns=st.columns(2) with leftUpColumns: drawSpectro(st.session_state.dataArray,title='RealSignal') make_sliders() if Apply: #sidebar apply_action() with rightUpColumns: drawSpectro(st.session_state.modifie...
def prep_pm_gps(self, pm_gps: pd.DataFrame, snapshot_minutes: int) -> None: """ Prepare the pm_gps dataframe for computing snapshot indices: 1. Set up index floored over snapshot duration 2. Average out multiple measurements at same locations in one snapshot Note that this funct...
This class initializes data processing for PM2.5 and GPS measurements, creating time snapshots, aligning with optional weather data, converting timestamps to features, and splitting data into batches for batched processing.
def __init__( self, pm_gps: pd.DataFrame, snapshot_minutes: int, weather: pd.DataFrame = None, minutes_to_weather: int = None, datetime_to_vec: Callable[[datetime], Any] = None, ): self.prep_pm_gps(pm_gps=pm_gps, snapshot_minutes=snapsh...
def approx_center(G: nx.Graph) -> Tuple[float, float]: """ Assumming the graph G is circular, get its center. The returned value usually insignificantly differs from the actual center of G; however, the difference might be significant if the graph is very sparse. """ pos = extract_positions(G) ...
The function generates random circular subgraphs of a given graph by sampling centers within a specified radius from the graph's approximate center. For each center, it creates a subgraph of nodes within a window radius, then extracts the largest connected component to ensure connectivity. It yields these subgraphs ite...
def random_circle_subgraphs(G: nx.Graph, center_radius: float, window_radius: float, n: int = 1, root: float = 4) -> Iterator[nx.Graph]: """ Generates random circular subgraphs of G where centers of the subgraphs are randomly distributed within center_radius distance from the cen...
def _validate_date(dt): LOG.debug('_validate_date(dt) called') today = datetime.today().date() begin = datetime(1995, 6, 16).date() # first APOD image date # validate input if (dt > today) or (dt < begin): today_str = today.strftime('%b %d, %Y') begin_str = begin.strftime('%b %d, %...
This function retrieves or generates JSON data for a specific date (defaulting to today if unspecified), validates the date, constructs a cache key, checks a results dictionary for cached data, fetches new data if needed, adds a service version, caches the result, and returns the data as JSON. It handles 404 errors if ...
def _get_json_for_date(input_date, use_concept_tags, thumbs): """ This returns the JSON data for a specific date, which must be a string of the form YYYY-MM-DD. If date is None, then it defaults to the current date. :param input_date: :param use_concept_tags: :return: """ # get the date...
def _validate(data): LOG.debug('_validate(data) called') for key in data: if key not in ALLOWED_APOD_FIELDS: return False return True def _abort(code, msg, usage=True): if usage: msg += " " + _usage() + "'" response = jsonify(service_version=SERVICE_VERSION, msg=msg, cod...
The function handles APOD (Astronomy Picture of the Day) requests by validating query parameters and routing to appropriate data retrieval methods. It processes date ranges, random counts, or specific dates, returning JSON responses. Invalid parameters trigger 400 errors, while unexpected exceptions result in 500 error...
def apod(): LOG.info('apod path called') try: # app/json GET method args = request.args if not _validate(args): return _abort(400, 'Bad Request: incorrect field passed.') # input_date = args.get('date') count = args.get('count') start_date =...
def github_owner(self) -> str: return self.__attributes[Tool.field(2, self.__logger)] def github_repo(self) -> str: return self.__attributes[Tool.field(1, self.__logger)] def set_version(self, platform: str, version: str): # if not hasattr(self, '__versions'): # self.get_versions = {...
The function fetches the latest release version from a GitHub repository by sending an authenticated GET request to the GitHub API, extracts the 'tag_name' from the JSON response, stores it, and returns the version. If authentication tokens are unavailable, it proceeds without them. Errors in JSON parsing log the respo...
def fetch_github_latest_release(self) -> str: if self.__GitHub_TOKEN != '': token = getenv('GITHUB_TOKEN', self.__GitHub_TOKEN) headers = {'Authorization': f'token {token}'} self.__logger.debug(token) self.__logger.debug(headers) else: headers ...
def conda_channel(self) -> str: return self.__attributes[Tool.field(4, self.__logger)] def conda_pkg(self) -> str: return self.conda_package() def set_version(self, platform: str, version: str): # if not hasattr(self, '__versions'): # self.get_versions = {} self.__versions[pl...
The main task of the code is to fetch the latest version of a Conda package from the Anaconda API by querying a constructed URL. It retrieves the JSON response, extracts the 'latest_version' field, sets it as the Conda version, and returns the version string. If parsing fails, it logs the response and returns an empty ...
def fetch_conda_latest_release(self) -> str: query_url = f'https://api.anaconda.org/package/{self.conda_channel()}/{self.conda_pkg()}' self.__logger.debug(query_url) r = requests_get(query_url) try: self.__logger.debug(r.json()) version = r.json().get('latest_vers...
def galaxy_wrapper(self) -> str: return self.__attributes[Tool.field(5, self.__logger)] def galaxy_owner(self) -> str: return self.__attributes[Tool.field(6, self.__logger)] def set_version(self, platform: str, version: str): # if not hasattr(self, '__versions'): # self.get_versions ...
The function retrieves the latest version of a Galaxy tool from a specified server by querying a repository endpoint with given parameters, parses the JSON response, logs the data, extracts the version, updates the internal version tracker, and returns the version string.
def __get_galaxy_latest_release( self, main_url: str, headers: str, rel_id: str ) -> str: r = requests_get( main_url + '/repositories/get_repository_revision_install_info', params={"name": self.galaxy_wrapper(), "owner": self.galaxy_owner(), "changeset...
def name(self) -> str: return re.sub(r'\s+', '_', self.__attributes[Tool.field(0, self.__logger)]) def platforms(self): return ['github', 'conda', 'galaxy'] def set_badge(self, platform: str): self.__badges[platform] = f'{platform}_{self.name()}.svg' def badge_file(self, platform: str) -> str: ...
The code sets badges for multiple platforms by checking if the badge file exists or if the 'force' flag is True. If either condition is met, it fetches the badge using a dynamically generated method. It logs debug information for each platform, indicating whether the badge is fetched or already present. The task involv...
def set_badges(self, force: bool=False): self.__logger.debug(self.name()) self.__logger.debug('='*len(self.name())) for platform in self.platforms(): self.set_badge(platform) if force or not os_path.exists(self.badge_file(platform)): self.__logger.debug(f'...
def is_None(value: str) -> bool: return value is None or value == 'None' or value == '' def galaxy_wrapper(self) -> str: return self.__attributes[Tool.field(5, self.__logger)] def galaxy_owner(self) -> str: return self.__attributes[Tool.field(6, self.__logger)] def __get_galaxy_latest_rel_id( ...
The main task of the code is to fetch the latest release version of a Galaxy tool from the Galaxy Tool Shed API. It first checks if the Galaxy wrapper and owner are valid, then constructs a JSON request to retrieve the latest release ID and subsequently fetches the corresponding release version using that ID.
def fetch_galaxy_latest_release(self) -> str: if is_None(self.galaxy_wrapper()) or is_None(self.galaxy_owner()): return '' headers = {'content-type': 'application/json'} main_url = 'https://toolshed.g2.bx.psu.edu/api' # Get the latest release ID rel_id = self.__get_ga...
def name(self) -> str: return re.sub(r'\s+', '_', self.__attributes[Tool.field(0, self.__logger)]) def version_file(self) -> str: return re.sub(r'\s+', '_', self.__version_file) def fetch_github_latest_release(self) -> str: if self.__GitHub_TOKEN != '': token = getenv('GITHUB_TOKEN',...
The code fetches or loads software versions from GitHub, Conda, and Galaxy based on the 'force' flag. If 'force' is True or the version file doesn't exist, it retrieves latest releases from all three sources. Otherwise, it reads pre-existing versions from a JSON file and sets them. The function logs debug information a...
def set_versions(self, force: bool): self.__logger.debug(self.name()) self.__logger.debug('='*len(self.name())) if force or not os_path.exists(self.version_file()): self.__logger.debug(f'Fetching GitHub {self.name()} release ') self.fetch_github_latest_release() ...
def dict(self) -> Dict: return self.__attributes def name(self) -> str: return re.sub(r'\s+', '_', self.__attributes[Tool.field(0, self.__logger)]) def set_versions(self, force: bool): self.__logger.debug(self.name()) self.__logger.debug('='*len(self.name())) if force or not os_p...
The main task of this code is to initialize an object that manages versioning and badge information for different platforms (e.g., GitHub, Conda, Galaxy). It sets up attributes like host, logger, GitHub token, and copies input values. It prepares version and badge storage paths, initializes version data using `set_vers...
def __init__( self, values: Dict, host: str, github_token: str='', force: bool=True, logger: Logger = getLogger(__name__) ): __HOST = host self.__logger = logger self.__GitHub_TOKEN = github_token self.__attributes = deepcopy(values) ...
def query(campaign_uuid): queryset = SMS_Queued.objects.all() queued = queryset.filter(campaign=str(campaign_uuid).replace('-',''), queued=1) print("Queued Non-Dict:",len(queued)) return queued def log_data(action, logname): # log_data will print action to screen and write to log file prin...
The code processes a list of queued SMS campaigns by checking each contact's timezone against specified start/end times. If valid, it composes and sends SMS messages via an agentless service, logs status updates, and updates contact records with send results. Contacts outside the time range are marked as inactive. The ...
def sendTexts(campaign_uuid, contact_list_id, startTime, endTime, connection, number): queued = query(campaign_uuid) # print(queued) for count, q in enumerate(queued): print('QQQQQ', q) log_data(f"Processing: Queued {len(queued)-1}\\{count}", "Queued") time.sleep(1) if q.Time...
def connect_to_purecloud(client_id, client_secret): log_data('Connecting to PureCloud', 'SMS_RUN_APP') # Set Purecloud region region = PureCloudPlatformClientV2.PureCloudRegionHosts.us_west_2 # Get API Host for Purecloud region PureCloudPlatformClientV2.configuration.host = region.get_api_host() ...
This code initializes an SMS campaign handler by retrieving campaign data from the database, establishing a PureCloud connection, downloading contact data, and scheduling SMS texts using specified parameters like call list IDs, time ranges, and campaign settings.
def __init__(self, event=''): campaign_uuid = event.job_id campaign_model = Campaign.objects.filter(send_texts_scheduler_uuid=campaign_uuid).values()[0] self.campaign_model = campaign_model if campaign_model['Call_List_ID']: self.Call_List_ID = campaign_model['Call_List_ID'] ...
def generate_character(): """Generates a new D&D character""" clear_screen() character = {} character['Class'] = select_class() character['Race'] = select_race() character['Ability Scores'] = roll_ability_scores() return character def display_character(character): """Displays the charact...
The main task of the code is to repeatedly generate and display a D&D character using the generate_character() and display_character() functions, allowing the user to create new characters by pressing 'R' or exit the program by pressing 'E', which clears the screen and displays a farewell message.
def main(): print("Welcome to the D&D Character Creator!") while True: character = generate_character() display_character(character) choice = input("Press 'R' to create another character or 'E' to exit: ").lower() if choice == 'e': clear_screen() print("\n...
def trst(): execute("pathmove RESET IDLE") def instr(instruction): """Load the specified instruction""" code = ir_codes[instruction.upper()] return execute(f"irscan core.tap {code}") def boundary_scan(scan_in=None): if test_mode: return None payload = "drscan core.tap" for reg, wi...
The code's main task is to debug and validate register data by comparing expected (correct) values with actual data. In test mode, it loads pre-saved incorrect data for comparison. Otherwise, it simulates a system by executing instructions, sampling data at each cycle (up to 24), and validating against reference data u...
def run_debug(): if test_mode: with open("bad_data.pkl", "rb") as f: incorrect_register_data = pickle.load(f) for idx, data in enumerate(correct_register_data): app.check_registers(idx + 1, data, incorrect_register_data[idx]) return trst() instr("halt") # st...
def trst(): execute("pathmove RESET IDLE") def instr(instruction): """Load the specified instruction""" code = ir_codes[instruction.upper()] return execute(f"irscan core.tap {code}") def boundary_scan(scan_in=None): if test_mode: return None payload = "drscan core.tap" for reg, wi...
The code simulates hardware debugging by executing test instructions, checking register values against expected data in test mode, and handling specific conditions to fix a bug. It halts the system, resets the core, steps through instructions, verifies register states, and resumes execution upon meeting predefined crit...
def fix_bug(): if test_mode: for idx, data in enumerate(correct_register_data): app.check_registers(idx + 1, data, data) return #reinit() trst() instr("halt") # stop system clock instr("reset") # reset the core cycle = 0 while True: instr("sample_...
def trst(): execute("pathmove RESET IDLE") def instr(instruction): """Load the specified instruction""" code = ir_codes[instruction.upper()] return execute(f"irscan core.tap {code}") def boundary_scan(scan_in=None): payload = "drscan core.tap" for reg, width in bsr_format.items(): if s...
The main task of the code is to debug and fix a system bug by halting the core, resetting it, stepping through execution to specific memory addresses (00000024 and 00000050), preloading targeted instructions, and resuming operation. It uses boundary scan data to detect program counter (PC) values, then manipulates the ...
def fix_bug(): trst() instr("halt") # stop system clock instr("reset") # reset the core while True: instr("step") # toggle system clock once instr("sample_preload") data = boundary_scan() if data["PC"] == "00000024": # jump to next instruction p...
def get_splits(examples: List, feature: str) -> List[float]: """ Given some examples and a feature, returns a list of potential split point values for the feature. :param examples: a set of examples :type examples: List[List[Any]] :param feature: a feature :type feature: str :return: a list...
The function `choose_feature_split` identifies the feature and split point from a given set of examples and features that yield the maximum expected information gain. It iterates through each feature, evaluates all possible split points, and computes the information gain for each. If multiple splits yield the same gain...
def choose_feature_split(examples: List, features: List[str]) -> (str, float): """ Given some examples and some features, returns a feature and a split point value with the max expected information gain. If there are no valid split points for the remaining features, return None and -1. Tie breakin...
def get_majority(labels): """ :param labels: List :return: the majority decision: int """ freqDict = Counter(labels) freq = 0 vote = None for key, value in freqDict.items(): if value > freq: freq = value vote = key elif value == freq: ...
This function recursively builds a decision tree by splitting examples using binary splits on selected features. It sets leaf nodes with majority class decisions when examples are homogeneous, no features remain, or maximum depth is reached. The tree grows by choosing the optimal feature to split, creating left/right c...
def split_node(cur_node: Node, examples: List, features: List[str], max_depth=math.inf): """ Given a tree with cur_node as the root, some examples, some features, and the max depth, grows a tree to classify the examples using the features by using binary splits. If cur_node is at max_depth, makes cur_n...
def load_Images(): for piece in pieces: icons[piece] = pygame.transform.scale(pygame.image.load(path + 'icons/' + piece + '.png'), (sq_size, sq_size)) for piece in pieces: small_icons[piece] = pygame.transform.scale(pygame.image.load(path + 'icons/' + piece + '.png'), (sq_size // 2, sq_size...
This code implements a graphical chess game with user interaction, allowing players to make moves via mouse clicks, undo moves, and reset the board. It tracks time limits for each player, checks for valid moves, updates the game state, and displays the board, captured pieces, and countdowns. The loop maintains a 60 FPS...
def main(): ### Constants for main() function ### load_Images() load_Sounds() game_Display.fill(white) draw_Board(0, 0) square_chosen = () player_Clicks = [] move_Made = False game_Over = False # Number of minutes for each player user_input = int(input('How much minutes for ...
def possible_Moves(self): possible_moves = [] #Total set of all potential moves for row in range(len(self.board)): for col in range(len(self.board[row])): color = self.board[row][col][0] if (self.white_Move and color == 'w') or (not self.white_Move and color =...
This function validates all possible moves by simulating each move, checking if it leaves the king in check. Invalid moves are removed, and it determines checkmate or stalemate if no valid moves remain.
def check_Moves(self): moves = self.possible_Moves() for i in range(len(moves)-1,-1,-1): self.make_Move(moves[i]) self.white_Move = not self.white_Move #Switches to other player to check if king can move if self.in_Check(): #If the move makes the king vulnerable to ch...
def pick(x): #input an integer x, and returns all x-long arrays of 0s and 1s xx = [0] * x xxxx = [] for xxx in range(0,2**x): xxxx.append(deepcopy(xx)) for yyy in range(x-1, -1, -1): if xx[yyy] == 0: for yyyy in range(x-1, yyy, -1): xx[yyyy] = 0 xx[yyy] = 1 break return(deepcopy(xxxx)) def ...
The code generates the smallest topology containing the given bad-topology $ x $ by first computing all finite intersections of $ x $'s elements, then forming arbitrary unions of these intersections. This ensures the resulting structure satisfies topology axioms, covering $ x $ with minimal closure properties.
def close(x): #given a bad-topology x (with empty and full in it though), take all finite intersections, #then arbitrary unions to find the smallest topology that 'covers' x xx = pick(len(x)) y = [] for yy in range(0,len(xx)): xxyy = 0 for xy in range(0,len(x)): if xx[yy][xy] == 1: yyy = deepcopy(x[xy])...
def _create_tofit_lists(self): if self.fit_vibrational_energies == 'None': self.fit_vibrational_energies = [] elif self.fit_vibrational_energies == 'all': self.fit_vibrational_energies = list(range(self.num_modes)) if self.fit_hr_params == 'None': self.fit_hr_...
The main task of the code is to perform parameter fitting using least-squares optimization. It constructs parameter arrays, applies constraints (non-negativity if enforced), and fits parameters to minimize residuals. The result updates model attributes like scaling factor, energy, and broadening, then computes the fitt...
def perform_fit(self): """ Do the fitting. Returns ------- None. """ self._create_tofit_lists() params = self._construct_parameter_array() mask = self._construct_parameters_tofit_mask() initial_guess = params[mask] params_tohold =...
def createStorage(self): if not os.path.isdir(self.directory): os.mkdir(self.disk) def getSizeBLOCK(self): file_name = 'temp.txt' if not os.path.isfile(self.directory + "/" + file_name): file_name = 'reut2-' + str(f'{0:03}') + '.sgm' reuters_file = open(self.p...
This code processes commands via the `map_request` function, executing tasks like creating a dictionary, merging blocks, or querying data. It initializes storage and checks disk usage, then performs actions based on the input command: creating a dictionary and computing statistics, merging blocks and writing them to di...
def map_request(self, args): print(args.command) self.createStorage() self.getSizeBLOCK() self.memoryUsedInDisk() if args.command == "createdictionary": self.createDictionary() self.writeBlockToDisk() self.stattable.computeCalcul...
def get_algorithm_hyperparameters(algorithm: Callable) -> List[str]: """Identifies the hyperparameters for each algorithm. Args: algorithm (Callable): algorithm to which we get the hyperparameters. Returns: List[str]: list of all the hyperparameters for the provided algorithm. """ ...
This function performs a hyperparameter sweep over specified combinations, using cross-validation to evaluate each set of hyperparameters on a dataset. It returns a list of dictionaries, each containing a hyperparameter combination and its corresponding cross-validation test accuracies. The process involves generating ...
def hyperparameter_sweep( y: np.ndarray, tx: np.ndarray, config: SimpleNamespace, ) -> list[dict[Union[str, Any], Any]]: """Train the algorithm algorithm on the dataset (tx, y) on all combinations of hyperparameters in hyperparameters_domain with cross-validation and return the accuracies obtain...
def setup_arg_parser(self, parser: argparse.ArgumentParser): pass def parse_arguments(self): pass def setup_commands(self): self.add_command("help", self.tg_help, simple=True) self.add_command("testtg", self.tg_testtg, simple=False)
This code initializes a class with logging, argument parsing, and optional Telegram bot integration. It sets up command-line options for testing and Telegram disablement, parses arguments, configures a Telegram bot (if enabled), and registers commands. The main task is to prepare the class for handling commands, loggin...
def __init__(self, name: str, use_telegram: bool = True): init_logging(dont_reinit=True) self.dev_chat_id = os.getenv("TG_DEV_CHAT_ID", "270129568") self.name = name self._log = logging.getLogger(name) self.commands = {} parser = argparse.ArgumentParser(description=nam...
def amazon_to_df(self) -> pd.DataFrame: """ Read an Amazon Data File to a DataFrame This is pretty simple, except duplicate header rows need to be cleaned If the exporter included a "subtotal" row, it is removed Returns ------- pd.DataFrame """ d...
The main task of the code is to synchronize Amazon and LunchMoney transactions by matching them within a specified time window. It processes Amazon transactions, caches relevant LunchMoney data, merges the datasets, and updates LunchMoney transactions with Amazon details, confirming each update based on the 'confirm' p...
def process_transactions(self, confirm: bool = True) -> None: """ Run the End-to-End Process """ logger.info( "Beginning search to match Amazon and LunchMoney - using %s day window", self.time_window, ) amazon_df = self.amazon_to_df() min_d...
def initialize_parameters_deep(layer_dims): np.random.seed(5) parameters = {} L = len(layer_dims) for l in range(1, L): parameters['W' + str(l)] = np.random.randn(layer_dims[l], layer_dims[l-1]) * 0.01 parameters['b' + str(l)] = np.zeros((layer_dims[l], 1)) assert(parameter...
This code implements a deep neural network with multiple layers using gradient descent. It initializes parameters, performs forward and backward propagation, updates weights, tracks the cost, and plots the learning curve. The model trains for a specified number of iterations, adjusting parameters to minimize the cost f...
def L_layer_model(X, Y, layers_dims, learning_rate = 0.0075, num_iterations = 3000, print_cost=False, filename='plot.png'): np.random.seed(1) costs = [] # keep track of cost # Parameters initialization. parameters = initialize_parameters_deep(layers_dims) # Loop (gradient descent) for i in...
def get_gfg_login_button(): login_button = browser.find_element('xpath', gfg_login_button_xref) if(login_button.text == "Login"): log.info('GFG login button found...') return login_button def lets_click_and_sleep(reference, t): reference.click() time.sleep(t) def fb_login_handler(): ...
The main task of the code is to handle a login process by locating and clicking a login button, triggering a Facebook login handler, and checking if a skip condition is required. It automates user authentication steps and decision-making for navigation or task execution.
def gfg_login_handler(): gfg_login_button = get_gfg_login_button() lets_click_and_sleep(gfg_login_button, 1) fb_login_handler() check_if_need_to_skip()
def init_main_menu() -> TerminalMenu: """ Returns the TerminalMenu object for Main Menu. Returns: TerminalMenu: A Main Menu object. """ return TerminalMenu( menu_entries=MAIN_MENU_OPTIONS, title=" Main Menu.\n Press Q or Esc to Quit.\n", ...
The function `with_menu()` manages a terminal-based menu system for a program, initializing the main menu and handling user selections to execute specific actions like carb calculations, dose tracking, insulin adjustments, and injection records. It loops until the user exits (selection 6 or None), with error handling f...
def with_menu(): """ Handles the main logic when the program is ran with terminal menu. """ try: main_menu = init_main_menu() except NameError: sys.exit( f"{Colors.FAIL}Your OS is not supported to run the program with the menu.{Colors.ENDC}" ) main_menu_exit =...
def init_carbs_calculation(): """ A function responsible for handling all of the calculation's logic and printing out the result into terminal. """ try: food_input = ask_user_to_input_the_food() response = get_nutrition_analysis(food_input) food_list = get_formatted_food_list(res...
This function processes CLI arguments to execute specific actions: calculates carbs, displays doses, updates insulin doses (validating 'short'/'long' type), views today's injections, or adds new injections, branching based on the provided argument keys.
def without_menu(args: dict): """ Handles the main logic when the program is ran through CLI with arguments. """ if args["calculate"]: init_carbs_calculation() elif args["doses"]: init_show_doses() elif args["update"]: insulin_type = args["<type>"].lower() if insu...
def run_menu(self): """runs pygame menu """ menu = Menu(self.go_to_game, self.set_minesweeper_size, self.surface, self.set_player_name, self.player_name, self.go_to_leaderboard) menu.menu() def change_game_state(self, desired_game_state: int): """changes the g...
The main task of the code is to transition the game to the gameplay state by first checking if the player name is empty, running the menu if necessary, setting the game state to 1, and then switching to the game view through the change_view method.
def go_to_game(self): """changes the game state to one and calls change_view to go to the game view """ if self.player_name == "": self.run_menu() self.change_game_state(1) self.change_view()
def color_frame1(self, frame): """Get the first frame in the video and return the mean color of the face""" face, len_faces, len_profile_faces = self.face_in_image(frame) # call face_in-image function if len_faces > 0 or len_profile_faces > 0: # if there is face in image- return the color ...
The main task of the code is to process a video stream in real-time by capturing, resizing, and analyzing frames for face and color recognition. It updates the GUI with processed frames, adds timestamps, and periodically checks for movement or changes, while maintaining a 1/3-second interval between frame analyses. The...
def video_loop(self): """This function loops over the video stream""" last_frame_time = datetime.datetime.now() # last time a frame was analyzed first_frame = None last_frame = None first_color = None while not self.stop_event.is_set(): # while the app is not closed ...
def resized_image(image, scale = 500): height, width = image.shape[:2] x = scale / width return cv.resize(image, (scale, int(height * x))) def extract_index_nparray(nparray): index = None for num in nparray[0]: index = num break return index def fill_triangle_min(image, blank, ve...
The code processes an image to generate geometric face art using MediaPipe's FaceMesh. It detects facial landmarks, performs Delaunay triangulation, and fills triangles with max/min values based on the 'model' parameter, saving the result as 'geometric_art.jpg'.
def get_face_mesh(img, model, save_dir): mp_face_mesh = mp.solutions.face_mesh img = resized_image(img) height, width = img.shape[:2] with mp_face_mesh.FaceMesh(static_image_mode=True, max_num_faces=2, refine_landmarks=True, ...
def make_bigger_lightning(dimension, start, end, thickness, bend=4): blank = np.zeros(dimension, np.uint8) # from center started point to make 2 left right started point x_center,y_center = start # length of lightning we will make # depth is number lightning zigzag length = dimension[1] - y_cen...
The code generates lightning effects based on the specified mode, creates a mask, applies color and shadow, then saves and displays the resulting image. Different modes produce varied lightning patterns (e.g., bolts, trees). The function uses parameters like color, thickness, and coordinates to customize the effect, ul...
def lightning_effect(save_dir, color, mode, start, end, thickness): blank = np.zeros(_DIMENSION, np.uint8) if mode == 1: mask = make_bigger_lightning(blank.shape[:2], start, end, thickness, 4) elif mode == 2: mask = make_lightning_tree(blank.shape[:2], (150,40), 20, 4) elif mode == 3: ...
def transform_point_cloud(self): raise NotImplementedError( "Updating the source point cloud should be defined in child classes.") def iterate(self): self.expectation() self.maximization() self.iteration += 1 def get_registration_parameters(self): raise NotImplemented...
This code performs iterative point cloud registration until convergence, calling a user-defined callback at each iteration to report progress. It transforms the point cloud, iterates to minimize error, and returns the registered points (TY) along with optimization parameters.
def register(self, callback=lambda **kwargs: None): self.transform_point_cloud() while self.iteration < self.max_iterations and self.diff > self.tolerance: self.iterate() if callable(callback): kwargs = {'iteration': self.iteration, 'erro...
def split_on(self, df, target): # no split if pure subset domain = df[target].unique() if len(domain) == 1: return '' # list attributes to check attrs = (attr for attr in df if attr != target) # find atrribute with hightest information-gain best = m...
The code recursively builds a decision tree by selecting the optimal attribute to split the dataset, partitioning the data into subsets based on attribute values, and creating tree nodes. It constructs a root node with the chosen attribute, then recursively generates child nodes for each subset until the tree is fully ...
def grow(self, df, target): # pick attribute to split attr = self.split_on(df, target) # split data into subsets subsets = self.splits(df, attr) # create tree-node root = Tree(df[target], attr) # add child-nodes root.nodes = {value: self.grow(subset, t...
def select_attr(self, X, Y, n_attrs): # check for single instance if len(X) <= 1: return None, None # check for pure subset if len(Y) in np.sum(Y, axis=0): return None, None # pick attributes to check attrs = np.random.choice(X.shape[1], n_attrs...
This code recursively constructs a decision tree by selecting the optimal attribute and cutoff value to split the dataset, creating a tree node, and recursively building left and right child nodes with subsets of the data until no further attributes remain for splitting.
def grow(self, X, Y, n_attrs): # pick attribute to split attr, cutoff = self.select_attr(X, Y, n_attrs) # split data into subsets X_l, Y_l, X_r, Y_r = self.split(X, Y, attr, cutoff) # grow root node node = Tree(Y, attr, cutoff) # grow child-nodes if at...
def make_img_unit_vectors(w_h, focal): img_pts = make_img_pts(w_h, focal) # add focal as 3rd dimension, units such that f=1 img_pts = np.concatenate([img_pts, np.ones((img_pts.shape[0], 1), dtype=img_pts.dtype)], axis=1) # normalize to put it on r=1 sphere img_pts /= np.linalg.norm(img_pts, axis=1)[:, None] ...
This function converts a panoramic image into a pinhole camera view by transforming unit vectors with given rotation angles, converting them to spherical coordinates, and sampling the panorama accordingly.
def panorama_to_pinhole(panorama_sampler, img_w_h, focal, pitch_yaw_roll_deg): unit_vs = make_img_unit_vectors(img_w_h, focal) # rotate rot_angles_rad = np.deg2rad(np.array(pitch_yaw_roll_deg)) cam_R = R_cam_to_world(*rot_angles_rad) unit_vs_rotated = unit_vs @ cam_R.T # to spherical spherical = unit_vectors...
def make_img_unit_vectors(w_h, focal): img_pts = make_img_pts(w_h, focal) # add focal as 3rd dimension, units such that f=1 img_pts = np.concatenate([img_pts, np.ones((img_pts.shape[0], 1), dtype=img_pts.dtype)], axis=1) # normalize to put it on r=1 sphere img_pts /= np.linalg.norm(img_pts, axis=1)[:, None] ...
This code converts a panoramic image into a pinhole camera depth map by projecting spherical coordinates onto a rotated image plane. It generates unit vectors, applies camera rotation, converts to spherical coordinates, samples the panorama, and reshapes the output to match the input image dimensions.
def panorama_to_pinhole_depth(panorama_sampler, img_w_h, focal, pitch_yaw_roll_deg): unit_vs = make_img_unit_vectors(img_w_h, focal) # rotate rot_angles_rad = np.deg2rad(np.array(pitch_yaw_roll_deg)) cam_R = R_cam_to_world(*rot_angles_rad) unit_vs_rotated = unit_vs @ cam_R.T # to spherical spherical = unit_v...
def get_floor_cloud(depth, floor_mask, camera_mtx): # estimate the floor function camera_mtx_inv = np.linalg.inv(camera_mtx) cloud = [] for i in range(depth.shape[0]): for j in range(depth.shape[1]): if(not floor_mask[i,j] and depth[i,j] > 0.1 and depth[i,j] < 5.0): p...
The function repairs floor depth maps by detecting the floor plane via RANSAC, removing points below the plane, and optionally filling gaps with the plane model to correct depth data. It processes depth values, filters based on a mask, and applies geometric checks to identify and repair invalid floor regions.
def floor_repairment(mvs_depth, mask, camera_mtx, iteration = 100, b_fill = False): # we need to decide : # 1. only delete point under the ground # 2. fill the floor mask with the plane model n_floor = mask.shape[0] * mask.shape[1] - np.sum(mask) if(n_floor < 14000): # too few points in ...
def recv_msg(self): chunk = b"" self.crypto.derived_key = self.crypto.get_derived_key(self.crypto.parameters, self.socket) data_length_bytes = self.socket.recv(4) data_length = int.from_bytes(data_length_bytes, byteorder="big") data_bytes = bytearray() while len(data_byte...
The code defines a network loop (`netloop`) that continuously receives and processes messages. It retrieves cryptographic parameters, listens for incoming messages, unpickles them, and invokes `handle_commands` to process the data. The loop handles connection errors, breaks on empty messages, and sends exceptions back ...
def netloop(self): self.crypto.parameters = self.crypto.get_params(self.socket) while True: try: msg = pickle.loads(self.recv_msg()) except ConnectionResetError: break if not msg: break try...
def pre_handle(self): if self.headers['url'] not in self.pre_handle_urls and \ self.headers['url'] not in self.urls and \ self.headers['url'] not in self.after_handle_urls: self.send_msg("route not right") raise Exception("route not right") if self...
This code handles WebSocket messages by receiving frames, processing opcodes (PING, TEXT, CLOSE), logging heartbeats, routing TEXT messages to URL-specific handlers via threads, and terminating the connection. It ensures thread management based on the class configuration and breaks the loop for unrecognized URLs or clo...
def handle(self): self.pre_handle() while True: frame = self.request.recv(self.recv_len) header, data = self.get_frame_data(frame) if header['opcode'] == OP_PING: logger.debug('heart beat') self.pong() elif header['opcode'] ...
def _get_L(self): """Compute the approximated normalizing factor for Bayes rule. Returns ------- L: list of arrays with shapes (product of variables domain in particular connection, ) The approximated factors needed for the Kullback-Leibler projections """ parame...
This method updates the model's sufficient statistics using current data, handling both single and multi-component mixtures. For multi-component cases, it either parallelizes updates via a multiprocessing pool or uses fsolve for sequential optimization. Single-component cases trigger a full-table update. Finally, it up...
def _update_statistics(self): """Update the sufficient statistics with the current data - self.current_data """ if len(self.variables_connection) > 1: # Updating for a mixture with at least 2 components L = self._get_L() if self.pool is not None: ...
def locate_cell_with_ppr(reduced_pressure): """Locates the cell containing ppr in the csv file Arg: reduced_pressure[float]-> input from user Returns: the found ppr """ target_ppr = truncate_to_one_dp(reduced_pressure) find_ppr = df2["pseudoreduced_pressures"].searchsorted(...
This function computes the unknown SCIV (sukkar&cornel integral value) using linear interpolation. It locates the pseudoreduced pressure (ppr) cell, retrieves adjacent values, calculates an interpolation factor, and applies it to the SCIV of the upper cell, adjusted by a denominator term. The result is derived without ...
def compute_the_value_of_unknown_sciv(reduced_temp, reduced_pressure): """Computes the unknown value of the sciv in the second linear interpolation Locates the cell with ppr and retrieves the values of the cell above and below Handles linear interpolation without recursion Args: reduced_temp[fl...
def print_board(board): print(" "+board[1]+" | "+board[2]+ " | "+board[3]) print("__________") print(" "+board[4]+" | "+board[5]+ " | "+board[6]) print("__________") print(" "+board[7]+" | "+board[8]+ " | "+board[9]) def isBoardFull(board): if board.count(" ")==1: return True def victor...
The main task of the code is to run a Tic-Tac-Toe game where a human player competes against a manual AI. The game initializes a 10-cell board, alternates human and computer moves, checks for victory conditions after each move, and declares a winner or a tie when the board is full.
def main(): global board board = [" " for i in range(10)] print("Welcome to the game of TIC-TAC-TOE Against a manual coded AI \n") print_board(board) while not(isBoardFull(board)): if not victory_check(board,"o"): human_move() else: print("Computer ...
def make_triangle(self: Matrix) -> Matrix: current = 0 for col in range(self.width): for row in range(current + 1, self.height): self.gcd_rows(current, row, col) if self.data[current][col] == 0: continue current += 1 if curr...
This code transforms a matrix into its reduced row echelon form (identity matrix) using Gaussian elimination. It first creates a triangular matrix, then normalizes each row and eliminates off-diagonal elements through row scaling and subtraction operations.
def make_perfect(self: Matrix) -> Matrix: self.make_triangle() for i in range(self.height): for col in range(self.width): if self.data[i][col] == 0: continue self.multiply_row(i, Fraction(1, self.data[i][col])) for j in rang...
def forwardPropagation(self, trainData): self.z = np.dot(trainData, self.W1) self.z2 = sigmoid(self.z) self.z3 = np.dot(self.z2, self.W2) sigma = sigmoid(self.z3) return sigma def backPropagation(self, trainData, trainDataOutput, sigma): self.sigmaError = trainDataOutput ...
The main task of the code is to train a neural network model using mini-batch gradient descent. It iterates over the training data in batches, performing forward and backward propagation for each batch to update model parameters. After each epoch, it calculates the cost using a prediction and appends it to a history li...
def train(self, trainData, trainDataOutput, batch_size=5, epochs=10000): costHistory = [] #sets up our mini batches in batches of 5 for epoch in range(epochs): for i in range(0, len(trainDataOutput), batch_size): sigma = self.forwardPropagation(trainData[i:i+batch_siz...
def drawGrid(): global board, SCALE # Set the size of the grid block for x in range(0, SCALE*size_x, SCALE): for y in range(0, SCALE*size_y, SCALE): rect = pygame.Rect(x, y+2*SCALE, SCALE, SCALE) location = board[int(x/SCALE)][int(y/SCALE)] if location == 0: ...
This code implements a Minesweeper game using Pygame, handling mouse/keyboard inputs for cell interaction, flagging, and AI toggling. It updates the game state, checks win/loss conditions, and renders the grid and statistics, with a main loop for event processing and display updates.
def main(): global SCREEN, CLOCK, SCALE, first_click, mines, size_x, size_y, total_mines, light, lighten, AI_ON SCREEN.fill(BLACK) while True: drawGrid() drawStats() for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() ...
def check_data_available(self, organelleidxlist): 'check whether raw data exists' rawdata_dir = os.path.join(arg.root_dir, arg.data_root_dir) filelist = self.get_filelist(rawdata_dir,[]) filelist = [ file for file in filelist if self.dataid in file.lower()] datapath = '//'.join...
This method generates processed data by checking data availability, creating a directory structure, and preprocessing specific organelle-type data (actin, vesicle, microtubule) if they exist in the input list, followed by a data update verification.
def generate_processed_data(self): self.check_data_available(self.organelletypelist) self.datanewpath = f'{arg.root_dir}/{arg.processed_data_dir}/{self.location}/{self.condition}/{self.dataid}' if not os.path.exists(self.datanewpath): os.makedirs(self.datanewpath) if self.actin...
def dictionary_to_vector(parameters): keys, layer_sizes = [], [] count = 0 params_keys = list(parameters.keys()) # print(params_keys) for key in params_keys: if key[0]=="W": layer_sizes.append(parameters[key].shape[1]) new_vector = np.reshape(parameters[key], (-1,1)) ...
The function `gradients_check` verifies the correctness of backpropagation by comparing analytically computed gradients with numerically approximated gradients. It perturbs each parameter slightly, computes the cost with these perturbations, and approximates gradients using finite differences. It then calculates the re...
def gradients_check(parameters, gradients, X, Y, epsilon = 1e-7, print_msg=False): parameters_values, cache = dictionary_to_vector(parameters) keys, params_keys, layer_sizes = cache grad = gradients_to_vector(gradients, params_keys) num_parameters = parameters_values.shape[0] J_plus = np.zeros((num...
def initialize_with_zeros(self, dim): """ This function initializes a vector zeros of shape (dim, 1) for w and 0 for b Arguments: dim -- the first dimension of b which is the number of parameters in X Return: w -- initialized vector w of shape (dim, 1) and b -- initialized scalar. ...
The code implements a logistic regression model by initializing parameters, optimizing them via gradient descent, predicting labels on training/test data, and returning a dictionary with model parameters, costs, and accuracy metrics.
def model(self, X_train, Y_train, X_test, Y_test, num_iterations=2000, learning_rate = 0.005, print_cost=False): """ This function calls the above implemented functions to build a logistic regression model. Arguments: X_train -- training data of size (num_px*num_px*3, number of ...
def initialize_parameters_deep(self, layer_sizes): """ This function initialize weights and bias paramters for deep learning algorithm. Arguments: -- layer_sizes: a list of array that contains the size of all the layers (including the input layer n_x or n_0) Return: ...
The main task of the code is to train a deep neural network using gradient descent. It iterates for a specified number of times, performing forward propagation, computing cost, backward propagation, and parameter updates. It tracks costs at intervals and returns the learned parameters and cost history for monitoring tr...
def fit(self, num_iterations, learning_rate, print_cost = False): """ This function aims to combine all the functions we have built earlier to make a deep neural networks model. Arguments: -- num_interations: an integer number of iterations we want to train the parameters. ...
def L_forward(X, parameters): L = len(parameters)//2 # Each layer contain 2 parameters Wi and bi in parameters dictionary A = X caches = [] """ From layer 1 to L-1, we want to use relu activation function. To compute AL, output layer, we use sigmoid activation function """ ## No dropout...
The function `deep_neural_net_opt` trains a deep neural network using forward and backward propagation, supporting various initialization methods (zeros, random, Xavier, He) and regularization techniques (L2, dropout). It iteratively computes the cost, gradients, and updates parameters with the specified learning rate....
def deep_neural_net_opt(X, Y, initialization, layer_sizes, learning_rate=0.075, num_iterations=300, lambd=0.0, keep_prob = 1.0, dropout_layers = None,random_scaled= None, xavier_option = None, print_cost = False, grad_check=False): """ Step 1: Initializae param...
def debugInitializeWeights(fan_out, fan_in): W = np.sin(np.arange(1, fan_out * (1 + fan_in) + 1)).reshape((fan_out, 1 + fan_in)) / 10 return W def nnCostFunction(nn_params, input_layer_size, hidden_layer_size, num_labels, X, y, lambda_): Theta1 = nn_params[:hidden_layer_size * (input_layer_size + 1)].reshap...
The code checks the correctness of a neural network's backpropagation implementation by comparing numerical and analytical gradients. It initializes a neural network with predefined parameters, computes gradients via the cost function and numerical approximation, then prints their difference. A small relative differenc...
def checkNNGradients(lambda_=0): input_layer_size = 3 hidden_layer_size = 5 num_labels = 3 m = 5 Theta1 = debugInitializeWeights(hidden_layer_size, input_layer_size) Theta2 = debugInitializeWeights(num_labels, hidden_layer_size) X = debugInitializeWeights(m, input_layer_size - 1) y = 1 +...
def len(self): return len(self.content) def float2code(num): exponent = 0 signExp = '-' while num % 1: exponent -= 1 num *= 16 if exponent == 0 and num < 2**16: return int2code(int(num)) while num % 16 == 0: exponent += 1 num /= 16 if exponent == 0: return int2code(int(num)) elif exponent < 0: si...
This code adds two objects by converting their tokens to floats, summing corresponding values, converting back to code format, and concatenating results. It processes tokens iteratively until one object is exhausted, then appends remaining content. The final result is a new Cell containing the combined string represent...
def add(self, other): sum = '' while self.len() > 0 and other.len() > 0: sum = sum + float2code(code2float(self.getToken()) + code2float(other.getToken())) + ' ' sum = sum + self.content + other.content return Cell(sum.strip())
def error(msg): global ep pos = ep.position code = ep.id if code == '': code = 'main' if code == '.': #print("error in error handler") pass elif storage.exists('.'): addressstack.push(Cell(ep.toCode())) # place return address on the address stack ep = ExecutionPointer('.') # execute custom error handler...
This code initializes a time object by either parsing a date string with a specific format and converting it to a numeric code, or converting a numeric code back to a datetime. It handles errors by setting default values, ensuring valid date-time conversions and code representations.
def __init__(self, code = '', timeText = ''): self.code = code if timeText: # parse date from string format = Cell(timeFormat) time = Cell(timeText) year = month = day = 1 hour = minute = second = 0 while format.len(): token = format.getToken() value = '' if time.len(): value = time....
def create_railyard(in_file): """ This function creates a list that represents the railyard. :param in_file: string, the name of railyard txt file. :return: list that represent railyard Pre-conditions: None """ try: in_file = open(in_file, 'r') railyard = [] for l...
The code simulates a railyard operation by processing user commands to move cars between tracks, validating inputs, updating the railyard state, and displaying changes. It reads a yard file, processes commands like 'move' or 'depart', checks command validity, and continues until the user quits or no locomotives remain....
def main(): print('Please give the yard file:') in_file = input() railyard = create_railyard(in_file) # We go further only if the yard file exists. if railyard != 'no file': rail_printer(railyard) go_on = True locomotive = 1 # used to know when there is no loc lef. ...
def process_maze(): """ This function reads a text file holding a maze. It processes maze. If the maze meets the criteria, the function returns True as well as a list of tuples representing maze and its 2-D list copy. :return: Boolean: shows if the maze is found and meets the criteria. ...
The main task of the code is to solve a maze by processing its structure, constructing a tree representation, searching for a path through the tree, and executing a command using the maze data and found path. It involves validating the maze format, generating cell coordinates, building a tree, performing a search algor...
def main(): # check the format of maze and convert it into a list. go_on, maze, maze_copy = process_maze() if go_on: cells, x, y = get_cells(maze) root = build_tree(x, y, maze_copy) path = [] # will hold the solution path search_tree(root, path) process_command(maz...
def create_dict(): """ The function reads a text file and creates a dictionary. It matches word with its pronunciations. :return: dictionary that matches word with pronunciations. Pre condition: The format of the word and pronunciation is: 'WORD PRONUNCIATION'. """ in_file = input("Dic...
The code processes a list of words to analyze their pronunciations against specific criteria. For each meaningful word, it checks valid pronunciations, applies conditions to filter matches, aggregates results, and determines output. If a word lacks pronunciation data, it handles the error by notifying the user. The cor...
def main(): pronunciaton_dict = create_dict() words_lst = get_words() for word in words_lst: if is_word_meaningful(word): try: match_dict_general = {} # ultimate rhyme dictionary true_list = [] # use to see if any pronun. works. for p...
def settingsFile(): # global settings file globalSettingsFolder = settingsFolder() globalSettingsFile = os.path.join(globalSettingsFolder, 'global_settings.p') return globalSettingsFile def resetLastDetectedFpsFile(): globalLastFps = settingsLastFpsFile() # default settings fsSettings = {}...
The function `resetSettingsFile` initializes default configuration settings, including platform detection and key mappings, then writes these defaults to a global settings file using `pickle`. It also triggers resets for related files like last detected FPS, frequency changes, auto-sync, and service config, ensuring a ...
def resetSettingsFile(): globalSettingsFile = settingsFile() # default settings fsSettings = {} # platform fsSettings['osPlatform'] = 'unknown' # key mapping fsSettings['radio60hz'] = False fsSettings['radio50hz'] = False fsSettings['radio30hz'] = False fsSettings['radio25hz'...
def loadServiceConfig(): globalServiceConfig = settingsServiceConfigFile() # read settings file try: with open(globalServiceConfig, 'rb') as settingsFileHandle: fsSettings = pickle.load(settingsFileHandle) # service config fsconfig.radioOnPlayStop60 = fsSettin...
The main task of the code is to load configuration settings from a pickle file into the `fsconfig` module, including platform-specific settings, radio/key mappings, and status configurations. It handles potential file loading errors, initializes auto-sync settings, and sets a service flag, returning a status indicating...
def loadSettings(): # load service configuration (first to allow for fsmsg debugging) loadServiceConfig() globalSettingsFile = settingsFile() # read settings file try: with open(globalSettingsFile, 'rb') as settingsFileHandle: fsSettings = pickle.load(settingsFileHandle) ...
def settingsFile(): # global settings file globalSettingsFolder = settingsFolder() globalSettingsFile = os.path.join(globalSettingsFolder, 'global_settings.p') return globalSettingsFile def saveAutoSyncSettings(): globalAutoSync = settingsAutoSyncFile() fsSettings = {} # auto-set configur...
The function `saveSettings` saves configuration parameters (os platform, radio/key mappings, statuses, and resolution) from `fsconfig` into a global settings file using `pickle`. It handles exceptions during file writing, updates auto-sync and service configurations, and adjusts a service flag based on `radioOnPlayStar...
def saveSettings(): globalSettingsFile = settingsFile() fsSettings = {} # platform fsSettings['osPlatform'] = fsconfig.osPlatform # key mapping fsSettings['radio60hz'] = fsconfig.radio60hz fsSettings['radio50hz'] = fsconfig.radio50hz fsSettings['radio30hz'] = fsconfig.radio30hz f...
def get_inds(labels, k): return np.argwhere(labels == k).reshape((-1,)) def between_clust_dist(X_1, X_2, type='1'): if type not in ['1']: raise ValueError('invalid distance type') deltas = [] for i in range(len(X_1)): for j in range(len(X_2)): deltas += [ np.linalg.norm(X_1[...
The function `XieBeniIndex` calculates the **Xie-Beni cluster validity index** for a clustering result. It computes the ratio of the **within-group sum of squares (WGSS)** to the product of the **minimum between-cluster distance** and the total number of data points. This index evaluates clustering quality by balancing...
def XieBeniIndex(X, labels, K=None): if K is None: K = len(np.unique(labels)) min_deltas = [] for i in range(K): inds_i = get_inds(labels, i) X_i = X[inds_i].copy() for j in range(i + 1, K): inds_j = get_inds(labels, j) X_j = X[inds_j].copy() ...
def closure(I): # This function calculates the closure of the set of items I for production, a in I: # This means that the dot is at the end and can be ignored if production.endswith("."): continue lhs, rhs = production.split('->') alpha, B_beta = rhs.split('.') ...
This function constructs a set of LR parser states using closure and goto operations. It starts with an initial state 'I0', iteratively generates new states by applying shifts, and stores them in a dictionary. If 'display' is True, it outputs all states to 'States.txt'. The main task is to build the canonical collectio...
def set_of_items(display=False): # Function to construct the set of items num_states = 1 states = ['I0'] items = {'I0': closure([('P->.S', '$')])} for I in states: for X in pending_shifts(items[I]): goto_I_X = goto(items[I], X) if len(goto_I_X) > 0 and goto_I_X not i...
def set_of_items(display=False): # Function to construct the set of items num_states = 1 states = ['I0'] items = {'I0': closure([('P->.S', '$')])} for I in states: for X in pending_shifts(items[I]): goto_I_X = goto(items[I], X) if len(goto_I_X) > 0 and goto_I_X not i...
The main task of the code is to construct the CLR parsing tables (ACTION and GOTO) for a given grammar. It processes LR(1) item sets to populate shift/reduce actions and state transitions, handling terminals via ACTION and non-terminals via GOTO, while marking "Accept" for the start symbol. The result is a clean DataFr...
def CLR_construction(num_states): # Function that returns the CLR Parsing Table function ACTION and GOTO C = set_of_items() # Construct collection of sets of LR(1) items # Initialize two tables for ACTION and GOTO respectively ACTION = pd.DataFrame(columns=list(terminals), index=range(num_states)) ...
def get_currencies(url): page = requests.get(url) if page.status_code != 200: print(f"{page.content}\nUsing saved rates from the past") return get_past_rates() live_data = get_live_rates(page) if live_data is None: return None save_current_rates(live_data, config.DATA_FI...
The main task of the code is to parse command-line arguments for currency conversion, fetch exchange rates from a URL, and convert a specified amount from one currency to multiple target currencies, displaying the results with rounded values. It supports listing all available EUR exchange rates or performing conversion...
def main(): # Has to be improved parser = argparse.ArgumentParser() parser.add_argument("--list", "-l", help="Display all availible exchange rates from EUR", action="store_true") parser.add_argument("--amount", "-n", type=int, nargs=1, help="Amount of from_currency to convert") parser.add_argum...
def parse_args(): """Parse arguments""" parser = argparse.ArgumentParser(description='Give arguments for running the classifier.') parser.add_argument('--phase', type=str, default='dev', help='Specify dev, test or all phase') parser.add_argument('--dates', type=bool, default=False, help='Predict the fut...
The main task of the code is to execute a text classification pipeline for multiple topics, using word embeddings (CBOW/Skip-gram) and machine learning models (LinearSVC). It processes training/test data, balances labels, runs baseline classifiers, and evaluates models with specific embeddings per topic. The script han...
def main(): """Main function that adds everything together. Some function calls are commented out when they were not used the last time the program was run.""" args = parse_args() if args.topic == 'all': topics = ['afrekening_servicekosten', 'gebreken', 'melding', 'punten', 'toetsing', 'woningve...
def parse_args(): """Parse arguments""" parser = argparse.ArgumentParser(description='Give arguments for running the classifier.') parser.add_argument('--phase', type=str, default='dev', help='Specify dev or test phase') parser.add_argument('--dates', type=bool, default=False, help='Predict the future')...
The main task of the code is to process text data for multiple topics using word embeddings (e.g., CBOW 300D) to perform regression experiments. It loads training/test data, extracts features, and evaluates models (e.g., ablation studies, baselines) based on command-line arguments specifying topics, phases (train/test/...
def main(): """Main function to bring everything together. Function calls are sometimes commented if they were not used the last time we ran the experiment.""" args = parse_args() if args.topic == 'all': topics = ['afrekening_servicekosten', 'gebreken', 'melding', 'punten', 'toetsing', 'woningve...
def _get_all_src_tables(self): logging.info('get all tables on src db') tables = self._engine_src.table_names() logging.info(tables) return tables def _drop_dest_tables(self, tables: list): logging.info('drop the specified tables on dest db') for one_table in tables: ...
The code's main task is to copy data from source to destination tables. If no tables are specified, it retrieves all source tables. It then drops existing destination tables, sets up new ones, and copies the data. This ensures the destination database is properly prepared and synchronized with the source.
def run(self, tables: list = None): ''' if tables is none, it means coping all tables ''' if not tables: tables = self._get_all_src_tables() self._drop_dest_tables(tables) self._setup_dest_tables(tables) self._copy_tables(tables)
def _print_coordinate(self): x, y = self._pointer_coordinates print(f"{x}{'+' if y >=0 else ''}{y}j") def _show_julia(self): if isinstance(self.welt, MandelbrotWelt): x, y = self._pointer_coordinates c = x + y * 1j print(c) self._welt = JuliaWelt(s...
This code defines a method that handles keyboard events, triggering specific actions based on the pressed key: 'c' prints coordinates, 'j' displays the Julia set, 'm' shows the Mandelbrot set, and 's' saves the current image. Its main task is to map keyboard inputs to fractal visualization or data-saving operations in ...
def _key_pressed(self, event): if event.char.lower() == "c": self._print_coordinate() if event.char.lower() == "j": self._show_julia() if event.char.lower() == "m": self._show_mandelbrot() if event.char.lower() == "s": self._save_image()
def rename_xml_files(annotdir): if os.path.isdir(annotdir): all_files = os.listdir(annotdir) annotations = [x for x in all_files if ".json" in x or ".xml" in x] for a in range(len(annotations)): annotation = annotations[a] if annotation.endswith(".xml"): ...
The function prepares datasets by randomly splitting images and annotations into train/val/test subsets based on specified ratios and initial data size. It renames XML files, verifies dataset splits, checks for existing JSON files, and converts annotations to JSON format for each subset, ensuring proper data organizati...
def prepare_all_dataset_randomly(rootdir, imgdir, classes, train_val_test_split, initial_datasize): rename_xml_files(imgdir) images, annotations = list_files(imgdir) print("{:d} images found!".format(len(images))) print("{:d} annotations found!".format(len(annotations))) datasets, names = split_dat...
def rename_xml_files(annotdir): if os.path.isdir(annotdir): all_files = os.listdir(annotdir) annotations = [x for x in all_files if ".json" in x or ".xml" in x] for a in range(len(annotations)): annotation = annotations[a] if annotation.endswith(".xml"): ...
This function prepares a complete dataset by processing training, validation, and test directories. It renames XML files, matches images with annotations, writes files, checks JSON presence, and generates JSON files for each dataset type. The goal is to organize images and annotations into structured formats for machin...
def prepare_complete_dataset(rootdir, classes, traindir, valdir, testdir): try: for imgdir, name in zip([traindir, valdir, testdir], ['train', 'val', 'test']): print("") print("Processing {:s}-dataset: {:s}".format(name, imgdir)) rename_xml_files(imgdir) image...
def rename_xml_files(annotdir): if os.path.isdir(annotdir): all_files = os.listdir(annotdir) annotations = [x for x in all_files if ".json" in x or ".xml" in x] for a in range(len(annotations)): annotation = annotations[a] if annotation.endswith(".xml"): ...
The main task of the code is to prepare initial datasets for training, validation, and test sets by randomly sampling images and annotations from specified directories. It handles incremental learning by filtering subfolders, generates JSON files for dataset structure, and writes sampled data to files. The function ens...
def prepare_initial_dataset_randomly(config): try: for imgdir, name, init_ds, group in zip([config['traindir'], config['valdir'], config['testdir']], ['train', 'val', 'test'], [config['initial_datasize'], 0, 0], [False, config["group_val_test_set"], config["group_val_test_set"]]): print("") ...
def rename_xml_files(annotdir): if os.path.isdir(annotdir): all_files = os.listdir(annotdir) annotations = [x for x in all_files if ".json" in x or ".xml" in x] for a in range(len(annotations)): annotation = annotations[a] if annotation.endswith(".xml"): ...
The main task of the code is to prepare initial datasets by processing image and annotation files. It iterates through specified directories, renames XML files, lists images/annotations, writes files to a data root, and generates JSON files for training, validation, and test sets. The function handles exceptions and en...
def prepare_initial_dataset(config): try: for i, (imgdir, name) in enumerate(zip([config['traindir'], config['initial_train_dir'], config['valdir'], config['testdir']], ['train', 'initial_train', 'val', 'test'])): print("") print("Processing {:s}-dataset: {:s}".format(name, imgdir)) ...
def rename_xml_files(annotdir): if os.path.isdir(annotdir): all_files = os.listdir(annotdir) annotations = [x for x in all_files if ".json" in x or ".xml" in x] for a in range(len(annotations)): annotation = annotations[a] if annotation.endswith(".xml"): ...
This function prepares initial datasets for training, validation, and test sets by processing image/annotation files. It renames XML files, lists images/annotations, filters data based on incremental learning flags, and generates JSON files. It handles group settings, subfolder filtering, and writes results to specifie...
def prepare_initial_dataset_from_list(config, train_list): try: for imgdir, name, group in zip([config['traindir'], config['valdir'], config['testdir']], ['train', 'val', 'test'], [False, config["group_val_test_set"], config["group_val_test_set"]]): print("") rename_xml_files(imgdir)...
def rename_xml_files(annotdir): if os.path.isdir(annotdir): all_files = os.listdir(annotdir) annotations = [x for x in all_files if ".json" in x or ".xml" in x] for a in range(len(annotations)): annotation = annotations[a] if annotation.endswith(".xml"): ...
The function updates training datasets by processing image directories, renaming XML files, listing images/annotations, checking JSON existence, and generating JSON annotations. It handles incremental learning by including validation/test sets when enabled, ensuring data consistency for model training.
def update_train_dataset(config, cfg, train_list, val_list, test_list): try: if config['incremental_learning']: dirlist = [config['traindir'], config['valdir'], config['testdir']] namelist = ['train', 'val', 'test'] filelist = [train_list, val_list, test_list] els...
def resetStats(self): self.stats = { "Data points": 0 } def loadZIPData(self, file_name, date_range): """ Load Google location data from a "takeout-*.zip" file. """ from bs4 import BeautifulSoup """ <div class="service_name"> <h1 cl...
The main task of the code is to process input data files (Google location data or ZIP archives), generate a heatmap based on specified settings, and save the resulting map to an output file. It handles multiple file formats, applies date ranges, streams data if enabled, and tracks processing statistics for output.
def run(self, data_files, output_file, date_range, stream_data, settings): print(data_files) """Load the data, generate the heatmap and save it. Arguments: data_files {list} -- List of names of the data files with the Google location data or the Google takeout ZIP ar...
def _key_write(self) -> None: """Write keys to container from the relation data.""" if self.unit.is_leader(): return keys = self.cluster.get_keys() if not keys: logger.debug('"key_repository" not in relation data yet...') return for key_reposi...
The function manages Fernet key rotation by writing existing keys to disk, checking if the unit is the leader, setting up keys if none exist, and then rotating and synchronizing them across the cluster to ensure secure encryption key management.
def _handle_fernet_key_rotation(self) -> None: """Handles fernet key rotation. First, the function writes the existing keys in the relation to disk. Then, if the unit is the leader, checks if the keys should be rotated or not. """ self._key_write() if self.unit.i...
def saySomething(phrase): print('Engine says...', phrase) pushGUITask('SHOW_TEXT', text=phrase) engine.say(phrase) engine.runAndWait() def pushGUITask(task_name, **kwargs): gui_pending_tasks.append((task_name, kwargs)) def handleFailure(): saySomething('Unexpected error occured! Please try again...
This function captures user voice input via a microphone, processes it using Google's speech recognition, and returns the transcribed text. It adjusts for ambient noise, allows customization of output formatting (e.g., removing spaces, lowercasing), confirms input if enabled, and handles errors with optional retry logi...
def getUserInput(stmt, confirm_input=True, doNotRetry=False, remove_spaces=False, to_lower_case=False): with sr.Microphone() as source: recognizer.adjust_for_ambient_noise(source, duration=1) if (stmt): saySomething(stmt) print('Listening...') pushGUITask('MIC_ENABLED') ...
def parseEmail(data): for response_part in data: if isinstance(response_part, tuple): return email.message_from_bytes(response_part[1]) def getUserInput(stmt, confirm_input=True, doNotRetry=False, remove_spaces=False, to_lower_case=False): with sr.Microphone() as source: recognizer.a...
This function searches the email inbox for messages in the "Primary" category, checks each email's sender against a given email ID, and returns the first matching email after user confirmation. It processes emails in batches, prompting the user to continue searching if no match is found, and returns "canceled" if the u...
def getMailDetailsByEmailId(emailId): global receive_mail_conn receive_mail_conn.select('INBOX') category = "Primary" status, response = receive_mail_conn.uid('search', 'X-GM-RAW "category:' + category + '"') response = response[0].decode('utf-8').split() response.reverse() mail_checked = 0 ...
def getUserInput(stmt, confirm_input=True, doNotRetry=False, remove_spaces=False, to_lower_case=False): with sr.Microphone() as source: recognizer.adjust_for_ambient_noise(source, duration=1) if (stmt): saySomething(stmt) print('Listening...') pushGUITask('MIC_ENABLED') ...
This function composes and sends an email via Gmail. It collects the recipient's email (with @gmail.com added), subject, and body through user input, requiring confirmation at each step. If confirmed, it creates an HTML-formatted email using MIMEMultipart, attaches the body, and sends it via sendMail. Cancellation at a...
def composeMail(): global emailId receipient = getUserInput('Please provide the receipient\'s email address.', remove_spaces=True, to_lower_case=True) receipient +='@gmail.com' confirmation = getUserInput('Do you want to continue?') if(confirmation == 'yes'): saySomething('Proceeding to next...
def saySomething(phrase): print('Engine says...', phrase) pushGUITask('SHOW_TEXT', text=phrase) engine.say(phrase) engine.runAndWait() def getMails(skip=0, limit=OFFSET): global receive_mail_conn receive_mail_conn.select('INBOX') category = "Primary" status, response = receive_mail_conn....
The function retrieves and displays emails from an inbox in batches, allowing users to read more emails, attempt to open a specific email (redirected to another function), navigate back, or quit. It uses a loop to handle user choices, incrementally loading additional emails by adjusting the skip parameter.
def readMailFromInbox(): saySomething("Please wait while we load your mails from the inbox.") skip = 0 mails = getMails(skip) saySomething("Here are the latest " + str(OFFSET) + " mails from your inbox.") readMails(mails) options = [ 'Read More', 'Open Mail', 'Go Back' ...