text stringlengths 81 112k |
|---|
Save configurations to a single string
def savetostr(self, sortkey = True):
"""
Save configurations to a single string
"""
return ''.join(k + '=' + repr(v) + '\n' for k,v in self.config_items(sortkey)) |
Save configurations to a file-like object which supports `writelines`
def savetofile(self, filelike, sortkey = True):
"""
Save configurations to a file-like object which supports `writelines`
"""
filelike.writelines(k + '=' + repr(v) + '\n' for k,v in self.config_items(sortkey)) |
Save configurations to path
def saveto(self, path, sortkey = True):
"""
Save configurations to path
"""
with open(path, 'w') as f:
self.savetofile(f, sortkey) |
Return the parent from which this class inherits configurations
def getConfigurableParent(cls):
"""
Return the parent from which this class inherits configurations
"""
for p in cls.__bases__:
if isinstance(p, Configurable) and p is not Configurable:
return p
... |
Return the mapped configuration root node
def getConfigRoot(cls, create = False):
"""
Return the mapped configuration root node
"""
try:
return manager.gettree(getattr(cls, 'configkey'), create)
except AttributeError:
return None |
Return all mapped configuration keys for this object
def config_value_keys(self, sortkey = False):
"""
Return all mapped configuration keys for this object
"""
ret = set()
cls = type(self)
while True:
root = cls.getConfigRoot()
if root:
... |
Return `(key, value)` tuples for all mapped configurations for this object
def config_value_items(self, sortkey = False):
"""
Return `(key, value)` tuples for all mapped configurations for this object
"""
return ((k, getattr(self, k)) for k in self.config_value_keys(sortkey)) |
The most simple way to start the VLCP framework
:param configpath: path of a configuration file to be loaded
:param startup: startup modules list. If None, `server.startup` in the configuration files
is used; if `server.startup` is not configured, any module defined or imported
... |
Wait for a VXLAN group to be created
async def wait_for_group(self, container, networkid, timeout = 120):
"""
Wait for a VXLAN group to be created
"""
if networkid in self._current_groups:
return self._current_groups[networkid]
else:
if not self._connecti... |
Coroutine method to read from the stream and return the data. Raises EOFError
when the stream end has been reached; raises IOError if there are other errors.
:param container: A routine container
:param size: maximum read size, or unlimited if is None
async def read(self, cont... |
Read from current buffer. If current buffer is empty, returns an empty string. You can use `prepareRead`
to read the next chunk of data.
This is not a coroutine method.
def readonce(self, size = None):
"""
Read from current buffer. If current buffer is empty, returns an empty s... |
Coroutine method which reads the next line or until EOF or size exceeds
async def readline(self, container = None, size = None):
"""
Coroutine method which reads the next line or until EOF or size exceeds
"""
ret = []
retsize = 0
if self.eof:
raise EOFError
... |
Coroutine method to copy content from this stream to another stream.
async def copy_to(self, dest, container, buffering = True):
"""
Coroutine method to copy content from this stream to another stream.
"""
if self.eof:
await dest.write(u'' if self.isunicode else b'', True)
... |
Coroutine method to write data to this stream.
:param data: data to write
:param container: the routine container
:param eof: if True, this is the last chunk of this stream. The other end will receive an EOF after reading
this chunk.
... |
Find a subtree from a matcher
:param matcher: the matcher to locate the subtree. If None, return the root of the tree.
:param create: if True, the subtree is created if not exists; otherwise return None if not exists
def subtree(self, matcher, create = False):
'''
Find... |
Insert a new matcher
:param matcher: an EventMatcher
:param obj: object to return
def insert(self, matcher, obj):
'''
Insert a new matcher
:param matcher: an EventMatcher
:param obj: object to return
'''
current = self.... |
Remove the matcher
:param matcher: an EventMatcher
:param obj: the object to remove
def remove(self, matcher, obj):
'''
Remove the matcher
:param matcher: an EventMatcher
:param obj: the object to remove
'''
current = s... |
Return all matches for this event. The first matcher is also returned for each matched object.
:param event: an input event
def matchesWithMatchers(self, event):
'''
Return all matches for this event. The first matcher is also returned for each matched object.
:param e... |
Return all matches for this event. The first matcher is also returned for each matched object.
:param event: an input event
def matches(self, event):
'''
Return all matches for this event. The first matcher is also returned for each matched object.
:param event: an inp... |
Return first match for this event
:param event: an input event
def matchfirst(self, event):
'''
Return first match for this event
:param event: an input event
'''
# 1. matches(self.index[ind], event)
# 2. matches(self.any, event)
# 3. se... |
Find a subtree from an event
def subtree(self, event, create = False):
'''
Find a subtree from an event
'''
current = self
for i in range(self.depth, len(event.indices)):
if not hasattr(current, 'index'):
return current
ind = event.indices... |
Return a walker function to retrieve necessary information from ObjectDB
def lognet_vxlan_walker(prepush = True):
"""
Return a walker function to retrieve necessary information from ObjectDB
"""
def _walk_lognet(key, value, walk, save):
save(key)
if value is None:
return
... |
Do an ObjectDB transact to update all VXLAN informations
:param container: Routine container
:param network_ip_dict: a {logicalnetwork_id: tunnel_ip} dictionary
:param created_ports: logical ports to be added, a {logicalport_id: tunnel_ip} dictionary
:param removed_ports: logical por... |
Get all IP addresses that are not local
:param vxlan_endpointset: a VXLANEndpointSet object
:param local_ips: list of local IP address to exclude with
:param ovsdb_vhost: identifier, vhost
:param system_id: identifier, system-id
:param bridge: identifier, bridge name
... |
:return: None if the result is not ready, the result from set_result, or raise the exception
from set_exception. If the result can be None, it is not possible to tell if the result is
available; use done() to determine that.
def result(self):
'''
:return: None if the r... |
:param container: DEPRECATED container of current routine
:return: The result, or raise the exception from set_exception.
async def wait(self, container = None):
'''
:param container: DEPRECATED container of current routine
:return: The result, or raise the exception f... |
Set the result to Future object, wake up all the waiters
:param result: result to set
def set_result(self, result):
'''
Set the result to Future object, wake up all the waiters
:param result: result to set
'''
if hasattr(self, '_result'):
ra... |
Set an exception to Future object, wake up all the waiters
:param exception: exception to set
def set_exception(self, exception):
'''
Set an exception to Future object, wake up all the waiters
:param exception: exception to set
'''
if hasattr(self, '_re... |
Context manager to ensure returning the result
def ensure_result(self, supress_exception = False, defaultresult = None):
'''
Context manager to ensure returning the result
'''
try:
yield self
except Exception as exc:
if not self.done():
se... |
Perform a data export of a given result set. This is a very
flexible exporter, allowing for various output formats, metadata
assignment, and file name templating to dump each record (or a set
of records) into individual files.
::
result = db['person'].all()
dataset.freeze(result, forma... |
Convert an X509 certificate into a Python dictionary
This function converts the given X509 certificate into a Python dictionary
in the manner established by the Python standard library's ssl module.
def decode_cert(cert):
"""Convert an X509 certificate into a Python dictionary
This function converts ... |
Retrieve a server certificate
Retrieve the certificate from the server at the specified address,
and return it as a PEM-encoded string.
If 'ca_certs' is specified, validate the server cert against it.
If 'ssl_version' is specified, use it in the connection attempt.
def _get_server_certificate(addr, ss... |
u''' Set supported curves by name, nid or nist.
:param str | tuple(int) curves: Example "secp384r1:secp256k1", (715, 714), "P-384", "K-409:B-409:K-571", ...
:return: 1 for success and 0 for failure
def set_curves(self, curves):
u''' Set supported curves by name, nid or nist.
:param st... |
u''' Select a curve to use for ECDH(E) key exchange or set it to auto mode
Used for server only!
s.a. openssl.exe ecparam -list_curves
:param None | str curve_name: None = Auto-mode, "secp256k1", "secp384r1", ...
:return: 1 for success and 0 for failure
def set_ecdh_curve(self, curve... |
u'''
Used for server side only!
:param flags:
:return: 1 for success and 0 for failure
def build_cert_chain(self, flags=SSL_BUILD_CHAIN_FLAG_NONE):
u'''
Used for server side only!
:param flags:
:return: 1 for success and 0 for failure
'''
retVal... |
u''' Enable or disable SSL logging
:param True | False enable: Enable or disable SSL logging
:param func: Callback function for logging
def set_ssl_logging(self, enable=False, func=_ssl_logging_cb):
u''' Enable or disable SSL logging
:param True | False enable: Enable or disable SSL l... |
Retrieve a socket used by this connection
When inbound is True, then the socket from which this connection reads
data is retrieved. Otherwise the socket to which this connection writes
data is retrieved.
Read and write sockets differ depending on whether this is a server- or
a ... |
Server-side cookie exchange
This method reads datagrams from the socket and initiates cookie
exchange, upon whose successful conclusion one can then proceed to
the accept method. Alternatively, accept can be called directly, in
which case it will call this method. In order to prevent de... |
Server-side UDP connection establishment
This method returns a server-side SSLConnection object, connected to
that peer most recently returned from the listen method and not yet
connected. If there is no such peer, then the listen method is invoked.
Return value: SSLConnection connecte... |
Client-side UDP connection establishment
This method connects this object's underlying socket. It subsequently
performs a handshake if do_handshake_on_connect was set during
initialization.
Arguments:
peer_address - address tuple of server peer
def connect(self, peer_address):... |
Perform a handshake with the peer
This method forces an explicit handshake to be performed with either
the client or server peer.
def do_handshake(self):
"""Perform a handshake with the peer
This method forces an explicit handshake to be performed with either
the client or ser... |
Read data from connection
Read up to len bytes and return them.
Arguments:
len -- maximum number of bytes to read
Return value:
string containing read bytes
def read(self, len=1024, buffer=None):
"""Read data from connection
Read up to len bytes and return the... |
Write data to connection
Write data as string of bytes.
Arguments:
data -- buffer containing data to be written
Return value:
number of bytes actually transmitted
def write(self, data):
"""Write data to connection
Write data as string of bytes.
Argum... |
Shut down the DTLS connection
This method attemps to complete a bidirectional shutdown between
peers. For non-blocking sockets, it should be called repeatedly until
it no longer raises continuation request exceptions.
def shutdown(self):
"""Shut down the DTLS connection
This m... |
Retrieve the peer's certificate
When binary form is requested, the peer's DER-encoded certficate is
returned if it was transmitted during the handshake.
When binary form is not requested, and the peer's certificate has been
validated, then a certificate dictionary is returned. If the c... |
Retrieve information about the current cipher
Return a triple consisting of cipher name, SSL protocol version defining
its use, and the number of secret bits. Return None if handshaking
has not been completed.
def cipher(self):
"""Retrieve information about the current cipher
... |
Support for running straight out of a cloned source directory instead
of an installed distribution
def _prep_bins():
"""
Support for running straight out of a cloned source directory instead
of an installed distribution
"""
from os import path
from sys import platform, maxsize
from shu... |
Create or retrieve a muxed connection
Arguments:
address -- a peer endpoint in IPv4/v6 address format; None refers
to the connection for unknown peers
Return:
a bound, connected datagram socket instance, or the root socket
in case address was None
def get_co... |
Set the info callback
:param callback: The Python callback to use
:return: None
def SSL_CTX_set_info_callback(ctx, app_info_cb):
"""
Set the info callback
:param callback: The Python callback to use
:return: None
"""
def py_info_callback(ssl, where, ret):
try:
app_... |
Raise an SSL error with the given error code
def raise_ssl_error(code, nested=None):
"""Raise an SSL error with the given error code"""
err_string = str(code) + ": " + _ssl_errors[code]
if nested:
raise SSLError(code, err_string + str(nested))
raise SSLError(code, err_string) |
Create or retrieve a muxed connection
Arguments:
address -- a peer endpoint in IPv4/v6 address format; None refers
to the connection for unknown peers
Return:
a bound, connected datagram socket instance
def get_connection(self, address):
"""Create or retriev... |
Service the root socket
Read from the root socket and forward one datagram to a
connection. The call will return without forwarding data
if any of the following occurs:
* An error is encountered while reading from the root socket
* Reading from the root socket times out
... |
Forward a stored datagram
When the service method returns the address of a new peer, it holds
the datagram from that peer in this instance. In this case, this
method will perform the forwarding step. The target connection is the
one associated with address None if get_connection has not... |
Convert any emoji in a string into accessible content.
def emojificate_filter(content, autoescape=True):
"Convert any emoji in a string into accessible content."
# return mark_safe(emojificate(content))
if autoescape:
esc = conditional_escape
else:
esc = lambda x: x
return mark_safe... |
Update the orders
def updateorders(self):
""" Update the orders
"""
log.info("Replacing orders")
# Canceling orders
self.cancelall()
# Target
target = self.bot.get("target", {})
price = self.getprice()
# prices
buy_price = price * (1 - ... |
Here we obtain the price for the quote and make sure it has
a feed price
def getprice(self):
""" Here we obtain the price for the quote and make sure it has
a feed price
"""
target = self.bot.get("target", {})
if target.get("reference") == "feed":
ass... |
ticks come in on every block
def tick(self, d):
""" ticks come in on every block
"""
if self.test_blocks:
if not (self.counter["blocks"] or 0) % self.test_blocks:
self.test()
self.counter["blocks"] += 1 |
Return the bot's open accounts in the current market
def orders(self):
""" Return the bot's open accounts in the current market
"""
self.account.refresh()
return [o for o in self.account.openorders if self.bot["market"] == o.market and self.account.openorders] |
This method distringuishes notifications caused by Matched orders
from those caused by placed orders
def _callbackPlaceFillOrders(self, d):
""" This method distringuishes notifications caused by Matched orders
from those caused by placed orders
"""
if isinstance(d, Fille... |
Execute a bundle of operations
def execute(self):
""" Execute a bundle of operations
"""
self.bitshares.blocking = "head"
r = self.bitshares.txbuffer.broadcast()
self.bitshares.blocking = False
return r |
Cancel all orders of this bot
def cancelall(self):
""" Cancel all orders of this bot
"""
if self.orders:
return self.bitshares.cancel(
[o["id"] for o in self.orders],
account=self.account
) |
Bytes representation of the XML content.
(`learn more <http://www.diveintopython3.net/strings.html>`_).
def raw_xml(self) -> _RawXML:
"""Bytes representation of the XML content.
(`learn more <http://www.diveintopython3.net/strings.html>`_).
"""
if self._xml:
return s... |
Unicode representation of the XML content
(`learn more <http://www.diveintopython3.net/strings.html>`_).
def xml(self) -> _BaseXML:
"""Unicode representation of the XML content
(`learn more <http://www.diveintopython3.net/strings.html>`_).
"""
if self._xml:
return se... |
`PyQuery <https://pythonhosted.org/pyquery/>`_ representation
of the :class:`Element <Element>` or :class:`HTML <HTML>`.
def pq(self) -> PyQuery:
"""`PyQuery <https://pythonhosted.org/pyquery/>`_ representation
of the :class:`Element <Element>` or :class:`HTML <HTML>`.
"""
if se... |
`lxml <http://lxml.de>`_ representation of the
:class:`Element <Element>` or :class:`XML <XML>`.
def lxml(self) -> _LXML:
"""`lxml <http://lxml.de>`_ representation of the
:class:`Element <Element>` or :class:`XML <XML>`.
"""
if self._lxml is None:
self._lxml = etree... |
All found links on page, in as–is form. Only works for Atom feeds.
def links(self) -> _Links:
"""All found links on page, in as–is form. Only works for Atom feeds."""
return list(set(x.text for x in self.xpath('//link'))) |
The encoding string to be used, extracted from the XML and
:class:`XMLResponse <XMLResponse>` header.
def encoding(self) -> _Encoding:
"""The encoding string to be used, extracted from the XML and
:class:`XMLResponse <XMLResponse>` header.
"""
if self._encoding:
retu... |
A JSON Representation of the XML. Default is badgerfish.
:param conversion: Which conversion method to use. (`learn more <https://github.com/sanand0/xmljson#conventions>`_)
def json(self, conversion: _Text = 'badgerfish') -> Mapping:
"""A JSON Representation of the XML. Default is badgerfish.
... |
Given an XPath selector, returns a list of
:class:`Element <Element>` objects or a single one.
:param selector: XPath Selector to use.
:param first: Whether or not to return just the first result.
:param _encoding: The encoding format.
If a sub-selector is specified (e.g. ``//a... |
Search the :class:`Element <Element>` for the given parse
template.
:param template: The Parse template to use.
def search(self, template: str, first: bool = False) -> _Result:
"""Search the :class:`Element <Element>` for the given parse
template.
:param template: The Parse te... |
Given a simple element name, returns a list of
:class:`Element <Element>` objects or a single one.
:param selector: Element name to find.
:param containing: If specified, only return elements that contain the provided text.
:param first: Whether or not to return just the... |
Requests HTTP Response handler. Attaches .html property to
class:`requests.Response <requests.Response>` objects.
def _handle_response(response, **kwargs) -> XMLResponse:
"""Requests HTTP Response handler. Attaches .html property to
class:`requests.Response <requests.Response>` objects.
... |
Makes an HTTP Request, with mocked User–Agent headers.
Returns a class:`HTTPResponse <HTTPResponse>`.
def request(self, *args, **kwargs) -> XMLResponse:
"""Makes an HTTP Request, with mocked User–Agent headers.
Returns a class:`HTTPResponse <HTTPResponse>`.
"""
# Convert Request... |
Change response enconding and replace it by a HTMLResponse.
def response_hook(response, **kwargs) -> XMLResponse:
""" Change response enconding and replace it by a HTMLResponse. """
response.encoding = DEFAULT_ENCODING
return XMLResponse._from_response(response) |
Start the background process.
def start(self):
"""Start the background process."""
self._lc = LoopingCall(self._download)
# Run immediately, and then every 30 seconds:
self._lc.start(30, now=True) |
Download the page.
def _download(self):
"""Download the page."""
print("Downloading!")
def parse(result):
print("Got %r back from Yahoo." % (result,))
values = result.strip().split(",")
self._value = float(values[1])
d = getPage(
"http://d... |
Register an EventualResult.
May be called in any thread.
def register(self, result):
"""
Register an EventualResult.
May be called in any thread.
"""
if self._stopped:
raise ReactorStopped()
self._results.add(result) |
Indicate no more results will get pushed into EventualResults, since
the reactor has stopped.
This should be called in the reactor thread.
def stop(self):
"""
Indicate no more results will get pushed into EventualResults, since
the reactor has stopped.
This should be c... |
Hook up the Deferred that that this will be the result of.
Should only be run in Twisted thread, and only called once.
def _connect_deferred(self, deferred):
"""
Hook up the Deferred that that this will be the result of.
Should only be run in Twisted thread, and only called once.
... |
Set the result of the EventualResult, if not already set.
This can only happen in the reactor thread, either as a result of
Deferred firing, or as a result of ResultRegistry.stop(). So, no need
for thread-safety.
def _set_result(self, result):
"""
Set the result of the Eventual... |
Return the result, if available.
It may take an unknown amount of time to return the result, so a
timeout option is provided. If the given number of seconds pass with
no result, a TimeoutError will be thrown.
If a previous call timed out, additional calls to this function will
... |
Return the result, or throw the exception if result is a failure.
It may take an unknown amount of time to return the result, so a
timeout option is provided. If the given number of seconds pass with
no result, a TimeoutError will be thrown.
If a previous call timed out, additional cal... |
Return the underlying Failure object, if the result is an error.
If no result is yet available, or the result was not an error, None is
returned.
This method is useful if you want to get the original traceback for an
error result.
def original_failure(self):
"""
Return... |
Start a LoopingCall that calls reapAllProcesses.
def _startReapingProcesses(self):
"""
Start a LoopingCall that calls reapAllProcesses.
"""
lc = LoopingCall(self._reapAllProcesses)
lc.clock = self._reactor
lc.start(0.1, False) |
The minimal amount of setup done by both setup() and no_setup().
def _common_setup(self):
"""
The minimal amount of setup done by both setup() and no_setup().
"""
self._started = True
self._reactor = self._reactorFactory()
self._registry = ResultRegistry()
# We w... |
Initialize the crochet library.
This starts the reactor in a thread, and connect's Twisted's logs to
Python's standard library logging module.
This must be called at least once before the library can be used, and
can be called multiple times.
def setup(self):
"""
Initi... |
Implementation: A decorator that ensures the wrapped function runs in
the reactor thread.
When the wrapped function is called, an EventualResult is returned.
def _run_in_reactor(self, function, _, args, kwargs):
"""
Implementation: A decorator that ensures the wrapped function runs in
... |
A decorator that ensures the wrapped function runs in the
reactor thread.
When the wrapped function is called, an EventualResult is returned.
def run_in_reactor(self, function):
"""
A decorator that ensures the wrapped function runs in the
reactor thread.
When the wrap... |
DEPRECATED, use wait_for(timeout) instead.
A decorator that ensures the wrapped function runs in the reactor
thread.
When the wrapped function is called, its result is returned or its
exception raised. Deferreds are handled transparently.
def wait_for_reactor(self, function):
... |
A decorator factory that ensures the wrapped function runs in the
reactor thread.
When the wrapped function is called, its result is returned or its
exception raised. Deferreds are handled transparently. Calls will
timeout after the given number of seconds (a float), raising a
c... |
DEPRECATED, use run_in_reactor.
A decorator that ensures the wrapped function runs in the reactor
thread.
The wrapped function will get the reactor passed in as a first
argument, in addition to any arguments it is called with.
When the wrapped function is called, an EventualRe... |
Return Deferred that fires with a list of (priority, MX domain) tuples for
a given domain.
def _mx(domain):
"""
Return Deferred that fires with a list of (priority, MX domain) tuples for
a given domain.
"""
def got_records(result):
return sorted(
[(int(record.payload.prefere... |
Store a EventualResult.
Return an integer, a unique identifier that can be used to retrieve
the object.
def store(self, deferred_result):
"""
Store a EventualResult.
Return an integer, a unique identifier that can be used to retrieve
the object.
"""
sel... |
Log errors for all stored EventualResults that have error results.
def log_errors(self):
"""
Log errors for all stored EventualResults that have error results.
"""
for result in self._stored.values():
failure = result.original_failure()
if failure is not None:
... |
Start an SSH server on the given port, exposing a Python prompt with the
given namespace.
def start_ssh_server(port, username, password, namespace):
"""
Start an SSH server on the given port, exposing a Python prompt with the
given namespace.
"""
# This is a lot of boilerplate, see http://tm.tl... |
Underlying synchronized wrapper.
def _synced(method, self, args, kwargs):
"""Underlying synchronized wrapper."""
with self._lock:
return method(*args, **kwargs) |
Register a function and arguments to be called later.
def register(self, f, *args, **kwargs):
"""
Register a function and arguments to be called later.
"""
self._functions.append(lambda: f(*args, **kwargs)) |
Register function to be called from EPC client.
:type function: callable
:arg function: Function to publish.
:type name: str
:arg name: Name by which function is published.
This method returns the given `function` as-is, so that you
can use it as a decorat... |
Get registered method callend `name`.
def get_method(self, name):
"""
Get registered method callend `name`.
"""
try:
return self.funcs[name]
except KeyError:
try:
return self.instance._get_method(name)
except AttributeError:
... |
Set debugger to run when an error occurs in published method.
You can also set debugger by passing `debugger` argument to
the class constructor.
:type debugger: {'pdb', 'ipdb', None}
:arg debugger: type of debugger.
def set_debugger(self, debugger):
"""
Set debugger t... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.