INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
Extract arXiv IDs from a text.
:param text: The text to extract arXiv IDs from.
:returns: A list of matching arXiv IDs, in canonical form.
>>> sorted(extract_from_text('1506.06690 1506.06690v1 arXiv:1506.06690 arXiv:1506.06690v1 arxiv:1506.06690 arxiv:1506.06690v1 math.GT/0309136 abcdf bar1506.06690foo ma... | def extract_from_text(text):
"""
Extract arXiv IDs from a text.
:param text: The text to extract arXiv IDs from.
:returns: A list of matching arXiv IDs, in canonical form.
>>> sorted(extract_from_text('1506.06690 1506.06690v1 arXiv:1506.06690 arXiv:1506.06690v1 arxiv:1506.06690 arxiv:1506.06690v1 ... |
Get the arXiv eprint id for a given DOI.
.. note::
Uses arXiv API. Will not return anything if arXiv is not aware of the
associated DOI.
:param doi: The DOI of the resource to look for.
:returns: The arXiv eprint id, or ``None`` if not found.
>>> from_doi('10.1209/0295-5075/111/40005... | def from_doi(doi):
"""
Get the arXiv eprint id for a given DOI.
.. note::
Uses arXiv API. Will not return anything if arXiv is not aware of the
associated DOI.
:param doi: The DOI of the resource to look for.
:returns: The arXiv eprint id, or ``None`` if not found.
>>> from_d... |
Download sources on arXiv for a given preprint.
.. note::
Bulk download of sources from arXiv is not permitted by their API. \
You should have a look at http://arxiv.org/help/bulk_data_s3.
:param eprint: The arXiv id (e.g. ``1401.2910`` or ``1401.2910v1``) in a \
canonical... | def get_sources(arxiv_id):
"""
Download sources on arXiv for a given preprint.
.. note::
Bulk download of sources from arXiv is not permitted by their API. \
You should have a look at http://arxiv.org/help/bulk_data_s3.
:param eprint: The arXiv id (e.g. ``1401.2910`` or ``1401... |
Get the .bbl files (if any) of a given preprint.
.. note::
Bulk download of sources from arXiv is not permitted by their API. \
You should have a look at http://arxiv.org/help/bulk_data_s3.
:param arxiv_id: The arXiv id (e.g. ``1401.2910`` or ``1401.2910v1``) in \
a canoni... | def get_bbl(arxiv_id):
"""
Get the .bbl files (if any) of a given preprint.
.. note::
Bulk download of sources from arXiv is not permitted by their API. \
You should have a look at http://arxiv.org/help/bulk_data_s3.
:param arxiv_id: The arXiv id (e.g. ``1401.2910`` or ``1401.... |
Extract semantic date information from an input string.
This is a convenience method which would only be used if
you'd rather not initialize a DateService object.
Args:
inp (str): The input string to be parsed.
tz: An optional Pytz timezone. All datetime objects returned will
be... | def extractDates(inp, tz=None, now=None):
"""Extract semantic date information from an input string.
This is a convenience method which would only be used if
you'd rather not initialize a DateService object.
Args:
inp (str): The input string to be parsed.
tz: An optional Pytz timezone. ... |
Extracts all day-related information from an input string.
Ignores any information related to the specific time-of-day.
Args:
inp (str): Input string to be parsed.
Returns:
A list of datetime objects containing the extracted date from the
input snippet, or a... | def extractDays(self, inp):
"""Extracts all day-related information from an input string.
Ignores any information related to the specific time-of-day.
Args:
inp (str): Input string to be parsed.
Returns:
A list of datetime objects containing the extracted date f... |
Extracts time-related information from an input string.
Ignores any information related to the specific date, focusing
on the time-of-day.
Args:
inp (str): Input string to be parsed.
Returns:
A list of datetime objects containing the extracted times from the
... | def extractTimes(self, inp):
"""Extracts time-related information from an input string.
Ignores any information related to the specific date, focusing
on the time-of-day.
Args:
inp (str): Input string to be parsed.
Returns:
A list of datetime objects con... |
Extract semantic date information from an input string.
In effect, runs both parseDay and parseTime on the input
string and merges the results to produce a comprehensive
datetime object.
Args:
inp (str): Input string to be parsed.
Returns:
A list of date... | def extractDates(self, inp):
"""Extract semantic date information from an input string.
In effect, runs both parseDay and parseTime on the input
string and merges the results to produce a comprehensive
datetime object.
Args:
inp (str): Input string to be parsed.
... |
Returns the first date found in the input string, or None if not
found. | def extractDate(self, inp):
"""Returns the first date found in the input string, or None if not
found."""
dates = self.extractDates(inp)
for date in dates:
return date
return None |
Convert a datetime object representing a day into a human-ready
string that can be read, spoken aloud, etc.
Args:
day (datetime.date): A datetime object to be converted into text.
prefix (str): An optional argument that prefixes the converted
string. For example,... | def convertDay(self, day, prefix="", weekday=False):
"""Convert a datetime object representing a day into a human-ready
string that can be read, spoken aloud, etc.
Args:
day (datetime.date): A datetime object to be converted into text.
prefix (str): An optional argument ... |
Convert a datetime object representing a time into a human-ready
string that can be read, spoken aloud, etc.
Args:
time (datetime.date): A datetime object to be converted into text.
Returns:
A string representation of the input time, ignoring any day-related
... | def convertTime(self, time):
"""Convert a datetime object representing a time into a human-ready
string that can be read, spoken aloud, etc.
Args:
time (datetime.date): A datetime object to be converted into text.
Returns:
A string representation of the input ti... |
Convert a datetime object representing into a human-ready
string that can be read, spoken aloud, etc. In effect, runs
both convertDay and convertTime on the input, merging the results.
Args:
date (datetime.date): A datetime object to be converted into text.
prefix (str):... | def convertDate(self, date, prefix="", weekday=False):
"""Convert a datetime object representing into a human-ready
string that can be read, spoken aloud, etc. In effect, runs
both convertDay and convertTime on the input, merging the results.
Args:
date (datetime.date): A da... |
Called during a PUT request where the action specifies
a move operation. Returns resource URI of the destination file. | def _move(self):
"""
Called during a PUT request where the action specifies
a move operation. Returns resource URI of the destination file.
"""
newpath = self.action['newpath']
try:
self.fs.move(self.fp,newpath)
except OSError:
raise tornad... |
Called during a PUT request where the action specifies
a copy operation. Returns resource URI of the new file. | def _copy(self):
"""
Called during a PUT request where the action specifies
a copy operation. Returns resource URI of the new file.
"""
copypath = self.action['copypath']
try:
self.fs.copy(self.fp,copypath)
except OSError:
raise tornado.web... |
Called during a PUT request where the action specifies
a rename operation. Returns resource URI of the renamed file. | def _rename(self):
"""
Called during a PUT request where the action specifies
a rename operation. Returns resource URI of the renamed file.
"""
newname = self.action['newname']
try:
newpath = self.fs.rename(self.fp,newname)
except OSError:
... |
Return details for the filesystem, including configured volumes. | def get(self):
"""
Return details for the filesystem, including configured volumes.
"""
res = self.fs.get_filesystem_details()
res = res.to_dict()
self.write(res) |
Provides move, copy, and rename functionality. An action must be
specified when calling this method. | def put(self):
"""
Provides move, copy, and rename functionality. An action must be
specified when calling this method.
"""
self.fp = self.get_body_argument('filepath')
self.action = self.get_body_argument('action')
try:
ptype = self.fs.get_type_from_... |
Start a new filewatcher at the specified path. | def post(self, *args):
"""
Start a new filewatcher at the specified path.
"""
filepath = self.get_body_argument('filepath')
if not self.fs.exists(filepath):
raise tornado.web.HTTPError(404)
Filewatcher.add_directory_to_watch(filepath)
self.write({'msg... |
Stop and delete the specified filewatcher. | def delete(self, filepath):
"""
Stop and delete the specified filewatcher.
"""
Filewatcher.remove_directory_to_watch(filepath)
self.write({'msg':'Watcher deleted for {}'.format(filepath)}) |
Get file details for the specified file. | def get(self, filepath):
"""
Get file details for the specified file.
"""
try:
res = self.fs.get_file_details(filepath)
res = res.to_dict()
self.write(res)
except OSError:
raise tornado.web.HTTPError(404) |
Change the group or permissions of the specified file. Action
must be specified when calling this method. | def put(self, filepath):
"""
Change the group or permissions of the specified file. Action
must be specified when calling this method.
"""
action = self.get_body_argument('action')
if action['action'] == 'update_group':
newgrp = action['group']
tr... |
Delete the specified file. | def delete(self, filepath):
"""
Delete the specified file.
"""
try:
self.fs.delete(filepath)
self.write({'msg':'File deleted at {}'.format(filepath)})
except OSError:
raise tornado.web.HTTPError(404) |
Get directory details for the specified file. If contents is
set to True (default) then the directory contents will be sent
along with the directory details. If dir_size is set to True
(default=False) then du -hs will be run against subdirectories
for accurate content sizes. | def get(self, filepath):
"""
Get directory details for the specified file. If contents is
set to True (default) then the directory contents will be sent
along with the directory details. If dir_size is set to True
(default=False) then du -hs will be run against subdirectories
... |
Create a new directory at the specified path. | def post(self):
"""
Create a new directory at the specified path.
"""
filepath = self.get_body_argument('filepath')
try:
self.fs.create_directory(filepath)
encoded_filepath = tornado.escape.url_escape(filepath,plus=True)
resource_uri = self.re... |
Get the contents of the specified file. | def get(self, filepath):
"""
Get the contents of the specified file.
"""
exists = self.fs.exists(filepath)
if exists:
mime = magic.Magic(mime=True)
mime_type = mime.from_file(filepath)
if mime_type in self.unsupported_types:
sel... |
Write the given contents to the specified file. This is not
an append, all file contents will be replaced by the contents
given. | def post(self, filepath):
"""
Write the given contents to the specified file. This is not
an append, all file contents will be replaced by the contents
given.
"""
try:
content = self.get_body_argument('content')
self.fs.write_file(filepath, content... |
Retrieve the content of the requested resource which is located
at the given absolute path.
This method should either return a byte string or an iterator
of byte strings. The latter is preferred for large files
as it helps reduce memory fragmentation. | def get_content(self, start=None, end=None):
"""
Retrieve the content of the requested resource which is located
at the given absolute path.
This method should either return a byte string or an iterator
of byte strings. The latter is preferred for large files
as it helps... |
Sets the content headers on the response. | def set_headers(self):
"""
Sets the content headers on the response.
"""
self.set_header("Accept-Ranges", "bytes")
content_type = self.get_content_type()
if content_type:
self.set_header("Content-Type", content_type) |
Returns the ``Content-Type`` header to be used for this request. | def get_content_type(self):
"""
Returns the ``Content-Type`` header to be used for this request.
"""
mime_type, encoding = mimetypes.guess_type(self.filepath)
if encoding == "gzip":
return "application/gzip"
elif encoding is not None:
return "appli... |
Callback, which gets executed, if the signal "plugin_deactivate_post" was send by the plugin. | def __deactivate_shared_objects(self, plugin, *args, **kwargs):
"""
Callback, which gets executed, if the signal "plugin_deactivate_post" was send by the plugin.
"""
shared_objects = self.get()
for shared_object in shared_objects.keys():
self.unregister(shared_object) |
Registers a new shared object.
:param name: Unique name for shared object
:type name: str
:param description: Description of shared object
:type description: str
:param obj: The object, which shall be shared
:type obj: any type | def register(self, name, description, obj):
"""
Registers a new shared object.
:param name: Unique name for shared object
:type name: str
:param description: Description of shared object
:type description: str
:param obj: The object, which shall be shared
... |
Returns requested shared objects, which were registered by the current plugin.
If access to objects of other plugins are needed, use :func:`access` or perform get on application level::
my_app.shared_objects.get(name="...")
:param name: Name of a request shared object
:type name: ... | def get(self, name=None):
"""
Returns requested shared objects, which were registered by the current plugin.
If access to objects of other plugins are needed, use :func:`access` or perform get on application level::
my_app.shared_objects.get(name="...")
:param name: Name o... |
Returns requested shared objects.
:param name: Name of a request shared object
:type name: str or None
:param plugin: Plugin, which has registered the requested shared object
:type plugin: GwBasePattern instance or None | def get(self, name=None, plugin=None):
"""
Returns requested shared objects.
:param name: Name of a request shared object
:type name: str or None
:param plugin: Plugin, which has registered the requested shared object
:type plugin: GwBasePattern instance or None
... |
Registers a new shared object.
:param name: Unique name for shared object
:type name: str
:param description: Description of shared object
:type description: str
:param obj: The object, which shall be shared
:type obj: any type
:param plugin: Plugin, which regist... | def register(self, name, description, obj, plugin):
"""
Registers a new shared object.
:param name: Unique name for shared object
:type name: str
:param description: Description of shared object
:type description: str
:param obj: The object, which shall be shared... |
Unregisters an existing shared object, so that this shared object is no longer available.
This function is mainly used during plugin deactivation.
:param shared_object: Name of the shared_object | def unregister(self, shared_object):
"""
Unregisters an existing shared object, so that this shared object is no longer available.
This function is mainly used during plugin deactivation.
:param shared_object: Name of the shared_object
"""
if shared_object not in self._... |
Prints a list of all registered signals. Including description and plugin name. | def list_signals(self):
"""
Prints a list of all registered signals. Including description and plugin name.
"""
print("Signal list")
print("***********\n")
for key, signal in self.app.signals.signals.items():
print("%s (%s)\n %s\n" % (signal.name, signal.plug... |
Prints a list of all registered receivers. Including signal, plugin name and description. | def list_receivers(self):
"""
Prints a list of all registered receivers. Including signal, plugin name and description.
"""
print("Receiver list")
print("*************\n")
for key, receiver in self.app.signals.receivers.items():
print("%s <-- %s (%s):\n %s\n"... |
Returns True if the type is elementary - not versioned
:param elem_type:
:return: | def is_elementary_type(elem_type):
"""
Returns True if the type is elementary - not versioned
:param elem_type:
:return:
"""
if not oh.is_type(elem_type, bt.XmrType):
return False
if oh.is_type(elem_type, (bt.UVarintType, bt.IntType, mt.UnicodeType)):
... |
Copy one or more source directory(s) below a destination directory.
Parts of the destination directory path are created if needed.
Similar to the UNIX command: 'cp -R srcdir destdir' | def command_copytree(args):
"""
Copy one or more source directory(s) below a destination directory.
Parts of the destination directory path are created if needed.
Similar to the UNIX command: 'cp -R srcdir destdir'
"""
for srcdir in args.srcdirs:
basename = os.path.basename(srcdir)
... |
Copy one or more source-files(s) to a destpath (destfile or destdir).
Destdir mode is used if:
* More than one srcfile is provided
* Last parameter ends with a slash ("/").
* Last parameter is an existing directory
Destination directory path is created if needed.
Similar to the UNIX comma... | def command_copy(args):
"""
Copy one or more source-files(s) to a destpath (destfile or destdir).
Destdir mode is used if:
* More than one srcfile is provided
* Last parameter ends with a slash ("/").
* Last parameter is an existing directory
Destination directory path is created if n... |
Create a non-existing directory (or more ...).
If the directory exists, the step is skipped.
Similar to the UNIX command: 'mkdir -p dir' | def command_mkdir(args):
"""
Create a non-existing directory (or more ...).
If the directory exists, the step is skipped.
Similar to the UNIX command: 'mkdir -p dir'
"""
errors = 0
for directory in args.dirs:
if os.path.exists(directory):
if not os.path.isdir(directory):
... |
Apply '2to3' tool (Python2 to Python3 conversion tool) to Python sources. | def command_py2to3(args):
"""
Apply '2to3' tool (Python2 to Python3 conversion tool) to Python sources.
"""
from lib2to3.main import main
sys.exit(main("lib2to3.fixes", args=args.sources)) |
Command util with subcommands for tox environments. | def toxcmd_main(args=None):
"""Command util with subcommands for tox environments."""
usage = "USAGE: %(prog)s [OPTIONS] COMMAND args..."
if args is None:
args = sys.argv[1:]
# -- STEP: Build command-line parser.
parser = argparse.ArgumentParser(description=inspect.getdoc(toxcmd_main),
... |
Gathers discharge macaroons for all the third party caveats in m
(and any subsequent caveats required by those) using get_discharge to
acquire each discharge macaroon.
The local_key parameter may optionally hold the key of the client, in
which case it will be used to discharge any third party caveats wi... | def discharge_all(m, get_discharge, local_key=None):
'''Gathers discharge macaroons for all the third party caveats in m
(and any subsequent caveats required by those) using get_discharge to
acquire each discharge macaroon.
The local_key parameter may optionally hold the key of the client, in
which ... |
Creates a macaroon to discharge a third party caveat.
The given parameters specify the caveat and how it should be checked.
The condition implicit in the caveat is checked for validity using checker.
If it is valid, a new macaroon is returned which discharges the caveat.
The macaroon is created with a ... | def discharge(ctx, id, caveat, key, checker, locator):
''' Creates a macaroon to discharge a third party caveat.
The given parameters specify the caveat and how it should be checked.
The condition implicit in the caveat is checked for validity using checker.
If it is valid, a new macaroon is returned w... |
Returns a third-party caveat that, when added to a macaroon with
add_caveat, results in a caveat with the location "local", encrypted with
the given PublicKey.
This can be automatically discharged by discharge_all passing a local key. | def local_third_party_caveat(key, version):
''' Returns a third-party caveat that, when added to a macaroon with
add_caveat, results in a caveat with the location "local", encrypted with
the given PublicKey.
This can be automatically discharged by discharge_all passing a local key.
'''
if versio... |
Deserialize a Namespace object.
:param data: bytes or str
:return: namespace | def deserialize_namespace(data):
''' Deserialize a Namespace object.
:param data: bytes or str
:return: namespace
'''
if isinstance(data, bytes):
data = data.decode('utf-8')
kvs = data.split()
uri_to_prefix = {}
for kv in kvs:
i = kv.rfind(':')
if i == -1:
... |
Returns a serialized form of the Namepace.
All the elements in the namespace are sorted by
URI, joined to the associated prefix with a colon and
separated with spaces.
:return: bytes | def serialize_text(self):
'''Returns a serialized form of the Namepace.
All the elements in the namespace are sorted by
URI, joined to the associated prefix with a colon and
separated with spaces.
:return: bytes
'''
if self._uri_to_prefix is None or len(self._uri... |
Registers the given URI and associates it with the given prefix.
If the URI has already been registered, this is a no-op.
:param uri: string
:param prefix: string | def register(self, uri, prefix):
'''Registers the given URI and associates it with the given prefix.
If the URI has already been registered, this is a no-op.
:param uri: string
:param prefix: string
'''
if not is_valid_schema_uri(uri):
raise KeyError(
... |
Resolves the given caveat(string) by using resolve to map from its
schema namespace to the appropriate prefix.
If there is no registered prefix for the namespace, it returns an error
caveat.
If cav.namespace is empty or cav.location is non-empty, it returns cav
unchanged.
... | def resolve_caveat(self, cav):
''' Resolves the given caveat(string) by using resolve to map from its
schema namespace to the appropriate prefix.
If there is no registered prefix for the namespace, it returns an error
caveat.
If cav.namespace is empty or cav.location is non-empty... |
Return a copy of the AuthContext object with the given key and
value added. | def with_value(self, key, val):
''' Return a copy of the AuthContext object with the given key and
value added.
'''
new_dict = dict(self._dict)
new_dict[key] = val
return AuthContext(new_dict) |
Save figures.
Parameters
----------
filename - str
Name of output file
fig_IDs - int, numpy.array, list, optional, default None
A list of open figure IDs or a figure ID that will be saved to a
pdf/png file respectively.
**kwargs -
Extra keyword arg... | def save_figures(filename, fig_IDs=None, **kwargs):
"""
Save figures.
Parameters
----------
filename - str
Name of output file
fig_IDs - int, numpy.array, list, optional, default None
A list of open figure IDs or a figure ID that will be saved to a
pdf/png f... |
Executes the command. | def execute(self):
"""
Executes the command.
"""
from vsgen.util.logger import VSGLogger
VSGLogger.info(self._logname, self._message)
start = time.clock()
for i in self._registerables:
i.register()
end = time.clock()
VSGLogger.info(sel... |
Make pattern for a data type with the specified cardinality.
.. code-block:: python
yes_no_pattern = r"yes|no"
many_yes_no = Cardinality.one_or_more.make_pattern(yes_no_pattern)
:param pattern: Regular expression for type (as string).
:param listsep: List separator f... | def make_pattern(self, pattern, listsep=','):
"""Make pattern for a data type with the specified cardinality.
.. code-block:: python
yes_no_pattern = r"yes|no"
many_yes_no = Cardinality.one_or_more.make_pattern(yes_no_pattern)
:param pattern: Regular expression for ty... |
Compute the number of regexp match groups when the pattern is provided
to the :func:`Cardinality.make_pattern()` method.
:param pattern: Item regexp pattern (as string).
:return: Number of regexp match groups in the cardinality pattern. | def compute_group_count(self, pattern):
"""Compute the number of regexp match groups when the pattern is provided
to the :func:`Cardinality.make_pattern()` method.
:param pattern: Item regexp pattern (as string).
:return: Number of regexp match groups in the cardinality pattern.
... |
Creates a type converter for the specified cardinality
by using the type converter for T.
:param cardinality: Cardinality to use (0..1, 0..*, 1..*).
:param converter: Type converter (function) for data type T.
:param pattern: Regexp pattern for an item (=converter.pattern).
:re... | def with_cardinality(cls, cardinality, converter, pattern=None,
listsep=','):
"""Creates a type converter for the specified cardinality
by using the type converter for T.
:param cardinality: Cardinality to use (0..1, 0..*, 1..*).
:param converter: Type converter... |
Creates a type converter for a T with 0..1 times
by using the type converter for one item of T.
:param converter: Type converter (function) for data type T.
:param pattern: Regexp pattern for an item (=converter.pattern).
:return: type-converter for optional<T> (T or None). | def with_zero_or_one(cls, converter, pattern=None):
"""Creates a type converter for a T with 0..1 times
by using the type converter for one item of T.
:param converter: Type converter (function) for data type T.
:param pattern: Regexp pattern for an item (=converter.pattern).
:... |
Creates a type converter function for a list<T> with 0..N items
by using the type converter for one item of T.
:param converter: Type converter (function) for data type T.
:param pattern: Regexp pattern for an item (=converter.pattern).
:param listsep: Optional list separator between ... | def with_zero_or_more(cls, converter, pattern=None, listsep=","):
"""Creates a type converter function for a list<T> with 0..N items
by using the type converter for one item of T.
:param converter: Type converter (function) for data type T.
:param pattern: Regexp pattern for an item (=... |
Creates a type converter function for a list<T> with 1..N items
by using the type converter for one item of T.
:param converter: Type converter (function) for data type T.
:param pattern: Regexp pattern for an item (=converter.pattern).
:param listsep: Optional list separator between ... | def with_one_or_more(cls, converter, pattern=None, listsep=","):
"""Creates a type converter function for a list<T> with 1..N items
by using the type converter for one item of T.
:param converter: Type converter (function) for data type T.
:param pattern: Regexp pattern for an item (=c... |
Alias for :py:meth:`with_one_or_more()` method. | def with_many(cls, converter, pattern=None, listsep=','):
"""Alias for :py:meth:`with_one_or_more()` method."""
return cls.with_one_or_more(converter, pattern, listsep) |
Alias for :py:meth:`with_zero_or_more()` method. | def with_many0(cls, converter, pattern=None, listsep=','):
"""Alias for :py:meth:`with_zero_or_more()` method."""
return cls.with_zero_or_more(converter, pattern, listsep) |
Compares objects with __slots__ defined
:param l:
:param r:
:return: | def eq_obj_slots(l, r):
"""
Compares objects with __slots__ defined
:param l:
:param r:
:return:
"""
for f in l.__slots__:
if getattr(l, f, None) != getattr(r, f, None):
return False
return True |
Compares object contents, supports slots
:param l:
:param r:
:return: | def eq_obj_contents(l, r):
"""
Compares object contents, supports slots
:param l:
:param r:
:return:
"""
if l.__class__ is not r.__class__:
return False
if hasattr(l, "__slots__"):
return eq_obj_slots(l, r)
else:
return l.__dict__ == r.__dict__ |
Returns true if x is of type in types tuple
:param x:
:param types:
:param full:
:return: | def is_type(x, types, full=False):
"""
Returns true if x is of type in types tuple
:param x:
:param types:
:param full:
:return:
"""
types = types if isinstance(types, tuple) else (types,)
ins = isinstance(x, types)
sub = False
try:
sub = issubclass(x, types)
exce... |
Builds dict for o with __slots__ defined
:param o:
:return: | def slot_obj_dict(o):
"""
Builds dict for o with __slots__ defined
:param o:
:return:
"""
d = {}
for f in o.__slots__:
d[f] = getattr(o, f, None)
return d |
Handler for serving static files. | def server_static(filepath):
"""Handler for serving static files."""
mimetype = "image/svg+xml" if filepath.endswith(".svg") else "auto"
return bottle.static_file(filepath, root=conf.StaticPath, mimetype=mimetype) |
Handler for showing mouse statistics for specified type and day. | def mouse(table, day=None):
"""Handler for showing mouse statistics for specified type and day."""
where = (("day", day),) if day else ()
events = db.fetch(table, where=where, order="day")
for e in events: e["dt"] = datetime.datetime.fromtimestamp(e["stamp"])
stats, positions, events = stats_mo... |
Handler for showing the keyboard statistics page. | def keyboard(table, day=None):
"""Handler for showing the keyboard statistics page."""
cols, group = "realkey AS key, COUNT(*) AS count", "realkey"
where = (("day", day),) if day else ()
counts_display = counts = db.fetch(table, cols, where, group, "count DESC")
if "combos" == table:
c... |
Handler for showing keyboard or mouse page with day and total links. | def inputindex(input):
"""Handler for showing keyboard or mouse page with day and total links."""
stats = {}
countminmax = "SUM(count) AS count, MIN(day) AS first, MAX(day) AS last"
tables = ("moves", "clicks", "scrolls") if "mouse" == input else ("keys", "combos")
for table in tables:
... |
Handler for showing the GUI index page. | def index():
"""Handler for showing the GUI index page."""
stats = dict((k, {"count": 0}) for k, tt in conf.InputTables)
countminmax = "SUM(count) AS count, MIN(day) AS first, MAX(day) AS last"
for input, table in [(x, t) for x, tt in conf.InputTables for t in tt]:
row = db.fetchone("counts... |
Return statistics and collated events for keyboard events. | def stats_keyboard(events, table):
"""Return statistics and collated events for keyboard events."""
if len(events) < 2: return [], []
deltas, prev_dt = [], None
sessions, session = [], None
UNBROKEN_DELTA = datetime.timedelta(seconds=conf.KeyboardSessionMaxDelta)
blank = collections.defaul... |
Returns statistics, positions and rescaled events for mouse events. | def stats_mouse(events, table):
"""Returns statistics, positions and rescaled events for mouse events."""
if not events: return [], [], []
distance, last, deltas = 0, None, []
HS = conf.MouseHeatmapSize
SC = dict(("xy"[i], conf.DefaultScreenSize[i] / float(HS[i])) for i in [0, 1])
xymap = ... |
Returns the total timedelta duration in seconds. | def timedelta_seconds(timedelta):
"""Returns the total timedelta duration in seconds."""
return (timedelta.total_seconds() if hasattr(timedelta, "total_seconds")
else timedelta.days * 24 * 3600 + timedelta.seconds +
timedelta.microseconds / 1000000.) |
Initialize configuration and web application. | def init():
"""Initialize configuration and web application."""
global app
if app: return app
conf.init(), db.init(conf.DbPath, conf.DbStatements)
bottle.TEMPLATE_PATH.insert(0, conf.TemplatePath)
app = bottle.default_app()
bottle.BaseTemplate.defaults.update(get_url=app.get_url)
... |
Starts the web server. | def start():
"""Starts the web server."""
global app
bottle.run(app, host=conf.WebHost, port=conf.WebPort,
debug=conf.WebAutoReload, reloader=conf.WebAutoReload,
quiet=conf.WebQuiet) |
Handle the download of an URL, using the proxy currently set in \
:mod:`socks`.
:param url: The URL to download.
:returns: A tuple of the raw content of the downloaded data and its \
associated content-type. Returns None if it was \
unable to download the document. | def _download_helper(url):
"""
Handle the download of an URL, using the proxy currently set in \
:mod:`socks`.
:param url: The URL to download.
:returns: A tuple of the raw content of the downloaded data and its \
associated content-type. Returns None if it was \
una... |
Download a PDF or DJVU document from a url, eventually using proxies.
:params url: The URL to the PDF/DJVU document to fetch.
:params proxies: An optional list of proxies to use. Proxies will be \
used sequentially. Proxies should be a list of proxy strings. \
Do not forget to include `... | def download(url, proxies=None):
"""
Download a PDF or DJVU document from a url, eventually using proxies.
:params url: The URL to the PDF/DJVU document to fetch.
:params proxies: An optional list of proxies to use. Proxies will be \
used sequentially. Proxies should be a list of proxy stri... |
Build format string from a format specification.
:param format_spec: Format specification (as FormatSpec object).
:return: Composed format (as string). | def make_format(format_spec):
"""Build format string from a format specification.
:param format_spec: Format specification (as FormatSpec object).
:return: Composed format (as string).
"""
fill = ''
align = ''
zero = ''
width = format_spec.width
... |
Pull apart the format: [[fill]align][0][width][.precision][type] | def extract_format_spec(cls, format):
"""Pull apart the format: [[fill]align][0][width][.precision][type]"""
# -- BASED-ON: parse.extract_format()
# pylint: disable=redefined-builtin, unsubscriptable-object
if not format:
raise ValueError("INVALID-FORMAT: %s (empty-string)" %... |
Extract fields in a parse expression schema.
:param schema: Parse expression schema/format to use (as string).
:return: Generator for fields in schema (as Field objects). | def extract_fields(cls, schema):
"""Extract fields in a parse expression schema.
:param schema: Parse expression schema/format to use (as string).
:return: Generator for fields in schema (as Field objects).
"""
# -- BASED-ON: parse.Parser._generate_expression()
for part ... |
Extract types (names) for typed fields (with format/type part).
:param schema: Parser schema/format to use.
:return: Generator for type names (as string). | def extract_types(cls, schema):
"""Extract types (names) for typed fields (with format/type part).
:param schema: Parser schema/format to use.
:return: Generator for type names (as string).
"""
for field in cls.extract_fields(schema):
if field.has_format:
... |
Registers a handler.
:param handler: A handler object. | def _registerHandler(self, handler):
"""
Registers a handler.
:param handler: A handler object.
"""
self._logger.addHandler(handler)
self._handlers.append(handler) |
Unregisters the logging handler.
:param handler: A handler previously registered with this loggger.
:param shutdown: Flag to shutdown the handler. | def _unregisterHandler(self, handler, shutdown=True):
"""
Unregisters the logging handler.
:param handler: A handler previously registered with this loggger.
:param shutdown: Flag to shutdown the handler.
"""
if handler in self._handlers:
self._handlers.remo... |
Retrieves the Python native logger
:param name: The name of the logger instance in the VSG namespace (VSG.<name>); a None value will use the VSG root.
:return: The instacne of the Python logger object. | def getLogger(cls, name=None):
"""
Retrieves the Python native logger
:param name: The name of the logger instance in the VSG namespace (VSG.<name>); a None value will use the VSG root.
:return: The instacne of the Python logger object.
"""
return logging.getLo... |
Convenience function to log a message at the DEBUG level.
:param name: The name of the logger instance in the VSG namespace (VSG.<name>)
:param message: A message format string.
:param args: The arguments that are are merged into msg using the string formatting operator.
:..note: ... | def debug(cls, name, message, *args):
"""
Convenience function to log a message at the DEBUG level.
:param name: The name of the logger instance in the VSG namespace (VSG.<name>)
:param message: A message format string.
:param args: The arguments that are are merged into m... |
Convenience function to log a message at the INFO level.
:param name: The name of the logger instance in the VSG namespace (VSG.<name>)
:param message: A message format string.
:param args: The arguments that are are merged into msg using the string formatting operator.
:..note: ... | def info(cls, name, message, *args):
"""
Convenience function to log a message at the INFO level.
:param name: The name of the logger instance in the VSG namespace (VSG.<name>)
:param message: A message format string.
:param args: The arguments that are are merged into msg... |
Convenience function to log a message at the WARNING level.
:param name: The name of the logger instance in the VSG namespace (VSG.<name>)
:param message: A message format string.
:param args: The arguments that are are merged into msg using the string formatting operator.
:..note... | def warning(cls, name, message, *args):
"""
Convenience function to log a message at the WARNING level.
:param name: The name of the logger instance in the VSG namespace (VSG.<name>)
:param message: A message format string.
:param args: The arguments that are are merged in... |
Convenience function to log a message at the ERROR level.
:param name: The name of the logger instance in the VSG namespace (VSG.<name>)
:param message: A message format string.
:param args: The arguments that are are merged into msg using the string formatting operator.
:..note: ... | def error(cls, name, message, *args):
"""
Convenience function to log a message at the ERROR level.
:param name: The name of the logger instance in the VSG namespace (VSG.<name>)
:param message: A message format string.
:param args: The arguments that are are merged into m... |
Convenience function to log a message at the CRITICAL level.
:param name: The name of the logger instance in the VSG namespace (VSG.<name>)
:param message: A message format string.
:param args: The arguments that are are merged into msg using the string formatting operator.
:..not... | def critical(cls, name, message, *args):
"""
Convenience function to log a message at the CRITICAL level.
:param name: The name of the logger instance in the VSG namespace (VSG.<name>)
:param message: A message format string.
:param args: The arguments that are are merged ... |
Convenience function to log a message at the ERROR level with additonal exception information.
:param name: The name of the logger instance in the VSG namespace (VSG.<name>)
:param message: A message format string.
:param args: The arguments that are are merged into msg using the string f... | def exception(cls, name, message, *args):
"""
Convenience function to log a message at the ERROR level with additonal exception information.
:param name: The name of the logger instance in the VSG namespace (VSG.<name>)
:param message: A message format string.
:param args: ... |
Checks that the authorizer's request is authorized to
perform all the given operations. Note that allow does not check
first party caveats - if there is more than one macaroon that may
authorize the request, it will choose the first one that does
regardless.
If all the operation... | def allow(self, ctx, ops):
''' Checks that the authorizer's request is authorized to
perform all the given operations. Note that allow does not check
first party caveats - if there is more than one macaroon that may
authorize the request, it will choose the first one that does
re... |
like allow except that it will authorize as many of the
operations as possible without requiring any to be authorized. If all
the operations succeeded, the array will be nil.
If any the operations failed, the returned error will be the same
that allow would return and each element in th... | def allow_any(self, ctx, ops):
''' like allow except that it will authorize as many of the
operations as possible without requiring any to be authorized. If all
the operations succeeded, the array will be nil.
If any the operations failed, the returned error will be the same
tha... |
Checks that the user is allowed to perform all the
given operations. If not, a discharge error will be raised.
If allow_capability succeeds, it returns a list of first party caveat
conditions that must be applied to any macaroon granting capability
to execute the operations. Those caveat... | def allow_capability(self, ctx, ops):
'''Checks that the user is allowed to perform all the
given operations. If not, a discharge error will be raised.
If allow_capability succeeds, it returns a list of first party caveat
conditions that must be applied to any macaroon granting capabilit... |
Deactivates/unregisters all recipes of the current plugin, if this plugin gets deactivated. | def __deactivate_recipes(self, plugin, *args, **kwargs):
"""
Deactivates/unregisters all recipes of the current plugin, if this plugin gets deactivated.
"""
recipes = self.get()
for recipe in recipes.keys():
self.unregister(recipe) |
Registers a new recipe in the context of the current plugin.
:param name: Name of the recipe
:param path: Absolute path of the recipe folder
:param description: A meaningful description of the recipe
:param final_words: A string, which gets printed after the recipe was build. | def register(self, name, path, description, final_words=None):
"""
Registers a new recipe in the context of the current plugin.
:param name: Name of the recipe
:param path: Absolute path of the recipe folder
:param description: A meaningful description of the recipe
:par... |
Gets a list of all recipes, which are registered by the current plugin.
If a name is provided, only the requested recipe is returned or None.
:param: name: Name of the recipe | def get(self, name=None):
"""
Gets a list of all recipes, which are registered by the current plugin.
If a name is provided, only the requested recipe is returned or None.
:param: name: Name of the recipe
"""
return self.__app.recipes.get(name, self._plugin) |
Builds a recipe
:param recipe: Name of the recipe to build. | def build(self, recipe):
"""
Builds a recipe
:param recipe: Name of the recipe to build.
"""
return self.__app.recipes.build(recipe, self._plugin) |
Registers a new recipe. | def register(self, name, path, plugin, description=None, final_words=None):
"""
Registers a new recipe.
"""
if name in self.recipes.keys():
raise RecipeExistsException("Recipe %s was already registered by %s" %
(name, self.recipes["name... |
Unregisters an existing recipe, so that this recipe is no longer available.
This function is mainly used during plugin deactivation.
:param recipe: Name of the recipe | def unregister(self, recipe):
"""
Unregisters an existing recipe, so that this recipe is no longer available.
This function is mainly used during plugin deactivation.
:param recipe: Name of the recipe
"""
if recipe not in self.recipes.keys():
self.__log.warn... |
Get one or more recipes.
:param recipe: Name of the recipe
:type recipe: str
:param plugin: Plugin object, under which the recipe was registered
:type plugin: GwBasePattern | def get(self, recipe=None, plugin=None):
"""
Get one or more recipes.
:param recipe: Name of the recipe
:type recipe: str
:param plugin: Plugin object, under which the recipe was registered
:type plugin: GwBasePattern
"""
if plugin is not None:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.