text_prompt
stringlengths 100
17.7k
⌀ | code_prompt
stringlengths 7
9.86k
⌀ |
---|---|
<SYSTEM_TASK:>
Save configurations to a list of strings
<END_TASK>
<USER_TASK:>
Description:
def save(self, sortkey = True):
"""
Save configurations to a list of strings
""" |
return [k + '=' + repr(v) for k,v in self.config_items(sortkey)] |
<SYSTEM_TASK:>
Save configurations to a single string
<END_TASK>
<USER_TASK:>
Description:
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)) |
<SYSTEM_TASK:>
Save configurations to a file-like object which supports `writelines`
<END_TASK>
<USER_TASK:>
Description:
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)) |
<SYSTEM_TASK:>
Save configurations to path
<END_TASK>
<USER_TASK:>
Description:
def saveto(self, path, sortkey = True):
"""
Save configurations to path
""" |
with open(path, 'w') as f:
self.savetofile(f, sortkey) |
<SYSTEM_TASK:>
Return the parent from which this class inherits configurations
<END_TASK>
<USER_TASK:>
Description:
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 None |
<SYSTEM_TASK:>
Return the mapped configuration root node
<END_TASK>
<USER_TASK:>
Description:
def getConfigRoot(cls, create = False):
"""
Return the mapped configuration root node
""" |
try:
return manager.gettree(getattr(cls, 'configkey'), create)
except AttributeError:
return None |
<SYSTEM_TASK:>
Return all mapped configuration keys for this object
<END_TASK>
<USER_TASK:>
Description:
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:
ret = ret.union(set(root.config_value_keys()))
parent = None
for c in cls.__bases__:
if issubclass(c, Configurable):
parent = c
if parent is None:
break
cls = parent
if sortkey:
return sorted(list(ret))
else:
return list(ret) |
<SYSTEM_TASK:>
Wait for a VXLAN group to be created
<END_TASK>
<USER_TASK:>
Description:
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._connection.connected:
raise ConnectionResetException
groupchanged = VXLANGroupChanged.createMatcher(self._connection, networkid, VXLANGroupChanged.UPDATED)
conn_down = self._connection.protocol.statematcher(self._connection)
timeout_, ev, m = await container.wait_with_timeout(timeout, groupchanged, conn_down)
if timeout_:
raise ValueError('VXLAN group is still not created after a long time')
elif m is conn_down:
raise ConnectionResetException
else:
return ev.physicalportid |
<SYSTEM_TASK:>
Read from current buffer. If current buffer is empty, returns an empty string. You can use `prepareRead`
<END_TASK>
<USER_TASK:>
Description:
def readonce(self, size = None):
"""
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.
""" |
if self.eof:
raise EOFError
if self.errored:
raise IOError('Stream is broken before EOF')
if size is not None and size < len(self.data) - self.pos:
ret = self.data[self.pos: self.pos + size]
self.pos += size
return ret
else:
ret = self.data[self.pos:]
self.pos = len(self.data)
if self.dataeof:
self.eof = True
return ret |
<SYSTEM_TASK:>
Coroutine method which reads the next line or until EOF or size exceeds
<END_TASK>
<USER_TASK:>
Description:
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
if self.errored:
raise IOError('Stream is broken before EOF')
while size is None or retsize < size:
if self.pos >= len(self.data):
await self.prepareRead(container)
if size is None or size - retsize >= len(self.data) - self.pos:
t = self.data[self.pos:]
if self.isunicode:
p = t.find(u'\n')
else:
p = t.find(b'\n')
if p >= 0:
t = t[0: p + 1]
ret.append(t)
retsize += len(t)
self.pos += len(t)
break
else:
ret.append(t)
retsize += len(t)
self.pos += len(t)
if self.dataeof:
self.eof = True
break
if self.dataerror:
self.errored = True
break
else:
t = self.data[self.pos:self.pos + (size - retsize)]
if self.isunicode:
p = t.find(u'\n')
else:
p = t.find(b'\n')
if p >= 0:
t = t[0: p + 1]
ret.append(t)
self.pos += len(t)
retsize += len(t)
break
if self.isunicode:
return u''.join(ret)
else:
return b''.join(ret)
if self.errored:
raise IOError('Stream is broken before EOF') |
<SYSTEM_TASK:>
Coroutine method to copy content from this stream to another stream.
<END_TASK>
<USER_TASK:>
Description:
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)
elif self.errored:
await dest.error(container)
else:
try:
while not self.eof:
await self.prepareRead(container)
data = self.readonce()
try:
await dest.write(data, container, self.eof, buffering = buffering)
except IOError:
break
except:
async def _cleanup():
try:
await dest.error(container)
except IOError:
pass
container.subroutine(_cleanup(), False)
raise
finally:
self.close(container.scheduler) |
<SYSTEM_TASK:>
Convert an X509 certificate into a Python dictionary
<END_TASK>
<USER_TASK:>
Description:
def decode_cert(cert):
"""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.
""" |
ret_dict = {}
subject_xname = X509_get_subject_name(cert.value)
ret_dict["subject"] = _create_tuple_for_X509_NAME(subject_xname)
notAfter = X509_get_notAfter(cert.value)
ret_dict["notAfter"] = ASN1_TIME_print(notAfter)
peer_alt_names = _get_peer_alt_names(cert)
if peer_alt_names is not None:
ret_dict["subjectAltName"] = peer_alt_names
return ret_dict |
<SYSTEM_TASK:>
Retrieve a server certificate
<END_TASK>
<USER_TASK:>
Description:
def _get_server_certificate(addr, ssl_version=PROTOCOL_SSLv23, ca_certs=None):
"""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.
""" |
if ssl_version not in (PROTOCOL_DTLS, PROTOCOL_DTLSv1, PROTOCOL_DTLSv1_2):
return _orig_get_server_certificate(addr, ssl_version, ca_certs)
if ca_certs is not None:
cert_reqs = ssl.CERT_REQUIRED
else:
cert_reqs = ssl.CERT_NONE
af = getaddrinfo(addr[0], addr[1])[0][0]
s = ssl.wrap_socket(socket(af, SOCK_DGRAM),
ssl_version=ssl_version,
cert_reqs=cert_reqs, ca_certs=ca_certs)
s.connect(addr)
dercert = s.getpeercert(True)
s.close()
return ssl.DER_cert_to_PEM_cert(dercert) |
<SYSTEM_TASK:>
Retrieve a socket used by this connection
<END_TASK>
<USER_TASK:>
Description:
def get_socket(self, inbound):
"""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 client-side connection, and on whether a routing demux is in use.
""" |
if inbound and hasattr(self, "_rsock"):
return self._rsock
return self._sock |
<SYSTEM_TASK:>
Server-side cookie exchange
<END_TASK>
<USER_TASK:>
Description:
def listen(self):
"""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 denial-of-
service attacks, only a small, constant set of computing resources
are used during the listen phase.
On some platforms, listen must be called so that packets will be
forwarded to accepted connections. Doing so is therefore recommened
in all cases for portable code.
Return value: a peer address if a datagram from a new peer was
encountered, None if a datagram for a known peer was forwarded
""" |
if not hasattr(self, "_listening"):
raise InvalidSocketError("listen called on non-listening socket")
self._pending_peer_address = None
try:
peer_address = self._udp_demux.service()
except socket.timeout:
peer_address = None
except socket.error as sock_err:
if sock_err.errno != errno.EWOULDBLOCK:
_logger.exception("Unexpected socket error in listen")
raise
peer_address = None
if not peer_address:
_logger.debug("Listen returning without peer")
return
# The demux advises that a datagram from a new peer may have arrived
if type(peer_address) is tuple:
# For this type of demux, the write BIO must be pointed at the peer
BIO_dgram_set_peer(self._wbio.value, peer_address)
self._udp_demux.forward()
self._listening_peer_address = peer_address
self._check_nbio()
self._listening = True
try:
_logger.debug("Invoking DTLSv1_listen for ssl: %d",
self._ssl.raw)
dtls_peer_address = DTLSv1_listen(self._ssl.value)
except openssl_error() as err:
if err.ssl_error == SSL_ERROR_WANT_READ:
# This method must be called again to forward the next datagram
_logger.debug("DTLSv1_listen must be resumed")
return
elif err.errqueue and err.errqueue[0][0] == ERR_WRONG_VERSION_NUMBER:
_logger.debug("Wrong version number; aborting handshake")
raise
elif err.errqueue and err.errqueue[0][0] == ERR_COOKIE_MISMATCH:
_logger.debug("Mismatching cookie received; aborting handshake")
raise
elif err.errqueue and err.errqueue[0][0] == ERR_NO_SHARED_CIPHER:
_logger.debug("No shared cipher; aborting handshake")
raise
_logger.exception("Unexpected error in DTLSv1_listen")
raise
finally:
self._listening = False
self._listening_peer_address = None
if type(peer_address) is tuple:
_logger.debug("New local peer: %s", dtls_peer_address)
self._pending_peer_address = peer_address
else:
self._pending_peer_address = dtls_peer_address
_logger.debug("New peer: %s", self._pending_peer_address)
return self._pending_peer_address |
<SYSTEM_TASK:>
Server-side UDP connection establishment
<END_TASK>
<USER_TASK:>
Description:
def accept(self):
"""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 connected to a new peer, None if packet
forwarding only to an existing peer occurred.
""" |
if not self._pending_peer_address:
if not self.listen():
_logger.debug("Accept returning without connection")
return
new_conn = SSLConnection(self, self._keyfile, self._certfile, True,
self._cert_reqs, self._ssl_version,
self._ca_certs, self._do_handshake_on_connect,
self._suppress_ragged_eofs, self._ciphers,
cb_user_config_ssl_ctx=self._user_config_ssl_ctx,
cb_user_config_ssl=self._user_config_ssl)
new_peer = self._pending_peer_address
self._pending_peer_address = None
if self._do_handshake_on_connect:
# Note that since that connection's socket was just created in its
# constructor, the following operation must be blocking; hence
# handshake-on-connect can only be used with a routing demux if
# listen is serviced by a separate application thread, or else we
# will hang in this call
new_conn.do_handshake()
_logger.debug("Accept returning new connection for new peer")
return new_conn, new_peer |
<SYSTEM_TASK:>
Client-side UDP connection establishment
<END_TASK>
<USER_TASK:>
Description:
def connect(self, peer_address):
"""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
""" |
self._sock.connect(peer_address)
peer_address = self._sock.getpeername() # substituted host addrinfo
BIO_dgram_set_connected(self._wbio.value, peer_address)
assert self._wbio is self._rbio
if self._do_handshake_on_connect:
self.do_handshake() |
<SYSTEM_TASK:>
Perform a handshake with the peer
<END_TASK>
<USER_TASK:>
Description:
def do_handshake(self):
"""Perform a handshake with the peer
This method forces an explicit handshake to be performed with either
the client or server peer.
""" |
_logger.debug("Initiating handshake...")
try:
self._wrap_socket_library_call(
lambda: SSL_do_handshake(self._ssl.value),
ERR_HANDSHAKE_TIMEOUT)
except openssl_error() as err:
if err.ssl_error == SSL_ERROR_SYSCALL and err.result == -1:
raise_ssl_error(ERR_PORT_UNREACHABLE, err)
raise
self._handshake_done = True
_logger.debug("...completed handshake") |
<SYSTEM_TASK:>
Read data from connection
<END_TASK>
<USER_TASK:>
Description:
def read(self, len=1024, buffer=None):
"""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
""" |
try:
return self._wrap_socket_library_call(
lambda: SSL_read(self._ssl.value, len, buffer), ERR_READ_TIMEOUT)
except openssl_error() as err:
if err.ssl_error == SSL_ERROR_SYSCALL and err.result == -1:
raise_ssl_error(ERR_PORT_UNREACHABLE, err)
raise |
<SYSTEM_TASK:>
Write data to connection
<END_TASK>
<USER_TASK:>
Description:
def write(self, data):
"""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
""" |
try:
ret = self._wrap_socket_library_call(
lambda: SSL_write(self._ssl.value, data), ERR_WRITE_TIMEOUT)
except openssl_error() as err:
if err.ssl_error == SSL_ERROR_SYSCALL and err.result == -1:
raise_ssl_error(ERR_PORT_UNREACHABLE, err)
raise
if ret:
self._handshake_done = True
return ret |
<SYSTEM_TASK:>
Shut down the DTLS connection
<END_TASK>
<USER_TASK:>
Description:
def shutdown(self):
"""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.
""" |
if hasattr(self, "_listening"):
# Listening server-side sockets cannot be shut down
return
try:
self._wrap_socket_library_call(
lambda: SSL_shutdown(self._ssl.value), ERR_READ_TIMEOUT)
except openssl_error() as err:
if err.result == 0:
# close-notify alert was just sent; wait for same from peer
# Note: while it might seem wise to suppress further read-aheads
# with SSL_set_read_ahead here, doing so causes a shutdown
# failure (ret: -1, SSL_ERROR_SYSCALL) on the DTLS shutdown
# initiator side. And test_starttls does pass.
self._wrap_socket_library_call(
lambda: SSL_shutdown(self._ssl.value), ERR_READ_TIMEOUT)
else:
raise
if hasattr(self, "_rsock"):
# Return wrapped connected server socket (non-listening)
return _UnwrappedSocket(self._sock, self._rsock, self._udp_demux,
self._ctx,
BIO_dgram_get_peer(self._wbio.value))
# Return unwrapped client-side socket or unwrapped server-side socket
# for single-socket servers
return self._sock |
<SYSTEM_TASK:>
Retrieve the peer's certificate
<END_TASK>
<USER_TASK:>
Description:
def getpeercert(self, binary_form=False):
"""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 certificate
was not validated, an empty dictionary is returned.
In all cases, None is returned if no certificate was received from the
peer.
""" |
try:
peer_cert = _X509(SSL_get_peer_certificate(self._ssl.value))
except openssl_error():
return
if binary_form:
return i2d_X509(peer_cert.value)
if self._cert_reqs == CERT_NONE:
return {}
return decode_cert(peer_cert) |
<SYSTEM_TASK:>
Retrieve information about the current cipher
<END_TASK>
<USER_TASK:>
Description:
def cipher(self):
"""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.
""" |
if not self._handshake_done:
return
current_cipher = SSL_get_current_cipher(self._ssl.value)
cipher_name = SSL_CIPHER_get_name(current_cipher)
cipher_version = SSL_CIPHER_get_version(current_cipher)
cipher_bits = SSL_CIPHER_get_bits(current_cipher)
return cipher_name, cipher_version, cipher_bits |
<SYSTEM_TASK:>
Support for running straight out of a cloned source directory instead
<END_TASK>
<USER_TASK:>
Description:
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 shutil import copy
bit_suffix = "-x86_64" if maxsize > 2**32 else "-x86"
package_root = path.abspath(path.dirname(__file__))
prebuilt_path = path.join(package_root, "prebuilt", platform + bit_suffix)
config = {"MANIFEST_DIR": prebuilt_path}
try:
execfile(path.join(prebuilt_path, "manifest.pycfg"), config)
except IOError:
return # there are no prebuilts for this platform - nothing to do
files = map(lambda x: path.join(prebuilt_path, x), config["FILES"])
for prebuilt_file in files:
try:
copy(path.join(prebuilt_path, prebuilt_file), package_root)
except IOError:
pass |
<SYSTEM_TASK:>
Raise an SSL error with the given error code
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Service the root socket
<END_TASK>
<USER_TASK:>
Description:
def service(self):
"""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
* The root socket is non-blocking and has no data available
* An empty payload is received
* A non-empty payload is received from an unknown peer (a peer
for which get_connection has not yet been called); in this case,
the payload is held by this instance and will be forwarded when
the forward method is called
Return:
if the datagram received was from a new peer, then the peer's
address; otherwise None
""" |
self.payload, self.payload_peer_address = \
self.datagram_socket.recvfrom(UDP_MAX_DGRAM_LENGTH)
_logger.debug("Received datagram from peer: %s",
self.payload_peer_address)
if not self.payload:
self.payload_peer_address = None
return
if self.connections.has_key(self.payload_peer_address):
self.forward()
else:
return self.payload_peer_address |
<SYSTEM_TASK:>
Forward a stored datagram
<END_TASK>
<USER_TASK:>
Description:
def forward(self):
"""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 been called
since the service method returned the new peer's address, and the
connection associated with the new peer's address if it has.
""" |
assert self.payload
assert self.payload_peer_address
if self.connections.has_key(self.payload_peer_address):
conn = self.connections[self.payload_peer_address]
default = False
else:
conn = self.connections[None] # propagate exception if not created
default = True
_logger.debug("Forwarding datagram from peer: %s, default: %s",
self.payload_peer_address, default)
self._forwarding_socket.sendto(self.payload, conn.getsockname())
self.payload = ""
self.payload_peer_address = None |
<SYSTEM_TASK:>
Here we obtain the price for the quote and make sure it has
<END_TASK>
<USER_TASK:>
Description:
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":
assert self.market == self.market.core_quote_market(), "Wrong market for 'feed' reference!"
ticker = self.market.ticker()
price = ticker.get("quoteSettlement_price")
assert abs(price["price"]) != float("inf"), "Check price feed of asset! (%s)" % str(price)
return price |
<SYSTEM_TASK:>
ticks come in on every block
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Return the bot's open accounts in the current market
<END_TASK>
<USER_TASK:>
Description:
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] |
<SYSTEM_TASK:>
This method distringuishes notifications caused by Matched orders
<END_TASK>
<USER_TASK:>
Description:
def _callbackPlaceFillOrders(self, d):
""" This method distringuishes notifications caused by Matched orders
from those caused by placed orders
""" |
if isinstance(d, FilledOrder):
self.onOrderMatched(d)
elif isinstance(d, Order):
self.onOrderPlaced(d)
elif isinstance(d, UpdateCallOrder):
self.onUpdateCallOrder(d)
else:
pass |
<SYSTEM_TASK:>
Execute a bundle of operations
<END_TASK>
<USER_TASK:>
Description:
def execute(self):
""" Execute a bundle of operations
""" |
self.bitshares.blocking = "head"
r = self.bitshares.txbuffer.broadcast()
self.bitshares.blocking = False
return r |
<SYSTEM_TASK:>
Cancel all orders of this bot
<END_TASK>
<USER_TASK:>
Description:
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
) |
<SYSTEM_TASK:>
Start the background process.
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Register an EventualResult.
<END_TASK>
<USER_TASK:>
Description:
def register(self, result):
"""
Register an EventualResult.
May be called in any thread.
""" |
if self._stopped:
raise ReactorStopped()
self._results.add(result) |
<SYSTEM_TASK:>
Indicate no more results will get pushed into EventualResults, since
<END_TASK>
<USER_TASK:>
Description:
def stop(self):
"""
Indicate no more results will get pushed into EventualResults, since
the reactor has stopped.
This should be called in the reactor thread.
""" |
self._stopped = True
for result in self._results:
result._set_result(Failure(ReactorStopped())) |
<SYSTEM_TASK:>
Hook up the Deferred that that this will be the result of.
<END_TASK>
<USER_TASK:>
Description:
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.
""" |
self._deferred = deferred
# Because we use __del__, we need to make sure there are no cycles
# involving this object, which is why we use a weakref:
def put(result, eventual=weakref.ref(self)):
eventual = eventual()
if eventual:
eventual._set_result(result)
else:
err(result, "Unhandled error in EventualResult")
deferred.addBoth(put) |
<SYSTEM_TASK:>
Set the result of the EventualResult, if not already set.
<END_TASK>
<USER_TASK:>
Description:
def _set_result(self, result):
"""
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.
""" |
if self._result_set.isSet():
return
self._value = result
self._result_set.set() |
<SYSTEM_TASK:>
Return the result, if available.
<END_TASK>
<USER_TASK:>
Description:
def _result(self, timeout=None):
"""
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
still wait for a result and return it if available. If a result was
returned on one call, additional calls will return/raise the same
result.
""" |
if timeout is None:
warnings.warn(
"Unlimited timeouts are deprecated.",
DeprecationWarning,
stacklevel=3)
# Queue.get(None) won't get interrupted by Ctrl-C...
timeout = 2**31
self._result_set.wait(timeout)
# In Python 2.6 we can't rely on the return result of wait(), so we
# have to check manually:
if not self._result_set.is_set():
raise TimeoutError()
self._result_retrieved = True
return self._value |
<SYSTEM_TASK:>
Return the result, or throw the exception if result is a failure.
<END_TASK>
<USER_TASK:>
Description:
def wait(self, timeout=None):
"""
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 calls to this function will
still wait for a result and return it if available. If a result was
returned or raised on one call, additional calls will return/raise the
same result.
""" |
if threadable.isInIOThread():
raise RuntimeError(
"EventualResult.wait() must not be run in the reactor thread.")
if imp.lock_held():
try:
imp.release_lock()
except RuntimeError:
# The lock is held by some other thread. We should be safe
# to continue.
pass
else:
# If EventualResult.wait() is run during module import, if the
# Twisted code that is being run also imports something the
# result will be a deadlock. Even if that is not an issue it
# would prevent importing in other threads until the call
# returns.
raise RuntimeError(
"EventualResult.wait() must not be run at module "
"import time.")
result = self._result(timeout)
if isinstance(result, Failure):
result.raiseException()
return result |
<SYSTEM_TASK:>
Return the underlying Failure object, if the result is an error.
<END_TASK>
<USER_TASK:>
Description:
def original_failure(self):
"""
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.
""" |
try:
result = self._result(0.0)
except TimeoutError:
return None
if isinstance(result, Failure):
return result
else:
return None |
<SYSTEM_TASK:>
Initialize the crochet library.
<END_TASK>
<USER_TASK:>
Description:
def setup(self):
"""
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.
""" |
if self._started:
return
self._common_setup()
if platform.type == "posix":
self._reactor.callFromThread(self._startReapingProcesses)
if self._startLoggingWithObserver:
observer = ThreadLogObserver(PythonLoggingObserver().emit)
def start():
# Twisted is going to override warnings.showwarning; let's
# make sure that has no effect:
from twisted.python import log
original = log.showwarning
log.showwarning = warnings.showwarning
self._startLoggingWithObserver(observer, False)
log.showwarning = original
self._reactor.callFromThread(start)
# We only want to stop the logging thread once the reactor has
# shut down:
self._reactor.addSystemEventTrigger(
"after", "shutdown", observer.stop)
t = threading.Thread(
target=lambda: self._reactor.run(installSignalHandlers=False),
name="CrochetReactor")
t.start()
self._atexit_register(self._reactor.callFromThread, self._reactor.stop)
self._atexit_register(_store.log_errors)
if self._watchdog_thread is not None:
self._watchdog_thread.start() |
<SYSTEM_TASK:>
A decorator that ensures the wrapped function runs in the
<END_TASK>
<USER_TASK:>
Description:
def run_in_reactor(self, function):
"""
A decorator that ensures the wrapped function runs in the
reactor thread.
When the wrapped function is called, an EventualResult is returned.
""" |
result = self._run_in_reactor(function)
# Backwards compatibility; use __wrapped__ instead.
try:
result.wrapped_function = function
except AttributeError:
pass
return result |
<SYSTEM_TASK:>
A decorator factory that ensures the wrapped function runs in the
<END_TASK>
<USER_TASK:>
Description:
def wait_for(self, timeout):
"""
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
crochet.TimeoutError, and cancelling the Deferred being waited on.
""" |
def decorator(function):
@wrapt.decorator
def wrapper(function, _, args, kwargs):
@self.run_in_reactor
def run():
return function(*args, **kwargs)
eventual_result = run()
try:
return eventual_result.wait(timeout)
except TimeoutError:
eventual_result.cancel()
raise
result = wrapper(function)
# Expose underling function for testing purposes; this attribute is
# deprecated, use __wrapped__ instead:
try:
result.wrapped_function = function
except AttributeError:
pass
return result
return decorator |
<SYSTEM_TASK:>
DEPRECATED, use run_in_reactor.
<END_TASK>
<USER_TASK:>
Description:
def in_reactor(self, function):
"""
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 EventualResult is returned.
""" |
warnings.warn(
"@in_reactor is deprecated, use @run_in_reactor",
DeprecationWarning,
stacklevel=2)
@self.run_in_reactor
@wraps(function)
def add_reactor(*args, **kwargs):
return function(self._reactor, *args, **kwargs)
return add_reactor |
<SYSTEM_TASK:>
Store a EventualResult.
<END_TASK>
<USER_TASK:>
Description:
def store(self, deferred_result):
"""
Store a EventualResult.
Return an integer, a unique identifier that can be used to retrieve
the object.
""" |
self._counter += 1
self._stored[self._counter] = deferred_result
return self._counter |
<SYSTEM_TASK:>
Log errors for all stored EventualResults that have error results.
<END_TASK>
<USER_TASK:>
Description:
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:
log.err(failure, "Unhandled error in stashed EventualResult:") |
<SYSTEM_TASK:>
Start an SSH server on the given port, exposing a Python prompt with the
<END_TASK>
<USER_TASK:>
Description:
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/6429 for a ticket to
# provide a utility function that simplifies this.
from twisted.internet import reactor
from twisted.conch.insults import insults
from twisted.conch import manhole, manhole_ssh
from twisted.cred.checkers import (
InMemoryUsernamePasswordDatabaseDontUse as MemoryDB)
from twisted.cred.portal import Portal
sshRealm = manhole_ssh.TerminalRealm()
def chainedProtocolFactory():
return insults.ServerProtocol(manhole.Manhole, namespace)
sshRealm.chainedProtocolFactory = chainedProtocolFactory
sshPortal = Portal(sshRealm, [MemoryDB(**{username: password})])
reactor.listenTCP(port, manhole_ssh.ConchFactory(sshPortal),
interface="127.0.0.1") |
<SYSTEM_TASK:>
Underlying synchronized wrapper.
<END_TASK>
<USER_TASK:>
Description:
def _synced(method, self, args, kwargs):
"""Underlying synchronized wrapper.""" |
with self._lock:
return method(*args, **kwargs) |
<SYSTEM_TASK:>
Register a function and arguments to be called later.
<END_TASK>
<USER_TASK:>
Description:
def register(self, f, *args, **kwargs):
"""
Register a function and arguments to be called later.
""" |
self._functions.append(lambda: f(*args, **kwargs)) |
<SYSTEM_TASK:>
Register function to be called from EPC client.
<END_TASK>
<USER_TASK:>
Description:
def register_function(self, function, name=None):
"""
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 decorator.
""" |
if name is None:
name = function.__name__
self.funcs[name] = function
return function |
<SYSTEM_TASK:>
Get registered method callend `name`.
<END_TASK>
<USER_TASK:>
Description:
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:
return SimpleXMLRPCServer.resolve_dotted_attribute(
self.instance, name, self.allow_dotted_names) |
<SYSTEM_TASK:>
Set debugger to run when an error occurs in published method.
<END_TASK>
<USER_TASK:>
Description:
def set_debugger(self, debugger):
"""
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.
""" |
if debugger == 'pdb':
import pdb
self.debugger = pdb
elif debugger == 'ipdb':
import ipdb
self.debugger = ipdb
else:
self.debugger = debugger |
<SYSTEM_TASK:>
Connect to server and start serving registered functions.
<END_TASK>
<USER_TASK:>
Description:
def connect(self, socket_or_address):
"""
Connect to server and start serving registered functions.
:type socket_or_address: tuple or socket object
:arg socket_or_address: A ``(host, port)`` pair to be passed
to `socket.create_connection`, or
a socket object.
""" |
if isinstance(socket_or_address, tuple):
import socket
self.socket = socket.create_connection(socket_or_address)
else:
self.socket = socket_or_address
# This is what BaseServer.finish_request does:
address = None # it is not used, so leave it empty
self.handler = EPCClientHandler(self.socket, address, self)
self.call = self.handler.call
self.call_sync = self.handler.call_sync
self.methods = self.handler.methods
self.methods_sync = self.handler.methods_sync
self.handler_thread = newthread(self, target=self.handler.start)
self.handler_thread.daemon = self.thread_daemon
self.handler_thread.start()
self.handler.wait_until_ready() |
<SYSTEM_TASK:>
Quick CLI to serve Python functions in a module.
<END_TASK>
<USER_TASK:>
Description:
def main(args=None):
"""
Quick CLI to serve Python functions in a module.
Example usage::
python -m epc.server --allow-dotted-names os
Note that only the functions which gets and returns simple
built-in types (str, int, float, list, tuple, dict) works.
""" |
import argparse
from textwrap import dedent
parser = argparse.ArgumentParser(
formatter_class=type('EPCHelpFormatter',
(argparse.ArgumentDefaultsHelpFormatter,
argparse.RawDescriptionHelpFormatter),
{}),
description=dedent(main.__doc__))
parser.add_argument(
'module', help='Serve python functions in this module.')
parser.add_argument(
'--address', default='localhost',
help='server address')
parser.add_argument(
'--port', default=0, type=int,
help='server port. 0 means to pick up random port.')
parser.add_argument(
'--allow-dotted-names', default=False, action='store_true')
parser.add_argument(
'--pdb', dest='debugger', const='pdb', action='store_const',
help='start pdb when error occurs.')
parser.add_argument(
'--ipdb', dest='debugger', const='ipdb', action='store_const',
help='start ipdb when error occurs.')
parser.add_argument(
'--log-traceback', action='store_true', default=False)
ns = parser.parse_args(args)
server = EPCServer((ns.address, ns.port),
debugger=ns.debugger,
log_traceback=ns.log_traceback)
server.register_instance(
__import__(ns.module),
allow_dotted_names=ns.allow_dotted_names)
server.print_port()
server.serve_forever() |
<SYSTEM_TASK:>
Print port this EPC server runs on.
<END_TASK>
<USER_TASK:>
Description:
def print_port(self, stream=sys.stdout):
"""
Print port this EPC server runs on.
As Emacs client reads port number from STDOUT, you need to
call this just before calling :meth:`serve_forever`.
:type stream: text stream
:arg stream: A stream object to write port on.
Default is :data:`sys.stdout`.
""" |
stream.write(str(self.server_address[1]))
stream.write("\n")
stream.flush() |
<SYSTEM_TASK:>
Call method connected to this handler.
<END_TASK>
<USER_TASK:>
Description:
def call(self, name, *args, **kwds):
"""
Call method connected to this handler.
:type name: str
:arg name: Method name to call.
:type args: list
:arg args: Arguments for remote method to call.
:type callback: callable
:arg callback: A function to be called with returned value of
the remote method.
:type errback: callable
:arg errback: A function to be called with an error occurred
in the remote method. It is either an instance
of :class:`ReturnError` or :class:`EPCError`.
""" |
self.callmanager.call(self, name, *args, **kwds) |
<SYSTEM_TASK:>
Request info of callable remote methods.
<END_TASK>
<USER_TASK:>
Description:
def methods(self, *args, **kwds):
"""
Request info of callable remote methods.
Arguments for :meth:`call` except for `name` can be applied to
this function too.
""" |
self.callmanager.methods(self, *args, **kwds) |
<SYSTEM_TASK:>
Return arguments and keyword arguments as formatted string
<END_TASK>
<USER_TASK:>
Description:
def func_call_as_str(name, *args, **kwds):
"""
Return arguments and keyword arguments as formatted string
>>> func_call_as_str('f', 1, 2, a=1)
'f(1, 2, a=1)'
""" |
return '{0}({1})'.format(
name,
', '.join(itertools.chain(
map('{0!r}'.format, args),
map('{0[0]!s}={0[1]!r}'.format, sorted(kwds.items()))))) |
<SYSTEM_TASK:>
A decorator to wrap execution of function with a context manager.
<END_TASK>
<USER_TASK:>
Description:
def callwith(context_manager):
"""
A decorator to wrap execution of function with a context manager.
""" |
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwds):
with context_manager:
return func(*args, **kwds)
return wrapper
return decorator |
<SYSTEM_TASK:>
Given a boolean potential cloud layer,
<END_TASK>
<USER_TASK:>
Description:
def gdal_nodata_mask(pcl, pcsl, tirs_arr):
"""
Given a boolean potential cloud layer,
a potential cloud shadow layer and a thermal band
Calculate the GDAL-style uint8 mask
""" |
tirs_mask = np.isnan(tirs_arr) | (tirs_arr == 0)
return ((~(pcl | pcsl | tirs_mask)) * 255).astype('uint8') |
<SYSTEM_TASK:>
Executes processing steps when reading a line
<END_TASK>
<USER_TASK:>
Description:
def _transstat(status, grouppath, dictpath, line):
"""Executes processing steps when reading a line""" |
if status == 0:
raise MTLParseError(
"Status should not be '%s' after reading line:\n%s"
% (STATUSCODE[status], line))
elif status == 1:
currentdict = dictpath[-1]
currentgroup = _getgroupname(line)
grouppath.append(currentgroup)
currentdict[currentgroup] = {}
dictpath.append(currentdict[currentgroup])
elif status == 2:
currentdict = dictpath[-1]
newkey, newval = _getmetadataitem(line)
# USGS has started quoting the scene center time. If this
# happens strip quotes before post processing.
if newkey == 'SCENE_CENTER_TIME' and newval.startswith('"') \
and newval.endswith('"'):
# logging.warning('Strip quotes off SCENE_CENTER_TIME.')
newval = newval[1:-1]
currentdict[newkey] = _postprocess(newval)
elif status == 3:
oldgroup = _getendgroupname(line)
if oldgroup != grouppath[-1]:
raise MTLParseError(
"Reached line '%s' while reading group '%s'."
% (line.strip(), grouppath[-1]))
del grouppath[-1]
del dictpath[-1]
try:
currentgroup = grouppath[-1]
except IndexError:
currentgroup = None
elif status == 4:
if grouppath:
raise MTLParseError(
"Reached end before end of group '%s'" % grouppath[-1])
return grouppath, dictpath |
<SYSTEM_TASK:>
Takes value as str, returns str, int, float, date, datetime, or time
<END_TASK>
<USER_TASK:>
Description:
def _postprocess(valuestr):
"""
Takes value as str, returns str, int, float, date, datetime, or time
""" |
# USGS has started quoting time sometimes. Grr, strip quotes in this case
intpattern = re.compile(r'^\-?\d+$')
floatpattern = re.compile(r'^\-?\d+\.\d+(E[+-]?\d\d+)?$')
datedtpattern = '%Y-%m-%d'
datedttimepattern = '%Y-%m-%dT%H:%M:%SZ'
timedtpattern = '%H:%M:%S.%f'
timepattern = re.compile(r'^\d{2}:\d{2}:\d{2}(\.\d{6})?')
if valuestr.startswith('"') and valuestr.endswith('"'):
# it's a string
return valuestr[1:-1]
elif re.match(intpattern, valuestr):
# it's an integer
return int(valuestr)
elif re.match(floatpattern, valuestr):
# floating point number
return float(valuestr)
# now let's try the datetime objects; throws exception if it doesn't match
try:
return datetime.datetime.strptime(valuestr, datedtpattern).date()
except ValueError:
pass
try:
return datetime.datetime.strptime(valuestr, datedttimepattern)
except ValueError:
pass
# time parsing is complicated: Python's datetime module only accepts
# fractions of a second only up to 6 digits
mat = re.match(timepattern, valuestr)
if mat:
test = mat.group(0)
try:
return datetime.datetime.strptime(test, timedtpattern).time()
except ValueError:
pass
# If we get here, we still haven't returned anything.
logging.info(
"The value %s couldn't be parsed as " % valuestr
+ "int, float, date, time, datetime. Returning it as string.")
return valuestr |
<SYSTEM_TASK:>
Return a python executable for the given python base name.
<END_TASK>
<USER_TASK:>
Description:
def tox_get_python_executable(envconfig):
"""Return a python executable for the given python base name.
The first plugin/hook which returns an executable path will determine it.
``envconfig`` is the testenv configuration which contains
per-testenv configuration, notably the ``.envname`` and ``.basepython``
setting.
""" |
try:
# pylint: disable=no-member
pyenv = (getattr(py.path.local.sysfind('pyenv'), 'strpath', 'pyenv')
or 'pyenv')
cmd = [pyenv, 'which', envconfig.basepython]
pipe = subprocess.Popen(
cmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
universal_newlines=True
)
out, err = pipe.communicate()
except OSError:
err = '\'pyenv\': command not found'
LOG.warning(
"pyenv doesn't seem to be installed, you probably "
"don't want this plugin installed either."
)
else:
if pipe.poll() == 0:
return out.strip()
else:
if not envconfig.tox_pyenv_fallback:
raise PyenvWhichFailed(err)
LOG.debug("`%s` failed thru tox-pyenv plugin, falling back. "
"STDERR: \"%s\" | To disable this behavior, set "
"tox_pyenv_fallback=False in your tox.ini or use "
" --tox-pyenv-no-fallback on the command line.",
' '.join([str(x) for x in cmd]), err) |
<SYSTEM_TASK:>
_doPrep is makes changes in-place.
<END_TASK>
<USER_TASK:>
Description:
def _doPrep(field_dict):
"""
_doPrep is makes changes in-place.
Do some prep work converting python types into formats that
Salesforce will accept.
This includes converting lists of strings to "apple;orange;pear".
Dicts will be converted to embedded objects
None or empty list values will be Null-ed
""" |
fieldsToNull = []
for key, value in field_dict.items():
if value is None:
fieldsToNull.append(key)
field_dict[key] = []
if hasattr(value, '__iter__'):
if len(value) == 0:
fieldsToNull.append(key)
elif isinstance(value, dict):
innerCopy = copy.deepcopy(value)
_doPrep(innerCopy)
field_dict[key] = innerCopy
else:
field_dict[key] = ";".join(value)
if 'fieldsToNull' in field_dict:
raise ValueError(
"fieldsToNull should be populated by the client, not the caller."
)
field_dict['fieldsToNull'] = fieldsToNull |
<SYSTEM_TASK:>
Given a list of types, construct a dictionary such that
<END_TASK>
<USER_TASK:>
Description:
def queryTypesDescriptions(self, types):
"""
Given a list of types, construct a dictionary such that
each key is a type, and each value is the corresponding sObject
for that type.
""" |
types = list(types)
if types:
types_descs = self.describeSObjects(types)
else:
types_descs = []
return dict(map(lambda t, d: (t, d), types, types_descs)) |
<SYSTEM_TASK:>
Create a session protection token for this client.
<END_TASK>
<USER_TASK:>
Description:
def create_token(self):
"""Create a session protection token for this client.
This method generates a session protection token for the cilent, which
consists in a hash of the user agent and the IP address. This method
can be overriden by subclasses to implement different token generation
algorithms.
""" |
user_agent = request.headers.get('User-Agent')
if user_agent is None: # pragma: no cover
user_agent = 'no user agent'
user_agent = user_agent.encode('utf-8')
base = self._get_remote_addr() + b'|' + user_agent
h = sha256()
h.update(base)
return h.hexdigest() |
<SYSTEM_TASK:>
Clear the session.
<END_TASK>
<USER_TASK:>
Description:
def clear_session(self, response):
"""Clear the session.
This method is invoked when the session is found to be invalid.
Subclasses can override this method to implement a custom session
reset.
""" |
session.clear()
# if flask-login is installed, we try to clear the
# "remember me" cookie, just in case it is set
if 'flask_login' in sys.modules:
remember_cookie = current_app.config.get('REMEMBER_COOKIE',
'remember_token')
response.set_cookie(remember_cookie, '', expires=0, max_age=0) |
<SYSTEM_TASK:>
Generate heroku-like random names to use in your python applications
<END_TASK>
<USER_TASK:>
Description:
def haikunate(self, delimiter='-', token_length=4, token_hex=False, token_chars='0123456789'):
"""
Generate heroku-like random names to use in your python applications
:param delimiter: Delimiter
:param token_length: TokenLength
:param token_hex: TokenHex
:param token_chars: TokenChars
:type delimiter: str
:type token_length: int
:type token_hex: bool
:type token_chars: str
:return: heroku-like random string
:rtype: str
""" |
if token_hex:
token_chars = '0123456789abcdef'
adjective = self._random_element(self._adjectives)
noun = self._random_element(self._nouns)
token = ''.join(self._random_element(token_chars) for _ in range(token_length))
sections = [adjective, noun, token]
return delimiter.join(filter(None, sections)) |
<SYSTEM_TASK:>
Returns the parser according to the system platform
<END_TASK>
<USER_TASK:>
Description:
def get_parser_class():
"""
Returns the parser according to the system platform
""" |
global distro
if distro == 'Linux':
Parser = parser.LinuxParser
if not os.path.exists(Parser.get_command()[0]):
Parser = parser.UnixIPParser
elif distro in ['Darwin', 'MacOSX']:
Parser = parser.MacOSXParser
elif distro == 'Windows':
# For some strange reason, Windows will always be win32, see:
# https://stackoverflow.com/a/2145582/405682
Parser = parser.WindowsParser
else:
Parser = parser.NullParser
Log.error("Unknown distro type '%s'." % distro)
Log.debug("Distro detected as '%s'" % distro)
Log.debug("Using '%s'" % Parser)
return Parser |
<SYSTEM_TASK:>
Return just the default interface device dictionary.
<END_TASK>
<USER_TASK:>
Description:
def default_interface(ifconfig=None, route_output=None):
"""
Return just the default interface device dictionary.
:param ifconfig: For mocking actual command output
:param route_output: For mocking actual command output
""" |
global Parser
return Parser(ifconfig=ifconfig)._default_interface(route_output=route_output) |
<SYSTEM_TASK:>
Parse ifconfig output into self._interfaces.
<END_TASK>
<USER_TASK:>
Description:
def parse(self, ifconfig=None): # noqa: max-complexity=12
"""
Parse ifconfig output into self._interfaces.
Optional Arguments:
ifconfig
The data (stdout) from the ifconfig command. Default is to
call exec_cmd(self.get_command()).
""" |
if not ifconfig:
ifconfig, __, __ = exec_cmd(self.get_command())
self.ifconfig_data = ifconfig
cur = None
patterns = self.get_patterns()
for line in self.ifconfig_data.splitlines():
for pattern in patterns:
m = re.match(pattern, line)
if not m:
continue
groupdict = m.groupdict()
# Special treatment to trigger which interface we're
# setting for if 'device' is in the line. Presumably the
# device of the interface is within the first line of the
# device block.
if 'device' in groupdict:
cur = groupdict['device']
self.add_device(cur)
elif cur is None:
raise RuntimeError(
"Got results that don't belong to a device"
)
for k, v in groupdict.items():
if k in self._interfaces[cur]:
if self._interfaces[cur][k] is None:
self._interfaces[cur][k] = v
elif hasattr(self._interfaces[cur][k], 'append'):
self._interfaces[cur][k].append(v)
elif self._interfaces[cur][k] == v:
# Silently ignore if the it's the same value as last. Example: Multiple
# inet4 addresses, result in multiple netmasks. Cardinality mismatch
continue
else:
raise RuntimeError(
"Tried to add {}={} multiple times to {}, it was already: {}".format(
k,
v,
cur,
self._interfaces[cur][k]
)
)
else:
self._interfaces[cur][k] = v
# Copy the first 'inet4' ip address to 'inet' for backwards compatibility
for device, device_dict in self._interfaces.items():
if len(device_dict['inet4']) > 0:
device_dict['inet'] = device_dict['inet4'][0]
# fix it up
self._interfaces = self.alter(self._interfaces) |
<SYSTEM_TASK:>
Return the needle positions or None.
<END_TASK>
<USER_TASK:>
Description:
def get(self, line_number):
"""Return the needle positions or None.
:param int line_number: the number of the line
:rtype: list
:return: the needle positions for a specific line specified by
:paramref:`line_number` or :obj:`None` if no were given
""" |
if line_number not in self._get_cache:
self._get_cache[line_number] = self._get(line_number)
return self._get_cache[line_number] |
<SYSTEM_TASK:>
Get the bytes representing needle positions or None.
<END_TASK>
<USER_TASK:>
Description:
def get_bytes(self, line_number):
"""Get the bytes representing needle positions or None.
:param int line_number: the line number to take the bytes from
:rtype: bytes
:return: the bytes that represent the message or :obj:`None` if no
data is there for the line.
Depending on the :attr:`machine`, the length and result may vary.
""" |
if line_number not in self._needle_position_bytes_cache:
line = self._get(line_number)
if line is None:
line_bytes = None
else:
line_bytes = self._machine.needle_positions_to_bytes(line)
self._needle_position_bytes_cache[line_number] = line_bytes
return self._needle_position_bytes_cache[line_number] |
<SYSTEM_TASK:>
Return the cnfLine content without id for the line.
<END_TASK>
<USER_TASK:>
Description:
def get_line_configuration_message(self, line_number):
"""Return the cnfLine content without id for the line.
:param int line_number: the number of the line
:rtype: bytes
:return: a cnfLine message without id as defined in :ref:`cnfLine`
""" |
if line_number not in self._line_configuration_message_cache:
line_bytes = self.get_bytes(line_number)
if line_bytes is not None:
line_bytes = bytes([line_number & 255]) + line_bytes
line_bytes += bytes([self.is_last(line_number)])
line_bytes += crc8(line_bytes).digest()
self._line_configuration_message_cache[line_number] = line_bytes
del line_bytes
line = self._line_configuration_message_cache[line_number]
if line is None:
# no need to cache a lot of empty lines
line = (bytes([line_number & 255]) +
b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' +
b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01')
line += crc8(line).digest()
return line |
<SYSTEM_TASK:>
Read the message type from a file.
<END_TASK>
<USER_TASK:>
Description:
def read_message_type(file):
"""Read the message type from a file.""" |
message_byte = file.read(1)
if message_byte == b'':
return ConnectionClosed
message_number = message_byte[0]
return _message_types.get(message_number, UnknownMessage) |
<SYSTEM_TASK:>
Read the line number.
<END_TASK>
<USER_TASK:>
Description:
def _init(self):
"""Read the line number.""" |
self._line_number = next_line(
self._communication.last_requested_line_number,
self._file.read(1)[0]) |
<SYSTEM_TASK:>
Send this message to the controller.
<END_TASK>
<USER_TASK:>
Description:
def send(self):
"""Send this message to the controller.""" |
self._file.write(self.as_bytes())
self._file.write(b'\r\n') |
<SYSTEM_TASK:>
Initialize the StartRequest with start and stop needle.
<END_TASK>
<USER_TASK:>
Description:
def init(self, left_end_needle, right_end_needle):
"""Initialize the StartRequest with start and stop needle.
:raises TypeError: if the arguments are not integers
:raises ValueError: if the values do not match the
:ref:`specification <m4-01>`
""" |
if not isinstance(left_end_needle, int):
raise TypeError(_left_end_needle_error_message(left_end_needle))
if left_end_needle < 0 or left_end_needle > 198:
raise ValueError(_left_end_needle_error_message(left_end_needle))
if not isinstance(right_end_needle, int):
raise TypeError(_right_end_needle_error_message(right_end_needle))
if right_end_needle < 1 or right_end_needle > 199:
raise ValueError(_right_end_needle_error_message(right_end_needle))
self._left_end_needle = left_end_needle
self._right_end_needle = right_end_needle |
<SYSTEM_TASK:>
Return the start and stop needle.
<END_TASK>
<USER_TASK:>
Description:
def content_bytes(self):
"""Return the start and stop needle.""" |
get_message = \
self._communication.needle_positions.get_line_configuration_message
return get_message(self._line_number) |
<SYSTEM_TASK:>
Sum up an iterable starting with a start value.
<END_TASK>
<USER_TASK:>
Description:
def sum_all(iterable, start):
"""Sum up an iterable starting with a start value.
In contrast to :func:`sum`, this also works on other types like
:class:`lists <list>` and :class:`sets <set>`.
""" |
if hasattr(start, "__add__"):
for value in iterable:
start += value
else:
for value in iterable:
start |= value
return start |
<SYSTEM_TASK:>
Compute the next line based on the last line and a 8bit next line.
<END_TASK>
<USER_TASK:>
Description:
def next_line(last_line, next_line_8bit):
"""Compute the next line based on the last line and a 8bit next line.
The behaviour of the function is specified in :ref:`reqline`.
:param int last_line: the last line that was processed
:param int next_line_8bit: the lower 8 bits of the next line
:return: the next line closest to :paramref:`last_line`
.. seealso:: :ref:`reqline`
""" |
# compute the line without the lowest byte
base_line = last_line - (last_line & 255)
# compute the three different lines
line = base_line + next_line_8bit
lower_line = line - 256
upper_line = line + 256
# compute the next line
if last_line - lower_line <= line - last_line:
return lower_line
if upper_line - last_line < last_line - line:
return upper_line
return line |
<SYSTEM_TASK:>
Return the underscore name of a camel case name.
<END_TASK>
<USER_TASK:>
Description:
def camel_case_to_under_score(camel_case_name):
"""Return the underscore name of a camel case name.
:param str camel_case_name: a name in camel case such as
``"ACamelCaseName"``
:return: the name using underscores, e.g. ``"a_camel_case_name"``
:rtype: str
""" |
result = []
for letter in camel_case_name:
if letter.lower() != letter:
result.append("_" + letter.lower())
else:
result.append(letter.lower())
if result[0].startswith("_"):
result[0] = result[0][1:]
return "".join(result) |
<SYSTEM_TASK:>
Notify the observers about the received message.
<END_TASK>
<USER_TASK:>
Description:
def _message_received(self, message):
"""Notify the observers about the received message.""" |
with self.lock:
self._state.receive_message(message)
for callable in chain(self._on_message_received, self._on_message):
callable(message) |
<SYSTEM_TASK:>
Receive a message from the file.
<END_TASK>
<USER_TASK:>
Description:
def receive_message(self):
"""Receive a message from the file.""" |
with self.lock:
assert self.can_receive_messages()
message_type = self._read_message_type(self._file)
message = message_type(self._file, self)
self._message_received(message) |
<SYSTEM_TASK:>
Whether tihs communication is ready to receive messages.]
<END_TASK>
<USER_TASK:>
Description:
def can_receive_messages(self):
"""Whether tihs communication is ready to receive messages.]
:rtype: bool
.. code:: python
assert not communication.can_receive_messages()
communication.start()
assert communication.can_receive_messages()
communication.stop()
assert not communication.can_receive_messages()
""" |
with self.lock:
return not self._state.is_waiting_for_start() and \
not self._state.is_connection_closed() |
<SYSTEM_TASK:>
Stop the communication with the shield.
<END_TASK>
<USER_TASK:>
Description:
def stop(self):
"""Stop the communication with the shield.""" |
with self.lock:
self._message_received(ConnectionClosed(self._file, self)) |
<SYSTEM_TASK:>
Send a host message.
<END_TASK>
<USER_TASK:>
Description:
def send(self, host_message_class, *args):
"""Send a host message.
:param type host_message_class: a subclass of
:class:`AYABImterface.communication.host_messages.Message`
:param args: additional arguments that shall be passed to the
:paramref:`host_message_class` as arguments
""" |
message = host_message_class(self._file, self, *args)
with self.lock:
message.send()
for callable in self._on_message:
callable(message) |
<SYSTEM_TASK:>
Start a parallel thread for receiving messages.
<END_TASK>
<USER_TASK:>
Description:
def parallelize(self, seconds_to_wait=2):
"""Start a parallel thread for receiving messages.
If :meth:`start` was no called before, start will be called in the
thread.
The thread calls :meth:`receive_message` until the :attr:`state`
:meth:`~AYABInterface.communication.states.State.is_connection_closed`.
:param float seconds_to_wait: A time in seconds to wait with the
parallel execution. This is useful to allow the controller time to
initialize.
.. seealso:: :attr:`lock`, :meth:`runs_in_parallel`
""" |
with self.lock:
thread = Thread(target=self._parallel_receive_loop,
args=(seconds_to_wait,))
thread.deamon = True
thread.start()
self._thread = thread |
<SYSTEM_TASK:>
Run the receiving in parallel.
<END_TASK>
<USER_TASK:>
Description:
def _parallel_receive_loop(self, seconds_to_wait):
"""Run the receiving in parallel.""" |
sleep(seconds_to_wait)
with self._lock:
self._number_of_threads_receiving_messages += 1
try:
with self._lock:
if self.state.is_waiting_for_start():
self.start()
while True:
with self.lock:
if self.state.is_connection_closed():
return
self.receive_message()
finally:
with self._lock:
self._number_of_threads_receiving_messages -= 1 |
<SYSTEM_TASK:>
Transition into the next state.
<END_TASK>
<USER_TASK:>
Description:
def _next(self, state_class, *args):
"""Transition into the next state.
:param type state_class: a subclass of :class:`State`. It is intialized
with the communication object and :paramref:`args`
:param args: additional arguments
""" |
self._communication.state = state_class(self._communication, *args) |
<SYSTEM_TASK:>
A InformationConfirmation is received.
<END_TASK>
<USER_TASK:>
Description:
def receive_information_confirmation(self, message):
"""A InformationConfirmation is received.
If :meth:`the api version is supported
<AYABInterface.communication.Communication.api_version_is_supported>`,
the communication object transitions into a
:class:`InitializingMachine`, if unsupported, into a
:class:`UnsupportedApiVersion`
""" |
if message.api_version_is_supported():
self._next(InitializingMachine)
else:
self._next(UnsupportedApiVersion)
self._communication.controller = message |
<SYSTEM_TASK:>
Receive a StartConfirmation message.
<END_TASK>
<USER_TASK:>
Description:
def receive_start_confirmation(self, message):
"""Receive a StartConfirmation message.
:param message: a :class:`StartConfirmation
<AYABInterface.communication.hardware_messages.StartConfirmation>`
message
If the message indicates success, the communication object transitions
into :class:`KnittingStarted` or else, into :class:`StartingFailed`.
""" |
if message.is_success():
self._next(KnittingStarted)
else:
self._next(StartingFailed) |
<SYSTEM_TASK:>
Send a LineConfirmation to the controller.
<END_TASK>
<USER_TASK:>
Description:
def enter(self):
"""Send a LineConfirmation to the controller.
When this state is entered, a
:class:`AYABInterface.communication.host_messages.LineConfirmation`
is sent to the controller.
Also, the :attr:`last line requested
<AYABInterface.communication.Communication.last_requested_line_number>`
is set.
""" |
self._communication.last_requested_line_number = self._line_number
self._communication.send(LineConfirmation, self._line_number) |
<SYSTEM_TASK:>
Convert rows to needle positions.
<END_TASK>
<USER_TASK:>
Description:
def colors_to_needle_positions(rows):
"""Convert rows to needle positions.
:return:
:rtype: list
""" |
needles = []
for row in rows:
colors = set(row)
if len(colors) == 1:
needles.append([NeedlePositions(row, tuple(colors), False)])
elif len(colors) == 2:
color1, color2 = colors
if color1 != row[0]:
color1, color2 = color2, color1
needles_ = _row_color(row, color1)
needles.append([NeedlePositions(needles_, (color1, color2), True)])
else:
colors = []
for color in row:
if color not in colors:
colors.append(color)
needles_ = []
for color in colors:
needles_.append(NeedlePositions(_row_color(row, color),
(color,), False))
needles.append(needles_)
return needles |
<SYSTEM_TASK:>
Check for validity.
<END_TASK>
<USER_TASK:>
Description:
def check(self):
"""Check for validity.
:raises ValueError:
- if not all lines are as long as the :attr:`number of needles
<AYABInterface.machines.Machine.number_of_needles>`
- if the contents of the rows are not :attr:`needle positions
<AYABInterface.machines.Machine.needle_positions>`
""" |
# TODO: This violates the law of demeter.
# The architecture should be changed that this check is either
# performed by the machine or by the unity of machine and
# carriage.
expected_positions = self._machine.needle_positions
expected_row_length = self._machine.number_of_needles
for row_index, row in enumerate(self._rows):
if len(row) != expected_row_length:
message = _ROW_LENGTH_ERROR_MESSAGE.format(
row_index, len(row), expected_row_length)
raise ValueError(message)
for needle_index, needle_position in enumerate(row):
if needle_position not in expected_positions:
message = _NEEDLE_POSITION_ERROR_MESSAGE.format(
row_index, needle_index, repr(needle_position),
", ".join(map(repr, expected_positions)))
raise ValueError(message) |
<SYSTEM_TASK:>
Return the row at the given index or the default value.
<END_TASK>
<USER_TASK:>
Description:
def get_row(self, index, default=None):
"""Return the row at the given index or the default value.""" |
if not isinstance(index, int) or index < 0 or index >= len(self._rows):
return default
return self._rows[index] |
<SYSTEM_TASK:>
Mark the row at index as completed.
<END_TASK>
<USER_TASK:>
Description:
def row_completed(self, index):
"""Mark the row at index as completed.
.. seealso:: :meth:`completed_row_indices`
This method notifies the obsevrers from :meth:`on_row_completed`.
""" |
self._completed_rows.append(index)
for row_completed in self._on_row_completed:
row_completed(index) |
<SYSTEM_TASK:>
Setup communication through a file.
<END_TASK>
<USER_TASK:>
Description:
def communicate_through(self, file):
"""Setup communication through a file.
:rtype: AYABInterface.communication.Communication
""" |
if self._communication is not None:
raise ValueError("Already communicating.")
self._communication = communication = Communication(
file, self._get_needle_positions,
self._machine, [self._on_message_received],
right_end_needle=self.right_end_needle,
left_end_needle=self.left_end_needle)
return communication |
<SYSTEM_TASK:>
A list of actions to perform.
<END_TASK>
<USER_TASK:>
Description:
def actions(self):
"""A list of actions to perform.
:return: a list of :class:`AYABInterface.actions.Action`
""" |
actions = []
do = actions.append
# determine the number of colors
colors = self.colors
# rows and colors
movements = (
MoveCarriageToTheRight(KnitCarriage()),
MoveCarriageToTheLeft(KnitCarriage()))
rows = self._rows
first_needles = self._get_row_needles(0)
# handle switches
if len(colors) == 1:
actions.extend([
SwitchOffMachine(),
SwitchCarriageToModeNl()])
else:
actions.extend([
SwitchCarriageToModeKc(),
SwitchOnMachine()])
# move needles
do(MoveNeedlesIntoPosition("B", first_needles))
do(MoveCarriageOverLeftHallSensor())
# use colors
if len(colors) == 1:
do(PutColorInNutA(colors[0]))
if len(colors) == 2:
do(PutColorInNutA(colors[0]))
do(PutColorInNutB(colors[1]))
# knit
for index, row in enumerate(rows):
do(movements[index & 1])
return actions |
Subsets and Splits