sentence1 stringlengths 52 3.87M | sentence2 stringlengths 1 47.2k | label stringclasses 1
value |
|---|---|---|
def _get(self, route, stream=False):
"""
run a get request against an url. Returns the response which can optionally be streamed
"""
log.debug("Running GET request against %s" % route)
return r.get(self._url(route), auth=c.auth, stream=stream) | run a get request against an url. Returns the response which can optionally be streamed | entailment |
def get_contents(self, folder: Folder):
"""
List all contents of a folder. Returns a list of all Documents and Folders (in this order) in the folder.
"""
log.debug("Listing Contents of %s/%s" % (folder.course.id, folder.id))
if isinstance(folder, Course):
response = j... | List all contents of a folder. Returns a list of all Documents and Folders (in this order) in the folder. | entailment |
def download_document(self, document: Document, overwrite=True, path=None):
"""
Download a document to the given path. if no path is provided the path is constructed frome the base_url + stud.ip path + filename.
If overwrite is set the local version will be overwritten if the file was changed on... | Download a document to the given path. if no path is provided the path is constructed frome the base_url + stud.ip path + filename.
If overwrite is set the local version will be overwritten if the file was changed on studip since the last check | entailment |
def get_semester_title(self, node: BaseNode):
"""
get the semester of a node
"""
log.debug("Getting Semester Title for %s" % node.course.id)
return self._get_semester_from_id(node.course.semester) | get the semester of a node | entailment |
def get_courses(self):
"""
use the base_url and auth data from the configuration to list all courses the user is subscribed to
"""
log.info("Listing Courses...")
courses = json.loads(self._get('/api/courses').text)["courses"]
courses = [Course.from_response(course) for co... | use the base_url and auth data from the configuration to list all courses the user is subscribed to | entailment |
def _minimize_scalar(
self, desc="Progress", rtol=1.4902e-08, atol=1.4902e-08, verbose=True
):
"""
Minimize a scalar function using Brent's method.
Parameters
----------
verbose : bool
``True`` for verbose output; ``False`` otherwise.
"""
... | Minimize a scalar function using Brent's method.
Parameters
----------
verbose : bool
``True`` for verbose output; ``False`` otherwise. | entailment |
def digest(self, alg='sha256', b64=True, strip=True):
"""return a url-safe hash of the string, optionally (and by default) base64-encoded
alg='sha256' = the hash algorithm, must be in hashlib
b64=True = whether to base64-encode the output
strip=True = wheth... | return a url-safe hash of the string, optionally (and by default) base64-encoded
alg='sha256' = the hash algorithm, must be in hashlib
b64=True = whether to base64-encode the output
strip=True = whether to strip trailing '=' from the base64 output
Using the... | entailment |
def camelify(self):
"""turn a string to CamelCase, omitting non-word characters"""
outstring = self.titleify(allwords=True)
outstring = re.sub(r"&[^;]+;", " ", outstring)
outstring = re.sub(r"\W+", "", outstring)
return String(outstring) | turn a string to CamelCase, omitting non-word characters | entailment |
def titleify(self, lang='en', allwords=False, lastword=True):
"""takes a string and makes a title from it"""
if lang in LOWERCASE_WORDS:
lc_words = LOWERCASE_WORDS[lang]
else:
lc_words = []
s = str(self).strip()
l = re.split(r"([_\W]+)", s)
... | takes a string and makes a title from it | entailment |
def identifier(self, camelsplit=False, ascii=True):
"""return a python identifier from the string (underscore separators)"""
return self.nameify(camelsplit=camelsplit, ascii=ascii, sep='_') | return a python identifier from the string (underscore separators) | entailment |
def nameify(self, camelsplit=False, ascii=True, sep='-'):
"""return an XML name (hyphen-separated by default, initial underscore if non-letter)"""
s = String(str(self)) # immutable
if camelsplit == True:
s = s.camelsplit()
s = s.hyphenify(ascii=ascii).replace('-', sep)
... | return an XML name (hyphen-separated by default, initial underscore if non-letter) | entailment |
def hyphenify(self, ascii=False):
"""Turn non-word characters (incl. underscore) into single hyphens.
If ascii=True, return ASCII-only.
If also lossless=True, use the UTF-8 codes for the non-ASCII characters.
"""
s = str(self)
s = re.sub("""['"\u2018\u2019\u201c\u20... | Turn non-word characters (incl. underscore) into single hyphens.
If ascii=True, return ASCII-only.
If also lossless=True, use the UTF-8 codes for the non-ASCII characters. | entailment |
def camelsplit(self):
"""Turn a CamelCase string into a string with spaces"""
s = str(self)
for i in range(len(s) - 1, -1, -1):
if i != 0 and (
(s[i].isupper() and s[i - 1].isalnum() and not s[i - 1].isupper())
or (s[i].isnumeric() and s[i - 1].i... | Turn a CamelCase string into a string with spaces | entailment |
def includeme(config):
"""Pyramid pluggable and discoverable function."""
global_settings = config.registry.settings
settings = local_settings(global_settings, PREFIX)
try:
file = settings['file']
except KeyError:
raise KeyError("Must supply '{}.file' configuration value "
... | Pyramid pluggable and discoverable function. | entailment |
def run(self):
"""Executed on startup of application"""
self.api = self.context.get("cls")(self.context)
self.context["inst"].append(self) # Adapters used by strategies
for call, calldata in self.context.get("calls", {}).items():
def loop():
"""Loop on event... | Executed on startup of application | entailment |
def call(self, callname, arguments=None):
"""Executed on each scheduled iteration"""
# See if a method override exists
action = getattr(self.api, callname, None)
if action is None:
try:
action = self.api.ENDPOINT_OVERRIDES.get(callname, None)
excep... | Executed on each scheduled iteration | entailment |
def _generate_request(self, callname, request):
"""Generate a request object for delivery to the API"""
# Retrieve path from API class
schema = self.api.request_schema()
schema.context['callname'] = callname
return schema.dump(request).data.get("payload") | Generate a request object for delivery to the API | entailment |
def _generate_result(self, callname, result):
"""Generate a results object for delivery to the context object"""
# Retrieve path from API class
schema = self.api.result_schema()
schema.context['callname'] = callname
self.callback(schema.load(result), self.context) | Generate a results object for delivery to the context object | entailment |
def excel_key(index):
"""create a key for index by converting index into a base-26 number, using A-Z as the characters."""
X = lambda n: ~n and X((n // 26)-1) + chr(65 + (n % 26)) or ''
return X(int(index)) | create a key for index by converting index into a base-26 number, using A-Z as the characters. | entailment |
def convert_to_crash_data(raw_crash, processed_crash):
"""
Takes a raw crash and a processed crash (these are Socorro-centric
data structures) and converts them to a crash data structure used
by signature generation.
:arg raw_crash: raw crash data from Socorro
:arg processed_crash: processed cr... | Takes a raw crash and a processed crash (these are Socorro-centric
data structures) and converts them to a crash data structure used
by signature generation.
:arg raw_crash: raw crash data from Socorro
:arg processed_crash: processed crash data from Socorro
:returns: crash data structure that conf... | entailment |
def drop_bad_characters(text):
"""Takes a text and drops all non-printable and non-ascii characters and
also any whitespace characters that aren't space.
:arg str text: the text to fix
:returns: text with all bad characters dropped
"""
# Strip all non-ascii and non-printable characters
te... | Takes a text and drops all non-printable and non-ascii characters and
also any whitespace characters that aren't space.
:arg str text: the text to fix
:returns: text with all bad characters dropped | entailment |
def parse_source_file(source_file):
"""Parses a source file thing and returns the file name
Example:
>>> parse_file('hg:hg.mozilla.org/releases/mozilla-esr52:js/src/jit/MIR.h:755067c14b06')
'js/src/jit/MIR.h'
:arg str source_file: the source file ("file") from a stack frame
:returns: the fil... | Parses a source file thing and returns the file name
Example:
>>> parse_file('hg:hg.mozilla.org/releases/mozilla-esr52:js/src/jit/MIR.h:755067c14b06')
'js/src/jit/MIR.h'
:arg str source_file: the source file ("file") from a stack frame
:returns: the filename or ``None`` if it couldn't determine ... | entailment |
def _is_exception(exceptions, before_token, after_token, token):
"""Predicate for whether the open token is in an exception context
:arg exceptions: list of strings or None
:arg before_token: the text of the function up to the token delimiter
:arg after_token: the text of the function after the token d... | Predicate for whether the open token is in an exception context
:arg exceptions: list of strings or None
:arg before_token: the text of the function up to the token delimiter
:arg after_token: the text of the function after the token delimiter
:arg token: the token (only if we're looking at a close del... | entailment |
def collapse(
function,
open_string,
close_string,
replacement='',
exceptions=None,
):
"""Collapses the text between two delimiters in a frame function value
This collapses the text between two delimiters and either removes the text
altogether or replaces it with a replacement string.
... | Collapses the text between two delimiters in a frame function value
This collapses the text between two delimiters and either removes the text
altogether or replaces it with a replacement string.
There are certain contexts in which we might not want to collapse the text
between two delimiters. These a... | entailment |
def drop_prefix_and_return_type(function):
"""Takes the function value from a frame and drops prefix and return type
For example::
static void * Allocator<MozJemallocBase>::malloc(unsigned __int64)
^ ^^^^^^ return type
prefix
This gets changes to this::
Allocator<Moz... | Takes the function value from a frame and drops prefix and return type
For example::
static void * Allocator<MozJemallocBase>::malloc(unsigned __int64)
^ ^^^^^^ return type
prefix
This gets changes to this::
Allocator<MozJemallocBase>::malloc(unsigned __int64)
This ... | entailment |
def wait_connected(self, conns=None, timeout=None):
'''Wait for connections to be made and their handshakes to finish
:param conns:
a single or list of (host, port) tuples with the connections that
must be finished before the method will return. defaults to all the
p... | Wait for connections to be made and their handshakes to finish
:param conns:
a single or list of (host, port) tuples with the connections that
must be finished before the method will return. defaults to all the
peers the :class:`Hub` was instantiated with.
:param tim... | entailment |
def shutdown(self):
'Close all peer connections and stop listening for new ones'
log.info("shutting down")
for peer in self._dispatcher.peers.values():
peer.go_down(reconnect=False)
if self._listener_coro:
backend.schedule_exception(
errors._... | Close all peer connections and stop listening for new ones | entailment |
def accept_publish(
self, service, mask, value, method, handler=None, schedule=False):
'''Set a handler for incoming publish messages
:param service: the incoming message must have this service
:type service: anything hash-able
:param mask:
value to be bitwise-an... | Set a handler for incoming publish messages
:param service: the incoming message must have this service
:type service: anything hash-able
:param mask:
value to be bitwise-and'ed against the incoming id, the result of
which must mask the 'value' param
:type mask: ... | entailment |
def unsubscribe_publish(self, service, mask, value):
'''Remove a publish subscription
:param service: the service of the subscription to remove
:type service: anything hash-able
:param mask: the mask of the subscription to remove
:type mask: int
:param value: the value i... | Remove a publish subscription
:param service: the service of the subscription to remove
:type service: anything hash-able
:param mask: the mask of the subscription to remove
:type mask: int
:param value: the value in the subscription to remove
:type value: int
:... | entailment |
def publish(self, service, routing_id, method, args=None, kwargs=None,
broadcast=False, udp=False):
'''Send a 1-way message
:param service: the service name (the routing top level)
:type service: anything hash-able
:param int routing_id:
the id used for routing w... | Send a 1-way message
:param service: the service name (the routing top level)
:type service: anything hash-able
:param int routing_id:
the id used for routing within the registered handlers of the
service
:param string method: the method name to call
:par... | entailment |
def publish_receiver_count(self, service, routing_id):
'''Get the number of peers that would handle a particular publish
:param service: the service name
:type service: anything hash-able
:param routing_id: the id used for limiting the service handlers
:type routing_id: int
... | Get the number of peers that would handle a particular publish
:param service: the service name
:type service: anything hash-able
:param routing_id: the id used for limiting the service handlers
:type routing_id: int | entailment |
def accept_rpc(self, service, mask, value, method,
handler=None, schedule=True):
'''Set a handler for incoming RPCs
:param service: the incoming RPC must have this service
:type service: anything hash-able
:param mask:
value to be bitwise-and'ed against the incom... | Set a handler for incoming RPCs
:param service: the incoming RPC must have this service
:type service: anything hash-able
:param mask:
value to be bitwise-and'ed against the incoming id, the result of
which must mask the 'value' param
:type mask: int
:par... | entailment |
def unsubscribe_rpc(self, service, mask, value):
'''Remove a rpc subscription
:param service: the service of the subscription to remove
:type service: anything hash-able
:param mask: the mask of the subscription to remove
:type mask: int
:param value: the value in the su... | Remove a rpc subscription
:param service: the service of the subscription to remove
:type service: anything hash-able
:param mask: the mask of the subscription to remove
:type mask: int
:param value: the value in the subscription to remove
:type value: int
:param... | entailment |
def send_rpc(self, service, routing_id, method, args=None, kwargs=None,
broadcast=False):
'''Send out an RPC request
:param service: the service name (the routing top level)
:type service: anything hash-able
:param routing_id:
The id used for routing within the r... | Send out an RPC request
:param service: the service name (the routing top level)
:type service: anything hash-able
:param routing_id:
The id used for routing within the registered handlers of the
service.
:type routing_id: int
:param method: the method na... | entailment |
def rpc(self, service, routing_id, method, args=None, kwargs=None,
timeout=None, broadcast=False):
'''Send an RPC request and return the corresponding response
This will block waiting until the response has been received.
:param service: the service name (the routing top level)
... | Send an RPC request and return the corresponding response
This will block waiting until the response has been received.
:param service: the service name (the routing top level)
:type service: anything hash-able
:param routing_id:
The id used for routing within the registere... | entailment |
def rpc_receiver_count(self, service, routing_id):
'''Get the number of peers that would handle a particular RPC
:param service: the service name
:type service: anything hash-able
:param routing_id:
the id used for narrowing within the service handlers
:type routing_... | Get the number of peers that would handle a particular RPC
:param service: the service name
:type service: anything hash-able
:param routing_id:
the id used for narrowing within the service handlers
:type routing_id: int
:returns:
the integer number of p... | entailment |
def start(self):
"Start up the hub's server, and have it start initiating connections"
log.info("starting")
self._listener_coro = backend.greenlet(self._listener)
self._udp_listener_coro = backend.greenlet(self._udp_listener)
backend.schedule(self._listener_coro)
backend... | Start up the hub's server, and have it start initiating connections | entailment |
def add_peer(self, peer_addr):
"Build a connection to the Hub at a given ``(host, port)`` address"
peer = connection.Peer(
self._ident, self._dispatcher, peer_addr, backend.Socket())
peer.start()
self._started_peers[peer_addr] = peer | Build a connection to the Hub at a given ``(host, port)`` address | entailment |
def peers(self):
"list of the (host, port) pairs of all connected peer Hubs"
return [addr for (addr, peer) in self._dispatcher.peers.items()
if peer.up] | list of the (host, port) pairs of all connected peer Hubs | entailment |
def main(argv=None):
"""Takes crash data via args and generates a Socorro signature
"""
parser = argparse.ArgumentParser(description=DESCRIPTION, epilog=EPILOG)
parser.add_argument(
'-v', '--verbose', help='increase output verbosity', action='store_true'
)
parser.add_argument(
'... | Takes crash data via args and generates a Socorro signature | entailment |
def send_result(self, return_code, output, service_description='', time_stamp=0, specific_servers=None):
'''
Send result to the Skinken WS
'''
if time_stamp == 0:
time_stamp = int(time.time())
if specific_servers == None:
specific_servers = self.servers
... | Send result to the Skinken WS | entailment |
def close_cache(self):
'''
Close cache of WS Shinken
'''
# Close all WS_Shinken cache files
for server in self.servers:
if self.servers[server]['cache'] == True:
self.servers[server]['file'].close() | Close cache of WS Shinken | entailment |
def prepare_dir(app, directory, delete=False):
"""Create apidoc dir, delete contents if delete is True.
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param directory: the apidoc directory. you can use relative paths here
:type directory: str
:param delete: if True, d... | Create apidoc dir, delete contents if delete is True.
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param directory: the apidoc directory. you can use relative paths here
:type directory: str
:param delete: if True, deletes the contents of apidoc. This acts like an overr... | entailment |
def makename(package, module):
"""Join package and module with a dot.
Package or Module can be empty.
:param package: the package name
:type package: :class:`str`
:param module: the module name
:type module: :class:`str`
:returns: the joined name
:rtype: :class:`str`
:raises: :clas... | Join package and module with a dot.
Package or Module can be empty.
:param package: the package name
:type package: :class:`str`
:param module: the module name
:type module: :class:`str`
:returns: the joined name
:rtype: :class:`str`
:raises: :class:`AssertionError`, if both package an... | entailment |
def write_file(app, name, text, dest, suffix, dryrun, force):
"""Write the output file for module/package <name>.
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param name: the file name without file extension
:type name: :class:`str`
:param text: the content of the f... | Write the output file for module/package <name>.
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param name: the file name without file extension
:type name: :class:`str`
:param text: the content of the file
:type text: :class:`str`
:param dest: the output director... | entailment |
def import_name(app, name):
"""Import the given name and return name, obj, parent, mod_name
:param name: name to import
:type name: str
:returns: the imported object or None
:rtype: object | None
:raises: None
"""
try:
logger.debug('Importing %r', name)
name, obj = autos... | Import the given name and return name, obj, parent, mod_name
:param name: name to import
:type name: str
:returns: the imported object or None
:rtype: object | None
:raises: None | entailment |
def get_members(app, mod, typ, include_public=None):
"""Return the members of mod of the given type
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param mod: the module with members
:type mod: module
:param typ: the typ, ``'class'``, ``'function'``, ``'exception'``, `... | Return the members of mod of the given type
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param mod: the module with members
:type mod: module
:param typ: the typ, ``'class'``, ``'function'``, ``'exception'``, ``'data'``, ``'members'``
:type typ: str
:param inclu... | entailment |
def _get_submodules(app, module):
"""Get all submodules for the given module/package
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param module: the module to query or module path
:type module: module | str
:returns: list of module names and boolean whether its a pac... | Get all submodules for the given module/package
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param module: the module to query or module path
:type module: module | str
:returns: list of module names and boolean whether its a package
:rtype: list
:raises: TypeEr... | entailment |
def get_submodules(app, module):
"""Get all submodules without packages for the given module/package
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param module: the module to query or module path
:type module: module | str
:returns: list of module names excluding pac... | Get all submodules without packages for the given module/package
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param module: the module to query or module path
:type module: module | str
:returns: list of module names excluding packages
:rtype: list
:raises: Type... | entailment |
def get_subpackages(app, module):
"""Get all subpackages for the given module/package
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param module: the module to query or module path
:type module: module | str
:returns: list of packages names
:rtype: list
:rais... | Get all subpackages for the given module/package
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param module: the module to query or module path
:type module: module | str
:returns: list of packages names
:rtype: list
:raises: TypeError | entailment |
def get_context(app, package, module, fullname):
"""Return a dict for template rendering
Variables:
* :package: The top package
* :module: the module
* :fullname: package.module
* :subpkgs: packages beneath module
* :submods: modules beneath module
* :classes: public classe... | Return a dict for template rendering
Variables:
* :package: The top package
* :module: the module
* :fullname: package.module
* :subpkgs: packages beneath module
* :submods: modules beneath module
* :classes: public classes in module
* :allclasses: public and private clas... | entailment |
def create_module_file(app, env, package, module, dest, suffix, dryrun, force):
"""Build the text of the file and write the file.
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param env: the jinja environment for the templates
:type env: :class:`jinja2.Environment`
:... | Build the text of the file and write the file.
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param env: the jinja environment for the templates
:type env: :class:`jinja2.Environment`
:param package: the package name
:type package: :class:`str`
:param module: the ... | entailment |
def create_package_file(app, env, root_package, sub_package, private,
dest, suffix, dryrun, force):
"""Build the text of the file and write the file.
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param env: the jinja environment for the templates
... | Build the text of the file and write the file.
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param env: the jinja environment for the templates
:type env: :class:`jinja2.Environment`
:param root_package: the parent package
:type root_package: :class:`str`
:param ... | entailment |
def shall_skip(app, module, private):
"""Check if we want to skip this module.
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param module: the module name
:type module: :class:`str`
:param private: True, if privates are allowed
:type private: :class:`bool`
""... | Check if we want to skip this module.
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param module: the module name
:type module: :class:`str`
:param private: True, if privates are allowed
:type private: :class:`bool` | entailment |
def recurse_tree(app, env, src, dest, excludes, followlinks, force, dryrun, private, suffix):
"""Look for every file in the directory tree and create the corresponding
ReST files.
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param env: the jinja environment
:type en... | Look for every file in the directory tree and create the corresponding
ReST files.
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param env: the jinja environment
:type env: :class:`jinja2.Environment`
:param src: the path to the python source files
:type src: :cl... | entailment |
def normalize_excludes(excludes):
"""Normalize the excluded directory list."""
return [os.path.normpath(os.path.abspath(exclude)) for exclude in excludes] | Normalize the excluded directory list. | entailment |
def is_excluded(root, excludes):
"""Check if the directory is in the exclude list.
Note: by having trailing slashes, we avoid common prefix issues, like
e.g. an exlude "foo" also accidentally excluding "foobar".
"""
root = os.path.normpath(root)
for exclude in excludes:
if root ==... | Check if the directory is in the exclude list.
Note: by having trailing slashes, we avoid common prefix issues, like
e.g. an exlude "foo" also accidentally excluding "foobar". | entailment |
def generate(app, src, dest, exclude=[], followlinks=False,
force=False, dryrun=False, private=False, suffix='rst',
template_dirs=None):
"""Generage the rst files
Raises an :class:`OSError` if the source path is not a directory.
:param app: the sphinx app
:type app: :class:`s... | Generage the rst files
Raises an :class:`OSError` if the source path is not a directory.
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param src: path to python source files
:type src: :class:`str`
:param dest: output directory
:type dest: :class:`str`
:para... | entailment |
def main(app):
"""Parse the config of the app and initiate the generation process
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:returns: None
:rtype: None
:raises: None
"""
c = app.config
src = c.jinjaapi_srcdir
if not src:
return
suffix... | Parse the config of the app and initiate the generation process
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:returns: None
:rtype: None
:raises: None | entailment |
def _isclose(obja, objb, rtol=1e-05, atol=1e-08):
"""Return floating point equality."""
return abs(obja - objb) <= (atol + rtol * abs(objb)) | Return floating point equality. | entailment |
def _isreal(obj):
"""
Determine if an object is a real number.
Both Python standard data types and Numpy data types are supported.
:param obj: Object
:type obj: any
:rtype: boolean
"""
# pylint: disable=W0702
if (obj is None) or isinstance(obj, bool):
return False
try... | Determine if an object is a real number.
Both Python standard data types and Numpy data types are supported.
:param obj: Object
:type obj: any
:rtype: boolean | entailment |
def _no_exp(number):
r"""
Convert a number to a string without using scientific notation.
:param number: Number to convert
:type number: integer or float
:rtype: string
:raises: RuntimeError (Argument \`number\` is not valid)
"""
if isinstance(number, bool) or (not isinstance(number,... | r"""
Convert a number to a string without using scientific notation.
:param number: Number to convert
:type number: integer or float
:rtype: string
:raises: RuntimeError (Argument \`number\` is not valid) | entailment |
def _to_scientific_tuple(number):
r"""
Return mantissa and exponent of a number expressed in scientific notation.
Full precision is maintained if the number is represented as a string.
:param number: Number
:type number: integer, float or string
:rtype: Tuple whose first item is the mantissa... | r"""
Return mantissa and exponent of a number expressed in scientific notation.
Full precision is maintained if the number is represented as a string.
:param number: Number
:type number: integer, float or string
:rtype: Tuple whose first item is the mantissa (*string*) and the second
... | entailment |
def gcd(vector):
"""
Calculate the greatest common divisor (GCD) of a sequence of numbers.
The sequence can be a list of numbers or a Numpy vector of numbers. The
computations are carried out with a precision of 1E-12 if the objects are
not `fractions <https://docs.python.org/3/library/fractions.ht... | Calculate the greatest common divisor (GCD) of a sequence of numbers.
The sequence can be a list of numbers or a Numpy vector of numbers. The
computations are carried out with a precision of 1E-12 if the objects are
not `fractions <https://docs.python.org/3/library/fractions.html>`_. When
possible it i... | entailment |
def normalize(value, series, offset=0):
r"""
Scale a value to the range defined by a series.
:param value: Value to normalize
:type value: number
:param series: List of numbers that defines the normalization range
:type series: list
:param offset: Normalization offset, i.e. the returned... | r"""
Scale a value to the range defined by a series.
:param value: Value to normalize
:type value: number
:param series: List of numbers that defines the normalization range
:type series: list
:param offset: Normalization offset, i.e. the returned value will be in
the ran... | entailment |
def per(arga, argb, prec=10):
r"""
Calculate percentage difference between numbers.
If only two numbers are given, the percentage difference between them is
computed. If two sequences of numbers are given (either two lists of
numbers or Numpy vectors), the element-wise percentage difference is
... | r"""
Calculate percentage difference between numbers.
If only two numbers are given, the percentage difference between them is
computed. If two sequences of numbers are given (either two lists of
numbers or Numpy vectors), the element-wise percentage difference is
computed. If any of the numbers in... | entailment |
def pgcd(numa, numb):
"""
Calculate the greatest common divisor (GCD) of two numbers.
:param numa: First number
:type numa: number
:param numb: Second number
:type numb: number
:rtype: number
For example:
>>> import pmisc, fractions
>>> pmisc.pgcd(10, 15)
5... | Calculate the greatest common divisor (GCD) of two numbers.
:param numa: First number
:type numa: number
:param numb: Second number
:type numb: number
:rtype: number
For example:
>>> import pmisc, fractions
>>> pmisc.pgcd(10, 15)
5
>>> str(pmisc.pgcd(0.05, ... | entailment |
def connect_ws(self, post_connect_callback, channels, reconnect=False):
"""
Connect to a websocket
:channels: List of SockChannel instances
"""
self.post_conn_cb = post_connect_callback
self.channels = channels
self.wsendpoint = self.context["conf"]["endpoints"].... | Connect to a websocket
:channels: List of SockChannel instances | entailment |
def wscall(self, method, query=None, callback=None):
"""Submit a request on the websocket"""
if callback is None:
self.sock.emit(method, query)
else:
self.sock.emitack(method, query, callback) | Submit a request on the websocket | entailment |
def connect_channels(self, channels):
"""Connect the provided channels"""
self.log.info(f"Connecting to channels...")
for chan in channels:
chan.connect(self.sock)
self.log.info(f"\t{chan.channel}") | Connect the provided channels | entailment |
def _on_set_auth(self, sock, token):
"""Set Auth request received from websocket"""
self.log.info(f"Token received: {token}")
sock.setAuthtoken(token) | Set Auth request received from websocket | entailment |
def _on_auth(self, sock, authenticated): # pylint: disable=unused-argument
"""Message received from websocket"""
def ack(eventname, error, data): # pylint: disable=unused-argument
"""Ack"""
if error:
self.log.error(f"""OnAuth: {error}""")
else:
... | Message received from websocket | entailment |
def _on_connect_error(self, sock, err): # pylint: disable=unused-argument
"""Error received from websocket"""
if isinstance(err, SystemExit):
self.log.error(f"Shutting down websocket connection")
else:
self.log.error(f"Websocket error: {err}") | Error received from websocket | entailment |
def connect(self, sock):
"""Attach a given socket to a channel"""
def cbwrap(*args, **kwargs):
"""Callback wrapper; passes in response_type"""
self.callback(self.response_type, *args, **kwargs)
self.sock = sock
self.sock.subscribe(self.channel)
self.sock.... | Attach a given socket to a channel | entailment |
def run_cmd(cmd, input=None, timeout=30, max_try=3, num_try=1):
'''Run command `cmd`.
It's like that, and that's the way it is.
'''
if type(cmd) == str:
cmd = cmd.split()
process = subprocess.Popen(cmd,
stdin=open('/dev/null', 'r'),
... | Run command `cmd`.
It's like that, and that's the way it is. | entailment |
def pop_first_arg(argv):
"""
find first positional arg (does not start with -), take it out of array and return it separately
returns (arg, array)
"""
for arg in argv:
if not arg.startswith('-'):
argv.remove(arg)
return (arg, argv)
return (None, argv) | find first positional arg (does not start with -), take it out of array and return it separately
returns (arg, array) | entailment |
def check_options(options, parser):
"""
check options requirements, print and return exit value
"""
if not options.get('release_environment', None):
print("release environment is required")
parser.print_help()
return os.EX_USAGE
return 0 | check options requirements, print and return exit value | entailment |
def write(self):
""" write all needed state info to filesystem """
dumped = self._fax.codec.dump(self.__state, open(self.state_file, 'w')) | write all needed state info to filesystem | entailment |
def package_config(path, template='__config__.ini.TEMPLATE', config_name='__config__.ini', **params):
"""configure the module at the given path with a config template and file.
path = the filesystem path to the given module
template = the config template filename within that path
... | configure the module at the given path with a config template and file.
path = the filesystem path to the given module
template = the config template filename within that path
config_name = the config filename within that path
params = a dict containing config params, ... | entailment |
def write(self, fn=None, sorted=False, wait=0):
"""write the contents of this config to fn or its __filename__.
"""
config = ConfigParser(interpolation=None)
if sorted==True: keys.sort()
for key in self.__dict__.get('ordered_keys') or self.keys():
config[key] = ... | write the contents of this config to fn or its __filename__. | entailment |
def expected_param_keys(self):
"""returns a list of params that this ConfigTemplate expects to receive"""
expected_keys = []
r = re.compile('%\(([^\)]+)\)s')
for block in self.keys():
for key in self[block].keys():
s = self[block][key]
i... | returns a list of params that this ConfigTemplate expects to receive | entailment |
def render(self, fn=None, prompt=False, **params):
"""return a Config with the given params formatted via ``str.format(**params)``.
fn=None : If given, will assign this filename to the rendered Config.
prompt=False : If True, will prompt for any param that is None.
"""
... | return a Config with the given params formatted via ``str.format(**params)``.
fn=None : If given, will assign this filename to the rendered Config.
prompt=False : If True, will prompt for any param that is None. | entailment |
def main():
"""Takes a crash id, pulls down data from Socorro, generates signature data"""
parser = argparse.ArgumentParser(
formatter_class=WrappedTextHelpFormatter,
description=DESCRIPTION
)
parser.add_argument(
'-v', '--verbose', help='increase output verbosity', action='store... | Takes a crash id, pulls down data from Socorro, generates signature data | entailment |
def _fill_text(self, text, width, indent):
"""Wraps text like HelpFormatter, but doesn't squash lines
This makes it easier to do lists and paragraphs.
"""
parts = text.split('\n\n')
for i, part in enumerate(parts):
# Check to see if it's a bulleted list--if so, then... | Wraps text like HelpFormatter, but doesn't squash lines
This makes it easier to do lists and paragraphs. | entailment |
def get_api_services_by_name(self):
"""Return a dict of services by name"""
if not self.services_by_name:
self.services_by_name = dict({s.get('name'): s for s in self.conf
.get("api")
.get("services")})
... | Return a dict of services by name | entailment |
def get_api_endpoints(self, apiname):
"""Returns the API endpoints"""
try:
return self.services_by_name\
.get(apiname)\
.get("endpoints")\
.copy()
except AttributeError:
raise Exception(f"Couldn't find the API en... | Returns the API endpoints | entailment |
def get_ws_subscriptions(self, apiname):
"""Returns the websocket subscriptions"""
try:
return self.services_by_name\
.get(apiname)\
.get("subscriptions")\
.copy()
except AttributeError:
raise Exception(f"Couldn'... | Returns the websocket subscriptions | entailment |
def get_api(self, name=None):
"""Returns the API configuration"""
if name is None:
try:
return self.conf.get("api").copy()
except: # NOQA
raise Exception(f"Couldn't find the API configuration") | Returns the API configuration | entailment |
def get_api_service(self, name=None):
"""Returns the specific service config definition"""
try:
svc = self.services_by_name.get(name, None)
if svc is None:
raise ValueError(f"Couldn't find the API service configuration")
return svc
except: # N... | Returns the specific service config definition | entailment |
def _ex_type_str(exobj):
"""Return a string corresponding to the exception type."""
regexp = re.compile(r"<(?:\bclass\b|\btype\b)\s+'?([\w|\.]+)'?>")
exc_type = str(exobj)
if regexp.match(exc_type):
exc_type = regexp.match(exc_type).groups()[0]
exc_type = exc_type[11:] if exc_type.starts... | Return a string corresponding to the exception type. | entailment |
def _unicode_to_ascii(obj): # pragma: no cover
"""Convert to ASCII."""
# pylint: disable=E0602,R1717
if isinstance(obj, dict):
return dict(
[
(_unicode_to_ascii(key), _unicode_to_ascii(value))
for key, value in obj.items()
]
)
if i... | Convert to ASCII. | entailment |
def send_result(self, return_code, output, service_description='', specific_servers=None):
'''
Send results
'''
if specific_servers == None:
specific_servers = self.servers
else:
specific_servers = set(self.servers).intersection(specific_servers)
... | Send results | entailment |
def get_remote_executors(hub_ip, port = 4444):
''' Get remote hosts from Selenium Grid Hub Console
@param hub_ip: hub ip of selenium grid hub
@param port: hub port of selenium grid hub
'''
resp = requests.get("http://%s:%s/grid/console" %(hub_ip, port))
re... | Get remote hosts from Selenium Grid Hub Console
@param hub_ip: hub ip of selenium grid hub
@param port: hub port of selenium grid hub | entailment |
def gen_remote_driver(executor, capabilities):
''' Generate remote drivers with desired capabilities(self.__caps) and command_executor
@param executor: command executor for selenium remote driver
@param capabilities: A dictionary of capabilities to request when starting the browser session.
... | Generate remote drivers with desired capabilities(self.__caps) and command_executor
@param executor: command executor for selenium remote driver
@param capabilities: A dictionary of capabilities to request when starting the browser session.
@return: remote driver | entailment |
def gen_local_driver(browser, capabilities):
''' Generate localhost drivers with desired capabilities(self.__caps)
@param browser: firefox or chrome
@param capabilities: A dictionary of capabilities to request when starting the browser session.
@return: localhost driver
'... | Generate localhost drivers with desired capabilities(self.__caps)
@param browser: firefox or chrome
@param capabilities: A dictionary of capabilities to request when starting the browser session.
@return: localhost driver | entailment |
def _production(self):
"""Calculate total energy production. Not rounded"""
return self._nuclear + self._diesel + self._gas + self._wind + self._combined + self._vapor + self._solar + self._hydraulic + self._carbon + self._waste + self._other | Calculate total energy production. Not rounded | entailment |
def _links(self):
"""Calculate total energy production. Not Rounded"""
total = 0.0
for value in self.link.values():
total += value
return total | Calculate total energy production. Not Rounded | entailment |
def query_yes_no(question, default="yes"):
"""Ask a yes/no question via raw_input() and return their answer.
"question" is a string that is presented to the user.
"default" is the presumed answer if the user just hits <Enter>.
It must be "yes" (the default), "no" or None (meaning
an answer i... | Ask a yes/no question via raw_input() and return their answer.
"question" is a string that is presented to the user.
"default" is the presumed answer if the user just hits <Enter>.
It must be "yes" (the default), "no" or None (meaning
an answer is required of the user).
The "answer" return v... | entailment |
def wall_of_name(self):
'''
Appends identifiers for the different databases (such as Entrez id's)
and returns them. Uses the CrossRef class below.
'''
names = []
if self.standard_name:
names.append(self.standard_name)
if self.systematic_name:
... | Appends identifiers for the different databases (such as Entrez id's)
and returns them. Uses the CrossRef class below. | entailment |
def save(self, *args, **kwargs):
"""
Override save() method to make sure that standard_name and
systematic_name won't be null or empty, or consist of only space
characters (such as space, tab, new line, etc).
"""
empty_std_name = False
if not self.standard_name or... | Override save() method to make sure that standard_name and
systematic_name won't be null or empty, or consist of only space
characters (such as space, tab, new line, etc). | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.