sentence1 stringlengths 52 3.87M | sentence2 stringlengths 1 47.2k | label stringclasses 1
value |
|---|---|---|
def secret(prompt=None, empty=False):
"""Prompt a string without echoing.
Parameters
----------
prompt : str, optional
Use an alternative prompt.
empty : bool, optional
Allow an empty response.
Returns
-------
str or None
A str if the user entered a non-empty st... | Prompt a string without echoing.
Parameters
----------
prompt : str, optional
Use an alternative prompt.
empty : bool, optional
Allow an empty response.
Returns
-------
str or None
A str if the user entered a non-empty string.
None if the user pressed only E... | entailment |
def string(prompt=None, empty=False):
"""Prompt a string.
Parameters
----------
prompt : str, optional
Use an alternative prompt.
empty : bool, optional
Allow an empty response.
Returns
-------
str or None
A str if the user entered a non-empty string.
No... | Prompt a string.
Parameters
----------
prompt : str, optional
Use an alternative prompt.
empty : bool, optional
Allow an empty response.
Returns
-------
str or None
A str if the user entered a non-empty string.
None if the user pressed only Enter and ``empty... | entailment |
def _get_cache_plus_key(self):
"""Return a cache region plus key."""
key = getattr(self, '_cache_key', self.key_from_query())
return self._cache.cache, key | Return a cache region plus key. | entailment |
def get_value(self, merge=True, createfunc=None,
expiration_time=None, ignore_expiration=False):
"""
Return the value from the cache for this query.
"""
cache, cache_key = self._get_cache_plus_key()
# ignore_expiration means, if the value is in the cache
... | Return the value from the cache for this query. | entailment |
def set_value(self, value):
"""Set the value in the cache for this query."""
cache, cache_key = self._get_cache_plus_key()
cache.set(cache_key, value) | Set the value in the cache for this query. | entailment |
def key_from_query(self, qualifier=None):
"""
Given a Query, create a cache key.
There are many approaches to this; here we use the simplest, which is
to create an md5 hash of the text of the SQL statement, combined with
stringified versions of all the bound parameters within it... | Given a Query, create a cache key.
There are many approaches to this; here we use the simplest, which is
to create an md5 hash of the text of the SQL statement, combined with
stringified versions of all the bound parameters within it.
There's a bit of a performance hit with compiling o... | entailment |
def process_query_conditionally(self, query):
"""
Process a Query that is used within a lazy loader.
(the process_query_conditionally() method is a SQLAlchemy
hook invoked only within lazyload.)
"""
if query._current_path:
mapper, prop = query._current_path[-... | Process a Query that is used within a lazy loader.
(the process_query_conditionally() method is a SQLAlchemy
hook invoked only within lazyload.) | entailment |
def fit(self, t, y, dy=1, presorted=False):
"""Fit the smoother
Parameters
----------
t : array_like
time locations of the points to smooth
y : array_like
y locations of the points to smooth
dy : array_like or float (default = 1)
Error... | Fit the smoother
Parameters
----------
t : array_like
time locations of the points to smooth
y : array_like
y locations of the points to smooth
dy : array_like or float (default = 1)
Errors in the y values
presorted : bool (default = F... | entailment |
def predict(self, t):
"""Predict the smoothed function value at time t
Parameters
----------
t : array_like
Times at which to predict the result
Returns
-------
y : ndarray
Smoothed values at time t
"""
t = np.asarray(t)
... | Predict the smoothed function value at time t
Parameters
----------
t : array_like
Times at which to predict the result
Returns
-------
y : ndarray
Smoothed values at time t | entailment |
def cv_residuals(self, cv=True):
"""Return the residuals of the cross-validation for the fit data"""
vals = self.cv_values(cv)
return (self.y - vals) / self.dy | Return the residuals of the cross-validation for the fit data | entailment |
def cv_error(self, cv=True, skip_endpoints=True):
"""Return the sum of cross-validation residuals for the input data"""
resids = self.cv_residuals(cv)
if skip_endpoints:
resids = resids[1:-1]
return np.mean(abs(resids)) | Return the sum of cross-validation residuals for the input data | entailment |
def arcfour(key, csbN=1):
'''Return a generator for the ARCFOUR/RC4 pseudorandom keystream for the
key provided. Keys should be byte strings or sequences of ints.'''
if isinstance(key, str):
key = [ord(c) for c in key]
s = range(256)
j = 0
for n in range(csbN):
for i in range(256):
j = (j + s[i] + key[... | Return a generator for the ARCFOUR/RC4 pseudorandom keystream for the
key provided. Keys should be byte strings or sequences of ints. | entailment |
def arcfour_drop(key, n=3072):
'''Return a generator for the RC4-drop pseudorandom keystream given by
the key and number of bytes to drop passed as arguments. Dropped bytes
default to the more conservative 3072, NOT the SCAN default of 768.'''
af = arcfour(key)
[af.next() for c in range(n)]
return af | Return a generator for the RC4-drop pseudorandom keystream given by
the key and number of bytes to drop passed as arguments. Dropped bytes
default to the more conservative 3072, NOT the SCAN default of 768. | entailment |
def resolve_ssl_protocol_version(version=None):
"""
Look up an SSL protocol version by name. If *version* is not specified, then
the strongest protocol available will be returned.
:param str version: The name of the version to look up.
:return: A protocol constant from the :py:mod:`ssl` module.
:rtype: int
"""
... | Look up an SSL protocol version by name. If *version* is not specified, then
the strongest protocol available will be returned.
:param str version: The name of the version to look up.
:return: A protocol constant from the :py:mod:`ssl` module.
:rtype: int | entailment |
def build_server_from_argparser(description=None, server_klass=None, handler_klass=None):
"""
Build a server from command line arguments. If a ServerClass or
HandlerClass is specified, then the object must inherit from the
corresponding AdvancedHTTPServer base class.
:param str description: Description string to ... | Build a server from command line arguments. If a ServerClass or
HandlerClass is specified, then the object must inherit from the
corresponding AdvancedHTTPServer base class.
:param str description: Description string to be passed to the argument parser.
:param server_klass: Alternative server class to use.
:type ... | entailment |
def build_server_from_config(config, section_name, server_klass=None, handler_klass=None):
"""
Build a server from a provided :py:class:`configparser.ConfigParser`
instance. If a ServerClass or HandlerClass is specified, then the
object must inherit from the corresponding AdvancedHTTPServer base
class.
:param co... | Build a server from a provided :py:class:`configparser.ConfigParser`
instance. If a ServerClass or HandlerClass is specified, then the
object must inherit from the corresponding AdvancedHTTPServer base
class.
:param config: Configuration to retrieve settings from.
:type config: :py:class:`configparser.ConfigParse... | entailment |
def set_serializer(self, serializer_name, compression=None):
"""
Configure the serializer to use for communication with the server.
The serializer specified must be valid and in the
:py:data:`.g_serializer_drivers` map.
:param str serializer_name: The name of the serializer to use.
:param str compression: ... | Configure the serializer to use for communication with the server.
The serializer specified must be valid and in the
:py:data:`.g_serializer_drivers` map.
:param str serializer_name: The name of the serializer to use.
:param str compression: The name of a compression library to use. | entailment |
def reconnect(self):
"""Reconnect to the remote server."""
self.lock.acquire()
if self.use_ssl:
self.client = http.client.HTTPSConnection(self.host, self.port, context=self.ssl_context)
else:
self.client = http.client.HTTPConnection(self.host, self.port)
self.lock.release() | Reconnect to the remote server. | entailment |
def call(self, method, *args, **kwargs):
"""
Issue a call to the remote end point to execute the specified
procedure.
:param str method: The name of the remote procedure to execute.
:return: The return value from the remote function.
"""
if kwargs:
options = self.encode(dict(args=args, kwargs=kwargs))... | Issue a call to the remote end point to execute the specified
procedure.
:param str method: The name of the remote procedure to execute.
:return: The return value from the remote function. | entailment |
def cache_call(self, method, *options):
"""
Call a remote method and store the result locally. Subsequent
calls to the same method with the same arguments will return the
cached result without invoking the remote procedure. Cached results are
kept indefinitely and must be manually refreshed with a call to
:... | Call a remote method and store the result locally. Subsequent
calls to the same method with the same arguments will return the
cached result without invoking the remote procedure. Cached results are
kept indefinitely and must be manually refreshed with a call to
:py:meth:`.cache_call_refresh`.
:param str met... | entailment |
def cache_call_refresh(self, method, *options):
"""
Call a remote method and update the local cache with the result
if it already existed.
:param str method: The name of the remote procedure to execute.
:return: The return value from the remote function.
"""
options_hash = self.encode(options)
if len(o... | Call a remote method and update the local cache with the result
if it already existed.
:param str method: The name of the remote procedure to execute.
:return: The return value from the remote function. | entailment |
def cache_clear(self):
"""Purge the local store of all cached function information."""
with self.cache_lock:
cursor = self.cache_db.cursor()
cursor.execute('DELETE FROM cache')
self.cache_db.commit()
self.logger.info('the RPC cache has been purged')
return | Purge the local store of all cached function information. | entailment |
def respond_file(self, file_path, attachment=False, query=None):
"""
Respond to the client by serving a file, either directly or as
an attachment.
:param str file_path: The path to the file to serve, this does not need to be in the web root.
:param bool attachment: Whether to serve the file as a download by ... | Respond to the client by serving a file, either directly or as
an attachment.
:param str file_path: The path to the file to serve, this does not need to be in the web root.
:param bool attachment: Whether to serve the file as a download by setting the Content-Disposition header. | entailment |
def respond_list_directory(self, dir_path, query=None):
"""
Respond to the client with an HTML page listing the contents of
the specified directory.
:param str dir_path: The path of the directory to list the contents of.
"""
del query
try:
dir_contents = os.listdir(dir_path)
except os.error:
self... | Respond to the client with an HTML page listing the contents of
the specified directory.
:param str dir_path: The path of the directory to list the contents of. | entailment |
def respond_redirect(self, location='/'):
"""
Respond to the client with a 301 message and redirect them with
a Location header.
:param str location: The new location to redirect the client to.
"""
self.send_response(301)
self.send_header('Content-Length', 0)
self.send_header('Location', location)
se... | Respond to the client with a 301 message and redirect them with
a Location header.
:param str location: The new location to redirect the client to. | entailment |
def respond_server_error(self, status=None, status_line=None, message=None):
"""
Handle an internal server error, logging a traceback if executed
within an exception handler.
:param int status: The status code to respond to the client with.
:param str status_line: The status message to respond to the client ... | Handle an internal server error, logging a traceback if executed
within an exception handler.
:param int status: The status code to respond to the client with.
:param str status_line: The status message to respond to the client with.
:param str message: The body of the response that is sent to the client. | entailment |
def respond_unauthorized(self, request_authentication=False):
"""
Respond to the client that the request is unauthorized.
:param bool request_authentication: Whether to request basic authentication information by sending a WWW-Authenticate header.
"""
headers = {}
if request_authentication:
headers['WWW... | Respond to the client that the request is unauthorized.
:param bool request_authentication: Whether to request basic authentication information by sending a WWW-Authenticate header. | entailment |
def dispatch_handler(self, query=None):
"""
Dispatch functions based on the established handler_map. It is
generally not necessary to override this function and doing so
will prevent any handlers from being executed. This function is
executed automatically when requests of either GET, HEAD, or POST
are rece... | Dispatch functions based on the established handler_map. It is
generally not necessary to override this function and doing so
will prevent any handlers from being executed. This function is
executed automatically when requests of either GET, HEAD, or POST
are received.
:param dict query: Parsed query paramet... | entailment |
def guess_mime_type(self, path):
"""
Guess an appropriate MIME type based on the extension of the
provided path.
:param str path: The of the file to analyze.
:return: The guessed MIME type of the default if non are found.
:rtype: str
"""
_, ext = posixpath.splitext(path)
if ext in self.extensions_map... | Guess an appropriate MIME type based on the extension of the
provided path.
:param str path: The of the file to analyze.
:return: The guessed MIME type of the default if non are found.
:rtype: str | entailment |
def check_authorization(self):
"""
Check for the presence of a basic auth Authorization header and
if the credentials contained within in are valid.
:return: Whether or not the credentials are valid.
:rtype: bool
"""
try:
store = self.__config.get('basic_auth')
if store is None:
return True
... | Check for the presence of a basic auth Authorization header and
if the credentials contained within in are valid.
:return: Whether or not the credentials are valid.
:rtype: bool | entailment |
def cookie_get(self, name):
"""
Check for a cookie value by name.
:param str name: Name of the cookie value to retreive.
:return: Returns the cookie value if it's set or None if it's not found.
"""
if not hasattr(self, 'cookies'):
return None
if self.cookies.get(name):
return self.cookies.get(name)... | Check for a cookie value by name.
:param str name: Name of the cookie value to retreive.
:return: Returns the cookie value if it's set or None if it's not found. | entailment |
def cookie_set(self, name, value):
"""
Set the value of a client cookie. This can only be called while
headers can be sent.
:param str name: The name of the cookie value to set.
:param str value: The value of the cookie to set.
"""
if not self.headers_active:
raise RuntimeError('headers have already b... | Set the value of a client cookie. This can only be called while
headers can be sent.
:param str name: The name of the cookie value to set.
:param str value: The value of the cookie to set. | entailment |
def get_content_type_charset(self, default='UTF-8'):
"""
Inspect the Content-Type header to retrieve the charset that the client
has specified.
:param str default: The default charset to return if none exists.
:return: The charset of the request.
:rtype: str
"""
encoding = default
header = self.heade... | Inspect the Content-Type header to retrieve the charset that the client
has specified.
:param str default: The default charset to return if none exists.
:return: The charset of the request.
:rtype: str | entailment |
def close(self):
"""
Close the web socket connection and stop processing results. If the
connection is still open, a WebSocket close message will be sent to the
peer.
"""
if not self.connected:
return
self.connected = False
if self.handler.wfile.closed:
return
if select.select([], [self.handler.... | Close the web socket connection and stop processing results. If the
connection is still open, a WebSocket close message will be sent to the
peer. | entailment |
def send_message(self, opcode, message):
"""
Send a message to the peer over the socket.
:param int opcode: The opcode for the message to send.
:param bytes message: The message data to send.
"""
if not isinstance(message, bytes):
message = message.encode('utf-8')
length = len(message)
if not select... | Send a message to the peer over the socket.
:param int opcode: The opcode for the message to send.
:param bytes message: The message data to send. | entailment |
def on_message(self, opcode, message):
"""
The primary dispatch function to handle incoming WebSocket messages.
:param int opcode: The opcode of the message that was received.
:param bytes message: The data contained within the message.
"""
self.logger.debug("processing {0} (opcode: 0x{1:02x}) message".for... | The primary dispatch function to handle incoming WebSocket messages.
:param int opcode: The opcode of the message that was received.
:param bytes message: The data contained within the message. | entailment |
def from_content_type(cls, content_type):
"""
Build a serializer object from a MIME Content-Type string.
:param str content_type: The Content-Type string to parse.
:return: A new serializer instance.
:rtype: :py:class:`.Serializer`
"""
name = content_type
options = {}
if ';' in content_type:
name,... | Build a serializer object from a MIME Content-Type string.
:param str content_type: The Content-Type string to parse.
:return: A new serializer instance.
:rtype: :py:class:`.Serializer` | entailment |
def dumps(self, data):
"""
Serialize a python data type for transmission or storage.
:param data: The python object to serialize.
:return: The serialized representation of the object.
:rtype: bytes
"""
data = g_serializer_drivers[self.name]['dumps'](data)
if sys.version_info[0] == 3 and isinstance(data... | Serialize a python data type for transmission or storage.
:param data: The python object to serialize.
:return: The serialized representation of the object.
:rtype: bytes | entailment |
def loads(self, data):
"""
Deserialize the data into it's original python object.
:param bytes data: The serialized object to load.
:return: The original python object.
"""
if not isinstance(data, bytes):
raise TypeError("loads() argument 1 must be bytes, not {0}".format(type(data).__name__))
if self.... | Deserialize the data into it's original python object.
:param bytes data: The serialized object to load.
:return: The original python object. | entailment |
def add_sni_cert(self, hostname, ssl_certfile=None, ssl_keyfile=None, ssl_version=None):
"""
Add an SSL certificate for a specific hostname as supported by SSL's
Server Name Indicator (SNI) extension. See :rfc:`3546` for more details
on SSL extensions. In order to use this method, the server instance must
hav... | Add an SSL certificate for a specific hostname as supported by SSL's
Server Name Indicator (SNI) extension. See :rfc:`3546` for more details
on SSL extensions. In order to use this method, the server instance must
have been initialized with at least one address configured for SSL.
.. warning::
This method ... | entailment |
def remove_sni_cert(self, hostname):
"""
Remove the SSL Server Name Indicator (SNI) certificate configuration for
the specified *hostname*.
.. warning::
This method will raise a :py:exc:`RuntimeError` if either the SNI
extension is not available in the :py:mod:`ssl` module or if SSL was
not enabled a... | Remove the SSL Server Name Indicator (SNI) certificate configuration for
the specified *hostname*.
.. warning::
This method will raise a :py:exc:`RuntimeError` if either the SNI
extension is not available in the :py:mod:`ssl` module or if SSL was
not enabled at initialization time through the use of argu... | entailment |
def sni_certs(self):
"""
.. versionadded:: 2.2.0
:return: Return a tuple of :py:class:`~.SSLSNICertificate` instances for each of the certificates that are configured.
:rtype: tuple
"""
if not g_ssl_has_server_sni or self._ssl_sni_entries is None:
return tuple()
return tuple(entry.certificate for entr... | .. versionadded:: 2.2.0
:return: Return a tuple of :py:class:`~.SSLSNICertificate` instances for each of the certificates that are configured.
:rtype: tuple | entailment |
def serve_forever(self, fork=False):
"""
Start handling requests. This method must be called and does not
return unless the :py:meth:`.shutdown` method is called from
another thread.
:param bool fork: Whether to fork or not before serving content.
:return: The child processes PID if *fork* is set to True.
... | Start handling requests. This method must be called and does not
return unless the :py:meth:`.shutdown` method is called from
another thread.
:param bool fork: Whether to fork or not before serving content.
:return: The child processes PID if *fork* is set to True.
:rtype: int | entailment |
def shutdown(self):
"""Shutdown the server and stop responding to requests."""
self.__should_stop.set()
if self.__server_thread == threading.current_thread():
self.__is_shutdown.set()
self.__is_running.clear()
else:
if self.__wakeup_fd is not None:
os.write(self.__wakeup_fd.write_fd, b'\x00')
se... | Shutdown the server and stop responding to requests. | entailment |
def auth_set(self, status):
"""
Enable or disable requiring authentication on all incoming requests.
:param bool status: Whether to enable or disable requiring authentication.
"""
if not bool(status):
self.__config['basic_auth'] = None
self.logger.info('basic authentication has been disabled')
else:
... | Enable or disable requiring authentication on all incoming requests.
:param bool status: Whether to enable or disable requiring authentication. | entailment |
def auth_delete_creds(self, username=None):
"""
Delete the credentials for a specific username if specified or all
stored credentials.
:param str username: The username of the credentials to delete.
"""
if not username:
self.__config['basic_auth'] = {}
self.logger.info('basic authentication database ... | Delete the credentials for a specific username if specified or all
stored credentials.
:param str username: The username of the credentials to delete. | entailment |
def auth_add_creds(self, username, password, pwtype='plain'):
"""
Add a valid set of credentials to be accepted for authentication.
Calling this function will automatically enable requiring
authentication. Passwords can be provided in either plaintext or
as a hash by specifying the hash type in the *pwtype* a... | Add a valid set of credentials to be accepted for authentication.
Calling this function will automatically enable requiring
authentication. Passwords can be provided in either plaintext or
as a hash by specifying the hash type in the *pwtype* argument.
:param str username: The username of the credentials to be... | entailment |
def setattr_context(obj, **kwargs):
"""
Context manager to temporarily change the values of object attributes
while executing a function.
Example
-------
>>> class Foo: pass
>>> f = Foo(); f.attr = 'hello'
>>> with setattr_context(f, attr='goodbye'):
... print(f.attr)
goodby... | Context manager to temporarily change the values of object attributes
while executing a function.
Example
-------
>>> class Foo: pass
>>> f = Foo(); f.attr = 'hello'
>>> with setattr_context(f, attr='goodbye'):
... print(f.attr)
goodbye
>>> print(f.attr)
hello | entailment |
def validate_inputs(*arrays, **kwargs):
"""Validate input arrays
This checks that
- Arrays are mutually broadcastable
- Broadcasted arrays are one-dimensional
Optionally, arrays are sorted according to the ``sort_by`` argument.
Parameters
----------
*args : ndarrays
All non-ke... | Validate input arrays
This checks that
- Arrays are mutually broadcastable
- Broadcasted arrays are one-dimensional
Optionally, arrays are sorted according to the ``sort_by`` argument.
Parameters
----------
*args : ndarrays
All non-keyword arguments are arrays which will be valida... | entailment |
def _prep_smooth(t, y, dy, span, t_out, span_out, period):
"""Private function to prepare & check variables for smooth utilities"""
# If period is provided, sort by phases. Otherwise sort by t
if period:
t = t % period
if t_out is not None:
t_out = t_out % period
t, y, dy =... | Private function to prepare & check variables for smooth utilities | entailment |
def moving_average_smooth(t, y, dy, span=None, cv=True,
t_out=None, span_out=None, period=None):
"""Perform a moving-average smooth of the data
Parameters
----------
t, y, dy : array_like
time, value, and error in value of the input data
span : array_like
t... | Perform a moving-average smooth of the data
Parameters
----------
t, y, dy : array_like
time, value, and error in value of the input data
span : array_like
the integer spans of the data
cv : boolean (default=True)
if True, treat the problem as a cross-validation, i.e. don't ... | entailment |
def linear_smooth(t, y, dy, span=None, cv=True,
t_out=None, span_out=None, period=None):
"""Perform a linear smooth of the data
Parameters
----------
t, y, dy : array_like
time, value, and error in value of the input data
span : array_like
the integer spans of the ... | Perform a linear smooth of the data
Parameters
----------
t, y, dy : array_like
time, value, and error in value of the input data
span : array_like
the integer spans of the data
cv : boolean (default=True)
if True, treat the problem as a cross-validation, i.e. don't use
... | entailment |
def multinterp(x, y, xquery, slow=False):
"""Multiple linear interpolations
Parameters
----------
x : array_like, shape=(N,)
sorted array of x values
y : array_like, shape=(N, M)
array of y values corresponding to each x value
xquery : array_like, shape=(M,)
array of que... | Multiple linear interpolations
Parameters
----------
x : array_like, shape=(N,)
sorted array of x values
y : array_like, shape=(N, M)
array of y values corresponding to each x value
xquery : array_like, shape=(M,)
array of query values
slow : boolean, default=False
... | entailment |
def _create_session(self, test_connection=False):
"""
Create a consulate.session object, and query for its leader to ensure
that the connection is made.
:param test_connection: call .leader() to ensure that the connection
is valid
:type test_connection: bool
... | Create a consulate.session object, and query for its leader to ensure
that the connection is made.
:param test_connection: call .leader() to ensure that the connection
is valid
:type test_connection: bool
:return consulate.Session instance | entailment |
def apply_remote_config(self, namespace=None):
"""
Applies all config values defined in consul's kv store to self.app.
There is no guarantee that these values will not be overwritten later
elsewhere.
:param namespace: kv namespace/directory. Defaults to
DEFAULT_... | Applies all config values defined in consul's kv store to self.app.
There is no guarantee that these values will not be overwritten later
elsewhere.
:param namespace: kv namespace/directory. Defaults to
DEFAULT_KV_NAMESPACE
:return: None | entailment |
def register_service(self, **kwargs):
"""
register this service with consul
kwargs passed to Consul.agent.service.register
"""
kwargs.setdefault('name', self.app.name)
self.session.agent.service.register(**kwargs) | register this service with consul
kwargs passed to Consul.agent.service.register | entailment |
def _resolve(self):
"""
Query the consul DNS server for the service IP and port
"""
endpoints = {}
r = self.resolver.query(self.service, 'SRV')
for rec in r.response.additional:
name = rec.name.to_text()
addr = rec.items[0].address
endp... | Query the consul DNS server for the service IP and port | entailment |
def request(self, method, endpoint, **kwargs):
"""
Proxy to requests.request
:param method: str formatted http method
:param endpoint: service endpoint
:param kwargs: kwargs passed directly to requests.request
:return:
"""
kwargs.setdefault('timeout', (1, ... | Proxy to requests.request
:param method: str formatted http method
:param endpoint: service endpoint
:param kwargs: kwargs passed directly to requests.request
:return: | entailment |
def with_retry_connections(max_tries=3, sleep=0.05):
"""
Decorator that wraps an entire function in a try/except clause. On
requests.exceptions.ConnectionError, will re-run the function code
until success or max_tries is reached.
:param max_tries: maximum number of attempts before giving up
:pa... | Decorator that wraps an entire function in a try/except clause. On
requests.exceptions.ConnectionError, will re-run the function code
until success or max_tries is reached.
:param max_tries: maximum number of attempts before giving up
:param sleep: time to sleep between tries, or None | entailment |
def crop(gens, seconds=5, cropper=None):
'''
Crop the generator to a finite number of frames
Return a generator which outputs the provided generator limited
to enough samples to produce seconds seconds of audio (default 5s)
at the provided frame rate.
'''
if hasattr(gens, "next"):
# single generator
gens = ... | Crop the generator to a finite number of frames
Return a generator which outputs the provided generator limited
to enough samples to produce seconds seconds of audio (default 5s)
at the provided frame rate. | entailment |
def crop_at_zero_crossing(gen, seconds=5, error=0.1):
'''
Crop the generator, ending at a zero-crossing
Crop the generator to produce approximately seconds seconds
(default 5s) of audio at the provided FRAME_RATE, attempting
to end the clip at a zero crossing point to avoid clicking.
'''
source = iter(gen)
... | Crop the generator, ending at a zero-crossing
Crop the generator to produce approximately seconds seconds
(default 5s) of audio at the provided FRAME_RATE, attempting
to end the clip at a zero crossing point to avoid clicking. | entailment |
def volume(gen, dB=0):
'''Change the volume of gen by dB decibles'''
if not hasattr(dB, 'next'):
# not a generator
scale = 10 ** (dB / 20.)
else:
def scale_gen():
while True:
yield 10 ** (next(dB) / 20.)
scale = scale_gen()
return envelope(gen, scale) | Change the volume of gen by dB decibles | entailment |
def mixer(inputs, mix=None):
'''
Mix `inputs` together based on `mix` tuple
`inputs` should be a tuple of *n* generators.
`mix` should be a tuple of *m* tuples, one per desired
output channel. Each of the *m* tuples should contain
*n* generators, corresponding to the time-sequence of
the desired mix levels f... | Mix `inputs` together based on `mix` tuple
`inputs` should be a tuple of *n* generators.
`mix` should be a tuple of *m* tuples, one per desired
output channel. Each of the *m* tuples should contain
*n* generators, corresponding to the time-sequence of
the desired mix levels for each of the *n* input channels.
... | entailment |
def channelize(gen, channels):
'''
Break multi-channel generator into one sub-generator per channel
Takes a generator producing n-tuples of samples and returns n generators,
each producing samples for a single channel.
Since multi-channel generators are the only reasonable way to synchronize samples
across chan... | Break multi-channel generator into one sub-generator per channel
Takes a generator producing n-tuples of samples and returns n generators,
each producing samples for a single channel.
Since multi-channel generators are the only reasonable way to synchronize samples
across channels, and the sampler functions only ... | entailment |
def file_is_seekable(f):
'''
Returns True if file `f` is seekable, and False if not
Useful to determine, for example, if `f` is STDOUT to
a pipe.
'''
try:
f.tell()
logger.info("File is seekable!")
except IOError, e:
if e.errno == errno.ESPIPE:
return False
else:
raise
return True | Returns True if file `f` is seekable, and False if not
Useful to determine, for example, if `f` is STDOUT to
a pipe. | entailment |
def sample(generator, min=-1, max=1, width=SAMPLE_WIDTH):
'''Convert audio waveform generator into packed sample generator.'''
# select signed char, short, or in based on sample width
fmt = { 1: '<B', 2: '<h', 4: '<i' }[width]
return (struct.pack(fmt, int(sample)) for sample in \
normalize(hard_clip(generator, m... | Convert audio waveform generator into packed sample generator. | entailment |
def sample_all(generators, *args, **kwargs):
'''Convert list of audio waveform generators into list of packed sample generators.'''
return [sample(gen, *args, **kwargs) for gen in generators] | Convert list of audio waveform generators into list of packed sample generators. | entailment |
def buffer(stream, buffer_size=BUFFER_SIZE):
'''
Buffer the generator into byte strings of buffer_size samples
Return a generator that outputs reasonably sized byte strings
containing buffer_size samples from the generator stream.
This allows us to outputing big chunks of the audio stream to
disk at once for ... | Buffer the generator into byte strings of buffer_size samples
Return a generator that outputs reasonably sized byte strings
containing buffer_size samples from the generator stream.
This allows us to outputing big chunks of the audio stream to
disk at once for faster writes. | entailment |
def wave_module_patched():
'''True if wave module can write data size of 0xFFFFFFFF, False otherwise.'''
f = StringIO()
w = wave.open(f, "wb")
w.setparams((1, 2, 44100, 0, "NONE", "no compression"))
patched = True
try:
w.setnframes((0xFFFFFFFF - 36) / w.getnchannels() / w.getsampwidth())
w._ensure_header_writ... | True if wave module can write data size of 0xFFFFFFFF, False otherwise. | entailment |
def cache_finite_samples(f):
'''Decorator to cache audio samples produced by the wrapped generator.'''
cache = {}
def wrap(*args):
key = FRAME_RATE, args
if key not in cache:
cache[key] = [sample for sample in f(*args)]
return (sample for sample in cache[key])
return wrap | Decorator to cache audio samples produced by the wrapped generator. | entailment |
def play(channels, blocking=True, raw_samples=False):
'''
Play the contents of the generator using PyAudio
Play to the system soundcard using PyAudio. PyAudio, an otherwise optional
depenency, must be installed for this feature to work.
'''
if not pyaudio_loaded:
raise Exception("Soundcard playback requires P... | Play the contents of the generator using PyAudio
Play to the system soundcard using PyAudio. PyAudio, an otherwise optional
depenency, must be installed for this feature to work. | entailment |
def windowed_sum_slow(arrays, span, t=None, indices=None, tpowers=0,
period=None, subtract_mid=False):
"""Compute the windowed sum of the given arrays.
This is a slow function, used primarily for testing and validation
of the faster version of ``windowed_sum()``
Parameters
--... | Compute the windowed sum of the given arrays.
This is a slow function, used primarily for testing and validation
of the faster version of ``windowed_sum()``
Parameters
----------
arrays : tuple of arrays
arrays to window
span : int or array of ints
The span to use for the sum a... | entailment |
def windowed_sum(arrays, span, t=None, indices=None, tpowers=0,
period=None, subtract_mid=False):
"""Compute the windowed sum of the given arrays.
Parameters
----------
arrays : tuple of arrays
arrays to window
span : int or array of ints
The span to use for the sum... | Compute the windowed sum of the given arrays.
Parameters
----------
arrays : tuple of arrays
arrays to window
span : int or array of ints
The span to use for the sum at each point. If array is provided,
it must be broadcastable with ``indices``
indices : array
the in... | entailment |
def _pad_arrays(t, arrays, indices, span, period):
"""Internal routine to pad arrays for periodic models."""
N = len(t)
if indices is None:
indices = np.arange(N)
pad_left = max(0, 0 - np.min(indices - span // 2))
pad_right = max(0, np.max(indices + span - span // 2) - (N - 1))
if pad_... | Internal routine to pad arrays for periodic models. | entailment |
def get_i2c_bus_numbers(glober = glob.glob):
"""Search all the available I2C devices in the system"""
res = []
for device in glober("/dev/i2c-*"):
r = re.match("/dev/i2c-([\d]){1,2}", device)
res.append(int(r.group(1)))
return res | Search all the available I2C devices in the system | entailment |
def get_led_register_from_name(self, name):
"""Parse the name for led number
:param name: attribute name, like: led_1
"""
res = re.match('^led_([0-9]{1,2})$', name)
if res is None:
raise AttributeError("Unknown attribute: '%s'" % name)
led_num = int(res.group... | Parse the name for led number
:param name: attribute name, like: led_1 | entailment |
def set_pwm(self, led_num, value):
"""Set PWM value for the specified LED
:param led_num: LED number (0-15)
:param value: the 12 bit value (0-4095)
"""
self.__check_range('led_number', led_num)
self.__check_range('led_value', value)
register_low = self.calc_led_... | Set PWM value for the specified LED
:param led_num: LED number (0-15)
:param value: the 12 bit value (0-4095) | entailment |
def get_pwm(self, led_num):
"""Generic getter for all LED PWM value"""
self.__check_range('led_number', led_num)
register_low = self.calc_led_register(led_num)
return self.__get_led_value(register_low) | Generic getter for all LED PWM value | entailment |
def sleep(self):
"""Send the controller to sleep"""
logger.debug("Sleep the controller")
self.write(Registers.MODE_1, self.mode_1 | (1 << Mode1.SLEEP)) | Send the controller to sleep | entailment |
def write(self, reg, value):
"""Write raw byte value to the specified register
:param reg: the register number (0-69, 250-255)
:param value: byte value
"""
# TODO: check reg: 0-69, 250-255
self.__check_range('register_value', value)
logger.debug("Write '%s' to re... | Write raw byte value to the specified register
:param reg: the register number (0-69, 250-255)
:param value: byte value | entailment |
def set_pwm_frequency(self, value):
"""Set the frequency for all PWM output
:param value: the frequency in Hz
"""
self.__check_range('pwm_frequency', value)
reg_val = self.calc_pre_scale(value)
logger.debug("Calculated prescale value is %s" % reg_val)
self.sleep(... | Set the frequency for all PWM output
:param value: the frequency in Hz | entailment |
def levenshtein_norm(source, target):
"""Calculates the normalized Levenshtein distance between two string
arguments. The result will be a float in the range [0.0, 1.0], with 1.0
signifying the biggest possible distance between strings with these lengths
"""
# Compute Levenshtein distance using hel... | Calculates the normalized Levenshtein distance between two string
arguments. The result will be a float in the range [0.0, 1.0], with 1.0
signifying the biggest possible distance between strings with these lengths | entailment |
def check_valid_color(color):
"""Check if the color provided by the user is valid.
If color is invalid the default is returned.
"""
if color in list(mcolors.CSS4_COLORS.keys()) + ["#4CB391"]:
logging.info("Nanoplotter: Valid color {}.".format(color))
return color
else:
loggi... | Check if the color provided by the user is valid.
If color is invalid the default is returned. | entailment |
def check_valid_format(figformat):
"""Check if the specified figure format is valid.
If format is invalid the default is returned.
Probably installation-dependent
"""
fig = plt.figure()
if figformat in list(fig.canvas.get_supported_filetypes().keys()):
logging.info("Nanoplotter: valid o... | Check if the specified figure format is valid.
If format is invalid the default is returned.
Probably installation-dependent | entailment |
def scatter(x, y, names, path, plots, color="#4CB391", figformat="png",
stat=None, log=False, minvalx=0, minvaly=0, title=None, plot_settings=None):
"""Create bivariate plots.
Create four types of bivariate plots of x vs y, containing marginal summaries
-A scatter plot with histograms on axes
... | Create bivariate plots.
Create four types of bivariate plots of x vs y, containing marginal summaries
-A scatter plot with histograms on axes
-A hexagonal binned plot with histograms on axes
-A kernel density plot with density curves on axes
-A pauvre-style plot using code from https://github.com/c... | entailment |
def contains_variance(arrays, names):
"""
Make sure both arrays for bivariate ("scatter") plot have a stddev > 0
"""
for ar, name in zip(arrays, names):
if np.std(ar) == 0:
sys.stderr.write(
"No variation in '{}', skipping bivariate plots.\n".format(name.lower()))
... | Make sure both arrays for bivariate ("scatter") plot have a stddev > 0 | entailment |
def length_plots(array, name, path, title=None, n50=None, color="#4CB391", figformat="png"):
"""Create histogram of normal and log transformed read lengths."""
logging.info("Nanoplotter: Creating length plots for {}.".format(name))
maxvalx = np.amax(array)
if n50:
logging.info("Nanoplotter: Usin... | Create histogram of normal and log transformed read lengths. | entailment |
def make_layout(maxval):
"""Make the physical layout of the MinION flowcell.
based on https://bioinformatics.stackexchange.com/a/749/681
returned as a numpy array
"""
if maxval > 512:
return Layout(
structure=np.concatenate([np.array([list(range(10 * i + 1, i * 10 + 11))
... | Make the physical layout of the MinION flowcell.
based on https://bioinformatics.stackexchange.com/a/749/681
returned as a numpy array | entailment |
def spatial_heatmap(array, path, title=None, color="Greens", figformat="png"):
"""Taking channel information and creating post run channel activity plots."""
logging.info("Nanoplotter: Creating heatmap of reads per channel using {} reads."
.format(array.size))
activity_map = Plot(
p... | Taking channel information and creating post run channel activity plots. | entailment |
def main(database_dir, target_dir):
"""Generate CSV files from a CronosPro/CronosPlus database."""
if not os.path.isdir(database_dir):
raise click.ClickException("Database directory does not exist!")
try:
os.makedirs(target_dir)
except:
pass
try:
parse(database_dir, t... | Generate CSV files from a CronosPro/CronosPlus database. | entailment |
def check_valid_time_and_sort(df, timescol, days=5, warning=True):
"""Check if the data contains reads created within the same `days` timeframe.
if not, print warning and only return part of the data which is within `days` days
Resetting the index twice to get also an "index" column for plotting the cum_yi... | Check if the data contains reads created within the same `days` timeframe.
if not, print warning and only return part of the data which is within `days` days
Resetting the index twice to get also an "index" column for plotting the cum_yield_reads plot | entailment |
def time_plots(df, path, title=None, color="#4CB391", figformat="png",
log_length=False, plot_settings=None):
"""Making plots of time vs read length, time vs quality and cumulative yield."""
dfs = check_valid_time_and_sort(df, "start_time")
logging.info("Nanoplotter: Creating timeplots using ... | Making plots of time vs read length, time vs quality and cumulative yield. | entailment |
def violin_or_box_plot(df, y, figformat, path, y_name,
title=None, plot="violin", log=False, palette=None):
"""Create a violin or boxplot from the received DataFrame.
The x-axis should be divided based on the 'dataset' column,
the y-axis is specified in the arguments
"""
comp... | Create a violin or boxplot from the received DataFrame.
The x-axis should be divided based on the 'dataset' column,
the y-axis is specified in the arguments | entailment |
def output_barplot(df, figformat, path, title=None, palette=None):
"""Create barplots based on number of reads and total sum of nucleotides sequenced."""
logging.info("Nanoplotter: Creating barplots for number of reads and total throughput.")
read_count = Plot(path=path + "NanoComp_number_of_reads." + figfo... | Create barplots based on number of reads and total sum of nucleotides sequenced. | entailment |
def overlay_histogram(df, path, palette=None):
"""
Use plotly to create an overlay of length histograms
Return html code, but also save as png
Only has 10 colors, which get recycled up to 5 times.
"""
if palette is None:
palette = plotly.colors.DEFAULT_PLOTLY_COLORS * 5
hist = Plot... | Use plotly to create an overlay of length histograms
Return html code, but also save as png
Only has 10 colors, which get recycled up to 5 times. | entailment |
def plot_log_histogram(df, palette, title, histnorm=""):
"""
Plot overlaying histograms with log transformation of length
Return both html and fig for png
"""
data = [go.Histogram(x=np.log10(df.loc[df["dataset"] == d, "lengths"]),
opacity=0.4,
name=d... | Plot overlaying histograms with log transformation of length
Return both html and fig for png | entailment |
def get_file(db_folder, file_name):
"""Glob for the poor."""
if not os.path.isdir(db_folder):
return
file_name = file_name.lower().strip()
for cand_name in os.listdir(db_folder):
if cand_name.lower().strip() == file_name:
return os.path.join(db_folder, cand_name) | Glob for the poor. | entailment |
def parse(db_folder, out_folder):
"""
Parse a cronos database.
Convert the database located in ``db_folder`` into CSV files in the
directory ``out_folder``.
"""
# The database structure, containing table and column definitions as
# well as other data.
stru_dat = get_file(db_folder, 'Cro... | Parse a cronos database.
Convert the database located in ``db_folder`` into CSV files in the
directory ``out_folder``. | entailment |
def encode1(self):
"""Return the base64 encoding of the figure file and insert in html image tag."""
data_uri = b64encode(open(self.path, 'rb').read()).decode('utf-8').replace('\n', '')
return '<img src="data:image/png;base64,{0}">'.format(data_uri) | Return the base64 encoding of the figure file and insert in html image tag. | entailment |
def encode2(self):
"""Return the base64 encoding of the fig attribute and insert in html image tag."""
buf = BytesIO()
self.fig.savefig(buf, format='png', bbox_inches='tight', dpi=100)
buf.seek(0)
string = b64encode(buf.read())
return '<img src="data:image/png;base64,{0}"... | Return the base64 encoding of the fig attribute and insert in html image tag. | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.