INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Takes an array of onsets or offsets ( shape = [ nfrequencies nsamples ] where a 1 corresponds to an on/ offset and samples are 0 otherwise ) and returns a new array of the same shape where each 1 has been replaced by either a 0 if the on/ offset has been discarded or a non - zero positive integer such that each front w...
def _form_onset_offset_fronts(ons_or_offs, sample_rate_hz, threshold_ms=20): """ Takes an array of onsets or offsets (shape = [nfrequencies, nsamples], where a 1 corresponds to an on/offset, and samples are 0 otherwise), and returns a new array of the same shape, where each 1 has been replaced by either...
Takes an onset index ( freq sample ) and returns the offset index ( freq sample ) such that frequency index is the same and sample index is the minimum of all offsets ocurring after the given onset. If there are no offsets after the given onset in that frequency channel the final sample in that channel is returned.
def _lookup_offset_by_onset_idx(onset_idx, onsets, offsets): """ Takes an onset index (freq, sample) and returns the offset index (freq, sample) such that frequency index is the same, and sample index is the minimum of all offsets ocurring after the given onset. If there are no offsets after the given ...
Return a list of tuples of the form ( frequency_idx sample_idx ) corresponding to all the indexes of the given front.
def _get_front_idxs_from_id(fronts, id): """ Return a list of tuples of the form (frequency_idx, sample_idx), corresponding to all the indexes of the given front. """ if id == -1: # This is the only special case. # -1 is the index of the catch-all final column offset front. f...
Returns a front ID which is the id of the offset front that contains the most overlap with offsets that correspond to the given onset front ID.
def _choose_front_id_from_candidates(candidate_offset_front_ids, offset_fronts, offsets_corresponding_to_onsets): """ Returns a front ID which is the id of the offset front that contains the most overlap with offsets that correspond to the given onset front ID. """ noverlaps = [] # will contain tup...
Returns the offset_front_id which corresponds to the offset front which occurs first entirely after the given onset sample_idx.
def _get_offset_front_id_after_onset_sample_idx(onset_sample_idx, offset_fronts): """ Returns the offset_front_id which corresponds to the offset front which occurs first entirely after the given onset sample_idx. """ # get all the offset_front_ids offset_front_ids = [i for i in np.unique(offset...
Get the ID corresponding to the offset which occurs first after the given onset_front_id. By first I mean the front which contains the offset which is closest to the latest point in the onset front. By after I mean that the offset must contain only offsets which occur after the latest onset in the onset front.
def _get_offset_front_id_after_onset_front(onset_front_id, onset_fronts, offset_fronts): """ Get the ID corresponding to the offset which occurs first after the given onset_front_id. By `first` I mean the front which contains the offset which is closest to the latest point in the onset front. By `after`...
Find all offset fronts which are composed of at least one offset which corresponds to one of the onsets in the given onset front. The offset front which contains the most of such offsets is the match. If there are no such offset fronts return - 1.
def _match_offset_front_id_to_onset_front_id(onset_front_id, onset_fronts, offset_fronts, onsets, offsets): """ Find all offset fronts which are composed of at least one offset which corresponds to one of the onsets in the given onset front. The offset front which contains the most of such offsets is th...
Yields lists of the form [ ( f s ) ( f s ) ] one at a time from the given front ( which is a list of the same form ) such that each list yielded is consecutive in frequency.
def _get_consecutive_portions_of_front(front): """ Yields lists of the form [(f, s), (f, s)], one at a time from the given front (which is a list of the same form), such that each list yielded is consecutive in frequency. """ last_f = None ls = [] for f, s in front: if last_f is not ...
Gets an onset_front and an offset_front such that they both occupy at least some of the same frequency channels then returns the portion of each that overlaps with the other.
def _get_consecutive_and_overlapping_fronts(onset_fronts, offset_fronts, onset_front_id, offset_front_id): """ Gets an onset_front and an offset_front such that they both occupy at least some of the same frequency channels, then returns the portion of each that overlaps with the other. """ # Get the...
Returns an updated segmentation mask such that the input segmentation_mask has been updated by segmenting between onset_front_id and offset_front_id as found in onset_fronts and offset_fronts respectively.
def _update_segmentation_mask(segmentation_mask, onset_fronts, offset_fronts, onset_front_id, offset_front_id_most_overlap): """ Returns an updated segmentation mask such that the input `segmentation_mask` has been updated by segmenting between `onset_front_id` and `offset_front_id`, as found in `onset_fron...
Returns the front ID found in front at the given index.
def _front_id_from_idx(front, index): """ Returns the front ID found in `front` at the given `index`. :param front: An onset or offset front array of shape [nfrequencies, nsamples] :index: A tuple of the form (frequency index, sample index) :returns: ...
Yields one onset front ID at a time until they are gone. All the onset fronts from a frequency channel are yielded then all of the next channel s etc. though one at a time.
def _get_front_ids_one_at_a_time(onset_fronts): """ Yields one onset front ID at a time until they are gone. All the onset fronts from a frequency channel are yielded, then all of the next channel's, etc., though one at a time. """ yielded_so_far = set() for row in onset_fronts: for id i...
Gets the offsets that occur as close as possible to the onsets in the given onset - front.
def _get_corresponding_offsets(onset_fronts, onset_front_id, onsets, offsets): """ Gets the offsets that occur as close as possible to the onsets in the given onset-front. """ corresponding_offsets = [] for index in _get_front_idxs_from_id(onset_fronts, onset_front_id): offset_fidx, offset_s...
Returns all the offset fronts that are composed of at least one of the given offset indexes. Also returns a dict of the form { offset_front_id: ntimes saw }
def _get_all_offset_fronts_from_offsets(offset_fronts, corresponding_offsets): """ Returns all the offset fronts that are composed of at least one of the given offset indexes. Also returns a dict of the form {offset_front_id: ntimes saw} """ all_offset_fronts_of_interest = [] ids_ntimes_seen = {...
Removes all points in the fronts that overlap with the segmentation mask.
def _remove_overlaps(segmentation_mask, fronts): """ Removes all points in the fronts that overlap with the segmentation mask. """ fidxs, sidxs = np.where((segmentation_mask != fronts) & (segmentation_mask != 0) & (fronts != 0)) fronts[fidxs, sidxs] = 0
Returns a segmentation mask which looks like this: frequency 1: 0 0 4 4 4 4 4 0 0 5 5 5 frequency 2: 0 4 4 4 4 4 0 0 0 0 5 5 frequency 3: 0 4 4 4 4 4 4 4 5 5 5 5
def _match_fronts(onset_fronts, offset_fronts, onsets, offsets, debug=False): """ Returns a segmentation mask, which looks like this: frequency 1: 0 0 4 4 4 4 4 0 0 5 5 5 frequency 2: 0 4 4 4 4 4 0 0 0 0 5 5 frequency 3: 0 4 4 4 4 4 4 4 5 5 5 5 That is, each item in the array is either a 0 (not...
Removes all fronts from fronts which are strictly smaller than size consecutive frequencies in length.
def _remove_fronts_that_are_too_small(fronts, size): """ Removes all fronts from `fronts` which are strictly smaller than `size` consecutive frequencies in length. """ ids = np.unique(fronts) for id in ids: if id == 0 or id == -1: continue front = _get_front_idxs_from...
For each onset front for each frequency in that front break the onset front if the signals between this frequency s onset and the next frequency s onset are not similar enough.
def _break_poorly_matched_fronts(fronts, threshold=0.1, threshold_overlap_samples=3): """ For each onset front, for each frequency in that front, break the onset front if the signals between this frequency's onset and the next frequency's onset are not similar enough. Specifically: If we have the f...
Merges the segments specified by id ( found in toupdate ) and otherid ( found in other ) if they overlap at all. Updates toupdate accordingly.
def _update_segmentation_mask_if_overlap(toupdate, other, id, otherid): """ Merges the segments specified by `id` (found in `toupdate`) and `otherid` (found in `other`) if they overlap at all. Updates `toupdate` accordingly. """ # If there is any overlap or touching, merge the two, otherwise just re...
Checks if seg1 and seg2 are adjacent at any point. Each is a tuple of the form ( fidxs sidxs ).
def _segments_are_adjacent(seg1, seg2): """ Checks if seg1 and seg2 are adjacent at any point. Each is a tuple of the form (fidxs, sidxs). """ # TODO: This is unnacceptably slow lsf1, lss1 = seg1 lsf2, lss2 = seg2 for i, f1 in enumerate(lsf1): for j, f2 in enumerate(lsf2): ...
Merges all segments in mask which are touching.
def _merge_adjacent_segments(mask): """ Merges all segments in `mask` which are touching. """ mask_ids = [id for id in np.unique(mask) if id != 0] for id in mask_ids: myfidxs, mysidxs = np.where(mask == id) for other in mask_ids: # Ugh, brute force O(N^2) algorithm.. gross.. ...
segmasks should be in sorted order of [ coarsest... finest ].
def _integrate_segmentation_masks(segmasks): """ `segmasks` should be in sorted order of [coarsest, ..., finest]. Integrates the given list of segmentation masks together to form one segmentation mask by having each segment subsume ones that exist in the finer masks. """ if len(segmasks) == 1: ...
Returns a list of segmentation masks each of the same dimension as the input one but where they each have exactly one segment in them and all other samples in them are zeroed.
def _separate_masks(mask, threshold=0.025): """ Returns a list of segmentation masks each of the same dimension as the input one, but where they each have exactly one segment in them and all other samples in them are zeroed. Only bothers to return segments that are larger in total area than `thresh...
Takes the given mask and stft which must be matrices of shape frequencies times and downsamples one of them into the other one s times so that the time dimensions are equal. Leaves the frequency dimension untouched.
def _downsample_one_or_the_other(mask, mask_indexes, stft, stft_indexes): """ Takes the given `mask` and `stft`, which must be matrices of shape `frequencies, times` and downsamples one of them into the other one's times, so that the time dimensions are equal. Leaves the frequency dimension untouched. ...
Maps the given mask which is in domain ( frequencies times ) to the new domain ( stft_frequencies stft_times ) and returns the result.
def _map_segmentation_mask_to_stft_domain(mask, times, frequencies, stft_times, stft_frequencies): """ Maps the given `mask`, which is in domain (`frequencies`, `times`) to the new domain (`stft_frequencies`, `stft_times`) and returns the result. """ assert mask.shape == (frequencies.shape[0], times...
Worker for the ASA algorithm s multiprocessing step.
def _asa_task(q, masks, stft, sample_width, frame_rate, nsamples_for_each_fft): """ Worker for the ASA algorithm's multiprocessing step. """ # Convert each mask to (1 or 0) rather than (ID or 0) for mask in masks: mask = np.where(mask > 0, 1, 0) # Multiply the masks against STFTs ma...
Runs a Markov Decision Process over the given seg in chunks of ms_per_input yielding True if this ms_per_input chunk has been classified as positive ( 1 ) and False if this chunk has been classified as negative ( 0 ).
def _get_filter_indices(seg, start_as_yes, prob_raw_yes, ms_per_input, model, transition_matrix, model_stats): """ Runs a Markov Decision Process over the given `seg` in chunks of `ms_per_input`, yielding `True` if this `ms_per_input` chunk has been classified as positive (1) and `False` if this chunk has b...
Takes a list of 1s and 0s and returns a list of tuples of the form: [ y/ n timestamp ].
def _group_filter_values(seg, filter_indices, ms_per_input): """ Takes a list of 1s and 0s and returns a list of tuples of the form: ['y/n', timestamp]. """ ret = [] for filter_value, (_segment, timestamp) in zip(filter_indices, seg.generate_frames_as_segments(ms_per_input)): if filter_v...
Takes ls ( a list of 1s and 0s ) and smoothes it so that adjacent values are more likely to be the same.
def _homogeneity_filter(ls, window_size): """ Takes `ls` (a list of 1s and 0s) and smoothes it so that adjacent values are more likely to be the same. :param ls: A list of 1s and 0s to smooth. :param window_size: How large the smoothing kernel is. :returns: A list of 1s and 0...
Does a bandpass filter over the given data.
def bandpass_filter(data, low, high, fs, order=5): """ Does a bandpass filter over the given data. :param data: The data (numpy array) to be filtered. :param low: The low cutoff in Hz. :param high: The high cutoff in Hz. :param fs: The sample rate (in Hz) of the data. :param order: The orde...
Does a lowpass filter over the given data.
def lowpass_filter(data, cutoff, fs, order=5): """ Does a lowpass filter over the given data. :param data: The data (numpy array) to be filtered. :param cutoff: The high cutoff in Hz. :param fs: The sample rate in Hz of the data. :param order: The order of the filter. The higher the order, the ...
Separates the outcome feature from the data and creates the onehot vector for each row.
def list_to_tf_input(data, response_index, num_outcomes): """ Separates the outcome feature from the data and creates the onehot vector for each row. """ matrix = np.matrix([row[:response_index] + row[response_index+1:] for row in data]) outcomes = np.asarray([row[response_index] for row in data], dtype=np.ui...
Standardizes continuous features and expands categorical features.
def expand_and_standardize_dataset(response_index, response_header, data_set, col_vals, headers, standardizers, feats_to_ignore, columns_to_expand, outcome_trans_dict): """ Standardizes continuous features and expands categorical features. """ # expand and standardize modified_set = [] for row_index, row in...
Used to check whether the two edge lists have the same edges when elements are neither hashable nor sortable.
def equal_ignore_order(a, b): """ Used to check whether the two edge lists have the same edges when elements are neither hashable nor sortable. """ unmatched = list(b) for element in a: try: unmatched.remove(element) except ValueError: return False return not unmatched
Create unique value structures: When performing repairs we choose median values. If repair is partial then values will be modified to some intermediate value between the original and the median value. However the partially repaired value will only be chosen out of values that exist in the data set. This prevents choosi...
def repair(self, data_to_repair): num_cols = len(data_to_repair[0]) col_ids = range(num_cols) # Get column type information col_types = ["Y"]*len(col_ids) for i, col in enumerate(col_ids): if i in self.features_to_ignore: col_types[i] = "I" elif i == self.feature_to_repair: ...
Given a list of audit files rank them using the measurer and return the features that never deviate more than similarity_bound across repairs.
def group_audit_ranks(filenames, measurer, similarity_bound=0.05): """ Given a list of audit files, rank them using the `measurer` and return the features that never deviate more than `similarity_bound` across repairs. """ def _partition_groups(feature_scores): groups = [] for feature, score in fea...
Given a confusion matrix returns the accuracy. Accuracy Definition: http:// research. ics. aalto. fi/ events/ eyechallenge2005/ evaluation. shtml
def accuracy(conf_matrix): """ Given a confusion matrix, returns the accuracy. Accuracy Definition: http://research.ics.aalto.fi/events/eyechallenge2005/evaluation.shtml """ total, correct = 0.0, 0.0 for true_response, guess_dict in conf_matrix.items(): for guess, count in guess_dict.items(): if t...
Given a confusion matrix returns Balanced Classification Rate. BCR is ( 1 - Balanced Error Rate ). BER Definition: http:// research. ics. aalto. fi/ events/ eyechallenge2005/ evaluation. shtml
def BCR(conf_matrix): """ Given a confusion matrix, returns Balanced Classification Rate. BCR is (1 - Balanced Error Rate). BER Definition: http://research.ics.aalto.fi/events/eyechallenge2005/evaluation.shtml """ parts = [] for true_response, guess_dict in conf_matrix.items(): error = 0.0 total =...
Given an unsorted list of numeric values return median value ( as a float ). Note that in the case of even - length lists of values we apply the value to the left of the center to be the median ( such that the median can only be a value from the list of values ). Eg: get_median ( [ 1 2 3 4 ] ) == 2 not 2. 5.
def get_median(values, kdd): """ Given an unsorted list of numeric values, return median value (as a float). Note that in the case of even-length lists of values, we apply the value to the left of the center to be the median (such that the median can only be a value from the list of values). Eg: get_median(...
with open ( brandon_testing/ test_ + str ( time. clock () ) +. csv w ) as f: writer = csv. writer ( f delimiter = ) for row in fin: writer. writerow ( row )
def expand_to_one_hot(data,expand = True,use_alternative=False): header_dict = {'ALCABUS':0,'PRIRCAT':1,'TMSRVC':2,'SEX1':3,'RACE':4,'RELTYP':5,'age_1st_arrest':6,'DRUGAB':7,'Class':8,'RLAGE':9,'NFRCTNS':10} new_data = [] for entry in data: temp = {} if expand == True: if entry[header_dict["SEX1"]] ...
Loads a confusion matrix in a two - level dictionary format.
def load_audit_confusion_matrices(filename): """ Loads a confusion matrix in a two-level dictionary format. For example, the confusion matrix of a 75%-accurate model that predicted 15 values (and mis-classified 5) may look like: {"A": {"A":10, "B": 5}, "B": {"B":5}} Note that raw boolean values are transl...
Separates the outcome feature from the data.
def list_to_tf_input(data, response_index, num_outcomes): """ Separates the outcome feature from the data. """ matrix = np.matrix([row[:response_index] + row[response_index+1:] for row in data]) outcomes = np.asarray([row[response_index] for row in data], dtype=np.uint8) return matrix, outcomes
The bin size in FD - binning is given by size = 2 * IQR ( x ) * n^ ( - 1/ 3 ) More Info: https:// en. wikipedia. org/ wiki/ Freedman%E2%80%93Diaconis_rule
def FreedmanDiaconisBinSize(feature_values): """ The bin size in FD-binning is given by size = 2 * IQR(x) * n^(-1/3) More Info: https://en.wikipedia.org/wiki/Freedman%E2%80%93Diaconis_rule If the BinSize ends up being 0 (in the case that all values are the same), return a BinSize of 1. """ q75, q25 = nu...
Checks for alternative index - url in pip. conf
def _update_index_url_from_configs(self): """ Checks for alternative index-url in pip.conf """ if 'VIRTUAL_ENV' in os.environ: self.pip_config_locations.append(os.path.join(os.environ['VIRTUAL_ENV'], 'pip.conf')) self.pip_config_locations.append(os.path.join(os.environ['VIRTUAL_...
: type package_name: str: type current_version: version. Version
def _fetch_index_package_info(self, package_name, current_version): """ :type package_name: str :type current_version: version.Version """ try: package_canonical_name = package_name if self.PYPI_API_TYPE == 'simple_html': package_canonical...
: type package_name: str: type current_version: version. Version: type response: requests. models. Response
def _parse_pypi_json_package_info(self, package_name, current_version, response): """ :type package_name: str :type current_version: version.Version :type response: requests.models.Response """ data = response.json() all_versions = [version.parse(vers) for vers i...
: type package_name: str: type current_version: version. Version: type response: requests. models. Response
def _parse_simple_html_package_info(self, package_name, current_version, response): """ :type package_name: str :type current_version: version.Version :type response: requests.models.Response """ pattern = r'<a.*>.*{name}-([A-z0-9\.-]*)(?:-py|\.tar).*<\/a>'.format(name=re...
Main CLI entrypoint.
def main(): """ Main CLI entrypoint. """ options = get_options() Windows.enable(auto_colors=True, reset_atexit=True) try: # maybe check if virtualenv is not activated check_for_virtualenv(options) # 1. detect requirements files filenames = RequirementsDetector(options.g...
Update ( install ) the package in current environment and if success also replace version in file
def _update_package(self, package): """ Update (install) the package in current environment, and if success, also replace version in file """ try: if not self.dry_run and not self.skip_package_installation: # pragma: nocover subprocess.check_call(['pip', 'install', '{}=={}'....
Attempt to detect requirements files in the current working directory
def autodetect_files(self): """ Attempt to detect requirements files in the current working directory """ if self._is_valid_requirements_file('requirements.txt'): self.filenames.append('requirements.txt') if self._is_valid_requirements_file('requirements.pip'): # pragma: nocover ...
Resolve all streams on the network.
def resolve_streams(wait_time=1.0): """Resolve all streams on the network. This function returns all currently available streams from any outlet on the network. The network is usually the subnet specified at the local router, but may also include a group of machines visible to each other via mul...
Resolve all streams with a specific value for a given property.
def resolve_byprop(prop, value, minimum=1, timeout=FOREVER): """Resolve all streams with a specific value for a given property. If the goal is to resolve a specific stream, this method is preferred over resolving all streams and then selecting the desired one. Keyword arguments: prop -- The S...
Resolve all streams that match a given predicate.
def resolve_bypred(predicate, minimum=1, timeout=FOREVER): """Resolve all streams that match a given predicate. Advanced query that allows to impose more conditions on the retrieved streams; the given string is an XPath 1.0 predicate for the <description> node (omitting the surrounding []'s), see also...
Error handler function. Translates an error code into an exception.
def handle_error(errcode): """Error handler function. Translates an error code into an exception.""" if type(errcode) is c_int: errcode = errcode.value if errcode == 0: pass # no error elif errcode == -1: raise TimeoutError("the operation failed due to a timeout.") elif errc...
Push a sample into the outlet.
def push_sample(self, x, timestamp=0.0, pushthrough=True): """Push a sample into the outlet. Each entry in the list corresponds to one channel. Keyword arguments: x -- A list of values to push (one per channel). timestamp -- Optionally the capture time of the sample, in agreeme...
Push a list of samples into the outlet.
def push_chunk(self, x, timestamp=0.0, pushthrough=True): """Push a list of samples into the outlet. samples -- A list of samples, either as a list of lists or a list of multiplexed values. timestamp -- Optionally the capture time of the most recent sample, in ...
Wait until some consumer shows up ( without wasting resources ).
def wait_for_consumers(self, timeout): """Wait until some consumer shows up (without wasting resources). Returns True if the wait was successful, False if the timeout expired. """ return bool(lib.lsl_wait_for_consumers(self.obj, c_double(timeout)))
Retrieve the complete information of the given stream.
def info(self, timeout=FOREVER): """Retrieve the complete information of the given stream. This includes the extended description. Can be invoked at any time of the stream's lifetime. Keyword arguments: timeout -- Timeout of the operation. (default FOREVER) ...
Subscribe to the data stream.
def open_stream(self, timeout=FOREVER): """Subscribe to the data stream. All samples pushed in at the other end from this moment onwards will be queued and eventually be delivered in response to pull_sample() or pull_chunk() calls. Pulling a sample without some preceding open_stream ...
Retrieve an estimated time correction offset for the given stream.
def time_correction(self, timeout=FOREVER): """Retrieve an estimated time correction offset for the given stream. The first call to this function takes several miliseconds until a reliable first estimate is obtained. Subsequent calls are instantaneous (and rely on periodic background ...
Pull a sample from the inlet and return it. Keyword arguments: timeout -- The timeout for this operation if any. ( default FOREVER ) If this is passed as 0. 0 then the function returns only a sample if one is buffered for immediate pickup. Returns a tuple ( sample timestamp ) where sample is a list of channel values an...
def pull_sample(self, timeout=FOREVER, sample=None): """Pull a sample from the inlet and return it. Keyword arguments: timeout -- The timeout for this operation, if any. (default FOREVER) If this is passed as 0.0, then the function returns only a s...
Pull a chunk of samples from the inlet. Keyword arguments: timeout -- The timeout of the operation ; if passed as 0. 0 then only samples available for immediate pickup will be returned. ( default 0. 0 ) max_samples -- Maximum number of samples to return. ( default 1024 ) dest_obj -- A Python object that supports the bu...
def pull_chunk(self, timeout=0.0, max_samples=1024, dest_obj=None): """Pull a chunk of samples from the inlet. Keyword arguments: timeout -- The timeout of the operation; if passed as 0.0, then only samples available for immediate pickup will be returned. ...
Get a child with a specified name.
def child(self, name): """Get a child with a specified name.""" return XMLElement(lib.lsl_child(self.e, str.encode(name)))
Get the next sibling in the children list of the parent node.
def next_sibling(self, name=None): """Get the next sibling in the children list of the parent node. If a name is provided, the next sibling with the given name is returned. """ if name is None: return XMLElement(lib.lsl_next_sibling(self.e)) else: return...
Get the previous sibling in the children list of the parent node.
def previous_sibling(self, name=None): """Get the previous sibling in the children list of the parent node. If a name is provided, the previous sibling with the given name is returned. """ if name is None: return XMLElement(lib.lsl_previous_sibling(self.e)) ...
Get child value ( value of the first child that is text ).
def child_value(self, name=None): """Get child value (value of the first child that is text). If a name is provided, then the value of the first child with the given name is returned. """ if name is None: res = lib.lsl_child_value(self.e) else: r...
Append a child node with a given name which has a ( nameless ) plain - text child with the given text value.
def append_child_value(self, name, value): """Append a child node with a given name, which has a (nameless) plain-text child with the given text value.""" return XMLElement(lib.lsl_append_child_value(self.e, str.encode(name), ...
Prepend a child node with a given name which has a ( nameless ) plain - text child with the given text value.
def prepend_child_value(self, name, value): """Prepend a child node with a given name, which has a (nameless) plain-text child with the given text value.""" return XMLElement(lib.lsl_prepend_child_value(self.e, str.encode(name), ...
Set the text value of the ( nameless ) plain - text child of a named child node.
def set_child_value(self, name, value): """Set the text value of the (nameless) plain-text child of a named child node.""" return XMLElement(lib.lsl_set_child_value(self.e, str.encode(name), str....
Set the element s name. Returns False if the node is empty.
def set_name(self, name): """Set the element's name. Returns False if the node is empty.""" return bool(lib.lsl_set_name(self.e, str.encode(name)))
Set the element s value. Returns False if the node is empty.
def set_value(self, value): """Set the element's value. Returns False if the node is empty.""" return bool(lib.lsl_set_value(self.e, str.encode(value)))
Append a child element with the specified name.
def append_child(self, name): """Append a child element with the specified name.""" return XMLElement(lib.lsl_append_child(self.e, str.encode(name)))
Prepend a child element with the specified name.
def prepend_child(self, name): """Prepend a child element with the specified name.""" return XMLElement(lib.lsl_prepend_child(self.e, str.encode(name)))
Append a copy of the specified element as a child.
def append_copy(self, elem): """Append a copy of the specified element as a child.""" return XMLElement(lib.lsl_append_copy(self.e, elem.e))
Prepend a copy of the specified element as a child.
def prepend_copy(self, elem): """Prepend a copy of the specified element as a child.""" return XMLElement(lib.lsl_prepend_copy(self.e, elem.e))
Remove a given child element specified by name or as element.
def remove_child(self, rhs): """Remove a given child element, specified by name or as element.""" if type(rhs) is XMLElement: lib.lsl_remove_child(self.e, rhs.e) else: lib.lsl_remove_child_n(self.e, rhs)
Obtain the set of currently present streams on the network.
def results(self): """Obtain the set of currently present streams on the network. Returns a list of matching StreamInfo objects (with empty desc field), any of which can subsequently be used to open an inlet. """ # noinspection PyCallingNonCallable buffer = (c_void_p*10...
See all token associated with a given token. PAIR lilas
def pair(cmd, word): """See all token associated with a given token. PAIR lilas""" word = list(preprocess_query(word))[0] key = pair_key(word) tokens = [t.decode() for t in DB.smembers(key)] tokens.sort() print(white(tokens)) print(magenta('(Total: {})'.format(len(tokens))))
Shows autocomplete results for a given token.
def do_AUTOCOMPLETE(cmd, s): """Shows autocomplete results for a given token.""" s = list(preprocess_query(s))[0] keys = [k.decode() for k in DB.smembers(edge_ngram_key(s))] print(white(keys)) print(magenta('({} elements)'.format(len(keys))))
Compute edge ngram of token from min. Does not include token itself.
def compute_edge_ngrams(token, min=None): """Compute edge ngram of token from min. Does not include token itself.""" if min is None: min = config.MIN_EDGE_NGRAMS token = token[:config.MAX_EDGE_NGRAMS + 1] return [token[:i] for i in range(min, len(token))]
Allow for iterators to return either an item or an iterator of items.
def iter_pipe(pipe, processors): """Allow for iterators to return either an item or an iterator of items.""" if isinstance(pipe, str): pipe = [pipe] for it in processors: pipe = it(pipe) yield from pipe
Import functions or class by their path. Should be of the form: path. to. module. func
def import_by_path(path): """ Import functions or class by their path. Should be of the form: path.to.module.func """ if not isinstance(path, str): return path module_path, *name = path.rsplit('.', 1) func = import_module(module_path) if name: func = getattr(func, name[0]...
Calculate the great circle distance between two points on the earth ( specified in decimal degrees ).
def haversine_distance(point1, point2): """ Calculate the great circle distance between two points on the earth (specified in decimal degrees). """ lat1, lon1 = point1 lat2, lon2 = point2 # Convert decimal degrees to radians. lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2...
Customized version of imap_unordered.
def imap_unordered(self, func, iterable, chunksize): """Customized version of imap_unordered. Directly send chunks to func, instead of iterating in each process and sending one by one. Original: https://hg.python.org/cpython/file/tip/Lib/multiprocessing/pool.py#l271 Ot...
Naive neighborhoods algo.
def make_fuzzy(word, max=1): """Naive neighborhoods algo.""" # inversions neighbors = [] for i in range(0, len(word) - 1): neighbor = list(word) neighbor[i], neighbor[i+1] = neighbor[i+1], neighbor[i] neighbors.append(''.join(neighbor)) # substitutions for letter in strin...
Compute fuzzy extensions of word. FUZZY lilas
def do_fuzzy(self, word): """Compute fuzzy extensions of word. FUZZY lilas""" word = list(preprocess_query(word))[0] print(white(make_fuzzy(word)))
Compute fuzzy extensions of word that exist in index. FUZZYINDEX lilas
def do_fuzzyindex(self, word): """Compute fuzzy extensions of word that exist in index. FUZZYINDEX lilas""" word = list(preprocess_query(word))[0] token = Token(word) neighbors = make_fuzzy(token) neighbors = [(n, DB.zcard(dbkeys.token_key(n))) for n in neighbors] neighbors.sort(key=lambda n...
Try to extract the bigger group of interlinked tokens.
def extend_results_extrapoling_relations(helper): """Try to extract the bigger group of interlinked tokens. Should generally be used at last in the collectors chain. """ if not helper.bucket_dry: return # No need. tokens = set(helper.meaningful + helper.common) for relation in _extract...
Display this help message.
def do_help(self, command): """Display this help message.""" if command: doc = getattr(self, 'do_' + command).__doc__ print(cyan(doc.replace(' ' * 8, ''))) else: print(magenta('Available commands:')) print(magenta('Type "HELP <command>" to get more...
Run a search many times to benchmark it. BENCH [ 100 ] rue des Lilas
def do_BENCH(self, query): """Run a search many times to benchmark it. BENCH [100] rue des Lilas""" try: count = int(re.match(r'^(\d+).*', query).group(1)) except AttributeError: count = 100 self._search(query, count=count)
Do a raw intersect between tokens ( default limit 100 ). INTERSECT rue des lilas [ LIMIT 100 ]
def do_INTERSECT(self, words): """Do a raw intersect between tokens (default limit 100). INTERSECT rue des lilas [LIMIT 100]""" start = time.time() limit = 100 if 'LIMIT' in words: words, limit = words.split('LIMIT') limit = int(limit) tokens = [ke...
Print some useful infos from Redis DB.
def do_DBINFO(self, *args): """Print some useful infos from Redis DB.""" info = DB.info() keys = [ 'keyspace_misses', 'keyspace_hits', 'used_memory_human', 'total_commands_processed', 'total_connections_received', 'connected_clients'] for key in keys: ...
Print raw content of a DB key. DBKEY g|u09tyzfe
def do_DBKEY(self, key): """Print raw content of a DB key. DBKEY g|u09tyzfe""" type_ = DB.type(key).decode() if type_ == 'set': out = DB.smembers(key) elif type_ == 'string': out = DB.get(key) else: out = 'Unsupported type {}'.format(ty...
Compute geodistance from a result to a point. GEODISTANCE 772210180J 48. 1234 2. 9876
def do_GEODISTANCE(self, s): """Compute geodistance from a result to a point. GEODISTANCE 772210180J 48.1234 2.9876""" try: _id, lat, lon = s.split() except: return self.error('Malformed query. Use: ID lat lon') try: result = Result(keys.docume...
Build GeoJSON corresponding to geohash given as parameter. GEOHASHTOGEOJSON u09vej04 [ NEIGHBORS 0|1|2 ]
def do_GEOHASHTOGEOJSON(self, geoh): """Build GeoJSON corresponding to geohash given as parameter. GEOHASHTOGEOJSON u09vej04 [NEIGHBORS 0|1|2]""" geoh, with_neighbors = self._match_option('NEIGHBORS', geoh) bbox = geohash.bbox(geoh) try: with_neighbors = int(with_neig...
Compute a geohash from latitude and longitude. GEOHASH 48. 1234 2. 9876
def do_GEOHASH(self, latlon): """Compute a geohash from latitude and longitude. GEOHASH 48.1234 2.9876""" try: lat, lon = map(float, latlon.split()) except ValueError: print(red('Invalid lat and lon {}'.format(latlon))) else: print(white(geohas...
Return members of a geohash and its neighbors. GEOHASHMEMBERS u09vej04 [ NEIGHBORS 0 ]
def do_GEOHASHMEMBERS(self, geoh): """Return members of a geohash and its neighbors. GEOHASHMEMBERS u09vej04 [NEIGHBORS 0]""" geoh, with_neighbors = self._match_option('NEIGHBORS', geoh) key = compute_geohash_key(geoh, with_neighbors != '0') if key: for id_ in DB.smem...
Get document from index with its id. GET 772210180J
def do_GET(self, _id): """Get document from index with its id. GET 772210180J""" doc = doc_by_id(_id) if not doc: return self.error('id "{}" not found'.format(_id)) for key, value in doc.items(): if key == config.HOUSENUMBERS_FIELD: continu...
Get index details for a document by its id. INDEX 772210180J
def do_INDEX(self, _id): """Get index details for a document by its id. INDEX 772210180J""" doc = doc_by_id(_id) if not doc: return self.error('id "{}" not found'.format(_id)) for field in config.FIELDS: key = field['key'] if key in doc: ...
Return document linked to word with higher score. BESTSCORE lilas
def do_BESTSCORE(self, word): """Return document linked to word with higher score. BESTSCORE lilas""" key = keys.token_key(indexed_string(word)[0]) for _id, score in DB.zrevrange(key, 0, 20, withscores=True): result = Result(_id) print(white(result), blue(score), ...