_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
31
13.1k
language
stringclasses
1 value
meta_information
dict
q259500
beat_position
validation
def beat_position(annotation, **kwargs): '''Plotting wrapper for beat-position data''' times, values = annotation.to_interval_values() labels = [_['position'] for _ in values] #
python
{ "resource": "" }
q259501
piano_roll
validation
def piano_roll(annotation, **kwargs): '''Plotting wrapper for piano rolls''' times, midi = annotation.to_interval_values()
python
{ "resource": "" }
q259502
display
validation
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 arguments to mir_eval.display functions Returns ------- ax Axis handles for the new display Raises ------ NamespaceError If the annotation cannot be visualized ''' for namespace, func in six.iteritems(VIZ_MAPPING): try: ann = coerce_annotation(annotation, namespace) axes = func(ann, **kwargs) # Title should correspond to original namespace, not the coerced version axes.set_title(annotation.namespace) if meta: description = pprint_jobject(annotation.annotation_metadata, indent=2) anchored_box = AnchoredText(description.strip('\n'),
python
{ "resource": "" }
q259503
display_multi
validation
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 If `True`, display annotation metadata for each annotation kwargs Additional keyword arguments to the `mir_eval.display` routines Returns ------- fig The created figure axs List of subplot axes corresponding to each displayed annotation ''' if fig_kw is None:
python
{ "resource": "" }
q259504
mkclick
validation
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 =
python
{ "resource": "" }
q259505
clicks
validation
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. '''
python
{ "resource": "" }
q259506
downbeat
validation
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(intervals[:, 0], values): if value['position'] == 1: downbeats.append(time) else: beats.append(time) if length is None: length = int(sr * np.max(intervals)) + len(beat_click) + 1 y = filter_kwargs(mir_eval.sonify.clicks,
python
{ "resource": "" }
q259507
multi_segment
validation
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(_) for _ in h_int) + 1. / DURATION) + 1) y = 0.0 for ints, (oc, scale) in zip(h_int, product(range(3, 3 + len(h_int)),
python
{ "resource": "" }
q259508
pitch_contour
validation
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 together. ''' # Map contours to lists of observations times = defaultdict(list) freqs = defaultdict(list) for obs in annotation: times[obs.value['index']].append(obs.time) freqs[obs.value['index']].append(obs.value['frequency'] * (-1)**(~obs.value['voiced']))
python
{ "resource": "" }
q259509
piano_roll
validation
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() # Construct the pitchogram pitch_map = {f: idx for idx, f in enumerate(np.unique(pitches))} gram = np.zeros((len(pitch_map), len(intervals)))
python
{ "resource": "" }
q259510
sonify
validation
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) Optional length (in seconds) of the output waveform kwargs Additional keyword arguments to mir_eval.sonify functions Returns ------- y_sonified : np.ndarray The waveform of the sonified annotation Raises ------ NamespaceError If the annotation has an un-sonifiable namespace ''' length = None if duration is None: duration = annotation.duration if duration is not None: length = int(duration * sr) # If the annotation can be directly sonified, try that first if annotation.namespace in SONIFY_MAPPING: ann = coerce_annotation(annotation, annotation.namespace) return SONIFY_MAPPING[annotation.namespace](ann,
python
{ "resource": "" }
q259511
validate
validation
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)
python
{ "resource": "" }
q259512
StreamSASLHandler._handle_auth_success
validation
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)
python
{ "resource": "" }
q259513
StreamSASLHandler._check_authorization
validation
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: - `properties`: data obtained during authentication :Types: - `properties`: mapping
python
{ "resource": "" }
q259514
StreamSASLHandler._sasl_authenticate
validation
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.initiator: raise SASLAuthenticationFailed("Only initiating entity start" " SASL authentication") if stream.features is None or not self.peer_sasl_mechanisms: raise SASLNotAvailable("Peer doesn't support SASL") props = dict(stream.auth_properties) if not props.get("service-domain") and ( stream.peer and stream.peer.domain): props["service-domain"] = stream.peer.domain if username is not None: props["username"] = username if authzid is not None: props["authzid"] = authzid if "password" in self.settings: props["password"] = self.settings["password"] props["available_mechanisms"] = self.peer_sasl_mechanisms enabled = sasl.filter_mechanism_list( self.settings['sasl_mechanisms'], props, self.settings['insecure_auth']) if not enabled: raise SASLNotAvailable( "None of SASL mechanism selected can be used") props["enabled_mechanisms"] = enabled mechanism = None for mech in enabled: if mech in self.peer_sasl_mechanisms: mechanism = mech break if not mechanism: raise SASLMechanismNotAvailable("Peer doesn't support any
python
{ "resource": "" }
q259515
timeout_handler
validation
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 will be called each `interval` seconds, when `False` it will be called only once. If `True`, then the handler should return the next interval or `None` if it should not be called again. :Types:
python
{ "resource": "" }
q259516
MainLoop.delayed_call
validation
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 DelayedCallHandler(TimeoutHandler): """Wrapper timeout handler class for the delayed call.""" # pylint: disable=R0903 @timeout_handler(delay, False) def callback(self):
python
{ "resource": "" }
q259517
RosterItem.from_xml
validation
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 != ITEM_TAG: raise ValueError("{0!r} is not a roster item".format(element)) try: jid = JID(element.get("jid")) except ValueError: raise BadRequestProtocolError(u"Bad item JID") subscription = element.get("subscription") ask = element.get("ask") name = element.get("name") duplicate_group = False groups = set() for child in element: if child.tag != GROUP_TAG: continue group = child.text if group is None: group = u"" if group in groups:
python
{ "resource": "" }
q259518
RosterItem.as_xml
validation
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) else: element = ElementTree.Element(ITEM_TAG)
python
{ "resource": "" }
q259519
RosterItem.verify_roster_push
validation
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'
python
{ "resource": "" }
q259520
RosterItem.verify_roster_set
validation
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 configured limits. :Parameters: - `fix`: if `True` than replace invalid 'subscription' and 'ask' values with right defaults - `settings`: settings object providing the name limits :Types: - `fix`: `bool` - `settings`: `XMPPSettings` :Raise: `BadRequestProtocolError` if the item is invalid. """ # pylint: disable=R0912 try: self._verify((None, u"remove"), fix) except ValueError, err: raise BadRequestProtocolError(unicode(err)) if self.ask: if fix: self.ask = None else: raise BadRequestProtocolError("'ask' in roster set") if self.approved: if fix: self.approved =
python
{ "resource": "" }
q259521
Roster.groups
validation
def groups(self): """Set of groups defined in the roster. :Return: the groups :ReturnType: `set` of
python
{ "resource": "" }
q259522
Roster.get_items_by_name
validation
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` - `case_sensitive`: `bool` :Returntype: `list` of `RosterItem` """ if not case_sensitive and name: name = name.lower()
python
{ "resource": "" }
q259523
Roster.get_items_by_group
validation
def get_items_by_group(self, group, case_sensitive = True): """ Return a list of items within a given group. :Parameters: - `name`: name to look-up - `case_sensitive`: if `False` the matching will be case insensitive. :Types: - `name`: `unicode` - `case_sensitive`: `bool` :Returntype: `list` of `RosterItem`
python
{ "resource": "" }
q259524
Roster.add_item
validation
def add_item(self, item, replace = False): """ Add an item to the roster. This will not automatically update the roster on the server. :Parameters: - `item`: the item to add - `replace`: if `True` then existing item will be replaced, otherwise a `ValueError` will be raised on conflict :Types: - `item`: `RosterItem` - `replace`: `bool` """
python
{ "resource": "" }
q259525
Roster.remove_item
validation
def remove_item(self, jid): """Remove item from the roster. :Parameters: - `jid`: JID of the item to remove :Types: - `jid`: `JID` """ if jid not in self._jids: raise KeyError(jid)
python
{ "resource": "" }
q259526
RosterClient.load_roster
validation
def load_roster(self, source): """Load roster from an XML file. Can be used before the connection is started to load saved roster copy, for efficient retrieval of versioned roster. :Parameters: - `source`: file name or a file object :Types: - `source`: `str` or file-like object """ try: tree = ElementTree.parse(source) except ElementTree.ParseError, err:
python
{ "resource": "" }
q259527
RosterClient.save_roster
validation
def save_roster(self, dest, pretty = True): """Save the roster to an XML file. Can be used to save the last know roster copy for faster loading of a verisoned roster (if server supports that). :Parameters: - `dest`: file name or a file object - `pretty`: pretty-format the roster XML :Types: - `dest`: `str` or file-like object - `pretty`: `bool` """ if self.roster is None: raise ValueError("No roster") element = self.roster.as_xml() if pretty: if len(element): element.text = u'\n ' p_child = None for child in element: if p_child is not None: p_child.tail = u'\n ' if len(child):
python
{ "resource": "" }
q259528
RosterClient.handle_got_features_event
validation
def handle_got_features_event(self, event): """Check for roster related features in the stream features received and set `server_features` accordingly. """ server_features = set() logger.debug("Checking roster-related features") if event.features.find(FEATURE_ROSTERVER) is not None: logger.debug(" Roster versioning available")
python
{ "resource": "" }
q259529
RosterClient.handle_authorized_event
validation
def handle_authorized_event(self, event): """Request roster upon login.""" self.server = event.authorized_jid.bare() if "versioning" in self.server_features: if self.roster is not None and self.roster.version is not None:
python
{ "resource": "" }
q259530
RosterClient.request_roster
validation
def request_roster(self, version = None): """Request roster from server. :Parameters: - `version`: if not `None` versioned roster will be requested for given local version. Use "" to request full roster.
python
{ "resource": "" }
q259531
RosterClient._get_success
validation
def _get_success(self, stanza): """Handle successful response to the roster request. """ payload = stanza.get_payload(RosterPayload) if payload is None: if "versioning" in self.server_features and self.roster: logger.debug("Server will send roster delta in pushes") else: logger.warning("Bad roster response (no payload)") self._event_queue.put(RosterNotReceivedEvent(self, stanza)) return
python
{ "resource": "" }
q259532
RosterClient._get_error
validation
def _get_error(self, stanza): """Handle failure of the roster request. """ if stanza: logger.debug(u"Roster request failed: {0}".format(
python
{ "resource": "" }
q259533
RosterClient.handle_roster_push
validation
def handle_roster_push(self, stanza): """Handle a roster push received from server. """ if self.server is None and stanza.from_jid: logger.debug(u"Server address not known, cannot verify roster push" " from {0}".format(stanza.from_jid)) return stanza.make_error_response(u"service-unavailable") if self.server and stanza.from_jid and stanza.from_jid != self.server: logger.debug(u"Roster push from invalid source: {0}".format( stanza.from_jid)) return stanza.make_error_response(u"service-unavailable") payload = stanza.get_payload(RosterPayload) if len(payload) != 1: logger.warning("Bad roster push received ({0} items)" .format(len(payload))) return stanza.make_error_response(u"bad-request") if self.roster is None:
python
{ "resource": "" }
q259534
RosterClient.add_item
validation
def add_item(self, jid, name = None, groups = None, callback = None, error_callback = None): """Add a contact to the roster. :Parameters: - `jid`: contact's jid - `name`: name for the contact - `groups`: sequence of group names the contact should belong to - `callback`: function to call when the request succeeds. It should accept a single argument - a `RosterItem` describing the requested change - `error_callback`: function to call when the request fails. It should accept a single argument - an error stanza received
python
{ "resource": "" }
q259535
RosterClient.update_item
validation
def update_item(self, jid, name = NO_CHANGE, groups = NO_CHANGE, callback = None, error_callback = None): """Modify a contact in the roster. :Parameters: - `jid`: contact's jid - `name`: a new name for the contact - `groups`: a sequence of group names the contact should belong to - `callback`: function to call when the request succeeds. It should accept a single argument - a `RosterItem` describing the
python
{ "resource": "" }
q259536
RosterClient.remove_item
validation
def remove_item(self, jid, callback = None, error_callback = None): """Remove a contact from the roster. :Parameters: - `jid`: contact's jid - `callback`: function to call when the request succeeds. It should accept a single argument - a `RosterItem` describing the requested change - `error_callback`: function to call when the request fails. It should accept a single argument - an error stanza received
python
{ "resource": "" }
q259537
RosterClient._roster_set
validation
def _roster_set(self, item, callback, error_callback): """Send a 'roster set' to the server. :Parameters: - `item`: the requested change :Types: - `item`: `RosterItem` """ stanza = Iq(to_jid = self.server, stanza_type = "set") payload = RosterPayload([item]) stanza.set_payload(payload) def success_cb(result_stanza): """Success callback for roster set.""" if callback: callback(item) def error_cb(error_stanza): """Error callback for
python
{ "resource": "" }
q259538
MucXBase.free
validation
def free(self): """ Unlink and free the XML node owned by `self`. """ if not self.borrowed:
python
{ "resource": "" }
q259539
MucXBase.xpath_eval
validation
def xpath_eval(self,expr): """ Evaluate XPath expression in context of `self.xmlnode`. :Parameters: - `expr`: the XPath expression :Types: - `expr`: `unicode` :return: the result of the expression evaluation. :returntype: list of `libxml2.xmlNode` """ ctxt
python
{ "resource": "" }
q259540
MucX.set_history
validation
def set_history(self, parameters): """ Set history parameters. Types: - `parameters`: `HistoryParameters` """ for child in xml_element_iter(self.xmlnode.children): if get_node_ns_uri(child) == MUC_NS and child.name == "history": child.unlinkNode() child.freeNode() break if parameters.maxchars and parameters.maxchars < 0: raise ValueError("History parameter maxchars must be positive") if parameters.maxstanzas and parameters.maxstanzas < 0: raise ValueError("History parameter maxstanzas must be positive") if parameters.maxseconds and parameters.maxseconds < 0: raise ValueError("History parameter maxseconds must be positive") hnode=self.xmlnode.newChild(self.xmlnode.ns(), "history", None)
python
{ "resource": "" }
q259541
MucX.get_history
validation
def get_history(self): """Return history parameters carried by the stanza. :returntype: `HistoryParameters`""" for child in xml_element_iter(self.xmlnode.children): if get_node_ns_uri(child) == MUC_NS and child.name == "history": maxchars = from_utf8(child.prop("maxchars")) if maxchars is not None: maxchars = int(maxchars) maxstanzas = from_utf8(child.prop("maxstanzas")) if maxstanzas is not None:
python
{ "resource": "" }
q259542
MucX.set_password
validation
def set_password(self, password): """Set password for the MUC request. :Parameters: - `password`: password :Types: - `password`: `unicode`""" for child in xml_element_iter(self.xmlnode.children): if get_node_ns_uri(child) == MUC_NS and child.name == "password":
python
{ "resource": "" }
q259543
MucX.get_password
validation
def get_password(self): """Get password from the MUC request. :returntype: `unicode` """ for child in xml_element_iter(self.xmlnode.children): if get_node_ns_uri(child) == MUC_NS
python
{ "resource": "" }
q259544
MucItem.__init
validation
def __init(self,affiliation,role,jid=None,nick=None,actor=None,reason=None): """Initialize a `MucItem` object from a set of attributes. :Parameters: - `affiliation`: affiliation of the user. - `role`: role of the user. - `jid`: JID of the user. - `nick`: nickname of the user. - `actor`: actor modyfying the user data. - `reason`: reason of change of the user data. :Types: - `affiliation`: `str` - `role`: `str` - `jid`: `JID` - `nick`: `unicode` - `actor`: `JID` - `reason`: `unicode` """ if not affiliation: affiliation=None elif affiliation not in affiliations: raise ValueError("Bad affiliation") self.affiliation=affiliation
python
{ "resource": "" }
q259545
MucItem.__from_xmlnode
validation
def __from_xmlnode(self, xmlnode): """Initialize a `MucItem` object from an XML node. :Parameters: - `xmlnode`: the XML node. :Types: - `xmlnode`: `libxml2.xmlNode` """ actor=None reason=None n=xmlnode.children while n: ns=n.ns() if ns and ns.getContent()!=MUC_USER_NS: continue if n.name=="actor": actor=n.getContent() if n.name=="reason":
python
{ "resource": "" }
q259546
MucStatus.__init
validation
def __init(self,code): """Initialize a `MucStatus` element from a status code. :Parameters: - `code`: the status code. :Types: - `code`: `int` """
python
{ "resource": "" }
q259547
MucUserX.get_items
validation
def get_items(self): """Get a list of objects describing the content of `self`. :return: the list of objects. :returntype: `list` of `MucItemBase` (`MucItem` and/or `MucStatus`) """ if not self.xmlnode.children: return [] ret=[] n=self.xmlnode.children while n: ns=n.ns() if ns and ns.getContent()!=self.ns:
python
{ "resource": "" }
q259548
MucUserX.add_item
validation
def add_item(self,item): """Add an item to `self`. :Parameters: - `item`: the item to add. :Types:
python
{ "resource": "" }
q259549
MucStanzaExt.get_muc_child
validation
def get_muc_child(self): """ Get the MUC specific payload element. :return: the object describing the stanza payload in MUC namespace. :returntype: `MucX` or `MucUserX` or `MucAdminQuery` or `MucOwnerX` """ if self.muc_child: return self.muc_child if not self.xmlnode.children: return None n=self.xmlnode.children while n: if n.name not in ("x","query"): n=n.next continue ns=n.ns() if not ns: n=n.next continue ns_uri=ns.getContent() if (n.name,ns_uri)==("x",MUC_NS): self.muc_child=MucX(n) return self.muc_child
python
{ "resource": "" }
q259550
MucStanzaExt.clear_muc_child
validation
def clear_muc_child(self): """ Remove the MUC specific stanza payload element. """ if self.muc_child: self.muc_child.free_borrowed() self.muc_child=None if not self.xmlnode.children: return n=self.xmlnode.children while n: if n.name not in ("x","query"): n=n.next continue
python
{ "resource": "" }
q259551
MucPresence.make_join_request
validation
def make_join_request(self, password = None, history_maxchars = None, history_maxstanzas = None, history_seconds = None, history_since = None): """ Make the presence stanza a MUC room join request. :Parameters: - `password`: password to the room. - `history_maxchars`: limit of the total number of characters in history. - `history_maxstanzas`: limit of the total number of messages in history. - `history_seconds`: send only messages received in the last `seconds` seconds. - `history_since`: Send only the messages received since the dateTime specified (UTC). :Types: - `password`: `unicode` - `history_maxchars`: `int` - `history_maxstanzas`: `int` - `history_seconds`: `int` - `history_since`: `datetime.datetime` """
python
{ "resource": "" }
q259552
MucPresence.get_join_info
validation
def get_join_info(self): """If `self` is a MUC room join request return the information contained. :return: the join request details or `None`. :returntype: `MucX` """ x=self.get_muc_child()
python
{ "resource": "" }
q259553
MucIq.make_kick_request
validation
def make_kick_request(self,nick,reason): """ Make the iq stanza a MUC room participant kick request. :Parameters: - `nick`: nickname of user to kick. - `reason`: reason of the kick. :Types:
python
{ "resource": "" }
q259554
nfkc
validation
def nfkc(data): """Do NFKC normalization of Unicode data. :Parameters: - `data`: list of Unicode characters or
python
{ "resource": "" }
q259555
set_stringprep_cache_size
validation
def set_stringprep_cache_size(size): """Modify stringprep cache size. :Parameters: - `size`: new cache size """ # pylint: disable-msg=W0603 global _stringprep_cache_size _stringprep_cache_size = size if len(Profile.cache_items) > size: remove = Profile.cache_items[:-size] for profile, key in remove:
python
{ "resource": "" }
q259556
Profile.map
validation
def map(self, data): """Mapping part of string preparation.""" result = [] for char in data: ret = None for lookup in self.mapping: ret = lookup(char) if ret is not None: break
python
{ "resource": "" }
q259557
Profile.prohibit
validation
def prohibit(self, data): """Checks for prohibited characters.""" for char in data: for lookup in self.prohibited: if lookup(char):
python
{ "resource": "" }
q259558
Profile.check_unassigned
validation
def check_unassigned(self, data): """Checks for unassigned character codes.""" for char in data: for lookup in self.unassigned: if lookup(char):
python
{ "resource": "" }
q259559
Profile.check_bidi
validation
def check_bidi(data): """Checks if sting is valid for bidirectional printing.""" has_l = False has_ral = False for char in data: if stringprep.in_table_d1(char): has_ral = True elif stringprep.in_table_d2(char): has_l = True if has_l and has_ral: raise StringprepError("Both RandALCat and LCat characters present") if has_ral and (not stringprep.in_table_d1(data[0])
python
{ "resource": "" }
q259560
hold_exception
validation
def hold_exception(method): """Decorator for glib callback methods of GLibMainLoop used to store the exception raised.""" @functools.wraps(method) def wrapper(self, *args, **kwargs): """Wrapper for methods decorated with `hold_exception`.""" # pylint: disable=W0703,W0212 try: return method(self, *args, **kwargs) except Exception: if self.exc_info:
python
{ "resource": "" }
q259561
GLibMainLoop._configure_io_handler
validation
def _configure_io_handler(self, handler): """Register an io-handler with the glib main loop.""" if self.check_events(): return if handler in self._unprepared_handlers: old_fileno = self._unprepared_handlers[handler] prepared = self._prepare_io_handler(handler) else: old_fileno = None prepared = True fileno = handler.fileno() if old_fileno is not None and fileno != old_fileno: tag = self._io_sources.pop(handler, None) if tag is not None: glib.source_remove(tag) if not prepared: self._unprepared_handlers[handler] = fileno if fileno is None: logger.debug(" {0!r}.fileno() is None, not polling" .format(handler)) return
python
{ "resource": "" }
q259562
GLibMainLoop._prepare_pending
validation
def _prepare_pending(self): """Prepare pending handlers. """ if not self._unprepared_pending: return
python
{ "resource": "" }
q259563
GLibMainLoop._prepare_io_handler_cb
validation
def _prepare_io_handler_cb(self, handler): """Timeout callback called to try prepare an IOHandler again.""" self._anything_done = True logger.debug("_prepar_io_handler_cb called for {0!r}".format(handler))
python
{ "resource": "" }
q259564
GLibMainLoop._timeout_cb
validation
def _timeout_cb(self, method): """Call the timeout handler due. """ self._anything_done = True logger.debug("_timeout_cb() called for: {0!r}".format(method)) result = method() # pylint: disable=W0212 rec = method._pyxmpp_recurring if rec: self._prepare_pending() return True if rec is None and result is not None: logger.debug(" auto-recurring, restarting in {0} s"
python
{ "resource": "" }
q259565
GLibMainLoop._loop_timeout_cb
validation
def _loop_timeout_cb(self, main_loop): """Stops the loop after the time specified in the `loop` call. """
python
{ "resource": "" }
q259566
stanza_factory
validation
def stanza_factory(element, return_path = None, language = None): """Creates Iq, Message or Presence object for XML stanza `element` :Parameters: - `element`: the stanza XML element - `return_path`: object through which responses to this stanza should be sent (will be weakly referenced by the stanza object). - `language`: default language for the stanza :Types: - `element`: :etree:`ElementTree.Element` - `return_path`: `StanzaRoute` - `language`: `unicode` """ tag = element.tag if tag.endswith("}iq") or tag == "iq": return Iq(element, return_path = return_path, language = language) if tag.endswith("}message")
python
{ "resource": "" }
q259567
StanzaProcessor._process_handler_result
validation
def _process_handler_result(self, response): """Examines out the response returned by a stanza handler and sends all stanzas provided. :Parameters: - `response`: the response to process. `None` or `False` means 'not handled'. `True` means 'handled'. Stanza or stanza list means handled with the stanzas to send back :Types: - `response`: `bool` or `Stanza` or iterable of `Stanza` :Returns: - `True`: if `response` is `Stanza`, iterable or `True` (meaning the stanza was processed). - `False`: when `response` is `False` or `None` :returntype: `bool` """ if response is None or response is False: return False if isinstance(response, Stanza): self.send(response) return True try:
python
{ "resource": "" }
q259568
StanzaProcessor._process_iq_response
validation
def _process_iq_response(self, stanza): """Process IQ stanza of type 'response' or 'error'. :Parameters: - `stanza`: the stanza received :Types: - `stanza`: `Iq` If a matching handler is available pass the stanza to it. Otherwise ignore it if it is "error" or "result" stanza or return "feature-not-implemented" error if it is "get" or "set". """ stanza_id = stanza.stanza_id from_jid = stanza.from_jid if from_jid: ufrom = from_jid.as_unicode() else: ufrom = None res_handler = err_handler = None try: res_handler, err_handler = self._iq_response_handlers.pop( (stanza_id, ufrom)) except KeyError: logger.debug("No response
python
{ "resource": "" }
q259569
StanzaProcessor.process_iq
validation
def process_iq(self, stanza): """Process IQ stanza received. :Parameters: - `stanza`: the stanza received :Types: - `stanza`: `Iq` If a matching handler is available pass the stanza to it. Otherwise ignore it if it is "error" or "result" stanza or return "feature-not-implemented" error if it is "get" or "set".""" typ = stanza.stanza_type if typ in ("result", "error"): return self._process_iq_response(stanza) if typ not in ("get", "set"): raise BadRequestProtocolError("Bad <iq/> type") logger.debug("Handling <iq type='{0}'> stanza: {1!r}".format( stanza, typ)) payload = stanza.get_payload(None) logger.debug(" payload: {0!r}".format(payload)) if not payload: raise BadRequestProtocolError("<iq/> stanza with no child element") handler = self._get_iq_handler(typ, payload)
python
{ "resource": "" }
q259570
StanzaProcessor.__try_handlers
validation
def __try_handlers(self, handler_list, stanza, stanza_type = None): """ Search the handler list for handlers matching given stanza type and payload namespace. Run the handlers found ordering them by priority until the first one which returns `True`. :Parameters: - `handler_list`: list of available handlers - `stanza`: the stanza to handle - `stanza_type`: stanza type override (value of its "type" attribute) :return: result of the last handler or `False` if no handler was found. """ # pylint: disable=W0212
python
{ "resource": "" }
q259571
StanzaProcessor.process_message
validation
def process_message(self, stanza): """Process message stanza. Pass it to a handler of the stanza's type and payload namespace. If no handler for the actual stanza type succeeds then hadlers for type "normal" are used. :Parameters: - `stanza`: message stanza to be handled """ stanza_type = stanza.stanza_type if stanza_type is None: stanza_type = "normal" if self.__try_handlers(self._message_handlers, stanza,
python
{ "resource": "" }
q259572
StanzaProcessor.process_presence
validation
def process_presence(self, stanza): """Process presence stanza. Pass it to a handler of the stanza's type and payload namespace. :Parameters: - `stanza`: presence stanza to be handled
python
{ "resource": "" }
q259573
StanzaProcessor.route_stanza
validation
def route_stanza(self, stanza): """Process stanza not addressed to us. Return "recipient-unavailable" return if it is not "error" nor "result" stanza. This method should be overriden in derived classes if they
python
{ "resource": "" }
q259574
StanzaProcessor.process_stanza
validation
def process_stanza(self, stanza): """Process stanza received from the stream. First "fix" the stanza with `self.fix_in_stanza()`, then pass it to `self.route_stanza()` if it is not directed to `self.me` and `self.process_all_stanzas` is not True. Otherwise stanza is passwd to `self.process_iq()`, `self.process_message()` or `self.process_presence()` appropriately. :Parameters: - `stanza`: the stanza received. :returns: `True` when stanza was handled """ self.fix_in_stanza(stanza) to_jid = stanza.to_jid if not self.process_all_stanzas and to_jid and ( to_jid != self.me and to_jid.bare() != self.me.bare()): return self.route_stanza(stanza) try: if isinstance(stanza, Iq): if self.process_iq(stanza): return True elif isinstance(stanza, Message): if self.process_message(stanza): return True
python
{ "resource": "" }
q259575
StanzaProcessor.set_response_handlers
validation
def set_response_handlers(self, stanza, res_handler, err_handler, timeout_handler = None, timeout = None): """Set response handler for an IQ "get" or "set" stanza. This should be called before the stanza is sent. :Parameters: - `stanza`: an IQ stanza - `res_handler`: result handler for the stanza. Will be called when matching <iq type="result"/> is received. Its only argument will be the stanza received. The handler may return a stanza or list of stanzas which should be sent in response. - `err_handler`: error handler for the stanza. Will be called when matching <iq type="error"/> is received. Its only argument will be the stanza received. The handler may return a stanza or list of stanzas which should be sent in response but this feature should rather not be used (it is better not to respond to 'error' stanzas). - `timeout_handler`: timeout handler for the stanza. Will be called (with no arguments) when no matching <iq type="result"/>
python
{ "resource": "" }
q259576
StanzaProcessor._set_response_handlers
validation
def _set_response_handlers(self, stanza, res_handler, err_handler, timeout_handler = None, timeout = None): """Same as `set_response_handlers` but assume `self.lock` is acquired.""" # pylint: disable-msg=R0913 self.fix_out_stanza(stanza) to_jid = stanza.to_jid if to_jid: to_jid = unicode(to_jid) if timeout_handler: def callback(dummy1, dummy2):
python
{ "resource": "" }
q259577
StanzaProcessor.setup_stanza_handlers
validation
def setup_stanza_handlers(self, handler_objects, usage_restriction): """Install stanza handlers provided by `handler_objects`""" # pylint: disable=W0212 iq_handlers = {"get": {}, "set": {}} message_handlers = [] presence_handlers = [] for obj in handler_objects: if not isinstance(obj, XMPPFeatureHandler): continue obj.stanza_processor = self for dummy, handler in inspect.getmembers(obj, callable): if not hasattr(handler, "_pyxmpp_stanza_handled"): continue element_name, stanza_type = handler._pyxmpp_stanza_handled restr = handler._pyxmpp_usage_restriction if restr and restr != usage_restriction: continue if element_name == "iq": payload_class = handler._pyxmpp_payload_class_handled payload_key = handler._pyxmpp_payload_key if (payload_class, payload_key) in iq_handlers[stanza_type]:
python
{ "resource": "" }
q259578
StanzaProcessor.send
validation
def send(self, stanza): """Send a stanza somwhere. The default implementation sends it via the `uplink` if it is defined or raises the `NoRouteError`. :Parameters: - `stanza`: the stanza to send.
python
{ "resource": "" }
q259579
MainLoopBase.check_events
validation
def check_events(self): """Call the event dispatcher. Quit the main loop when the `QUIT` event is reached.
python
{ "resource": "" }
q259580
MainLoopBase._call_timeout_handlers
validation
def _call_timeout_handlers(self): """Call the timeout handlers due. :Return: (next_event_timeout, sources_handled) tuple. next_event_timeout is number of seconds until the next timeout event, sources_handled is number of handlers called. """ sources_handled = 0 now = time.time() schedule = None while self._timeout_handlers: schedule, handler = self._timeout_handlers[0] if schedule <= now: # pylint: disable-msg=W0212 logger.debug("About to call a timeout handler: {0!r}" .format(handler)) self._timeout_handlers = self._timeout_handlers[1:] result = handler()
python
{ "resource": "" }
q259581
xml_elements_equal
validation
def xml_elements_equal(element1, element2, ignore_level1_cdata = False): """Check if two XML elements are equal. :Parameters: - `element1`: the first element to compare - `element2`: the other element to compare - `ignore_level1_cdata`: if direct text children of the elements should be ignored for the comparision :Types: - `element1`: :etree:`ElementTree.Element` - `element2`: :etree:`ElementTree.Element` - `ignore_level1_cdata`: `bool` :Returntype: `bool` """ # pylint: disable-msg=R0911 if None in (element1, element2) or element1.tag != element2.tag: return False attrs1 = element1.items() attrs1.sort() attrs2 = element2.items() attrs2.sort() if not ignore_level1_cdata:
python
{ "resource": "" }
q259582
Message.make_error_response
validation
def make_error_response(self, cond): """Create error response for any non-error message stanza. :Parameters: - `cond`: error condition name, as defined in XMPP specification. :return: new message stanza with the same "id" as self, "from" and "to" attributes swapped, type="error" and containing <error /> element plus payload of `self`. :returntype: `Message`""" if self.stanza_type == "error":
python
{ "resource": "" }
q259583
_move_session_handler
validation
def _move_session_handler(handlers): """Find a SessionHandler instance in the list and move it to the beginning. """ index = 0 for i, handler in enumerate(handlers): if isinstance(handler, SessionHandler):
python
{ "resource": "" }
q259584
Client.connect
validation
def connect(self): """Schedule a new XMPP c2s connection. """ with self.lock: if self.stream: logger.debug("Closing the previously used stream.") self._close_stream() transport = TCPTransport(self.settings) addr = self.settings["server"] if addr: service = None else: addr = self.jid.domain service = self.settings["c2s_service"] transport.connect(addr, self.settings["c2s_port"], service) handlers = self._base_handlers[:] handlers += self.handlers + [self]
python
{ "resource": "" }
q259585
Client.disconnect
validation
def disconnect(self): """Gracefully disconnect from the server.""" with self.lock: if self.stream: if self.settings[u"initial_presence"]:
python
{ "resource": "" }
q259586
Client._close_stream
validation
def _close_stream(self): """Same as `close_stream` but with the `lock` acquired. """ self.stream.close() if self.stream.transport in self._ml_handlers: self._ml_handlers.remove(self.stream.transport)
python
{ "resource": "" }
q259587
Client._stream_authenticated
validation
def _stream_authenticated(self, event): """Handle the `AuthenticatedEvent`. """ with self.lock: if event.stream != self.stream: return self.me = event.stream.me
python
{ "resource": "" }
q259588
Client._stream_authorized
validation
def _stream_authorized(self, event): """Handle the `AuthorizedEvent`. """ with self.lock: if event.stream != self.stream: return self.me = event.stream.me
python
{ "resource": "" }
q259589
Client._stream_disconnected
validation
def _stream_disconnected(self, event): """Handle stream disconnection event. """ with self.lock: if event.stream != self.stream: return if self.stream is not None and event.stream == self.stream: if self.stream.transport in self._ml_handlers:
python
{ "resource": "" }
q259590
Client.base_handlers_factory
validation
def base_handlers_factory(self): """Default base client handlers factory. Subclasses can provide different behaviour by overriding this. :Return: list of handlers """
python
{ "resource": "" }
q259591
payload_class_for_element_name
validation
def payload_class_for_element_name(element_name): """Return a payload class for given element name.""" logger.debug(" looking up payload class for element: {0!r}".format(
python
{ "resource": "" }
q259592
_unquote
validation
def _unquote(data): """Unquote quoted value from DIGEST-MD5 challenge or response. If `data` doesn't start or doesn't end with '"' then return it unchanged, remove the quotes and escape backslashes otherwise. :Parameters: - `data`: a quoted string. :Types: - `data`: `bytes`
python
{ "resource": "" }
q259593
_quote
validation
def _quote(data): """Prepare a string for quoting for DIGEST-MD5 challenge or response. Don't add the quotes, only escape '"' and "\\" with backslashes. :Parameters: - `data`: a raw string. :Types: - `data`: `bytes` :return: `data`
python
{ "resource": "" }
q259594
_compute_response
validation
def _compute_response(urp_hash, nonce, cnonce, nonce_count, authzid, digest_uri): """Compute DIGEST-MD5 response value. :Parameters: - `urp_hash`: MD5 sum of username:realm:password. - `nonce`: nonce value from a server challenge. - `cnonce`: cnonce value from the client response. - `nonce_count`: nonce count value. - `authzid`: authorization id. - `digest_uri`: digest-uri value. :Types: - `urp_hash`: `bytes` - `nonce`: `bytes` - `nonce_count`: `int` - `authzid`: `bytes` - `digest_uri`: `bytes` :return: the computed response value.
python
{ "resource": "" }
q259595
rfc2425encode
validation
def rfc2425encode(name,value,parameters=None,charset="utf-8"): """Encodes a vCard field into an RFC2425 line. :Parameters: - `name`: field type name - `value`: field value - `parameters`: optional parameters - `charset`: encoding of the output and of the `value` (if not `unicode`) :Types: - `name`: `str` - `value`: `unicode` or `str` - `parameters`: `dict` of `str` -> `str` - `charset`: `str` :return: the encoded RFC2425 line (possibly folded) :returntype: `str`""" if not parameters: parameters={} if type(value) is unicode: value=value.replace(u"\r\n",u"\\n") value=value.replace(u"\n",u"\\n") value=value.replace(u"\r",u"\\n") value=value.encode(charset,"replace")
python
{ "resource": "" }
q259596
VCardAdr.__from_xml
validation
def __from_xml(self,value): """Initialize a `VCardAdr` object from and XML element. :Parameters: - `value`: field value as an XML node :Types: - `value`: `libxml2.xmlNode`""" n=value.children vns=get_node_ns(value) while n: if n.type!='element': n=n.next continue ns=get_node_ns(n) if (ns and vns and ns.getContent()!=vns.getContent()): n=n.next continue if n.name=='POBOX': self.pobox=unicode(n.getContent(),"utf-8","replace") elif n.name in ('EXTADR', 'EXTADD'):
python
{ "resource": "" }
q259597
VCard.__make_fn
validation
def __make_fn(self): """Initialize the mandatory `self.fn` from `self.n`. This is a workaround for buggy clients which set only one of them.""" s=[] if self.n.prefix: s.append(self.n.prefix)
python
{ "resource": "" }
q259598
VCard.__from_xml
validation
def __from_xml(self,data): """Initialize a VCard object from XML node. :Parameters: - `data`: vcard to parse. :Types: - `data`: `libxml2.xmlNode`""" ns=get_node_ns(data) if ns and ns.getContent()!=VCARD_NS: raise ValueError("Not in the %r namespace" % (VCARD_NS,)) if data.name!="vCard": raise ValueError("Bad root element name: %r" % (data.name,)) n=data.children dns=get_node_ns(data) while n: if n.type!='element': n=n.next continue ns=get_node_ns(n) if (ns and dns and ns.getContent()!=dns.getContent()): n=n.next continue if not self.components.has_key(n.name): n=n.next continue cl,tp=self.components[n.name] if
python
{ "resource": "" }
q259599
VCard.__from_rfc2426
validation
def __from_rfc2426(self,data): """Initialize a VCard object from an RFC2426 string. :Parameters: - `data`: vcard to parse. :Types: - `data`: `libxml2.xmlNode`, `unicode` or `str`""" data=from_utf8(data) lines=data.split("\n") started=0 current=None for l in lines: if not l: continue if l[-1]=="\r": l=l[:-1] if not l: continue if l[0] in " \t": if current is None: continue current+=l[1:] continue
python
{ "resource": "" }