text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def create(tournament, name, **params):
"""Add a participant to a tournament."""
params.update({"name": name})
return api.fetch_and_parse(
"POST",
"tournaments/%s/participants" % tournament,
"participant",
**params) | [
"def",
"create",
"(",
"tournament",
",",
"name",
",",
"*",
"*",
"params",
")",
":",
"params",
".",
"update",
"(",
"{",
"\"name\"",
":",
"name",
"}",
")",
"return",
"api",
".",
"fetch_and_parse",
"(",
"\"POST\"",
",",
"\"tournaments/%s/participants\"",
"%",... | 28 | 14.888889 |
def run(module_name, args=None, env_vars=None, wait=True, capture_error=False):
# type: (str, list, dict, bool, bool) -> subprocess.Popen
"""Run Python module as a script.
Search sys.path for the named module and execute its contents as the __main__ module.
Since the argument is a module name, you mus... | [
"def",
"run",
"(",
"module_name",
",",
"args",
"=",
"None",
",",
"env_vars",
"=",
"None",
",",
"wait",
"=",
"True",
",",
"capture_error",
"=",
"False",
")",
":",
"# type: (str, list, dict, bool, bool) -> subprocess.Popen",
"args",
"=",
"args",
"or",
"[",
"]",
... | 50.328125 | 38.453125 |
def genome(self):
"""
"genome" dictionary ready for pybedtools, based on the BAM header.
"""
# This gets the underlying pysam Samfile object
f = self.adapter.fileobj
d = {}
for ref, length in zip(f.references, f.lengths):
d[ref] = (0, length)
r... | [
"def",
"genome",
"(",
"self",
")",
":",
"# This gets the underlying pysam Samfile object",
"f",
"=",
"self",
".",
"adapter",
".",
"fileobj",
"d",
"=",
"{",
"}",
"for",
"ref",
",",
"length",
"in",
"zip",
"(",
"f",
".",
"references",
",",
"f",
".",
"length... | 31.8 | 15.4 |
def set_service_value(self, service_id, set_name, parameter_name, value):
"""Set a variable on the vera device.
This will call the Vera api to change device state.
"""
payload = {
'id': 'lu_action',
'action': 'Set' + set_name,
'serviceId': service_id,... | [
"def",
"set_service_value",
"(",
"self",
",",
"service_id",
",",
"set_name",
",",
"parameter_name",
",",
"value",
")",
":",
"payload",
"=",
"{",
"'id'",
":",
"'lu_action'",
",",
"'action'",
":",
"'Set'",
"+",
"set_name",
",",
"'serviceId'",
":",
"service_id"... | 36.2 | 13.133333 |
def _coefficient_handler_factory(trans_table, parse_func, assertion=lambda c, ctx: True,
ion_type=None, append_first_if_not=None):
"""Generates a handler co-routine which tokenizes a numeric coefficient.
Args:
trans_table (dict): lookup table for the handler for the nex... | [
"def",
"_coefficient_handler_factory",
"(",
"trans_table",
",",
"parse_func",
",",
"assertion",
"=",
"lambda",
"c",
",",
"ctx",
":",
"True",
",",
"ion_type",
"=",
"None",
",",
"append_first_if_not",
"=",
"None",
")",
":",
"def",
"transition",
"(",
"prev",
",... | 68.285714 | 35.761905 |
def extraneous_whitespace(logical_line):
r"""Avoid extraneous whitespace.
Avoid extraneous whitespace in these situations:
- Immediately inside parentheses, brackets or braces.
- Immediately before a comma, semicolon, or colon.
Okay: spam(ham[1], {eggs: 2})
E201: spam( ham[1], {eggs: 2})
E... | [
"def",
"extraneous_whitespace",
"(",
"logical_line",
")",
":",
"line",
"=",
"logical_line",
"for",
"match",
"in",
"EXTRANEOUS_WHITESPACE_REGEX",
".",
"finditer",
"(",
"line",
")",
":",
"text",
"=",
"match",
".",
"group",
"(",
")",
"char",
"=",
"text",
".",
... | 36.4 | 13.366667 |
def requiredAttribute(requiredAttributeName):
"""
Utility for defining attributes on base classes/mixins which require their
values to be supplied by their derived classes. C{None} is a common, but
almost never suitable default value for these kinds of attributes, as it
may cause operations in the ... | [
"def",
"requiredAttribute",
"(",
"requiredAttributeName",
")",
":",
"class",
"RequiredAttribute",
"(",
"attribute",
")",
":",
"def",
"get",
"(",
"self",
")",
":",
"if",
"requiredAttributeName",
"not",
"in",
"self",
".",
"__dict__",
":",
"raise",
"AttributeError"... | 40.708333 | 19.833333 |
def is_complete(self) -> bool:
""" Determines if a stub completely types a function """
if not self.actual:
return False
for parameter in self.parameters:
if parameter["name"] != "self" and not parameter["type"]:
return False
return True | [
"def",
"is_complete",
"(",
"self",
")",
"->",
"bool",
":",
"if",
"not",
"self",
".",
"actual",
":",
"return",
"False",
"for",
"parameter",
"in",
"self",
".",
"parameters",
":",
"if",
"parameter",
"[",
"\"name\"",
"]",
"!=",
"\"self\"",
"and",
"not",
"p... | 37.75 | 12.75 |
def get_private_ip(self, addr_family=None, *args, **kwargs):
"""Alias for get_ip('private')"""
return self.get_ip('private', addr_family, *args, **kwargs) | [
"def",
"get_private_ip",
"(",
"self",
",",
"addr_family",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"get_ip",
"(",
"'private'",
",",
"addr_family",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | 56 | 15.666667 |
def port_profile_vlan_profile_switchport_basic_basic(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
port_profile = ET.SubElement(config, "port-profile", xmlns="urn:brocade.com:mgmt:brocade-port-profile")
name_key = ET.SubElement(port_profile, "name")
... | [
"def",
"port_profile_vlan_profile_switchport_basic_basic",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"port_profile",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"port-profile\"",
",",
"... | 49.076923 | 20.076923 |
def cli(obj, username):
"""Authenticate using Azure, Github, Gitlab, Google OAuth2, OpenID or
Basic Auth username/password instead of using an API key."""
client = obj['client']
provider = obj['provider']
client_id = obj['client_id']
try:
if provider == 'azure':
token = azur... | [
"def",
"cli",
"(",
"obj",
",",
"username",
")",
":",
"client",
"=",
"obj",
"[",
"'client'",
"]",
"provider",
"=",
"obj",
"[",
"'provider'",
"]",
"client_id",
"=",
"obj",
"[",
"'client_id'",
"]",
"try",
":",
"if",
"provider",
"==",
"'azure'",
":",
"to... | 40.794872 | 19.333333 |
def join(input_layer, others, include_self=True, join_function=None):
"""Joins the provided PrettyTensors with this using the join function.
Args:
input_layer: The input layer for this op.
others: Sequence of PrettyTensor objects.
include_self: Whether or not this includes itself or if the value is onl... | [
"def",
"join",
"(",
"input_layer",
",",
"others",
",",
"include_self",
"=",
"True",
",",
"join_function",
"=",
"None",
")",
":",
"if",
"include_self",
":",
"list_of_tensors",
"=",
"[",
"input_layer",
"]",
"list_of_tensors",
".",
"extend",
"(",
"others",
")",... | 37.25 | 20 |
def inverse_m4x4_transform(mat):
"""
Return the inverse transformation of a m4x4 transformation
:param mat: A m4x4 transform
:return: inv_transform inverse of the tranformation
"""
inv_transform = zeros((4, 4))
rot = mat[:-1, :-1].T
inv_transform[:-1, :-1] = rot
inv_transform[:-1, -1... | [
"def",
"inverse_m4x4_transform",
"(",
"mat",
")",
":",
"inv_transform",
"=",
"zeros",
"(",
"(",
"4",
",",
"4",
")",
")",
"rot",
"=",
"mat",
"[",
":",
"-",
"1",
",",
":",
"-",
"1",
"]",
".",
"T",
"inv_transform",
"[",
":",
"-",
"1",
",",
":",
... | 32.583333 | 10.083333 |
def _key_to_index(keys, key, single_only=False):
'convert ``key`` of various types to int or list of int'
if isinstance(key, int): # validate the int index
try:
keys[key]
except IndexError:
raise KeyError('Index out of range of keys: %s' % (key,))
if key < 0:
... | [
"def",
"_key_to_index",
"(",
"keys",
",",
"key",
",",
"single_only",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"key",
",",
"int",
")",
":",
"# validate the int index",
"try",
":",
"keys",
"[",
"key",
"]",
"except",
"IndexError",
":",
"raise",
"Key... | 35.588235 | 15.647059 |
def GetOutputPluginIndex(
plugin_descriptors,
plugin_id):
"""Gets an output plugin index for a plugin with a given id.
Historically output plugins descriptors were stored in dicts-like
structures with unique identifiers as keys. In REL_DB-based implementation,
however, both plugin descriptors and their... | [
"def",
"GetOutputPluginIndex",
"(",
"plugin_descriptors",
",",
"plugin_id",
")",
":",
"used_names",
"=",
"collections",
".",
"Counter",
"(",
")",
"for",
"(",
"index",
",",
"desc",
")",
"in",
"enumerate",
"(",
"plugin_descriptors",
")",
":",
"cur_plugin_id",
"=... | 36.4 | 26.375 |
def logpdf(self, mu):
"""
Log PDF for Laplace prior
Parameters
----------
mu : float
Latent variable for which the prior is being formed over
Returns
----------
- log(p(mu))
"""
if self.transform is not None:
mu = ... | [
"def",
"logpdf",
"(",
"self",
",",
"mu",
")",
":",
"if",
"self",
".",
"transform",
"is",
"not",
"None",
":",
"mu",
"=",
"self",
".",
"transform",
"(",
"mu",
")",
"return",
"ss",
".",
"laplace",
".",
"logpdf",
"(",
"mu",
",",
"loc",
"=",
"self",
... | 24.875 | 18.75 |
def get_account_id(region=None, key=None, keyid=None, profile=None):
'''
Get a the AWS account id associated with the used credentials.
CLI Example:
.. code-block:: bash
salt myminion boto_iam.get_account_id
'''
cache_key = 'boto_iam.account_id'
if cache_key not in __context__:
... | [
"def",
"get_account_id",
"(",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"cache_key",
"=",
"'boto_iam.account_id'",
"if",
"cache_key",
"not",
"in",
"__context__",
":",
"conn",
"=",
"_... | 38.891892 | 20.081081 |
def _get_secret_from_vault(
key, environment=None, stage=None, namespace=None,
wait_exponential_multiplier=50, wait_exponential_max=5000,
stop_max_delay=10000):
"""Retrieves a secret from the secrets vault."""
# Get the encrypted secret from DynamoDB
table_name = _secrets_table_name(... | [
"def",
"_get_secret_from_vault",
"(",
"key",
",",
"environment",
"=",
"None",
",",
"stage",
"=",
"None",
",",
"namespace",
"=",
"None",
",",
"wait_exponential_multiplier",
"=",
"50",
",",
"wait_exponential_max",
"=",
"5000",
",",
"stop_max_delay",
"=",
"10000",
... | 31.368421 | 20.385965 |
def add_parameters(self,template_file,in_file=None,pst_path=None):
""" add new parameters to a control file
Parameters
----------
template_file : str
template file
in_file : str(optional)
model input file. If None, template_file.replace('.... | [
"def",
"add_parameters",
"(",
"self",
",",
"template_file",
",",
"in_file",
"=",
"None",
",",
"pst_path",
"=",
"None",
")",
":",
"assert",
"os",
".",
"path",
".",
"exists",
"(",
"template_file",
")",
",",
"\"template file '{0}' not found\"",
".",
"format",
"... | 44.490566 | 26.396226 |
def find_conflicts_between_sub_selection_sets(
context: ValidationContext,
cached_fields_and_fragment_names: Dict,
compared_fragment_pairs: "PairSet",
are_mutually_exclusive: bool,
parent_type1: Optional[GraphQLNamedType],
selection_set1: SelectionSetNode,
parent_type2: Optional[GraphQLNamed... | [
"def",
"find_conflicts_between_sub_selection_sets",
"(",
"context",
":",
"ValidationContext",
",",
"cached_fields_and_fragment_names",
":",
"Dict",
",",
"compared_fragment_pairs",
":",
"\"PairSet\"",
",",
"are_mutually_exclusive",
":",
"bool",
",",
"parent_type1",
":",
"Opt... | 36.5 | 17.190476 |
def _build_instance_common_args(self, ec2_keyname, availability_zone,
keep_alive, hadoop_version):
"""
Takes a number of parameters used when starting a jobflow (as
specified in run_jobflow() above). Returns a comparable dict for
use in making a RunJob... | [
"def",
"_build_instance_common_args",
"(",
"self",
",",
"ec2_keyname",
",",
"availability_zone",
",",
"keep_alive",
",",
"hadoop_version",
")",
":",
"params",
"=",
"{",
"'Instances.KeepJobFlowAliveWhenNoSteps'",
":",
"str",
"(",
"keep_alive",
")",
".",
"lower",
"(",... | 38.894737 | 22.368421 |
def set_bytes_transferred(self, bytes_transferred):
''' set the number of bytes transferred - if it has changed return True '''
_changed = False
if bytes_transferred:
_changed = (self._bytes_transferred != int(bytes_transferred))
if _changed:
self._bytes_t... | [
"def",
"set_bytes_transferred",
"(",
"self",
",",
"bytes_transferred",
")",
":",
"_changed",
"=",
"False",
"if",
"bytes_transferred",
":",
"_changed",
"=",
"(",
"self",
".",
"_bytes_transferred",
"!=",
"int",
"(",
"bytes_transferred",
")",
")",
"if",
"_changed",... | 48.5 | 20.666667 |
def cut_module_meta(app, what, name, obj, options, lines):
"""Don't render lines that start with ``:copyright:`` or
``:license:`` when rendering module autodoc. These lines are useful
meta information in the source code, but are noisy in the docs.
"""
if what != "module":
return
lines[:... | [
"def",
"cut_module_meta",
"(",
"app",
",",
"what",
",",
"name",
",",
"obj",
",",
"options",
",",
"lines",
")",
":",
"if",
"what",
"!=",
"\"module\"",
":",
"return",
"lines",
"[",
":",
"]",
"=",
"[",
"line",
"for",
"line",
"in",
"lines",
"if",
"not"... | 36.818182 | 23.636364 |
def set_pending_boot_mode(self, boot_mode):
"""Sets the boot mode of the system for next boot.
:param boot_mode: either 'uefi' or 'legacy'.
:raises: IloInvalidInputError, on an invalid input.
:raises: IloError, on an error from iLO.
:raises: IloCommandNotSupportedError, if the c... | [
"def",
"set_pending_boot_mode",
"(",
"self",
",",
"boot_mode",
")",
":",
"boot_mode",
"=",
"boot_mode",
".",
"lower",
"(",
")",
"if",
"boot_mode",
"not",
"in",
"[",
"'uefi'",
",",
"'legacy'",
"]",
":",
"msg",
"=",
"'Invalid Boot mode specified'",
"raise",
"e... | 38.375 | 16.833333 |
def client(self):
"""The lazy-created OAuth session with the return value of
:meth:`tokengetter`.
:returns: The OAuth session instance or ``None`` while token missing.
"""
token = self.obtain_token()
if token is None:
raise AccessTokenNotFound
return ... | [
"def",
"client",
"(",
"self",
")",
":",
"token",
"=",
"self",
".",
"obtain_token",
"(",
")",
"if",
"token",
"is",
"None",
":",
"raise",
"AccessTokenNotFound",
"return",
"self",
".",
"_make_client_with_token",
"(",
"token",
")"
] | 34.6 | 14.5 |
def _dummify_expr(expr, basename, symbs):
"""
Useful to robustify prior to e.g. regexp substitution of
code strings
"""
dummies = sympy.symbols(basename+':'+str(len(symbs)))
for i, s in enumerate(symbs):
expr = expr.subs({s: dummies[i]})
return expr | [
"def",
"_dummify_expr",
"(",
"expr",
",",
"basename",
",",
"symbs",
")",
":",
"dummies",
"=",
"sympy",
".",
"symbols",
"(",
"basename",
"+",
"':'",
"+",
"str",
"(",
"len",
"(",
"symbs",
")",
")",
")",
"for",
"i",
",",
"s",
"in",
"enumerate",
"(",
... | 30.777778 | 10.555556 |
def _append_comment(ret, comment):
'''
append ``comment`` to ``ret['comment']``
'''
if ret['comment']:
ret['comment'] = ret['comment'].rstrip() + '\n' + comment
else:
ret['comment'] = comment
return ret | [
"def",
"_append_comment",
"(",
"ret",
",",
"comment",
")",
":",
"if",
"ret",
"[",
"'comment'",
"]",
":",
"ret",
"[",
"'comment'",
"]",
"=",
"ret",
"[",
"'comment'",
"]",
".",
"rstrip",
"(",
")",
"+",
"'\\n'",
"+",
"comment",
"else",
":",
"ret",
"["... | 23.4 | 22.4 |
def resolve_attr(obj, path):
"""A recursive version of getattr for navigating dotted paths.
Args:
obj: An object for which we want to retrieve a nested attribute.
path: A dot separated string containing zero or more attribute names.
Returns:
The attribute referred to by obj.a1.a2.a... | [
"def",
"resolve_attr",
"(",
"obj",
",",
"path",
")",
":",
"if",
"not",
"path",
":",
"return",
"obj",
"head",
",",
"_",
",",
"tail",
"=",
"path",
".",
"partition",
"(",
"'.'",
")",
"head_obj",
"=",
"getattr",
"(",
"obj",
",",
"head",
")",
"return",
... | 29.611111 | 20.555556 |
def get_or_generate_tabbed_vocab(data_dir, tmp_dir, source_filename,
index, vocab_filename, vocab_size):
r"""Generate a vocabulary from a tabbed source file.
The source is a file of source, target pairs, where each line contains
a source string and a target string, separated by a... | [
"def",
"get_or_generate_tabbed_vocab",
"(",
"data_dir",
",",
"tmp_dir",
",",
"source_filename",
",",
"index",
",",
"vocab_filename",
",",
"vocab_size",
")",
":",
"def",
"generate",
"(",
")",
":",
"filepath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"tmp_dir... | 37.15625 | 19.9375 |
def mkdir_uchroot(dirpath, root="."):
"""
Create a file inside a uchroot env.
You will want to use this when you need to create a file with apropriate
rights inside a uchroot container with subuid/subgid handling enabled.
Args:
dirpath:
The dirpath that should be created. Absol... | [
"def",
"mkdir_uchroot",
"(",
"dirpath",
",",
"root",
"=",
"\".\"",
")",
":",
"from",
"benchbuild",
".",
"utils",
".",
"uchroot",
"import",
"no_args",
",",
"uretry",
"uchroot",
"=",
"no_args",
"(",
")",
"uchroot",
"=",
"uchroot",
"[",
"\"-E\"",
",",
"\"-A... | 33.619048 | 20.285714 |
def _document_frequency(X):
"""
Count the number of non-zero values for each feature in sparse X.
"""
if sp.isspmatrix_csr(X):
return np.bincount(X.indices, minlength=X.shape[1])
return np.diff(sp.csc_matrix(X, copy=False).indptr) | [
"def",
"_document_frequency",
"(",
"X",
")",
":",
"if",
"sp",
".",
"isspmatrix_csr",
"(",
"X",
")",
":",
"return",
"np",
".",
"bincount",
"(",
"X",
".",
"indices",
",",
"minlength",
"=",
"X",
".",
"shape",
"[",
"1",
"]",
")",
"return",
"np",
".",
... | 36 | 12.571429 |
def connect_put_namespaced_pod_proxy_with_path(self, name, namespace, path, **kwargs):
"""
connect PUT requests to proxy of Pod
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.connect_put_n... | [
"def",
"connect_put_namespaced_pod_proxy_with_path",
"(",
"self",
",",
"name",
",",
"namespace",
",",
"path",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async_req'",
")",
... | 53.608696 | 27.173913 |
def remove_entities(self, entity_ids):
"""
Remove entities by index.
Parameters
-----------
entity_ids : (n,) int
Indexes of self.entities to remove
"""
if len(entity_ids) == 0:
return
keep = np.ones(len(self.entities))
keep[... | [
"def",
"remove_entities",
"(",
"self",
",",
"entity_ids",
")",
":",
"if",
"len",
"(",
"entity_ids",
")",
"==",
"0",
":",
"return",
"keep",
"=",
"np",
".",
"ones",
"(",
"len",
"(",
"self",
".",
"entities",
")",
")",
"keep",
"[",
"entity_ids",
"]",
"... | 26.428571 | 10.714286 |
def subtask(*args, **kwargs):
'''Decorator which prints out the name of the decorated function on
execution.
'''
depth = kwargs.get('depth', 2)
prefix = kwargs.get('prefix', '\n' + '#' * depth + ' ')
tail = kwargs.get('tail', '\n')
doc1 = kwargs.get('doc1', False)
color = kwargs.get('col... | [
"def",
"subtask",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"depth",
"=",
"kwargs",
".",
"get",
"(",
"'depth'",
",",
"2",
")",
"prefix",
"=",
"kwargs",
".",
"get",
"(",
"'prefix'",
",",
"'\\n'",
"+",
"'#'",
"*",
"depth",
"+",
"' '",
... | 36.285714 | 19.238095 |
def list_repos(**kwargs):
'''
List all repos known by XBPS
CLI Example:
.. code-block:: bash
salt '*' pkg.list_repos
'''
repos = {}
out = __salt__['cmd.run']('xbps-query -L', output_loglevel='trace')
for line in out.splitlines():
repo = {}
if not line:
... | [
"def",
"list_repos",
"(",
"*",
"*",
"kwargs",
")",
":",
"repos",
"=",
"{",
"}",
"out",
"=",
"__salt__",
"[",
"'cmd.run'",
"]",
"(",
"'xbps-query -L'",
",",
"output_loglevel",
"=",
"'trace'",
")",
"for",
"line",
"in",
"out",
".",
"splitlines",
"(",
")",... | 26.535714 | 21.392857 |
def reference_contexts_for_variants(
variants,
context_size,
transcript_id_whitelist=None):
"""
Extract a set of reference contexts for each variant in the collection.
Parameters
----------
variants : varcode.VariantCollection
context_size : int
Max of nucleotid... | [
"def",
"reference_contexts_for_variants",
"(",
"variants",
",",
"context_size",
",",
"transcript_id_whitelist",
"=",
"None",
")",
":",
"result",
"=",
"OrderedDict",
"(",
")",
"for",
"variant",
"in",
"variants",
":",
"result",
"[",
"variant",
"]",
"=",
"reference... | 32.285714 | 19.571429 |
def _get_win_argv():
"""Returns a unicode argv under Windows and standard sys.argv otherwise
Returns:
List[`fsnative`]
"""
assert is_win
argc = ctypes.c_int()
try:
argv = winapi.CommandLineToArgvW(
winapi.GetCommandLineW(), ctypes.byref(argc))
except WindowsErr... | [
"def",
"_get_win_argv",
"(",
")",
":",
"assert",
"is_win",
"argc",
"=",
"ctypes",
".",
"c_int",
"(",
")",
"try",
":",
"argv",
"=",
"winapi",
".",
"CommandLineToArgvW",
"(",
"winapi",
".",
"GetCommandLineW",
"(",
")",
",",
"ctypes",
".",
"byref",
"(",
"... | 19.208333 | 24.125 |
def gen_topomask(h, lon, lat, dx=1.0, kind="linear", plot=False):
"""
Generates a topography mask from an oceanographic transect taking the
deepest CTD scan as the depth of each station.
Inputs
------
h : array
Pressure of the deepest CTD scan for each station [dbar].
lons : array
... | [
"def",
"gen_topomask",
"(",
"h",
",",
"lon",
",",
"lat",
",",
"dx",
"=",
"1.0",
",",
"kind",
"=",
"\"linear\"",
",",
"plot",
"=",
"False",
")",
":",
"import",
"gsw",
"from",
"scipy",
".",
"interpolate",
"import",
"interp1d",
"h",
",",
"lon",
",",
"... | 28.6 | 23.088889 |
def update_user(self):
"""
Save the state of the current user
"""
# First create a copy of the current user
user_dict = self.serialize()
# Then delete the entities in the description field
del user_dict['description']['entities']
# Then upload user_dict
... | [
"def",
"update_user",
"(",
"self",
")",
":",
"# First create a copy of the current user",
"user_dict",
"=",
"self",
".",
"serialize",
"(",
")",
"# Then delete the entities in the description field",
"del",
"user_dict",
"[",
"'description'",
"]",
"[",
"'entities'",
"]",
... | 37.3 | 9.3 |
def upload_file_from_url(self, url, file_name, dir_name=None):
"""简单上传文件(https://www.qcloud.com/document/product/436/6066)
:param url: 文件url地址
:param file_name: 文件名称
:param dir_name: 文件夹名称(可选)
:return:json数据串
"""
real_file_name = str(int(time.time()*1000))
... | [
"def",
"upload_file_from_url",
"(",
"self",
",",
"url",
",",
"file_name",
",",
"dir_name",
"=",
"None",
")",
":",
"real_file_name",
"=",
"str",
"(",
"int",
"(",
"time",
".",
"time",
"(",
")",
"*",
"1000",
")",
")",
"urllib",
".",
"request",
".",
"url... | 36.923077 | 14.615385 |
async def pause(self, pause: bool = True):
"""
Pauses the current song.
Parameters
----------
pause : bool
Set to ``False`` to resume.
"""
self._paused = pause
await self.node.pause(self.channel.guild.id, pause) | [
"async",
"def",
"pause",
"(",
"self",
",",
"pause",
":",
"bool",
"=",
"True",
")",
":",
"self",
".",
"_paused",
"=",
"pause",
"await",
"self",
".",
"node",
".",
"pause",
"(",
"self",
".",
"channel",
".",
"guild",
".",
"id",
",",
"pause",
")"
] | 25.272727 | 13.272727 |
def values(self, start=None, stop=None):
"""Like :meth:`items` but returns only the values."""
return (item[1] for item in self.items(start, stop)) | [
"def",
"values",
"(",
"self",
",",
"start",
"=",
"None",
",",
"stop",
"=",
"None",
")",
":",
"return",
"(",
"item",
"[",
"1",
"]",
"for",
"item",
"in",
"self",
".",
"items",
"(",
"start",
",",
"stop",
")",
")"
] | 53.666667 | 6.666667 |
def bind_to(self, table, name):
"""
Bind this column to a table, and assign it a name. This method
can only be called once per instance, because a Column cannot be
bound to multiple tables. (The sort order would be ambiguous.)
"""
if self.bound_to is not None:
... | [
"def",
"bind_to",
"(",
"self",
",",
"table",
",",
"name",
")",
":",
"if",
"self",
".",
"bound_to",
"is",
"not",
"None",
":",
"raise",
"AttributeError",
"(",
"\"Column is already bound to '%s' as '%s'\"",
"%",
"self",
".",
"bound_to",
")",
"self",
".",
"bound... | 38.833333 | 15 |
def reset(self):
"""
Empties all internal storage containers
"""
self.X = []
self.Y = []
self.w = []
self.Xnorm = []
self.graph_rep = None | [
"def",
"reset",
"(",
"self",
")",
":",
"self",
".",
"X",
"=",
"[",
"]",
"self",
".",
"Y",
"=",
"[",
"]",
"self",
".",
"w",
"=",
"[",
"]",
"self",
".",
"Xnorm",
"=",
"[",
"]",
"self",
".",
"graph_rep",
"=",
"None"
] | 18 | 18.727273 |
def _is_valid_position(self, position):
'''
check if given position is valid for this collection
'''
row, col = position
valid_r = row in self.row_labels
valid_c = col in self.col_labels
return valid_r and valid_c | [
"def",
"_is_valid_position",
"(",
"self",
",",
"position",
")",
":",
"row",
",",
"col",
"=",
"position",
"valid_r",
"=",
"row",
"in",
"self",
".",
"row_labels",
"valid_c",
"=",
"col",
"in",
"self",
".",
"col_labels",
"return",
"valid_r",
"and",
"valid_c"
] | 32.75 | 12.25 |
def SCG(f, gradf, x, optargs=(), maxiters=500, max_f_eval=np.inf, xtol=None, ftol=None, gtol=None):
"""
Optimisation through Scaled Conjugate Gradients (SCG)
f: the objective function
gradf : the gradient function (should return a 1D np.ndarray)
x : the initial condition
Returns
x the opti... | [
"def",
"SCG",
"(",
"f",
",",
"gradf",
",",
"x",
",",
"optargs",
"=",
"(",
")",
",",
"maxiters",
"=",
"500",
",",
"max_f_eval",
"=",
"np",
".",
"inf",
",",
"xtol",
"=",
"None",
",",
"ftol",
"=",
"None",
",",
"gtol",
"=",
"None",
")",
":",
"if"... | 31.847328 | 17.648855 |
def _get_file_size(path, get_retriever):
"""Return file size in megabytes, including querying remote integrations
"""
integration, config = get_retriever.integration_and_config(path)
if integration:
return integration.file_size(path, config)
elif os.path.exists(path):
return os.path.... | [
"def",
"_get_file_size",
"(",
"path",
",",
"get_retriever",
")",
":",
"integration",
",",
"config",
"=",
"get_retriever",
".",
"integration_and_config",
"(",
"path",
")",
"if",
"integration",
":",
"return",
"integration",
".",
"file_size",
"(",
"path",
",",
"c... | 43.25 | 10.625 |
def array(self, size, type, name, *parameters):
"""Define a new array of given `size` and containing fields of type `type`.
`name` if the name of this array element. The `type` is the name of keyword that is executed as the contents of
the array and optional extra parameters are passed as argum... | [
"def",
"array",
"(",
"self",
",",
"size",
",",
"type",
",",
"name",
",",
"*",
"parameters",
")",
":",
"self",
".",
"_new_list",
"(",
"size",
",",
"name",
")",
"BuiltIn",
"(",
")",
".",
"run_keyword",
"(",
"type",
",",
"''",
",",
"*",
"parameters",
... | 40.866667 | 24.466667 |
def resample(samples, oldsr, newsr):
# type: (np.ndarray, int, int) -> np.ndarray
"""
Resample `samples` with given samplerate `sr` to new samplerate `newsr`
samples: mono or multichannel frames
oldsr : original samplerate
newsr : new sample rate
Returns: the new samples
"""
back... | [
"def",
"resample",
"(",
"samples",
",",
"oldsr",
",",
"newsr",
")",
":",
"# type: (np.ndarray, int, int) -> np.ndarray",
"backends",
"=",
"[",
"_resample_samplerate",
",",
"# turns the samples into float32, which is ok for audio ",
"_resample_scikits",
",",
"_resample_nnresampl... | 36.434783 | 20.173913 |
def _receive(self, root, directory, dirs, files, include, exclude):
"""Internal function processing each yield from os.walk."""
self._received += 1
if not self.symlinks:
where = root + os.path.sep + directory + os.path.sep
files = [
file_name for file_na... | [
"def",
"_receive",
"(",
"self",
",",
"root",
",",
"directory",
",",
"dirs",
",",
"files",
",",
"include",
",",
"exclude",
")",
":",
"self",
".",
"_received",
"+=",
"1",
"if",
"not",
"self",
".",
"symlinks",
":",
"where",
"=",
"root",
"+",
"os",
"."... | 37.793103 | 20.172414 |
def camera_to_rays(camera):
"""
Convert a trimesh.scene.Camera object to ray origins
and direction vectors. Will return one ray per pixel,
as set in camera.resolution.
Parameters
--------------
camera : trimesh.scene.Camera
Camera with transform defined
Returns
--------------... | [
"def",
"camera_to_rays",
"(",
"camera",
")",
":",
"# radians of half the field of view",
"half",
"=",
"np",
".",
"radians",
"(",
"camera",
".",
"fov",
"/",
"2.0",
")",
"# scale it down by two pixels to keep image under resolution",
"half",
"*=",
"(",
"camera",
".",
... | 30.137255 | 16.72549 |
def stats(request, server_name):
"""
Show server statistics.
"""
server_name = server_name.strip('/')
data = _context_data({
'title': _('Memcache Statistics for %s') % server_name,
'cache_stats': _get_cache_stats(server_name),
},
request)
return render_to_response('me... | [
"def",
"stats",
"(",
"request",
",",
"server_name",
")",
":",
"server_name",
"=",
"server_name",
".",
"strip",
"(",
"'/'",
")",
"data",
"=",
"_context_data",
"(",
"{",
"'title'",
":",
"_",
"(",
"'Memcache Statistics for %s'",
")",
"%",
"server_name",
",",
... | 33.272727 | 16.181818 |
def add_device_with_name_location_timezone( self,
model,
serial,
name,
location,
... | [
"def",
"add_device_with_name_location_timezone",
"(",
"self",
",",
"model",
",",
"serial",
",",
"name",
",",
"location",
",",
"timezone",
")",
":",
"retval",
"=",
"None",
"retval",
"=",
"self",
".",
"add_location_timezone_to_device",
"(",
"self",
".",
"rename_de... | 35.458333 | 13.458333 |
def chisq_red(self):
"""
The reduced chi-square of the linear least squares
"""
if self._chisq_red is None:
self._chisq_red = chisquare(self.y_unweighted.transpose(), _np.dot(self.X_unweighted, self.beta), self.y_error, ddof=3, verbose=False)
return self._chisq_red | [
"def",
"chisq_red",
"(",
"self",
")",
":",
"if",
"self",
".",
"_chisq_red",
"is",
"None",
":",
"self",
".",
"_chisq_red",
"=",
"chisquare",
"(",
"self",
".",
"y_unweighted",
".",
"transpose",
"(",
")",
",",
"_np",
".",
"dot",
"(",
"self",
".",
"X_unw... | 44.428571 | 22.714286 |
def topic_content(self, W, output_file="topic_description.csv"):
"""
Print top W words in each topic to file.
"""
topic_top_probs = []
topic_top_words = []
tt = self.tt_avg(False)
for t in range(self.K):
top_word_indices = list(tt[:, t]... | [
"def",
"topic_content",
"(",
"self",
",",
"W",
",",
"output_file",
"=",
"\"topic_description.csv\"",
")",
":",
"topic_top_probs",
"=",
"[",
"]",
"topic_top_words",
"=",
"[",
"]",
"tt",
"=",
"self",
".",
"tt_avg",
"(",
"False",
")",
"for",
"t",
"in",
"ran... | 38.769231 | 19.538462 |
def connect(self):
"""
Connects to publisher
"""
self.client = redis.Redis(
host=self.host, port=self.port, password=self.password) | [
"def",
"connect",
"(",
"self",
")",
":",
"self",
".",
"client",
"=",
"redis",
".",
"Redis",
"(",
"host",
"=",
"self",
".",
"host",
",",
"port",
"=",
"self",
".",
"port",
",",
"password",
"=",
"self",
".",
"password",
")"
] | 28.333333 | 11 |
def set_level(level):
"""
Set the logging level of the root handler.
:param level: The logging level to filter on (an integer or string).
If no root handler exists yet this automatically calls :func:`install()`.
"""
handler, logger = find_handler(logging.getLogger(), match_stream_handler)
... | [
"def",
"set_level",
"(",
"level",
")",
":",
"handler",
",",
"logger",
"=",
"find_handler",
"(",
"logging",
".",
"getLogger",
"(",
")",
",",
"match_stream_handler",
")",
"if",
"handler",
"and",
"logger",
":",
"# Change the level of the existing handler.",
"handler"... | 35.647059 | 18.470588 |
def validate_auto_threaded_json(pjson):
"""Takes a parsed JSON dict representing a set of tests in the auto-threaded
format and validates it, descending recursively if necessary."""
# pjson should be a dict or unicode
if not type(pjson) is dict:
raise ParseError("Expected a J... | [
"def",
"validate_auto_threaded_json",
"(",
"pjson",
")",
":",
"# pjson should be a dict or unicode",
"if",
"not",
"type",
"(",
"pjson",
")",
"is",
"dict",
":",
"raise",
"ParseError",
"(",
"\"Expected a JSON object/dictionary or a string representing a test. Instead got %s.\"",
... | 44.275 | 21.625 |
def get_observation_fields(search_query: str="", page: int=1) -> List[Dict[str, Any]]:
"""
Search the (globally available) observation
:param search_query:
:param page:
:return:
"""
payload = {
'q': search_query,
'page': page
} # type: Dict[str, Union[int, str]]
res... | [
"def",
"get_observation_fields",
"(",
"search_query",
":",
"str",
"=",
"\"\"",
",",
"page",
":",
"int",
"=",
"1",
")",
"->",
"List",
"[",
"Dict",
"[",
"str",
",",
"Any",
"]",
"]",
":",
"payload",
"=",
"{",
"'q'",
":",
"search_query",
",",
"'page'",
... | 31.357143 | 21.928571 |
def mag_field_motors(RAW_IMU, SENSOR_OFFSETS, ofs, SERVO_OUTPUT_RAW, motor_ofs):
'''calculate magnetic field strength from raw magnetometer'''
mag_x = RAW_IMU.xmag
mag_y = RAW_IMU.ymag
mag_z = RAW_IMU.zmag
ofs = get_motor_offsets(SERVO_OUTPUT_RAW, ofs, motor_ofs)
if SENSOR_OFFSETS is not None ... | [
"def",
"mag_field_motors",
"(",
"RAW_IMU",
",",
"SENSOR_OFFSETS",
",",
"ofs",
",",
"SERVO_OUTPUT_RAW",
",",
"motor_ofs",
")",
":",
"mag_x",
"=",
"RAW_IMU",
".",
"xmag",
"mag_y",
"=",
"RAW_IMU",
".",
"ymag",
"mag_z",
"=",
"RAW_IMU",
".",
"zmag",
"ofs",
"=",... | 40.692308 | 20.384615 |
def _handle_extract_pattern(self, pattern):
'''Handle input option pattern'''
if pattern is None or not pattern:
patterns = []
elif isinstance(pattern, str):
patterns = [pattern]
elif isinstance(pattern, Iterable):
patterns = pattern
else:
... | [
"def",
"_handle_extract_pattern",
"(",
"self",
",",
"pattern",
")",
":",
"if",
"pattern",
"is",
"None",
"or",
"not",
"pattern",
":",
"patterns",
"=",
"[",
"]",
"elif",
"isinstance",
"(",
"pattern",
",",
"str",
")",
":",
"patterns",
"=",
"[",
"pattern",
... | 38.294118 | 13 |
def handle(self,
t_input: inference.TranslatorInput,
t_output: inference.TranslatorOutput,
t_walltime: float = 0.):
"""
:param t_input: Translator input.
:param t_output: Translator output.
:param t_walltime: Total walltime for translation.
... | [
"def",
"handle",
"(",
"self",
",",
"t_input",
":",
"inference",
".",
"TranslatorInput",
",",
"t_output",
":",
"inference",
".",
"TranslatorOutput",
",",
"t_walltime",
":",
"float",
"=",
"0.",
")",
":",
"self",
".",
"stream",
".",
"write",
"(",
"\"%s\\n\"",... | 36.727273 | 8.909091 |
def robust_zscore(mat, ctrl_mat=None, min_mad=0.1):
''' Robustly z-score a pandas df along the rows.
Args:
mat (pandas df): Matrix of data that z-scoring will be applied to
ctrl_mat (pandas df): Optional matrix from which to compute medians and MADs
(e.g. vehicle control)
min_mad (float): M... | [
"def",
"robust_zscore",
"(",
"mat",
",",
"ctrl_mat",
"=",
"None",
",",
"min_mad",
"=",
"0.1",
")",
":",
"# If optional df exists, calc medians and mads from it",
"if",
"ctrl_mat",
"is",
"not",
"None",
":",
"medians",
"=",
"ctrl_mat",
".",
"median",
"(",
"axis",
... | 32.6 | 22.142857 |
def check_color(cls, raw_image):
"""
Just check if raw_image is completely white.
http://stackoverflow.com/questions/14041562/python-pil-detect-if-an-image-is-completely-black-or-white
"""
# sum(img.convert("L").getextrema()) in (0, 2)
extrema = raw_image.convert("L... | [
"def",
"check_color",
"(",
"cls",
",",
"raw_image",
")",
":",
"# sum(img.convert(\"L\").getextrema()) in (0, 2)\r",
"extrema",
"=",
"raw_image",
".",
"convert",
"(",
"\"L\"",
")",
".",
"getextrema",
"(",
")",
"if",
"extrema",
"==",
"(",
"255",
",",
"255",
")",... | 46.222222 | 14 |
def load_re_from_file(filepath):
"""Converts a re file to Regular Grammar instance"""
regexp = None
with open(filepath,'r') as mlfile:
flagstr = ""
for line in mlfile:
cleanline = re.sub("//.*$", "", line)
if re.search("^\s*$", cleanline):
continue
... | [
"def",
"load_re_from_file",
"(",
"filepath",
")",
":",
"regexp",
"=",
"None",
"with",
"open",
"(",
"filepath",
",",
"'r'",
")",
"as",
"mlfile",
":",
"flagstr",
"=",
"\"\"",
"for",
"line",
"in",
"mlfile",
":",
"cleanline",
"=",
"re",
".",
"sub",
"(",
... | 35.380952 | 12.904762 |
def on_btn_delete_fit(self, event):
"""
removes the current interpretation
Parameters
----------
event : the wx.ButtonEvent that triggered this function
"""
self.delete_fit(self.current_fit, specimen=self.s) | [
"def",
"on_btn_delete_fit",
"(",
"self",
",",
"event",
")",
":",
"self",
".",
"delete_fit",
"(",
"self",
".",
"current_fit",
",",
"specimen",
"=",
"self",
".",
"s",
")"
] | 28.444444 | 14.666667 |
def alignmentPanelHTML(titlesAlignments, sortOn='maxScore',
outputDir=None, idList=False, equalizeXAxes=False,
xRange='subject', logLinearXAxis=False,
logBase=DEFAULT_LOG_LINEAR_X_AXIS_BASE,
rankScores=False, showFeatures=True, ... | [
"def",
"alignmentPanelHTML",
"(",
"titlesAlignments",
",",
"sortOn",
"=",
"'maxScore'",
",",
"outputDir",
"=",
"None",
",",
"idList",
"=",
"False",
",",
"equalizeXAxes",
"=",
"False",
",",
"xRange",
"=",
"'subject'",
",",
"logLinearXAxis",
"=",
"False",
",",
... | 46.506849 | 24.424658 |
def initUI(self):
#self.setMinimumSize(WIDTH,HEIGTH)
#self.setMaximumSize(WIDTH,HEIGTH)
'''Radio buttons for Original/RGB/HSV/YUV images'''
self.origButton = QRadioButton("Original")
self.rgbButton = QRadioButton("RGB")
self.hsvButton = QRadioButton("HSV")
self.... | [
"def",
"initUI",
"(",
"self",
")",
":",
"#self.setMinimumSize(WIDTH,HEIGTH)",
"#self.setMaximumSize(WIDTH,HEIGTH)",
"self",
".",
"origButton",
"=",
"QRadioButton",
"(",
"\"Original\"",
")",
"self",
".",
"rgbButton",
"=",
"QRadioButton",
"(",
"\"RGB\"",
")",
"self",
... | 44.781609 | 13.264368 |
def get_instance(self, payload):
"""
Build an instance of WorkerInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.taskrouter.v1.workspace.worker.WorkerInstance
:rtype: twilio.rest.taskrouter.v1.workspace.worker.WorkerInstance
"""
... | [
"def",
"get_instance",
"(",
"self",
",",
"payload",
")",
":",
"return",
"WorkerInstance",
"(",
"self",
".",
"_version",
",",
"payload",
",",
"workspace_sid",
"=",
"self",
".",
"_solution",
"[",
"'workspace_sid'",
"]",
",",
")"
] | 40.5 | 23.9 |
def _nemo_accpars(self,vo,ro):
"""
NAME:
_nemo_accpars
PURPOSE:
return the accpars potential parameters for use of this potential with NEMO
INPUT:
vo - velocity unit in km/s
ro - length unit in kpc
OUTPUT:
accpars str... | [
"def",
"_nemo_accpars",
"(",
"self",
",",
"vo",
",",
"ro",
")",
":",
"GM",
"=",
"self",
".",
"_amp",
"*",
"vo",
"**",
"2.",
"*",
"ro",
"/",
"2.",
"return",
"\"0,1,%s,%s,0\"",
"%",
"(",
"GM",
",",
"self",
".",
"a",
"*",
"ro",
")"
] | 16.888889 | 25.111111 |
def generator_to_list(fn):
"""This decorator is for flat_list function.
It converts returned generator to list.
"""
def wrapper(*args, **kw):
return list(fn(*args, **kw))
return wrapper | [
"def",
"generator_to_list",
"(",
"fn",
")",
":",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"return",
"list",
"(",
"fn",
"(",
"*",
"args",
",",
"*",
"*",
"kw",
")",
")",
"return",
"wrapper"
] | 29.571429 | 7.714286 |
def association_rules(self):
"""
Returns association rules that were generated. Only if implements AssociationRulesProducer.
:return: the association rules that were generated
:rtype: AssociationRules
"""
if not self.check_type(self.jobject, "weka.associations.Associatio... | [
"def",
"association_rules",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"check_type",
"(",
"self",
".",
"jobject",
",",
"\"weka.associations.AssociationRulesProducer\"",
")",
":",
"return",
"None",
"return",
"AssociationRules",
"(",
"javabridge",
".",
"call",... | 44.727273 | 25.454545 |
def push(self, variables, interactive=True):
"""Inject a group of variables into the IPython user namespace.
Parameters
----------
variables : dict, str or list/tuple of str
The variables to inject into the user's namespace. If a dict, a
simple update is done. ... | [
"def",
"push",
"(",
"self",
",",
"variables",
",",
"interactive",
"=",
"True",
")",
":",
"vdict",
"=",
"None",
"# We need a dict of name/value pairs to do namespace updates.",
"if",
"isinstance",
"(",
"variables",
",",
"dict",
")",
":",
"vdict",
"=",
"variables",
... | 39.043478 | 19.217391 |
def elixir_decode(elixir_filename):
"""
Takes an elixir style file name and decodes it's content.
Values returned as a dictionary. Elixir filenames have the format
RUNID.TYPE.FILTER/EXPTIME.CHIPID.VERSION.fits
"""
import re, pyfits
parts_RE=re.compile(r'([^\.\s]+)')
dataset_name =... | [
"def",
"elixir_decode",
"(",
"elixir_filename",
")",
":",
"import",
"re",
",",
"pyfits",
"parts_RE",
"=",
"re",
".",
"compile",
"(",
"r'([^\\.\\s]+)'",
")",
"dataset_name",
"=",
"parts_RE",
".",
"findall",
"(",
"elixir_filename",
")",
"### check that this was a va... | 33.319149 | 17.191489 |
def CB(self):
'''
Vertices C and B, list.
'''
try:
return self._CB
except AttributeError:
pass
self._CB = [self.C, self.B]
return self._CB | [
"def",
"CB",
"(",
"self",
")",
":",
"try",
":",
"return",
"self",
".",
"_CB",
"except",
"AttributeError",
":",
"pass",
"self",
".",
"_CB",
"=",
"[",
"self",
".",
"C",
",",
"self",
".",
"B",
"]",
"return",
"self",
".",
"_CB"
] | 19 | 21 |
def dump(self, blob, stream):
"""
Call json.dump with the attributes of this instance as
arguments.
"""
json.dump(
blob, stream, indent=self.indent, sort_keys=True,
separators=self.separators,
) | [
"def",
"dump",
"(",
"self",
",",
"blob",
",",
"stream",
")",
":",
"json",
".",
"dump",
"(",
"blob",
",",
"stream",
",",
"indent",
"=",
"self",
".",
"indent",
",",
"sort_keys",
"=",
"True",
",",
"separators",
"=",
"self",
".",
"separators",
",",
")"... | 25.8 | 17 |
def protect(self, password=None, read_protect=False, protect_from=0):
"""Set lock bits to disable future memory modifications.
If *password* is None, all memory pages except the 16-bit
counter in page 41 are protected by setting the relevant lock
bits (note that lock bits can not be res... | [
"def",
"protect",
"(",
"self",
",",
"password",
"=",
"None",
",",
"read_protect",
"=",
"False",
",",
"protect_from",
"=",
"0",
")",
":",
"return",
"super",
"(",
"NTAG203",
",",
"self",
")",
".",
"protect",
"(",
"password",
",",
"read_protect",
",",
"pr... | 42.875 | 21.8125 |
def isclose(a, b, rtol=4*np.finfo(float).eps, atol=0.0, equal_nan=False):
"""
Returns a boolean array where two arrays are element-wise equal within a
tolerance.
This function is essentially a copy of the `numpy.isclose` function,
with different default tolerances and one minor changes necessary to... | [
"def",
"isclose",
"(",
"a",
",",
"b",
",",
"rtol",
"=",
"4",
"*",
"np",
".",
"finfo",
"(",
"float",
")",
".",
"eps",
",",
"atol",
"=",
"0.0",
",",
"equal_nan",
"=",
"False",
")",
":",
"def",
"within_tol",
"(",
"x",
",",
"y",
",",
"atol",
",",... | 37.111111 | 23.759259 |
def replace(self, text, pattern=None):
"""Replace selected text by *text*
If *pattern* is not None, replacing selected text using regular
expression text substitution"""
cursor = self.textCursor()
cursor.beginEditBlock()
if pattern is not None:
seltxt =... | [
"def",
"replace",
"(",
"self",
",",
"text",
",",
"pattern",
"=",
"None",
")",
":",
"cursor",
"=",
"self",
".",
"textCursor",
"(",
")",
"cursor",
".",
"beginEditBlock",
"(",
")",
"if",
"pattern",
"is",
"not",
"None",
":",
"seltxt",
"=",
"to_text_string"... | 43.142857 | 10.5 |
def sample_measurements(
self,
indices: List[int],
repetitions: int=1) -> List[List[bool]]:
"""Samples from measurements in the computational basis.
Note that this does not collapse the wave function.
Args:
indices: Which qubits are measured.
... | [
"def",
"sample_measurements",
"(",
"self",
",",
"indices",
":",
"List",
"[",
"int",
"]",
",",
"repetitions",
":",
"int",
"=",
"1",
")",
"->",
"List",
"[",
"List",
"[",
"bool",
"]",
"]",
":",
"# Stepper uses little endian while sample_state uses big endian.",
"... | 38.521739 | 23.434783 |
def get_vaults(self):
"""Pass through to provider VaultLookupSession.get_vaults"""
# Implemented from kitosid template for -
# osid.resource.BinLookupSession.get_bins_template
catalogs = self._get_provider_session('vault_lookup_session').get_vaults()
cat_list = []
for cat... | [
"def",
"get_vaults",
"(",
"self",
")",
":",
"# Implemented from kitosid template for -",
"# osid.resource.BinLookupSession.get_bins_template",
"catalogs",
"=",
"self",
".",
"_get_provider_session",
"(",
"'vault_lookup_session'",
")",
".",
"get_vaults",
"(",
")",
"cat_list",
... | 50.222222 | 19.555556 |
def value(self, new_value):
"""Set the value of this measurement.
Raises:
AttributeError: if the new value isn't of the correct units.
"""
if self.unit != units.Undefined and new_value.unit != self.unit:
raise AttributeError("%s must be in %s" % (
... | [
"def",
"value",
"(",
"self",
",",
"new_value",
")",
":",
"if",
"self",
".",
"unit",
"!=",
"units",
".",
"Undefined",
"and",
"new_value",
".",
"unit",
"!=",
"self",
".",
"unit",
":",
"raise",
"AttributeError",
"(",
"\"%s must be in %s\"",
"%",
"(",
"self"... | 37.1 | 16.9 |
def reduce(function, initval=None):
"""
Curried version of the built-in reduce.
>>> reduce(lambda x,y: x+y)( [1, 2, 3, 4, 5] )
15
"""
if initval is None:
return lambda s: __builtin__.reduce(function, s)
else:
return lambda s: __builtin__.reduce(function, s, initval) | [
"def",
"reduce",
"(",
"function",
",",
"initval",
"=",
"None",
")",
":",
"if",
"initval",
"is",
"None",
":",
"return",
"lambda",
"s",
":",
"__builtin__",
".",
"reduce",
"(",
"function",
",",
"s",
")",
"else",
":",
"return",
"lambda",
"s",
":",
"__bui... | 24.454545 | 15.545455 |
def _eval_cell(self, key, code):
"""Evaluates one cell and returns its result"""
# Flatten helper function
def nn(val):
"""Returns flat numpy arraz without None values"""
try:
return numpy.array(filter(None, val.flat))
except AttributeError:
... | [
"def",
"_eval_cell",
"(",
"self",
",",
"key",
",",
"code",
")",
":",
"# Flatten helper function",
"def",
"nn",
"(",
"val",
")",
":",
"\"\"\"Returns flat numpy arraz without None values\"\"\"",
"try",
":",
"return",
"numpy",
".",
"array",
"(",
"filter",
"(",
"Non... | 28.357798 | 20.862385 |
def arrows(self):
"""
Returns a glyph representation of the active vector data as
arrows. Arrows will be located at the points of the mesh and
their size will be dependent on the length of the vector.
Their direction will be the "direction" of the vector
Returns
... | [
"def",
"arrows",
"(",
"self",
")",
":",
"if",
"self",
".",
"active_vectors",
"is",
"None",
":",
"return",
"arrow",
"=",
"vtk",
".",
"vtkArrowSource",
"(",
")",
"arrow",
".",
"Update",
"(",
")",
"alg",
"=",
"vtk",
".",
"vtkGlyph3D",
"(",
")",
"alg",
... | 30.615385 | 16.153846 |
def has_bad_headers(self, default_from=None):
"""Checks for bad headers i.e. newlines in subject, sender or recipients.
"""
sender = self.sender or default_from
reply_to = self.reply_to or ''
for val in [self.subject, sender, reply_to] + self.recipients:
for c in '\r... | [
"def",
"has_bad_headers",
"(",
"self",
",",
"default_from",
"=",
"None",
")",
":",
"sender",
"=",
"self",
".",
"sender",
"or",
"default_from",
"reply_to",
"=",
"self",
".",
"reply_to",
"or",
"''",
"for",
"val",
"in",
"[",
"self",
".",
"subject",
",",
"... | 36 | 12.181818 |
def check_service(self):
"""Check the service exists and is a repository service"""
try:
service = yield Service.get(self.service_id)
except couch.NotFound:
raise exceptions.ValidationError('Service {} not found'
.format(self.s... | [
"def",
"check_service",
"(",
"self",
")",
":",
"try",
":",
"service",
"=",
"yield",
"Service",
".",
"get",
"(",
"self",
".",
"service_id",
")",
"except",
"couch",
".",
"NotFound",
":",
"raise",
"exceptions",
".",
"ValidationError",
"(",
"'Service {} not foun... | 47.266667 | 23.4 |
def value_type(value):
"""Classify `value` of bold, color, and underline keys.
Parameters
----------
value : style value
Returns
-------
str, {"simple", "lookup", "re_lookup", "interval"}
"""
try:
keys = list(value.keys())
except AttributeError:
return "simple"
... | [
"def",
"value_type",
"(",
"value",
")",
":",
"try",
":",
"keys",
"=",
"list",
"(",
"value",
".",
"keys",
"(",
")",
")",
"except",
"AttributeError",
":",
"return",
"\"simple\"",
"if",
"keys",
"in",
"[",
"[",
"\"lookup\"",
"]",
",",
"[",
"\"re_lookup\"",... | 24.833333 | 20.388889 |
def _process_state_embryo(self, job_record):
""" method that takes care of processing job records in STATE_EMBRYO state"""
uow, is_duplicate = self.insert_and_publish_uow(job_record, 0, 0)
try:
target_state = self._compute_next_job_state(job_record)
self.update_job(job_re... | [
"def",
"_process_state_embryo",
"(",
"self",
",",
"job_record",
")",
":",
"uow",
",",
"is_duplicate",
"=",
"self",
".",
"insert_and_publish_uow",
"(",
"job_record",
",",
"0",
",",
"0",
")",
"try",
":",
"target_state",
"=",
"self",
".",
"_compute_next_job_state... | 48.666667 | 18.333333 |
def explain_prediction_xgboost(
xgb, doc,
vec=None,
top=None,
top_targets=None,
target_names=None,
targets=None,
feature_names=None,
feature_re=None, # type: Pattern[str]
feature_filter=None,
vectorized=False, # type: bool
is_regr... | [
"def",
"explain_prediction_xgboost",
"(",
"xgb",
",",
"doc",
",",
"vec",
"=",
"None",
",",
"top",
"=",
"None",
",",
"top_targets",
"=",
"None",
",",
"target_names",
"=",
"None",
",",
"targets",
"=",
"None",
",",
"feature_names",
"=",
"None",
",",
"featur... | 36.837209 | 18.139535 |
def parse(cls, line, encoding=pydle.protocol.DEFAULT_ENCODING):
"""
Parse given line into IRC message structure.
Returns a Message.
"""
valid = True
# Decode message.
try:
message = line.decode(encoding)
except UnicodeDecodeError:
... | [
"def",
"parse",
"(",
"cls",
",",
"line",
",",
"encoding",
"=",
"pydle",
".",
"protocol",
".",
"DEFAULT_ENCODING",
")",
":",
"valid",
"=",
"True",
"# Decode message.",
"try",
":",
"message",
"=",
"line",
".",
"decode",
"(",
"encoding",
")",
"except",
"Uni... | 37.628205 | 20.602564 |
def build_decryption_materials_cache_key(partition, request):
"""Generates a cache key for a decrypt request.
:param bytes partition: Partition name for which to generate key
:param request: Request for which to generate key
:type request: aws_encryption_sdk.materials_managers.DecryptionMaterialsReques... | [
"def",
"build_decryption_materials_cache_key",
"(",
"partition",
",",
"request",
")",
":",
"hasher",
"=",
"_new_cache_key_hasher",
"(",
")",
"_partition_hash",
"=",
"_partition_name_hash",
"(",
"hasher",
"=",
"hasher",
".",
"copy",
"(",
")",
",",
"partition_name",
... | 45.047619 | 23.333333 |
def byaxis_out(self):
"""Object to index along output dimensions.
This is only valid for non-trivial `out_shape`.
Examples
--------
Indexing with integers or slices:
>>> domain = odl.IntervalProd(0, 1)
>>> fspace = odl.FunctionSpace(domain, out_dtype=(float, (2... | [
"def",
"byaxis_out",
"(",
"self",
")",
":",
"space",
"=",
"self",
"class",
"FspaceByaxisOut",
"(",
"object",
")",
":",
"\"\"\"Helper class for indexing by output axes.\"\"\"",
"def",
"__getitem__",
"(",
"self",
",",
"indices",
")",
":",
"\"\"\"Return ``self[indices]``... | 33.047619 | 20.380952 |
def _post_process(self):
"""
There are cases where a loop has two overlapping loop headers thanks
to the way VEX is dealing with continuous instructions. As we were
breaking the connection between the second loop header and its
successor, we shall restore them in our CDG.
... | [
"def",
"_post_process",
"(",
"self",
")",
":",
"# TODO: Verify its correctness",
"loop_back_edges",
"=",
"self",
".",
"_cfg",
".",
"get_loop_back_edges",
"(",
")",
"for",
"b1",
",",
"b2",
"in",
"loop_back_edges",
":",
"self",
".",
"_graph",
".",
"add_edge",
"(... | 44.636364 | 13.545455 |
def set_cache(config_fpath, cache_dir):
"""Write the cache directory to the dtool config file.
:param config_fpath: path to the dtool config file
:param cache_dir: the path to the dtool cache direcotory
"""
cache_dir = os.path.abspath(cache_dir)
return write_config_value_to_file(
CACHE_... | [
"def",
"set_cache",
"(",
"config_fpath",
",",
"cache_dir",
")",
":",
"cache_dir",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"cache_dir",
")",
"return",
"write_config_value_to_file",
"(",
"CACHE_DIRECTORY_KEY",
",",
"cache_dir",
",",
"config_fpath",
")"
] | 30.75 | 14 |
def get_orbital_resolved_cohp(self, label, orbitals):
"""
Get orbital-resolved COHP.
Args:
label: bond label (Lobster: labels as in ICOHPLIST/ICOOPLIST.lobster).
orbitals: The orbitals as a label, or list or tuple of the form
[(n1, orbital1), (n2, orbita... | [
"def",
"get_orbital_resolved_cohp",
"(",
"self",
",",
"label",
",",
"orbitals",
")",
":",
"if",
"self",
".",
"orb_res_cohp",
"is",
"None",
":",
"return",
"None",
"elif",
"isinstance",
"(",
"orbitals",
",",
"list",
")",
"or",
"isinstance",
"(",
"orbitals",
... | 43.255319 | 21.042553 |
def lock(tmp_dir, timeout=NOT_SET, min_wait=None, max_wait=None, verbosity=1):
"""Obtain lock.
Obtain lock access by creating a given temporary directory (whose base
will be created if needed, but will not be deleted after the lock is
removed). If access is refused by the same lock owner during more th... | [
"def",
"lock",
"(",
"tmp_dir",
",",
"timeout",
"=",
"NOT_SET",
",",
"min_wait",
"=",
"None",
",",
"max_wait",
"=",
"None",
",",
"verbosity",
"=",
"1",
")",
":",
"if",
"min_wait",
"is",
"None",
":",
"min_wait",
"=",
"MIN_WAIT",
"if",
"max_wait",
"is",
... | 39.465116 | 19.476744 |
def __dbfRecords(self):
"""Writes the dbf records."""
f = self.__getFileObj(self.dbf)
for record in self.records:
if not self.fields[0][0].startswith("Deletion"):
f.write(b(' ')) # deletion flag
for (fieldName, fieldType, size, dec), value in zip(sel... | [
"def",
"__dbfRecords",
"(",
"self",
")",
":",
"f",
"=",
"self",
".",
"__getFileObj",
"(",
"self",
".",
"dbf",
")",
"for",
"record",
"in",
"self",
".",
"records",
":",
"if",
"not",
"self",
".",
"fields",
"[",
"0",
"]",
"[",
"0",
"]",
".",
"startsw... | 43.444444 | 10.555556 |
def interfaces(self) -> Iterable[ConstantClass]:
"""
A list of direct superinterfaces of this class as indexes into
the constant pool, in left-to-right order.
"""
return [self._constants[idx] for idx in self._interfaces] | [
"def",
"interfaces",
"(",
"self",
")",
"->",
"Iterable",
"[",
"ConstantClass",
"]",
":",
"return",
"[",
"self",
".",
"_constants",
"[",
"idx",
"]",
"for",
"idx",
"in",
"self",
".",
"_interfaces",
"]"
] | 42.5 | 12.166667 |
def make_dataset_models(dataset, schemas_and_tables, metadata_dict = None, version: int = 1, include_contacts=False):
"""make all the models for a dataset
Parameters
----------
dataset: str
name of dataset
table_and_types: list[(schema_name, table_name)]
list of tuples with types an... | [
"def",
"make_dataset_models",
"(",
"dataset",
",",
"schemas_and_tables",
",",
"metadata_dict",
"=",
"None",
",",
"version",
":",
"int",
"=",
"1",
",",
"include_contacts",
"=",
"False",
")",
":",
"if",
"metadata_dict",
"is",
"None",
":",
"metadata_dict",
"=",
... | 40.234043 | 23.276596 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.