code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def is_byte_range_valid(start, stop, length):
"""Checks if a given byte content range is valid for the given length.
.. versionadded:: 0.7
"""
if (start is None) != (stop is None):
return False
elif start is None:
return length is None or length >= 0
elif length is None:
... | Checks if a given byte content range is valid for the given length.
.. versionadded:: 0.7 |
def _build_specs(self, specs, kwargs, fp_precision):
"""
Returns the specs, the remaining kwargs and whether or not the
constructor was called with kwarg or explicit specs.
"""
if specs is None:
overrides = param.ParamOverrides(self, kwargs,
... | Returns the specs, the remaining kwargs and whether or not the
constructor was called with kwarg or explicit specs. |
def process_tags(self, user, msg, reply, st=[], bst=[], depth=0, ignore_object_errors=True):
"""Post process tags in a message.
:param str user: The user ID.
:param str msg: The user's formatted message.
:param str reply: The raw RiveScript reply for the message.
:param []str st... | Post process tags in a message.
:param str user: The user ID.
:param str msg: The user's formatted message.
:param str reply: The raw RiveScript reply for the message.
:param []str st: The array of ``<star>`` matches from the trigger.
:param []str bst: The array of ``<botstar>``... |
def run(self, module, post_check):
''' Execute the configured source code in a module and run any post
checks.
Args:
module (Module) : a module to execute the configured code in.
post_check(callable) : a function that can raise an exception
if expected p... | Execute the configured source code in a module and run any post
checks.
Args:
module (Module) : a module to execute the configured code in.
post_check(callable) : a function that can raise an exception
if expected post-conditions are not met after code execution... |
def merge_extras(items, config):
"""Merge extra disambiguated reads into a final BAM file.
"""
final = {}
for extra_name in items[0]["disambiguate"].keys():
in_files = []
for data in items:
in_files.append(data["disambiguate"][extra_name])
out_file = "%s-allmerged%s" ... | Merge extra disambiguated reads into a final BAM file. |
def _get_raw_xsrf_token(self) -> Tuple[Optional[int], bytes, float]:
"""Read or generate the xsrf token in its raw form.
The raw_xsrf_token is a tuple containing:
* version: the version of the cookie from which this token was read,
or None if we generated a new token in this request.... | Read or generate the xsrf token in its raw form.
The raw_xsrf_token is a tuple containing:
* version: the version of the cookie from which this token was read,
or None if we generated a new token in this request.
* token: the raw token data; random (non-ascii) bytes.
* timest... |
def group_add(self, name='Ungrouped'):
"""
Dynamically add a group instance to the system if not exist.
Parameters
----------
name : str, optional ('Ungrouped' as default)
Name of the group
Returns
-------
None
"""
if not hasa... | Dynamically add a group instance to the system if not exist.
Parameters
----------
name : str, optional ('Ungrouped' as default)
Name of the group
Returns
-------
None |
def to_json(data, filename='data.json', indent=4):
"""
Write an object to a json file
:param data: The object
:param filename: The name of the file
:param indent: The indentation of the file
:return: None
"""
with open(filename, 'w') as f:
f.write(json.dumps(data, in... | Write an object to a json file
:param data: The object
:param filename: The name of the file
:param indent: The indentation of the file
:return: None |
def send_once(remote, codes, count=None, device=None, address=None):
"""
All parameters are passed to irsend. See the man page for irsend
for details about their usage.
Parameters
----------
remote: str
codes: [str]
count: int
device: str
address: str
Notes
-----
No... | All parameters are passed to irsend. See the man page for irsend
for details about their usage.
Parameters
----------
remote: str
codes: [str]
count: int
device: str
address: str
Notes
-----
No attempt is made to catch or handle errors. See the documentation
for subproc... |
def POST(self):
""" The HTTP POST body parsed into a MultiDict.
This supports urlencoded and multipart POST requests. Multipart
is commonly used for file uploads and may result in some of the
values beeing cgi.FieldStorage objects instead of strings.
Multiple va... | The HTTP POST body parsed into a MultiDict.
This supports urlencoded and multipart POST requests. Multipart
is commonly used for file uploads and may result in some of the
values beeing cgi.FieldStorage objects instead of strings.
Multiple values per key are possible. S... |
def crossdomain(f):
"""This decorator sets the rules for the crossdomain request per http
method. The settings are taken from the actual resource itself, and
returned as per the CORS spec.
All CORS requests are rejected if the resource's `allow_methods`
doesn't include the 'OPTIONS' met... | This decorator sets the rules for the crossdomain request per http
method. The settings are taken from the actual resource itself, and
returned as per the CORS spec.
All CORS requests are rejected if the resource's `allow_methods`
doesn't include the 'OPTIONS' method. |
def _expand_variable_match(positional_vars, named_vars, match):
"""Expand a matched variable with its value.
Args:
positional_vars (list): A list of positonal variables. This list will
be modified.
named_vars (dict): A dictionary of named variables.
match (re.Match): A regul... | Expand a matched variable with its value.
Args:
positional_vars (list): A list of positonal variables. This list will
be modified.
named_vars (dict): A dictionary of named variables.
match (re.Match): A regular expression match.
Returns:
str: The expanded variable t... |
def hash_str(data, hasher=None):
"""Checksum hash a string."""
hasher = hasher or hashlib.sha1()
hasher.update(data)
return hasher | Checksum hash a string. |
def assign_objective_requisite(self, objective_id=None, requisite_objective_id=None):
"""Creates a requirement dependency between two Objectives.
arg: objective_id (osid.id.Id): the Id of the dependent
Objective
arg: requisite_objective_id (osid.id.Id): the Id of the
... | Creates a requirement dependency between two Objectives.
arg: objective_id (osid.id.Id): the Id of the dependent
Objective
arg: requisite_objective_id (osid.id.Id): the Id of the
required Objective
raise: AlreadyExists - objective_id already mapped to
... |
def sunion(self, keys, *args):
"""Emulate sunion."""
func = lambda left, right: left.union(right)
return self._apply_to_sets(func, "SUNION", keys, *args) | Emulate sunion. |
def verify_submit(self, job_ids, timeout, delay, **kwargs):
"""Verifies that the results were successfully submitted."""
if self.skip:
return False
jobs = self.wait_for_jobs(job_ids, timeout, delay)
self.get_logs(jobs, log_file=kwargs.get("log_file"))
return self._c... | Verifies that the results were successfully submitted. |
def key_size(self):
"""*new in 0.4.1*
The size pertaining to this key. ``int`` for non-EC key algorithms; :py:obj:`constants.EllipticCurveOID` for EC keys.
"""
if self.key_algorithm in {PubKeyAlgorithm.ECDSA, PubKeyAlgorithm.ECDH}:
return self._key.keymaterial.oid
ret... | *new in 0.4.1*
The size pertaining to this key. ``int`` for non-EC key algorithms; :py:obj:`constants.EllipticCurveOID` for EC keys. |
def run_toy_DistilledSGLD(gpu_id):
"""Run DistilledSGLD on toy dataset"""
X, Y, X_test, Y_test = load_toy()
minibatch_size = 1
teacher_noise_precision = 1.0
teacher_net = get_toy_sym(True, teacher_noise_precision)
student_net = get_toy_sym(False)
data_shape = (minibatch_size,) + X.shape[1::]... | Run DistilledSGLD on toy dataset |
def input_fields(self, preamble, *args):
"""Get a set of fields from the user. Optionally a preamble may be
shown to the user secribing the fields to return. The fields are
specified as the remaining arguments with each field being a a
list with the following entries:
- a pr... | Get a set of fields from the user. Optionally a preamble may be
shown to the user secribing the fields to return. The fields are
specified as the remaining arguments with each field being a a
list with the following entries:
- a programmer-visible name for the field
- a ... |
def _extract_authors(pub, idx, _root):
"""
Create a concatenated string of author names. Separate names with semi-colons.
:param any pub: Publication author structure is ambiguous
:param int idx: Index number of Pub
"""
logger_ts.info("enter extract_authors")
try:
# DOI Author data. ... | Create a concatenated string of author names. Separate names with semi-colons.
:param any pub: Publication author structure is ambiguous
:param int idx: Index number of Pub |
def create_queue_wrapper(name, queue_size, fed_arrays, data_sources, *args, **kwargs):
"""
Arguments
name: string
Name of the queue
queue_size: integer
Size of the queue
fed_arrays: list
array names that will be fed by this queue
data_sources: ... | Arguments
name: string
Name of the queue
queue_size: integer
Size of the queue
fed_arrays: list
array names that will be fed by this queue
data_sources: dict
(lambda/method, dtype) tuples, keyed on array names |
def read_playlists(self):
self.playlists = []
self.selected_playlist = -1
files = glob.glob(path.join(self.stations_dir, '*.csv'))
if len(files) == 0:
return 0, -1
else:
for a_file in files:
a_file_name = ''.join(path.basename(a_file).split... | get already loaded playlist id |
def negative_directional_index(close_data, high_data, low_data, period):
"""
Negative Directional Index (-DI).
Formula:
-DI = 100 * SMMA(-DM) / ATR
"""
catch_errors.check_for_input_len_diff(close_data, high_data, low_data)
ndi = (100 *
smma(negative_directional_movement(high_data... | Negative Directional Index (-DI).
Formula:
-DI = 100 * SMMA(-DM) / ATR |
def exec_container_commands(self, action, c_name, **kwargs):
"""
Runs all configured commands of a container configuration inside the container instance.
:param action: Action configuration.
:type action: dockermap.map.runner.ActionConfig
:param c_name: Container name.
:... | Runs all configured commands of a container configuration inside the container instance.
:param action: Action configuration.
:type action: dockermap.map.runner.ActionConfig
:param c_name: Container name.
:type c_name: unicode | str
:return: List of exec command return values (e... |
def get_composite_keywords(ckw_db, fulltext, skw_spans):
"""Return a list of composite keywords bound with number of occurrences.
:param ckw_db: list of KewordToken objects
(they are supposed to be composite ones)
:param fulltext: string to search in
:param skw_spans: dictionary of a... | Return a list of composite keywords bound with number of occurrences.
:param ckw_db: list of KewordToken objects
(they are supposed to be composite ones)
:param fulltext: string to search in
:param skw_spans: dictionary of already identified single keywords
:return : dictionary of m... |
def make_prototype_request(*args, **kwargs):
"""Make a prototype Request for a Matcher."""
if args and inspect.isclass(args[0]) and issubclass(args[0], Request):
request_cls, arg_list = args[0], args[1:]
return request_cls(*arg_list, **kwargs)
if args and isinstance(args[0], Request):
... | Make a prototype Request for a Matcher. |
def get_autype_list(self, code_list):
"""
获取给定股票列表的复权因子
:param code_list: 股票列表,例如['HK.00700']
:return: (ret, data)
ret == RET_OK 返回pd dataframe数据,data.DataFrame数据, 数据列格式如下
ret != RET_OK 返回错误字符串
===================== =========== ====... | 获取给定股票列表的复权因子
:param code_list: 股票列表,例如['HK.00700']
:return: (ret, data)
ret == RET_OK 返回pd dataframe数据,data.DataFrame数据, 数据列格式如下
ret != RET_OK 返回错误字符串
===================== =========== ==============================================================... |
def registerDirectory(self,name,physicalPath,directoryType,cleanupMode,
maxFileAge,description):
"""
Registers a new server directory. While registering the server directory,
you can also specify the directory's cleanup parameters. You can also
register a direct... | Registers a new server directory. While registering the server directory,
you can also specify the directory's cleanup parameters. You can also
register a directory by using its JSON representation as a value of the
directory parameter.
Inputs:
name - The name of the server d... |
def is_git_directory_clean(path_to_repo: Path,
search_parent_dirs: bool = True,
check_untracked: bool = False) -> None:
"""
Check that the git working directory is in a clean state
and raise exceptions if not.
:path_to_repo: The path of the git repo
... | Check that the git working directory is in a clean state
and raise exceptions if not.
:path_to_repo: The path of the git repo |
def _generate_for_subfolder(self, sid):
''' Generate report for a subfolder.
:param sid: The subfolder id; assumed valid
'''
# TODO: the following assumes subfolder names can be constructed from a
# subfolder id, which might not be the case in the future.
name = self._sa... | Generate report for a subfolder.
:param sid: The subfolder id; assumed valid |
def dispatch(restricted=False):
"""
Dispatch registered handlers.
When dispatching in restricted mode, only matching hook handlers are executed.
Handlers are dispatched according to the following rules:
* Handlers are repeatedly tested and invoked in iterations, until the system
settles int... | Dispatch registered handlers.
When dispatching in restricted mode, only matching hook handlers are executed.
Handlers are dispatched according to the following rules:
* Handlers are repeatedly tested and invoked in iterations, until the system
settles into quiescence (that is, until no new handlers... |
def random_walk(network):
"""Take a random walk from a source.
Start at a node randomly selected from those that receive input from a
source. At each step, transmit to a randomly-selected downstream node.
"""
latest = network.latest_transmission_recipient()
if (not network.transmissions() or l... | Take a random walk from a source.
Start at a node randomly selected from those that receive input from a
source. At each step, transmit to a randomly-selected downstream node. |
def num_dml_affected_rows(self):
"""Return the number of DML rows affected by the job.
See:
https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#statistics.query.numDmlAffectedRows
:rtype: int or None
:returns: number of DML rows affected by the job, or None if job is ... | Return the number of DML rows affected by the job.
See:
https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#statistics.query.numDmlAffectedRows
:rtype: int or None
:returns: number of DML rows affected by the job, or None if job is not
yet complete. |
def bbox(width=1.0, height=1.0, depth=1.0):
"""
Generates a bounding box with (0.0, 0.0, 0.0) as the center.
This is simply a box with ``LINE_STRIP`` as draw mode.
Keyword Args:
width (float): Width of the box
height (float): Height of the box
depth (float): Depth of the box
... | Generates a bounding box with (0.0, 0.0, 0.0) as the center.
This is simply a box with ``LINE_STRIP`` as draw mode.
Keyword Args:
width (float): Width of the box
height (float): Height of the box
depth (float): Depth of the box
Returns:
A :py:class:`demosys.opengl.vao.VAO` ... |
def valid_processor_options(processors=None):
"""
Return a list of unique valid options for a list of image processors
(and/or source generators)
"""
if processors is None:
processors = [
dynamic_import(p) for p in
tuple(settings.THUMBNAIL_PROCESSORS) +
tu... | Return a list of unique valid options for a list of image processors
(and/or source generators) |
def training_data(job_id):
'''Returns training_examples for a given job_id from offset to limit
If full_info parameter is greater than 0, will return extra architecture
info,
GET /jobs/139/vectors?offset=0&limit=10&full_info=1
{
"labeled_vectors": [{"vector":{"indices": {"0": 1}, "reductions": 3... | Returns training_examples for a given job_id from offset to limit
If full_info parameter is greater than 0, will return extra architecture
info,
GET /jobs/139/vectors?offset=0&limit=10&full_info=1
{
"labeled_vectors": [{"vector":{"indices": {"0": 1}, "reductions": 3}, "label":0},
... |
def flux_balance(model, reaction, tfba, solver):
"""Run flux balance analysis on the given model.
Yields the reaction id and flux value for each reaction in the model.
This is a convenience function for sertting up and running the
FluxBalanceProblem. If the FBA is solved for more than one parameter
... | Run flux balance analysis on the given model.
Yields the reaction id and flux value for each reaction in the model.
This is a convenience function for sertting up and running the
FluxBalanceProblem. If the FBA is solved for more than one parameter
it is recommended to setup and reuse the FluxBalancePr... |
def princomp(x):
"""Determine the principal components of a vector of measurements
Determine the principal components of a vector of measurements
x should be a M x N numpy array composed of M observations of n variables
The output is:
coeffs - the NxN correlation matrix that can be used to tran... | Determine the principal components of a vector of measurements
Determine the principal components of a vector of measurements
x should be a M x N numpy array composed of M observations of n variables
The output is:
coeffs - the NxN correlation matrix that can be used to transform x into its compone... |
def edit_asn(self, auth, asn, attr):
""" Edit AS number
* `auth` [BaseAuth]
AAA options.
* `asn` [integer]
AS number to edit.
* `attr` [asn_attr]
New AS attributes.
This is the documentation of the internal backend... | Edit AS number
* `auth` [BaseAuth]
AAA options.
* `asn` [integer]
AS number to edit.
* `attr` [asn_attr]
New AS attributes.
This is the documentation of the internal backend function. It's
exposed over XML-RPC,... |
def html_print_file(self, catalog, destination):
"""
Prints text_file in html.
:param catalog: text file you wish to pretty print
:param destination: where you wish to save the HTML data
:return: output in html_file.html.
"""
with open(destination, mode='r+', enco... | Prints text_file in html.
:param catalog: text file you wish to pretty print
:param destination: where you wish to save the HTML data
:return: output in html_file.html. |
def startElement (self, name, attrs):
'''if there's a start method for this element, call it
'''
func = getattr(self, 'start_' + name, None)
if func:
func(attrs) | if there's a start method for this element, call it |
def delete_view(self, request, object_id, extra_context=None):
"""
Overrides the default to enable redirecting to the directory view after
deletion of a folder.
we need to fetch the object and find out who the parent is
before super, because super will delete the object and make... | Overrides the default to enable redirecting to the directory view after
deletion of a folder.
we need to fetch the object and find out who the parent is
before super, because super will delete the object and make it
impossible to find out the parent folder to redirect to. |
def notebook_to_rst(npth, rpth, rdir, cr=None):
"""
Convert notebook at `npth` to rst document at `rpth`, in directory
`rdir`. Parameter `cr` is a CrossReferenceLookup object.
"""
# Read the notebook file
ntbk = nbformat.read(npth, nbformat.NO_CONVERT)
# Convert notebook object to rstpth
... | Convert notebook at `npth` to rst document at `rpth`, in directory
`rdir`. Parameter `cr` is a CrossReferenceLookup object. |
def requireCompatibleAPI():
"""If PyQt4's API should be configured to be compatible with PySide's
(i.e. QString and QVariant should not be explicitly exported,
cf. documentation of sip.setapi()), call this function to check that
the PyQt4 was properly imported. (It will always be config... | If PyQt4's API should be configured to be compatible with PySide's
(i.e. QString and QVariant should not be explicitly exported,
cf. documentation of sip.setapi()), call this function to check that
the PyQt4 was properly imported. (It will always be configured this
way by this module, b... |
def get_info(
self,
userSpecifier,
**kwargs
):
"""
Fetch the user information for the specified user. This endpoint is
intended to be used by the user themself to obtain their own
information.
Args:
userSpecifier:
The User ... | Fetch the user information for the specified user. This endpoint is
intended to be used by the user themself to obtain their own
information.
Args:
userSpecifier:
The User Specifier
Returns:
v20.response.Response containing the results from submi... |
def get_text_for_repeated_menu_item(
self, request=None, current_site=None, original_menu_tag='', **kwargs
):
"""Return the a string to use as 'text' for this page when it is being
included as a 'repeated' menu item in a menu. You might want to
override this method if you're creating... | Return the a string to use as 'text' for this page when it is being
included as a 'repeated' menu item in a menu. You might want to
override this method if you're creating a multilingual site and you
have different translations of 'repeated_item_text' that you wish to
surface. |
def disable_on_env(func):
"""Disable the ``func`` called if its name is present in ``VALIDATORS_DISABLED``.
:param func: The function/validator to be disabled.
:type func: callable
:returns: If disabled, the ``value`` (first positional argument) passed to
``func``. If enabled, the result of ``fu... | Disable the ``func`` called if its name is present in ``VALIDATORS_DISABLED``.
:param func: The function/validator to be disabled.
:type func: callable
:returns: If disabled, the ``value`` (first positional argument) passed to
``func``. If enabled, the result of ``func``. |
def imbox(xy, w, h, angle=0.0, **kwargs):
"""
draw boundary box
:param xy: start index xy (ji)
:param w: width
:param h: height
:param angle:
:param kwargs:
:return:
"""
from matplotlib.patches import Rectangle
return imbound(Rectangle, xy, w, h, angle, **kwargs) | draw boundary box
:param xy: start index xy (ji)
:param w: width
:param h: height
:param angle:
:param kwargs:
:return: |
def load_files(files, tag=None, sat_id=None, altitude_bin=None):
'''Loads a list of COSMIC data files, supplied by user.
Returns a list of dicts, a dict for each file.
'''
output = [None]*len(files)
drop_idx = []
for (i,file) in enumerate(files):
try:
#data = net... | Loads a list of COSMIC data files, supplied by user.
Returns a list of dicts, a dict for each file. |
def write_data(filename, data, data_format=None, compress=False, add=False):
""" Write image data to file
Function to write image data to specified file. If file format is not provided
explicitly, it is guessed from the filename extension. If format is TIFF, geo
information and compression can be optio... | Write image data to file
Function to write image data to specified file. If file format is not provided
explicitly, it is guessed from the filename extension. If format is TIFF, geo
information and compression can be optionally added.
:param filename: name of file to write data to
:type filename: ... |
def flatten(nested_list):
'''converts a list-of-lists to a single flat list'''
return_list = []
for i in nested_list:
if isinstance(i,list):
return_list += flatten(i)
else:
return_list.append(i)
return return_list | converts a list-of-lists to a single flat list |
def _win32_junction(path, link, verbose=0):
"""
On older (pre 10) versions of windows we need admin privledges to make
symlinks, however junctions seem to work.
For paths we do a junction (softlink) and for files we use a hard link
CommandLine:
python -m ubelt._win32_links _win32_junction
... | On older (pre 10) versions of windows we need admin privledges to make
symlinks, however junctions seem to work.
For paths we do a junction (softlink) and for files we use a hard link
CommandLine:
python -m ubelt._win32_links _win32_junction
Example:
>>> # xdoc: +REQUIRES(WIN32)
... |
def _check_nonlocal_and_global(self, node):
"""Check that a name is both nonlocal and global."""
def same_scope(current):
return current.scope() is node
from_iter = itertools.chain.from_iterable
nonlocals = set(
from_iter(
child.names
... | Check that a name is both nonlocal and global. |
def drawPoints(points, bg=','):
"""A small debug function that takes an iterable of (x, y) integer tuples
and draws them to the screen."""
# Note: I set bg to ',' instead of '.' because using ... in the docstrings
# confuses doctest and makes it think it's Python's secondary ... prompt,
# causing d... | A small debug function that takes an iterable of (x, y) integer tuples
and draws them to the screen. |
def cart_add(self, items, CartId=None, HMAC=None, **kwargs):
"""CartAdd.
:param items:
A dictionary containing the items to be added to the cart.
Or a list containing these dictionaries.
It is not possible to create an empty cart!
example: [{'offer_id': 'r... | CartAdd.
:param items:
A dictionary containing the items to be added to the cart.
Or a list containing these dictionaries.
It is not possible to create an empty cart!
example: [{'offer_id': 'rt2ofih3f389nwiuhf8934z87o3f4h',
'quantity': 1}]
:par... |
def _save_state(self):
"""
Helper context manager for :meth:`buffer` which saves the whole state.
This is broken out in a separate method for readability and tested
indirectly by testing :meth:`buffer`.
"""
ns_prefixes_floating_in = copy.copy(self._ns_prefixes_floating_i... | Helper context manager for :meth:`buffer` which saves the whole state.
This is broken out in a separate method for readability and tested
indirectly by testing :meth:`buffer`. |
def _get_node(template, context, name):
'''
taken originally from
http://stackoverflow.com/questions/2687173/django-how-can-i-get-a-block-from-a-template
'''
for node in template:
if isinstance(node, BlockNode) and node.name == name:
return node.nodelist.render(context)
e... | taken originally from
http://stackoverflow.com/questions/2687173/django-how-can-i-get-a-block-from-a-template |
def jsonify(symbol):
""" returns json format for symbol """
try:
# all symbols have a toJson method, try it
return json.dumps(symbol.toJson(), indent=' ')
except AttributeError:
pass
return json.dumps(symbol, indent=' ') | returns json format for symbol |
def dnld_assc(assc_name, go2obj=None, prt=sys.stdout):
"""Download association from http://geneontology.org/gene-associations."""
# Example assc_name: "tair.gaf"
# Download the Association
dirloc, assc_base = os.path.split(assc_name)
if not dirloc:
dirloc = os.getcwd()
assc_locfile = os.... | Download association from http://geneontology.org/gene-associations. |
def __sort_registry(self, svc_ref):
# type: (ServiceReference) -> None
"""
Sorts the registry, after the update of the sort key of given service
reference
:param svc_ref: A service reference with a modified sort key
"""
with self.__svc_lock:
if svc_re... | Sorts the registry, after the update of the sort key of given service
reference
:param svc_ref: A service reference with a modified sort key |
def _at(self, idx):
"""Returns a view of the array sliced at `idx` in the first dim.
This is called through ``x[idx]``.
Parameters
----------
idx : int
index for slicing the `NDArray` in the first dim.
Returns
-------
NDArray
`NDA... | Returns a view of the array sliced at `idx` in the first dim.
This is called through ``x[idx]``.
Parameters
----------
idx : int
index for slicing the `NDArray` in the first dim.
Returns
-------
NDArray
`NDArray` sharing the memory with t... |
def image(request, data):
"""
Generates identicon image based on passed data.
Arguments:
data - Data which should be used for generating an identicon. This data
will be used in order to create a digest which is used for generating the
identicon. If the data passed is a hex digest already... | Generates identicon image based on passed data.
Arguments:
data - Data which should be used for generating an identicon. This data
will be used in order to create a digest which is used for generating the
identicon. If the data passed is a hex digest already, the digest will be
used as-is.... |
def extra_reading_spec(self):
"""Additional data fields to store on disk and their decoders."""
field_names = ("frame_number", "action", "reward", "done")
data_fields = {
name: tf.FixedLenFeature([1], tf.int64) for name in field_names
}
decoders = {
name: tf.contrib.slim.tfexample_de... | Additional data fields to store on disk and their decoders. |
def split_array_like(df, columns=None): #TODO rename TODO if it's not a big performance hit, just make them arraylike? We already indicated the column explicitly (sort of) so...
'''
Split cells with array-like values along row axis.
Column names are maintained. The index is dropped.
Parameters
---... | Split cells with array-like values along row axis.
Column names are maintained. The index is dropped.
Parameters
----------
df : ~pandas.DataFrame
Data frame ``df[columns]`` should contain :py:class:`~pytil.numpy.ArrayLike`
values.
columns : ~typing.Collection[str] or str or None
... |
def getrefnames(idf, objname):
"""get the reference names for this object"""
iddinfo = idf.idd_info
dtls = idf.model.dtls
index = dtls.index(objname)
fieldidds = iddinfo[index]
for fieldidd in fieldidds:
if 'field' in fieldidd:
if fieldidd['field'][0].endswith('Name'):
... | get the reference names for this object |
def mpub(self, topic, messages, binary=True):
'''Send multiple messages to a topic. Optionally pack the messages'''
if binary:
# Pack and ship the data
return self.post('mpub', data=pack(messages)[4:],
params={'topic': topic, 'binary': True})
elif any('\n'... | Send multiple messages to a topic. Optionally pack the messages |
def _write_value(self, field_type, value):
"""
Writes an item of an array
:param field_type: Value type
:param value: The value itself
"""
if len(field_type) > 1:
# We don't need details for arrays and objects
field_type = field_type[0]
i... | Writes an item of an array
:param field_type: Value type
:param value: The value itself |
def encrypt_to(self, f, mac_bytes=10):
""" Returns a file like object `ef'. Anything written to `ef'
will be encrypted for this pubkey and written to `f'. """
ctx = EncryptionContext(f, self.p, mac_bytes)
yield ctx
ctx.finish() | Returns a file like object `ef'. Anything written to `ef'
will be encrypted for this pubkey and written to `f'. |
def salt_and_pepper_noise(X, v):
"""Apply salt and pepper noise to data in X.
In other words a fraction v of elements of X
(chosen at random) is set to its maximum or minimum value according to a
fair coin flip.
If minimum or maximum are not given, the min (max) value in X is taken.
:param X: a... | Apply salt and pepper noise to data in X.
In other words a fraction v of elements of X
(chosen at random) is set to its maximum or minimum value according to a
fair coin flip.
If minimum or maximum are not given, the min (max) value in X is taken.
:param X: array_like, Input data
:param v: int,... |
def load(self):
"""
Extract tabular data as |TableData| instances from a MediaWiki text
object.
|load_source_desc_text|
:return:
Loaded table data iterator.
|load_table_name_desc|
=================== =========================================... | Extract tabular data as |TableData| instances from a MediaWiki text
object.
|load_source_desc_text|
:return:
Loaded table data iterator.
|load_table_name_desc|
=================== ==============================================
Format specifier ... |
def import_new_atlas_pointings(
self,
recent=False):
"""
*Import any new ATLAS pointings from the atlas3/atlas4 databases into the ``atlas_exposures`` table of the Atlas Movers database*
**Key Arguments:**
- ``recent`` -- only sync the most recent 2 weeks of ... | *Import any new ATLAS pointings from the atlas3/atlas4 databases into the ``atlas_exposures`` table of the Atlas Movers database*
**Key Arguments:**
- ``recent`` -- only sync the most recent 2 weeks of data (speeds things up)
**Return:**
- None
**Usage:**
... |
def compress_encoder(inputs,
hparams,
strides=(2, 2),
kernel_size=(3, 3),
name=None):
"""Encoder that compresses 2-D inputs by 2**num_compress_steps.
Args:
inputs: Tensor of shape [batch, height, width, channels].
hparams: ... | Encoder that compresses 2-D inputs by 2**num_compress_steps.
Args:
inputs: Tensor of shape [batch, height, width, channels].
hparams: HParams.
strides: Tuple, strides for conv block.
kernel_size: Tuple, kernel window size for conv block.
name: string, variable scope.
Returns:
Tensor of sha... |
def getObjectWorkflowStates(self):
"""This method is used to populate catalog values
Returns a dictionary with the workflow id as key and workflow state as
value.
:return: {'review_state':'active',...}
"""
workflow = getToolByName(self, 'portal_workflow')
states =... | This method is used to populate catalog values
Returns a dictionary with the workflow id as key and workflow state as
value.
:return: {'review_state':'active',...} |
def _map_term_using_schema(master, path, term, schema_edges):
"""
IF THE WHERE CLAUSE REFERS TO FIELDS IN THE SCHEMA, THEN EXPAND THEM
"""
output = FlatList()
for k, v in term.items():
dimension = schema_edges[k]
if isinstance(dimension, Dimension):
domain = dimension.get... | IF THE WHERE CLAUSE REFERS TO FIELDS IN THE SCHEMA, THEN EXPAND THEM |
def PrintField(self, field, value):
"""Print a single field name/value pair."""
out = self.out
out.write(' ' * self.indent)
if self.use_field_number:
out.write(str(field.number))
else:
if field.is_extension:
out.write('[')
if (field.containing_type.GetOptions().message_se... | Print a single field name/value pair. |
def create_doc_dict(self, document, doc_key=None, owner_document=None):
"""
Generate a dictionary representation of the document. (no recursion)
DO NOT CALL DIRECTLY
"""
# Get doc field for top level documents
if owner_document:
doc_field = owner_document._f... | Generate a dictionary representation of the document. (no recursion)
DO NOT CALL DIRECTLY |
def from_ep_string(cls, ep_string, location):
"""Initalize from an EnergyPlus string of a SizingPeriod:DesignDay.
args:
ep_string: A full string representing a SizingPeriod:DesignDay.
"""
# format the object into a list of properties
ep_string = ep_string.strip()
... | Initalize from an EnergyPlus string of a SizingPeriod:DesignDay.
args:
ep_string: A full string representing a SizingPeriod:DesignDay. |
def _op_to_matrix(self,
op: Optional[ops.Operation],
qubits: Tuple[ops.Qid, ...]
) -> Optional[np.ndarray]:
"""Determines the effect of an operation on the given qubits.
If the operation is a 1-qubit operation on one of the given qubits,... | Determines the effect of an operation on the given qubits.
If the operation is a 1-qubit operation on one of the given qubits,
or a 2-qubit operation on both of the given qubits, and also the
operation has a known matrix, then a matrix is returned. Otherwise None
is returned.
A... |
def delete_node(self, node_name, graph=None):
""" Deletes this node and all edges referencing it. """
if not graph:
graph = self.graph
if node_name not in graph:
raise KeyError('node %s does not exist' % node_name)
graph.pop(node_name)
for node, edges in ... | Deletes this node and all edges referencing it. |
def get_line_pattern_rules(declarations, dirs):
""" Given a list of declarations, return a list of output.Rule objects.
Optionally provide an output directory for local copies of image files.
"""
property_map = {'line-pattern-file': 'file', 'line-pattern-width': 'width',
... | Given a list of declarations, return a list of output.Rule objects.
Optionally provide an output directory for local copies of image files. |
def __check_classes(self):
"""
Check if any of the default classes (`Authentication`, `Configuration`
and / or `Responses`) have been overwitten and if they're still valid
"""
# msg took from BaseAuthentication
msg = (
"Sanic JWT was not initialized properly. ... | Check if any of the default classes (`Authentication`, `Configuration`
and / or `Responses`) have been overwitten and if they're still valid |
def read(self, size=None):
"""Read at most size bytes from this buffer.
Bytes read from this buffer are consumed and are permanently removed.
Args:
size: If provided, read no more than size bytes from the buffer.
Otherwise, this reads the entire buffer.
Returns:
... | Read at most size bytes from this buffer.
Bytes read from this buffer are consumed and are permanently removed.
Args:
size: If provided, read no more than size bytes from the buffer.
Otherwise, this reads the entire buffer.
Returns:
The bytes read from this buf... |
def lowercase(state):
"""Convert all column names to their lower case versions to improve robustness
:Example:
Suppose we are testing the following SELECT statements
* solution: ``SELECT artist_id as id FROM artists``
* student : ``SELECT artist_id as ID FROM artists``
We... | Convert all column names to their lower case versions to improve robustness
:Example:
Suppose we are testing the following SELECT statements
* solution: ``SELECT artist_id as id FROM artists``
* student : ``SELECT artist_id as ID FROM artists``
We can write the following SCTs... |
def get_contents_debug_adapter_protocol(self, lst, fmt=None):
'''
This method is to be used in the case where the variables are all saved by its id (and as
such don't need to have the `resolve` method called later on, so, keys don't need to
embed the reference in the key).
Note ... | This method is to be used in the case where the variables are all saved by its id (and as
such don't need to have the `resolve` method called later on, so, keys don't need to
embed the reference in the key).
Note that the return should be ordered.
:return list(tuple(name:str, value:obj... |
def series_resistance(self, channel, resistor_index=None):
'''
Parameters
----------
channel : int
Analog channel index.
resistor_index : int, optional
Series resistor channel index.
If :data:`resistor_index` is not specified, the resistor-ind... | Parameters
----------
channel : int
Analog channel index.
resistor_index : int, optional
Series resistor channel index.
If :data:`resistor_index` is not specified, the resistor-index from
the current context _(i.e., the result of
:attr... |
def cartpole():
"""Configuration for the cart pole classic control task."""
locals().update(default())
# Environment
env = 'CartPole-v1'
max_length = 500
steps = 2e5 # 200k
normalize_ranges = False # The env reports wrong ranges.
# Network
network = networks.feed_forward_categorical
return locals(... | Configuration for the cart pole classic control task. |
def _infer_record_outputs(inputs, unlist, file_vs, std_vs, parallel, to_include=None,
exclude=None):
"""Infer the outputs of a record from the original inputs
"""
fields = []
unlist = set([_get_string_vid(x) for x in unlist])
input_vids = set([_get_string_vid(v) for v in _h... | Infer the outputs of a record from the original inputs |
def _ows_check_charm_func(state, message, charm_func_with_configs):
"""Run a custom check function for the charm to see if it wants to
change the state. This is only run if not in 'maintenance' and
tests to see if the new state is more important that the previous
one determined by the interfaces/relati... | Run a custom check function for the charm to see if it wants to
change the state. This is only run if not in 'maintenance' and
tests to see if the new state is more important that the previous
one determined by the interfaces/relations check.
@param state: the previously determined state so far.
@... |
def S_isothermal_pipe_to_two_planes(D, Z, L=1.):
r'''Returns the Shape factor `S` of a pipe of constant outer temperature
and of outer diameter `D` which is `Z` distance from two infinite
isothermal planes of equal temperatures, parallel to each other and
enclosing the pipe. Length `L` must be provided,... | r'''Returns the Shape factor `S` of a pipe of constant outer temperature
and of outer diameter `D` which is `Z` distance from two infinite
isothermal planes of equal temperatures, parallel to each other and
enclosing the pipe. Length `L` must be provided, but can be set to
1 to obtain a dimensionless sh... |
def init_layout(self):
""" Initialize the layout of the toolkit shape.
This method is called during the bottom-up pass. This method
should initialize the layout of the widget. The child widgets
will be fully initialized and layed out when this is called.
"""
for... | Initialize the layout of the toolkit shape.
This method is called during the bottom-up pass. This method
should initialize the layout of the widget. The child widgets
will be fully initialized and layed out when this is called. |
def fetch_by_client_id(self, client_id):
"""
Retrieve a client by its identifier.
:param client_id: Identifier of a client app.
:return: An instance of :class:`oauth2.Client`.
:raises: ClientNotFoundError
"""
if client_id not in self.clients:
raise C... | Retrieve a client by its identifier.
:param client_id: Identifier of a client app.
:return: An instance of :class:`oauth2.Client`.
:raises: ClientNotFoundError |
def fillna(self, column_name, value):
"""
Fill all missing values with a given value in a given column. If the
``value`` is not the same type as the values in ``column_name``, this method
attempts to convert the value to the original column's type. If this
fails, an error is rais... | Fill all missing values with a given value in a given column. If the
``value`` is not the same type as the values in ``column_name``, this method
attempts to convert the value to the original column's type. If this
fails, an error is raised.
Parameters
----------
column_... |
def audio_send_stream(self, httptype=None,
channel=None, path_file=None, encode=None):
"""
Params:
path_file - path to audio file
channel: - integer
httptype - type string (singlepart or multipart)
singlepart: HTTP content i... | Params:
path_file - path to audio file
channel: - integer
httptype - type string (singlepart or multipart)
singlepart: HTTP content is a continuos flow of audio packets
multipart: HTTP content type is multipart/x-mixed-replace, and
... |
def AssignVar(self, value):
"""Assign a value to this Value."""
self.value = value
# Call OnAssignVar on options.
[option.OnAssignVar() for option in self.options] | Assign a value to this Value. |
def dependents(self, on_predicate=None, from_predicate=None):
"""Returns a map from targets that satisfy the from_predicate to targets they depend on that
satisfy the on_predicate.
:API: public
"""
core = set(self.targets(on_predicate))
dependees = defaultdict(set)
for target in self.tar... | Returns a map from targets that satisfy the from_predicate to targets they depend on that
satisfy the on_predicate.
:API: public |
def __fetch_issue_attachments(self, issue_id):
"""Get attachments of an issue"""
for attachments_raw in self.client.issue_collection(issue_id, "attachments"):
attachments = json.loads(attachments_raw)
for attachment in attachments['entries']:
yield attachment | Get attachments of an issue |
def getEvents(self):
""" Returns a list of all events that have occurred.
Empties the internal queue.
"""
caught_events = self._observer.caught_events
self._observer.caught_events = []
for event in caught_events:
self._observer.activate_event(event["name"])
... | Returns a list of all events that have occurred.
Empties the internal queue. |
def session_end(self):
"""
End a session. Se session_begin for an in depth description of TREZOR sessions.
"""
self.session_depth -= 1
self.session_depth = max(0, self.session_depth)
if self.session_depth == 0:
self._session_end() | End a session. Se session_begin for an in depth description of TREZOR sessions. |
def report_errors_to_ga(self, errors):
"""
Report errors to Google Analytics
https://developers.google.com/analytics/devguides/collection/protocol/v1/devguide
"""
hits = []
responses = []
for field_name in sorted(errors):
for error_message in errors[fi... | Report errors to Google Analytics
https://developers.google.com/analytics/devguides/collection/protocol/v1/devguide |
def postman(host, port=587, auth=(None, None),
force_tls=False, options=None):
"""
Creates a Postman object with TLS and Auth
middleware. TLS is placed before authentication
because usually authentication happens and is
accepted only after TLS is enabled.
:param auth: Tuple of (user... | Creates a Postman object with TLS and Auth
middleware. TLS is placed before authentication
because usually authentication happens and is
accepted only after TLS is enabled.
:param auth: Tuple of (username, password) to
be used to ``login`` to the server.
:param force_tls: Whether TLS should... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.