INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
:type relax: float
:param relax: seconds between each :meth:`.getUpdates`
:type offset: int
:param offset:
initial ``offset`` parameter supplied to :meth:`.getUpdates`
:type timeout: int
:param timeout:
``timeout`` parameter supplied to :meth:`.getUpdate... | def run_forever(self, *args, **kwargs):
"""
:type relax: float
:param relax: seconds between each :meth:`.getUpdates`
:type offset: int
:param offset:
initial ``offset`` parameter supplied to :meth:`.getUpdates`
:type timeout: int
:param timeout:
... |
:type maxhold: float
:param maxhold:
The maximum number of seconds an update is held waiting for a
not-yet-arrived smaller ``update_id``. When this number of seconds
is up, the update is delivered to the message-handling function
even if some smaller ``update_id``... | def run_forever(self, *args, **kwargs):
"""
:type maxhold: float
:param maxhold:
The maximum number of seconds an update is held waiting for a
not-yet-arrived smaller ``update_id``. When this number of seconds
is up, the update is delivered to the message-hand... |
:param data:
One of these:
- ``str``, ``unicode`` (Python 2.7), or ``bytes`` (Python 3, decoded using UTF-8)
representing a JSON-serialized `Update <https://core.telegram.org/bots/api#update>`_ object.
- a ``dict`` representing an Update object. | def feed(self, data):
"""
:param data:
One of these:
- ``str``, ``unicode`` (Python 2.7), or ``bytes`` (Python 3, decoded using UTF-8)
representing a JSON-serialized `Update <https://core.telegram.org/bots/api#update>`_ object.
- a ``dict`` representing... |
:return:
a dictionary roughly equivalent to ``{'key1': obj.on_key1, 'key2': obj.on_key2, ...}``,
but ``obj`` does not have to define all methods. It may define the needed ones only.
:param obj: the object
:param keys: a list of keys
:param prefix: a string to be prepended to keys to make ... | def make_routing_table(obj, keys, prefix='on_'):
"""
:return:
a dictionary roughly equivalent to ``{'key1': obj.on_key1, 'key2': obj.on_key2, ...}``,
but ``obj`` does not have to define all methods. It may define the needed ones only.
:param obj: the object
:param keys: a list of keys
... |
:return:
A key function that returns a 2-tuple (content_type, (msg[content_type],)).
In plain English, it returns the message's *content type* as the key,
and the corresponding content as a positional argument to the handler
function. | def by_content_type():
"""
:return:
A key function that returns a 2-tuple (content_type, (msg[content_type],)).
In plain English, it returns the message's *content type* as the key,
and the corresponding content as a positional argument to the handler
function.
"""
def f(... |
:param extractor:
a function that takes one argument (the message) and returns a portion
of message to be interpreted. To extract the text of a chat message,
use ``lambda msg: msg['text']``.
:param prefix:
a list of special characters expected to indicate the head of a command.
... | def by_command(extractor, prefix=('/',), separator=' ', pass_args=False):
"""
:param extractor:
a function that takes one argument (the message) and returns a portion
of message to be interpreted. To extract the text of a chat message,
use ``lambda msg: msg['text']``.
:param prefix:... |
:param prefix:
a list of special characters expected to indicate the head of a command.
:param separator:
a command may be followed by arguments separated by ``separator``.
:type pass_args: bool
:param pass_args:
If ``True``, arguments following a command will be passed to the hand... | def by_chat_command(prefix=('/',), separator=' ', pass_args=False):
"""
:param prefix:
a list of special characters expected to indicate the head of a command.
:param separator:
a command may be followed by arguments separated by ``separator``.
:type pass_args: bool
:param pass_arg... |
:param extractor:
a function that takes one argument (the message) and returns a portion
of message to be interpreted. To extract the text of a chat message,
use ``lambda msg: msg['text']``.
:type regex: str or regex object
:param regex: the pattern to look for
:param key: the part... | def by_regex(extractor, regex, key=1):
"""
:param extractor:
a function that takes one argument (the message) and returns a portion
of message to be interpreted. To extract the text of a chat message,
use ``lambda msg: msg['text']``.
:type regex: str or regex object
:param regex... |
:param processor:
a function to process the key returned by the supplied key function
:param fn:
a key function
:return:
a function that wraps around the supplied key function to further
process the key before returning. | def process_key(processor, fn):
"""
:param processor:
a function to process the key returned by the supplied key function
:param fn:
a key function
:return:
a function that wraps around the supplied key function to further
process the key before returning.
"""
d... |
:param fn: a key function
:return:
a function that wraps around the supplied key function to ensure
the returned key is in lowercase. | def lower_key(fn):
"""
:param fn: a key function
:return:
a function that wraps around the supplied key function to ensure
the returned key is in lowercase.
"""
def lower(key):
try:
return key.lower()
except AttributeError:
return key
retu... |
:param fn: a key function
:return:
a function that wraps around the supplied key function to ensure
the returned key is in uppercase. | def upper_key(fn):
"""
:param fn: a key function
:return:
a function that wraps around the supplied key function to ensure
the returned key is in uppercase.
"""
def upper(key):
try:
return key.upper()
except AttributeError:
return key
retu... |
:return:
a dictionary roughly equivalent to ``{'key1': obj.on_key1, 'key2': obj.on_key2, ...}``,
but ``obj`` does not have to define all methods. It may define the needed ones only.
:param obj: the object
:param keys: a list of keys
:param prefix: a string to be prepended to keys to make ... | def make_routing_table(obj, keys, prefix='on_'):
"""
:return:
a dictionary roughly equivalent to ``{'key1': obj.on_key1, 'key2': obj.on_key2, ...}``,
but ``obj`` does not have to define all methods. It may define the needed ones only.
:param obj: the object
:param keys: a list of keys
... |
A class decorator to fill in certain methods and properties to ensure
a class can be used by :func:`.create_open`.
These instance methods and property will be added, if not defined
by the class:
- ``open(self, initial_msg, seed)``
- ``on_message(self, msg)``
- ``on_close(self, ex)``
- ``cl... | def openable(cls):
"""
A class decorator to fill in certain methods and properties to ensure
a class can be used by :func:`.create_open`.
These instance methods and property will be added, if not defined
by the class:
- ``open(self, initial_msg, seed)``
- ``on_message(self, msg)``
- ``... |
Block until a matched message appears. | def wait(self):
"""
Block until a matched message appears.
"""
if not self._patterns:
raise RuntimeError('Listener has nothing to capture')
while 1:
msg = self._queue.get(block=True)
if any(map(lambda p: filtering.match_all(msg, p), self._pat... |
Spawns a thread that calls ``compute fn`` (along with additional arguments
``*compute_args`` and ``**compute_kwargs``), then applies the returned value to
:meth:`.Bot.answerInlineQuery` to answer the inline query.
If a preceding thread is already working for a user, that thread is cancelled,
... | def answer(outerself, inline_query, compute_fn, *compute_args, **compute_kwargs):
"""
Spawns a thread that calls ``compute fn`` (along with additional arguments
``*compute_args`` and ``**compute_kwargs``), then applies the returned value to
:meth:`.Bot.answerInlineQuery` to answer the in... |
Configure a :class:`.Listener` to capture callback query | def configure(self, listener):
"""
Configure a :class:`.Listener` to capture callback query
"""
listener.capture([
lambda msg: flavor(msg) == 'callback_query',
{'message': self._chat_origin_included}
])
listener.capture([
lambda msg: f... |
:param send_func:
a function that sends messages, such as :meth:`.Bot.send\*`
:return:
a function that wraps around ``send_func`` and examines whether the
sent message contains an inline keyboard with callback data. If so,
future callback query originating from t... | def augment_send(self, send_func):
"""
:param send_func:
a function that sends messages, such as :meth:`.Bot.send\*`
:return:
a function that wraps around ``send_func`` and examines whether the
sent message contains an inline keyboard with callback data. If s... |
:param delete_func:
a function that deletes messages, such as :meth:`.Bot.deleteMessage`
:return:
a function that wraps around ``delete_func`` and stops capturing
callback query originating from that deleted message. | def augment_delete(self, delete_func):
"""
:param delete_func:
a function that deletes messages, such as :meth:`.Bot.deleteMessage`
:return:
a function that wraps around ``delete_func`` and stops capturing
callback query originating from that deleted message.... |
:return:
a proxy to ``bot`` with these modifications:
- all ``send*`` methods augmented by :meth:`augment_send`
- all ``edit*`` methods augmented by :meth:`augment_edit`
- ``deleteMessage()`` augmented by :meth:`augment_delete`
- all other public methods, inc... | def augment_bot(self, bot):
"""
:return:
a proxy to ``bot`` with these modifications:
- all ``send*`` methods augmented by :meth:`augment_send`
- all ``edit*`` methods augmented by :meth:`augment_edit`
- ``deleteMessage()`` augmented by :meth:`augment_del... |
Refresh timeout timer | def refresh(self):
""" Refresh timeout timer """
try:
if self._timeout_event:
self._scheduler.cancel(self._timeout_event)
# Timeout event has been popped from queue prematurely
except exception.EventNotFound:
pass
# Ensure a new event is ... |
:return:
a function wrapping ``handler`` to refresh timer for every
non-event message | def augment_on_message(self, handler):
"""
:return:
a function wrapping ``handler`` to refresh timer for every
non-event message
"""
def augmented(msg):
# Reset timer if this is an external message
is_event(msg) or self.refresh()
... |
:return:
a function wrapping ``handler`` to cancel timeout event | def augment_on_close(self, handler):
"""
:return:
a function wrapping ``handler`` to cancel timeout event
"""
def augmented(ex):
try:
if self._timeout_event:
self._scheduler.cancel(self._timeout_event)
self._... |
Configure a :class:`.Listener` to capture events with this object's
event space and source id. | def configure(self, listener):
"""
Configure a :class:`.Listener` to capture events with this object's
event space and source id.
"""
listener.capture([{re.compile('^_.+'): {'source': {'space': self._event_space, 'id': self._source_id}}}]) |
Marshall ``flavor`` and ``data`` into a standard event. | def make_event_data(self, flavor, data):
"""
Marshall ``flavor`` and ``data`` into a standard event.
"""
if not flavor.startswith('_'):
raise ValueError('Event flavor must start with _underscore')
d = {'source': {'space': self._event_space, 'id': self._source_id}}
... |
Schedule an event to be emitted at a certain time.
:param when: an absolute timestamp
:param data_tuple: a 2-tuple (flavor, data)
:return: an event object, useful for cancelling. | def event_at(self, when, data_tuple):
"""
Schedule an event to be emitted at a certain time.
:param when: an absolute timestamp
:param data_tuple: a 2-tuple (flavor, data)
:return: an event object, useful for cancelling.
"""
return self._base.event_at(when, self.... |
Schedule an event to be emitted after a delay.
:param delay: number of seconds
:param data_tuple: a 2-tuple (flavor, data)
:return: an event object, useful for cancelling. | def event_later(self, delay, data_tuple):
"""
Schedule an event to be emitted after a delay.
:param delay: number of seconds
:param data_tuple: a 2-tuple (flavor, data)
:return: an event object, useful for cancelling.
"""
return self._base.event_later(delay, self... |
Apply key function to ``msg`` to obtain a key. Return the routing table entry. | def map(self, msg):
"""
Apply key function to ``msg`` to obtain a key. Return the routing table entry.
"""
k = self.key_function(msg)
key = k[0] if isinstance(k, (tuple, list)) else k
return self.routing_table[key] |
Apply key function to ``msg`` to obtain a key, look up routing table
to obtain a handler function, then call the handler function with
positional and keyword arguments, if any is returned by the key function.
``*aa`` and ``**kw`` are dummy placeholders for easy chaining.
Regardless of a... | def route(self, msg, *aa, **kw):
"""
Apply key function to ``msg`` to obtain a key, look up routing table
to obtain a handler function, then call the handler function with
positional and keyword arguments, if any is returned by the key function.
``*aa`` and ``**kw`` are dummy pl... |
Format text as HTML. Also take care of escaping special characters.
Returned value can be passed to :meth:`.Bot.sendMessage` with appropriate
``parse_mode``.
:param text:
plain text
:param entities:
a list of `MessageEntity <https://core.telegram.org/bots/api#messageentity>`_ objects | def apply_entities_as_html(text, entities):
"""
Format text as HTML. Also take care of escaping special characters.
Returned value can be passed to :meth:`.Bot.sendMessage` with appropriate
``parse_mode``.
:param text:
plain text
:param entities:
a list of `MessageEntity <https... |
:return:
a delegator function that returns a coroutine object by calling
``corofunc(seed_tuple, *args, **kwargs)``. | def call(corofunc, *args, **kwargs):
"""
:return:
a delegator function that returns a coroutine object by calling
``corofunc(seed_tuple, *args, **kwargs)``.
"""
corofunc = _ensure_coroutine_function(corofunc)
def f(seed_tuple):
return corofunc(seed_tuple, *args, **kwargs)
... |
See: https://core.telegram.org/bots/api#sendphoto
:param photo:
- string: ``file_id`` for a photo existing on Telegram servers
- string: HTTP URL of a photo from the Internet
- file-like object: obtained by ``open(path, 'rb')``
- tuple: (filename, file-like objec... | async def sendPhoto(self, chat_id, photo,
caption=None,
parse_mode=None,
disable_notification=None,
reply_to_message_id=None,
reply_markup=None):
"""
See: https://core.telegram.org/bot... |
See: https://core.telegram.org/bots/api#sendaudio
:param audio: Same as ``photo`` in :meth:`telepot.aio.Bot.sendPhoto` | async def sendAudio(self, chat_id, audio,
caption=None,
parse_mode=None,
duration=None,
performer=None,
title=None,
disable_notification=None,
reply_to_... |
See: https://core.telegram.org/bots/api#editmessagelivelocation
:param msg_identifier: Same as in :meth:`.Bot.editMessageText` | async def editMessageLiveLocation(self, msg_identifier, latitude, longitude,
reply_markup=None):
"""
See: https://core.telegram.org/bots/api#editmessagelivelocation
:param msg_identifier: Same as in :meth:`.Bot.editMessageText`
"""
p = _stri... |
See: https://core.telegram.org/bots/api#getfile | async def getFile(self, file_id):
""" See: https://core.telegram.org/bots/api#getfile """
p = _strip(locals())
return await self._api_request('getFile', _rectify(p)) |
See: https://core.telegram.org/bots/api#kickchatmember | async def kickChatMember(self, chat_id, user_id,
until_date=None):
""" See: https://core.telegram.org/bots/api#kickchatmember """
p = _strip(locals())
return await self._api_request('kickChatMember', _rectify(p)) |
See: https://core.telegram.org/bots/api#restrictchatmember | async def restrictChatMember(self, chat_id, user_id,
until_date=None,
can_send_messages=None,
can_send_media_messages=None,
can_send_other_messages=None,
c... |
See: https://core.telegram.org/bots/api#setchattitle | async def setChatTitle(self, chat_id, title):
""" See: https://core.telegram.org/bots/api#setchattitle """
p = _strip(locals())
return await self._api_request('setChatTitle', _rectify(p)) |
See: https://core.telegram.org/bots/api#setchatdescription | async def setChatDescription(self, chat_id,
description=None):
""" See: https://core.telegram.org/bots/api#setchatdescription """
p = _strip(locals())
return await self._api_request('setChatDescription', _rectify(p)) |
See: https://core.telegram.org/bots/api#pinchatmessage | async def pinChatMessage(self, chat_id, message_id,
disable_notification=None):
""" See: https://core.telegram.org/bots/api#pinchatmessage """
p = _strip(locals())
return await self._api_request('pinChatMessage', _rectify(p)) |
See: https://core.telegram.org/bots/api#unpinchatmessage | async def unpinChatMessage(self, chat_id):
""" See: https://core.telegram.org/bots/api#unpinchatmessage """
p = _strip(locals())
return await self._api_request('unpinChatMessage', _rectify(p)) |
See: https://core.telegram.org/bots/api#getchatmember | async def getChatMember(self, chat_id, user_id):
""" See: https://core.telegram.org/bots/api#getchatmember """
p = _strip(locals())
return await self._api_request('getChatMember', _rectify(p)) |
See: https://core.telegram.org/bots/api#setchatstickerset | async def setChatStickerSet(self, chat_id, sticker_set_name):
""" See: https://core.telegram.org/bots/api#setchatstickerset """
p = _strip(locals())
return await self._api_request('setChatStickerSet', _rectify(p)) |
See: https://core.telegram.org/bots/api#deletechatstickerset | async def deleteChatStickerSet(self, chat_id):
""" See: https://core.telegram.org/bots/api#deletechatstickerset """
p = _strip(locals())
return await self._api_request('deleteChatStickerSet', _rectify(p)) |
See: https://core.telegram.org/bots/api#answercallbackquery | async def answerCallbackQuery(self, callback_query_id,
text=None,
show_alert=None,
url=None,
cache_time=None):
""" See: https://core.telegram.org/bots/api#answercallbackquery "... |
See: https://core.telegram.org/bots/api#deletemessage
:param msg_identifier:
Same as ``msg_identifier`` in :meth:`telepot.aio.Bot.editMessageText`,
except this method does not work on inline messages. | async def deleteMessage(self, msg_identifier):
"""
See: https://core.telegram.org/bots/api#deletemessage
:param msg_identifier:
Same as ``msg_identifier`` in :meth:`telepot.aio.Bot.editMessageText`,
except this method does not work on inline messages.
"""
... |
See: https://core.telegram.org/bots/api#sendsticker
:param sticker: Same as ``photo`` in :meth:`telepot.aio.Bot.sendPhoto` | async def sendSticker(self, chat_id, sticker,
disable_notification=None,
reply_to_message_id=None,
reply_markup=None):
"""
See: https://core.telegram.org/bots/api#sendsticker
:param sticker: Same as ``photo`` in :meth... |
See: https://core.telegram.org/bots/api#getstickerset | async def getStickerSet(self, name):
"""
See: https://core.telegram.org/bots/api#getstickerset
"""
p = _strip(locals())
return await self._api_request('getStickerSet', _rectify(p)) |
See: https://core.telegram.org/bots/api#deletestickerfromset | async def deleteStickerFromSet(self, sticker):
"""
See: https://core.telegram.org/bots/api#deletestickerfromset
"""
p = _strip(locals())
return await self._api_request('deleteStickerFromSet', _rectify(p)) |
See: https://core.telegram.org/bots/api#answerinlinequery | async def answerInlineQuery(self, inline_query_id, results,
cache_time=None,
is_personal=None,
next_offset=None,
switch_pm_text=None,
switch_pm_parameter=None):... |
See: https://core.telegram.org/bots/api#getupdates | async def getUpdates(self,
offset=None,
limit=None,
timeout=None,
allowed_updates=None):
""" See: https://core.telegram.org/bots/api#getupdates """
p = _strip(locals())
return await self._api_requ... |
See: https://core.telegram.org/bots/api#setwebhook | async def setWebhook(self,
url=None,
certificate=None,
max_connections=None,
allowed_updates=None):
""" See: https://core.telegram.org/bots/api#setwebhook """
p = _strip(locals(), more=['certificate'])
... |
Download a file to local disk.
:param dest: a path or a ``file`` object | async def download_file(self, file_id, dest):
"""
Download a file to local disk.
:param dest: a path or a ``file`` object
"""
f = await self.getFile(file_id)
try:
d = dest if isinstance(dest, io.IOBase) else open(dest, 'wb')
session, request = a... |
Return a task to constantly ``getUpdates`` or pull updates from a queue.
Apply ``handler`` to every message received.
:param handler:
a function that takes one argument (the message), or a routing table.
If ``None``, the bot's ``handle`` method is used.
A *routing table... | async def message_loop(self, handler=None, relax=0.1,
timeout=20, allowed_updates=None,
source=None, ordered=True, maxhold=3):
"""
Return a task to constantly ``getUpdates`` or pull updates from a queue.
Apply ``handler`` to every message rec... |
Gather proxies from the providers without checking.
:param list countries: (optional) List of ISO country codes
where should be located proxies
:param int limit: (optional) The maximum number of proxies
:ref:`Example of usage <proxybroker-examples-grab>`. | async def grab(self, *, countries=None, limit=0):
"""Gather proxies from the providers without checking.
:param list countries: (optional) List of ISO country codes
where should be located proxies
:param int limit: (optional) The maximum number of proxies
... |
Gather and check proxies from providers or from a passed data.
:ref:`Example of usage <proxybroker-examples-find>`.
:param list types:
Types (protocols) that need to be check on support by proxy.
Supported: HTTP, HTTPS, SOCKS4, SOCKS5, CONNECT:80, CONNECT:25
And lev... | async def find(
self,
*,
types=None,
data=None,
countries=None,
post=False,
strict=False,
dnsbl=None,
limit=0,
**kwargs
):
"""Gather and check proxies from providers or from a passed data.
:ref:`Example of usage <proxyb... |
Start a local proxy server.
The server distributes incoming requests to a pool of found proxies.
When the server receives an incoming request, it chooses the optimal
proxy (based on the percentage of errors and average response time)
and passes to it the incoming request.
In a... | def serve(self, host='127.0.0.1', port=8888, limit=100, **kwargs):
"""Start a local proxy server.
The server distributes incoming requests to a pool of found proxies.
When the server receives an incoming request, it chooses the optimal
proxy (based on the percentage of errors and avera... |
Looking for proxies in the passed data.
Transform the passed data from [raw string | file-like object | list]
to set {(host, port), ...}: {('192.168.0.1', '80'), } | async def _load(self, data, check=True):
"""Looking for proxies in the passed data.
Transform the passed data from [raw string | file-like object | list]
to set {(host, port), ...}: {('192.168.0.1', '80'), }
"""
log.debug('Load proxies from the raw data')
if isinstance(d... |
Stop all tasks, and the local proxy server if it's running. | def stop(self):
"""Stop all tasks, and the local proxy server if it's running."""
self._done()
if self._server:
self._server.stop()
self._server = None
log.info('Stop!') |
Show statistics on the found proxies.
Useful for debugging, but you can also use if you're interested.
:param verbose: Flag indicating whether to print verbose stats
.. deprecated:: 0.2.0
Use :attr:`verbose` instead of :attr:`full`. | def show_stats(self, verbose=False, **kwargs):
"""Show statistics on the found proxies.
Useful for debugging, but you can also use if you're interested.
:param verbose: Flag indicating whether to print verbose stats
.. deprecated:: 0.2.0
Use :attr:`verbose` instead of :att... |
Save proxies to a file. | async def save(proxies, filename):
"""Save proxies to a file."""
with open(filename, 'w') as f:
while True:
proxy = await proxies.get()
if proxy is None:
break
f.write('%s:%d\n' % (proxy.host, proxy.port)) |
Return geo information about IP address.
`code` - ISO country code
`name` - Full name of country
`region_code` - ISO region code
`region_name` - Full name of region
`city_name` - Full name of city | def get_ip_info(ip):
"""Return geo information about IP address.
`code` - ISO country code
`name` - Full name of country
`region_code` - ISO region code
`region_name` - Full name of region
`city_name` - Full name of city
"""
# from pprint import pprint
... |
Return real external IP address. | async def get_real_ext_ip(self):
"""Return real external IP address."""
while self._ip_hosts:
try:
timeout = aiohttp.ClientTimeout(total=self._timeout)
async with aiohttp.ClientSession(
timeout=timeout, loop=self._loop
) as ... |
Return resolving IP address(es) from host name. | async def resolve(
self, host, port=80, family=None, qtype='A', logging=True
):
"""Return resolving IP address(es) from host name."""
if self.host_is_ip(host):
return host
_host = self._cached_hosts.get(host)
if _host:
return _host
resp = awa... |
Asynchronously create a :class:`Proxy` object.
:param str host: A passed host can be a domain or IP address.
If the host is a domain, try to resolve it
:param str \*args:
(optional) Positional arguments that :class:`Proxy` takes
:param str \*\*kwargs:
... | async def create(cls, host, *args, **kwargs):
"""Asynchronously create a :class:`Proxy` object.
:param str host: A passed host can be a domain or IP address.
If the host is a domain, try to resolve it
:param str \*args:
(optional) Positional arguments that :... |
Error rate: from 0 to 1.
For example: 0.7 = 70% requests ends with error.
:rtype: float
.. versionadded:: 0.2.0 | def error_rate(self):
"""Error rate: from 0 to 1.
For example: 0.7 = 70% requests ends with error.
:rtype: float
.. versionadded:: 0.2.0
"""
if not self.stat['requests']:
return 0
return round(
sum(self.stat['errors'].values()) / self.st... |
Return supported schemes. | def schemes(self):
"""Return supported schemes."""
if not self._schemes:
_schemes = []
if self.types.keys() & _HTTP_PROTOS:
_schemes.append('HTTP')
if self.types.keys() & _HTTPS_PROTOS:
_schemes.append('HTTPS')
self._schemes... |
The average connection/response time.
:rtype: float | def avg_resp_time(self):
"""The average connection/response time.
:rtype: float
"""
if not self._runtimes:
return 0
return round(sum(self._runtimes) / len(self._runtimes), 2) |
Return the proxy's properties in JSON format.
:rtype: dict | def as_json(self):
"""Return the proxy's properties in JSON format.
:rtype: dict
"""
info = {
'host': self.host,
'port': self.port,
'geo': {
'country': {'code': self._geo.code, 'name': self._geo.name},
'region': {
... |
Receive proxies from the provider and return them.
:return: :attr:`.proxies` | async def get_proxies(self):
"""Receive proxies from the provider and return them.
:return: :attr:`.proxies`
"""
log.debug('Try to get proxies from %s' % self.domain)
async with aiohttp.ClientSession(
headers=get_headers(), cookies=self._cookies, loop=self._loop
... |
Save proxies to a file. | async def save(proxies, filename):
"""Save proxies to a file."""
with open(filename, 'w') as f:
while True:
proxy = await proxies.get()
if proxy is None:
break
proto = 'https' if 'HTTPS' in proxy.types else 'http'
row = '%s://%s:%d\n' % (pr... |
Updates global configuration settings with given values.
First checks if given configuration values differ from current values.
If any of the configuration values changed, generates a change event.
Currently we generate change event for any configuration change.
Note: This method is ide... | def update(self, **kwargs):
"""Updates global configuration settings with given values.
First checks if given configuration values differ from current values.
If any of the configuration values changed, generates a change event.
Currently we generate change event for any configuration c... |
Converts binary representation label to integer.
:param buf: Binary representation of label.
:return: MPLS Label and BoS bit. | def label_from_bin(buf):
"""
Converts binary representation label to integer.
:param buf: Binary representation of label.
:return: MPLS Label and BoS bit.
"""
mpls_label = type_desc.Int3.to_user(six.binary_type(buf))
return mpls_label >> 4, mpls_label & 1 |
Removes VRF table associated with given `vrf_conf`.
Cleans up other links to this table as well. | def on_remove_vrf_conf(self, evt):
"""Removes VRF table associated with given `vrf_conf`.
Cleans up other links to this table as well.
"""
vrf_conf = evt.value
# Detach VrfConf change listener.
vrf_conf.remove_listener(VrfConf.VRF_CHG_EVT, self.on_chg_vrf_conf)
... |
Event handler for new VrfConf.
Creates a VrfTable to store routing information related to new Vrf.
Also arranges for related paths to be imported to this VrfTable. | def on_add_vrf_conf(self, evt):
"""Event handler for new VrfConf.
Creates a VrfTable to store routing information related to new Vrf.
Also arranges for related paths to be imported to this VrfTable.
"""
vrf_conf = evt.value
route_family = vrf_conf.route_family
as... |
Parses family and prefix in Zebra format. | def _parse_zebra_family_prefix(buf):
"""
Parses family and prefix in Zebra format.
"""
(family,) = struct.unpack_from(_ZEBRA_FAMILY_FMT, buf)
rest = buf[_ZEBRA_FAMILY_SIZE:]
if socket.AF_INET == family:
(prefix, p_len) = struct.unpack_from(_ZEBRA_IPV4_PREFIX_FMT, rest)
prefix = ... |
Serializes family and prefix in Zebra format. | def _serialize_zebra_family_prefix(prefix):
"""
Serializes family and prefix in Zebra format.
"""
if ip.valid_ipv4(prefix):
family = socket.AF_INET # fixup
prefix_addr, prefix_num = prefix.split('/')
return family, struct.pack(
_ZEBRA_FAMILY_IPV4_PREFIX_FMT,
... |
Returns True if the given MAC address is valid.
The given MAC address should be a colon hexadecimal notation string.
Samples:
- valid address: aa:bb:cc:dd:ee:ff, 11:22:33:44:55:66
- invalid address: aa:bb:cc:dd, 11-22-33-44-55-66, etc. | def is_valid_mac(mac):
"""Returns True if the given MAC address is valid.
The given MAC address should be a colon hexadecimal notation string.
Samples:
- valid address: aa:bb:cc:dd:ee:ff, 11:22:33:44:55:66
- invalid address: aa:bb:cc:dd, 11-22-33-44-55-66, etc.
"""
return bool(re.m... |
Returns True if *prefix* is a valid IPv4 or IPv6 address prefix.
*prefix* should be a number between 0 to *bits* length. | def is_valid_ip_prefix(prefix, bits):
"""Returns True if *prefix* is a valid IPv4 or IPv6 address prefix.
*prefix* should be a number between 0 to *bits* length.
"""
try:
# Prefix should be a number
prefix = int(prefix)
except ValueError:
return False
# Prefix should be... |
Returns True if *ipv4_prefix* is a valid prefix with mask.
Samples:
- valid prefix: 1.1.1.0/32, 244.244.244.1/10
- invalid prefix: 255.2.2.2/2, 2.2.2/22, etc. | def is_valid_ipv4_prefix(ipv4_prefix):
"""Returns True if *ipv4_prefix* is a valid prefix with mask.
Samples:
- valid prefix: 1.1.1.0/32, 244.244.244.1/10
- invalid prefix: 255.2.2.2/2, 2.2.2/22, etc.
"""
if not isinstance(ipv4_prefix, str):
return False
tokens = ipv4_prefi... |
Returns True if given `ipv6_prefix` is a valid IPv6 prefix. | def is_valid_ipv6_prefix(ipv6_prefix):
"""Returns True if given `ipv6_prefix` is a valid IPv6 prefix."""
# Validate input type
if not isinstance(ipv6_prefix, str):
return False
tokens = ipv6_prefix.split('/')
if len(tokens) != 2:
return False
# Validate address/mask and return... |
Returns True if given prefix is a string represent vpnv4 prefix.
Vpnv4 prefix is made up of RD:Ipv4, where RD is represents route
distinguisher and Ipv4 represents valid dot-decimal ipv4 notation string. | def is_valid_vpnv4_prefix(prefix):
"""Returns True if given prefix is a string represent vpnv4 prefix.
Vpnv4 prefix is made up of RD:Ipv4, where RD is represents route
distinguisher and Ipv4 represents valid dot-decimal ipv4 notation string.
"""
if not isinstance(prefix, str):
return False
... |
Returns True if given prefix is a string represent vpnv6 prefix.
Vpnv6 prefix is made up of RD:Ipv6, where RD is represents route
distinguisher and Ipv6 represents valid colon hexadecimal notation string. | def is_valid_vpnv6_prefix(prefix):
"""Returns True if given prefix is a string represent vpnv6 prefix.
Vpnv6 prefix is made up of RD:Ipv6, where RD is represents route
distinguisher and Ipv6 represents valid colon hexadecimal notation string.
"""
if not isinstance(prefix, str):
return False... |
Validates `label` according to MPLS label rules
RFC says:
This 20-bit field.
A value of 0 represents the "IPv4 Explicit NULL Label".
A value of 1 represents the "Router Alert Label".
A value of 2 represents the "IPv6 Explicit NULL Label".
A value of 3 represents the "Implicit NULL Label".
V... | def is_valid_mpls_label(label):
"""Validates `label` according to MPLS label rules
RFC says:
This 20-bit field.
A value of 0 represents the "IPv4 Explicit NULL Label".
A value of 1 represents the "Router Alert Label".
A value of 2 represents the "IPv6 Explicit NULL Label".
A value of 3 repr... |
Returns True if the given value is a list of valid MPLS labels. | def is_valid_mpls_labels(labels):
"""Returns True if the given value is a list of valid MPLS labels.
"""
if not isinstance(labels, (list, tuple)):
return False
for label in labels:
if not is_valid_mpls_label(label):
return False
return True |
Validates *attr* as string representation of RT or SOO.
Returns True if *attr* is as per our convention of RT or SOO, else
False. Our convention is to represent RT/SOO is a string with format:
*global_admin_part:local_admin_path* | def is_valid_ext_comm_attr(attr):
"""Validates *attr* as string representation of RT or SOO.
Returns True if *attr* is as per our convention of RT or SOO, else
False. Our convention is to represent RT/SOO is a string with format:
*global_admin_part:local_admin_path*
"""
if not isinstance(attr, ... |
Returns True if the given EVPN Ethernet SegmentEthernet ID is valid. | def is_valid_esi(esi):
"""Returns True if the given EVPN Ethernet SegmentEthernet ID is valid."""
if isinstance(esi, numbers.Integral):
return 0 <= esi <= 0xffffffffffffffffff
return isinstance(esi, dict) |
dissect messages from a raw stream data.
disp_table[type] should be a callable for the corresponding
MessageType. | def get_and_dispatch_messages(self, data, disp_table):
"""dissect messages from a raw stream data.
disp_table[type] should be a callable for the corresponding
MessageType.
"""
self._unpacker.feed(data)
for m in self._unpacker:
self._dispatch_message(m, disp_ta... |
Send a request | def send_request(self, method, params):
"""Send a request
"""
msg, msgid = self._encoder.create_request(method, params)
self._send_message(msg)
self._pending_requests.add(msgid)
return msgid |
Send a response | def send_response(self, msgid, error=None, result=None):
"""Send a response
"""
msg = self._encoder.create_response(msgid, error, result)
self._send_message(msg) |
Send a notification | def send_notification(self, method, params):
"""Send a notification
"""
msg = self._encoder.create_notification(method, params)
self._send_message(msg) |
Try to receive some messages.
Received messages are put on the internal queues.
They can be retrieved using get_xxx() methods.
Returns True if there's something queued for get_xxx() methods. | def receive_messages(self, all=False):
"""Try to receive some messages.
Received messages are put on the internal queues.
They can be retrieved using get_xxx() methods.
Returns True if there's something queued for get_xxx() methods.
"""
while all or self._incoming == 0:
... |
synchronous call.
send a request and wait for a response.
return a result. or raise RPCError exception if the peer
sends us an error. | def call(self, method, params):
"""synchronous call.
send a request and wait for a response.
return a result. or raise RPCError exception if the peer
sends us an error.
"""
msgid = self._endpoint.send_request(method, params)
while True:
if not self._e... |
wait for the next incoming message.
intended to be used when we have nothing to send but want to receive
notifications. | def receive_notification(self):
"""wait for the next incoming message.
intended to be used when we have nothing to send but want to receive
notifications.
"""
if not self._endpoint.receive_messages():
raise EOFError("EOF")
self._process_input_notification()
... |
Start running pre-set function every interval seconds. | def start(self, interval, now=True):
"""Start running pre-set function every interval seconds.
"""
if interval < 0:
raise ValueError('interval must be >= 0')
if self._running:
self.stop()
self._running = True
self._interval = interval
if ... |
Stop running scheduled function. | def stop(self):
"""Stop running scheduled function.
"""
self._running = False
if self._self_thread is not None:
self._self_thread.cancel()
self._self_thread = None |
Skip the next iteration and reset timer. | def reset(self):
"""Skip the next iteration and reset timer.
"""
if self._self_thread is not None:
# Cancel currently scheduled call
self._self_thread.cancel()
self._self_thread = None
# Schedule a new call
self._self_thread = hub.spawn_after(s... |
Returns *conf_name* settings if provided in *all_config*, else returns
*default_value*.
Validates *conf_name* value if provided. | def compute_optional_conf(conf_name, default_value, **all_config):
"""Returns *conf_name* settings if provided in *all_config*, else returns
*default_value*.
Validates *conf_name* value if provided.
"""
conf_value = all_config.get(conf_name)
if conf_value is not None:
# Validate config... |
Encode a BFD Control packet without authentication section. | def pack(self):
"""
Encode a BFD Control packet without authentication section.
"""
diag = (self.ver << 5) + self.diag
flags = (self.state << 6) + self.flags
length = len(self)
return struct.pack(self._PACK_STR, diag, flags, self.detect_mult,
... |
Authenticate this packet.
Returns a boolean indicates whether the packet can be authenticated
or not.
Returns ``False`` if the Authentication Present (A) is not set in the
flag of this packet.
Returns ``False`` if the Authentication Section for this packet is not
prese... | def authenticate(self, *args, **kwargs):
"""Authenticate this packet.
Returns a boolean indicates whether the packet can be authenticated
or not.
Returns ``False`` if the Authentication Present (A) is not set in the
flag of this packet.
Returns ``False`` if the Authent... |
Parser for common part of authentication section. | def parser_hdr(cls, buf):
"""
Parser for common part of authentication section.
"""
return struct.unpack_from(cls._PACK_HDR_STR,
buf[:cls._PACK_HDR_STR_LEN]) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.