_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q8300
validate
train
def validate(message, ssldir=None, **config): """ Validate the signature on the given message. Four things must be true for the signature to be valid: 1) The X.509 cert must be signed by our CA 2) The cert must not be in our CRL. 3) We must be able to verify the signature using the RSA p...
python
{ "resource": "" }
q8301
_validate_signing_cert
train
def _validate_signing_cert(ca_certificate, certificate, crl=None): """ Validate an X509 certificate using pyOpenSSL. .. note:: pyOpenSSL is a short-term solution to certificate validation. pyOpenSSL is basically in maintenance mode and there's a desire in upstream to move all the fu...
python
{ "resource": "" }
q8302
IRCBotConsumer.consume
train
def consume(self, msg): """ Forward on messages from the bus to all IRC connections. """ log.debug("Got message %r" % msg) topic, body = msg.get('topic'), msg.get('body') for client in self.irc_clients: if not client.factory.filters or ( client.factory.filter...
python
{ "resource": "" }
q8303
check
train
def check(timeout, consumer=None, producer=None): """This command is used to check the status of consumers and producers. If no consumers and producers are provided, the status of all consumers and producers is printed. """ # It's weird to say --consumers, but there are multiple, so rename the vari...
python
{ "resource": "" }
q8304
CollectdConsumer.dump
train
def dump(self): """ Called by CollectdProducer every `n` seconds. """ # Print out the collectd feedback. # This is sent to stdout while other log messages are sent to stderr. for k, v in sorted(self._dict.items()): print(self.formatter(k, v)) # Reset each entry to z...
python
{ "resource": "" }
q8305
CollectdConsumer.formatter
train
def formatter(self, key, value): """ Format messages for collectd to consume. """ template = "PUTVAL {host}/fedmsg/fedmsg_wallboard-{key} " +\ "interval={interval} {timestamp}:{value}" timestamp = int(time.time()) interval = self.hub.config['collectd_interval'] return...
python
{ "resource": "" }
q8306
init
train
def init(**config): """ Initialize the crypto backend. The backend can be one of two plugins: - 'x509' - Uses x509 certificates. - 'gpg' - Uses GnuPG keys. """ global _implementation global _validate_implementations if config.get('crypto_backend') == 'gpg': _implementa...
python
{ "resource": "" }
q8307
validate_signed_by
train
def validate_signed_by(message, signer, **config): """ Validate that a message was signed by a particular certificate. This works much like ``validate(...)``, but additionally accepts a ``signer`` argument. It will reject a message for any of the regular circumstances, but will also reject it if its n...
python
{ "resource": "" }
q8308
strip_credentials
train
def strip_credentials(message): """ Strip credentials from a message dict. A new dict is returned without either `signature` or `certificate` keys. This method can be called safely; the original dict is not modified. This function is applicable using either using the x509 or gpg backends. """ ...
python
{ "resource": "" }
q8309
get_replay
train
def get_replay(name, query, config, context=None): """ Query the replay endpoint for missed messages. Args: name (str): The replay endpoint name. query (dict): A dictionary used to query the replay endpoint for messages. Queries are dictionaries with the following any of the fol...
python
{ "resource": "" }
q8310
check_for_replay
train
def check_for_replay(name, names_to_seq_id, msg, config, context=None): """ Check to see if messages need to be replayed. Args: name (str): The consumer's name. names_to_seq_id (dict): A dictionary that maps names to the last seen sequence ID. msg (dict): The latest message that has...
python
{ "resource": "" }
q8311
validate_policy
train
def validate_policy(topic, signer, routing_policy, nitpicky=False): """ Checks that the sender is allowed to emit messages for the given topic. Args: topic (str): The message topic the ``signer`` used when sending the message. signer (str): The Common Name of the certificate used to sign th...
python
{ "resource": "" }
q8312
load_certificates
train
def load_certificates(ca_location, crl_location=None, invalidate_cache=False): """ Load the CA certificate and CRL, caching it for future use. .. note:: Providing the location of the CA and CRL as an HTTPS URL is deprecated and will be removed in a future release. Args: ca_loca...
python
{ "resource": "" }
q8313
_load_certificate
train
def _load_certificate(location): """ Load a certificate from the given location. Args: location (str): The location to load. This can either be an HTTPS URL or an absolute file path. This is intended to be used with PEM-encoded certificates and therefore assumes ASCII encodi...
python
{ "resource": "" }
q8314
_get_config_files
train
def _get_config_files(): """ Load the list of file paths for fedmsg configuration files. Returns: list: List of files containing fedmsg configuration. """ config_paths = [] if os.environ.get('FEDMSG_CONFIG'): config_location = os.environ['FEDMSG_CONFIG'] else: config...
python
{ "resource": "" }
q8315
_validate_none_or_type
train
def _validate_none_or_type(t): """ Create a validator that checks if a setting is either None or a given type. Args: t: The type to assert. Returns: callable: A callable that will validate a setting for that type. """ def _validate(setting): """ Check the settin...
python
{ "resource": "" }
q8316
_validate_bool
train
def _validate_bool(value): """ Validate a setting is a bool. Returns: bool: The value as a boolean. Raises: ValueError: If the value can't be parsed as a bool string or isn't already bool. """ if isinstance(value, six.text_type): if value.strip().lower() == 'true': ...
python
{ "resource": "" }
q8317
_gather_configs_in
train
def _gather_configs_in(directory): """ Return list of fully qualified python filenames in the given dir """ try: return sorted([ os.path.join(directory, fname) for fname in os.listdir(directory) if fname.endswith('.py') ]) except OSError: return []
python
{ "resource": "" }
q8318
execfile
train
def execfile(fname, variables): """ This is builtin in python2, but we have to roll our own on py3. """ with open(fname) as f: code = compile(f.read(), fname, 'exec') exec(code, variables)
python
{ "resource": "" }
q8319
FedmsgConfig.load_config
train
def load_config(self, settings=None): """ Load the configuration either from the config file, or from the given settings. Args: settings (dict): If given, the settings are pulled from this dictionary. Otherwise, the config file is used. """ self._load...
python
{ "resource": "" }
q8320
FedmsgConfig._load_defaults
train
def _load_defaults(self): """Iterate over self._defaults and set all default values on self.""" for k, v in self._defaults.items(): self[k] = v['default']
python
{ "resource": "" }
q8321
FedmsgConfig._validate
train
def _validate(self): """ Run the validators found in self._defaults on all the corresponding values. Raises: ValueError: If the configuration contains an invalid configuration value. """ errors = [] for k in self._defaults.keys(): try: ...
python
{ "resource": "" }
q8322
make_processors
train
def make_processors(**config): """ Initialize all of the text processors. You'll need to call this once before using any of the other functions in this module. >>> import fedmsg.config >>> import fedmsg.meta >>> config = fedmsg.config.load_config([], None) >>> fedmsg.meta.m...
python
{ "resource": "" }
q8323
msg2processor
train
def msg2processor(msg, **config): """ For a given message return the text processor that can handle it. This will raise a :class:`fedmsg.meta.ProcessorsNotInitialized` exception if :func:`fedmsg.meta.make_processors` hasn't been called yet. """ for processor in processors: if processor.hand...
python
{ "resource": "" }
q8324
graceful
train
def graceful(cls): """ A decorator to protect against message structure changes. Many of our processors expect messages to be in a certain format. If the format changes, they may start to fail and raise exceptions. This decorator is in place to catch and log those exceptions and to gracefully return ...
python
{ "resource": "" }
q8325
conglomerate
train
def conglomerate(messages, subject=None, lexers=False, **config): """ Return a list of messages with some of them grouped into conglomerate messages. Conglomerate messages represent several other messages. For example, you might pass this function a list of 40 messages. 38 of those are git.commit mess...
python
{ "resource": "" }
q8326
msg2repr
train
def msg2repr(msg, processor, **config): """ Return a human-readable or "natural language" representation of a dict-like fedmsg message. Think of this as the 'top-most level' function in this module. """ fmt = u"{title} -- {subtitle} {link}" title = msg2title(msg, **config) subtitle = proce...
python
{ "resource": "" }
q8327
msg2long_form
train
def msg2long_form(msg, processor, **config): """ Return a 'long form' text representation of a message. For most message, this will just default to the terse subtitle, but for some messages a long paragraph-structured block of text may be returned. """ result = processor.long_form(msg, **config) ...
python
{ "resource": "" }
q8328
msg2usernames
train
def msg2usernames(msg, processor=None, legacy=False, **config): """ Return a set of FAS usernames associated with a message. """ return processor.usernames(msg, **config)
python
{ "resource": "" }
q8329
msg2agent
train
def msg2agent(msg, processor=None, legacy=False, **config): """ Return the single username who is the "agent" for an event. An "agent" is the one responsible for the event taking place, for example, if one person gives karma to another, then both usernames are returned by msg2usernames, but only the on...
python
{ "resource": "" }
q8330
msg2subjective
train
def msg2subjective(msg, processor, subject, **config): """ Return a human-readable text representation of a dict-like fedmsg message from the subjective perspective of a user. For example, if the subject viewing the message is "oddshocks" and the message would normally translate into "oddshocks comment...
python
{ "resource": "" }
q8331
TriggerCommand.run_command
train
def run_command(self, command, message): """ Use subprocess; feed the message to our command over stdin """ proc = subprocess.Popen([ 'echo \'%s\' | %s' % (fedmsg.encoding.dumps(message), command) ], shell=True, executable='/bin/bash') return proc.wait()
python
{ "resource": "" }
q8332
BaseProcessor.conglomerate
train
def conglomerate(self, messages, **config): """ Given N messages, return another list that has some of them grouped together into a common 'item'. A conglomeration of messages should be of the following form:: { 'subtitle': 'relrod pushed commits to ghc and 487 other pack...
python
{ "resource": "" }
q8333
BaseProcessor.handle_msg
train
def handle_msg(self, msg, **config): """ If we can handle the given message, return the remainder of the topic. Returns None if we can't handle the message. """ match = self.__prefix__.match(msg['topic']) if match: return match.groups()[-1] or ""
python
{ "resource": "" }
q8334
Consumer.begin
train
def begin(self, user_url, anonymous=False): """Start the OpenID authentication process. See steps 1-2 in the overview at the top of this file. @param user_url: Identity URL given by the user. This method performs a textual transformation of the URL to try and make sure i...
python
{ "resource": "" }
q8335
Consumer.beginWithoutDiscovery
train
def beginWithoutDiscovery(self, service, anonymous=False): """Start OpenID verification without doing OpenID server discovery. This method is used internally by Consumer.begin after discovery is performed, and exists to provide an interface for library users needing to perform their own ...
python
{ "resource": "" }
q8336
GenericConsumer._checkReturnTo
train
def _checkReturnTo(self, message, return_to): """Check an OpenID message and its openid.return_to value against a return_to URL from an application. Return True on success, False on failure. """ # Check the openid.return_to args against args in the original # message. ...
python
{ "resource": "" }
q8337
GenericConsumer._checkAuth
train
def _checkAuth(self, message, server_url): """Make a check_authentication request to verify this message. @returns: True if the request is valid. @rtype: bool """ logging.info('Using OpenID check_authentication') request = self._createCheckAuthRequest(message) if...
python
{ "resource": "" }
q8338
GenericConsumer._negotiateAssociation
train
def _negotiateAssociation(self, endpoint): """Make association requests to the server, attempting to create a new association. @returns: a new association object @rtype: L{openid.association.Association} """ # Get our preferred session/association type from the negotiat...
python
{ "resource": "" }
q8339
importSafeElementTree
train
def importSafeElementTree(module_names=None): """Find a working ElementTree implementation that is not vulnerable to XXE, using `defusedxml`. >>> XXESafeElementTree = importSafeElementTree() @param module_names: The names of modules to try to use as a safe ElementTree. Defaults to C{L{xxe_safe...
python
{ "resource": "" }
q8340
FetchRequest.getExtensionArgs
train
def getExtensionArgs(self): """Get the serialized form of this attribute fetch request. @returns: The fetch request message parameters @rtype: {unicode:unicode} """ aliases = NamespaceMap() required = [] if_available = [] ax_args = self._newArgs() ...
python
{ "resource": "" }
q8341
FetchRequest.fromOpenIDRequest
train
def fromOpenIDRequest(cls, openid_request): """Extract a FetchRequest from an OpenID message @param openid_request: The OpenID authentication request containing the attribute fetch request @type openid_request: C{L{openid.server.server.CheckIDRequest}} @rtype: C{L{FetchRequ...
python
{ "resource": "" }
q8342
FetchRequest.parseExtensionArgs
train
def parseExtensionArgs(self, ax_args): """Given attribute exchange arguments, populate this FetchRequest. @param ax_args: Attribute Exchange arguments from the request. As returned from L{Message.getArgs<openid.message.Message.getArgs>}. @type ax_args: dict @raises KeyError...
python
{ "resource": "" }
q8343
findLinksRel
train
def findLinksRel(link_attrs_list, target_rel): """Filter the list of link attributes on whether it has target_rel as a relationship.""" # XXX: TESTME matchesTarget = lambda attrs: linkHasRel(attrs, target_rel) return list(filter(matchesTarget, link_attrs_list))
python
{ "resource": "" }
q8344
SQLStore.txn_getAssociation
train
def txn_getAssociation(self, server_url, handle=None): """Get the most recent association that has been set for this server URL and handle. str -> NoneType or Association """ if handle is not None: self.db_get_assoc(server_url, handle) else: self....
python
{ "resource": "" }
q8345
Urllib2Fetcher._makeResponse
train
def _makeResponse(self, urllib2_response): ''' Construct an HTTPResponse from the the urllib response. Attempt to decode the response body from bytes to str if the necessary information is available. ''' resp = HTTPResponse() resp.body = urllib2_response.read(MAX_...
python
{ "resource": "" }
q8346
Message.toPostArgs
train
def toPostArgs(self): """ Return all arguments with openid. in front of namespaced arguments. @return bytes """ args = {} # Add namespace definitions to the output for ns_uri, alias in self.namespaces.items(): if self.namespaces.isImplicit(ns_uri): ...
python
{ "resource": "" }
q8347
Message.toArgs
train
def toArgs(self): """Return all namespaced arguments, failing if any non-namespaced arguments exist.""" # FIXME - undocumented exception post_args = self.toPostArgs() kvargs = {} for k, v in post_args.items(): if not k.startswith('openid.'): ra...
python
{ "resource": "" }
q8348
NamespaceMap.addAlias
train
def addAlias(self, namespace_uri, desired_alias, implicit=False): """Add an alias from this namespace URI to the desired alias """ if isinstance(namespace_uri, bytes): namespace_uri = str(namespace_uri, encoding="utf-8") # Check that desired_alias is not an openid protocol fi...
python
{ "resource": "" }
q8349
_appendArgs
train
def _appendArgs(url, args): """Append some arguments to an HTTP query. """ # to be merged with oidutil.appendArgs when we combine the projects. if hasattr(args, 'items'): args = list(args.items()) args.sort() if len(args) == 0: return url # According to XRI Resolution s...
python
{ "resource": "" }
q8350
iriToURI
train
def iriToURI(iri): """Transform an IRI to a URI by escaping unicode.""" # According to RFC 3987, section 3.1, "Mapping of IRIs to URIs" if isinstance(iri, bytes): iri = str(iri, encoding="utf-8") return iri.encode('ascii', errors='oid_percent_escape').decode()
python
{ "resource": "" }
q8351
urinorm
train
def urinorm(uri): ''' Normalize a URI ''' # TODO: use urllib.parse instead of these complex regular expressions if isinstance(uri, bytes): uri = str(uri, encoding='utf-8') uri = uri.encode('ascii', errors='oid_percent_escape').decode('utf-8') # _escapeme_re.sub(_pct_escape_unicode, ...
python
{ "resource": "" }
q8352
_removeIfPresent
train
def _removeIfPresent(filename): """Attempt to remove a file, returning whether the file existed at the time of the call. str -> bool """ try: os.unlink(filename) except OSError as why: if why.errno == ENOENT: # Someone beat us to it, but it's gone, so that's OK ...
python
{ "resource": "" }
q8353
FileOpenIDStore.storeAssociation
train
def storeAssociation(self, server_url, association): """Store an association in the association directory. (str, Association) -> NoneType """ association_s = association.serialize() # NOTE: UTF-8 encoded bytes filename = self.getAssociationFilename(server_url, association.handl...
python
{ "resource": "" }
q8354
OpenIDRequestHandler.doVerify
train
def doVerify(self): """Process the form submission, initating OpenID verification. """ # First, make sure that the user entered something openid_url = self.query.get('openid_identifier') if not openid_url: self.render( 'Enter an OpenID Identifier to v...
python
{ "resource": "" }
q8355
ResponsiveFlask._response_mimetype_based_on_accept_header
train
def _response_mimetype_based_on_accept_header(self): """Determines mimetype to response based on Accept header. If mimetype is not found, it returns ``None``. """ response_mimetype = None if not request.accept_mimetypes: response_mimetype = self.default_mimetype ...
python
{ "resource": "" }
q8356
ResponsiveFlask.make_response
train
def make_response(self, rv): """Returns response based on Accept header. If no Accept header field is present, then it is assumed that the client accepts all media types. This way JSON format will be used. If an Accept header field is present, and if the server cannot s...
python
{ "resource": "" }
q8357
IrcServer.notice
train
def notice(self, client, message): """send a notice to client""" if client and message: messages = utils.split_message(message, self.config.max_length) for msg in messages: client.fwrite(':{c.srv} NOTICE {c.nick} :{msg}', msg=msg)
python
{ "resource": "" }
q8358
Hawk.client_key_loader
train
def client_key_loader(self, f): """Registers a function to be called to find a client key. Function you set has to take a client id and return a client key:: @hawk.client_key_loader def get_client_key(client_id): if client_id == 'Alice': retu...
python
{ "resource": "" }
q8359
Hawk.auth_required
train
def auth_required(self, view_func): """Decorator that provides an access to view function for authenticated users only. Note that we don't run authentication when `HAWK_ENABLED` is `False`. """ @wraps(view_func) def wrapped_view_func(*args, **kwargs): if cur...
python
{ "resource": "" }
q8360
Hawk._sign_response
train
def _sign_response(self, response): """Signs a response if it's possible.""" if 'Authorization' not in request.headers: return response try: mohawk_receiver = mohawk.Receiver( credentials_map=self._client_key_loader_func, request_header=re...
python
{ "resource": "" }
q8361
DCCManager.create
train
def create(self, name_or_class, mask, filepath=None, **kwargs): """Create a new DCC connection. Return an ``asyncio.Protocol``""" if isinstance(name_or_class, type): name = name_or_class.type protocol = name_or_class else: name = name_or_class prot...
python
{ "resource": "" }
q8362
DCCManager.resume
train
def resume(self, mask, filename, port, pos): """Resume a DCC send""" self.connections['send']['masks'][mask][port].offset = pos message = 'DCC ACCEPT %s %d %d' % (filename, port, pos) self.bot.ctcp(mask, message)
python
{ "resource": "" }
q8363
DCCManager.is_allowed
train
def is_allowed(self, name_or_class, mask): # pragma: no cover """Return True is a new connection is allowed""" if isinstance(name_or_class, type): name = name_or_class.type else: name = name_or_class info = self.connections[name] limit = self.config[name ...
python
{ "resource": "" }
q8364
split_message
train
def split_message(message, max_length): """Split long messages""" if len(message) > max_length: for message in textwrap.wrap(message, max_length): yield message else: yield message.rstrip(STRIPPED_CHARS)
python
{ "resource": "" }
q8365
parse_config
train
def parse_config(main_section, *filenames): """parse config files""" filename = filenames[-1] filename = os.path.abspath(filename) here = os.path.dirname(filename) defaults = dict(here=here, hash='#') defaults['#'] = '#' config = configparser.ConfigParser( defaults, allow_no_value=F...
python
{ "resource": "" }
q8366
extract_config
train
def extract_config(config, prefix): """return all keys with the same prefix without the prefix""" prefix = prefix.strip('.') + '.' plen = len(prefix) value = {} for k, v in config.items(): if k.startswith(prefix): value[k[plen:]] = v return value
python
{ "resource": "" }
q8367
IrcString.tagdict
train
def tagdict(self): """return a dict converted from this string interpreted as a tag-string .. code-block:: py >>> from pprint import pprint >>> dict_ = IrcString('aaa=bbb;ccc;example.com/ddd=eee').tagdict >>> pprint({str(k): str(v) for k, v in dict_.items()}) ...
python
{ "resource": "" }
q8368
IrcBot.send_line
train
def send_line(self, data, nowait=False): """send a line to the server. replace CR by spaces""" data = data.replace('\n', ' ').replace('\r', ' ') f = asyncio.Future(loop=self.loop) if self.queue is not None and nowait is False: self.queue.put_nowait((f, data)) else: ...
python
{ "resource": "" }
q8369
IrcBot.privmsg
train
def privmsg(self, target, message, nowait=False): """send a privmsg to target""" if message: messages = utils.split_message(message, self.config.max_length) if isinstance(target, DCCChat): for message in messages: target.send_line(message) ...
python
{ "resource": "" }
q8370
IrcBot.ctcp
train
def ctcp(self, target, message, nowait=False): """send a ctcp to target""" if target and message: messages = utils.split_message(message, self.config.max_length) f = None for message in messages: f = self.send_line('PRIVMSG %s :\x01%s\x01' % (target, ...
python
{ "resource": "" }
q8371
IrcBot.mode
train
def mode(self, target, *data): """set user or channel mode""" self.send_line('MODE %s %s' % (target, ' '.join(data)), nowait=True)
python
{ "resource": "" }
q8372
IrcBot.join
train
def join(self, target): """join a channel""" password = self.config.passwords.get( target.strip(self.server_config['CHANTYPES'])) if password: target += ' ' + password self.send_line('JOIN %s' % target)
python
{ "resource": "" }
q8373
IrcBot.part
train
def part(self, target, reason=None): """quit a channel""" if reason: target += ' :' + reason self.send_line('PART %s' % target)
python
{ "resource": "" }
q8374
IrcBot.kick
train
def kick(self, channel, target, reason=None): """kick target from channel""" if reason: target += ' :' + reason self.send_line('KICK %s %s' % (channel, target), nowait=True)
python
{ "resource": "" }
q8375
IrcBot.topic
train
def topic(self, channel, topic=None): """change or request the topic of a channel""" if topic: channel += ' :' + topic self.send_line('TOPIC %s' % channel)
python
{ "resource": "" }
q8376
IrcBot.away
train
def away(self, message=None): """mark ourself as away""" cmd = 'AWAY' if message: cmd += ' :' + message self.send_line(cmd)
python
{ "resource": "" }
q8377
IrcBot.ip
train
def ip(self): """return bot's ip as an ``ip_address`` object""" if not self._ip: if 'ip' in self.config: ip = self.config['ip'] else: ip = self.protocol.transport.get_extra_info('sockname')[0] ip = ip_address(ip) if ip.versi...
python
{ "resource": "" }
q8378
IrcBot.dcc_get
train
def dcc_get(self, mask, host, port, filepath, filesize=None): """DCC GET a file from mask. filepath must be an absolute path with an existing directory. filesize is the expected file size.""" return self.dcc.create( 'get', mask, filepath=filepath, filesize=filesize, host=...
python
{ "resource": "" }
q8379
IrcBot.dcc_send
train
def dcc_send(self, mask, filepath): """DCC SEND a file to mask. filepath must be an absolute path to existing file""" return self.dcc.create('send', mask, filepath=filepath).ready
python
{ "resource": "" }
q8380
IrcBot.dcc_accept
train
def dcc_accept(self, mask, filepath, port, pos): """accept a DCC RESUME for an axisting DCC SEND. filepath is the filename to sent. port is the port opened on the server. pos is the expected offset""" return self.dcc.resume(mask, filepath, port, pos)
python
{ "resource": "" }
q8381
challenge_auth
train
def challenge_auth(username, password, challenge, lower, digest='sha256'): """Calculates quakenet's challenge auth hash .. code-block:: python >>> challenge_auth("mooking", "0000000000", ... "12345678901234567890123456789012", str.lower, "md5") '2ed1a1f1d2cd5487d2e18f27213286b9' ...
python
{ "resource": "" }
q8382
auto_retweet
train
def auto_retweet(bot): """retweet author tweets about irc3 and pypi releases""" conn = bot.get_social_connection(id='twitter') dirname = os.path.expanduser('~/.irc3/twitter/{nick}'.format(**bot.config)) if not os.path.isdir(dirname): os.makedirs(dirname) filename = os.path.join(dirname, 'r...
python
{ "resource": "" }
q8383
FeedsHook.filter_travis
train
def filter_travis(self, entry): """Only show the latest entry iif this entry is in a new state""" fstate = entry.filename + '.state' if os.path.isfile(fstate): with open(fstate) as fd: state = fd.read().strip() else: state = None if 'failed...
python
{ "resource": "" }
q8384
FeedsHook.filter_pypi
train
def filter_pypi(self, entry): """Show only usefull packages""" for package in self.packages: if entry.title.lower().startswith(package): return entry
python
{ "resource": "" }
q8385
Whois.process_results
train
def process_results(self, results=None, **value): """take results list of all events and put them in a dict""" channels = [] for res in results: channels.extend(res.pop('channels', '').split()) value.update(res) value['channels'] = channels value['success'...
python
{ "resource": "" }
q8386
CTCP.process_results
train
def process_results(self, results=None, **value): """take results list of all events and return first dict""" for res in results: if 'mask' in res: res['mask'] = utils.IrcString(res['mask']) value['success'] = res.pop('retcode', None) != '486' value.up...
python
{ "resource": "" }
q8387
quote
train
def quote(bot, mask, target, args): """send quote to the server %%quote <args>... """ msg = ' '.join(args['<args>']) bot.log.info('quote> %r', msg) bot.send(msg)
python
{ "resource": "" }
q8388
print_help_page
train
def print_help_page(bot, file=sys.stdout): """print help page""" def p(text): print(text, file=file) plugin = bot.get_plugin(Commands) title = "Available Commands for {nick} at {host}".format(**bot.config) p("=" * len(title)) p(title) p("=" * len(title)) p('') p('.. contents:...
python
{ "resource": "" }
q8389
Core.connected
train
def connected(self, **kwargs): """triger the server_ready event""" self.bot.log.info('Server config: %r', self.bot.server_config) # recompile when I'm sure of my nickname self.bot.config['nick'] = kwargs['me'] self.bot.recompile() # Let all plugins know that server can ...
python
{ "resource": "" }
q8390
Core.recompile
train
def recompile(self, nick=None, new_nick=None, **kw): """recompile regexp on new nick""" if self.bot.nick == nick.nick: self.bot.config['nick'] = new_nick self.bot.recompile()
python
{ "resource": "" }
q8391
Core.badnick
train
def badnick(self, me=None, nick=None, **kw): """Use alt nick on nick error""" if me == '*': self.bot.set_nick(self.bot.nick + '_') self.bot.log.debug('Trying to regain nickname in 30s...') self.nick_handle = self.bot.loop.call_later( 30, self.bot.set_nick, self.bo...
python
{ "resource": "" }
q8392
Core.set_config
train
def set_config(self, data=None, **kwargs): """Store server config""" config = self.bot.config['server_config'] for opt in data.split(' '): if '=' in opt: opt, value = opt.split('=', 1) else: value = True if opt.isupper(): ...
python
{ "resource": "" }
q8393
fetch
train
def fetch(args): """fetch a feed""" session = args['session'] for feed, filename in zip(args['feeds'], args['filenames']): try: resp = session.get(feed, timeout=5) content = resp.content except Exception: # pragma: no cover pass else: ...
python
{ "resource": "" }
q8394
parse
train
def parse(feedparser, args): """parse a feed using feedparser""" entries = [] args = irc3.utils.Config(args) max_date = datetime.datetime.now() - datetime.timedelta(days=2) for filename in args['filenames']: try: with open(filename + '.updated') as fd: updated = ...
python
{ "resource": "" }
q8395
IrcObject.attach_events
train
def attach_events(self, *events, **kwargs): """Attach one or more events to the bot instance""" reg = self.registry insert = 'insert' in kwargs for e in events: cregexp = e.compile(self.config) regexp = getattr(e.regexp, 're', e.regexp) if regexp not i...
python
{ "resource": "" }
q8396
IrcObject.detach_events
train
def detach_events(self, *events): """Detach one or more events from the bot instance""" reg = self.registry delete = defaultdict(list) # remove from self.events all_events = reg.events for e in events: regexp = getattr(e.regexp, 're', e.regexp) io...
python
{ "resource": "" }
q8397
IrcObject.reload
train
def reload(self, *modules): """Reload one or more plugins""" self.notify('before_reload') if 'configfiles' in self.config: # reload configfiles self.log.info('Reloading configuration...') cfg = utils.parse_config( self.server and 'server' or '...
python
{ "resource": "" }
q8398
IrcObject.call_many
train
def call_many(self, callback, args): """callback is run with each arg but run a call per second""" if isinstance(callback, str): callback = getattr(self, callback) f = None for arg in args: f = callback(*arg) return f
python
{ "resource": "" }
q8399
IrcObject.run
train
def run(self, forever=True): """start the bot""" loop = self.create_connection() self.add_signal_handlers() if forever: loop.run_forever()
python
{ "resource": "" }