Search is not available for this dataset
text
stringlengths
75
104k
def __cluster_distance(self, cluster1, cluster2): """! @brief Calculate minimal distance between clusters using representative points. @param[in] cluster1 (cure_cluster): The first cluster. @param[in] cluster2 (cure_cluster): The second cluster. @return (...
def allocate_observation_matrix(self): """! @brief Allocates observation matrix in line with output dynamic of the network. @details Matrix where state of each neuron is denoted by zero/one in line with Heaviside function on each iteration. @return (list) Observation matrix...
def __allocate_neuron_patterns(self, start_iteration, stop_iteration): """! @brief Allocates observation transposed matrix of neurons that is limited by specified periods of simulation. @details Matrix where state of each neuron is denoted by zero/one in line with Heaviside function on each i...
def allocate_sync_ensembles(self, steps): """! @brief Allocate clusters in line with ensembles of synchronous neurons where each synchronous ensemble corresponds to only one cluster. @param[in] steps (double): Amount of steps from the end that is used for analysis. During spe...
def show_dynamic_matrix(cnn_output_dynamic): """! @brief Shows output dynamic as matrix in grey colors. @details This type of visualization is convenient for observing allocated clusters. @param[in] cnn_output_dynamic (cnn_dynamic): Output dynamic of the chaotic neural netw...
def show_observation_matrix(cnn_output_dynamic): """! @brief Shows observation matrix as black/white blocks. @details This type of visualization is convenient for observing allocated clusters. @param[in] cnn_output_dynamic (cnn_dynamic): Output dynamic of the chaotic neural...
def simulate(self, steps, stimulus): """! @brief Simulates chaotic neural network with extrnal stimulus during specified steps. @details Stimulus are considered as a coordinates of neurons and in line with that weights are initialized. @param[in] steps (ui...
def __calculate_states(self): """! @brief Calculates new state of each neuron. @detail There is no any assignment. @return (list) Returns new states (output). """ output = [ 0.0 for _ in range(self.__num_osc) ] for i ...
def __neuron_evolution(self, index): """! @brief Calculates state of the neuron with specified index. @param[in] index (uint): Index of neuron in the network. @return (double) New output of the specified neuron. """ value = 0.0 ...
def __create_weights(self, stimulus): """! @brief Create weights between neurons in line with stimulus. @param[in] stimulus (list): External stimulus for the chaotic neural network. """ self.__average_distance = average_neighbor_distance(stimulu...
def __create_weights_all_to_all(self, stimulus): """! @brief Create weight all-to-all structure between neurons in line with stimulus. @param[in] stimulus (list): External stimulus for the chaotic neural network. """ for i in range(len(stimulus)...
def __create_weights_delaunay_triangulation(self, stimulus): """! @brief Create weight Denlauny triangulation structure between neurons in line with stimulus. @param[in] stimulus (list): External stimulus for the chaotic neural network. """ poin...
def __calculate_weight(self, stimulus1, stimulus2): """! @brief Calculate weight between neurons that have external stimulus1 and stimulus2. @param[in] stimulus1 (list): External stimulus of the first neuron. @param[in] stimulus2 (list): External stimulus of the second neur...
def show_network(self): """! @brief Shows structure of the network: neurons and connections between them. """ dimension = len(self.__location[0]) if (dimension != 3) and (dimension != 2): raise NameError('Network that is located in different ...
def __create_surface(self, dimension): """! @brief Prepares surface for showing network structure in line with specified dimension. @param[in] dimension (uint): Dimension of processed data (external stimulus). @return (tuple) Description of surface for drawing net...
def show_pattern(syncpr_output_dynamic, image_height, image_width): """! @brief Displays evolution of phase oscillators as set of patterns where the last one means final result of recognition. @param[in] syncpr_output_dynamic (syncpr_dynamic): Output dynamic of a syncpr network. ...
def animate_pattern_recognition(syncpr_output_dynamic, image_height, image_width, animation_velocity = 75, title = None, save_movie = None): """! @brief Shows animation of pattern recognition process that has been preformed by the oscillatory network. @param[in] syncpr_output_dynamic (s...
def __show_pattern(ax_handle, syncpr_output_dynamic, image_height, image_width, iteration): """! @brief Draws pattern on specified ax. @param[in] ax_handle (Axis): Axis where pattern should be drawn. @param[in] syncpr_output_dynamic (syncpr_dynamic): Output dynamic of a syncpr n...
def train(self, samples): """! @brief Trains syncpr network using Hebbian rule for adjusting strength of connections between oscillators during training. @param[in] samples (list): list of patterns where each pattern is represented by list of features that are equal to [-1; 1]. ...
def simulate_dynamic(self, pattern, order = 0.998, solution = solve_type.RK4, collect_dynamic = False, step = 0.1, int_step = 0.01, threshold_changes = 0.0000001): """! @brief Performs dynamic simulation of the network until stop condition is not reached. @details In other words network performs...
def simulate_static(self, steps, time, pattern, solution = solve_type.FAST, collect_dynamic = False): """! @brief Performs static simulation of syncpr oscillatory network. @details In other words network performs pattern recognition during simulation. @param[in] steps (uint): Nu...
def memory_order(self, pattern): """! @brief Calculates function of the memorized pattern. @details Throws exception if length of pattern is not equal to size of the network or if it consists feature with value that are not equal to [-1; 1]. @param[in] pattern (list): Pattern fo...
def __calculate_memory_order(self, pattern): """! @brief Calculates function of the memorized pattern without any pattern validation. @param[in] pattern (list): Pattern for recognition represented by list of features that are equal to [-1; 1]. @return (double) Order of ...
def _phase_kuramoto(self, teta, t, argv): """! @brief Returns result of phase calculation for specified oscillator in the network. @param[in] teta (double): Phase of the oscillator that is differentiated. @param[in] t (double): Current time of simulation. @param[in] argv...
def __validate_pattern(self, pattern): """! @brief Validates pattern. @details Throws exception if length of pattern is not equal to size of the network or if it consists feature with value that are not equal to [-1; 1]. @param[in] pattern (list): Pattern for recognition represe...
def process(self): """! @brief Performs cluster analysis in line with rules of K-Medians algorithm. @return (kmedians) Returns itself (K-Medians instance). @remark Results of clustering can be obtained using corresponding get methods. @see get_clusters() ...
def __update_clusters(self): """! @brief Calculate Manhattan distance to each point from the each cluster. @details Nearest points are captured by according clusters and as a result clusters are updated. @return (list) updated clusters as list of clusters where each cluste...
def __update_medians(self): """! @brief Calculate medians of clusters in line with contained objects. @return (list) list of medians for current number of clusters. """ medians = [[] for i in range(len(self.__clusters))] for...
def cleanup_old_versions( src, keep_last_versions, config_file='config.yaml', profile_name=None, ): """Deletes old deployed versions of the function in AWS Lambda. Won't delete $Latest and any aliased version :param str src: The path to your Lambda ready project (folder must contain a vali...
def deploy( src, requirements=None, local_package=None, config_file='config.yaml', profile_name=None, preserve_vpc=False ): """Deploys a new function to AWS Lambda. :param str src: The path to your Lambda ready project (folder must contain a valid config.yaml and handler...
def deploy_s3( src, requirements=None, local_package=None, config_file='config.yaml', profile_name=None, preserve_vpc=False ): """Deploys a new function via AWS S3. :param str src: The path to your Lambda ready project (folder must contain a valid config.yaml and handler module (e.g...
def upload( src, requirements=None, local_package=None, config_file='config.yaml', profile_name=None, ): """Uploads a new function to AWS S3. :param str src: The path to your Lambda ready project (folder must contain a valid config.yaml and handler module (e.g.: service.py). ...
def invoke( src, event_file='event.json', config_file='config.yaml', profile_name=None, verbose=False, ): """Simulates a call to your function. :param str src: The path to your Lambda ready project (folder must contain a valid config.yaml and handler module (e.g.: service.py). :...
def init(src, minimal=False): """Copies template files to a given directory. :param str src: The path to output the template lambda project files. :param bool minimal: Minimal possible template files (excludes event.json). """ templates_path = os.path.join( os.path.dirname(...
def build( src, requirements=None, local_package=None, config_file='config.yaml', profile_name=None, ): """Builds the file bundle. :param str src: The path to your Lambda ready project (folder must contain a valid config.yaml and handler module (e.g.: service.py). :param str local_pa...
def get_callable_handler_function(src, handler): """Tranlate a string of the form "module.function" into a callable function. :param str src: The path to your Lambda project containing a valid handler file. :param str handler: A dot delimited string representing the `<module>.<function name...
def _install_packages(path, packages): """Install all packages listed to the target directory. Ignores any package that includes Python itself and python-lambda as well since its only needed for deploying and not running the code :param str path: Path to copy installed pip packages to. :pa...
def pip_install_to_target(path, requirements=None, local_package=None): """For a given active virtualenv, gather all installed pip packages then copy (re-install) them to the path provided. :param str path: Path to copy installed pip packages to. :param str requirements: If set, only th...
def get_role_name(region, account_id, role): """Shortcut to insert the `account_id` and `role` into the iam string.""" prefix = ARN_PREFIXES.get(region, 'aws') return 'arn:{0}:iam::{1}:role/{2}'.format(prefix, account_id, role)
def get_account_id( profile_name, aws_access_key_id, aws_secret_access_key, region=None, ): """Query STS for a users' account_id""" client = get_client( 'sts', profile_name, aws_access_key_id, aws_secret_access_key, region, ) return client.get_caller_identity().get('Account')
def get_client( client, profile_name, aws_access_key_id, aws_secret_access_key, region=None, ): """Shortcut for getting an initialized instance of the boto3 client.""" boto3.setup_default_session( profile_name=profile_name, aws_access_key_id=aws_access_key_id, aws_secret_access_...
def create_function(cfg, path_to_zip_file, use_s3=False, s3_file=None): """Register and upload a function to AWS Lambda.""" print('Creating your new Lambda function') byte_stream = read(path_to_zip_file, binary_file=True) profile_name = cfg.get('profile') aws_access_key_id = cfg.get('aws_access_key...
def update_function( cfg, path_to_zip_file, existing_cfg, use_s3=False, s3_file=None, preserve_vpc=False ): """Updates the code of an existing Lambda function""" print('Updating your Lambda function') byte_stream = read(path_to_zip_file, binary_file=True) profile_name = cfg.get('profile') a...
def upload_s3(cfg, path_to_zip_file, *use_s3): """Upload a function to AWS S3.""" print('Uploading your new Lambda function') profile_name = cfg.get('profile') aws_access_key_id = cfg.get('aws_access_key_id') aws_secret_access_key = cfg.get('aws_secret_access_key') client = get_client( ...
def get_function_config(cfg): """Check whether a function exists or not and return its config""" function_name = cfg.get('function_name') profile_name = cfg.get('profile') aws_access_key_id = cfg.get('aws_access_key_id') aws_secret_access_key = cfg.get('aws_secret_access_key') client = get_clie...
def cached_download(url, name): """Download the data at a URL, and cache it under the given name. The file is stored under `pyav/test` with the given name in the directory :envvar:`PYAV_TESTDATA_DIR`, or the first that is writeable of: - the current virtualenv - ``/usr/local/share`` - ``/usr/...
def fate(name): """Download and return a path to a sample from the FFmpeg test suite. Data is handled by :func:`cached_download`. See the `FFmpeg Automated Test Environment <https://www.ffmpeg.org/fate.html>`_ """ return cached_download('http://fate.ffmpeg.org/fate-suite/' + name, ...
def curated(name): """Download and return a path to a sample that is curated by the PyAV developers. Data is handled by :func:`cached_download`. """ return cached_download('https://docs.mikeboers.com/pyav/samples/' + name, os.path.join('pyav-curated', name.replace('/', os.pa...
def get_library_config(name): """Get distutils-compatible extension extras for the given library. This requires ``pkg-config``. """ try: proc = Popen(['pkg-config', '--cflags', '--libs', name], stdout=PIPE, stderr=PIPE) except OSError: print('pkg-config is required for building PyA...
def update_extend(dst, src): """Update the `dst` with the `src`, extending values where lists. Primiarily useful for integrating results from `get_library_config`. """ for k, v in src.items(): existing = dst.setdefault(k, []) for x in v: if x not in existing: ...
def dump_config(): """Print out all the config information we have so far (for debugging).""" print('PyAV:', version, git_commit or '(unknown commit)') print('Python:', sys.version.encode('unicode_escape' if PY3 else 'string-escape')) print('platform:', platform.platform()) print('extension_extra:')...
def _CCompiler_spawn_silent(cmd, dry_run=None): """Spawn a process, and eat the stdio.""" proc = Popen(cmd, stdout=PIPE, stderr=PIPE) out, err = proc.communicate() if proc.returncode: raise DistutilsExecError(err)
def new_compiler(*args, **kwargs): """Create a C compiler. :param bool silent: Eat all stdio? Defaults to ``True``. All other arguments passed to ``distutils.ccompiler.new_compiler``. """ make_silent = kwargs.pop('silent', True) cc = _new_compiler(*args, **kwargs) # If MSVC10, initialize ...
def iter_cython(path): '''Yield all ``.pyx`` and ``.pxd`` files in the given root.''' for dir_path, dir_names, file_names in os.walk(path): for file_name in file_names: if file_name.startswith('.'): continue if os.path.splitext(file_name)[1] not in ('.pyx', '.pxd'...
def cleanup_text (text): """ It scrubs the garbled from its stream... Or it gets the debugger again. """ x = " ".join(map(lambda s: s.strip(), text.split("\n"))).strip() x = x.replace('“', '"').replace('”', '"') x = x.replace("‘", "'").replace("’", "'").replace("`", "'") x = x.replace('...
def split_grafs (lines): """ segment the raw text into paragraphs """ graf = [] for line in lines: line = line.strip() if len(line) < 1: if len(graf) > 0: yield "\n".join(graf) graf = [] else: graf.append(line) if...
def filter_quotes (text, is_email=True): """ filter the quoted text out of a message """ global DEBUG global PAT_FORWARD, PAT_REPLIED, PAT_UNSUBSC if is_email: text = filter(lambda x: x in string.printable, text) if DEBUG: print("text:", text) # strip off q...
def get_word_id (root): """ lookup/assign a unique identify for each word root """ global UNIQ_WORDS # in practice, this should use a microservice via some robust # distributed cache, e.g., Redis, Cassandra, etc. if root not in UNIQ_WORDS: UNIQ_WORDS[root] = len(UNIQ_WORDS) ret...
def fix_microsoft (foo): """ fix special case for `c#`, `f#`, etc.; thanks Microsoft """ i = 0 bar = [] while i < len(foo): text, lemma, pos, tag = foo[i] if (text == "#") and (i > 0): prev_tok = bar[-1] prev_tok[0] += "#" prev_tok[1] += "#"...
def fix_hypenation (foo): """ fix hyphenation in the word list for a parsed sentence """ i = 0 bar = [] while i < len(foo): text, lemma, pos, tag = foo[i] if (tag == "HYPH") and (i > 0) and (i < len(foo) - 1): prev_tok = bar[-1] next_tok = foo[i + 1] ...
def parse_graf (doc_id, graf_text, base_idx, spacy_nlp=None): """ CORE ALGORITHM: parse and markup sentences in the given paragraph """ global DEBUG global POS_KEEPS, POS_LEMMA, SPACY_NLP # set up the spaCy NLP parser if not spacy_nlp: if not SPACY_NLP: SPACY_NLP = spacy...
def parse_doc (json_iter): """ parse one document to prep for TextRank """ global DEBUG for meta in json_iter: base_idx = 0 for graf_text in filter_quotes(meta["text"], is_email=False): if DEBUG: print("graf_text:", graf_text) grafs, new_bas...
def get_tiles (graf, size=3): """ generate word pairs for the TextRank graph """ keeps = list(filter(lambda w: w.word_id > 0, graf)) keeps_len = len(keeps) for i in iter(range(0, keeps_len - 1)): w0 = keeps[i] for j in iter(range(i + 1, min(keeps_len, i + 1 + size))): ...
def build_graph (json_iter): """ construct the TextRank graph from parsed paragraphs """ global DEBUG, WordNode graph = nx.DiGraph() for meta in json_iter: if DEBUG: print(meta["graf"]) for pair in get_tiles(map(WordNode._make, meta["graf"])): if DEBUG: ...
def write_dot (graph, ranks, path="graph.dot"): """ output the graph in Dot file format """ dot = Digraph() for node in graph.nodes(): dot.node(node, "%s %0.3f" % (node, ranks[node])) for edge in graph.edges(): dot.edge(edge[0], edge[1], constraint="false") with open(path,...
def render_ranks (graph, ranks, dot_file="graph.dot"): """ render the TextRank graph for visual formats """ if dot_file: write_dot(graph, ranks, path=dot_file)
def text_rank (path): """ run the TextRank algorithm """ graph = build_graph(json_iter(path)) ranks = nx.pagerank(graph) return graph, ranks
def find_chunk (phrase, np): """ leverage noun phrase chunking """ for i in iter(range(0, len(phrase))): parsed_np = find_chunk_sub(phrase, np, i) if parsed_np: return parsed_np
def enumerate_chunks (phrase, spacy_nlp): """ iterate through the noun phrases """ if (len(phrase) > 1): found = False text = " ".join([rl.text for rl in phrase]) doc = spacy_nlp(text.strip(), parse=True) for np in doc.noun_chunks: if np.text != text: ...
def collect_keyword (sent, ranks, stopwords): """ iterator for collecting the single-word keyphrases """ for w in sent: if (w.word_id > 0) and (w.root in ranks) and (w.pos[0] in "NV") and (w.root not in stopwords): rl = RankedLexeme(text=w.raw.lower(), rank=ranks[w.root]/2.0, ids=[w....
def collect_entities (sent, ranks, stopwords, spacy_nlp): """ iterator for collecting the named-entities """ global DEBUG sent_text = " ".join([w.raw for w in sent]) if DEBUG: print("sent:", sent_text) for ent in spacy_nlp(sent_text).ents: if DEBUG: print("NER:"...
def collect_phrases (sent, ranks, spacy_nlp): """ iterator for collecting the noun phrases """ tail = 0 last_idx = sent[0].idx - 1 phrase = [] while tail < len(sent): w = sent[tail] if (w.word_id > 0) and (w.root in ranks) and ((w.idx - last_idx) == 1): # keep c...
def normalize_key_phrases (path, ranks, stopwords=None, spacy_nlp=None, skip_ner=True): """ collect keyphrases, named entities, etc., while removing stop words """ global STOPWORDS, SPACY_NLP # set up the stop words if (type(stopwords) is list) or (type(stopwords) is set): # explicit co...
def mh_digest (data): """ create a MinHash digest """ num_perm = 512 m = MinHash(num_perm) for d in data: m.update(d.encode('utf8')) return m
def rank_kernel (path): """ return a list (matrix-ish) of the key phrases and their ranks """ kernel = [] if isinstance(path, str): path = json_iter(path) for meta in path: if not isinstance(meta, RankedLexeme): rl = RankedLexeme(**meta) else: rl...
def top_sentences (kernel, path): """ determine distance for each sentence """ key_sent = {} i = 0 if isinstance(path, str): path = json_iter(path) for meta in path: graf = meta["graf"] tagged_sent = [WordNode._make(x) for x in graf] text = " ".join([w.raw f...
def limit_keyphrases (path, phrase_limit=20): """ iterator for the most significant key phrases """ rank_thresh = None if isinstance(path, str): lex = [] for meta in json_iter(path): rl = RankedLexeme(**meta) lex.append(rl) else: lex = path ...
def limit_sentences (path, word_limit=100): """ iterator for the most significant sentences, up to a specified limit """ word_count = 0 if isinstance(path, str): path = json_iter(path) for meta in path: if not isinstance(meta, SummarySent): p = SummarySent(**meta) ...
def make_sentence (sent_text): """ construct a sentence text, with proper spacing """ lex = [] idx = 0 for word in sent_text: if len(word) > 0: if (idx > 0) and not (word[0] in ",.:;!?-\"'"): lex.append(" ") lex.append(word) idx += 1 ...
def json_iter (path): """ iterator for JSON-per-line in a file pattern """ with open(path, 'r') as f: for line in f.readlines(): yield json.loads(line)
def pretty_print (obj, indent=False): """ pretty print a JSON object """ if indent: return json.dumps(obj, sort_keys=True, indent=2, separators=(',', ': ')) else: return json.dumps(obj, sort_keys=True)
def get_object(cls, api_token, snapshot_id): """ Class method that will return a Snapshot object by ID. """ snapshot = cls(token=api_token, id=snapshot_id) snapshot.load() return snapshot
def load(self): """ Fetch data about tag """ tags = self.get_data("tags/%s" % self.name) tag = tags['tag'] for attr in tag.keys(): setattr(self, attr, tag[attr]) return self
def create(self, **kwargs): """ Create the tag. """ for attr in kwargs.keys(): setattr(self, attr, kwargs[attr]) params = {"name": self.name} output = self.get_data("tags", type="POST", params=params) if output: self.name = output['ta...
def __get_resources(self, resources, method): """ Method used to talk directly to the API (TAGs' Resources) """ tagged = self.get_data( 'tags/%s/resources' % self.name, params={ "resources": resources }, type=method, ) return tagged
def __extract_resources_from_droplets(self, data): """ Private method to extract from a value, the resources. It will check the type of object in the array provided and build the right structure for the API. """ resources = [] if not isinstance(data, l...
def add_droplets(self, droplet): """ Add the Tag to a Droplet. Attributes accepted at creation time: droplet: array of string or array of int, or array of Droplets. """ droplets = droplet if not isinstance(droplets, list): droplets = [...
def remove_droplets(self, droplet): """ Remove the Tag from the Droplet. Attributes accepted at creation time: droplet: array of string or array of int, or array of Droplets. """ droplets = droplet if not isinstance(droplets, list): dr...
def get_object(cls, api_token, action_id): """ Class method that will return a Action object by ID. """ action = cls(token=api_token, id=action_id) action.load_directly() return action
def wait(self, update_every_seconds=1): """ Wait until the action is marked as completed or with an error. It will return True in case of success, otherwise False. Optional Args: update_every_seconds - int : number of seconds to wait before ...
def get_object(cls, api_token, droplet_id): """Class method that will return a Droplet object by ID. Args: api_token (str): token droplet_id (int): droplet id """ droplet = cls(token=api_token, id=droplet_id) droplet.load() return droplet
def get_data(self, *args, **kwargs): """ Customized version of get_data to perform __check_actions_in_data """ data = super(Droplet, self).get_data(*args, **kwargs) if "type" in kwargs: if kwargs["type"] == POST: self.__check_actions_in_data(data) ...
def load(self): """ Fetch data about droplet - use this instead of get_data() """ droplets = self.get_data("droplets/%s" % self.id) droplet = droplets['droplet'] for attr in droplet.keys(): setattr(self, attr, droplet[attr]) for net in self.networ...
def _perform_action(self, params, return_dict=True): """ Perform a droplet action. Args: params (dict): parameters of the action Optional Args: return_dict (bool): Return a dict when True (default), otherwise return an Act...
def resize(self, new_size_slug, return_dict=True, disk=True): """Resize the droplet to a new size slug. https://developers.digitalocean.com/documentation/v2/#resize-a-droplet Args: new_size_slug (str): name of new size Optional Args: return_dict (bool): Return a...
def take_snapshot(self, snapshot_name, return_dict=True, power_off=False): """Take a snapshot! Args: snapshot_name (str): name of snapshot Optional Args: return_dict (bool): Return a dict when True (default), otherwise return an Action. power...
def rebuild(self, image_id=None, return_dict=True): """Restore the droplet to an image ( snapshot or backup ) Args: image_id (int): id of image Optional Args: return_dict (bool): Return a dict when True (default), otherwise return an Action. Ret...
def change_kernel(self, kernel, return_dict=True): """Change the kernel to a new one Args: kernel : instance of digitalocean.Kernel.Kernel Optional Args: return_dict (bool): Return a dict when True (default), otherwise return an Action. Returns ...
def __get_ssh_keys_id_or_fingerprint(ssh_keys, token, name): """ Check and return a list of SSH key IDs or fingerprints according to DigitalOcean's API. This method is used to check and create a droplet with the correct SSH keys. """ ssh_keys_id = list() ...
def create(self, *args, **kwargs): """ Create the droplet with object properties. Note: Every argument and parameter given to this method will be assigned to the object. """ for attr in kwargs.keys(): setattr(self, attr, kwargs[attr]) # P...