code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
for evdev in glob.glob('/sys/class/input/event*'):
try:
with io.open(os.path.join(evdev, 'device', 'name'), 'r') as f:
if f.read().strip() == self.SENSE_HAT_EVDEV_NAME:
return os.path.join('/dev', 'input', os.path.basename(evdev))
... | def _stick_device(self) | Discovers the filename of the evdev device that represents the Sense
HAT's joystick. | 2.987829 | 2.270711 | 1.315812 |
event = self._stick_file.read(self.EVENT_SIZE)
(tv_sec, tv_usec, type, code, value) = struct.unpack(self.EVENT_FORMAT, event)
if type == self.EV_KEY:
return InputEvent(
timestamp=tv_sec + (tv_usec / 1000000),
direction={
se... | def _read(self) | Reads a single event from the joystick, blocking until one is
available. Returns `None` if a non-key event was read, or an
`InputEvent` tuple describing the event otherwise. | 2.483518 | 2.29124 | 1.083919 |
r, w, x = select.select([self._stick_file], [], [], timeout)
return bool(r) | def _wait(self, timeout=None) | Waits *timeout* seconds until an event is available from the
joystick. Returns `True` if an event became available, and `False`
if the timeout expired. | 7.617963 | 6.004929 | 1.268618 |
if emptybuffer:
while self._wait(0):
self._read()
while self._wait():
event = self._read()
if event:
return event | def wait_for_event(self, emptybuffer=False) | Waits until a joystick event becomes available. Returns the event, as
an `InputEvent` tuple.
If *emptybuffer* is `True` (it defaults to `False`), any pending
events will be thrown away first. This is most useful if you are only
interested in "pressed" events. | 4.622499 | 4.660356 | 0.991877 |
result = []
while self._wait(0):
event = self._read()
if event:
result.append(event)
return result | def get_events(self) | Returns a list of all joystick events that have occurred since the last
call to `get_events`. The list contains events in the order that they
occurred. If no events have occurred in the intervening time, the
result is an empty list. | 5.380918 | 4.044836 | 1.330318 |
for client in connected_clients[:]:
if client.is_asyncio_based():
client.start_background_task(client.disconnect, abort=True)
else:
client.disconnect(abort=True)
return original_signal_handler(sig, frame) | def signal_handler(sig, frame) | SIGINT handler.
Disconnect all active clients and then invoke the original signal handler. | 6.28091 | 5.110072 | 1.229124 |
if event not in self.event_names:
raise ValueError('Invalid event')
def set_handler(handler):
self.handlers[event] = handler
return handler
if handler is None:
return set_handler
set_handler(handler) | def on(self, event, handler=None) | Register an event handler.
:param event: The event name. Can be ``'connect'``, ``'message'`` or
``'disconnect'``.
:param handler: The function that should be invoked to handle the
event. When this parameter is not given, the method
a... | 2.891917 | 4.295052 | 0.673314 |
th = threading.Thread(target=target, args=args, kwargs=kwargs)
th.start()
return th | def start_background_task(self, target, *args, **kwargs) | Start a background task.
This is a utility function that applications can use to start a
background task.
:param target: the target function to execute.
:param args: arguments to pass to the function.
:param kwargs: keyword arguments to pass to the function.
This funct... | 2.505272 | 3.332029 | 0.751876 |
q = queue.Queue(*args, **kwargs)
q.Empty = queue.Empty
return q | def create_queue(self, *args, **kwargs) | Create a queue object. | 5.192486 | 4.379092 | 1.185745 |
if websocket is None: # pragma: no cover
# not installed
self.logger.warning('websocket-client package not installed, only '
'polling transport is available')
return False
websocket_url = self._get_engineio_url(url, engineio_p... | def _connect_websocket(self, url, headers, engineio_path) | Establish or upgrade to a WebSocket connection with the server. | 2.470984 | 2.456217 | 1.006012 |
run_async = kwargs.pop('run_async', False)
if event in self.handlers:
if run_async:
return self.start_background_task(self.handlers[event], *args)
else:
try:
return self.handlers[event](*args)
except:
... | def _trigger_event(self, event, *args, **kwargs) | Invoke an event handler. | 2.909454 | 2.770495 | 1.050157 |
engineio_path = engineio_path.strip('/')
parsed_url = urllib.parse.urlparse(url)
if transport == 'polling':
scheme = 'http'
elif transport == 'websocket':
scheme = 'ws'
else: # pragma: no cover
raise ValueError('invalid transport')
... | def _get_engineio_url(self, url, engineio_path, transport) | Generate the Engine.IO connection URL. | 2.427289 | 2.312674 | 1.04956 |
self.pong_received = True
self.ping_loop_event.clear()
while self.state == 'connected':
if not self.pong_received:
self.logger.info(
'PONG response has not been received, aborting')
if self.ws:
self.ws.c... | def _ping_loop(self) | This background task sends a PING to the server at the requested
interval. | 3.492357 | 3.28543 | 1.062983 |
while self.state == 'connected':
self.logger.info(
'Sending polling GET request to ' + self.base_url)
r = self._send_request(
'GET', self.base_url + self._get_url_timestamp())
if r is None:
self.logger.warning(
... | def _read_loop_polling(self) | Read packets by polling the Engine.IO server. | 3.142275 | 3.090973 | 1.016597 |
while self.state == 'connected':
p = None
try:
p = self.ws.recv()
except websocket.WebSocketConnectionClosedException:
self.logger.warning(
'WebSocket connection was closed, aborting')
self.queue.put... | def _read_loop_websocket(self) | Read packets from the Engine.IO WebSocket connection. | 3.001254 | 2.896595 | 1.036132 |
while self.state == 'connected':
# to simplify the timeout handling, use the maximum of the
# ping interval and ping timeout as timeout, with an extra 5
# seconds grace period
timeout = max(self.ping_interval, self.ping_timeout) + 5
packets = ... | def _write_loop(self) | This background task sends packages to the server as they are
pushed to the send queue. | 3.227853 | 3.13329 | 1.03018 |
if sid is not None:
try:
socket = self._get_socket(sid)
except KeyError: # pragma: no cover
# the socket was already closed or gone
pass
else:
socket.close()
del self.sockets[sid]
... | def disconnect(self, sid=None) | Disconnect a client.
:param sid: The session id of the client to close. If this parameter
is not given, then all clients are closed. | 3.048918 | 3.142972 | 0.970075 |
method = environ['REQUEST_METHOD']
query = urllib.parse.parse_qs(environ.get('QUERY_STRING', ''))
if 'j' in query:
self.logger.warning('JSONP requests are not supported')
r = self._bad_request()
else:
sid = query['sid'][0] if 'sid' in query el... | def handle_request(self, environ, start_response) | Handle an HTTP request from the client.
This is the entry point of the Engine.IO application, using the same
interface as a WSGI application. For the typical usage, this function
is invoked by the :class:`Middleware` instance, but it can be invoked
directly when the middleware is not us... | 2.264925 | 2.266745 | 0.999197 |
th = self._async['thread'](target=target, args=args, kwargs=kwargs)
th.start()
return th | def start_background_task(self, target, *args, **kwargs) | Start a background task using the appropriate async model.
This is a utility function that applications can use to start a
background task using the method that is compatible with the
selected async mode.
:param target: the target function to execute.
:param args: arguments to ... | 7.291382 | 5.609754 | 1.299769 |
if self.start_service_task:
# start the service task to monitor connected clients
self.start_service_task = False
self.start_background_task(self._service_task)
sid = self._generate_id()
s = socket.Socket(self, sid)
self.sockets[sid] = s
... | def _handle_connect(self, environ, start_response, transport, b64=False) | Handle a client connection request. | 4.423061 | 4.391181 | 1.00726 |
if not self.allow_upgrades or self._get_socket(sid).upgraded or \
self._async['websocket'] is None or transport == 'websocket':
return []
return ['websocket'] | def _upgrades(self, sid, transport) | Return the list of possible upgrades for a client connection. | 10.18218 | 8.220472 | 1.238637 |
try:
s = self.sockets[sid]
except KeyError:
raise KeyError('Session not found')
if s.closed:
del self.sockets[sid]
raise KeyError('Session is disconnected')
return s | def _get_socket(self, sid) | Return the socket object for a given session. | 3.110165 | 2.877608 | 1.080816 |
if packets is not None:
if headers is None:
headers = []
if b64:
headers += [('Content-Type', 'text/plain; charset=UTF-8')]
else:
headers += [('Content-Type', 'application/octet-stream')]
return {'status': '... | def _ok(self, packets=None, headers=None, b64=False) | Generate a successful HTTP response. | 2.207058 | 2.109187 | 1.046402 |
if isinstance(self.cors_allowed_origins, six.string_types):
if self.cors_allowed_origins == '*':
allowed_origins = None
else:
allowed_origins = [self.cors_allowed_origins]
else:
allowed_origins = self.cors_allowed_origins
... | def _cors_headers(self, environ) | Return the cross-origin-resource-sharing headers. | 1.595076 | 1.565857 | 1.01866 |
bytesio = six.BytesIO()
with gzip.GzipFile(fileobj=bytesio, mode='w') as gz:
gz.write(response)
return bytesio.getvalue() | def _gzip(self, response) | Apply gzip compression to a response. | 2.811639 | 2.627673 | 1.070011 |
if len(self.sockets) == 0:
# nothing to do
self.sleep(self.ping_timeout)
continue
# go through the entire client list in a ping interval cycle
sleep_interval = self.ping_timeout / len(self.sockets)
try:
# i... | def _service_task(self): # pragma: no cover
while True | Monitor connected clients and clean up those that time out. | 5.257684 | 4.600681 | 1.142806 |
uwsgi.disconnect()
if self._req_ctx is None:
# better kill it here in case wait() is not called again
self._select_greenlet.kill()
self._event.set() | def close(self) | Disconnects uWSGI from the client. | 18.972836 | 16.651094 | 1.139435 |
if isinstance(msg, six.binary_type):
method = uwsgi.websocket_send_binary
else:
method = uwsgi.websocket_send
if self._req_ctx is not None:
method(msg, request_context=self._req_ctx)
else:
method(msg) | def _send(self, msg) | Transmits message either in binary or UTF-8 text mode,
depending on its type. | 3.678502 | 3.595519 | 1.023079 |
if not isinstance(msg, six.binary_type):
# already decoded - do nothing
return msg
# only decode from utf-8 if message is not binary data
type = six.byte2int(msg[0:1])
if type >= 48: # no binary
return msg.decode('utf-8')
# binary mes... | def _decode_received(self, msg) | Returns either bytes or str, depending on message type. | 5.558545 | 5.149343 | 1.079467 |
if self._req_ctx is not None:
self._send(msg)
else:
self._send_queue.put(msg)
self._event.set() | def send(self, msg) | Queues a message for sending. Real transmission is done in
wait method.
Sends directly if uWSGI version is new enough. | 4.621206 | 4.770613 | 0.968682 |
while True:
if self._req_ctx is not None:
try:
msg = uwsgi.websocket_recv(request_context=self._req_ctx)
except IOError: # connection closed
return None
return self._decode_received(msg)
els... | def wait(self) | Waits and returns received messages.
If running in compatibility mode for older uWSGI versions,
it also sends messages that have been queued by send().
A return value of None means that connection was closed.
This must be called repeatedly. For uWSGI < 2.1.x it must
be called fro... | 4.136112 | 3.82738 | 1.080664 |
app.add_route(engineio_server.handle_request, engineio_endpoint,
methods=['GET', 'POST', 'OPTIONS'])
try:
app.enable_websocket()
except AttributeError:
# ignore, this version does not support websocket
pass | def create_route(app, engineio_server, engineio_endpoint) | This function sets up the engine.io endpoint as a route for the
application.
Note that both GET and POST requests must be hooked up on the engine.io
endpoint. | 4.389029 | 5.345257 | 0.821107 |
class AwaitablePayload(object):
def __init__(self, payload):
self.payload = payload or b''
async def read(self, length=None):
if length is None:
r = self.payload
self.payload = b''
else:
r = self.payload[:lengt... | def translate_request(request) | This function takes the arguments passed to the request handler and
uses them to generate a WSGI compatible environ dictionary. | 1.840501 | 1.799852 | 1.022585 |
headers_dict = {}
content_type = None
for h in headers:
if h[0].lower() == 'content-type':
content_type = h[1]
else:
headers_dict[h[0]] = h[1]
return HTTPResponse(body_bytes=payload, content_type=content_type,
status=int(status.split()... | def make_response(status, headers, payload, environ) | This function generates an appropriate response object for this async
mode. | 2.213057 | 2.294756 | 0.964397 |
engineio_path = engineio_path.strip('/')
self._async['create_route'](app, self, '/{}/'.format(engineio_path)) | def attach(self, app, engineio_path='engine.io') | Attach the Engine.IO server to an application. | 6.670685 | 6.023062 | 1.107524 |
try:
socket = self._get_socket(sid)
except KeyError:
# the socket is not available
self.logger.warning('Cannot send to sid %s', sid)
return
await socket.send(packet.Packet(packet.MESSAGE, data=data,
... | async def send(self, sid, data, binary=None) | Send a message to a client.
:param sid: The session id of the recipient client.
:param data: The data to send to the client. Data can be of type
``str``, ``bytes``, ``list`` or ``dict``. If a ``list``
or ``dict``, the data will be serialized as JSON.
:p... | 4.853177 | 5.149139 | 0.942522 |
socket = self._get_socket(sid)
socket.session = session | async def save_session(self, sid, session) | Store the user session for a client.
:param sid: The session id of the client.
:param session: The session dictionary. | 8.629184 | 9.722005 | 0.887593 |
class _session_context_manager(object):
def __init__(self, server, sid):
self.server = server
self.sid = sid
self.session = None
async def __aenter__(self):
self.session = await self.server.get_session(sid)
... | def session(self, sid) | Return the user session for a client with context manager syntax.
:param sid: The session id of the client.
This is a context manager that returns the user session dictionary for
the client. Any changes that are made to this dictionary inside the
context manager block are saved back to... | 2.034378 | 2.122486 | 0.958488 |
return asyncio.ensure_future(target(*args, **kwargs)) | def start_background_task(self, target, *args, **kwargs) | Start a background task using the appropriate async model.
This is a utility function that applications can use to start a
background task using the method that is compatible with the
selected async mode.
:param target: the target function to execute.
:param args: arguments to ... | 5.154509 | 8.126941 | 0.63425 |
run_async = kwargs.pop('run_async', False)
ret = None
if event in self.handlers:
if asyncio.iscoroutinefunction(self.handlers[event]) is True:
if run_async:
return self.start_background_task(self.handlers[event],
... | async def _trigger_event(self, event, *args, **kwargs) | Invoke an event handler. | 2.426059 | 2.34128 | 1.036211 |
if len(self.sockets) == 0:
# nothing to do
await self.sleep(self.ping_timeout)
continue
# go through the entire client list in a ping interval cycle
sleep_interval = self.ping_timeout / len(self.sockets)
try:
... | async def _service_task(self): # pragma: no cover
while True | Monitor connected clients and clean up those that time out. | 4.420553 | 3.977726 | 1.111327 |
queue_empty = self.server.get_queue_empty_exception()
try:
packets = [self.queue.get(timeout=self.server.ping_timeout)]
self.queue.task_done()
except queue_empty:
raise exceptions.QueueEmpty()
if packets == [None]:
return []
... | def poll(self) | Wait for packets to send to the client. | 3.550239 | 3.255618 | 1.090496 |
connections = [
s.strip()
for s in environ.get('HTTP_CONNECTION', '').lower().split(',')]
transport = environ.get('HTTP_UPGRADE', '').lower()
if 'upgrade' in connections and transport in self.upgrade_protocols:
self.server.logger.info('%s: Received re... | def handle_get_request(self, environ, start_response) | Handle a long-polling GET request from the client. | 4.057508 | 3.907233 | 1.038461 |
if not self.closed and not self.closing:
self.closing = True
self.server._trigger_event('disconnect', self.sid, run_async=False)
if not abort:
self.send(packet.Packet(packet.CLOSE))
self.closed = True
self.queue.put(None)
... | def close(self, wait=True, abort=False) | Close the socket connection. | 4.32093 | 4.070291 | 1.061578 |
# try to set a socket timeout matching the configured ping interval
for attr in ['_sock', 'socket']: # pragma: no cover
if hasattr(ws, attr) and hasattr(getattr(ws, attr), 'settimeout'):
getattr(ws, attr).settimeout(self.server.ping_timeout)
if self.connect... | def _websocket_handler(self, ws) | Engine.IO handler for websocket transport. | 3.623797 | 3.594402 | 1.008178 |
if self.state != 'disconnected':
raise ValueError('Client is not in a disconnected state')
valid_transports = ['polling', 'websocket']
if transports is not None:
if isinstance(transports, six.text_type):
transports = [transports]
trans... | async def connect(self, url, headers={}, transports=None,
engineio_path='engine.io') | Connect to an Engine.IO server.
:param url: The URL of the Engine.IO server. It can include custom
query string parameters if required by the server.
:param headers: A dictionary with custom headers to send with the
connection request.
:param transpor... | 2.5397 | 2.933179 | 0.865853 |
await self._send_packet(packet.Packet(packet.MESSAGE, data=data,
binary=binary)) | async def send(self, data, binary=None) | Send a message to a client.
:param data: The data to send to the client. Data can be of type
``str``, ``bytes``, ``list`` or ``dict``. If a ``list``
or ``dict``, the data will be serialized as JSON.
:param binary: ``True`` to send packet as binary, ``False`` to... | 8.684542 | 7.867284 | 1.10388 |
if self.state == 'connected':
await self._send_packet(packet.Packet(packet.CLOSE))
await self.queue.put(None)
self.state = 'disconnecting'
await self._trigger_event('disconnect', run_async=False)
if self.current_transport == 'websocket':
... | async def disconnect(self, abort=False) | Disconnect from the server.
:param abort: If set to ``True``, do not wait for background tasks
associated with the connection to end.
Note: this method is a coroutine. | 3.974004 | 4.227205 | 0.940102 |
q = asyncio.Queue()
q.Empty = asyncio.QueueEmpty
return q | def create_queue(self) | Create a queue object. | 12.676034 | 9.301678 | 1.362769 |
if aiohttp is None: # pragma: no cover
self.logger.error('aiohttp not installed -- cannot make HTTP '
'requests!')
return
self.base_url = self._get_engineio_url(url, engineio_path, 'polling')
self.logger.info('Attempting polling con... | async def _connect_polling(self, url, headers, engineio_path) | Establish a long-polling connection to the Engine.IO server. | 2.920943 | 2.891672 | 1.010122 |
if websockets is None: # pragma: no cover
self.logger.error('websockets package not installed')
return False
websocket_url = self._get_engineio_url(url, engineio_path,
'websocket')
if self.sid:
self.logg... | async def _connect_websocket(self, url, headers, engineio_path) | Establish or upgrade to a WebSocket connection with the server. | 2.37655 | 2.34723 | 1.012492 |
packet_name = packet.packet_names[pkt.packet_type] \
if pkt.packet_type < len(packet.packet_names) else 'UNKNOWN'
self.logger.info(
'Received packet %s data %s', packet_name,
pkt.data if not isinstance(pkt.data, bytes) else '<binary>')
if pkt.packet_t... | async def _receive_packet(self, pkt) | Handle incoming packets from the server. | 2.889875 | 2.781695 | 1.03889 |
if self.state != 'connected':
return
await self.queue.put(pkt)
self.logger.info(
'Sending packet %s data %s',
packet.packet_names[pkt.packet_type],
pkt.data if not isinstance(pkt.data, bytes) else '<binary>') | async def _send_packet(self, pkt) | Queue a packet to be sent to the server. | 5.12023 | 4.666163 | 1.097311 |
while self.state == 'connected':
# to simplify the timeout handling, use the maximum of the
# ping interval and ping timeout as timeout, with an extra 5
# seconds grace period
timeout = max(self.ping_interval, self.ping_timeout) + 5
packets = ... | async def _write_loop(self) | This background task sends packages to the server as they are
pushed to the send queue. | 3.33092 | 3.273744 | 1.017465 |
encoded_payload = b''
for pkt in self.packets:
encoded_packet = pkt.encode(b64=b64)
packet_len = len(encoded_packet)
if b64:
encoded_payload += str(packet_len).encode('utf-8') + b':' + \
encoded_packet
else:
... | def encode(self, b64=False) | Encode the payload for transmission. | 2.586015 | 2.469209 | 1.047305 |
self.packets = []
while encoded_payload:
if six.byte2int(encoded_payload[0:1]) <= 1:
packet_len = 0
i = 1
while six.byte2int(encoded_payload[i:i + 1]) != 255:
packet_len = packet_len * 10 + six.byte2int(
... | def decode(self, encoded_payload) | Decode a transmitted payload. | 3.581871 | 3.567727 | 1.003964 |
tornado_handler = environ['tornado.handler']
tornado_handler.set_status(int(status.split()[0]))
for header, value in headers:
tornado_handler.set_header(header, value)
tornado_handler.write(payload)
tornado_handler.finish() | def make_response(status, headers, payload, environ) | This function generates an appropriate response object for this async
mode. | 2.153163 | 2.274608 | 0.946608 |
app.router.add_get(engineio_endpoint, engineio_server.handle_request)
app.router.add_post(engineio_endpoint, engineio_server.handle_request)
app.router.add_route('OPTIONS', engineio_endpoint,
engineio_server.handle_request) | def create_route(app, engineio_server, engineio_endpoint) | This function sets up the engine.io endpoint as a route for the
application.
Note that both GET and POST requests must be hooked up on the engine.io
endpoint. | 1.871755 | 2.026762 | 0.92352 |
message = request._message
payload = request._payload
uri_parts = urlsplit(message.path)
environ = {
'wsgi.input': payload,
'wsgi.errors': sys.stderr,
'wsgi.version': (1, 0),
'wsgi.async': True,
'wsgi.multithread': False,
'wsgi.multiprocess': False,
... | def translate_request(request) | This function takes the arguments passed to the request handler and
uses them to generate a WSGI compatible environ dictionary. | 1.916202 | 1.894394 | 1.011512 |
return Response(body=payload, status=int(status.split()[0]),
headers=headers) | def make_response(status, headers, payload, environ) | This function generates an appropriate response object for this async
mode. | 4.132579 | 5.467999 | 0.755775 |
if self.binary and not b64:
encoded_packet = six.int2byte(self.packet_type)
else:
encoded_packet = six.text_type(self.packet_type)
if self.binary and b64:
encoded_packet = 'b' + encoded_packet
if self.binary:
if b64:
... | def encode(self, b64=False, always_bytes=True) | Encode the packet for transmission. | 2.053682 | 1.994595 | 1.029624 |
b64 = False
if not isinstance(encoded_packet, binary_types):
encoded_packet = encoded_packet.encode('utf-8')
elif not isinstance(encoded_packet, bytes):
encoded_packet = bytes(encoded_packet)
self.packet_type = six.byte2int(encoded_packet[0:1])
if... | def decode(self, encoded_packet) | Decode a transmitted package. | 2.510539 | 2.483733 | 1.010793 |
try:
packets = [await asyncio.wait_for(self.queue.get(),
self.server.ping_timeout)]
self.queue.task_done()
except (asyncio.TimeoutError, asyncio.CancelledError):
raise exceptions.QueueEmpty()
if packets ==... | async def poll(self) | Wait for packets to send to the client. | 3.199857 | 2.829579 | 1.13086 |
self.server.logger.info('%s: Received packet %s data %s',
self.sid, packet.packet_names[pkt.packet_type],
pkt.data if not isinstance(pkt.data, bytes)
else '<binary>')
if pkt.packet_type == packet.PIN... | async def receive(self, pkt) | Receive packet from the client. | 3.322487 | 3.221803 | 1.031251 |
if self.closed:
raise exceptions.SocketIsClosedError()
if time.time() - self.last_ping > self.server.ping_interval + 5:
self.server.logger.info('%s: Client is gone, closing socket',
self.sid)
# Passing abort=False here will... | async def check_ping_timeout(self) | Make sure the client is still sending pings.
This helps detect disconnections for long-polling clients. | 8.215903 | 7.612498 | 1.079265 |
if not await self.check_ping_timeout():
return
if self.upgrading:
self.packet_backlog.append(pkt)
else:
await self.queue.put(pkt)
self.server.logger.info('%s: Sending packet %s data %s',
self.sid, packet.packet_... | async def send(self, pkt) | Send a packet to the client. | 5.584305 | 5.297565 | 1.054127 |
length = int(environ.get('CONTENT_LENGTH', '0'))
if length > self.server.max_http_buffer_size:
raise exceptions.ContentTooLongError()
else:
body = await environ['wsgi.input'].read(length)
p = payload.Payload(encoded_payload=body)
for pkt i... | async def handle_post_request(self, environ) | Handle a long-polling POST request from the client. | 4.468547 | 3.948082 | 1.131827 |
if self.upgraded:
raise IOError('Socket has been upgraded already')
if self.server._async['websocket'] is None:
# the selected async mode does not support websocket
return self.server._bad_request()
ws = self.server._async['websocket'](self._websocket... | async def _upgrade_websocket(self, environ) | Upgrade the connection from polling to websocket. | 8.564822 | 7.758703 | 1.103899 |
if self.connected:
# the socket was already connected, so this is an upgrade
self.upgrading = True # hold packet sends during the upgrade
try:
pkt = await ws.wait()
except IOError: # pragma: no cover
return
d... | async def _websocket_handler(self, ws) | Engine.IO handler for websocket transport. | 3.677525 | 3.633437 | 1.012134 |
found = re.search(
(
"(10 assert_exception: Assert Exception\n|"
"3030000 tx_missing_posting_auth)"
".*: (.*)\n"
),
str(e),
flags=re.M,
)
if found:
return found.group(2).strip()
else:
return str(e) | def decodeRPCErrorMsg(e) | Helper function to decode the raised Exception and give it a
python Exception class | 7.528493 | 8.098162 | 0.929655 |
from .memo import Memo
if not account:
if "default_account" in self.config:
account = self.config["default_account"]
if not account:
raise ValueError("You need to provide an account")
account = Account(account, blockchain_instance=self)
... | def transfer(self, to, amount, asset, memo="", account=None, **kwargs) | Transfer an asset to another account.
:param str to: Recipient
:param float amount: Amount to transfer
:param str asset: Asset to transfer
:param str memo: (optional) Memo, may begin with `#` for encrypted
messaging
:param str account: (option... | 1.948949 | 2.016152 | 0.966668 |
if not account:
if "default_account" in self.config:
account = self.config["default_account"]
if not account:
raise ValueError("You need to provide an account")
account = Account(account, blockchain_instance=self)
op = operations.Account_u... | def upgrade_account(self, account=None, **kwargs) | Upgrade an account to Lifetime membership
:param str account: (optional) the account to allow access
to (defaults to ``default_account``) | 2.044562 | 2.002738 | 1.020884 |
from copy import deepcopy
if not account:
if "default_account" in self.config:
account = self.config["default_account"]
if not account:
raise ValueError("You need to provide an account")
if permission not in ["owner", "active"]:
... | def allow(
self,
foreign,
weight=None,
permission="active",
account=None,
threshold=None,
**kwargs
) | Give additional access to an account by some other public
key or account.
:param str foreign: The foreign account that will obtain access
:param int weight: (optional) The weight to use. If not
define, the threshold will be used. If the weight is
smal... | 2.475877 | 2.475941 | 0.999974 |
if not account:
if "default_account" in self.config:
account = self.config["default_account"]
if not account:
raise ValueError("You need to provide an account")
PublicKey(key, prefix=self.prefix)
account = Account(account, blockchain_ins... | def update_memo_key(self, key, account=None, **kwargs) | Update an account's memo public key
This method does **not** add any private keys to your
wallet but merely changes the memo public key.
:param str key: New memo public key
:param str account: (optional) the account to allow access
to (defaults to ``defa... | 2.32981 | 2.215822 | 1.051443 |
from .proposal import Proposal
if not account:
if "default_account" in self.config:
account = self.config["default_account"]
if not account:
raise ValueError("You need to provide an account")
account = Account(account, blockchain_instance... | def approveproposal(self, proposal_ids, account=None, approver=None, **kwargs) | Approve Proposal
:param list proposal_id: Ids of the proposals
:param str appprover: The account or key to use for approval
(defaults to ``account``)
:param str account: (optional) the account to allow access
to (defaults to ``default_account``) | 2.340876 | 2.345795 | 0.997903 |
from .proposal import Proposal
if not account:
if "default_account" in self.config:
account = self.config["default_account"]
if not account:
raise ValueError("You need to provide an account")
account = Account(account, blockchain_instance... | def disapproveproposal(self, proposal_ids, account=None, approver=None, **kwargs) | Disapprove Proposal
:param list proposal_ids: Ids of the proposals
:param str account: (optional) the account to allow access
to (defaults to ``default_account``) | 1.867551 | 1.916893 | 0.974259 |
if not account:
if "default_account" in self.config:
account = self.config["default_account"]
if not account:
raise ValueError("You need to provide an account")
account = Account(account, blockchain_instance=self)
options = account["option... | def approveworker(self, workers, account=None, **kwargs) | Approve a worker
:param list workers: list of worker member name or id
:param str account: (optional) the account to allow access
to (defaults to ``default_account``) | 2.628959 | 2.678729 | 0.98142 |
if not account:
if "default_account" in self.config:
account = self.config["default_account"]
if not account:
raise ValueError("You need to provide an account")
account = Account(account, blockchain_instance=self)
proxy = Account(proxy_acc... | def set_proxy(self, proxy_account, account=None, **kwargs) | Set a specific proxy for account
:param bitshares.account.Account proxy_account: Account to be
proxied
:param str account: (optional) the account to allow access
to (defaults to ``default_account``) | 2.205327 | 2.179156 | 1.01201 |
if not account:
if "default_account" in self.config:
account = self.config["default_account"]
if not account:
raise ValueError("You need to provide an account")
account = Account(account, full=False, blockchain_instance=self)
if not isins... | def cancel(self, orderNumbers, account=None, **kwargs) | Cancels an order you have placed in a given market. Requires
only the "orderNumbers". An order number takes the form
``1.7.xxx``.
:param str orderNumbers: The Order Object ide of the form
``1.7.xxxx`` | 2.41764 | 2.524953 | 0.957499 |
if not account:
if "default_account" in self.config:
account = self.config["default_account"]
if not account:
raise ValueError("You need to provide an account")
account = Account(account, blockchain_instance=self)
if not amount:
... | def vesting_balance_withdraw(self, vesting_id, amount=None, account=None, **kwargs) | Withdraw vesting balance
:param str vesting_id: Id of the vesting object
:param bitshares.amount.Amount Amount: to withdraw ("all" if not
provided")
:param str account: (optional) the account to allow access
to (defaults to ``default_account``) | 2.184346 | 2.177725 | 1.00304 |
assert mcr > 100
assert mssr > 100
assert isinstance(
settlement_price, Price
), "settlement_price needs to be instance of `bitshares.price.Price`!"
assert cer is None or isinstance(
cer, Price
), "cer needs to be instance of `bitshares.pr... | def publish_price_feed(
self, symbol, settlement_price, cer=None, mssr=110, mcr=200, account=None
) | Publish a price feed for a market-pegged asset
:param str symbol: Symbol of the asset to publish feed for
:param bitshares.price.Price settlement_price: Price for settlement
:param bitshares.price.Price cer: Core exchange Rate (default
``settlement_price + 5%``)
... | 2.468681 | 2.268529 | 1.08823 |
assert isinstance(
cer, Price
), "cer needs to be instance of `bitshares.price.Price`!"
if not account:
if "default_account" in self.config:
account = self.config["default_account"]
if not account:
raise ValueError("You need to... | def update_cer(self, symbol, cer, account=None) | Update the Core Exchange Rate (CER) of an asset
:param str symbol: Symbol of the asset to publish feed for
:param bitshares.price.Price cer: Core exchange Rate
:param str account: (optional) the account to allow access
to (defaults to ``default_account``) | 3.118919 | 2.695596 | 1.157043 |
witness = Witness(witness_identifier)
account = witness.account
op = operations.Witness_update(
**{
"fee": {"amount": 0, "asset_id": "1.3.0"},
"prefix": self.prefix,
"witness": witness["id"],
"witness_account": ... | def update_witness(self, witness_identifier, url=None, key=None, **kwargs) | Upgrade a witness account
:param str witness_identifier: Identifier for the witness
:param str url: New URL for the witness
:param str key: Public Key for the signing | 2.425125 | 2.554087 | 0.949508 |
assert isinstance(amount, Amount)
if not account:
if "default_account" in self.config:
account = self.config["default_account"]
if not account:
raise ValueError("You need to provide an account")
account = Account(account, blockchain_instan... | def reserve(self, amount, account=None, **kwargs) | Reserve/Burn an amount of this shares
This removes the shares from the supply
:param bitshares.amount.Amount amount: The amount to be burned.
:param str account: (optional) the account to allow access
to (defaults to ``default_account``) | 2.063395 | 2.044208 | 1.009386 |
from bitsharesbase.transactions import timeformat
assert isinstance(daily_pay, Amount)
assert daily_pay["asset"]["id"] == "1.3.0"
if not begin:
begin = datetime.utcnow() + timedelta(seconds=30)
if not account:
if "default_account" in self.config:... | def create_worker(
self,
name,
daily_pay,
end,
url="",
begin=None,
payment_type="vesting",
pay_vesting_period_days=0,
account=None,
**kwargs
) | Create a worker
This removes the shares from the supply
**Required**
:param str name: Name of the worke
:param bitshares.amount.Amount daily_pay: The amount to be paid
daily
:param datetime end: Date/time of end of the worker
**... | 2.357634 | 2.153575 | 1.094754 |
assert isinstance(amount, float)
if not account:
if "default_account" in self.config:
account = self.config["default_account"]
if not account:
raise ValueError("You need to provide an account")
amount = Amount(amount, "1.3.0", blockchain_i... | def fund_fee_pool(self, symbol, amount, account=None, **kwargs) | Fund the fee pool of an asset
:param str symbol: The symbol to fund the fee pool of
:param float amount: The amount to be burned.
:param str account: (optional) the account to allow access
to (defaults to ``default_account``) | 2.19411 | 2.278318 | 0.96304 |
if not account:
if "default_account" in self.config:
account = self.config["default_account"]
if not account:
raise ValueError("You need to provide an account")
account = Account(account, blockchain_instance=self)
op = operations.Committe... | def create_committee_member(self, url="", account=None, **kwargs) | Create a committee member
:param str url: URL to read more about the worker
:param str account: (optional) the account to allow access
to (defaults to ``default_account``) | 2.000345 | 2.011278 | 0.994564 |
if not account:
if "default_account" in self.config:
account = self.config["default_account"]
if not account:
raise ValueError("You need to provide an account")
account = Account(account, blockchain_instance=self)
account_to_list = Account... | def account_whitelist(
self,
account_to_whitelist,
lists=["white"], # set of 'white' and/or 'black'
account=None,
**kwargs
) | Account whitelisting
:param str account_to_whitelist: The account we want to add
to either the white- or the blacklist
:param set lists: (defaults to ``('white')``). Lists the
user should be added to. Either empty set, 'black',
'white' or both.
... | 2.390337 | 2.370468 | 1.008382 |
self.websocket.reset_subscriptions(
accounts, self.get_market_ids(markets), objects
) | def reset_subscriptions(self, accounts=[], markets=[], objects=[]) | Change the subscriptions of a running Notify instance | 5.545433 | 5.895288 | 0.940655 |
for d in data:
if not d:
continue
if isinstance(d, str):
# Single order has been placed
log.debug("Calling on_market with Order()")
self.on_market(Order(d, blockchain_instance=self.blockchain))
conti... | def process_market(self, data) | This method is used for post processing of market
notifications. It will return instances of either
* :class:`bitshares.price.Order` or
* :class:`bitshares.price.FilledOrder` or
* :class:`bitshares.price.UpdateCallOrder`
Also possible are limit order updates... | 3.174141 | 2.690295 | 1.179849 |
self.on_account(AccountUpdate(message, blockchain_instance=self.blockchain)) | def process_account(self, message) | This is used for processing of account Updates. It will
return instances of :class:bitshares.account.AccountUpdate` | 13.769238 | 6.920245 | 1.989704 |
from bitsharesbase.operations import operations
r = {}
obj, base = self.blockchain.rpc.get_objects(["2.0.0", "1.3.0"])
fees = obj["parameters"]["current_fees"]["parameters"]
scale = float(obj["parameters"]["current_fees"]["scale"])
for f in fees:
op_... | def returnFees(self) | Returns a dictionary of all fees that apply through the
network
Example output:
.. code-block:: js
{'proposal_create': {'fee': 400000.0},
'asset_publish_feed': {'fee': 1000.0}, 'account_create':
{'basic_fee': 950000.0, 'price_per_kby... | 4.842974 | 4.648092 | 1.041927 |
if not account:
if "default_account" in self.blockchain.config:
account = self.blockchain.config["default_account"]
if not account:
raise ValueError("You need to provide an account")
account = Account(account, full=True, blockchain_instance=self.b... | def list_debt_positions(self, account=None) | List Call Positions (borrowed assets and amounts)
:return: Struct of assets with amounts and call price
:rtype: dict
**Example**:
.. code-block: js
{'USD': {'collateral': '865893.75000',
'collateral_asset': 'BTS',
... | 2.375765 | 2.330418 | 1.019459 |
if not account:
if "default_account" in self.blockchain.config:
account = self.blockchain.config["default_account"]
if not account:
raise ValueError("You need to provide an account")
account = Account(account, full=True, blockchain_instance=self.b... | def close_debt_position(self, symbol, account=None) | Close a debt position and reclaim the collateral
:param str symbol: Symbol to close debt position for
:raises ValueError: if symbol has no open call position | 2.307238 | 2.194114 | 1.051558 |
if not account:
if "default_account" in self.blockchain.config:
account = self.blockchain.config["default_account"]
if not account:
raise ValueError("You need to provide an account")
account = Account(account, full=True, blockchain_instance=self.b... | def adjust_debt(
self,
delta,
new_collateral_ratio=None,
account=None,
target_collateral_ratio=None,
) | Adjust the amount of debt for an asset
:param Amount delta: Delta amount of the debt (-10 means reduce
debt by 10, +10 means borrow another 10)
:param float new_collateral_ratio: collateral ratio to maintain
(optional, by default tries to maintain old ratio)
... | 2.584624 | 2.502683 | 1.032741 |
if not account:
if "default_account" in self.blockchain.config:
account = self.blockchain.config["default_account"]
if not account:
raise ValueError("You need to provide an account")
account = Account(account, full=True, blockchain_instance=self.b... | def adjust_collateral_ratio(
self, symbol, new_collateral_ratio, account=None, target_collateral_ratio=None
) | Adjust the collataral ratio of a debt position
:param Asset amount: Amount to borrow (denoted in 'asset')
:param float new_collateral_ratio: desired collateral ratio
:param float target_collateral_ratio: Tag the call order so that in
case of margin call, only enough ... | 3.60638 | 3.203257 | 1.125848 |
return self.adjust_debt(
amount,
collateral_ratio,
account,
target_collateral_ratio=target_collateral_ratio,
) | def borrow(
self, amount, collateral_ratio=None, account=None, target_collateral_ratio=None
) | Borrow bitassets/smartcoins from the network by putting up
collateral in a CFD at a given collateral ratio.
:param float amount: Amount to borrow (denoted in 'asset')
:param float collateral_ratio: Collateral ratio to borrow at
:param float target_collateral_ratio: Tag t... | 3.407412 | 4.114146 | 0.828219 |
for key in operations:
if int(operations[key]) is int(i):
return key
return "Unknown Operation ID %d" % i | def getOperationNameForId(i) | Convert an operation id into the corresponding string | 4.419726 | 4.530818 | 0.975481 |
if isinstance(id, str):
# Some graphene chains (e.g. steem) do not encode the
# operation_type as id but in its string form
assert id in operations.keys(), "Unknown operation {}".format(id)
return id
elif isinstance(id, int):
return getOperationNameForId(id)
else... | def getOperationName(id: str) | This method returns the name representation of an operation given
its value as used in the API | 7.780972 | 7.962045 | 0.977258 |
props = self.get_chain_properties()
chain_id = props["chain_id"]
for k, v in known_chains.items():
if v["chain_id"] == chain_id:
return v
raise exceptions.UnknownNetworkException(
"Connecting to unknown network (chain_id: {})!".format(prop... | def get_network(self) | Identify the connected network. This call returns a
dictionary with keys chain_id, core_symbol and prefix | 4.322816 | 3.81758 | 1.132345 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.