text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def _deserialize_property_value(self, to_deserialize: PrimitiveJsonType, deserializer_cls: Type) -> Any:
"""
Deserializes the given value using the given deserializer.
:param to_deserialize: the value to deserialize
:param deserializer_cls: the type of deserializer to use
:return... | [
"def",
"_deserialize_property_value",
"(",
"self",
",",
"to_deserialize",
":",
"PrimitiveJsonType",
",",
"deserializer_cls",
":",
"Type",
")",
"->",
"Any",
":",
"deserializer",
"=",
"self",
".",
"_create_deserializer_of_type_with_cache",
"(",
"deserializer_cls",
")",
... | 52.5 | 19.5 |
def write_ctl(name, imap, guidetree, nloci,
infer_sptree, infer_delimit, delimit_alg,
seed, burnin, nsample, sampfreq,
thetaprior, tauprior, traits_df, nu0, kappa0,
cleandata, useseqdata, usetraitdata, wdir,
finetune, verbose):
""" write outfile... | [
"def",
"write_ctl",
"(",
"name",
",",
"imap",
",",
"guidetree",
",",
"nloci",
",",
"infer_sptree",
",",
"infer_delimit",
",",
"delimit_alg",
",",
"seed",
",",
"burnin",
",",
"nsample",
",",
"sampfreq",
",",
"thetaprior",
",",
"tauprior",
",",
"traits_df",
... | 38.513889 | 20.152778 |
def open_relative(self, url, *args, **kwargs):
"""Like :func:`open`, but ``url`` can be relative to the currently
visited page.
"""
return self.open(self.absolute_url(url), *args, **kwargs) | [
"def",
"open_relative",
"(",
"self",
",",
"url",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"open",
"(",
"self",
".",
"absolute_url",
"(",
"url",
")",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | 43.4 | 10 |
def checkAndCreate(self, key, payload):
""" Function checkAndCreate
Check if an object exists and create it if not
@param key: The targeted object
@param payload: The targeted object description
@return RETURN: The id of the object
"""
if key not in self:
... | [
"def",
"checkAndCreate",
"(",
"self",
",",
"key",
",",
"payload",
")",
":",
"if",
"key",
"not",
"in",
"self",
":",
"self",
"[",
"key",
"]",
"=",
"payload",
"return",
"self",
"[",
"key",
"]",
"[",
"'id'",
"]"
] | 33.181818 | 9.727273 |
def _map_arg_names(source, mapping):
"""Map one set of keys to another."""
return {cartopy_name: source[cf_name] for cartopy_name, cf_name in mapping
if cf_name in source} | [
"def",
"_map_arg_names",
"(",
"source",
",",
"mapping",
")",
":",
"return",
"{",
"cartopy_name",
":",
"source",
"[",
"cf_name",
"]",
"for",
"cartopy_name",
",",
"cf_name",
"in",
"mapping",
"if",
"cf_name",
"in",
"source",
"}"
] | 50 | 12.25 |
def per_month(start: datetime, end: datetime, n: int=1):
"""
Iterates over time range in one month steps.
Clamps to number of days in given month.
:param start: Start of time range (inclusive)
:param end: End of time range (exclusive)
:param n: Number of months to step. Default is 1.
:retu... | [
"def",
"per_month",
"(",
"start",
":",
"datetime",
",",
"end",
":",
"datetime",
",",
"n",
":",
"int",
"=",
"1",
")",
":",
"curr",
"=",
"start",
".",
"replace",
"(",
"day",
"=",
"1",
",",
"hour",
"=",
"0",
",",
"minute",
"=",
"0",
",",
"second",... | 36.125 | 16.625 |
def get_content_type(self, msg, content_type="HTML"):
"""
Given an Email.Message object, gets the content-type payload
as specified by @content_type. This is the actual body of the
email.
@Params
msg - Email.Message object to get message content for
content_type -... | [
"def",
"get_content_type",
"(",
"self",
",",
"msg",
",",
"content_type",
"=",
"\"HTML\"",
")",
":",
"if",
"\"HTML\"",
"in",
"content_type",
".",
"upper",
"(",
")",
":",
"content_type",
"=",
"self",
".",
"HTML",
"elif",
"\"PLAIN\"",
"in",
"content_type",
".... | 38.842105 | 15.789474 |
def is_cupy_array(arr):
"""Check whether an array is a cupy array"""
if cupy is None:
return False
elif isinstance(arr, cupy.ndarray):
return True
else:
return False | [
"def",
"is_cupy_array",
"(",
"arr",
")",
":",
"if",
"cupy",
"is",
"None",
":",
"return",
"False",
"elif",
"isinstance",
"(",
"arr",
",",
"cupy",
".",
"ndarray",
")",
":",
"return",
"True",
"else",
":",
"return",
"False"
] | 24.75 | 16.25 |
def gp_background():
""" plot background methods and S/B vs energy """
inDir, outDir = getWorkDirs()
data, REBIN = OrderedDict(), None
titles = [ 'SE_{+-}', 'SE@^{corr}_{/Symbol \\261\\261}', 'ME@^{N}_{+-}' ]
Apm = OrderedDict([
('19', 0.026668), ('27', 0.026554), ('39', 0.026816), ('62', 0.... | [
"def",
"gp_background",
"(",
")",
":",
"inDir",
",",
"outDir",
"=",
"getWorkDirs",
"(",
")",
"data",
",",
"REBIN",
"=",
"OrderedDict",
"(",
")",
",",
"None",
"titles",
"=",
"[",
"'SE_{+-}'",
",",
"'SE@^{corr}_{/Symbol \\\\261\\\\261}'",
",",
"'ME@^{N}_{+-}'",
... | 45.5625 | 19.010417 |
def interpolate(x, scale=None, output_size=None, mode='linear', align_corners=None):
'''
Resize an ND array with interpolation.
Scaling factors for spatial dimensions are determined by either
``scale`` or ``output_size``.
``nd = len(scale)`` or ``nd = len(output_size)`` determines the number of
... | [
"def",
"interpolate",
"(",
"x",
",",
"scale",
"=",
"None",
",",
"output_size",
"=",
"None",
",",
"mode",
"=",
"'linear'",
",",
"align_corners",
"=",
"None",
")",
":",
"from",
".",
"function_bases",
"import",
"interpolate",
"as",
"interpolate_base",
"import",... | 37.816901 | 23.56338 |
def save_grid_data(self):
"""
Save grid data in the data object
"""
if not self.grid.changes:
print('-I- No changes to save')
return
if self.grid_type == 'age':
age_data_type = self.er_magic.age_type
self.er_magic.write_ages = True... | [
"def",
"save_grid_data",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"grid",
".",
"changes",
":",
"print",
"(",
"'-I- No changes to save'",
")",
"return",
"if",
"self",
".",
"grid_type",
"==",
"'age'",
":",
"age_data_type",
"=",
"self",
".",
"er_magic... | 53.171171 | 28.522523 |
def list_virtual_machine_scale_set_vm_network_interfaces(scale_set,
vm_index,
resource_group,
**kwargs):
'''
.. versionadded:: 2019.2.0
... | [
"def",
"list_virtual_machine_scale_set_vm_network_interfaces",
"(",
"scale_set",
",",
"vm_index",
",",
"resource_group",
",",
"*",
"*",
"kwargs",
")",
":",
"result",
"=",
"{",
"}",
"netconn",
"=",
"__utils__",
"[",
"'azurearm.get_client'",
"]",
"(",
"'network'",
"... | 33.853659 | 28.487805 |
def _submit_metrics(self, metrics, metric_name_and_type_by_property):
"""
Resolve metric names and types and submit it.
"""
for metric in metrics:
if (
metric.name not in metric_name_and_type_by_property
and metric.name.lower() not in metric_na... | [
"def",
"_submit_metrics",
"(",
"self",
",",
"metrics",
",",
"metric_name_and_type_by_property",
")",
":",
"for",
"metric",
"in",
"metrics",
":",
"if",
"(",
"metric",
".",
"name",
"not",
"in",
"metric_name_and_type_by_property",
"and",
"metric",
".",
"name",
".",... | 44.653846 | 27.269231 |
def predict_features(self, df_features, df_target, idx=0, **kwargs):
"""For one variable, predict its neighbouring nodes.
Args:
df_features (pandas.DataFrame):
df_target (pandas.Series):
idx (int): (optional) for printing purposes
kwargs (dict): additiona... | [
"def",
"predict_features",
"(",
"self",
",",
"df_features",
",",
"df_target",
",",
"idx",
"=",
"0",
",",
"*",
"*",
"kwargs",
")",
":",
"X",
"=",
"df_features",
".",
"values",
"y",
"=",
"df_target",
".",
"values",
"[",
":",
",",
"0",
"]",
"rr",
"=",... | 31.833333 | 17.777778 |
def validate_spec(cls, spec, backends=None):
"""
Given a specification, validated it against the options tree for
the specified backends by raising OptionError for invalid
options. If backends is None, validates against all the
currently loaded backend.
Only useful when ... | [
"def",
"validate_spec",
"(",
"cls",
",",
"spec",
",",
"backends",
"=",
"None",
")",
":",
"loaded_backends",
"=",
"Store",
".",
"loaded_backends",
"(",
")",
"if",
"backends",
"is",
"None",
"else",
"backends",
"error_info",
"=",
"{",
"}",
"backend_errors",
"... | 47.833333 | 21.722222 |
def explode():
'''
This method **assumes** that :func:`~exhale.configs.apply_sphinx_configurations` has
already been applied. It performs minimal sanity checking, and then performs in
order
1. Creates a :class:`~exhale.graph.ExhaleRoot` object.
2. Executes :func:`~exhale.graph.ExhaleRoot.parse... | [
"def",
"explode",
"(",
")",
":",
"# Quick sanity check to make sure the bare minimum have been set in the configs",
"err_msg",
"=",
"\"`configs.{config}` was `None`. Do not call `deploy.explode` directly.\"",
"if",
"configs",
".",
"containmentFolder",
"is",
"None",
":",
"raise",
"... | 39.15493 | 26.760563 |
def _report_container_state_metrics(self, pod_list, instance_tags):
"""Reports container state & reasons by looking at container statuses"""
if pod_list.get('expired_count'):
self.gauge(self.NAMESPACE + '.pods.expired', pod_list.get('expired_count'), tags=instance_tags)
for pod in p... | [
"def",
"_report_container_state_metrics",
"(",
"self",
",",
"pod_list",
",",
"instance_tags",
")",
":",
"if",
"pod_list",
".",
"get",
"(",
"'expired_count'",
")",
":",
"self",
".",
"gauge",
"(",
"self",
".",
"NAMESPACE",
"+",
"'.pods.expired'",
",",
"pod_list"... | 47.28125 | 28.71875 |
def get_object_header(self, ref):
""" Use this method to quickly examine the type and size of the object behind
the given ref.
:note: The method will only suffer from the costs of command invocation
once and reuses the command in subsequent calls.
:return: (hexsha, type_string, size_as_int)"""
cm... | [
"def",
"get_object_header",
"(",
"self",
",",
"ref",
")",
":",
"cmd",
"=",
"self",
".",
"__get_persistent_cmd",
"(",
"\"cat_file_header\"",
",",
"\"cat_file\"",
",",
"batch_check",
"=",
"True",
")",
"return",
"self",
".",
"__get_object_header",
"(",
"cmd",
","... | 43.3 | 19.7 |
def crypto_sign_ed25519ph_final_verify(edph,
signature,
pk):
"""
Verify a prehashed signature using the public key pk
:param edph: the ed25519ph state for the data
being verified
:type edph: crypto_sign_ed255... | [
"def",
"crypto_sign_ed25519ph_final_verify",
"(",
"edph",
",",
"signature",
",",
"pk",
")",
":",
"ensure",
"(",
"isinstance",
"(",
"edph",
",",
"crypto_sign_ed25519ph_state",
")",
",",
"'edph parameter must be a ed25519ph_state object'",
",",
"raising",
"=",
"exc",
".... | 39.658537 | 13.170732 |
def parse_itms_services(url_data):
"""Get "url" CGI parameter value as child URL."""
query = url_data.urlparts[3]
for k, v, sep in urlutil.parse_qsl(query, keep_blank_values=True):
if k == "url":
url_data.add_url(v)
break | [
"def",
"parse_itms_services",
"(",
"url_data",
")",
":",
"query",
"=",
"url_data",
".",
"urlparts",
"[",
"3",
"]",
"for",
"k",
",",
"v",
",",
"sep",
"in",
"urlutil",
".",
"parse_qsl",
"(",
"query",
",",
"keep_blank_values",
"=",
"True",
")",
":",
"if",... | 37 | 13.428571 |
def cross(vec1, vec2):
"""Returns the cross product of two Vectors"""
if isinstance(vec1, Vector3) and isinstance(vec2, Vector3):
vec3 = Vector3()
vec3.x = (vec1.y * vec2.z) - (vec1.z * vec2.y)
vec3.y = (vec1.z * vec2.x) - (vec1.x * vec2.z)
vec3.z = (vec1.... | [
"def",
"cross",
"(",
"vec1",
",",
"vec2",
")",
":",
"if",
"isinstance",
"(",
"vec1",
",",
"Vector3",
")",
"and",
"isinstance",
"(",
"vec2",
",",
"Vector3",
")",
":",
"vec3",
"=",
"Vector3",
"(",
")",
"vec3",
".",
"x",
"=",
"(",
"vec1",
".",
"y",
... | 44.3 | 17.7 |
def set_count_auto(self, count=None):
"""Sets workers count.
By default sets it to detected number of available cores
:param int count:
"""
count = count or self._section.vars.CPU_CORES
self._set('workers', count)
return self._section | [
"def",
"set_count_auto",
"(",
"self",
",",
"count",
"=",
"None",
")",
":",
"count",
"=",
"count",
"or",
"self",
".",
"_section",
".",
"vars",
".",
"CPU_CORES",
"self",
".",
"_set",
"(",
"'workers'",
",",
"count",
")",
"return",
"self",
".",
"_section"
... | 23.583333 | 19.333333 |
def inline(self) -> str:
"""
Return an inline string of the Identity
:return:
"""
return "{pubkey}:{signature}:{timestamp}:{uid}".format(
pubkey=self.pubkey,
signature=self.signatures[0],
timestamp=self.timestamp,
uid=self.uid) | [
"def",
"inline",
"(",
"self",
")",
"->",
"str",
":",
"return",
"\"{pubkey}:{signature}:{timestamp}:{uid}\"",
".",
"format",
"(",
"pubkey",
"=",
"self",
".",
"pubkey",
",",
"signature",
"=",
"self",
".",
"signatures",
"[",
"0",
"]",
",",
"timestamp",
"=",
"... | 30.6 | 9.8 |
def get_field_info(self, field):
"""
This method is basically a mirror from rest_framework==3.3.3
We are currently pinned to rest_framework==3.1.1. If we upgrade,
this can be refactored and simplified to rely more heavily on
rest_framework's built in logic.
"""
... | [
"def",
"get_field_info",
"(",
"self",
",",
"field",
")",
":",
"field_info",
"=",
"self",
".",
"get_attributes",
"(",
"field",
")",
"field_info",
"[",
"\"required\"",
"]",
"=",
"getattr",
"(",
"field",
",",
"\"required\"",
",",
"False",
")",
"field_info",
"... | 38.931034 | 21.551724 |
def separation_in_list(separation_indices, separation_indices_list):
"""
Checks if the separation indices of a plane are already in the list
:param separation_indices: list of separation indices (three arrays of integers)
:param separation_indices_list: list of the list of separation indices to be compa... | [
"def",
"separation_in_list",
"(",
"separation_indices",
",",
"separation_indices_list",
")",
":",
"sorted_separation",
"=",
"sort_separation",
"(",
"separation_indices",
")",
"for",
"sep",
"in",
"separation_indices_list",
":",
"if",
"len",
"(",
"sep",
"[",
"1",
"]",... | 54 | 26.5 |
def tvdb_login(api_key):
""" Logs into TVDb using the provided api key
Note: You can register for a free TVDb key at thetvdb.com/?tab=apiregister
Online docs: api.thetvdb.com/swagger#!/Authentication/post_login=
"""
url = "https://api.thetvdb.com/login"
body = {"apikey": api_key}
status, co... | [
"def",
"tvdb_login",
"(",
"api_key",
")",
":",
"url",
"=",
"\"https://api.thetvdb.com/login\"",
"body",
"=",
"{",
"\"apikey\"",
":",
"api_key",
"}",
"status",
",",
"content",
"=",
"_request_json",
"(",
"url",
",",
"body",
"=",
"body",
",",
"cache",
"=",
"F... | 41.285714 | 17 |
def add(self, item, group_by=None):
"""General purpose class to group items by certain criteria."""
key = None
if not group_by:
group_by = self.group_by
if group_by:
# if group_by is a function, use it with item as argument
if hasattr(group_by, '__ca... | [
"def",
"add",
"(",
"self",
",",
"item",
",",
"group_by",
"=",
"None",
")",
":",
"key",
"=",
"None",
"if",
"not",
"group_by",
":",
"group_by",
"=",
"self",
".",
"group_by",
"if",
"group_by",
":",
"# if group_by is a function, use it with item as argument",
"if"... | 36.357143 | 18.821429 |
def gc_content_plot (self):
""" Create the HTML for the FastQC GC content plot """
data = dict()
data_norm = dict()
for s_name in self.fastqc_data:
try:
data[s_name] = {d['gc_content']: d['count'] for d in self.fastqc_data[s_name]['per_sequence_gc_content']}
... | [
"def",
"gc_content_plot",
"(",
"self",
")",
":",
"data",
"=",
"dict",
"(",
")",
"data_norm",
"=",
"dict",
"(",
")",
"for",
"s_name",
"in",
"self",
".",
"fastqc_data",
":",
"try",
":",
"data",
"[",
"s_name",
"]",
"=",
"{",
"d",
"[",
"'gc_content'",
... | 48.298246 | 24.245614 |
async def getArtifact(self, *args, **kwargs):
"""
Get Artifact from Run
Get artifact by `<name>` from a specific run.
**Public Artifacts**, in-order to get an artifact you need the scope
`queue:get-artifact:<name>`, where `<name>` is the name of the artifact.
But if the... | [
"async",
"def",
"getArtifact",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"await",
"self",
".",
"_makeApiCall",
"(",
"self",
".",
"funcinfo",
"[",
"\"getArtifact\"",
"]",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"... | 58.321839 | 34.896552 |
def _list_resource_descriptors(args, _):
"""Lists the resource descriptors in the project."""
project_id = args['project']
pattern = args['type'] or '*'
descriptors = gcm.ResourceDescriptors(project_id=project_id)
dataframe = descriptors.as_dataframe(pattern=pattern)
return _render_dataframe(dataframe) | [
"def",
"_list_resource_descriptors",
"(",
"args",
",",
"_",
")",
":",
"project_id",
"=",
"args",
"[",
"'project'",
"]",
"pattern",
"=",
"args",
"[",
"'type'",
"]",
"or",
"'*'",
"descriptors",
"=",
"gcm",
".",
"ResourceDescriptors",
"(",
"project_id",
"=",
... | 44.142857 | 8.428571 |
def _reindex_multi(self, axes, copy, fill_value):
"""
We are guaranteed non-Nones in the axes.
"""
new_index, row_indexer = self.index.reindex(axes['index'])
new_columns, col_indexer = self.columns.reindex(axes['columns'])
if row_indexer is not None and col_indexer is n... | [
"def",
"_reindex_multi",
"(",
"self",
",",
"axes",
",",
"copy",
",",
"fill_value",
")",
":",
"new_index",
",",
"row_indexer",
"=",
"self",
".",
"index",
".",
"reindex",
"(",
"axes",
"[",
"'index'",
"]",
")",
"new_columns",
",",
"col_indexer",
"=",
"self"... | 48.684211 | 23 |
def cmd_kill(opts):
"""Kill some or all containers
"""
kill_signal = opts.signal if hasattr(opts, 'signal') else "SIGKILL"
__with_containers(opts, Blockade.kill, signal=kill_signal) | [
"def",
"cmd_kill",
"(",
"opts",
")",
":",
"kill_signal",
"=",
"opts",
".",
"signal",
"if",
"hasattr",
"(",
"opts",
",",
"'signal'",
")",
"else",
"\"SIGKILL\"",
"__with_containers",
"(",
"opts",
",",
"Blockade",
".",
"kill",
",",
"signal",
"=",
"kill_signal... | 38.6 | 14.8 |
def install(self): # pragma: no cover
"""Install/download ssh keys from LDAP for consumption by SSH."""
keys = self.get_keys_from_ldap()
for user, ssh_keys in keys.items():
user_dir = API.__authorized_keys_path(user)
if not os.path.isdir(user_dir):
os.mak... | [
"def",
"install",
"(",
"self",
")",
":",
"# pragma: no cover",
"keys",
"=",
"self",
".",
"get_keys_from_ldap",
"(",
")",
"for",
"user",
",",
"ssh_keys",
"in",
"keys",
".",
"items",
"(",
")",
":",
"user_dir",
"=",
"API",
".",
"__authorized_keys_path",
"(",
... | 53.7 | 11.4 |
def srcmdl_xml(self, **kwargs):
""" return the file name for source model xml files
"""
kwargs_copy = self.base_dict.copy()
kwargs_copy.update(**kwargs)
localpath = NameFactory.srcmdl_xml_format.format(**kwargs_copy)
if kwargs.get('fullpath', False):
return se... | [
"def",
"srcmdl_xml",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs_copy",
"=",
"self",
".",
"base_dict",
".",
"copy",
"(",
")",
"kwargs_copy",
".",
"update",
"(",
"*",
"*",
"kwargs",
")",
"localpath",
"=",
"NameFactory",
".",
"srcmdl_xml_format... | 41 | 8.555556 |
def list_lbaas_members(self, lbaas_pool, retrieve_all=True, **_params):
"""Fetches a list of all lbaas_members for a project."""
return self.list('members', self.lbaas_members_path % lbaas_pool,
retrieve_all, **_params) | [
"def",
"list_lbaas_members",
"(",
"self",
",",
"lbaas_pool",
",",
"retrieve_all",
"=",
"True",
",",
"*",
"*",
"_params",
")",
":",
"return",
"self",
".",
"list",
"(",
"'members'",
",",
"self",
".",
"lbaas_members_path",
"%",
"lbaas_pool",
",",
"retrieve_all"... | 64.25 | 18.25 |
def _move_stream_token(coordinator, token):
"""Move to the Stream position described by the token.
The following rules are applied when interpolation is required:
- If a shard does not exist (past the trim_horizon) it is ignored. If that
shard had children, its children are also checked against the ... | [
"def",
"_move_stream_token",
"(",
"coordinator",
",",
"token",
")",
":",
"stream_arn",
"=",
"coordinator",
".",
"stream_arn",
"=",
"token",
"[",
"\"stream_arn\"",
"]",
"# 0) Everything will be rebuilt from the DescribeStream masked by the token.",
"coordinator",
".",
"roots... | 55.618182 | 28.872727 |
def dt_dt(sdat, tstart=None, tend=None):
"""Derivative of temperature.
Compute dT/dt as a function of time using an explicit Euler scheme.
Args:
sdat (:class:`~stagpy.stagyydata.StagyyData`): a StagyyData instance.
tstart (float): time at which the computation should start. Use the
... | [
"def",
"dt_dt",
"(",
"sdat",
",",
"tstart",
"=",
"None",
",",
"tend",
"=",
"None",
")",
":",
"tseries",
"=",
"sdat",
".",
"tseries_between",
"(",
"tstart",
",",
"tend",
")",
"time",
"=",
"tseries",
"[",
"'t'",
"]",
".",
"values",
"temp",
"=",
"tser... | 39.75 | 21.15 |
def vertex_to_face_color(vertex_colors, faces):
"""
Convert a list of vertex colors to face colors.
Parameters
----------
vertex_colors: (n,(3,4)), colors
faces: (m,3) int, face indexes
Returns
-----------
face_colors: (m,4) colors
"""
vertex_colors = to_rgba(verte... | [
"def",
"vertex_to_face_color",
"(",
"vertex_colors",
",",
"faces",
")",
":",
"vertex_colors",
"=",
"to_rgba",
"(",
"vertex_colors",
")",
"face_colors",
"=",
"vertex_colors",
"[",
"faces",
"]",
".",
"mean",
"(",
"axis",
"=",
"1",
")",
"return",
"face_colors",
... | 25.375 | 14.625 |
def _create_dict_with_nested_keys_and_val(cls, keys, value):
"""Recursively constructs a nested dictionary with the keys pointing to the value.
For example:
Given the list of keys ['a', 'b', 'c', 'd'] and a primitive
value 'hello world', the method will produce the nested dictionary
{'a': {'b': {'c... | [
"def",
"_create_dict_with_nested_keys_and_val",
"(",
"cls",
",",
"keys",
",",
"value",
")",
":",
"if",
"len",
"(",
"keys",
")",
">",
"1",
":",
"new_keys",
"=",
"keys",
"[",
":",
"-",
"1",
"]",
"new_val",
"=",
"{",
"keys",
"[",
"-",
"1",
"]",
":",
... | 43.782609 | 24.26087 |
def gif(self, gif_id, strict=False):
"""
Retrieves a specifc gif from giphy based on unique id
:param gif_id: Unique giphy gif ID
:type gif_id: string
:param strict: Whether an exception should be raised when no results
:type strict: boolean
"""
resp = se... | [
"def",
"gif",
"(",
"self",
",",
"gif_id",
",",
"strict",
"=",
"False",
")",
":",
"resp",
"=",
"self",
".",
"_fetch",
"(",
"gif_id",
")",
"if",
"resp",
"[",
"'data'",
"]",
":",
"return",
"GiphyImage",
"(",
"resp",
"[",
"'data'",
"]",
")",
"elif",
... | 33.0625 | 13.9375 |
async def get_files_to_delete(self) -> List[str]:
"""
Determine the files to delete when rolling over.
"""
dir_name, base_name = os.path.split(self.absolute_file_path)
file_names = await self.loop.run_in_executor(
None, lambda: os.listdir(dir_name)
)
r... | [
"async",
"def",
"get_files_to_delete",
"(",
"self",
")",
"->",
"List",
"[",
"str",
"]",
":",
"dir_name",
",",
"base_name",
"=",
"os",
".",
"path",
".",
"split",
"(",
"self",
".",
"absolute_file_path",
")",
"file_names",
"=",
"await",
"self",
".",
"loop",... | 37.6 | 12.9 |
def is_read_only(cls,
db: DATABASE_SUPPORTER_FWD_REF,
logger: logging.Logger = None) -> bool:
"""Do we have read-only access?"""
def convert_enums(row_):
# All these columns are of type enum('N', 'Y');
# https://dev.mysql.com/doc/refman/... | [
"def",
"is_read_only",
"(",
"cls",
",",
"db",
":",
"DATABASE_SUPPORTER_FWD_REF",
",",
"logger",
":",
"logging",
".",
"Logger",
"=",
"None",
")",
"->",
"bool",
":",
"def",
"convert_enums",
"(",
"row_",
")",
":",
"# All these columns are of type enum('N', 'Y');",
... | 41.060241 | 15.084337 |
def read_text(self, file_handle):
"""Parse the TEXT segment of the FCS file.
The TEXT segment contains meta data associated with the FCS file.
Converting all meta keywords to lower case.
"""
header = self.annotation['__header__'] # For convenience
#####
# Read ... | [
"def",
"read_text",
"(",
"self",
",",
"file_handle",
")",
":",
"header",
"=",
"self",
".",
"annotation",
"[",
"'__header__'",
"]",
"# For convenience",
"#####",
"# Read in the TEXT segment of the FCS file",
"# There are some differences in how the",
"file_handle",
".",
"s... | 39.529412 | 24.985294 |
def getStore(self, name, domain):
"""Convenience method for the REPL. I got tired of typing this string every time I logged in."""
return IRealm(self.original.store.parent).accountByAddress(name, domain).avatars.open() | [
"def",
"getStore",
"(",
"self",
",",
"name",
",",
"domain",
")",
":",
"return",
"IRealm",
"(",
"self",
".",
"original",
".",
"store",
".",
"parent",
")",
".",
"accountByAddress",
"(",
"name",
",",
"domain",
")",
".",
"avatars",
".",
"open",
"(",
")"
... | 77.333333 | 20.666667 |
def local_targets(self):
"""Iterator over the targets defined in this build file."""
for node in self.node:
if (node.repo, node.path) == (self.target.repo, self.target.path):
yield node | [
"def",
"local_targets",
"(",
"self",
")",
":",
"for",
"node",
"in",
"self",
".",
"node",
":",
"if",
"(",
"node",
".",
"repo",
",",
"node",
".",
"path",
")",
"==",
"(",
"self",
".",
"target",
".",
"repo",
",",
"self",
".",
"target",
".",
"path",
... | 45 | 15.6 |
def referenced(word, article=INDEFINITE, gender=MALE, role=SUBJECT):
""" Returns a string with the article + the word.
"""
return "%s %s" % (_article(word, article, gender, role), word) | [
"def",
"referenced",
"(",
"word",
",",
"article",
"=",
"INDEFINITE",
",",
"gender",
"=",
"MALE",
",",
"role",
"=",
"SUBJECT",
")",
":",
"return",
"\"%s %s\"",
"%",
"(",
"_article",
"(",
"word",
",",
"article",
",",
"gender",
",",
"role",
")",
",",
"w... | 48.5 | 13.5 |
def extend_from_instances(self,
params: Params,
instances: Iterable['adi.Instance'] = ()) -> None:
"""
Extends an already generated vocabulary using a collection of instances.
"""
min_count = params.pop("min_count", None)
... | [
"def",
"extend_from_instances",
"(",
"self",
",",
"params",
":",
"Params",
",",
"instances",
":",
"Iterable",
"[",
"'adi.Instance'",
"]",
"=",
"(",
")",
")",
"->",
"None",
":",
"min_count",
"=",
"params",
".",
"pop",
"(",
"\"min_count\"",
",",
"None",
")... | 56.962963 | 22.740741 |
def parse_data(self, sline):
"""This function builds the addRawResults dictionary using the header values of the labels section
as sample Ids.
"""
if sline[0] == '':
return 0
for idx, label in enumerate(self._labels_values[sline[0]]):
if label != '':
... | [
"def",
"parse_data",
"(",
"self",
",",
"sline",
")",
":",
"if",
"sline",
"[",
"0",
"]",
"==",
"''",
":",
"return",
"0",
"for",
"idx",
",",
"label",
"in",
"enumerate",
"(",
"self",
".",
"_labels_values",
"[",
"sline",
"[",
"0",
"]",
"]",
")",
":",... | 42.1 | 18.6 |
def add_schema(self, database, schema):
"""Add a schema to the set of known schemas (case-insensitive)
:param str database: The database name to add.
:param str schema: The schema name to add.
"""
self.schemas.add((_lower(database), _lower(schema))) | [
"def",
"add_schema",
"(",
"self",
",",
"database",
",",
"schema",
")",
":",
"self",
".",
"schemas",
".",
"add",
"(",
"(",
"_lower",
"(",
"database",
")",
",",
"_lower",
"(",
"schema",
")",
")",
")"
] | 40.571429 | 12.142857 |
def get_contact(self, contact_id):
"""
Get single contact
"""
url = self.CONTACTS_ID_URL % contact_id
connection = Connection(self.token)
connection.set_url(self.production, url)
return connection.get_request() | [
"def",
"get_contact",
"(",
"self",
",",
"contact_id",
")",
":",
"url",
"=",
"self",
".",
"CONTACTS_ID_URL",
"%",
"contact_id",
"connection",
"=",
"Connection",
"(",
"self",
".",
"token",
")",
"connection",
".",
"set_url",
"(",
"self",
".",
"production",
",... | 25.9 | 11.9 |
def plot_ARD(kernel, filtering=None, legend=False, canvas=None, **kwargs):
"""
If an ARD kernel is present, plot a bar representation using matplotlib
:param fignum: figure number of the plot
:param filtering: list of names, which to use for plotting ARD parameters.
Only kernels w... | [
"def",
"plot_ARD",
"(",
"kernel",
",",
"filtering",
"=",
"None",
",",
"legend",
"=",
"False",
",",
"canvas",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"Tango",
".",
"reset",
"(",
")",
"ard_params",
"=",
"np",
".",
"atleast_2d",
"(",
"kernel",
... | 35.346939 | 24.571429 |
def to_unicode(string):
"""
Ensure a passed string is unicode
"""
if isinstance(string, six.binary_type):
return string.decode('utf8')
if isinstance(string, six.text_type):
return string
if six.PY2:
return unicode(string)
return str(string) | [
"def",
"to_unicode",
"(",
"string",
")",
":",
"if",
"isinstance",
"(",
"string",
",",
"six",
".",
"binary_type",
")",
":",
"return",
"string",
".",
"decode",
"(",
"'utf8'",
")",
"if",
"isinstance",
"(",
"string",
",",
"six",
".",
"text_type",
")",
":",... | 25.636364 | 9.090909 |
def value_to_string(self, obj):
"""This descriptor acts as a Field, as far as the serializer is concerned."""
try:
return force_unicode(self.__get__(obj))
except TypeError:
return str(self.__get__(obj)) | [
"def",
"value_to_string",
"(",
"self",
",",
"obj",
")",
":",
"try",
":",
"return",
"force_unicode",
"(",
"self",
".",
"__get__",
"(",
"obj",
")",
")",
"except",
"TypeError",
":",
"return",
"str",
"(",
"self",
".",
"__get__",
"(",
"obj",
")",
")"
] | 40.833333 | 10.666667 |
def suspend(self):
"""
Suspends this router.
"""
status = yield from self.get_status()
if status == "running":
yield from self._hypervisor.send('vm suspend "{name}"'.format(name=self._name))
self.status = "suspended"
log.info('Router "{name}" ... | [
"def",
"suspend",
"(",
"self",
")",
":",
"status",
"=",
"yield",
"from",
"self",
".",
"get_status",
"(",
")",
"if",
"status",
"==",
"\"running\"",
":",
"yield",
"from",
"self",
".",
"_hypervisor",
".",
"send",
"(",
"'vm suspend \"{name}\"'",
".",
"format",... | 37.5 | 20.3 |
def parse_bookmark_json (data):
"""Parse complete JSON data for Chromium Bookmarks."""
for entry in data["roots"].values():
for url, name in parse_bookmark_node(entry):
yield url, name | [
"def",
"parse_bookmark_json",
"(",
"data",
")",
":",
"for",
"entry",
"in",
"data",
"[",
"\"roots\"",
"]",
".",
"values",
"(",
")",
":",
"for",
"url",
",",
"name",
"in",
"parse_bookmark_node",
"(",
"entry",
")",
":",
"yield",
"url",
",",
"name"
] | 41.6 | 6.8 |
def init_config(self, app):
"""Initialize configuration.
:param app: An instance of :class:`~flask.Flask`.
"""
_vars = ['BASE_TEMPLATE', 'COVER_TEMPLATE', 'SETTINGS_TEMPLATE']
# Sets RequireJS config and SASS binary as well if not already set.
for k in dir(config):
... | [
"def",
"init_config",
"(",
"self",
",",
"app",
")",
":",
"_vars",
"=",
"[",
"'BASE_TEMPLATE'",
",",
"'COVER_TEMPLATE'",
",",
"'SETTINGS_TEMPLATE'",
"]",
"# Sets RequireJS config and SASS binary as well if not already set.",
"for",
"k",
"in",
"dir",
"(",
"config",
")",... | 38.909091 | 20.681818 |
def pivot(self, speed, durationS=-1.0):
"""
pivot() controls the pivot speed of the RedBot. The values of the pivot function inputs
range from -255:255, with -255 indicating a full speed counter-clockwise rotation.
255 indicates a full speed clockwise rotation
"""
... | [
"def",
"pivot",
"(",
"self",
",",
"speed",
",",
"durationS",
"=",
"-",
"1.0",
")",
":",
"if",
"speed",
"<",
"0",
":",
"self",
".",
"left_fwd",
"(",
"min",
"(",
"abs",
"(",
"speed",
")",
",",
"255",
")",
")",
"self",
".",
"right_rev",
"(",
"min"... | 41 | 15.375 |
def apply_handler_to_root_log(handler: logging.Handler,
remove_existing: bool = False) -> None:
"""
Applies a handler to all logs, optionally removing existing handlers.
Should ONLY be called from the ``if __name__ == 'main'`` script;
see https://docs.python.org/3.4/howto/... | [
"def",
"apply_handler_to_root_log",
"(",
"handler",
":",
"logging",
".",
"Handler",
",",
"remove_existing",
":",
"bool",
"=",
"False",
")",
"->",
"None",
":",
"rootlog",
"=",
"logging",
".",
"getLogger",
"(",
")",
"if",
"remove_existing",
":",
"rootlog",
"."... | 36.111111 | 21.777778 |
def trace_buffer_capacity(self):
"""Retrieves the trace buffer's current capacity.
Args:
self (JLink): the ``JLink`` instance.
Returns:
The current capacity of the trace buffer. This is not necessarily
the maximum possible size the buffer could be configured with... | [
"def",
"trace_buffer_capacity",
"(",
"self",
")",
":",
"cmd",
"=",
"enums",
".",
"JLinkTraceCommand",
".",
"GET_CONF_CAPACITY",
"data",
"=",
"ctypes",
".",
"c_uint32",
"(",
"0",
")",
"res",
"=",
"self",
".",
"_dll",
".",
"JLINKARM_TRACE_Control",
"(",
"cmd",... | 37.8125 | 20.9375 |
def _conf(cls, opts):
"""Setup logging via ini-file from logging_conf_file option."""
if not opts.logging_conf_file:
return False
if not os.path.exists(opts.logging_conf_file):
# FileNotFoundError added only in Python 3.3
# https://docs.python.org/3/whatsnew/... | [
"def",
"_conf",
"(",
"cls",
",",
"opts",
")",
":",
"if",
"not",
"opts",
".",
"logging_conf_file",
":",
"return",
"False",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"opts",
".",
"logging_conf_file",
")",
":",
"# FileNotFoundError added only in Pytho... | 47.666667 | 28.083333 |
def label_context(label_info, multi_line=True, sep=': '):
"""
Create an unabiguous label string
If facetting over a single variable, `label_value` is
used, if two or more variables then `label_both` is used.
Parameters
----------
label_info : series
Series whose values will be retu... | [
"def",
"label_context",
"(",
"label_info",
",",
"multi_line",
"=",
"True",
",",
"sep",
"=",
"': '",
")",
":",
"if",
"len",
"(",
"label_info",
")",
"==",
"1",
":",
"return",
"label_value",
"(",
"label_info",
",",
"multi_line",
")",
"else",
":",
"return",
... | 28.518519 | 19.777778 |
def from_input(cls, input_file=sys.stdin, modify=None, backend=None):
"""
Creates a Task object, directly from the stdin, by reading one line.
If modify=True, two lines are used, first line interpreted as the
original state of the Task object, and second line as its new,
modified... | [
"def",
"from_input",
"(",
"cls",
",",
"input_file",
"=",
"sys",
".",
"stdin",
",",
"modify",
"=",
"None",
",",
"backend",
"=",
"None",
")",
":",
"# Detect the hook type if not given directly",
"name",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"sys",
".... | 41.128205 | 24.25641 |
def load_dictionary(filename):
"""Load dictionary from .spydata file"""
filename = osp.abspath(filename)
old_cwd = getcwd()
tmp_folder = tempfile.mkdtemp()
os.chdir(tmp_folder)
data = None
error_message = None
try:
with tarfile.open(filename, "r") as tar:
tar.extracta... | [
"def",
"load_dictionary",
"(",
"filename",
")",
":",
"filename",
"=",
"osp",
".",
"abspath",
"(",
"filename",
")",
"old_cwd",
"=",
"getcwd",
"(",
")",
"tmp_folder",
"=",
"tempfile",
".",
"mkdtemp",
"(",
")",
"os",
".",
"chdir",
"(",
"tmp_folder",
")",
... | 39.195122 | 14.95122 |
def watch(self, filepath, func=None, delay=None, ignore=None):
"""Add the given filepath for watcher list.
Once you have intialized a server, watch file changes before
serve the server::
server.watch('static/*.stylus', 'make static')
def alert():
print('... | [
"def",
"watch",
"(",
"self",
",",
"filepath",
",",
"func",
"=",
"None",
",",
"delay",
"=",
"None",
",",
"ignore",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"func",
",",
"string_types",
")",
":",
"cmd",
"=",
"func",
"func",
"=",
"shell",
"(",
... | 41.793103 | 20.413793 |
def to_dataframe(self, bqstorage_client=None, dtypes=None, progress_bar_type=None):
"""Create an empty dataframe.
Args:
bqstorage_client (Any):
Ignored. Added for compatibility with RowIterator.
dtypes (Any):
Ignored. Added for compatibility with ... | [
"def",
"to_dataframe",
"(",
"self",
",",
"bqstorage_client",
"=",
"None",
",",
"dtypes",
"=",
"None",
",",
"progress_bar_type",
"=",
"None",
")",
":",
"if",
"pandas",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"_NO_PANDAS_ERROR",
")",
"return",
"pandas",... | 35.555556 | 18.111111 |
def convert(input_file_name, **kwargs):
"""Convert CSV file to HTML table"""
delimiter = kwargs["delimiter"] or ","
quotechar = kwargs["quotechar"] or "|"
if six.PY2:
delimiter = delimiter.encode("utf-8")
quotechar = quotechar.encode("utf-8")
# Read CSV and form a header and rows l... | [
"def",
"convert",
"(",
"input_file_name",
",",
"*",
"*",
"kwargs",
")",
":",
"delimiter",
"=",
"kwargs",
"[",
"\"delimiter\"",
"]",
"or",
"\",\"",
"quotechar",
"=",
"kwargs",
"[",
"\"quotechar\"",
"]",
"or",
"\"|\"",
"if",
"six",
".",
"PY2",
":",
"delimi... | 33.30303 | 15.181818 |
def process_info(pid=None):
'''Returns a dictionary of system information for the process ``pid``.
It uses the psutil_ module for the purpose. If psutil_ is not available
it returns an empty dictionary.
.. _psutil: http://code.google.com/p/psutil/
'''
if psutil is None: # pragma nocover
... | [
"def",
"process_info",
"(",
"pid",
"=",
"None",
")",
":",
"if",
"psutil",
"is",
"None",
":",
"# pragma nocover",
"return",
"{",
"}",
"pid",
"=",
"pid",
"or",
"os",
".",
"getpid",
"(",
")",
"try",
":",
"p",
"=",
"psutil",
".",
"Process",
"(",
"pi... | 34.652174 | 18.913043 |
def load_from_string(self, content, container, **kwargs):
"""
Load config from given string 'cnf_content'.
:param content: Config content string
:param container: callble to make a container object later
:param kwargs: optional keyword parameters to be sanitized :: dict
... | [
"def",
"load_from_string",
"(",
"self",
",",
"content",
",",
"container",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"load_from_stream",
"(",
"anyconfig",
".",
"compat",
".",
"StringIO",
"(",
"content",
")",
",",
"container",
",",
"*",
"*"... | 42 | 20.166667 |
def n50(args):
"""
%prog n50 filename
Given a file with a list of numbers denoting contig lengths, calculate N50.
Input file can be both FASTA or a list of sizes.
"""
from jcvi.graphics.histogram import loghistogram
p = OptionParser(n50.__doc__)
p.add_option("--print0", default=False, ... | [
"def",
"n50",
"(",
"args",
")",
":",
"from",
"jcvi",
".",
"graphics",
".",
"histogram",
"import",
"loghistogram",
"p",
"=",
"OptionParser",
"(",
"n50",
".",
"__doc__",
")",
"p",
".",
"add_option",
"(",
"\"--print0\"",
",",
"default",
"=",
"False",
",",
... | 27.826923 | 20.211538 |
def __remove_trailing_empty_lines(lines):
"""
Removes leading empty lines from a list of lines.
:param list[str] lines: The lines.
"""
lines.reverse()
tmp = DocBlockReflection.__remove_leading_empty_lines(lines)
lines.reverse()
tmp.reverse()
retu... | [
"def",
"__remove_trailing_empty_lines",
"(",
"lines",
")",
":",
"lines",
".",
"reverse",
"(",
")",
"tmp",
"=",
"DocBlockReflection",
".",
"__remove_leading_empty_lines",
"(",
"lines",
")",
"lines",
".",
"reverse",
"(",
")",
"tmp",
".",
"reverse",
"(",
")",
"... | 26.25 | 16.916667 |
def median(data):
"""Calculate the median of a list."""
data.sort()
num_values = len(data)
half = num_values // 2
if num_values % 2:
return data[half]
return 0.5 * (data[half-1] + data[half]) | [
"def",
"median",
"(",
"data",
")",
":",
"data",
".",
"sort",
"(",
")",
"num_values",
"=",
"len",
"(",
"data",
")",
"half",
"=",
"num_values",
"//",
"2",
"if",
"num_values",
"%",
"2",
":",
"return",
"data",
"[",
"half",
"]",
"return",
"0.5",
"*",
... | 27 | 14.125 |
def get_content(self, start=None, end=None):
"""
Retrieve the content of the requested resource which is located
at the given absolute path.
This method should either return a byte string or an iterator
of byte strings. The latter is preferred for large files
as it helps... | [
"def",
"get_content",
"(",
"self",
",",
"start",
"=",
"None",
",",
"end",
"=",
"None",
")",
":",
"with",
"open",
"(",
"self",
".",
"filepath",
",",
"\"rb\"",
")",
"as",
"file",
":",
"if",
"start",
"is",
"not",
"None",
":",
"file",
".",
"seek",
"(... | 39.035714 | 10.821429 |
def get_tag_cloud(context, steps=6, min_count=None,
template='zinnia/tags/tag_cloud.html'):
"""
Return a cloud of published tags.
"""
tags = Tag.objects.usage_for_queryset(
Entry.published.all(), counts=True,
min_count=min_count)
return {'template': template,
... | [
"def",
"get_tag_cloud",
"(",
"context",
",",
"steps",
"=",
"6",
",",
"min_count",
"=",
"None",
",",
"template",
"=",
"'zinnia/tags/tag_cloud.html'",
")",
":",
"tags",
"=",
"Tag",
".",
"objects",
".",
"usage_for_queryset",
"(",
"Entry",
".",
"published",
".",... | 36.363636 | 6.363636 |
def get_fee(speed=FEE_SPEED_MEDIUM):
"""Gets the recommended satoshi per byte fee.
:param speed: One of: 'fast', 'medium', 'slow'.
:type speed: ``string``
:rtype: ``int``
"""
if speed == FEE_SPEED_FAST:
return DEFAULT_FEE_FAST
elif speed == FEE_SPEED_MEDIUM:
return DEFAULT_F... | [
"def",
"get_fee",
"(",
"speed",
"=",
"FEE_SPEED_MEDIUM",
")",
":",
"if",
"speed",
"==",
"FEE_SPEED_FAST",
":",
"return",
"DEFAULT_FEE_FAST",
"elif",
"speed",
"==",
"FEE_SPEED_MEDIUM",
":",
"return",
"DEFAULT_FEE_MEDIUM",
"elif",
"speed",
"==",
"FEE_SPEED_SLOW",
":... | 29.533333 | 11.8 |
def hypo_list(nodes):
"""
:param nodes: a hypoList node with N hypocenter nodes
:returns: a numpy array of shape (N, 3) with strike, dip and weight
"""
check_weights(nodes)
data = []
for node in nodes:
data.append([node['alongStrike'], node['downDip'], node['weight']])
return num... | [
"def",
"hypo_list",
"(",
"nodes",
")",
":",
"check_weights",
"(",
"nodes",
")",
"data",
"=",
"[",
"]",
"for",
"node",
"in",
"nodes",
":",
"data",
".",
"append",
"(",
"[",
"node",
"[",
"'alongStrike'",
"]",
",",
"node",
"[",
"'downDip'",
"]",
",",
"... | 33.2 | 16.8 |
def is_standard(action):
""" actions which are general "store" instructions.
e.g. anything which has an argument style like:
$ script.py -f myfilename.txt
"""
boolean_actions = (
_StoreConstAction, _StoreFalseAction,
_StoreTrueAction
)
return (not action.choices
... | [
"def",
"is_standard",
"(",
"action",
")",
":",
"boolean_actions",
"=",
"(",
"_StoreConstAction",
",",
"_StoreFalseAction",
",",
"_StoreTrueAction",
")",
"return",
"(",
"not",
"action",
".",
"choices",
"and",
"not",
"isinstance",
"(",
"action",
",",
"_CountAction... | 35.923077 | 11.307692 |
def sort_values(expr, by, ascending=True):
"""
Sort the collection by values. `sort` is an alias name for `sort_values`
:param expr: collection
:param by: the sequence or sequences to sort
:param ascending: Sort ascending vs. descending. Sepecify list for multiple sort orders.
... | [
"def",
"sort_values",
"(",
"expr",
",",
"by",
",",
"ascending",
"=",
"True",
")",
":",
"if",
"not",
"isinstance",
"(",
"by",
",",
"list",
")",
":",
"by",
"=",
"[",
"by",
",",
"]",
"by",
"=",
"[",
"it",
"(",
"expr",
")",
"if",
"inspect",
".",
... | 40 | 21.090909 |
def transformer_image_decoder(targets,
encoder_output,
ed_attention_bias,
hparams,
name=None):
"""Transformer image decoder over targets with local attention.
Args:
targets: Tensor of shape [... | [
"def",
"transformer_image_decoder",
"(",
"targets",
",",
"encoder_output",
",",
"ed_attention_bias",
",",
"hparams",
",",
"name",
"=",
"None",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"name",
",",
"default_name",
"=",
"\"transformer_dec\"",
")",
":",
... | 43.853659 | 17.707317 |
def add_site_states(self, site, states):
"""Create new states on an agent site if the state doesn't exist."""
for state in states:
if state not in self.site_states[site]:
self.site_states[site].append(state) | [
"def",
"add_site_states",
"(",
"self",
",",
"site",
",",
"states",
")",
":",
"for",
"state",
"in",
"states",
":",
"if",
"state",
"not",
"in",
"self",
".",
"site_states",
"[",
"site",
"]",
":",
"self",
".",
"site_states",
"[",
"site",
"]",
".",
"appen... | 49.4 | 7 |
def register(self, model, values=None, instance_values=None):
"""
Registers a model with this group.
:param values: A list of values that should be incremented \
whenever invalidate_cache is called for a instance or class \
of this type.
:param instance_values: A list o... | [
"def",
"register",
"(",
"self",
",",
"model",
",",
"values",
"=",
"None",
",",
"instance_values",
"=",
"None",
")",
":",
"if",
"model",
"in",
"self",
".",
"_models",
":",
"raise",
"Exception",
"(",
"\"%s is already registered\"",
"%",
"model",
")",
"self",... | 37.833333 | 22.5 |
def _request(self, method, path, server=None, **kwargs):
"""Execute a request to the cluster
A server is selected from the server pool.
"""
while True:
next_server = server or self._get_server()
try:
response = self.server_pool[next_server].reques... | [
"def",
"_request",
"(",
"self",
",",
"method",
",",
"path",
",",
"server",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"while",
"True",
":",
"next_server",
"=",
"server",
"or",
"self",
".",
"_get_server",
"(",
")",
"try",
":",
"response",
"=",
... | 48.840909 | 17.431818 |
def run(classes, args=None, msg_stream=sys.stdout,
verbose=False, util=None, event_loop=None,
post_init_callback=None, green_mode=None,
raises=False):
"""
Provides a simple way to run a tango server. It handles exceptions
by writting a message to the msg_stream.
The `classes` pa... | [
"def",
"run",
"(",
"classes",
",",
"args",
"=",
"None",
",",
"msg_stream",
"=",
"sys",
".",
"stdout",
",",
"verbose",
"=",
"False",
",",
"util",
"=",
"None",
",",
"event_loop",
"=",
"None",
",",
"post_init_callback",
"=",
"None",
",",
"green_mode",
"="... | 31.779221 | 19.974026 |
def clear_tc(self, owner, data, clear_type):
"""Delete threat intel from ThreatConnect platform.
Args:
owner (str): The ThreatConnect owner.
data (dict): The data for the threat intel to clear.
clear_type (str): The type of clear action.
"""
batch = s... | [
"def",
"clear_tc",
"(",
"self",
",",
"owner",
",",
"data",
",",
"clear_type",
")",
":",
"batch",
"=",
"self",
".",
"tcex",
".",
"batch",
"(",
"owner",
",",
"action",
"=",
"'Delete'",
")",
"tc_type",
"=",
"data",
".",
"get",
"(",
"'type'",
")",
"pat... | 42.387755 | 16.632653 |
def get_current_item(self):
"""Returns (first) selected item or None"""
l = self.selectedIndexes()
if len(l) > 0:
return self.model().get_item(l[0]) | [
"def",
"get_current_item",
"(",
"self",
")",
":",
"l",
"=",
"self",
".",
"selectedIndexes",
"(",
")",
"if",
"len",
"(",
"l",
")",
">",
"0",
":",
"return",
"self",
".",
"model",
"(",
")",
".",
"get_item",
"(",
"l",
"[",
"0",
"]",
")"
] | 36 | 8.6 |
def add_leverage(self):
""" Adds leverage term to the model
Returns
----------
None (changes instance attributes)
"""
if self.leverage is True:
pass
else:
self.leverage = True
self.z_no += 1
... | [
"def",
"add_leverage",
"(",
"self",
")",
":",
"if",
"self",
".",
"leverage",
"is",
"True",
":",
"pass",
"else",
":",
"self",
".",
"leverage",
"=",
"True",
"self",
".",
"z_no",
"+=",
"1",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"X... | 43.392857 | 30.428571 |
def _maybe_expand_trailing_dim(observed_time_series_tensor):
"""Ensures `observed_time_series_tensor` has a trailing dimension of size 1.
The `tfd.LinearGaussianStateSpaceModel` Distribution has event shape of
`[num_timesteps, observation_size]`, but canonical BSTS models
are univariate, so their observation_s... | [
"def",
"_maybe_expand_trailing_dim",
"(",
"observed_time_series_tensor",
")",
":",
"with",
"tf",
".",
"compat",
".",
"v1",
".",
"name_scope",
"(",
"'maybe_expand_trailing_dim'",
",",
"values",
"=",
"[",
"observed_time_series_tensor",
"]",
")",
":",
"if",
"(",
"obs... | 46.641026 | 24.102564 |
def _disbatch_runner_async(self, chunk):
'''
Disbatch runner client_async commands
'''
pub_data = self.saltclients['runner'](chunk)
raise tornado.gen.Return(pub_data) | [
"def",
"_disbatch_runner_async",
"(",
"self",
",",
"chunk",
")",
":",
"pub_data",
"=",
"self",
".",
"saltclients",
"[",
"'runner'",
"]",
"(",
"chunk",
")",
"raise",
"tornado",
".",
"gen",
".",
"Return",
"(",
"pub_data",
")"
] | 33.5 | 12.833333 |
def deserialize(to_deserialize, *args, **kwargs):
"""
Deserializes a string into a PyMongo BSON
"""
if isinstance(to_deserialize, string_types):
if re.match('^[0-9a-f]{24}$', to_deserialize):
return ObjectId(to_deserialize)
try:
return bson_loads(to_deserialize, *... | [
"def",
"deserialize",
"(",
"to_deserialize",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"isinstance",
"(",
"to_deserialize",
",",
"string_types",
")",
":",
"if",
"re",
".",
"match",
"(",
"'^[0-9a-f]{24}$'",
",",
"to_deserialize",
")",
":",
... | 38.076923 | 16.076923 |
def inspect_io_obj(obj):
"""
:param obj: a path string, a pathlib.Path or a file / file-like object
:return: A tuple of (objtype, objpath, objopener)
:raises: UnknownFileTypeError
"""
itype = guess_io_type(obj)
if itype == IOI_PATH_STR:
ipath = anyconfig.utils.normpath(obj)
... | [
"def",
"inspect_io_obj",
"(",
"obj",
")",
":",
"itype",
"=",
"guess_io_type",
"(",
"obj",
")",
"if",
"itype",
"==",
"IOI_PATH_STR",
":",
"ipath",
"=",
"anyconfig",
".",
"utils",
".",
"normpath",
"(",
"obj",
")",
"ext",
"=",
"anyconfig",
".",
"utils",
"... | 33.035714 | 15.678571 |
def message(message_type, payload, payload_length):
""" Build a message. """
return packet.build(
Container(
type=message_type,
id=1,
refer=0,
sent=Container(
secs=0,
usecs=0
),
recv=Container(
... | [
"def",
"message",
"(",
"message_type",
",",
"payload",
",",
"payload_length",
")",
":",
"return",
"packet",
".",
"build",
"(",
"Container",
"(",
"type",
"=",
"message_type",
",",
"id",
"=",
"1",
",",
"refer",
"=",
"0",
",",
"sent",
"=",
"Container",
"(... | 23.421053 | 17.315789 |
async def get_data(self):
"""Get details of OpenSenseMap station."""
try:
async with async_timeout.timeout(5, loop=self._loop):
response = await self._session.get(self.base_url)
_LOGGER.info(
"Response from OpenSenseMap API: %s", response.status)
... | [
"async",
"def",
"get_data",
"(",
"self",
")",
":",
"try",
":",
"async",
"with",
"async_timeout",
".",
"timeout",
"(",
"5",
",",
"loop",
"=",
"self",
".",
"_loop",
")",
":",
"response",
"=",
"await",
"self",
".",
"_session",
".",
"get",
"(",
"self",
... | 42.357143 | 21.928571 |
def get_instance(self, instance_id, project_id=None):
"""
Gets information about a particular instance.
:param project_id: Optional, The ID of the GCP project that owns the Cloud Spanner
database. If set to None or missing, the default project_id from the GCP connection is used.
... | [
"def",
"get_instance",
"(",
"self",
",",
"instance_id",
",",
"project_id",
"=",
"None",
")",
":",
"instance",
"=",
"self",
".",
"_get_client",
"(",
"project_id",
"=",
"project_id",
")",
".",
"instance",
"(",
"instance_id",
"=",
"instance_id",
")",
"if",
"n... | 43.6875 | 22.3125 |
def failure(self):
"""Update the timer to reflect a failed call"""
self.short_interval += self.short_unit
self.long_interval += self.long_unit
self.short_interval = min(self.short_interval, self.max_short_timer)
self.long_interval = min(self.long_interval, self.max_long_timer)
... | [
"def",
"failure",
"(",
"self",
")",
":",
"self",
".",
"short_interval",
"+=",
"self",
".",
"short_unit",
"self",
".",
"long_interval",
"+=",
"self",
".",
"long_unit",
"self",
".",
"short_interval",
"=",
"min",
"(",
"self",
".",
"short_interval",
",",
"self... | 48.857143 | 15.857143 |
def Connect(host='localhost', port=443, user='root', pwd='',
service="hostd", adapter="SOAP", namespace=None, path="/sdk",
connectionPoolTimeout=CONNECTION_POOL_IDLE_TIMEOUT_SEC,
version=None, keyFile=None, certFile=None, thumbprint=None,
sslContext=None, b64token=None, m... | [
"def",
"Connect",
"(",
"host",
"=",
"'localhost'",
",",
"port",
"=",
"443",
",",
"user",
"=",
"'root'",
",",
"pwd",
"=",
"''",
",",
"service",
"=",
"\"hostd\"",
",",
"adapter",
"=",
"\"SOAP\"",
",",
"namespace",
"=",
"None",
",",
"path",
"=",
"\"/sdk... | 35.52381 | 20.714286 |
def diff(self):
"""The Difference between a PDA and a DFA"""
self.mmb.complement(self.alphabet)
self.mmb.minimize()
print 'start intersection'
self.mmc = self._intesect()
print 'end intersection'
return self.mmc | [
"def",
"diff",
"(",
"self",
")",
":",
"self",
".",
"mmb",
".",
"complement",
"(",
"self",
".",
"alphabet",
")",
"self",
".",
"mmb",
".",
"minimize",
"(",
")",
"print",
"'start intersection'",
"self",
".",
"mmc",
"=",
"self",
".",
"_intesect",
"(",
")... | 32.5 | 9.5 |
def centralManager_didDisconnectPeripheral_error_(self, manager, peripheral, error):
"""Called when a device is disconnected."""
logger.debug('centralManager_didDisconnectPeripheral called')
# Get the device and remove it from the device list, then fire its
# disconnected event.
... | [
"def",
"centralManager_didDisconnectPeripheral_error_",
"(",
"self",
",",
"manager",
",",
"peripheral",
",",
"error",
")",
":",
"logger",
".",
"debug",
"(",
"'centralManager_didDisconnectPeripheral called'",
")",
"# Get the device and remove it from the device list, then fire its... | 53.8 | 17.3 |
def check_credentials(client):
"""
Checks credentials for given socket.
"""
pid, uid, gid = get_peercred(client)
euid = os.geteuid()
client_name = "PID:%s UID:%s GID:%s" % (pid, uid, gid)
if uid not in (0, euid):
raise SuspiciousClient("Can't accept client with %s. It doesn't match ... | [
"def",
"check_credentials",
"(",
"client",
")",
":",
"pid",
",",
"uid",
",",
"gid",
"=",
"get_peercred",
"(",
"client",
")",
"euid",
"=",
"os",
".",
"geteuid",
"(",
")",
"client_name",
"=",
"\"PID:%s UID:%s GID:%s\"",
"%",
"(",
"pid",
",",
"uid",
",",
... | 32.533333 | 20.4 |
def mayContainTextNodes(node):
"""
Returns True if the passed-in node is probably a text element, or at least
one of its descendants is probably a text element.
If False is returned, it is guaranteed that the passed-in node has no
business having text-based attributes.
If True is returned, the... | [
"def",
"mayContainTextNodes",
"(",
"node",
")",
":",
"# Cached result of a prior call?",
"try",
":",
"return",
"node",
".",
"mayContainTextNodes",
"except",
"AttributeError",
":",
"pass",
"result",
"=",
"True",
"# Default value",
"# Comment, text and CDATA nodes don't have ... | 39.414634 | 19.804878 |
def is_valid(self, csdl):
""" Checks if the given CSDL is valid.
Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/validate
:param csdl: CSDL to validate
:type csdl: str
:returns: Boolean indicating the validity of the CSDL
:... | [
"def",
"is_valid",
"(",
"self",
",",
"csdl",
")",
":",
"try",
":",
"self",
".",
"validate",
"(",
"csdl",
")",
"except",
"DataSiftApiException",
"as",
"e",
":",
"if",
"e",
".",
"response",
".",
"status_code",
"==",
"400",
":",
"return",
"False",
"else",... | 34.789474 | 20.631579 |
def context_chunks(self, context):
"""
Retrieves all tokens, divided into the chunks in context ``context``.
If ``context`` is not found in a feature, then the feature will be
treated as a single chunk.
Parameters
----------
context : str
Context nam... | [
"def",
"context_chunks",
"(",
"self",
",",
"context",
")",
":",
"chunks",
"=",
"[",
"]",
"papers",
"=",
"[",
"]",
"for",
"paper",
",",
"feature",
"in",
"self",
".",
"features",
".",
"iteritems",
"(",
")",
":",
"if",
"context",
"in",
"feature",
".",
... | 30.064516 | 19.16129 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.