code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def matches(self, other):
'''
A disjunctive list matches a phoneme if any of its members matches the phoneme.
If other is also a disjunctive list, any match between this list and the other returns true.
'''
if other is None:
return False
if isinstance(other, PhonemeDisjunction):
return any([ph... | A disjunctive list matches a phoneme if any of its members matches the phoneme.
If other is also a disjunctive list, any match between this list and the other returns true. |
def load_rules(self):
"""
load the rules from file
"""
self.col_maps = []
#print("reading mapping table")
with open(self.col_file, 'r') as f:
for line in f:
rule = MapColumn(line)
#rule = line
self.col_maps.appe... | load the rules from file |
def is_indexed(self, dataset):
""" Returns True if dataset is already indexed. Otherwise returns False. """
query = text("""
SELECT vid
FROM dataset_index
WHERE vid = :vid;
""")
result = self.backend.library.database.connection.execute(query, vid=datas... | Returns True if dataset is already indexed. Otherwise returns False. |
def _buildStaticFiles(self):
""" move over static files so that relative imports work
Note: if a dir is passed, it is copied with all of its contents
If the file is a zip, it is copied and extracted too
# By default folder name is 'static', unless *output_path_static* is passed (now allo... | move over static files so that relative imports work
Note: if a dir is passed, it is copied with all of its contents
If the file is a zip, it is copied and extracted too
# By default folder name is 'static', unless *output_path_static* is passed (now allowed only in special applications like Kom... |
def parse_sgtin_96(sgtin_96):
'''Given a SGTIN-96 hex string, parse each segment.
Returns a dictionary of the segments.'''
if not sgtin_96:
raise Exception('Pass in a value.')
if not sgtin_96.startswith("30"):
# not a sgtin, not handled
raise Exception('Not SGTIN-96.')
bin... | Given a SGTIN-96 hex string, parse each segment.
Returns a dictionary of the segments. |
def compare_params(defined, existing, return_old_value=False):
'''
.. versionadded:: 2017.7
Compares Zabbix object definition against existing Zabbix object.
:param defined: Zabbix object definition taken from sls file.
:param existing: Existing Zabbix object taken from result of an API call.
... | .. versionadded:: 2017.7
Compares Zabbix object definition against existing Zabbix object.
:param defined: Zabbix object definition taken from sls file.
:param existing: Existing Zabbix object taken from result of an API call.
:param return_old_value: Default False. If True, returns dict("old"=old_val... |
def global_state_code(self):
"""
Returns global variables for generating function from ``func_code`` as code.
Includes compiled regular expressions and imports.
"""
self._generate_func_code()
if not self._compile_regexps:
return '\n'.join(
[
... | Returns global variables for generating function from ``func_code`` as code.
Includes compiled regular expressions and imports. |
def save(self, filename):
'''save waypoints to a file'''
f = open(filename, mode='w')
f.write("QGC WPL 110\n")
for w in self.wpoints:
if getattr(w, 'comment', None):
f.write("# %s\n" % w.comment)
f.write("%u\t%u\t%u\t%u\t%f\t%f\t%f\t%f\t%f\t%f\t%f\... | save waypoints to a file |
def parse_xml_node(self, node):
'''Parse an xml.dom Node object representing a preceding condition into
this object.
'''
super(Preceding, self).parse_xml_node(node)
p_nodes = node.getElementsByTagNameNS(RTS_NS, 'Preceding')
if p_nodes.length != 1:
raise Inval... | Parse an xml.dom Node object representing a preceding condition into
this object. |
def connect():
"""Connect to FTP server, login and return an ftplib.FTP instance."""
ftp_class = ftplib.FTP if not SSL else ftplib.FTP_TLS
ftp = ftp_class(timeout=TIMEOUT)
ftp.connect(HOST, PORT)
ftp.login(USER, PASSWORD)
if SSL:
ftp.prot_p() # secure data connection
return ftp | Connect to FTP server, login and return an ftplib.FTP instance. |
def add_argument(self, parser, bootstrap=False):
"""Add dict-style item as an argument to the given parser.
The dict item will take all the nested items in the dictionary and
namespace them with the dict name, adding each child item as
their own CLI argument.
Examples:
... | Add dict-style item as an argument to the given parser.
The dict item will take all the nested items in the dictionary and
namespace them with the dict name, adding each child item as
their own CLI argument.
Examples:
A non-nested dict item with the name 'db' and children n... |
def safe_sort(values, labels=None, na_sentinel=-1, assume_unique=False):
"""
Sort ``values`` and reorder corresponding ``labels``.
``values`` should be unique if ``labels`` is not None.
Safe for use with mixed types (int, str), orders ints before strs.
.. versionadded:: 0.19.0
Parameters
-... | Sort ``values`` and reorder corresponding ``labels``.
``values`` should be unique if ``labels`` is not None.
Safe for use with mixed types (int, str), orders ints before strs.
.. versionadded:: 0.19.0
Parameters
----------
values : list-like
Sequence; must be unique if ``labels`` is no... |
def set_file_atrificat_of_project(self, doc, symbol, value):
"""Sets a file name, uri or home artificat.
Raises OrderError if no package or file defined.
"""
if self.has_package(doc) and self.has_file(doc):
self.file(doc).add_artifact(symbol, value)
else:
... | Sets a file name, uri or home artificat.
Raises OrderError if no package or file defined. |
def config_args(self):
"""Set config options"""
# Module list options:
self.arg_parser.add_argument('--version', action='version',
version='%(prog)s ' + str(__version__))
self.arg_parser.add_argument('--verbose',
action='store_true', dest = 'verbosemode',
... | Set config options |
def _rest_request_to_json(self, address, object_path, service_name, requests_config, tags, *args, **kwargs):
"""
Query the given URL and return the JSON response
"""
response = self._rest_request(address, object_path, service_name, requests_config, tags, *args, **kwargs)
try:
... | Query the given URL and return the JSON response |
def main():
""" Main function when running as a program. """
global args
args = parse_args()
if not args:
return 1
state = MyState(args)
for path in args.paths:
if os.path.isdir(path):
walk_dir(path, args, state)
else:
safe_process_files(os.path... | Main function when running as a program. |
def calc_crc16(buf):
""" Drop in pure python replacement for ekmcrc.c extension.
Args:
buf (bytes): String or byte array (implicit Python 2.7 cast)
Returns:
str: 16 bit CRC per EKM Omnimeters formatted as hex string.
"""
crc_table = [0x0000, 0xc0c1, 0xc1... | Drop in pure python replacement for ekmcrc.c extension.
Args:
buf (bytes): String or byte array (implicit Python 2.7 cast)
Returns:
str: 16 bit CRC per EKM Omnimeters formatted as hex string. |
def flush_template(context, declaration=None, reconstruct=True):
"""Emit the code needed to flush the buffer.
Will only emit the yield and clear if the buffer is known to be dirty.
"""
if declaration is None:
declaration = Line(0, '')
if {'text', 'dirty'}.issubset(context.flag):
yield declaration.clone(... | Emit the code needed to flush the buffer.
Will only emit the yield and clear if the buffer is known to be dirty. |
def evaluate_with_predictions(data_file, predictions):
'''
Evalutate with predictions/
'''
expected_version = '1.1'
with open(data_file) as dataset_file:
dataset_json = json.load(dataset_file)
if dataset_json['version'] != expected_version:
print('Evaluation expects v-' +... | Evalutate with predictions/ |
def permission_required(perm, queryset=None,
login_url=None, raise_exception=False):
"""
Permission check decorator for function-base generic view
This decorator works as function decorator
Parameters
----------
perm : string
A permission string
queryset : q... | Permission check decorator for function-base generic view
This decorator works as function decorator
Parameters
----------
perm : string
A permission string
queryset : queryset or model
A queryset or model for finding object.
With classbased generic view, ``None`` for using... |
def header(heading_text, header_level, style="atx"):
"""Return a header of specified level.
Keyword arguments:
style -- Specifies the header style (default atx).
The "atx" style uses hash signs, and has 6 levels.
The "setext" style uses dashes or equals signs for headers of
... | Return a header of specified level.
Keyword arguments:
style -- Specifies the header style (default atx).
The "atx" style uses hash signs, and has 6 levels.
The "setext" style uses dashes or equals signs for headers of
levels 1 and 2 respectively, and is limited to those... |
def get_alert(self, id, **kwargs): # noqa: E501
"""Get a specific alert # noqa: E501
# noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_alert(id, async_req=True)
... | Get a specific alert # noqa: E501
# noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_alert(id, async_req=True)
>>> result = thread.get()
:param async_req bool
... |
def _shutdown_transport(self):
"""Unwrap a Python 2.6 SSL socket, so we can call shutdown()"""
if self.sock is not None:
try:
unwrap = self.sock.unwrap
except AttributeError:
return
try:
self.sock = unwrap()
... | Unwrap a Python 2.6 SSL socket, so we can call shutdown() |
def format_response_data_type(self, response_data):
"""格式化返回的值为正确的类型
:param response_data: 返回的数据
"""
if isinstance(response_data, list) and not isinstance(
response_data, str
):
return response_data
int_match_str = "|".join(self.config["response_f... | 格式化返回的值为正确的类型
:param response_data: 返回的数据 |
def getclosurevars(func):
"""
Get the mapping of free variables to their current values.
Returns a named tuple of dicts mapping the current nonlocal, global
and builtin references as seen by the body of the function. A final
set of unbound names that could not be resolved is also provided.
Not... | Get the mapping of free variables to their current values.
Returns a named tuple of dicts mapping the current nonlocal, global
and builtin references as seen by the body of the function. A final
set of unbound names that could not be resolved is also provided.
Note:
Modified function from the ... |
def _partition(episodes):
"""Divides metrics data into true rollouts vs off-policy estimates."""
from ray.rllib.evaluation.sampler import RolloutMetrics
rollouts, estimates = [], []
for e in episodes:
if isinstance(e, RolloutMetrics):
rollouts.append(e)
elif isinstance(e, O... | Divides metrics data into true rollouts vs off-policy estimates. |
def qteMakeAppletActive(self, applet: (QtmacsApplet, str)):
"""
Make ``applet`` visible and give it the focus.
If ``applet`` is not yet visible it will replace the
currently active applet, otherwise only the focus will shift.
The ``applet`` parameter can either be an instance o... | Make ``applet`` visible and give it the focus.
If ``applet`` is not yet visible it will replace the
currently active applet, otherwise only the focus will shift.
The ``applet`` parameter can either be an instance of
``QtmacsApplet`` or a string denoting an applet ID. In the
lat... |
def delete(
self, resource_group_name, if_match, provisioning_service_name, certificate_name, certificatename=None, certificateraw_bytes=None, certificateis_verified=None, certificatepurpose=None, certificatecreated=None, certificatelast_updated=None, certificatehas_private_key=None, certificatenonce=None, ... | Delete the Provisioning Service Certificate.
Deletes the specified certificate assosciated with the Provisioning
Service.
:param resource_group_name: Resource group identifier.
:type resource_group_name: str
:param if_match: ETag of the certificate
:type if_match: str
... |
def source_file(pymux, variables):
"""
Source configuration file.
"""
filename = os.path.expanduser(variables['<filename>'])
try:
with open(filename, 'rb') as f:
for line in f:
line = line.decode('utf-8')
handle_command(pymux, line)
except IOEr... | Source configuration file. |
def run(self):
"""Run flux analysis command."""
# Load compound information
def compound_name(id):
if id not in self._model.compounds:
return id
return self._model.compounds[id].properties.get('name', id)
# Reaction genes information
def ... | Run flux analysis command. |
def Serialize(self, writer):
"""
Serialize object.
Raises:
Exception: if hash writing fails.
Args:
writer (neo.IO.BinaryWriter):
"""
try:
writer.WriteByte(self.Type)
writer.WriteHashes(self.Hashes)
except Exception... | Serialize object.
Raises:
Exception: if hash writing fails.
Args:
writer (neo.IO.BinaryWriter): |
def par_relax_AX(i):
"""Parallel implementation of relaxation if option ``RelaxParam`` !=
1.0.
"""
global mp_X
global mp_Xnr
global mp_DX
global mp_DXnr
mp_Xnr[mp_grp[i]:mp_grp[i+1]] = mp_X[mp_grp[i]:mp_grp[i+1]]
mp_DXnr[i] = mp_DX[i]
if mp_rlx != 1.0:
grpind = slice(mp_... | Parallel implementation of relaxation if option ``RelaxParam`` !=
1.0. |
def create_provider_directory(provider, redirect_uri):
"""Helper function for creating a provider directory"""
dir = CLIENT.directories.create({
'name': APPLICATION.name + '-' + provider,
'provider': {
'client_id': settings.STORMPATH_SOCIAL[provider.upper()]['client_id'],
... | Helper function for creating a provider directory |
def _log_multivariate_normal_density_tied(X, means, covars):
"""Compute Gaussian log-density at X for a tied model."""
cv = np.tile(covars, (means.shape[0], 1, 1))
return _log_multivariate_normal_density_full(X, means, cv) | Compute Gaussian log-density at X for a tied model. |
def get(self, request, uri):
"""
Return published node or specified version.
JSON Response:
{uri: x, content: y}
"""
uri = self.decode_uri(uri)
node = cio.get(uri, lazy=False)
if node.content is None:
raise Http404
return self.re... | Return published node or specified version.
JSON Response:
{uri: x, content: y} |
def sg_mse(tensor, opt):
r"""Returns squared error between `tensor` and `target`.
Args:
tensor: A `Tensor`.
opt:
target: A `Tensor` with the same shape and dtype as `tensor`.
name: A `string`. A name to display in the tensor board web UI.
Returns:
A `Tensor` of... | r"""Returns squared error between `tensor` and `target`.
Args:
tensor: A `Tensor`.
opt:
target: A `Tensor` with the same shape and dtype as `tensor`.
name: A `string`. A name to display in the tensor board web UI.
Returns:
A `Tensor` of the same shape and dtype as ... |
def create_channels(chan_name=None, n_chan=None):
"""Create instance of Channels with random xyz coordinates
Parameters
----------
chan_name : list of str
names of the channels
n_chan : int
if chan_name is not specified, this defines the number of channels
Returns
-------
... | Create instance of Channels with random xyz coordinates
Parameters
----------
chan_name : list of str
names of the channels
n_chan : int
if chan_name is not specified, this defines the number of channels
Returns
-------
instance of Channels
where the location of the... |
def relieve_state_machines(self, model, prop_name, info):
""" The method relieves observed models before those get removed from the list of state_machines hold by
observed StateMachineMangerModel. The method register as observer of observable
StateMachineMangerModel.state_machines."""
if... | The method relieves observed models before those get removed from the list of state_machines hold by
observed StateMachineMangerModel. The method register as observer of observable
StateMachineMangerModel.state_machines. |
def comments(self):
"""The AST comments."""
if self._comments is None:
self._comments = [c for c in self.grammar.children if c.is_type(TokenType.comment)]
return self._comments | The AST comments. |
def log(self, cause=None, do_message=True, custom_msg=None):
"""
Loads exception data from the current exception frame - should be called inside the except block
:return:
"""
message = error_message(self, cause=cause)
exc_type, exc_value, exc_traceback = sys.exc_info()
... | Loads exception data from the current exception frame - should be called inside the except block
:return: |
def get_ip_address():
"""Simple utility to get host IP address."""
try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("8.8.8.8", 80))
ip_address = s.getsockname()[0]
except socket_error as sockerr:
if sockerr.errno != errno.ENETUNREACH:
raise sockerr
ip_address = socket... | Simple utility to get host IP address. |
def main(argString=None):
"""The main function of this module.
:param argString: the options.
:type argString: list of strings
"""
# Getting and checking the options
args = parseArgs(argString)
checkArgs(args)
logger.info("Options used:")
for key, value in vars(args).iteritems():... | The main function of this module.
:param argString: the options.
:type argString: list of strings |
def tasks_from_nids(self, nids):
"""
Return the list of tasks associated to the given list of node identifiers (nids).
.. note::
Invalid ids are ignored
"""
if not isinstance(nids, collections.abc.Iterable): nids = [nids]
n2task = {task.node_id: task for ta... | Return the list of tasks associated to the given list of node identifiers (nids).
.. note::
Invalid ids are ignored |
def depends_on(self, dependency):
"""
List of packages that depend on dependency
:param dependency: package name, e.g. 'vext' or 'Pillow'
"""
packages = self.package_info()
return [package for package in packages if dependency in package.get("requires", "")] | List of packages that depend on dependency
:param dependency: package name, e.g. 'vext' or 'Pillow' |
def addresses_from_address_families(address_mapper, specs):
"""Given an AddressMapper and list of Specs, return matching BuildFileAddresses.
:raises: :class:`ResolveError` if:
- there were no matching AddressFamilies, or
- the Spec matches no addresses for SingleAddresses.
:raises: :class:`AddressLooku... | Given an AddressMapper and list of Specs, return matching BuildFileAddresses.
:raises: :class:`ResolveError` if:
- there were no matching AddressFamilies, or
- the Spec matches no addresses for SingleAddresses.
:raises: :class:`AddressLookupError` if no targets are matched for non-SingleAddress specs. |
def _matcher(self, other):
"""
QueryCGRContainer < CGRContainer
QueryContainer < QueryCGRContainer[more general]
"""
if isinstance(other, CGRContainer):
return GraphMatcher(other, self, lambda x, y: y == x, lambda x, y: y == x)
elif isinstance(other, QueryCGRC... | QueryCGRContainer < CGRContainer
QueryContainer < QueryCGRContainer[more general] |
def decode(self, bytes, raw=False):
"""decode(bytearray, raw=False) -> value
Decodes the given bytearray according to this PrimitiveType
definition.
NOTE: The parameter ``raw`` is present to adhere to the
``decode()`` inteface, but has no effect for PrimitiveType
defini... | decode(bytearray, raw=False) -> value
Decodes the given bytearray according to this PrimitiveType
definition.
NOTE: The parameter ``raw`` is present to adhere to the
``decode()`` inteface, but has no effect for PrimitiveType
definitions. |
def get_seq(self,obj,default=None):
"""Return sequence."""
if is_sequence(obj):
return obj
if is_number(obj): return [obj]
if obj is None and default is not None:
log.warning('using default value (%s)'%(default))
return self.get_seq(default)
ra... | Return sequence. |
def obfn_f(self, X=None):
r"""Compute data fidelity term :math:`(1/2) \| D \mathbf{x} -
\mathbf{s} \|_2^2`.
"""
if X is None:
X = self.X
return 0.5 * np.linalg.norm((self.D.dot(X) - self.S).ravel())**2 | r"""Compute data fidelity term :math:`(1/2) \| D \mathbf{x} -
\mathbf{s} \|_2^2`. |
def get_new_author(self, api_author):
"""
Instantiate a new Author from api data.
:param api_author: the api data for the Author
:return: the new Author
"""
return Author(site_id=self.site_id,
wp_id=api_author["ID"],
**self.api... | Instantiate a new Author from api data.
:param api_author: the api data for the Author
:return: the new Author |
def can_create(self):
"""
If the key_name, value_name, and value_type has been provided returns that the
Registry Key can be created, otherwise returns that the Registry Key cannot be created.
Returns:
"""
if (
self.data.get('key_name')
and s... | If the key_name, value_name, and value_type has been provided returns that the
Registry Key can be created, otherwise returns that the Registry Key cannot be created.
Returns: |
def _aligned_series(*many_series):
"""
Return a new list of series containing the data in the input series, but
with their indices aligned. NaNs will be filled in for missing values.
Parameters
----------
*many_series
The series to align.
Returns
-------
aligned_series : it... | Return a new list of series containing the data in the input series, but
with their indices aligned. NaNs will be filled in for missing values.
Parameters
----------
*many_series
The series to align.
Returns
-------
aligned_series : iterable[array-like]
A new list of series... |
def key_from_protobuf(pb):
"""Factory method for creating a key based on a protobuf.
The protobuf should be one returned from the Cloud Datastore
Protobuf API.
:type pb: :class:`.entity_pb2.Key`
:param pb: The Protobuf representing the key.
:rtype: :class:`google.cloud.datastore.key.Key`
... | Factory method for creating a key based on a protobuf.
The protobuf should be one returned from the Cloud Datastore
Protobuf API.
:type pb: :class:`.entity_pb2.Key`
:param pb: The Protobuf representing the key.
:rtype: :class:`google.cloud.datastore.key.Key`
:returns: a new `Key` instance |
def root():
"""Home page."""
return {
"message": "Welcome to the SIP Master Controller (flask variant)",
"_links": {
"items": [
{
"Link": "Health",
"href": "{}health".format(request.url)
},
{
... | Home page. |
def security_rules_list(security_group, resource_group, **kwargs):
'''
.. versionadded:: 2019.2.0
List security rules within a network security group.
:param security_group: The network security group to query.
:param resource_group: The resource group name assigned to the
network securit... | .. versionadded:: 2019.2.0
List security rules within a network security group.
:param security_group: The network security group to query.
:param resource_group: The resource group name assigned to the
network security group.
CLI Example:
.. code-block:: bash
salt-call azurear... |
def validate_args(**args):
"""
function to check if input query is not None
and set missing arguments to default value
"""
if not args['query']:
print("\nMissing required query argument.")
sys.exit()
for key in DEFAULTS:
if key not in args:
args[key] = DEFAULTS[key]
return args | function to check if input query is not None
and set missing arguments to default value |
def delete_types(self, base_key, out_key, *types):
"""
Method to delete a parameter from a parameter documentation.
This method deletes the given `param` from the `base_key` item in the
:attr:`params` dictionary and creates a new item with the original
documentation without the ... | Method to delete a parameter from a parameter documentation.
This method deletes the given `param` from the `base_key` item in the
:attr:`params` dictionary and creates a new item with the original
documentation without the description of the param. This method works
for ``'Results'`` l... |
def serializeCorpus(self):
"""
This method creates a fixture for the "django-tethne_corpus" model.
Returns
-------
corpus_details in JSON format which can written to a file.
"""
corpus_details = [{
"model": "django-tethne.corpus",
... | This method creates a fixture for the "django-tethne_corpus" model.
Returns
-------
corpus_details in JSON format which can written to a file. |
def Expand(self):
"""Reads the contents of the current node and the full
subtree. It then makes the subtree available until the next
xmlTextReaderRead() call """
ret = libxml2mod.xmlTextReaderExpand(self._o)
if ret is None:raise treeError('xmlTextReaderExpand() failed')
... | Reads the contents of the current node and the full
subtree. It then makes the subtree available until the next
xmlTextReaderRead() call |
def path_glob(pattern, current_dir=None):
"""Use pathlib for ant-like patterns, like: "**/*.py"
:param pattern: File/directory pattern to use (as string).
:param current_dir: Current working directory (as Path, pathlib.Path, str)
:return Resolved Path (as path.Path).
"""
if not current_di... | Use pathlib for ant-like patterns, like: "**/*.py"
:param pattern: File/directory pattern to use (as string).
:param current_dir: Current working directory (as Path, pathlib.Path, str)
:return Resolved Path (as path.Path). |
def on_created(self, event):
""" on_created handler """
logger.debug("file created: %s", event.src_path)
if not event.is_directory:
self.update_file(event.src_path) | on_created handler |
def delete_topic(self, topic_name, fail_not_exist=False):
"""Delete a topic entity.
:param topic_name: The name of the topic to delete.
:type topic_name: str
:param fail_not_exist: Whether to raise an exception if the named topic is not
found. If set to True, a ServiceBusResour... | Delete a topic entity.
:param topic_name: The name of the topic to delete.
:type topic_name: str
:param fail_not_exist: Whether to raise an exception if the named topic is not
found. If set to True, a ServiceBusResourceNotFound will be raised.
Default value is False.
:... |
def render_layout(self, form, context):
"""
Returns safe html of the rendering of the layout
"""
form.rendered_fields = []
html = self.layout.render(form, self.form_style, context)
for field in form.fields.keys():
if not field in form.rendered_fields... | Returns safe html of the rendering of the layout |
def make_index_lookup(list_, dict_factory=dict):
r"""
Args:
list_ (list): assumed to have unique items
Returns:
dict: mapping from item to index
CommandLine:
python -m utool.util_list --exec-make_index_lookup
Example:
>>> # ENABLE_DOCTEST
>>> from utool.uti... | r"""
Args:
list_ (list): assumed to have unique items
Returns:
dict: mapping from item to index
CommandLine:
python -m utool.util_list --exec-make_index_lookup
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_list import * # NOQA
>>> import utool as u... |
def primary_key(self, hkey, rkey=None):
"""
Construct a primary key dictionary
You can either pass in a (hash_key[, range_key]) as the arguments, or
you may pass in an Item itself
"""
if isinstance(hkey, dict):
def decode(val):
""" Convert D... | Construct a primary key dictionary
You can either pass in a (hash_key[, range_key]) as the arguments, or
you may pass in an Item itself |
def build_highlight_objects(html, highlights, uniformize_html=True):
'''converts a dict of pretty_name --> [tuple(string, score), ...] to
`Highlight` objects as specified above.
'''
if uniformize_html:
try:
html = uniform_html(html.encode('utf-8')).decode('utf-8')
except Exc... | converts a dict of pretty_name --> [tuple(string, score), ...] to
`Highlight` objects as specified above. |
def interface_list(env, securitygroup_id, sortby):
"""List interfaces associated with security groups."""
mgr = SoftLayer.NetworkManager(env.client)
table = formatting.Table(COLUMNS)
table.sortby = sortby
mask = (
'''networkComponentBindings[
networkComponentId,
net... | List interfaces associated with security groups. |
def get_trial_info(current_trial):
"""Get job information for current trial."""
if current_trial.end_time and ("_" in current_trial.end_time):
# end time is parsed from result.json and the format
# is like: yyyy-mm-dd_hh-MM-ss, which will be converted
# to yyyy-mm-dd hh:MM:ss here
... | Get job information for current trial. |
def hkdf_extract(salt, input_key_material, hash=hashlib.sha512):
'''
Extract a pseudorandom key suitable for use with hkdf_expand
from the input_key_material and a salt using HMAC with the
provided hash (default SHA-512).
salt should be a random, application-specific byte string. If
salt is None or the empty str... | Extract a pseudorandom key suitable for use with hkdf_expand
from the input_key_material and a salt using HMAC with the
provided hash (default SHA-512).
salt should be a random, application-specific byte string. If
salt is None or the empty string, an all-zeros string of the same
length as the hash's block size w... |
def read(message):
"""Convert a parsed protobuf message into a histogram."""
require_compatible_version(message.physt_compatible)
# Currently the only implementation
a_dict = _dict_from_v0342(message)
return create_from_dict(a_dict, "Message") | Convert a parsed protobuf message into a histogram. |
def set_speed(self, aspirate=None, dispense=None):
"""
Set the speed (mm/second) the :any:`Pipette` plunger will move
during :meth:`aspirate` and :meth:`dispense`
Parameters
----------
aspirate: int
The speed in millimeters-per-second, at which the plunger wi... | Set the speed (mm/second) the :any:`Pipette` plunger will move
during :meth:`aspirate` and :meth:`dispense`
Parameters
----------
aspirate: int
The speed in millimeters-per-second, at which the plunger will
move while performing an aspirate
dispense: int... |
def WriteEventBody(self, event):
"""Writes the body of an event object to the output.
Args:
event (EventObject): event.
Raises:
NoFormatterFound: If no event formatter can be found to match the data
type in the event object.
"""
output_values = self._GetOutputValues(event)
... | Writes the body of an event object to the output.
Args:
event (EventObject): event.
Raises:
NoFormatterFound: If no event formatter can be found to match the data
type in the event object. |
def find_censored_md5ext(post_id: int) -> Optional[str]:
"Find MD5 for a censored post's ID, return None if can't find."
try:
last_pull_date = LAST_PULL_DATE_FILE.read_text().strip()
except FileNotFoundError:
last_pull_date = ""
date = datetime.utcnow()
date = f"{date.year}{date.mon... | Find MD5 for a censored post's ID, return None if can't find. |
def get(self, user_id, lang='zh_CN'):
"""
获取用户基本信息(包括UnionID机制)
详情请参考
https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140839
:param user_id: 普通用户的标识,对当前公众号唯一
:param lang: 返回国家地区语言版本,zh_CN 简体,zh_TW 繁体,en 英语
:return: 返回的 JSON 数据包
使用示例::
... | 获取用户基本信息(包括UnionID机制)
详情请参考
https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140839
:param user_id: 普通用户的标识,对当前公众号唯一
:param lang: 返回国家地区语言版本,zh_CN 简体,zh_TW 繁体,en 英语
:return: 返回的 JSON 数据包
使用示例::
from wechatpy import WeChatClient
client... |
def dryRun(self, func, *args, **kwargs):
"""Instead of running function with `*args` and `**kwargs`, just print
out the function call."""
print >> self.out, \
self.formatterDict.get(func, self.defaultFormatter)(func, *args, **kwargs) | Instead of running function with `*args` and `**kwargs`, just print
out the function call. |
def path_without_suffix(self):
"""The relative path to asset without suffix.
Example::
>>> attrs = AssetAttributes(environment, 'js/app.js')
>>> attrs.path_without_suffix
'js/app'
"""
if self.suffix:
return self.path[:-len(''.join(self.suf... | The relative path to asset without suffix.
Example::
>>> attrs = AssetAttributes(environment, 'js/app.js')
>>> attrs.path_without_suffix
'js/app' |
def get_day_start_ut_span(self):
"""
Return the first and last day_start_ut
Returns
-------
first_day_start_ut: int
last_day_start_ut: int
"""
cur = self.conn.cursor()
first_day_start_ut, last_day_start_ut = \
cur.execute("SELECT min(d... | Return the first and last day_start_ut
Returns
-------
first_day_start_ut: int
last_day_start_ut: int |
def update(pkg, slot=None, fromrepo=None, refresh=False, binhost=None, **kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's cont... | .. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any emerge commands spawned by Sa... |
def get_field_analysis(self, field):
"""
Get the FieldAnalysis for a given fieldname
:param field: TODO
:return: :class:`FieldClassAnalysis`
"""
class_analysis = self.get_class_analysis(field.get_class_name())
if class_analysis:
return class_analysis.... | Get the FieldAnalysis for a given fieldname
:param field: TODO
:return: :class:`FieldClassAnalysis` |
def pause(self):
"""Pauses all the snippet clients under management.
This clears the host port of a client because a new port will be
allocated in `resume`.
"""
for client in self._snippet_clients.values():
self._device.log.debug(
'Clearing host port ... | Pauses all the snippet clients under management.
This clears the host port of a client because a new port will be
allocated in `resume`. |
def update(self, *args, **kwargs):
"""See `__setitem__`."""
super(TAG_Compound, self).update(*args, **kwargs)
for key, item in self.items():
if item.name is None:
item.name = key | See `__setitem__`. |
def get_server_build_info(self):
"""
issues a buildinfo command
"""
if self.is_online():
try:
return self.get_mongo_client().server_info()
except OperationFailure, ofe:
log_exception(ofe)
if "there are no users authe... | issues a buildinfo command |
def scale_sfs(s):
"""Scale a site frequency spectrum.
Parameters
----------
s : array_like, int, shape (n_chromosomes,)
Site frequency spectrum.
Returns
-------
sfs_scaled : ndarray, int, shape (n_chromosomes,)
Scaled site frequency spectrum.
"""
k = np.arange(s.si... | Scale a site frequency spectrum.
Parameters
----------
s : array_like, int, shape (n_chromosomes,)
Site frequency spectrum.
Returns
-------
sfs_scaled : ndarray, int, shape (n_chromosomes,)
Scaled site frequency spectrum. |
def parse_qualifier(parser, event, node): #pylint: disable=unused-argument
"""Parse CIM/XML QUALIFIER element and return CIMQualifier"""
name = _get_required_attribute(node, 'NAME')
cim_type = _get_required_attribute(node, 'TYPE')
# TODO 2/16 KS: Why is propagated not used?
propagated = _get_attrib... | Parse CIM/XML QUALIFIER element and return CIMQualifier |
def configure_db(self, hostname, database, username, admin=False):
"""Configure access to database for username from hostname."""
self.connect(password=self.get_mysql_root_password())
if not self.database_exists(database):
self.create_database(database)
remote_ip = self.norm... | Configure access to database for username from hostname. |
def _load_torrents_directory(self):
"""
Load torrents directory
If it does not exist yet, this request will cause the system to create
one
"""
r = self._req_lixian_get_id(torrent=True)
self._downloads_directory = self._load_directory(r['cid']) | Load torrents directory
If it does not exist yet, this request will cause the system to create
one |
def add(self, arg1, arg2=None, arg3=None, bucket_type=None):
"""
Start assembling a Map/Reduce operation. A shortcut for
:func:`RiakMapReduce.add`.
:param arg1: the object or bucket to add
:type arg1: RiakObject, string
:param arg2: a key or list of keys to add (if a buc... | Start assembling a Map/Reduce operation. A shortcut for
:func:`RiakMapReduce.add`.
:param arg1: the object or bucket to add
:type arg1: RiakObject, string
:param arg2: a key or list of keys to add (if a bucket is
given in arg1)
:type arg2: string, list, None
:p... |
def update_layers(self):
"""
Update layers for a service.
"""
signals.post_save.disconnect(layer_post_save, sender=Layer)
try:
LOGGER.debug('Updating layers for service id %s' % self.id)
if self.type == 'OGC:WMS':
update_layers_wms(self)
... | Update layers for a service. |
def _extract_timeseries_list(tsvol, roivol, maskvol=None, roi_values=None, zeroe=True):
"""Partition the timeseries in tsvol according to the ROIs in roivol.
If a mask is given, will use it to exclude any voxel outside of it.
Parameters
----------
tsvol: numpy.ndarray
4D timeseries volume o... | Partition the timeseries in tsvol according to the ROIs in roivol.
If a mask is given, will use it to exclude any voxel outside of it.
Parameters
----------
tsvol: numpy.ndarray
4D timeseries volume or a 3D volume to be partitioned
roivol: numpy.ndarray
3D ROIs volume
maskvol:... |
def progress(self) -> List[bool]:
"""A list of True/False for the number of games the played in the mini series indicating if the player won or lost."""
return [True if p == "W" else False for p in self._data[MiniSeriesData].progress if p != "N"] | A list of True/False for the number of games the played in the mini series indicating if the player won or lost. |
def com_google_fonts_check_metadata_nameid_family_name(ttFont, font_metadata):
"""Checks METADATA.pb font.name field matches
family name declared on the name table.
"""
from fontbakery.utils import get_name_entry_strings
familynames = get_name_entry_strings(ttFont, NameID.TYPOGRAPHIC_FAMILY_NAME)
if not... | Checks METADATA.pb font.name field matches
family name declared on the name table. |
def check_format(self, full_check=True):
"""Check whether the NDArray format is valid.
Parameters
----------
full_check : bool, optional
If `True`, rigorous check, O(N) operations. Otherwise
basic check, O(1) operations (default True).
"""
check_c... | Check whether the NDArray format is valid.
Parameters
----------
full_check : bool, optional
If `True`, rigorous check, O(N) operations. Otherwise
basic check, O(1) operations (default True). |
def offering(self):
"""
Deprecated. Use course and run independently.
"""
warnings.warn(
"Offering is no longer a supported property of Locator. Please use the course and run properties.",
DeprecationWarning,
stacklevel=2
)
if not self.... | Deprecated. Use course and run independently. |
def replace_zeros(self, val, zero_thresh=0.0):
""" Replaces all zeros in the image with a specified value
Returns
-------
image dtype
value to replace zeros with
"""
new_data = self.data.copy()
new_data[new_data <= zero_thresh] = val
return t... | Replaces all zeros in the image with a specified value
Returns
-------
image dtype
value to replace zeros with |
def nvmlUnitGetUnitInfo(unit):
r"""
/**
* Retrieves the static information associated with a unit.
*
* For S-class products.
*
* See \ref nvmlUnitInfo_t for details on available unit info.
*
* @param unit The identifier of the target unit
*... | r"""
/**
* Retrieves the static information associated with a unit.
*
* For S-class products.
*
* See \ref nvmlUnitInfo_t for details on available unit info.
*
* @param unit The identifier of the target unit
* @param info ... |
def initialize(self):
"""Instantiates the cache area to be ready for updates"""
self.Base.metadata.create_all(self.session.bind)
logger.debug("initialized sqlalchemy orm tables") | Instantiates the cache area to be ready for updates |
def extract_header_comment_key_value_tuples_from_file(file_descriptor):
""" Extracts tuples representing comments and localization entries from strings file.
Args:
file_descriptor (file): The file to read the tuples from
Returns:
list : List of tuples representing the headers and localizat... | Extracts tuples representing comments and localization entries from strings file.
Args:
file_descriptor (file): The file to read the tuples from
Returns:
list : List of tuples representing the headers and localization entries. |
def newton_solver_comp(f, x0, lb, ub, infos=False, backsteps=10, maxit=50, numdiff=False):
'''Solves many independent systems f(x)=0 simultaneously using a simple gradient descent.
:param f: objective function to be solved with values p x N . The second output argument represents the derivative with
values ... | Solves many independent systems f(x)=0 simultaneously using a simple gradient descent.
:param f: objective function to be solved with values p x N . The second output argument represents the derivative with
values in (p x p x N)
:param x0: initial value ( p x N )
:param lb: bounds for first variable
... |
def run_function(app_function, event, context):
"""
Given a function and event context,
detect signature and execute, returning any result.
"""
# getargspec does not support python 3 method with type hints
# Related issue: https://github.com/Miserlou/Zappa/issues/1452
... | Given a function and event context,
detect signature and execute, returning any result. |
def symbol_scores(self, symbol):
"""Find matches for symbol.
:param symbol: A . separated symbol. eg. 'os.path.basename'
:returns: A list of tuples of (score, package, reference|None),
ordered by score from highest to lowest.
"""
scores = []
path = []
... | Find matches for symbol.
:param symbol: A . separated symbol. eg. 'os.path.basename'
:returns: A list of tuples of (score, package, reference|None),
ordered by score from highest to lowest. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.