text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def to_string(self, obj):
"""
Picks up an object and transforms it
into a string, by coercing each element
in an iterable to a string and then joining
them, or by trying to coerce the object directly
"""
try:
converted = [str(element) for element in ob... | [
"def",
"to_string",
"(",
"self",
",",
"obj",
")",
":",
"try",
":",
"converted",
"=",
"[",
"str",
"(",
"element",
")",
"for",
"element",
"in",
"obj",
"]",
"string",
"=",
"','",
".",
"join",
"(",
"converted",
")",
"except",
"TypeError",
":",
"# for now... | 33.857143 | 10.571429 |
def write(to, _vars, _secrets, path, env, y):
"""Writes data to specific source"""
_vars = split_vars(_vars)
_secrets = split_vars(_secrets)
loader = importlib.import_module("dynaconf.loaders.{}_loader".format(to))
if to in EXTS:
# Lets write to a file
path = Path(path)
if... | [
"def",
"write",
"(",
"to",
",",
"_vars",
",",
"_secrets",
",",
"path",
",",
"env",
",",
"y",
")",
":",
"_vars",
"=",
"split_vars",
"(",
"_vars",
")",
"_secrets",
"=",
"split_vars",
"(",
"_secrets",
")",
"loader",
"=",
"importlib",
".",
"import_module",... | 36.462687 | 19 |
def from_(self, win_pts):
"""Reverse of :meth:`to_`."""
# make relative to center pixel to convert from window
# graphics space to standard X/Y coordinate space
win_pts = np.asarray(win_pts, dtype=np.float)
has_z = (win_pts.shape[-1] > 2)
ctr_pt = list(self.viewer.get_ce... | [
"def",
"from_",
"(",
"self",
",",
"win_pts",
")",
":",
"# make relative to center pixel to convert from window",
"# graphics space to standard X/Y coordinate space",
"win_pts",
"=",
"np",
".",
"asarray",
"(",
"win_pts",
",",
"dtype",
"=",
"np",
".",
"float",
")",
"has... | 29.652174 | 17.26087 |
def _get_secrets_to_compare(old_baseline, new_baseline):
"""
:rtype: list(tuple)
:param: tuple is in the following format:
filename: str; filename where identified secret is found
secret: dict; PotentialSecret json representation
is_secret_removed: bool; has the secret been removed f... | [
"def",
"_get_secrets_to_compare",
"(",
"old_baseline",
",",
"new_baseline",
")",
":",
"def",
"_check_string",
"(",
"a",
",",
"b",
")",
":",
"if",
"a",
"==",
"b",
":",
"return",
"0",
"if",
"a",
"<",
"b",
":",
"return",
"-",
"1",
"return",
"1",
"def",
... | 30.434783 | 18.173913 |
def pb2dict(obj):
"""
Takes a ProtoBuf Message obj and convertes it to a dict.
"""
adict = {}
if not obj.IsInitialized():
return None
for field in obj.DESCRIPTOR.fields:
if not getattr(obj, field.name):
continue
if not field.label == FD.LABEL_REPEATED:
... | [
"def",
"pb2dict",
"(",
"obj",
")",
":",
"adict",
"=",
"{",
"}",
"if",
"not",
"obj",
".",
"IsInitialized",
"(",
")",
":",
"return",
"None",
"for",
"field",
"in",
"obj",
".",
"DESCRIPTOR",
".",
"fields",
":",
"if",
"not",
"getattr",
"(",
"obj",
",",
... | 34.25 | 14.916667 |
def _prt_edge(dag_edge, attr):
"""Print edge attribute"""
# sequence parent_graph points attributes type parent_edge_list
print("Edge {ATTR}: {VAL}".format(ATTR=attr, VAL=dag_edge.obj_dict[attr])) | [
"def",
"_prt_edge",
"(",
"dag_edge",
",",
"attr",
")",
":",
"# sequence parent_graph points attributes type parent_edge_list",
"print",
"(",
"\"Edge {ATTR}: {VAL}\"",
".",
"format",
"(",
"ATTR",
"=",
"attr",
",",
"VAL",
"=",
"dag_edge",
".",
"obj_dict",
"[",
"attr",... | 54.25 | 20.75 |
def v2_runner_on_ok(self, result, **kwargs):
"""Run when a task finishes correctly."""
failed = "failed" in result._result
unreachable = "unreachable" in result._result
if (
"print_action" in result._task.tags
or failed
or unreachable
or s... | [
"def",
"v2_runner_on_ok",
"(",
"self",
",",
"result",
",",
"*",
"*",
"kwargs",
")",
":",
"failed",
"=",
"\"failed\"",
"in",
"result",
".",
"_result",
"unreachable",
"=",
"\"unreachable\"",
"in",
"result",
".",
"_result",
"if",
"(",
"\"print_action\"",
"in",
... | 35.714286 | 16.125 |
def build(self, polygons):
"""
Build a BSP tree out of `polygons`. When called on an existing tree, the
new polygons are filtered down to the bottom of the tree and become new
nodes there. Each set of polygons is partitioned using the first polygon
(no heuristic is used to pick a... | [
"def",
"build",
"(",
"self",
",",
"polygons",
")",
":",
"if",
"len",
"(",
"polygons",
")",
"==",
"0",
":",
"return",
"if",
"not",
"self",
".",
"plane",
":",
"self",
".",
"plane",
"=",
"polygons",
"[",
"0",
"]",
".",
"plane",
".",
"clone",
"(",
... | 39.758621 | 14.448276 |
def build_weights(realizations, imt_dt):
"""
:returns: an array with the realization weights of shape (R, M)
"""
arr = numpy.zeros((len(realizations), len(imt_dt.names)))
for m, imt in enumerate(imt_dt.names):
arr[:, m] = [rlz.weight[imt] for rlz in realizations]
return arr | [
"def",
"build_weights",
"(",
"realizations",
",",
"imt_dt",
")",
":",
"arr",
"=",
"numpy",
".",
"zeros",
"(",
"(",
"len",
"(",
"realizations",
")",
",",
"len",
"(",
"imt_dt",
".",
"names",
")",
")",
")",
"for",
"m",
",",
"imt",
"in",
"enumerate",
"... | 37.375 | 12.125 |
def jinja2_output_as_string(impact_report, component_key):
"""Get a given jinja2 component output as string.
Useful for composing complex document.
:param impact_report: Impact Report that contains the component key.
:type impact_report: safe.report.impact_report.ImpactReport
:param component_key... | [
"def",
"jinja2_output_as_string",
"(",
"impact_report",
",",
"component_key",
")",
":",
"metadata",
"=",
"impact_report",
".",
"metadata",
"for",
"c",
"in",
"metadata",
".",
"components",
":",
"if",
"c",
".",
"key",
"==",
"component_key",
":",
"if",
"c",
"."... | 35.388889 | 18.222222 |
def _caching_enabled(self):
"""Returns True if caching is enabled per configuration, false otherwise."""
try:
config = self._runtime.get_configuration()
parameter_id = Id('parameter:useCachingForQualifierIds@json')
if config.get_value_by_parameter(parameter_id).get_bo... | [
"def",
"_caching_enabled",
"(",
"self",
")",
":",
"try",
":",
"config",
"=",
"self",
".",
"_runtime",
".",
"get_configuration",
"(",
")",
"parameter_id",
"=",
"Id",
"(",
"'parameter:useCachingForQualifierIds@json'",
")",
"if",
"config",
".",
"get_value_by_paramete... | 44 | 19.090909 |
def ranges_intersect(rset):
"""
Recursively calls the range_intersect() - pairwise version.
>>> ranges_intersect([(48, 65), (45, 55), (50, 56)])
[50, 55]
"""
if not rset:
return None
a = rset[0]
for b in rset[1:]:
if not a:
return None
a = range_inte... | [
"def",
"ranges_intersect",
"(",
"rset",
")",
":",
"if",
"not",
"rset",
":",
"return",
"None",
"a",
"=",
"rset",
"[",
"0",
"]",
"for",
"b",
"in",
"rset",
"[",
"1",
":",
"]",
":",
"if",
"not",
"a",
":",
"return",
"None",
"a",
"=",
"range_intersect"... | 19.352941 | 21.352941 |
def export(self, path, variables_saver=None):
"""Exports to SavedModel directory.
Args:
path: path where to export the SavedModel to.
variables_saver: lambda that receives a directory path where to
export checkpoints of variables.
"""
# Operate on a copy of self._proto since it need... | [
"def",
"export",
"(",
"self",
",",
"path",
",",
"variables_saver",
"=",
"None",
")",
":",
"# Operate on a copy of self._proto since it needs to be modified.",
"proto",
"=",
"saved_model_pb2",
".",
"SavedModel",
"(",
")",
"proto",
".",
"CopyFrom",
"(",
"self",
".",
... | 36.25 | 14.25 |
def _calc_F_guess(self, alpha, predictions, theta, weights):
"""Calculate an estimate of the F-measure based on the scores"""
num = np.sum(predictions.T * theta * weights, axis=1)
den = np.sum((1 - alpha) * theta * weights + \
alpha * predictions.T * weights, axis=1)
... | [
"def",
"_calc_F_guess",
"(",
"self",
",",
"alpha",
",",
"predictions",
",",
"theta",
",",
"weights",
")",
":",
"num",
"=",
"np",
".",
"sum",
"(",
"predictions",
".",
"T",
"*",
"theta",
"*",
"weights",
",",
"axis",
"=",
"1",
")",
"den",
"=",
"np",
... | 47 | 13.444444 |
def edit(self, pid=None):
"""Edit deposit.
#. The signal :data:`invenio_records.signals.before_record_update`
is sent before the edit execution.
#. The following meta information are saved inside the deposit:
.. code-block:: python
deposit['_deposit']['pid'] = ... | [
"def",
"edit",
"(",
"self",
",",
"pid",
"=",
"None",
")",
":",
"pid",
"=",
"pid",
"or",
"self",
".",
"pid",
"with",
"db",
".",
"session",
".",
"begin_nested",
"(",
")",
":",
"before_record_update",
".",
"send",
"(",
"current_app",
".",
"_get_current_ob... | 33.533333 | 21.644444 |
def bacpypes_debugging(obj):
"""Function for attaching a debugging logger to a class or function."""
# create a logger for this object
logger = logging.getLogger(obj.__module__ + '.' + obj.__name__)
# make it available to instances
obj._logger = logger
obj._debug = logger.debug
obj._info = ... | [
"def",
"bacpypes_debugging",
"(",
"obj",
")",
":",
"# create a logger for this object",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"obj",
".",
"__module__",
"+",
"'.'",
"+",
"obj",
".",
"__name__",
")",
"# make it available to instances",
"obj",
".",
"_logge... | 31 | 14.933333 |
def store_psm_protein_relations(fn, header, pgdb, proteins):
"""Reads PSMs from file, extracts their proteins and peptides and passes
them to a database backend in chunks.
"""
# TODO do we need an OrderedDict or is regular dict enough?
# Sorting for psm_id useful?
allpsms = OrderedDict()
las... | [
"def",
"store_psm_protein_relations",
"(",
"fn",
",",
"header",
",",
"pgdb",
",",
"proteins",
")",
":",
"# TODO do we need an OrderedDict or is regular dict enough?",
"# Sorting for psm_id useful?",
"allpsms",
"=",
"OrderedDict",
"(",
")",
"last_id",
",",
"psmids_to_store",... | 39.896552 | 11.655172 |
def nss(prediction, fix):
"""
Compute the normalized scanpath salience
input:
fix : list, l[0] contains y, l[1] contains x
"""
prediction = prediction - np.mean(prediction)
prediction = prediction / np.std(prediction)
return np.mean(prediction[fix[0], fix[1]]) | [
"def",
"nss",
"(",
"prediction",
",",
"fix",
")",
":",
"prediction",
"=",
"prediction",
"-",
"np",
".",
"mean",
"(",
"prediction",
")",
"prediction",
"=",
"prediction",
"/",
"np",
".",
"std",
"(",
"prediction",
")",
"return",
"np",
".",
"mean",
"(",
... | 26.181818 | 14.909091 |
def _decompose_slice(key, size):
""" convert a slice to successive two slices. The first slice always has
a positive step.
"""
start, stop, step = key.indices(size)
if step > 0:
# If key already has a positive step, use it as is in the backend
return key, slice(None)
else:
... | [
"def",
"_decompose_slice",
"(",
"key",
",",
"size",
")",
":",
"start",
",",
"stop",
",",
"step",
"=",
"key",
".",
"indices",
"(",
"size",
")",
"if",
"step",
">",
"0",
":",
"# If key already has a positive step, use it as is in the backend",
"return",
"key",
",... | 40.142857 | 13.5 |
def use_plenary_authorization_view(self):
"""Pass through to provider AuthorizationLookupSession.use_plenary_authorization_view"""
self._object_views['authorization'] = PLENARY
# self._get_provider_session('authorization_lookup_session') # To make sure the session is tracked
for session ... | [
"def",
"use_plenary_authorization_view",
"(",
"self",
")",
":",
"self",
".",
"_object_views",
"[",
"'authorization'",
"]",
"=",
"PLENARY",
"# self._get_provider_session('authorization_lookup_session') # To make sure the session is tracked",
"for",
"session",
"in",
"self",
".",
... | 52.777778 | 17.666667 |
def getPeersCustomFilter(self, filterFunc):
'''
getPeersCustomFilter - Get elements who share a parent with this element and also pass a custom filter check
@param filterFunc <lambda/function> - Passed in an element, and returns True if it should be treated as a match, otherwise Fal... | [
"def",
"getPeersCustomFilter",
"(",
"self",
",",
"filterFunc",
")",
":",
"peers",
"=",
"self",
".",
"peers",
"if",
"peers",
"is",
"None",
":",
"return",
"None",
"return",
"TagCollection",
"(",
"[",
"peer",
"for",
"peer",
"in",
"peers",
"if",
"filterFunc",
... | 43.923077 | 38.384615 |
def get_metrics_rollups_queue(self, name, queue_name, metric):
'''
This operation gets rollup data for Service Bus metrics queue.
Rollup data includes the time granularity for the telemetry aggregation as well as
the retention settings for each time granularity.
name:
... | [
"def",
"get_metrics_rollups_queue",
"(",
"self",
",",
"name",
",",
"queue_name",
",",
"metric",
")",
":",
"response",
"=",
"self",
".",
"_perform_get",
"(",
"self",
".",
"_get_get_metrics_rollup_queue_path",
"(",
"name",
",",
"queue_name",
",",
"metric",
")",
... | 35.625 | 23.625 |
def find_field(browser, field_type, value):
"""
Locate an input field.
:param browser: ``world.browser``
:param string field_type: a field type (i.e. `button`)
:param string value: an id, name or label
This first looks for `value` as the id of the element, else
the name of the element, els... | [
"def",
"find_field",
"(",
"browser",
",",
"field_type",
",",
"value",
")",
":",
"return",
"find_field_by_id",
"(",
"browser",
",",
"field_type",
",",
"value",
")",
"+",
"find_field_by_name",
"(",
"browser",
",",
"field_type",
",",
"value",
")",
"+",
"find_fi... | 34.9375 | 16.1875 |
def package_install(name, **kwargs):
'''
Install a "package" on the REST server
'''
DETAILS = _load_state()
if kwargs.get('version', False):
version = kwargs['version']
else:
version = '1.0'
DETAILS['packages'][name] = version
_save_state(DETAILS)
return {name: versio... | [
"def",
"package_install",
"(",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"DETAILS",
"=",
"_load_state",
"(",
")",
"if",
"kwargs",
".",
"get",
"(",
"'version'",
",",
"False",
")",
":",
"version",
"=",
"kwargs",
"[",
"'version'",
"]",
"else",
":",
"ve... | 25.916667 | 14.416667 |
def middle_end(self, index):
"""
Set the index (+1) where MIDDLE ends.
:param int index: the new index for MIDDLE end
"""
if (index < 0) or (index > self.all_length):
raise ValueError(u"The given index is not valid")
self.__middle_end = index | [
"def",
"middle_end",
"(",
"self",
",",
"index",
")",
":",
"if",
"(",
"index",
"<",
"0",
")",
"or",
"(",
"index",
">",
"self",
".",
"all_length",
")",
":",
"raise",
"ValueError",
"(",
"u\"The given index is not valid\"",
")",
"self",
".",
"__middle_end",
... | 32.777778 | 12.333333 |
def account_status(request):
"""
Set following ``RequestContext`` variables:
* ``ACCOUNT_EXPIRED = boolean``, account was expired state,
* ``ACCOUNT_NOT_ACTIVE = boolean``, set when account is not expired, but it is over quotas so it is
not active
* ``EXPI... | [
"def",
"account_status",
"(",
"request",
")",
":",
"if",
"request",
".",
"user",
".",
"is_authenticated",
":",
"try",
":",
"return",
"{",
"'ACCOUNT_EXPIRED'",
":",
"request",
".",
"user",
".",
"userplan",
".",
"is_expired",
"(",
")",
",",
"'ACCOUNT_NOT_ACTIV... | 41.192308 | 24.115385 |
def __get_ws_distance(wstation, latitude, longitude):
"""Get the distance to the weatherstation from wstation section of json.
wstation: weerstation section of buienradar json (dict)
latitude: our latitude
longitude: our longitude
"""
if wstation:
try:
wslat = float(wstation... | [
"def",
"__get_ws_distance",
"(",
"wstation",
",",
"latitude",
",",
"longitude",
")",
":",
"if",
"wstation",
":",
"try",
":",
"wslat",
"=",
"float",
"(",
"wstation",
"[",
"__LAT",
"]",
")",
"wslon",
"=",
"float",
"(",
"wstation",
"[",
"__LON",
"]",
")",... | 35.590909 | 17.636364 |
def get_certificate_issuer_config(self, **kwargs): # noqa: E501
"""Get certificate issuer configuration. # noqa: E501
Provides the configured certificate issuer to be used when creating device certificates for LwM2M communication.<br> # noqa: E501
This method makes a synchronous HTTP reques... | [
"def",
"get_certificate_issuer_config",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'asynchronous'",
")",
":",
"return",
"self",
".",
"get_certif... | 50.4 | 24.85 |
def unpacktar(tarfile, destdir):
""" Unpack given tarball into the specified dir """
nullfd = open(os.devnull, "w")
tarfile = cygpath(os.path.abspath(tarfile))
log.debug("unpack tar %s into %s", tarfile, destdir)
try:
check_call([TAR, '-xzf', tarfile], cwd=destdir,
stdout=... | [
"def",
"unpacktar",
"(",
"tarfile",
",",
"destdir",
")",
":",
"nullfd",
"=",
"open",
"(",
"os",
".",
"devnull",
",",
"\"w\"",
")",
"tarfile",
"=",
"cygpath",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"tarfile",
")",
")",
"log",
".",
"debug",
"("... | 39.083333 | 16.833333 |
def _reg(self, name, dtype=BIT, defVal=None, clk=None, rst=None):
"""
Create register in this unit
:param defVal: default value of this register,
if this value is specified reset of this component is used
(unit has to have single interface of class Rst or Rst_n)
... | [
"def",
"_reg",
"(",
"self",
",",
"name",
",",
"dtype",
"=",
"BIT",
",",
"defVal",
"=",
"None",
",",
"clk",
"=",
"None",
",",
"rst",
"=",
"None",
")",
":",
"if",
"clk",
"is",
"None",
":",
"clk",
"=",
"getClk",
"(",
"self",
")",
"if",
"defVal",
... | 36.282051 | 14.641026 |
def _make_autoenv(self, action):
""" Generate a suitable env variable for this action. This is
dependant on our subcommand hierarchy. Review the prog setter for
details. """
env = ('%s_%s' % (self.prog, action.dest)).upper()
env = re.sub(self.env_scrub_re, '', env.strip())
... | [
"def",
"_make_autoenv",
"(",
"self",
",",
"action",
")",
":",
"env",
"=",
"(",
"'%s_%s'",
"%",
"(",
"self",
".",
"prog",
",",
"action",
".",
"dest",
")",
")",
".",
"upper",
"(",
")",
"env",
"=",
"re",
".",
"sub",
"(",
"self",
".",
"env_scrub_re",... | 43.636364 | 11.636364 |
def validate(self, value, model=None, context=None):
""" Perform validation """
from boiler.user.services import role_service
self_id = None
if model:
if isinstance(model, dict):
self_id = model.get('id')
else:
self_id = getattr(mo... | [
"def",
"validate",
"(",
"self",
",",
"value",
",",
"model",
"=",
"None",
",",
"context",
"=",
"None",
")",
":",
"from",
"boiler",
".",
"user",
".",
"services",
"import",
"role_service",
"self_id",
"=",
"None",
"if",
"model",
":",
"if",
"isinstance",
"(... | 30.1875 | 16.4375 |
def get_jids():
'''
Return a list of all job ids
'''
query = '''SELECT jid, load FROM {keyspace}.jids;'''.format(keyspace=_get_keyspace())
ret = {}
# cassandra_cql.cql_query may raise a CommandExecutionError
try:
data = __salt__['cassandra_cql.cql_query'](query)
if data:
... | [
"def",
"get_jids",
"(",
")",
":",
"query",
"=",
"'''SELECT jid, load FROM {keyspace}.jids;'''",
".",
"format",
"(",
"keyspace",
"=",
"_get_keyspace",
"(",
")",
")",
"ret",
"=",
"{",
"}",
"# cassandra_cql.cql_query may raise a CommandExecutionError",
"try",
":",
"data"... | 29.928571 | 22.857143 |
def transform_assign_magic(line):
"""Handle the `a = %who` syntax."""
m = _assign_magic_re.match(line)
if m is not None:
cmd = m.group('cmd')
lhs = m.group('lhs')
new_line = '%s = get_ipython().magic(%r)' % (lhs, cmd)
return new_line
return line | [
"def",
"transform_assign_magic",
"(",
"line",
")",
":",
"m",
"=",
"_assign_magic_re",
".",
"match",
"(",
"line",
")",
"if",
"m",
"is",
"not",
"None",
":",
"cmd",
"=",
"m",
".",
"group",
"(",
"'cmd'",
")",
"lhs",
"=",
"m",
".",
"group",
"(",
"'lhs'"... | 31.666667 | 13.111111 |
def post_send_process(context):
"""
Task to ensure subscription is bumped or converted
"""
if "error" in context:
return context
[deserialized_subscription] = serializers.deserialize(
"json", context["subscription"]
)
subscription = deserialized_subscription.object
[mess... | [
"def",
"post_send_process",
"(",
"context",
")",
":",
"if",
"\"error\"",
"in",
"context",
":",
"return",
"context",
"[",
"deserialized_subscription",
"]",
"=",
"serializers",
".",
"deserialize",
"(",
"\"json\"",
",",
"context",
"[",
"\"subscription\"",
"]",
")",... | 40.647059 | 16.764706 |
def zip2bytes(compressed):
"""
UNZIP DATA
"""
if hasattr(compressed, "read"):
return gzip.GzipFile(fileobj=compressed, mode='r')
buff = BytesIO(compressed)
archive = gzip.GzipFile(fileobj=buff, mode='r')
from pyLibrary.env.big_data import safe_size
return safe_size(archive) | [
"def",
"zip2bytes",
"(",
"compressed",
")",
":",
"if",
"hasattr",
"(",
"compressed",
",",
"\"read\"",
")",
":",
"return",
"gzip",
".",
"GzipFile",
"(",
"fileobj",
"=",
"compressed",
",",
"mode",
"=",
"'r'",
")",
"buff",
"=",
"BytesIO",
"(",
"compressed",... | 27.727273 | 13 |
def fitness(self, width, height):
"""
In guillotine algorithm case, returns the min of the fitness of all
free sections, for the given dimension, both normal and rotated
(if rotation enabled.)
"""
assert(width > 0 and height > 0)
# Get best fitness section.
... | [
"def",
"fitness",
"(",
"self",
",",
"width",
",",
"height",
")",
":",
"assert",
"(",
"width",
">",
"0",
"and",
"height",
">",
"0",
")",
"# Get best fitness section.",
"section",
",",
"rotated",
"=",
"self",
".",
"_select_fittest_section",
"(",
"width",
","... | 37.052632 | 19.052632 |
def _get_jenks_config():
""" retrieve the jenks configuration object """
config_file = (get_configuration_file() or
os.path.expanduser(os.path.join("~", CONFIG_FILE_NAME)))
if not os.path.exists(config_file):
open(config_file, 'w').close()
with open(config_file, 'r') as fh:
... | [
"def",
"_get_jenks_config",
"(",
")",
":",
"config_file",
"=",
"(",
"get_configuration_file",
"(",
")",
"or",
"os",
".",
"path",
".",
"expanduser",
"(",
"os",
".",
"path",
".",
"join",
"(",
"\"~\"",
",",
"CONFIG_FILE_NAME",
")",
")",
")",
"if",
"not",
... | 34.076923 | 16.923077 |
def compute(self, activeInput, predictedActiveInput, learn):
"""
Computes one cycle of the Union Temporal Pooler algorithm.
@param activeInput (numpy array) A numpy array of 0's and 1's that comprises the input to the union pooler
@param predictedActiveInput (numpy array) A numpy array of 0... | [
"def",
"compute",
"(",
"self",
",",
"activeInput",
",",
"predictedActiveInput",
",",
"learn",
")",
":",
"assert",
"numpy",
".",
"size",
"(",
"activeInput",
")",
"==",
"self",
".",
"getNumInputs",
"(",
")",
"assert",
"numpy",
".",
"size",
"(",
"predictedAct... | 48.507463 | 29.432836 |
def create_item(self, item):
"""
Create a new item in D4S2 service for item at the specified destination.
:param item: D4S2Item data to use for creating a D4S2 item
:return: requests.Response containing the successful result
"""
item_dict = {
'project_id': ite... | [
"def",
"create_item",
"(",
"self",
",",
"item",
")",
":",
"item_dict",
"=",
"{",
"'project_id'",
":",
"item",
".",
"project_id",
",",
"'from_user_id'",
":",
"item",
".",
"from_user_id",
",",
"'to_user_id'",
":",
"item",
".",
"to_user_id",
",",
"'role'",
":... | 41.157895 | 15.578947 |
def send(self, email=None):
""" send email message """
if email is None and self.send_as_one:
self.smtp.send_message(
self.multipart, self.config['EMAIL'], self.addresses)
elif email is not None and self.send_as_one is False:
self.smtp.send_message(
... | [
"def",
"send",
"(",
"self",
",",
"email",
"=",
"None",
")",
":",
"if",
"email",
"is",
"None",
"and",
"self",
".",
"send_as_one",
":",
"self",
".",
"smtp",
".",
"send_message",
"(",
"self",
".",
"multipart",
",",
"self",
".",
"config",
"[",
"'EMAIL'",... | 47.555556 | 12.555556 |
def migrate(settings_module,
app_label=None,
migration_name=None,
bin_env=None,
database=None,
pythonpath=None,
env=None,
noinput=True,
runas=None):
'''
Run migrate
Execute the Django-Admin migrate command (requires Dja... | [
"def",
"migrate",
"(",
"settings_module",
",",
"app_label",
"=",
"None",
",",
"migration_name",
"=",
"None",
",",
"bin_env",
"=",
"None",
",",
"database",
"=",
"None",
",",
"pythonpath",
"=",
"None",
",",
"env",
"=",
"None",
",",
"noinput",
"=",
"True",
... | 30.404255 | 25.297872 |
def configure_volume(before_change=lambda: None, after_change=lambda: None):
'''Set up storage (or don't) according to the charm's volume configuration.
Returns the mount point or "ephemeral". before_change and after_change
are optional functions to be called if the volume configuration changes.
'... | [
"def",
"configure_volume",
"(",
"before_change",
"=",
"lambda",
":",
"None",
",",
"after_change",
"=",
"lambda",
":",
"None",
")",
":",
"config",
"=",
"get_config",
"(",
")",
"if",
"not",
"config",
":",
"hookenv",
".",
"log",
"(",
"'Failed to read volume con... | 36.483871 | 18.741935 |
def _preprocess_successor(self, state, add_guard=True): #pylint:disable=unused-argument
"""
Preprocesses the successor state.
:param state: the successor state
"""
# Next, simplify what needs to be simplified
if o.SIMPLIFY_EXIT_STATE in state.options:
state.... | [
"def",
"_preprocess_successor",
"(",
"self",
",",
"state",
",",
"add_guard",
"=",
"True",
")",
":",
"#pylint:disable=unused-argument",
"# Next, simplify what needs to be simplified",
"if",
"o",
".",
"SIMPLIFY_EXIT_STATE",
"in",
"state",
".",
"options",
":",
"state",
"... | 42.918919 | 22.324324 |
def to_dict(self):
"""Converts this object to an (ordered) dictionary of field-value pairs.
>>> m = MRZ(['IDAUT10000999<6<<<<<<<<<<<<<<<', '7109094F1112315AUT<<<<<<<<<<<6', 'MUSTERFRAU<<ISOLDE<<<<<<<<<<<<']).to_dict()
>>> assert m['type'] == 'ID' and m['country'] == 'AUT' and m['number'] == '10... | [
"def",
"to_dict",
"(",
"self",
")",
":",
"result",
"=",
"OrderedDict",
"(",
")",
"result",
"[",
"'mrz_type'",
"]",
"=",
"self",
".",
"mrz_type",
"result",
"[",
"'valid_score'",
"]",
"=",
"self",
".",
"valid_score",
"if",
"self",
".",
"mrz_type",
"is",
... | 51.977778 | 19.422222 |
async def create_sentinel_pool(sentinels, *, db=None, password=None,
encoding=None, minsize=1, maxsize=10,
ssl=None, parser=None, timeout=0.2, loop=None):
"""Create SentinelPool."""
# FIXME: revise default timeout value
assert isinstance(sentinel... | [
"async",
"def",
"create_sentinel_pool",
"(",
"sentinels",
",",
"*",
",",
"db",
"=",
"None",
",",
"password",
"=",
"None",
",",
"encoding",
"=",
"None",
",",
"minsize",
"=",
"1",
",",
"maxsize",
"=",
"10",
",",
"ssl",
"=",
"None",
",",
"parser",
"=",
... | 39.55 | 11.75 |
def get_node(conn, name):
'''
Return a node for the named VM
'''
for node in conn.list_servers(per_page=1000):
if node['name'] == name:
return node | [
"def",
"get_node",
"(",
"conn",
",",
"name",
")",
":",
"for",
"node",
"in",
"conn",
".",
"list_servers",
"(",
"per_page",
"=",
"1000",
")",
":",
"if",
"node",
"[",
"'name'",
"]",
"==",
"name",
":",
"return",
"node"
] | 25.285714 | 17.285714 |
async def lookup_entities(client, args):
"""Search for entities by phone number, email, or gaia_id."""
lookup_spec = _get_lookup_spec(args.entity_identifier)
request = hangups.hangouts_pb2.GetEntityByIdRequest(
request_header=client.get_request_header(),
batch_lookup_spec=[lookup_spec],
... | [
"async",
"def",
"lookup_entities",
"(",
"client",
",",
"args",
")",
":",
"lookup_spec",
"=",
"_get_lookup_spec",
"(",
"args",
".",
"entity_identifier",
")",
"request",
"=",
"hangups",
".",
"hangouts_pb2",
".",
"GetEntityByIdRequest",
"(",
"request_header",
"=",
... | 40.230769 | 12.153846 |
def summary(self, prn=None, lfilter=None):
"""prints a summary of each SndRcv packet pair
prn: function to apply to each packet pair instead of lambda s, r: "%s ==> %s" % (s.summary(),r.summary())
lfilter: truth function to apply to each packet pair to decide whether it will be displayed"""
for s, r... | [
"def",
"summary",
"(",
"self",
",",
"prn",
"=",
"None",
",",
"lfilter",
"=",
"None",
")",
":",
"for",
"s",
",",
"r",
"in",
"self",
".",
"res",
":",
"if",
"lfilter",
"is",
"not",
"None",
":",
"if",
"not",
"lfilter",
"(",
"s",
",",
"r",
")",
":... | 45.75 | 12.583333 |
def _encode_uuid(name, value, dummy, opts):
"""Encode uuid.UUID."""
uuid_representation = opts.uuid_representation
# Python Legacy Common Case
if uuid_representation == OLD_UUID_SUBTYPE:
return b"\x05" + name + b'\x10\x00\x00\x00\x03' + value.bytes
# Java Legacy
elif uuid_representation ... | [
"def",
"_encode_uuid",
"(",
"name",
",",
"value",
",",
"dummy",
",",
"opts",
")",
":",
"uuid_representation",
"=",
"opts",
".",
"uuid_representation",
"# Python Legacy Common Case",
"if",
"uuid_representation",
"==",
"OLD_UUID_SUBTYPE",
":",
"return",
"b\"\\x05\"",
... | 41.111111 | 16.055556 |
def is_in_bounds(self, x):
"""not yet tested"""
if self.bounds is None:
return True
for ib in [0, 1]:
if self.bounds[ib] is None:
continue
for i in rglen(x):
idx = min([i, len(self.bounds[ib]) - 1])
if self.bound... | [
"def",
"is_in_bounds",
"(",
"self",
",",
"x",
")",
":",
"if",
"self",
".",
"bounds",
"is",
"None",
":",
"return",
"True",
"for",
"ib",
"in",
"[",
"0",
",",
"1",
"]",
":",
"if",
"self",
".",
"bounds",
"[",
"ib",
"]",
"is",
"None",
":",
"continue... | 35.692308 | 13.692308 |
def topics_in(self, d, topn=5):
"""
List the top ``topn`` topics in document ``d``.
"""
return self.theta.features[d].top(topn) | [
"def",
"topics_in",
"(",
"self",
",",
"d",
",",
"topn",
"=",
"5",
")",
":",
"return",
"self",
".",
"theta",
".",
"features",
"[",
"d",
"]",
".",
"top",
"(",
"topn",
")"
] | 31 | 6.2 |
def thaw(vault_client, src_file, opt):
"""Given the combination of a Secretfile and the output of
a freeze operation, will restore secrets to usable locations"""
if not os.path.exists(src_file):
raise aomi.exceptions.AomiFile("%s does not exist" % src_file)
tmp_dir = ensure_tmpdir()
zip_fil... | [
"def",
"thaw",
"(",
"vault_client",
",",
"src_file",
",",
"opt",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"src_file",
")",
":",
"raise",
"aomi",
".",
"exceptions",
".",
"AomiFile",
"(",
"\"%s does not exist\"",
"%",
"src_file",
")",
... | 42.111111 | 13.722222 |
def namePop(ctxt):
"""Pops the top element name from the name stack """
if ctxt is None: ctxt__o = None
else: ctxt__o = ctxt._o
ret = libxml2mod.namePop(ctxt__o)
return ret | [
"def",
"namePop",
"(",
"ctxt",
")",
":",
"if",
"ctxt",
"is",
"None",
":",
"ctxt__o",
"=",
"None",
"else",
":",
"ctxt__o",
"=",
"ctxt",
".",
"_o",
"ret",
"=",
"libxml2mod",
".",
"namePop",
"(",
"ctxt__o",
")",
"return",
"ret"
] | 31.166667 | 11.5 |
def accpro20_summary(self, cutoff):
"""Parse the ACCpro output file and return a summary of percent exposed/buried residues based on a cutoff.
Below the cutoff = buried
Equal to or greater than cutoff = exposed
The default cutoff used in accpro is 25%.
The output file is just a... | [
"def",
"accpro20_summary",
"(",
"self",
",",
"cutoff",
")",
":",
"summary",
"=",
"{",
"}",
"if",
"cutoff",
"<",
"1",
":",
"cutoff",
"=",
"1",
"*",
"100",
"records",
"=",
"read_accpro20",
"(",
"self",
".",
"out_accpro20",
")",
"for",
"k",
",",
"v",
... | 28.780488 | 23.292683 |
def matrix(self):
""":obj:`numpy.ndarray` of float: The canonical 4x4 matrix
representation of this transform.
The first three columns contain the columns of the rotation matrix
followed by a zero, and the last column contains the translation vector
followed by a one.
""... | [
"def",
"matrix",
"(",
"self",
")",
":",
"return",
"np",
".",
"r_",
"[",
"np",
".",
"c_",
"[",
"self",
".",
"_rotation",
",",
"self",
".",
"_translation",
"]",
",",
"[",
"[",
"0",
",",
"0",
",",
"0",
",",
"1",
"]",
"]",
"]"
] | 43.222222 | 20.666667 |
def offset_mode(data):
"""Compute Mode using a histogram with `sqrt(data.size)` bins"""
nbins = int(np.ceil(np.sqrt(data.size)))
mind, maxd = data.min(), data.max()
histo = np.histogram(data, nbins, density=True, range=(mind, maxd))
dx = abs(histo[1][1] - histo[1][2]) / 2
hx = histo[1][1:] - dx
... | [
"def",
"offset_mode",
"(",
"data",
")",
":",
"nbins",
"=",
"int",
"(",
"np",
".",
"ceil",
"(",
"np",
".",
"sqrt",
"(",
"data",
".",
"size",
")",
")",
")",
"mind",
",",
"maxd",
"=",
"data",
".",
"min",
"(",
")",
",",
"data",
".",
"max",
"(",
... | 37.5 | 12.9 |
def complete_rule(rule, cmd):
'''complete using one rule'''
global rline_mpstate
rule_components = rule.split(' ')
# complete the empty string (e.g "graph <TAB><TAB>")
if len(cmd) == 0:
return rule_expand(rule_components[0], "")
# check it matches so far
for i in range(len(cmd)-1)... | [
"def",
"complete_rule",
"(",
"rule",
",",
"cmd",
")",
":",
"global",
"rline_mpstate",
"rule_components",
"=",
"rule",
".",
"split",
"(",
"' '",
")",
"# complete the empty string (e.g \"graph <TAB><TAB>\")",
"if",
"len",
"(",
"cmd",
")",
"==",
"0",
":",
"return"... | 29.705882 | 17.941176 |
def mouseGestureHandler(self, info):
"""This is the callback for MouseClickContext. Passed to VideoWidget as a parameter
"""
print(self.pre, ": mouseGestureHandler: ")
# *** single click events ***
if (info.fsingle):
print(self.pre, ": mouseGestureHandler: single cli... | [
"def",
"mouseGestureHandler",
"(",
"self",
",",
"info",
")",
":",
"print",
"(",
"self",
".",
"pre",
",",
"\": mouseGestureHandler: \"",
")",
"# *** single click events ***",
"if",
"(",
"info",
".",
"fsingle",
")",
":",
"print",
"(",
"self",
".",
"pre",
",",
... | 48.086957 | 15.26087 |
def ignore(self, matcher):
'''
Unblock and ignore the matched events, if any.
'''
events = self.eventtree.findAndRemove(matcher)
for e in events:
self.queue.unblock(e)
e.canignore = True | [
"def",
"ignore",
"(",
"self",
",",
"matcher",
")",
":",
"events",
"=",
"self",
".",
"eventtree",
".",
"findAndRemove",
"(",
"matcher",
")",
"for",
"e",
"in",
"events",
":",
"self",
".",
"queue",
".",
"unblock",
"(",
"e",
")",
"e",
".",
"canignore",
... | 30.625 | 16.875 |
def replace(self, year=None, month=None, day=None):
"""
Returns a new datetime.date or asn1crypto.util.extended_date
object with the specified components replaced
:return:
A datetime.date or asn1crypto.util.extended_date object
"""
if year is None:
... | [
"def",
"replace",
"(",
"self",
",",
"year",
"=",
"None",
",",
"month",
"=",
"None",
",",
"day",
"=",
"None",
")",
":",
"if",
"year",
"is",
"None",
":",
"year",
"=",
"self",
".",
"year",
"if",
"month",
"is",
"None",
":",
"month",
"=",
"self",
".... | 22.961538 | 20.884615 |
def version(self):
"""Returns the device's version.
The device's version is returned as a string of the format: M.mr where
``M`` is major number, ``m`` is minor number, and ``r`` is revision
character.
Args:
self (JLink): the ``JLink`` instance
Returns:
... | [
"def",
"version",
"(",
"self",
")",
":",
"version",
"=",
"int",
"(",
"self",
".",
"_dll",
".",
"JLINKARM_GetDLLVersion",
"(",
")",
")",
"major",
"=",
"version",
"/",
"10000",
"minor",
"=",
"(",
"version",
"/",
"100",
")",
"%",
"100",
"rev",
"=",
"v... | 31.789474 | 19.421053 |
def get_column_list_prefixed(self):
"""
Returns a list of columns
"""
return map(
lambda x: ".".join([self.name, x]),
self.columns
) | [
"def",
"get_column_list_prefixed",
"(",
"self",
")",
":",
"return",
"map",
"(",
"lambda",
"x",
":",
"\".\"",
".",
"join",
"(",
"[",
"self",
".",
"name",
",",
"x",
"]",
")",
",",
"self",
".",
"columns",
")"
] | 24.125 | 10.375 |
def setProp(self, name, value):
"""Set (or reset) an attribute carried by a node. If @name has
a prefix, then the corresponding namespace-binding will be
used, if in scope; it is an error it there's no such
ns-binding for the prefix in scope. """
ret = libxml2mod.xmlSetPro... | [
"def",
"setProp",
"(",
"self",
",",
"name",
",",
"value",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlSetProp",
"(",
"self",
".",
"_o",
",",
"name",
",",
"value",
")",
"if",
"ret",
"is",
"None",
":",
"raise",
"treeError",
"(",
"'xmlSetProp() failed'",... | 50.222222 | 13.777778 |
def warn(msg, level=0, prefix=True):
"""Prints the specified message as a warning; prepends "WARNING" to
the message, so that can be left off.
"""
if will_print(level):
printer(("WARNING: " if prefix else "") + msg, "yellow") | [
"def",
"warn",
"(",
"msg",
",",
"level",
"=",
"0",
",",
"prefix",
"=",
"True",
")",
":",
"if",
"will_print",
"(",
"level",
")",
":",
"printer",
"(",
"(",
"\"WARNING: \"",
"if",
"prefix",
"else",
"\"\"",
")",
"+",
"msg",
",",
"\"yellow\"",
")"
] | 40.666667 | 7.333333 |
async def fetchrow(self, *, timeout=None):
r"""Return the next row.
:param float timeout: Optional timeout value in seconds.
:return: A :class:`Record` instance.
"""
self._check_ready()
if self._exhausted:
return None
recs = await self._exec(1, timeo... | [
"async",
"def",
"fetchrow",
"(",
"self",
",",
"*",
",",
"timeout",
"=",
"None",
")",
":",
"self",
".",
"_check_ready",
"(",
")",
"if",
"self",
".",
"_exhausted",
":",
"return",
"None",
"recs",
"=",
"await",
"self",
".",
"_exec",
"(",
"1",
",",
"tim... | 27.8 | 14.133333 |
def _should_fetch_reason_with_robots(self, request: Request) -> Tuple[bool, str]:
'''Return info whether the URL should be fetched including checking
robots.txt.
Coroutine.
'''
result = yield from \
self._fetch_rule.check_initial_web_request(self._item_session, reque... | [
"def",
"_should_fetch_reason_with_robots",
"(",
"self",
",",
"request",
":",
"Request",
")",
"->",
"Tuple",
"[",
"bool",
",",
"str",
"]",
":",
"result",
"=",
"yield",
"from",
"self",
".",
"_fetch_rule",
".",
"check_initial_web_request",
"(",
"self",
".",
"_i... | 37.444444 | 29 |
def phonetic_fingerprint(
phrase, phonetic_algorithm=double_metaphone, joiner=' ', *args, **kwargs
):
"""Return the phonetic fingerprint of a phrase.
This is a wrapper for :py:meth:`Phonetic.fingerprint`.
Parameters
----------
phrase : str
The string from which to calculate the phoneti... | [
"def",
"phonetic_fingerprint",
"(",
"phrase",
",",
"phonetic_algorithm",
"=",
"double_metaphone",
",",
"joiner",
"=",
"' '",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"Phonetic",
"(",
")",
".",
"fingerprint",
"(",
"phrase",
",",
"phone... | 31.05 | 22.95 |
def create_assessment(self, assessment_form):
"""Creates a new ``Assessment``.
arg: assessment_form (osid.assessment.AssessmentForm): the
form for this ``Assessment``
return: (osid.assessment.Assessment) - the new ``Assessment``
raise: IllegalState - ``assessment_for... | [
"def",
"create_assessment",
"(",
"self",
",",
"assessment_form",
")",
":",
"# Implemented from template for",
"# osid.resource.ResourceAdminSession.create_resource_template",
"collection",
"=",
"JSONClientValidated",
"(",
"'assessment'",
",",
"collection",
"=",
"'Assessment'",
... | 51.186047 | 24.27907 |
def get_blob(self, index):
"""Return a blob with the event at the given index"""
self.log.info("Retrieving blob #{}".format(index))
if index > len(self.event_offsets) - 1:
self.log.info("Index not in cache, caching offsets")
self._cache_offsets(index, verbose=False)
... | [
"def",
"get_blob",
"(",
"self",
",",
"index",
")",
":",
"self",
".",
"log",
".",
"info",
"(",
"\"Retrieving blob #{}\"",
".",
"format",
"(",
"index",
")",
")",
"if",
"index",
">",
"len",
"(",
"self",
".",
"event_offsets",
")",
"-",
"1",
":",
"self",
... | 41.294118 | 12.411765 |
def _compensate_humidity(self, adc_h):
"""Compensate humidity.
Formula from datasheet Bosch BME280 Environmental sensor.
8.1 Compensation formulas in double precision floating point
Edition BST-BME280-DS001-10 | Revision 1.1 | May 2015.
"""
var_h = self._temp_fine - 7680... | [
"def",
"_compensate_humidity",
"(",
"self",
",",
"adc_h",
")",
":",
"var_h",
"=",
"self",
".",
"_temp_fine",
"-",
"76800.0",
"if",
"var_h",
"==",
"0",
":",
"return",
"0",
"var_h",
"=",
"(",
"(",
"adc_h",
"-",
"(",
"self",
".",
"_calibration_h",
"[",
... | 36.25 | 21.333333 |
def newick_replace_otuids(tree, biomf):
"""
Replace the OTU ids in the Newick phylogenetic tree format with truncated
OTU names
"""
for val, id_, md in biomf.iter(axis="observation"):
otu_loc = find_otu(id_, tree)
if otu_loc is not None:
tree = tree[:otu_loc] + \
... | [
"def",
"newick_replace_otuids",
"(",
"tree",
",",
"biomf",
")",
":",
"for",
"val",
",",
"id_",
",",
"md",
"in",
"biomf",
".",
"iter",
"(",
"axis",
"=",
"\"observation\"",
")",
":",
"otu_loc",
"=",
"find_otu",
"(",
"id_",
",",
"tree",
")",
"if",
"otu_... | 34.333333 | 11.166667 |
def insertVariantAnnotationSet(self, variantAnnotationSet):
"""
Inserts a the specified variantAnnotationSet into this repository.
"""
analysisJson = json.dumps(
protocol.toJsonDict(variantAnnotationSet.getAnalysis()))
try:
models.Variantannotationset.crea... | [
"def",
"insertVariantAnnotationSet",
"(",
"self",
",",
"variantAnnotationSet",
")",
":",
"analysisJson",
"=",
"json",
".",
"dumps",
"(",
"protocol",
".",
"toJsonDict",
"(",
"variantAnnotationSet",
".",
"getAnalysis",
"(",
")",
")",
")",
"try",
":",
"models",
"... | 50.578947 | 18.473684 |
def close(self):
""" Close a Circuit Breaker #TODO Check
"""
self.grid._graph.add_edge(self.branch_nodes[0], self.branch_nodes[1], branch=self.branch)
self.status = 'closed' | [
"def",
"close",
"(",
"self",
")",
":",
"self",
".",
"grid",
".",
"_graph",
".",
"add_edge",
"(",
"self",
".",
"branch_nodes",
"[",
"0",
"]",
",",
"self",
".",
"branch_nodes",
"[",
"1",
"]",
",",
"branch",
"=",
"self",
".",
"branch",
")",
"self",
... | 40.2 | 18.2 |
def goldstein_price(theta):
"""Goldstein-Price function"""
x, y = theta
obj = (1 + (x + y + 1) ** 2 * (19 - 14 * x + 3 * x ** 2 - 14 * y + 6 * x * y + 3 * y ** 2)) * \
(30 + (2 * x - 3 * y) ** 2 *
(18 - 32 * x + 12 * x ** 2 + 48 * y - 36 * x * y + 27 * x ** 2))
grad = np.array([
... | [
"def",
"goldstein_price",
"(",
"theta",
")",
":",
"x",
",",
"y",
"=",
"theta",
"obj",
"=",
"(",
"1",
"+",
"(",
"x",
"+",
"y",
"+",
"1",
")",
"**",
"2",
"*",
"(",
"19",
"-",
"14",
"*",
"x",
"+",
"3",
"*",
"x",
"**",
"2",
"-",
"14",
"*",
... | 55.636364 | 27.454545 |
def EncoderLayer(feature_depth,
feedforward_depth,
num_heads,
dropout,
mode):
"""Transformer encoder layer.
The input to the encoder is a pair (embedded source, mask) where
the mask is created from the original source to prevent attending
to t... | [
"def",
"EncoderLayer",
"(",
"feature_depth",
",",
"feedforward_depth",
",",
"num_heads",
",",
"dropout",
",",
"mode",
")",
":",
"# The encoder block expects (activation, mask) as input and returns",
"# the new activations only, we add the mask back to output next.",
"encoder_block",
... | 37.552632 | 19.657895 |
def _generate_url_root(protocol, host, port):
"""
Generate API root URL without resources
:param protocol: Web protocol [HTTP | HTTPS] (string)
:param host: Hostname or IP (string)
:param port: Service port (string)
:return: ROOT url
"""
return URL_ROOT_PA... | [
"def",
"_generate_url_root",
"(",
"protocol",
",",
"host",
",",
"port",
")",
":",
"return",
"URL_ROOT_PATTERN",
".",
"format",
"(",
"protocol",
"=",
"protocol",
",",
"host",
"=",
"host",
",",
"port",
"=",
"port",
")"
] | 40.555556 | 10.333333 |
def variable(self, var_name, shape, init, dt=tf.float32, train=None):
"""Adds a named variable to this bookkeeper or returns an existing one.
Variables marked train are returned by the training_variables method. If
the requested name already exists and it is compatible (same shape, dt and
train) then i... | [
"def",
"variable",
"(",
"self",
",",
"var_name",
",",
"shape",
",",
"init",
",",
"dt",
"=",
"tf",
".",
"float32",
",",
"train",
"=",
"None",
")",
":",
"# Make sure it is a TF dtype and convert it into a base dtype.",
"dt",
"=",
"tf",
".",
"as_dtype",
"(",
"d... | 42.018519 | 20.462963 |
def rescale(inlist, newrange=(0, 1)):
"""
rescale the values in a list between the values in newrange (a tuple with the new minimum and maximum)
"""
OldMax = max(inlist)
OldMin = min(inlist)
if OldMin == OldMax:
raise RuntimeError('list contains of only one unique value')
O... | [
"def",
"rescale",
"(",
"inlist",
",",
"newrange",
"=",
"(",
"0",
",",
"1",
")",
")",
":",
"OldMax",
"=",
"max",
"(",
"inlist",
")",
"OldMin",
"=",
"min",
"(",
"inlist",
")",
"if",
"OldMin",
"==",
"OldMax",
":",
"raise",
"RuntimeError",
"(",
"'list ... | 34.428571 | 21.428571 |
def keyPressEvent(self, event):
"""
Listens for the enter event to check if the query is setup.
"""
if event.key() in (Qt.Key_Enter, Qt.Key_Return):
self.queryEntered.emit(self.query())
super(XOrbQuickFilterWidget, self).keyPressEvent(event) | [
"def",
"keyPressEvent",
"(",
"self",
",",
"event",
")",
":",
"if",
"event",
".",
"key",
"(",
")",
"in",
"(",
"Qt",
".",
"Key_Enter",
",",
"Qt",
".",
"Key_Return",
")",
":",
"self",
".",
"queryEntered",
".",
"emit",
"(",
"self",
".",
"query",
"(",
... | 37.75 | 14.5 |
def call(func, *args, **kwargs):
"""
:return:
a delegator function that returns a tuple (``func``, (seed tuple,)+ ``args``, ``kwargs``).
That is, seed tuple is inserted before supplied positional arguments.
By default, a thread wrapping ``func`` and all those arguments is spawned.
""... | [
"def",
"call",
"(",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"f",
"(",
"seed_tuple",
")",
":",
"return",
"func",
",",
"(",
"seed_tuple",
",",
")",
"+",
"args",
",",
"kwargs",
"return",
"f"
] | 39.6 | 22.6 |
def get_postmortem_exclusion_list(cls, bits = None):
"""
Returns the exclusion list for the postmortem debugger.
@see: L{get_postmortem_debugger}
@type bits: int
@param bits: Set to C{32} for the 32 bits debugger, or C{64} for the
64 bits debugger. Set to {None} fo... | [
"def",
"get_postmortem_exclusion_list",
"(",
"cls",
",",
"bits",
"=",
"None",
")",
":",
"if",
"bits",
"is",
"None",
":",
"bits",
"=",
"cls",
".",
"bits",
"elif",
"bits",
"not",
"in",
"(",
"32",
",",
"64",
")",
":",
"raise",
"NotImplementedError",
"(",
... | 34.6875 | 24.375 |
def enter_event_loop(self):
"""\
Main loop of the IRCConnection - reads from the socket and dispatches
based on regex matching
"""
patterns = self.dispatch_patterns()
self.logger.debug('entering receive loop')
while 1:
try:
data = self... | [
"def",
"enter_event_loop",
"(",
"self",
")",
":",
"patterns",
"=",
"self",
".",
"dispatch_patterns",
"(",
")",
"self",
".",
"logger",
".",
"debug",
"(",
"'entering receive loop'",
")",
"while",
"1",
":",
"try",
":",
"data",
"=",
"self",
".",
"_sock_file",
... | 29 | 16.48 |
def run(self):
"""Start the game loop"""
global world
self.__is_running = True
while(self.__is_running):
#Our game loop
#Catch our events
self.__handle_events()
#Update our clock
self.__clock.tick(self.preferred_fps)
... | [
"def",
"run",
"(",
"self",
")",
":",
"global",
"world",
"self",
".",
"__is_running",
"=",
"True",
"while",
"(",
"self",
".",
"__is_running",
")",
":",
"#Our game loop",
"#Catch our events",
"self",
".",
"__handle_events",
"(",
")",
"#Update our clock",
"self",... | 31.363636 | 14.909091 |
def movement(self):
""" Returns the movement of this aspect.
The movement is the one of the active object, except
if the active is separating but within less than 1
degree.
"""
mov = self.active.movement
if self.orb < 1 and mov == const.SEPARATIVE:
... | [
"def",
"movement",
"(",
"self",
")",
":",
"mov",
"=",
"self",
".",
"active",
".",
"movement",
"if",
"self",
".",
"orb",
"<",
"1",
"and",
"mov",
"==",
"const",
".",
"SEPARATIVE",
":",
"mov",
"=",
"const",
".",
"EXACT",
"return",
"mov"
] | 32.181818 | 15.272727 |
def dummytable(numrows=100,
fields=(('foo', partial(random.randint, 0, 100)),
('bar', partial(random.choice, ('apples', 'pears',
'bananas', 'oranges'))),
('baz', random.random)),
wait=0, se... | [
"def",
"dummytable",
"(",
"numrows",
"=",
"100",
",",
"fields",
"=",
"(",
"(",
"'foo'",
",",
"partial",
"(",
"random",
".",
"randint",
",",
"0",
",",
"100",
")",
")",
",",
"(",
"'bar'",
",",
"partial",
"(",
"random",
".",
"choice",
",",
"(",
"'ap... | 43.241935 | 17.951613 |
def size_tee(Q1, Q2, D, D2, n=1, pipe_diameters=5):
r'''Calculates CoV of an optimal or specified tee for mixing at a tee
according to [1]_. Assumes turbulent flow.
The smaller stream in injected into the main pipe, which continues
straight.
COV calculation is according to [2]_.
.. math::
... | [
"def",
"size_tee",
"(",
"Q1",
",",
"Q2",
",",
"D",
",",
"D2",
",",
"n",
"=",
"1",
",",
"pipe_diameters",
"=",
"5",
")",
":",
"V1",
"=",
"Q1",
"/",
"(",
"pi",
"/",
"4",
"*",
"D",
"**",
"2",
")",
"Cv",
"=",
"Q2",
"/",
"(",
"Q1",
"+",
"Q2"... | 29.439024 | 22.804878 |
def set_tag(self, namespace, repository, tag, image_id):
"""PUT /v1/repositories/(namespace)/(repository)/tags/(tag*)"""
return self._http_call(self.TAGS + '/' + tag, put, data=image_id,
namespace=namespace, repository=repository) | [
"def",
"set_tag",
"(",
"self",
",",
"namespace",
",",
"repository",
",",
"tag",
",",
"image_id",
")",
":",
"return",
"self",
".",
"_http_call",
"(",
"self",
".",
"TAGS",
"+",
"'/'",
"+",
"tag",
",",
"put",
",",
"data",
"=",
"image_id",
",",
"namespac... | 68.5 | 20.75 |
def simulate_static(self, steps, time, solution = solve_type.RK4):
"""!
@brief Performs static simulation of oscillatory network based on Hodgkin-Huxley neuron model.
@details Output dynamic is sensible to amount of steps of simulation and solver of differential equation.
P... | [
"def",
"simulate_static",
"(",
"self",
",",
"steps",
",",
"time",
",",
"solution",
"=",
"solve_type",
".",
"RK4",
")",
":",
"# Check solver before simulation\r",
"if",
"(",
"solution",
"==",
"solve_type",
".",
"FAST",
")",
":",
"raise",
"NameError",
"(",
"\"... | 52.017241 | 31.551724 |
def set_footer(self, *, text=EmptyEmbed, icon_url=EmptyEmbed):
"""Sets the footer for the embed content.
This function returns the class instance to allow for fluent-style
chaining.
Parameters
-----------
text: :class:`str`
The footer text.
icon_url:... | [
"def",
"set_footer",
"(",
"self",
",",
"*",
",",
"text",
"=",
"EmptyEmbed",
",",
"icon_url",
"=",
"EmptyEmbed",
")",
":",
"self",
".",
"_footer",
"=",
"{",
"}",
"if",
"text",
"is",
"not",
"EmptyEmbed",
":",
"self",
".",
"_footer",
"[",
"'text'",
"]",... | 27.818182 | 20.181818 |
def fake_print(self):
'''
This is the overridden __str__ method for Operation
Recursively prints out the actual query to be executed
'''
def _fake_run():
kwargs = self.kwargs.copy()
kwargs['generate'] = True
return _fake_handle_result(
getattr(self.migrator, self.... | [
"def",
"fake_print",
"(",
"self",
")",
":",
"def",
"_fake_run",
"(",
")",
":",
"kwargs",
"=",
"self",
".",
"kwargs",
".",
"copy",
"(",
")",
"kwargs",
"[",
"'generate'",
"]",
"=",
"True",
"return",
"_fake_handle_result",
"(",
"getattr",
"(",
"self",
"."... | 33.227273 | 17.954545 |
def get_preference_type(self, type, user_id, address, notification):
"""
Get a preference.
Fetch the preference for the given notification for the given communicaiton channel
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - user_id
... | [
"def",
"get_preference_type",
"(",
"self",
",",
"type",
",",
"user_id",
",",
"address",
",",
"notification",
")",
":",
"path",
"=",
"{",
"}",
"data",
"=",
"{",
"}",
"params",
"=",
"{",
"}",
"# REQUIRED - PATH - user_id\r",
"\"\"\"ID\"\"\"",
"path",
"[",
"\... | 37.964286 | 28.321429 |
def request(self, method, url, **kwargs): # pylint: disable=arguments-differ
"""
Overrides Session.request to ensure that the session is authenticated
"""
self._check_auth()
return super(OAuthAPIClient, self).request(method, url, **kwargs) | [
"def",
"request",
"(",
"self",
",",
"method",
",",
"url",
",",
"*",
"*",
"kwargs",
")",
":",
"# pylint: disable=arguments-differ",
"self",
".",
"_check_auth",
"(",
")",
"return",
"super",
"(",
"OAuthAPIClient",
",",
"self",
")",
".",
"request",
"(",
"metho... | 45.833333 | 20.166667 |
def image_delete(self, product_id, position, session):
'''taobao.fenxiao.product.image.delete 产品图片删除
产品图片删除,只删除图片信息,不真正删除图片'''
request = TOPRequest('taobao.fenxiao.product.image.delete')
request['product_id'] = product_id
request['position'] = position
self.creat... | [
"def",
"image_delete",
"(",
"self",
",",
"product_id",
",",
"position",
",",
"session",
")",
":",
"request",
"=",
"TOPRequest",
"(",
"'taobao.fenxiao.product.image.delete'",
")",
"request",
"[",
"'product_id'",
"]",
"=",
"product_id",
"request",
"[",
"'position'",... | 46.888889 | 20.666667 |
def get_client(client=None):
"""
Get an ElasticAPM client.
:param client:
:return:
:rtype: elasticapm.base.Client
"""
global _client
tmp_client = client is not None
if not tmp_client:
config = getattr(django_settings, "ELASTIC_APM", {})
client = config.get("CLIENT",... | [
"def",
"get_client",
"(",
"client",
"=",
"None",
")",
":",
"global",
"_client",
"tmp_client",
"=",
"client",
"is",
"not",
"None",
"if",
"not",
"tmp_client",
":",
"config",
"=",
"getattr",
"(",
"django_settings",
",",
"\"ELASTIC_APM\"",
",",
"{",
"}",
")",
... | 24.727273 | 16.181818 |
def list(self, options=None, **kwds):
"""
Endpoint: /photos[/<options>]/list.json
Returns a list of Photo objects.
The options parameter can be used to narrow down the list.
Eg: options={"album": <album_id>}
"""
option_string = self._build_option_string(options)
... | [
"def",
"list",
"(",
"self",
",",
"options",
"=",
"None",
",",
"*",
"*",
"kwds",
")",
":",
"option_string",
"=",
"self",
".",
"_build_option_string",
"(",
"options",
")",
"photos",
"=",
"self",
".",
"_client",
".",
"get",
"(",
"\"/photos%s/list.json\"",
"... | 41.692308 | 12.769231 |
def radrec(inrange, re, dec):
"""
Convert from range, right ascension, and declination to rectangular
coordinates.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/radrec_c.html
:param inrange: Distance of a point from the origin.
:type inrange: float
:param re: Right ascension of p... | [
"def",
"radrec",
"(",
"inrange",
",",
"re",
",",
"dec",
")",
":",
"inrange",
"=",
"ctypes",
".",
"c_double",
"(",
"inrange",
")",
"re",
"=",
"ctypes",
".",
"c_double",
"(",
"re",
")",
"dec",
"=",
"ctypes",
".",
"c_double",
"(",
"dec",
")",
"rectan"... | 33.272727 | 14.363636 |
def update_eff_ruptures(self, count_ruptures):
"""
:param count_ruptures: function or dict src_group_id -> num_ruptures
"""
for smodel in self.source_models:
for sg in smodel.src_groups:
sg.eff_ruptures = (count_ruptures(sg.id)
... | [
"def",
"update_eff_ruptures",
"(",
"self",
",",
"count_ruptures",
")",
":",
"for",
"smodel",
"in",
"self",
".",
"source_models",
":",
"for",
"sg",
"in",
"smodel",
".",
"src_groups",
":",
"sg",
".",
"eff_ruptures",
"=",
"(",
"count_ruptures",
"(",
"sg",
"."... | 45.777778 | 12.222222 |
def validate_sum(parameter_container, validation_message, **kwargs):
"""Validate the sum of parameter value's.
:param parameter_container: The container that use this validator.
:type parameter_container: ParameterContainer
:param validation_message: The message if there is validation error.
:type... | [
"def",
"validate_sum",
"(",
"parameter_container",
",",
"validation_message",
",",
"*",
"*",
"kwargs",
")",
":",
"parameters",
"=",
"parameter_container",
".",
"get_parameters",
"(",
"False",
")",
"values",
"=",
"[",
"]",
"for",
"parameter",
"in",
"parameters",
... | 32.574468 | 20.404255 |
async def findArtifactFromTask(self, *args, **kwargs):
"""
Get Artifact From Indexed Task
Find a task by index path and redirect to the artifact on the most recent
run with the given `name`.
Note that multiple calls to this endpoint may return artifacts from differen tasks
... | [
"async",
"def",
"findArtifactFromTask",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"await",
"self",
".",
"_makeApiCall",
"(",
"self",
".",
"funcinfo",
"[",
"\"findArtifactFromTask\"",
"]",
",",
"*",
"args",
",",
"*",
"*",... | 51.782609 | 36.478261 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.