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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
carpedm20/NAF-tensorflow | 5754bd40fe135f79272b333ba2b911b02ca293f7 | src/network.py | python | Network.hard_copy_from | (self, network) | [] | def hard_copy_from(self, network):
logger.info("Creating ops for hard target update...")
assert len(network.variables) == len(self.variables), \
"target and prediction network should have same # of variables"
for from_, to_ in zip(network.variables, self.variables):
self.sess.run(to_.assign(from_)) | [
"def",
"hard_copy_from",
"(",
"self",
",",
"network",
")",
":",
"logger",
".",
"info",
"(",
"\"Creating ops for hard target update...\"",
")",
"assert",
"len",
"(",
"network",
".",
"variables",
")",
"==",
"len",
"(",
"self",
".",
"variables",
")",
",",
"\"ta... | https://github.com/carpedm20/NAF-tensorflow/blob/5754bd40fe135f79272b333ba2b911b02ca293f7/src/network.py#L123-L129 | ||||
ChineseGLUE/ChineseGLUE | 1591b85cf5427c2ff60f718d359ecb71d2b44879 | baselines/models_pytorch/mrc_pytorch/pytorch_modeling.py | python | BertPreTrainingHeads.forward | (self, sequence_output, pooled_output) | return prediction_scores, seq_relationship_score | [] | def forward(self, sequence_output, pooled_output):
prediction_scores = self.predictions(sequence_output)
seq_relationship_score = self.seq_relationship(pooled_output)
return prediction_scores, seq_relationship_score | [
"def",
"forward",
"(",
"self",
",",
"sequence_output",
",",
"pooled_output",
")",
":",
"prediction_scores",
"=",
"self",
".",
"predictions",
"(",
"sequence_output",
")",
"seq_relationship_score",
"=",
"self",
".",
"seq_relationship",
"(",
"pooled_output",
")",
"re... | https://github.com/ChineseGLUE/ChineseGLUE/blob/1591b85cf5427c2ff60f718d359ecb71d2b44879/baselines/models_pytorch/mrc_pytorch/pytorch_modeling.py#L593-L596 | |||
pypa/setuptools | 9f37366aab9cd8f6baa23e6a77cfdb8daf97757e | setuptools/_vendor/pyparsing.py | python | NoMatch.__init__ | ( self ) | [] | def __init__( self ):
super(NoMatch,self).__init__()
self.name = "NoMatch"
self.mayReturnEmpty = True
self.mayIndexError = False
self.errmsg = "Unmatchable token" | [
"def",
"__init__",
"(",
"self",
")",
":",
"super",
"(",
"NoMatch",
",",
"self",
")",
".",
"__init__",
"(",
")",
"self",
".",
"name",
"=",
"\"NoMatch\"",
"self",
".",
"mayReturnEmpty",
"=",
"True",
"self",
".",
"mayIndexError",
"=",
"False",
"self",
"."... | https://github.com/pypa/setuptools/blob/9f37366aab9cd8f6baa23e6a77cfdb8daf97757e/setuptools/_vendor/pyparsing.py#L2387-L2392 | ||||
lmjohns3/theanets | 79db9f878ef2071f2f576a1cf5d43a752a55894a | theanets/layers/convolution.py | python | Conv2.setup | (self) | [] | def setup(self):
self.add_conv_weights('w')
self.add_bias('b', self.output_size) | [
"def",
"setup",
"(",
"self",
")",
":",
"self",
".",
"add_conv_weights",
"(",
"'w'",
")",
"self",
".",
"add_bias",
"(",
"'b'",
",",
"self",
".",
"output_size",
")"
] | https://github.com/lmjohns3/theanets/blob/79db9f878ef2071f2f576a1cf5d43a752a55894a/theanets/layers/convolution.py#L174-L176 | ||||
fastnlp/fastNLP | fb645d370f4cc1b00c7dbb16c1ff4542327c46e5 | fastNLP/models/star_transformer.py | python | STSeqLabel.forward | (self, words, seq_len) | return {Const.OUTPUT: output} | r"""
:param words: [batch, seq_len] 输入序列
:param seq_len: [batch,] 输入序列的长度
:return output: [batch, num_cls, seq_len] 输出序列中每个元素的分类的概率 | r""" | [
"r"
] | def forward(self, words, seq_len):
r"""
:param words: [batch, seq_len] 输入序列
:param seq_len: [batch,] 输入序列的长度
:return output: [batch, num_cls, seq_len] 输出序列中每个元素的分类的概率
"""
mask = seq_len_to_mask(seq_len)
nodes, _ = self.enc(words, mask)
output = self.cls(nodes)
output = output.transpose(1, 2) # make hidden to be dim 1
return {Const.OUTPUT: output} | [
"def",
"forward",
"(",
"self",
",",
"words",
",",
"seq_len",
")",
":",
"mask",
"=",
"seq_len_to_mask",
"(",
"seq_len",
")",
"nodes",
",",
"_",
"=",
"self",
".",
"enc",
"(",
"words",
",",
"mask",
")",
"output",
"=",
"self",
".",
"cls",
"(",
"nodes",... | https://github.com/fastnlp/fastNLP/blob/fb645d370f4cc1b00c7dbb16c1ff4542327c46e5/fastNLP/models/star_transformer.py#L145-L156 | |
okpy/ok | 50a00190f05363d096478dd8e53aa1a36dd40c4a | server/controllers/admin.py | python | client_version | (name) | return render_template('staff/client_version.html',
courses=courses, current_course=current_course,
version=version, form=form) | [] | def client_version(name):
courses, current_course = get_courses()
version = Version.query.filter_by(name=name).one_or_none()
if not version:
version = Version(name=name)
form = forms.VersionForm(obj=version)
if form.validate_on_submit():
form.populate_obj(version)
version.save()
flash(name + " version updated successfully.", "success")
return redirect(url_for(".client_version", name=name))
return render_template('staff/client_version.html',
courses=courses, current_course=current_course,
version=version, form=form) | [
"def",
"client_version",
"(",
"name",
")",
":",
"courses",
",",
"current_course",
"=",
"get_courses",
"(",
")",
"version",
"=",
"Version",
".",
"query",
".",
"filter_by",
"(",
"name",
"=",
"name",
")",
".",
"one_or_none",
"(",
")",
"if",
"not",
"version"... | https://github.com/okpy/ok/blob/50a00190f05363d096478dd8e53aa1a36dd40c4a/server/controllers/admin.py#L338-L353 | |||
clinton-hall/nzbToMedia | 27669389216902d1085660167e7bda0bd8527ecf | libs/common/requests/adapters.py | python | HTTPAdapter.add_headers | (self, request, **kwargs) | Add any headers needed by the connection. As of v2.0 this does
nothing by default, but is left for overriding by users that subclass
the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
This should not be called from user code, and is only exposed for use
when subclassing the
:class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
:param request: The :class:`PreparedRequest <PreparedRequest>` to add headers to.
:param kwargs: The keyword arguments from the call to send(). | Add any headers needed by the connection. As of v2.0 this does
nothing by default, but is left for overriding by users that subclass
the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`. | [
"Add",
"any",
"headers",
"needed",
"by",
"the",
"connection",
".",
"As",
"of",
"v2",
".",
"0",
"this",
"does",
"nothing",
"by",
"default",
"but",
"is",
"left",
"for",
"overriding",
"by",
"users",
"that",
"subclass",
"the",
":",
"class",
":",
"HTTPAdapter... | def add_headers(self, request, **kwargs):
"""Add any headers needed by the connection. As of v2.0 this does
nothing by default, but is left for overriding by users that subclass
the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
This should not be called from user code, and is only exposed for use
when subclassing the
:class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
:param request: The :class:`PreparedRequest <PreparedRequest>` to add headers to.
:param kwargs: The keyword arguments from the call to send().
"""
pass | [
"def",
"add_headers",
"(",
"self",
",",
"request",
",",
"*",
"*",
"kwargs",
")",
":",
"pass"
] | https://github.com/clinton-hall/nzbToMedia/blob/27669389216902d1085660167e7bda0bd8527ecf/libs/common/requests/adapters.py#L358-L370 | ||
fhamborg/news-please | 3c2562470601f060828e9d0ad05ebdbb5907641f | newsplease/crawler/commoncrawl_extractor.py | python | CommonCrawlExtractor.__get_remote_index | (self) | return lines | Gets the index of news crawl files from commoncrawl.org and returns an array of names
:return: | Gets the index of news crawl files from commoncrawl.org and returns an array of names
:return: | [
"Gets",
"the",
"index",
"of",
"news",
"crawl",
"files",
"from",
"commoncrawl",
".",
"org",
"and",
"returns",
"an",
"array",
"of",
"names",
":",
"return",
":"
] | def __get_remote_index(self):
"""
Gets the index of news crawl files from commoncrawl.org and returns an array of names
:return:
"""
temp_filename = "tmpaws.txt"
if os.name == 'nt':
awk_parameter = '"{ print $4 }"'
else:
awk_parameter = "'{ print $4 }'"
# get the remote info
cmd = "aws s3 ls --recursive s3://commoncrawl/crawl-data/CC-NEWS/ --no-sign-request > %s && " \
"awk %s %s " % (temp_filename, awk_parameter, temp_filename)
self.__logger.info('executing: %s', cmd)
exitcode, stdout_data = subprocess.getstatusoutput(cmd)
if exitcode > 0:
raise Exception(stdout_data)
print(stdout_data)
try:
os.remove(temp_filename)
except OSError:
pass
lines = stdout_data.splitlines()
return lines | [
"def",
"__get_remote_index",
"(",
"self",
")",
":",
"temp_filename",
"=",
"\"tmpaws.txt\"",
"if",
"os",
".",
"name",
"==",
"'nt'",
":",
"awk_parameter",
"=",
"'\"{ print $4 }\"'",
"else",
":",
"awk_parameter",
"=",
"\"'{ print $4 }'\"",
"# get the remote info",
"cmd... | https://github.com/fhamborg/news-please/blob/3c2562470601f060828e9d0ad05ebdbb5907641f/newsplease/crawler/commoncrawl_extractor.py#L157-L187 | |
theislab/anndata | 664e32b0aa6625fe593370d37174384c05abfd4e | anndata/_core/raw.py | python | Raw.to_adata | (self) | return anndata.AnnData(
X=self.X.copy(),
var=self.var.copy(),
varm=None if self._varm is None else self._varm.copy(),
obs=self._adata.obs.copy(),
obsm=self._adata.obsm.copy(),
uns=self._adata.uns.copy(),
) | Create full AnnData object. | Create full AnnData object. | [
"Create",
"full",
"AnnData",
"object",
"."
] | def to_adata(self):
"""Create full AnnData object."""
return anndata.AnnData(
X=self.X.copy(),
var=self.var.copy(),
varm=None if self._varm is None else self._varm.copy(),
obs=self._adata.obs.copy(),
obsm=self._adata.obsm.copy(),
uns=self._adata.uns.copy(),
) | [
"def",
"to_adata",
"(",
"self",
")",
":",
"return",
"anndata",
".",
"AnnData",
"(",
"X",
"=",
"self",
".",
"X",
".",
"copy",
"(",
")",
",",
"var",
"=",
"self",
".",
"var",
".",
"copy",
"(",
")",
",",
"varm",
"=",
"None",
"if",
"self",
".",
"_... | https://github.com/theislab/anndata/blob/664e32b0aa6625fe593370d37174384c05abfd4e/anndata/_core/raw.py#L137-L146 | |
sagemath/sage | f9b2db94f675ff16963ccdefba4f1a3393b3fe0d | src/sage/combinat/species/product_species.py | python | ProductSpecies.weight_ring | (self) | return self._common_parent([self.left_factor().weight_ring(),
self.right_factor().weight_ring(),
self._weight.parent()]) | Returns the weight ring for this species. This is determined by
asking Sage's coercion model what the result is when you multiply
(and add) elements of the weight rings for each of the operands.
EXAMPLES::
sage: S = species.SetSpecies()
sage: C = S*S
sage: C.weight_ring()
Rational Field
::
sage: S = species.SetSpecies(weight=QQ['t'].gen())
sage: C = S*S
sage: C.weight_ring()
Univariate Polynomial Ring in t over Rational Field
::
sage: S = species.SetSpecies()
sage: C = (S*S).weighted(QQ['t'].gen())
sage: C.weight_ring()
Univariate Polynomial Ring in t over Rational Field | Returns the weight ring for this species. This is determined by
asking Sage's coercion model what the result is when you multiply
(and add) elements of the weight rings for each of the operands. | [
"Returns",
"the",
"weight",
"ring",
"for",
"this",
"species",
".",
"This",
"is",
"determined",
"by",
"asking",
"Sage",
"s",
"coercion",
"model",
"what",
"the",
"result",
"is",
"when",
"you",
"multiply",
"(",
"and",
"add",
")",
"elements",
"of",
"the",
"w... | def weight_ring(self):
"""
Returns the weight ring for this species. This is determined by
asking Sage's coercion model what the result is when you multiply
(and add) elements of the weight rings for each of the operands.
EXAMPLES::
sage: S = species.SetSpecies()
sage: C = S*S
sage: C.weight_ring()
Rational Field
::
sage: S = species.SetSpecies(weight=QQ['t'].gen())
sage: C = S*S
sage: C.weight_ring()
Univariate Polynomial Ring in t over Rational Field
::
sage: S = species.SetSpecies()
sage: C = (S*S).weighted(QQ['t'].gen())
sage: C.weight_ring()
Univariate Polynomial Ring in t over Rational Field
"""
return self._common_parent([self.left_factor().weight_ring(),
self.right_factor().weight_ring(),
self._weight.parent()]) | [
"def",
"weight_ring",
"(",
"self",
")",
":",
"return",
"self",
".",
"_common_parent",
"(",
"[",
"self",
".",
"left_factor",
"(",
")",
".",
"weight_ring",
"(",
")",
",",
"self",
".",
"right_factor",
"(",
")",
".",
"weight_ring",
"(",
")",
",",
"self",
... | https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/combinat/species/product_species.py#L370-L399 | |
dimagi/commcare-hq | d67ff1d3b4c51fa050c19e60c3253a79d3452a39 | corehq/apps/reports/filters/fixtures.py | python | AsyncLocationFilter.location_hierarchy_config | (self) | return location_hierarchy_config(self.domain) | [] | def location_hierarchy_config(self):
return location_hierarchy_config(self.domain) | [
"def",
"location_hierarchy_config",
"(",
"self",
")",
":",
"return",
"location_hierarchy_config",
"(",
"self",
".",
"domain",
")"
] | https://github.com/dimagi/commcare-hq/blob/d67ff1d3b4c51fa050c19e60c3253a79d3452a39/corehq/apps/reports/filters/fixtures.py#L29-L30 | |||
huggingface/datasets | 249b4a38390bf1543f5b6e2f3dc208b5689c1c13 | datasets/ttc4900/ttc4900.py | python | TTC4900._generate_examples | (self, filepath) | Generate TTC4900 examples. | Generate TTC4900 examples. | [
"Generate",
"TTC4900",
"examples",
"."
] | def _generate_examples(self, filepath):
"""Generate TTC4900 examples."""
logger.info("⏳ Generating examples from = %s", filepath)
with open(filepath, encoding="utf-8") as f:
rdr = csv.reader(f, delimiter=",")
next(rdr)
rownum = 0
for row in rdr:
rownum += 1
yield rownum, {
"category": row[0],
"text": row[1],
} | [
"def",
"_generate_examples",
"(",
"self",
",",
"filepath",
")",
":",
"logger",
".",
"info",
"(",
"\"⏳ Generating examples from = %s\", ",
"f",
"lepath)",
"",
"with",
"open",
"(",
"filepath",
",",
"encoding",
"=",
"\"utf-8\"",
")",
"as",
"f",
":",
"rdr",
"=",... | https://github.com/huggingface/datasets/blob/249b4a38390bf1543f5b6e2f3dc208b5689c1c13/datasets/ttc4900/ttc4900.py#L118-L130 | ||
annoviko/pyclustering | bf4f51a472622292627ec8c294eb205585e50f52 | pyclustering/nnet/syncpr.py | python | syncpr.memory_order | (self, pattern) | !
@brief Calculates function of the memorized pattern.
@details Throws exception if length of pattern is not equal to size of the network or if it consists feature with value that are not equal to [-1; 1].
@param[in] pattern (list): Pattern for recognition represented by list of features that are equal to [-1; 1].
@return (double) Order of memory for the specified pattern. | ! | [
"!"
] | def memory_order(self, pattern):
"""!
@brief Calculates function of the memorized pattern.
@details Throws exception if length of pattern is not equal to size of the network or if it consists feature with value that are not equal to [-1; 1].
@param[in] pattern (list): Pattern for recognition represented by list of features that are equal to [-1; 1].
@return (double) Order of memory for the specified pattern.
"""
self.__validate_pattern(pattern)
if self._ccore_network_pointer is not None:
return wrapper.syncpr_memory_order(self._ccore_network_pointer, pattern)
else:
return self.__calculate_memory_order(pattern) | [
"def",
"memory_order",
"(",
"self",
",",
"pattern",
")",
":",
"self",
".",
"__validate_pattern",
"(",
"pattern",
")",
"if",
"self",
".",
"_ccore_network_pointer",
"is",
"not",
"None",
":",
"return",
"wrapper",
".",
"syncpr_memory_order",
"(",
"self",
".",
"_... | https://github.com/annoviko/pyclustering/blob/bf4f51a472622292627ec8c294eb205585e50f52/pyclustering/nnet/syncpr.py#L429-L446 | ||
getsentry/sentry | 83b1f25aac3e08075e0e2495bc29efaf35aca18a | src/sentry/integrations/vercel/generic_webhook.py | python | get_commit_sha | (meta: Mapping[str, str]) | return commit_sha | Find the commit SHA so we can use it as as the release. | Find the commit SHA so we can use it as as the release. | [
"Find",
"the",
"commit",
"SHA",
"so",
"we",
"can",
"use",
"it",
"as",
"as",
"the",
"release",
"."
] | def get_commit_sha(meta: Mapping[str, str]) -> str:
"""Find the commit SHA so we can use it as as the release."""
commit_sha = (
meta.get("githubCommitSha") or meta.get("gitlabCommitSha") or meta.get("bitbucketCommitSha")
)
if not commit_sha:
# This can happen with manual builds.
raise NoCommitFoundError("No commit found")
return commit_sha | [
"def",
"get_commit_sha",
"(",
"meta",
":",
"Mapping",
"[",
"str",
",",
"str",
"]",
")",
"->",
"str",
":",
"commit_sha",
"=",
"(",
"meta",
".",
"get",
"(",
"\"githubCommitSha\"",
")",
"or",
"meta",
".",
"get",
"(",
"\"gitlabCommitSha\"",
")",
"or",
"met... | https://github.com/getsentry/sentry/blob/83b1f25aac3e08075e0e2495bc29efaf35aca18a/src/sentry/integrations/vercel/generic_webhook.py#L60-L70 | |
nutonomy/nuscenes-devkit | 05d05b3c994fb3c17b6643016d9f622a001c7275 | python-sdk/nuimages/nuimages.py | python | NuImages.shortcut | (self, src_table: str, tgt_table: str, src_token: str) | Convenience function to navigate between different tables that have one-to-one relations.
E.g. we can use this function to conveniently retrieve the sensor for a sample_data.
:param src_table: The name of the source table.
:param tgt_table: The name of the target table.
:param src_token: The source token.
:return: The entry of the destination table corresponding to the source token. | Convenience function to navigate between different tables that have one-to-one relations.
E.g. we can use this function to conveniently retrieve the sensor for a sample_data.
:param src_table: The name of the source table.
:param tgt_table: The name of the target table.
:param src_token: The source token.
:return: The entry of the destination table corresponding to the source token. | [
"Convenience",
"function",
"to",
"navigate",
"between",
"different",
"tables",
"that",
"have",
"one",
"-",
"to",
"-",
"one",
"relations",
".",
"E",
".",
"g",
".",
"we",
"can",
"use",
"this",
"function",
"to",
"conveniently",
"retrieve",
"the",
"sensor",
"f... | def shortcut(self, src_table: str, tgt_table: str, src_token: str) -> Dict[str, Any]:
"""
Convenience function to navigate between different tables that have one-to-one relations.
E.g. we can use this function to conveniently retrieve the sensor for a sample_data.
:param src_table: The name of the source table.
:param tgt_table: The name of the target table.
:param src_token: The source token.
:return: The entry of the destination table corresponding to the source token.
"""
if src_table == 'sample_data' and tgt_table == 'sensor':
sample_data = self.get('sample_data', src_token)
calibrated_sensor = self.get('calibrated_sensor', sample_data['calibrated_sensor_token'])
sensor = self.get('sensor', calibrated_sensor['sensor_token'])
return sensor
elif (src_table == 'object_ann' or src_table == 'surface_ann') and tgt_table == 'sample':
src = self.get(src_table, src_token)
sample_data = self.get('sample_data', src['sample_data_token'])
sample = self.get('sample', sample_data['sample_token'])
return sample
else:
raise Exception('Error: Shortcut from %s to %s not implemented!' % (src_table, tgt_table)) | [
"def",
"shortcut",
"(",
"self",
",",
"src_table",
":",
"str",
",",
"tgt_table",
":",
"str",
",",
"src_token",
":",
"str",
")",
"->",
"Dict",
"[",
"str",
",",
"Any",
"]",
":",
"if",
"src_table",
"==",
"'sample_data'",
"and",
"tgt_table",
"==",
"'sensor'... | https://github.com/nutonomy/nuscenes-devkit/blob/05d05b3c994fb3c17b6643016d9f622a001c7275/python-sdk/nuimages/nuimages.py#L167-L189 | ||
andresriancho/w3af | cd22e5252243a87aaa6d0ddea47cf58dacfe00a9 | w3af/core/data/parsers/doc/sgml.py | python | SGMLParser.meta_tags | (self) | return self._meta_tags | Return list of all meta tags. | Return list of all meta tags. | [
"Return",
"list",
"of",
"all",
"meta",
"tags",
"."
] | def meta_tags(self):
"""
Return list of all meta tags.
"""
return self._meta_tags | [
"def",
"meta_tags",
"(",
"self",
")",
":",
"return",
"self",
".",
"_meta_tags"
] | https://github.com/andresriancho/w3af/blob/cd22e5252243a87aaa6d0ddea47cf58dacfe00a9/w3af/core/data/parsers/doc/sgml.py#L497-L501 | |
home-assistant/core | 265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1 | homeassistant/components/zwave_js/switch.py | python | ZWaveSwitch.async_turn_on | (self, **kwargs: Any) | Turn the switch on. | Turn the switch on. | [
"Turn",
"the",
"switch",
"on",
"."
] | async def async_turn_on(self, **kwargs: Any) -> None:
"""Turn the switch on."""
if self._target_value is not None:
await self.info.node.async_set_value(self._target_value, True) | [
"async",
"def",
"async_turn_on",
"(",
"self",
",",
"*",
"*",
"kwargs",
":",
"Any",
")",
"->",
"None",
":",
"if",
"self",
".",
"_target_value",
"is",
"not",
"None",
":",
"await",
"self",
".",
"info",
".",
"node",
".",
"async_set_value",
"(",
"self",
"... | https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/components/zwave_js/switch.py#L75-L78 | ||
slackapi/python-slack-sdk | 2dee6656ffacb7de0c29bb2a6c2b51ec6b5dbce7 | slack_sdk/models/blocks/basic_components.py | python | MarkdownTextObject.__init__ | (self, *, text: str, verbatim: Optional[bool] = None) | A Markdown text object, meaning markdown characters will be parsed as
formatting information.
https://api.slack.com/reference/block-kit/composition-objects#text
Args:
text (required): The text for the block. This field accepts any of the standard text formatting markup
when type is mrkdwn.
verbatim: When set to false (as is default) URLs will be auto-converted into links,
conversation names will be link-ified, and certain mentions will be automatically parsed.
Using a value of true will skip any preprocessing of this nature,
although you can still include manual parsing strings. This field is only usable when type is mrkdwn. | A Markdown text object, meaning markdown characters will be parsed as
formatting information.
https://api.slack.com/reference/block-kit/composition-objects#text | [
"A",
"Markdown",
"text",
"object",
"meaning",
"markdown",
"characters",
"will",
"be",
"parsed",
"as",
"formatting",
"information",
".",
"https",
":",
"//",
"api",
".",
"slack",
".",
"com",
"/",
"reference",
"/",
"block",
"-",
"kit",
"/",
"composition",
"-"... | def __init__(self, *, text: str, verbatim: Optional[bool] = None):
"""A Markdown text object, meaning markdown characters will be parsed as
formatting information.
https://api.slack.com/reference/block-kit/composition-objects#text
Args:
text (required): The text for the block. This field accepts any of the standard text formatting markup
when type is mrkdwn.
verbatim: When set to false (as is default) URLs will be auto-converted into links,
conversation names will be link-ified, and certain mentions will be automatically parsed.
Using a value of true will skip any preprocessing of this nature,
although you can still include manual parsing strings. This field is only usable when type is mrkdwn.
"""
super().__init__(text=text, type=self.type)
self.verbatim = verbatim | [
"def",
"__init__",
"(",
"self",
",",
"*",
",",
"text",
":",
"str",
",",
"verbatim",
":",
"Optional",
"[",
"bool",
"]",
"=",
"None",
")",
":",
"super",
"(",
")",
".",
"__init__",
"(",
"text",
"=",
"text",
",",
"type",
"=",
"self",
".",
"type",
"... | https://github.com/slackapi/python-slack-sdk/blob/2dee6656ffacb7de0c29bb2a6c2b51ec6b5dbce7/slack_sdk/models/blocks/basic_components.py#L118-L132 | ||
jliljebl/flowblade | 995313a509b80e99eb1ad550d945bdda5995093b | flowblade-trunk/Flowblade/jobs.py | python | JobProxy.get_elapsed_str | (self) | return utils.get_time_str_for_sec_float(self.elapsed) | [] | def get_elapsed_str(self):
return utils.get_time_str_for_sec_float(self.elapsed) | [
"def",
"get_elapsed_str",
"(",
"self",
")",
":",
"return",
"utils",
".",
"get_time_str_for_sec_float",
"(",
"self",
".",
"elapsed",
")"
] | https://github.com/jliljebl/flowblade/blob/995313a509b80e99eb1ad550d945bdda5995093b/flowblade-trunk/Flowblade/jobs.py#L89-L90 | |||
JiYou/openstack | 8607dd488bde0905044b303eb6e52bdea6806923 | packages/source/nova/tools/hacking.py | python | readlines | (filename) | return open(filename).readlines() | Record the current file being tested. | Record the current file being tested. | [
"Record",
"the",
"current",
"file",
"being",
"tested",
"."
] | def readlines(filename):
"""Record the current file being tested."""
pep8.current_file = filename
return open(filename).readlines() | [
"def",
"readlines",
"(",
"filename",
")",
":",
"pep8",
".",
"current_file",
"=",
"filename",
"return",
"open",
"(",
"filename",
")",
".",
"readlines",
"(",
")"
] | https://github.com/JiYou/openstack/blob/8607dd488bde0905044b303eb6e52bdea6806923/packages/source/nova/tools/hacking.py#L572-L575 | |
openembedded/bitbake | 98407efc8c670abd71d3fa88ec3776ee9b5c38f3 | lib/bb/runqueue.py | python | RunQueueScheduler.next | (self) | Return the id of the task we should build next | Return the id of the task we should build next | [
"Return",
"the",
"id",
"of",
"the",
"task",
"we",
"should",
"build",
"next"
] | def next(self):
"""
Return the id of the task we should build next
"""
if self.rq.can_start_task():
return self.next_buildable_task() | [
"def",
"next",
"(",
"self",
")",
":",
"if",
"self",
".",
"rq",
".",
"can_start_task",
"(",
")",
":",
"return",
"self",
".",
"next_buildable_task",
"(",
")"
] | https://github.com/openembedded/bitbake/blob/98407efc8c670abd71d3fa88ec3776ee9b5c38f3/lib/bb/runqueue.py#L218-L223 | ||
HypothesisWorks/hypothesis | d1bfc4acc86899caa7a40f892322e1a69fbf36f4 | hypothesis-python/src/hypothesis/strategies/_internal/types.py | python | has_type_arguments | (type_) | return bool(args) | Decides whethere or not this type has applied type arguments. | Decides whethere or not this type has applied type arguments. | [
"Decides",
"whethere",
"or",
"not",
"this",
"type",
"has",
"applied",
"type",
"arguments",
"."
] | def has_type_arguments(type_):
"""Decides whethere or not this type has applied type arguments."""
args = getattr(type_, "__args__", None)
if args and isinstance(type_, _GenericAlias):
# There are some cases when declared types do already have type arguments
# Like `Sequence`, that is `_GenericAlias(abc.Sequence[T])[T]`
parameters = getattr(type_, "__parameters__", None)
if parameters: # So, we need to know if type args are just "aliases"
return args != parameters
return bool(args) | [
"def",
"has_type_arguments",
"(",
"type_",
")",
":",
"args",
"=",
"getattr",
"(",
"type_",
",",
"\"__args__\"",
",",
"None",
")",
"if",
"args",
"and",
"isinstance",
"(",
"type_",
",",
"_GenericAlias",
")",
":",
"# There are some cases when declared types do alread... | https://github.com/HypothesisWorks/hypothesis/blob/d1bfc4acc86899caa7a40f892322e1a69fbf36f4/hypothesis-python/src/hypothesis/strategies/_internal/types.py#L187-L196 | |
tahoe-lafs/tahoe-lafs | 766a53b5208c03c45ca0a98e97eee76870276aa1 | src/allmydata/util/time_format.py | python | iso_utc_time_to_seconds | (isotime, _conversion_re=re.compile(r"(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})[T_ ](?P<hour>\d{2}):(?P<minute>\d{2}):(?P<second>\d{2})(?P<subsecond>\.\d+)?")) | return calendar.timegm( (year, month, day, hour, minute, second, 0, 1, 0) ) + subsecfloat | The inverse of iso_utc().
Real ISO-8601 is "2003-01-08T06:30:59". We also accept the widely
used variants "2003-01-08_06:30:59" and "2003-01-08 06:30:59". | The inverse of iso_utc(). | [
"The",
"inverse",
"of",
"iso_utc",
"()",
"."
] | def iso_utc_time_to_seconds(isotime, _conversion_re=re.compile(r"(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})[T_ ](?P<hour>\d{2}):(?P<minute>\d{2}):(?P<second>\d{2})(?P<subsecond>\.\d+)?")):
"""
The inverse of iso_utc().
Real ISO-8601 is "2003-01-08T06:30:59". We also accept the widely
used variants "2003-01-08_06:30:59" and "2003-01-08 06:30:59".
"""
m = _conversion_re.match(isotime)
if not m:
raise ValueError(isotime, "not a complete ISO8601 timestamp")
year, month, day = int(m.group('year')), int(m.group('month')), int(m.group('day'))
hour, minute, second = int(m.group('hour')), int(m.group('minute')), int(m.group('second'))
subsecstr = m.group('subsecond')
if subsecstr:
subsecfloat = float(subsecstr)
else:
subsecfloat = 0
return calendar.timegm( (year, month, day, hour, minute, second, 0, 1, 0) ) + subsecfloat | [
"def",
"iso_utc_time_to_seconds",
"(",
"isotime",
",",
"_conversion_re",
"=",
"re",
".",
"compile",
"(",
"r\"(?P<year>\\d{4})-(?P<month>\\d{2})-(?P<day>\\d{2})[T_ ](?P<hour>\\d{2}):(?P<minute>\\d{2}):(?P<second>\\d{2})(?P<subsecond>\\.\\d+)?\"",
")",
")",
":",
"m",
"=",
"_conversio... | https://github.com/tahoe-lafs/tahoe-lafs/blob/766a53b5208c03c45ca0a98e97eee76870276aa1/src/allmydata/util/time_format.py#L33-L51 | |
axcore/tartube | 36dd493642923fe8b9190a41db596c30c043ae90 | tartube/mainwin.py | python | MainWin.on_video_index_mark_not_new | (self, menu_item, media_data_obj,
only_child_videos_flag) | Called from a callback in self.video_index_popup_menu().
Mark all videos in this channel, playlist or folder (and in any child
channels, playlists and folders) as not new.
Args:
menu_item (Gtk.MenuItem): The clicked menu item
media_data_obj (media.Channel, media.Playlist or media.Channel):
The clicked media data object
only_child_videos_flag (bool): Set to True if only child video
objects should be marked; False if all descendants should be
marked | Called from a callback in self.video_index_popup_menu(). | [
"Called",
"from",
"a",
"callback",
"in",
"self",
".",
"video_index_popup_menu",
"()",
"."
] | def on_video_index_mark_not_new(self, menu_item, media_data_obj,
only_child_videos_flag):
"""Called from a callback in self.video_index_popup_menu().
Mark all videos in this channel, playlist or folder (and in any child
channels, playlists and folders) as not new.
Args:
menu_item (Gtk.MenuItem): The clicked menu item
media_data_obj (media.Channel, media.Playlist or media.Channel):
The clicked media data object
only_child_videos_flag (bool): Set to True if only child video
objects should be marked; False if all descendants should be
marked
"""
if DEBUG_FUNC_FLAG:
utils.debug_time('mwn 12576 on_video_index_mark_not_new')
self.app_obj.mark_container_new(
media_data_obj,
False,
only_child_videos_flag,
) | [
"def",
"on_video_index_mark_not_new",
"(",
"self",
",",
"menu_item",
",",
"media_data_obj",
",",
"only_child_videos_flag",
")",
":",
"if",
"DEBUG_FUNC_FLAG",
":",
"utils",
".",
"debug_time",
"(",
"'mwn 12576 on_video_index_mark_not_new'",
")",
"self",
".",
"app_obj",
... | https://github.com/axcore/tartube/blob/36dd493642923fe8b9190a41db596c30c043ae90/tartube/mainwin.py#L13630-L13658 | ||
openshift/openshift-tools | 1188778e728a6e4781acf728123e5b356380fe6f | ansible/roles/lib_openshift_3.2/library/oadm_router.py | python | OpenShiftCLI.openshift_cmd | (self, cmd, oadm=False, output=False, output_type='json', input_data=None) | return rval | Base command for oc | Base command for oc | [
"Base",
"command",
"for",
"oc"
] | def openshift_cmd(self, cmd, oadm=False, output=False, output_type='json', input_data=None):
'''Base command for oc '''
cmds = []
if oadm:
cmds = ['/usr/bin/oc', 'adm']
else:
cmds = ['/usr/bin/oc']
cmds.extend(cmd)
rval = {}
results = ''
err = None
if self.verbose:
print ' '.join(cmds)
proc = subprocess.Popen(cmds,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
env={'KUBECONFIG': self.kubeconfig})
stdout, stderr = proc.communicate(input_data)
rval = {"returncode": proc.returncode,
"results": results,
"cmd": ' '.join(cmds),
}
if proc.returncode == 0:
if output:
if output_type == 'json':
try:
rval['results'] = json.loads(stdout)
except ValueError as err:
if "No JSON object could be decoded" in err.message:
err = err.message
elif output_type == 'raw':
rval['results'] = stdout
if self.verbose:
print stdout
print stderr
if err:
rval.update({"err": err,
"stderr": stderr,
"stdout": stdout,
"cmd": cmds
})
else:
rval.update({"stderr": stderr,
"stdout": stdout,
"results": {},
})
return rval | [
"def",
"openshift_cmd",
"(",
"self",
",",
"cmd",
",",
"oadm",
"=",
"False",
",",
"output",
"=",
"False",
",",
"output_type",
"=",
"'json'",
",",
"input_data",
"=",
"None",
")",
":",
"cmds",
"=",
"[",
"]",
"if",
"oadm",
":",
"cmds",
"=",
"[",
"'/usr... | https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/ansible/roles/lib_openshift_3.2/library/oadm_router.py#L221-L278 | |
guillermooo/Vintageous | f958207009902052aed5fcac09745f1742648604 | xmotions.py | python | _vi_k_select.run | (self, count=1, mode=None) | [] | def run(self, count=1, mode=None):
# FIXME: It isn't working.
if mode != modes.SELECT:
utils.blink()
return
for i in range(count):
self.view.window().run_command('soft_undo')
return | [
"def",
"run",
"(",
"self",
",",
"count",
"=",
"1",
",",
"mode",
"=",
"None",
")",
":",
"# FIXME: It isn't working.",
"if",
"mode",
"!=",
"modes",
".",
"SELECT",
":",
"utils",
".",
"blink",
"(",
")",
"return",
"for",
"i",
"in",
"range",
"(",
"count",
... | https://github.com/guillermooo/Vintageous/blob/f958207009902052aed5fcac09745f1742648604/xmotions.py#L615-L623 | ||||
pyparallel/pyparallel | 11e8c6072d48c8f13641925d17b147bf36ee0ba3 | Lib/email/message.py | python | Message.as_string | (self, unixfrom=False, maxheaderlen=0) | return fp.getvalue() | Return the entire formatted message as a string.
Optional `unixfrom' when True, means include the Unix From_ envelope
header.
This is a convenience method and may not generate the message exactly
as you intend. For more flexibility, use the flatten() method of a
Generator instance. | Return the entire formatted message as a string.
Optional `unixfrom' when True, means include the Unix From_ envelope
header. | [
"Return",
"the",
"entire",
"formatted",
"message",
"as",
"a",
"string",
".",
"Optional",
"unixfrom",
"when",
"True",
"means",
"include",
"the",
"Unix",
"From_",
"envelope",
"header",
"."
] | def as_string(self, unixfrom=False, maxheaderlen=0):
"""Return the entire formatted message as a string.
Optional `unixfrom' when True, means include the Unix From_ envelope
header.
This is a convenience method and may not generate the message exactly
as you intend. For more flexibility, use the flatten() method of a
Generator instance.
"""
from email.generator import Generator
fp = StringIO()
g = Generator(fp, mangle_from_=False, maxheaderlen=maxheaderlen)
g.flatten(self, unixfrom=unixfrom)
return fp.getvalue() | [
"def",
"as_string",
"(",
"self",
",",
"unixfrom",
"=",
"False",
",",
"maxheaderlen",
"=",
"0",
")",
":",
"from",
"email",
".",
"generator",
"import",
"Generator",
"fp",
"=",
"StringIO",
"(",
")",
"g",
"=",
"Generator",
"(",
"fp",
",",
"mangle_from_",
"... | https://github.com/pyparallel/pyparallel/blob/11e8c6072d48c8f13641925d17b147bf36ee0ba3/Lib/email/message.py#L139-L152 | |
home-assistant/core | 265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1 | homeassistant/components/airvisual/__init__.py | python | AirVisualEntity.async_added_to_hass | (self) | Register callbacks. | Register callbacks. | [
"Register",
"callbacks",
"."
] | async def async_added_to_hass(self) -> None:
"""Register callbacks."""
@callback
def update() -> None:
"""Update the state."""
self.update_from_latest_data()
self.async_write_ha_state()
self.async_on_remove(self.coordinator.async_add_listener(update))
self.update_from_latest_data() | [
"async",
"def",
"async_added_to_hass",
"(",
"self",
")",
"->",
"None",
":",
"@",
"callback",
"def",
"update",
"(",
")",
"->",
"None",
":",
"\"\"\"Update the state.\"\"\"",
"self",
".",
"update_from_latest_data",
"(",
")",
"self",
".",
"async_write_ha_state",
"("... | https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/components/airvisual/__init__.py#L361-L372 | ||
pointhi/kicad-footprint-generator | 76fedd51e8680e6cd3b729dcbd6f1a56af53b12c | scripts/SMD_chip_package_rlc-etc/SMD_chip_package_rlc-etc.py | python | merge_dicts | (*dict_args) | return result | Given any number of dicts, shallow copy and merge into a new dict,
precedence goes to key value pairs in latter dicts. | Given any number of dicts, shallow copy and merge into a new dict,
precedence goes to key value pairs in latter dicts. | [
"Given",
"any",
"number",
"of",
"dicts",
"shallow",
"copy",
"and",
"merge",
"into",
"a",
"new",
"dict",
"precedence",
"goes",
"to",
"key",
"value",
"pairs",
"in",
"latter",
"dicts",
"."
] | def merge_dicts(*dict_args):
"""
Given any number of dicts, shallow copy and merge into a new dict,
precedence goes to key value pairs in latter dicts.
"""
result = {}
for dictionary in dict_args:
result.update(dictionary)
return result | [
"def",
"merge_dicts",
"(",
"*",
"dict_args",
")",
":",
"result",
"=",
"{",
"}",
"for",
"dictionary",
"in",
"dict_args",
":",
"result",
".",
"update",
"(",
"dictionary",
")",
"return",
"result"
] | https://github.com/pointhi/kicad-footprint-generator/blob/76fedd51e8680e6cd3b729dcbd6f1a56af53b12c/scripts/SMD_chip_package_rlc-etc/SMD_chip_package_rlc-etc.py#L22-L30 | |
neozhaoliang/pywonderland | 4fc110ba2e7db7db0a0d89369f02c479282239db | src/misc/ust_leaves.py | python | grid_graph | (*size) | return {v: neighbors(v) for v in product(*map(range, size))} | Return a grid graph stored in a dict. | Return a grid graph stored in a dict. | [
"Return",
"a",
"grid",
"graph",
"stored",
"in",
"a",
"dict",
"."
] | def grid_graph(*size):
"""
Return a grid graph stored in a dict.
"""
def neighbors(v):
neighborhood = []
for i in range(len(size)):
for dx in [-1, 1]:
w = list(v)
w[i] += dx
if 0 <= w[i] < size[i]:
neighborhood.append(tuple(w))
return neighborhood
return {v: neighbors(v) for v in product(*map(range, size))} | [
"def",
"grid_graph",
"(",
"*",
"size",
")",
":",
"def",
"neighbors",
"(",
"v",
")",
":",
"neighborhood",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"size",
")",
")",
":",
"for",
"dx",
"in",
"[",
"-",
"1",
",",
"1",
"]",
":",
... | https://github.com/neozhaoliang/pywonderland/blob/4fc110ba2e7db7db0a0d89369f02c479282239db/src/misc/ust_leaves.py#L32-L47 | |
GoogleCloudPlatform/gsutil | 5be882803e76608e2fd29cf8c504ccd1fe0a7746 | gslib/progress_callback.py | python | ProgressCallbackWithTimeout.__init__ | (self,
total_size,
callback_func,
start_bytes_per_callback=_START_BYTES_PER_CALLBACK,
timeout=_TIMEOUT_SECONDS) | Initializes the callback with timeout.
Args:
total_size: Total bytes to process. If this is None, size is not known
at the outset.
callback_func: Func of (int: processed_so_far, int: total_bytes)
used to make callbacks.
start_bytes_per_callback: Lower bound of bytes per callback.
timeout: Number maximum of seconds without a callback. | Initializes the callback with timeout. | [
"Initializes",
"the",
"callback",
"with",
"timeout",
"."
] | def __init__(self,
total_size,
callback_func,
start_bytes_per_callback=_START_BYTES_PER_CALLBACK,
timeout=_TIMEOUT_SECONDS):
"""Initializes the callback with timeout.
Args:
total_size: Total bytes to process. If this is None, size is not known
at the outset.
callback_func: Func of (int: processed_so_far, int: total_bytes)
used to make callbacks.
start_bytes_per_callback: Lower bound of bytes per callback.
timeout: Number maximum of seconds without a callback.
"""
self._bytes_per_callback = start_bytes_per_callback
self._callback_func = callback_func
self._total_size = total_size
self._last_time = time.time()
self._timeout = timeout
self._bytes_processed_since_callback = 0
self._callbacks_made = 0
self._total_bytes_processed = 0 | [
"def",
"__init__",
"(",
"self",
",",
"total_size",
",",
"callback_func",
",",
"start_bytes_per_callback",
"=",
"_START_BYTES_PER_CALLBACK",
",",
"timeout",
"=",
"_TIMEOUT_SECONDS",
")",
":",
"self",
".",
"_bytes_per_callback",
"=",
"start_bytes_per_callback",
"self",
... | https://github.com/GoogleCloudPlatform/gsutil/blob/5be882803e76608e2fd29cf8c504ccd1fe0a7746/gslib/progress_callback.py#L44-L67 | ||
andresriancho/w3af | cd22e5252243a87aaa6d0ddea47cf58dacfe00a9 | w3af/core/data/kb/vuln_templates/file_upload_template.py | python | FileUploadTemplate.get_vulnerability_desc | (self) | return 'Code execution through arbitrary file upload vulnerability' | [] | def get_vulnerability_desc(self):
return 'Code execution through arbitrary file upload vulnerability' | [
"def",
"get_vulnerability_desc",
"(",
"self",
")",
":",
"return",
"'Code execution through arbitrary file upload vulnerability'"
] | https://github.com/andresriancho/w3af/blob/cd22e5252243a87aaa6d0ddea47cf58dacfe00a9/w3af/core/data/kb/vuln_templates/file_upload_template.py#L107-L108 | |||
bikalims/bika.lims | 35e4bbdb5a3912cae0b5eb13e51097c8b0486349 | bika/lims/content/referencesample.py | python | ReferenceSample.workflow_script_expire | (self) | expire sample | expire sample | [
"expire",
"sample"
] | def workflow_script_expire(self):
""" expire sample """
self.setDateExpired(DateTime())
self.reindexObject() | [
"def",
"workflow_script_expire",
"(",
"self",
")",
":",
"self",
".",
"setDateExpired",
"(",
"DateTime",
"(",
")",
")",
"self",
".",
"reindexObject",
"(",
")"
] | https://github.com/bikalims/bika.lims/blob/35e4bbdb5a3912cae0b5eb13e51097c8b0486349/bika/lims/content/referencesample.py#L380-L383 | ||
videoflow/videoflow | 7894f72c4373e78060f0c0448cc04f1083f0bffa | videoflow/core/node.py | python | Node.add_child | (self, child) | Adds child to the set of childs that depend on it. | Adds child to the set of childs that depend on it. | [
"Adds",
"child",
"to",
"the",
"set",
"of",
"childs",
"that",
"depend",
"on",
"it",
"."
] | def add_child(self, child):
'''
Adds child to the set of childs that depend on it.
'''
self._children.add(child) | [
"def",
"add_child",
"(",
"self",
",",
"child",
")",
":",
"self",
".",
"_children",
".",
"add",
"(",
"child",
")"
] | https://github.com/videoflow/videoflow/blob/7894f72c4373e78060f0c0448cc04f1083f0bffa/videoflow/core/node.py#L101-L105 | ||
OpenCobolIDE/OpenCobolIDE | c78d0d335378e5fe0a5e74f53c19b68b55e85388 | open_cobol_ide/extlibs/pyqode/core/widgets/menu_recents.py | python | RecentFilesManager.set_value | (self, key, value) | Set the recent files value in QSettings.
:param key: value key
:param value: new value | Set the recent files value in QSettings.
:param key: value key
:param value: new value | [
"Set",
"the",
"recent",
"files",
"value",
"in",
"QSettings",
".",
":",
"param",
"key",
":",
"value",
"key",
":",
"param",
"value",
":",
"new",
"value"
] | def set_value(self, key, value):
"""
Set the recent files value in QSettings.
:param key: value key
:param value: new value
"""
if value is None:
value = []
value = [os.path.normpath(pth) for pth in value]
self._settings.setValue('recent_files/%s' % key, value) | [
"def",
"set_value",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"if",
"value",
"is",
"None",
":",
"value",
"=",
"[",
"]",
"value",
"=",
"[",
"os",
".",
"path",
".",
"normpath",
"(",
"pth",
")",
"for",
"pth",
"in",
"value",
"]",
"self",
"."... | https://github.com/OpenCobolIDE/OpenCobolIDE/blob/c78d0d335378e5fe0a5e74f53c19b68b55e85388/open_cobol_ide/extlibs/pyqode/core/widgets/menu_recents.py#L74-L83 | ||
Esri/ArcREST | ab240fde2b0200f61d4a5f6df033516e53f2f416 | src/arcrest/security/security.py | python | PKISecurityHandler.__init__ | (self, org_url, keyfile, certificatefile,
proxy_url=None, proxy_port=None, referer_url=None) | Constructor | Constructor | [
"Constructor"
] | def __init__(self, org_url, keyfile, certificatefile,
proxy_url=None, proxy_port=None, referer_url=None):
"""Constructor"""
self._keyfile = keyfile
self._certificatefile = certificatefile
self._proxy_url = proxy_url
self._proxy_port = proxy_port
self._initURL(org_url=org_url,
referer_url=referer_url) | [
"def",
"__init__",
"(",
"self",
",",
"org_url",
",",
"keyfile",
",",
"certificatefile",
",",
"proxy_url",
"=",
"None",
",",
"proxy_port",
"=",
"None",
",",
"referer_url",
"=",
"None",
")",
":",
"self",
".",
"_keyfile",
"=",
"keyfile",
"self",
".",
"_cert... | https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/security/security.py#L381-L391 | ||
demisto/content | 5c664a65b992ac8ca90ac3f11b1b2cdf11ee9b07 | Packs/Sepio/Integrations/SepioPrimeAPI/SepioPrimeAPI.py | python | sepio_query_system_events_command | (client, args) | return CommandResults(
outputs_prefix='Sepio.Event',
outputs_key_field='EventID',
outputs=outputs,
readable_output=readable_output,
raw_response=events
) if outputs else empty_get_result_to_readable_result(readable_output) | Returns CommandResults with all the events that are in the query args
Args:
client (Client): SepioPrimeAPI client.
args (dict): all command arguments.
Returns:
All the agents that are in the query args
readable_output (str): This will be presented in the war room - should be in markdown syntax - human readable
outputs (dict): Dictionary/JSON - saved in the incident context in order to be used as inputs
for other tasks in the playbook | Returns CommandResults with all the events that are in the query args | [
"Returns",
"CommandResults",
"with",
"all",
"the",
"events",
"that",
"are",
"in",
"the",
"query",
"args"
] | def sepio_query_system_events_command(client, args):
"""
Returns CommandResults with all the events that are in the query args
Args:
client (Client): SepioPrimeAPI client.
args (dict): all command arguments.
Returns:
All the agents that are in the query args
readable_output (str): This will be presented in the war room - should be in markdown syntax - human readable
outputs (dict): Dictionary/JSON - saved in the incident context in order to be used as inputs
for other tasks in the playbook
"""
start_datetime = args.get('start_datetime')
end_datetime = args.get('end_datetime')
min_severity = args.get('min_severity')
category = argToList(args.get('category'))
source = args.get('source')
peripheral_type = args.get('peripheral_type')
limit = validate_fetch_data_max_result(arg_to_int(args.get('limit', 20), 'limit', False), MAX_RESULTS, 'limit')
events = client.prime_get_events(start_datetime, min_severity, category, limit, end_datetime, source, peripheral_type)
outputs = [{
'EventID': event['eventID'],
'CreationDatetime': event['creationTime'],
'Severity': event['severityString'],
'Description': event['description'],
'Category': event['category'],
'Source': event['eventEntityID'],
'PeripheralType': event['peripheralIcon'],
'Details': event['details']
} for event in events]
outputs_headers = ['EventID', 'CreationDatetime', 'Category', 'Source', 'Description']
readable_output = list_of_objects_to_readable_output('Events', outputs, outputs_headers)
return CommandResults(
outputs_prefix='Sepio.Event',
outputs_key_field='EventID',
outputs=outputs,
readable_output=readable_output,
raw_response=events
) if outputs else empty_get_result_to_readable_result(readable_output) | [
"def",
"sepio_query_system_events_command",
"(",
"client",
",",
"args",
")",
":",
"start_datetime",
"=",
"args",
".",
"get",
"(",
"'start_datetime'",
")",
"end_datetime",
"=",
"args",
".",
"get",
"(",
"'end_datetime'",
")",
"min_severity",
"=",
"args",
".",
"g... | https://github.com/demisto/content/blob/5c664a65b992ac8ca90ac3f11b1b2cdf11ee9b07/Packs/Sepio/Integrations/SepioPrimeAPI/SepioPrimeAPI.py#L981-L1026 | |
JaniceWuo/MovieRecommend | 4c86db64ca45598917d304f535413df3bc9fea65 | movierecommend/venv1/Lib/site-packages/django/core/checks/registry.py | python | CheckRegistry.tag_exists | (self, tag, include_deployment_checks=False) | return tag in self.tags_available(include_deployment_checks) | [] | def tag_exists(self, tag, include_deployment_checks=False):
return tag in self.tags_available(include_deployment_checks) | [
"def",
"tag_exists",
"(",
"self",
",",
"tag",
",",
"include_deployment_checks",
"=",
"False",
")",
":",
"return",
"tag",
"in",
"self",
".",
"tags_available",
"(",
"include_deployment_checks",
")"
] | https://github.com/JaniceWuo/MovieRecommend/blob/4c86db64ca45598917d304f535413df3bc9fea65/movierecommend/venv1/Lib/site-packages/django/core/checks/registry.py#L88-L89 | |||
parkouss/webmacs | 35f174303af8c9147825c45ad41ff35706fa8bfa | webmacs/commands/caret_browsing.py | python | up | (ctx) | Move the caret up a line. | Move the caret up a line. | [
"Move",
"the",
"caret",
"up",
"a",
"line",
"."
] | def up(ctx):
"""
Move the caret up a line.
"""
call_js(ctx, "CaretBrowsing.move('backward', 'line');") | [
"def",
"up",
"(",
"ctx",
")",
":",
"call_js",
"(",
"ctx",
",",
"\"CaretBrowsing.move('backward', 'line');\"",
")"
] | https://github.com/parkouss/webmacs/blob/35f174303af8c9147825c45ad41ff35706fa8bfa/webmacs/commands/caret_browsing.py#L50-L54 | ||
kuri65536/python-for-android | 26402a08fc46b09ef94e8d7a6bbc3a54ff9d0891 | python-modules/twisted/twisted/internet/wxreactor.py | python | WxReactor._installSignalHandlersAgain | (self) | wx sometimes removes our own signal handlers, so re-add them. | wx sometimes removes our own signal handlers, so re-add them. | [
"wx",
"sometimes",
"removes",
"our",
"own",
"signal",
"handlers",
"so",
"re",
"-",
"add",
"them",
"."
] | def _installSignalHandlersAgain(self):
"""
wx sometimes removes our own signal handlers, so re-add them.
"""
try:
# make _handleSignals happy:
import signal
signal.signal(signal.SIGINT, signal.default_int_handler)
except ImportError:
return
self._handleSignals() | [
"def",
"_installSignalHandlersAgain",
"(",
"self",
")",
":",
"try",
":",
"# make _handleSignals happy:",
"import",
"signal",
"signal",
".",
"signal",
"(",
"signal",
".",
"SIGINT",
",",
"signal",
".",
"default_int_handler",
")",
"except",
"ImportError",
":",
"retur... | https://github.com/kuri65536/python-for-android/blob/26402a08fc46b09ef94e8d7a6bbc3a54ff9d0891/python-modules/twisted/twisted/internet/wxreactor.py#L75-L85 | ||
weechat/scripts | 99ec0e7eceefabb9efb0f11ec26d45d6e8e84335 | python/minesweeper.py | python | minesweeper_mouse_cb | (data, hsignal, hashtable) | return weechat.WEECHAT_RC_OK | Mouse callback. | Mouse callback. | [
"Mouse",
"callback",
"."
] | def minesweeper_mouse_cb(data, hsignal, hashtable):
"""Mouse callback."""
global minesweeper
if minesweeper['end']:
minesweeper_new_game()
else:
minesweeper['cursor'] = False
x = int(hashtable.get('_chat_line_x', '-1'))
y = int(hashtable.get('_chat_line_y', '-1'))
key = hashtable.get('_key', '')
if x >= 0 and y >= 1:
x = x // (4 + (minesweeper['zoom'] * 2))
y = (y - 1) // (minesweeper['zoom'] + 2)
if x >= 0 and x <= minesweeper['size'] - 1 and y >= 0 and y <= minesweeper['size'] - 1:
minesweeper_timer_start()
if key.startswith('button1'):
minesweeper_explore(x, y)
if not minesweeper['end'] and minesweeper_all_squares_explored():
minesweeper_end('win')
minesweeper_display()
elif key.startswith('button2'):
minesweeper_flag(x, y)
return weechat.WEECHAT_RC_OK | [
"def",
"minesweeper_mouse_cb",
"(",
"data",
",",
"hsignal",
",",
"hashtable",
")",
":",
"global",
"minesweeper",
"if",
"minesweeper",
"[",
"'end'",
"]",
":",
"minesweeper_new_game",
"(",
")",
"else",
":",
"minesweeper",
"[",
"'cursor'",
"]",
"=",
"False",
"x... | https://github.com/weechat/scripts/blob/99ec0e7eceefabb9efb0f11ec26d45d6e8e84335/python/minesweeper.py#L522-L544 | |
angr/angr | 4b04d56ace135018083d36d9083805be8146688b | angr/state_plugins/solver.py | python | SimSolver.describe_variables | (self, v) | Given an AST, iterate over all the keys of all the BVS leaves in the tree which are registered. | Given an AST, iterate over all the keys of all the BVS leaves in the tree which are registered. | [
"Given",
"an",
"AST",
"iterate",
"over",
"all",
"the",
"keys",
"of",
"all",
"the",
"BVS",
"leaves",
"in",
"the",
"tree",
"which",
"are",
"registered",
"."
] | def describe_variables(self, v):
"""
Given an AST, iterate over all the keys of all the BVS leaves in the tree which are registered.
"""
# pylint: disable=stop-iteration-return
# ??? wtf pylint
reverse_mapping = {next(iter(var.variables)): k for k, var in self.eternal_tracked_variables.items()}
reverse_mapping.update({next(iter(var.variables)): k for k, var in self.temporal_tracked_variables.items() if k[-1] is not None})
for var in v.variables:
if var in reverse_mapping:
yield reverse_mapping[var] | [
"def",
"describe_variables",
"(",
"self",
",",
"v",
")",
":",
"# pylint: disable=stop-iteration-return",
"# ??? wtf pylint",
"reverse_mapping",
"=",
"{",
"next",
"(",
"iter",
"(",
"var",
".",
"variables",
")",
")",
":",
"k",
"for",
"k",
",",
"var",
"in",
"se... | https://github.com/angr/angr/blob/4b04d56ace135018083d36d9083805be8146688b/angr/state_plugins/solver.py#L251-L262 | ||
microsoft/ProphetNet | 32f806bf16598c59990fc932da3dbb3746716f7c | GLGE_baselines/script/script/evaluate/gigaword/bs_pyrouge.py | python | Rouge155.__clean_rouge_args | (self, rouge_args) | Remove enclosing quotation marks, if any. | Remove enclosing quotation marks, if any. | [
"Remove",
"enclosing",
"quotation",
"marks",
"if",
"any",
"."
] | def __clean_rouge_args(self, rouge_args):
"""
Remove enclosing quotation marks, if any.
"""
if not rouge_args:
return
quot_mark_pattern = re.compile('"(.+)"')
match = quot_mark_pattern.match(rouge_args)
if match:
cleaned_args = match.group(1)
return cleaned_args
else:
return rouge_args | [
"def",
"__clean_rouge_args",
"(",
"self",
",",
"rouge_args",
")",
":",
"if",
"not",
"rouge_args",
":",
"return",
"quot_mark_pattern",
"=",
"re",
".",
"compile",
"(",
"'\"(.+)\"'",
")",
"match",
"=",
"quot_mark_pattern",
".",
"match",
"(",
"rouge_args",
")",
... | https://github.com/microsoft/ProphetNet/blob/32f806bf16598c59990fc932da3dbb3746716f7c/GLGE_baselines/script/script/evaluate/gigaword/bs_pyrouge.py#L604-L617 | ||
mcfletch/pyopengl | 02d11dad9ff18e50db10e975c4756e17bf198464 | OpenGL/GLU/glunurbs.py | python | gluNurbsCallbackDataEXT | ( baseFunction,nurb, userData ) | return baseFunction(
nurb, nurb.noteObject( userData )
) | Note the Python object for use as userData by the nurb | Note the Python object for use as userData by the nurb | [
"Note",
"the",
"Python",
"object",
"for",
"use",
"as",
"userData",
"by",
"the",
"nurb"
] | def gluNurbsCallbackDataEXT( baseFunction,nurb, userData ):
"""Note the Python object for use as userData by the nurb"""
return baseFunction(
nurb, nurb.noteObject( userData )
) | [
"def",
"gluNurbsCallbackDataEXT",
"(",
"baseFunction",
",",
"nurb",
",",
"userData",
")",
":",
"return",
"baseFunction",
"(",
"nurb",
",",
"nurb",
".",
"noteObject",
"(",
"userData",
")",
")"
] | https://github.com/mcfletch/pyopengl/blob/02d11dad9ff18e50db10e975c4756e17bf198464/OpenGL/GLU/glunurbs.py#L203-L207 | |
simoncadman/CUPS-Cloud-Print | 5d96eaa5ba1d3ffe40845498917879b0e907f6bd | oauth2client/multistore_file.py | python | _MultiStore._get_all_credential_keys | (self) | return [dict(key) for key in self._data.keys()] | Gets all the registered credential keys in the multistore.
Returns:
A list of dictionaries corresponding to all the keys currently registered | Gets all the registered credential keys in the multistore. | [
"Gets",
"all",
"the",
"registered",
"credential",
"keys",
"in",
"the",
"multistore",
"."
] | def _get_all_credential_keys(self):
"""Gets all the registered credential keys in the multistore.
Returns:
A list of dictionaries corresponding to all the keys currently registered
"""
return [dict(key) for key in self._data.keys()] | [
"def",
"_get_all_credential_keys",
"(",
"self",
")",
":",
"return",
"[",
"dict",
"(",
"key",
")",
"for",
"key",
"in",
"self",
".",
"_data",
".",
"keys",
"(",
")",
"]"
] | https://github.com/simoncadman/CUPS-Cloud-Print/blob/5d96eaa5ba1d3ffe40845498917879b0e907f6bd/oauth2client/multistore_file.py#L405-L411 | |
openstack/kuryr-kubernetes | 513ada72685ef02cd9f3aca418ac1b2e0dc1b8ba | kuryr_kubernetes/utils.py | python | is_available | (resource, resource_quota) | return True | [] | def is_available(resource, resource_quota):
availability = resource_quota['limit'] - resource_quota['used']
if availability <= 0:
LOG.error("Neutron quota exceeded for %s. Used %d out of %d limit.",
resource, resource_quota['used'], resource_quota['limit'])
return False
elif availability <= 3:
LOG.warning("Neutron quota low for %s. Used %d out of %d limit.",
resource, resource_quota['used'], resource_quota['limit'])
return True | [
"def",
"is_available",
"(",
"resource",
",",
"resource_quota",
")",
":",
"availability",
"=",
"resource_quota",
"[",
"'limit'",
"]",
"-",
"resource_quota",
"[",
"'used'",
"]",
"if",
"availability",
"<=",
"0",
":",
"LOG",
".",
"error",
"(",
"\"Neutron quota exc... | https://github.com/openstack/kuryr-kubernetes/blob/513ada72685ef02cd9f3aca418ac1b2e0dc1b8ba/kuryr_kubernetes/utils.py#L391-L400 | |||
apache/libcloud | 90971e17bfd7b6bb97b2489986472c531cc8e140 | libcloud/container/base.py | python | ContainerDriver.install_image | (self, path) | Install a container image from a remote path.
:param path: Path to the container image
:type path: ``str``
:rtype: :class:`.ContainerImage` | Install a container image from a remote path. | [
"Install",
"a",
"container",
"image",
"from",
"a",
"remote",
"path",
"."
] | def install_image(self, path):
# type: (str) -> ContainerImage
"""
Install a container image from a remote path.
:param path: Path to the container image
:type path: ``str``
:rtype: :class:`.ContainerImage`
"""
raise NotImplementedError("install_image not implemented for this driver") | [
"def",
"install_image",
"(",
"self",
",",
"path",
")",
":",
"# type: (str) -> ContainerImage",
"raise",
"NotImplementedError",
"(",
"\"install_image not implemented for this driver\"",
")"
] | https://github.com/apache/libcloud/blob/90971e17bfd7b6bb97b2489986472c531cc8e140/libcloud/container/base.py#L288-L298 | ||
JaniceWuo/MovieRecommend | 4c86db64ca45598917d304f535413df3bc9fea65 | movierecommend/venv1/Lib/site-packages/django/contrib/gis/gdal/layer.py | python | Layer.srs | (self) | Returns the Spatial Reference used in this Layer. | Returns the Spatial Reference used in this Layer. | [
"Returns",
"the",
"Spatial",
"Reference",
"used",
"in",
"this",
"Layer",
"."
] | def srs(self):
"Returns the Spatial Reference used in this Layer."
try:
ptr = capi.get_layer_srs(self.ptr)
return SpatialReference(srs_api.clone_srs(ptr))
except SRSException:
return None | [
"def",
"srs",
"(",
"self",
")",
":",
"try",
":",
"ptr",
"=",
"capi",
".",
"get_layer_srs",
"(",
"self",
".",
"ptr",
")",
"return",
"SpatialReference",
"(",
"srs_api",
".",
"clone_srs",
"(",
"ptr",
")",
")",
"except",
"SRSException",
":",
"return",
"Non... | https://github.com/JaniceWuo/MovieRecommend/blob/4c86db64ca45598917d304f535413df3bc9fea65/movierecommend/venv1/Lib/site-packages/django/contrib/gis/gdal/layer.py#L126-L132 | ||
mozman/ezdxf | 59d0fc2ea63f5cf82293428f5931da7e9f9718e9 | src/ezdxf/tools/crypt.py | python | encode | (text_lines: Iterable[str]) | return (_encode(line) for line in text_lines) | Encode the Standard :term:`ACIS` Text (SAT) format by AutoCAD "encryption" algorithm. | Encode the Standard :term:`ACIS` Text (SAT) format by AutoCAD "encryption" algorithm. | [
"Encode",
"the",
"Standard",
":",
"term",
":",
"ACIS",
"Text",
"(",
"SAT",
")",
"format",
"by",
"AutoCAD",
"encryption",
"algorithm",
"."
] | def encode(text_lines: Iterable[str]) -> Iterable[str]:
""" Encode the Standard :term:`ACIS` Text (SAT) format by AutoCAD "encryption" algorithm. """
def _encode(text):
s = []
enctab = _encode_table # fast local var
for c in text:
if c in enctab:
s += enctab[c]
if c == 'A':
s += ' ' # append a space for an 'A' -> cryptography
else:
s += chr(ord(c) ^ 0x5F)
return ''.join(s)
return (_encode(line) for line in text_lines) | [
"def",
"encode",
"(",
"text_lines",
":",
"Iterable",
"[",
"str",
"]",
")",
"->",
"Iterable",
"[",
"str",
"]",
":",
"def",
"_encode",
"(",
"text",
")",
":",
"s",
"=",
"[",
"]",
"enctab",
"=",
"_encode_table",
"# fast local var",
"for",
"c",
"in",
"tex... | https://github.com/mozman/ezdxf/blob/59d0fc2ea63f5cf82293428f5931da7e9f9718e9/src/ezdxf/tools/crypt.py#L45-L58 | |
pycontribs/jira | 09ece94f3cae7e6d0becfa87d77d6a05ce01cdf6 | jira/resources.py | python | Role.add_user | (
self,
users: Union[str, List, Tuple] = None,
groups: Union[str, List, Tuple] = None,
) | Add the specified users or groups to this project role.
One of ``users`` or ``groups`` must be specified.
Args:
users (Optional[Union[str,List,Tuple]]): a user or users to add to the role
groups (Optional[Union[str,List,Tuple]]): a group or groups to add to the role | Add the specified users or groups to this project role. | [
"Add",
"the",
"specified",
"users",
"or",
"groups",
"to",
"this",
"project",
"role",
"."
] | def add_user(
self,
users: Union[str, List, Tuple] = None,
groups: Union[str, List, Tuple] = None,
):
"""Add the specified users or groups to this project role.
One of ``users`` or ``groups`` must be specified.
Args:
users (Optional[Union[str,List,Tuple]]): a user or users to add to the role
groups (Optional[Union[str,List,Tuple]]): a group or groups to add to the role
"""
if users is not None and isinstance(users, str):
users = (users,)
if groups is not None and isinstance(groups, str):
groups = (groups,)
data = {"user": users, "group": groups}
self._session.post(self.self, data=json.dumps(data)) | [
"def",
"add_user",
"(",
"self",
",",
"users",
":",
"Union",
"[",
"str",
",",
"List",
",",
"Tuple",
"]",
"=",
"None",
",",
"groups",
":",
"Union",
"[",
"str",
",",
"List",
",",
"Tuple",
"]",
"=",
"None",
",",
")",
":",
"if",
"users",
"is",
"not"... | https://github.com/pycontribs/jira/blob/09ece94f3cae7e6d0becfa87d77d6a05ce01cdf6/jira/resources.py#L1000-L1020 | ||
suavecode/SUAVE | 4f83c467c5662b6cc611ce2ab6c0bdd25fd5c0a5 | trunk/SUAVE/Methods/Missions/Segments/Cruise/Constant_Pitch_Rate_Constant_Altitude.py | python | unpack_unknowns | (segment) | Unpacks the throttle setting and velocity from the solver to the mission
Assumptions:
N/A
Inputs:
state.unknowns:
throttle [Unitless]
velocity [meters/second]
Outputs:
state.conditions:
propulsion.throttle [Unitless]
frames.inertial.velocity_vector [meters/second]
Properties Used:
N/A | Unpacks the throttle setting and velocity from the solver to the mission
Assumptions:
N/A
Inputs:
state.unknowns:
throttle [Unitless]
velocity [meters/second]
Outputs:
state.conditions:
propulsion.throttle [Unitless]
frames.inertial.velocity_vector [meters/second] | [
"Unpacks",
"the",
"throttle",
"setting",
"and",
"velocity",
"from",
"the",
"solver",
"to",
"the",
"mission",
"Assumptions",
":",
"N",
"/",
"A",
"Inputs",
":",
"state",
".",
"unknowns",
":",
"throttle",
"[",
"Unitless",
"]",
"velocity",
"[",
"meters",
"/",
... | def unpack_unknowns(segment):
""" Unpacks the throttle setting and velocity from the solver to the mission
Assumptions:
N/A
Inputs:
state.unknowns:
throttle [Unitless]
velocity [meters/second]
Outputs:
state.conditions:
propulsion.throttle [Unitless]
frames.inertial.velocity_vector [meters/second]
Properties Used:
N/A
"""
# unpack unknowns
throttle = segment.state.unknowns.throttle
air_speed = segment.state.unknowns.velocity
# apply unknowns
segment.state.conditions.propulsion.throttle[:,0] = throttle[:,0]
segment.state.conditions.frames.inertial.velocity_vector[:,0] = air_speed[:,0] | [
"def",
"unpack_unknowns",
"(",
"segment",
")",
":",
"# unpack unknowns",
"throttle",
"=",
"segment",
".",
"state",
".",
"unknowns",
".",
"throttle",
"air_speed",
"=",
"segment",
".",
"state",
".",
"unknowns",
".",
"velocity",
"# apply unknowns",
"segment",
".",
... | https://github.com/suavecode/SUAVE/blob/4f83c467c5662b6cc611ce2ab6c0bdd25fd5c0a5/trunk/SUAVE/Methods/Missions/Segments/Cruise/Constant_Pitch_Rate_Constant_Altitude.py#L120-L147 | ||
ikostrikov/pytorch-flows | bf12ed91b86867b38d74982f5e2d44c248604df9 | datasets/util.py | python | make_folder | (folder) | Creates given folder (or path) if it doesn't exist. | Creates given folder (or path) if it doesn't exist. | [
"Creates",
"given",
"folder",
"(",
"or",
"path",
")",
"if",
"it",
"doesn",
"t",
"exist",
"."
] | def make_folder(folder):
"""
Creates given folder (or path) if it doesn't exist.
"""
if not os.path.exists(folder):
os.makedirs(folder) | [
"def",
"make_folder",
"(",
"folder",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"folder",
")",
":",
"os",
".",
"makedirs",
"(",
"folder",
")"
] | https://github.com/ikostrikov/pytorch-flows/blob/bf12ed91b86867b38d74982f5e2d44c248604df9/datasets/util.py#L379-L385 | ||
Tencent/bk-bcs-saas | 2b437bf2f5fd5ce2078f7787c3a12df609f7679d | bcs-app/backend/packages/blue_krill/data_types/enum.py | python | FeatureFlag.get_default_flags | (cls) | return features.copy() | Get the default user feature flags, client is safe to modify the result because it's a copy | Get the default user feature flags, client is safe to modify the result because it's a copy | [
"Get",
"the",
"default",
"user",
"feature",
"flags",
"client",
"is",
"safe",
"to",
"modify",
"the",
"result",
"because",
"it",
"s",
"a",
"copy"
] | def get_default_flags(cls) -> Dict[str, bool]:
"""Get the default user feature flags, client is safe to modify the result because it's a copy"""
features = {field.name: field.default for field in cls._get_feature_fields_().values()}
return features.copy() | [
"def",
"get_default_flags",
"(",
"cls",
")",
"->",
"Dict",
"[",
"str",
",",
"bool",
"]",
":",
"features",
"=",
"{",
"field",
".",
"name",
":",
"field",
".",
"default",
"for",
"field",
"in",
"cls",
".",
"_get_feature_fields_",
"(",
")",
".",
"values",
... | https://github.com/Tencent/bk-bcs-saas/blob/2b437bf2f5fd5ce2078f7787c3a12df609f7679d/bcs-app/backend/packages/blue_krill/data_types/enum.py#L102-L105 | |
RexYing/gnn-model-explainer | bc984829f4f4829e93c760e9bbdc8e73f96e2cc1 | utils/synthetic_structsim.py | python | house | (start, role_start=0) | return graph, roles | Builds a house-like graph, with index of nodes starting at start
and role_ids at role_start
INPUT:
-------------
start : starting index for the shape
role_start : starting index for the roles
OUTPUT:
-------------
graph : a house shape graph, with ids beginning at start
roles : list of the roles of the nodes (indexed starting at
role_start) | Builds a house-like graph, with index of nodes starting at start
and role_ids at role_start
INPUT:
-------------
start : starting index for the shape
role_start : starting index for the roles
OUTPUT:
-------------
graph : a house shape graph, with ids beginning at start
roles : list of the roles of the nodes (indexed starting at
role_start) | [
"Builds",
"a",
"house",
"-",
"like",
"graph",
"with",
"index",
"of",
"nodes",
"starting",
"at",
"start",
"and",
"role_ids",
"at",
"role_start",
"INPUT",
":",
"-------------",
"start",
":",
"starting",
"index",
"for",
"the",
"shape",
"role_start",
":",
"start... | def house(start, role_start=0):
"""Builds a house-like graph, with index of nodes starting at start
and role_ids at role_start
INPUT:
-------------
start : starting index for the shape
role_start : starting index for the roles
OUTPUT:
-------------
graph : a house shape graph, with ids beginning at start
roles : list of the roles of the nodes (indexed starting at
role_start)
"""
graph = nx.Graph()
graph.add_nodes_from(range(start, start + 5))
graph.add_edges_from(
[
(start, start + 1),
(start + 1, start + 2),
(start + 2, start + 3),
(start + 3, start),
]
)
# graph.add_edges_from([(start, start + 2), (start + 1, start + 3)])
graph.add_edges_from([(start + 4, start), (start + 4, start + 1)])
roles = [role_start, role_start, role_start + 1, role_start + 1, role_start + 2]
return graph, roles | [
"def",
"house",
"(",
"start",
",",
"role_start",
"=",
"0",
")",
":",
"graph",
"=",
"nx",
".",
"Graph",
"(",
")",
"graph",
".",
"add_nodes_from",
"(",
"range",
"(",
"start",
",",
"start",
"+",
"5",
")",
")",
"graph",
".",
"add_edges_from",
"(",
"[",... | https://github.com/RexYing/gnn-model-explainer/blob/bc984829f4f4829e93c760e9bbdc8e73f96e2cc1/utils/synthetic_structsim.py#L178-L204 | |
tariqdaouda/pyGeno | 6311c9cd94443e05b130d8b4babc24c374a77d7c | pyGeno/tools/parsers/FastaTools.py | python | FastaFile.__len__ | (self) | return len(self.data) | returns the number of entries | returns the number of entries | [
"returns",
"the",
"number",
"of",
"entries"
] | def __len__(self) :
"""returns the number of entries"""
return len(self.data) | [
"def",
"__len__",
"(",
"self",
")",
":",
"return",
"len",
"(",
"self",
".",
"data",
")"
] | https://github.com/tariqdaouda/pyGeno/blob/6311c9cd94443e05b130d8b4babc24c374a77d7c/pyGeno/tools/parsers/FastaTools.py#L98-L100 | |
zhl2008/awd-platform | 0416b31abea29743387b10b3914581fbe8e7da5e | web_flaskbb/Python-2.7.9/Lib/idlelib/RemoteDebugger.py | python | IdbAdapter.set_return | (self, fid) | [] | def set_return(self, fid):
frame = frametable[fid]
self.idb.set_return(frame) | [
"def",
"set_return",
"(",
"self",
",",
"fid",
")",
":",
"frame",
"=",
"frametable",
"[",
"fid",
"]",
"self",
".",
"idb",
".",
"set_return",
"(",
"frame",
")"
] | https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/Python-2.7.9/Lib/idlelib/RemoteDebugger.py#L91-L93 | ||||
postgres/pgadmin4 | 374c5e952fa594d749fadf1f88076c1cba8c5f64 | web/pgadmin/browser/server_groups/servers/databases/schemas/__init__.py | python | check_precondition | (f) | return wrap | This function will behave as a decorator which will checks
database connection before running view, it will also attaches
manager,conn & template_path properties to instance of the method.
Assumptions:
This function will always be used as decorator of a class method. | This function will behave as a decorator which will checks
database connection before running view, it will also attaches
manager,conn & template_path properties to instance of the method. | [
"This",
"function",
"will",
"behave",
"as",
"a",
"decorator",
"which",
"will",
"checks",
"database",
"connection",
"before",
"running",
"view",
"it",
"will",
"also",
"attaches",
"manager",
"conn",
"&",
"template_path",
"properties",
"to",
"instance",
"of",
"the"... | def check_precondition(f):
"""
This function will behave as a decorator which will checks
database connection before running view, it will also attaches
manager,conn & template_path properties to instance of the method.
Assumptions:
This function will always be used as decorator of a class method.
"""
@wraps(f)
def wrap(*args, **kwargs):
# Here args[0] will hold self & kwargs will hold gid,sid,did
self = args[0]
self.manager = get_driver(PG_DEFAULT_DRIVER).connection_manager(
kwargs['sid']
)
if not self.manager:
return gone(errormsg=gettext("Could not find the server."))
self.conn = self.manager.connection(did=kwargs['did'])
self.datlastsysoid = \
self.manager.db_info[kwargs['did']]['datlastsysoid'] \
if self.manager.db_info is not None and \
kwargs['did'] in self.manager.db_info else 0
self.datistemplate = False
if (
self.manager.db_info is not None and
kwargs['did'] in self.manager.db_info and
'datistemplate' in self.manager.db_info[kwargs['did']]
):
self.datistemplate = self.manager.db_info[
kwargs['did']]['datistemplate']
# Set the template path for the SQL scripts
if self.manager.server_type == 'ppas':
_temp = self.ppas_template_path(self.manager.version)
else:
_temp = self.pg_template_path(self.manager.version)
self.template_path = self.template_initial + '/' + _temp
return f(*args, **kwargs)
return wrap | [
"def",
"check_precondition",
"(",
"f",
")",
":",
"@",
"wraps",
"(",
"f",
")",
"def",
"wrap",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# Here args[0] will hold self & kwargs will hold gid,sid,did",
"self",
"=",
"args",
"[",
"0",
"]",
"self",
".... | https://github.com/postgres/pgadmin4/blob/374c5e952fa594d749fadf1f88076c1cba8c5f64/web/pgadmin/browser/server_groups/servers/databases/schemas/__init__.py#L122-L166 | |
tensorflow/lattice | 784eca50cbdfedf39f183cc7d298c9fe376b69c0 | tensorflow_lattice/python/utils.py | python | canonicalize_trust | (trusts) | return None | Converts string constants representing trust direction into integers.
Args:
trusts: edgeworth_trusts or trapezoid_trusts hyperparameter of
`tfl.layers.Lattice` layer.
Returns:
A list of trust constraint tuples of the form
(feature_a, feature_b, direction) where direction can be -1 or 1, or the
value None if trusts is None.
Raises:
ValueError: If one of trust constraints does not have 3 elements.
ValueError: If one of trust constraints' direction is not in the set
{-1, 1, 'negative', 'positive'}. | Converts string constants representing trust direction into integers. | [
"Converts",
"string",
"constants",
"representing",
"trust",
"direction",
"into",
"integers",
"."
] | def canonicalize_trust(trusts):
"""Converts string constants representing trust direction into integers.
Args:
trusts: edgeworth_trusts or trapezoid_trusts hyperparameter of
`tfl.layers.Lattice` layer.
Returns:
A list of trust constraint tuples of the form
(feature_a, feature_b, direction) where direction can be -1 or 1, or the
value None if trusts is None.
Raises:
ValueError: If one of trust constraints does not have 3 elements.
ValueError: If one of trust constraints' direction is not in the set
{-1, 1, 'negative', 'positive'}.
"""
if trusts:
canonicalized = []
for trust in trusts:
if len(trust) != 3:
raise ValueError("Trust constraints must consist of 3 elements. Seeing "
"constraint tuple {}".format(trust))
feature_a, feature_b, direction = trust
if direction in [-1, 1]:
canonicalized.append(trust)
elif (isinstance(direction, six.string_types) and
direction.lower() == "negative"):
canonicalized.append((feature_a, feature_b, -1))
elif (isinstance(direction, six.string_types) and
direction.lower() == "positive"):
canonicalized.append((feature_a, feature_b, 1))
else:
raise ValueError("trust constraint direction must be from: [-1, 1, "
"'negative', 'positive']. Given: {}".format(direction))
return canonicalized
return None | [
"def",
"canonicalize_trust",
"(",
"trusts",
")",
":",
"if",
"trusts",
":",
"canonicalized",
"=",
"[",
"]",
"for",
"trust",
"in",
"trusts",
":",
"if",
"len",
"(",
"trust",
")",
"!=",
"3",
":",
"raise",
"ValueError",
"(",
"\"Trust constraints must consist of 3... | https://github.com/tensorflow/lattice/blob/784eca50cbdfedf39f183cc7d298c9fe376b69c0/tensorflow_lattice/python/utils.py#L157-L193 | |
mrkipling/maraschino | c6be9286937783ae01df2d6d8cebfc8b2734a7d7 | lib/transmissionrpc/client.py | python | Client.locate | (self, ids, location, timeout=None) | Locate torrent data at the location. | Locate torrent data at the location. | [
"Locate",
"torrent",
"data",
"at",
"the",
"location",
"."
] | def locate(self, ids, location, timeout=None):
"""Locate torrent data at the location."""
self._rpc_version_warning(6)
args = {'location': location, 'move': False}
self._request('torrent-set-location', args, ids, True, timeout=timeout) | [
"def",
"locate",
"(",
"self",
",",
"ids",
",",
"location",
",",
"timeout",
"=",
"None",
")",
":",
"self",
".",
"_rpc_version_warning",
"(",
"6",
")",
"args",
"=",
"{",
"'location'",
":",
"location",
",",
"'move'",
":",
"False",
"}",
"self",
".",
"_re... | https://github.com/mrkipling/maraschino/blob/c6be9286937783ae01df2d6d8cebfc8b2734a7d7/lib/transmissionrpc/client.py#L564-L568 | ||
log2timeline/plaso | fe2e316b8c76a0141760c0f2f181d84acb83abc2 | plaso/parsers/sqlite_plugins/kodi.py | python | KodiMyVideosPlugin.ParseVideoRow | (self, parser_mediator, query, row, **unused_kwargs) | Parses a Video row.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
query (str): query that created the row.
row (sqlite3.Row): row. | Parses a Video row. | [
"Parses",
"a",
"Video",
"row",
"."
] | def ParseVideoRow(self, parser_mediator, query, row, **unused_kwargs):
"""Parses a Video row.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
query (str): query that created the row.
row (sqlite3.Row): row.
"""
query_hash = hash(query)
event_data = KodiVideoEventData()
event_data.filename = self._GetRowValue(query_hash, row, 'strFilename')
event_data.play_count = self._GetRowValue(query_hash, row, 'playCount')
event_data.query = query
timestamp = self._GetRowValue(query_hash, row, 'lastPlayed')
date_time = dfdatetime_time_elements.TimeElements()
date_time.CopyFromDateTimeString(timestamp)
event = time_events.DateTimeValuesEvent(
date_time, definitions.TIME_DESCRIPTION_LAST_VISITED)
parser_mediator.ProduceEventWithEventData(event, event_data) | [
"def",
"ParseVideoRow",
"(",
"self",
",",
"parser_mediator",
",",
"query",
",",
"row",
",",
"*",
"*",
"unused_kwargs",
")",
":",
"query_hash",
"=",
"hash",
"(",
"query",
")",
"event_data",
"=",
"KodiVideoEventData",
"(",
")",
"event_data",
".",
"filename",
... | https://github.com/log2timeline/plaso/blob/fe2e316b8c76a0141760c0f2f181d84acb83abc2/plaso/parsers/sqlite_plugins/kodi.py#L164-L185 | ||
PySimpleGUI/PySimpleGUI | 6c0d1fb54f493d45e90180b322fbbe70f7a5af3c | PySimpleGUI.py | python | SystemTray.__init__ | (self, menu=None, filename=None, data=None, data_base64=None, tooltip=None, metadata=None) | SystemTray - create an icon in the system tray
:param menu: Menu definition. Example - ['UNUSED', ['My', 'Simple', '---', 'Menu', 'Exit']]
:type menu: List[List[List[str] or str]]
:param filename: filename for icon
:type filename: (str)
:param data: in-ram image for icon (same as data_base64 parm)
:type data: (bytes)
:param data_base64: base-64 data for icon
:type data_base64: (bytes)
:param tooltip: tooltip string
:type tooltip: (str)
:param metadata: User metadata that can be set to ANYTHING
:type metadata: (Any) | SystemTray - create an icon in the system tray
:param menu: Menu definition. Example - ['UNUSED', ['My', 'Simple', '---', 'Menu', 'Exit']]
:type menu: List[List[List[str] or str]]
:param filename: filename for icon
:type filename: (str)
:param data: in-ram image for icon (same as data_base64 parm)
:type data: (bytes)
:param data_base64: base-64 data for icon
:type data_base64: (bytes)
:param tooltip: tooltip string
:type tooltip: (str)
:param metadata: User metadata that can be set to ANYTHING
:type metadata: (Any) | [
"SystemTray",
"-",
"create",
"an",
"icon",
"in",
"the",
"system",
"tray",
":",
"param",
"menu",
":",
"Menu",
"definition",
".",
"Example",
"-",
"[",
"UNUSED",
"[",
"My",
"Simple",
"---",
"Menu",
"Exit",
"]]",
":",
"type",
"menu",
":",
"List",
"[",
"L... | def __init__(self, menu=None, filename=None, data=None, data_base64=None, tooltip=None, metadata=None):
"""
SystemTray - create an icon in the system tray
:param menu: Menu definition. Example - ['UNUSED', ['My', 'Simple', '---', 'Menu', 'Exit']]
:type menu: List[List[List[str] or str]]
:param filename: filename for icon
:type filename: (str)
:param data: in-ram image for icon (same as data_base64 parm)
:type data: (bytes)
:param data_base64: base-64 data for icon
:type data_base64: (bytes)
:param tooltip: tooltip string
:type tooltip: (str)
:param metadata: User metadata that can be set to ANYTHING
:type metadata: (Any)
"""
self._metadata = None
self.Menu = menu
self.TrayIcon = None
self.Shown = False
self.MenuItemChosen = TIMEOUT_KEY
self.metadata = metadata
self.last_message_event = None
screen_size = Window.get_screen_size()
if filename:
image_elem = Image(filename=filename, background_color='red', enable_events=True, tooltip=tooltip, key='-IMAGE-')
elif data_base64:
image_elem = Image(data=data_base64, background_color='red', enable_events=True, tooltip=tooltip, key='-IMAGE-')
elif data:
image_elem = Image(data=data, background_color='red', enable_events=True, tooltip=tooltip, key='-IMAGE-')
else:
image_elem = Image(background_color='red', enable_events=True, tooltip=tooltip, key='-IMAGE-')
layout = [
[image_elem],
]
self.window = Window('Window Title', layout, element_padding=(0, 0), margins=(0, 0), grab_anywhere=True, no_titlebar=True, transparent_color='red',
keep_on_top=True, right_click_menu=menu, location=(screen_size[0] - 100, screen_size[1] - 100), finalize=True)
self.window['-IMAGE-'].bind('<Double-Button-1>', '+DOUBLE_CLICK') | [
"def",
"__init__",
"(",
"self",
",",
"menu",
"=",
"None",
",",
"filename",
"=",
"None",
",",
"data",
"=",
"None",
",",
"data_base64",
"=",
"None",
",",
"tooltip",
"=",
"None",
",",
"metadata",
"=",
"None",
")",
":",
"self",
".",
"_metadata",
"=",
"... | https://github.com/PySimpleGUI/PySimpleGUI/blob/6c0d1fb54f493d45e90180b322fbbe70f7a5af3c/PySimpleGUI.py#L11206-L11246 | ||
liyi14/mx-DeepIM | f1c850e5f8f75f1051a89c40daff9185870020f5 | lib/dataset/LM6D_REFINE.py | python | LM6D_REFINE.depth_path_from_index | (self, index, type, check=True, cls_name="") | return depth_file | given image index, find out the full path of depth map
:param index: index of a specific image
:return: full path of depth image | given image index, find out the full path of depth map
:param index: index of a specific image
:return: full path of depth image | [
"given",
"image",
"index",
"find",
"out",
"the",
"full",
"path",
"of",
"depth",
"map",
":",
"param",
"index",
":",
"index",
"of",
"a",
"specific",
"image",
":",
"return",
":",
"full",
"path",
"of",
"depth",
"image"
] | def depth_path_from_index(self, index, type, check=True, cls_name=""):
"""
given image index, find out the full path of depth map
:param index: index of a specific image
:return: full path of depth image
"""
if type == "observed":
depth_file = os.path.join(self.observed_data_path, index + "-depth.png")
elif type == "gt_observed":
depth_file = os.path.join(self.gt_observed_data_path, cls_name, index.split("/")[1] + "-depth.png")
elif type == "rendered":
depth_file = os.path.join(self.rendered_data_path, index + "-depth.png")
if check:
assert os.path.exists(depth_file), "type:{}, Path does not exist: {}".format(type, depth_file)
return depth_file | [
"def",
"depth_path_from_index",
"(",
"self",
",",
"index",
",",
"type",
",",
"check",
"=",
"True",
",",
"cls_name",
"=",
"\"\"",
")",
":",
"if",
"type",
"==",
"\"observed\"",
":",
"depth_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"... | https://github.com/liyi14/mx-DeepIM/blob/f1c850e5f8f75f1051a89c40daff9185870020f5/lib/dataset/LM6D_REFINE.py#L155-L169 | |
oilshell/oil | 94388e7d44a9ad879b12615f6203b38596b5a2d3 | Python-2.7.13/Lib/sre_parse.py | python | _parse_sub_cond | (source, state, condgroup) | return subpattern | [] | def _parse_sub_cond(source, state, condgroup):
item_yes = _parse(source, state)
if source.match("|"):
item_no = _parse(source, state)
if source.match("|"):
raise error, "conditional backref with more than two branches"
else:
item_no = None
if source.next and not source.match(")", 0):
raise error, "pattern not properly closed"
subpattern = SubPattern(state)
subpattern.append((GROUPREF_EXISTS, (condgroup, item_yes, item_no)))
return subpattern | [
"def",
"_parse_sub_cond",
"(",
"source",
",",
"state",
",",
"condgroup",
")",
":",
"item_yes",
"=",
"_parse",
"(",
"source",
",",
"state",
")",
"if",
"source",
".",
"match",
"(",
"\"|\"",
")",
":",
"item_no",
"=",
"_parse",
"(",
"source",
",",
"state",... | https://github.com/oilshell/oil/blob/94388e7d44a9ad879b12615f6203b38596b5a2d3/Python-2.7.13/Lib/sre_parse.py#L378-L390 | |||
Source-Python-Dev-Team/Source.Python | d0ffd8ccbd1e9923c9bc44936f20613c1c76b7fb | addons/source-python/Python3/traceback.py | python | TracebackException._load_lines | (self) | Private API. force all lines in the stack to be loaded. | Private API. force all lines in the stack to be loaded. | [
"Private",
"API",
".",
"force",
"all",
"lines",
"in",
"the",
"stack",
"to",
"be",
"loaded",
"."
] | def _load_lines(self):
"""Private API. force all lines in the stack to be loaded."""
for frame in self.stack:
frame.line
if self.__context__:
self.__context__._load_lines()
if self.__cause__:
self.__cause__._load_lines() | [
"def",
"_load_lines",
"(",
"self",
")",
":",
"for",
"frame",
"in",
"self",
".",
"stack",
":",
"frame",
".",
"line",
"if",
"self",
".",
"__context__",
":",
"self",
".",
"__context__",
".",
"_load_lines",
"(",
")",
"if",
"self",
".",
"__cause__",
":",
... | https://github.com/Source-Python-Dev-Team/Source.Python/blob/d0ffd8ccbd1e9923c9bc44936f20613c1c76b7fb/addons/source-python/Python3/traceback.py#L517-L524 | ||
trakt/Plex-Trakt-Scrobbler | aeb0bfbe62fad4b06c164f1b95581da7f35dce0b | Trakttv.bundle/Contents/Libraries/MacOSX/x86_64/ucs4/cryptography/x509/base.py | python | CertificateSigningRequestBuilder.__init__ | (self, subject_name=None, extensions=[]) | Creates an empty X.509 certificate request (v1). | Creates an empty X.509 certificate request (v1). | [
"Creates",
"an",
"empty",
"X",
".",
"509",
"certificate",
"request",
"(",
"v1",
")",
"."
] | def __init__(self, subject_name=None, extensions=[]):
"""
Creates an empty X.509 certificate request (v1).
"""
self._subject_name = subject_name
self._extensions = extensions | [
"def",
"__init__",
"(",
"self",
",",
"subject_name",
"=",
"None",
",",
"extensions",
"=",
"[",
"]",
")",
":",
"self",
".",
"_subject_name",
"=",
"subject_name",
"self",
".",
"_extensions",
"=",
"extensions"
] | https://github.com/trakt/Plex-Trakt-Scrobbler/blob/aeb0bfbe62fad4b06c164f1b95581da7f35dce0b/Trakttv.bundle/Contents/Libraries/MacOSX/x86_64/ucs4/cryptography/x509/base.py#L334-L339 | ||
NationalSecurityAgency/qgis-d3datavis-plugin | c3f0280158b0b4f7818604ef410de56a5f56c0be | __init__.py | python | classFactory | (iface) | return D3DataVis(iface) | [] | def classFactory(iface):
from .d3datavis import D3DataVis
return D3DataVis(iface) | [
"def",
"classFactory",
"(",
"iface",
")",
":",
"from",
".",
"d3datavis",
"import",
"D3DataVis",
"return",
"D3DataVis",
"(",
"iface",
")"
] | https://github.com/NationalSecurityAgency/qgis-d3datavis-plugin/blob/c3f0280158b0b4f7818604ef410de56a5f56c0be/__init__.py#L1-L3 | |||
AutodeskRoboticsLab/Mimic | 85447f0d346be66988303a6a054473d92f1ed6f4 | mimic/scripts/extern/pyqtgraph_0_11_0_dev0/pyqtgraph/opengl/items/GLMeshItem.py | python | GLMeshItem.setColor | (self, c) | Set the default color to use when no vertex or face colors are specified. | Set the default color to use when no vertex or face colors are specified. | [
"Set",
"the",
"default",
"color",
"to",
"use",
"when",
"no",
"vertex",
"or",
"face",
"colors",
"are",
"specified",
"."
] | def setColor(self, c):
"""Set the default color to use when no vertex or face colors are specified."""
self.opts['color'] = c
self.update() | [
"def",
"setColor",
"(",
"self",
",",
"c",
")",
":",
"self",
".",
"opts",
"[",
"'color'",
"]",
"=",
"c",
"self",
".",
"update",
"(",
")"
] | https://github.com/AutodeskRoboticsLab/Mimic/blob/85447f0d346be66988303a6a054473d92f1ed6f4/mimic/scripts/extern/pyqtgraph_0_11_0_dev0/pyqtgraph/opengl/items/GLMeshItem.py#L78-L81 | ||
mypaint/mypaint | 90b36dbc7b8bd2f323383f7edf608a5e0a3a1a33 | lib/meta.py | python | _get_release_info_script | (gitprefix="gitexport") | return release_info | Returns a script fragment describing the release.
Like _get_versions(), this must only be called from build scripting
or similar machinery. The returned string can be processed by either
Python or Bourne Shell. | Returns a script fragment describing the release. | [
"Returns",
"a",
"script",
"fragment",
"describing",
"the",
"release",
"."
] | def _get_release_info_script(gitprefix="gitexport"):
"""Returns a script fragment describing the release.
Like _get_versions(), this must only be called from build scripting
or similar machinery. The returned string can be processed by either
Python or Bourne Shell.
"""
base, formal, ceremonial = _get_versions(gitprefix=gitprefix)
release_info = "MYPAINT_VERSION_BASE=%r\n" % (base,)
release_info += "MYPAINT_VERSION_FORMAL=%r\n" % (formal,)
release_info += "MYPAINT_VERSION_CEREMONIAL=%r\n" % (ceremonial,)
return release_info | [
"def",
"_get_release_info_script",
"(",
"gitprefix",
"=",
"\"gitexport\"",
")",
":",
"base",
",",
"formal",
",",
"ceremonial",
"=",
"_get_versions",
"(",
"gitprefix",
"=",
"gitprefix",
")",
"release_info",
"=",
"\"MYPAINT_VERSION_BASE=%r\\n\"",
"%",
"(",
"base",
"... | https://github.com/mypaint/mypaint/blob/90b36dbc7b8bd2f323383f7edf608a5e0a3a1a33/lib/meta.py#L412-L424 | |
deepset-ai/haystack | 79fdda8a7cf393d774803608a4874f2a6e63cf6f | haystack/nodes/file_classifier/file_type.py | python | FileTypeClassifier.run | (self, file_paths: Union[Path, List[Path]]) | Return the output based on file extension | Return the output based on file extension | [
"Return",
"the",
"output",
"based",
"on",
"file",
"extension"
] | def run(self, file_paths: Union[Path, List[Path]]): # type: ignore
"""
Return the output based on file extension
"""
if isinstance(file_paths, Path):
file_paths = [file_paths]
extension: set = self._get_files_extension(file_paths)
if len(extension) > 1:
raise ValueError(f"Multiple files types are not allowed at once.")
output = {"file_paths": file_paths}
ext: str = extension.pop()
try:
index = ["txt", "pdf", "md", "docx", "html"].index(ext) + 1
return output, f"output_{index}"
except ValueError:
raise Exception(f"Files with an extension '{ext}' are not supported.") | [
"def",
"run",
"(",
"self",
",",
"file_paths",
":",
"Union",
"[",
"Path",
",",
"List",
"[",
"Path",
"]",
"]",
")",
":",
"# type: ignore",
"if",
"isinstance",
"(",
"file_paths",
",",
"Path",
")",
":",
"file_paths",
"=",
"[",
"file_paths",
"]",
"extension... | https://github.com/deepset-ai/haystack/blob/79fdda8a7cf393d774803608a4874f2a6e63cf6f/haystack/nodes/file_classifier/file_type.py#L23-L40 | ||
IBM/lale | b4d6829c143a4735b06083a0e6c70d2cca244162 | lale/operators.py | python | get_available_operators | (
tag: str, more_tags: AbstractSet[str] = None
) | return [op for op in _all_available_operators if filter(op)] | [] | def get_available_operators(
tag: str, more_tags: AbstractSet[str] = None
) -> List[PlannedOperator]:
singleton = set([tag])
tags = singleton if (more_tags is None) else singleton.union(more_tags)
def filter(op):
tags_dict = op.get_tags()
if tags_dict is None:
return False
tags_set = {tag for prefix in tags_dict for tag in tags_dict[prefix]}
return tags.issubset(tags_set)
return [op for op in _all_available_operators if filter(op)] | [
"def",
"get_available_operators",
"(",
"tag",
":",
"str",
",",
"more_tags",
":",
"AbstractSet",
"[",
"str",
"]",
"=",
"None",
")",
"->",
"List",
"[",
"PlannedOperator",
"]",
":",
"singleton",
"=",
"set",
"(",
"[",
"tag",
"]",
")",
"tags",
"=",
"singlet... | https://github.com/IBM/lale/blob/b4d6829c143a4735b06083a0e6c70d2cca244162/lale/operators.py#L3399-L3412 | |||
linxid/Machine_Learning_Study_Path | 558e82d13237114bbb8152483977806fc0c222af | Machine Learning In Action/Chapter5-LogisticRegression/venv/Lib/site-packages/pip/_vendor/requests/packages/urllib3/packages/six.py | python | MovedAttribute._resolve | (self) | return getattr(module, self.attr) | [] | def _resolve(self):
module = _import_module(self.mod)
return getattr(module, self.attr) | [
"def",
"_resolve",
"(",
"self",
")",
":",
"module",
"=",
"_import_module",
"(",
"self",
".",
"mod",
")",
"return",
"getattr",
"(",
"module",
",",
"self",
".",
"attr",
")"
] | https://github.com/linxid/Machine_Learning_Study_Path/blob/558e82d13237114bbb8152483977806fc0c222af/Machine Learning In Action/Chapter5-LogisticRegression/venv/Lib/site-packages/pip/_vendor/requests/packages/urllib3/packages/six.py#L159-L161 | |||
WerWolv/EdiZon_CheatsConfigsAndScripts | d16d36c7509c01dca770f402babd83ff2e9ae6e7 | Scripts/lib/python3.5/email/message.py | python | Message.replace_header | (self, _name, _value) | Replace a header.
Replace the first matching header found in the message, retaining
header order and case. If no matching header was found, a KeyError is
raised. | Replace a header. | [
"Replace",
"a",
"header",
"."
] | def replace_header(self, _name, _value):
"""Replace a header.
Replace the first matching header found in the message, retaining
header order and case. If no matching header was found, a KeyError is
raised.
"""
_name = _name.lower()
for i, (k, v) in zip(range(len(self._headers)), self._headers):
if k.lower() == _name:
self._headers[i] = self.policy.header_store_parse(k, _value)
break
else:
raise KeyError(_name) | [
"def",
"replace_header",
"(",
"self",
",",
"_name",
",",
"_value",
")",
":",
"_name",
"=",
"_name",
".",
"lower",
"(",
")",
"for",
"i",
",",
"(",
"k",
",",
"v",
")",
"in",
"zip",
"(",
"range",
"(",
"len",
"(",
"self",
".",
"_headers",
")",
")",... | https://github.com/WerWolv/EdiZon_CheatsConfigsAndScripts/blob/d16d36c7509c01dca770f402babd83ff2e9ae6e7/Scripts/lib/python3.5/email/message.py#L546-L559 | ||
jgoguen/calibre-kobo-driver | 6d331a80f6098c105fbf4bbb440a3e3c7024b4f8 | device/driver.py | python | KOBOTOUCHEXTENDED.disable_hyphenation | (self) | return self.get_pref("disable_hyphenation") | Determine if hyphenation should be disabled. | Determine if hyphenation should be disabled. | [
"Determine",
"if",
"hyphenation",
"should",
"be",
"disabled",
"."
] | def disable_hyphenation(self):
"""Determine if hyphenation should be disabled."""
return self.get_pref("disable_hyphenation") | [
"def",
"disable_hyphenation",
"(",
"self",
")",
":",
"return",
"self",
".",
"get_pref",
"(",
"\"disable_hyphenation\"",
")"
] | https://github.com/jgoguen/calibre-kobo-driver/blob/6d331a80f6098c105fbf4bbb440a3e3c7024b4f8/device/driver.py#L689-L691 | |
bendmorris/static-python | 2e0f8c4d7ed5b359dc7d8a75b6fb37e6b6c5c473 | Lib/distutils/msvc9compiler.py | python | Reg.read_values | (cls, base, key) | return d | Return dict of registry keys and values.
All names are converted to lowercase. | Return dict of registry keys and values. | [
"Return",
"dict",
"of",
"registry",
"keys",
"and",
"values",
"."
] | def read_values(cls, base, key):
"""Return dict of registry keys and values.
All names are converted to lowercase.
"""
try:
handle = RegOpenKeyEx(base, key)
except RegError:
return None
d = {}
i = 0
while True:
try:
name, value, type = RegEnumValue(handle, i)
except RegError:
break
name = name.lower()
d[cls.convert_mbcs(name)] = cls.convert_mbcs(value)
i += 1
return d | [
"def",
"read_values",
"(",
"cls",
",",
"base",
",",
"key",
")",
":",
"try",
":",
"handle",
"=",
"RegOpenKeyEx",
"(",
"base",
",",
"key",
")",
"except",
"RegError",
":",
"return",
"None",
"d",
"=",
"{",
"}",
"i",
"=",
"0",
"while",
"True",
":",
"t... | https://github.com/bendmorris/static-python/blob/2e0f8c4d7ed5b359dc7d8a75b6fb37e6b6c5c473/Lib/distutils/msvc9compiler.py#L91-L110 | |
LiuXingMing/Scrapy_Redis_Bloomfilter | 6608c9188f7a1738e2b4265324079898d61f8447 | scrapyWithBloomfilter_demo/scrapyWithBloomfilter_demo/scrapy_redis/spiders.py | python | RedisMixin.schedule_next_request | (self) | Schedules a request if available | Schedules a request if available | [
"Schedules",
"a",
"request",
"if",
"available"
] | def schedule_next_request(self):
"""Schedules a request if available"""
req = self.next_request()
if req:
self.crawler.engine.crawl(req, spider=self) | [
"def",
"schedule_next_request",
"(",
"self",
")",
":",
"req",
"=",
"self",
".",
"next_request",
"(",
")",
"if",
"req",
":",
"self",
".",
"crawler",
".",
"engine",
".",
"crawl",
"(",
"req",
",",
"spider",
"=",
"self",
")"
] | https://github.com/LiuXingMing/Scrapy_Redis_Bloomfilter/blob/6608c9188f7a1738e2b4265324079898d61f8447/scrapyWithBloomfilter_demo/scrapyWithBloomfilter_demo/scrapy_redis/spiders.py#L32-L36 | ||
HuobiRDCenter/huobi_Python | c75a7fa8b31e99ffc1c173d74dcfcad83682e943 | huobi/client/trade.py | python | TradeClient.create_super_margin_order | (self, symbol: 'str', account_id: 'int', order_type: 'OrderType', amount: 'float',
price: 'float', client_order_id=None, stop_price=None,
operator=None) | return self.create_order(symbol=symbol, account_id=account_id, order_type=order_type, amount=amount,
price=price, source=order_source, client_order_id=client_order_id,
stop_price=stop_price,
operator=operator) | [] | def create_super_margin_order(self, symbol: 'str', account_id: 'int', order_type: 'OrderType', amount: 'float',
price: 'float', client_order_id=None, stop_price=None,
operator=None) -> int:
order_source = OrderSource.SUPER_MARGIN_API
return self.create_order(symbol=symbol, account_id=account_id, order_type=order_type, amount=amount,
price=price, source=order_source, client_order_id=client_order_id,
stop_price=stop_price,
operator=operator) | [
"def",
"create_super_margin_order",
"(",
"self",
",",
"symbol",
":",
"'str'",
",",
"account_id",
":",
"'int'",
",",
"order_type",
":",
"'OrderType'",
",",
"amount",
":",
"'float'",
",",
"price",
":",
"'float'",
",",
"client_order_id",
"=",
"None",
",",
"stop... | https://github.com/HuobiRDCenter/huobi_Python/blob/c75a7fa8b31e99ffc1c173d74dcfcad83682e943/huobi/client/trade.py#L369-L376 | |||
Python-Markdown/markdown | af38c42706f8dff93694d4a7572003dbd8b0ddc0 | markdown/util.py | python | Registry.get_index_for_name | (self, name) | Return the index of the given name. | Return the index of the given name. | [
"Return",
"the",
"index",
"of",
"the",
"given",
"name",
"."
] | def get_index_for_name(self, name):
"""
Return the index of the given name.
"""
if name in self:
self._sort()
return self._priority.index(
[x for x in self._priority if x.name == name][0]
)
raise ValueError('No item named "{}" exists.'.format(name)) | [
"def",
"get_index_for_name",
"(",
"self",
",",
"name",
")",
":",
"if",
"name",
"in",
"self",
":",
"self",
".",
"_sort",
"(",
")",
"return",
"self",
".",
"_priority",
".",
"index",
"(",
"[",
"x",
"for",
"x",
"in",
"self",
".",
"_priority",
"if",
"x"... | https://github.com/Python-Markdown/markdown/blob/af38c42706f8dff93694d4a7572003dbd8b0ddc0/markdown/util.py#L330-L339 | ||
rembo10/headphones | b3199605be1ebc83a7a8feab6b1e99b64014187c | headphones/cuesplit.py | python | MetaFile.folders | (self) | return artist, album | [] | def folders(self):
artist = self.content['artist']
album = self.content['date'] + ' - ' + self.content['title'] + ' (' + self.content[
'label'] + ' - ' + self.content['catalog'] + ')'
return artist, album | [
"def",
"folders",
"(",
"self",
")",
":",
"artist",
"=",
"self",
".",
"content",
"[",
"'artist'",
"]",
"album",
"=",
"self",
".",
"content",
"[",
"'date'",
"]",
"+",
"' - '",
"+",
"self",
".",
"content",
"[",
"'title'",
"]",
"+",
"' ('",
"+",
"self"... | https://github.com/rembo10/headphones/blob/b3199605be1ebc83a7a8feab6b1e99b64014187c/headphones/cuesplit.py#L486-L490 | |||
nltk/nltk | 3f74ac55681667d7ef78b664557487145f51eb02 | nltk/tokenize/texttiling.py | python | TextTilingTokenizer._create_token_table | (self, token_sequences, par_breaks) | return token_table | Creates a table of TokenTableFields | Creates a table of TokenTableFields | [
"Creates",
"a",
"table",
"of",
"TokenTableFields"
] | def _create_token_table(self, token_sequences, par_breaks):
"Creates a table of TokenTableFields"
token_table = {}
current_par = 0
current_tok_seq = 0
pb_iter = par_breaks.__iter__()
current_par_break = next(pb_iter)
if current_par_break == 0:
try:
current_par_break = next(pb_iter) # skip break at 0
except StopIteration as e:
raise ValueError(
"No paragraph breaks were found(text too short perhaps?)"
) from e
for ts in token_sequences:
for word, index in ts.wrdindex_list:
try:
while index > current_par_break:
current_par_break = next(pb_iter)
current_par += 1
except StopIteration:
# hit bottom
pass
if word in token_table:
token_table[word].total_count += 1
if token_table[word].last_par != current_par:
token_table[word].last_par = current_par
token_table[word].par_count += 1
if token_table[word].last_tok_seq != current_tok_seq:
token_table[word].last_tok_seq = current_tok_seq
token_table[word].ts_occurences.append([current_tok_seq, 1])
else:
token_table[word].ts_occurences[-1][1] += 1
else: # new word
token_table[word] = TokenTableField(
first_pos=index,
ts_occurences=[[current_tok_seq, 1]],
total_count=1,
par_count=1,
last_par=current_par,
last_tok_seq=current_tok_seq,
)
current_tok_seq += 1
return token_table | [
"def",
"_create_token_table",
"(",
"self",
",",
"token_sequences",
",",
"par_breaks",
")",
":",
"token_table",
"=",
"{",
"}",
"current_par",
"=",
"0",
"current_tok_seq",
"=",
"0",
"pb_iter",
"=",
"par_breaks",
".",
"__iter__",
"(",
")",
"current_par_break",
"=... | https://github.com/nltk/nltk/blob/3f74ac55681667d7ef78b664557487145f51eb02/nltk/tokenize/texttiling.py#L235-L283 | |
erevus-cn/pocscan | 5fef32b1abe22a9f666ad3aacfd1f99d784cb72d | pocscan/plugins/pocsuite/packages/requests/packages/urllib3/util/timeout.py | python | Timeout._validate_timeout | (cls, value, name) | return value | Check that a timeout attribute is valid
:param value: The timeout value to validate
:param name: The name of the timeout attribute to validate. This is used
for clear error messages
:return: the value
:raises ValueError: if the type is not an integer or a float, or if it
is a numeric value less than zero | Check that a timeout attribute is valid | [
"Check",
"that",
"a",
"timeout",
"attribute",
"is",
"valid"
] | def _validate_timeout(cls, value, name):
""" Check that a timeout attribute is valid
:param value: The timeout value to validate
:param name: The name of the timeout attribute to validate. This is used
for clear error messages
:return: the value
:raises ValueError: if the type is not an integer or a float, or if it
is a numeric value less than zero
"""
if value is _Default:
return cls.DEFAULT_TIMEOUT
if value is None or value is cls.DEFAULT_TIMEOUT:
return value
try:
float(value)
except (TypeError, ValueError):
raise ValueError("Timeout value %s was %s, but it must be an "
"int or float." % (name, value))
try:
if value < 0:
raise ValueError("Attempted to set %s timeout to %s, but the "
"timeout cannot be set to a value less "
"than 0." % (name, value))
except TypeError: # Python 3
raise ValueError("Timeout value %s was %s, but it must be an "
"int or float." % (name, value))
return value | [
"def",
"_validate_timeout",
"(",
"cls",
",",
"value",
",",
"name",
")",
":",
"if",
"value",
"is",
"_Default",
":",
"return",
"cls",
".",
"DEFAULT_TIMEOUT",
"if",
"value",
"is",
"None",
"or",
"value",
"is",
"cls",
".",
"DEFAULT_TIMEOUT",
":",
"return",
"v... | https://github.com/erevus-cn/pocscan/blob/5fef32b1abe22a9f666ad3aacfd1f99d784cb72d/pocscan/plugins/pocsuite/packages/requests/packages/urllib3/util/timeout.py#L99-L130 | |
openshift/openshift-tools | 1188778e728a6e4781acf728123e5b356380fe6f | openshift/installer/vendored/openshift-ansible-3.9.40/roles/lib_openshift/library/oc_volume.py | python | Yedit.yaml_dict | (self, value) | setter method for yaml_dict | setter method for yaml_dict | [
"setter",
"method",
"for",
"yaml_dict"
] | def yaml_dict(self, value):
''' setter method for yaml_dict '''
self.__yaml_dict = value | [
"def",
"yaml_dict",
"(",
"self",
",",
"value",
")",
":",
"self",
".",
"__yaml_dict",
"=",
"value"
] | https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/openshift/installer/vendored/openshift-ansible-3.9.40/roles/lib_openshift/library/oc_volume.py#L222-L224 | ||
khanhnamle1994/natural-language-processing | 01d450d5ac002b0156ef4cf93a07cb508c1bcdc5 | assignment1/.env/lib/python2.7/site-packages/IPython/utils/frame.py | python | extract_module_locals | (depth=0) | return (module, f.f_locals) | Returns (module, locals) of the funciton `depth` frames away from the caller | Returns (module, locals) of the funciton `depth` frames away from the caller | [
"Returns",
"(",
"module",
"locals",
")",
"of",
"the",
"funciton",
"depth",
"frames",
"away",
"from",
"the",
"caller"
] | def extract_module_locals(depth=0):
"""Returns (module, locals) of the funciton `depth` frames away from the caller"""
f = sys._getframe(depth + 1)
global_ns = f.f_globals
module = sys.modules[global_ns['__name__']]
return (module, f.f_locals) | [
"def",
"extract_module_locals",
"(",
"depth",
"=",
"0",
")",
":",
"f",
"=",
"sys",
".",
"_getframe",
"(",
"depth",
"+",
"1",
")",
"global_ns",
"=",
"f",
".",
"f_globals",
"module",
"=",
"sys",
".",
"modules",
"[",
"global_ns",
"[",
"'__name__'",
"]",
... | https://github.com/khanhnamle1994/natural-language-processing/blob/01d450d5ac002b0156ef4cf93a07cb508c1bcdc5/assignment1/.env/lib/python2.7/site-packages/IPython/utils/frame.py#L92-L97 | |
sqall01/alertR | e1d1a83e54f876cc4cd7bd87387e05cb75d4dc13 | alertClientRaspberryPi/lib/update.py | python | Updater.getInstanceInformation | (self) | return self.instanceInfo | This function returns the instance information data.
:return: instance information data. | This function returns the instance information data. | [
"This",
"function",
"returns",
"the",
"instance",
"information",
"data",
"."
] | def getInstanceInformation(self) -> Dict[str, Any]:
"""
This function returns the instance information data.
:return: instance information data.
"""
self._acquireLock()
utcTimestamp = int(time.time())
if (utcTimestamp - self.lastChecked) > 60 or self.instanceInfo is None:
if not self._getInstanceInformation():
self._releaseLock()
raise ValueError("Not able to get newest instance information.")
self._releaseLock()
return self.instanceInfo | [
"def",
"getInstanceInformation",
"(",
"self",
")",
"->",
"Dict",
"[",
"str",
",",
"Any",
"]",
":",
"self",
".",
"_acquireLock",
"(",
")",
"utcTimestamp",
"=",
"int",
"(",
"time",
".",
"time",
"(",
")",
")",
"if",
"(",
"utcTimestamp",
"-",
"self",
"."... | https://github.com/sqall01/alertR/blob/e1d1a83e54f876cc4cd7bd87387e05cb75d4dc13/alertClientRaspberryPi/lib/update.py#L633-L648 | |
reviewboard/reviewboard | 7395902e4c181bcd1d633f61105012ffb1d18e1b | reviewboard/scmtools/core.py | python | SCMTool.__init__ | (self, repository) | Initialize the SCMTool.
This will be initialized on demand, when first needed by a client
working with a repository. It will generally be bound to the lifetime
of the repository instance.
Args:
repository (reviewboard.scmtools.models.Repository):
The repository owning this SCMTool. | Initialize the SCMTool. | [
"Initialize",
"the",
"SCMTool",
"."
] | def __init__(self, repository):
"""Initialize the SCMTool.
This will be initialized on demand, when first needed by a client
working with a repository. It will generally be bound to the lifetime
of the repository instance.
Args:
repository (reviewboard.scmtools.models.Repository):
The repository owning this SCMTool.
"""
self.repository = repository | [
"def",
"__init__",
"(",
"self",
",",
"repository",
")",
":",
"self",
".",
"repository",
"=",
"repository"
] | https://github.com/reviewboard/reviewboard/blob/7395902e4c181bcd1d633f61105012ffb1d18e1b/reviewboard/scmtools/core.py#L752-L763 | ||
kubernetes-client/python | 47b9da9de2d02b2b7a34fbe05afb44afd130d73a | kubernetes/client/models/v1_deployment_status.py | python | V1DeploymentStatus.__eq__ | (self, other) | return self.to_dict() == other.to_dict() | Returns true if both objects are equal | Returns true if both objects are equal | [
"Returns",
"true",
"if",
"both",
"objects",
"are",
"equal"
] | def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, V1DeploymentStatus):
return False
return self.to_dict() == other.to_dict() | [
"def",
"__eq__",
"(",
"self",
",",
"other",
")",
":",
"if",
"not",
"isinstance",
"(",
"other",
",",
"V1DeploymentStatus",
")",
":",
"return",
"False",
"return",
"self",
".",
"to_dict",
"(",
")",
"==",
"other",
".",
"to_dict",
"(",
")"
] | https://github.com/kubernetes-client/python/blob/47b9da9de2d02b2b7a34fbe05afb44afd130d73a/kubernetes/client/models/v1_deployment_status.py#L306-L311 | |
aws-samples/aws-kube-codesuite | ab4e5ce45416b83bffb947ab8d234df5437f4fca | src/kubernetes/client/models/v1beta1_subject_access_review_status.py | python | V1beta1SubjectAccessReviewStatus.__repr__ | (self) | return self.to_str() | For `print` and `pprint` | For `print` and `pprint` | [
"For",
"print",
"and",
"pprint"
] | def __repr__(self):
"""
For `print` and `pprint`
"""
return self.to_str() | [
"def",
"__repr__",
"(",
"self",
")",
":",
"return",
"self",
".",
"to_str",
"(",
")"
] | https://github.com/aws-samples/aws-kube-codesuite/blob/ab4e5ce45416b83bffb947ab8d234df5437f4fca/src/kubernetes/client/models/v1beta1_subject_access_review_status.py#L152-L156 | |
XX-net/XX-Net | a9898cfcf0084195fb7e69b6bc834e59aecdf14f | python3.8.2/Lib/email/mime/image.py | python | MIMEImage.__init__ | (self, _imagedata, _subtype=None,
_encoder=encoders.encode_base64, *, policy=None, **_params) | Create an image/* type MIME document.
_imagedata is a string containing the raw image data. If this data
can be decoded by the standard Python `imghdr' module, then the
subtype will be automatically included in the Content-Type header.
Otherwise, you can specify the specific image subtype via the _subtype
parameter.
_encoder is a function which will perform the actual encoding for
transport of the image data. It takes one argument, which is this
Image instance. It should use get_payload() and set_payload() to
change the payload to the encoded form. It should also add any
Content-Transfer-Encoding or other headers to the message as
necessary. The default encoding is Base64.
Any additional keyword arguments are passed to the base class
constructor, which turns them into parameters on the Content-Type
header. | Create an image/* type MIME document. | [
"Create",
"an",
"image",
"/",
"*",
"type",
"MIME",
"document",
"."
] | def __init__(self, _imagedata, _subtype=None,
_encoder=encoders.encode_base64, *, policy=None, **_params):
"""Create an image/* type MIME document.
_imagedata is a string containing the raw image data. If this data
can be decoded by the standard Python `imghdr' module, then the
subtype will be automatically included in the Content-Type header.
Otherwise, you can specify the specific image subtype via the _subtype
parameter.
_encoder is a function which will perform the actual encoding for
transport of the image data. It takes one argument, which is this
Image instance. It should use get_payload() and set_payload() to
change the payload to the encoded form. It should also add any
Content-Transfer-Encoding or other headers to the message as
necessary. The default encoding is Base64.
Any additional keyword arguments are passed to the base class
constructor, which turns them into parameters on the Content-Type
header.
"""
if _subtype is None:
_subtype = imghdr.what(None, _imagedata)
if _subtype is None:
raise TypeError('Could not guess image MIME subtype')
MIMENonMultipart.__init__(self, 'image', _subtype, policy=policy,
**_params)
self.set_payload(_imagedata)
_encoder(self) | [
"def",
"__init__",
"(",
"self",
",",
"_imagedata",
",",
"_subtype",
"=",
"None",
",",
"_encoder",
"=",
"encoders",
".",
"encode_base64",
",",
"*",
",",
"policy",
"=",
"None",
",",
"*",
"*",
"_params",
")",
":",
"if",
"_subtype",
"is",
"None",
":",
"_... | https://github.com/XX-net/XX-Net/blob/a9898cfcf0084195fb7e69b6bc834e59aecdf14f/python3.8.2/Lib/email/mime/image.py#L19-L47 | ||
mypaint/mypaint | 90b36dbc7b8bd2f323383f7edf608a5e0a3a1a33 | gui/compatibility.py | python | update_default_layer_type | (app) | Update default layer type from settings | Update default layer type from settings | [
"Update",
"default",
"layer",
"type",
"from",
"settings"
] | def update_default_layer_type(app):
"""Update default layer type from settings
"""
prefs = app.preferences
mode_settings = prefs[COMPAT_SETTINGS][app.compat_mode]
if mode_settings[config.PIGMENT_LAYER_BY_DEFAULT]:
logger.info("Setting default layer type to Pigment")
set_default_mode(CombineSpectralWGM)
else:
logger.info("Setting default layer type to Normal")
set_default_mode(CombineNormal) | [
"def",
"update_default_layer_type",
"(",
"app",
")",
":",
"prefs",
"=",
"app",
".",
"preferences",
"mode_settings",
"=",
"prefs",
"[",
"COMPAT_SETTINGS",
"]",
"[",
"app",
".",
"compat_mode",
"]",
"if",
"mode_settings",
"[",
"config",
".",
"PIGMENT_LAYER_BY_DEFAU... | https://github.com/mypaint/mypaint/blob/90b36dbc7b8bd2f323383f7edf608a5e0a3a1a33/gui/compatibility.py#L456-L466 | ||
catalyst-team/catalyst | 678dc06eda1848242df010b7f34adb572def2598 | catalyst/engines/xla.py | python | DistributedXLAEngine.sync_tensor | (self, tensor: torch.Tensor, mode: str) | Syncs ``tensor`` over ``world_size`` in distributed mode.
Args:
tensor: tensor to sync across the processes.
mode: tensor synchronization type,
should be one of 'sum' or 'mean'.
Default is 'mean'.
Returns:
torch.Tensor with synchronized values.
Raises:
ValueError: if mode is out of ``sum``, ``mean``. | Syncs ``tensor`` over ``world_size`` in distributed mode. | [
"Syncs",
"tensor",
"over",
"world_size",
"in",
"distributed",
"mode",
"."
] | def sync_tensor(self, tensor: torch.Tensor, mode: str) -> torch.Tensor:
"""Syncs ``tensor`` over ``world_size`` in distributed mode.
Args:
tensor: tensor to sync across the processes.
mode: tensor synchronization type,
should be one of 'sum' or 'mean'.
Default is 'mean'.
Returns:
torch.Tensor with synchronized values.
Raises:
ValueError: if mode is out of ``sum``, ``mean``.
"""
# return tensor
if mode not in {"sum", "mean"}:
raise ValueError(f"Unknown sync_type '{mode}'")
if mode == "sum":
return xm.all_reduce("sum", tensor)
elif mode == "mean":
return xm.all_reduce("sum", tensor, scale=1.0 / self.world_size) | [
"def",
"sync_tensor",
"(",
"self",
",",
"tensor",
":",
"torch",
".",
"Tensor",
",",
"mode",
":",
"str",
")",
"->",
"torch",
".",
"Tensor",
":",
"# return tensor",
"if",
"mode",
"not",
"in",
"{",
"\"sum\"",
",",
"\"mean\"",
"}",
":",
"raise",
"ValueErro... | https://github.com/catalyst-team/catalyst/blob/678dc06eda1848242df010b7f34adb572def2598/catalyst/engines/xla.py#L378-L399 | ||
wardbradt/peregrine | 685c60237926e54181866cd0ded8c4199a3c6fa2 | peregrinearb/async_build_markets.py | python | SpecificCollectionBuilder.__init__ | (self, blacklist=False, **kwargs) | **kwargs should restrict acceptable exchanges. Only acceptable keys and values are strings. Look at this part of
the ccxt manual: https://github.com/ccxt/ccxt/wiki/Manual#user-content-exchange-structure for insight into what
are acceptable rules.
When a value in kwargs is a list x, SpecificCollectionBuilder builds a collection of exchanges in which
the property (designated by the key corresponding to x) contains all elements in x.
When a value in kwargs is a dict x, SpecificCollectionBuilder builds a collection of exchanges in which the
specified property (designated by the key corresponding to x) is a dict and contains all key/ value pairs in x.
Typical use case for **kwargs is 'countries' as a key and Australia, Bulgaria, Brazil, British Virgin
Islands, Canada, China, Czech Republic, EU, Germany, Hong Kong, Iceland, India, Indonesia, Israel, Japan,
Mexico, New Zealand, Panama, Philippines, Poland, Russia, Seychelles, Singapore, South Korea,
St. Vincent & Grenadines, Sweden, Tanzania, Thailand, Turkey, US, UK, Ukraine, or Vietnam as a value. | **kwargs should restrict acceptable exchanges. Only acceptable keys and values are strings. Look at this part of
the ccxt manual: https://github.com/ccxt/ccxt/wiki/Manual#user-content-exchange-structure for insight into what
are acceptable rules. | [
"**",
"kwargs",
"should",
"restrict",
"acceptable",
"exchanges",
".",
"Only",
"acceptable",
"keys",
"and",
"values",
"are",
"strings",
".",
"Look",
"at",
"this",
"part",
"of",
"the",
"ccxt",
"manual",
":",
"https",
":",
"//",
"github",
".",
"com",
"/",
"... | def __init__(self, blacklist=False, **kwargs):
"""
**kwargs should restrict acceptable exchanges. Only acceptable keys and values are strings. Look at this part of
the ccxt manual: https://github.com/ccxt/ccxt/wiki/Manual#user-content-exchange-structure for insight into what
are acceptable rules.
When a value in kwargs is a list x, SpecificCollectionBuilder builds a collection of exchanges in which
the property (designated by the key corresponding to x) contains all elements in x.
When a value in kwargs is a dict x, SpecificCollectionBuilder builds a collection of exchanges in which the
specified property (designated by the key corresponding to x) is a dict and contains all key/ value pairs in x.
Typical use case for **kwargs is 'countries' as a key and Australia, Bulgaria, Brazil, British Virgin
Islands, Canada, China, Czech Republic, EU, Germany, Hong Kong, Iceland, India, Indonesia, Israel, Japan,
Mexico, New Zealand, Panama, Philippines, Poland, Russia, Seychelles, Singapore, South Korea,
St. Vincent & Grenadines, Sweden, Tanzania, Thailand, Turkey, US, UK, Ukraine, or Vietnam as a value.
"""
super().__init__()
self.rules = kwargs
self.blacklist = blacklist | [
"def",
"__init__",
"(",
"self",
",",
"blacklist",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"super",
"(",
")",
".",
"__init__",
"(",
")",
"self",
".",
"rules",
"=",
"kwargs",
"self",
".",
"blacklist",
"=",
"blacklist"
] | https://github.com/wardbradt/peregrine/blob/685c60237926e54181866cd0ded8c4199a3c6fa2/peregrinearb/async_build_markets.py#L139-L158 | ||
eugene-eeo/graphlite | 8d17e9549ee8610570dcde1b427431a2584395b7 | graphlite/sql.py | python | limit | (lower, upper) | return smt, () | Returns a SQlite-compliant LIMIT statement that
takes the *lower* and *upper* bounds into account.
:param lower: The lower bound.
:param upper: The upper bound. | Returns a SQlite-compliant LIMIT statement that
takes the *lower* and *upper* bounds into account. | [
"Returns",
"a",
"SQlite",
"-",
"compliant",
"LIMIT",
"statement",
"that",
"takes",
"the",
"*",
"lower",
"*",
"and",
"*",
"upper",
"*",
"bounds",
"into",
"account",
"."
] | def limit(lower, upper):
"""
Returns a SQlite-compliant LIMIT statement that
takes the *lower* and *upper* bounds into account.
:param lower: The lower bound.
:param upper: The upper bound.
"""
offset = lower or 0
lim = (upper - offset) if upper else -1
smt = 'LIMIT %d OFFSET %d' % (lim, offset)
return smt, () | [
"def",
"limit",
"(",
"lower",
",",
"upper",
")",
":",
"offset",
"=",
"lower",
"or",
"0",
"lim",
"=",
"(",
"upper",
"-",
"offset",
")",
"if",
"upper",
"else",
"-",
"1",
"smt",
"=",
"'LIMIT %d OFFSET %d'",
"%",
"(",
"lim",
",",
"offset",
")",
"return... | https://github.com/eugene-eeo/graphlite/blob/8d17e9549ee8610570dcde1b427431a2584395b7/graphlite/sql.py#L120-L131 | |
frappe/erpnext | 9d36e30ef7043b391b5ed2523b8288bf46c45d18 | erpnext/stock/get_item_details.py | python | get_item_price | (args, item_code, ignore_party=False) | return frappe.db.sql(""" select name, price_list_rate, uom
from `tabItem Price` {conditions}
order by valid_from desc, batch_no desc, uom desc """.format(conditions=conditions), args) | Get name, price_list_rate from Item Price based on conditions
Check if the desired qty is within the increment of the packing list.
:param args: dict (or frappe._dict) with mandatory fields price_list, uom
optional fields transaction_date, customer, supplier
:param item_code: str, Item Doctype field item_code | Get name, price_list_rate from Item Price based on conditions
Check if the desired qty is within the increment of the packing list.
:param args: dict (or frappe._dict) with mandatory fields price_list, uom
optional fields transaction_date, customer, supplier
:param item_code: str, Item Doctype field item_code | [
"Get",
"name",
"price_list_rate",
"from",
"Item",
"Price",
"based",
"on",
"conditions",
"Check",
"if",
"the",
"desired",
"qty",
"is",
"within",
"the",
"increment",
"of",
"the",
"packing",
"list",
".",
":",
"param",
"args",
":",
"dict",
"(",
"or",
"frappe",... | def get_item_price(args, item_code, ignore_party=False):
"""
Get name, price_list_rate from Item Price based on conditions
Check if the desired qty is within the increment of the packing list.
:param args: dict (or frappe._dict) with mandatory fields price_list, uom
optional fields transaction_date, customer, supplier
:param item_code: str, Item Doctype field item_code
"""
args['item_code'] = item_code
conditions = """where item_code=%(item_code)s
and price_list=%(price_list)s
and ifnull(uom, '') in ('', %(uom)s)"""
conditions += "and ifnull(batch_no, '') in ('', %(batch_no)s)"
if not ignore_party:
if args.get("customer"):
conditions += " and customer=%(customer)s"
elif args.get("supplier"):
conditions += " and supplier=%(supplier)s"
else:
conditions += "and (customer is null or customer = '') and (supplier is null or supplier = '')"
if args.get('transaction_date'):
conditions += """ and %(transaction_date)s between
ifnull(valid_from, '2000-01-01') and ifnull(valid_upto, '2500-12-31')"""
if args.get('posting_date'):
conditions += """ and %(posting_date)s between
ifnull(valid_from, '2000-01-01') and ifnull(valid_upto, '2500-12-31')"""
return frappe.db.sql(""" select name, price_list_rate, uom
from `tabItem Price` {conditions}
order by valid_from desc, batch_no desc, uom desc """.format(conditions=conditions), args) | [
"def",
"get_item_price",
"(",
"args",
",",
"item_code",
",",
"ignore_party",
"=",
"False",
")",
":",
"args",
"[",
"'item_code'",
"]",
"=",
"item_code",
"conditions",
"=",
"\"\"\"where item_code=%(item_code)s\n\t\tand price_list=%(price_list)s\n\t\tand ifnull(uom, '') in ('', ... | https://github.com/frappe/erpnext/blob/9d36e30ef7043b391b5ed2523b8288bf46c45d18/erpnext/stock/get_item_details.py#L727-L762 | |
leancloud/satori | 701caccbd4fe45765001ca60435c0cb499477c03 | satori-rules/plugin/libs/requests/cookies.py | python | MockRequest.get_header | (self, name, default=None) | return self._r.headers.get(name, self._new_headers.get(name, default)) | [] | def get_header(self, name, default=None):
return self._r.headers.get(name, self._new_headers.get(name, default)) | [
"def",
"get_header",
"(",
"self",
",",
"name",
",",
"default",
"=",
"None",
")",
":",
"return",
"self",
".",
"_r",
".",
"headers",
".",
"get",
"(",
"name",
",",
"self",
".",
"_new_headers",
".",
"get",
"(",
"name",
",",
"default",
")",
")"
] | https://github.com/leancloud/satori/blob/701caccbd4fe45765001ca60435c0cb499477c03/satori-rules/plugin/libs/requests/cookies.py#L69-L70 | |||
volatilityfoundation/volatility | a438e768194a9e05eb4d9ee9338b881c0fa25937 | volatility/plugins/gui/win32k_core.py | python | tagWINDOWSTATION.Name | (self) | return str(object_hdr.NameInfo.Name or '') | Get the window station name.
Since window stations are securable objects,
and are managed by the same object manager as
processes, threads, etc, there is an object
header which stores the name. | Get the window station name. | [
"Get",
"the",
"window",
"station",
"name",
"."
] | def Name(self):
"""Get the window station name.
Since window stations are securable objects,
and are managed by the same object manager as
processes, threads, etc, there is an object
header which stores the name.
"""
object_hdr = obj.Object("_OBJECT_HEADER",
vm = self.obj_vm, offset = self.obj_offset - \
self.obj_vm.profile.get_obj_offset('_OBJECT_HEADER', 'Body'),
native_vm = self.obj_native_vm)
return str(object_hdr.NameInfo.Name or '') | [
"def",
"Name",
"(",
"self",
")",
":",
"object_hdr",
"=",
"obj",
".",
"Object",
"(",
"\"_OBJECT_HEADER\"",
",",
"vm",
"=",
"self",
".",
"obj_vm",
",",
"offset",
"=",
"self",
".",
"obj_offset",
"-",
"self",
".",
"obj_vm",
".",
"profile",
".",
"get_obj_of... | https://github.com/volatilityfoundation/volatility/blob/a438e768194a9e05eb4d9ee9338b881c0fa25937/volatility/plugins/gui/win32k_core.py#L355-L369 | |
tomplus/kubernetes_asyncio | f028cc793e3a2c519be6a52a49fb77ff0b014c9b | kubernetes_asyncio/client/api/networking_v1_api.py | python | NetworkingV1Api.delete_namespaced_network_policy_with_http_info | (self, name, namespace, **kwargs) | return self.api_client.call_api(
'/apis/networking.k8s.io/v1/namespaces/{namespace}/networkpolicies/{name}', 'DELETE',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1Status', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats) | delete_namespaced_network_policy # noqa: E501
delete a NetworkPolicy # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.delete_namespaced_network_policy_with_http_info(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the NetworkPolicy (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately.
:param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both.
:param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground.
:param V1DeleteOptions body:
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1Status, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread. | delete_namespaced_network_policy # noqa: E501 | [
"delete_namespaced_network_policy",
"#",
"noqa",
":",
"E501"
] | def delete_namespaced_network_policy_with_http_info(self, name, namespace, **kwargs): # noqa: E501
"""delete_namespaced_network_policy # noqa: E501
delete a NetworkPolicy # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.delete_namespaced_network_policy_with_http_info(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the NetworkPolicy (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately.
:param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both.
:param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground.
:param V1DeleteOptions body:
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1Status, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'namespace',
'pretty',
'dry_run',
'grace_period_seconds',
'orphan_dependents',
'propagation_policy',
'body'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method delete_namespaced_network_policy" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `delete_namespaced_network_policy`") # noqa: E501
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `delete_namespaced_network_policy`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501
query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501
if 'grace_period_seconds' in local_var_params and local_var_params['grace_period_seconds'] is not None: # noqa: E501
query_params.append(('gracePeriodSeconds', local_var_params['grace_period_seconds'])) # noqa: E501
if 'orphan_dependents' in local_var_params and local_var_params['orphan_dependents'] is not None: # noqa: E501
query_params.append(('orphanDependents', local_var_params['orphan_dependents'])) # noqa: E501
if 'propagation_policy' in local_var_params and local_var_params['propagation_policy'] is not None: # noqa: E501
query_params.append(('propagationPolicy', local_var_params['propagation_policy'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/apis/networking.k8s.io/v1/namespaces/{namespace}/networkpolicies/{name}', 'DELETE',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1Status', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats) | [
"def",
"delete_namespaced_network_policy_with_http_info",
"(",
"self",
",",
"name",
",",
"namespace",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"local_var_params",
"=",
"locals",
"(",
")",
"all_params",
"=",
"[",
"'name'",
",",
"'namespace'",
",",
"'pre... | https://github.com/tomplus/kubernetes_asyncio/blob/f028cc793e3a2c519be6a52a49fb77ff0b014c9b/kubernetes_asyncio/client/api/networking_v1_api.py#L1301-L1420 | |
NiaOrg/NiaPy | 08f24ffc79fe324bc9c66ee7186ef98633026005 | niapy/algorithms/basic/ba.py | python | BatAlgorithm.get_parameters | (self) | return d | r"""Get parameters of the algorithm.
Returns:
Dict[str, Any]: Algorithm parameters. | r"""Get parameters of the algorithm. | [
"r",
"Get",
"parameters",
"of",
"the",
"algorithm",
"."
] | def get_parameters(self):
r"""Get parameters of the algorithm.
Returns:
Dict[str, Any]: Algorithm parameters.
"""
d = super().get_parameters()
d.update({
'loudness': self.loudness,
'pulse_rate': self.pulse_rate,
'alpha': self.alpha,
'gamma': self.gamma,
'min_frequency': self.min_frequency,
'max_frequency': self.max_frequency
})
return d | [
"def",
"get_parameters",
"(",
"self",
")",
":",
"d",
"=",
"super",
"(",
")",
".",
"get_parameters",
"(",
")",
"d",
".",
"update",
"(",
"{",
"'loudness'",
":",
"self",
".",
"loudness",
",",
"'pulse_rate'",
":",
"self",
".",
"pulse_rate",
",",
"'alpha'",... | https://github.com/NiaOrg/NiaPy/blob/08f24ffc79fe324bc9c66ee7186ef98633026005/niapy/algorithms/basic/ba.py#L112-L128 | |
zenodo/zenodo | 3c45e52a742ad5a0a7788a67b02fbbc15ab4d8d5 | zenodo/modules/auditor/api.py | python | Check.is_ok | (self) | return not bool(self.issues) | Get if check is considered passed. | Get if check is considered passed. | [
"Get",
"if",
"check",
"is",
"considered",
"passed",
"."
] | def is_ok(self):
"""Get if check is considered passed."""
return not bool(self.issues) | [
"def",
"is_ok",
"(",
"self",
")",
":",
"return",
"not",
"bool",
"(",
"self",
".",
"issues",
")"
] | https://github.com/zenodo/zenodo/blob/3c45e52a742ad5a0a7788a67b02fbbc15ab4d8d5/zenodo/modules/auditor/api.py#L79-L81 | |
cloudera/hue | 23f02102d4547c17c32bd5ea0eb24e9eadd657a4 | desktop/libs/azure/src/azure/abfs/__init__.py | python | get_home_dir_for_abfs | (user=None) | return remote_home_abfs | Attempts to go to the directory set in the config file or core-site.xml else defaults to abfs:// | Attempts to go to the directory set in the config file or core-site.xml else defaults to abfs:// | [
"Attempts",
"to",
"go",
"to",
"the",
"directory",
"set",
"in",
"the",
"config",
"file",
"or",
"core",
"-",
"site",
".",
"xml",
"else",
"defaults",
"to",
"abfs",
":",
"//"
] | def get_home_dir_for_abfs(user=None):
"""
Attempts to go to the directory set in the config file or core-site.xml else defaults to abfs://
"""
from desktop.models import _handle_user_dir_raz
try:
filesystem = parse_uri(get_default_abfs_fs())[0]
remote_home_abfs = "abfs://" + filesystem
except:
remote_home_abfs = 'abfs://'
# Check from remote_storage_home config only for RAZ env
if RAZ.IS_ENABLED.get() and hasattr(REMOTE_STORAGE_HOME, 'get') and REMOTE_STORAGE_HOME.get():
remote_home_abfs = REMOTE_STORAGE_HOME.get()
remote_home_abfs = _handle_user_dir_raz(user, remote_home_abfs)
return remote_home_abfs | [
"def",
"get_home_dir_for_abfs",
"(",
"user",
"=",
"None",
")",
":",
"from",
"desktop",
".",
"models",
"import",
"_handle_user_dir_raz",
"try",
":",
"filesystem",
"=",
"parse_uri",
"(",
"get_default_abfs_fs",
"(",
")",
")",
"[",
"0",
"]",
"remote_home_abfs",
"=... | https://github.com/cloudera/hue/blob/23f02102d4547c17c32bd5ea0eb24e9eadd657a4/desktop/libs/azure/src/azure/abfs/__init__.py#L173-L190 | |
python/cpython | e13cdca0f5224ec4e23bdd04bb3120506964bc8b | Lib/inspect.py | python | walktree | (classes, children, parent) | return results | Recursive helper function for getclasstree(). | Recursive helper function for getclasstree(). | [
"Recursive",
"helper",
"function",
"for",
"getclasstree",
"()",
"."
] | def walktree(classes, children, parent):
"""Recursive helper function for getclasstree()."""
results = []
classes.sort(key=attrgetter('__module__', '__name__'))
for c in classes:
results.append((c, c.__bases__))
if c in children:
results.append(walktree(children[c], children, c))
return results | [
"def",
"walktree",
"(",
"classes",
",",
"children",
",",
"parent",
")",
":",
"results",
"=",
"[",
"]",
"classes",
".",
"sort",
"(",
"key",
"=",
"attrgetter",
"(",
"'__module__'",
",",
"'__name__'",
")",
")",
"for",
"c",
"in",
"classes",
":",
"results",... | https://github.com/python/cpython/blob/e13cdca0f5224ec4e23bdd04bb3120506964bc8b/Lib/inspect.py#L1266-L1274 | |
jgagneastro/coffeegrindsize | 22661ebd21831dba4cf32bfc6ba59fe3d49f879c | App/venv/lib/python3.7/site-packages/pip/_vendor/pyparsing.py | python | replaceHTMLEntity | (t) | return _htmlEntityMap.get(t.entity) | Helper parser action to replace common HTML entities with their special characters | Helper parser action to replace common HTML entities with their special characters | [
"Helper",
"parser",
"action",
"to",
"replace",
"common",
"HTML",
"entities",
"with",
"their",
"special",
"characters"
] | def replaceHTMLEntity(t):
"""Helper parser action to replace common HTML entities with their special characters"""
return _htmlEntityMap.get(t.entity) | [
"def",
"replaceHTMLEntity",
"(",
"t",
")",
":",
"return",
"_htmlEntityMap",
".",
"get",
"(",
"t",
".",
"entity",
")"
] | https://github.com/jgagneastro/coffeegrindsize/blob/22661ebd21831dba4cf32bfc6ba59fe3d49f879c/App/venv/lib/python3.7/site-packages/pip/_vendor/pyparsing.py#L5938-L5940 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.