text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def _deserialize(self, stream):
"""Initialize this instance with index values read from the given stream"""
self.version, self.entries, self._extension_data, conten_sha = read_cache(stream) # @UnusedVariable
return self | [
"def",
"_deserialize",
"(",
"self",
",",
"stream",
")",
":",
"self",
".",
"version",
",",
"self",
".",
"entries",
",",
"self",
".",
"_extension_data",
",",
"conten_sha",
"=",
"read_cache",
"(",
"stream",
")",
"# @UnusedVariable",
"return",
"self"
] | 60.25 | 0.016393 |
def file_envs(self, load=None):
'''
Return environments for all backends for requests from fileclient
'''
if load is None:
load = {}
load.pop('cmd', None)
return self.envs(**load) | [
"def",
"file_envs",
"(",
"self",
",",
"load",
"=",
"None",
")",
":",
"if",
"load",
"is",
"None",
":",
"load",
"=",
"{",
"}",
"load",
".",
"pop",
"(",
"'cmd'",
",",
"None",
")",
"return",
"self",
".",
"envs",
"(",
"*",
"*",
"load",
")"
] | 29 | 0.008368 |
def get_reference(proxy):
'''
Return the object that is referenced by the specified proxy.
If the proxy has not been bound to a reference for the current thread,
the behavior depends on th the ``fallback_to_shared`` flag that has
been specified when creating the proxy. If the fl... | [
"def",
"get_reference",
"(",
"proxy",
")",
":",
"thread_local",
"=",
"object",
".",
"__getattribute__",
"(",
"proxy",
",",
"'_thread_local'",
")",
"try",
":",
"return",
"thread_local",
".",
"reference",
"except",
"AttributeError",
":",
"fallback_to_shared",
"=",
... | 52.869565 | 0.001615 |
def _upstart_enable(name):
'''
Enable an Upstart service.
'''
if _upstart_is_enabled(name):
return _upstart_is_enabled(name)
override = '/etc/init/{0}.override'.format(name)
files = ['/etc/init/{0}.conf'.format(name), override]
for file_name in filter(os.path.isfile, files):
... | [
"def",
"_upstart_enable",
"(",
"name",
")",
":",
"if",
"_upstart_is_enabled",
"(",
"name",
")",
":",
"return",
"_upstart_is_enabled",
"(",
"name",
")",
"override",
"=",
"'/etc/init/{0}.override'",
".",
"format",
"(",
"name",
")",
"files",
"=",
"[",
"'/etc/init... | 36.12 | 0.001079 |
def has_activity(graph: BELGraph, node: BaseEntity) -> bool:
"""Return true if over any of the node's edges, it has a molecular activity."""
return _node_has_modifier(graph, node, ACTIVITY) | [
"def",
"has_activity",
"(",
"graph",
":",
"BELGraph",
",",
"node",
":",
"BaseEntity",
")",
"->",
"bool",
":",
"return",
"_node_has_modifier",
"(",
"graph",
",",
"node",
",",
"ACTIVITY",
")"
] | 65 | 0.010152 |
def _process_figure(value, fmt):
"""Processes the figure. Returns a dict containing figure properties."""
# pylint: disable=global-statement
global Nreferences # Global references counter
global has_unnumbered_figures # Flags unnumbered figures were found
global cursec ... | [
"def",
"_process_figure",
"(",
"value",
",",
"fmt",
")",
":",
"# pylint: disable=global-statement",
"global",
"Nreferences",
"# Global references counter",
"global",
"has_unnumbered_figures",
"# Flags unnumbered figures were found",
"global",
"cursec",
"# Current section",
"# Par... | 41.049383 | 0.002056 |
def read_from_endpoint(self, endpoint, timeout=15):
"""
Blocking read from an endpoint. Will block until a message is received, or it times out. Also see
:meth:`get_endpoint_queue` if you are considering calling this in a loop.
.. warning::
Avoid calling this method from an e... | [
"def",
"read_from_endpoint",
"(",
"self",
",",
"endpoint",
",",
"timeout",
"=",
"15",
")",
":",
"return",
"self",
".",
"event_handler",
".",
"wait_for_event",
"(",
"(",
"_EventType",
".",
"Watch",
",",
"endpoint",
")",
",",
"timeout",
"=",
"timeout",
")"
] | 51.588235 | 0.010078 |
def discover_group(group, separator="/", exclude=None):
"""Produce a list of all services and their addresses in a group
A group is an optional form of namespace within the discovery mechanism.
If an advertised name has the form <group><sep><name> it is deemed to
belong to <group>. Note that the se... | [
"def",
"discover_group",
"(",
"group",
",",
"separator",
"=",
"\"/\"",
",",
"exclude",
"=",
"None",
")",
":",
"_start_beacon",
"(",
")",
"if",
"exclude",
"is",
"None",
":",
"names_to_exclude",
"=",
"set",
"(",
")",
"else",
":",
"names_to_exclude",
"=",
"... | 39.923077 | 0.009407 |
def save_json(data, path, fatal=True, logger=None, sort_keys=True, indent=2, **kwargs):
"""
Args:
data (object | None): Data to serialize and save
path (str | None): Path to file where to save
fatal (bool | None): Abort execution on failure if True
logger (callable | None): Logge... | [
"def",
"save_json",
"(",
"data",
",",
"path",
",",
"fatal",
"=",
"True",
",",
"logger",
"=",
"None",
",",
"sort_keys",
"=",
"True",
",",
"indent",
"=",
"2",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"data",
"is",
"None",
"or",
"not",
"path",
":",
... | 31.439024 | 0.001505 |
def reverse(self, viewname, args=None, kwargs=None):
"""
Reverse a blog page, taking different configuration options into account.
For example, the blog can be mounted using *django-fluent-pages* on multiple nodes.
"""
# TODO: django-fluent-pages needs a public API to get the cur... | [
"def",
"reverse",
"(",
"self",
",",
"viewname",
",",
"args",
"=",
"None",
",",
"kwargs",
"=",
"None",
")",
":",
"# TODO: django-fluent-pages needs a public API to get the current page.",
"current_page",
"=",
"getattr",
"(",
"self",
".",
"request",
",",
"'_current_fl... | 61.125 | 0.010081 |
def conditional_jit(function=None, **kwargs): # noqa: D202
"""Use numba's jit decorator if numba is installed.
Notes
-----
If called without arguments then return wrapped function.
@conditional_jit
def my_func():
return
else called with arguments
@co... | [
"def",
"conditional_jit",
"(",
"function",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: D202",
"def",
"wrapper",
"(",
"function",
")",
":",
"try",
":",
"numba",
"=",
"importlib",
".",
"import_module",
"(",
"\"numba\"",
")",
"return",
"numba",
... | 21.064516 | 0.001464 |
def match_https_hostname(cls, hostname):
"""
:param hostname: a string
:returns: an :py:class:`~httpretty.core.URLMatcher` or ``None``
"""
items = sorted(
cls._entries.items(),
key=lambda matcher_entries: matcher_entries[0].priority,
reverse=Tr... | [
"def",
"match_https_hostname",
"(",
"cls",
",",
"hostname",
")",
":",
"items",
"=",
"sorted",
"(",
"cls",
".",
"_entries",
".",
"items",
"(",
")",
",",
"key",
"=",
"lambda",
"matcher_entries",
":",
"matcher_entries",
"[",
"0",
"]",
".",
"priority",
",",
... | 37.115385 | 0.00202 |
async def getaccountbywallet(**params):
"""Receives account by wallet
Accepts:
- public key hex or checksum format
"""
if params.get("message"):
params = json.loads(params.get("message"))
for coinid in coin_ids:
database = client[coinid]
wallet_collection = database[settings.WALLET]
wallet = await walle... | [
"async",
"def",
"getaccountbywallet",
"(",
"*",
"*",
"params",
")",
":",
"if",
"params",
".",
"get",
"(",
"\"message\"",
")",
":",
"params",
"=",
"json",
".",
"loads",
"(",
"params",
".",
"get",
"(",
"\"message\"",
")",
")",
"for",
"coinid",
"in",
"c... | 31.25 | 0.037516 |
def sharedFiles(self):
'iterate over shared files and get their public URI'
for f in self.sharing.files.iterchildren():
yield (f.attrib['name'], f.attrib['uuid'],
'https://www.jottacloud.com/p/%s/%s' % (self.jfs.username, f.publicURI.text)) | [
"def",
"sharedFiles",
"(",
"self",
")",
":",
"for",
"f",
"in",
"self",
".",
"sharing",
".",
"files",
".",
"iterchildren",
"(",
")",
":",
"yield",
"(",
"f",
".",
"attrib",
"[",
"'name'",
"]",
",",
"f",
".",
"attrib",
"[",
"'uuid'",
"]",
",",
"'htt... | 56 | 0.014085 |
def save_record(self, instance, update_fields=None, **kwargs):
"""Saves the record.
If `update_fields` is set, this method will use partial_update_object()
and will update only the given fields (never `_geoloc` and `_tags`).
For more information about partial_update_object:
htt... | [
"def",
"save_record",
"(",
"self",
",",
"instance",
",",
"update_fields",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"self",
".",
"_should_index",
"(",
"instance",
")",
":",
"# Should not index, but since we don't now the state of the",
"# instan... | 43.53125 | 0.001404 |
def iter_field_objects(fields):
"""
Iterate over fields.
Supports list of (k, v) tuples and dicts, and lists of
:class:`~urllib3.fields.RequestField`.
"""
if isinstance(fields, dict):
i = six.iteritems(fields)
else:
i = iter(fields)
for field in i:
if isinstanc... | [
"def",
"iter_field_objects",
"(",
"fields",
")",
":",
"if",
"isinstance",
"(",
"fields",
",",
"dict",
")",
":",
"i",
"=",
"six",
".",
"iteritems",
"(",
"fields",
")",
"else",
":",
"i",
"=",
"iter",
"(",
"fields",
")",
"for",
"field",
"in",
"i",
":"... | 23.055556 | 0.002315 |
def __leaf(i, j, first, maxfirst, prevleaf, ancestor):
"""
Determine if j is leaf of i'th row subtree.
"""
jleaf = 0
if i<=j or first[j] <= maxfirst[i]: return -1, jleaf
maxfirst[i] = first[j]
jprev = prevleaf[i]
prevleaf[i] = j
if jprev == -1: jleaf = 1
else: jleaf = 2
if jl... | [
"def",
"__leaf",
"(",
"i",
",",
"j",
",",
"first",
",",
"maxfirst",
",",
"prevleaf",
",",
"ancestor",
")",
":",
"jleaf",
"=",
"0",
"if",
"i",
"<=",
"j",
"or",
"first",
"[",
"j",
"]",
"<=",
"maxfirst",
"[",
"i",
"]",
":",
"return",
"-",
"1",
"... | 25.5 | 0.013233 |
def animate(zdata, xdata, ydata,
conversionFactorArray, timedata,
BoxSize,
timeSteps=100, filename="particle"):
"""
Animates the particle's motion given the z, x and y signal (in Volts)
and the conversion factor (to convert between V and nm).
Parameters
---------... | [
"def",
"animate",
"(",
"zdata",
",",
"xdata",
",",
"ydata",
",",
"conversionFactorArray",
",",
"timedata",
",",
"BoxSize",
",",
"timeSteps",
"=",
"100",
",",
"filename",
"=",
"\"particle\"",
")",
":",
"timePerFrame",
"=",
"0.203",
"print",
"(",
"\"This will ... | 34.601449 | 0.000814 |
def check(projects):
"""Check the specified projects for Python 3 compatibility."""
log = logging.getLogger('ciu')
log.info('{0} top-level projects to check'.format(len(projects)))
print('Finding and checking dependencies ...')
blockers = dependencies.blockers(projects)
print('')
for line i... | [
"def",
"check",
"(",
"projects",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"'ciu'",
")",
"log",
".",
"info",
"(",
"'{0} top-level projects to check'",
".",
"format",
"(",
"len",
"(",
"projects",
")",
")",
")",
"print",
"(",
"'Finding and chec... | 28.6875 | 0.00211 |
def compare2(args):
"""
%prog compare2
Compare performances of various variant callers on simulated STR datasets.
"""
p = OptionParser(compare2.__doc__)
p.add_option('--maxinsert', default=300, type="int",
help="Maximum number of repeats")
add_simulate_options(p)
opts, ... | [
"def",
"compare2",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"compare2",
".",
"__doc__",
")",
"p",
".",
"add_option",
"(",
"'--maxinsert'",
",",
"default",
"=",
"300",
",",
"type",
"=",
"\"int\"",
",",
"help",
"=",
"\"Maximum number of repeats\... | 36.04 | 0.001621 |
def point_in_tetrahedron(tetra, pt):
'''
point_in_tetrahedron(tetrahedron, point) yields True if the given point is in the given
tetrahedron. If either tetrahedron or point (or both) are lists of shapes/points, then this
calculation is automatically threaded over all the given arguments.
'''
... | [
"def",
"point_in_tetrahedron",
"(",
"tetra",
",",
"pt",
")",
":",
"bcs",
"=",
"tetrahedral_barycentric_coordinates",
"(",
"tetra",
",",
"pt",
")",
"return",
"np",
".",
"logical_not",
"(",
"np",
".",
"all",
"(",
"np",
".",
"isclose",
"(",
"bcs",
",",
"0",... | 53.625 | 0.009174 |
def run(
self,
cluster_config,
rg_parser,
partition_measurer,
cluster_balancer,
args,
):
"""Initialize cluster_config, args, and zk then call run_command."""
self.cluster_config = cluster_config
self.args = args
... | [
"def",
"run",
"(",
"self",
",",
"cluster_config",
",",
"rg_parser",
",",
"partition_measurer",
",",
"cluster_balancer",
",",
"args",
",",
")",
":",
"self",
".",
"cluster_config",
"=",
"cluster_config",
"self",
".",
"args",
"=",
"args",
"with",
"ZK",
"(",
"... | 33.119048 | 0.002095 |
def encode_osgi_props(ed):
# type: (EndpointDescription) -> Dict[str, str]
"""
Prepares a dictionary of OSGi properties for the given EndpointDescription
"""
result_props = {}
intfs = ed.get_interfaces()
result_props[OBJECTCLASS] = " ".join(intfs)
for intf in intfs:
pkg_name = pa... | [
"def",
"encode_osgi_props",
"(",
"ed",
")",
":",
"# type: (EndpointDescription) -> Dict[str, str]",
"result_props",
"=",
"{",
"}",
"intfs",
"=",
"ed",
".",
"get_interfaces",
"(",
")",
"result_props",
"[",
"OBJECTCLASS",
"]",
"=",
"\" \"",
".",
"join",
"(",
"intf... | 38.117647 | 0.000752 |
def dump_conf(self, config_pathname=None):
"""write a config file to the pathname specified in the parameter. The
file extention determines the type of file written and must match a
registered type.
parameters:
config_pathname - the full path and filename of the target conf... | [
"def",
"dump_conf",
"(",
"self",
",",
"config_pathname",
"=",
"None",
")",
":",
"if",
"not",
"config_pathname",
":",
"config_pathname",
"=",
"self",
".",
"_get_option",
"(",
"'admin.dump_conf'",
")",
".",
"value",
"opener",
"=",
"functools",
".",
"partial",
... | 37.636364 | 0.002356 |
def post_attachment(self, bugid, attachment):
'''http://bugzilla.readthedocs.org/en/latest/api/core/v1/attachment.html#create-attachment'''
assert type(attachment) is DotDict
assert 'data' in attachment
assert 'file_name' in attachment
assert 'summary' in attachment
if (n... | [
"def",
"post_attachment",
"(",
"self",
",",
"bugid",
",",
"attachment",
")",
":",
"assert",
"type",
"(",
"attachment",
")",
"is",
"DotDict",
"assert",
"'data'",
"in",
"attachment",
"assert",
"'file_name'",
"in",
"attachment",
"assert",
"'summary'",
"in",
"atta... | 55.909091 | 0.0128 |
def tasks_file_to_task_descriptors(tasks, retries, input_file_param_util,
output_file_param_util):
"""Parses task parameters from a TSV.
Args:
tasks: Dict containing the path to a TSV file and task numbers to run
variables, input, and output parameters as column headings.... | [
"def",
"tasks_file_to_task_descriptors",
"(",
"tasks",
",",
"retries",
",",
"input_file_param_util",
",",
"output_file_param_util",
")",
":",
"task_descriptors",
"=",
"[",
"]",
"path",
"=",
"tasks",
"[",
"'path'",
"]",
"task_min",
"=",
"tasks",
".",
"get",
"(",
... | 34.284091 | 0.008376 |
def get_user_enclaves(self):
"""
Gets the list of enclaves that the user has access to.
:return: A list of |EnclavePermissions| objects, each representing an enclave and whether the requesting user
has read, create, and update access to it.
"""
resp = self._client.g... | [
"def",
"get_user_enclaves",
"(",
"self",
")",
":",
"resp",
"=",
"self",
".",
"_client",
".",
"get",
"(",
"\"enclaves\"",
")",
"return",
"[",
"EnclavePermissions",
".",
"from_dict",
"(",
"enclave",
")",
"for",
"enclave",
"in",
"resp",
".",
"json",
"(",
")... | 40.7 | 0.009615 |
def get_success_url(self):
"""Get the url depending on what type of configuration I deleted."""
if self.stage_id:
url = reverse('projects_stage_view', args=(self.project_id, self.stage_id))
else:
url = reverse('projects_project_view', args=(self.project_id,))
re... | [
"def",
"get_success_url",
"(",
"self",
")",
":",
"if",
"self",
".",
"stage_id",
":",
"url",
"=",
"reverse",
"(",
"'projects_stage_view'",
",",
"args",
"=",
"(",
"self",
".",
"project_id",
",",
"self",
".",
"stage_id",
")",
")",
"else",
":",
"url",
"=",... | 35.555556 | 0.009146 |
def _create_label(self, array):
"""Create sample PDS3 label for NumPy Array.
It is called by 'image.py' to create PDS3Image object
from Numpy Array.
Returns
-------
PVLModule label for the given NumPy array.
Usage: self.label = _create_label(array)
"""
... | [
"def",
"_create_label",
"(",
"self",
",",
"array",
")",
":",
"if",
"len",
"(",
"array",
".",
"shape",
")",
"==",
"3",
":",
"bands",
"=",
"array",
".",
"shape",
"[",
"0",
"]",
"lines",
"=",
"array",
".",
"shape",
"[",
"1",
"]",
"line_samples",
"="... | 32.2 | 0.001507 |
def clistream(reporter, *args, **kwargs):
""" Handle stream data on command line interface,
and returns statistics of success, error, and total amount.
More detailed information is available on underlying feature,
:mod:`clitool.processor`.
:param Handler: [DEPRECATED] Handler for file-like streams... | [
"def",
"clistream",
"(",
"reporter",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# Follow the rule of `parse_arguments()`",
"files",
"=",
"kwargs",
".",
"get",
"(",
"'files'",
")",
"encoding",
"=",
"kwargs",
".",
"get",
"(",
"'input_encoding'",
","... | 38.914286 | 0.001433 |
def optimize_logger_level(logger, log_level):
"""
At runtime, when logging is not active,
replace the .debug() call with a no-op.
"""
function_name = _log_functions[log_level]
if getattr(logger, function_name) is _dummy_log:
return False
is_level_logged = logger.isEnabledFor(log_lev... | [
"def",
"optimize_logger_level",
"(",
"logger",
",",
"log_level",
")",
":",
"function_name",
"=",
"_log_functions",
"[",
"log_level",
"]",
"if",
"getattr",
"(",
"logger",
",",
"function_name",
")",
"is",
"_dummy_log",
":",
"return",
"False",
"is_level_logged",
"=... | 29.785714 | 0.002326 |
def validate_config_parameters(config_json, allowed_keys, allowed_types):
"""Validate parameters in config file."""
custom_fields = config_json.get(defs.PARAMETERS, [])
for field in custom_fields:
validate_field(field, allowed_keys, allowed_types)
default = field.get(defs.DEFAULT)
fi... | [
"def",
"validate_config_parameters",
"(",
"config_json",
",",
"allowed_keys",
",",
"allowed_types",
")",
":",
"custom_fields",
"=",
"config_json",
".",
"get",
"(",
"defs",
".",
"PARAMETERS",
",",
"[",
"]",
")",
"for",
"field",
"in",
"custom_fields",
":",
"vali... | 49.222222 | 0.002217 |
def positive_volume_index(close_data, volume):
"""
Positive Volume Index (PVI).
Formula:
PVI0 = 1
IF Vt > Vt-1
PVIt = PVIt-1 + (CLOSEt - CLOSEt-1 / CLOSEt-1 * PVIt-1)
ELSE:
PVIt = PVIt-1
"""
catch_errors.check_for_input_len_diff(close_data, volume)
pvi = np.zeros(len... | [
"def",
"positive_volume_index",
"(",
"close_data",
",",
"volume",
")",
":",
"catch_errors",
".",
"check_for_input_len_diff",
"(",
"close_data",
",",
"volume",
")",
"pvi",
"=",
"np",
".",
"zeros",
"(",
"len",
"(",
"volume",
")",
")",
"pvi",
"[",
"0",
"]",
... | 26.55 | 0.001818 |
def round_to_n(x, n):
"""
Round to sig figs
"""
return round(x, -int(np.floor(np.log10(x))) + (n - 1)) | [
"def",
"round_to_n",
"(",
"x",
",",
"n",
")",
":",
"return",
"round",
"(",
"x",
",",
"-",
"int",
"(",
"np",
".",
"floor",
"(",
"np",
".",
"log10",
"(",
"x",
")",
")",
")",
"+",
"(",
"n",
"-",
"1",
")",
")"
] | 22.8 | 0.008475 |
def scheduled(self, offset=0, count=25):
'''Return all the currently-scheduled jobs'''
return self.client('jobs', 'scheduled', self.name, offset, count) | [
"def",
"scheduled",
"(",
"self",
",",
"offset",
"=",
"0",
",",
"count",
"=",
"25",
")",
":",
"return",
"self",
".",
"client",
"(",
"'jobs'",
",",
"'scheduled'",
",",
"self",
".",
"name",
",",
"offset",
",",
"count",
")"
] | 55.333333 | 0.011905 |
def greylisting(data):
"""
Run ChIP-seq greylisting
"""
input_bam = data.get("work_bam_input", None)
if not input_bam:
logger.info("No input BAM file detected, skipping greylisting.")
return None
try:
greylister = config_utils.get_program("chipseq-greylist", data)
exc... | [
"def",
"greylisting",
"(",
"data",
")",
":",
"input_bam",
"=",
"data",
".",
"get",
"(",
"\"work_bam_input\"",
",",
"None",
")",
"if",
"not",
"input_bam",
":",
"logger",
".",
"info",
"(",
"\"No input BAM file detected, skipping greylisting.\"",
")",
"return",
"No... | 42.071429 | 0.00249 |
def checkout(self, ref, cb=None):
"""Checkout a bundle from the remote. Returns a file-like object"""
if self.is_api:
return self._checkout_api(ref, cb=cb)
else:
return self._checkout_fs(ref, cb=cb) | [
"def",
"checkout",
"(",
"self",
",",
"ref",
",",
"cb",
"=",
"None",
")",
":",
"if",
"self",
".",
"is_api",
":",
"return",
"self",
".",
"_checkout_api",
"(",
"ref",
",",
"cb",
"=",
"cb",
")",
"else",
":",
"return",
"self",
".",
"_checkout_fs",
"(",
... | 40.166667 | 0.00813 |
def designPrimers(p3_args, input_log=None, output_log=None, err_log=None):
''' Return the raw primer3_core output for the provided primer3 args.
Returns an ordered dict of the boulderIO-format primer3 output file
'''
sp = subprocess.Popen([pjoin(PRIMER3_HOME, 'primer3_core')],
... | [
"def",
"designPrimers",
"(",
"p3_args",
",",
"input_log",
"=",
"None",
",",
"output_log",
"=",
"None",
",",
"err_log",
"=",
"None",
")",
":",
"sp",
"=",
"subprocess",
".",
"Popen",
"(",
"[",
"pjoin",
"(",
"PRIMER3_HOME",
",",
"'primer3_core'",
")",
"]",
... | 41 | 0.001083 |
def follow_path(self, path, weight=None):
"""Go to several :class:`Place`s in succession, deciding how long to
spend in each by consulting the ``weight`` stat of the
:class:`Portal` connecting the one :class:`Place` to the next.
Return the total number of turns the travel will take. Rai... | [
"def",
"follow_path",
"(",
"self",
",",
"path",
",",
"weight",
"=",
"None",
")",
":",
"if",
"len",
"(",
"path",
")",
"<",
"2",
":",
"raise",
"ValueError",
"(",
"\"Paths need at least 2 nodes\"",
")",
"eng",
"=",
"self",
".",
"character",
".",
"engine",
... | 41.020408 | 0.000972 |
def binarize_percent(netin, level, sign='pos', axis='time'):
"""
Binarizes a network proprtionally. When axis='time' (only one available at the moment) then the top values for each edge time series are considered.
Parameters
----------
netin : array or dict
network (graphlet or contact rep... | [
"def",
"binarize_percent",
"(",
"netin",
",",
"level",
",",
"sign",
"=",
"'pos'",
",",
"axis",
"=",
"'time'",
")",
":",
"netin",
",",
"netinfo",
"=",
"process_input",
"(",
"netin",
",",
"[",
"'C'",
",",
"'G'",
",",
"'TO'",
"]",
")",
"# Set diagonal to ... | 38.469697 | 0.002304 |
def make_clust(net, dist_type='cosine', run_clustering=True, dendro=True,
requested_views=['pct_row_sum', 'N_row_sum'],
linkage_type='average', sim_mat=False, filter_sim=0.1,
calc_cat_pval=False, sim_mat_views=['N_row_sum'],
... | [
"def",
"make_clust",
"(",
"net",
",",
"dist_type",
"=",
"'cosine'",
",",
"run_clustering",
"=",
"True",
",",
"dendro",
"=",
"True",
",",
"requested_views",
"=",
"[",
"'pct_row_sum'",
",",
"'N_row_sum'",
"]",
",",
"linkage_type",
"=",
"'average'",
",",
"sim_m... | 32.131313 | 0.015554 |
def dual_obj_grad(alpha, beta, a, b, C, regul):
"""
Compute objective value and gradients of dual objective.
Parameters
----------
alpha: array, shape = len(a)
beta: array, shape = len(b)
Current iterate of dual potentials.
a: array, shape = len(a)
b: array, shape = len(b)
... | [
"def",
"dual_obj_grad",
"(",
"alpha",
",",
"beta",
",",
"a",
",",
"b",
",",
"C",
",",
"regul",
")",
":",
"obj",
"=",
"np",
".",
"dot",
"(",
"alpha",
",",
"a",
")",
"+",
"np",
".",
"dot",
"(",
"beta",
",",
"b",
")",
"grad_alpha",
"=",
"a",
"... | 26.452381 | 0.000868 |
def admin_tools_render_dashboard(context, location='index', dashboard=None):
"""
Template tag that renders the dashboard, it takes two optional arguments:
``location``
The location of the dashboard, it can be 'index' (for the admin index
dashboard) or 'app_index' (for the app index dashboar... | [
"def",
"admin_tools_render_dashboard",
"(",
"context",
",",
"location",
"=",
"'index'",
",",
"dashboard",
"=",
"None",
")",
":",
"if",
"dashboard",
"is",
"None",
":",
"dashboard",
"=",
"get_dashboard",
"(",
"context",
",",
"location",
")",
"dashboard",
".",
... | 34.42 | 0.000565 |
def parse_gene_set(gene_set_fp):
"""Parses gene set file and returns a (group)-(gene set) dictionary.
Attribute:
gene_set_fp (str): File path to a gene set file.
"""
group_gene_set_dict = OrderedDict()
with open(gene_set_fp) as inFile:
for line in inFile.readlines():
... | [
"def",
"parse_gene_set",
"(",
"gene_set_fp",
")",
":",
"group_gene_set_dict",
"=",
"OrderedDict",
"(",
")",
"with",
"open",
"(",
"gene_set_fp",
")",
"as",
"inFile",
":",
"for",
"line",
"in",
"inFile",
".",
"readlines",
"(",
")",
":",
"tokens",
"=",
"line",... | 31.375 | 0.001934 |
def prompt_file(prompt, default=None):
"""Prompt a file name with autocompletion"""
def complete(text: str, state):
text = text.replace('~', HOME)
sugg = (glob.glob(text + '*') + [None])[state]
if sugg is None:
return
sugg = sugg.replace(HOME, '~')
sugg = ... | [
"def",
"prompt_file",
"(",
"prompt",
",",
"default",
"=",
"None",
")",
":",
"def",
"complete",
"(",
"text",
":",
"str",
",",
"state",
")",
":",
"text",
"=",
"text",
".",
"replace",
"(",
"'~'",
",",
"HOME",
")",
"sugg",
"=",
"(",
"glob",
".",
"glo... | 24.088235 | 0.001174 |
def replace_certificate_signing_request_status(self, name, body, **kwargs): # noqa: E501
"""replace_certificate_signing_request_status # noqa: E501
replace status of the specified CertificateSigningRequest # noqa: E501
This method makes a synchronous HTTP request by default. To make an
... | [
"def",
"replace_certificate_signing_request_status",
"(",
"self",
",",
"name",
",",
"body",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async_req'",
")",
":"... | 63.625 | 0.00129 |
def getSimpleFileData(self, fileInfo, data):
"""Function to initialize the simple data for file info"""
result = fileInfo[fileInfo.find(data + "</td>"):]
result = result[:result.find("</A></td>")]
result = result[result.rfind(">") + 1:]
return result | [
"def",
"getSimpleFileData",
"(",
"self",
",",
"fileInfo",
",",
"data",
")",
":",
"result",
"=",
"fileInfo",
"[",
"fileInfo",
".",
"find",
"(",
"data",
"+",
"\"</td>\"",
")",
":",
"]",
"result",
"=",
"result",
"[",
":",
"result",
".",
"find",
"(",
"\"... | 42.5 | 0.026923 |
def shell_exec(command):
"""Executes the given shell command and returns its output."""
out = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0]
return out.decode('utf-8') | [
"def",
"shell_exec",
"(",
"command",
")",
":",
"out",
"=",
"subprocess",
".",
"Popen",
"(",
"command",
",",
"shell",
"=",
"True",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"stderr",
"=",
"subprocess",
".",
"STDOUT",
")",
".",
"communicate",
"... | 58.5 | 0.008439 |
def timezone(haystack_tz, version=LATEST_VER):
"""
Retrieve the Haystack timezone
"""
tz_map = get_tz_map(version=version)
try:
tz_name = tz_map[haystack_tz]
except KeyError:
raise ValueError('%s is not a recognised timezone on this host' \
% haystack_tz)
retu... | [
"def",
"timezone",
"(",
"haystack_tz",
",",
"version",
"=",
"LATEST_VER",
")",
":",
"tz_map",
"=",
"get_tz_map",
"(",
"version",
"=",
"version",
")",
"try",
":",
"tz_name",
"=",
"tz_map",
"[",
"haystack_tz",
"]",
"except",
"KeyError",
":",
"raise",
"ValueE... | 30.454545 | 0.008696 |
def parse_args(self, args):
"""
Parse arguments and return an arguments object
>>> from margaritashotgun.cli import Cli
>>> cli = CLi()
>>> cli.parse_args(sys.argv[1:])
:type args: list
:param args: list of arguments
"""
parser = argp... | [
"def",
"parse_args",
"(",
"self",
",",
"args",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"'Remote memory aquisition wrapper for LiME'",
")",
"root",
"=",
"parser",
".",
"add_mutually_exclusive_group",
"(",
"required",
"=",
... | 47.794521 | 0.000842 |
def prepare_check(data):
"""Prepare check for catalog endpoint
Parameters:
data (Object or ObjectID): Check ID or check definition
Returns:
Tuple[str, dict]: where first is ID and second is check definition
"""
if not data:
return None, {}
if isinstance(data, str):
... | [
"def",
"prepare_check",
"(",
"data",
")",
":",
"if",
"not",
"data",
":",
"return",
"None",
",",
"{",
"}",
"if",
"isinstance",
"(",
"data",
",",
"str",
")",
":",
"return",
"data",
",",
"{",
"}",
"result",
"=",
"{",
"}",
"if",
"\"ID\"",
"in",
"data... | 27.652174 | 0.00152 |
def parse_hgnc_genes(lines):
"""Parse lines with hgnc formated genes
This is designed to take a dump with genes from HGNC.
This is downloaded from:
ftp://ftp.ebi.ac.uk/pub/databases/genenames/new/tsv/hgnc_complete_set.txt
Args:
lines(iterable(str)): An iterable with HGN... | [
"def",
"parse_hgnc_genes",
"(",
"lines",
")",
":",
"header",
"=",
"[",
"]",
"logger",
".",
"info",
"(",
"\"Parsing hgnc genes...\"",
")",
"for",
"index",
",",
"line",
"in",
"enumerate",
"(",
"lines",
")",
":",
"if",
"index",
"==",
"0",
":",
"header",
"... | 34.428571 | 0.001346 |
def check_last_err(func, self, *args, **kwargs):
"""Check and raise deferred errors before running the function
This method checks :python:`_last_err` before running the wrapped
function. If present and not None, the exception will be raised
with its original traceback.
"""
if self._last_err ... | [
"def",
"check_last_err",
"(",
"func",
",",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"_last_err",
"is",
"not",
"None",
":",
"try",
":",
"if",
"six",
".",
"PY2",
":",
"six",
".",
"reraise",
"(",
"type",
"(",
... | 34.771429 | 0.000799 |
def _send_ffd(self, pid, aplx_data, address):
"""Send flood-fill data packets."""
block = 0
pos = 0
aplx_size = len(aplx_data)
while pos < aplx_size:
# Get the next block of data, send and progress the block
# counter and the address
data = ap... | [
"def",
"_send_ffd",
"(",
"self",
",",
"pid",
",",
"aplx_data",
",",
"address",
")",
":",
"block",
"=",
"0",
"pos",
"=",
"0",
"aplx_size",
"=",
"len",
"(",
"aplx_data",
")",
"while",
"pos",
"<",
"aplx_size",
":",
"# Get the next block of data, send and progre... | 36.545455 | 0.002424 |
def zernike(zernike_indexes,labels,indexes):
"""Compute the Zernike features for the labels with the label #s in indexes
returns the score per labels and an array of one image per zernike feature
"""
#
# "Reverse_indexes" is -1 if a label # is not to be processed. Otherwise
# reverse_index[... | [
"def",
"zernike",
"(",
"zernike_indexes",
",",
"labels",
",",
"indexes",
")",
":",
"#",
"# \"Reverse_indexes\" is -1 if a label # is not to be processed. Otherwise",
"# reverse_index[label] gives you the index into indexes of the label",
"# and other similarly shaped vectors (like the resu... | 36.78 | 0.010064 |
def set_index(data,col_index):
"""
Sets the index if the index is not present
:param data: pandas table
:param col_index: column name which will be assigned as a index
"""
if col_index in data:
data=data.reset_index().set_index(col_index)
if 'index' in data:
del dat... | [
"def",
"set_index",
"(",
"data",
",",
"col_index",
")",
":",
"if",
"col_index",
"in",
"data",
":",
"data",
"=",
"data",
".",
"reset_index",
"(",
")",
".",
"set_index",
"(",
"col_index",
")",
"if",
"'index'",
"in",
"data",
":",
"del",
"data",
"[",
"'i... | 28.117647 | 0.010121 |
def _apply_uncertainty_to_geometry(self, source, value):
"""
Modify ``source`` geometry with the uncertainty value ``value``
"""
if self.uncertainty_type == 'simpleFaultDipRelative':
source.modify('adjust_dip', dict(increment=value))
elif self.uncertainty_type == 'sim... | [
"def",
"_apply_uncertainty_to_geometry",
"(",
"self",
",",
"source",
",",
"value",
")",
":",
"if",
"self",
".",
"uncertainty_type",
"==",
"'simpleFaultDipRelative'",
":",
"source",
".",
"modify",
"(",
"'adjust_dip'",
",",
"dict",
"(",
"increment",
"=",
"value",
... | 53.894737 | 0.001919 |
def get_layers(self, class_: Type[L], became: bool=True) -> List[L]:
"""
Proxy to stack
"""
return self.stack.get_layers(class_, became) | [
"def",
"get_layers",
"(",
"self",
",",
"class_",
":",
"Type",
"[",
"L",
"]",
",",
"became",
":",
"bool",
"=",
"True",
")",
"->",
"List",
"[",
"L",
"]",
":",
"return",
"self",
".",
"stack",
".",
"get_layers",
"(",
"class_",
",",
"became",
")"
] | 32.8 | 0.02381 |
def session(self):
""" Returns the current db session """
if not self.__session:
self.__session = dal.get_default_session()
return self.__session | [
"def",
"session",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"__session",
":",
"self",
".",
"__session",
"=",
"dal",
".",
"get_default_session",
"(",
")",
"return",
"self",
".",
"__session"
] | 35.4 | 0.01105 |
def address_to_ip(address):
"""Convert a hostname to a numerical IP addresses in an address.
This should be a no-op if address already contains an actual numerical IP
address.
Args:
address: This can be either a string containing a hostname (or an IP
address) and a port or it can b... | [
"def",
"address_to_ip",
"(",
"address",
")",
":",
"address_parts",
"=",
"address",
".",
"split",
"(",
"\":\"",
")",
"ip_address",
"=",
"socket",
".",
"gethostbyname",
"(",
"address_parts",
"[",
"0",
"]",
")",
"# Make sure localhost isn't resolved to the loopback ip"... | 36.25 | 0.001344 |
def generate_header_signature(secret, payload, request_type):
'''Authorize a client based on encrypting the payload with the client
secret, timestamp, and other metadata
'''
# Use the payload to generate a digest push|collection|name|tag|user
timestamp = generate_timestamp()
credential = ... | [
"def",
"generate_header_signature",
"(",
"secret",
",",
"payload",
",",
"request_type",
")",
":",
"# Use the payload to generate a digest push|collection|name|tag|user",
"timestamp",
"=",
"generate_timestamp",
"(",
")",
"credential",
"=",
"\"%s/%s\"",
"%",
"(",
"request_t... | 43.727273 | 0.014257 |
def split_Text( text, file_name, verbose = True ):
''' Tokenizes the *text* (from *file_name*) into sentences, and if the number of
sentences exceeds *max_sentences*, splits the text into smaller texts.
Returns a list containing the original text (if no splitting was required),
or a list c... | [
"def",
"split_Text",
"(",
"text",
",",
"file_name",
",",
"verbose",
"=",
"True",
")",
":",
"if",
"verbose",
":",
"print",
"(",
"' processing '",
"+",
"file_name",
"+",
"' ... '",
",",
"end",
"=",
"\"\"",
")",
"# Tokenize text into sentences",
"start",
"=",
... | 44.777778 | 0.027115 |
def file_upload(context, id, name, path, jobstate_id, test_id, mime):
"""file_upload(context, id, path)
Upload a file in a job
>>> dcictl job-upload-file [OPTIONS]
:param string id: ID of the job to attach file to [required]
:param string name: Name of the file [required]
:param string path: ... | [
"def",
"file_upload",
"(",
"context",
",",
"id",
",",
"name",
",",
"path",
",",
"jobstate_id",
",",
"test_id",
",",
"mime",
")",
":",
"result",
"=",
"dci_file",
".",
"create_with_stream",
"(",
"context",
",",
"name",
"=",
"name",
",",
"job_id",
"=",
"i... | 44.045455 | 0.00101 |
def parseExtensionArgs(self, args, is_openid1, strict=False):
"""Parse the provider authentication policy arguments into the
internal state of this object
@param args: unqualified provider authentication policy
arguments
@param strict: Whether to raise an exception when bad... | [
"def",
"parseExtensionArgs",
"(",
"self",
",",
"args",
",",
"is_openid1",
",",
"strict",
"=",
"False",
")",
":",
"policies_str",
"=",
"args",
".",
"get",
"(",
"'auth_policies'",
")",
"if",
"policies_str",
":",
"auth_policies",
"=",
"policies_str",
".",
"spli... | 35.090909 | 0.00084 |
def validate(self, instance, value):
"""Determine if array is valid based on shape and dtype"""
if not isinstance(value, (tuple, list, np.ndarray)):
self.error(instance, value)
if self.coerce:
value = self.wrapper(value)
valid_class = (
self.wrapper if... | [
"def",
"validate",
"(",
"self",
",",
"instance",
",",
"value",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"(",
"tuple",
",",
"list",
",",
"np",
".",
"ndarray",
")",
")",
":",
"self",
".",
"error",
"(",
"instance",
",",
"value",
")",
... | 40.52 | 0.001929 |
def merge_bams(self, input_bams, merged_bam, in_sorted="TRUE", tmp_dir=None):
"""
Combine multiple files into one.
The tmp_dir parameter is important because on poorly configured
systems, the default can sometimes fill up.
:param Iterable[str] input_bams: Paths to files to comb... | [
"def",
"merge_bams",
"(",
"self",
",",
"input_bams",
",",
"merged_bam",
",",
"in_sorted",
"=",
"\"TRUE\"",
",",
"tmp_dir",
"=",
"None",
")",
":",
"if",
"not",
"len",
"(",
"input_bams",
")",
">",
"1",
":",
"print",
"(",
"\"No merge required\"",
")",
"retu... | 39.166667 | 0.001384 |
def hardware_info(self, mask=0xFFFFFFFF):
"""Returns a list of 32 integer values corresponding to the bitfields
specifying the power consumption of the target.
The values returned by this function only have significance if the
J-Link is powering the target.
The words, indexed, ... | [
"def",
"hardware_info",
"(",
"self",
",",
"mask",
"=",
"0xFFFFFFFF",
")",
":",
"buf",
"=",
"(",
"ctypes",
".",
"c_uint32",
"*",
"32",
")",
"(",
")",
"res",
"=",
"self",
".",
"_dll",
".",
"JLINKARM_GetHWInfo",
"(",
"mask",
",",
"ctypes",
".",
"byref",... | 39.142857 | 0.001425 |
def _as_medium(exchanges, tolerance=1e-6, exports=False):
"""Convert a solution to medium.
Arguments
---------
exchanges : list of cobra.reaction
The exchange reactions to consider.
tolerance : positive double
The absolute tolerance for fluxes. Fluxes with an absolute value
... | [
"def",
"_as_medium",
"(",
"exchanges",
",",
"tolerance",
"=",
"1e-6",
",",
"exports",
"=",
"False",
")",
":",
"LOGGER",
".",
"debug",
"(",
"\"Formatting medium.\"",
")",
"medium",
"=",
"pd",
".",
"Series",
"(",
")",
"for",
"rxn",
"in",
"exchanges",
":",
... | 27.818182 | 0.001053 |
def _polytree_node_to_shapely(node):
"""
Recurses down a Clipper PolyTree, extracting the results as Shapely
objects.
Returns a tuple of (list of polygons, list of children)
"""
polygons = []
children = []
for ch in node.Childs:
p, c = _polytree_node_to_shapely(ch)
poly... | [
"def",
"_polytree_node_to_shapely",
"(",
"node",
")",
":",
"polygons",
"=",
"[",
"]",
"children",
"=",
"[",
"]",
"for",
"ch",
"in",
"node",
".",
"Childs",
":",
"p",
",",
"c",
"=",
"_polytree_node_to_shapely",
"(",
"ch",
")",
"polygons",
".",
"extend",
... | 35.096386 | 0.000668 |
def deploy_templates():
"""
Deploy any templates from your shortest TEMPLATE_DIRS setting
"""
deployed = None
if not hasattr(env, 'project_template_dir'):
#the normal pattern would mean the shortest path is the main one.
#its probably the last listed
length = 1000
... | [
"def",
"deploy_templates",
"(",
")",
":",
"deployed",
"=",
"None",
"if",
"not",
"hasattr",
"(",
"env",
",",
"'project_template_dir'",
")",
":",
"#the normal pattern would mean the shortest path is the main one.",
"#its probably the last listed",
"length",
"=",
"1000",
"fo... | 35.956522 | 0.015312 |
def ping(
self,
destination,
source=c.PING_SOURCE,
ttl=c.PING_TTL,
timeout=c.PING_TIMEOUT,
size=c.PING_SIZE,
count=c.PING_COUNT,
vrf=c.PING_VRF,
):
"""
Execute ping on the device and returns a dictionary with the result.
Output ... | [
"def",
"ping",
"(",
"self",
",",
"destination",
",",
"source",
"=",
"c",
".",
"PING_SOURCE",
",",
"ttl",
"=",
"c",
".",
"PING_TTL",
",",
"timeout",
"=",
"c",
".",
"PING_TIMEOUT",
",",
"size",
"=",
"c",
".",
"PING_SIZE",
",",
"count",
"=",
"c",
".",... | 36.960317 | 0.001255 |
def fetch(context, data):
"""Do an HTTP GET on the ``url`` specified in the inbound data."""
url = data.get('url')
attempt = data.pop('retry_attempt', 1)
try:
result = context.http.get(url, lazy=True)
rules = context.get('rules', {'match_all': {}})
if not Rule.get_rule(rules).app... | [
"def",
"fetch",
"(",
"context",
",",
"data",
")",
":",
"url",
"=",
"data",
".",
"get",
"(",
"'url'",
")",
"attempt",
"=",
"data",
".",
"pop",
"(",
"'retry_attempt'",
",",
"1",
")",
"try",
":",
"result",
"=",
"context",
".",
"http",
".",
"get",
"(... | 38.617647 | 0.000743 |
def batch_length(batch):
'''Determine the number of samples in a batch.
Parameters
----------
batch : dict
A batch dictionary. Each value must implement `len`.
All values must have the same `len`.
Returns
-------
n : int >= 0 or None
The number of samples in this b... | [
"def",
"batch_length",
"(",
"batch",
")",
":",
"n",
"=",
"None",
"for",
"value",
"in",
"six",
".",
"itervalues",
"(",
"batch",
")",
":",
"if",
"n",
"is",
"None",
":",
"n",
"=",
"len",
"(",
"value",
")",
"elif",
"len",
"(",
"value",
")",
"!=",
"... | 21.466667 | 0.001486 |
def _run_prospector(filename,
stamp_file_name,
disabled_linters,
show_lint_files):
"""Run prospector."""
linter_tools = [
"pep257",
"pep8",
"pyflakes"
]
if can_run_pylint():
linter_tools.append("pylint")
# ... | [
"def",
"_run_prospector",
"(",
"filename",
",",
"stamp_file_name",
",",
"disabled_linters",
",",
"show_lint_files",
")",
":",
"linter_tools",
"=",
"[",
"\"pep257\"",
",",
"\"pep8\"",
",",
"\"pyflakes\"",
"]",
"if",
"can_run_pylint",
"(",
")",
":",
"linter_tools",
... | 32.348837 | 0.000698 |
def save(self, collection):
"""
Save an asset collection to the service.
"""
assert isinstance(collection, predix.data.asset.AssetCollection), "Expected AssetCollection"
collection.validate()
self.put_collection(collection.uri, collection.__dict__) | [
"def",
"save",
"(",
"self",
",",
"collection",
")",
":",
"assert",
"isinstance",
"(",
"collection",
",",
"predix",
".",
"data",
".",
"asset",
".",
"AssetCollection",
")",
",",
"\"Expected AssetCollection\"",
"collection",
".",
"validate",
"(",
")",
"self",
"... | 41.428571 | 0.010135 |
def get_rec_features(self, features=None):
"""
Returns a df of features for recalled items
"""
if features is None:
features = self.dist_funcs.keys()
elif not isinstance(features, list):
features = [features]
return self.rec.applymap(lambda x: {k:v... | [
"def",
"get_rec_features",
"(",
"self",
",",
"features",
"=",
"None",
")",
":",
"if",
"features",
"is",
"None",
":",
"features",
"=",
"self",
".",
"dist_funcs",
".",
"keys",
"(",
")",
"elif",
"not",
"isinstance",
"(",
"features",
",",
"list",
")",
":",... | 41.888889 | 0.012987 |
def is_zhuyin_compatible(s):
"""Checks if *s* is consists of Zhuyin-compatible characters.
This does not check if *s* contains valid Zhuyin syllables; for that
see :func:`is_zhuyin`.
Besides Zhuyin characters and tone marks, spaces are also accepted.
This function checks that all characters in *s*... | [
"def",
"is_zhuyin_compatible",
"(",
"s",
")",
":",
"printable_zhuyin",
"=",
"zhon",
".",
"zhuyin",
".",
"characters",
"+",
"zhon",
".",
"zhuyin",
".",
"marks",
"+",
"' '",
"return",
"_is_pattern_match",
"(",
"'[%s]+'",
"%",
"printable_zhuyin",
",",
"s",
")"
... | 41 | 0.001835 |
def write(self, oprot):
'''
Write this object to the given output protocol and return self.
:type oprot: thryft.protocol._output_protocol._OutputProtocol
:rtype: pastpy.gen.database.impl.online.online_database_object_detail_image.OnlineDatabaseObjectDetailImage
'''
opro... | [
"def",
"write",
"(",
"self",
",",
"oprot",
")",
":",
"oprot",
".",
"write_struct_begin",
"(",
"'OnlineDatabaseObjectDetailImage'",
")",
"oprot",
".",
"write_field_begin",
"(",
"name",
"=",
"'full_size_url'",
",",
"type",
"=",
"11",
",",
"id",
"=",
"None",
")... | 32.906977 | 0.002059 |
def generic_in(self, **kwargs):
'''Bypass buggy GenericReferenceField querying issue'''
query = {}
for key, value in kwargs.items():
if not value:
continue
# Optimize query for when there is only one value
if isinstance(value, (list, tuple)) an... | [
"def",
"generic_in",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"query",
"=",
"{",
"}",
"for",
"key",
",",
"value",
"in",
"kwargs",
".",
"items",
"(",
")",
":",
"if",
"not",
"value",
":",
"continue",
"# Optimize query for when there is only one value"... | 50 | 0.001635 |
def expires_at(self):
"""
A :py:obj:`~datetime.datetime` of when this signature expires, if a signature expiration date is specified.
Otherwise, ``None``
"""
if 'SignatureExpirationTime' in self._signature.subpackets:
expd = next(iter(self._signature.subpackets['Signa... | [
"def",
"expires_at",
"(",
"self",
")",
":",
"if",
"'SignatureExpirationTime'",
"in",
"self",
".",
"_signature",
".",
"subpackets",
":",
"expd",
"=",
"next",
"(",
"iter",
"(",
"self",
".",
"_signature",
".",
"subpackets",
"[",
"'SignatureExpirationTime'",
"]",
... | 44.555556 | 0.00978 |
def main():
"""
This example demonstrates how to generate pretty equations from the analytic
expressions found in ``chempy.kinetics.integrated``.
"""
t, kf, t0, major, minor, prod, beta = sympy.symbols(
't k_f t0 Y Z X beta', negative=False)
for f in funcs:
args = [t, kf, prod, m... | [
"def",
"main",
"(",
")",
":",
"t",
",",
"kf",
",",
"t0",
",",
"major",
",",
"minor",
",",
"prod",
",",
"beta",
"=",
"sympy",
".",
"symbols",
"(",
"'t k_f t0 Y Z X beta'",
",",
"negative",
"=",
"False",
")",
"for",
"f",
"in",
"funcs",
":",
"args",
... | 47.578947 | 0.002169 |
def makeService(opt):
"""Make a service
:params opt: dictionary-like object with 'freq', 'config' and 'messages'
:returns: twisted.application.internet.TimerService that at opt['freq']
checks for stale processes in opt['config'], and sends
restart messages through opt['messages'... | [
"def",
"makeService",
"(",
"opt",
")",
":",
"restarter",
",",
"path",
"=",
"parseConfig",
"(",
"opt",
")",
"now",
"=",
"time",
".",
"time",
"(",
")",
"checker",
"=",
"functools",
".",
"partial",
"(",
"check",
",",
"path",
",",
"now",
")",
"beatcheck"... | 41.866667 | 0.001558 |
def _get_host_libc_from_host_compiler(self):
"""Locate the host's libc-dev installation using a specified host compiler's search dirs."""
compiler_exe = self.get_options().host_compiler
# Implicitly, we are passing in the environment of the executing pants process to
# `get_compiler_library_dirs()`.
... | [
"def",
"_get_host_libc_from_host_compiler",
"(",
"self",
")",
":",
"compiler_exe",
"=",
"self",
".",
"get_options",
"(",
")",
".",
"host_compiler",
"# Implicitly, we are passing in the environment of the executing pants process to",
"# `get_compiler_library_dirs()`.",
"# These dire... | 50.08 | 0.008621 |
def _add_person_to_group(person, group):
""" Call datastores after adding a person to a group. """
from karaage.datastores import add_accounts_to_group
from karaage.datastores import add_accounts_to_project
from karaage.datastores import add_accounts_to_institute
a_list = person.account_set
add... | [
"def",
"_add_person_to_group",
"(",
"person",
",",
"group",
")",
":",
"from",
"karaage",
".",
"datastores",
"import",
"add_accounts_to_group",
"from",
"karaage",
".",
"datastores",
"import",
"add_accounts_to_project",
"from",
"karaage",
".",
"datastores",
"import",
... | 44.666667 | 0.001828 |
def doc_type(self, *doc_type, **kwargs):
"""
Set the type to search through. You can supply a single value or
multiple. Values can be strings or subclasses of ``Document``.
You can also pass in any keyword arguments, mapping a doc_type to a
callback that should be used instead o... | [
"def",
"doc_type",
"(",
"self",
",",
"*",
"doc_type",
",",
"*",
"*",
"kwargs",
")",
":",
"# .doc_type() resets",
"s",
"=",
"self",
".",
"_clone",
"(",
")",
"if",
"not",
"doc_type",
"and",
"not",
"kwargs",
":",
"s",
".",
"_doc_type",
"=",
"[",
"]",
... | 33.6 | 0.002315 |
def parse_instancepath(parser, event, node):
#pylint: disable=unused-argument
"""Parse the CIM/XML INSTANCEPATH element and return an
instancname
<!ELEMENT INSTANCEPATH (NAMESPACEPATH, INSTANCENAME)>
"""
(next_event, next_node) = six.next(parser)
if not _is_start(next_event, next_no... | [
"def",
"parse_instancepath",
"(",
"parser",
",",
"event",
",",
"node",
")",
":",
"#pylint: disable=unused-argument",
"(",
"next_event",
",",
"next_node",
")",
"=",
"six",
".",
"next",
"(",
"parser",
")",
"if",
"not",
"_is_start",
"(",
"next_event",
",",
"nex... | 30.037037 | 0.002389 |
def getByteStatistic(self, wanInterfaceId=1, timeout=1):
"""Execute GetTotalBytesSent&GetTotalBytesReceived actions to get WAN statistics.
:param int wanInterfaceId: the id of the WAN device
:param float timeout: the timeout to wait for the action to be executed
:return: a tuple of two ... | [
"def",
"getByteStatistic",
"(",
"self",
",",
"wanInterfaceId",
"=",
"1",
",",
"timeout",
"=",
"1",
")",
":",
"namespace",
"=",
"Wan",
".",
"getServiceType",
"(",
"\"getByteStatistic\"",
")",
"+",
"str",
"(",
"wanInterfaceId",
")",
"uri",
"=",
"self",
".",
... | 50.0625 | 0.008578 |
def f_df_nc(self,x):
'''
Wrapper of the derivative of *f*: takes an input x with size of the not
fixed dimensions expands it and evaluates the gradient of the entire function.
'''
x = np.atleast_2d(x)
xx = self.context_manager._expand_vector(x)
f_nocontext_xx , df... | [
"def",
"f_df_nc",
"(",
"self",
",",
"x",
")",
":",
"x",
"=",
"np",
".",
"atleast_2d",
"(",
"x",
")",
"xx",
"=",
"self",
".",
"context_manager",
".",
"_expand_vector",
"(",
"x",
")",
"f_nocontext_xx",
",",
"df_nocontext_xx",
"=",
"self",
".",
"f_df",
... | 48 | 0.014315 |
def confirms(self, txid):
"""Returns number of confirms or None if unpublished."""
txid = deserialize.txid(txid)
return self.service.confirms(txid) | [
"def",
"confirms",
"(",
"self",
",",
"txid",
")",
":",
"txid",
"=",
"deserialize",
".",
"txid",
"(",
"txid",
")",
"return",
"self",
".",
"service",
".",
"confirms",
"(",
"txid",
")"
] | 42 | 0.011696 |
def wait_for_tasks(self, tasks):
"""Given the service instance si and tasks, it returns after all the
tasks are complete
"""
property_collector = self.service_instance.RetrieveContent().propertyCollector
task_list = [str(task) for task in tasks]
# Create filter
obj_... | [
"def",
"wait_for_tasks",
"(",
"self",
",",
"tasks",
")",
":",
"property_collector",
"=",
"self",
".",
"service_instance",
".",
"RetrieveContent",
"(",
")",
".",
"propertyCollector",
"task_list",
"=",
"[",
"str",
"(",
"task",
")",
"for",
"task",
"in",
"tasks"... | 47.777778 | 0.002279 |
def triads(reference_labels, estimated_labels):
"""Compare chords along triad (root & quality to #5) relationships.
Examples
--------
>>> (ref_intervals,
... ref_labels) = mir_eval.io.load_labeled_intervals('ref.lab')
>>> (est_intervals,
... est_labels) = mir_eval.io.load_labeled_interval... | [
"def",
"triads",
"(",
"reference_labels",
",",
"estimated_labels",
")",
":",
"validate",
"(",
"reference_labels",
",",
"estimated_labels",
")",
"ref_roots",
",",
"ref_semitones",
"=",
"encode_many",
"(",
"reference_labels",
",",
"False",
")",
"[",
":",
"2",
"]",... | 37.76087 | 0.000561 |
def astra_algorithm(direction, ndim, vol_id, sino_id, proj_id, impl):
"""Create an ASTRA algorithm object to run the projector.
Parameters
----------
direction : {'forward', 'backward'}
For ``'forward'``, apply the forward projection, for ``'backward'``
the backprojection.
ndim : {2... | [
"def",
"astra_algorithm",
"(",
"direction",
",",
"ndim",
",",
"vol_id",
",",
"sino_id",
",",
"proj_id",
",",
"impl",
")",
":",
"if",
"direction",
"not",
"in",
"(",
"'forward'",
",",
"'backward'",
")",
":",
"raise",
"ValueError",
"(",
"\"`direction` '{}' not ... | 37.150943 | 0.000495 |
def ser_iuwt_recomposition(in1, scale_adjust, smoothed_array):
"""
This function calls the a trous algorithm code to recompose the input into a single array. This is the
implementation of the isotropic undecimated wavelet transform recomposition for a single CPU core.
INPUTS:
in1 (no de... | [
"def",
"ser_iuwt_recomposition",
"(",
"in1",
",",
"scale_adjust",
",",
"smoothed_array",
")",
":",
"wavelet_filter",
"=",
"(",
"1.",
"/",
"16",
")",
"*",
"np",
".",
"array",
"(",
"[",
"1",
",",
"4",
",",
"6",
",",
"4",
",",
"1",
"]",
")",
"# Filter... | 44.378378 | 0.010131 |
def get_devices(filename, bundled):
"""Get a Devices object from a file.
:param filename: full path of the file to parse or name of the resource.
:param is_resource: boolean indicating if it is a resource.
:rtype: Devices
"""
loader = Loader(filename, bundled)
data = loader.data
devi... | [
"def",
"get_devices",
"(",
"filename",
",",
"bundled",
")",
":",
"loader",
"=",
"Loader",
"(",
"filename",
",",
"bundled",
")",
"data",
"=",
"loader",
".",
"data",
"devices",
"=",
"Devices",
"(",
")",
"# Iterate through the resources and generate each individual d... | 31.586207 | 0.001059 |
def dragEnterEvent( self, event ):
"""
Processes the drag drop event using the filter set by the \
setDragDropFilter
:param event | <QDragEvent>
"""
filt = self.dragDropFilter()
if ( not filt ):
super(XCalendarWidget, self).dragE... | [
"def",
"dragEnterEvent",
"(",
"self",
",",
"event",
")",
":",
"filt",
"=",
"self",
".",
"dragDropFilter",
"(",
")",
"if",
"(",
"not",
"filt",
")",
":",
"super",
"(",
"XCalendarWidget",
",",
"self",
")",
".",
"dragEnterEvent",
"(",
"event",
")",
"return... | 29.307692 | 0.022901 |
def common_mean_watson(Data1, Data2, NumSims=5000, print_result=True, plot='no', save=False, save_folder='.', fmt='svg'):
"""
Conduct a Watson V test for a common mean on two directional data sets.
This function calculates Watson's V statistic from input files through
Monte Carlo simulation in order to... | [
"def",
"common_mean_watson",
"(",
"Data1",
",",
"Data2",
",",
"NumSims",
"=",
"5000",
",",
"print_result",
"=",
"True",
",",
"plot",
"=",
"'no'",
",",
"save",
"=",
"False",
",",
"save_folder",
"=",
"'.'",
",",
"fmt",
"=",
"'svg'",
")",
":",
"pars_1",
... | 41.552147 | 0.001154 |
def bitmap_pattern_to_list(self, bmp_pat):
"""
takes a list of bitmap points (drawn via Life screen)
and converts to a list of full coordinates
"""
res = []
x = 1
y = 1
lines = bmp_pat.split('\n')
for line in lines:
y += 1
... | [
"def",
"bitmap_pattern_to_list",
"(",
"self",
",",
"bmp_pat",
")",
":",
"res",
"=",
"[",
"]",
"x",
"=",
"1",
"y",
"=",
"1",
"lines",
"=",
"bmp_pat",
".",
"split",
"(",
"'\\n'",
")",
"for",
"line",
"in",
"lines",
":",
"y",
"+=",
"1",
"for",
"char"... | 27.1875 | 0.011111 |
def subj_has_perm(self, subj_str, perm_str):
"""Returns:
bool: ``True`` if ``subj_str`` has perm equal to or higher than ``perm_str``.
"""
self._assert_valid_permission(perm_str)
return perm_str in self.get_effective_perm_list(subj_str) | [
"def",
"subj_has_perm",
"(",
"self",
",",
"subj_str",
",",
"perm_str",
")",
":",
"self",
".",
"_assert_valid_permission",
"(",
"perm_str",
")",
"return",
"perm_str",
"in",
"self",
".",
"get_effective_perm_list",
"(",
"subj_str",
")"
] | 33.875 | 0.010791 |
def connected_emulators(self, host=enums.JLinkHost.USB):
"""Returns a list of all the connected emulators.
Args:
self (JLink): the ``JLink`` instance
host (int): host type to search (default: ``JLinkHost.USB``)
Returns:
List of ``JLinkConnectInfo`` specifying the ... | [
"def",
"connected_emulators",
"(",
"self",
",",
"host",
"=",
"enums",
".",
"JLinkHost",
".",
"USB",
")",
":",
"res",
"=",
"self",
".",
"_dll",
".",
"JLINKARM_EMU_GetList",
"(",
"host",
",",
"0",
",",
"0",
")",
"if",
"res",
"<",
"0",
":",
"raise",
"... | 33.416667 | 0.002424 |
def most_frequent_terms(self, depth):
"""
Get the X most frequent terms in the text, and then probe down to get
any other terms that have the same count as the last term.
Args:
depth (int): The number of terms.
Returns:
set: The set of frequent terms.
... | [
"def",
"most_frequent_terms",
"(",
"self",
",",
"depth",
")",
":",
"counts",
"=",
"self",
".",
"term_counts",
"(",
")",
"# Get the top X terms and the instance count of the last word.",
"top_terms",
"=",
"set",
"(",
"list",
"(",
"counts",
".",
"keys",
"(",
")",
... | 33.08 | 0.00235 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.