INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
r Beat tracking evaluation
def beat(ref, est, **kwargs): r'''Beat tracking evaluation Parameters ---------- ref : jams.Annotation Reference annotation object est : jams.Annotation Estimated annotation object kwargs Additional keyword arguments Returns ------- scores : dict Dic...
r Chord evaluation
def chord(ref, est, **kwargs): r'''Chord evaluation Parameters ---------- ref : jams.Annotation Reference annotation object est : jams.Annotation Estimated annotation object kwargs Additional keyword arguments Returns ------- scores : dict Dictionary...
Flatten a multi_segment annotation into mir_eval style.
def hierarchy_flatten(annotation): '''Flatten a multi_segment annotation into mir_eval style. Parameters ---------- annotation : jams.Annotation An annotation in the `multi_segment` namespace Returns ------- hier_intervalss : list A list of lists of intervals, ordered by in...
r Multi - level segmentation evaluation
def hierarchy(ref, est, **kwargs): r'''Multi-level segmentation evaluation Parameters ---------- ref : jams.Annotation Reference annotation object est : jams.Annotation Estimated annotation object kwargs Additional keyword arguments Returns ------- scores : ...
r Tempo evaluation
def tempo(ref, est, **kwargs): r'''Tempo evaluation Parameters ---------- ref : jams.Annotation Reference annotation object est : jams.Annotation Estimated annotation object kwargs Additional keyword arguments Returns ------- scores : dict Dictionary...
r Melody extraction evaluation
def melody(ref, est, **kwargs): r'''Melody extraction evaluation Parameters ---------- ref : jams.Annotation Reference annotation object est : jams.Annotation Estimated annotation object kwargs Additional keyword arguments Returns ------- scores : dict ...
Convert a pattern_jku annotation object to mir_eval format.
def pattern_to_mireval(ann): '''Convert a pattern_jku annotation object to mir_eval format. Parameters ---------- ann : jams.Annotation Must have `namespace='pattern_jku'` Returns ------- patterns : list of list of tuples - `patterns[x]` is a list containing all occurrences...
r Pattern detection evaluation
def pattern(ref, est, **kwargs): r'''Pattern detection evaluation Parameters ---------- ref : jams.Annotation Reference annotation object est : jams.Annotation Estimated annotation object kwargs Additional keyword arguments Returns ------- scores : dict ...
r Note transcription evaluation
def transcription(ref, est, **kwargs): r'''Note transcription evaluation Parameters ---------- ref : jams.Annotation Reference annotation object est : jams.Annotation Estimated annotation object kwargs Additional keyword arguments Returns ------- scores : di...
Add a namespace definition to our working set.
def add_namespace(filename): '''Add a namespace definition to our working set. Namespace files consist of partial JSON schemas defining the behavior of the `value` and `confidence` fields of an Annotation. Parameters ---------- filename : str Path to json file defining the namespace ob...
Construct a validation schema for a given namespace.
def namespace(ns_key): '''Construct a validation schema for a given namespace. Parameters ---------- ns_key : str Namespace key identifier (eg, 'beat' or 'segment_tut') Returns ------- schema : dict JSON schema of `namespace` ''' if ns_key not in __NAMESPACE__: ...
Construct a validation schema for arrays of a given namespace.
def namespace_array(ns_key): '''Construct a validation schema for arrays of a given namespace. Parameters ---------- ns_key : str Namespace key identifier Returns ------- schema : dict JSON schema of `namespace` observation arrays ''' obs_sch = namespace(ns_key) ...
Return the allowed values for an enumerated namespace.
def values(ns_key): '''Return the allowed values for an enumerated namespace. Parameters ---------- ns_key : str Namespace key identifier Returns ------- values : list Raises ------ NamespaceError If `ns_key` is not found, or does not have enumerated values ...
Get the dtypes associated with the value and confidence fields for a given namespace.
def get_dtypes(ns_key): '''Get the dtypes associated with the value and confidence fields for a given namespace. Parameters ---------- ns_key : str The namespace key in question Returns ------- value_dtype, confidence_dtype : numpy.dtype Type identifiers for value and c...
Print out a listing of available namespaces
def list_namespaces(): '''Print out a listing of available namespaces''' print('{:30s}\t{:40s}'.format('NAME', 'DESCRIPTION')) print('-' * 78) for sch in sorted(__NAMESPACE__): desc = __NAMESPACE__[sch]['description'] desc = (desc[:44] + '..') if len(desc) > 46 else desc print('{...
Get the dtype associated with a jsonschema type definition
def __get_dtype(typespec): '''Get the dtype associated with a jsonschema type definition Parameters ---------- typespec : dict The schema definition Returns ------- dtype : numpy.dtype The associated dtype ''' if 'type' in typespec: return __TYPE_MAP__.get(...
Load the schema file from the package.
def __load_jams_schema(): '''Load the schema file from the package.''' schema_file = os.path.join(SCHEMA_DIR, 'jams_schema.json') jams_schema = None with open(resource_filename(__name__, schema_file), mode='r') as fdesc: jams_schema = json.load(fdesc) if jams_schema is None: raise...
r Load a. lab file as an Annotation object.
def import_lab(namespace, filename, infer_duration=True, **parse_options): r'''Load a .lab file as an Annotation object. .lab files are assumed to have the following format: ``TIME_START\tTIME_END\tANNOTATION`` By default, .lab files are assumed to have columns separated by one or more white-...
Expand a list of relative paths to a give base directory.
def expand_filepaths(base_dir, rel_paths): """Expand a list of relative paths to a give base directory. Parameters ---------- base_dir : str The target base directory rel_paths : list (or list-like) Collection of relative path strings Returns ------- expanded_paths : l...
Safely make a full directory path if it doesn t exist.
def smkdirs(dpath, mode=0o777): """Safely make a full directory path if it doesn't exist. Parameters ---------- dpath : str Path of directory/directories to create mode : int [default=0777] Permissions for the new directories See also -------- os.makedirs """ i...
Naive depth - search into a directory for files with a given extension.
def find_with_extension(in_dir, ext, depth=3, sort=True): """Naive depth-search into a directory for files with a given extension. Parameters ---------- in_dir : str Path to search. ext : str File extension to match. depth : int Depth of directories to search. sort :...
Get the metadata from a jam and an annotation combined as a string.
def get_comments(jam, ann): '''Get the metadata from a jam and an annotation, combined as a string. Parameters ---------- jam : JAMS The jams object ann : Annotation An annotation object Returns ------- comments : str The jam.file_metadata and ann.annotation_me...
Save an annotation as a lab/ csv.
def lab_dump(ann, comment, filename, sep, comment_char): '''Save an annotation as a lab/csv. Parameters ---------- ann : Annotation The annotation object comment : str The comment string header filename : str The output filename sep : str The separator str...
Convert jams to labs.
def convert_jams(jams_file, output_prefix, csv=False, comment_char='#', namespaces=None): '''Convert jams to labs. Parameters ---------- jams_file : str The path on disk to the jams file in question output_prefix : str The file path prefix of the outputs csv : bool Whe...
Parse arguments from the command line
def parse_arguments(args): '''Parse arguments from the command line''' parser = argparse.ArgumentParser(description='Convert JAMS to .lab files') parser.add_argument('-c', '--comma-separated', dest='csv', action='store_true', ...
A decorator to register namespace conversions.
def _conversion(target, source): '''A decorator to register namespace conversions. Usage ----- >>> @conversion('tag_open', 'tag_.*') ... def tag_to_open(annotation): ... annotation.namespace = 'tag_open' ... return annotation ''' def register(func): '''This decorato...
Convert a given annotation to the target namespace.
def convert(annotation, target_namespace): '''Convert a given annotation to the target namespace. Parameters ---------- annotation : jams.Annotation An annotation object target_namespace : str The target namespace Returns ------- mapped_annotation : jams.Annotation ...
Test if an annotation can be mapped to a target namespace
def can_convert(annotation, target_namespace): '''Test if an annotation can be mapped to a target namespace Parameters ---------- annotation : jams.Annotation An annotation object target_namespace : str The target namespace Returns ------- True if `annotation` ...
Convert a pitch_hz annotation to a contour
def pitch_hz_to_contour(annotation): '''Convert a pitch_hz annotation to a contour''' annotation.namespace = 'pitch_contour' data = annotation.pop_data() for obs in data: annotation.append(time=obs.time, duration=obs.duration, confidence=obs.confidence, ...
Convert a pitch_hz annotation to pitch_midi
def note_hz_to_midi(annotation): '''Convert a pitch_hz annotation to pitch_midi''' annotation.namespace = 'note_midi' data = annotation.pop_data() for obs in data: annotation.append(time=obs.time, duration=obs.duration, confidence=obs.confidence, ...
Convert scaper annotations to tag_open
def scaper_to_tag(annotation): '''Convert scaper annotations to tag_open''' annotation.namespace = 'tag_open' data = annotation.pop_data() for obs in data: annotation.append(time=obs.time, duration=obs.duration, confidence=obs.confidence, value=obs.value['label']) ...
This is a decorator which can be used to mark functions as deprecated.
def deprecated(version, version_removed): '''This is a decorator which can be used to mark functions as deprecated. It will result in a warning being emitted when the function is used.''' def __wrapper(func, *args, **kwargs): '''Warn the user, and then proceed.''' code = six.get_functi...
An intelligent wrapper for open.
def _open(name_or_fdesc, mode='r', fmt='auto'): '''An intelligent wrapper for ``open``. Parameters ---------- name_or_fdesc : string-type or open file descriptor If a string type, refers to the path to a file on disk. If an open file descriptor, it is returned as-is. mode : string...
r Load a JAMS Annotation from a file.
def load(path_or_file, validate=True, strict=True, fmt='auto'): r"""Load a JAMS Annotation from a file. Parameters ---------- path_or_file : str or file-like Path to the JAMS file to load OR An open file handle to load from. validate : bool Attempt to validate the ...
Pop a prefix from a query string.
def query_pop(query, prefix, sep='.'): '''Pop a prefix from a query string. Parameters ---------- query : str The query string prefix : str The prefix string to pop, if it exists sep : str The string to separate fields Returns ------- popped : str ...
Test if a string matches a query.
def match_query(string, query): '''Test if a string matches a query. Parameters ---------- string : str The string to test query : string, callable, or object Either a regular expression, callable function, or object. Returns ------- match : bool `True` if: ...
Custom serialization functionality for working with advanced data types.
def serialize_obj(obj): '''Custom serialization functionality for working with advanced data types. - numpy arrays are converted to lists - lists are recursively serialized element-wise ''' if isinstance(obj, np.integer): return int(obj) elif isinstance(obj, np.floating): ret...
Helper function to format repr strings for JObjects and friends.
def summary(obj, indent=0): '''Helper function to format repr strings for JObjects and friends. Parameters ---------- obj The object to repr indent : int >= 0 indent each new line by `indent` spaces Returns ------- r : str If `obj` has a `__summary__` method, i...
Update the attributes of a JObject.
def update(self, **kwargs): '''Update the attributes of a JObject. Parameters ---------- kwargs Keyword arguments of the form `attribute=new_value` Examples -------- >>> J = jams.JObject(foo=5) >>> J.dumps() '{"foo": 5}' >>> J...
Query this object ( and its descendants ).
def search(self, **kwargs): '''Query this object (and its descendants). Parameters ---------- kwargs Each `(key, value)` pair encodes a search field in `key` and a target value in `value`. `key` must be a string, and should correspond to a property i...
Validate a JObject against its schema
def validate(self, strict=True): '''Validate a JObject against its schema Parameters ---------- strict : bool Enforce strict schema validation Returns ------- valid : bool True if the jam validates False if not, and `strict==F...
Append an observation to the data field
def append(self, time=None, duration=None, value=None, confidence=None): '''Append an observation to the data field Parameters ---------- time : float >= 0 duration : float >= 0 The time and duration of the new observation, in seconds value confidence...
Add observations from row - major storage.
def append_records(self, records): '''Add observations from row-major storage. This is primarily useful for deserializing sparsely packed data. Parameters ---------- records : iterable of dicts or Observations Each element of `records` corresponds to one observation...
Add observations from column - major storage.
def append_columns(self, columns): '''Add observations from column-major storage. This is primarily used for deserializing densely packed data. Parameters ---------- columns : dict of lists Keys must be `time, duration, value, confidence`, and each much ...
Validate this annotation object against the JAMS schema and its data against the namespace schema.
def validate(self, strict=True): '''Validate this annotation object against the JAMS schema, and its data against the namespace schema. Parameters ---------- strict : bool If `True`, then schema violations will cause an Exception. If `False`, then schema ...
Trim the annotation and return as a new Annotation object.
def trim(self, start_time, end_time, strict=False): ''' Trim the annotation and return as a new `Annotation` object. Trimming will result in the new annotation only containing observations that occur in the intersection of the time range spanned by the annotation and the time ra...
Slice the annotation and return as a new Annotation object.
def slice(self, start_time, end_time, strict=False): ''' Slice the annotation and return as a new `Annotation` object. Slicing has the same effect as trimming (see `Annotation.trim`) except that while trimming does not modify the start time of the annotation or the observations ...
Replace this observation s data with a fresh container.
def pop_data(self): '''Replace this observation's data with a fresh container. Returns ------- annotation_data : SortedKeyList The original annotation data container ''' data = self.data self.data = SortedKeyList(key=self._key) return data
Extract observation data in a mir_eval - friendly format.
def to_interval_values(self): '''Extract observation data in a `mir_eval`-friendly format. Returns ------- intervals : np.ndarray [shape=(n, 2), dtype=float] Start- and end-times of all valued intervals `intervals[i, :] = [time[i], time[i] + duration[i]]` ...
Extract observation data in a mir_eval - friendly format.
def to_event_values(self): '''Extract observation data in a `mir_eval`-friendly format. Returns ------- times : np.ndarray [shape=(n,), dtype=float] Start-time of all observations labels : list List view of value field. ''' ints, vals = [...
Sample the annotation at specified times.
def to_samples(self, times, confidence=False): '''Sample the annotation at specified times. Parameters ---------- times : np.ndarray, non-negative, ndim=1 The times (in seconds) to sample the annotation confidence : bool If `True`, return both values and...
Render this annotation list in HTML
def to_html(self, max_rows=None): '''Render this annotation list in HTML Returns ------- rendered : str An HTML table containing this annotation's data. ''' n = len(self.data) div_id = _get_divid(self) out = r''' <div class="panel panel-def...
Provides sorting index for Observation objects
def _key(cls, obs): '''Provides sorting index for Observation objects''' if not isinstance(obs, Observation): raise JamsError('{} must be of type jams.Observation'.format(obs)) return obs.time
Filter the annotation array down to only those Annotation objects matching the query.
def search(self, **kwargs): '''Filter the annotation array down to only those Annotation objects matching the query. Parameters ---------- kwargs : search parameters See JObject.search Returns ------- results : AnnotationArray An...
Trim every annotation contained in the annotation array using Annotation. trim and return as a new AnnotationArray.
def trim(self, start_time, end_time, strict=False): ''' Trim every annotation contained in the annotation array using `Annotation.trim` and return as a new `AnnotationArray`. See `Annotation.trim` for details about trimming. This function does not modify the annotations in the o...
Slice every annotation contained in the annotation array using Annotation. slice and return as a new AnnotationArray
def slice(self, start_time, end_time, strict=False): ''' Slice every annotation contained in the annotation array using `Annotation.slice` and return as a new AnnotationArray See `Annotation.slice` for details about slicing. This function does not modify the annotations ...
Add the contents of another jam to this object.
def add(self, jam, on_conflict='fail'): """Add the contents of another jam to this object. Note that, by default, this method fails if file_metadata is not identical and raises a ValueError; either resolve this manually (because conflicts should almost never happen), force an 'overwrite...
Serialize annotation as a JSON formatted stream to file.
def save(self, path_or_file, strict=True, fmt='auto'): """Serialize annotation as a JSON formatted stream to file. Parameters ---------- path_or_file : str or file-like Path to save the JAMS object on disk OR An open file descriptor to write into ...
Validate a JAMS object against the schema.
def validate(self, strict=True): '''Validate a JAMS object against the schema. Parameters ---------- strict : bool If `True`, an exception will be raised on validation failure. If `False`, a warning will be raised on validation failure. Returns -...
Trim all the annotations inside the jam and return as a new JAMS object.
def trim(self, start_time, end_time, strict=False): ''' Trim all the annotations inside the jam and return as a new `JAMS` object. See `Annotation.trim` for details about how the annotations are trimmed. This operation is also documented in the jam-level sandbox ...
Slice all the annotations inside the jam and return as a new JAMS object.
def slice(self, start_time, end_time, strict=False): ''' Slice all the annotations inside the jam and return as a new `JAMS` object. See `Annotation.slice` for details about how the annotations are sliced. This operation is also documented in the jam-level sandbox ...
Pretty - print a jobject.
def pprint_jobject(obj, **kwargs): '''Pretty-print a jobject. Parameters ---------- obj : jams.JObject kwargs additional parameters to `json.dumps` Returns ------- string A simplified display of `obj` contents. ''' obj_simple = {k: v for k, v in six.iteritems(...
Plotting wrapper for labeled intervals
def intervals(annotation, **kwargs): '''Plotting wrapper for labeled intervals''' times, labels = annotation.to_interval_values() return mir_eval.display.labeled_intervals(times, labels, **kwargs)
Plotting wrapper for hierarchical segmentations
def hierarchy(annotation, **kwargs): '''Plotting wrapper for hierarchical segmentations''' htimes, hlabels = hierarchy_flatten(annotation) htimes = [np.asarray(_) for _ in htimes] return mir_eval.display.hierarchy(htimes, hlabels, **kwargs)
Plotting wrapper for pitch contours
def pitch_contour(annotation, **kwargs): '''Plotting wrapper for pitch contours''' ax = kwargs.pop('ax', None) # If the annotation is empty, we need to construct a new axes ax = mir_eval.display.__get_axes(ax=ax)[0] times, values = annotation.to_interval_values() indices = np.unique([v['index...
Plotting wrapper for events
def event(annotation, **kwargs): '''Plotting wrapper for events''' times, values = annotation.to_interval_values() if any(values): labels = values else: labels = None return mir_eval.display.events(times, labels=labels, **kwargs)
Plotting wrapper for beat - position data
def beat_position(annotation, **kwargs): '''Plotting wrapper for beat-position data''' times, values = annotation.to_interval_values() labels = [_['position'] for _ in values] # TODO: plot time signature, measure number return mir_eval.display.events(times, labels=labels, **kwargs)
Plotting wrapper for piano rolls
def piano_roll(annotation, **kwargs): '''Plotting wrapper for piano rolls''' times, midi = annotation.to_interval_values() return mir_eval.display.piano_roll(times, midi=midi, **kwargs)
Visualize a jams annotation through mir_eval
def display(annotation, meta=True, **kwargs): '''Visualize a jams annotation through mir_eval Parameters ---------- annotation : jams.Annotation The annotation to display meta : bool If `True`, include annotation metadata in the figure kwargs Additional keyword argumen...
Display multiple annotations with shared axes
def display_multi(annotations, fig_kw=None, meta=True, **kwargs): '''Display multiple annotations with shared axes Parameters ---------- annotations : jams.AnnotationArray A collection of annotations to display fig_kw : dict Keyword arguments to `plt.figure` meta : bool ...
Generate a click sample.
def mkclick(freq, sr=22050, duration=0.1): '''Generate a click sample. This replicates functionality from mir_eval.sonify.clicks, but exposes the target frequency and duration. ''' times = np.arange(int(sr * duration)) click = np.sin(2 * np.pi * times * freq / float(sr)) click *= np.exp(- ...
Sonify events with clicks.
def clicks(annotation, sr=22050, length=None, **kwargs): '''Sonify events with clicks. This uses mir_eval.sonify.clicks, and is appropriate for instantaneous events such as beats or segment boundaries. ''' interval, _ = annotation.to_interval_values() return filter_kwargs(mir_eval.sonify.clic...
Sonify beats and downbeats together.
def downbeat(annotation, sr=22050, length=None, **kwargs): '''Sonify beats and downbeats together. ''' beat_click = mkclick(440 * 2, sr=sr) downbeat_click = mkclick(440 * 3, sr=sr) intervals, values = annotation.to_interval_values() beats, downbeats = [], [] for time, value in zip(interv...
Sonify multi - level segmentations
def multi_segment(annotation, sr=22050, length=None, **kwargs): '''Sonify multi-level segmentations''' # Pentatonic scale, because why not PENT = [1, 32./27, 4./3, 3./2, 16./9] DURATION = 0.1 h_int, _ = hierarchy_flatten(annotation) if length is None: length = int(sr * (max(np.max(_) ...
Sonify chords
def chord(annotation, sr=22050, length=None, **kwargs): '''Sonify chords This uses mir_eval.sonify.chords. ''' intervals, chords = annotation.to_interval_values() return filter_kwargs(mir_eval.sonify.chords, chords, intervals, fs=sr, length=length...
Sonify pitch contours.
def pitch_contour(annotation, sr=22050, length=None, **kwargs): '''Sonify pitch contours. This uses mir_eval.sonify.pitch_contour, and should only be applied to pitch annotations using the pitch_contour namespace. Each contour is sonified independently, and the resulting waveforms are summed toget...
Sonify a piano - roll
def piano_roll(annotation, sr=22050, length=None, **kwargs): '''Sonify a piano-roll This uses mir_eval.sonify.time_frequency, and is appropriate for sparse transcription data, e.g., annotations in the `note_midi` namespace. ''' intervals, pitches = annotation.to_interval_values() # Constr...
Sonify a jams annotation through mir_eval
def sonify(annotation, sr=22050, duration=None, **kwargs): '''Sonify a jams annotation through mir_eval Parameters ---------- annotation : jams.Annotation The annotation to sonify sr = : positive number The sampling rate of the output waveform duration : float (optional) ...
Validate a jams file against a schema
def validate(schema_file=None, jams_files=None): '''Validate a jams file against a schema''' schema = load_json(schema_file) for jams_file in jams_files: try: jams = load_json(jams_file) jsonschema.validate(jams, schema) print '{:s} was successfully validated'.f...
Add SASL features to the <features/ > element of the stream.
def make_stream_features(self, stream, features): """Add SASL features to the <features/> element of the stream. [receving entity only] :returns: update <features/> element.""" mechs = self.settings['sasl_mechanisms'] if mechs and not stream.authenticated: sub = Ele...
Process incoming <stream: features/ > element.
def handle_stream_features(self, stream, features): """Process incoming <stream:features/> element. [initiating entity only] """ element = features.find(MECHANISMS_TAG) self.peer_sasl_mechanisms = [] if element is None: return None for sub in element:...
Process incoming <sasl: auth/ > element.
def process_sasl_auth(self, stream, element): """Process incoming <sasl:auth/> element. [receiving entity only] """ if self.authenticator: logger.debug("Authentication already started") return False password_db = self.settings["password_database"] ...
Handle successful authentication.
def _handle_auth_success(self, stream, success): """Handle successful authentication. Send <success/> and mark the stream peer authenticated. [receiver only] """ if not self._check_authorization(success.properties, stream): element = ElementTree.Element(FAILURE_TAG)...
Process incoming <sasl: challenge/ > element.
def _process_sasl_challenge(self, stream, element): """Process incoming <sasl:challenge/> element. [initiating entity only] """ if not self.authenticator: logger.debug("Unexpected SASL challenge") return False content = element.text.encode("us-ascii") ...
Process incoming <sasl: response/ > element.
def _process_sasl_response(self, stream, element): """Process incoming <sasl:response/> element. [receiving entity only] """ if not self.authenticator: logger.debug("Unexpected SASL response") return False content = element.text.encode("us-ascii") ...
Check authorization id and other properties returned by the authentication mechanism.
def _check_authorization(self, properties, stream): """Check authorization id and other properties returned by the authentication mechanism. [receiving entity only] Allow only no authzid or authzid equal to current username@domain FIXME: other rules in s2s :Parameters...
Process incoming <sasl: success/ > element.
def _process_sasl_success(self, stream, element): """Process incoming <sasl:success/> element. [initiating entity only] """ if not self.authenticator: logger.debug("Unexpected SASL response") return False content = element.text if content: ...
Process incoming <sasl: failure/ > element.
def _process_sasl_failure(self, stream, element): """Process incoming <sasl:failure/> element. [initiating entity only] """ _unused = stream if not self.authenticator: logger.debug("Unexpected SASL response") return False logger.debug("SASL authe...
Process incoming <sasl: abort/ > element.
def _process_sasl_abort(self, stream, element): """Process incoming <sasl:abort/> element. [receiving entity only]""" _unused, _unused = stream, element if not self.authenticator: logger.debug("Unexpected SASL response") return False self.authenticator =...
Start SASL authentication process.
def _sasl_authenticate(self, stream, username, authzid): """Start SASL authentication process. [initiating entity only] :Parameters: - `username`: user name. - `authzid`: authorization ID. - `mechanism`: SASL mechanism to use.""" if not stream.initia...
Method decorator generator for decorating event handlers.
def timeout_handler(interval, recurring = None): """Method decorator generator for decorating event handlers. To be used on `TimeoutHandler` subclass methods only. :Parameters: - `interval`: interval (in seconds) before the method will be called. - `recurring`: When `True`, the handler wil...
Schedule function to be called from the main loop after delay seconds.
def delayed_call(self, delay, function): """Schedule function to be called from the main loop after `delay` seconds. :Parameters: - `delay`: seconds to wait :Types: - `delay`: `float` """ main_loop = self handler = [] class Delayed...
Make a RosterItem from an XML element.
def from_xml(cls, element): """Make a RosterItem from an XML element. :Parameters: - `element`: the XML element :Types: - `element`: :etree:`ElementTree.Element` :return: a freshly created roster item :returntype: `cls` """ if element.tag...
Make an XML element from self.
def as_xml(self, parent = None): """Make an XML element from self. :Parameters: - `parent`: Parent element :Types: - `parent`: :etree:`ElementTree.Element` """ if parent is not None: element = ElementTree.SubElement(parent, ITEM_TAG) e...
Check if self is valid roster item.
def _verify(self, valid_subscriptions, fix): """Check if `self` is valid roster item. Valid item must have proper `subscription` and valid value for 'ask'. :Parameters: - `valid_subscriptions`: sequence of valid subscription values - `fix`: if `True` than replace invali...
Check if self is valid roster item.
def verify_roster_result(self, fix = False): """Check if `self` is valid roster item. Valid item must have proper `subscription` value other than 'remove' and valid value for 'ask'. :Parameters: - `fix`: if `True` than replace invalid 'subscription' and 'ask' ...
Check if self is valid roster push item.
def verify_roster_push(self, fix = False): """Check if `self` is valid roster push item. Valid item must have proper `subscription` value other and valid value for 'ask'. :Parameters: - `fix`: if `True` than replace invalid 'subscription' and 'ask' values with...
Check if self is valid roster set item.
def verify_roster_set(self, fix = False, settings = None): """Check if `self` is valid roster set item. For use on server to validate incoming roster sets. Valid item must have proper `subscription` value other and valid value for 'ask'. The lengths of name and group names must fit the...
Set of groups defined in the roster.
def groups(self): """Set of groups defined in the roster. :Return: the groups :ReturnType: `set` of `unicode` """ groups = set() for item in self._items: groups |= item.groups return groups
Return a list of items with given name.
def get_items_by_name(self, name, case_sensitive = True): """ Return a list of items with given name. :Parameters: - `name`: name to look-up - `case_sensitive`: if `False` the matching will be case insensitive. :Types: - `name`: `unicode...