INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
Return the 0-based index (rank) of ``score``.
If the score is not available it returns a negative integer which
absolute score is the right most closest index with score less than
``score``. | def rank(self, score):
'''Return the 0-based index (rank) of ``score``.
If the score is not available it returns a negative integer which
absolute score is the right most closest index with score less than
``score``.
'''
node = self._head
rank = 0
for i i... |
Remove a range by rank.
This is equivalent to perform::
del l[start:end]
on a python list.
It returns the number of element removed. | def remove_range(self, start, end, callback=None):
'''Remove a range by rank.
This is equivalent to perform::
del l[start:end]
on a python list.
It returns the number of element removed.
'''
N = len(self)
if start < 0:
start = max(N + st... |
Remove a range with scores between ``minval`` and ``maxval``.
:param minval: the start value of the range to remove
:param maxval: the end value of the range to remove
:param include_min: whether or not to include ``minval`` in the
values to remove
:param include_max: whethe... | def remove_range_by_score(self, minval, maxval, include_min=True,
include_max=True, callback=None):
'''Remove a range with scores between ``minval`` and ``maxval``.
:param minval: the start value of the range to remove
:param maxval: the end value of the range to r... |
Returns the number of elements in the skiplist with a score
between min and max. | def count(self, minval, maxval, include_min=True, include_max=True):
'''Returns the number of elements in the skiplist with a score
between min and max.
'''
rank1 = self.rank(minval)
if rank1 < 0:
rank1 = -rank1 - 1
elif not include_min:
rank1 += 1... |
Get a connection from the pool.
The connection is either a new one or retrieved from the
:attr:`available` connections in the pool.
:return: a :class:`~asyncio.Future` resulting in the connection. | async def connect(self):
'''Get a connection from the pool.
The connection is either a new one or retrieved from the
:attr:`available` connections in the pool.
:return: a :class:`~asyncio.Future` resulting in the connection.
'''
assert not self.closed
connection... |
Close all connections
Return a :class:`~asyncio.Future` called once all connections
have closed | def close(self):
'''Close all connections
Return a :class:`~asyncio.Future` called once all connections
have closed
'''
if not self.closed:
waiters = []
queue = self._queue
while queue.qsize():
connection = queue.get_nowait()
... |
Close this pool connection by releasing the underlying
:attr:`connection` back to the :attr:`pool`. | def close(self, discard=False):
'''Close this pool connection by releasing the underlying
:attr:`connection` back to the :attr:`pool`.
'''
if self.pool is not None:
self.pool._put(self.connection, discard)
self.pool = None
conn, self.connection = self.... |
Remove the underlying :attr:`connection` from the connection
:attr:`pool`. | async def detach(self, discard=True):
'''Remove the underlying :attr:`connection` from the connection
:attr:`pool`.
'''
if discard:
return self.close(True)
else:
self.connection._exit_ = False
return self |
Helper method for creating a connection to an ``address``. | async def create_connection(self, address=None, protocol_factory=None,
**kwargs):
"""Helper method for creating a connection to an ``address``.
"""
loop = self._loop
protocol_factory = protocol_factory or self.create_protocol
if isinstance(address,... |
Helper method for creating a connection to an ``address``. | async def create_datagram_endpoint(self, protocol_factory=None, **kw):
'''Helper method for creating a connection to an ``address``.
'''
protocol_factory = protocol_factory or self.create_protocol
_, protocol = await self._loop.create_datagram_endpoint(
protocol_factory, **kw... |
Returns the quality of the key.
.. versionadded:: 0.6
In previous versions you had to use the item-lookup syntax
(eg: ``obj[key]`` instead of ``obj.quality(key)``) | def quality(self, key):
"""Returns the quality of the key.
.. versionadded:: 0.6
In previous versions you had to use the item-lookup syntax
(eg: ``obj[key]`` instead of ``obj.quality(key)``)
"""
for item, quality in self:
if self._value_matches(key, ite... |
Get the position of an entry or raise :exc:`ValueError`.
:param key: The key to be looked up.
.. versionchanged:: 0.5
This used to raise :exc:`IndexError`, which was inconsistent
with the list API. | def index(self, key):
"""Get the position of an entry or raise :exc:`ValueError`.
:param key: The key to be looked up.
.. versionchanged:: 0.5
This used to raise :exc:`IndexError`, which was inconsistent
with the list API.
"""
if isinstance(key, str):
... |
Convert the header set into an HTTP header string. | def to_header(self):
"""Convert the header set into an HTTP header string."""
result = []
for value, quality in self:
if quality != 1:
value = '%s;q=%s' % (value, quality)
result.append(value)
return ','.join(result) |
Returns the best match from a list of possible matches based
on the quality of the client. If two items have the same quality,
the one is returned that comes first.
:param matches: a list of matches to check for
:param default: the value that is returned if none match | def best_match(self, matches, default=None):
"""Returns the best match from a list of possible matches based
on the quality of the client. If two items have the same quality,
the one is returned that comes first.
:param matches: a list of matches to check for
:param default: th... |
Convert a number of bytes into a human readable memory usage, bytes,
kilo, mega, giga, tera, peta, exa, zetta, yotta | def convert_bytes(b):
'''Convert a number of bytes into a human readable memory usage, bytes,
kilo, mega, giga, tera, peta, exa, zetta, yotta'''
if b is None:
return '#NA'
for s in reversed(memory_symbols):
if b >= memory_size[s]:
value = float(b) / memory_size[s]
ret... |
Returns a dictionary of system information for the process ``pid``.
It uses the psutil_ module for the purpose. If psutil_ is not available
it returns an empty dictionary.
.. _psutil: http://code.google.com/p/psutil/ | def process_info(pid=None):
'''Returns a dictionary of system information for the process ``pid``.
It uses the psutil_ module for the purpose. If psutil_ is not available
it returns an empty dictionary.
.. _psutil: http://code.google.com/p/psutil/
'''
if psutil is None: # pragma nocover
... |
Close by closing the :attr:`transport`
Return the ``connection_lost`` event which can be used to wait
for complete transport closure. | def close(self):
"""Close by closing the :attr:`transport`
Return the ``connection_lost`` event which can be used to wait
for complete transport closure.
"""
if not self._closed:
closed = False
event = self.event('connection_lost')
if self.tra... |
Abort by aborting the :attr:`transport` | def abort(self):
"""Abort by aborting the :attr:`transport`
"""
if self.transport:
self.transport.abort()
self.event('connection_lost').fire() |
Start serving.
:param address: optional address to bind to
:param sockets: optional list of sockets to bind to
:param backlog: Number of maximum connections
:param sslcontext: optional SSLContext object | async def start_serving(self, address=None, sockets=None,
backlog=100, sslcontext=None):
"""Start serving.
:param address: optional address to bind to
:param sockets: optional list of sockets to bind to
:param backlog: Number of maximum connections
:p... |
Stop serving the :attr:`.Server.sockets`. | async def close(self):
"""Stop serving the :attr:`.Server.sockets`.
"""
if self._server:
self._server.close()
self._server = None
coro = self._close_connections()
if coro:
await coro
self.logger.debug('%s closed', self)
... |
Close ``connection`` if specified, otherwise close all connections.
Return a list of :class:`.Future` called back once the connection/s
are closed. | def _close_connections(self, connection=None, timeout=5):
"""Close ``connection`` if specified, otherwise close all connections.
Return a list of :class:`.Future` called back once the connection/s
are closed.
"""
all = []
if connection:
waiter = connection.ev... |
Stop serving the :attr:`.Server.sockets` and close all
concurrent connections. | def close(self):
"""Stop serving the :attr:`.Server.sockets` and close all
concurrent connections.
"""
transports, self.transports = self.transports, []
for transport in transports:
transport.close() |
create the server endpoint. | async def start_serving(self, address=None, sockets=None, **kw):
"""create the server endpoint.
"""
if self._server:
raise RuntimeError('Already serving')
server = DGServer(self._loop)
loop = self._loop
if sockets:
for sock in sockets:
... |
Stop serving the :attr:`.Server.sockets` and close all
concurrent connections. | async def close(self):
"""Stop serving the :attr:`.Server.sockets` and close all
concurrent connections.
"""
if self._server:
self._server.close()
self._server = None
self.event('stop').fire() |
When a new websocket connection is established it creates a
new :class:`ChatClient` and adds it to the set of clients of the
:attr:`pubsub` handler. | def on_open(self, websocket):
'''When a new websocket connection is established it creates a
new :class:`ChatClient` and adds it to the set of clients of the
:attr:`pubsub` handler.'''
LOGGER.info('New websocket opened. Add client to %s on "%s" channel',
self.pubsub, ... |
Create the socket listening to the ``bind`` address.
If the platform does not support multiprocessing sockets set the
number of workers to 0. | async def monitor_start(self, monitor):
'''Create the socket listening to the ``bind`` address.
If the platform does not support multiprocessing sockets set the
number of workers to 0.
'''
cfg = self.cfg
if (not platform.has_multiprocessing_socket or
cfg.... |
Start the worker by invoking the :meth:`create_server` method. | async def worker_start(self, worker, exc=None):
'''Start the worker by invoking the :meth:`create_server` method.
'''
if not exc and self.name not in worker.servers:
servers = await self.binds(worker, worker.sockets)
for server in servers.values():
server.... |
Create the Server which will listen for requests.
:return: a :class:`.TcpServer`. | async def create_server(self, worker, protocol_factory, address=None,
sockets=None, idx=0):
'''Create the Server which will listen for requests.
:return: a :class:`.TcpServer`.
'''
cfg = self.cfg
max_requests = cfg.max_requests
if max_requests... |
Lists the currently active channels matching ``pattern`` | def channels(self, pattern=None):
'''Lists the currently active channels matching ``pattern``
'''
if pattern:
return self.store.execute('PUBSUB', 'CHANNELS', pattern)
else:
return self.store.execute('PUBSUB', 'CHANNELS') |
Stop listening for messages. | async def close(self):
'''Stop listening for messages.
'''
if self.push_connection:
self._execute('PUNSUBSCRIBE')
self._execute('UNSUBSCRIBE')
await self.push_connection.close() |
Global distributed lock | def lock(self, name, **kwargs):
"""Global distributed lock
"""
return self.pubsub.store.client().lock(self.prefixed(name), **kwargs) |
Publish a new ``event`` on a ``channel``
:param channel: channel name
:param event: event name
:param data: optional payload to include in the event
:return: a coroutine and therefore it must be awaited | async def publish(self, channel, event, data=None):
"""Publish a new ``event`` on a ``channel``
:param channel: channel name
:param event: event name
:param data: optional payload to include in the event
:return: a coroutine and therefore it must be awaited
"""
m... |
Close channels and underlying pubsub handler
:return: a coroutine and therefore it must be awaited | async def close(self):
"""Close channels and underlying pubsub handler
:return: a coroutine and therefore it must be awaited
"""
push_connection = self.pubsub.push_connection
self.status = self.statusType.closed
if push_connection:
push_connection.event('conn... |
Update the :class:`zset` with an iterable over pairs of
scores and values. | def update(self, score_vals):
'''Update the :class:`zset` with an iterable over pairs of
scores and values.'''
add = self.add
for score, value in score_vals:
add(score, value) |
Remove ``item`` for the :class:`zset` it it exists.
If found it returns the score of the item removed. | def remove(self, item):
'''Remove ``item`` for the :class:`zset` it it exists.
If found it returns the score of the item removed.
'''
score = self._dict.pop(item, None)
if score is not None:
index = self._sl.rank(score)
assert index >= 0, 'could not find s... |
Remove a range by score. | def remove_range(self, start, end):
'''Remove a range by score.
'''
return self._sl.remove_range(
start, end, callback=lambda sc, value: self._dict.pop(value)) |
Remove a range by score. | def remove_range_by_score(self, minval, maxval,
include_min=True, include_max=True):
'''Remove a range by score.
'''
return self._sl.remove_range_by_score(
minval, maxval, include_min=include_min, include_max=include_max,
callback=lambda sc, ... |
Return the rank (index) of ``item`` in this :class:`zset`. | def rank(self, item):
'''Return the rank (index) of ``item`` in this :class:`zset`.'''
score = self._dict.get(item)
if score is not None:
return self._sl.rank(score) |
Tries to guess the filename of the given object. | def guess_filename(obj):
"""Tries to guess the filename of the given object."""
name = getattr(obj, 'name', None)
if name and name[0] != '<' and name[-1] != '>':
return os.path.basename(name) |
Required by Cookies handlers | def origin_req_host(self):
"""Required by Cookies handlers
"""
if self.history:
return self.history[0].request.origin_req_host
else:
return scheme_host_port(self.url)[1] |
The bytes representation of this :class:`HttpRequest`.
Called by :class:`HttpResponse` when it needs to encode this
:class:`HttpRequest` before sending it to the HTTP resource. | def encode(self):
"""The bytes representation of this :class:`HttpRequest`.
Called by :class:`HttpResponse` when it needs to encode this
:class:`HttpRequest` before sending it to the HTTP resource.
"""
# Call body before fist_line in case the query is changes.
first_line... |
Retrieve ``header_name`` from this request headers. | def get_header(self, header_name, default=None):
"""Retrieve ``header_name`` from this request headers.
"""
return self.headers.get(
header_name, self.unredirected_headers.get(header_name, default)) |
Remove ``header_name`` from this request. | def remove_header(self, header_name):
"""Remove ``header_name`` from this request.
"""
val1 = self.headers.pop(header_name, None)
val2 = self.unredirected_headers.pop(header_name, None)
return val1 or val2 |
A raw asynchronous Http response | def raw(self):
"""A raw asynchronous Http response
"""
if self._raw is None:
self._raw = HttpStream(self)
return self._raw |
Returns the parsed header links of the response, if any | def links(self):
"""Returns the parsed header links of the response, if any
"""
headers = self.headers or {}
header = headers.get('link')
li = {}
if header:
links = parse_header_links(header)
for link in links:
key = link.get('rel')... |
Decode content as a string. | def text(self):
"""Decode content as a string.
"""
data = self.content
return data.decode(self.encoding or 'utf-8') if data else '' |
Return the best possible representation of the response body. | def decode_content(self):
"""Return the best possible representation of the response body.
"""
ct = self.headers.get('content-type')
if ct:
ct, options = parse_options_header(ct)
charset = options.get('charset')
if ct in JSON_CONTENT_TYPES:
... |
Raises stored :class:`HTTPError` or :class:`URLError`, if occurred. | def raise_for_status(self):
"""Raises stored :class:`HTTPError` or :class:`URLError`, if occurred.
"""
if not self.ok:
reason = self.reason or 'No response from %s' % self.url
if not self.status_code:
raise HttpConnectionError(reason, response=self)
... |
Constructs and sends a request to a remote server.
It returns a :class:`.Future` which results in a
:class:`.HttpResponse` object.
:param method: request method for the :class:`HttpRequest`.
:param url: URL for the :class:`HttpRequest`.
:param params: optional parameters for th... | def request(self, method, url, **params):
"""Constructs and sends a request to a remote server.
It returns a :class:`.Future` which results in a
:class:`.HttpResponse` object.
:param method: request method for the :class:`HttpRequest`.
:param url: URL for the :class:`HttpReques... |
Close all connections | def close(self):
"""Close all connections
"""
waiters = []
for p in self.connection_pools.values():
waiters.append(p.close())
self.connection_pools.clear()
return asyncio.gather(*waiters, loop=self._loop) |
Create a SSL context object.
This method should not be called by from user code | def ssl_context(self, verify=True, cert_reqs=None,
check_hostname=False, certfile=None, keyfile=None,
cafile=None, capath=None, cadata=None, **kw):
"""Create a SSL context object.
This method should not be called by from user code
"""
assert ssl, ... |
Create a tunnel connection | async def create_tunnel_connection(self, req):
"""Create a tunnel connection
"""
tunnel_address = req.tunnel_address
connection = await self.create_connection(tunnel_address)
response = connection.current_consumer()
for event in response.events().values():
eve... |
Fetch an :class:`Application` associated with ``name`` if available.
This function may return an :ref:`asynchronous component <coroutine>`.
The application name is set during initialisation. Check the
:attr:`Configurator.name` attribute for more information. | def get_application(name):
"""Fetch an :class:`Application` associated with ``name`` if available.
This function may return an :ref:`asynchronous component <coroutine>`.
The application name is set during initialisation. Check the
:attr:`Configurator.name` attribute for more information.
"""
ac... |
Root directory of this :class:`Configurator`.
Evaluated from the :attr:`script` attribute. | def root_dir(self):
"""Root directory of this :class:`Configurator`.
Evaluated from the :attr:`script` attribute.
"""
if self.cfg.script:
return os.path.dirname(self.cfg.script) |
Called during initialisation to obtain the ``script`` name.
If ``script`` does not evaluate to ``True`` it is evaluated from
the ``__main__`` import. Returns the real path of the python
script which runs the application. | def python_path(self, script):
"""Called during initialisation to obtain the ``script`` name.
If ``script`` does not evaluate to ``True`` it is evaluated from
the ``__main__`` import. Returns the real path of the python
script which runs the application.
"""
if not scrip... |
Load the application configuration from a file and/or
from the command line.
Called during application initialisation. The parameters
overriding order is the following:
* default parameters.
* the key-valued params passed in the initialisation.
* the parameters in the o... | def load_config(self):
"""Load the application configuration from a file and/or
from the command line.
Called during application initialisation. The parameters
overriding order is the following:
* default parameters.
* the key-valued params passed in the initialisation.... |
Invoked the application callable method and start
the ``arbiter`` if it wasn't already started.
It returns a :class:`~asyncio.Future` called back once the
application/applications are running. It returns ``None`` if
called more than once. | def start(self, exit=True):
"""Invoked the application callable method and start
the ``arbiter`` if it wasn't already started.
It returns a :class:`~asyncio.Future` called back once the
application/applications are running. It returns ``None`` if
called more than once.
"... |
Create a new :class:`.Config` container.
Invoked during initialisation, it overrides defaults
with ``params`` and apply the ``prefix`` to non global
settings. | def create_config(cls, params, prefix=None, name=None):
"""Create a new :class:`.Config` container.
Invoked during initialisation, it overrides defaults
with ``params`` and apply the ``prefix`` to non global
settings.
"""
if isinstance(cls.cfg, Config):
cfg =... |
Stop the application | def stop(self, actor=None):
"""Stop the application
"""
if actor is None:
actor = get_actor()
if actor and actor.is_arbiter():
monitor = actor.get_actor(self.name)
if monitor:
return monitor.stop()
raise RuntimeError('Cannot sto... |
List of :class:`Application` for this :class:`MultiApp`.
The list is lazily loaded from the :meth:`build` method. | def apps(self):
"""List of :class:`Application` for this :class:`MultiApp`.
The list is lazily loaded from the :meth:`build` method.
"""
if self._apps is None:
# Add modified settings values to the list of cfg params
self.cfg.params.update(((s.name, s.value) for ... |
Invoke this method in the :meth:`build` method as many times
as the number of :class:`Application` required by this
:class:`MultiApp`.
:param App: an :class:`Application` class.
:param prefix: The prefix to use for the application,
the prefix is appended to
the a... | def new_app(self, App, prefix=None, callable=None, **params):
"""Invoke this method in the :meth:`build` method as many times
as the number of :class:`Application` required by this
:class:`MultiApp`.
:param App: an :class:`Application` class.
:param prefix: The prefix to use for... |
set user and group of workers processes | def set_owner_process(uid, gid):
""" set user and group of workers processes """
if gid:
try:
os.setgid(gid)
except OverflowError:
# versions of python < 2.6.2 don't manage unsigned int for
# groups like on osx or fedora
os.setgid(-ctypes.c_int(-gi... |
\
Standard daemonization of a process.
http://www.svbug.com/documentation/comp.unix.programmer-FAQ/faq_2.html#SEC16 | def daemonize(enable_stdio_inheritance=False,
auto_close_fds=True,
keep_fds=None): # pragma nocover
"""\
Standard daemonization of a process.
http://www.svbug.com/documentation/comp.unix.programmer-FAQ/faq_2.html#SEC16
"""
if os.fork():
os._exit(0)
os.set... |
Convert *s* into bytes | def to_bytes(s, encoding=None, errors=None):
'''Convert *s* into bytes'''
if not isinstance(s, bytes):
return ('%s' % s).encode(encoding or 'utf-8', errors or 'strict')
elif not encoding or encoding == 'utf-8':
return s
else:
d = s.decode('utf-8')
return d.encode(encoding... |
Inverse of to_bytes | def to_string(s, encoding=None, errors='strict'):
"""Inverse of to_bytes"""
if isinstance(s, bytes):
return s.decode(encoding or 'utf-8', errors)
elif not isinstance(s, str):
return str(s)
else:
return s |
Wait for a possible asynchronous value to complete. | def wait(value, must_be_child=False):
'''Wait for a possible asynchronous value to complete.
'''
current = getcurrent()
parent = current.parent
if must_be_child and not parent:
raise MustBeInChildGreenlet('Cannot wait on main greenlet')
return parent.switch(value) if parent else value |
Decorator to run a ``callable`` on a new greenlet.
A ``callable`` decorated with this decorator returns a coroutine | def run_in_greenlet(callable):
"""Decorator to run a ``callable`` on a new greenlet.
A ``callable`` decorated with this decorator returns a coroutine
"""
@wraps(callable)
async def _(*args, **kwargs):
green = greenlet(callable)
# switch to the new greenlet
result = green.swi... |
Build response, add headers | def build_response(content, code=200):
"""Build response, add headers"""
response = make_response( jsonify(content), content['code'] )
response.headers['Access-Control-Allow-Origin'] = '*'
response.headers['Access-Control-Allow-Headers'] = \
'Origin, X-Requested-With, Content-Type, Accept, A... |
return executed sql result to client.
post data format:
{"options": ['all', 'last', 'first', 'format'], "sql_raw": "raw sql ..."}
Returns:
sql result. | def post(self):
'''return executed sql result to client.
post data format:
{"options": ['all', 'last', 'first', 'format'], "sql_raw": "raw sql ..."}
Returns:
sql result.
'''
## format sql
data = request.get_json()
options, sql_raw = dat... |
Send an object to storage[redis]. key is the obj name,
value is the serialized object[a dict most of the time]
Args:
obj: unserialized-obj need persistent in storage, currently using redis.
the object maybe [pandas.DataFrame, matplotlib.plt.plot, dict];
key: option, key to store in... | def sender(obj, key, value="", meta={}, force=True):
"""Send an object to storage[redis]. key is the obj name,
value is the serialized object[a dict most of the time]
Args:
obj: unserialized-obj need persistent in storage, currently using redis.
the object maybe [pandas.DataFrame, matp... |
Get dashboard meta info from in page `page` and page size is `size`.
Args:
page: page number.
size: size number.
Returns:
list of dict containing the dash_id and accordingly meta info.
maybe empty list [] when page * size > total dashes in db. that's rea... | def get(self, page=0, size=10):
"""Get dashboard meta info from in page `page` and page size is `size`.
Args:
page: page number.
size: size number.
Returns:
list of dict containing the dash_id and accordingly meta info.
maybe empty list [] when p... |
Get key list in storage. | def get(self):
"""Get key list in storage.
"""
keys = r_kv.keys()
keys.sort()
return build_response(dict(data=keys, code=200)) |
Get a key-value from storage according to the key name. | def get(self, key):
"""Get a key-value from storage according to the key name.
"""
data = r_kv.get(key)
# data = json.dumps(data) if isinstance(data, str) else data
# data = json.loads(data) if data else {}
return build_response(dict(data=data, code=200)) |
Just return the dashboard id in the rendering html.
JS will do other work [ajax and rendering] according to the dash_id.
Args:
dash_id: dashboard id.
Returns:
rendered html. | def get(self, dash_id):
"""Just return the dashboard id in the rendering html.
JS will do other work [ajax and rendering] according to the dash_id.
Args:
dash_id: dashboard id.
Returns:
rendered html.
"""
return make_response(render_template('da... |
Read dashboard content.
Args:
dash_id: dashboard id.
Returns:
A dict containing the content of that dashboard, not include the meta info. | def get(self, dash_id):
"""Read dashboard content.
Args:
dash_id: dashboard id.
Returns:
A dict containing the content of that dashboard, not include the meta info.
"""
data = json.loads(r_db.hmget(config.DASH_CONTENT_KEY, dash_id)[0])
return bui... |
Update a dash meta and content, return updated dash content.
Args:
dash_id: dashboard id.
Returns:
A dict containing the updated content of that dashboard, not include the meta info. | def put(self, dash_id=0):
"""Update a dash meta and content, return updated dash content.
Args:
dash_id: dashboard id.
Returns:
A dict containing the updated content of that dashboard, not include the meta info.
"""
data = request.get_json()
upda... |
Delete a dash meta and content, return updated dash content.
Actually, just remove it to a specfied place in database.
Args:
dash_id: dashboard id.
Returns:
Redirect to home page. | def delete(self, dash_id):
"""Delete a dash meta and content, return updated dash content.
Actually, just remove it to a specfied place in database.
Args:
dash_id: dashboard id.
Returns:
Redirect to home page.
"""
removed_info = dict(
... |
Train an LSTM encoder-decoder squence-to-sequence model on Anki flashcards for international translation
>>> model = main('spa', n=400, epochs=3, batch_size=128, num_neurons=32)
Train on 360 samples, validate on 40 samples
Epoch 1/3
...
>>> len(model.get_weights())
8
# 64 common characters... | def main(
lang='deu', n=900, epochs=50, batch_size=64, num_neurons=256,
encoder_input_data=None,
decoder_input_data=None,
decoder_target_data=None,
checkpoint_dir=os.path.join(BIGDATA_PATH, 'checkpoints'),
):
""" Train an LSTM encoder-decoder squence-to-sequence model... |
r"""
>>> tablify(range(3), range(10, 13))
[[0, 10], [1, 11], [2, 12]] | def tablify(*args):
r"""
>>> tablify(range(3), range(10, 13))
[[0, 10], [1, 11], [2, 12]]
"""
table = []
args = [listify(arg) for arg in args]
for row in zip(*args):
r = []
for x in row:
r += listify(x)
table += [r]
return table
return [sum([listif... |
Compute the global energy for the current joint state of all nodes
>>> q11_4 = BoltzmanMachine(bv=[0., 0.], bh=[-2.], Whh=np.zeros((1, 1)), Wvv=np.zeros((2, 2)), Wvh=[[3.], [-1.]])
>>> q11_4.configurations()
>>> v1v2h = product([0, 1], [0, 1], [0, 1])
>>> E = np.array([q11_4.energy(v=x... | def energy(self, v, h=None):
"""Compute the global energy for the current joint state of all nodes
>>> q11_4 = BoltzmanMachine(bv=[0., 0.], bh=[-2.], Whh=np.zeros((1, 1)), Wvv=np.zeros((2, 2)), Wvh=[[3.], [-1.]])
>>> q11_4.configurations()
>>> v1v2h = product([0, 1], [0, 1], [0, 1])
... |
r""" Compute the global energy for the current joint state of all nodes
- sum(s[i] * b[i]) - sum([s[i]*s[j]*W[i,j] for (i, j) in product(range(N), range(N)) if i<j)])
E = − ∑ s i b i − ∑
i i< j
s i s j w ij | def energy(self):
r""" Compute the global energy for the current joint state of all nodes
- sum(s[i] * b[i]) - sum([s[i]*s[j]*W[i,j] for (i, j) in product(range(N), range(N)) if i<j)])
E = − ∑ s i b i − ∑
i i< j
s i s j w ij
"""
s, b, W, N = self.state, self.b, ... |
like compiled_re.match() but returns True or False | def ismatch(self, s):
""" like compiled_re.match() but returns True or False """
if self._ismatchfun(s) and self._compiled_pattern.match(s):
return True
return False |
Replace all occurrences of rendered from_template in text with `template` rendered from each match.groupdict()
TODO: from_template
>>> translator = HyperlinkStyleCorrector()
>>> adoc = 'See http://totalgood.com[Total Good] about that.'
>>> translator.replace(adoc, '{scheme_type}s://',... | def replace(self, text, to_template='{name} ({url})', from_template=None,
name_matcher=Matcher(looks_like_name), url_matcher=Matcher(r'.*[^:]+$')):
""" Replace all occurrences of rendered from_template in text with `template` rendered from each match.groupdict()
TODO: from_template
... |
Translate hyperinks into printable book style for Manning Publishing
>>> translator = HyperlinkStyleCorrector()
>>> adoc = 'See http://totalgood.com[Total Good] about that.'
>>> translator.translate(adoc)
'See Total Good (http://totalgood.com) about that.' | def translate(self, text, to_template='{name} ({url})', from_template=None, name_matcher=None, url_matcher=None):
""" Translate hyperinks into printable book style for Manning Publishing
>>> translator = HyperlinkStyleCorrector()
>>> adoc = 'See http://totalgood.com[Total Good] about that.'
... |
Parse the state transition graph for a set of dialog-definition tables to find an fix deadends | def main(dialogpath=None):
""" Parse the state transition graph for a set of dialog-definition tables to find an fix deadends """
if dialogpath is None:
args = parse_args()
dialogpath = os.path.abspath(os.path.expanduser(args.dialogpath))
else:
dialogpath = os.path.abspath(os.path.ex... |
Translates the dialog to a list of lists of utterances. In the first
list each item holds subsequent utterances from the same user. The second level
list holds the individual utterances.
:param dialog_filename:
:return: | def translate_dialog_to_lists(dialog_filename):
"""
Translates the dialog to a list of lists of utterances. In the first
list each item holds subsequent utterances from the same user. The second level
list holds the individual utterances.
:param dialog_filename:
:return:
"""
dialog_file... |
Sample multiple random utterances from the whole corpus.
:param candidate_dialog_paths:
:param rng:
:param utterances_num: number of utterances to generate
:param min_turn: minimal index of turn that the utterance is selected from
:return: | def get_random_utterances_from_corpus(candidate_dialog_paths, rng, utterances_num=9, min_turn=3, max_turn=20):
"""
Sample multiple random utterances from the whole corpus.
:param candidate_dialog_paths:
:param rng:
:param utterances_num: number of utterances to generate
:param min_turn: minimal ... |
Translates the whole dialog (list of lists) to a string
:param dialog:
:return: | def dialog_turns_to_string(dialog):
"""
Translates the whole dialog (list of lists) to a string
:param dialog:
:return:
"""
# join utterances
turns_as_strings = map(singe_user_utterances_to_string, dialog)
# join turns
return "".join(map(lambda x: x + " " + end_of_turn_symbol + " ", ... |
Samples random context from a dialog. Contexts are uniformly sampled from the whole dialog.
:param dialog:
:param rng:
:return: context, index of next utterance that follows the context | def create_random_context(dialog, rng, minimum_context_length=2, max_context_length=20):
"""
Samples random context from a dialog. Contexts are uniformly sampled from the whole dialog.
:param dialog:
:param rng:
:return: context, index of next utterance that follows the context
"""
# sample ... |
Creates a single example for training set.
:param context_dialog_path:
:param candidate_dialog_paths:
:param rng:
:param positive_probability:
:return: | def create_single_dialog_train_example(context_dialog_path, candidate_dialog_paths, rng, positive_probability,
minimum_context_length=2, max_context_length=20):
"""
Creates a single example for training set.
:param context_dialog_path:
:param candidate_dialog_paths... |
Creates single training example.
:param candidate_dialog_paths:
:param rng:
:param positive_probability: probability of selecting positive training example
:return: | def create_examples_train(candidate_dialog_paths, rng, positive_probability=0.5, max_context_length=20):
"""
Creates single training example.
:param candidate_dialog_paths:
:param rng:
:param positive_probability: probability of selecting positive training example
:return:
"""
i = 0
... |
Creates a list of training examples from a list of dialogs and function that transforms a dialog to an example.
:param candidate_dialog_paths:
:param creator_function:
:return: | def create_examples(candidate_dialog_paths, examples_num, creator_function):
"""
Creates a list of training examples from a list of dialogs and function that transforms a dialog to an example.
:param candidate_dialog_paths:
:param creator_function:
:return:
"""
i = 0
examples = []
un... |
Converts CSV file with comma separated paths to filesystem paths.
:param csv_file:
:return: | def convert_csv_with_dialog_paths(csv_file):
"""
Converts CSV file with comma separated paths to filesystem paths.
:param csv_file:
:return:
"""
def convert_line_to_path(line):
file, dir = map(lambda x: x.strip(), line.split(","))
return os.path.join(dir, file)
return map(co... |
Download and unpack dialogs if necessary. | def prepare_data_maybe_download(directory):
"""
Download and unpack dialogs if necessary.
"""
filename = 'ubuntu_dialogs.tgz'
url = 'http://cs.mcgill.ca/~jpineau/datasets/ubuntu-corpus-1.0/ubuntu_dialogs.tgz'
dialogs_path = os.path.join(directory, 'dialogs')
# test it there are some dialogs... |
Fibonacci example function
Args:
n (int): integer
Returns:
int: n-th Fibonacci number | def fib(n):
"""Fibonacci example function
Args:
n (int): integer
Returns:
int: n-th Fibonacci number
"""
assert n > 0
a, b = 1, 1
for i in range(n - 1):
a, b = b, a + b
return a |
Parse command line parameters
Args:
args ([str]): command line parameters as list of strings
Returns:
:obj:`argparse.Namespace`: command line parameters namespace | def parse_args(args):
"""Parse command line parameters
Args:
args ([str]): command line parameters as list of strings
Returns:
:obj:`argparse.Namespace`: command line parameters namespace
"""
parser = argparse.ArgumentParser(
description="Just a Fibonnaci demonstration")
pa... |
Setup basic logging
Args:
loglevel (int): minimum loglevel for emitting messages | def setup_logging(loglevel):
"""Setup basic logging
Args:
loglevel (int): minimum loglevel for emitting messages
"""
logformat = "[%(asctime)s] %(levelname)s:%(name)s:%(message)s"
logging.basicConfig(level=loglevel, stream=sys.stdout,
format=logformat, datefmt="%Y-%m-%... |
Main entry point allowing external calls
Args:
args ([str]): command line parameter list | def main(args):
"""Main entry point allowing external calls
Args:
args ([str]): command line parameter list
"""
args = parse_args(args)
setup_logging(args.loglevel)
_logger.debug("Starting crazy calculations...")
print("The {}-th Fibonacci number is {}".format(args.n, fib(args.n)))
... |
Plot the correlation coefficient for various exponential scalings of input features
>>> np.random.seed(314159)
>>> df = pd.DataFrame()
>>> df['output'] = np.random.randn(1000)
>>> df['x10'] = df.output * 10
>>> df['sq'] = df.output ** 2
>>> df['sqrt'] = df.output ** .5
>>> optimize_feature_... | def optimize_feature_power(df, output_column_name=None, exponents=[2., 1., .8, .5, .25, .1, .01]):
""" Plot the correlation coefficient for various exponential scalings of input features
>>> np.random.seed(314159)
>>> df = pd.DataFrame()
>>> df['output'] = np.random.randn(1000)
>>> df['x10'] = df.o... |
Sample vectors in X, preferring edge cases and vectors farthest from other vectors in sample set | def representative_sample(X, num_samples, save=False):
"""Sample vectors in X, preferring edge cases and vectors farthest from other vectors in sample set
"""
X = X.values if hasattr(X, 'values') else np.array(X)
N, M = X.shape
rownums = np.arange(N)
np.random.shuffle(rownums)
idx = Annoy... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.