code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def find_slot(self, wanted, slots=None):
"""
Searches the given slots or, if not given,
active hotbar slot, hotbar, inventory, open window in this order.
Args:
wanted: function(Slot) or Slot or itemID or (itemID, metadata)
Returns:
Optional[Slot]: The fi... | Searches the given slots or, if not given,
active hotbar slot, hotbar, inventory, open window in this order.
Args:
wanted: function(Slot) or Slot or itemID or (itemID, metadata)
Returns:
Optional[Slot]: The first slot containing the item
or N... |
def on_open(self):
"""
Shows an open file dialog and open the file if the dialog was
accepted.
"""
filename, filter = QtWidgets.QFileDialog.getOpenFileName(
self, _('Open'))
if filename:
self.open_file(filename) | Shows an open file dialog and open the file if the dialog was
accepted. |
def setColumnCount( self, count ):
"""
Sets the number of columns used for this tree widget, updating the \
column resizing modes to stretch the first column.
:param count | <int>
"""
super(XColorTreeWidget, self).setColumnCount(count)
heade... | Sets the number of columns used for this tree widget, updating the \
column resizing modes to stretch the first column.
:param count | <int> |
def add_unique_rule(self, rule, opname, arg_count, customize):
"""Add rule to grammar, but only if it hasn't been added previously
opname and stack_count are used in the customize() semantic
the actions to add the semantic action rule. Stack_count is
used in custom opcodes like ... | Add rule to grammar, but only if it hasn't been added previously
opname and stack_count are used in the customize() semantic
the actions to add the semantic action rule. Stack_count is
used in custom opcodes like MAKE_FUNCTION to indicate how
many arguments it has. Often it i... |
def ParseFromUnicode(self, value):
"""Parse a string into a client URN.
Convert case so that all URNs are of the form C.[0-9a-f].
Args:
value: string value to parse
"""
precondition.AssertType(value, Text)
value = value.strip()
super(ClientURN, self).ParseFromUnicode(value)
mat... | Parse a string into a client URN.
Convert case so that all URNs are of the form C.[0-9a-f].
Args:
value: string value to parse |
def get_matrix(self, x1, x2=None):
"""
Get the covariance matrix at a given set or two of independent
coordinates.
:param x1: ``(nsamples,)`` or ``(nsamples, ndim)``
A list of samples.
:param x2: ``(nsamples,)`` or ``(nsamples, ndim)`` (optional)
A secon... | Get the covariance matrix at a given set or two of independent
coordinates.
:param x1: ``(nsamples,)`` or ``(nsamples, ndim)``
A list of samples.
:param x2: ``(nsamples,)`` or ``(nsamples, ndim)`` (optional)
A second list of samples. If this is given, the cross covarian... |
def update(self, model_alias, code='general', name=None, order=None, display_filter=None):
"""
Update given tab
:param model_alias:
:param code:
:param name:
:param order:
:param display_filter:
:return:
"""
model_alias = self.get_model_al... | Update given tab
:param model_alias:
:param code:
:param name:
:param order:
:param display_filter:
:return: |
def _warn_deprecated_outside_JSONField(self): # pylint: disable=invalid-name
"""Certain methods will be moved to JSONField.
This warning marks calls when the object is not
derived from that class.
"""
if not isinstance(self, JSONField) and not self.warned:
warnings.... | Certain methods will be moved to JSONField.
This warning marks calls when the object is not
derived from that class. |
def delete(self, dict_name):
'''Delete an entire dictionary.
This operation on its own is atomic and does not require a
session lock, but a session lock is honored.
:param str dict_name: name of the dictionary to delete
:raises rejester.exceptions.LockError: if called with a se... | Delete an entire dictionary.
This operation on its own is atomic and does not require a
session lock, but a session lock is honored.
:param str dict_name: name of the dictionary to delete
:raises rejester.exceptions.LockError: if called with a session
lock, but the system doe... |
async def sign_url(self, url, method=HASH):
"""
Sign an URL with this request's auth token
"""
token = await self.get_token()
if method == self.QUERY:
return patch_qs(url, {
settings.WEBVIEW_TOKEN_KEY: token,
})
elif method == sel... | Sign an URL with this request's auth token |
def startProducing(self, consumer):
"""
Start a cooperative task which will read bytes from the input file and
write them to C{consumer}. Return a L{Deferred} which fires after all
bytes have been written.
@param consumer: Any L{IConsumer} provider
"""
self._tas... | Start a cooperative task which will read bytes from the input file and
write them to C{consumer}. Return a L{Deferred} which fires after all
bytes have been written.
@param consumer: Any L{IConsumer} provider |
def _load_features_from_array(self, features):
""" Load feature data from a 2D ndarray on disk. """
self.feature_images = np.load(features)
self.feature_names = range(self.feature_images.shape[1]) | Load feature data from a 2D ndarray on disk. |
def register_seo_admin(admin_site, metadata_class):
"""Register the backends specified in Meta.backends with the admin."""
if metadata_class._meta.use_sites:
path_admin = SitePathMetadataAdmin
model_instance_admin = SiteModelInstanceMetadataAdmin
model_admin = SiteModelMetadataAdmin
... | Register the backends specified in Meta.backends with the admin. |
def draw_to_notebook(layers, **kwargs):
"""
Draws a network diagram in an IPython notebook
:parameters:
- layers : list or NeuralNet instance
List of layers or the neural net to draw.
- **kwargs : see the docstring of make_pydot_graph for other options
"""
from IPython.di... | Draws a network diagram in an IPython notebook
:parameters:
- layers : list or NeuralNet instance
List of layers or the neural net to draw.
- **kwargs : see the docstring of make_pydot_graph for other options |
def is_integer(self, value, strict=False):
"""if value is an integer"""
if value is not None:
if isinstance(value, numbers.Number):
return
value = stringify(value)
if value is not None and value.isnumeric():
return
self.shout('value %r is n... | if value is an integer |
def post(method, hmc, uri, uri_parms, body, logon_required,
wait_for_completion):
"""Operation: Create Hipersocket (requires DPM mode)."""
assert wait_for_completion is True
cpc_oid = uri_parms[0]
try:
cpc = hmc.cpcs.lookup_by_oid(cpc_oid)
except KeyError... | Operation: Create Hipersocket (requires DPM mode). |
def sqlalch_datetime(dt):
"""Convert a SQLAlchemy datetime string to a datetime object."""
if isinstance(dt, str):
return datetime.strptime(dt, "%Y-%m-%d %H:%M:%S.%f").replace(tzinfo=UTC)
if dt.tzinfo is not None and dt.tzinfo.utcoffset(dt) is not None:
return dt.astimezone(UTC)
return d... | Convert a SQLAlchemy datetime string to a datetime object. |
def is_parent_of_gradebook(self, id_, gradebook_id):
"""Tests if an ``Id`` is a direct parent of a gradebook.
arg: id (osid.id.Id): an ``Id``
arg: gradebook_id (osid.id.Id): the ``Id`` of a gradebook
return: (boolean) - ``true`` if this ``id`` is a parent of
``grad... | Tests if an ``Id`` is a direct parent of a gradebook.
arg: id (osid.id.Id): an ``Id``
arg: gradebook_id (osid.id.Id): the ``Id`` of a gradebook
return: (boolean) - ``true`` if this ``id`` is a parent of
``gradebook_id,`` ``false`` otherwise
raise: NotFound - ``gr... |
def _normal_model(self, beta):
""" Creates the structure of the model (model matrices etc) for
a Normal family ARIMA model.
Parameters
----------
beta : np.ndarray
Contains untransformed starting values for the latent variables
Returns
----------
... | Creates the structure of the model (model matrices etc) for
a Normal family ARIMA model.
Parameters
----------
beta : np.ndarray
Contains untransformed starting values for the latent variables
Returns
----------
mu : np.ndarray
Contains t... |
def find_period(data,
min_period=0.2, max_period=32.0,
coarse_precision=1e-5, fine_precision=1e-9,
periodogram=Lomb_Scargle,
period_jobs=1):
"""find_period(data, min_period=0.2, max_period=32.0, coarse_precision=1e-5, fine_precision=1e-9, periodogram=L... | find_period(data, min_period=0.2, max_period=32.0, coarse_precision=1e-5, fine_precision=1e-9, periodogram=Lomb_Scargle, period_jobs=1)
Returns the period of *data* according to the given *periodogram*,
searching first with a coarse precision, and then a fine precision.
**Parameters**
data : array-li... |
def resolve_compound_variable_fields(dbg, thread_id, frame_id, scope, attrs):
"""
Resolve compound variable in debugger scopes by its name and attributes
:param thread_id: id of the variable's thread
:param frame_id: id of the variable's frame
:param scope: can be BY_ID, EXPRESSION, GLOBAL, LOCAL, ... | Resolve compound variable in debugger scopes by its name and attributes
:param thread_id: id of the variable's thread
:param frame_id: id of the variable's frame
:param scope: can be BY_ID, EXPRESSION, GLOBAL, LOCAL, FRAME
:param attrs: after reaching the proper scope, we have to get the attributes unt... |
def neural_gpu_body(inputs, hparams, name=None):
"""The core Neural GPU."""
with tf.variable_scope(name, "neural_gpu"):
def step(state, inp): # pylint: disable=missing-docstring
x = tf.nn.dropout(state, 1.0 - hparams.dropout)
for layer in range(hparams.num_hidden_layers):
x = common_layers... | The core Neural GPU. |
def create_asset_browser(self, ):
"""Create the asset browser
This creates a list browser for assets
and adds it to the ui
:returns: the created borwser
:rtype: :class:`jukeboxcore.gui.widgets.browser.ListBrowser`
:raises: None
"""
assetbrws = ListBrowse... | Create the asset browser
This creates a list browser for assets
and adds it to the ui
:returns: the created borwser
:rtype: :class:`jukeboxcore.gui.widgets.browser.ListBrowser`
:raises: None |
def drop_namespace_by_url(self, url: str) -> None:
"""Drop the namespace at the given URL.
Won't work if the edge store is in use.
:param url: The URL of the namespace to drop
"""
namespace = self.get_namespace_by_url(url)
self.session.query(NamespaceEntry).filter(Names... | Drop the namespace at the given URL.
Won't work if the edge store is in use.
:param url: The URL of the namespace to drop |
def bayesfactor_pearson(r, n):
"""
Bayes Factor of a Pearson correlation.
Parameters
----------
r : float
Pearson correlation coefficient
n : int
Sample size
Returns
-------
bf : str
Bayes Factor (BF10).
The Bayes Factor quantifies the evidence in fa... | Bayes Factor of a Pearson correlation.
Parameters
----------
r : float
Pearson correlation coefficient
n : int
Sample size
Returns
-------
bf : str
Bayes Factor (BF10).
The Bayes Factor quantifies the evidence in favour of the alternative
hypothesis.... |
def find_by_any(self, identifier, how):
"""
how should be a string with any or all of the characters "ilc"
"""
if "i" in how:
match = self.find_by_id(identifier)
if match:
return match
if "l" in how:
match = self.find_by_localpa... | how should be a string with any or all of the characters "ilc" |
def initialize_repository(path, spor_dir='.spor'):
"""Initialize a spor repository in `path` if one doesn't already exist.
Args:
path: Path to any file or directory within the repository.
spor_dir: The name of the directory containing spor data.
Returns: A `Repository` instance.
Raise... | Initialize a spor repository in `path` if one doesn't already exist.
Args:
path: Path to any file or directory within the repository.
spor_dir: The name of the directory containing spor data.
Returns: A `Repository` instance.
Raises:
ValueError: A repository already exists at `pat... |
def close(self):
"""Shut down an SOL session,
"""
if self.ipmi_session:
self.ipmi_session.unregister_keepalive(self.keepaliveid)
if self.activated:
try:
self.ipmi_session.raw_command(netfn=6, command=0x49,
... | Shut down an SOL session, |
def func_str(func, args=[], kwargs={}, type_aliases=[], packed=False,
packkw=None, truncate=False):
"""
string representation of function definition
Returns:
str: a representation of func with args, kwargs, and type_aliases
Args:
func (function):
args (list): argum... | string representation of function definition
Returns:
str: a representation of func with args, kwargs, and type_aliases
Args:
func (function):
args (list): argument values (default = [])
kwargs (dict): kwargs values (default = {})
type_aliases (list): (default = [])
... |
def valid_flows_array(catchment):
"""
Return array of valid flows (i.e. excluding rejected years etc)
:param catchment: gauged catchment with amax_records set
:type catchment: :class:`floodestimation.entities.Catchment`
:return: 1D array of flow values
:rtype: :class:`numpy.ndarray`
"""
... | Return array of valid flows (i.e. excluding rejected years etc)
:param catchment: gauged catchment with amax_records set
:type catchment: :class:`floodestimation.entities.Catchment`
:return: 1D array of flow values
:rtype: :class:`numpy.ndarray` |
def vars(self):
"""
:return: Returns a list of dependent, independent and sigma variables, in that order.
"""
return self.independent_vars + self.dependent_vars + [self.sigmas[var] for var in self.dependent_vars] | :return: Returns a list of dependent, independent and sigma variables, in that order. |
def add_directories(self, directories, except_blacklisted=True):
"""
Adds `directories` to the set of plugin directories.
`directories` may be either a single object or a iterable.
`directories` can be relative paths, but will be converted into
absolute paths based on the curre... | Adds `directories` to the set of plugin directories.
`directories` may be either a single object or a iterable.
`directories` can be relative paths, but will be converted into
absolute paths based on the current working directory.
if `except_blacklisted` is `True` all `directories` in... |
def stream(self, model, position):
"""Create a :class:`~bloop.stream.Stream` that provides approximate chronological ordering.
.. code-block:: pycon
# Create a user so we have a record
>>> engine = Engine()
>>> user = User(id=3, email="user@domain.com")
... | Create a :class:`~bloop.stream.Stream` that provides approximate chronological ordering.
.. code-block:: pycon
# Create a user so we have a record
>>> engine = Engine()
>>> user = User(id=3, email="user@domain.com")
>>> engine.save(user)
>>> user.ema... |
def keypoint_scale(keypoint, scale_x, scale_y, **params):
"""Scales a keypoint by scale_x and scale_y."""
x, y, a, s = keypoint
return [x * scale_x, y * scale_y, a, s * max(scale_x, scale_y)] | Scales a keypoint by scale_x and scale_y. |
def get_backend(alias):
"""
Returns ``Repository`` class identified by the given alias or raises
VCSError if alias is not recognized or backend class cannot be imported.
"""
if alias not in settings.BACKENDS:
raise VCSError("Given alias '%s' is not recognized! Allowed aliases:\n"
... | Returns ``Repository`` class identified by the given alias or raises
VCSError if alias is not recognized or backend class cannot be imported. |
def is_fnmatch_regex(string):
"""
Returns True if the given string is considered a fnmatch
regular expression, False otherwise.
It will look for
:param string: str
"""
is_regex = False
regex_chars = ['!', '*', '$']
for c in regex_chars:
if string.find(c) > -1:
r... | Returns True if the given string is considered a fnmatch
regular expression, False otherwise.
It will look for
:param string: str |
def get_instance(self, payload):
"""
Build an instance of SessionInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.proxy.v1.service.session.SessionInstance
:rtype: twilio.rest.proxy.v1.service.session.SessionInstance
"""
return Se... | Build an instance of SessionInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.proxy.v1.service.session.SessionInstance
:rtype: twilio.rest.proxy.v1.service.session.SessionInstance |
async def main():
redis = await create_pool(RedisSettings())
job = await redis.enqueue_job('the_task')
# get the job's id
print(job.job_id)
"""
> 68362958a244465b9be909db4b7b5ab4 (or whatever)
"""
# get information about the job, will include results if the job has finished, but
... | > 68362958a244465b9be909db4b7b5ab4 (or whatever) |
def _endCodeIfNeeded(line, inCodeBlock):
"""Simple routine to append end code marker if needed."""
assert isinstance(line, str)
if inCodeBlock:
line = '# @endcode{0}{1}'.format(linesep, line.rstrip())
inCodeBlock = False
return line, inCodeBlock | Simple routine to append end code marker if needed. |
def configure(self, cfg, handler, path=""):
"""
Start configuration process for the provided handler
Args:
cfg (dict): config container
handler (config.Handler class): config handler to use
path (str): current path in the configuration progress
"""
... | Start configuration process for the provided handler
Args:
cfg (dict): config container
handler (config.Handler class): config handler to use
path (str): current path in the configuration progress |
def keep_entry_range(entry, lows, highs, converter, regex):
"""
Check if an entry falls into a desired range.
Every number in the entry will be extracted using *regex*,
if any are within a given low to high range the entry will
be kept.
Parameters
----------
entry : str
lows : iter... | Check if an entry falls into a desired range.
Every number in the entry will be extracted using *regex*,
if any are within a given low to high range the entry will
be kept.
Parameters
----------
entry : str
lows : iterable
Collection of low values against which to compare the entry... |
def card_names_and_ids(self):
"""Returns [(name, id), ...] pairs of cards from current board"""
b = Board(self.client, self.board_id)
cards = b.getCards()
card_names_and_ids = [(unidecode(c.name), c.id) for c in cards]
return card_names_and_ids | Returns [(name, id), ...] pairs of cards from current board |
def close(self):
"""Flush data, write 28 bytes BGZF EOF marker, and close BGZF file.
samtools will look for a magic EOF marker, just a 28 byte empty BGZF
block, and if it is missing warns the BAM file may be truncated. In
addition to samtools writing this block, so too does bgzip - so th... | Flush data, write 28 bytes BGZF EOF marker, and close BGZF file.
samtools will look for a magic EOF marker, just a 28 byte empty BGZF
block, and if it is missing warns the BAM file may be truncated. In
addition to samtools writing this block, so too does bgzip - so this
implementation do... |
def get_sds_by_ip(self,ip):
"""
Get ScaleIO SDS object by its ip address
:param name: IP address of SDS
:return: ScaleIO SDS object
:raise KeyError: No SDS with specified ip found
:rtype: SDS object
"""
if self.conn.is_ip_addr(ip):
for sds in s... | Get ScaleIO SDS object by its ip address
:param name: IP address of SDS
:return: ScaleIO SDS object
:raise KeyError: No SDS with specified ip found
:rtype: SDS object |
def mass_fraction_within_radius(self, kwargs_lens, center_x, center_y, theta_E, numPix=100):
"""
computes the mean convergence of all the different lens model components within a spherical aperture
:param kwargs_lens: lens model keyword argument list
:param center_x: center of the apert... | computes the mean convergence of all the different lens model components within a spherical aperture
:param kwargs_lens: lens model keyword argument list
:param center_x: center of the aperture
:param center_y: center of the aperture
:param theta_E: radius of aperture
:return: l... |
def isometric_load(script, AbsName="TEMP3D.abs"):
"""Isometric parameterization: Load Abstract Domain
"""
filter_xml = ''.join([
' <filter name="Iso Parametrization Load Abstract Domain">\n',
' <Param name="AbsName"',
'value="%s"' % AbsName,
'description="Abstract Mesh f... | Isometric parameterization: Load Abstract Domain |
def patches(self, dwn, install, comp_sum, uncomp_sum):
"""Seperates packages from patches/ directory
"""
dwnp, installp, comp_sump, uncomp_sump = ([] for i in range(4))
for d, i, c, u in zip(dwn, install, comp_sum, uncomp_sum):
if "_slack" + slack_ver() in i:
... | Seperates packages from patches/ directory |
def inject_url_defaults(self, endpoint, values):
"""Injects the URL defaults for the given endpoint directly into
the values dictionary passed. This is used internally and
automatically called on URL building.
.. versionadded:: 0.7
"""
funcs = self.url_default_functions... | Injects the URL defaults for the given endpoint directly into
the values dictionary passed. This is used internally and
automatically called on URL building.
.. versionadded:: 0.7 |
async def forget(request, response):
"""Forget previously remembered identity.
Usually it clears cookie or server-side storage to forget user
session.
"""
identity_policy = request.config_dict.get(IDENTITY_KEY)
if identity_policy is None:
text = ("Security subsystem is not initialized, ... | Forget previously remembered identity.
Usually it clears cookie or server-side storage to forget user
session. |
def _parse_array(stream):
"""Parse an array, stream should be passed the initial [
returns:
Parsed array
"""
logger.debug("parsing array")
arr = []
while True:
c = stream.read(1)
if c in _GDB_MI_VALUE_START_CHARS:
stream.seek(-1)
val = _parse_val... | Parse an array, stream should be passed the initial [
returns:
Parsed array |
def _classify_move_register(self, regs_init, regs_fini, mem_fini, written_regs, read_regs):
"""Classify move-register gadgets.
"""
matches = []
regs_init_inv = self._invert_dictionary(regs_init)
# Check for "dst_reg <- src_reg" pattern.
for dst_reg, dst_val in regs_fini... | Classify move-register gadgets. |
def parse(cls, args):
"""
Parse command line arguments to construct a dictionary of command
parameters that can be used to create a command
Args:
`args`: sequence of arguments
Returns:
Dictionary that can be used in create method
Raises:
... | Parse command line arguments to construct a dictionary of command
parameters that can be used to create a command
Args:
`args`: sequence of arguments
Returns:
Dictionary that can be used in create method
Raises:
ParseError: when the arguments are no... |
def dump_artifact(obj, path, filename=None):
'''
Write the artifact to disk at the specified path
Args:
obj (string): The string object to be dumped to disk in the specified
path. The artifact filename will be automatically created
path (string): The full path to the artifacts... | Write the artifact to disk at the specified path
Args:
obj (string): The string object to be dumped to disk in the specified
path. The artifact filename will be automatically created
path (string): The full path to the artifacts data directory.
filename (string, optional): Th... |
def parse_args(self, argv=None):
""" Return an argparse.Namespace of the argv string or sys.argv if
argv is None. """
arg_input = shlex.split(argv) if argv is not None else None
self.get_or_create_session()
return self.argparser.parse_args(arg_input) | Return an argparse.Namespace of the argv string or sys.argv if
argv is None. |
def _get_base_url(request):
"""
Construct a base URL, given a request object.
This comprises the protocol prefix (http:// or https://) and the host,
which can include the port number. For example:
http://www.openquake.org or https://www.openquake.org:8000.
"""
if request.is_secure():
... | Construct a base URL, given a request object.
This comprises the protocol prefix (http:// or https://) and the host,
which can include the port number. For example:
http://www.openquake.org or https://www.openquake.org:8000. |
def split_certificate(certificate_path, destination_folder, password=None):
"""Splits a PKCS12 certificate into Base64-encoded DER certificate and key.
This method splits a potentially password-protected
`PKCS12 <https://en.wikipedia.org/wiki/PKCS_12>`_ certificate
(format ``.p12`` or ``.pfx``) into on... | Splits a PKCS12 certificate into Base64-encoded DER certificate and key.
This method splits a potentially password-protected
`PKCS12 <https://en.wikipedia.org/wiki/PKCS_12>`_ certificate
(format ``.p12`` or ``.pfx``) into one certificate and one key part, both in
`pem <https://en.wikipedia.org/wiki/X.5... |
def map_sprinkler(self, sx, sy, watered_crop='^', watered_field='_', dry_field=' ', dry_crop='x'):
"""
Return a version of the ASCII map showing reached crop cells.
"""
# convert strings (rows) to lists of characters for easier map editing
maplist = [list(s) for s in self.maplist... | Return a version of the ASCII map showing reached crop cells. |
def search(self, cond):
"""
Search for all documents matching a 'where' cond.
:param cond: the condition to check against
:type cond: Query
:returns: list of matching documents
:rtype: list[Element]
"""
if cond in self._query_cache:
return s... | Search for all documents matching a 'where' cond.
:param cond: the condition to check against
:type cond: Query
:returns: list of matching documents
:rtype: list[Element] |
def diff_archives(archive1, archive2, verbosity=0, interactive=True):
"""Print differences between two archives."""
util.check_existing_filename(archive1)
util.check_existing_filename(archive2)
if verbosity >= 0:
util.log_info("Comparing %s with %s ..." % (archive1, archive2))
res = _diff_ar... | Print differences between two archives. |
def get_question_mdata():
"""Return default mdata map for Question"""
return {
'item': {
'element_label': {
'text': 'item',
'languageTypeId': str(DEFAULT_LANGUAGE_TYPE),
'scriptTypeId': str(DEFAULT_SCRIPT_TYPE),
'formatTypeId': ... | Return default mdata map for Question |
def _remove_call(self, real_time, call):
"""
Internal helper. Removes a (possibly still pending) call from a
bucket. It is *not* an error of the bucket is gone (e.g. the
call has already happened).
"""
try:
(delayed_call, calls) = self._buckets[real_time]
... | Internal helper. Removes a (possibly still pending) call from a
bucket. It is *not* an error of the bucket is gone (e.g. the
call has already happened). |
def install_python_package(self, arch, name=None, env=None, is_dir=True):
'''Automate the installation of a Python package (or a cython
package where the cython components are pre-built).'''
# arch = self.filtered_archs[0] # old kivy-ios way
if name is None:
name = self.name... | Automate the installation of a Python package (or a cython
package where the cython components are pre-built). |
def walk_links(directory, prefix='', linkbase=None):
""" Return all links contained in directory (or any sub directory).
"""
links = {}
try:
for child in os.listdir(directory):
fullname = os.path.join(directory, child)
if os.path.islink(fullname):
link_pat... | Return all links contained in directory (or any sub directory). |
def _add_cytomine_cli_args(argparse):
"""
Add cytomine CLI args to the ArgumentParser object: cytomine_host, cytomine_public_key, cytomine_private_key and
cytomine_verbose.
Parameters
----------
argparse: ArgumentParser
The argument parser
Return
... | Add cytomine CLI args to the ArgumentParser object: cytomine_host, cytomine_public_key, cytomine_private_key and
cytomine_verbose.
Parameters
----------
argparse: ArgumentParser
The argument parser
Return
------
argparse: ArgumentParser
T... |
def clean_conf_folder(self, locale):
"""Remove the configuration directory for `locale`"""
dirname = self.configuration.get_messages_dir(locale)
dirname.removedirs_p() | Remove the configuration directory for `locale` |
def create_user(username):
"Create a new user."
password = prompt_pass("Enter password")
user = User(username=username, password=password)
db.session.add(user)
db.session.commit() | Create a new user. |
def admin_tools_render_menu_css(context, menu=None):
"""
Template tag that renders the menu css files,, it takes an optional
``Menu`` instance as unique argument, if not given, the menu will be
retrieved with the ``get_admin_menu`` function.
"""
if menu is None:
menu = get_admin_menu(con... | Template tag that renders the menu css files,, it takes an optional
``Menu`` instance as unique argument, if not given, the menu will be
retrieved with the ``get_admin_menu`` function. |
def isConnected(self, signal, slot):
"""
Returns if the given signal is connected to the inputted slot.
:param signal | <variant>
slot | <callable>
:return <bool> | is connected
"""
sig_calls = self._callbacks.get(signal, [... | Returns if the given signal is connected to the inputted slot.
:param signal | <variant>
slot | <callable>
:return <bool> | is connected |
def community_post_comment_down_create(self, post_id, id, data, **kwargs):
"https://developer.zendesk.com/rest_api/docs/help_center/votes#create-vote"
api_path = "/api/v2/community/posts/{post_id}/comments/{id}/down.json"
api_path = api_path.format(post_id=post_id, id=id)
return self.cal... | https://developer.zendesk.com/rest_api/docs/help_center/votes#create-vote |
def put_multi(entities):
"""Persist a set of entities to Datastore.
Note:
This uses the adapter that is tied to the first Entity in the
list. If the entities have disparate adapters this function may
behave in unexpected ways.
Warning:
You must pass a **list** and not a generator ... | Persist a set of entities to Datastore.
Note:
This uses the adapter that is tied to the first Entity in the
list. If the entities have disparate adapters this function may
behave in unexpected ways.
Warning:
You must pass a **list** and not a generator or some other kind
of iter... |
def get_bel_resource_hash(location, hash_function=None):
"""Get a BEL resource file and returns its semantic hash.
:param str location: URL of a resource
:param hash_function: A hash function or list of hash functions, like :func:`hashlib.md5` or :code:`hashlib.sha512`
:return: The hexadecimal digest o... | Get a BEL resource file and returns its semantic hash.
:param str location: URL of a resource
:param hash_function: A hash function or list of hash functions, like :func:`hashlib.md5` or :code:`hashlib.sha512`
:return: The hexadecimal digest of the hash of the values in the resource
:rtype: str
:ra... |
def installed(name,
pkgs=None,
pip_bin=None,
requirements=None,
bin_env=None,
use_wheel=False,
no_use_wheel=False,
log=None,
proxy=None,
timeout=None,
repo=None,
edit... | Make sure the package is installed
name
The name of the python package to install. You can also specify version
numbers here using the standard operators ``==, >=, <=``. If
``requirements`` is given, this parameter will be ignored.
Example:
.. code-block:: yaml
django:
... |
def _create_bv_circuit(self, bit_map: Dict[str, str]) -> Program:
"""
Implementation of the Bernstein-Vazirani Algorithm.
Given a list of input qubits and an ancilla bit, all initially in the
:math:`\\vert 0\\rangle` state, create a program that can find :math:`\\vec{a}` with one
... | Implementation of the Bernstein-Vazirani Algorithm.
Given a list of input qubits and an ancilla bit, all initially in the
:math:`\\vert 0\\rangle` state, create a program that can find :math:`\\vec{a}` with one
query to the given oracle.
:param Dict[String, String] bit_map: truth-table... |
def register(self, model_cls):
"""Register model(s) with app"""
assert issubclass(model_cls, peewee.Model)
assert not hasattr(model_cls._meta, 'database_manager')
if model_cls in self:
raise RuntimeError("Model already registered")
self.append(model_cls)
model... | Register model(s) with app |
def DisplayGetter(accessor, *args, **kwargs):
"""
Returns a Getter that gets the display name for a model field with choices.
"""
short_description = get_pretty_name(accessor)
accessor = 'get_%s_display' % accessor
getter = Getter(accessor, *args, **kwargs)
getter.short_description = short_d... | Returns a Getter that gets the display name for a model field with choices. |
def start_state_manager_watches(self):
"""
Receive updates to the packing plan from the statemgrs and update processes as needed.
"""
Log.info("Start state manager watches")
statemgr_config = StateMgrConfig()
statemgr_config.set_state_locations(configloader.load_state_manager_locations(
... | Receive updates to the packing plan from the statemgrs and update processes as needed. |
def merge_arena(self, mujoco_arena):
"""Adds arena model to the MJCF model."""
self.arena = mujoco_arena
self.bin_offset = mujoco_arena.bin_abs
self.bin_size = mujoco_arena.table_full_size
self.bin2_body = mujoco_arena.bin2_body
self.merge(mujoco_arena) | Adds arena model to the MJCF model. |
def ParseTable(table):
"""Parses table of osquery output.
Args:
table: A table in a "parsed JSON" representation.
Returns:
A parsed `rdf_osquery.OsqueryTable` instance.
"""
precondition.AssertIterableType(table, dict)
result = rdf_osquery.OsqueryTable()
result.header = ParseHeader(table)
for ... | Parses table of osquery output.
Args:
table: A table in a "parsed JSON" representation.
Returns:
A parsed `rdf_osquery.OsqueryTable` instance. |
def bestfit(self):
"""
Returns a series with the bestfit values.
Example:
Series.bestfit()
Returns: series
The returned series contains a parameter
called 'formula' which includes the string representation
of the bestfit line.
"""
# statsmodel cannot be included on requirements.txt
# see https://g... | Returns a series with the bestfit values.
Example:
Series.bestfit()
Returns: series
The returned series contains a parameter
called 'formula' which includes the string representation
of the bestfit line. |
def rebuild_system(self, override=False, **kwargs):
"""
Rebuild molecules in molecular system.
Parameters
----------
override : :class:`bool`, optional (default=False)
If False the rebuild molecular system is returned as a new
:class:`MolecularSystem`, if... | Rebuild molecules in molecular system.
Parameters
----------
override : :class:`bool`, optional (default=False)
If False the rebuild molecular system is returned as a new
:class:`MolecularSystem`, if True, the current
:class:`MolecularSystem` is modified. |
def render_exception_js(self, exception):
"""
Return a response with the body containing a JSON-formatter version of the exception.
"""
from .http import JsonResponse
response = {}
response["error"] = exception.error
response["error_description"] = exception.rea... | Return a response with the body containing a JSON-formatter version of the exception. |
def set_temperature(self, temp):
"""Set current goal temperature / setpoint"""
self.set_service_value(
self.thermostat_setpoint,
'CurrentSetpoint',
'NewCurrentSetpoint',
temp)
self.set_cache_value('setpoint', temp) | Set current goal temperature / setpoint |
def _update_records(self, records, data):
"""Insert or update a list of DNS records, specified in the netcup API
convention.
The fields ``hostname``, ``type``, and ``destination`` are mandatory
and must be provided either in the record dict or through ``data``!
"""
data ... | Insert or update a list of DNS records, specified in the netcup API
convention.
The fields ``hostname``, ``type``, and ``destination`` are mandatory
and must be provided either in the record dict or through ``data``! |
def get_input_shape(sym, proto_obj):
"""Helper function to obtain the shape of an array"""
arg_params = proto_obj.arg_dict
aux_params = proto_obj.aux_dict
model_input_shape = [data[1] for data in proto_obj.model_metadata.get('input_tensor_data')]
data_names = [data[0] for data in proto_obj.model_... | Helper function to obtain the shape of an array |
def get_program(self, program_resource_name: str) -> Dict:
"""Returns the previously created quantum program.
Params:
program_resource_name: A string of the form
`projects/project_id/programs/program_id`.
Returns:
A dictionary containing the metadata and... | Returns the previously created quantum program.
Params:
program_resource_name: A string of the form
`projects/project_id/programs/program_id`.
Returns:
A dictionary containing the metadata and the program. |
def _execute_callback_async(self, callback, data):
"""Execute the callback asynchronously.
If the callback is not a coroutine, convert it.
Note: The WebClient passed into the callback is running in "async" mode.
This means all responses will be futures.
"""
if asyncio.i... | Execute the callback asynchronously.
If the callback is not a coroutine, convert it.
Note: The WebClient passed into the callback is running in "async" mode.
This means all responses will be futures. |
def remove_image_info_cb(self, viewer, channel, image_info):
"""Almost the same as remove_image_cb().
"""
return self.remove_image_cb(viewer, channel.name,
image_info.name, image_info.path) | Almost the same as remove_image_cb(). |
def rect(self, x, y, width, height, roundness=0.0, draw=True, **kwargs):
'''
Draw a rectangle from x, y of width, height.
:param startx: top left x-coordinate
:param starty: top left y-coordinate
:param width: height Size of rectangle.
:roundness: Corner roundness defa... | Draw a rectangle from x, y of width, height.
:param startx: top left x-coordinate
:param starty: top left y-coordinate
:param width: height Size of rectangle.
:roundness: Corner roundness defaults to 0.0 (a right-angle).
:draw: If True draws immediately.
:fill: Optiona... |
def infer(self, **options):
"""https://github.com/frictionlessdata/datapackage-py#resource
"""
descriptor = deepcopy(self.__current_descriptor)
# Blank -> Stop
if self.__source_inspection.get('blank'):
return descriptor
# Name
if not descriptor.get('... | https://github.com/frictionlessdata/datapackage-py#resource |
def get(self):
"""Returns a requests.Session object.
Gets Session from sqlite3 cache or creates a new Session.
"""
if not HAS_SQL: # pragma: nocover
return requests.session()
try:
conn, c = self.connect()
except:
log.traceback(loggi... | Returns a requests.Session object.
Gets Session from sqlite3 cache or creates a new Session. |
def update(self, instance, condition):
"""Update the instance to the database
:param instance: an instance of modeled data object
:param condition: condition evaluated to determine record(s) to update
:returns: record id updated or None
:rtype: int
"""
item = sel... | Update the instance to the database
:param instance: an instance of modeled data object
:param condition: condition evaluated to determine record(s) to update
:returns: record id updated or None
:rtype: int |
def get_instance(self, payload):
"""
Build an instance of TranscriptionInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.api.v2010.account.recording.transcription.TranscriptionInstance
:rtype: twilio.rest.api.v2010.account.recording.transcription... | Build an instance of TranscriptionInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.api.v2010.account.recording.transcription.TranscriptionInstance
:rtype: twilio.rest.api.v2010.account.recording.transcription.TranscriptionInstance |
def content(self):
"""
:return: string (unicode) with Dockerfile content
"""
if self.cache_content and self.cached_content:
return self.cached_content
try:
with self._open_dockerfile('rb') as dockerfile:
content = b2u(dockerfile.read())
... | :return: string (unicode) with Dockerfile content |
def decode_offset_commit_response(cls, data):
"""
Decode bytes to an OffsetCommitResponse
Arguments:
data: bytes to decode
"""
((correlation_id,), cur) = relative_unpack('>i', data, 0)
((num_topics,), cur) = relative_unpack('>i', data, cur)
for _ in ... | Decode bytes to an OffsetCommitResponse
Arguments:
data: bytes to decode |
def create_from_fitsfile(cls, fitsfile):
""" Read a fits file and use it to make a mapping
"""
from fermipy.skymap import Map
index_map = Map.create_from_fits(fitsfile)
mult_map = Map.create_from_fits(fitsfile, hdu=1)
ff = fits.open(fitsfile)
hpx = HPX.create_from... | Read a fits file and use it to make a mapping |
def add_raw_code(self, string_or_list):
"""Add raw Gmsh code.
"""
if _is_string(string_or_list):
self._GMSH_CODE.append(string_or_list)
else:
assert isinstance(string_or_list, list)
for string in string_or_list:
self._GMSH_CODE.append(s... | Add raw Gmsh code. |
def dump_dict_to_file(dictionary, filepath):
"""Dump @dictionary as a line to @filepath."""
create_dirs(
os.path.dirname(filepath)
)
with open(filepath, 'a') as outfile:
json.dump(dictionary, outfile)
outfile.write('\n') | Dump @dictionary as a line to @filepath. |
def get_globals(self):
"""Get enriched globals"""
if self.shell:
globals_ = dict(_initial_globals)
else:
globals_ = dict(self.current_frame.f_globals)
globals_['_'] = self.db.last_obj
if cut is not None:
globals_.setdefault('cut', cut)
... | Get enriched globals |
def truncate(self, before=None, after=None):
"""
Slice index between two labels / tuples, return new MultiIndex
Parameters
----------
before : label or tuple, can be partial. Default None
None defaults to start
after : label or tuple, can be partial. Default ... | Slice index between two labels / tuples, return new MultiIndex
Parameters
----------
before : label or tuple, can be partial. Default None
None defaults to start
after : label or tuple, can be partial. Default None
None defaults to end
Returns
--... |
def launch_frozen(in_name, out_name, script_path, frozen_tar_path=None,
temp_path='_hadoopy_temp', cache=True, check_script=False,
**kw):
"""Freezes a script and then launches it.
This function will freeze your python program, and place it on HDFS
in 'temp_path'. It wil... | Freezes a script and then launches it.
This function will freeze your python program, and place it on HDFS
in 'temp_path'. It will not remove it afterwards as they are typically
small, you can easily reuse/debug them, and to avoid any risks involved
with removing the file.
:param in_name: Input p... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.