repo stringlengths 7 54 | path stringlengths 4 192 | url stringlengths 87 284 | code stringlengths 78 104k | code_tokens list | docstring stringlengths 1 46.9k | docstring_tokens list | language stringclasses 1
value | partition stringclasses 3
values |
|---|---|---|---|---|---|---|---|---|
Kappa-Dev/KaSim | python/kappy/kappa_common.py | https://github.com/Kappa-Dev/KaSim/blob/12a01c616a47e3046323103625795fb2fca8273a/python/kappy/kappa_common.py#L72-L77 | def toJSON(self):
"""Get a json dict of the attributes of this object."""
return {"id": self.id,
"compile": self.compile,
"position": self.position,
"version": self.version} | [
"def",
"toJSON",
"(",
"self",
")",
":",
"return",
"{",
"\"id\"",
":",
"self",
".",
"id",
",",
"\"compile\"",
":",
"self",
".",
"compile",
",",
"\"position\"",
":",
"self",
".",
"position",
",",
"\"version\"",
":",
"self",
".",
"version",
"}"
] | Get a json dict of the attributes of this object. | [
"Get",
"a",
"json",
"dict",
"of",
"the",
"attributes",
"of",
"this",
"object",
"."
] | python | valid |
HumanCellAtlas/cloud-blobstore | cloud_blobstore/s3.py | https://github.com/HumanCellAtlas/cloud-blobstore/blob/b8a60e8e8c0da0e39dda084cb467a34cd2d1ef0a/cloud_blobstore/s3.py#L295-L308 | def get_creation_date(
self,
bucket: str,
key: str,
) -> datetime:
"""
Retrieves the creation date for a given key in a given bucket.
:param bucket: the bucket the object resides in.
:param key: the key of the object for which the creation date is ... | [
"def",
"get_creation_date",
"(",
"self",
",",
"bucket",
":",
"str",
",",
"key",
":",
"str",
",",
")",
"->",
"datetime",
":",
"# An S3 object's creation date is stored in its LastModified field which stores the",
"# most recent value between the two.",
"return",
"self",
".",... | Retrieves the creation date for a given key in a given bucket.
:param bucket: the bucket the object resides in.
:param key: the key of the object for which the creation date is being retrieved.
:return: the creation date | [
"Retrieves",
"the",
"creation",
"date",
"for",
"a",
"given",
"key",
"in",
"a",
"given",
"bucket",
".",
":",
"param",
"bucket",
":",
"the",
"bucket",
"the",
"object",
"resides",
"in",
".",
":",
"param",
"key",
":",
"the",
"key",
"of",
"the",
"object",
... | python | train |
shoebot/shoebot | lib/graph/__init__.py | https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/graph/__init__.py#L551-L554 | def nodes_by_category(self, category):
""" Returns nodes with the given category attribute.
"""
return [n for n in self.nodes if n.category == category] | [
"def",
"nodes_by_category",
"(",
"self",
",",
"category",
")",
":",
"return",
"[",
"n",
"for",
"n",
"in",
"self",
".",
"nodes",
"if",
"n",
".",
"category",
"==",
"category",
"]"
] | Returns nodes with the given category attribute. | [
"Returns",
"nodes",
"with",
"the",
"given",
"category",
"attribute",
"."
] | python | valid |
VikParuchuri/percept | percept/utils/input.py | https://github.com/VikParuchuri/percept/blob/90304ba82053e2a9ad2bacaab3479403d3923bcf/percept/utils/input.py#L1-L11 | def import_from_string(import_string):
"""
Import a class from a string
import_string - string path to module to import using dot notation (foo.bar)
"""
import_split = import_string.split(".")
import_class = import_split[-1]
module_path = ".".join(import_split[:-1])
mod = __import__(modu... | [
"def",
"import_from_string",
"(",
"import_string",
")",
":",
"import_split",
"=",
"import_string",
".",
"split",
"(",
"\".\"",
")",
"import_class",
"=",
"import_split",
"[",
"-",
"1",
"]",
"module_path",
"=",
"\".\"",
".",
"join",
"(",
"import_split",
"[",
"... | Import a class from a string
import_string - string path to module to import using dot notation (foo.bar) | [
"Import",
"a",
"class",
"from",
"a",
"string",
"import_string",
"-",
"string",
"path",
"to",
"module",
"to",
"import",
"using",
"dot",
"notation",
"(",
"foo",
".",
"bar",
")"
] | python | train |
MisterWil/abodepy | abodepy/automation.py | https://github.com/MisterWil/abodepy/blob/6f84bb428fd1da98855f55083cd427bebbcc57ae/abodepy/automation.py#L42-L54 | def trigger(self, only_manual=True):
"""Trigger a quick-action automation."""
if not self.is_quick_action and only_manual:
raise AbodeException((ERROR.TRIGGER_NON_QUICKACTION))
url = CONST.AUTOMATION_APPLY_URL
url = url.replace(
'$AUTOMATIONID$', self.automation_... | [
"def",
"trigger",
"(",
"self",
",",
"only_manual",
"=",
"True",
")",
":",
"if",
"not",
"self",
".",
"is_quick_action",
"and",
"only_manual",
":",
"raise",
"AbodeException",
"(",
"(",
"ERROR",
".",
"TRIGGER_NON_QUICKACTION",
")",
")",
"url",
"=",
"CONST",
"... | Trigger a quick-action automation. | [
"Trigger",
"a",
"quick",
"-",
"action",
"automation",
"."
] | python | train |
bokeh/bokeh | bokeh/model.py | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/model.py#L734-L777 | def _to_json_like(self, include_defaults):
''' Returns a dictionary of the attributes of this object, in
a layout corresponding to what BokehJS expects at unmarshalling time.
This method does not convert "Bokeh types" into "plain JSON types,"
for example each child Model will still be a... | [
"def",
"_to_json_like",
"(",
"self",
",",
"include_defaults",
")",
":",
"all_attrs",
"=",
"self",
".",
"properties_with_values",
"(",
"include_defaults",
"=",
"include_defaults",
")",
"# If __subtype__ is defined, then this model may introduce properties",
"# that don't exist o... | Returns a dictionary of the attributes of this object, in
a layout corresponding to what BokehJS expects at unmarshalling time.
This method does not convert "Bokeh types" into "plain JSON types,"
for example each child Model will still be a Model, rather
than turning into a reference, n... | [
"Returns",
"a",
"dictionary",
"of",
"the",
"attributes",
"of",
"this",
"object",
"in",
"a",
"layout",
"corresponding",
"to",
"what",
"BokehJS",
"expects",
"at",
"unmarshalling",
"time",
"."
] | python | train |
annoviko/pyclustering | pyclustering/cluster/ga_maths.py | https://github.com/annoviko/pyclustering/blob/98aa0dd89fd36f701668fb1eb29c8fb5662bf7d0/pyclustering/cluster/ga_maths.py#L60-L66 | def get_centres(chromosomes, data, count_clusters):
"""!
"""
centres = ga_math.calc_centers(chromosomes, data, count_clusters)
return centres | [
"def",
"get_centres",
"(",
"chromosomes",
",",
"data",
",",
"count_clusters",
")",
":",
"centres",
"=",
"ga_math",
".",
"calc_centers",
"(",
"chromosomes",
",",
"data",
",",
"count_clusters",
")",
"return",
"centres"
] | ! | [
"!"
] | python | valid |
hearsaycorp/normalize | normalize/property/meta.py | https://github.com/hearsaycorp/normalize/blob/8b36522ddca6d41b434580bd848f3bdaa7a999c8/normalize/property/meta.py#L36-L113 | def has(selfie, self, args, kwargs):
"""This is called 'has' but is called indirectly. Each Property sub-class
is installed with this function which replaces their __new__.
It is called 'has', because it runs during property declaration, processes
the arguments and is responsible for returning an appr... | [
"def",
"has",
"(",
"selfie",
",",
"self",
",",
"args",
",",
"kwargs",
")",
":",
"if",
"args",
":",
"raise",
"exc",
".",
"PositionalArgumentsProhibited",
"(",
")",
"extra_traits",
"=",
"set",
"(",
"kwargs",
".",
"pop",
"(",
"'traits'",
",",
"tuple",
"("... | This is called 'has' but is called indirectly. Each Property sub-class
is installed with this function which replaces their __new__.
It is called 'has', because it runs during property declaration, processes
the arguments and is responsible for returning an appropriate Property
subclass. As such it i... | [
"This",
"is",
"called",
"has",
"but",
"is",
"called",
"indirectly",
".",
"Each",
"Property",
"sub",
"-",
"class",
"is",
"installed",
"with",
"this",
"function",
"which",
"replaces",
"their",
"__new__",
"."
] | python | train |
cocagne/txdbus | txdbus/client.py | https://github.com/cocagne/txdbus/blob/eb424918764b7b93eecd2a4e2e5c2d0b2944407b/txdbus/client.py#L570-L575 | def _onMethodTimeout(self, serial, d):
"""
Called when a remote method invocation timeout occurs
"""
del self._pendingCalls[serial]
d.errback(error.TimeOut('Method call timed out')) | [
"def",
"_onMethodTimeout",
"(",
"self",
",",
"serial",
",",
"d",
")",
":",
"del",
"self",
".",
"_pendingCalls",
"[",
"serial",
"]",
"d",
".",
"errback",
"(",
"error",
".",
"TimeOut",
"(",
"'Method call timed out'",
")",
")"
] | Called when a remote method invocation timeout occurs | [
"Called",
"when",
"a",
"remote",
"method",
"invocation",
"timeout",
"occurs"
] | python | train |
zeaphoo/reston | reston/core/dvm.py | https://github.com/zeaphoo/reston/blob/96502487b2259572df55237c9526f92627465088/reston/core/dvm.py#L7938-L7948 | def get_fields(self):
"""
Return all field objects
:rtype: a list of :class:`EncodedField` objects
"""
l = []
for i in self.classes.class_def:
for j in i.get_fields():
l.append(j)
return l | [
"def",
"get_fields",
"(",
"self",
")",
":",
"l",
"=",
"[",
"]",
"for",
"i",
"in",
"self",
".",
"classes",
".",
"class_def",
":",
"for",
"j",
"in",
"i",
".",
"get_fields",
"(",
")",
":",
"l",
".",
"append",
"(",
"j",
")",
"return",
"l"
] | Return all field objects
:rtype: a list of :class:`EncodedField` objects | [
"Return",
"all",
"field",
"objects"
] | python | train |
jhuapl-boss/intern | intern/remote/boss/remote.py | https://github.com/jhuapl-boss/intern/blob/d8fc6df011d8f212c87e6a1fd4cc21cfb5d103ed/intern/remote/boss/remote.py#L794-L809 | def create_metadata(self, resource, keys_vals):
"""
Associates new key-value pairs with the given resource.
Will attempt to add all key-value pairs even if some fail.
Args:
resource (intern.resource.boss.BossResource)
keys_vals (dictionary): Collection of key-va... | [
"def",
"create_metadata",
"(",
"self",
",",
"resource",
",",
"keys_vals",
")",
":",
"self",
".",
"metadata_service",
".",
"set_auth",
"(",
"self",
".",
"_token_metadata",
")",
"self",
".",
"metadata_service",
".",
"create",
"(",
"resource",
",",
"keys_vals",
... | Associates new key-value pairs with the given resource.
Will attempt to add all key-value pairs even if some fail.
Args:
resource (intern.resource.boss.BossResource)
keys_vals (dictionary): Collection of key-value pairs to assign to
given resource.
Rais... | [
"Associates",
"new",
"key",
"-",
"value",
"pairs",
"with",
"the",
"given",
"resource",
"."
] | python | train |
soravux/scoop | scoop/launch/workerLaunch.py | https://github.com/soravux/scoop/blob/d391dfa62f47e49d48328ee9cf08aa114256fd33/scoop/launch/workerLaunch.py#L80-L106 | def _WorkerCommand_environment(self):
"""Return list of shell commands to prepare the environment for
bootstrap."""
worker = self.workersArguments
c = []
if worker.prolog:
c.extend([
"source",
worker.prolog,
"&&",
... | [
"def",
"_WorkerCommand_environment",
"(",
"self",
")",
":",
"worker",
"=",
"self",
".",
"workersArguments",
"c",
"=",
"[",
"]",
"if",
"worker",
".",
"prolog",
":",
"c",
".",
"extend",
"(",
"[",
"\"source\"",
",",
"worker",
".",
"prolog",
",",
"\"&&\"",
... | Return list of shell commands to prepare the environment for
bootstrap. | [
"Return",
"list",
"of",
"shell",
"commands",
"to",
"prepare",
"the",
"environment",
"for",
"bootstrap",
"."
] | python | train |
square/connect-python-sdk | squareconnect/models/order_fulfillment_pickup_details.py | https://github.com/square/connect-python-sdk/blob/adc1d09e817986cdc607391580f71d6b48ed4066/squareconnect/models/order_fulfillment_pickup_details.py#L456-L470 | def cancel_reason(self, cancel_reason):
"""
Sets the cancel_reason of this OrderFulfillmentPickupDetails.
A description of why the pickup was canceled. Max length is 100 characters.
:param cancel_reason: The cancel_reason of this OrderFulfillmentPickupDetails.
:type: str
... | [
"def",
"cancel_reason",
"(",
"self",
",",
"cancel_reason",
")",
":",
"if",
"cancel_reason",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Invalid value for `cancel_reason`, must not be `None`\"",
")",
"if",
"len",
"(",
"cancel_reason",
")",
">",
"100",
":",
"r... | Sets the cancel_reason of this OrderFulfillmentPickupDetails.
A description of why the pickup was canceled. Max length is 100 characters.
:param cancel_reason: The cancel_reason of this OrderFulfillmentPickupDetails.
:type: str | [
"Sets",
"the",
"cancel_reason",
"of",
"this",
"OrderFulfillmentPickupDetails",
".",
"A",
"description",
"of",
"why",
"the",
"pickup",
"was",
"canceled",
".",
"Max",
"length",
"is",
"100",
"characters",
"."
] | python | train |
common-workflow-language/cwltool | cwltool/docker_id.py | https://github.com/common-workflow-language/cwltool/blob/cb81b22abc52838823da9945f04d06739ab32fda/cwltool/docker_id.py#L109-L120 | def docker_machine_id(): # type: () -> Tuple[Optional[int], Optional[int]]
"""
Asks docker-machine for active machine and gets the UID of the docker user
inside the vm
:return: tuple (UID, GID), or (None, None) if error (e.g. docker-machine not present or stopped)
"""
machine_name = docker_mach... | [
"def",
"docker_machine_id",
"(",
")",
":",
"# type: () -> Tuple[Optional[int], Optional[int]]",
"machine_name",
"=",
"docker_machine_name",
"(",
")",
"if",
"not",
"machine_name",
":",
"return",
"(",
"None",
",",
"None",
")",
"uid",
"=",
"cmd_output_to_int",
"(",
"["... | Asks docker-machine for active machine and gets the UID of the docker user
inside the vm
:return: tuple (UID, GID), or (None, None) if error (e.g. docker-machine not present or stopped) | [
"Asks",
"docker",
"-",
"machine",
"for",
"active",
"machine",
"and",
"gets",
"the",
"UID",
"of",
"the",
"docker",
"user",
"inside",
"the",
"vm",
":",
"return",
":",
"tuple",
"(",
"UID",
"GID",
")",
"or",
"(",
"None",
"None",
")",
"if",
"error",
"(",
... | python | train |
a1ezzz/wasp-general | wasp_general/cache.py | https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/cache.py#L299-L331 | def put(self, result, decorated_function, *args, **kwargs):
""" :meth:`WCacheStorage.put` method implementation
"""
self.__check(decorated_function, *args, **kwargs)
ref = weakref.ref(args[0])
if decorated_function not in self._storage:
cache_entry = self._cache_record_cls.create(result, decorated_functio... | [
"def",
"put",
"(",
"self",
",",
"result",
",",
"decorated_function",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"__check",
"(",
"decorated_function",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"ref",
"=",
"weakref",
".",
... | :meth:`WCacheStorage.put` method implementation | [
":",
"meth",
":",
"WCacheStorage",
".",
"put",
"method",
"implementation"
] | python | train |
emilydolson/avida-spatial-tools | avidaspatial/utils.py | https://github.com/emilydolson/avida-spatial-tools/blob/7beb0166ccefad5fa722215b030ac2a53d62b59e/avidaspatial/utils.py#L195-L214 | def convert_world_to_phenotype(world):
"""
Converts sets indicating the resources present in a single cell to binary
strings (bit order is based on the order of resources in world.resources).
TODO: Figure out how to handle relationship between resources and tasks
Inputs: world - an EnvironmentFile... | [
"def",
"convert_world_to_phenotype",
"(",
"world",
")",
":",
"if",
"set",
"(",
"world",
".",
"resources",
")",
"!=",
"set",
"(",
"world",
".",
"tasks",
")",
":",
"print",
"(",
"\"Warning: world phenotypes don't correspond to phenotypes\"",
")",
"if",
"set",
"(",... | Converts sets indicating the resources present in a single cell to binary
strings (bit order is based on the order of resources in world.resources).
TODO: Figure out how to handle relationship between resources and tasks
Inputs: world - an EnvironmentFile object with a grid of resource sets
Returns: a... | [
"Converts",
"sets",
"indicating",
"the",
"resources",
"present",
"in",
"a",
"single",
"cell",
"to",
"binary",
"strings",
"(",
"bit",
"order",
"is",
"based",
"on",
"the",
"order",
"of",
"resources",
"in",
"world",
".",
"resources",
")",
"."
] | python | train |
kdeldycke/maildir-deduplicate | maildir_deduplicate/mail.py | https://github.com/kdeldycke/maildir-deduplicate/blob/f1c6ff25b80c6c1a4dc2dc7a65b34d808b0b7733/maildir_deduplicate/mail.py#L117-L125 | def subject(self):
""" Normalized subject.
Only used for debugging and human-friendly logging.
"""
# Fetch subject from first message.
subject = self.message.get('Subject', '')
subject, _ = re.subn(r'\s+', ' ', subject)
return subject | [
"def",
"subject",
"(",
"self",
")",
":",
"# Fetch subject from first message.",
"subject",
"=",
"self",
".",
"message",
".",
"get",
"(",
"'Subject'",
",",
"''",
")",
"subject",
",",
"_",
"=",
"re",
".",
"subn",
"(",
"r'\\s+'",
",",
"' '",
",",
"subject",... | Normalized subject.
Only used for debugging and human-friendly logging. | [
"Normalized",
"subject",
"."
] | python | train |
theiviaxx/Frog | frog/views/piece.py | https://github.com/theiviaxx/Frog/blob/a9475463a8eed1323fe3ef5d51f9751fb1dc9edd/frog/views/piece.py#L57-L67 | def image(request, obj_id):
"""Handles a request based on method and calls the appropriate function"""
obj = Image.objects.get(pk=obj_id)
if request.method == 'POST':
return post(request, obj)
elif request.method == 'PUT':
getPutData(request)
return put(request, obj)
elif req... | [
"def",
"image",
"(",
"request",
",",
"obj_id",
")",
":",
"obj",
"=",
"Image",
".",
"objects",
".",
"get",
"(",
"pk",
"=",
"obj_id",
")",
"if",
"request",
".",
"method",
"==",
"'POST'",
":",
"return",
"post",
"(",
"request",
",",
"obj",
")",
"elif",... | Handles a request based on method and calls the appropriate function | [
"Handles",
"a",
"request",
"based",
"on",
"method",
"and",
"calls",
"the",
"appropriate",
"function"
] | python | train |
jf-parent/brome | brome/core/proxy_driver.py | https://github.com/jf-parent/brome/blob/784f45d96b83b703dd2181cb59ca8ea777c2510e/brome/core/proxy_driver.py#L208-L303 | def find_all(self, selector, **kwargs):
"""Return all the elements found with a selector
Args:
selector (str): the selector used to find the element
Kwargs:
wait_until_present (bool) default configurable via
proxy_driver:wait_until_present_before_find
... | [
"def",
"find_all",
"(",
"self",
",",
"selector",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"debug_log",
"(",
"\"Finding elements with selector: %s\"",
"%",
"selector",
")",
"raise_exception",
"=",
"kwargs",
".",
"get",
"(",
"'raise_exception'",
",",
"BRO... | Return all the elements found with a selector
Args:
selector (str): the selector used to find the element
Kwargs:
wait_until_present (bool) default configurable via
proxy_driver:wait_until_present_before_find
wait_until_visible (bool) default configu... | [
"Return",
"all",
"the",
"elements",
"found",
"with",
"a",
"selector"
] | python | train |
stevearc/dynamo3 | dynamo3/connection.py | https://github.com/stevearc/dynamo3/blob/f897c40ece28586272dbcab8f0d99a14a1831dda/dynamo3/connection.py#L781-L811 | def batch_get(self, tablename, keys, attributes=None, alias=None,
consistent=False, return_capacity=None):
"""
Perform a batch get of many items in a table
Parameters
----------
tablename : str
Name of the table to fetch from
keys : list or ... | [
"def",
"batch_get",
"(",
"self",
",",
"tablename",
",",
"keys",
",",
"attributes",
"=",
"None",
",",
"alias",
"=",
"None",
",",
"consistent",
"=",
"False",
",",
"return_capacity",
"=",
"None",
")",
":",
"keys",
"=",
"[",
"self",
".",
"dynamizer",
".",
... | Perform a batch get of many items in a table
Parameters
----------
tablename : str
Name of the table to fetch from
keys : list or iterable
List or iterable of primary key dicts that specify the hash key and
the optional range key of each item to fetch... | [
"Perform",
"a",
"batch",
"get",
"of",
"many",
"items",
"in",
"a",
"table"
] | python | train |
googleapis/google-cloud-python | bigtable/google/cloud/bigtable/column_family.py | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigtable/google/cloud/bigtable/column_family.py#L242-L251 | def to_pb(self):
"""Converts the column family to a protobuf.
:rtype: :class:`.table_v2_pb2.ColumnFamily`
:returns: The converted current object.
"""
if self.gc_rule is None:
return table_v2_pb2.ColumnFamily()
else:
return table_v2_pb2.ColumnFamil... | [
"def",
"to_pb",
"(",
"self",
")",
":",
"if",
"self",
".",
"gc_rule",
"is",
"None",
":",
"return",
"table_v2_pb2",
".",
"ColumnFamily",
"(",
")",
"else",
":",
"return",
"table_v2_pb2",
".",
"ColumnFamily",
"(",
"gc_rule",
"=",
"self",
".",
"gc_rule",
".",... | Converts the column family to a protobuf.
:rtype: :class:`.table_v2_pb2.ColumnFamily`
:returns: The converted current object. | [
"Converts",
"the",
"column",
"family",
"to",
"a",
"protobuf",
"."
] | python | train |
limix/glimix-core | glimix_core/cov/_linear.py | https://github.com/limix/glimix-core/blob/cddd0994591d100499cc41c1f480ddd575e7a980/glimix_core/cov/_linear.py#L79-L89 | def value(self):
"""
Covariance matrix.
Returns
-------
K : ndarray
s⋅XXᵀ.
"""
X = self.X
return self.scale * (X @ X.T) | [
"def",
"value",
"(",
"self",
")",
":",
"X",
"=",
"self",
".",
"X",
"return",
"self",
".",
"scale",
"*",
"(",
"X",
"@",
"X",
".",
"T",
")"
] | Covariance matrix.
Returns
-------
K : ndarray
s⋅XXᵀ. | [
"Covariance",
"matrix",
"."
] | python | valid |
amaas-fintech/amaas-core-sdk-python | amaascore/assets/asset.py | https://github.com/amaas-fintech/amaas-core-sdk-python/blob/347b71f8e776b2dde582b015e31b4802d91e8040/amaascore/assets/asset.py#L91-L97 | def maturity_date(self, value):
"""
The date on which the asset matures and no longer holds value
:param value:
:return:
"""
self._maturity_date = parse(value).date() if isinstance(value, type_check) else value | [
"def",
"maturity_date",
"(",
"self",
",",
"value",
")",
":",
"self",
".",
"_maturity_date",
"=",
"parse",
"(",
"value",
")",
".",
"date",
"(",
")",
"if",
"isinstance",
"(",
"value",
",",
"type_check",
")",
"else",
"value"
] | The date on which the asset matures and no longer holds value
:param value:
:return: | [
"The",
"date",
"on",
"which",
"the",
"asset",
"matures",
"and",
"no",
"longer",
"holds",
"value",
":",
"param",
"value",
":",
":",
"return",
":"
] | python | train |
nfcpy/nfcpy | src/nfc/snep/client.py | https://github.com/nfcpy/nfcpy/blob/6649146d1afdd5e82b2b6b1ea00aa58d50785117/src/nfc/snep/client.py#L223-L252 | def put(self, ndef_message, timeout=1.0):
"""Send an NDEF message to the server. Temporarily connects to
the default SNEP server if the client is not yet connected.
.. deprecated:: 0.13
Use :meth:`put_records` or :meth:`put_octets`.
"""
if not self.socket:
... | [
"def",
"put",
"(",
"self",
",",
"ndef_message",
",",
"timeout",
"=",
"1.0",
")",
":",
"if",
"not",
"self",
".",
"socket",
":",
"try",
":",
"self",
".",
"connect",
"(",
"'urn:nfc:sn:snep'",
")",
"except",
"nfc",
".",
"llcp",
".",
"ConnectRefused",
":",
... | Send an NDEF message to the server. Temporarily connects to
the default SNEP server if the client is not yet connected.
.. deprecated:: 0.13
Use :meth:`put_records` or :meth:`put_octets`. | [
"Send",
"an",
"NDEF",
"message",
"to",
"the",
"server",
".",
"Temporarily",
"connects",
"to",
"the",
"default",
"SNEP",
"server",
"if",
"the",
"client",
"is",
"not",
"yet",
"connected",
"."
] | python | train |
SuperCowPowers/workbench | workbench/utils/pcap_streamer.py | https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench/utils/pcap_streamer.py#L83-L98 | def store_file(self, filename):
''' Store a file into workbench '''
# Spin up workbench
self.workbench = zerorpc.Client(timeout=300, heartbeat=60)
self.workbench.connect("tcp://127.0.0.1:4242")
# Open the file and send it to workbench
storage_name = "streamin... | [
"def",
"store_file",
"(",
"self",
",",
"filename",
")",
":",
"# Spin up workbench",
"self",
".",
"workbench",
"=",
"zerorpc",
".",
"Client",
"(",
"timeout",
"=",
"300",
",",
"heartbeat",
"=",
"60",
")",
"self",
".",
"workbench",
".",
"connect",
"(",
"\"t... | Store a file into workbench | [
"Store",
"a",
"file",
"into",
"workbench"
] | python | train |
pytroll/satpy | satpy/composites/__init__.py | https://github.com/pytroll/satpy/blob/1f21d20ac686b745fb0da9b4030d139893e066dd/satpy/composites/__init__.py#L114-L143 | def load_compositors(self, sensor_names):
"""Load all compositor configs for the provided sensors.
Args:
sensor_names (list of strings): Sensor names that have matching
``sensor_name.yaml`` config files.
Returns:
(comps, mods)... | [
"def",
"load_compositors",
"(",
"self",
",",
"sensor_names",
")",
":",
"comps",
"=",
"{",
"}",
"mods",
"=",
"{",
"}",
"for",
"sensor_name",
"in",
"sensor_names",
":",
"if",
"sensor_name",
"not",
"in",
"self",
".",
"compositors",
":",
"self",
".",
"load_s... | Load all compositor configs for the provided sensors.
Args:
sensor_names (list of strings): Sensor names that have matching
``sensor_name.yaml`` config files.
Returns:
(comps, mods): Where `comps` is a dictionary:
... | [
"Load",
"all",
"compositor",
"configs",
"for",
"the",
"provided",
"sensors",
"."
] | python | train |
MikaSoftware/django-starterkit | starterkit/auth/backends.py | https://github.com/MikaSoftware/django-starterkit/blob/b82c4cb56ab8ec0b46136e9efcc3d6481fca1eeb/starterkit/auth/backends.py#L27-L38 | def authenticate(self, username=None, password=None, **kwargs):
"""Allow users to log in with their email address or username."""
try:
# Try to fetch the user by searching the username or email field
user = get_user_model().objects.filter(Q(username=username)|Q(email=username))[0]... | [
"def",
"authenticate",
"(",
"self",
",",
"username",
"=",
"None",
",",
"password",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"# Try to fetch the user by searching the username or email field",
"user",
"=",
"get_user_model",
"(",
")",
".",
"obje... | Allow users to log in with their email address or username. | [
"Allow",
"users",
"to",
"log",
"in",
"with",
"their",
"email",
"address",
"or",
"username",
"."
] | python | train |
aparo/pyes | pyes/orm/queryset.py | https://github.com/aparo/pyes/blob/712eb6095961755067b2b5baa262008ade6584b3/pyes/orm/queryset.py#L427-L435 | def bulk_create(self, objs, batch_size=None):
"""
Inserts each of the instances into the database. This does *not* call
save() on each of the instances, does not send any pre/post save
signals, and does not set the primary key attribute if it is an
autoincrement field.
""... | [
"def",
"bulk_create",
"(",
"self",
",",
"objs",
",",
"batch_size",
"=",
"None",
")",
":",
"self",
".",
"_insert",
"(",
"objs",
",",
"batch_size",
"=",
"batch_size",
",",
"return_id",
"=",
"False",
",",
"force_insert",
"=",
"True",
")",
"self",
".",
"re... | Inserts each of the instances into the database. This does *not* call
save() on each of the instances, does not send any pre/post save
signals, and does not set the primary key attribute if it is an
autoincrement field. | [
"Inserts",
"each",
"of",
"the",
"instances",
"into",
"the",
"database",
".",
"This",
"does",
"*",
"not",
"*",
"call",
"save",
"()",
"on",
"each",
"of",
"the",
"instances",
"does",
"not",
"send",
"any",
"pre",
"/",
"post",
"save",
"signals",
"and",
"doe... | python | train |
nerdvegas/rez | src/rez/serialise.py | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/serialise.py#L369-L395 | def load_yaml(stream, **kwargs):
"""Load yaml-formatted data from a stream.
Args:
stream (file-like object).
Returns:
dict.
"""
# if there's an error parsing the yaml, and you pass yaml.load a string,
# it will print lines of context, but will print "<string>" instead of a
... | [
"def",
"load_yaml",
"(",
"stream",
",",
"*",
"*",
"kwargs",
")",
":",
"# if there's an error parsing the yaml, and you pass yaml.load a string,",
"# it will print lines of context, but will print \"<string>\" instead of a",
"# filename; if you pass a stream, it will print the filename, but n... | Load yaml-formatted data from a stream.
Args:
stream (file-like object).
Returns:
dict. | [
"Load",
"yaml",
"-",
"formatted",
"data",
"from",
"a",
"stream",
"."
] | python | train |
cloud-custodian/cloud-custodian | c7n/filters/offhours.py | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/filters/offhours.py#L448-L463 | def get_tag_value(self, i):
"""Get the resource's tag value specifying its schedule."""
# Look for the tag, Normalize tag key and tag value
found = False
for t in i.get('Tags', ()):
if t['Key'].lower() == self.tag_key:
found = t['Value']
break
... | [
"def",
"get_tag_value",
"(",
"self",
",",
"i",
")",
":",
"# Look for the tag, Normalize tag key and tag value",
"found",
"=",
"False",
"for",
"t",
"in",
"i",
".",
"get",
"(",
"'Tags'",
",",
"(",
")",
")",
":",
"if",
"t",
"[",
"'Key'",
"]",
".",
"lower",
... | Get the resource's tag value specifying its schedule. | [
"Get",
"the",
"resource",
"s",
"tag",
"value",
"specifying",
"its",
"schedule",
"."
] | python | train |
QInfer/python-qinfer | src/qinfer/domains.py | https://github.com/QInfer/python-qinfer/blob/8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3/src/qinfer/domains.py#L640-L657 | def values(self):
"""
Returns an `np.array` of type `self.dtype` containing
some values from the domain.
For domains where ``is_finite`` is ``True``, all elements
of the domain will be yielded exactly once.
:rtype: `np.ndarray`
"""
# This code comes from... | [
"def",
"values",
"(",
"self",
")",
":",
"# This code comes from Jared Goguen at http://stackoverflow.com/a/37712597/1082565",
"partition_array",
"=",
"np",
".",
"empty",
"(",
"(",
"self",
".",
"n_members",
",",
"self",
".",
"n_elements",
")",
",",
"dtype",
"=",
"int... | Returns an `np.array` of type `self.dtype` containing
some values from the domain.
For domains where ``is_finite`` is ``True``, all elements
of the domain will be yielded exactly once.
:rtype: `np.ndarray` | [
"Returns",
"an",
"np",
".",
"array",
"of",
"type",
"self",
".",
"dtype",
"containing",
"some",
"values",
"from",
"the",
"domain",
".",
"For",
"domains",
"where",
"is_finite",
"is",
"True",
"all",
"elements",
"of",
"the",
"domain",
"will",
"be",
"yielded",
... | python | train |
pyapi-gitlab/pyapi-gitlab | gitlab/__init__.py | https://github.com/pyapi-gitlab/pyapi-gitlab/blob/f74b6fb5c13cecae9524997847e928905cc60acf/gitlab/__init__.py#L63-L74 | def get_project(self, project):
"""
Get info for a project identified by id or namespace/project_name
:param project: The ID or URL-encoded path of the project
:return: Dictionary containing the Project
:raise: HttpError: If invalid response returned
"""
project ... | [
"def",
"get_project",
"(",
"self",
",",
"project",
")",
":",
"project",
"=",
"format_string",
"(",
"project",
")",
"return",
"self",
".",
"get",
"(",
"'/projects/{project}'",
".",
"format",
"(",
"project",
"=",
"project",
")",
")"
] | Get info for a project identified by id or namespace/project_name
:param project: The ID or URL-encoded path of the project
:return: Dictionary containing the Project
:raise: HttpError: If invalid response returned | [
"Get",
"info",
"for",
"a",
"project",
"identified",
"by",
"id",
"or",
"namespace",
"/",
"project_name"
] | python | train |
gregmuellegger/django-superform | django_superform/fields.py | https://github.com/gregmuellegger/django-superform/blob/5f389911ad38932b6dad184cc7fa81f27db752f9/django_superform/fields.py#L301-L310 | def allow_blank(self, form, name):
"""
Allow blank determines if the form might be completely empty. If it's
empty it will result in a None as the saved value for the ForeignKey.
"""
if self.blank is not None:
return self.blank
model = form._meta.model
... | [
"def",
"allow_blank",
"(",
"self",
",",
"form",
",",
"name",
")",
":",
"if",
"self",
".",
"blank",
"is",
"not",
"None",
":",
"return",
"self",
".",
"blank",
"model",
"=",
"form",
".",
"_meta",
".",
"model",
"field",
"=",
"model",
".",
"_meta",
".",... | Allow blank determines if the form might be completely empty. If it's
empty it will result in a None as the saved value for the ForeignKey. | [
"Allow",
"blank",
"determines",
"if",
"the",
"form",
"might",
"be",
"completely",
"empty",
".",
"If",
"it",
"s",
"empty",
"it",
"will",
"result",
"in",
"a",
"None",
"as",
"the",
"saved",
"value",
"for",
"the",
"ForeignKey",
"."
] | python | train |
mabuchilab/QNET | src/qnet/algebra/pattern_matching/__init__.py | https://github.com/mabuchilab/QNET/blob/cc20d26dad78691d34c67173e5cd67dcac94208a/src/qnet/algebra/pattern_matching/__init__.py#L604-L606 | def from_expr(cls, expr):
"""Instantiate proto-expression from the given Expression"""
return cls(expr.args, expr.kwargs, cls=expr.__class__) | [
"def",
"from_expr",
"(",
"cls",
",",
"expr",
")",
":",
"return",
"cls",
"(",
"expr",
".",
"args",
",",
"expr",
".",
"kwargs",
",",
"cls",
"=",
"expr",
".",
"__class__",
")"
] | Instantiate proto-expression from the given Expression | [
"Instantiate",
"proto",
"-",
"expression",
"from",
"the",
"given",
"Expression"
] | python | train |
gem/oq-engine | openquake/commands/abort.py | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commands/abort.py#L27-L53 | def abort(job_id):
"""
Abort the given job
"""
job = logs.dbcmd('get_job', job_id) # job_id can be negative
if job is None:
print('There is no job %d' % job_id)
return
elif job.status not in ('executing', 'running'):
print('Job %d is %s' % (job.id, job.status))
r... | [
"def",
"abort",
"(",
"job_id",
")",
":",
"job",
"=",
"logs",
".",
"dbcmd",
"(",
"'get_job'",
",",
"job_id",
")",
"# job_id can be negative",
"if",
"job",
"is",
"None",
":",
"print",
"(",
"'There is no job %d'",
"%",
"job_id",
")",
"return",
"elif",
"job",
... | Abort the given job | [
"Abort",
"the",
"given",
"job"
] | python | train |
rbw/pysnow | pysnow/url_builder.py | https://github.com/rbw/pysnow/blob/87c8ce0d3a089c2f59247f30efbd545fcdb8e985/pysnow/url_builder.py#L23-L36 | def validate_path(path):
"""Validates the provided path
:param path: path to validate (string)
:raise:
:InvalidUsage: If validation fails.
"""
if not isinstance(path, six.string_types) or not re.match('^/(?:[._a-zA-Z0-9-]/?)+[^/]$', path):
raise InvalidU... | [
"def",
"validate_path",
"(",
"path",
")",
":",
"if",
"not",
"isinstance",
"(",
"path",
",",
"six",
".",
"string_types",
")",
"or",
"not",
"re",
".",
"match",
"(",
"'^/(?:[._a-zA-Z0-9-]/?)+[^/]$'",
",",
"path",
")",
":",
"raise",
"InvalidUsage",
"(",
"\"Pat... | Validates the provided path
:param path: path to validate (string)
:raise:
:InvalidUsage: If validation fails. | [
"Validates",
"the",
"provided",
"path"
] | python | train |
albahnsen/CostSensitiveClassification | costcla/models/cost_tree.py | https://github.com/albahnsen/CostSensitiveClassification/blob/75778ae32c70671c0cdde6c4651277b6a8b58871/costcla/models/cost_tree.py#L185-L242 | def _calculate_gain(self, cost_base, y_true, X, cost_mat, split):
""" Private function to calculate the gain in cost of using split in the
current node.
Parameters
----------
cost_base : float
Cost of the naive prediction
y_true : array indicator matrix
... | [
"def",
"_calculate_gain",
"(",
"self",
",",
"cost_base",
",",
"y_true",
",",
"X",
",",
"cost_mat",
",",
"split",
")",
":",
"# Check if cost_base == 0, then no gain is possible",
"#TODO: This must be check in _best_split",
"if",
"cost_base",
"==",
"0.0",
":",
"return",
... | Private function to calculate the gain in cost of using split in the
current node.
Parameters
----------
cost_base : float
Cost of the naive prediction
y_true : array indicator matrix
Ground truth (correct) labels.
X : array-like of shape = [n_... | [
"Private",
"function",
"to",
"calculate",
"the",
"gain",
"in",
"cost",
"of",
"using",
"split",
"in",
"the",
"current",
"node",
"."
] | python | train |
saltstack/salt | salt/modules/npm.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/npm.py#L364-L406 | def cache_list(path=None, runas=None, env=None):
'''
List NPM cached packages.
If no path for a specific package is provided this will list all the cached packages.
path
The cache subpath to list, or None to list the entire cache
runas
The user to run NPM with
env
Env... | [
"def",
"cache_list",
"(",
"path",
"=",
"None",
",",
"runas",
"=",
"None",
",",
"env",
"=",
"None",
")",
":",
"env",
"=",
"env",
"or",
"{",
"}",
"if",
"runas",
":",
"uid",
"=",
"salt",
".",
"utils",
".",
"user",
".",
"get_uid",
"(",
"runas",
")"... | List NPM cached packages.
If no path for a specific package is provided this will list all the cached packages.
path
The cache subpath to list, or None to list the entire cache
runas
The user to run NPM with
env
Environment variables to set when invoking npm. Uses the same ``... | [
"List",
"NPM",
"cached",
"packages",
"."
] | python | train |
jay-johnson/antinex-client | antinex_client/log/setup_logging.py | https://github.com/jay-johnson/antinex-client/blob/850ba2a2fe21c836e071def618dcecc9caf5d59c/antinex_client/log/setup_logging.py#L6-L59 | def setup_logging(
default_level=logging.INFO,
default_path="{}/logging.json".format(
os.getenv(
"LOG_DIR",
os.path.dirname(os.path.realpath(__file__)))),
env_key="LOG_CFG",
config_name=None):
"""setup_logging
Setup logging configurati... | [
"def",
"setup_logging",
"(",
"default_level",
"=",
"logging",
".",
"INFO",
",",
"default_path",
"=",
"\"{}/logging.json\"",
".",
"format",
"(",
"os",
".",
"getenv",
"(",
"\"LOG_DIR\"",
",",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
... | setup_logging
Setup logging configuration
:param default_level: level to log
:param default_path: path to config (optional)
:param env_key: path to config in this env var
:param config_name: filename for config | [
"setup_logging"
] | python | train |
a10networks/a10-neutron-lbaas | a10_neutron_lbaas/neutron_ext/extensions/a10Certificate.py | https://github.com/a10networks/a10-neutron-lbaas/blob/ff834c295c8019874ca4b209d864367e40cc9881/a10_neutron_lbaas/neutron_ext/extensions/a10Certificate.py#L78-L88 | def get_resources(cls):
"""Returns external resources."""
my_plurals = resource_helper.build_plural_mappings(
{}, RESOURCE_ATTRIBUTE_MAP)
attributes.PLURALS.update(my_plurals)
attr_map = RESOURCE_ATTRIBUTE_MAP
ext_resources = resource_helper.build_resource_info(my_plu... | [
"def",
"get_resources",
"(",
"cls",
")",
":",
"my_plurals",
"=",
"resource_helper",
".",
"build_plural_mappings",
"(",
"{",
"}",
",",
"RESOURCE_ATTRIBUTE_MAP",
")",
"attributes",
".",
"PLURALS",
".",
"update",
"(",
"my_plurals",
")",
"attr_map",
"=",
"RESOURCE_A... | Returns external resources. | [
"Returns",
"external",
"resources",
"."
] | python | train |
inveniosoftware/invenio-oauth2server | invenio_oauth2server/views/server.py | https://github.com/inveniosoftware/invenio-oauth2server/blob/7033d3495c1a2b830e101e43918e92a37bbb49f2/invenio_oauth2server/views/server.py#L108-L116 | def errors():
"""Error view in case of invalid oauth requests."""
from oauthlib.oauth2.rfc6749.errors import raise_from_error
try:
error = None
raise_from_error(request.values.get('error'), params=dict())
except OAuth2Error as raised:
error = raised
return render_template('in... | [
"def",
"errors",
"(",
")",
":",
"from",
"oauthlib",
".",
"oauth2",
".",
"rfc6749",
".",
"errors",
"import",
"raise_from_error",
"try",
":",
"error",
"=",
"None",
"raise_from_error",
"(",
"request",
".",
"values",
".",
"get",
"(",
"'error'",
")",
",",
"pa... | Error view in case of invalid oauth requests. | [
"Error",
"view",
"in",
"case",
"of",
"invalid",
"oauth",
"requests",
"."
] | python | train |
libnano/primer3-py | primer3/bindings.py | https://github.com/libnano/primer3-py/blob/0901c0ef3ac17afd69329d23db71136c00bcb635/primer3/bindings.py#L70-L97 | def calcHairpin(seq, mv_conc=50.0, dv_conc=0.0, dntp_conc=0.8, dna_conc=50.0,
temp_c=37, max_loop=30):
''' Calculate the hairpin formation thermodynamics of a DNA sequence.
**Note that the maximum length of `seq` is 60 bp.** This is a cap suggested
by the Primer3 team as the longest reasona... | [
"def",
"calcHairpin",
"(",
"seq",
",",
"mv_conc",
"=",
"50.0",
",",
"dv_conc",
"=",
"0.0",
",",
"dntp_conc",
"=",
"0.8",
",",
"dna_conc",
"=",
"50.0",
",",
"temp_c",
"=",
"37",
",",
"max_loop",
"=",
"30",
")",
":",
"_setThermoArgs",
"(",
"*",
"*",
... | Calculate the hairpin formation thermodynamics of a DNA sequence.
**Note that the maximum length of `seq` is 60 bp.** This is a cap suggested
by the Primer3 team as the longest reasonable sequence length for which
a two-state NN model produces reliable results (see primer3/src/libnano/thal.h:50).
Args... | [
"Calculate",
"the",
"hairpin",
"formation",
"thermodynamics",
"of",
"a",
"DNA",
"sequence",
"."
] | python | train |
sys-git/certifiable | certifiable/operators.py | https://github.com/sys-git/certifiable/blob/a3c33c0d4f3ac2c53be9eded3fae633fa5f697f8/certifiable/operators.py#L58-L83 | def NAND(*args, **kwargs):
"""
ALL args must raise an exception when called overall.
Raise the specified exception on failure OR the first exception.
:params iterable[Certifier] args:
The certifiers to call
:param callable kwargs['exc']:
Callable that excepts the unexpectedly raised... | [
"def",
"NAND",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"errors",
"=",
"[",
"]",
"for",
"arg",
"in",
"args",
":",
"try",
":",
"arg",
"(",
")",
"except",
"CertifierError",
"as",
"e",
":",
"errors",
".",
"append",
"(",
"e",
")",
"if",... | ALL args must raise an exception when called overall.
Raise the specified exception on failure OR the first exception.
:params iterable[Certifier] args:
The certifiers to call
:param callable kwargs['exc']:
Callable that excepts the unexpectedly raised exception as argument and return an
... | [
"ALL",
"args",
"must",
"raise",
"an",
"exception",
"when",
"called",
"overall",
".",
"Raise",
"the",
"specified",
"exception",
"on",
"failure",
"OR",
"the",
"first",
"exception",
"."
] | python | train |
bitesofcode/projexui | projexui/widgets/xorbbrowserwidget/xorbquerywidget.py | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xorbbrowserwidget/xorbquerywidget.py#L609-L629 | def query( self ):
"""
Returns the query this widget is representing from the tree widget.
:return <Query> || <QueryCompound> || None
"""
# build a query if not searching all
q = Q()
operator = 'and'
for i in range(se... | [
"def",
"query",
"(",
"self",
")",
":",
"# build a query if not searching all\r",
"q",
"=",
"Q",
"(",
")",
"operator",
"=",
"'and'",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"uiQueryTREE",
".",
"topLevelItemCount",
"(",
")",
")",
":",
"item",
"=",
"se... | Returns the query this widget is representing from the tree widget.
:return <Query> || <QueryCompound> || None | [
"Returns",
"the",
"query",
"this",
"widget",
"is",
"representing",
"from",
"the",
"tree",
"widget",
".",
":",
"return",
"<Query",
">",
"||",
"<QueryCompound",
">",
"||",
"None"
] | python | train |
PMEAL/OpenPNM | openpnm/models/physics/capillary_pressure.py | https://github.com/PMEAL/OpenPNM/blob/0547b5724ffedc0a593aae48639d36fe10e0baed/openpnm/models/physics/capillary_pressure.py#L279-L340 | def purcell_bidirectional(target, r_toroid,
num_points=1e2,
surface_tension='pore.surface_tension',
contact_angle='pore.contact_angle',
throat_diameter='throat.diameter',
pore_diameter='pore... | [
"def",
"purcell_bidirectional",
"(",
"target",
",",
"r_toroid",
",",
"num_points",
"=",
"1e2",
",",
"surface_tension",
"=",
"'pore.surface_tension'",
",",
"contact_angle",
"=",
"'pore.contact_angle'",
",",
"throat_diameter",
"=",
"'throat.diameter'",
",",
"pore_diameter... | r"""
Computes the throat capillary entry pressure assuming the throat is a
toroid. Makes use of the toroidal meniscus model with mode touch.
This model accounts for mensicus protrusion into adjacent pores and
touching solid features.
It is bidirectional becauase the connected pores generally have di... | [
"r",
"Computes",
"the",
"throat",
"capillary",
"entry",
"pressure",
"assuming",
"the",
"throat",
"is",
"a",
"toroid",
".",
"Makes",
"use",
"of",
"the",
"toroidal",
"meniscus",
"model",
"with",
"mode",
"touch",
".",
"This",
"model",
"accounts",
"for",
"mensic... | python | train |
mcash/merchant-api-python-sdk | mcash/mapi_client/mapi_client.py | https://github.com/mcash/merchant-api-python-sdk/blob/ebe8734126790354b71077aca519ff263235944e/mcash/mapi_client/mapi_client.py#L777-L784 | def upload_receipt(self, url, data):
"""Upload a receipt to the give url
:param url:
:param data:
:return:
"""
return self.upload_attachment(url=url, data=data, mime_type='application/vnd.mcash.receipt.v1+json') | [
"def",
"upload_receipt",
"(",
"self",
",",
"url",
",",
"data",
")",
":",
"return",
"self",
".",
"upload_attachment",
"(",
"url",
"=",
"url",
",",
"data",
"=",
"data",
",",
"mime_type",
"=",
"'application/vnd.mcash.receipt.v1+json'",
")"
] | Upload a receipt to the give url
:param url:
:param data:
:return: | [
"Upload",
"a",
"receipt",
"to",
"the",
"give",
"url"
] | python | train |
pybel/pybel | src/pybel/canonicalize.py | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/canonicalize.py#L244-L273 | def _to_bel_lines_footer(graph) -> Iterable[str]:
"""Iterate the lines of a BEL graph's corresponding BEL script's footer.
:param pybel.BELGraph graph: A BEL graph
"""
unqualified_edges_to_serialize = [
(u, v, d)
for u, v, d in graph.edges(data=True)
if d[RELATION] in UNQUALIFIE... | [
"def",
"_to_bel_lines_footer",
"(",
"graph",
")",
"->",
"Iterable",
"[",
"str",
"]",
":",
"unqualified_edges_to_serialize",
"=",
"[",
"(",
"u",
",",
"v",
",",
"d",
")",
"for",
"u",
",",
"v",
",",
"d",
"in",
"graph",
".",
"edges",
"(",
"data",
"=",
... | Iterate the lines of a BEL graph's corresponding BEL script's footer.
:param pybel.BELGraph graph: A BEL graph | [
"Iterate",
"the",
"lines",
"of",
"a",
"BEL",
"graph",
"s",
"corresponding",
"BEL",
"script",
"s",
"footer",
"."
] | python | train |
quantopian/zipline | zipline/pipeline/factors/factor.py | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/factors/factor.py#L285-L308 | def function_application(func):
"""
Factory function for producing function application methods for Factor
subclasses.
"""
if func not in NUMEXPR_MATH_FUNCS:
raise ValueError("Unsupported mathematical function '%s'" % func)
@with_doc(func)
@with_name(func)
def mathfunc(self):
... | [
"def",
"function_application",
"(",
"func",
")",
":",
"if",
"func",
"not",
"in",
"NUMEXPR_MATH_FUNCS",
":",
"raise",
"ValueError",
"(",
"\"Unsupported mathematical function '%s'\"",
"%",
"func",
")",
"@",
"with_doc",
"(",
"func",
")",
"@",
"with_name",
"(",
"fun... | Factory function for producing function application methods for Factor
subclasses. | [
"Factory",
"function",
"for",
"producing",
"function",
"application",
"methods",
"for",
"Factor",
"subclasses",
"."
] | python | train |
dmlc/gluon-nlp | scripts/parsing/common/utils.py | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/parsing/common/utils.py#L56-L144 | def update(self, current, values=[], exact=[], strict=[]):
"""
Updates the progress bar.
# Arguments
current: Index of current step.
values: List of tuples (name, value_for_last_step).
The progress bar will display averages for these values.
ex... | [
"def",
"update",
"(",
"self",
",",
"current",
",",
"values",
"=",
"[",
"]",
",",
"exact",
"=",
"[",
"]",
",",
"strict",
"=",
"[",
"]",
")",
":",
"for",
"k",
",",
"v",
"in",
"values",
":",
"if",
"k",
"not",
"in",
"self",
".",
"sum_values",
":"... | Updates the progress bar.
# Arguments
current: Index of current step.
values: List of tuples (name, value_for_last_step).
The progress bar will display averages for these values.
exact: List of tuples (name, value_for_last_step).
The progress b... | [
"Updates",
"the",
"progress",
"bar",
".",
"#",
"Arguments",
"current",
":",
"Index",
"of",
"current",
"step",
".",
"values",
":",
"List",
"of",
"tuples",
"(",
"name",
"value_for_last_step",
")",
".",
"The",
"progress",
"bar",
"will",
"display",
"averages",
... | python | train |
tensorflow/tensor2tensor | tensor2tensor/models/research/transformer_symshard.py | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/transformer_symshard.py#L227-L339 | def _layer_stack(mp,
inputs,
self_attention_bias,
layers,
hparams,
encoder_output=None,
encoder_decoder_attention_bias=None):
"""A stack of layers.
Args:
mp: a Parallelism object
inputs: a list of Tensors
... | [
"def",
"_layer_stack",
"(",
"mp",
",",
"inputs",
",",
"self_attention_bias",
",",
"layers",
",",
"hparams",
",",
"encoder_output",
"=",
"None",
",",
"encoder_decoder_attention_bias",
"=",
"None",
")",
":",
"layers",
"=",
"layers",
".",
"strip",
"(",
"\",\"",
... | A stack of layers.
Args:
mp: a Parallelism object
inputs: a list of Tensors
self_attention_bias: list of bias Tensor for self-attention
(see common_attention.attention_bias())
layers: a string
hparams: hyperparameters for model
encoder_output: optional list of tensors
encoder_decode... | [
"A",
"stack",
"of",
"layers",
"."
] | python | train |
Alignak-monitoring/alignak | alignak/external_command.py | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/external_command.py#L1463-L1485 | def change_normal_host_check_interval(self, host, check_interval):
"""Modify host check interval
Format of the line that triggers function call::
CHANGE_NORMAL_HOST_CHECK_INTERVAL;<host_name>;<check_interval>
:param host: host to edit
:type host: alignak.objects.host.Host
... | [
"def",
"change_normal_host_check_interval",
"(",
"self",
",",
"host",
",",
"check_interval",
")",
":",
"host",
".",
"modified_attributes",
"|=",
"DICT_MODATTR",
"[",
"\"MODATTR_NORMAL_CHECK_INTERVAL\"",
"]",
".",
"value",
"old_interval",
"=",
"host",
".",
"check_inter... | Modify host check interval
Format of the line that triggers function call::
CHANGE_NORMAL_HOST_CHECK_INTERVAL;<host_name>;<check_interval>
:param host: host to edit
:type host: alignak.objects.host.Host
:param check_interval: new value to set
:type check_interval:
... | [
"Modify",
"host",
"check",
"interval",
"Format",
"of",
"the",
"line",
"that",
"triggers",
"function",
"call",
"::"
] | python | train |
bcbio/bcbio-nextgen | bcbio/variation/annotation.py | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/annotation.py#L17-L46 | def get_gatk_annotations(config, include_depth=True, include_baseqranksum=True,
gatk_input=True):
"""Retrieve annotations to use for GATK VariantAnnotator.
If include_depth is false, we'll skip annotating DP. Since GATK downsamples
this will undercount on high depth sequencing and ... | [
"def",
"get_gatk_annotations",
"(",
"config",
",",
"include_depth",
"=",
"True",
",",
"include_baseqranksum",
"=",
"True",
",",
"gatk_input",
"=",
"True",
")",
":",
"broad_runner",
"=",
"broad",
".",
"runner_from_config",
"(",
"config",
")",
"anns",
"=",
"[",
... | Retrieve annotations to use for GATK VariantAnnotator.
If include_depth is false, we'll skip annotating DP. Since GATK downsamples
this will undercount on high depth sequencing and the standard outputs
from the original callers may be preferable.
BaseQRankSum can cause issues with some MuTect2 and oth... | [
"Retrieve",
"annotations",
"to",
"use",
"for",
"GATK",
"VariantAnnotator",
"."
] | python | train |
nutechsoftware/alarmdecoder | alarmdecoder/messages/lrr/message.py | https://github.com/nutechsoftware/alarmdecoder/blob/b0c014089e24455228cb4402cf30ba98157578cd/alarmdecoder/messages/lrr/message.py#L59-L94 | def _parse_message(self, data):
"""
Parses the raw message from the device.
:param data: message data to parse
:type data: string
:raises: :py:class:`~alarmdecoder.util.InvalidMessageError`
"""
try:
_, values = data.split(':')
values = va... | [
"def",
"_parse_message",
"(",
"self",
",",
"data",
")",
":",
"try",
":",
"_",
",",
"values",
"=",
"data",
".",
"split",
"(",
"':'",
")",
"values",
"=",
"values",
".",
"split",
"(",
"','",
")",
"# Handle older-format events",
"if",
"len",
"(",
"values",... | Parses the raw message from the device.
:param data: message data to parse
:type data: string
:raises: :py:class:`~alarmdecoder.util.InvalidMessageError` | [
"Parses",
"the",
"raw",
"message",
"from",
"the",
"device",
"."
] | python | train |
rigetti/pyquil | pyquil/gates.py | https://github.com/rigetti/pyquil/blob/ec98e453084b0037d69d8c3245f6822a5422593d/pyquil/gates.py#L290-L304 | def CPHASE00(angle, control, target):
"""Produces a controlled-phase gate that phases the ``|00>`` state::
CPHASE00(phi) = diag([exp(1j * phi), 1, 1, 1])
This gate applies to two qubit arguments to produce the variant of the controlled phase
instruction that affects the state 00.
:param angle... | [
"def",
"CPHASE00",
"(",
"angle",
",",
"control",
",",
"target",
")",
":",
"qubits",
"=",
"[",
"unpack_qubit",
"(",
"q",
")",
"for",
"q",
"in",
"(",
"control",
",",
"target",
")",
"]",
"return",
"Gate",
"(",
"name",
"=",
"\"CPHASE00\"",
",",
"params",... | Produces a controlled-phase gate that phases the ``|00>`` state::
CPHASE00(phi) = diag([exp(1j * phi), 1, 1, 1])
This gate applies to two qubit arguments to produce the variant of the controlled phase
instruction that affects the state 00.
:param angle: The input phase angle to apply when both qu... | [
"Produces",
"a",
"controlled",
"-",
"phase",
"gate",
"that",
"phases",
"the",
"|00",
">",
"state",
"::"
] | python | train |
ggravlingen/pytradfri | examples/debug_info.py | https://github.com/ggravlingen/pytradfri/blob/63750fa8fb27158c013d24865cdaa7fb82b3ab53/examples/debug_info.py#L115-L125 | def print_lamps():
"""Print all lamp devices as JSON"""
print("Printing information about all lamps paired to the Gateway")
lights = [dev for dev in devices if dev.has_light_control]
if len(lights) == 0:
exit(bold("No lamps paired"))
container = []
for l in lights:
container.app... | [
"def",
"print_lamps",
"(",
")",
":",
"print",
"(",
"\"Printing information about all lamps paired to the Gateway\"",
")",
"lights",
"=",
"[",
"dev",
"for",
"dev",
"in",
"devices",
"if",
"dev",
".",
"has_light_control",
"]",
"if",
"len",
"(",
"lights",
")",
"==",... | Print all lamp devices as JSON | [
"Print",
"all",
"lamp",
"devices",
"as",
"JSON"
] | python | train |
jobovy/galpy | galpy/orbit/Orbit.py | https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/orbit/Orbit.py#L2287-L2319 | def ra(self,*args,**kwargs):
"""
NAME:
ra
PURPOSE:
return the right ascension
INPUT:
t - (optional) time at which to get ra (can be Quantity)
obs=[X,Y,Z] - (optional) position of observer (in kpc; entries can be Quantity)
(def... | [
"def",
"ra",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"out",
"=",
"self",
".",
"_orb",
".",
"ra",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"if",
"len",
"(",
"out",
")",
"==",
"1",
":",
"return",
"out",
"[",
... | NAME:
ra
PURPOSE:
return the right ascension
INPUT:
t - (optional) time at which to get ra (can be Quantity)
obs=[X,Y,Z] - (optional) position of observer (in kpc; entries can be Quantity)
(default=[8.0,0.,0.]) OR Orbit object that correspond... | [
"NAME",
":"
] | python | train |
dopefishh/pympi | pympi/Praat.py | https://github.com/dopefishh/pympi/blob/79c747cde45b5ba203ed93154d8c123ac9c3ef56/pympi/Praat.py#L401-L408 | def get_intervals(self, sort=False):
"""Give all the intervals or points.
:param bool sort: Flag for yielding the intervals or points sorted.
:yields: All the intervals
"""
for i in sorted(self.intervals) if sort else self.intervals:
yield i | [
"def",
"get_intervals",
"(",
"self",
",",
"sort",
"=",
"False",
")",
":",
"for",
"i",
"in",
"sorted",
"(",
"self",
".",
"intervals",
")",
"if",
"sort",
"else",
"self",
".",
"intervals",
":",
"yield",
"i"
] | Give all the intervals or points.
:param bool sort: Flag for yielding the intervals or points sorted.
:yields: All the intervals | [
"Give",
"all",
"the",
"intervals",
"or",
"points",
"."
] | python | test |
doconix/django-mako-plus | django_mako_plus/provider/__init__.py | https://github.com/doconix/django-mako-plus/blob/a90f9b4af19e5fa9f83452989cdcaed21569a181/django_mako_plus/provider/__init__.py#L35-L55 | def template_obj_links(request, template_obj, context=None, group=None):
'''
Returns the HTML for the given provider group, using a template object.
This method should not normally be used (use links() instead). The use of
this method is when provider need to be called from regular python code instead
... | [
"def",
"template_obj_links",
"(",
"request",
",",
"template_obj",
",",
"context",
"=",
"None",
",",
"group",
"=",
"None",
")",
":",
"# the template_obj can be a MakoTemplateAdapter or a Mako Template",
"# if our DMP-defined MakoTemplateAdapter, switch to the embedded Mako Template"... | Returns the HTML for the given provider group, using a template object.
This method should not normally be used (use links() instead). The use of
this method is when provider need to be called from regular python code instead
of from within a rendering template environment. | [
"Returns",
"the",
"HTML",
"for",
"the",
"given",
"provider",
"group",
"using",
"a",
"template",
"object",
".",
"This",
"method",
"should",
"not",
"normally",
"be",
"used",
"(",
"use",
"links",
"()",
"instead",
")",
".",
"The",
"use",
"of",
"this",
"metho... | python | train |
joshspeagle/dynesty | dynesty/sampler.py | https://github.com/joshspeagle/dynesty/blob/9e482aafeb5cf84bedb896fa6f07a761d917983e/dynesty/sampler.py#L482-L759 | def sample(self, maxiter=None, maxcall=None, dlogz=0.01,
logl_max=np.inf, save_bounds=True, save_samples=True):
"""
**The main nested sampling loop.** Iteratively replace the worst live
point with a sample drawn uniformly from the prior until the
provided stopping criteria... | [
"def",
"sample",
"(",
"self",
",",
"maxiter",
"=",
"None",
",",
"maxcall",
"=",
"None",
",",
"dlogz",
"=",
"0.01",
",",
"logl_max",
"=",
"np",
".",
"inf",
",",
"save_bounds",
"=",
"True",
",",
"save_samples",
"=",
"True",
")",
":",
"# Initialize quanti... | **The main nested sampling loop.** Iteratively replace the worst live
point with a sample drawn uniformly from the prior until the
provided stopping criteria are reached. Instantiates a generator
that will be called by the user.
Parameters
----------
maxiter : int, optio... | [
"**",
"The",
"main",
"nested",
"sampling",
"loop",
".",
"**",
"Iteratively",
"replace",
"the",
"worst",
"live",
"point",
"with",
"a",
"sample",
"drawn",
"uniformly",
"from",
"the",
"prior",
"until",
"the",
"provided",
"stopping",
"criteria",
"are",
"reached",
... | python | train |
secure-systems-lab/securesystemslib | securesystemslib/ed25519_keys.py | https://github.com/secure-systems-lab/securesystemslib/blob/beb3109d5bb462e5a60eed88fb40ed1167bd354e/securesystemslib/ed25519_keys.py#L289-L404 | def verify_signature(public_key, scheme, signature, data, use_pynacl=False):
"""
<Purpose>
Determine whether the private key corresponding to 'public_key' produced
'signature'. verify_signature() will use the public key, the 'scheme' and
'sig', and 'data' arguments to complete the verification.
>>... | [
"def",
"verify_signature",
"(",
"public_key",
",",
"scheme",
",",
"signature",
",",
"data",
",",
"use_pynacl",
"=",
"False",
")",
":",
"# Does 'public_key' have the correct format?",
"# This check will ensure 'public_key' conforms to",
"# 'securesystemslib.formats.ED25519PUBLIC_S... | <Purpose>
Determine whether the private key corresponding to 'public_key' produced
'signature'. verify_signature() will use the public key, the 'scheme' and
'sig', and 'data' arguments to complete the verification.
>>> public, private = generate_public_and_private()
>>> data = b'The quick brown fo... | [
"<Purpose",
">",
"Determine",
"whether",
"the",
"private",
"key",
"corresponding",
"to",
"public_key",
"produced",
"signature",
".",
"verify_signature",
"()",
"will",
"use",
"the",
"public",
"key",
"the",
"scheme",
"and",
"sig",
"and",
"data",
"arguments",
"to",... | python | train |
tensorflow/datasets | tensorflow_datasets/core/utils/py_utils.py | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/utils/py_utils.py#L276-L280 | def reraise(additional_msg):
"""Reraise an exception with an additional message."""
exc_type, exc_value, exc_traceback = sys.exc_info()
msg = str(exc_value) + "\n" + additional_msg
six.reraise(exc_type, exc_type(msg), exc_traceback) | [
"def",
"reraise",
"(",
"additional_msg",
")",
":",
"exc_type",
",",
"exc_value",
",",
"exc_traceback",
"=",
"sys",
".",
"exc_info",
"(",
")",
"msg",
"=",
"str",
"(",
"exc_value",
")",
"+",
"\"\\n\"",
"+",
"additional_msg",
"six",
".",
"reraise",
"(",
"ex... | Reraise an exception with an additional message. | [
"Reraise",
"an",
"exception",
"with",
"an",
"additional",
"message",
"."
] | python | train |
mikedh/trimesh | trimesh/scene/scene.py | https://github.com/mikedh/trimesh/blob/25e059bf6d4caa74f62ffd58ce4f61a90ee4e518/trimesh/scene/scene.py#L77-L164 | def add_geometry(self,
geometry,
node_name=None,
geom_name=None,
parent_node_name=None,
transform=None):
"""
Add a geometry to the scene.
If the mesh has multiple transforms defined in its
... | [
"def",
"add_geometry",
"(",
"self",
",",
"geometry",
",",
"node_name",
"=",
"None",
",",
"geom_name",
"=",
"None",
",",
"parent_node_name",
"=",
"None",
",",
"transform",
"=",
"None",
")",
":",
"if",
"geometry",
"is",
"None",
":",
"return",
"# PointCloud o... | Add a geometry to the scene.
If the mesh has multiple transforms defined in its
metadata, they will all be copied into the
TransformForest of the current scene automatically.
Parameters
----------
geometry : Trimesh, Path2D, Path3D PointCloud or list
Geometry ... | [
"Add",
"a",
"geometry",
"to",
"the",
"scene",
"."
] | python | train |
deepmipt/DeepPavlov | deeppavlov/settings.py | https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/settings.py#L24-L35 | def main():
"""DeepPavlov console configuration utility."""
args = parser.parse_args()
path = get_settings_path()
if args.default:
if populate_settings_dir(force=True):
print(f'Populated {path} with default settings files')
else:
print(f'{path} is already a defau... | [
"def",
"main",
"(",
")",
":",
"args",
"=",
"parser",
".",
"parse_args",
"(",
")",
"path",
"=",
"get_settings_path",
"(",
")",
"if",
"args",
".",
"default",
":",
"if",
"populate_settings_dir",
"(",
"force",
"=",
"True",
")",
":",
"print",
"(",
"f'Popula... | DeepPavlov console configuration utility. | [
"DeepPavlov",
"console",
"configuration",
"utility",
"."
] | python | test |
jbarlow83/OCRmyPDF | src/ocrmypdf/__main__.py | https://github.com/jbarlow83/OCRmyPDF/blob/79c84eefa353632a3d7ccddbd398c6678c1c1777/src/ocrmypdf/__main__.py#L759-L819 | def do_ruffus_exception(ruffus_five_tuple, options, log):
"""Replace the elaborate ruffus stack trace with a user friendly
description of the error message that occurred."""
exit_code = None
_task_name, _job_name, exc_name, exc_value, exc_stack = ruffus_five_tuple
if isinstance(exc_name, type):
... | [
"def",
"do_ruffus_exception",
"(",
"ruffus_five_tuple",
",",
"options",
",",
"log",
")",
":",
"exit_code",
"=",
"None",
"_task_name",
",",
"_job_name",
",",
"exc_name",
",",
"exc_value",
",",
"exc_stack",
"=",
"ruffus_five_tuple",
"if",
"isinstance",
"(",
"exc_n... | Replace the elaborate ruffus stack trace with a user friendly
description of the error message that occurred. | [
"Replace",
"the",
"elaborate",
"ruffus",
"stack",
"trace",
"with",
"a",
"user",
"friendly",
"description",
"of",
"the",
"error",
"message",
"that",
"occurred",
"."
] | python | train |
davidcarboni/Flask-B3 | b3/__init__.py | https://github.com/davidcarboni/Flask-B3/blob/55092cb1070568aeecfd2c07c5ad6122e15ca345/b3/__init__.py#L42-L85 | def start_span(request_headers=None):
"""Collects incoming B3 headers and sets up values for this request as needed.
The collected/computed values are stored on the application context g using the defined http header names as keys.
:param request_headers: Incoming request headers can be passed explicitly.
... | [
"def",
"start_span",
"(",
"request_headers",
"=",
"None",
")",
":",
"global",
"debug",
"try",
":",
"headers",
"=",
"request_headers",
"if",
"request_headers",
"else",
"request",
".",
"headers",
"except",
"RuntimeError",
":",
"# We're probably working outside the Appli... | Collects incoming B3 headers and sets up values for this request as needed.
The collected/computed values are stored on the application context g using the defined http header names as keys.
:param request_headers: Incoming request headers can be passed explicitly.
If not passed, Flask request.headers will ... | [
"Collects",
"incoming",
"B3",
"headers",
"and",
"sets",
"up",
"values",
"for",
"this",
"request",
"as",
"needed",
".",
"The",
"collected",
"/",
"computed",
"values",
"are",
"stored",
"on",
"the",
"application",
"context",
"g",
"using",
"the",
"defined",
"htt... | python | train |
Leeps-Lab/otree-redwood | otree_redwood/models.py | https://github.com/Leeps-Lab/otree-redwood/blob/59212f61a256ef77e0a9ed392ff497ea83ee6245/otree_redwood/models.py#L255-L268 | def _on_decisions_event(self, event=None, **kwargs):
"""Called when an Event is received on the decisions channel. Saves
the value in group_decisions. If num_subperiods is None, immediately
broadcasts the event back out on the group_decisions channel.
"""
if not self.ran_ready_fu... | [
"def",
"_on_decisions_event",
"(",
"self",
",",
"event",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"self",
".",
"ran_ready_function",
":",
"logger",
".",
"warning",
"(",
"'ignoring decision from {} before when_all_players_ready: {}'",
".",
"form... | Called when an Event is received on the decisions channel. Saves
the value in group_decisions. If num_subperiods is None, immediately
broadcasts the event back out on the group_decisions channel. | [
"Called",
"when",
"an",
"Event",
"is",
"received",
"on",
"the",
"decisions",
"channel",
".",
"Saves",
"the",
"value",
"in",
"group_decisions",
".",
"If",
"num_subperiods",
"is",
"None",
"immediately",
"broadcasts",
"the",
"event",
"back",
"out",
"on",
"the",
... | python | train |
gem/oq-engine | openquake/calculators/export/risk.py | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/export/risk.py#L131-L148 | def export_avg_losses(ekey, dstore):
"""
:param ekey: export key, i.e. a pair (datastore key, fmt)
:param dstore: datastore object
"""
dskey = ekey[0]
oq = dstore['oqparam']
dt = oq.loss_dt()
name, value, tags = _get_data(dstore, dskey, oq.hazard_stats().items())
writer = writers.Csv... | [
"def",
"export_avg_losses",
"(",
"ekey",
",",
"dstore",
")",
":",
"dskey",
"=",
"ekey",
"[",
"0",
"]",
"oq",
"=",
"dstore",
"[",
"'oqparam'",
"]",
"dt",
"=",
"oq",
".",
"loss_dt",
"(",
")",
"name",
",",
"value",
",",
"tags",
"=",
"_get_data",
"(",
... | :param ekey: export key, i.e. a pair (datastore key, fmt)
:param dstore: datastore object | [
":",
"param",
"ekey",
":",
"export",
"key",
"i",
".",
"e",
".",
"a",
"pair",
"(",
"datastore",
"key",
"fmt",
")",
":",
"param",
"dstore",
":",
"datastore",
"object"
] | python | train |
quantum5/2048 | _2048/game.py | https://github.com/quantum5/2048/blob/93ada2e3026eaf154e1bbee943d0500c9253e66f/_2048/game.py#L197-L211 | def _draw_button(self, overlay, text, location):
"""Draws a button on the won and lost overlays, and return its hitbox."""
label = self.button_font.render(text, True, (119, 110, 101))
w, h = label.get_size()
# Let the callback calculate the location based on
# the width and heigh... | [
"def",
"_draw_button",
"(",
"self",
",",
"overlay",
",",
"text",
",",
"location",
")",
":",
"label",
"=",
"self",
".",
"button_font",
".",
"render",
"(",
"text",
",",
"True",
",",
"(",
"119",
",",
"110",
",",
"101",
")",
")",
"w",
",",
"h",
"=",
... | Draws a button on the won and lost overlays, and return its hitbox. | [
"Draws",
"a",
"button",
"on",
"the",
"won",
"and",
"lost",
"overlays",
"and",
"return",
"its",
"hitbox",
"."
] | python | train |
MouseLand/rastermap | rastermap/isorec.py | https://github.com/MouseLand/rastermap/blob/eee7a46db80b6e33207543778e11618d0fed08a6/rastermap/isorec.py#L363-L413 | def fit(self, X=None, u=None, s = None):
"""Fit X into an embedded space.
Inputs
----------
X : array, shape (n_samples, n_features)
u,s,v : svd decomposition of X (optional)
Assigns
----------
embedding : array-like, shape (n_samples, n_components)
... | [
"def",
"fit",
"(",
"self",
",",
"X",
"=",
"None",
",",
"u",
"=",
"None",
",",
"s",
"=",
"None",
")",
":",
"X",
"=",
"X",
".",
"copy",
"(",
")",
"X",
"-=",
"X",
".",
"mean",
"(",
"axis",
"=",
"0",
")",
"if",
"self",
".",
"mode",
"is",
"'... | Fit X into an embedded space.
Inputs
----------
X : array, shape (n_samples, n_features)
u,s,v : svd decomposition of X (optional)
Assigns
----------
embedding : array-like, shape (n_samples, n_components)
Stores the embedding vectors.
u,sv,v ... | [
"Fit",
"X",
"into",
"an",
"embedded",
"space",
".",
"Inputs",
"----------",
"X",
":",
"array",
"shape",
"(",
"n_samples",
"n_features",
")",
"u",
"s",
"v",
":",
"svd",
"decomposition",
"of",
"X",
"(",
"optional",
")"
] | python | train |
cloud9ers/gurumate | environment/lib/python2.7/site-packages/nose/plugins/attrib.py | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/nose/plugins/attrib.py#L126-L137 | def get_method_attr(method, cls, attr_name, default = False):
"""Look up an attribute on a method/ function.
If the attribute isn't found there, looking it up in the
method's class, if any.
"""
Missing = object()
value = getattr(method, attr_name, Missing)
if value is Missing and cls is not... | [
"def",
"get_method_attr",
"(",
"method",
",",
"cls",
",",
"attr_name",
",",
"default",
"=",
"False",
")",
":",
"Missing",
"=",
"object",
"(",
")",
"value",
"=",
"getattr",
"(",
"method",
",",
"attr_name",
",",
"Missing",
")",
"if",
"value",
"is",
"Miss... | Look up an attribute on a method/ function.
If the attribute isn't found there, looking it up in the
method's class, if any. | [
"Look",
"up",
"an",
"attribute",
"on",
"a",
"method",
"/",
"function",
".",
"If",
"the",
"attribute",
"isn",
"t",
"found",
"there",
"looking",
"it",
"up",
"in",
"the",
"method",
"s",
"class",
"if",
"any",
"."
] | python | test |
saltstack/salt | salt/modules/xapi_virt.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/xapi_virt.py#L200-L240 | def vm_info(vm_=None):
'''
Return detailed information about the vms.
If you pass a VM name in as an argument then it will return info
for just the named VM, otherwise it will return all VMs.
CLI Example:
.. code-block:: bash
salt '*' virt.vm_info
'''
with _get_xapi_session()... | [
"def",
"vm_info",
"(",
"vm_",
"=",
"None",
")",
":",
"with",
"_get_xapi_session",
"(",
")",
"as",
"xapi",
":",
"def",
"_info",
"(",
"vm_",
")",
":",
"vm_rec",
"=",
"_get_record_by_label",
"(",
"xapi",
",",
"'VM'",
",",
"vm_",
")",
"if",
"vm_rec",
"is... | Return detailed information about the vms.
If you pass a VM name in as an argument then it will return info
for just the named VM, otherwise it will return all VMs.
CLI Example:
.. code-block:: bash
salt '*' virt.vm_info | [
"Return",
"detailed",
"information",
"about",
"the",
"vms",
"."
] | python | train |
henzk/ape | ape/__init__.py | https://github.com/henzk/ape/blob/a1b7ea5e5b25c42beffeaaa5c32d94ad82634819/ape/__init__.py#L198-L205 | def superimpose(self, module):
"""
superimpose a task module on registered tasks'''
:param module: ape tasks module that is superimposed on available ape tasks
:return: None
"""
featuremonkey.compose(module, self._tasks)
self._tasks.FEATURE_SELECTION.append(module... | [
"def",
"superimpose",
"(",
"self",
",",
"module",
")",
":",
"featuremonkey",
".",
"compose",
"(",
"module",
",",
"self",
".",
"_tasks",
")",
"self",
".",
"_tasks",
".",
"FEATURE_SELECTION",
".",
"append",
"(",
"module",
".",
"__name__",
")"
] | superimpose a task module on registered tasks'''
:param module: ape tasks module that is superimposed on available ape tasks
:return: None | [
"superimpose",
"a",
"task",
"module",
"on",
"registered",
"tasks",
":",
"param",
"module",
":",
"ape",
"tasks",
"module",
"that",
"is",
"superimposed",
"on",
"available",
"ape",
"tasks",
":",
"return",
":",
"None"
] | python | train |
sublee/etc | etc/adapters/mock.py | https://github.com/sublee/etc/blob/f2be64604da5af0d7739cfacf36f55712f0fc5cb/etc/adapters/mock.py#L87-L101 | def canonicalize(self, include_nodes=True, sorted=False):
"""Generates a canonical :class:`etc.Node` object from this mock node.
"""
node_class = Directory if self.dir else Value
kwargs = {attr: getattr(self, attr) for attr in node_class.__slots__}
if self.dir:
if inc... | [
"def",
"canonicalize",
"(",
"self",
",",
"include_nodes",
"=",
"True",
",",
"sorted",
"=",
"False",
")",
":",
"node_class",
"=",
"Directory",
"if",
"self",
".",
"dir",
"else",
"Value",
"kwargs",
"=",
"{",
"attr",
":",
"getattr",
"(",
"self",
",",
"attr... | Generates a canonical :class:`etc.Node` object from this mock node. | [
"Generates",
"a",
"canonical",
":",
"class",
":",
"etc",
".",
"Node",
"object",
"from",
"this",
"mock",
"node",
"."
] | python | train |
wummel/linkchecker | linkcheck/strformat.py | https://github.com/wummel/linkchecker/blob/c2ce810c3fb00b895a841a7be6b2e78c64e7b042/linkcheck/strformat.py#L297-L312 | def limit (s, length=72):
"""If the length of the string exceeds the given limit, it will be cut
off and three dots will be appended.
@param s: the string to limit
@type s: string
@param length: maximum length
@type length: non-negative integer
@return: limited string, at most length+3 char... | [
"def",
"limit",
"(",
"s",
",",
"length",
"=",
"72",
")",
":",
"assert",
"length",
">=",
"0",
",",
"\"length limit must be a non-negative integer\"",
"if",
"not",
"s",
"or",
"len",
"(",
"s",
")",
"<=",
"length",
":",
"return",
"s",
"if",
"length",
"==",
... | If the length of the string exceeds the given limit, it will be cut
off and three dots will be appended.
@param s: the string to limit
@type s: string
@param length: maximum length
@type length: non-negative integer
@return: limited string, at most length+3 characters long | [
"If",
"the",
"length",
"of",
"the",
"string",
"exceeds",
"the",
"given",
"limit",
"it",
"will",
"be",
"cut",
"off",
"and",
"three",
"dots",
"will",
"be",
"appended",
"."
] | python | train |
tensorflow/tensor2tensor | tensor2tensor/layers/common_layers.py | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L4118-L4151 | def build(self, input_shape=None):
"""Build `Layer`."""
input_shape = tf.TensorShape(input_shape).as_list()
self.input_spec = layers().InputSpec(shape=input_shape)
if not self.layer.built:
self.layer.build(input_shape)
self.layer.built = False
if not hasattr(self.layer, "kernel"):
... | [
"def",
"build",
"(",
"self",
",",
"input_shape",
"=",
"None",
")",
":",
"input_shape",
"=",
"tf",
".",
"TensorShape",
"(",
"input_shape",
")",
".",
"as_list",
"(",
")",
"self",
".",
"input_spec",
"=",
"layers",
"(",
")",
".",
"InputSpec",
"(",
"shape",... | Build `Layer`. | [
"Build",
"Layer",
"."
] | python | train |
treycucco/bidon | bidon/experimental/transfer_tracker.py | https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/experimental/transfer_tracker.py#L54-L82 | def setup(self):
"""Creates the default relations and transfers tables. The SQL used may not work on all
databases. (It was written for SQLite3)
"""
cmds = [
"""
create table if not exists relations (
id integer not null primary key,
name text not null unique,
... | [
"def",
"setup",
"(",
"self",
")",
":",
"cmds",
"=",
"[",
"\"\"\"\n create table if not exists relations (\n id integer not null primary key,\n name text not null unique,\n completed_at datetime\n );\n \"\"\"",
",",
"\"\"\"\n create table if ... | Creates the default relations and transfers tables. The SQL used may not work on all
databases. (It was written for SQLite3) | [
"Creates",
"the",
"default",
"relations",
"and",
"transfers",
"tables",
".",
"The",
"SQL",
"used",
"may",
"not",
"work",
"on",
"all",
"databases",
".",
"(",
"It",
"was",
"written",
"for",
"SQLite3",
")"
] | python | train |
Alveo/pyalveo | pyalveo/pyalveo.py | https://github.com/Alveo/pyalveo/blob/1e9eec22bc031bc9a08066f9966565a546e6242e/pyalveo/pyalveo.py#L1317-L1339 | def add_to_item_list_by_name(self, item_urls, item_list_name):
""" Instruct the server to add the given items to the specified
Item List (which will be created if it does not already exist)
:type item_urls: List or ItemGroup
:param item_urls: List of URLs for the items to add,
... | [
"def",
"add_to_item_list_by_name",
"(",
"self",
",",
"item_urls",
",",
"item_list_name",
")",
":",
"url_name",
"=",
"urlencode",
"(",
"(",
"(",
"'name'",
",",
"item_list_name",
")",
",",
")",
")",
"request_url",
"=",
"'/item_lists?'",
"+",
"url_name",
"data",
... | Instruct the server to add the given items to the specified
Item List (which will be created if it does not already exist)
:type item_urls: List or ItemGroup
:param item_urls: List of URLs for the items to add,
or an ItemGroup object
:type item_list_name: String
:par... | [
"Instruct",
"the",
"server",
"to",
"add",
"the",
"given",
"items",
"to",
"the",
"specified",
"Item",
"List",
"(",
"which",
"will",
"be",
"created",
"if",
"it",
"does",
"not",
"already",
"exist",
")"
] | python | train |
minhhoit/yacms | yacms/core/views.py | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/core/views.py#L224-L231 | def server_error(request, template_name="errors/500.html"):
"""
Mimics Django's error handler but adds ``STATIC_URL`` to the
context.
"""
context = {"STATIC_URL": settings.STATIC_URL}
t = get_template(template_name)
return HttpResponseServerError(t.render(context, request)) | [
"def",
"server_error",
"(",
"request",
",",
"template_name",
"=",
"\"errors/500.html\"",
")",
":",
"context",
"=",
"{",
"\"STATIC_URL\"",
":",
"settings",
".",
"STATIC_URL",
"}",
"t",
"=",
"get_template",
"(",
"template_name",
")",
"return",
"HttpResponseServerErr... | Mimics Django's error handler but adds ``STATIC_URL`` to the
context. | [
"Mimics",
"Django",
"s",
"error",
"handler",
"but",
"adds",
"STATIC_URL",
"to",
"the",
"context",
"."
] | python | train |
bastibe/SoundFile | soundfile.py | https://github.com/bastibe/SoundFile/blob/161e930da9c9ea76579b6ee18a131e10bca8a605/soundfile.py#L1472-L1480 | def _format_info(format_int, format_flag=_snd.SFC_GET_FORMAT_INFO):
"""Return the ID and short description of a given format."""
format_info = _ffi.new("SF_FORMAT_INFO*")
format_info.format = format_int
_snd.sf_command(_ffi.NULL, format_flag, format_info,
_ffi.sizeof("SF_FORMAT_INFO"... | [
"def",
"_format_info",
"(",
"format_int",
",",
"format_flag",
"=",
"_snd",
".",
"SFC_GET_FORMAT_INFO",
")",
":",
"format_info",
"=",
"_ffi",
".",
"new",
"(",
"\"SF_FORMAT_INFO*\"",
")",
"format_info",
".",
"format",
"=",
"format_int",
"_snd",
".",
"sf_command",
... | Return the ID and short description of a given format. | [
"Return",
"the",
"ID",
"and",
"short",
"description",
"of",
"a",
"given",
"format",
"."
] | python | train |
danilobellini/audiolazy | examples/save_and_memoize_synth.py | https://github.com/danilobellini/audiolazy/blob/dba0a278937909980ed40b976d866b8e97c35dee/examples/save_and_memoize_synth.py#L92-L110 | def new_note_track(env, synth):
"""
Audio track with the frequencies.
Parameters
----------
env:
Envelope Stream (which imposes the duration).
synth:
One-argument function that receives a frequency (in rad/sample) and
returns a Stream instance (a synthesized note).
Returns
-------
Endles... | [
"def",
"new_note_track",
"(",
"env",
",",
"synth",
")",
":",
"list_env",
"=",
"list",
"(",
"env",
")",
"return",
"chain",
".",
"from_iterable",
"(",
"synth",
"(",
"freq",
")",
"*",
"list_env",
"for",
"freq",
"in",
"freq_gen",
"(",
")",
")"
] | Audio track with the frequencies.
Parameters
----------
env:
Envelope Stream (which imposes the duration).
synth:
One-argument function that receives a frequency (in rad/sample) and
returns a Stream instance (a synthesized note).
Returns
-------
Endless Stream instance that joins synthesized... | [
"Audio",
"track",
"with",
"the",
"frequencies",
"."
] | python | train |
michael-lazar/rtv | rtv/packages/praw/objects.py | https://github.com/michael-lazar/rtv/blob/ccef2af042566ad384977028cf0bde01bc524dda/rtv/packages/praw/objects.py#L994-L1010 | def get_upvoted(self, *args, **kwargs):
"""Return a listing of the Submissions the user has upvoted.
:returns: get_content generator of Submission items.
The additional parameters are passed directly into
:meth:`.get_content`. Note: the `url` parameter cannot be altered.
As a ... | [
"def",
"get_upvoted",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_use_oauth'",
"]",
"=",
"self",
".",
"reddit_session",
".",
"is_oauth_session",
"(",
")",
"return",
"_get_redditor_listing",
"(",
"'upvoted'",
")",
"("... | Return a listing of the Submissions the user has upvoted.
:returns: get_content generator of Submission items.
The additional parameters are passed directly into
:meth:`.get_content`. Note: the `url` parameter cannot be altered.
As a default, this listing is only accessible by the use... | [
"Return",
"a",
"listing",
"of",
"the",
"Submissions",
"the",
"user",
"has",
"upvoted",
"."
] | python | train |
chinapnr/fishbase | fishbase/fish_data.py | https://github.com/chinapnr/fishbase/blob/23c5147a6bc0d8ed36409e55352ffb2c5b0edc82/fishbase/fish_data.py#L197-L281 | def get_zone_info(cls, area_str, match_type='EXACT', result_type='LIST'):
"""
输入包含省份、城市、地区信息的内容,返回地区编号;
:param:
* area_str: (string) 要查询的区域,省份、城市、地区信息,比如 北京市
* match_type: (string) 查询匹配模式,默认值 'EXACT',表示精确匹配,可选 'FUZZY',表示模糊查询
* result_type: (string) 返回结果数量类型,默... | [
"def",
"get_zone_info",
"(",
"cls",
",",
"area_str",
",",
"match_type",
"=",
"'EXACT'",
",",
"result_type",
"=",
"'LIST'",
")",
":",
"values",
"=",
"[",
"]",
"if",
"match_type",
"==",
"'EXACT'",
":",
"values",
"=",
"sqlite_query",
"(",
"'fish_data.sqlite'",
... | 输入包含省份、城市、地区信息的内容,返回地区编号;
:param:
* area_str: (string) 要查询的区域,省份、城市、地区信息,比如 北京市
* match_type: (string) 查询匹配模式,默认值 'EXACT',表示精确匹配,可选 'FUZZY',表示模糊查询
* result_type: (string) 返回结果数量类型,默认值 'LIST',表示返回列表,可选 'SINGLE_STR',返回结果的第一个地区编号字符串
:returns:
* 返回类型 根据 resu... | [
"输入包含省份、城市、地区信息的内容,返回地区编号;"
] | python | train |
pyokagan/pyglreg | glreg.py | https://github.com/pyokagan/pyglreg/blob/68fa5a6c6cee8667879840fbbcc7d30f52852915/glreg.py#L533-L552 | def get_requires(self, api=None, profile=None, support=None):
"""Returns filtered list of Require objects in this registry
:param str api: Return Require objects with this api name or None to
return all Require objects.
:param str profile: Return Require objects with thi... | [
"def",
"get_requires",
"(",
"self",
",",
"api",
"=",
"None",
",",
"profile",
"=",
"None",
",",
"support",
"=",
"None",
")",
":",
"out",
"=",
"[",
"]",
"for",
"ft",
"in",
"self",
".",
"get_features",
"(",
"api",
")",
":",
"out",
".",
"extend",
"("... | Returns filtered list of Require objects in this registry
:param str api: Return Require objects with this api name or None to
return all Require objects.
:param str profile: Return Require objects with this profile or None
to return all Require objec... | [
"Returns",
"filtered",
"list",
"of",
"Require",
"objects",
"in",
"this",
"registry"
] | python | train |
openid/JWTConnect-Python-CryptoJWT | src/cryptojwt/jwk/rsa.py | https://github.com/openid/JWTConnect-Python-CryptoJWT/blob/8863cfbfe77ca885084870b234a66b55bd52930c/src/cryptojwt/jwk/rsa.py#L244-L259 | def cmp_private_numbers(pn1, pn2):
"""
Compare 2 sets of private numbers. This is for comparing 2
private RSA keys.
:param pn1: The set of values belonging to the 1st key
:param pn2: The set of values belonging to the 2nd key
:return: True is the sets are the same otherwise False.
"""
i... | [
"def",
"cmp_private_numbers",
"(",
"pn1",
",",
"pn2",
")",
":",
"if",
"not",
"cmp_public_numbers",
"(",
"pn1",
".",
"public_numbers",
",",
"pn2",
".",
"public_numbers",
")",
":",
"return",
"False",
"for",
"param",
"in",
"[",
"'d'",
",",
"'p'",
",",
"'q'"... | Compare 2 sets of private numbers. This is for comparing 2
private RSA keys.
:param pn1: The set of values belonging to the 1st key
:param pn2: The set of values belonging to the 2nd key
:return: True is the sets are the same otherwise False. | [
"Compare",
"2",
"sets",
"of",
"private",
"numbers",
".",
"This",
"is",
"for",
"comparing",
"2",
"private",
"RSA",
"keys",
"."
] | python | train |
opencobra/cobrapy | cobra/manipulation/delete.py | https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/manipulation/delete.py#L36-L56 | def prune_unused_reactions(cobra_model):
"""Remove reactions with no assigned metabolites, returns pruned model
Parameters
----------
cobra_model: class:`~cobra.core.Model.Model` object
the model to remove unused reactions from
Returns
-------
output_model: class:`~cobra.core.Model... | [
"def",
"prune_unused_reactions",
"(",
"cobra_model",
")",
":",
"output_model",
"=",
"cobra_model",
".",
"copy",
"(",
")",
"reactions_to_prune",
"=",
"[",
"r",
"for",
"r",
"in",
"output_model",
".",
"reactions",
"if",
"len",
"(",
"r",
".",
"metabolites",
")",... | Remove reactions with no assigned metabolites, returns pruned model
Parameters
----------
cobra_model: class:`~cobra.core.Model.Model` object
the model to remove unused reactions from
Returns
-------
output_model: class:`~cobra.core.Model.Model` object
input model with unused r... | [
"Remove",
"reactions",
"with",
"no",
"assigned",
"metabolites",
"returns",
"pruned",
"model"
] | python | valid |
ethereum/lahja | lahja/endpoint.py | https://github.com/ethereum/lahja/blob/e3993c5892232887a11800ed3e66332febcee96b/lahja/endpoint.py#L188-L196 | async def start_serving(self,
connection_config: ConnectionConfig,
loop: Optional[asyncio.AbstractEventLoop] = None) -> None:
"""
Start serving this :class:`~lahja.endpoint.Endpoint` so that it can receive events. Await
until the :class:`~l... | [
"async",
"def",
"start_serving",
"(",
"self",
",",
"connection_config",
":",
"ConnectionConfig",
",",
"loop",
":",
"Optional",
"[",
"asyncio",
".",
"AbstractEventLoop",
"]",
"=",
"None",
")",
"->",
"None",
":",
"self",
".",
"start_serving_nowait",
"(",
"connec... | Start serving this :class:`~lahja.endpoint.Endpoint` so that it can receive events. Await
until the :class:`~lahja.endpoint.Endpoint` is ready. | [
"Start",
"serving",
"this",
":",
"class",
":",
"~lahja",
".",
"endpoint",
".",
"Endpoint",
"so",
"that",
"it",
"can",
"receive",
"events",
".",
"Await",
"until",
"the",
":",
"class",
":",
"~lahja",
".",
"endpoint",
".",
"Endpoint",
"is",
"ready",
"."
] | python | train |
UCBerkeleySETI/blimpy | blimpy/calib_utils/fluxcal.py | https://github.com/UCBerkeleySETI/blimpy/blob/b8822d3e3e911944370d84371a91fa0c29e9772e/blimpy/calib_utils/fluxcal.py#L92-L137 | def integrate_calib(name,chan_per_coarse,fullstokes=False,**kwargs):
'''
Folds Stokes I noise diode data and integrates along coarse channels
Parameters
----------
name : str
Path to noise diode filterbank file
chan_per_coarse : int
Number of frequency bins per coarse channel
... | [
"def",
"integrate_calib",
"(",
"name",
",",
"chan_per_coarse",
",",
"fullstokes",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"#Load data",
"obs",
"=",
"Waterfall",
"(",
"name",
",",
"max_load",
"=",
"150",
")",
"data",
"=",
"obs",
".",
"data",
"#... | Folds Stokes I noise diode data and integrates along coarse channels
Parameters
----------
name : str
Path to noise diode filterbank file
chan_per_coarse : int
Number of frequency bins per coarse channel
fullstokes : boolean
Use fullstokes=True if data is in IQUV format or j... | [
"Folds",
"Stokes",
"I",
"noise",
"diode",
"data",
"and",
"integrates",
"along",
"coarse",
"channels"
] | python | test |
erdc/RAPIDpy | RAPIDpy/postprocess/goodness_of_fit.py | https://github.com/erdc/RAPIDpy/blob/50e14e130554b254a00ff23b226cd7e4c6cfe91a/RAPIDpy/postprocess/goodness_of_fit.py#L21-L32 | def filter_nan(s, o):
"""
this functions removed the data from simulated and observed data
whereever the observed data contains nan
this is used by all other functions, otherwise they will produce nan as
output
"""
data = np.array([s.flatten(), o.flatten()])
data = ... | [
"def",
"filter_nan",
"(",
"s",
",",
"o",
")",
":",
"data",
"=",
"np",
".",
"array",
"(",
"[",
"s",
".",
"flatten",
"(",
")",
",",
"o",
".",
"flatten",
"(",
")",
"]",
")",
"data",
"=",
"np",
".",
"transpose",
"(",
"data",
")",
"data",
"=",
"... | this functions removed the data from simulated and observed data
whereever the observed data contains nan
this is used by all other functions, otherwise they will produce nan as
output | [
"this",
"functions",
"removed",
"the",
"data",
"from",
"simulated",
"and",
"observed",
"data",
"whereever",
"the",
"observed",
"data",
"contains",
"nan"
] | python | train |
wbond/oscrypto | oscrypto/_openssl/_libcrypto.py | https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/_openssl/_libcrypto.py#L57-L85 | def handle_openssl_error(result, exception_class=None):
"""
Checks if an error occured, and if so throws an OSError containing the
last OpenSSL error message
:param result:
An integer result code - 1 or greater indicates success
:param exception_class:
The exception class to use fo... | [
"def",
"handle_openssl_error",
"(",
"result",
",",
"exception_class",
"=",
"None",
")",
":",
"if",
"result",
">",
"0",
":",
"return",
"if",
"exception_class",
"is",
"None",
":",
"exception_class",
"=",
"OSError",
"error_num",
"=",
"libcrypto",
".",
"ERR_get_er... | Checks if an error occured, and if so throws an OSError containing the
last OpenSSL error message
:param result:
An integer result code - 1 or greater indicates success
:param exception_class:
The exception class to use for the exception if an error occurred
:raises:
OSError -... | [
"Checks",
"if",
"an",
"error",
"occured",
"and",
"if",
"so",
"throws",
"an",
"OSError",
"containing",
"the",
"last",
"OpenSSL",
"error",
"message"
] | python | valid |
rhgrant10/Groupy | groupy/utils.py | https://github.com/rhgrant10/Groupy/blob/ffd8cac57586fa1c218e3b4bfaa531142c3be766/groupy/utils.py#L89-L104 | def find(self, objects):
"""Find exactly one match in the list of objects.
:param objects: objects to filter
:type objects: :class:`list`
:return: the one matching object
:raises groupy.exceptions.NoMatchesError: if no objects match
:raises groupy.exceptions.MultipleMatc... | [
"def",
"find",
"(",
"self",
",",
"objects",
")",
":",
"matches",
"=",
"list",
"(",
"self",
".",
"__call__",
"(",
"objects",
")",
")",
"if",
"not",
"matches",
":",
"raise",
"exceptions",
".",
"NoMatchesError",
"(",
"objects",
",",
"self",
".",
"tests",
... | Find exactly one match in the list of objects.
:param objects: objects to filter
:type objects: :class:`list`
:return: the one matching object
:raises groupy.exceptions.NoMatchesError: if no objects match
:raises groupy.exceptions.MultipleMatchesError: if multiple objects match | [
"Find",
"exactly",
"one",
"match",
"in",
"the",
"list",
"of",
"objects",
"."
] | python | train |
broadinstitute/fiss | firecloud/api.py | https://github.com/broadinstitute/fiss/blob/dddf91547479506dbbafb69ec84d44dcc4a94ab4/firecloud/api.py#L918-L935 | def update_repository_config_acl(namespace, config, snapshot_id, acl_updates):
"""Set configuration permissions.
The configuration should exist in the methods repository.
Args:
namespace (str): Configuration namespace
config (str): Configuration name
snapshot_id (int): snapshot_id ... | [
"def",
"update_repository_config_acl",
"(",
"namespace",
",",
"config",
",",
"snapshot_id",
",",
"acl_updates",
")",
":",
"uri",
"=",
"\"configurations/{0}/{1}/{2}/permissions\"",
".",
"format",
"(",
"namespace",
",",
"config",
",",
"snapshot_id",
")",
"return",
"__... | Set configuration permissions.
The configuration should exist in the methods repository.
Args:
namespace (str): Configuration namespace
config (str): Configuration name
snapshot_id (int): snapshot_id of the method
acl_updates (list(dict)): List of access control updates
Sw... | [
"Set",
"configuration",
"permissions",
"."
] | python | train |
saltstack/salt | salt/states/logadm.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/logadm.py#L117-L168 | def remove(name, log_file=None):
'''
Remove a log from the logadm configuration
name : string
entryname
log_file : string
(optional) log file path
.. note::
If log_file is specified it will be used instead of the entry name.
'''
ret = {'name': name,
'cha... | [
"def",
"remove",
"(",
"name",
",",
"log_file",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",",
"'result'",
":",
"None",
",",
"'comment'",
":",
"''",
"}",
"# retrieve all log configuration",
"config",
... | Remove a log from the logadm configuration
name : string
entryname
log_file : string
(optional) log file path
.. note::
If log_file is specified it will be used instead of the entry name. | [
"Remove",
"a",
"log",
"from",
"the",
"logadm",
"configuration"
] | python | train |
Duke-GCB/DukeDSClient | ddsc/versioncheck.py | https://github.com/Duke-GCB/DukeDSClient/blob/117f68fb9bae82e4c81ea487ad5d61ac350f3726/ddsc/versioncheck.py#L18-L31 | def get_pypi_version():
"""
Returns the version info from pypi for this app.
"""
try:
response = requests.get(PYPI_URL, timeout=HALF_SECOND_TIMEOUT)
response.raise_for_status()
data = response.json()
version_str = data["info"]["version"]
return _parse_version_str(... | [
"def",
"get_pypi_version",
"(",
")",
":",
"try",
":",
"response",
"=",
"requests",
".",
"get",
"(",
"PYPI_URL",
",",
"timeout",
"=",
"HALF_SECOND_TIMEOUT",
")",
"response",
".",
"raise_for_status",
"(",
")",
"data",
"=",
"response",
".",
"json",
"(",
")",
... | Returns the version info from pypi for this app. | [
"Returns",
"the",
"version",
"info",
"from",
"pypi",
"for",
"this",
"app",
"."
] | python | train |
learningequality/ricecooker | ricecooker/utils/jsontrees.py | https://github.com/learningequality/ricecooker/blob/2f0385282500cb77ef2894646c6f9ce11bd7a853/ricecooker/utils/jsontrees.py#L48-L56 | def read_tree_from_json(srcpath):
"""
Load ricecooker json tree data from json file at `srcpath`.
"""
with open(srcpath) as infile:
json_tree = json.load(infile)
if json_tree is None:
raise ValueError('Could not find ricecooker json tree')
return json_tree | [
"def",
"read_tree_from_json",
"(",
"srcpath",
")",
":",
"with",
"open",
"(",
"srcpath",
")",
"as",
"infile",
":",
"json_tree",
"=",
"json",
".",
"load",
"(",
"infile",
")",
"if",
"json_tree",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'Could not find ... | Load ricecooker json tree data from json file at `srcpath`. | [
"Load",
"ricecooker",
"json",
"tree",
"data",
"from",
"json",
"file",
"at",
"srcpath",
"."
] | python | train |
vtkiorg/vtki | vtki/common.py | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/common.py#L907-L920 | def update(self, data):
"""
Update this dictionary with th key-value pairs from a given
dictionary
"""
if not isinstance(data, dict):
raise TypeError('Data to update must be in a dictionary.')
for k, v in data.items():
arr = np.array(v)
... | [
"def",
"update",
"(",
"self",
",",
"data",
")",
":",
"if",
"not",
"isinstance",
"(",
"data",
",",
"dict",
")",
":",
"raise",
"TypeError",
"(",
"'Data to update must be in a dictionary.'",
")",
"for",
"k",
",",
"v",
"in",
"data",
".",
"items",
"(",
")",
... | Update this dictionary with th key-value pairs from a given
dictionary | [
"Update",
"this",
"dictionary",
"with",
"th",
"key",
"-",
"value",
"pairs",
"from",
"a",
"given",
"dictionary"
] | python | train |
RJT1990/pyflux | pyflux/ssm/dynlin.py | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/ssm/dynlin.py#L115-L138 | def _ss_matrices(self, beta):
""" Creates the state space matrices required
Parameters
----------
beta : np.array
Contains untransformed starting values for latent variables
Returns
----------
T, Z, R, Q, H : np.array
State space matrices... | [
"def",
"_ss_matrices",
"(",
"self",
",",
"beta",
")",
":",
"T",
"=",
"np",
".",
"identity",
"(",
"self",
".",
"z_no",
"-",
"1",
")",
"H",
"=",
"np",
".",
"identity",
"(",
"1",
")",
"*",
"self",
".",
"latent_variables",
".",
"z_list",
"[",
"0",
... | Creates the state space matrices required
Parameters
----------
beta : np.array
Contains untransformed starting values for latent variables
Returns
----------
T, Z, R, Q, H : np.array
State space matrices used in KFS algorithm | [
"Creates",
"the",
"state",
"space",
"matrices",
"required"
] | python | train |
apache/incubator-mxnet | python/mxnet/recordio.py | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/recordio.py#L358-L391 | def pack(header, s):
"""Pack a string into MXImageRecord.
Parameters
----------
header : IRHeader
Header of the image record.
``header.label`` can be a number or an array. See more detail in ``IRHeader``.
s : str
Raw image string to be packed.
Returns
-------
s ... | [
"def",
"pack",
"(",
"header",
",",
"s",
")",
":",
"header",
"=",
"IRHeader",
"(",
"*",
"header",
")",
"if",
"isinstance",
"(",
"header",
".",
"label",
",",
"numbers",
".",
"Number",
")",
":",
"header",
"=",
"header",
".",
"_replace",
"(",
"flag",
"... | Pack a string into MXImageRecord.
Parameters
----------
header : IRHeader
Header of the image record.
``header.label`` can be a number or an array. See more detail in ``IRHeader``.
s : str
Raw image string to be packed.
Returns
-------
s : str
The packed str... | [
"Pack",
"a",
"string",
"into",
"MXImageRecord",
"."
] | python | train |
saltstack/salt | salt/states/nexus.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/nexus.py#L27-L110 | def downloaded(name, artifact, target_dir='/tmp', target_file=None):
'''
Ensures that the artifact from nexus exists at given location. If it doesn't exist, then
it will be downloaded. If it already exists then the checksum of existing file is checked
against checksum in nexus. If it is different then t... | [
"def",
"downloaded",
"(",
"name",
",",
"artifact",
",",
"target_dir",
"=",
"'/tmp'",
",",
"target_file",
"=",
"None",
")",
":",
"log",
".",
"debug",
"(",
"\" ======================== STATE: nexus.downloaded (name: %s) \"",
",",
"name",
")",
"ret",
"=",
"{",
"'na... | Ensures that the artifact from nexus exists at given location. If it doesn't exist, then
it will be downloaded. If it already exists then the checksum of existing file is checked
against checksum in nexus. If it is different then the step will fail.
artifact
Details of the artifact to be downloaded... | [
"Ensures",
"that",
"the",
"artifact",
"from",
"nexus",
"exists",
"at",
"given",
"location",
".",
"If",
"it",
"doesn",
"t",
"exist",
"then",
"it",
"will",
"be",
"downloaded",
".",
"If",
"it",
"already",
"exists",
"then",
"the",
"checksum",
"of",
"existing",... | python | train |
hishnash/djangochannelsrestframework | djangochannelsrestframework/consumers.py | https://github.com/hishnash/djangochannelsrestframework/blob/19fdec7efd785b1a94d19612a8de934e1948e344/djangochannelsrestframework/consumers.py#L104-L123 | async def handle_exception(self, exc: Exception, action: str, request_id):
"""
Handle any exception that occurs, by sending an appropriate message
"""
if isinstance(exc, APIException):
await self.reply(
action=action,
errors=self._format_errors... | [
"async",
"def",
"handle_exception",
"(",
"self",
",",
"exc",
":",
"Exception",
",",
"action",
":",
"str",
",",
"request_id",
")",
":",
"if",
"isinstance",
"(",
"exc",
",",
"APIException",
")",
":",
"await",
"self",
".",
"reply",
"(",
"action",
"=",
"ac... | Handle any exception that occurs, by sending an appropriate message | [
"Handle",
"any",
"exception",
"that",
"occurs",
"by",
"sending",
"an",
"appropriate",
"message"
] | python | train |
dschreij/python-mediadecoder | mediadecoder/decoder.py | https://github.com/dschreij/python-mediadecoder/blob/f01b02d790f2abc52d9792e43076cf4cb7d3ce51/mediadecoder/decoder.py#L345-L357 | def __calculate_audio_frames(self):
""" Aligns audio with video.
This should be called for instance after a seeking operation or resuming
from a pause. """
if self.audioformat is None:
return
start_frame = self.clock.current_frame
totalsize = int(self.clip.audio.fps*self.clip.audio.duration)
self.au... | [
"def",
"__calculate_audio_frames",
"(",
"self",
")",
":",
"if",
"self",
".",
"audioformat",
"is",
"None",
":",
"return",
"start_frame",
"=",
"self",
".",
"clock",
".",
"current_frame",
"totalsize",
"=",
"int",
"(",
"self",
".",
"clip",
".",
"audio",
".",
... | Aligns audio with video.
This should be called for instance after a seeking operation or resuming
from a pause. | [
"Aligns",
"audio",
"with",
"video",
".",
"This",
"should",
"be",
"called",
"for",
"instance",
"after",
"a",
"seeking",
"operation",
"or",
"resuming",
"from",
"a",
"pause",
"."
] | python | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.