nwo stringlengths 5 106 | sha stringlengths 40 40 | path stringlengths 4 174 | language stringclasses 1
value | identifier stringlengths 1 140 | parameters stringlengths 0 87.7k | argument_list stringclasses 1
value | return_statement stringlengths 0 426k | docstring stringlengths 0 64.3k | docstring_summary stringlengths 0 26.3k | docstring_tokens list | function stringlengths 18 4.83M | function_tokens list | url stringlengths 83 304 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
JacquesLucke/animation_nodes | b1e3ace8dcb0a771fd882fc3ac4e490b009fa0d1 | animation_nodes/nodes/mesh/edge_info.py | python | EdgeInfoNode.getExecutionCode | (self, required) | [] | def getExecutionCode(self, required):
if self.useEdgeList:
yield from self.iterExecutionCode_List(required)
else:
yield from self.iterExecutionCode_Single(required) | [
"def",
"getExecutionCode",
"(",
"self",
",",
"required",
")",
":",
"if",
"self",
".",
"useEdgeList",
":",
"yield",
"from",
"self",
".",
"iterExecutionCode_List",
"(",
"required",
")",
"else",
":",
"yield",
"from",
"self",
".",
"iterExecutionCode_Single",
"(",
... | https://github.com/JacquesLucke/animation_nodes/blob/b1e3ace8dcb0a771fd882fc3ac4e490b009fa0d1/animation_nodes/nodes/mesh/edge_info.py#L39-L43 | ||||
renatoviolin/Question-Answering-Albert-Electra | 8ca885c27c89af16bb2484ea0e6aeb960801259a | rank_models/use.py | python | get_similarity | (query, documents) | return res | [] | def get_similarity(query, documents):
q = encode(query)
doc = encode(documents)
res = []
for i, v in enumerate(doc):
res.append(tuple([i, cosine(q, v.reshape(1, -1))[0][0]]))
res.sort(key=lambda x: x[1], reverse=True)
return res | [
"def",
"get_similarity",
"(",
"query",
",",
"documents",
")",
":",
"q",
"=",
"encode",
"(",
"query",
")",
"doc",
"=",
"encode",
"(",
"documents",
")",
"res",
"=",
"[",
"]",
"for",
"i",
",",
"v",
"in",
"enumerate",
"(",
"doc",
")",
":",
"res",
"."... | https://github.com/renatoviolin/Question-Answering-Albert-Electra/blob/8ca885c27c89af16bb2484ea0e6aeb960801259a/rank_models/use.py#L77-L85 | |||
jhorey/ferry | bbaa047df08386e17130a939e20fde5e840d1ffa | ferry/config/cassandra/cassandraclientconfig.py | python | CassandraClientInitializer.get_total_instances | (self, num_instances, layers) | return instances | Get total number of instances. | Get total number of instances. | [
"Get",
"total",
"number",
"of",
"instances",
"."
] | def get_total_instances(self, num_instances, layers):
"""
Get total number of instances.
"""
instances = []
for i in range(num_instances):
instances.append('cassandra-client')
return instances | [
"def",
"get_total_instances",
"(",
"self",
",",
"num_instances",
",",
"layers",
")",
":",
"instances",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"num_instances",
")",
":",
"instances",
".",
"append",
"(",
"'cassandra-client'",
")",
"return",
"instances"... | https://github.com/jhorey/ferry/blob/bbaa047df08386e17130a939e20fde5e840d1ffa/ferry/config/cassandra/cassandraclientconfig.py#L73-L82 | |
google/jax | bebe9845a873b3203f8050395255f173ba3bbb71 | jax/_src/lax/lax.py | python | expand_dims | (array: Array, dimensions: Sequence[int]) | return broadcast_in_dim(array, result_shape, broadcast_dims) | Insert any number of size 1 dimensions into an array. | Insert any number of size 1 dimensions into an array. | [
"Insert",
"any",
"number",
"of",
"size",
"1",
"dimensions",
"into",
"an",
"array",
"."
] | def expand_dims(array: Array, dimensions: Sequence[int]) -> Array:
"""Insert any number of size 1 dimensions into an array."""
ndim_out = np.ndim(array) + len(dimensions)
dims_set = frozenset(canonicalize_axis(i, ndim_out) for i in dimensions)
result_shape = list(np.shape(array))
for i in sorted(dims_set):
result_shape.insert(i, 1)
broadcast_dims = [i for i in range(ndim_out) if i not in dims_set]
return broadcast_in_dim(array, result_shape, broadcast_dims) | [
"def",
"expand_dims",
"(",
"array",
":",
"Array",
",",
"dimensions",
":",
"Sequence",
"[",
"int",
"]",
")",
"->",
"Array",
":",
"ndim_out",
"=",
"np",
".",
"ndim",
"(",
"array",
")",
"+",
"len",
"(",
"dimensions",
")",
"dims_set",
"=",
"frozenset",
"... | https://github.com/google/jax/blob/bebe9845a873b3203f8050395255f173ba3bbb71/jax/_src/lax/lax.py#L1143-L1151 | |
santatic/web2attack | 44b6e481a3d56cf0d98073ae0fb69833dda563d9 | w2a/lib/smtpd.py | python | SMTPChannel.__conn | (self, value) | [] | def __conn(self, value):
warn("Setting __conn attribute on SMTPChannel is deprecated, "
"set 'conn' instead", PendingDeprecationWarning, 2)
self.conn = value | [
"def",
"__conn",
"(",
"self",
",",
"value",
")",
":",
"warn",
"(",
"\"Setting __conn attribute on SMTPChannel is deprecated, \"",
"\"set 'conn' instead\"",
",",
"PendingDeprecationWarning",
",",
"2",
")",
"self",
".",
"conn",
"=",
"value"
] | https://github.com/santatic/web2attack/blob/44b6e481a3d56cf0d98073ae0fb69833dda563d9/w2a/lib/smtpd.py#L247-L250 | ||||
autotest/autotest | 4614ae5f550cc888267b9a419e4b90deb54f8fae | frontend/afe/rpc_interface.py | python | get_jobs | (not_yet_run=False, running=False, finished=False, **filter_data) | return rpc_utils.prepare_for_serialization(job_dicts) | Extra filter args for get_jobs:
-not_yet_run: Include only jobs that have not yet started running.
-running: Include only jobs that have start running but for which not
all hosts have completed.
-finished: Include only jobs for which all hosts have completed (or
aborted).
At most one of these three fields should be specified. | Extra filter args for get_jobs:
-not_yet_run: Include only jobs that have not yet started running.
-running: Include only jobs that have start running but for which not
all hosts have completed.
-finished: Include only jobs for which all hosts have completed (or
aborted).
At most one of these three fields should be specified. | [
"Extra",
"filter",
"args",
"for",
"get_jobs",
":",
"-",
"not_yet_run",
":",
"Include",
"only",
"jobs",
"that",
"have",
"not",
"yet",
"started",
"running",
".",
"-",
"running",
":",
"Include",
"only",
"jobs",
"that",
"have",
"start",
"running",
"but",
"for"... | def get_jobs(not_yet_run=False, running=False, finished=False, **filter_data):
"""
Extra filter args for get_jobs:
-not_yet_run: Include only jobs that have not yet started running.
-running: Include only jobs that have start running but for which not
all hosts have completed.
-finished: Include only jobs for which all hosts have completed (or
aborted).
At most one of these three fields should be specified.
"""
filter_data['extra_args'] = rpc_utils.extra_job_filters(not_yet_run,
running,
finished)
job_dicts = []
jobs = list(models.Job.query_objects(filter_data))
models.Job.objects.populate_relationships(jobs, models.Label,
'dependencies')
models.Job.objects.populate_relationships(jobs, models.JobKeyval, 'keyvals')
for job in jobs:
job_dict = job.get_object_dict()
job_dict['dependencies'] = ','.join(label.name
for label in job.dependencies)
job_dict['keyvals'] = dict((keyval.key, keyval.value)
for keyval in job.keyvals)
job_dicts.append(job_dict)
return rpc_utils.prepare_for_serialization(job_dicts) | [
"def",
"get_jobs",
"(",
"not_yet_run",
"=",
"False",
",",
"running",
"=",
"False",
",",
"finished",
"=",
"False",
",",
"*",
"*",
"filter_data",
")",
":",
"filter_data",
"[",
"'extra_args'",
"]",
"=",
"rpc_utils",
".",
"extra_job_filters",
"(",
"not_yet_run",... | https://github.com/autotest/autotest/blob/4614ae5f550cc888267b9a419e4b90deb54f8fae/frontend/afe/rpc_interface.py#L1013-L1038 | |
getsentry/snuba | 6f92898b37c89d5d41a1894b313726d85ede0170 | snuba/web/query.py | python | _format_storage_query_and_run | (
timer: Timer,
query_metadata: SnubaQueryMetadata,
referrer: str,
clickhouse_query: Union[Query, CompositeQuery[Table]],
request_settings: RequestSettings,
reader: Reader,
robust: bool,
concurrent_queries_gauge: Optional[Gauge] = None,
) | Formats the Storage Query and pass it to the DB specific code for execution. | Formats the Storage Query and pass it to the DB specific code for execution. | [
"Formats",
"the",
"Storage",
"Query",
"and",
"pass",
"it",
"to",
"the",
"DB",
"specific",
"code",
"for",
"execution",
"."
] | def _format_storage_query_and_run(
timer: Timer,
query_metadata: SnubaQueryMetadata,
referrer: str,
clickhouse_query: Union[Query, CompositeQuery[Table]],
request_settings: RequestSettings,
reader: Reader,
robust: bool,
concurrent_queries_gauge: Optional[Gauge] = None,
) -> QueryResult:
"""
Formats the Storage Query and pass it to the DB specific code for execution.
"""
from_clause = clickhouse_query.get_from_clause()
visitor = TablesCollector()
visitor.visit(from_clause)
table_names = ",".join(sorted(visitor.get_tables()))
with sentry_sdk.start_span(description="create_query", op="db") as span:
_apply_turbo_sampling_if_needed(clickhouse_query, request_settings)
formatted_query = format_query(clickhouse_query)
span.set_data("query", formatted_query.structured())
span.set_data(
"query_size_bytes", _string_size_in_bytes(formatted_query.get_sql())
)
sentry_sdk.set_tag(
"query_size_group", get_query_size_group(formatted_query.get_sql())
)
metrics.increment("execute")
timer.mark("prepare_query")
stats = {
"clickhouse_table": table_names,
"final": visitor.any_final(),
"referrer": referrer,
"sample": visitor.get_sample_rate(),
}
with sentry_sdk.start_span(description=formatted_query.get_sql(), op="db") as span:
span.set_tag("table", table_names)
def execute() -> QueryResult:
return raw_query(
clickhouse_query,
request_settings,
formatted_query,
reader,
timer,
query_metadata,
stats,
span.trace_id,
robust=robust,
)
if concurrent_queries_gauge is not None:
with concurrent_queries_gauge:
return execute()
else:
return execute() | [
"def",
"_format_storage_query_and_run",
"(",
"timer",
":",
"Timer",
",",
"query_metadata",
":",
"SnubaQueryMetadata",
",",
"referrer",
":",
"str",
",",
"clickhouse_query",
":",
"Union",
"[",
"Query",
",",
"CompositeQuery",
"[",
"Table",
"]",
"]",
",",
"request_s... | https://github.com/getsentry/snuba/blob/6f92898b37c89d5d41a1894b313726d85ede0170/snuba/web/query.py#L282-L341 | ||
mpatacchiola/deepgaze | fddc129da9692d7a2002d0df5baf142eae3b722b | deepgaze/color_classification.py | python | HistogramColorClassifier.addModelHistogram | (self, model_frame, name='') | Add the histogram to internal container. If the name of the object
is already present then replace that histogram with a new one.
@param model_frame the frame to add to the model, its histogram
is obtained and saved in internal list.
@param name a string representing the name of the model.
If nothing is specified then the name will be the index of the element. | Add the histogram to internal container. If the name of the object
is already present then replace that histogram with a new one. | [
"Add",
"the",
"histogram",
"to",
"internal",
"container",
".",
"If",
"the",
"name",
"of",
"the",
"object",
"is",
"already",
"present",
"then",
"replace",
"that",
"histogram",
"with",
"a",
"new",
"one",
"."
] | def addModelHistogram(self, model_frame, name=''):
"""Add the histogram to internal container. If the name of the object
is already present then replace that histogram with a new one.
@param model_frame the frame to add to the model, its histogram
is obtained and saved in internal list.
@param name a string representing the name of the model.
If nothing is specified then the name will be the index of the element.
"""
if(self.hist_type=='HSV'): model_frame = cv2.cvtColor(model_frame, cv2.COLOR_BGR2HSV)
elif(self.hist_type=='GRAY'): model_frame = cv2.cvtColor(model_frame, cv2.COLOR_BGR2GRAY)
elif(self.hist_type=='RGB'): model_frame = cv2.cvtColor(model_frame, cv2.COLOR_BGR2RGB)
hist = cv2.calcHist([model_frame], self.channels, None, self.hist_size, self.hist_range)
hist = cv2.normalize(hist, hist).flatten()
if name == '': name = str(len(self.model_list))
if name not in self.name_list:
self.model_list.append(hist)
self.name_list.append(name)
else:
for i in range(len(self.name_list)):
if self.name_list[i] == name:
self.model_list[i] = hist
break | [
"def",
"addModelHistogram",
"(",
"self",
",",
"model_frame",
",",
"name",
"=",
"''",
")",
":",
"if",
"(",
"self",
".",
"hist_type",
"==",
"'HSV'",
")",
":",
"model_frame",
"=",
"cv2",
".",
"cvtColor",
"(",
"model_frame",
",",
"cv2",
".",
"COLOR_BGR2HSV",... | https://github.com/mpatacchiola/deepgaze/blob/fddc129da9692d7a2002d0df5baf142eae3b722b/deepgaze/color_classification.py#L63-L85 | ||
openshift/openshift-tools | 1188778e728a6e4781acf728123e5b356380fe6f | openshift/installer/vendored/openshift-ansible-3.11.28-1/roles/lib_openshift/library/oc_adm_router.py | python | Router.__init__ | (self,
router_config,
verbose=False) | Constructor for OpenshiftOC
a router consists of 3 or more parts
- dc/router
- svc/router
- sa/router
- secret/router-certs
- clusterrolebinding/router-router-role | Constructor for OpenshiftOC | [
"Constructor",
"for",
"OpenshiftOC"
] | def __init__(self,
router_config,
verbose=False):
''' Constructor for OpenshiftOC
a router consists of 3 or more parts
- dc/router
- svc/router
- sa/router
- secret/router-certs
- clusterrolebinding/router-router-role
'''
super(Router, self).__init__(router_config.namespace, router_config.kubeconfig, verbose)
self.config = router_config
self.verbose = verbose
self.router_parts = [{'kind': 'dc', 'name': self.config.name},
{'kind': 'svc', 'name': self.config.name},
{'kind': 'sa', 'name': self.config.config_options['service_account']['value']},
{'kind': 'secret', 'name': self.config.name + '-certs'},
{'kind': 'clusterrolebinding', 'name': 'router-' + self.config.name + '-role'},
]
self.__prepared_router = None
self.dconfig = None
self.svc = None
self._secret = None
self._serviceaccount = None
self._rolebinding = None | [
"def",
"__init__",
"(",
"self",
",",
"router_config",
",",
"verbose",
"=",
"False",
")",
":",
"super",
"(",
"Router",
",",
"self",
")",
".",
"__init__",
"(",
"router_config",
".",
"namespace",
",",
"router_config",
".",
"kubeconfig",
",",
"verbose",
")",
... | https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/openshift/installer/vendored/openshift-ansible-3.11.28-1/roles/lib_openshift/library/oc_adm_router.py#L2693-L2720 | ||
twilio/twilio-python | 6e1e811ea57a1edfadd5161ace87397c563f6915 | twilio/rest/api/v2010/account/sip/domain/__init__.py | python | DomainInstance.voice_url | (self) | return self._properties['voice_url'] | :returns: The URL we call when receiving a call
:rtype: unicode | :returns: The URL we call when receiving a call
:rtype: unicode | [
":",
"returns",
":",
"The",
"URL",
"we",
"call",
"when",
"receiving",
"a",
"call",
":",
"rtype",
":",
"unicode"
] | def voice_url(self):
"""
:returns: The URL we call when receiving a call
:rtype: unicode
"""
return self._properties['voice_url'] | [
"def",
"voice_url",
"(",
"self",
")",
":",
"return",
"self",
".",
"_properties",
"[",
"'voice_url'",
"]"
] | https://github.com/twilio/twilio-python/blob/6e1e811ea57a1edfadd5161ace87397c563f6915/twilio/rest/api/v2010/account/sip/domain/__init__.py#L564-L569 | |
garnaat/kappa | a06a0047cc51f6a210beec4028a5fbe8ebcd5c53 | kappa/log.py | python | Log.add_log_retention_policy | (self,log_retention_policy_days) | [] | def add_log_retention_policy(self,log_retention_policy_days):
if not self._check_for_log_group():
LOG.debug('log group %s has not been created yet, creating', self.log_group_name)
try:
response = self._log_client.call('create_log_group',
logGroupName=self.log_group_name)
LOG.debug(response)
except ClientError:
LOG.exception('unable to create log group')
LOG.debug('adding log group retention policy', self.log_group_name)
try:
response = self._log_client.call('put_retention_policy',
logGroupName=self.log_group_name,
retentionInDays=log_retention_policy_days)
LOG.debug(response)
except ClientError:
LOG.exception('unable to add retention policy to log group') | [
"def",
"add_log_retention_policy",
"(",
"self",
",",
"log_retention_policy_days",
")",
":",
"if",
"not",
"self",
".",
"_check_for_log_group",
"(",
")",
":",
"LOG",
".",
"debug",
"(",
"'log group %s has not been created yet, creating'",
",",
"self",
".",
"log_group_nam... | https://github.com/garnaat/kappa/blob/a06a0047cc51f6a210beec4028a5fbe8ebcd5c53/kappa/log.py#L80-L96 | ||||
wxGlade/wxGlade | 44ed0d1cba78f27c5c0a56918112a737653b7b27 | widgets/search_ctrl/search_ctrl.py | python | xml_builder | (parser, base, name, parent, index) | return EditSearchCtrl(name, parent, index) | factory function to build EditSearchCtrl objects from a XML file | factory function to build EditSearchCtrl objects from a XML file | [
"factory",
"function",
"to",
"build",
"EditSearchCtrl",
"objects",
"from",
"a",
"XML",
"file"
] | def xml_builder(parser, base, name, parent, index):
"factory function to build EditSearchCtrl objects from a XML file"
return EditSearchCtrl(name, parent, index) | [
"def",
"xml_builder",
"(",
"parser",
",",
"base",
",",
"name",
",",
"parent",
",",
"index",
")",
":",
"return",
"EditSearchCtrl",
"(",
"name",
",",
"parent",
",",
"index",
")"
] | https://github.com/wxGlade/wxGlade/blob/44ed0d1cba78f27c5c0a56918112a737653b7b27/widgets/search_ctrl/search_ctrl.py#L81-L83 | |
007gzs/dingtalk-sdk | 7979da2e259fdbc571728cae2425a04dbc65850a | dingtalk/client/api/taobao.py | python | TbTianMaoMenDian.tmall_store_item_update | (
self,
update_item_request=None
) | return self._top_request(
"tmall.store.item.update",
{
"update_item_request": update_item_request
}
) | 更新商品信息
新零售中台门店商品更新接口,提供对外更新相关门店的商品详情
文档地址:https://open-doc.dingtalk.com/docs/api.htm?apiId=31410
:param update_item_request: 入参 | 更新商品信息
新零售中台门店商品更新接口,提供对外更新相关门店的商品详情
文档地址:https://open-doc.dingtalk.com/docs/api.htm?apiId=31410 | [
"更新商品信息",
"新零售中台门店商品更新接口,提供对外更新相关门店的商品详情",
"文档地址:https",
":",
"//",
"open",
"-",
"doc",
".",
"dingtalk",
".",
"com",
"/",
"docs",
"/",
"api",
".",
"htm?apiId",
"=",
"31410"
] | def tmall_store_item_update(
self,
update_item_request=None
):
"""
更新商品信息
新零售中台门店商品更新接口,提供对外更新相关门店的商品详情
文档地址:https://open-doc.dingtalk.com/docs/api.htm?apiId=31410
:param update_item_request: 入参
"""
return self._top_request(
"tmall.store.item.update",
{
"update_item_request": update_item_request
}
) | [
"def",
"tmall_store_item_update",
"(",
"self",
",",
"update_item_request",
"=",
"None",
")",
":",
"return",
"self",
".",
"_top_request",
"(",
"\"tmall.store.item.update\"",
",",
"{",
"\"update_item_request\"",
":",
"update_item_request",
"}",
")"
] | https://github.com/007gzs/dingtalk-sdk/blob/7979da2e259fdbc571728cae2425a04dbc65850a/dingtalk/client/api/taobao.py#L83552-L83568 | |
odlgroup/odl | 0b088df8dc4621c68b9414c3deff9127f4c4f11d | odl/diagnostics/space.py | python | SpaceTest.equals | (self) | Verify `LinearSpace.__eq__`. | Verify `LinearSpace.__eq__`. | [
"Verify",
"LinearSpace",
".",
"__eq__",
"."
] | def equals(self):
"""Verify `LinearSpace.__eq__`."""
self.log('\n== Verifying __eq__ ==\n')
if not self.space == self.space:
print('** space == space failed ***')
if self.space != self.space:
print('** not space != space failed***')
if self.space != copy(self.space):
print('** space == copy(space) failed***')
if self.space != deepcopy(self.space):
print('** space == deepcopy(space) failed***')
with fail_counter(
test_name='Verify behavior of `space == obj` when `obj` '
'is not a space',
logger=self.log
) as counter:
for obj in [[1, 2], list(), tuple(), dict(), 5.0]:
if self.space == obj:
counter.fail('space == obj, with obj={}'
''.format(obj))
if not self.space != obj:
counter.fail('not space != obj, with obj={}'
''.format(obj)) | [
"def",
"equals",
"(",
"self",
")",
":",
"self",
".",
"log",
"(",
"'\\n== Verifying __eq__ ==\\n'",
")",
"if",
"not",
"self",
".",
"space",
"==",
"self",
".",
"space",
":",
"print",
"(",
"'** space == space failed ***'",
")",
"if",
"self",
".",
"space",
"!=... | https://github.com/odlgroup/odl/blob/0b088df8dc4621c68b9414c3deff9127f4c4f11d/odl/diagnostics/space.py#L838-L868 | ||
beville/ComicStreamer | 62eb914652695ea41a5e1f0cfbd044cbc6854e84 | libs/comictaggerlib/comicarchive.py | python | ComicArchive.removeCoMet | ( self ) | return True | [] | def removeCoMet( self ):
if self.hasCoMet():
write_success = self.archiver.removeArchiveFile( self.comet_filename )
if write_success:
self.has_comet = False
self.comet_md = None
self.resetCache()
return write_success
return True | [
"def",
"removeCoMet",
"(",
"self",
")",
":",
"if",
"self",
".",
"hasCoMet",
"(",
")",
":",
"write_success",
"=",
"self",
".",
"archiver",
".",
"removeArchiveFile",
"(",
"self",
".",
"comet_filename",
")",
"if",
"write_success",
":",
"self",
".",
"has_comet... | https://github.com/beville/ComicStreamer/blob/62eb914652695ea41a5e1f0cfbd044cbc6854e84/libs/comictaggerlib/comicarchive.py#L967-L975 | |||
soravux/scoop | 3c0357c32cec3169a19c822a3857c968a48775c5 | examples/tree/dtm-tree.py | python | main | () | return executeTree() | [] | def main():
return executeTree() | [
"def",
"main",
"(",
")",
":",
"return",
"executeTree",
"(",
")"
] | https://github.com/soravux/scoop/blob/3c0357c32cec3169a19c822a3857c968a48775c5/examples/tree/dtm-tree.py#L7-L8 | |||
linxid/Machine_Learning_Study_Path | 558e82d13237114bbb8152483977806fc0c222af | Machine Learning In Action/Chapter5-LogisticRegression/venv/Lib/site-packages/setuptools/command/egg_info.py | python | egg_info.tags | (self) | return version | [] | def tags(self):
version = ''
if self.tag_build:
version += self.tag_build
if self.tag_date:
version += time.strftime("-%Y%m%d")
return version | [
"def",
"tags",
"(",
"self",
")",
":",
"version",
"=",
"''",
"if",
"self",
".",
"tag_build",
":",
"version",
"+=",
"self",
".",
"tag_build",
"if",
"self",
".",
"tag_date",
":",
"version",
"+=",
"time",
".",
"strftime",
"(",
"\"-%Y%m%d\"",
")",
"return",... | https://github.com/linxid/Machine_Learning_Study_Path/blob/558e82d13237114bbb8152483977806fc0c222af/Machine Learning In Action/Chapter5-LogisticRegression/venv/Lib/site-packages/setuptools/command/egg_info.py#L280-L286 | |||
rowliny/DiffHelper | ab3a96f58f9579d0023aed9ebd785f4edf26f8af | Tool/SitePackages/PIL/TiffImagePlugin.py | python | TiffImageFile.getxmp | (self) | return self._getxmp(self.tag_v2[700]) if 700 in self.tag_v2 else {} | Returns a dictionary containing the XMP tags.
Requires defusedxml to be installed.
:returns: XMP tags in a dictionary. | Returns a dictionary containing the XMP tags.
Requires defusedxml to be installed.
:returns: XMP tags in a dictionary. | [
"Returns",
"a",
"dictionary",
"containing",
"the",
"XMP",
"tags",
".",
"Requires",
"defusedxml",
"to",
"be",
"installed",
".",
":",
"returns",
":",
"XMP",
"tags",
"in",
"a",
"dictionary",
"."
] | def getxmp(self):
"""
Returns a dictionary containing the XMP tags.
Requires defusedxml to be installed.
:returns: XMP tags in a dictionary.
"""
return self._getxmp(self.tag_v2[700]) if 700 in self.tag_v2 else {} | [
"def",
"getxmp",
"(",
"self",
")",
":",
"return",
"self",
".",
"_getxmp",
"(",
"self",
".",
"tag_v2",
"[",
"700",
"]",
")",
"if",
"700",
"in",
"self",
".",
"tag_v2",
"else",
"{",
"}"
] | https://github.com/rowliny/DiffHelper/blob/ab3a96f58f9579d0023aed9ebd785f4edf26f8af/Tool/SitePackages/PIL/TiffImagePlugin.py#L1120-L1126 | |
sagemath/sage | f9b2db94f675ff16963ccdefba4f1a3393b3fe0d | src/sage/modules/free_module_integer.py | python | FreeModule_submodule_with_basis_integer.is_unimodular | (self) | return self.volume() == 1 | Return ``True`` if this lattice is unimodular.
OUTPUT:
A boolean.
EXAMPLES::
sage: from sage.modules.free_module_integer import IntegerLattice
sage: L = IntegerLattice([[1, 0], [0, 1]])
sage: L.is_unimodular()
True
sage: IntegerLattice([[2, 0], [0, 3]]).is_unimodular()
False | Return ``True`` if this lattice is unimodular. | [
"Return",
"True",
"if",
"this",
"lattice",
"is",
"unimodular",
"."
] | def is_unimodular(self):
"""
Return ``True`` if this lattice is unimodular.
OUTPUT:
A boolean.
EXAMPLES::
sage: from sage.modules.free_module_integer import IntegerLattice
sage: L = IntegerLattice([[1, 0], [0, 1]])
sage: L.is_unimodular()
True
sage: IntegerLattice([[2, 0], [0, 3]]).is_unimodular()
False
"""
return self.volume() == 1 | [
"def",
"is_unimodular",
"(",
"self",
")",
":",
"return",
"self",
".",
"volume",
"(",
")",
"==",
"1"
] | https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/modules/free_module_integer.py#L515-L532 | |
FSecureLABS/Jandroid | e31d0dab58a2bfd6ed8e0a387172b8bd7c893436 | libs/platform-tools/platform-tools_darwin/systrace/catapult/common/py_vulcanize/third_party/rjsmin/bench/jsmin.py | python | JavascriptMinify._next | (self) | return c | get the next character, excluding comments. peek() is used to see
if an unescaped '/' is followed by a '/' or '*'. | get the next character, excluding comments. peek() is used to see
if an unescaped '/' is followed by a '/' or '*'. | [
"get",
"the",
"next",
"character",
"excluding",
"comments",
".",
"peek",
"()",
"is",
"used",
"to",
"see",
"if",
"an",
"unescaped",
"/",
"is",
"followed",
"by",
"a",
"/",
"or",
"*",
"."
] | def _next(self):
"""get the next character, excluding comments. peek() is used to see
if an unescaped '/' is followed by a '/' or '*'.
"""
c = self._get()
if c == '/' and self.theA != '\\':
p = self._peek()
if p == '/':
c = self._get()
while c > '\n':
c = self._get()
return c
if p == '*':
c = self._get()
while 1:
c = self._get()
if c == '*':
if self._peek() == '/':
self._get()
return ' '
if c == '\000':
raise UnterminatedComment()
return c | [
"def",
"_next",
"(",
"self",
")",
":",
"c",
"=",
"self",
".",
"_get",
"(",
")",
"if",
"c",
"==",
"'/'",
"and",
"self",
".",
"theA",
"!=",
"'\\\\'",
":",
"p",
"=",
"self",
".",
"_peek",
"(",
")",
"if",
"p",
"==",
"'/'",
":",
"c",
"=",
"self"... | https://github.com/FSecureLABS/Jandroid/blob/e31d0dab58a2bfd6ed8e0a387172b8bd7c893436/libs/platform-tools/platform-tools_darwin/systrace/catapult/common/py_vulcanize/third_party/rjsmin/bench/jsmin.py#L96-L119 | |
textX/Arpeggio | 9ec6c7ee402054616b2f81e76557d39d3d376fcd | examples/json/json.py | python | jsonMembers | () | return memberDef, ZeroOrMore(",", memberDef) | [] | def jsonMembers(): return memberDef, ZeroOrMore(",", memberDef) | [
"def",
"jsonMembers",
"(",
")",
":",
"return",
"memberDef",
",",
"ZeroOrMore",
"(",
"\",\"",
",",
"memberDef",
")"
] | https://github.com/textX/Arpeggio/blob/9ec6c7ee402054616b2f81e76557d39d3d376fcd/examples/json/json.py#L27-L27 | |||
pfalcon/pycopy-lib | 56ebf2110f3caa63a3785d439ce49b11e13c75c0 | difflib/difflib.py | python | diff_bytes | (dfunc, a, b, fromfile=b'', tofile=b'',
fromfiledate=b'', tofiledate=b'', n=3, lineterm=b'\n') | r"""
Compare `a` and `b`, two sequences of lines represented as bytes rather
than str. This is a wrapper for `dfunc`, which is typically either
unified_diff() or context_diff(). Inputs are losslessly converted to
strings so that `dfunc` only has to worry about strings, and encoded
back to bytes on return. This is necessary to compare files with
unknown or inconsistent encoding. All other inputs (except `n`) must be
bytes rather than str. | r"""
Compare `a` and `b`, two sequences of lines represented as bytes rather
than str. This is a wrapper for `dfunc`, which is typically either
unified_diff() or context_diff(). Inputs are losslessly converted to
strings so that `dfunc` only has to worry about strings, and encoded
back to bytes on return. This is necessary to compare files with
unknown or inconsistent encoding. All other inputs (except `n`) must be
bytes rather than str. | [
"r",
"Compare",
"a",
"and",
"b",
"two",
"sequences",
"of",
"lines",
"represented",
"as",
"bytes",
"rather",
"than",
"str",
".",
"This",
"is",
"a",
"wrapper",
"for",
"dfunc",
"which",
"is",
"typically",
"either",
"unified_diff",
"()",
"or",
"context_diff",
... | def diff_bytes(dfunc, a, b, fromfile=b'', tofile=b'',
fromfiledate=b'', tofiledate=b'', n=3, lineterm=b'\n'):
r"""
Compare `a` and `b`, two sequences of lines represented as bytes rather
than str. This is a wrapper for `dfunc`, which is typically either
unified_diff() or context_diff(). Inputs are losslessly converted to
strings so that `dfunc` only has to worry about strings, and encoded
back to bytes on return. This is necessary to compare files with
unknown or inconsistent encoding. All other inputs (except `n`) must be
bytes rather than str.
"""
def decode(s):
try:
return s.decode('ascii', 'surrogateescape')
except AttributeError as err:
msg = ('all arguments must be bytes, not %s (%r)' %
(type(s).__name__, s))
raise TypeError(msg) from err
a = list(map(decode, a))
b = list(map(decode, b))
fromfile = decode(fromfile)
tofile = decode(tofile)
fromfiledate = decode(fromfiledate)
tofiledate = decode(tofiledate)
lineterm = decode(lineterm)
lines = dfunc(a, b, fromfile, tofile, fromfiledate, tofiledate, n, lineterm)
for line in lines:
yield line.encode('ascii', 'surrogateescape') | [
"def",
"diff_bytes",
"(",
"dfunc",
",",
"a",
",",
"b",
",",
"fromfile",
"=",
"b''",
",",
"tofile",
"=",
"b''",
",",
"fromfiledate",
"=",
"b''",
",",
"tofiledate",
"=",
"b''",
",",
"n",
"=",
"3",
",",
"lineterm",
"=",
"b'\\n'",
")",
":",
"def",
"d... | https://github.com/pfalcon/pycopy-lib/blob/56ebf2110f3caa63a3785d439ce49b11e13c75c0/difflib/difflib.py#L1315-L1343 | ||
riptideio/pymodbus | c5772b35ae3f29d1947f3ab453d8d00df846459f | pymodbus/bit_read_message.py | python | ReadBitsResponseBase.__init__ | (self, values, **kwargs) | Initializes a new instance
:param values: The requested values to be returned | Initializes a new instance | [
"Initializes",
"a",
"new",
"instance"
] | def __init__(self, values, **kwargs):
''' Initializes a new instance
:param values: The requested values to be returned
'''
ModbusResponse.__init__(self, **kwargs)
self.bits = values or [] | [
"def",
"__init__",
"(",
"self",
",",
"values",
",",
"*",
"*",
"kwargs",
")",
":",
"ModbusResponse",
".",
"__init__",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
"self",
".",
"bits",
"=",
"values",
"or",
"[",
"]"
] | https://github.com/riptideio/pymodbus/blob/c5772b35ae3f29d1947f3ab453d8d00df846459f/pymodbus/bit_read_message.py#L68-L74 | ||
emmetio/livestyle-sublime-old | c42833c046e9b2f53ebce3df3aa926528f5a33b5 | tornado/template.py | python | _IntermediateControlBlock.generate | (self, writer) | [] | def generate(self, writer):
# In case the previous block was empty
writer.write_line("pass", self.line)
writer.write_line("%s:" % self.statement, self.line, writer.indent_size() - 1) | [
"def",
"generate",
"(",
"self",
",",
"writer",
")",
":",
"# In case the previous block was empty",
"writer",
".",
"write_line",
"(",
"\"pass\"",
",",
"self",
".",
"line",
")",
"writer",
".",
"write_line",
"(",
"\"%s:\"",
"%",
"self",
".",
"statement",
",",
"... | https://github.com/emmetio/livestyle-sublime-old/blob/c42833c046e9b2f53ebce3df3aa926528f5a33b5/tornado/template.py#L516-L519 | ||||
daoluan/decode-Django | d46a858b45b56de48b0355f50dd9e45402d04cfd | Django-1.5.1/django/utils/html.py | python | escape | (text) | return mark_safe(force_text(text).replace('&', '&').replace('<', '<').replace('>', '>').replace('"', '"').replace("'", ''')) | Returns the given text with ampersands, quotes and angle brackets encoded for use in HTML. | Returns the given text with ampersands, quotes and angle brackets encoded for use in HTML. | [
"Returns",
"the",
"given",
"text",
"with",
"ampersands",
"quotes",
"and",
"angle",
"brackets",
"encoded",
"for",
"use",
"in",
"HTML",
"."
] | def escape(text):
"""
Returns the given text with ampersands, quotes and angle brackets encoded for use in HTML.
"""
return mark_safe(force_text(text).replace('&', '&').replace('<', '<').replace('>', '>').replace('"', '"').replace("'", ''')) | [
"def",
"escape",
"(",
"text",
")",
":",
"return",
"mark_safe",
"(",
"force_text",
"(",
"text",
")",
".",
"replace",
"(",
"'&'",
",",
"'&'",
")",
".",
"replace",
"(",
"'<'",
",",
"'<'",
")",
".",
"replace",
"(",
"'>'",
",",
"'>'",
")",
"."... | https://github.com/daoluan/decode-Django/blob/d46a858b45b56de48b0355f50dd9e45402d04cfd/Django-1.5.1/django/utils/html.py#L39-L43 | |
danieluhricek/LiSa | 897fc5133e368273f5fd78339f72a5c3c1e490ce | lisa/core/base.py | python | AnalyzedPcap.path | (self) | return self._path | Full pcap path. | Full pcap path. | [
"Full",
"pcap",
"path",
"."
] | def path(self):
"""Full pcap path."""
return self._path | [
"def",
"path",
"(",
"self",
")",
":",
"return",
"self",
".",
"_path"
] | https://github.com/danieluhricek/LiSa/blob/897fc5133e368273f5fd78339f72a5c3c1e490ce/lisa/core/base.py#L159-L161 | |
moemen95/Pytorch-Project-Template | dbd8d76e17f693a30c3205c263184de9c45d205c | utils/misc.py | python | timeit | (f) | return timed | Decorator to time Any Function | Decorator to time Any Function | [
"Decorator",
"to",
"time",
"Any",
"Function"
] | def timeit(f):
""" Decorator to time Any Function """
def timed(*args, **kwargs):
start_time = time.time()
result = f(*args, **kwargs)
end_time = time.time()
seconds = end_time - start_time
logging.getLogger("Timer").info(" [-] %s : %2.5f sec, which is %2.5f min, which is %2.5f hour" %
(f.__name__, seconds, seconds / 60, seconds / 3600))
return result
return timed | [
"def",
"timeit",
"(",
"f",
")",
":",
"def",
"timed",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"start_time",
"=",
"time",
".",
"time",
"(",
")",
"result",
"=",
"f",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"end_time",
"=",
"... | https://github.com/moemen95/Pytorch-Project-Template/blob/dbd8d76e17f693a30c3205c263184de9c45d205c/utils/misc.py#L5-L17 | |
saimadhu-polamuri/DataAspirant_codes | 4adfdad255a90ef39fca1bf83a927ffb129dda78 | evaluation_metrics/evaluation_metrics.py | python | get_confusion_matrix_components | (y_ture, y_pred) | Input :- y_true - list of actual values
y_pred - list of predicted values
Output :- None | Input :- y_true - list of actual values
y_pred - list of predicted values
Output :- None | [
"Input",
":",
"-",
"y_true",
"-",
"list",
"of",
"actual",
"values",
"y_pred",
"-",
"list",
"of",
"predicted",
"values",
"Output",
":",
"-",
"None"
] | def get_confusion_matrix_components(y_ture, y_pred):
"""
Input :- y_true - list of actual values
y_pred - list of predicted values
Output :- None
"""
tp = true_positive(y_true, y_pred) # Calculating ture positive
print(f"True Positive {tp}")
tn = true_negative(y_true, y_pred) # Calculating ture negative
print(f"True Negative {tn}")
fp = false_positive(y_true, y_pred) # Calculating false positive
print(f"False Positive {fp}")
fn = false_negative(y_true, y_pred) # Calculating false negative
print(f"False Negative {fn}") | [
"def",
"get_confusion_matrix_components",
"(",
"y_ture",
",",
"y_pred",
")",
":",
"tp",
"=",
"true_positive",
"(",
"y_true",
",",
"y_pred",
")",
"# Calculating ture positive",
"print",
"(",
"f\"True Positive {tp}\"",
")",
"tn",
"=",
"true_negative",
"(",
"y_true",
... | https://github.com/saimadhu-polamuri/DataAspirant_codes/blob/4adfdad255a90ef39fca1bf83a927ffb129dda78/evaluation_metrics/evaluation_metrics.py#L86-L105 | ||
actionless/pikaur | d489838d4c720cafac672985609eebdbdfb93a1b | pikaur/build.py | python | last_installed_hash | (self) | return None | Commit hash of AUR repo of last version of the pkg installed by Pikaur | Commit hash of AUR repo of last version of the pkg installed by Pikaur | [
"Commit",
"hash",
"of",
"AUR",
"repo",
"of",
"last",
"version",
"of",
"the",
"pkg",
"installed",
"by",
"Pikaur"
] | def last_installed_hash(self) -> Optional[str]:
"""
Commit hash of AUR repo of last version of the pkg installed by Pikaur
"""
if os.path.exists(self.last_installed_file_path):
with open_file(self.last_installed_file_path) as last_installed_file:
lines = last_installed_file.readlines()
if lines:
return lines[0].strip()
return None | [
"def",
"last_installed_hash",
"(",
"self",
")",
"->",
"Optional",
"[",
"str",
"]",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"last_installed_file_path",
")",
":",
"with",
"open_file",
"(",
"self",
".",
"last_installed_file_path",
")",
... | https://github.com/actionless/pikaur/blob/d489838d4c720cafac672985609eebdbdfb93a1b/pikaur/build.py#L225-L234 | |
lovelylain/pyctp | fd304de4b50c4ddc31a4190b1caaeb5dec66bc5d | stock2/ctp/ApiStruct.py | python | QryNotice.__init__ | (self, BrokerID='') | [] | def __init__(self, BrokerID=''):
self.BrokerID = '' | [
"def",
"__init__",
"(",
"self",
",",
"BrokerID",
"=",
"''",
")",
":",
"self",
".",
"BrokerID",
"=",
"''"
] | https://github.com/lovelylain/pyctp/blob/fd304de4b50c4ddc31a4190b1caaeb5dec66bc5d/stock2/ctp/ApiStruct.py#L2865-L2866 | ||||
henkelis/sonospy | 841f52010fd6e1e932d8f1a8896ad4e5a0667b8a | sonospy/control_point_sonos.py | python | ControlPointSonos.seek | (self, unit, target) | <InstanceID>0</InstanceID>
<Unit>TRACK_NR</Unit>
<Target>57</Target> | <InstanceID>0</InstanceID>
<Unit>TRACK_NR</Unit>
<Target>57</Target> | [
"<InstanceID",
">",
"0<",
"/",
"InstanceID",
">",
"<Unit",
">",
"TRACK_NR<",
"/",
"Unit",
">",
"<Target",
">",
"57<",
"/",
"Target",
">"
] | def seek(self, unit, target):
'''
<InstanceID>0</InstanceID>
<Unit>TRACK_NR</Unit>
<Target>57</Target>
'''
ssresult = self.get_at_service().Seek(InstanceID=0, Unit=unit, Target=target)
log.debug('seek result: %s', ssresult) | [
"def",
"seek",
"(",
"self",
",",
"unit",
",",
"target",
")",
":",
"ssresult",
"=",
"self",
".",
"get_at_service",
"(",
")",
".",
"Seek",
"(",
"InstanceID",
"=",
"0",
",",
"Unit",
"=",
"unit",
",",
"Target",
"=",
"target",
")",
"log",
".",
"debug",
... | https://github.com/henkelis/sonospy/blob/841f52010fd6e1e932d8f1a8896ad4e5a0667b8a/sonospy/control_point_sonos.py#L797-L804 | ||
radlab/sparrow | afb8efadeb88524f1394d1abe4ea66c6fd2ac744 | src/main/python/third_party/stats.py | python | lttest_ind | (a, b, printit=0, name1='Samp1', name2='Samp2', writemode='a') | return t,prob | Calculates the t-obtained T-test on TWO INDEPENDENT samples of
scores a, and b. From Numerical Recipies, p.483. If printit=1, results
are printed to the screen. If printit='filename', the results are output
to 'filename' using the given writemode (default=append). Returns t-value,
and prob.
Usage: lttest_ind(a,b,printit=0,name1='Samp1',name2='Samp2',writemode='a')
Returns: t-value, two-tailed prob | Calculates the t-obtained T-test on TWO INDEPENDENT samples of
scores a, and b. From Numerical Recipies, p.483. If printit=1, results
are printed to the screen. If printit='filename', the results are output
to 'filename' using the given writemode (default=append). Returns t-value,
and prob. | [
"Calculates",
"the",
"t",
"-",
"obtained",
"T",
"-",
"test",
"on",
"TWO",
"INDEPENDENT",
"samples",
"of",
"scores",
"a",
"and",
"b",
".",
"From",
"Numerical",
"Recipies",
"p",
".",
"483",
".",
"If",
"printit",
"=",
"1",
"results",
"are",
"printed",
"to... | def lttest_ind (a, b, printit=0, name1='Samp1', name2='Samp2', writemode='a'):
"""
Calculates the t-obtained T-test on TWO INDEPENDENT samples of
scores a, and b. From Numerical Recipies, p.483. If printit=1, results
are printed to the screen. If printit='filename', the results are output
to 'filename' using the given writemode (default=append). Returns t-value,
and prob.
Usage: lttest_ind(a,b,printit=0,name1='Samp1',name2='Samp2',writemode='a')
Returns: t-value, two-tailed prob
"""
x1 = mean(a)
x2 = mean(b)
v1 = stdev(a)**2
v2 = stdev(b)**2
n1 = len(a)
n2 = len(b)
df = n1+n2-2
svar = ((n1-1)*v1+(n2-1)*v2)/float(df)
t = (x1-x2)/math.sqrt(svar*(1.0/n1 + 1.0/n2))
prob = betai(0.5*df,0.5,df/(df+t*t))
if printit <> 0:
statname = 'Independent samples T-test.'
outputpairedstats(printit,writemode,
name1,n1,x1,v1,min(a),max(a),
name2,n2,x2,v2,min(b),max(b),
statname,t,prob)
return t,prob | [
"def",
"lttest_ind",
"(",
"a",
",",
"b",
",",
"printit",
"=",
"0",
",",
"name1",
"=",
"'Samp1'",
",",
"name2",
"=",
"'Samp2'",
",",
"writemode",
"=",
"'a'",
")",
":",
"x1",
"=",
"mean",
"(",
"a",
")",
"x2",
"=",
"mean",
"(",
"b",
")",
"v1",
"... | https://github.com/radlab/sparrow/blob/afb8efadeb88524f1394d1abe4ea66c6fd2ac744/src/main/python/third_party/stats.py#L1024-L1052 | |
IJDykeman/wangTiles | 7c1ee2095ebdf7f72bce07d94c6484915d5cae8b | experimental_code/tiles_3d/venv/lib/python2.7/site-packages/pip/_vendor/html5lib/inputstream.py | python | EncodingBytes.skip | (self, chars=spaceCharactersBytes) | return None | Skip past a list of characters | Skip past a list of characters | [
"Skip",
"past",
"a",
"list",
"of",
"characters"
] | def skip(self, chars=spaceCharactersBytes):
"""Skip past a list of characters"""
p = self.position # use property for the error-checking
while p < len(self):
c = self[p:p + 1]
if c not in chars:
self._position = p
return c
p += 1
self._position = p
return None | [
"def",
"skip",
"(",
"self",
",",
"chars",
"=",
"spaceCharactersBytes",
")",
":",
"p",
"=",
"self",
".",
"position",
"# use property for the error-checking",
"while",
"p",
"<",
"len",
"(",
"self",
")",
":",
"c",
"=",
"self",
"[",
"p",
":",
"p",
"+",
"1"... | https://github.com/IJDykeman/wangTiles/blob/7c1ee2095ebdf7f72bce07d94c6484915d5cae8b/experimental_code/tiles_3d/venv/lib/python2.7/site-packages/pip/_vendor/html5lib/inputstream.py#L601-L611 | |
enthought/traitsui | b7c38c7a47bf6ae7971f9ddab70c8a358647dd25 | traitsui/table_column.py | python | TableColumn.is_editable | (self, object) | return self.editable | Returns whether the column is editable for a specified object. | Returns whether the column is editable for a specified object. | [
"Returns",
"whether",
"the",
"column",
"is",
"editable",
"for",
"a",
"specified",
"object",
"."
] | def is_editable(self, object):
"""Returns whether the column is editable for a specified object."""
return self.editable | [
"def",
"is_editable",
"(",
"self",
",",
"object",
")",
":",
"return",
"self",
".",
"editable"
] | https://github.com/enthought/traitsui/blob/b7c38c7a47bf6ae7971f9ddab70c8a358647dd25/traitsui/table_column.py#L222-L224 | |
OpenMDAO/OpenMDAO-Framework | f2e37b7de3edeaaeb2d251b375917adec059db9b | openmdao.main/src/openmdao/main/hasparameters.py | python | ParameterGroup.get_referenced_varpaths | (self, refs=False) | return result | Return a set of Variable names referenced in our target strings. | Return a set of Variable names referenced in our target strings. | [
"Return",
"a",
"set",
"of",
"Variable",
"names",
"referenced",
"in",
"our",
"target",
"strings",
"."
] | def get_referenced_varpaths(self, refs=False):
"""Return a set of Variable names referenced in our target strings."""
result = set()
for param in self._params:
result.update(param.get_referenced_varpaths(refs=refs))
return result | [
"def",
"get_referenced_varpaths",
"(",
"self",
",",
"refs",
"=",
"False",
")",
":",
"result",
"=",
"set",
"(",
")",
"for",
"param",
"in",
"self",
".",
"_params",
":",
"result",
".",
"update",
"(",
"param",
".",
"get_referenced_varpaths",
"(",
"refs",
"="... | https://github.com/OpenMDAO/OpenMDAO-Framework/blob/f2e37b7de3edeaaeb2d251b375917adec059db9b/openmdao.main/src/openmdao/main/hasparameters.py#L449-L454 | |
apple/ccs-calendarserver | 13c706b985fb728b9aab42dc0fef85aae21921c3 | txweb2/dav/method/mkcol.py | python | http_MKCOL | (self, request) | Respond to a MKCOL request. (RFC 2518, section 8.3) | Respond to a MKCOL request. (RFC 2518, section 8.3) | [
"Respond",
"to",
"a",
"MKCOL",
"request",
".",
"(",
"RFC",
"2518",
"section",
"8",
".",
"3",
")"
] | def http_MKCOL(self, request):
"""
Respond to a MKCOL request. (RFC 2518, section 8.3)
"""
parent = waitForDeferred(request.locateResource(parentForURL(request.uri)))
yield parent
parent = parent.getResult()
x = waitForDeferred(parent.authorize(request, (davxml.Bind(),)))
yield x
x.getResult()
if self.exists():
log.error("Attempt to create collection where file exists: %s"
% (self,))
raise HTTPError(responsecode.NOT_ALLOWED)
if not parent.isCollection():
log.error("Attempt to create collection with non-collection parent: %s"
% (self,))
raise HTTPError(StatusResponse(
responsecode.CONFLICT,
"Parent resource is not a collection."
))
#
# Read request body
#
x = waitForDeferred(noDataFromStream(request.stream))
yield x
try:
x.getResult()
except ValueError, e:
log.error("Error while handling MKCOL body: %s" % (e,))
raise HTTPError(responsecode.UNSUPPORTED_MEDIA_TYPE)
response = waitForDeferred(mkcollection(self.fp))
yield response
yield response.getResult() | [
"def",
"http_MKCOL",
"(",
"self",
",",
"request",
")",
":",
"parent",
"=",
"waitForDeferred",
"(",
"request",
".",
"locateResource",
"(",
"parentForURL",
"(",
"request",
".",
"uri",
")",
")",
")",
"yield",
"parent",
"parent",
"=",
"parent",
".",
"getResult... | https://github.com/apple/ccs-calendarserver/blob/13c706b985fb728b9aab42dc0fef85aae21921c3/txweb2/dav/method/mkcol.py#L44-L82 | ||
robcarver17/pysystemtrade | b0385705b7135c52d39cb6d2400feece881bcca9 | systems/provided/example/rules.py | python | ewmac_forecast_with_defaults | (price, Lfast=32, Lslow=128) | return raw_ewmac / vol | Calculate the ewmac trading rule forecast, given a price and EWMA speeds
Lfast, Lslow
Assumes that 'price' is daily data
This version recalculates the price volatility, and does not do capping or
scaling
:param price: The price or other series to use (assumed Tx1)
:type price: pd.Series
:param Lfast: Lookback for fast in days
:type Lfast: int
:param Lslow: Lookback for slow in days
:type Lslow: int
:returns: pd.Series -- unscaled, uncapped forecast | Calculate the ewmac trading rule forecast, given a price and EWMA speeds
Lfast, Lslow | [
"Calculate",
"the",
"ewmac",
"trading",
"rule",
"forecast",
"given",
"a",
"price",
"and",
"EWMA",
"speeds",
"Lfast",
"Lslow"
] | def ewmac_forecast_with_defaults(price, Lfast=32, Lslow=128):
"""
Calculate the ewmac trading rule forecast, given a price and EWMA speeds
Lfast, Lslow
Assumes that 'price' is daily data
This version recalculates the price volatility, and does not do capping or
scaling
:param price: The price or other series to use (assumed Tx1)
:type price: pd.Series
:param Lfast: Lookback for fast in days
:type Lfast: int
:param Lslow: Lookback for slow in days
:type Lslow: int
:returns: pd.Series -- unscaled, uncapped forecast
"""
# price: This is the stitched price series
# We can't use the price of the contract we're trading, or the volatility
# will be jumpy
# And we'll miss out on the rolldown. See
# https://qoppac.blogspot.com/2015/05/systems-building-futures-rolling.html
# We don't need to calculate the decay parameter, just use the span
# directly
fast_ewma = price.ewm(span=Lfast).mean()
slow_ewma = price.ewm(span=Lslow).mean()
raw_ewmac = fast_ewma - slow_ewma
vol = robust_vol_calc(price.diff())
return raw_ewmac / vol | [
"def",
"ewmac_forecast_with_defaults",
"(",
"price",
",",
"Lfast",
"=",
"32",
",",
"Lslow",
"=",
"128",
")",
":",
"# price: This is the stitched price series",
"# We can't use the price of the contract we're trading, or the volatility",
"# will be jumpy",
"# And we'll miss out on t... | https://github.com/robcarver17/pysystemtrade/blob/b0385705b7135c52d39cb6d2400feece881bcca9/systems/provided/example/rules.py#L8-L46 | |
TencentCloud/tencentcloud-sdk-python | 3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2 | tencentcloud/essbasic/v20201222/essbasic_client.py | python | EssbasicClient.CreateSubOrganizationAndSeal | (self, request) | 此接口(CreateSubOrganizationAndSeal)用于注册子机构,同时系统将为该子企业自动生成一个默认电子印章图片。
注意:
1. 在后续的签署流程中,若未指定签署使用的印章ID,则默认调用自动生成的印章图片进行签署。
2. 此接口为白名单接口,如您需要使用此能力,请提前与客户经理沟通或邮件至e-contract@tencent.com与我们联系。
:param request: Request instance for CreateSubOrganizationAndSeal.
:type request: :class:`tencentcloud.essbasic.v20201222.models.CreateSubOrganizationAndSealRequest`
:rtype: :class:`tencentcloud.essbasic.v20201222.models.CreateSubOrganizationAndSealResponse` | 此接口(CreateSubOrganizationAndSeal)用于注册子机构,同时系统将为该子企业自动生成一个默认电子印章图片。 | [
"此接口(CreateSubOrganizationAndSeal)用于注册子机构,同时系统将为该子企业自动生成一个默认电子印章图片。"
] | def CreateSubOrganizationAndSeal(self, request):
"""此接口(CreateSubOrganizationAndSeal)用于注册子机构,同时系统将为该子企业自动生成一个默认电子印章图片。
注意:
1. 在后续的签署流程中,若未指定签署使用的印章ID,则默认调用自动生成的印章图片进行签署。
2. 此接口为白名单接口,如您需要使用此能力,请提前与客户经理沟通或邮件至e-contract@tencent.com与我们联系。
:param request: Request instance for CreateSubOrganizationAndSeal.
:type request: :class:`tencentcloud.essbasic.v20201222.models.CreateSubOrganizationAndSealRequest`
:rtype: :class:`tencentcloud.essbasic.v20201222.models.CreateSubOrganizationAndSealResponse`
"""
try:
params = request._serialize()
body = self.call("CreateSubOrganizationAndSeal", params)
response = json.loads(body)
if "Error" not in response["Response"]:
model = models.CreateSubOrganizationAndSealResponse()
model._deserialize(response["Response"])
return model
else:
code = response["Response"]["Error"]["Code"]
message = response["Response"]["Error"]["Message"]
reqid = response["Response"]["RequestId"]
raise TencentCloudSDKException(code, message, reqid)
except Exception as e:
if isinstance(e, TencentCloudSDKException):
raise
else:
raise TencentCloudSDKException(e.message, e.message) | [
"def",
"CreateSubOrganizationAndSeal",
"(",
"self",
",",
"request",
")",
":",
"try",
":",
"params",
"=",
"request",
".",
"_serialize",
"(",
")",
"body",
"=",
"self",
".",
"call",
"(",
"\"CreateSubOrganizationAndSeal\"",
",",
"params",
")",
"response",
"=",
"... | https://github.com/TencentCloud/tencentcloud-sdk-python/blob/3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2/tencentcloud/essbasic/v20201222/essbasic_client.py#L580-L609 | ||
chainer/chainer | e9da1423255c58c37be9733f51b158aa9b39dc93 | chainer/training/trainer.py | python | Trainer.is_before_training | (self) | return self.updater.iteration == 0 | Flag that represents if training has started or not.
``True`` represents 'before training' and
``False`` represents 'during/after training'.
This flag is supposed to be used in :meth:`Extension.__call__`
(e.g., :meth:`PlotReport.__call__`) to decide to execute its operation
or not. This additional condition is necessary since
``Extension._trigger(trainer)`` is always ``False`` before training
and cannot be used. | Flag that represents if training has started or not. | [
"Flag",
"that",
"represents",
"if",
"training",
"has",
"started",
"or",
"not",
"."
] | def is_before_training(self):
"""Flag that represents if training has started or not.
``True`` represents 'before training' and
``False`` represents 'during/after training'.
This flag is supposed to be used in :meth:`Extension.__call__`
(e.g., :meth:`PlotReport.__call__`) to decide to execute its operation
or not. This additional condition is necessary since
``Extension._trigger(trainer)`` is always ``False`` before training
and cannot be used.
"""
return self.updater.iteration == 0 | [
"def",
"is_before_training",
"(",
"self",
")",
":",
"return",
"self",
".",
"updater",
".",
"iteration",
"==",
"0"
] | https://github.com/chainer/chainer/blob/e9da1423255c58c37be9733f51b158aa9b39dc93/chainer/training/trainer.py#L170-L183 | |
tomplus/kubernetes_asyncio | f028cc793e3a2c519be6a52a49fb77ff0b014c9b | kubernetes_asyncio/client/models/v1_custom_resource_definition_spec.py | python | V1CustomResourceDefinitionSpec.scope | (self, scope) | Sets the scope of this V1CustomResourceDefinitionSpec.
scope indicates whether the defined custom resource is cluster- or namespace-scoped. Allowed values are `Cluster` and `Namespaced`. # noqa: E501
:param scope: The scope of this V1CustomResourceDefinitionSpec. # noqa: E501
:type: str | Sets the scope of this V1CustomResourceDefinitionSpec. | [
"Sets",
"the",
"scope",
"of",
"this",
"V1CustomResourceDefinitionSpec",
"."
] | def scope(self, scope):
"""Sets the scope of this V1CustomResourceDefinitionSpec.
scope indicates whether the defined custom resource is cluster- or namespace-scoped. Allowed values are `Cluster` and `Namespaced`. # noqa: E501
:param scope: The scope of this V1CustomResourceDefinitionSpec. # noqa: E501
:type: str
"""
if self.local_vars_configuration.client_side_validation and scope is None: # noqa: E501
raise ValueError("Invalid value for `scope`, must not be `None`") # noqa: E501
self._scope = scope | [
"def",
"scope",
"(",
"self",
",",
"scope",
")",
":",
"if",
"self",
".",
"local_vars_configuration",
".",
"client_side_validation",
"and",
"scope",
"is",
"None",
":",
"# noqa: E501",
"raise",
"ValueError",
"(",
"\"Invalid value for `scope`, must not be `None`\"",
")",
... | https://github.com/tomplus/kubernetes_asyncio/blob/f028cc793e3a2c519be6a52a49fb77ff0b014c9b/kubernetes_asyncio/client/models/v1_custom_resource_definition_spec.py#L180-L191 | ||
deluge-torrent/deluge | 2316088f5c0dd6cb044d9d4832fa7d56dcc79cdc | deluge/ui/client.py | python | Client.start_standalone | (self) | Starts a daemon in the same process as the client. | Starts a daemon in the same process as the client. | [
"Starts",
"a",
"daemon",
"in",
"the",
"same",
"process",
"as",
"the",
"client",
"."
] | def start_standalone(self):
"""
Starts a daemon in the same process as the client.
"""
self._daemon_proxy = DaemonStandaloneProxy(self.__event_handlers)
self.__started_standalone = True | [
"def",
"start_standalone",
"(",
"self",
")",
":",
"self",
".",
"_daemon_proxy",
"=",
"DaemonStandaloneProxy",
"(",
"self",
".",
"__event_handlers",
")",
"self",
".",
"__started_standalone",
"=",
"True"
] | https://github.com/deluge-torrent/deluge/blob/2316088f5c0dd6cb044d9d4832fa7d56dcc79cdc/deluge/ui/client.py#L633-L638 | ||
theotherp/nzbhydra | 4b03d7f769384b97dfc60dade4806c0fc987514e | libs/mimetypes.py | python | MimeTypes.add_type | (self, type, ext, strict=True) | Add a mapping between a type and an extension.
When the extension is already known, the new
type will replace the old one. When the type
is already known the extension will be added
to the list of known extensions.
If strict is true, information will be added to
list of standard types, else to the list of non-standard
types. | Add a mapping between a type and an extension. | [
"Add",
"a",
"mapping",
"between",
"a",
"type",
"and",
"an",
"extension",
"."
] | def add_type(self, type, ext, strict=True):
"""Add a mapping between a type and an extension.
When the extension is already known, the new
type will replace the old one. When the type
is already known the extension will be added
to the list of known extensions.
If strict is true, information will be added to
list of standard types, else to the list of non-standard
types.
"""
self.types_map[strict][ext] = type
exts = self.types_map_inv[strict].setdefault(type, [])
if ext not in exts:
exts.append(ext) | [
"def",
"add_type",
"(",
"self",
",",
"type",
",",
"ext",
",",
"strict",
"=",
"True",
")",
":",
"self",
".",
"types_map",
"[",
"strict",
"]",
"[",
"ext",
"]",
"=",
"type",
"exts",
"=",
"self",
".",
"types_map_inv",
"[",
"strict",
"]",
".",
"setdefau... | https://github.com/theotherp/nzbhydra/blob/4b03d7f769384b97dfc60dade4806c0fc987514e/libs/mimetypes.py#L78-L93 | ||
magic282/NeuSum | f1933bc1f32849733aee449f7bff821f66d938dc | neusum_pt/neusum/modules/Maxout.py | python | MaxOut.forward | (self, input) | return output | input:
reduce_size: | input:
reduce_size: | [
"input",
":",
"reduce_size",
":"
] | def forward(self, input):
"""
input:
reduce_size:
"""
input_size = list(input.size())
assert input_size[-1] % self.pool_size == 0
output_size = [d for d in input_size]
output_size[-1] = output_size[-1] // self.pool_size
output_size.append(self.pool_size)
last_dim = len(output_size) - 1
input = input.view(*output_size)
# TODO: This a temp fix
if torch.__version__[:6] == '0.1.12':
input, idx = input.max(last_dim)
else:
input, idx = input.max(last_dim, keepdim=True)
output = input.squeeze(last_dim)
return output | [
"def",
"forward",
"(",
"self",
",",
"input",
")",
":",
"input_size",
"=",
"list",
"(",
"input",
".",
"size",
"(",
")",
")",
"assert",
"input_size",
"[",
"-",
"1",
"]",
"%",
"self",
".",
"pool_size",
"==",
"0",
"output_size",
"=",
"[",
"d",
"for",
... | https://github.com/magic282/NeuSum/blob/f1933bc1f32849733aee449f7bff821f66d938dc/neusum_pt/neusum/modules/Maxout.py#L11-L30 | |
fake-name/ReadableWebProxy | ed5c7abe38706acc2684a1e6cd80242a03c5f010 | WebMirror/management/rss_parser_funcs/feed_parse_extractFuel2RocktranslationsWordpressCom.py | python | extractFuel2RocktranslationsWordpressCom | (item) | return False | Parser for 'fuel2rocktranslations.wordpress.com' | Parser for 'fuel2rocktranslations.wordpress.com' | [
"Parser",
"for",
"fuel2rocktranslations",
".",
"wordpress",
".",
"com"
] | def extractFuel2RocktranslationsWordpressCom(item):
'''
Parser for 'fuel2rocktranslations.wordpress.com'
'''
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or "preview" in item['title'].lower():
return None
tagmap = [
('PRC', 'PRC', 'translated'),
('Loiterous', 'Loiterous', 'oel'),
]
for tagname, name, tl_type in tagmap:
if tagname in item['tags']:
return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type)
return False | [
"def",
"extractFuel2RocktranslationsWordpressCom",
"(",
"item",
")",
":",
"vol",
",",
"chp",
",",
"frag",
",",
"postfix",
"=",
"extractVolChapterFragmentPostfix",
"(",
"item",
"[",
"'title'",
"]",
")",
"if",
"not",
"(",
"chp",
"or",
"vol",
")",
"or",
"\"prev... | https://github.com/fake-name/ReadableWebProxy/blob/ed5c7abe38706acc2684a1e6cd80242a03c5f010/WebMirror/management/rss_parser_funcs/feed_parse_extractFuel2RocktranslationsWordpressCom.py#L2-L21 | |
KalleHallden/AutoTimer | 2d954216700c4930baa154e28dbddc34609af7ce | env/lib/python2.7/site-packages/pip/_vendor/requests/cookies.py | python | _copy_cookie_jar | (jar) | return new_jar | [] | def _copy_cookie_jar(jar):
if jar is None:
return None
if hasattr(jar, 'copy'):
# We're dealing with an instance of RequestsCookieJar
return jar.copy()
# We're dealing with a generic CookieJar instance
new_jar = copy.copy(jar)
new_jar.clear()
for cookie in jar:
new_jar.set_cookie(copy.copy(cookie))
return new_jar | [
"def",
"_copy_cookie_jar",
"(",
"jar",
")",
":",
"if",
"jar",
"is",
"None",
":",
"return",
"None",
"if",
"hasattr",
"(",
"jar",
",",
"'copy'",
")",
":",
"# We're dealing with an instance of RequestsCookieJar",
"return",
"jar",
".",
"copy",
"(",
")",
"# We're d... | https://github.com/KalleHallden/AutoTimer/blob/2d954216700c4930baa154e28dbddc34609af7ce/env/lib/python2.7/site-packages/pip/_vendor/requests/cookies.py#L426-L438 | |||
tomplus/kubernetes_asyncio | f028cc793e3a2c519be6a52a49fb77ff0b014c9b | kubernetes_asyncio/client/models/v1beta1_lease_spec.py | python | V1beta1LeaseSpec.renew_time | (self, renew_time) | Sets the renew_time of this V1beta1LeaseSpec.
renewTime is a time when the current holder of a lease has last updated the lease. # noqa: E501
:param renew_time: The renew_time of this V1beta1LeaseSpec. # noqa: E501
:type: datetime | Sets the renew_time of this V1beta1LeaseSpec. | [
"Sets",
"the",
"renew_time",
"of",
"this",
"V1beta1LeaseSpec",
"."
] | def renew_time(self, renew_time):
"""Sets the renew_time of this V1beta1LeaseSpec.
renewTime is a time when the current holder of a lease has last updated the lease. # noqa: E501
:param renew_time: The renew_time of this V1beta1LeaseSpec. # noqa: E501
:type: datetime
"""
self._renew_time = renew_time | [
"def",
"renew_time",
"(",
"self",
",",
"renew_time",
")",
":",
"self",
".",
"_renew_time",
"=",
"renew_time"
] | https://github.com/tomplus/kubernetes_asyncio/blob/f028cc793e3a2c519be6a52a49fb77ff0b014c9b/kubernetes_asyncio/client/models/v1beta1_lease_spec.py#L179-L188 | ||
pallets/flask | 660994efc761efdfd49ca442b73f6712dc77b6cf | src/flask/app.py | python | Flask.handle_url_build_error | (
self, error: Exception, endpoint: str, values: dict
) | Handle :class:`~werkzeug.routing.BuildError` on
:meth:`url_for`. | Handle :class:`~werkzeug.routing.BuildError` on
:meth:`url_for`. | [
"Handle",
":",
"class",
":",
"~werkzeug",
".",
"routing",
".",
"BuildError",
"on",
":",
"meth",
":",
"url_for",
"."
] | def handle_url_build_error(
self, error: Exception, endpoint: str, values: dict
) -> str:
"""Handle :class:`~werkzeug.routing.BuildError` on
:meth:`url_for`.
"""
for handler in self.url_build_error_handlers:
try:
rv = handler(error, endpoint, values)
except BuildError as e:
# make error available outside except block
error = e
else:
if rv is not None:
return rv
# Re-raise if called with an active exception, otherwise raise
# the passed in exception.
if error is sys.exc_info()[1]:
raise
raise error | [
"def",
"handle_url_build_error",
"(",
"self",
",",
"error",
":",
"Exception",
",",
"endpoint",
":",
"str",
",",
"values",
":",
"dict",
")",
"->",
"str",
":",
"for",
"handler",
"in",
"self",
".",
"url_build_error_handlers",
":",
"try",
":",
"rv",
"=",
"ha... | https://github.com/pallets/flask/blob/660994efc761efdfd49ca442b73f6712dc77b6cf/src/flask/app.py#L1806-L1827 | ||
quodlibet/quodlibet | e3099c89f7aa6524380795d325cc14630031886c | quodlibet/query/_parser.py | python | QueryParser.space | (self) | Advance to the first non-space token | Advance to the first non-space token | [
"Advance",
"to",
"the",
"first",
"non",
"-",
"space",
"token"
] | def space(self):
"""Advance to the first non-space token"""
while not self.eof() and self.tokens[self.index] == ' ':
self.index += 1 | [
"def",
"space",
"(",
"self",
")",
":",
"while",
"not",
"self",
".",
"eof",
"(",
")",
"and",
"self",
".",
"tokens",
"[",
"self",
".",
"index",
"]",
"==",
"' '",
":",
"self",
".",
"index",
"+=",
"1"
] | https://github.com/quodlibet/quodlibet/blob/e3099c89f7aa6524380795d325cc14630031886c/quodlibet/query/_parser.py#L42-L45 | ||
google/timesketch | 1ce6b60e125d104e6644947c6f1dbe1b82ac76b6 | timesketch/api/v1/resources/sigma.py | python | SigmaListResource.get | (self) | return jsonify({'objects': sigma_rules, 'meta': meta}) | Handles GET request to the resource.
Returns:
Dict of sigma rules | Handles GET request to the resource. | [
"Handles",
"GET",
"request",
"to",
"the",
"resource",
"."
] | def get(self):
"""Handles GET request to the resource.
Returns:
Dict of sigma rules
"""
sigma_rules = []
try:
sigma_rules = ts_sigma_lib.get_all_sigma_rules()
except ValueError as e:
logger.error('OS Error, unable to get the path to the Sigma rules',
exc_info=True)
abort(
HTTP_STATUS_CODE_NOT_FOUND,
f'Value Error, {e}')
# TODO: idea for meta: add a list of folders that have been parsed
meta = {'current_user': current_user.username,
'rules_count': len(sigma_rules)}
return jsonify({'objects': sigma_rules, 'meta': meta}) | [
"def",
"get",
"(",
"self",
")",
":",
"sigma_rules",
"=",
"[",
"]",
"try",
":",
"sigma_rules",
"=",
"ts_sigma_lib",
".",
"get_all_sigma_rules",
"(",
")",
"except",
"ValueError",
"as",
"e",
":",
"logger",
".",
"error",
"(",
"'OS Error, unable to get the path to ... | https://github.com/google/timesketch/blob/1ce6b60e125d104e6644947c6f1dbe1b82ac76b6/timesketch/api/v1/resources/sigma.py#L41-L61 | |
dulwich/dulwich | 1f66817d712e3563ce1ff53b1218491a2eae39da | dulwich/repo.py | python | MemoryRepo._determine_file_mode | (self) | return sys.platform != "win32" | Probe the file-system to determine whether permissions can be trusted.
Returns: True if permissions can be trusted, False otherwise. | Probe the file-system to determine whether permissions can be trusted. | [
"Probe",
"the",
"file",
"-",
"system",
"to",
"determine",
"whether",
"permissions",
"can",
"be",
"trusted",
"."
] | def _determine_file_mode(self):
"""Probe the file-system to determine whether permissions can be trusted.
Returns: True if permissions can be trusted, False otherwise.
"""
return sys.platform != "win32" | [
"def",
"_determine_file_mode",
"(",
"self",
")",
":",
"return",
"sys",
".",
"platform",
"!=",
"\"win32\""
] | https://github.com/dulwich/dulwich/blob/1f66817d712e3563ce1ff53b1218491a2eae39da/dulwich/repo.py#L1680-L1685 | |
IntelLabs/coach | dea46ae0d22b0a0cd30b9fc138a4a2642e1b9d9d | rl_coach/data_stores/redis_data_store.py | python | RedisDataStore._load_policy | (self, graph_manager) | return True | Get the most recent policy from redis and loaded into the graph_manager | Get the most recent policy from redis and loaded into the graph_manager | [
"Get",
"the",
"most",
"recent",
"policy",
"from",
"redis",
"and",
"loaded",
"into",
"the",
"graph_manager"
] | def _load_policy(self, graph_manager) -> bool:
"""
Get the most recent policy from redis and loaded into the graph_manager
"""
policy_string = self.redis_connection.get(self.params.redis_channel)
if policy_string is None:
return False
self.saver.from_string(graph_manager.sess, policy_string)
return True | [
"def",
"_load_policy",
"(",
"self",
",",
"graph_manager",
")",
"->",
"bool",
":",
"policy_string",
"=",
"self",
".",
"redis_connection",
".",
"get",
"(",
"self",
".",
"params",
".",
"redis_channel",
")",
"if",
"policy_string",
"is",
"None",
":",
"return",
... | https://github.com/IntelLabs/coach/blob/dea46ae0d22b0a0cd30b9fc138a4a2642e1b9d9d/rl_coach/data_stores/redis_data_store.py#L132-L141 | |
BloodAxe/pytorch-toolbelt | cab4fc4e209d9c9e5db18cf1e01bb979c65cf08b | pytorch_toolbelt/inference/tta.py | python | fliplr_image2mask | (model: nn.Module, image: Tensor) | return fliplr_image_deaugment(model(fliplr_image_augment(image))) | Test-time augmentation for image segmentation that averages predictions
for input image and vertically flipped one.
For segmentation we need to reverse the transformation after making a prediction
on augmented input.
:param model: Model to use for making predictions.
:param image: Model input.
:return: Arithmetically averaged predictions | Test-time augmentation for image segmentation that averages predictions
for input image and vertically flipped one. | [
"Test",
"-",
"time",
"augmentation",
"for",
"image",
"segmentation",
"that",
"averages",
"predictions",
"for",
"input",
"image",
"and",
"vertically",
"flipped",
"one",
"."
] | def fliplr_image2mask(model: nn.Module, image: Tensor) -> Tensor:
"""Test-time augmentation for image segmentation that averages predictions
for input image and vertically flipped one.
For segmentation we need to reverse the transformation after making a prediction
on augmented input.
:param model: Model to use for making predictions.
:param image: Model input.
:return: Arithmetically averaged predictions
"""
return fliplr_image_deaugment(model(fliplr_image_augment(image))) | [
"def",
"fliplr_image2mask",
"(",
"model",
":",
"nn",
".",
"Module",
",",
"image",
":",
"Tensor",
")",
"->",
"Tensor",
":",
"return",
"fliplr_image_deaugment",
"(",
"model",
"(",
"fliplr_image_augment",
"(",
"image",
")",
")",
")"
] | https://github.com/BloodAxe/pytorch-toolbelt/blob/cab4fc4e209d9c9e5db18cf1e01bb979c65cf08b/pytorch_toolbelt/inference/tta.py#L213-L223 | |
holoviz/holoviews | cc6b27f01710402fdfee2aeef1507425ca78c91f | holoviews/core/data/cudf.py | python | cuDFInterface.select_mask | (cls, dataset, selection) | return mask | Given a Dataset object and a dictionary with dimension keys and
selection keys (i.e. tuple ranges, slices, sets, lists, or literals)
return a boolean mask over the rows in the Dataset object that
have been selected. | Given a Dataset object and a dictionary with dimension keys and
selection keys (i.e. tuple ranges, slices, sets, lists, or literals)
return a boolean mask over the rows in the Dataset object that
have been selected. | [
"Given",
"a",
"Dataset",
"object",
"and",
"a",
"dictionary",
"with",
"dimension",
"keys",
"and",
"selection",
"keys",
"(",
"i",
".",
"e",
".",
"tuple",
"ranges",
"slices",
"sets",
"lists",
"or",
"literals",
")",
"return",
"a",
"boolean",
"mask",
"over",
... | def select_mask(cls, dataset, selection):
"""
Given a Dataset object and a dictionary with dimension keys and
selection keys (i.e. tuple ranges, slices, sets, lists, or literals)
return a boolean mask over the rows in the Dataset object that
have been selected.
"""
mask = None
for dim, sel in selection.items():
if isinstance(sel, tuple):
sel = slice(*sel)
arr = cls.values(dataset, dim, keep_index=True)
if util.isdatetime(arr) and util.pd:
try:
sel = util.parse_datetime_selection(sel)
except:
pass
new_masks = []
if isinstance(sel, slice):
with warnings.catch_warnings():
warnings.filterwarnings('ignore', r'invalid value encountered')
if sel.start is not None:
new_masks.append(sel.start <= arr)
if sel.stop is not None:
new_masks.append(arr < sel.stop)
if not new_masks:
continue
new_mask = new_masks[0]
for imask in new_masks[1:]:
new_mask &= imask
elif isinstance(sel, (set, list)):
for v in sel:
new_masks.append(arr==v)
if not new_masks:
continue
new_mask = new_masks[0]
for imask in new_masks[1:]:
new_mask |= imask
elif callable(sel):
new_mask = sel(arr)
else:
new_mask = arr == sel
if mask is None:
mask = new_mask
else:
mask &= new_mask
return mask | [
"def",
"select_mask",
"(",
"cls",
",",
"dataset",
",",
"selection",
")",
":",
"mask",
"=",
"None",
"for",
"dim",
",",
"sel",
"in",
"selection",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"sel",
",",
"tuple",
")",
":",
"sel",
"=",
"slice"... | https://github.com/holoviz/holoviews/blob/cc6b27f01710402fdfee2aeef1507425ca78c91f/holoviews/core/data/cudf.py#L190-L238 | |
tomplus/kubernetes_asyncio | f028cc793e3a2c519be6a52a49fb77ff0b014c9b | kubernetes_asyncio/client/models/v1_deployment_status.py | python | V1DeploymentStatus.unavailable_replicas | (self, unavailable_replicas) | Sets the unavailable_replicas of this V1DeploymentStatus.
Total number of unavailable pods targeted by this deployment. This is the total number of pods that are still required for the deployment to have 100% available capacity. They may either be pods that are running but not yet available or pods that still have not been created. # noqa: E501
:param unavailable_replicas: The unavailable_replicas of this V1DeploymentStatus. # noqa: E501
:type: int | Sets the unavailable_replicas of this V1DeploymentStatus. | [
"Sets",
"the",
"unavailable_replicas",
"of",
"this",
"V1DeploymentStatus",
"."
] | def unavailable_replicas(self, unavailable_replicas):
"""Sets the unavailable_replicas of this V1DeploymentStatus.
Total number of unavailable pods targeted by this deployment. This is the total number of pods that are still required for the deployment to have 100% available capacity. They may either be pods that are running but not yet available or pods that still have not been created. # noqa: E501
:param unavailable_replicas: The unavailable_replicas of this V1DeploymentStatus. # noqa: E501
:type: int
"""
self._unavailable_replicas = unavailable_replicas | [
"def",
"unavailable_replicas",
"(",
"self",
",",
"unavailable_replicas",
")",
":",
"self",
".",
"_unavailable_replicas",
"=",
"unavailable_replicas"
] | https://github.com/tomplus/kubernetes_asyncio/blob/f028cc793e3a2c519be6a52a49fb77ff0b014c9b/kubernetes_asyncio/client/models/v1_deployment_status.py#L240-L249 | ||
neurolib-dev/neurolib | 8d8ed2ceb422e9a1367193495a7e2df96cf4e4a3 | neurolib/models/aln/loadDefaultParams.py | python | generateRandomICs | (N, seed=None) | return (
mufe_init,
mufi_init,
IA_init,
seem_init,
seim_init,
seev_init,
seiv_init,
siim_init,
siem_init,
siiv_init,
siev_init,
rates_exc_init,
rates_inh_init,
) | Generates random Initial Conditions for the interareal network
:params N: Number of area in the large scale network
:returns: A tuple of 9 N-length numpy arrays representining:
mufe_init, IA_init, mufi_init, sem_init, sev_init,
sim_init, siv_init, rates_exc_init, rates_inh_init | Generates random Initial Conditions for the interareal network | [
"Generates",
"random",
"Initial",
"Conditions",
"for",
"the",
"interareal",
"network"
] | def generateRandomICs(N, seed=None):
"""Generates random Initial Conditions for the interareal network
:params N: Number of area in the large scale network
:returns: A tuple of 9 N-length numpy arrays representining:
mufe_init, IA_init, mufi_init, sem_init, sev_init,
sim_init, siv_init, rates_exc_init, rates_inh_init
"""
np.random.seed(seed)
mufe_init = 3 * np.random.uniform(0, 1, (N,)) # mV/ms
mufi_init = 3 * np.random.uniform(0, 1, (N,)) # mV/ms
seem_init = 0.5 * np.random.uniform(0, 1, (N,))
seim_init = 0.5 * np.random.uniform(0, 1, (N,))
seev_init = 0.001 * np.random.uniform(0, 1, (N,))
seiv_init = 0.001 * np.random.uniform(0, 1, (N,))
siim_init = 0.5 * np.random.uniform(0, 1, (N,))
siem_init = 0.5 * np.random.uniform(0, 1, (N,))
siiv_init = 0.01 * np.random.uniform(0, 1, (N,))
siev_init = 0.01 * np.random.uniform(0, 1, (N,))
rates_exc_init = 0.01 * np.random.uniform(0, 1, (N, 1))
rates_inh_init = 0.01 * np.random.uniform(0, 1, (N, 1))
IA_init = 200.0 * np.random.uniform(0, 1, (N, 1)) # pA
return (
mufe_init,
mufi_init,
IA_init,
seem_init,
seim_init,
seev_init,
seiv_init,
siim_init,
siem_init,
siiv_init,
siev_init,
rates_exc_init,
rates_inh_init,
) | [
"def",
"generateRandomICs",
"(",
"N",
",",
"seed",
"=",
"None",
")",
":",
"np",
".",
"random",
".",
"seed",
"(",
"seed",
")",
"mufe_init",
"=",
"3",
"*",
"np",
".",
"random",
".",
"uniform",
"(",
"0",
",",
"1",
",",
"(",
"N",
",",
")",
")",
"... | https://github.com/neurolib-dev/neurolib/blob/8d8ed2ceb422e9a1367193495a7e2df96cf4e4a3/neurolib/models/aln/loadDefaultParams.py#L211-L250 | |
intel/virtual-storage-manager | 00706ab9701acbd0d5e04b19cc80c6b66a2973b8 | source/vsm/vsm/api/v1/agents.py | python | AgentsController._write_openstack_ip | (self) | return True | Write Openstack nova controller ips
and cinder volume ips into DB.
Openstack Ips:
10.239.82.xx
10.239.82.yy
Just write Ip addr here. | Write Openstack nova controller ips
and cinder volume ips into DB. | [
"Write",
"Openstack",
"nova",
"controller",
"ips",
"and",
"cinder",
"volume",
"ips",
"into",
"DB",
"."
] | def _write_openstack_ip(self):
""" Write Openstack nova controller ips
and cinder volume ips into DB.
Openstack Ips:
10.239.82.xx
10.239.82.yy
Just write Ip addr here.
"""
ip_list = self._cluster_info['openstack_ip']
if ip_list:
try:
# fake one user id and project id
self._context.user_id = 32 * '1'
self._context.project_id = 32 * '1'
node_list = appnodes.create(self._context, ip_list, allow_duplicate=True)
#LOG.debug('app nodes added %s' % node_list)
for node in node_list:
status = 'reachable'
appnodes.update(self._context, node.id, status)
except Exception as e:
LOG.error('Failed to add app nodes with error %s' % e)
return False
return True | [
"def",
"_write_openstack_ip",
"(",
"self",
")",
":",
"ip_list",
"=",
"self",
".",
"_cluster_info",
"[",
"'openstack_ip'",
"]",
"if",
"ip_list",
":",
"try",
":",
"# fake one user id and project id",
"self",
".",
"_context",
".",
"user_id",
"=",
"32",
"*",
"'1'"... | https://github.com/intel/virtual-storage-manager/blob/00706ab9701acbd0d5e04b19cc80c6b66a2973b8/source/vsm/vsm/api/v1/agents.py#L314-L337 | |
bungnoid/glTools | 8ff0899de43784a18bd4543285655e68e28fb5e5 | ui/utils.py | python | exportFolderBrowser | (textField) | Set the output directory from file browser selection | Set the output directory from file browser selection | [
"Set",
"the",
"output",
"directory",
"from",
"file",
"browser",
"selection"
] | def exportFolderBrowser(textField):
'''
Set the output directory from file browser selection
'''
mm.eval('global proc exportGetFolder(string $textField,string $path,string $type){ textFieldButtonGrp -e -text $path $textField; /*deleteUI projectViewerWindow;*/ }')
mm.eval('fileBrowser "exportGetFolder '+textField+'" Export "" 4') | [
"def",
"exportFolderBrowser",
"(",
"textField",
")",
":",
"mm",
".",
"eval",
"(",
"'global proc exportGetFolder(string $textField,string $path,string $type){ textFieldButtonGrp -e -text $path $textField; /*deleteUI projectViewerWindow;*/ }'",
")",
"mm",
".",
"eval",
"(",
"'fileBrowse... | https://github.com/bungnoid/glTools/blob/8ff0899de43784a18bd4543285655e68e28fb5e5/ui/utils.py#L105-L110 | ||
KoreLogicSecurity/mastiff | 04d569e4fa59513572e77c74b049cad82f9b0310 | mastiff/plugins/output/OUTPUT-text.py | python | _extend | (data, length=0) | Returns a unicode string that is left justified by the length given. | Returns a unicode string that is left justified by the length given. | [
"Returns",
"a",
"unicode",
"string",
"that",
"is",
"left",
"justified",
"by",
"the",
"length",
"given",
"."
] | def _extend(data, length=0):
""" Returns a unicode string that is left justified by the length given. """
if data is None:
return u""
try:
outstr = data.ljust(length)
except AttributeError:
outstr = str(data).ljust(length)
except UnicodeEncodeError:
outstr = data.decode('utf-8').ljust(length)
if isinstance(outstr, unicode):
return outstr
else:
return unicode(outstr, 'utf-8', 'replace') | [
"def",
"_extend",
"(",
"data",
",",
"length",
"=",
"0",
")",
":",
"if",
"data",
"is",
"None",
":",
"return",
"u\"\"",
"try",
":",
"outstr",
"=",
"data",
".",
"ljust",
"(",
"length",
")",
"except",
"AttributeError",
":",
"outstr",
"=",
"str",
"(",
"... | https://github.com/KoreLogicSecurity/mastiff/blob/04d569e4fa59513572e77c74b049cad82f9b0310/mastiff/plugins/output/OUTPUT-text.py#L52-L67 | ||
mdiazcl/fuzzbunch-debian | 2b76c2249ade83a389ae3badb12a1bd09901fd2c | windows/Resources/Python/Core/Lib/mailbox.py | python | MH.close | (self) | Flush and close the mailbox. | Flush and close the mailbox. | [
"Flush",
"and",
"close",
"the",
"mailbox",
"."
] | def close(self):
"""Flush and close the mailbox."""
if self._locked:
self.unlock() | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"self",
".",
"_locked",
":",
"self",
".",
"unlock",
"(",
")"
] | https://github.com/mdiazcl/fuzzbunch-debian/blob/2b76c2249ade83a389ae3badb12a1bd09901fd2c/windows/Resources/Python/Core/Lib/mailbox.py#L1028-L1031 | ||
gramps-project/gramps | 04d4651a43eb210192f40a9f8c2bad8ee8fa3753 | gramps/gen/lib/date.py | python | Date.newyear_to_str | (self) | return nyear | Return the string representation of the newyear. | Return the string representation of the newyear. | [
"Return",
"the",
"string",
"representation",
"of",
"the",
"newyear",
"."
] | def newyear_to_str(self):
"""
Return the string representation of the newyear.
"""
if self.newyear == Date.NEWYEAR_JAN1:
nyear = ""
elif self.newyear == Date.NEWYEAR_MAR1:
nyear = "Mar1"
elif self.newyear == Date.NEWYEAR_MAR25:
nyear = "Mar25"
elif self.newyear == Date.NEWYEAR_SEP1:
nyear = "Sep1"
elif isinstance(self.newyear, (list, tuple)):
nyear = "%s-%s" % (self.newyear[0], self.newyear[1])
else:
nyear = "Err"
return nyear | [
"def",
"newyear_to_str",
"(",
"self",
")",
":",
"if",
"self",
".",
"newyear",
"==",
"Date",
".",
"NEWYEAR_JAN1",
":",
"nyear",
"=",
"\"\"",
"elif",
"self",
".",
"newyear",
"==",
"Date",
".",
"NEWYEAR_MAR1",
":",
"nyear",
"=",
"\"Mar1\"",
"elif",
"self",
... | https://github.com/gramps-project/gramps/blob/04d4651a43eb210192f40a9f8c2bad8ee8fa3753/gramps/gen/lib/date.py#L1089-L1105 | |
facebookresearch/mmf | fb6fe390287e1da12c3bd28d4ab43c5f7dcdfc9f | mmf/datasets/mmf_dataset.py | python | MMFDataset.build_features_db | (self) | return FeaturesDatabase(
self.config, features_path, annotation_db=self.annotation_db
) | [] | def build_features_db(self):
features_path = self._get_path_based_on_index(
self.config, "features", self._index
)
return FeaturesDatabase(
self.config, features_path, annotation_db=self.annotation_db
) | [
"def",
"build_features_db",
"(",
"self",
")",
":",
"features_path",
"=",
"self",
".",
"_get_path_based_on_index",
"(",
"self",
".",
"config",
",",
"\"features\"",
",",
"self",
".",
"_index",
")",
"return",
"FeaturesDatabase",
"(",
"self",
".",
"config",
",",
... | https://github.com/facebookresearch/mmf/blob/fb6fe390287e1da12c3bd28d4ab43c5f7dcdfc9f/mmf/datasets/mmf_dataset.py#L48-L54 | |||
hyperspy/hyperspy | 1ffb3fab33e607045a37f30c1463350b72617e10 | hyperspy/drawing/_widgets/line2d.py | python | Line2DWidget._onmousemove | (self, event) | Delegate to _move(), _resize() or _rotate(). | Delegate to _move(), _resize() or _rotate(). | [
"Delegate",
"to",
"_move",
"()",
"_resize",
"()",
"or",
"_rotate",
"()",
"."
] | def _onmousemove(self, event):
"""Delegate to _move(), _resize() or _rotate().
"""
if self.picked is True:
if self.func & self.FUNC_MOVE and event.inaxes:
self._move(event)
elif self.func & self.FUNC_RESIZE and event.inaxes:
self._resize(event)
elif self.func & self.FUNC_ROTATE:
self._rotate(event)
elif self.func & self.FUNC_SIZERS and event.inaxes:
self._width_resize(event) | [
"def",
"_onmousemove",
"(",
"self",
",",
"event",
")",
":",
"if",
"self",
".",
"picked",
"is",
"True",
":",
"if",
"self",
".",
"func",
"&",
"self",
".",
"FUNC_MOVE",
"and",
"event",
".",
"inaxes",
":",
"self",
".",
"_move",
"(",
"event",
")",
"elif... | https://github.com/hyperspy/hyperspy/blob/1ffb3fab33e607045a37f30c1463350b72617e10/hyperspy/drawing/_widgets/line2d.py#L390-L401 | ||
kanzure/nanoengineer | 874e4c9f8a9190f093625b267f9767e19f82e6c4 | cad/src/protein/commands/BackrubProteinSim/BackrubProteinSim_PropertyManager.py | python | BackrubProteinSim_PropertyManager.update_soft_rep_design | (self, state) | return | Update the command text edit depending on the state of the update_soft_rep_design
checkbox
@param state:state of the update_soft_rep_design checkbox
@type state: int | Update the command text edit depending on the state of the update_soft_rep_design
checkbox | [
"Update",
"the",
"command",
"text",
"edit",
"depending",
"on",
"the",
"state",
"of",
"the",
"update_soft_rep_design",
"checkbox"
] | def update_soft_rep_design(self, state):
"""
Update the command text edit depending on the state of the update_soft_rep_design
checkbox
@param state:state of the update_soft_rep_design checkbox
@type state: int
"""
otherOptionsText = str(self.otherCommandLineOptions.toPlainText())
if self.softRepDesignCheckbox.isChecked() == True:
otherOptionsText = otherOptionsText + ' -soft_rep_design '
else:
otherOptionsText = otherOptionsText.replace(' -soft_rep_design ', '')
self.otherCommandLineOptions.setText(otherOptionsText)
return | [
"def",
"update_soft_rep_design",
"(",
"self",
",",
"state",
")",
":",
"otherOptionsText",
"=",
"str",
"(",
"self",
".",
"otherCommandLineOptions",
".",
"toPlainText",
"(",
")",
")",
"if",
"self",
".",
"softRepDesignCheckbox",
".",
"isChecked",
"(",
")",
"==",
... | https://github.com/kanzure/nanoengineer/blob/874e4c9f8a9190f093625b267f9767e19f82e6c4/cad/src/protein/commands/BackrubProteinSim/BackrubProteinSim_PropertyManager.py#L458-L471 | |
saltstack/salt | fae5bc757ad0f1716483ce7ae180b451545c2058 | salt/utils/boto3mod.py | python | get_region | (service, region, profile) | return region | Retrieve the region for a particular AWS service based on configured region and/or profile. | Retrieve the region for a particular AWS service based on configured region and/or profile. | [
"Retrieve",
"the",
"region",
"for",
"a",
"particular",
"AWS",
"service",
"based",
"on",
"configured",
"region",
"and",
"/",
"or",
"profile",
"."
] | def get_region(service, region, profile):
"""
Retrieve the region for a particular AWS service based on configured region and/or profile.
"""
_, region, _, _ = _get_profile(service, region, None, None, profile)
return region | [
"def",
"get_region",
"(",
"service",
",",
"region",
",",
"profile",
")",
":",
"_",
",",
"region",
",",
"_",
",",
"_",
"=",
"_get_profile",
"(",
"service",
",",
"region",
",",
"None",
",",
"None",
",",
"profile",
")",
"return",
"region"
] | https://github.com/saltstack/salt/blob/fae5bc757ad0f1716483ce7ae180b451545c2058/salt/utils/boto3mod.py#L227-L233 | |
ClusterHQ/flocker | eaa586248986d7cd681c99c948546c2b507e44de | flocker/node/_docker.py | python | IDockerClient.list | () | List all known units.
:return: ``Deferred`` firing with ``set`` of :class:`Unit`. | List all known units. | [
"List",
"all",
"known",
"units",
"."
] | def list():
"""
List all known units.
:return: ``Deferred`` firing with ``set`` of :class:`Unit`.
""" | [
"def",
"list",
"(",
")",
":"
] | https://github.com/ClusterHQ/flocker/blob/eaa586248986d7cd681c99c948546c2b507e44de/flocker/node/_docker.py#L280-L285 | ||
omz/PythonistaAppTemplate | f560f93f8876d82a21d108977f90583df08d55af | PythonistaAppTemplate/PythonistaKit.framework/pylib_ext/sympy/polys/densebasic.py | python | dmp_degree | (f, u) | Return the leading degree of ``f`` in ``x_0`` in ``K[X]``.
Note that the degree of 0 is negative infinity (the SymPy object -oo).
Examples
========
>>> from sympy.polys.domains import ZZ
>>> from sympy.polys.densebasic import dmp_degree
>>> dmp_degree([[[]]], 2)
-oo
>>> f = ZZ.map([[2], [1, 2, 3]])
>>> dmp_degree(f, 1)
1 | Return the leading degree of ``f`` in ``x_0`` in ``K[X]``. | [
"Return",
"the",
"leading",
"degree",
"of",
"f",
"in",
"x_0",
"in",
"K",
"[",
"X",
"]",
"."
] | def dmp_degree(f, u):
"""
Return the leading degree of ``f`` in ``x_0`` in ``K[X]``.
Note that the degree of 0 is negative infinity (the SymPy object -oo).
Examples
========
>>> from sympy.polys.domains import ZZ
>>> from sympy.polys.densebasic import dmp_degree
>>> dmp_degree([[[]]], 2)
-oo
>>> f = ZZ.map([[2], [1, 2, 3]])
>>> dmp_degree(f, 1)
1
"""
if dmp_zero_p(f, u):
return -oo
else:
return len(f) - 1 | [
"def",
"dmp_degree",
"(",
"f",
",",
"u",
")",
":",
"if",
"dmp_zero_p",
"(",
"f",
",",
"u",
")",
":",
"return",
"-",
"oo",
"else",
":",
"return",
"len",
"(",
"f",
")",
"-",
"1"
] | https://github.com/omz/PythonistaAppTemplate/blob/f560f93f8876d82a21d108977f90583df08d55af/PythonistaAppTemplate/PythonistaKit.framework/pylib_ext/sympy/polys/densebasic.py#L161-L185 | ||
bigmlcom/python | 35f69d2f3121f1b3dde43495cf145d4992796ad5 | bigml/api_handlers/batchcentroidhandler.py | python | BatchCentroidHandlerMixin.download_batch_centroid | (self, batch_centroid, filename=None,
retries=10) | return self._download_resource(batch_centroid, filename,
retries=retries) | Retrieves the batch centroid file.
Downloads centroids, that are stored in a remote CSV file. If
a path is given in filename, the contents of the file are downloaded
and saved locally. A file-like object is returned otherwise. | Retrieves the batch centroid file. | [
"Retrieves",
"the",
"batch",
"centroid",
"file",
"."
] | def download_batch_centroid(self, batch_centroid, filename=None,
retries=10):
"""Retrieves the batch centroid file.
Downloads centroids, that are stored in a remote CSV file. If
a path is given in filename, the contents of the file are downloaded
and saved locally. A file-like object is returned otherwise.
"""
check_resource_type(batch_centroid, BATCH_CENTROID_PATH,
message="A batch centroid id is needed.")
return self._download_resource(batch_centroid, filename,
retries=retries) | [
"def",
"download_batch_centroid",
"(",
"self",
",",
"batch_centroid",
",",
"filename",
"=",
"None",
",",
"retries",
"=",
"10",
")",
":",
"check_resource_type",
"(",
"batch_centroid",
",",
"BATCH_CENTROID_PATH",
",",
"message",
"=",
"\"A batch centroid id is needed.\""... | https://github.com/bigmlcom/python/blob/35f69d2f3121f1b3dde43495cf145d4992796ad5/bigml/api_handlers/batchcentroidhandler.py#L81-L92 | |
qtile/qtile | 803dc06fc1f8b121a1d8fe047f26a43812cd427f | libqtile/core/manager.py | python | Qtile.async_loop | (self) | Run the event loop
Finalizes the Qtile instance on exit. | Run the event loop | [
"Run",
"the",
"event",
"loop"
] | async def async_loop(self) -> None:
"""Run the event loop
Finalizes the Qtile instance on exit.
"""
self._eventloop = asyncio.get_running_loop()
# Set the event loop policy to facilitate access to main event loop
asyncio.set_event_loop_policy(QtileEventLoopPolicy(self))
self._stopped_event = asyncio.Event()
self.core.setup_listener(self)
try:
async with LoopContext(
{
signal.SIGTERM: self.stop,
signal.SIGINT: self.stop,
signal.SIGHUP: self.stop,
signal.SIGUSR1: self.cmd_reload_config,
signal.SIGUSR2: self.cmd_restart,
}
), ipc.Server(
self._prepare_socket_path(self.socket_path),
self.server.call,
):
self.load_config(initial=True)
await self._stopped_event.wait()
finally:
self.finalize()
self.core.remove_listener() | [
"async",
"def",
"async_loop",
"(",
"self",
")",
"->",
"None",
":",
"self",
".",
"_eventloop",
"=",
"asyncio",
".",
"get_running_loop",
"(",
")",
"# Set the event loop policy to facilitate access to main event loop",
"asyncio",
".",
"set_event_loop_policy",
"(",
"QtileEv... | https://github.com/qtile/qtile/blob/803dc06fc1f8b121a1d8fe047f26a43812cd427f/libqtile/core/manager.py#L192-L219 | ||
chribsen/simple-machine-learning-examples | dc94e52a4cebdc8bb959ff88b81ff8cfeca25022 | venv/lib/python2.7/site-packages/sklearn/discriminant_analysis.py | python | QuadraticDiscriminantAnalysis.fit | (self, X, y, store_covariances=None, tol=None) | return self | Fit the model according to the given training data and parameters.
.. versionchanged:: 0.17
Deprecated *store_covariance* have been moved to main constructor.
.. versionchanged:: 0.17
Deprecated *tol* have been moved to main constructor.
Parameters
----------
X : array-like, shape = [n_samples, n_features]
Training vector, where n_samples in the number of samples and
n_features is the number of features.
y : array, shape = [n_samples]
Target values (integers) | Fit the model according to the given training data and parameters. | [
"Fit",
"the",
"model",
"according",
"to",
"the",
"given",
"training",
"data",
"and",
"parameters",
"."
] | def fit(self, X, y, store_covariances=None, tol=None):
"""Fit the model according to the given training data and parameters.
.. versionchanged:: 0.17
Deprecated *store_covariance* have been moved to main constructor.
.. versionchanged:: 0.17
Deprecated *tol* have been moved to main constructor.
Parameters
----------
X : array-like, shape = [n_samples, n_features]
Training vector, where n_samples in the number of samples and
n_features is the number of features.
y : array, shape = [n_samples]
Target values (integers)
"""
if store_covariances:
warnings.warn("The parameter 'store_covariances' is deprecated as "
"of version 0.17 and will be removed in 0.19. The "
"parameter is no longer necessary because the value "
"is set via the estimator initialisation or "
"set_params method.", DeprecationWarning)
self.store_covariances = store_covariances
if tol:
warnings.warn("The parameter 'tol' is deprecated as of version "
"0.17 and will be removed in 0.19. The parameter is "
"no longer necessary because the value is set via "
"the estimator initialisation or set_params method.",
DeprecationWarning)
self.tol = tol
X, y = check_X_y(X, y)
check_classification_targets(y)
self.classes_, y = np.unique(y, return_inverse=True)
n_samples, n_features = X.shape
n_classes = len(self.classes_)
if n_classes < 2:
raise ValueError('y has less than 2 classes')
if self.priors is None:
self.priors_ = bincount(y) / float(n_samples)
else:
self.priors_ = self.priors
cov = None
if self.store_covariances:
cov = []
means = []
scalings = []
rotations = []
for ind in xrange(n_classes):
Xg = X[y == ind, :]
meang = Xg.mean(0)
means.append(meang)
if len(Xg) == 1:
raise ValueError('y has only 1 sample in class %s, covariance '
'is ill defined.' % str(self.classes_[ind]))
Xgc = Xg - meang
# Xgc = U * S * V.T
U, S, Vt = np.linalg.svd(Xgc, full_matrices=False)
rank = np.sum(S > self.tol)
if rank < n_features:
warnings.warn("Variables are collinear")
S2 = (S ** 2) / (len(Xg) - 1)
S2 = ((1 - self.reg_param) * S2) + self.reg_param
if self.store_covariances:
# cov = V * (S^2 / (n-1)) * V.T
cov.append(np.dot(S2 * Vt.T, Vt))
scalings.append(S2)
rotations.append(Vt.T)
if self.store_covariances:
self.covariances_ = cov
self.means_ = np.asarray(means)
self.scalings_ = scalings
self.rotations_ = rotations
return self | [
"def",
"fit",
"(",
"self",
",",
"X",
",",
"y",
",",
"store_covariances",
"=",
"None",
",",
"tol",
"=",
"None",
")",
":",
"if",
"store_covariances",
":",
"warnings",
".",
"warn",
"(",
"\"The parameter 'store_covariances' is deprecated as \"",
"\"of version 0.17 and... | https://github.com/chribsen/simple-machine-learning-examples/blob/dc94e52a4cebdc8bb959ff88b81ff8cfeca25022/venv/lib/python2.7/site-packages/sklearn/discriminant_analysis.py#L633-L708 | |
orsinium-archive/django-bruteforce-protection | f4b1d44c37ea0c4893878ecf4dc9669a6035ea42 | djbrut/checkers.py | python | IPChecker.get_value | (self, request, ip=None, **kwargs) | return request.META['REMOTE_ADDR'] | [] | def get_value(self, request, ip=None, **kwargs):
if not request:
return
# from kwargs
if ip is not None:
return ip
# from axes or ipware
ip = get_client_ip(request)
if ip:
return ip
# directly from headers
return request.META['REMOTE_ADDR'] | [
"def",
"get_value",
"(",
"self",
",",
"request",
",",
"ip",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"request",
":",
"return",
"# from kwargs",
"if",
"ip",
"is",
"not",
"None",
":",
"return",
"ip",
"# from axes or ipware",
"ip",
"="... | https://github.com/orsinium-archive/django-bruteforce-protection/blob/f4b1d44c37ea0c4893878ecf4dc9669a6035ea42/djbrut/checkers.py#L153-L164 | |||
elfi-dev/elfi | 07ac0ed5e81d5d5fb42de63db3cf9ccc9135b88c | elfi/visualization/visualization.py | python | ProgressBar.reinit_progressbar | (self, scaling=0, reinit_msg="") | Reinitialize new round of progress bar.
Parameters
----------
scaling : int, optional
Integer used to scale current and total iterations of the progress bar
reinit_msg : str, optional
Message printed before restarting an empty progess bar on a new line | Reinitialize new round of progress bar. | [
"Reinitialize",
"new",
"round",
"of",
"progress",
"bar",
"."
] | def reinit_progressbar(self, scaling=0, reinit_msg=""):
"""Reinitialize new round of progress bar.
Parameters
----------
scaling : int, optional
Integer used to scale current and total iterations of the progress bar
reinit_msg : str, optional
Message printed before restarting an empty progess bar on a new line
"""
self.scaling = scaling
self.finished = False
print(reinit_msg) | [
"def",
"reinit_progressbar",
"(",
"self",
",",
"scaling",
"=",
"0",
",",
"reinit_msg",
"=",
"\"\"",
")",
":",
"self",
".",
"scaling",
"=",
"scaling",
"self",
".",
"finished",
"=",
"False",
"print",
"(",
"reinit_msg",
")"
] | https://github.com/elfi-dev/elfi/blob/07ac0ed5e81d5d5fb42de63db3cf9ccc9135b88c/elfi/visualization/visualization.py#L616-L629 | ||
LinkedInAttic/indextank-service | 880c6295ce8e7a3a55bf9b3777cc35c7680e0d7e | storefront/boto/rds/__init__.py | python | RDSConnection.get_all_dbsnapshots | (self, snapshot_id=None, instance_id=None,
max_records=None, marker=None) | return self.get_list('DescribeDBSnapshots', params,
[('DBSnapshots', DBSnapshot)]) | Get information about DB Snapshots.
:type snapshot_id: str
:param snapshot_id: The unique identifier of an RDS snapshot.
If not provided, all RDS snapshots will be returned.
:type instance_id: str
:param instance_id: The identifier of a DBInstance. If provided,
only the DBSnapshots related to that instance will
be returned.
If not provided, all RDS snapshots will be returned.
:type max_records: int
:param max_records: The maximum number of records to be returned.
If more results are available, a MoreToken will
be returned in the response that can be used to
retrieve additional records. Default is 100.
:type marker: str
:param marker: The marker provided by a previous request.
:rtype: list
:return: A list of :class:`boto.rds.dbsnapshot.DBSnapshot` | Get information about DB Snapshots.
:type snapshot_id: str
:param snapshot_id: The unique identifier of an RDS snapshot.
If not provided, all RDS snapshots will be returned.
:type instance_id: str
:param instance_id: The identifier of a DBInstance. If provided,
only the DBSnapshots related to that instance will
be returned.
If not provided, all RDS snapshots will be returned.
:type max_records: int
:param max_records: The maximum number of records to be returned.
If more results are available, a MoreToken will
be returned in the response that can be used to
retrieve additional records. Default is 100.
:type marker: str
:param marker: The marker provided by a previous request.
:rtype: list
:return: A list of :class:`boto.rds.dbsnapshot.DBSnapshot` | [
"Get",
"information",
"about",
"DB",
"Snapshots",
".",
":",
"type",
"snapshot_id",
":",
"str",
":",
"param",
"snapshot_id",
":",
"The",
"unique",
"identifier",
"of",
"an",
"RDS",
"snapshot",
".",
"If",
"not",
"provided",
"all",
"RDS",
"snapshots",
"will",
... | def get_all_dbsnapshots(self, snapshot_id=None, instance_id=None,
max_records=None, marker=None):
"""
Get information about DB Snapshots.
:type snapshot_id: str
:param snapshot_id: The unique identifier of an RDS snapshot.
If not provided, all RDS snapshots will be returned.
:type instance_id: str
:param instance_id: The identifier of a DBInstance. If provided,
only the DBSnapshots related to that instance will
be returned.
If not provided, all RDS snapshots will be returned.
:type max_records: int
:param max_records: The maximum number of records to be returned.
If more results are available, a MoreToken will
be returned in the response that can be used to
retrieve additional records. Default is 100.
:type marker: str
:param marker: The marker provided by a previous request.
:rtype: list
:return: A list of :class:`boto.rds.dbsnapshot.DBSnapshot`
"""
params = {}
if snapshot_id:
params['DBSnapshotIdentifier'] = snapshot_id
if instance_id:
params['DBInstanceIdentifier'] = instance_id
if max_records:
params['MaxRecords'] = max_records
if marker:
params['Marker'] = marker
return self.get_list('DescribeDBSnapshots', params,
[('DBSnapshots', DBSnapshot)]) | [
"def",
"get_all_dbsnapshots",
"(",
"self",
",",
"snapshot_id",
"=",
"None",
",",
"instance_id",
"=",
"None",
",",
"max_records",
"=",
"None",
",",
"marker",
"=",
"None",
")",
":",
"params",
"=",
"{",
"}",
"if",
"snapshot_id",
":",
"params",
"[",
"'DBSnap... | https://github.com/LinkedInAttic/indextank-service/blob/880c6295ce8e7a3a55bf9b3777cc35c7680e0d7e/storefront/boto/rds/__init__.py#L589-L626 | |
evhub/coconut | 27a4af9dc06667870f736f20c862930001b8cbb2 | coconut/compiler/compiler.py | python | Compiler.parse_eval | (self, inputstring) | return self.parse(inputstring, self.eval_parser, {"strip": True}, {"header": "none", "initial": "none", "final_endline": False}) | Parse eval code. | Parse eval code. | [
"Parse",
"eval",
"code",
"."
] | def parse_eval(self, inputstring):
"""Parse eval code."""
return self.parse(inputstring, self.eval_parser, {"strip": True}, {"header": "none", "initial": "none", "final_endline": False}) | [
"def",
"parse_eval",
"(",
"self",
",",
"inputstring",
")",
":",
"return",
"self",
".",
"parse",
"(",
"inputstring",
",",
"self",
".",
"eval_parser",
",",
"{",
"\"strip\"",
":",
"True",
"}",
",",
"{",
"\"header\"",
":",
"\"none\"",
",",
"\"initial\"",
":"... | https://github.com/evhub/coconut/blob/27a4af9dc06667870f736f20c862930001b8cbb2/coconut/compiler/compiler.py#L3143-L3145 | |
ucbdrive/skipnet | 4825e53aaf72a505c3328cd89ad27533946d8a96 | cifar/train_sp.py | python | adjust_learning_rate | (args, optimizer, _iter) | divide lr by 10 at 32k and 48k | divide lr by 10 at 32k and 48k | [
"divide",
"lr",
"by",
"10",
"at",
"32k",
"and",
"48k"
] | def adjust_learning_rate(args, optimizer, _iter):
""" divide lr by 10 at 32k and 48k """
if args.warm_up and (_iter < 400):
lr = 0.01
elif 32000 <= _iter < 48000:
lr = args.lr * (args.step_ratio ** 1)
elif _iter >= 48000:
lr = args.lr * (args.step_ratio ** 2)
else:
lr = args.lr
if _iter % args.eval_every == 0:
logging.info('Iter [{}] learning rate = {}'.format(_iter, lr))
for param_group in optimizer.param_groups:
param_group['lr'] = lr | [
"def",
"adjust_learning_rate",
"(",
"args",
",",
"optimizer",
",",
"_iter",
")",
":",
"if",
"args",
".",
"warm_up",
"and",
"(",
"_iter",
"<",
"400",
")",
":",
"lr",
"=",
"0.01",
"elif",
"32000",
"<=",
"_iter",
"<",
"48000",
":",
"lr",
"=",
"args",
... | https://github.com/ucbdrive/skipnet/blob/4825e53aaf72a505c3328cd89ad27533946d8a96/cifar/train_sp.py#L376-L391 | ||
TencentCloud/tencentcloud-sdk-python | 3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2 | tencentcloud/cdb/v20170320/models.py | python | DescribeDBInstanceGTIDRequest.__init__ | (self) | r"""
:param InstanceId: 实例 ID,格式如:cdb-c1nl9rpv,与云数据库控制台页面中显示的实例 ID 相同,可使用 [查询实例列表](https://cloud.tencent.com/document/api/236/15872) 接口获取,其值为输出参数中字段 InstanceId 的值。
:type InstanceId: str | r"""
:param InstanceId: 实例 ID,格式如:cdb-c1nl9rpv,与云数据库控制台页面中显示的实例 ID 相同,可使用 [查询实例列表](https://cloud.tencent.com/document/api/236/15872) 接口获取,其值为输出参数中字段 InstanceId 的值。
:type InstanceId: str | [
"r",
":",
"param",
"InstanceId",
":",
"实例",
"ID,格式如:cdb",
"-",
"c1nl9rpv,与云数据库控制台页面中显示的实例",
"ID",
"相同,可使用",
"[",
"查询实例列表",
"]",
"(",
"https",
":",
"//",
"cloud",
".",
"tencent",
".",
"com",
"/",
"document",
"/",
"api",
"/",
"236",
"/",
"15872",
")",
"接... | def __init__(self):
r"""
:param InstanceId: 实例 ID,格式如:cdb-c1nl9rpv,与云数据库控制台页面中显示的实例 ID 相同,可使用 [查询实例列表](https://cloud.tencent.com/document/api/236/15872) 接口获取,其值为输出参数中字段 InstanceId 的值。
:type InstanceId: str
"""
self.InstanceId = None | [
"def",
"__init__",
"(",
"self",
")",
":",
"self",
".",
"InstanceId",
"=",
"None"
] | https://github.com/TencentCloud/tencentcloud-sdk-python/blob/3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2/tencentcloud/cdb/v20170320/models.py#L3882-L3887 | ||
tobegit3hub/deep_image_model | 8a53edecd9e00678b278bb10f6fb4bdb1e4ee25e | java_predict_client/src/main/proto/tensorflow/contrib/training/python/training/sequence_queueing_state_saver.py | python | NextQueuedSequenceBatch.sequence | (self) | return self._state_saver._received_sequence | An int32 vector, length `batch_size`: the sequence index of each entry.
When an input is split up, the sequence values
```
0, 1, ..., sequence_count - 1
```
are assigned to each split.
Returns:
An int32 vector `Tensor`. | An int32 vector, length `batch_size`: the sequence index of each entry. | [
"An",
"int32",
"vector",
"length",
"batch_size",
":",
"the",
"sequence",
"index",
"of",
"each",
"entry",
"."
] | def sequence(self):
"""An int32 vector, length `batch_size`: the sequence index of each entry.
When an input is split up, the sequence values
```
0, 1, ..., sequence_count - 1
```
are assigned to each split.
Returns:
An int32 vector `Tensor`.
"""
return self._state_saver._received_sequence | [
"def",
"sequence",
"(",
"self",
")",
":",
"return",
"self",
".",
"_state_saver",
".",
"_received_sequence"
] | https://github.com/tobegit3hub/deep_image_model/blob/8a53edecd9e00678b278bb10f6fb4bdb1e4ee25e/java_predict_client/src/main/proto/tensorflow/contrib/training/python/training/sequence_queueing_state_saver.py#L454-L466 | |
leo-editor/leo-editor | 383d6776d135ef17d73d935a2f0ecb3ac0e99494 | leo/external/npyscreen/wgmultiselect.py | python | MultiSelectAction.actionSelected | (self, act_on_these, keypress) | Override this Method | Override this Method | [
"Override",
"this",
"Method"
] | def actionSelected(self, act_on_these, keypress):
"Override this Method"
pass | [
"def",
"actionSelected",
"(",
"self",
",",
"act_on_these",
",",
"keypress",
")",
":",
"pass"
] | https://github.com/leo-editor/leo-editor/blob/383d6776d135ef17d73d935a2f0ecb3ac0e99494/leo/external/npyscreen/wgmultiselect.py#L68-L70 | ||
dropbox/dropbox-sdk-python | 015437429be224732990041164a21a0501235db1 | dropbox/team_log.py | python | EventCategory.is_members | (self) | return self._tag == 'members' | Check if the union tag is ``members``.
:rtype: bool | Check if the union tag is ``members``. | [
"Check",
"if",
"the",
"union",
"tag",
"is",
"members",
"."
] | def is_members(self):
"""
Check if the union tag is ``members``.
:rtype: bool
"""
return self._tag == 'members' | [
"def",
"is_members",
"(",
"self",
")",
":",
"return",
"self",
".",
"_tag",
"==",
"'members'"
] | https://github.com/dropbox/dropbox-sdk-python/blob/015437429be224732990041164a21a0501235db1/dropbox/team_log.py#L7944-L7950 | |
redis/redis-py | 0affa0ed3f3cbcb6dec29b34a580f769f69ae9f7 | redis/commands/core.py | python | GeoCommands.geosearch | (
self,
name,
member=None,
longitude=None,
latitude=None,
unit="m",
radius=None,
width=None,
height=None,
sort=None,
count=None,
any=False,
withcoord=False,
withdist=False,
withhash=False,
) | return self._geosearchgeneric(
"GEOSEARCH",
name,
member=member,
longitude=longitude,
latitude=latitude,
unit=unit,
radius=radius,
width=width,
height=height,
sort=sort,
count=count,
any=any,
withcoord=withcoord,
withdist=withdist,
withhash=withhash,
store=None,
store_dist=None,
) | Return the members of specified key identified by the
``name`` argument, which are within the borders of the
area specified by a given shape. This command extends the
GEORADIUS command, so in addition to searching within circular
areas, it supports searching within rectangular areas.
This command should be used in place of the deprecated
GEORADIUS and GEORADIUSBYMEMBER commands.
``member`` Use the position of the given existing
member in the sorted set. Can't be given with ``longitude``
and ``latitude``.
``longitude`` and ``latitude`` Use the position given by
this coordinates. Can't be given with ``member``
``radius`` Similar to GEORADIUS, search inside circular
area according the given radius. Can't be given with
``height`` and ``width``.
``height`` and ``width`` Search inside an axis-aligned
rectangle, determined by the given height and width.
Can't be given with ``radius``
``unit`` must be one of the following : m, km, mi, ft.
`m` for meters (the default value), `km` for kilometers,
`mi` for miles and `ft` for feet.
``sort`` indicates to return the places in a sorted way,
ASC for nearest to farest and DESC for farest to nearest.
``count`` limit the results to the first count matching items.
``any`` is set to True, the command will return as soon as
enough matches are found. Can't be provided without ``count``
``withdist`` indicates to return the distances of each place.
``withcoord`` indicates to return the latitude and longitude of
each place.
``withhash`` indicates to return the geohash string of each place.
For more information check https://redis.io/commands/geosearch | Return the members of specified key identified by the
``name`` argument, which are within the borders of the
area specified by a given shape. This command extends the
GEORADIUS command, so in addition to searching within circular
areas, it supports searching within rectangular areas.
This command should be used in place of the deprecated
GEORADIUS and GEORADIUSBYMEMBER commands.
``member`` Use the position of the given existing
member in the sorted set. Can't be given with ``longitude``
and ``latitude``.
``longitude`` and ``latitude`` Use the position given by
this coordinates. Can't be given with ``member``
``radius`` Similar to GEORADIUS, search inside circular
area according the given radius. Can't be given with
``height`` and ``width``.
``height`` and ``width`` Search inside an axis-aligned
rectangle, determined by the given height and width.
Can't be given with ``radius``
``unit`` must be one of the following : m, km, mi, ft.
`m` for meters (the default value), `km` for kilometers,
`mi` for miles and `ft` for feet.
``sort`` indicates to return the places in a sorted way,
ASC for nearest to farest and DESC for farest to nearest.
``count`` limit the results to the first count matching items.
``any`` is set to True, the command will return as soon as
enough matches are found. Can't be provided without ``count``
``withdist`` indicates to return the distances of each place.
``withcoord`` indicates to return the latitude and longitude of
each place.
``withhash`` indicates to return the geohash string of each place. | [
"Return",
"the",
"members",
"of",
"specified",
"key",
"identified",
"by",
"the",
"name",
"argument",
"which",
"are",
"within",
"the",
"borders",
"of",
"the",
"area",
"specified",
"by",
"a",
"given",
"shape",
".",
"This",
"command",
"extends",
"the",
"GEORADI... | def geosearch(
self,
name,
member=None,
longitude=None,
latitude=None,
unit="m",
radius=None,
width=None,
height=None,
sort=None,
count=None,
any=False,
withcoord=False,
withdist=False,
withhash=False,
):
"""
Return the members of specified key identified by the
``name`` argument, which are within the borders of the
area specified by a given shape. This command extends the
GEORADIUS command, so in addition to searching within circular
areas, it supports searching within rectangular areas.
This command should be used in place of the deprecated
GEORADIUS and GEORADIUSBYMEMBER commands.
``member`` Use the position of the given existing
member in the sorted set. Can't be given with ``longitude``
and ``latitude``.
``longitude`` and ``latitude`` Use the position given by
this coordinates. Can't be given with ``member``
``radius`` Similar to GEORADIUS, search inside circular
area according the given radius. Can't be given with
``height`` and ``width``.
``height`` and ``width`` Search inside an axis-aligned
rectangle, determined by the given height and width.
Can't be given with ``radius``
``unit`` must be one of the following : m, km, mi, ft.
`m` for meters (the default value), `km` for kilometers,
`mi` for miles and `ft` for feet.
``sort`` indicates to return the places in a sorted way,
ASC for nearest to farest and DESC for farest to nearest.
``count`` limit the results to the first count matching items.
``any`` is set to True, the command will return as soon as
enough matches are found. Can't be provided without ``count``
``withdist`` indicates to return the distances of each place.
``withcoord`` indicates to return the latitude and longitude of
each place.
``withhash`` indicates to return the geohash string of each place.
For more information check https://redis.io/commands/geosearch
"""
return self._geosearchgeneric(
"GEOSEARCH",
name,
member=member,
longitude=longitude,
latitude=latitude,
unit=unit,
radius=radius,
width=width,
height=height,
sort=sort,
count=count,
any=any,
withcoord=withcoord,
withdist=withdist,
withhash=withhash,
store=None,
store_dist=None,
) | [
"def",
"geosearch",
"(",
"self",
",",
"name",
",",
"member",
"=",
"None",
",",
"longitude",
"=",
"None",
",",
"latitude",
"=",
"None",
",",
"unit",
"=",
"\"m\"",
",",
"radius",
"=",
"None",
",",
"width",
"=",
"None",
",",
"height",
"=",
"None",
","... | https://github.com/redis/redis-py/blob/0affa0ed3f3cbcb6dec29b34a580f769f69ae9f7/redis/commands/core.py#L4196-L4266 | |
jupyterhub/repo2docker | a37a205c0e8a59240933d20c1c4fb80767e71db2 | repo2docker/utils.py | python | is_local_pip_requirement | (line) | return False | Return whether a pip requirement (e.g. in requirements.txt file) references a local file | Return whether a pip requirement (e.g. in requirements.txt file) references a local file | [
"Return",
"whether",
"a",
"pip",
"requirement",
"(",
"e",
".",
"g",
".",
"in",
"requirements",
".",
"txt",
"file",
")",
"references",
"a",
"local",
"file"
] | def is_local_pip_requirement(line):
"""Return whether a pip requirement (e.g. in requirements.txt file) references a local file"""
# trim comments and skip empty lines
line = line.split("#", 1)[0].strip()
if not line:
return False
if line.startswith(("-r", "-c")):
# local -r or -c references break isolation
return True
if line.startswith(("--requirement", "--constraint")):
# as above but flags are spelt out
return True
# the `--pre` flag is a global flag and should appear on a line by itself
# we just care that this isn't a "local pip requirement"
if line.startswith("--pre"):
return False
# strip off things like `--editable=`. Long form arguments require a =
# if there is no = it is probably because the line contains
# a syntax error or our "parser" is too simplistic
if line.startswith("--") and "=" in line:
_, line = line.split("=", 1)
# strip off short form arguments like `-e`. Short form arguments can be
# followed by a space `-e foo` or use `-e=foo`. The latter is not handled
# here. We can deal with it when we see someone using it.
if line.startswith("-"):
_, *rest = line.split(None, 1)
if not rest:
# no argument after `--flag`, skip line
return False
line = rest[0]
if "file://" in line:
# file references break isolation
return True
if "://" in line:
# handle git://../local/file
path = line.split("://", 1)[1]
else:
path = line
if path.startswith("."):
# references a local file
return True
return False | [
"def",
"is_local_pip_requirement",
"(",
"line",
")",
":",
"# trim comments and skip empty lines",
"line",
"=",
"line",
".",
"split",
"(",
"\"#\"",
",",
"1",
")",
"[",
"0",
"]",
".",
"strip",
"(",
")",
"if",
"not",
"line",
":",
"return",
"False",
"if",
"l... | https://github.com/jupyterhub/repo2docker/blob/a37a205c0e8a59240933d20c1c4fb80767e71db2/repo2docker/utils.py#L460-L510 | |
LagoLunatic/wwrando | 33164143eb9f51c3015be3e31402a79dfcebacfd | tweaks.py | python | update_game_name_icon_and_banners | (self) | [] | def update_game_name_icon_and_banners(self):
new_game_name = "Wind Waker Randomized %s" % self.seed
banner_data = self.get_raw_file("files/opening.bnr")
write_magic_str(banner_data, 0x1860, new_game_name, 0x40)
new_game_id = "GZLE99"
boot_data = self.get_raw_file("sys/boot.bin")
write_magic_str(boot_data, 0, new_game_id, 6)
new_memory_card_game_name = "Wind Waker Randomizer"
self.dol.write_data(write_magic_str, 0x80339690, new_memory_card_game_name, 21)
new_image_file_path = os.path.join(ASSETS_PATH, "banner.png")
image_format = texture_utils.ImageFormat.RGB5A3
palette_format = texture_utils.PaletteFormat.RGB5A3
image_data, _, _, image_width, image_height = texture_utils.encode_image_from_path(new_image_file_path, image_format, palette_format)
assert image_width == 96
assert image_height == 32
assert data_len(image_data) == 0x1800
image_data.seek(0)
write_bytes(banner_data, 0x20, image_data.read())
cardicon_arc = self.get_arc("files/res/CardIcon/cardicon.arc")
memory_card_icon_file_path = os.path.join(ASSETS_PATH, "memory card icon.png")
memory_card_icon = cardicon_arc.get_file("ipl_icon1.bti")
memory_card_icon.replace_image_from_path(memory_card_icon_file_path)
memory_card_icon.save_changes()
memory_card_banner_file_path = os.path.join(ASSETS_PATH, "memory card banner.png")
memory_card_banner = cardicon_arc.get_file("ipl_banner.bti")
memory_card_banner.replace_image_from_path(memory_card_banner_file_path)
memory_card_banner.save_changes() | [
"def",
"update_game_name_icon_and_banners",
"(",
"self",
")",
":",
"new_game_name",
"=",
"\"Wind Waker Randomized %s\"",
"%",
"self",
".",
"seed",
"banner_data",
"=",
"self",
".",
"get_raw_file",
"(",
"\"files/opening.bnr\"",
")",
"write_magic_str",
"(",
"banner_data",
... | https://github.com/LagoLunatic/wwrando/blob/33164143eb9f51c3015be3e31402a79dfcebacfd/tweaks.py#L527-L559 | ||||
marcoeilers/nagini | a2a19df7d833e67841e03c9885869c3dddef3327 | src/nagini_translation/translators/contract.py | python | ContractTranslator.translate_lowval | (self, node: ast.Call, ctx: Context) | return self.translate_low(node, ctx) | Translates a call to the LowVal() contract function. | Translates a call to the LowVal() contract function. | [
"Translates",
"a",
"call",
"to",
"the",
"LowVal",
"()",
"contract",
"function",
"."
] | def translate_lowval(self, node: ast.Call, ctx: Context) -> StmtsAndExpr:
"""
Translates a call to the LowVal() contract function.
"""
return self.translate_low(node, ctx) | [
"def",
"translate_lowval",
"(",
"self",
",",
"node",
":",
"ast",
".",
"Call",
",",
"ctx",
":",
"Context",
")",
"->",
"StmtsAndExpr",
":",
"return",
"self",
".",
"translate_low",
"(",
"node",
",",
"ctx",
")"
] | https://github.com/marcoeilers/nagini/blob/a2a19df7d833e67841e03c9885869c3dddef3327/src/nagini_translation/translators/contract.py#L518-L522 | |
jliljebl/flowblade | 995313a509b80e99eb1ad550d945bdda5995093b | flowblade-trunk/Flowblade/projectmediaimport.py | python | write_files | (filename) | [] | def write_files(filename):
print("Starting media import...")
FLOG = open(userfolders.get_cache_dir() + "log_media_import", 'w')
p = subprocess.Popen([sys.executable, respaths.LAUNCH_DIR + "flowblademediaimport", filename], stdin=FLOG, stdout=FLOG, stderr=FLOG)
p.wait()
GLib.idle_add(assets_write_complete) | [
"def",
"write_files",
"(",
"filename",
")",
":",
"print",
"(",
"\"Starting media import...\"",
")",
"FLOG",
"=",
"open",
"(",
"userfolders",
".",
"get_cache_dir",
"(",
")",
"+",
"\"log_media_import\"",
",",
"'w'",
")",
"p",
"=",
"subprocess",
".",
"Popen",
"... | https://github.com/jliljebl/flowblade/blob/995313a509b80e99eb1ad550d945bdda5995093b/flowblade-trunk/Flowblade/projectmediaimport.py#L123-L129 | ||||
jeffgortmaker/pyblp | 33ad24d8a800b8178aafa47304a822077a607558 | pyblp/micro.py | python | MicroMoment.__init__ | (self, name: str, dataset: MicroDataset, value: float, compute_values: Callable) | Validate information to the greatest extent possible without calling the function. | Validate information to the greatest extent possible without calling the function. | [
"Validate",
"information",
"to",
"the",
"greatest",
"extent",
"possible",
"without",
"calling",
"the",
"function",
"."
] | def __init__(self, name: str, dataset: MicroDataset, value: float, compute_values: Callable) -> None:
"""Validate information to the greatest extent possible without calling the function."""
if not isinstance(name, str):
raise TypeError("name must be a string.")
if not isinstance(dataset, MicroDataset):
raise TypeError("dataset must be a MicroDataset instance.")
if not isinstance(value, (int, float)):
raise TypeError("value must be a float.")
if not callable(compute_values):
raise ValueError("compute_values must be callable.")
self.name = name
self.dataset = dataset
self.value = value
self.compute_values = functools.partial(compute_values) | [
"def",
"__init__",
"(",
"self",
",",
"name",
":",
"str",
",",
"dataset",
":",
"MicroDataset",
",",
"value",
":",
"float",
",",
"compute_values",
":",
"Callable",
")",
"->",
"None",
":",
"if",
"not",
"isinstance",
"(",
"name",
",",
"str",
")",
":",
"r... | https://github.com/jeffgortmaker/pyblp/blob/33ad24d8a800b8178aafa47304a822077a607558/pyblp/micro.py#L170-L184 | ||
Pyomo/pyomo | dbd4faee151084f343b893cc2b0c04cf2b76fd92 | pyomo/contrib/pynumero/sparse/mpi_block_matrix.py | python | MPIBlockMatrix.is_empty_block | (self, idx, jdx) | Indicates if a block is empty
Parameters
----------
idx: int
block-row index
jdx: int
block-column index
Returns
-------
boolean | Indicates if a block is empty | [
"Indicates",
"if",
"a",
"block",
"is",
"empty"
] | def is_empty_block(self, idx, jdx):
"""
Indicates if a block is empty
Parameters
----------
idx: int
block-row index
jdx: int
block-column index
Returns
-------
boolean
"""
raise NotImplementedError('Operation not supported by MPIBlockMatrix') | [
"def",
"is_empty_block",
"(",
"self",
",",
"idx",
",",
"jdx",
")",
":",
"raise",
"NotImplementedError",
"(",
"'Operation not supported by MPIBlockMatrix'",
")"
] | https://github.com/Pyomo/pyomo/blob/dbd4faee151084f343b893cc2b0c04cf2b76fd92/pyomo/contrib/pynumero/sparse/mpi_block_matrix.py#L342-L358 | ||
facebookresearch/ParlAI | e4d59c30eef44f1f67105961b82a83fd28d7d78b | parlai/tasks/google_sgd/agents.py | python | GoogleSGDParser.setup_episodes | (self, fold) | return result | Parses Google SGD episodes into TodStructuredEpisode. | Parses Google SGD episodes into TodStructuredEpisode. | [
"Parses",
"Google",
"SGD",
"episodes",
"into",
"TodStructuredEpisode",
"."
] | def setup_episodes(self, fold):
"""
Parses Google SGD episodes into TodStructuredEpisode.
"""
schema_lookup, dialogues = self._load_data(fold)
result = []
for dialogue in dialogues:
domains = {s.split("_")[0].strip() for s in dialogue["services"]}
turns = dialogue["turns"]
rounds = []
for turn_id in range(0, len(turns), 2):
user_turn = turns[turn_id]
sys_turn = turns[turn_id + 1]
api_call, api_results = self._get_api_call_and_results(sys_turn)
r = tod.TodStructuredRound(
user_utt=user_turn["utterance"],
api_call_machine=api_call,
api_resp_machine=api_results,
sys_utt=sys_turn["utterance"],
)
rounds.append(r)
# Now that we've got the rounds, make the episode
episode = tod.TodStructuredEpisode(
domain=SerializationHelpers.inner_list_join(domains),
api_schemas_machine=self._get_intent_groundinging(
schema_lookup, set(dialogue["services"])
),
goal_calls_machine=self._get_all_service_calls(turns),
rounds=rounds,
delex=self.opt.get("delex"),
extras={"dialogue_id": dialogue["dialogue_id"]},
)
result.append(episode)
# check if the number of episodes should be limited and truncate as required
return result | [
"def",
"setup_episodes",
"(",
"self",
",",
"fold",
")",
":",
"schema_lookup",
",",
"dialogues",
"=",
"self",
".",
"_load_data",
"(",
"fold",
")",
"result",
"=",
"[",
"]",
"for",
"dialogue",
"in",
"dialogues",
":",
"domains",
"=",
"{",
"s",
".",
"split"... | https://github.com/facebookresearch/ParlAI/blob/e4d59c30eef44f1f67105961b82a83fd28d7d78b/parlai/tasks/google_sgd/agents.py#L162-L196 | |
oulutan/ACAM_Demo | e9929264fa3e7a4dc05e87c479a86b22e39c35f4 | action_detection/action_detector.py | python | Action_Detector.crop_tubes_in_tf_with_memory | (self, frame_shape, memory_size) | return updated_frames, rois, batch_indices, cropped_frames | [] | def crop_tubes_in_tf_with_memory(self, frame_shape, memory_size):
T,H,W,C = frame_shape
no_updated_frames = T - memory_size
with self.act_graph.as_default():
updated_frames, combined_sequence = memory_placeholder(tf.float32, [1, T, H,W,C], memory_size)
rois = tf.placeholder(tf.float32, [None, T, 4]) # top, left, bottom, right
batch_indices = tf.placeholder(tf.int32, [None])
# use temporal rois since we track the actor over time
cropped_frames = temporal_roi_cropping(combined_sequence, rois, batch_indices, self.input_size, temp_rois=True)
return updated_frames, rois, batch_indices, cropped_frames | [
"def",
"crop_tubes_in_tf_with_memory",
"(",
"self",
",",
"frame_shape",
",",
"memory_size",
")",
":",
"T",
",",
"H",
",",
"W",
",",
"C",
"=",
"frame_shape",
"no_updated_frames",
"=",
"T",
"-",
"memory_size",
"with",
"self",
".",
"act_graph",
".",
"as_default... | https://github.com/oulutan/ACAM_Demo/blob/e9929264fa3e7a4dc05e87c479a86b22e39c35f4/action_detection/action_detector.py#L383-L394 | |||
fabioz/PyDev.Debugger | 0f8c02a010fe5690405da1dd30ed72326191ce63 | _pydevd_bundle/pydevd_vars.py | python | evaluate_expression | (py_db, frame, expression, is_exec) | There are some changes in this function depending on whether it's an exec or an eval.
When it's an exec (i.e.: is_exec==True):
This function returns None.
Any exception that happens during the evaluation is reraised.
If the expression could actually be evaluated, the variable is printed to the console if not None.
When it's an eval (i.e.: is_exec==False):
This function returns the result from the evaluation.
If some exception happens in this case, the exception is caught and a ExceptionOnEvaluate is returned.
Also, in this case we try to resolve name-mangling (i.e.: to be able to add a self.__my_var watch).
:param is_exec: determines if we should do an exec or an eval. | There are some changes in this function depending on whether it's an exec or an eval. | [
"There",
"are",
"some",
"changes",
"in",
"this",
"function",
"depending",
"on",
"whether",
"it",
"s",
"an",
"exec",
"or",
"an",
"eval",
"."
] | def evaluate_expression(py_db, frame, expression, is_exec):
'''
There are some changes in this function depending on whether it's an exec or an eval.
When it's an exec (i.e.: is_exec==True):
This function returns None.
Any exception that happens during the evaluation is reraised.
If the expression could actually be evaluated, the variable is printed to the console if not None.
When it's an eval (i.e.: is_exec==False):
This function returns the result from the evaluation.
If some exception happens in this case, the exception is caught and a ExceptionOnEvaluate is returned.
Also, in this case we try to resolve name-mangling (i.e.: to be able to add a self.__my_var watch).
:param is_exec: determines if we should do an exec or an eval.
'''
if frame is None:
return
# Note: not using frame.f_globals directly because we need variables to be mutated in that
# context to support generator expressions (i.e.: the case below doesn't work unless
# globals=locals) because a generator expression actually creates a new function context.
# i.e.:
# global_vars = {}
# local_vars = {'ar':["foo", "bar"], 'y':"bar"}
# print eval('all((x == y for x in ar))', global_vars, local_vars)
# See: https://mail.python.org/pipermail/python-list/2009-January/522213.html
updated_globals = {}
updated_globals.update(frame.f_globals)
updated_globals.update(frame.f_locals) # locals later because it has precedence over the actual globals
try:
if IS_PY2 and isinstance(expression, unicode):
expression = expression.replace(u'@LINE@', u'\n')
else:
expression = expression.replace('@LINE@', '\n')
if is_exec:
try:
# try to make it an eval (if it is an eval we can print it, otherwise we'll exec it and
# it will have whatever the user actually did)
compiled = compile_as_eval(expression)
except Exception:
Exec(_expression_to_evaluate(expression), updated_globals, frame.f_locals)
pydevd_save_locals.save_locals(frame)
else:
result = eval(compiled, updated_globals, frame.f_locals)
if result is not None: # Only print if it's not None (as python does)
if IS_PY2 and isinstance(result, unicode):
encoding = sys.stdout.encoding
if not encoding:
encoding = os.environ.get('PYTHONIOENCODING', 'utf-8')
result = result.encode(encoding, 'replace')
sys.stdout.write('%s\n' % (result,))
return
else:
ret = eval_in_context(expression, updated_globals, frame.f_locals)
try:
is_exception_returned = ret.__class__ == ExceptionOnEvaluate
except:
pass
else:
if not is_exception_returned:
# i.e.: by using a walrus assignment (:=), expressions can change the locals,
# so, make sure that we save the locals back to the frame.
pydevd_save_locals.save_locals(frame)
return ret
finally:
# Should not be kept alive if an exception happens and this frame is kept in the stack.
del updated_globals
del frame | [
"def",
"evaluate_expression",
"(",
"py_db",
",",
"frame",
",",
"expression",
",",
"is_exec",
")",
":",
"if",
"frame",
"is",
"None",
":",
"return",
"# Note: not using frame.f_globals directly because we need variables to be mutated in that",
"# context to support generator expre... | https://github.com/fabioz/PyDev.Debugger/blob/0f8c02a010fe5690405da1dd30ed72326191ce63/_pydevd_bundle/pydevd_vars.py#L378-L450 | ||
fkie/multimaster_fkie | 3d23df29d25d71a75c66bbd3cc6e9cbb255724d8 | fkie_master_discovery/src/fkie_master_discovery/master_info.py | python | MasterInfo.timestamp | (self) | return self.__timestamp | :return: The timestamp when this MasterInfo was first time filled with the
information. See :mod:`fkie_master_discovery.master_info.MasterInfo.check_ts()`
to get the time, when the information was compared with the data of ROS Master.
:rtype: float | :return: The timestamp when this MasterInfo was first time filled with the
information. See :mod:`fkie_master_discovery.master_info.MasterInfo.check_ts()`
to get the time, when the information was compared with the data of ROS Master. | [
":",
"return",
":",
"The",
"timestamp",
"when",
"this",
"MasterInfo",
"was",
"first",
"time",
"filled",
"with",
"the",
"information",
".",
"See",
":",
"mod",
":",
"fkie_master_discovery",
".",
"master_info",
".",
"MasterInfo",
".",
"check_ts",
"()",
"to",
"g... | def timestamp(self):
'''
:return: The timestamp when this MasterInfo was first time filled with the
information. See :mod:`fkie_master_discovery.master_info.MasterInfo.check_ts()`
to get the time, when the information was compared with the data of ROS Master.
:rtype: float
'''
return self.__timestamp | [
"def",
"timestamp",
"(",
"self",
")",
":",
"return",
"self",
".",
"__timestamp"
] | https://github.com/fkie/multimaster_fkie/blob/3d23df29d25d71a75c66bbd3cc6e9cbb255724d8/fkie_master_discovery/src/fkie_master_discovery/master_info.py#L738-L746 | |
calmevtime/DCTNet | bd7c669b478e47fde230119045133d10e135de97 | classification/datasets/cvtransforms.py | python | RandomGaussianNoise.__call__ | (self, img) | return img | Args:
img (np.ndarray): Image to be noised.
Returns:
np.ndarray: Randomly noised image. | Args:
img (np.ndarray): Image to be noised. | [
"Args",
":",
"img",
"(",
"np",
".",
"ndarray",
")",
":",
"Image",
"to",
"be",
"noised",
"."
] | def __call__(self, img):
"""
Args:
img (np.ndarray): Image to be noised.
Returns:
np.ndarray: Randomly noised image.
"""
if random.random() < self.p:
return F.gaussian_noise(img, mean=self.mean, std=self.std)
return img | [
"def",
"__call__",
"(",
"self",
",",
"img",
")",
":",
"if",
"random",
".",
"random",
"(",
")",
"<",
"self",
".",
"p",
":",
"return",
"F",
".",
"gaussian_noise",
"(",
"img",
",",
"mean",
"=",
"self",
".",
"mean",
",",
"std",
"=",
"self",
".",
"s... | https://github.com/calmevtime/DCTNet/blob/bd7c669b478e47fde230119045133d10e135de97/classification/datasets/cvtransforms.py#L1386-L1396 | |
hasegaw/IkaLog | bd476da541fcc296f792d4db76a6b9174c4777ad | ikalog/utils/ikamatcher2/arm_neon.py | python | NEON.encode | (self, img) | return dest | Encode the image to internal image format.
Bits per pixel: 1bit (uint8)
Alignment per lines: 0
Alignment of returned image: self._align bytes | Encode the image to internal image format. | [
"Encode",
"the",
"image",
"to",
"internal",
"image",
"format",
"."
] | def encode(self, img):
"""
Encode the image to internal image format.
Bits per pixel: 1bit (uint8)
Alignment per lines: 0
Alignment of returned image: self._align bytes
"""
align = 128 # encode func is read per 128bytes
assert img.shape[0] == self._h
assert img.shape[1] == self._w
img_8b_1d = np.reshape(img, (-1))
img_8b_1d_p = img_8b_1d
if len(img_8b_1d) & (align-1):
padding_len = align - (len(img_8b_1d) % align)
img_8b_1d_p = np.append(img_8b_1d, zeros512[0: padding_len])
assert len(img_8b_1d_p.shape) == 1
assert img_8b_1d_p.shape[0] >= (self._h * self._w / 8)
assert img_8b_1d_p.shape[0] % align == 0
dest_len = int(img_8b_1d_p.shape[0]/8)
dest = np.empty(dest_len , dtype=np.uint8)
ikamat2_neon.encode(dest, img_8b_1d_p, (self._h * self._w))
return dest | [
"def",
"encode",
"(",
"self",
",",
"img",
")",
":",
"align",
"=",
"128",
"# encode func is read per 128bytes",
"assert",
"img",
".",
"shape",
"[",
"0",
"]",
"==",
"self",
".",
"_h",
"assert",
"img",
".",
"shape",
"[",
"1",
"]",
"==",
"self",
".",
"_w... | https://github.com/hasegaw/IkaLog/blob/bd476da541fcc296f792d4db76a6b9174c4777ad/ikalog/utils/ikamatcher2/arm_neon.py#L33-L59 | |
kchua/handful-of-trials | 77fd8802cc30b7683f0227c90527b5414c0df34c | dmbrl/modeling/layers/FC.py | python | FC.get_output_dim | (self) | return self.output_dim | Returns the dimension of the output.
Returns: The dimension of the output. | Returns the dimension of the output. | [
"Returns",
"the",
"dimension",
"of",
"the",
"output",
"."
] | def get_output_dim(self):
"""Returns the dimension of the output.
Returns: The dimension of the output.
"""
return self.output_dim | [
"def",
"get_output_dim",
"(",
"self",
")",
":",
"return",
"self",
".",
"output_dim"
] | https://github.com/kchua/handful-of-trials/blob/77fd8802cc30b7683f0227c90527b5414c0df34c/dmbrl/modeling/layers/FC.py#L158-L163 | |
facebookresearch/ClassyVision | 309d4f12431c6b4d8540010a781dc2aa25fe88e7 | classy_vision/hooks/__init__.py | python | register_hook | (name, bypass_checks=False) | return register_hook_cls | Registers a :class:`ClassyHook` subclass.
This decorator allows Classy Vision to instantiate a subclass of
:class:`ClassyHook` from a configuration file, even if the class
itself is not part of the base Classy Vision framework. To use it,
apply this decorator to a ClassyHook subclass, like this:
.. code-block:: python
@register_hook('custom_hook')
class CustomHook(ClassyHook):
...
To instantiate a hook from a configuration file, see
:func:`build_hook`. | Registers a :class:`ClassyHook` subclass. | [
"Registers",
"a",
":",
"class",
":",
"ClassyHook",
"subclass",
"."
] | def register_hook(name, bypass_checks=False):
"""Registers a :class:`ClassyHook` subclass.
This decorator allows Classy Vision to instantiate a subclass of
:class:`ClassyHook` from a configuration file, even if the class
itself is not part of the base Classy Vision framework. To use it,
apply this decorator to a ClassyHook subclass, like this:
.. code-block:: python
@register_hook('custom_hook')
class CustomHook(ClassyHook):
...
To instantiate a hook from a configuration file, see
:func:`build_hook`.
"""
def register_hook_cls(cls):
if not bypass_checks:
if name in HOOK_REGISTRY:
msg = (
"Cannot register duplicate hook ({}). Already registered at \n{}\n"
)
raise ValueError(msg.format(name, HOOK_REGISTRY_TB[name]))
if not issubclass(cls, ClassyHook):
raise ValueError(
"Hook ({}: {}) must extend ClassyHook".format(name, cls.__name__)
)
if cls.__name__ in HOOK_CLASS_NAMES:
msg = (
"Cannot register hook with duplicate class name({})."
+ "Previously registered at \n{}\n"
)
raise ValueError(
msg.format(cls.__name__, HOOK_CLASS_NAMES_TB[cls.__name__])
)
tb = "".join(traceback.format_stack())
HOOK_REGISTRY[name] = cls
HOOK_CLASS_NAMES.add(cls.__name__)
HOOK_REGISTRY_TB[name] = tb
HOOK_CLASS_NAMES_TB[cls.__name__] = tb
return cls
return register_hook_cls | [
"def",
"register_hook",
"(",
"name",
",",
"bypass_checks",
"=",
"False",
")",
":",
"def",
"register_hook_cls",
"(",
"cls",
")",
":",
"if",
"not",
"bypass_checks",
":",
"if",
"name",
"in",
"HOOK_REGISTRY",
":",
"msg",
"=",
"(",
"\"Cannot register duplicate hook... | https://github.com/facebookresearch/ClassyVision/blob/309d4f12431c6b4d8540010a781dc2aa25fe88e7/classy_vision/hooks/__init__.py#L27-L71 | |
lazylibrarian/LazyLibrarian | ae3c14e9db9328ce81765e094ab2a14ed7155624 | cherrypy/_cpconfig.py | python | _tree_namespace_handler | (k, v) | Namespace handler for the 'tree' config namespace. | Namespace handler for the 'tree' config namespace. | [
"Namespace",
"handler",
"for",
"the",
"tree",
"config",
"namespace",
"."
] | def _tree_namespace_handler(k, v):
"""Namespace handler for the 'tree' config namespace."""
if isinstance(v, dict):
for script_name, app in v.items():
cherrypy.tree.graft(app, script_name)
cherrypy.engine.log("Mounted: %s on %s" %
(app, script_name or "/"))
else:
cherrypy.tree.graft(v, v.script_name)
cherrypy.engine.log("Mounted: %s on %s" % (v, v.script_name or "/")) | [
"def",
"_tree_namespace_handler",
"(",
"k",
",",
"v",
")",
":",
"if",
"isinstance",
"(",
"v",
",",
"dict",
")",
":",
"for",
"script_name",
",",
"app",
"in",
"v",
".",
"items",
"(",
")",
":",
"cherrypy",
".",
"tree",
".",
"graft",
"(",
"app",
",",
... | https://github.com/lazylibrarian/LazyLibrarian/blob/ae3c14e9db9328ce81765e094ab2a14ed7155624/cherrypy/_cpconfig.py#L307-L316 | ||
tomerfiliba/plumbum | 20cdda5e8bbd9f83d64b154f6b4fcd28216c63e1 | plumbum/path/base.py | python | Path.glob | (self, pattern) | Returns a (possibly empty) list of paths that matched the glob-pattern under this path | Returns a (possibly empty) list of paths that matched the glob-pattern under this path | [
"Returns",
"a",
"(",
"possibly",
"empty",
")",
"list",
"of",
"paths",
"that",
"matched",
"the",
"glob",
"-",
"pattern",
"under",
"this",
"path"
] | def glob(self, pattern):
"""Returns a (possibly empty) list of paths that matched the glob-pattern under this path""" | [
"def",
"glob",
"(",
"self",
",",
"pattern",
")",
":"
] | https://github.com/tomerfiliba/plumbum/blob/20cdda5e8bbd9f83d64b154f6b4fcd28216c63e1/plumbum/path/base.py#L249-L250 | ||
kuri65536/python-for-android | 26402a08fc46b09ef94e8d7a6bbc3a54ff9d0891 | python-build/python-libs/gdata/src/gdata/books/service.py | python | BookService.search_library | (self, q, id='me', **kwargs) | return self.search(q, feed=feed, **kwargs) | Like search, but in a library feed. Default is the authenticated
user's feed. Change by setting id. | Like search, but in a library feed. Default is the authenticated
user's feed. Change by setting id. | [
"Like",
"search",
"but",
"in",
"a",
"library",
"feed",
".",
"Default",
"is",
"the",
"authenticated",
"user",
"s",
"feed",
".",
"Change",
"by",
"setting",
"id",
"."
] | def search_library(self, q, id='me', **kwargs):
"""Like search, but in a library feed. Default is the authenticated
user's feed. Change by setting id."""
if 'feed' in kwargs:
raise ValueError("kwarg 'feed' conflicts with library_id")
feed = LIBRARY_FEED % id
return self.search(q, feed=feed, **kwargs) | [
"def",
"search_library",
"(",
"self",
",",
"q",
",",
"id",
"=",
"'me'",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'feed'",
"in",
"kwargs",
":",
"raise",
"ValueError",
"(",
"\"kwarg 'feed' conflicts with library_id\"",
")",
"feed",
"=",
"LIBRARY_FEED",
"%",
... | https://github.com/kuri65536/python-for-android/blob/26402a08fc46b09ef94e8d7a6bbc3a54ff9d0891/python-build/python-libs/gdata/src/gdata/books/service.py#L155-L162 | |
determined-ai/determined | f637264493acc14f12e66550cb51c520b5d27f6c | harness/determined/keras/_tf_keras_trial.py | python | load_optimizer_weights | (
model: Model, h5group: Any, optimizer: tf.keras.optimizers.Optimizer
) | Load the optimizer states from a tf.keras model saved with
tf.keras.models.save_model(). Ignores and prints a warning message when
encountering a graph network. This implementation is lifted from
tf.keras.models.load_model(). | Load the optimizer states from a tf.keras model saved with
tf.keras.models.save_model(). Ignores and prints a warning message when
encountering a graph network. This implementation is lifted from
tf.keras.models.load_model(). | [
"Load",
"the",
"optimizer",
"states",
"from",
"a",
"tf",
".",
"keras",
"model",
"saved",
"with",
"tf",
".",
"keras",
".",
"models",
".",
"save_model",
"()",
".",
"Ignores",
"and",
"prints",
"a",
"warning",
"message",
"when",
"encountering",
"a",
"graph",
... | def load_optimizer_weights(
model: Model, h5group: Any, optimizer: tf.keras.optimizers.Optimizer
) -> None:
"""
Load the optimizer states from a tf.keras model saved with
tf.keras.models.save_model(). Ignores and prints a warning message when
encountering a graph network. This implementation is lifted from
tf.keras.models.load_model().
"""
tf2_2_or_newer = version.parse(tf.__version__) >= version.parse("2.2.0")
if model._is_graph_network or tf2_2_or_newer: # pylint: disable=protected-access
if tf2_2_or_newer:
try:
optimizer._create_all_weights(model.trainable_variables)
except (NotImplementedError, AttributeError):
logging.warning(
"Error when creating the weights of optimizer, making it "
"impossible to restore the saved optimizer state. As a result, "
"your model is starting with a freshly initialized optimizer."
)
else:
# Build train function (to get weight updates). Models that aren't
# graph networks must wait until they are called with data to
# _make_train_function() and so can't load optimizer weights.
model._make_train_function()
optimizer_weight_values = load_optimizer_weights_from_hdf5_group(h5group)
try:
optimizer.set_weights(optimizer_weight_values)
except ValueError:
logging.warning(
"Error in loading the saved optimizer "
"state. As a result, your model is "
"starting with a freshly initialized "
"optimizer."
)
else:
logging.warning(
"Sequential models without an `input_shape` "
"passed to the first layer cannot reload their "
"optimizer state. As a result, your model is "
"starting with a freshly initialized optimizer."
) | [
"def",
"load_optimizer_weights",
"(",
"model",
":",
"Model",
",",
"h5group",
":",
"Any",
",",
"optimizer",
":",
"tf",
".",
"keras",
".",
"optimizers",
".",
"Optimizer",
")",
"->",
"None",
":",
"tf2_2_or_newer",
"=",
"version",
".",
"parse",
"(",
"tf",
".... | https://github.com/determined-ai/determined/blob/f637264493acc14f12e66550cb51c520b5d27f6c/harness/determined/keras/_tf_keras_trial.py#L56-L98 | ||
selfboot/LeetCode | 473c0c5451651140d75cbd143309c51cd8fe1cf1 | Stack/232_ImplementQueueUsingStacks.py | python | Queue.__init__ | (self) | [] | def __init__(self):
self.in_stack, self.out_stack = [], [] | [
"def",
"__init__",
"(",
"self",
")",
":",
"self",
".",
"in_stack",
",",
"self",
".",
"out_stack",
"=",
"[",
"]",
",",
"[",
"]"
] | https://github.com/selfboot/LeetCode/blob/473c0c5451651140d75cbd143309c51cd8fe1cf1/Stack/232_ImplementQueueUsingStacks.py#L12-L13 | ||||
jliljebl/flowblade | 995313a509b80e99eb1ad550d945bdda5995093b | flowblade-trunk/Flowblade/res/mediaplugins/animations_1/plugin_script.py | python | render_frame | (frame, fctx, w, h) | [] | def render_frame(frame, fctx, w, h):
cr = fctx.get_frame_cr()
bg_color = cairo.SolidPattern(*fctx.get_data_obj("hue_tuple"))
ball_colors = fctx.get_data_obj("ball_colors")
ball_data = fctx.get_data_obj("ball_data")
cr.set_source(bg_color)
cr.rectangle(0, 0, w, h)
cr.fill()
number_of_balls = fctx.get_editor_value("Number of Items")
size_max = fctx.get_data_obj("size_max")
path_start_x = - size_max
path_end_x = w + size_max
path_len = path_end_x - path_start_x
SPEED_NORM_PER_FRAME = 15.0 / float(w)
for i in range(0, number_of_balls):
path_pos, y, ball_speed, ball_size, color_index = ball_data[i]
xc = ball_size / 2.0
yc = ball_size / 2.0
xpos_norm = path_pos + (float(frame) * ball_speed * SPEED_NORM_PER_FRAME)
while xpos_norm > 1.0:
xpos_norm = xpos_norm - 1.0
x = path_start_x + path_len * xpos_norm
cr.save()
cr.translate(x, y)
cr.arc(xc, yc, ball_size / 4.0, 0.0, 2.0 * math.pi)
cr.set_source(ball_colors[color_index])
cr.fill()
cr.restore() | [
"def",
"render_frame",
"(",
"frame",
",",
"fctx",
",",
"w",
",",
"h",
")",
":",
"cr",
"=",
"fctx",
".",
"get_frame_cr",
"(",
")",
"bg_color",
"=",
"cairo",
".",
"SolidPattern",
"(",
"*",
"fctx",
".",
"get_data_obj",
"(",
"\"hue_tuple\"",
")",
")",
"b... | https://github.com/jliljebl/flowblade/blob/995313a509b80e99eb1ad550d945bdda5995093b/flowblade-trunk/Flowblade/res/mediaplugins/animations_1/plugin_script.py#L68-L98 | ||||
HonglinChu/SiamTrackers | 8471660b14f970578a43f077b28207d44a27e867 | SiamFCpp/SiamFCpp-video_analyst/siamfcpp/model/common_opr/common_block.py | python | conv_bn_relu.__init__ | (self,
in_channel,
out_channel,
stride=1,
kszie=3,
pad=0,
has_bn=True,
has_relu=True,
bias=True,
groups=1) | r"""
Basic block with one conv, one bn, one relu in series.
Arguments
---------
in_channel: int
number of input channels
out_channel: int
number of output channels
stride: int
stride number
kszie: int
kernel size
pad: int
padding on each edge
has_bn: bool
use bn or not
has_relu: bool
use relu or not
bias: bool
conv has bias or not
groups: int or str
number of groups. To be forwarded to torch.nn.Conv2d | r"""
Basic block with one conv, one bn, one relu in series. | [
"r",
"Basic",
"block",
"with",
"one",
"conv",
"one",
"bn",
"one",
"relu",
"in",
"series",
"."
] | def __init__(self,
in_channel,
out_channel,
stride=1,
kszie=3,
pad=0,
has_bn=True,
has_relu=True,
bias=True,
groups=1):
r"""
Basic block with one conv, one bn, one relu in series.
Arguments
---------
in_channel: int
number of input channels
out_channel: int
number of output channels
stride: int
stride number
kszie: int
kernel size
pad: int
padding on each edge
has_bn: bool
use bn or not
has_relu: bool
use relu or not
bias: bool
conv has bias or not
groups: int or str
number of groups. To be forwarded to torch.nn.Conv2d
"""
super(conv_bn_relu, self).__init__()
self.conv = nn.Conv2d(in_channel,
out_channel,
kernel_size=kszie,
stride=stride,
padding=pad,
bias=bias,
groups=groups)
if has_bn:
self.bn = nn.BatchNorm2d(out_channel)
else:
self.bn = None
if has_relu:
self.relu = nn.ReLU()
else:
self.relu = None | [
"def",
"__init__",
"(",
"self",
",",
"in_channel",
",",
"out_channel",
",",
"stride",
"=",
"1",
",",
"kszie",
"=",
"3",
",",
"pad",
"=",
"0",
",",
"has_bn",
"=",
"True",
",",
"has_relu",
"=",
"True",
",",
"bias",
"=",
"True",
",",
"groups",
"=",
... | https://github.com/HonglinChu/SiamTrackers/blob/8471660b14f970578a43f077b28207d44a27e867/SiamFCpp/SiamFCpp-video_analyst/siamfcpp/model/common_opr/common_block.py#L9-L60 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.