code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def PluginTagToContent(self, plugin_name):
"""Returns a dict mapping tags to content specific to that plugin.
Args:
plugin_name: The name of the plugin for which to fetch plugin-specific
content.
Raises:
KeyError: if the plugin name is not found.
Returns:
A dict mapping tags... | Returns a dict mapping tags to content specific to that plugin.
Args:
plugin_name: The name of the plugin for which to fetch plugin-specific
content.
Raises:
KeyError: if the plugin name is not found.
Returns:
A dict mapping tags to plugin-specific content (which are always stri... |
def ask_backend(self):
""" Ask the user to choose the backend """
response = self._ask_boolean(
"Do you have a local docker daemon (on Linux), do you use docker-machine via a local machine, or do you use "
"Docker for macOS?", True)
if (response):
self._displa... | Ask the user to choose the backend |
def begin_write(self, content_type=None):
"""Open content as a stream for writing.
See DAVResource.begin_write()
"""
assert not self.is_collection
self._check_write_access()
mode = "wb"
# GC issue 57: always store as binary
# if contentType and con... | Open content as a stream for writing.
See DAVResource.begin_write() |
def suggest_move(self, position):
"""Used for playing a single game.
For parallel play, use initialize_move, select_leaf,
incorporate_results, and pick_move
"""
start = time.time()
if self.timed_match:
while time.time() - start < self.seconds_per_move:
... | Used for playing a single game.
For parallel play, use initialize_move, select_leaf,
incorporate_results, and pick_move |
def to_internal_value(self, data):
"""
List of dicts of native values <- List of dicts of primitive datatypes.
"""
if html.is_html_input(data):
data = html.parse_html_list(data)
if not isinstance(data, list):
message = self.error_messages['not_a_list'].fo... | List of dicts of native values <- List of dicts of primitive datatypes. |
def _flush_tile_queue_blits(self, surface):
""" Blit the queued tiles and block until the tile queue is empty
for pygame 1.9.4 +
"""
tw, th = self.data.tile_size
ltw = self._tile_view.left * tw
tth = self._tile_view.top * th
self.data.prepare_tiles(self._tile_vi... | Blit the queued tiles and block until the tile queue is empty
for pygame 1.9.4 + |
def _make_load_template(self):
"""
Return a function that loads a template by name.
"""
loader = self._make_loader()
def load_template(template_name):
return loader.load_name(template_name)
return load_template | Return a function that loads a template by name. |
def wants(cls, *service_names):
"""A class decorator to indicate that an XBlock class wants particular services."""
def _decorator(cls_): # pylint: disable=missing-docstring
for service_name in service_names:
cls_._services_requested[service_nam... | A class decorator to indicate that an XBlock class wants particular services. |
def multiifo_noise_coinc_rate(rates, slop):
"""
Calculate the expected rate of noise coincidences for multiple detectors
Parameters
----------
rates: dict
Dictionary keyed on ifo string
Value is a sequence of single-detector trigger rates, units assumed
to be Hz
slop: fl... | Calculate the expected rate of noise coincidences for multiple detectors
Parameters
----------
rates: dict
Dictionary keyed on ifo string
Value is a sequence of single-detector trigger rates, units assumed
to be Hz
slop: float
time added to maximum time-of-flight between... |
def set_env(self, key, value):
"""Sets environment variables by prepending the app_name to `key`. Also registers the
environment variable with the instance object preventing an otherwise-required call to
`reload()`.
"""
os.environ[make_env_key(self.appname, key)] = str(value) # ... | Sets environment variables by prepending the app_name to `key`. Also registers the
environment variable with the instance object preventing an otherwise-required call to
`reload()`. |
def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'entity') and self.entity is not None:
_dict['entity'] = self.entity
if hasattr(self, 'location') and self.location is not None:
_dict['location'] = self.locati... | Return a json dictionary representing this model. |
def stop_execution(self):
"""
Triggers the stopping of the object.
"""
if not (self._stopping or self._stopped):
for actor in self.owner.actors:
actor.stop_execution()
self._stopping = True | Triggers the stopping of the object. |
def explain_weights_dfs(estimator, **kwargs):
# type: (...) -> Dict[str, pd.DataFrame]
""" Explain weights and export them to a dict with ``pandas.DataFrame``
values (as :func:`eli5.formatters.as_dataframe.format_as_dataframes` does).
All keyword arguments are passed to :func:`eli5.explain_weights`.
... | Explain weights and export them to a dict with ``pandas.DataFrame``
values (as :func:`eli5.formatters.as_dataframe.format_as_dataframes` does).
All keyword arguments are passed to :func:`eli5.explain_weights`.
Weights of all features are exported by default. |
def sync_local_to_remote(force="no"):
"""
Sync your local postgres database with remote
Example:
fabrik prod sync_local_to_remote:force=yes
"""
_check_requirements()
if force != "yes":
message = "This will replace the remote database '%s' with your "\
"local '%s', ... | Sync your local postgres database with remote
Example:
fabrik prod sync_local_to_remote:force=yes |
def _serialize_object(self, response_data, request):
""" Override to not serialize doc responses. """
if self._is_doc_request(request):
return response_data
else:
return super(DocumentedResource, self)._serialize_object(
response_data, request) | Override to not serialize doc responses. |
def count_never_executed(self):
"""Count statements that were never executed."""
lineno = self.firstlineno
counter = 0
for line in self.source:
if self.sourcelines.get(lineno) == 0:
if not self.blank_rx.match(line):
counter += 1
... | Count statements that were never executed. |
def _agl_compliant_name(glyph_name):
"""Return an AGL-compliant name string or None if we can't make one."""
MAX_GLYPH_NAME_LENGTH = 63
clean_name = re.sub("[^0-9a-zA-Z_.]", "", glyph_name)
if len(clean_name) > MAX_GLYPH_NAME_LENGTH:
return None
return clean_name | Return an AGL-compliant name string or None if we can't make one. |
def is_form_get(attr, attrs):
"""Check if this is a GET form action URL."""
res = False
if attr == "action":
method = attrs.get_true('method', u'').lower()
res = method != 'post'
return res | Check if this is a GET form action URL. |
def print_input(i):
"""
Input: {
}
Output: {
return - return code = 0, if successful
> 0, if error
(error) - error text if return > 0
html - input as JSON
}
"""
o=i.ge... | Input: {
}
Output: {
return - return code = 0, if successful
> 0, if error
(error) - error text if return > 0
html - input as JSON
} |
async def set_gs(self, mgr_addr, gs):
'''Set grid size for :py:class:`GridEnvironment` which manager is in
given address.
:param str mgr_addr: Address of the manager agent
:param gs:
New grid size of the grid environment, iterable with length 2.
'''
remote_m... | Set grid size for :py:class:`GridEnvironment` which manager is in
given address.
:param str mgr_addr: Address of the manager agent
:param gs:
New grid size of the grid environment, iterable with length 2. |
def _parse_query(self, source):
"""Parse one of the rules as either objectfilter or dottysql.
Example:
_parse_query("5 + 5")
# Returns Sum(Literal(5), Literal(5))
Arguments:
source: A rule in either objectfilter or dottysql syntax.
Returns:
... | Parse one of the rules as either objectfilter or dottysql.
Example:
_parse_query("5 + 5")
# Returns Sum(Literal(5), Literal(5))
Arguments:
source: A rule in either objectfilter or dottysql syntax.
Returns:
The AST to represent the rule. |
def to_python(self, value):
"""Convert value if needed."""
if isinstance(value, GroupDescriptor):
value = value._value # pylint: disable=protected-access
result = {}
for name, field in self.fields.items():
result[name] = field.to_python(value.get(name, None))
... | Convert value if needed. |
def parse_table_definition_file(file):
'''
Read an parse the XML of a table-definition file.
@return: an ElementTree object for the table definition
'''
logging.info("Reading table definition from '%s'...", file)
if not os.path.isfile(file):
logging.error("File '%s' does not exist.", fil... | Read an parse the XML of a table-definition file.
@return: an ElementTree object for the table definition |
def get_if_raw_addr(ifname):
"""Returns the IPv4 address configured on 'ifname', packed with inet_pton.""" # noqa: E501
# Get ifconfig output
try:
fd = os.popen("%s %s" % (conf.prog.ifconfig, ifname))
except OSError as msg:
warning("Failed to execute ifconfig: (%s)", msg)
retur... | Returns the IPv4 address configured on 'ifname', packed with inet_pton. |
def _parse(self, threshold):
"""
internal threshold string parser
arguments:
threshold: string describing the threshold
"""
match = re.search(r'^(@?)((~|\d*):)?(\d*)$', threshold)
if not match:
raise ValueError('Error parsing Threshold: {0}'.form... | internal threshold string parser
arguments:
threshold: string describing the threshold |
def merge(root, head, update, head_source=None):
"""
This function instantiate a ``Merger`` object using a configuration in
according to the ``source`` value of head and update params.
Then it run the merger on the three files provided in input.
Params
root(dict): the last common parent jso... | This function instantiate a ``Merger`` object using a configuration in
according to the ``source`` value of head and update params.
Then it run the merger on the three files provided in input.
Params
root(dict): the last common parent json of head and update
head(dict): the last version of ... |
def set_control_scheme(self, index):
"""Sets the control scheme for the agent. See :obj:`ControlSchemes`.
Args:
index (int): The control scheme to use. Should be set with an enum from :obj:`ControlSchemes`.
"""
self._current_control_scheme = index % self._num_control_schemes... | Sets the control scheme for the agent. See :obj:`ControlSchemes`.
Args:
index (int): The control scheme to use. Should be set with an enum from :obj:`ControlSchemes`. |
def fill_model(self, model=None):
"""
Populates a model with normalized properties. If no model is provided (None) a new one will be created.
:param model: model to be populade
:return: populated model
"""
normalized_dct = self.normalize()
if model:
if... | Populates a model with normalized properties. If no model is provided (None) a new one will be created.
:param model: model to be populade
:return: populated model |
def compute_sims(inputs: mx.nd.NDArray, normalize: bool) -> mx.nd.NDArray:
"""
Returns a matrix with pair-wise similarity scores between inputs.
Similarity score is (normalized) Euclidean distance. 'Similarity with self' is masked
to large negative value.
:param inputs: NDArray of inputs.
:para... | Returns a matrix with pair-wise similarity scores between inputs.
Similarity score is (normalized) Euclidean distance. 'Similarity with self' is masked
to large negative value.
:param inputs: NDArray of inputs.
:param normalize: Whether to normalize to unit-length.
:return: NDArray with pairwise si... |
def bounding_box(alpha, threshold=0.1):
"""
Returns a bounding box of the support.
Parameters
----------
alpha : ndarray, ndim=2
Any one-channel image where the background has zero or low intensity.
threshold : float
The threshold that divides background from foreground.
Re... | Returns a bounding box of the support.
Parameters
----------
alpha : ndarray, ndim=2
Any one-channel image where the background has zero or low intensity.
threshold : float
The threshold that divides background from foreground.
Returns
-------
bounding_box : (top, left, bot... |
def _pack(self, msg_type, payload):
"""
Packs the given message type and payload. Turns the resulting
message into a byte string.
"""
pb = payload.encode('utf-8')
s = struct.pack('=II', len(pb), msg_type.value)
return self.MAGIC.encode('utf-8') + s + pb | Packs the given message type and payload. Turns the resulting
message into a byte string. |
def phonenumber_validation(data):
""" Validates phonenumber
Similar to phonenumber_field.validators.validate_international_phonenumber() but uses a different message if the
country prefix is absent.
"""
from phonenumber_field.phonenumber import to_python
phone_number = to_python(data)
if no... | Validates phonenumber
Similar to phonenumber_field.validators.validate_international_phonenumber() but uses a different message if the
country prefix is absent. |
def mkdir_chown(paths, user_group=None, permissions='ug=rwX,o=rX', create_parent=True, check_if_exists=False, recursive=False):
"""
Generates a unix command line for creating a directory and assigning permissions to it. Shortcut to a combination of
:func:`~mkdir`, :func:`~chown`, and :func:`~chmod`.
No... | Generates a unix command line for creating a directory and assigning permissions to it. Shortcut to a combination of
:func:`~mkdir`, :func:`~chown`, and :func:`~chmod`.
Note that if `check_if_exists` has been set to ``True``, and the directory is found, `mkdir` is not called, but
`user_group` and `permissi... |
def generate_image_commands():
''' The Image client holds the Singularity image command group, mainly
deprecated commands (image.import) and additional command helpers
that are commonly use but not provided by Singularity
The levels of verbosity (debug and quiet) are passed from the main
... | The Image client holds the Singularity image command group, mainly
deprecated commands (image.import) and additional command helpers
that are commonly use but not provided by Singularity
The levels of verbosity (debug and quiet) are passed from the main
client via the environment variab... |
def sort_dict(d, desc=True):
"""
Sort an ordered dictionary by value, descending.
Args:
d (OrderedDict): An ordered dictionary.
desc (bool): If true, sort desc.
Returns:
OrderedDict: The sorted dictionary.
"""
sort = sorted(d.items(), key=lambda x: x[1], reverse=desc)... | Sort an ordered dictionary by value, descending.
Args:
d (OrderedDict): An ordered dictionary.
desc (bool): If true, sort desc.
Returns:
OrderedDict: The sorted dictionary. |
def find_xenon_grpc_jar():
"""Find the Xenon-GRPC jar-file, windows version."""
prefix = Path(sys.prefix)
locations = [
prefix / 'lib',
prefix / 'local' / 'lib'
]
for location in locations:
jar_file = location / 'xenon-grpc-{}-all.jar'.format(
xenon_grpc_ver... | Find the Xenon-GRPC jar-file, windows version. |
def asyncStarCmap(asyncCallable, iterable):
"""itertools.starmap for deferred callables using cooperative multitasking
"""
results = []
yield coopStar(asyncCallable, results.append, iterable)
returnValue(results) | itertools.starmap for deferred callables using cooperative multitasking |
def add_acquisition_source(
self,
method,
submission_number=None,
internal_uid=None,
email=None,
orcid=None,
source=None,
datetime=None,
):
"""Add acquisition source.
:type submission_number: integer
:type email: integer
... | Add acquisition source.
:type submission_number: integer
:type email: integer
:type source: string
:param method: method of acquisition for the suggested document
:type method: string
:param orcid: orcid of the user that is creating the record
:type orcid: st... |
def get_labels(data, centroids,K):
"""
Returns a label for each piece of data in the dataset
Parameters
------------
data: array-like, shape= (m_samples,n_samples)
K: integer
number of K clusters
centroids: array-like, shape=(K, n_samples)
returns
-----------... | Returns a label for each piece of data in the dataset
Parameters
------------
data: array-like, shape= (m_samples,n_samples)
K: integer
number of K clusters
centroids: array-like, shape=(K, n_samples)
returns
-------------
labels: array-like, shape (1,n_samples) |
def _deserialize_data(self, json_data):
"""
Deserialize a JSON into a dictionary
"""
my_dict = json.loads(json_data.decode('utf8').replace("'", '"'),
encoding='UTF-8')
for item in my_dict:
if item == const.ADIF:
my_dict[item] = int(my_dic... | Deserialize a JSON into a dictionary |
def _process_download_descriptor(self, dd):
# type: (Downloader, blobxfer.models.download.Descriptor) -> None
"""Process download descriptor
:param Downloader self: this
:param blobxfer.models.download.Descriptor dd: download descriptor
"""
# update progress bar
s... | Process download descriptor
:param Downloader self: this
:param blobxfer.models.download.Descriptor dd: download descriptor |
def _construct_message(self):
"""Set the message token/channel, then call the bas class constructor."""
self.message = {"token": self._auth, "channel": self.channel}
super()._construct_message() | Set the message token/channel, then call the bas class constructor. |
def _resolve_datacenter(dc, pillarenv):
'''
If ``dc`` is a string - return it as is.
If it's a dict then sort it in descending order by key length and try
to use keys as RegEx patterns to match against ``pillarenv``.
The value for matched pattern should be a string (that can use
``str.format`` ... | If ``dc`` is a string - return it as is.
If it's a dict then sort it in descending order by key length and try
to use keys as RegEx patterns to match against ``pillarenv``.
The value for matched pattern should be a string (that can use
``str.format`` syntax togetehr with captured variables from pattern... |
def enqueue_mod(self, dn, mod):
"""Enqueue a LDAP modification.
Arguments:
dn -- the distinguished name of the object to modify
mod -- an ldap modfication entry to enqueue
"""
# mark for update
if dn not in self.__pending_mod_dn__:
self.__pending_mod_... | Enqueue a LDAP modification.
Arguments:
dn -- the distinguished name of the object to modify
mod -- an ldap modfication entry to enqueue |
def create_custom_gradebook_column(self, course_id, column_title, column_hidden=None, column_position=None, column_teacher_notes=None):
"""
Create a custom gradebook column.
Create a custom gradebook column
"""
path = {}
data = {}
params = {}
#... | Create a custom gradebook column.
Create a custom gradebook column |
def get_number_of_atoms(self):
"""Get the number of atoms in the calculated structure.
Returns: Property, where number of atoms is a scalar.
"""
strc = self.get_output_structure()
if not strc:
return None
return Property(scalars=[Scalar(value=len(strc))], uni... | Get the number of atoms in the calculated structure.
Returns: Property, where number of atoms is a scalar. |
def get_preparation_cmd(user, permissions, path):
"""
Generates the command lines for adjusting a volume's ownership and permission flags. Returns an empty list if there
is nothing to adjust.
:param user: User to set ownership for on the path via ``chown``.
:type user: unicode | str | int | dockerm... | Generates the command lines for adjusting a volume's ownership and permission flags. Returns an empty list if there
is nothing to adjust.
:param user: User to set ownership for on the path via ``chown``.
:type user: unicode | str | int | dockermap.functional.AbstractLazyObject
:param permissions: Permi... |
def get_config(self):
""" Get and set config options from config file """
if 'rmq_port' in self.config:
self.rmq_port = int(self.config['rmq_port'])
if 'rmq_user' in self.config:
self.rmq_user = self.config['rmq_user']
if 'rmq_password' in self.config:
... | Get and set config options from config file |
def setValue(self, p_float):
"""Override method to set a value to show it as 0 to 100.
:param p_float: The float number that want to be set.
:type p_float: float
"""
p_float = p_float * 100
super(PercentageSpinBox, self).setValue(p_float) | Override method to set a value to show it as 0 to 100.
:param p_float: The float number that want to be set.
:type p_float: float |
def admin_url(obj):
"""
Returns the admin URL of the object.
No permissions checking is involved, so use with caution to avoid exposing
the link to unauthorised users.
Example::
{{ foo_obj|admin_url }}
renders as::
/admin/foo/123
:param obj: A Django model instance.
... | Returns the admin URL of the object.
No permissions checking is involved, so use with caution to avoid exposing
the link to unauthorised users.
Example::
{{ foo_obj|admin_url }}
renders as::
/admin/foo/123
:param obj: A Django model instance.
:return: the admin URL of the o... |
def title(label, style=None):
"""Sets the title for the current figure.
Parameters
----------
label : str
The new title for the current figure.
style: dict
The CSS style to be applied to the figure title
"""
fig = current_figure()
fig.title = label
if style is not No... | Sets the title for the current figure.
Parameters
----------
label : str
The new title for the current figure.
style: dict
The CSS style to be applied to the figure title |
def expect_column_kl_divergence_to_be_less_than(self,
column,
partition_object=None,
threshold=None,
tail_weight... | Expect the Kulback-Leibler (KL) divergence (relative entropy) of the specified column with respect to the \
partition object to be lower than the provided threshold.
KL divergence compares two distributions. The higher the divergence value (relative entropy), the larger the \
difference between... |
def compile_pythrancode(module_name, pythrancode, specs=None,
opts=None, cpponly=False, pyonly=False,
output_file=None, module_dir=None, **kwargs):
'''Pythran code (string) -> c++ code -> native module
if `cpponly` is set to true, return the generated C++ filenam... | Pythran code (string) -> c++ code -> native module
if `cpponly` is set to true, return the generated C++ filename
if `pyonly` is set to true, prints the generated Python filename,
unless `output_file` is set
otherwise, return the generated native library filename |
def write(self, buf):
"""Write bytes to the stream."""
underflow = self._audio_stream.write(buf)
if underflow:
logging.warning('SoundDeviceStream write underflow (size: %d)',
len(buf))
return len(buf) | Write bytes to the stream. |
def plot_fermi_surface(data, structure, cbm, energy_levels=[],
multiple_figure=True,
mlab_figure=None, kpoints_dict={}, color=(0, 0, 1),
transparency_factor=[], labels_scale_factor=0.05,
points_scale_factor=0.02, interative=True... | Plot the Fermi surface at specific energy value.
Args:
data: energy values in a 3D grid from a CUBE file
via read_cube_file function, or from a
BoltztrapAnalyzer.fermi_surface_data
structure: structure object of the material
energy_levels: list of energy value ... |
def feature_importances(data, top_n=None, feature_names=None, ax=None):
"""
Get and order feature importances from a scikit-learn model
or from an array-like structure. If data is a scikit-learn model with
sub-estimators (e.g. RandomForest, AdaBoost) the function will compute the
standard deviation ... | Get and order feature importances from a scikit-learn model
or from an array-like structure. If data is a scikit-learn model with
sub-estimators (e.g. RandomForest, AdaBoost) the function will compute the
standard deviation of each feature.
Parameters
----------
data : sklearn model or array-li... |
def need_latex_rerun(self):
'''
Test for all rerun patterns if they match the output.
'''
for pattern in LATEX_RERUN_PATTERNS:
if pattern.search(self.out):
return True
return False | Test for all rerun patterns if they match the output. |
def save_model(self, directory=None, append_timestep=True):
"""
Save TensorFlow model. If no checkpoint directory is given, the model's default saver
directory is used. Optionally appends current timestep to prevent overwriting previous
checkpoint files. Turn off to be able to load model... | Save TensorFlow model. If no checkpoint directory is given, the model's default saver
directory is used. Optionally appends current timestep to prevent overwriting previous
checkpoint files. Turn off to be able to load model from the same given path argument as
given here.
Args:
... |
def get_division(self, obj):
"""Division."""
if self.context.get("division"):
return DivisionSerializer(self.context.get("division")).data
else:
if obj.slug == "senate":
return DivisionSerializer(obj.jurisdiction.division).data
else:
... | Division. |
def exec_command(self, cmd, tmp_path, sudo_user, sudoable=False, executable='/bin/sh'):
''' run a command on the local host '''
if not self.runner.sudo or not sudoable:
if executable:
local_cmd = [executable, '-c', cmd]
else:
local_cmd = cmd
... | run a command on the local host |
def _cho_solve_AATI(A, rho, b, c, lwr, check_finite=True):
"""Patched version of :func:`sporco.linalg.cho_solve_AATI`."""
N, M = A.shape
if N >= M:
x = (b - _cho_solve((c, lwr), b.dot(A).T,
check_finite=check_finite).T.dot(A.T)) / rho
else:
x = _cho_solve((c, lwr), b.T, chec... | Patched version of :func:`sporco.linalg.cho_solve_AATI`. |
def txid_to_block_data(txid, bitcoind_proxy, proxy=None):
"""
Given a txid, get its block's data.
Use SPV to verify the information we receive from the (untrusted)
bitcoind host.
@bitcoind_proxy must be a BitcoindConnection (from virtualchain.lib.session)
Return the (block hash, block data, t... | Given a txid, get its block's data.
Use SPV to verify the information we receive from the (untrusted)
bitcoind host.
@bitcoind_proxy must be a BitcoindConnection (from virtualchain.lib.session)
Return the (block hash, block data, txdata) on success
Return (None, None, None) on error |
async def validate(state, holdout_glob):
"""Validate the trained model against holdout games.
Args:
state: the RL loop State instance.
holdout_glob: a glob that matches holdout games.
"""
if not glob.glob(holdout_glob):
print('Glob "{}" didn\'t match any files, skipping validation'.format(
... | Validate the trained model against holdout games.
Args:
state: the RL loop State instance.
holdout_glob: a glob that matches holdout games. |
def _required_child(parent, tag):
"""
Add child element with *tag* to *parent* if it doesn't already exist.
"""
if _child(parent, tag) is None:
parent.append(_Element(tag)) | Add child element with *tag* to *parent* if it doesn't already exist. |
def get(cls, uuid):
"""Return a `Resource` instance of this class identified by
the given code or UUID.
Only `Resource` classes with specified `member_path` attributes
can be directly requested with this method.
"""
if not uuid:
raise ValueError("get must ha... | Return a `Resource` instance of this class identified by
the given code or UUID.
Only `Resource` classes with specified `member_path` attributes
can be directly requested with this method. |
def generate_checker(value):
"""Generate state checker for given value."""
@property
@wraps(can_be_)
def checker(self):
return self.can_be_(value)
return checker | Generate state checker for given value. |
def get_metric_values(self):
"""
Get the faked metrics, for all metric groups and all resources that
have been prepared on the manager object of this context object.
Returns:
iterable of tuple (group_name, iterable of values): The faked
metrics, in the order they ... | Get the faked metrics, for all metric groups and all resources that
have been prepared on the manager object of this context object.
Returns:
iterable of tuple (group_name, iterable of values): The faked
metrics, in the order they had been added, where:
group_name (s... |
def evaluate(self, x):
"""TODO: will become _evaluate once polynomial filtering is merged."""
if not hasattr(self, '_coefficients'):
# Graph Fourier transform -> modulation -> inverse GFT.
c = self.G.igft(self._kernels.evaluate(self.G.e).squeeze())
c = np.sqrt(self.G... | TODO: will become _evaluate once polynomial filtering is merged. |
def _detach_received(self, error):
"""Callback called when a link DETACH frame is received.
This callback will process the received DETACH error to determine if
the link is recoverable or whether it should be shutdown.
:param error: The error information from the detach
frame.
... | Callback called when a link DETACH frame is received.
This callback will process the received DETACH error to determine if
the link is recoverable or whether it should be shutdown.
:param error: The error information from the detach
frame.
:type error: ~uamqp.errors.ErrorRespon... |
def check_auth(self, username, password):
''' This function is called to check if a username password combination
is valid. '''
return username == self.queryname and password == self.querypw | This function is called to check if a username password combination
is valid. |
def enable(self):
"""
Enables WinQuad setting
"""
nquad = self.nquad.value()
for label, xsll, xsul, xslr, xsur, ys, nx, ny in \
zip(self.label[:nquad], self.xsll[:nquad], self.xsul[:nquad],
self.xslr[:nquad], self.xsur[:nquad], self.ys[:nquad],... | Enables WinQuad setting |
def complete_vhwa_command(self, command):
"""Signals that the Video HW Acceleration command has completed.
in command of type str
Pointer to VBOXVHWACMD containing the completed command.
"""
if not isinstance(command, basestring):
raise TypeError("command can on... | Signals that the Video HW Acceleration command has completed.
in command of type str
Pointer to VBOXVHWACMD containing the completed command. |
def _run_program(self, bin, fastafile, params=None):
"""
Run MotifSampler and predict motifs from a FASTA file.
Parameters
----------
bin : str
Command used to run the tool.
fastafile : str
Name of the FASTA input file.
params : ... | Run MotifSampler and predict motifs from a FASTA file.
Parameters
----------
bin : str
Command used to run the tool.
fastafile : str
Name of the FASTA input file.
params : dict, optional
Optional parameters. For some of the tools req... |
def iter_org_events(self, org, number=-1, etag=None):
"""Iterate over events as they appear on the user's organization
dashboard. You must be authenticated to view this.
:param str org: (required), name of the organization
:param int number: (optional), number of events to return. Defau... | Iterate over events as they appear on the user's organization
dashboard. You must be authenticated to view this.
:param str org: (required), name of the organization
:param int number: (optional), number of events to return. Default: -1
returns all available events
:param st... |
def get_objects_dex(self):
"""
Yields all dex objects inclduing their Analysis objects
:returns: tuple of (sha256, DalvikVMFormat, Analysis)
"""
# TODO: there is no variant like get_objects_apk
for digest, d in self.analyzed_dex.items():
yield digest, d, self... | Yields all dex objects inclduing their Analysis objects
:returns: tuple of (sha256, DalvikVMFormat, Analysis) |
def from_string(cls, s):
"""
Instantiate a `Derivation` from a UDF or UDX string representation.
The UDF/UDX representations are as output by a processor like the
`LKB <http://moin.delph-in.net/LkbTop>`_ or
`ACE <http://sweaglesw.org/linguistics/ace/>`_, or from the
:met... | Instantiate a `Derivation` from a UDF or UDX string representation.
The UDF/UDX representations are as output by a processor like the
`LKB <http://moin.delph-in.net/LkbTop>`_ or
`ACE <http://sweaglesw.org/linguistics/ace/>`_, or from the
:meth:`UdfNode.to_udf` or :meth:`UdfNode.to_udx` ... |
def solar_position_loop(unixtime, loc_args, out):
"""Loop through the time array and calculate the solar position"""
lat = loc_args[0]
lon = loc_args[1]
elev = loc_args[2]
pressure = loc_args[3]
temp = loc_args[4]
delta_t = loc_args[5]
atmos_refract = loc_args[6]
sst = loc_args[7]
... | Loop through the time array and calculate the solar position |
def _check_input(self, X, R):
"""Check whether input data and coordinates in right type
Parameters
----------
X : list of 2D arrays, element i has shape=[voxels_i, samples]
Each element in the list contains the fMRI data of one subject.
R : list of 2D arrays, eleme... | Check whether input data and coordinates in right type
Parameters
----------
X : list of 2D arrays, element i has shape=[voxels_i, samples]
Each element in the list contains the fMRI data of one subject.
R : list of 2D arrays, element i has shape=[n_voxel, n_dim]
... |
def qteStartRecordingHook(self, msgObj):
"""
Commence macro recording.
Macros are recorded by connecting to the 'keypressed' signal
it emits.
If the recording has already commenced, or if this method was
called during a macro replay, then return immediately.
"""... | Commence macro recording.
Macros are recorded by connecting to the 'keypressed' signal
it emits.
If the recording has already commenced, or if this method was
called during a macro replay, then return immediately. |
def set_continous_wave(self, enabled):
"""
Enable/disable the client side X-mode. When enabled this recalculates
the setpoints before sending them to the Crazyflie.
"""
pk = CRTPPacket()
pk.set_header(CRTPPort.PLATFORM, PLATFORM_COMMAND)
pk.data = (0, enabled)
... | Enable/disable the client side X-mode. When enabled this recalculates
the setpoints before sending them to the Crazyflie. |
def pick_auth(endpoint_context, areq, all=False):
"""
Pick authentication method
:param areq: AuthorizationRequest instance
:return: A dictionary with the authentication method and its authn class ref
"""
acrs = []
try:
if len(endpoint_context.authn_broker) == 1:
return... | Pick authentication method
:param areq: AuthorizationRequest instance
:return: A dictionary with the authentication method and its authn class ref |
def _get_unicode(data, force=False):
"""Try to return a text aka unicode object from the given data."""
if isinstance(data, binary_type):
return data.decode('utf-8')
elif data is None:
return ''
elif force:
if PY2:
return unicode(data)
else:
return... | Try to return a text aka unicode object from the given data. |
def InteractiveShell(self, cmd=None, strip_cmd=True, delim=None, strip_delim=True):
"""Get stdout from the currently open interactive shell and optionally run a command
on the device, returning all output.
Args:
cmd: Optional. Command to run on the target.
strip_cmd: Opt... | Get stdout from the currently open interactive shell and optionally run a command
on the device, returning all output.
Args:
cmd: Optional. Command to run on the target.
strip_cmd: Optional (default True). Strip command name from stdout.
delim: Optional. Delimiter to l... |
def take_action(self, production_rule: str) -> 'GrammarStatelet':
"""
Takes an action in the current grammar state, returning a new grammar state with whatever
updates are necessary. The production rule is assumed to be formatted as "LHS -> RHS".
This will update the non-terminal stack... | Takes an action in the current grammar state, returning a new grammar state with whatever
updates are necessary. The production rule is assumed to be formatted as "LHS -> RHS".
This will update the non-terminal stack. Updating the non-terminal stack involves popping
the non-terminal that was ... |
def init_flatpak():
"""
If we are in Flatpak, we must build a tessdata/ directory using the
.traineddata files from each locale directory
"""
tessdata_files = glob.glob("/app/share/locale/*/*.traineddata")
if len(tessdata_files) <= 0:
return os.path.exists("/app")
localdir = os.path... | If we are in Flatpak, we must build a tessdata/ directory using the
.traineddata files from each locale directory |
def drop_prefix_and_return_type(function):
"""Takes the function value from a frame and drops prefix and return type
For example::
static void * Allocator<MozJemallocBase>::malloc(unsigned __int64)
^ ^^^^^^ return type
prefix
This gets changes to this::
Allocator<Moz... | Takes the function value from a frame and drops prefix and return type
For example::
static void * Allocator<MozJemallocBase>::malloc(unsigned __int64)
^ ^^^^^^ return type
prefix
This gets changes to this::
Allocator<MozJemallocBase>::malloc(unsigned __int64)
This ... |
def load(self):
"""
Fetch data about droplet - use this instead of get_data()
"""
droplets = self.get_data("droplets/%s" % self.id)
droplet = droplets['droplet']
for attr in droplet.keys():
setattr(self, attr, droplet[attr])
for net in self.networ... | Fetch data about droplet - use this instead of get_data() |
def _CollectHistory_(lookupType, fromVal, toVal, using={}, pattern=''):
"""
Return a dictionary detailing what, if any, change was made to a record field
:param string lookupType: what cleaning rule made the change; one of: genericLookup, genericRegex, fieldSpecificLookup, fieldSpecificRegex, normLookup, n... | Return a dictionary detailing what, if any, change was made to a record field
:param string lookupType: what cleaning rule made the change; one of: genericLookup, genericRegex, fieldSpecificLookup, fieldSpecificRegex, normLookup, normRegex, normIncludes, deriveValue, copyValue, deriveRegex
:param string fromVa... |
def get_direct_queue(self):
"""Returns a :class: `kombu.Queue` instance to be used to listen
for messages send to this specific Actor instance"""
return Queue(self.id, self.inbox_direct, routing_key=self.routing_key,
auto_delete=True) | Returns a :class: `kombu.Queue` instance to be used to listen
for messages send to this specific Actor instance |
def plot(self, columns=None, loc=None, iloc=None, **kwargs):
""""
A wrapper around plotting. Matplotlib plot arguments can be passed in, plus:
Parameters
-----------
columns: string or list-like, optional
If not empty, plot a subset of columns from the ``cumulative_haz... | A wrapper around plotting. Matplotlib plot arguments can be passed in, plus:
Parameters
-----------
columns: string or list-like, optional
If not empty, plot a subset of columns from the ``cumulative_hazards_``. Default all.
loc:
iloc: slice, optional
specif... |
def LightcurveHDU(model):
'''
Construct the data HDU file containing the arrays and the observing info.
'''
# Get mission cards
cards = model._mission.HDUCards(model.meta, hdu=1)
# Add EVEREST info
cards.append(('COMMENT', '************************'))
cards.append(('COMMENT', '* E... | Construct the data HDU file containing the arrays and the observing info. |
def unpack(self, buff, offset=0):
"""Unpack a binary message into this object's attributes.
Unpack the binary value *buff* and update this object attributes based
on the results.
Args:
buff (bytes): Binary data package to be unpacked.
offset (int): Where to begi... | Unpack a binary message into this object's attributes.
Unpack the binary value *buff* and update this object attributes based
on the results.
Args:
buff (bytes): Binary data package to be unpacked.
offset (int): Where to begin unpacking.
Raises:
Exc... |
def _build_http(http=None):
"""Construct an http client suitable for googleapiclient usage w/ user agent.
"""
if not http:
http = httplib2.Http(
timeout=HTTP_REQUEST_TIMEOUT, ca_certs=HTTPLIB_CA_BUNDLE)
user_agent = 'Python-httplib2/{} (gzip), {}/{}'.format(
httplib2.__versi... | Construct an http client suitable for googleapiclient usage w/ user agent. |
def kill(self) -> None:
"""Kill ffmpeg job."""
self._proc.kill()
self._loop.run_in_executor(None, self._proc.communicate) | Kill ffmpeg job. |
def generate_signed_url_v2(
credentials,
resource,
expiration,
api_access_endpoint="",
method="GET",
content_md5=None,
content_type=None,
response_type=None,
response_disposition=None,
generation=None,
headers=None,
query_parameters=None,
):
"""Generate a V2 signed UR... | Generate a V2 signed URL to provide query-string auth'n to a resource.
.. note::
Assumes ``credentials`` implements the
:class:`google.auth.credentials.Signing` interface. Also assumes
``credentials`` has a ``service_account_email`` property which
identifies the credentials.
.... |
def render_field(self, obj, field_name, **options):
"""Render field"""
try:
field = obj._meta.get_field(field_name)
except FieldDoesNotExist:
return getattr(obj, field_name, '')
if hasattr(field, 'choices') and getattr(field, 'choices'):
return getatt... | Render field |
def add_dependency(self, p_from_todo, p_to_todo):
""" Adds a dependency from task 1 to task 2. """
def find_next_id():
"""
Find a new unused ID.
Unused means that no task has it as an 'id' value or as a 'p'
value.
"""
def id_exists(... | Adds a dependency from task 1 to task 2. |
def unpack_kinesis_event(kinesis_event, deserializer=None, unpacker=None,
embed_timestamp=False):
"""Extracts events (a list of dicts) from a Kinesis event."""
records = kinesis_event["Records"]
events = []
shard_ids = set()
for rec in records:
data = rec["kinesis"][... | Extracts events (a list of dicts) from a Kinesis event. |
def getstate(self):
"""
Returns RUNNING, -1
COMPLETE, 0
or
EXECUTOR_ERROR, 255
"""
state = "RUNNING"
exit_code = -1
exitcode_file = os.path.join(self.workdir, "exit_code")
pid_file = os.path.join(self.workdir, "pid"... | Returns RUNNING, -1
COMPLETE, 0
or
EXECUTOR_ERROR, 255 |
def find_sample_min_std(self, Intensities):
'''
find the best interpretation with the minimum stratard deviation (in units of percent % !)
'''
Best_array = []
best_array_std_perc = inf
Best_array_tmp = []
Best_interpretations = {}
Best_interpretations_tmp... | find the best interpretation with the minimum stratard deviation (in units of percent % !) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.