repo stringlengths 7 55 | path stringlengths 4 223 | url stringlengths 87 315 | code stringlengths 75 104k | code_tokens list | docstring stringlengths 1 46.9k | docstring_tokens list | language stringclasses 1
value | partition stringclasses 3
values | avg_line_len float64 7.91 980 |
|---|---|---|---|---|---|---|---|---|---|
saltstack/salt | salt/loader.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/loader.py#L1067-L1076 | def cache(opts, serial):
'''
Returns the returner modules
'''
return LazyLoader(
_module_dirs(opts, 'cache', 'cache'),
opts,
tag='cache',
pack={'__opts__': opts, '__context__': {'serial': serial}},
) | [
"def",
"cache",
"(",
"opts",
",",
"serial",
")",
":",
"return",
"LazyLoader",
"(",
"_module_dirs",
"(",
"opts",
",",
"'cache'",
",",
"'cache'",
")",
",",
"opts",
",",
"tag",
"=",
"'cache'",
",",
"pack",
"=",
"{",
"'__opts__'",
":",
"opts",
",",
"'__c... | Returns the returner modules | [
"Returns",
"the",
"returner",
"modules"
] | python | train | 24.2 |
devassistant/devassistant | devassistant/gui/gui_helper.py | https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/gui/gui_helper.py#L138-L144 | def create_button(self, style=Gtk.ReliefStyle.NORMAL):
"""
This is generalized method for creating Gtk.Button
"""
btn = Gtk.Button()
btn.set_relief(style)
return btn | [
"def",
"create_button",
"(",
"self",
",",
"style",
"=",
"Gtk",
".",
"ReliefStyle",
".",
"NORMAL",
")",
":",
"btn",
"=",
"Gtk",
".",
"Button",
"(",
")",
"btn",
".",
"set_relief",
"(",
"style",
")",
"return",
"btn"
] | This is generalized method for creating Gtk.Button | [
"This",
"is",
"generalized",
"method",
"for",
"creating",
"Gtk",
".",
"Button"
] | python | train | 29.571429 |
coded-by-hand/mass | env/lib/python2.7/site-packages/pip-1.0.2-py2.7.egg/pip/util.py | https://github.com/coded-by-hand/mass/blob/59005479efed3cd8598a8f0c66791a4482071899/env/lib/python2.7/site-packages/pip-1.0.2-py2.7.egg/pip/util.py#L321-L332 | def dist_location(dist):
"""
Get the site-packages location of this distribution. Generally
this is dist.location, except in the case of develop-installed
packages, where dist.location is the source code location, and we
want to know where the egg-link file is.
"""
egg_link = egg_link_path(... | [
"def",
"dist_location",
"(",
"dist",
")",
":",
"egg_link",
"=",
"egg_link_path",
"(",
"dist",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"egg_link",
")",
":",
"return",
"egg_link",
"return",
"dist",
".",
"location"
] | Get the site-packages location of this distribution. Generally
this is dist.location, except in the case of develop-installed
packages, where dist.location is the source code location, and we
want to know where the egg-link file is. | [
"Get",
"the",
"site",
"-",
"packages",
"location",
"of",
"this",
"distribution",
".",
"Generally",
"this",
"is",
"dist",
".",
"location",
"except",
"in",
"the",
"case",
"of",
"develop",
"-",
"installed",
"packages",
"where",
"dist",
".",
"location",
"is",
... | python | train | 33 |
google/mobly | mobly/controllers/monsoon.py | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controllers/monsoon.py#L290-L298 | def SetMaxCurrent(self, i):
"""Set the max output current.
"""
if i < 0 or i > 8:
raise MonsoonError(("Target max current %sA, is out of acceptable "
"range [0, 8].") % i)
val = 1023 - int((i / 8) * 1023)
self._SendStruct("BBB", 0x01, 0... | [
"def",
"SetMaxCurrent",
"(",
"self",
",",
"i",
")",
":",
"if",
"i",
"<",
"0",
"or",
"i",
">",
"8",
":",
"raise",
"MonsoonError",
"(",
"(",
"\"Target max current %sA, is out of acceptable \"",
"\"range [0, 8].\"",
")",
"%",
"i",
")",
"val",
"=",
"1023",
"-"... | Set the max output current. | [
"Set",
"the",
"max",
"output",
"current",
"."
] | python | train | 42.444444 |
linkhub-sdk/popbill.py | popbill/cashbillService.py | https://github.com/linkhub-sdk/popbill.py/blob/68a0dd7f7a937603318e93be321fde73c50b96cc/popbill/cashbillService.py#L304-L351 | def search(self, CorpNum, DType, SDate, EDate, State, TradeType, TradeUsage, TaxationType, Page, PerPage, Order,
UserID=None, QString=None, TradeOpt=None):
""" λͺ©λ‘ μ‘°ν
args
CorpNum : νλΉνμ μ¬μ
μλ²νΈ
DType : μΌμμ ν, R-λ±λ‘μΌμ, T-κ±°λμΌμ, I-λ°νμΌμ μ€ ν 1
... | [
"def",
"search",
"(",
"self",
",",
"CorpNum",
",",
"DType",
",",
"SDate",
",",
"EDate",
",",
"State",
",",
"TradeType",
",",
"TradeUsage",
",",
"TaxationType",
",",
"Page",
",",
"PerPage",
",",
"Order",
",",
"UserID",
"=",
"None",
",",
"QString",
"=",
... | λͺ©λ‘ μ‘°ν
args
CorpNum : νλΉνμ μ¬μ
μλ²νΈ
DType : μΌμμ ν, R-λ±λ‘μΌμ, T-κ±°λμΌμ, I-λ°νμΌμ μ€ ν 1
SDate : μμμΌμ, νμνμ(yyyyMMdd)
EDate : μ’
λ£μΌμ, νμνμ(yyyyMMdd)
State : μνμ½λ λ°°μ΄, 2,3λ²μ§Έ μ리μ μμΌλμΉ΄λ(*) μ¬μ©κ°λ₯
TradeType : λ¬Έμνν λ°°μ΄, N-μΌλ°νκΈμμμ¦,... | [
"λͺ©λ‘",
"μ‘°ν",
"args",
"CorpNum",
":",
"νλΉνμ",
"μ¬μ
μλ²νΈ",
"DType",
":",
"μΌμμ ν",
"R",
"-",
"λ±λ‘μΌμ",
"T",
"-",
"κ±°λμΌμ",
"I",
"-",
"λ°νμΌμ",
"μ€",
"ν",
"1",
"SDate",
":",
"μμμΌμ",
"νμνμ",
"(",
"yyyyMMdd",
")",
"EDate",
":",
"μ’
λ£μΌμ",
"νμνμ",
"(",
"yyyyMMdd",
")"... | python | train | 38.729167 |
apache/spark | python/pyspark/sql/streaming.py | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/sql/streaming.py#L811-L825 | def queryName(self, queryName):
"""Specifies the name of the :class:`StreamingQuery` that can be started with
:func:`start`. This name must be unique among all the currently active queries
in the associated SparkSession.
.. note:: Evolving.
:param queryName: unique name for the... | [
"def",
"queryName",
"(",
"self",
",",
"queryName",
")",
":",
"if",
"not",
"queryName",
"or",
"type",
"(",
"queryName",
")",
"!=",
"str",
"or",
"len",
"(",
"queryName",
".",
"strip",
"(",
")",
")",
"==",
"0",
":",
"raise",
"ValueError",
"(",
"'The que... | Specifies the name of the :class:`StreamingQuery` that can be started with
:func:`start`. This name must be unique among all the currently active queries
in the associated SparkSession.
.. note:: Evolving.
:param queryName: unique name for the query
>>> writer = sdf.writeStrea... | [
"Specifies",
"the",
"name",
"of",
"the",
":",
"class",
":",
"StreamingQuery",
"that",
"can",
"be",
"started",
"with",
":",
"func",
":",
"start",
".",
"This",
"name",
"must",
"be",
"unique",
"among",
"all",
"the",
"currently",
"active",
"queries",
"in",
"... | python | train | 43 |
DistrictDataLabs/yellowbrick | yellowbrick/base.py | https://github.com/DistrictDataLabs/yellowbrick/blob/59b67236a3862c73363e8edad7cd86da5b69e3b2/yellowbrick/base.py#L236-L247 | def set_title(self, title=None):
"""
Sets the title on the current axes.
Parameters
----------
title: string, default: None
Add title to figure or if None leave untitled.
"""
title = self.title or title
if title is not None:
self.a... | [
"def",
"set_title",
"(",
"self",
",",
"title",
"=",
"None",
")",
":",
"title",
"=",
"self",
".",
"title",
"or",
"title",
"if",
"title",
"is",
"not",
"None",
":",
"self",
".",
"ax",
".",
"set_title",
"(",
"title",
")"
] | Sets the title on the current axes.
Parameters
----------
title: string, default: None
Add title to figure or if None leave untitled. | [
"Sets",
"the",
"title",
"on",
"the",
"current",
"axes",
"."
] | python | train | 27.25 |
andreikop/qutepart | qutepart/syntax/__init__.py | https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/syntax/__init__.py#L205-L212 | def _getSyntaxByFirstLine(self, firstLine):
"""Get syntax by first line of the file
"""
for pattern, xmlFileName in self._firstLineToXmlFileName.items():
if fnmatch.fnmatch(firstLine, pattern):
return self._getSyntaxByXmlFileName(xmlFileName)
else:
... | [
"def",
"_getSyntaxByFirstLine",
"(",
"self",
",",
"firstLine",
")",
":",
"for",
"pattern",
",",
"xmlFileName",
"in",
"self",
".",
"_firstLineToXmlFileName",
".",
"items",
"(",
")",
":",
"if",
"fnmatch",
".",
"fnmatch",
"(",
"firstLine",
",",
"pattern",
")",
... | Get syntax by first line of the file | [
"Get",
"syntax",
"by",
"first",
"line",
"of",
"the",
"file"
] | python | train | 44.75 |
merll/docker-map | dockermap/map/runner/base.py | https://github.com/merll/docker-map/blob/e14fe86a6ff5c33d121eb2f9157e9359cb80dd02/dockermap/map/runner/base.py#L450-L465 | def get_network_remove_kwargs(self, action, network_name, kwargs=None):
"""
Generates keyword arguments for the Docker client to remove a network.
:param action: Action configuration.
:type action: ActionConfig
:param network_name: Network name or id.
:type network_name:... | [
"def",
"get_network_remove_kwargs",
"(",
"self",
",",
"action",
",",
"network_name",
",",
"kwargs",
"=",
"None",
")",
":",
"c_kwargs",
"=",
"dict",
"(",
"net_id",
"=",
"network_name",
")",
"update_kwargs",
"(",
"c_kwargs",
",",
"kwargs",
")",
"return",
"c_kw... | Generates keyword arguments for the Docker client to remove a network.
:param action: Action configuration.
:type action: ActionConfig
:param network_name: Network name or id.
:type network_name: unicode | str
:param kwargs: Additional keyword arguments to complement or override... | [
"Generates",
"keyword",
"arguments",
"for",
"the",
"Docker",
"client",
"to",
"remove",
"a",
"network",
"."
] | python | train | 40.25 |
basho/riak-python-client | riak/codecs/pbuf.py | https://github.com/basho/riak-python-client/blob/91de13a16607cdf553d1a194e762734e3bec4231/riak/codecs/pbuf.py#L758-L787 | def encode_timeseries_put(self, tsobj):
"""
Fills an TsPutReq message with the appropriate data and
metadata from a TsObject.
:param tsobj: a TsObject
:type tsobj: TsObject
:param req: the protobuf message to fill
:type req: riak.pb.riak_ts_pb2.TsPutReq
"... | [
"def",
"encode_timeseries_put",
"(",
"self",
",",
"tsobj",
")",
":",
"req",
"=",
"riak",
".",
"pb",
".",
"riak_ts_pb2",
".",
"TsPutReq",
"(",
")",
"req",
".",
"table",
"=",
"str_to_bytes",
"(",
"tsobj",
".",
"table",
".",
"name",
")",
"if",
"tsobj",
... | Fills an TsPutReq message with the appropriate data and
metadata from a TsObject.
:param tsobj: a TsObject
:type tsobj: TsObject
:param req: the protobuf message to fill
:type req: riak.pb.riak_ts_pb2.TsPutReq | [
"Fills",
"an",
"TsPutReq",
"message",
"with",
"the",
"appropriate",
"data",
"and",
"metadata",
"from",
"a",
"TsObject",
"."
] | python | train | 38 |
bhmm/bhmm | bhmm/_external/sklearn/mixture/gmm.py | https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/_external/sklearn/mixture/gmm.py#L285-L322 | def score_samples(self, X):
"""Return the per-sample likelihood of the data under the model.
Compute the log probability of X under the model and
return the posterior distribution (responsibilities) of each
mixture component for each element of X.
Parameters
----------
... | [
"def",
"score_samples",
"(",
"self",
",",
"X",
")",
":",
"check_is_fitted",
"(",
"self",
",",
"'means_'",
")",
"X",
"=",
"check_array",
"(",
"X",
")",
"if",
"X",
".",
"ndim",
"==",
"1",
":",
"X",
"=",
"X",
"[",
":",
",",
"np",
".",
"newaxis",
"... | Return the per-sample likelihood of the data under the model.
Compute the log probability of X under the model and
return the posterior distribution (responsibilities) of each
mixture component for each element of X.
Parameters
----------
X: array_like, shape (n_samples... | [
"Return",
"the",
"per",
"-",
"sample",
"likelihood",
"of",
"the",
"data",
"under",
"the",
"model",
"."
] | python | train | 37.763158 |
secdev/scapy | scapy/layers/tls/record.py | https://github.com/secdev/scapy/blob/3ffe757c184017dd46464593a8f80f85abc1e79a/scapy/layers/tls/record.py#L543-L555 | def _tls_auth_encrypt(self, s):
"""
Return the TLSCiphertext.fragment for AEAD ciphers, i.e. the whole
GenericAEADCipher. Also, the additional data is computed right here.
"""
write_seq_num = struct.pack("!Q", self.tls_session.wcs.seq_num)
self.tls_session.wcs.seq_num += ... | [
"def",
"_tls_auth_encrypt",
"(",
"self",
",",
"s",
")",
":",
"write_seq_num",
"=",
"struct",
".",
"pack",
"(",
"\"!Q\"",
",",
"self",
".",
"tls_session",
".",
"wcs",
".",
"seq_num",
")",
"self",
".",
"tls_session",
".",
"wcs",
".",
"seq_num",
"+=",
"1"... | Return the TLSCiphertext.fragment for AEAD ciphers, i.e. the whole
GenericAEADCipher. Also, the additional data is computed right here. | [
"Return",
"the",
"TLSCiphertext",
".",
"fragment",
"for",
"AEAD",
"ciphers",
"i",
".",
"e",
".",
"the",
"whole",
"GenericAEADCipher",
".",
"Also",
"the",
"additional",
"data",
"is",
"computed",
"right",
"here",
"."
] | python | train | 48.076923 |
pypa/pipenv | pipenv/vendor/cerberus/errors.py | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/cerberus/errors.py#L407-L431 | def encode_unicode(f):
"""Cerberus error messages expect regular binary strings.
If unicode is used in a ValidationError message can't be printed.
This decorator ensures that if legacy Python is used unicode
strings are encoded before passing to a function.
"""
@wraps(f)
def wrapped(obj, er... | [
"def",
"encode_unicode",
"(",
"f",
")",
":",
"@",
"wraps",
"(",
"f",
")",
"def",
"wrapped",
"(",
"obj",
",",
"error",
")",
":",
"def",
"_encode",
"(",
"value",
")",
":",
"\"\"\"Helper encoding unicode strings into binary utf-8\"\"\"",
"if",
"isinstance",
"(",
... | Cerberus error messages expect regular binary strings.
If unicode is used in a ValidationError message can't be printed.
This decorator ensures that if legacy Python is used unicode
strings are encoded before passing to a function. | [
"Cerberus",
"error",
"messages",
"expect",
"regular",
"binary",
"strings",
".",
"If",
"unicode",
"is",
"used",
"in",
"a",
"ValidationError",
"message",
"can",
"t",
"be",
"printed",
"."
] | python | train | 35.32 |
BernardFW/bernard | src/bernard/storage/register/redis.py | https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/storage/register/redis.py#L82-L88 | async def _replace(self, key: Text, data: Dict[Text, Any]) -> None:
"""
Replace the register with a new value.
"""
with await self.pool as r:
await r.set(self.register_key(key), ujson.dumps(data)) | [
"async",
"def",
"_replace",
"(",
"self",
",",
"key",
":",
"Text",
",",
"data",
":",
"Dict",
"[",
"Text",
",",
"Any",
"]",
")",
"->",
"None",
":",
"with",
"await",
"self",
".",
"pool",
"as",
"r",
":",
"await",
"r",
".",
"set",
"(",
"self",
".",
... | Replace the register with a new value. | [
"Replace",
"the",
"register",
"with",
"a",
"new",
"value",
"."
] | python | train | 33.571429 |
Jaymon/prom | prom/cli/generate.py | https://github.com/Jaymon/prom/blob/b7ad2c259eca198da03e1e4bc7d95014c168c361/prom/cli/generate.py#L50-L84 | def main_generate(table_names, stream):
"""This will print out valid prom python code for given tables that already exist
in a database.
This is really handy when you want to bootstrap an existing database to work
with prom and don't want to manually create Orm objects for the tables you want
to us... | [
"def",
"main_generate",
"(",
"table_names",
",",
"stream",
")",
":",
"with",
"stream",
".",
"open",
"(",
")",
"as",
"fp",
":",
"fp",
".",
"write_line",
"(",
"\"from datetime import datetime, date\"",
")",
"fp",
".",
"write_line",
"(",
"\"from decimal import Deci... | This will print out valid prom python code for given tables that already exist
in a database.
This is really handy when you want to bootstrap an existing database to work
with prom and don't want to manually create Orm objects for the tables you want
to use, let `generate` do it for you | [
"This",
"will",
"print",
"out",
"valid",
"prom",
"python",
"code",
"for",
"given",
"tables",
"that",
"already",
"exist",
"in",
"a",
"database",
"."
] | python | train | 43.314286 |
Karaage-Cluster/python-tldap | tldap/database/__init__.py | https://github.com/Karaage-Cluster/python-tldap/blob/61f1af74a3648cb6491e7eeb1ee2eb395d67bf59/tldap/database/__init__.py#L448-L475 | def search(table: LdapObjectClass, query: Optional[Q] = None,
database: Optional[Database] = None, base_dn: Optional[str] = None) -> Iterator[LdapObject]:
""" Search for a object of given type in the database. """
fields = table.get_fields()
db_fields = {
name: field
for name, fie... | [
"def",
"search",
"(",
"table",
":",
"LdapObjectClass",
",",
"query",
":",
"Optional",
"[",
"Q",
"]",
"=",
"None",
",",
"database",
":",
"Optional",
"[",
"Database",
"]",
"=",
"None",
",",
"base_dn",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
")",... | Search for a object of given type in the database. | [
"Search",
"for",
"a",
"object",
"of",
"given",
"type",
"in",
"the",
"database",
"."
] | python | train | 32.357143 |
Neurita/boyle | boyle/dicom/convert.py | https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/dicom/convert.py#L44-L102 | def add_meta_to_nii(nii_file, dicom_file, dcm_tags=''):
""" Add slice duration and acquisition times to the headers of the nifit1 files in `nii_file`.
It will add the repetition time of the DICOM file (field: {0x0018, 0x0080, DS, Repetition Time})
to the NifTI file as well as any other tag in `dcm_tags`.
... | [
"def",
"add_meta_to_nii",
"(",
"nii_file",
",",
"dicom_file",
",",
"dcm_tags",
"=",
"''",
")",
":",
"# Load a dicom image",
"dcmimage",
"=",
"dicom",
".",
"read_file",
"(",
"dicom_file",
")",
"# Load the nifti1 image",
"image",
"=",
"nibabel",
".",
"load",
"(",
... | Add slice duration and acquisition times to the headers of the nifit1 files in `nii_file`.
It will add the repetition time of the DICOM file (field: {0x0018, 0x0080, DS, Repetition Time})
to the NifTI file as well as any other tag in `dcm_tags`.
All selected DICOM tags values are set in the `descrip` nifti ... | [
"Add",
"slice",
"duration",
"and",
"acquisition",
"times",
"to",
"the",
"headers",
"of",
"the",
"nifit1",
"files",
"in",
"nii_file",
".",
"It",
"will",
"add",
"the",
"repetition",
"time",
"of",
"the",
"DICOM",
"file",
"(",
"field",
":",
"{",
"0x0018",
"0... | python | valid | 35.186441 |
saltstack/salt | salt/modules/pushbullet.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/pushbullet.py#L65-L84 | def push_note(device=None, title=None, body=None):
'''
Pushing a text note.
:param device: Pushbullet target device
:param title: Note title
:param body: Note body
:return: Boolean if message was sent successfully.
CLI Example:
.. code-block:: bash
salt "... | [
"def",
"push_note",
"(",
"device",
"=",
"None",
",",
"title",
"=",
"None",
",",
"body",
"=",
"None",
")",
":",
"spb",
"=",
"_SaltPushbullet",
"(",
"device",
")",
"res",
"=",
"spb",
".",
"push_note",
"(",
"title",
",",
"body",
")",
"return",
"res"
] | Pushing a text note.
:param device: Pushbullet target device
:param title: Note title
:param body: Note body
:return: Boolean if message was sent successfully.
CLI Example:
.. code-block:: bash
salt "*" pushbullet.push_note device="Chrome" title="Example title" b... | [
"Pushing",
"a",
"text",
"note",
"."
] | python | train | 23.9 |
raphaelm/django-hierarkey | hierarkey/forms.py | https://github.com/raphaelm/django-hierarkey/blob/3ca822f94fa633c9a6d5abe9c80cb1551299ae46/hierarkey/forms.py#L30-L64 | def save(self) -> None:
"""
Saves all changed values to the database.
"""
for name, field in self.fields.items():
value = self.cleaned_data[name]
if isinstance(value, UploadedFile):
# Delete old file
fname = self._s.get(name, as_typ... | [
"def",
"save",
"(",
"self",
")",
"->",
"None",
":",
"for",
"name",
",",
"field",
"in",
"self",
".",
"fields",
".",
"items",
"(",
")",
":",
"value",
"=",
"self",
".",
"cleaned_data",
"[",
"name",
"]",
"if",
"isinstance",
"(",
"value",
",",
"Uploaded... | Saves all changed values to the database. | [
"Saves",
"all",
"changed",
"values",
"to",
"the",
"database",
"."
] | python | train | 41.057143 |
ktbyers/netmiko | netmiko/base_connection.py | https://github.com/ktbyers/netmiko/blob/54e6116c0b4664de2123081937e0a9a27bdfdfea/netmiko/base_connection.py#L996-L1016 | def set_terminal_width(self, command="", delay_factor=1):
"""CLI terminals try to automatically adjust the line based on the width of the terminal.
This causes the output to get distorted when accessed programmatically.
Set terminal width to 511 which works on a broad set of devices.
:... | [
"def",
"set_terminal_width",
"(",
"self",
",",
"command",
"=",
"\"\"",
",",
"delay_factor",
"=",
"1",
")",
":",
"if",
"not",
"command",
":",
"return",
"\"\"",
"delay_factor",
"=",
"self",
".",
"select_delay_factor",
"(",
"delay_factor",
")",
"command",
"=",
... | CLI terminals try to automatically adjust the line based on the width of the terminal.
This causes the output to get distorted when accessed programmatically.
Set terminal width to 511 which works on a broad set of devices.
:param command: Command string to send to the device
:type com... | [
"CLI",
"terminals",
"try",
"to",
"automatically",
"adjust",
"the",
"line",
"based",
"on",
"the",
"width",
"of",
"the",
"terminal",
".",
"This",
"causes",
"the",
"output",
"to",
"get",
"distorted",
"when",
"accessed",
"programmatically",
"."
] | python | train | 39.666667 |
saltstack/salt | salt/utils/args.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/args.py#L72-L88 | def condition_input(args, kwargs):
'''
Return a single arg structure for the publisher to safely use
'''
ret = []
for arg in args:
if (six.PY3 and isinstance(arg, six.integer_types) and salt.utils.jid.is_jid(six.text_type(arg))) or \
(six.PY2 and isinstance(arg, long)): # pylint: di... | [
"def",
"condition_input",
"(",
"args",
",",
"kwargs",
")",
":",
"ret",
"=",
"[",
"]",
"for",
"arg",
"in",
"args",
":",
"if",
"(",
"six",
".",
"PY3",
"and",
"isinstance",
"(",
"arg",
",",
"six",
".",
"integer_types",
")",
"and",
"salt",
".",
"utils"... | Return a single arg structure for the publisher to safely use | [
"Return",
"a",
"single",
"arg",
"structure",
"for",
"the",
"publisher",
"to",
"safely",
"use"
] | python | train | 37 |
twilio/twilio-python | twilio/rest/taskrouter/v1/workspace/workflow/workflow_cumulative_statistics.py | https://github.com/twilio/twilio-python/blob/c867895f55dcc29f522e6e8b8868d0d18483132f/twilio/rest/taskrouter/v1/workspace/workflow/workflow_cumulative_statistics.py#L93-L107 | def get_instance(self, payload):
"""
Build an instance of WorkflowCumulativeStatisticsInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.taskrouter.v1.workspace.workflow.workflow_cumulative_statistics.WorkflowCumulativeStatisticsInstance
:rtype: t... | [
"def",
"get_instance",
"(",
"self",
",",
"payload",
")",
":",
"return",
"WorkflowCumulativeStatisticsInstance",
"(",
"self",
".",
"_version",
",",
"payload",
",",
"workspace_sid",
"=",
"self",
".",
"_solution",
"[",
"'workspace_sid'",
"]",
",",
"workflow_sid",
"... | Build an instance of WorkflowCumulativeStatisticsInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.taskrouter.v1.workspace.workflow.workflow_cumulative_statistics.WorkflowCumulativeStatisticsInstance
:rtype: twilio.rest.taskrouter.v1.workspace.workflow.workflow_... | [
"Build",
"an",
"instance",
"of",
"WorkflowCumulativeStatisticsInstance"
] | python | train | 43.733333 |
brocade/pynos | pynos/versions/ver_6/ver_6_0_1/yang/tailf_confd_monitoring.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_6/ver_6_0_1/yang/tailf_confd_monitoring.py#L698-L710 | def confd_state_internal_callpoints_validationpoint_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
confd_state = ET.SubElement(config, "confd-state", xmlns="http://tail-f.com/yang/confd-monitoring")
internal = ET.SubElement(confd_state, "internal")
... | [
"def",
"confd_state_internal_callpoints_validationpoint_id",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"confd_state",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"confd-state\"",
",",
"... | Auto Generated Code | [
"Auto",
"Generated",
"Code"
] | python | train | 47.076923 |
pyQode/pyqode.core | pyqode/core/modes/right_margin.py | https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/modes/right_margin.py#L72-L83 | def _paint_margin(self, event):
""" Paints the right margin after editor paint event. """
font = QtGui.QFont(self.editor.font_name, self.editor.font_size +
self.editor.zoom_level)
metrics = QtGui.QFontMetricsF(font)
pos = self._margin_pos
offset = self.... | [
"def",
"_paint_margin",
"(",
"self",
",",
"event",
")",
":",
"font",
"=",
"QtGui",
".",
"QFont",
"(",
"self",
".",
"editor",
".",
"font_name",
",",
"self",
".",
"editor",
".",
"font_size",
"+",
"self",
".",
"editor",
".",
"zoom_level",
")",
"metrics",
... | Paints the right margin after editor paint event. | [
"Paints",
"the",
"right",
"margin",
"after",
"editor",
"paint",
"event",
"."
] | python | train | 48.666667 |
twitterdev/twitter-python-ads-sdk | twitter_ads/audience.py | https://github.com/twitterdev/twitter-python-ads-sdk/blob/b4488333ac2a794b85b7f16ded71e98b60e51c74/twitter_ads/audience.py#L116-L136 | def save(self):
"""
Saves or updates the current tailored audience permission.
"""
if self.id:
method = 'put'
resource = self.RESOURCE.format(
account_id=self.account.id,
tailored_audience_id=self.tailored_audience_id,
... | [
"def",
"save",
"(",
"self",
")",
":",
"if",
"self",
".",
"id",
":",
"method",
"=",
"'put'",
"resource",
"=",
"self",
".",
"RESOURCE",
".",
"format",
"(",
"account_id",
"=",
"self",
".",
"account",
".",
"id",
",",
"tailored_audience_id",
"=",
"self",
... | Saves or updates the current tailored audience permission. | [
"Saves",
"or",
"updates",
"the",
"current",
"tailored",
"audience",
"permission",
"."
] | python | train | 33.571429 |
gcrahay/python-wer | src/wer/schema.py | https://github.com/gcrahay/python-wer/blob/fad6bc4e379ec96a9483d32079098f19dfff1be5/src/wer/schema.py#L186-L199 | def id(self):
"""
Computes the signature of the record, a SHA-512 of significant values
:return: SHa-512 Hex string
"""
h = hashlib.new('sha512')
for value in (self.machine.name, self.machine.os, self.user, self.application.name,
self.application.pa... | [
"def",
"id",
"(",
"self",
")",
":",
"h",
"=",
"hashlib",
".",
"new",
"(",
"'sha512'",
")",
"for",
"value",
"in",
"(",
"self",
".",
"machine",
".",
"name",
",",
"self",
".",
"machine",
".",
"os",
",",
"self",
".",
"user",
",",
"self",
".",
"appl... | Computes the signature of the record, a SHA-512 of significant values
:return: SHa-512 Hex string | [
"Computes",
"the",
"signature",
"of",
"the",
"record",
"a",
"SHA",
"-",
"512",
"of",
"significant",
"values"
] | python | train | 44.071429 |
openstack/horizon | openstack_dashboard/management/commands/migrate_settings.py | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/management/commands/migrate_settings.py#L164-L220 | def patch(self, force=False):
"""Patch local_settings.py.example with local_settings.diff.
The patch application generates the local_settings.py file (the
local_settings.py.example remains unchanged).
http://github.com/sitkatech/pypatch fails if the
local_settings.py.example fi... | [
"def",
"patch",
"(",
"self",
",",
"force",
"=",
"False",
")",
":",
"with",
"DirContext",
"(",
"self",
".",
"local_settings_dir",
")",
"as",
"dircontext",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"local_settings_diff",
")",
":",
"i... | Patch local_settings.py.example with local_settings.diff.
The patch application generates the local_settings.py file (the
local_settings.py.example remains unchanged).
http://github.com/sitkatech/pypatch fails if the
local_settings.py.example file is not 100% identical to the one used ... | [
"Patch",
"local_settings",
".",
"py",
".",
"example",
"with",
"local_settings",
".",
"diff",
"."
] | python | train | 46.596491 |
bpsmith/tia | tia/analysis/model/ins.py | https://github.com/bpsmith/tia/blob/a7043b6383e557aeea8fc7112bbffd6e36a230e9/tia/analysis/model/ins.py#L30-L34 | def total_return(self):
"""http://en.wikipedia.org/wiki/Total_shareholder_return - mimics bloomberg total return"""
pxend = self.close
pxstart = pxend.shift(1).bfill()
return (1. + (pxend - pxstart + self.dvds.fillna(0)) / pxstart).cumprod() - 1 | [
"def",
"total_return",
"(",
"self",
")",
":",
"pxend",
"=",
"self",
".",
"close",
"pxstart",
"=",
"pxend",
".",
"shift",
"(",
"1",
")",
".",
"bfill",
"(",
")",
"return",
"(",
"1.",
"+",
"(",
"pxend",
"-",
"pxstart",
"+",
"self",
".",
"dvds",
".",... | http://en.wikipedia.org/wiki/Total_shareholder_return - mimics bloomberg total return | [
"http",
":",
"//",
"en",
".",
"wikipedia",
".",
"org",
"/",
"wiki",
"/",
"Total_shareholder_return",
"-",
"mimics",
"bloomberg",
"total",
"return"
] | python | train | 54.6 |
welbornprod/colr | colr/colr.py | https://github.com/welbornprod/colr/blob/417117fdbddbc53142096685ac2af006b2bd0220/colr/colr.py#L400-L405 | def get_all_names() -> Tuple[str]:
""" Retrieve a tuple of all known color names, basic and 'known names'.
"""
names = list(basic_names)
names.extend(name_data)
return tuple(sorted(set(names))) | [
"def",
"get_all_names",
"(",
")",
"->",
"Tuple",
"[",
"str",
"]",
":",
"names",
"=",
"list",
"(",
"basic_names",
")",
"names",
".",
"extend",
"(",
"name_data",
")",
"return",
"tuple",
"(",
"sorted",
"(",
"set",
"(",
"names",
")",
")",
")"
] | Retrieve a tuple of all known color names, basic and 'known names'. | [
"Retrieve",
"a",
"tuple",
"of",
"all",
"known",
"color",
"names",
"basic",
"and",
"known",
"names",
"."
] | python | train | 34.666667 |
googleads/googleads-python-lib | examples/adwords/v201809/shopping/add_smart_shopping_ad.py | https://github.com/googleads/googleads-python-lib/blob/aa3b1b474b0f9789ca55ca46f4b2b57aeae38874/examples/adwords/v201809/shopping/add_smart_shopping_ad.py#L132-L162 | def CreateSmartShoppingAdGroup(client, campaign_id):
"""Adds a new Smart Shopping ad group.
Args:
client: an AdWordsClient instance.
campaign_id: the str ID of a Smart Shopping campaign.
Returns:
An ad group ID.
"""
ad_group_service = client.GetService('AdGroupService', version='v201809')
# Cre... | [
"def",
"CreateSmartShoppingAdGroup",
"(",
"client",
",",
"campaign_id",
")",
":",
"ad_group_service",
"=",
"client",
".",
"GetService",
"(",
"'AdGroupService'",
",",
"version",
"=",
"'v201809'",
")",
"# Create the ad group.",
"ad_group",
"=",
"{",
"'campaignId'",
":... | Adds a new Smart Shopping ad group.
Args:
client: an AdWordsClient instance.
campaign_id: the str ID of a Smart Shopping campaign.
Returns:
An ad group ID. | [
"Adds",
"a",
"new",
"Smart",
"Shopping",
"ad",
"group",
"."
] | python | train | 29.580645 |
MatiasSM/fcb | fcb/processing/transformations/ToImage.py | https://github.com/MatiasSM/fcb/blob/92a6c535287ea1c1ef986954a5d66e7905fb6221/fcb/processing/transformations/ToImage.py#L83-L93 | def do_heavy_work(self, block):
"""
Note: Expects Compressor Block like objects
"""
src_file_path = block.latest_file_info.path
img_path = src_file_path + self.get_extension()
self.log.debug("Converting file '%s' to image '%s'", src_file_path, img_path)
from_file_... | [
"def",
"do_heavy_work",
"(",
"self",
",",
"block",
")",
":",
"src_file_path",
"=",
"block",
".",
"latest_file_info",
".",
"path",
"img_path",
"=",
"src_file_path",
"+",
"self",
".",
"get_extension",
"(",
")",
"self",
".",
"log",
".",
"debug",
"(",
"\"Conve... | Note: Expects Compressor Block like objects | [
"Note",
":",
"Expects",
"Compressor",
"Block",
"like",
"objects"
] | python | train | 44.545455 |
chorsley/python-Wappalyzer | Wappalyzer/Wappalyzer.py | https://github.com/chorsley/python-Wappalyzer/blob/b785e29f12c8032c54279cfa9ce01ead702a386c/Wappalyzer/Wappalyzer.py#L244-L252 | def get_categories(self, app_name):
"""
Returns a list of the categories for an app name.
"""
cat_nums = self.apps.get(app_name, {}).get("cats", [])
cat_names = [self.categories.get("%s" % cat_num, "")
for cat_num in cat_nums]
return cat_names | [
"def",
"get_categories",
"(",
"self",
",",
"app_name",
")",
":",
"cat_nums",
"=",
"self",
".",
"apps",
".",
"get",
"(",
"app_name",
",",
"{",
"}",
")",
".",
"get",
"(",
"\"cats\"",
",",
"[",
"]",
")",
"cat_names",
"=",
"[",
"self",
".",
"categories... | Returns a list of the categories for an app name. | [
"Returns",
"a",
"list",
"of",
"the",
"categories",
"for",
"an",
"app",
"name",
"."
] | python | train | 33.888889 |
HttpRunner/HttpRunner | httprunner/parser.py | https://github.com/HttpRunner/HttpRunner/blob/f259551bf9c8ba905eae5c1afcf2efea20ae0871/httprunner/parser.py#L757-L838 | def _extend_with_api(test_dict, api_def_dict):
""" extend test with api definition, test will merge and override api definition.
Args:
test_dict (dict): test block, this will override api_def_dict
api_def_dict (dict): api definition
Examples:
>>> api_def_dict = {
"n... | [
"def",
"_extend_with_api",
"(",
"test_dict",
",",
"api_def_dict",
")",
":",
"# override api name",
"test_dict",
".",
"setdefault",
"(",
"\"name\"",
",",
"api_def_dict",
".",
"pop",
"(",
"\"name\"",
",",
"\"api name undefined\"",
")",
")",
"# override variables",
"de... | extend test with api definition, test will merge and override api definition.
Args:
test_dict (dict): test block, this will override api_def_dict
api_def_dict (dict): api definition
Examples:
>>> api_def_dict = {
"name": "get token 1",
"request": {...},
... | [
"extend",
"test",
"with",
"api",
"definition",
"test",
"will",
"merge",
"and",
"override",
"api",
"definition",
"."
] | python | train | 35.646341 |
shad7/tvrenamer | tvrenamer/services/tvdb.py | https://github.com/shad7/tvrenamer/blob/7fb59cb02669357e73b7acb92dcb6d74fdff4654/tvrenamer/services/tvdb.py#L81-L108 | def get_episode_name(self, series, episode_numbers, season_number):
"""Perform lookup for name of episode numbers for a given series.
:param object series: instance of a series
:param list episode_numbers: the episode sequence number
:param int season_number: numeric season of series
... | [
"def",
"get_episode_name",
"(",
"self",
",",
"series",
",",
"episode_numbers",
",",
"season_number",
")",
":",
"try",
":",
"episodes",
"=",
"self",
".",
"api",
".",
"get_episodes",
"(",
"series",
".",
"get",
"(",
"'id'",
")",
",",
"airedSeason",
"=",
"se... | Perform lookup for name of episode numbers for a given series.
:param object series: instance of a series
:param list episode_numbers: the episode sequence number
:param int season_number: numeric season of series
:returns: list of episode name
:rtype: list(str) | [
"Perform",
"lookup",
"for",
"name",
"of",
"episode",
"numbers",
"for",
"a",
"given",
"series",
"."
] | python | train | 38.75 |
obriencj/python-javatools | javatools/distinfo.py | https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/distinfo.py#L179-L188 | def close(self):
""" if this was a zip'd distribution, any introspection
may have resulted in opening or creating temporary files.
Call close in order to clean up. """
if self.tmpdir:
rmtree(self.tmpdir)
self.tmpdir = None
self._contents = None | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"self",
".",
"tmpdir",
":",
"rmtree",
"(",
"self",
".",
"tmpdir",
")",
"self",
".",
"tmpdir",
"=",
"None",
"self",
".",
"_contents",
"=",
"None"
] | if this was a zip'd distribution, any introspection
may have resulted in opening or creating temporary files.
Call close in order to clean up. | [
"if",
"this",
"was",
"a",
"zip",
"d",
"distribution",
"any",
"introspection",
"may",
"have",
"resulted",
"in",
"opening",
"or",
"creating",
"temporary",
"files",
".",
"Call",
"close",
"in",
"order",
"to",
"clean",
"up",
"."
] | python | train | 30.1 |
bradmontgomery/django-redis-metrics | redis_metrics/models.py | https://github.com/bradmontgomery/django-redis-metrics/blob/2c92332920113d28c39234b949aa496b39a091d1/redis_metrics/models.py#L620-L624 | def delete_gauge(self, slug):
"""Removes all gauges with the given ``slug``."""
key = self._gauge_key(slug)
self.r.delete(key) # Remove the Gauge
self.r.srem(self._gauge_slugs_key, slug) | [
"def",
"delete_gauge",
"(",
"self",
",",
"slug",
")",
":",
"key",
"=",
"self",
".",
"_gauge_key",
"(",
"slug",
")",
"self",
".",
"r",
".",
"delete",
"(",
"key",
")",
"# Remove the Gauge",
"self",
".",
"r",
".",
"srem",
"(",
"self",
".",
"_gauge_slugs... | Removes all gauges with the given ``slug``. | [
"Removes",
"all",
"gauges",
"with",
"the",
"given",
"slug",
"."
] | python | train | 43 |
google/google-visualization-python | gviz_api.py | https://github.com/google/google-visualization-python/blob/cbfb4d69ad2f4ca30dc55791629280aa3214c8e3/gviz_api.py#L1011-L1049 | def ToJSonResponse(self, columns_order=None, order_by=(), req_id=0,
response_handler="google.visualization.Query.setResponse"):
"""Writes a table as a JSON response that can be returned as-is to a client.
This method writes a JSON response to return to a client in response to a
Google ... | [
"def",
"ToJSonResponse",
"(",
"self",
",",
"columns_order",
"=",
"None",
",",
"order_by",
"=",
"(",
")",
",",
"req_id",
"=",
"0",
",",
"response_handler",
"=",
"\"google.visualization.Query.setResponse\"",
")",
":",
"response_obj",
"=",
"{",
"\"version\"",
":",
... | Writes a table as a JSON response that can be returned as-is to a client.
This method writes a JSON response to return to a client in response to a
Google Visualization API query. This string can be processed by the calling
page, and is used to deliver a data table to a visualization hosted on
a differ... | [
"Writes",
"a",
"table",
"as",
"a",
"JSON",
"response",
"that",
"can",
"be",
"returned",
"as",
"-",
"is",
"to",
"a",
"client",
"."
] | python | train | 43.282051 |
ulule/django-badgify | badgify/utils.py | https://github.com/ulule/django-badgify/blob/1bf233ffeb6293ee659454de7b3794682128b6ca/badgify/utils.py#L115-L120 | def chunks(l, n):
"""
Yields successive n-sized chunks from l.
"""
for i in _range(0, len(l), n):
yield l[i:i + n] | [
"def",
"chunks",
"(",
"l",
",",
"n",
")",
":",
"for",
"i",
"in",
"_range",
"(",
"0",
",",
"len",
"(",
"l",
")",
",",
"n",
")",
":",
"yield",
"l",
"[",
"i",
":",
"i",
"+",
"n",
"]"
] | Yields successive n-sized chunks from l. | [
"Yields",
"successive",
"n",
"-",
"sized",
"chunks",
"from",
"l",
"."
] | python | train | 22.166667 |
wbond/asn1crypto | asn1crypto/core.py | https://github.com/wbond/asn1crypto/blob/ecda20176f55d37021cbca1f6da9083a8e491197/asn1crypto/core.py#L1482-L1491 | def debug(self, nest_level=1):
"""
Show the binary data and parsed data in a tree structure
"""
prefix = ' ' * nest_level
print('%s%s Object #%s' % (prefix, type_name(self), id(self)))
print('%s Children:' % (prefix,))
for child in self._children:
c... | [
"def",
"debug",
"(",
"self",
",",
"nest_level",
"=",
"1",
")",
":",
"prefix",
"=",
"' '",
"*",
"nest_level",
"print",
"(",
"'%s%s Object #%s'",
"%",
"(",
"prefix",
",",
"type_name",
"(",
"self",
")",
",",
"id",
"(",
"self",
")",
")",
")",
"print",
... | Show the binary data and parsed data in a tree structure | [
"Show",
"the",
"binary",
"data",
"and",
"parsed",
"data",
"in",
"a",
"tree",
"structure"
] | python | train | 33.7 |
echinopsii/net.echinopsii.ariane.community.cli.python3 | ariane_clip3/injector.py | https://github.com/echinopsii/net.echinopsii.ariane.community.cli.python3/blob/0a7feddebf66fee4bef38d64f456d93a7e9fcd68/ariane_clip3/injector.py#L950-L963 | def injector_gear_2_json(self):
"""
transform this local object to JSON.
:return: the JSON from this local object
"""
LOGGER.debug("InjectorCachedGear.injector_gear_2_json")
json_obj = {
'gearId': self.id,
'gearName': self.name,
'gearAd... | [
"def",
"injector_gear_2_json",
"(",
"self",
")",
":",
"LOGGER",
".",
"debug",
"(",
"\"InjectorCachedGear.injector_gear_2_json\"",
")",
"json_obj",
"=",
"{",
"'gearId'",
":",
"self",
".",
"id",
",",
"'gearName'",
":",
"self",
".",
"name",
",",
"'gearAdminQueue'",... | transform this local object to JSON.
:return: the JSON from this local object | [
"transform",
"this",
"local",
"object",
"to",
"JSON",
".",
":",
"return",
":",
"the",
"JSON",
"from",
"this",
"local",
"object"
] | python | train | 34.071429 |
h2oai/h2o-3 | h2o-py/h2o/model/regression.py | https://github.com/h2oai/h2o-3/blob/dd62aaa1e7f680a8b16ee14bc66b0fb5195c2ad8/h2o-py/h2o/model/regression.py#L56-L66 | def h2o_mean_squared_error(y_actual, y_predicted, weights=None):
"""
Mean squared error regression loss
:param y_actual: H2OFrame of actual response.
:param y_predicted: H2OFrame of predicted response.
:param weights: (Optional) sample weights
:returns: mean squared error loss (best is 0.0).
... | [
"def",
"h2o_mean_squared_error",
"(",
"y_actual",
",",
"y_predicted",
",",
"weights",
"=",
"None",
")",
":",
"ModelBase",
".",
"_check_targets",
"(",
"y_actual",
",",
"y_predicted",
")",
"return",
"_colmean",
"(",
"(",
"y_predicted",
"-",
"y_actual",
")",
"**"... | Mean squared error regression loss
:param y_actual: H2OFrame of actual response.
:param y_predicted: H2OFrame of predicted response.
:param weights: (Optional) sample weights
:returns: mean squared error loss (best is 0.0). | [
"Mean",
"squared",
"error",
"regression",
"loss"
] | python | test | 38 |
pymc-devs/pymc | pymc/distributions.py | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/distributions.py#L2467-L2501 | def truncated_normal_expval(mu, tau, a, b):
"""Expected value of the truncated normal distribution.
.. math::
E(X) =\mu + \frac{\sigma(\varphi_1-\varphi_2)}{T}
where
.. math::
T & =\Phi\left(\frac{B-\mu}{\sigma}\right)-\Phi
\left(\frac{A-\mu}{\sigma}\right)\text \\
\varph... | [
"def",
"truncated_normal_expval",
"(",
"mu",
",",
"tau",
",",
"a",
",",
"b",
")",
":",
"phia",
"=",
"np",
".",
"exp",
"(",
"normal_like",
"(",
"a",
",",
"mu",
",",
"tau",
")",
")",
"phib",
"=",
"np",
".",
"exp",
"(",
"normal_like",
"(",
"b",
",... | Expected value of the truncated normal distribution.
.. math::
E(X) =\mu + \frac{\sigma(\varphi_1-\varphi_2)}{T}
where
.. math::
T & =\Phi\left(\frac{B-\mu}{\sigma}\right)-\Phi
\left(\frac{A-\mu}{\sigma}\right)\text \\
\varphi_1 &=
\varphi\left(\frac{A-\mu}{\sigma}\rig... | [
"Expected",
"value",
"of",
"the",
"truncated",
"normal",
"distribution",
"."
] | python | train | 29.571429 |
nicolargo/glances | glances/plugins/glances_ports.py | https://github.com/nicolargo/glances/blob/5bd4d587a736e0d2b03170b56926841d2a3eb7ee/glances/plugins/glances_ports.py#L104-L128 | def get_ports_alert(self, port, header="", log=False):
"""Return the alert status relative to the port scan return value."""
ret = 'OK'
if port['status'] is None:
ret = 'CAREFUL'
elif port['status'] == 0:
ret = 'CRITICAL'
elif (isinstance(port['status'], (... | [
"def",
"get_ports_alert",
"(",
"self",
",",
"port",
",",
"header",
"=",
"\"\"",
",",
"log",
"=",
"False",
")",
":",
"ret",
"=",
"'OK'",
"if",
"port",
"[",
"'status'",
"]",
"is",
"None",
":",
"ret",
"=",
"'CAREFUL'",
"elif",
"port",
"[",
"'status'",
... | Return the alert status relative to the port scan return value. | [
"Return",
"the",
"alert",
"status",
"relative",
"to",
"the",
"port",
"scan",
"return",
"value",
"."
] | python | train | 32.12 |
jaraco/jaraco.functools | jaraco/functools.py | https://github.com/jaraco/jaraco.functools/blob/cc972095e5aa2ae80d1d69d7ca84ee94178e869a/jaraco/functools.py#L184-L211 | def _special_method_cache(method, cache_wrapper):
"""
Because Python treats special methods differently, it's not
possible to use instance attributes to implement the cached
methods.
Instead, install the wrapper method under a different name
and return a simple proxy to that wrapper.
https://github.com/jaraco/... | [
"def",
"_special_method_cache",
"(",
"method",
",",
"cache_wrapper",
")",
":",
"name",
"=",
"method",
".",
"__name__",
"special_names",
"=",
"'__getattr__'",
",",
"'__getitem__'",
"if",
"name",
"not",
"in",
"special_names",
":",
"return",
"wrapper_name",
"=",
"'... | Because Python treats special methods differently, it's not
possible to use instance attributes to implement the cached
methods.
Instead, install the wrapper method under a different name
and return a simple proxy to that wrapper.
https://github.com/jaraco/jaraco.functools/issues/5 | [
"Because",
"Python",
"treats",
"special",
"methods",
"differently",
"it",
"s",
"not",
"possible",
"to",
"use",
"instance",
"attributes",
"to",
"implement",
"the",
"cached",
"methods",
"."
] | python | train | 26.678571 |
mahmoudimus/nose-timer | nosetimer/plugin.py | https://github.com/mahmoudimus/nose-timer/blob/3d8ff21ce3a68efd6cd018ea67c32f1da27ea3f9/nosetimer/plugin.py#L147-L165 | def configure(self, options, config):
"""Configures the test timer plugin."""
super(TimerPlugin, self).configure(options, config)
self.config = config
if self.enabled:
self.timer_top_n = int(options.timer_top_n)
self.timer_ok = self._parse_time(options.timer_ok)
... | [
"def",
"configure",
"(",
"self",
",",
"options",
",",
"config",
")",
":",
"super",
"(",
"TimerPlugin",
",",
"self",
")",
".",
"configure",
"(",
"options",
",",
"config",
")",
"self",
".",
"config",
"=",
"config",
"if",
"self",
".",
"enabled",
":",
"s... | Configures the test timer plugin. | [
"Configures",
"the",
"test",
"timer",
"plugin",
"."
] | python | train | 47.631579 |
fabioz/PyDev.Debugger | third_party/pep8/pycodestyle.py | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/third_party/pep8/pycodestyle.py#L1585-L1590 | def run_check(self, check, argument_names):
"""Run a check plugin."""
arguments = []
for name in argument_names:
arguments.append(getattr(self, name))
return check(*arguments) | [
"def",
"run_check",
"(",
"self",
",",
"check",
",",
"argument_names",
")",
":",
"arguments",
"=",
"[",
"]",
"for",
"name",
"in",
"argument_names",
":",
"arguments",
".",
"append",
"(",
"getattr",
"(",
"self",
",",
"name",
")",
")",
"return",
"check",
"... | Run a check plugin. | [
"Run",
"a",
"check",
"plugin",
"."
] | python | train | 35.666667 |
xolox/python-verboselogs | verboselogs/__init__.py | https://github.com/xolox/python-verboselogs/blob/3cebc69e03588bb6c3726c38c324b12732989292/verboselogs/__init__.py#L163-L166 | def verbose(self, msg, *args, **kw):
"""Log a message with level :data:`VERBOSE`. The arguments are interpreted as for :func:`logging.debug()`."""
if self.isEnabledFor(VERBOSE):
self._log(VERBOSE, msg, args, **kw) | [
"def",
"verbose",
"(",
"self",
",",
"msg",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"if",
"self",
".",
"isEnabledFor",
"(",
"VERBOSE",
")",
":",
"self",
".",
"_log",
"(",
"VERBOSE",
",",
"msg",
",",
"args",
",",
"*",
"*",
"kw",
")"
] | Log a message with level :data:`VERBOSE`. The arguments are interpreted as for :func:`logging.debug()`. | [
"Log",
"a",
"message",
"with",
"level",
":",
"data",
":",
"VERBOSE",
".",
"The",
"arguments",
"are",
"interpreted",
"as",
"for",
":",
"func",
":",
"logging",
".",
"debug",
"()",
"."
] | python | train | 59.5 |
Parisson/TimeSide | timeside/plugins/grapher/utils.py | https://github.com/Parisson/TimeSide/blob/0618d75cd2f16021afcfd3d5b77f692adad76ea5/timeside/plugins/grapher/utils.py#L168-L179 | def im_watermark(im, inputtext, font=None, color=None, opacity=.6, margin=(30, 30)):
"""imprints a PIL image with the indicated text in lower-right corner"""
if im.mode != "RGBA":
im = im.convert("RGBA")
textlayer = Image.new("RGBA", im.size, (0, 0, 0, 0))
textdraw = ImageDraw.Draw(textlayer)
... | [
"def",
"im_watermark",
"(",
"im",
",",
"inputtext",
",",
"font",
"=",
"None",
",",
"color",
"=",
"None",
",",
"opacity",
"=",
".6",
",",
"margin",
"=",
"(",
"30",
",",
"30",
")",
")",
":",
"if",
"im",
".",
"mode",
"!=",
"\"RGBA\"",
":",
"im",
"... | imprints a PIL image with the indicated text in lower-right corner | [
"imprints",
"a",
"PIL",
"image",
"with",
"the",
"indicated",
"text",
"in",
"lower",
"-",
"right",
"corner"
] | python | train | 51.666667 |
bcb/jsonrpcserver | jsonrpcserver/dispatcher.py | https://github.com/bcb/jsonrpcserver/blob/26bb70e868f81691816cabfc4b60a83428842b2f/jsonrpcserver/dispatcher.py#L84-L96 | def validate(request: Union[Dict, List], schema: dict) -> Union[Dict, List]:
"""
Wraps jsonschema.validate, returning the same object passed in.
Args:
request: The deserialized-from-json request.
schema: The jsonschema schema to validate against.
Raises:
jsonschema.ValidationEr... | [
"def",
"validate",
"(",
"request",
":",
"Union",
"[",
"Dict",
",",
"List",
"]",
",",
"schema",
":",
"dict",
")",
"->",
"Union",
"[",
"Dict",
",",
"List",
"]",
":",
"jsonschema_validate",
"(",
"request",
",",
"schema",
")",
"return",
"request"
] | Wraps jsonschema.validate, returning the same object passed in.
Args:
request: The deserialized-from-json request.
schema: The jsonschema schema to validate against.
Raises:
jsonschema.ValidationError | [
"Wraps",
"jsonschema",
".",
"validate",
"returning",
"the",
"same",
"object",
"passed",
"in",
"."
] | python | train | 29.153846 |
programa-stic/barf-project | barf/core/reil/emulator/cpu.py | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/core/reil/emulator/cpu.py#L459-L468 | def __execute_bisz(self, instr):
"""Execute BISZ instruction.
"""
op0_val = self.read_operand(instr.operands[0])
op2_val = 1 if op0_val == 0 else 0
self.write_operand(instr.operands[2], op2_val)
return None | [
"def",
"__execute_bisz",
"(",
"self",
",",
"instr",
")",
":",
"op0_val",
"=",
"self",
".",
"read_operand",
"(",
"instr",
".",
"operands",
"[",
"0",
"]",
")",
"op2_val",
"=",
"1",
"if",
"op0_val",
"==",
"0",
"else",
"0",
"self",
".",
"write_operand",
... | Execute BISZ instruction. | [
"Execute",
"BISZ",
"instruction",
"."
] | python | train | 24.8 |
Jajcus/pyxmpp2 | pyxmpp2/transport.py | https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/transport.py#L201-L206 | def _set_state(self, state):
"""Set `_state` and notify any threads waiting for the change.
"""
logger.debug(" _set_state({0!r})".format(state))
self._state = state
self._state_cond.notify() | [
"def",
"_set_state",
"(",
"self",
",",
"state",
")",
":",
"logger",
".",
"debug",
"(",
"\" _set_state({0!r})\"",
".",
"format",
"(",
"state",
")",
")",
"self",
".",
"_state",
"=",
"state",
"self",
".",
"_state_cond",
".",
"notify",
"(",
")"
] | Set `_state` and notify any threads waiting for the change. | [
"Set",
"_state",
"and",
"notify",
"any",
"threads",
"waiting",
"for",
"the",
"change",
"."
] | python | valid | 37.5 |
RedHatInsights/insights-core | insights/util/subproc.py | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/util/subproc.py#L165-L214 | def call(cmd,
timeout=None,
signum=signal.SIGKILL,
keep_rc=False,
encoding="utf-8",
env=os.environ):
"""
Execute a cmd or list of commands with an optional timeout in seconds.
If `timeout` is supplied and expires, the process is killed with
SIGKILL (kill -9)... | [
"def",
"call",
"(",
"cmd",
",",
"timeout",
"=",
"None",
",",
"signum",
"=",
"signal",
".",
"SIGKILL",
",",
"keep_rc",
"=",
"False",
",",
"encoding",
"=",
"\"utf-8\"",
",",
"env",
"=",
"os",
".",
"environ",
")",
":",
"if",
"not",
"isinstance",
"(",
... | Execute a cmd or list of commands with an optional timeout in seconds.
If `timeout` is supplied and expires, the process is killed with
SIGKILL (kill -9) and an exception is raised. Otherwise, the command
output is returned.
Parameters
----------
cmd: str or [[str]]
The command(s) to e... | [
"Execute",
"a",
"cmd",
"or",
"list",
"of",
"commands",
"with",
"an",
"optional",
"timeout",
"in",
"seconds",
"."
] | python | train | 26.18 |
scraperwiki/data-services-helpers | dshelpers.py | https://github.com/scraperwiki/data-services-helpers/blob/a31ea2f40d20fd99d4c0938b87466330679db2c9/dshelpers.py#L109-L117 | def download_url(url, back_off=True, **kwargs):
"""
Get the content of a URL and return a file-like object.
back_off=True provides retry
"""
if back_off:
return _download_with_backoff(url, as_file=True, **kwargs)
else:
return _download_without_backoff(url, as_file=True, **kwargs) | [
"def",
"download_url",
"(",
"url",
",",
"back_off",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"back_off",
":",
"return",
"_download_with_backoff",
"(",
"url",
",",
"as_file",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
"else",
":",
"return",... | Get the content of a URL and return a file-like object.
back_off=True provides retry | [
"Get",
"the",
"content",
"of",
"a",
"URL",
"and",
"return",
"a",
"file",
"-",
"like",
"object",
".",
"back_off",
"=",
"True",
"provides",
"retry"
] | python | train | 34.666667 |
pantsbuild/pants | src/python/pants/engine/rules.py | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/engine/rules.py#L417-L465 | def create(cls, rule_entries, union_rules=None):
"""Creates a RuleIndex with tasks indexed by their output type."""
serializable_rules = OrderedDict()
serializable_roots = OrderedSet()
union_rules = OrderedDict(union_rules or ())
def add_task(product_type, rule):
# TODO(#7311): make a default... | [
"def",
"create",
"(",
"cls",
",",
"rule_entries",
",",
"union_rules",
"=",
"None",
")",
":",
"serializable_rules",
"=",
"OrderedDict",
"(",
")",
"serializable_roots",
"=",
"OrderedSet",
"(",
")",
"union_rules",
"=",
"OrderedDict",
"(",
"union_rules",
"or",
"("... | Creates a RuleIndex with tasks indexed by their output type. | [
"Creates",
"a",
"RuleIndex",
"with",
"tasks",
"indexed",
"by",
"their",
"output",
"type",
"."
] | python | train | 38.102041 |
pallets/werkzeug | src/werkzeug/debug/__init__.py | https://github.com/pallets/werkzeug/blob/a220671d66755a94630a212378754bb432811158/src/werkzeug/debug/__init__.py#L357-L367 | def get_resource(self, request, filename):
"""Return a static resource from the shared folder."""
filename = join("shared", basename(filename))
try:
data = pkgutil.get_data(__package__, filename)
except OSError:
data = None
if data is not None:
... | [
"def",
"get_resource",
"(",
"self",
",",
"request",
",",
"filename",
")",
":",
"filename",
"=",
"join",
"(",
"\"shared\"",
",",
"basename",
"(",
"filename",
")",
")",
"try",
":",
"data",
"=",
"pkgutil",
".",
"get_data",
"(",
"__package__",
",",
"filename... | Return a static resource from the shared folder. | [
"Return",
"a",
"static",
"resource",
"from",
"the",
"shared",
"folder",
"."
] | python | train | 44.272727 |
astropy/photutils | photutils/segmentation/properties.py | https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/segmentation/properties.py#L987-L1000 | def covariance(self):
"""
The covariance matrix of the 2D Gaussian function that has the
same second-order moments as the source.
"""
mu = self.moments_central
if mu[0, 0] != 0:
m = mu / mu[0, 0]
covariance = self._check_covariance(
... | [
"def",
"covariance",
"(",
"self",
")",
":",
"mu",
"=",
"self",
".",
"moments_central",
"if",
"mu",
"[",
"0",
",",
"0",
"]",
"!=",
"0",
":",
"m",
"=",
"mu",
"/",
"mu",
"[",
"0",
",",
"0",
"]",
"covariance",
"=",
"self",
".",
"_check_covariance",
... | The covariance matrix of the 2D Gaussian function that has the
same second-order moments as the source. | [
"The",
"covariance",
"matrix",
"of",
"the",
"2D",
"Gaussian",
"function",
"that",
"has",
"the",
"same",
"second",
"-",
"order",
"moments",
"as",
"the",
"source",
"."
] | python | train | 33.642857 |
rohankapoorcom/zm-py | zoneminder/monitor.py | https://github.com/rohankapoorcom/zm-py/blob/bd3a9f6b2f7b84b37589e2939f628b479a5531bf/zoneminder/monitor.py#L163-L192 | def get_events(self, time_period, include_archived=False) -> Optional[int]:
"""Get the number of events that have occurred on this Monitor.
Specifically only gets events that have occurred within the TimePeriod
provided.
"""
date_filter = '1%20{}'.format(time_period.period)
... | [
"def",
"get_events",
"(",
"self",
",",
"time_period",
",",
"include_archived",
"=",
"False",
")",
"->",
"Optional",
"[",
"int",
"]",
":",
"date_filter",
"=",
"'1%20{}'",
".",
"format",
"(",
"time_period",
".",
"period",
")",
"if",
"time_period",
"==",
"Tim... | Get the number of events that have occurred on this Monitor.
Specifically only gets events that have occurred within the TimePeriod
provided. | [
"Get",
"the",
"number",
"of",
"events",
"that",
"have",
"occurred",
"on",
"this",
"Monitor",
"."
] | python | train | 34.366667 |
vpelletier/python-functionfs | functionfs/__init__.py | https://github.com/vpelletier/python-functionfs/blob/e19f729bb47a7d1edd2488531af24551bb86726f/functionfs/__init__.py#L574-L584 | def getRealInterfaceNumber(self, interface):
"""
Returns the host-visible interface number, or None if there is no such
interface.
"""
try:
return self._ioctl(INTERFACE_REVMAP, interface)
except IOError as exc:
if exc.errno == errno.EDOM:
... | [
"def",
"getRealInterfaceNumber",
"(",
"self",
",",
"interface",
")",
":",
"try",
":",
"return",
"self",
".",
"_ioctl",
"(",
"INTERFACE_REVMAP",
",",
"interface",
")",
"except",
"IOError",
"as",
"exc",
":",
"if",
"exc",
".",
"errno",
"==",
"errno",
".",
"... | Returns the host-visible interface number, or None if there is no such
interface. | [
"Returns",
"the",
"host",
"-",
"visible",
"interface",
"number",
"or",
"None",
"if",
"there",
"is",
"no",
"such",
"interface",
"."
] | python | train | 31.454545 |
weblyzard/inscriptis | src/inscriptis/__init__.py | https://github.com/weblyzard/inscriptis/blob/0d04f81e69d643bb5f470f33b4ca67b62fc1037c/src/inscriptis/__init__.py#L18-L34 | def get_text(html_content, display_images=False, deduplicate_captions=False, display_links=False):
'''
::param: html_content
::returns:
a text representation of the html content.
'''
html_content = html_content.strip()
if not html_content:
return ""
# strip XML declaration, ... | [
"def",
"get_text",
"(",
"html_content",
",",
"display_images",
"=",
"False",
",",
"deduplicate_captions",
"=",
"False",
",",
"display_links",
"=",
"False",
")",
":",
"html_content",
"=",
"html_content",
".",
"strip",
"(",
")",
"if",
"not",
"html_content",
":",... | ::param: html_content
::returns:
a text representation of the html content. | [
"::",
"param",
":",
"html_content",
"::",
"returns",
":",
"a",
"text",
"representation",
"of",
"the",
"html",
"content",
"."
] | python | train | 38 |
bitesofcode/projexui | projexui/widgets/xnavigationedit.py | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xnavigationedit.py#L319-L331 | def cancelEdit( self ):
"""
Rejects the current edit and shows the parts widget.
"""
if ( self._partsWidget.isVisible() ):
return False
self._completerTree.hide()
self.completer().popup().hide()
self.setText(self._origina... | [
"def",
"cancelEdit",
"(",
"self",
")",
":",
"if",
"(",
"self",
".",
"_partsWidget",
".",
"isVisible",
"(",
")",
")",
":",
"return",
"False",
"self",
".",
"_completerTree",
".",
"hide",
"(",
")",
"self",
".",
"completer",
"(",
")",
".",
"popup",
"(",
... | Rejects the current edit and shows the parts widget. | [
"Rejects",
"the",
"current",
"edit",
"and",
"shows",
"the",
"parts",
"widget",
"."
] | python | train | 25.692308 |
googleapis/google-cloud-python | firestore/google/cloud/firestore_v1beta1/gapic/firestore_client.py | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/gapic/firestore_client.py#L744-L864 | def batch_get_documents(
self,
database,
documents,
mask=None,
transaction=None,
new_transaction=None,
read_time=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
... | [
"def",
"batch_get_documents",
"(",
"self",
",",
"database",
",",
"documents",
",",
"mask",
"=",
"None",
",",
"transaction",
"=",
"None",
",",
"new_transaction",
"=",
"None",
",",
"read_time",
"=",
"None",
",",
"retry",
"=",
"google",
".",
"api_core",
".",
... | Gets multiple documents.
Documents returned by this method are not guaranteed to be returned in the
same order that they were requested.
Example:
>>> from google.cloud import firestore_v1beta1
>>>
>>> client = firestore_v1beta1.FirestoreClient()
... | [
"Gets",
"multiple",
"documents",
"."
] | python | train | 44.338843 |
spotify/luigi | luigi/tools/luigi_grep.py | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/tools/luigi_grep.py#L46-L53 | def status_search(self, status):
"""Searches for jobs matching the given ``status``."""
json = self._fetch_json()
jobs = json['response']
for job in jobs:
job_info = jobs[job]
if job_info['status'].lower() == status.lower():
yield self._build_resul... | [
"def",
"status_search",
"(",
"self",
",",
"status",
")",
":",
"json",
"=",
"self",
".",
"_fetch_json",
"(",
")",
"jobs",
"=",
"json",
"[",
"'response'",
"]",
"for",
"job",
"in",
"jobs",
":",
"job_info",
"=",
"jobs",
"[",
"job",
"]",
"if",
"job_info",... | Searches for jobs matching the given ``status``. | [
"Searches",
"for",
"jobs",
"matching",
"the",
"given",
"status",
"."
] | python | train | 40.75 |
ocaballeror/LyricFetch | lyricfetch/scraping.py | https://github.com/ocaballeror/LyricFetch/blob/86e62fb39c4c413ad7e1acf5bf0d28c9ed7c8fcb/lyricfetch/scraping.py#L170-L185 | def azlyrics(song):
"""
Returns the lyrics found in azlyrics for the specified mp3 file or an empty
string if not found.
"""
artist = song.artist.lower()
if artist[0:2] == 'a ':
artist = artist[2:]
artist = normalize(artist, URLESCAPES, '')
title = song.title.lower()
title = ... | [
"def",
"azlyrics",
"(",
"song",
")",
":",
"artist",
"=",
"song",
".",
"artist",
".",
"lower",
"(",
")",
"if",
"artist",
"[",
"0",
":",
"2",
"]",
"==",
"'a '",
":",
"artist",
"=",
"artist",
"[",
"2",
":",
"]",
"artist",
"=",
"normalize",
"(",
"a... | Returns the lyrics found in azlyrics for the specified mp3 file or an empty
string if not found. | [
"Returns",
"the",
"lyrics",
"found",
"in",
"azlyrics",
"for",
"the",
"specified",
"mp3",
"file",
"or",
"an",
"empty",
"string",
"if",
"not",
"found",
"."
] | python | train | 32.5625 |
PSPC-SPAC-buyandsell/von_anchor | von_anchor/wallet/wallet.py | https://github.com/PSPC-SPAC-buyandsell/von_anchor/blob/78ac1de67be42a676274f4bf71fe12f66e72f309/von_anchor/wallet/wallet.py#L818-L834 | async def delete_pairwise(self, their_did: str) -> None:
"""
Remove a pairwise DID record by its remote DID. Silently return if no such record is present.
Raise WalletState for closed wallet, or BadIdentifier for invalid pairwise DID.
:param their_did: remote DID marking pairwise DID to... | [
"async",
"def",
"delete_pairwise",
"(",
"self",
",",
"their_did",
":",
"str",
")",
"->",
"None",
":",
"LOGGER",
".",
"debug",
"(",
"'Wallet.delete_pairwise >>> their_did: %s'",
",",
"their_did",
")",
"if",
"not",
"ok_did",
"(",
"their_did",
")",
":",
"LOGGER",... | Remove a pairwise DID record by its remote DID. Silently return if no such record is present.
Raise WalletState for closed wallet, or BadIdentifier for invalid pairwise DID.
:param their_did: remote DID marking pairwise DID to remove | [
"Remove",
"a",
"pairwise",
"DID",
"record",
"by",
"its",
"remote",
"DID",
".",
"Silently",
"return",
"if",
"no",
"such",
"record",
"is",
"present",
".",
"Raise",
"WalletState",
"for",
"closed",
"wallet",
"or",
"BadIdentifier",
"for",
"invalid",
"pairwise",
"... | python | train | 40.705882 |
archman/pyrpn | pyrpn/rpn.py | https://github.com/archman/pyrpn/blob/fee706fccee1aa5c527f3f4221cc6b0d69bdde2c/pyrpn/rpn.py#L144-L171 | def solve(self):
"""Solve rpn expression, return None if not valid."""
popflag = True
self.tmpopslist = []
while True:
while self.opslist and popflag:
op = self.opslist.pop()
if self.is_variable(op):
op = self.variables.get(... | [
"def",
"solve",
"(",
"self",
")",
":",
"popflag",
"=",
"True",
"self",
".",
"tmpopslist",
"=",
"[",
"]",
"while",
"True",
":",
"while",
"self",
".",
"opslist",
"and",
"popflag",
":",
"op",
"=",
"self",
".",
"opslist",
".",
"pop",
"(",
")",
"if",
... | Solve rpn expression, return None if not valid. | [
"Solve",
"rpn",
"expression",
"return",
"None",
"if",
"not",
"valid",
"."
] | python | train | 30.25 |
log2timeline/plaso | plaso/engine/extractors.py | https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/engine/extractors.py#L548-L571 | def _ExtractPathSpecsFromFile(self, file_entry):
"""Extracts path specification from a file.
Args:
file_entry (dfvfs.FileEntry): file entry that refers to the file.
Yields:
dfvfs.PathSpec: path specification of a file entry found in the file.
"""
produced_main_path_spec = False
for... | [
"def",
"_ExtractPathSpecsFromFile",
"(",
"self",
",",
"file_entry",
")",
":",
"produced_main_path_spec",
"=",
"False",
"for",
"data_stream",
"in",
"file_entry",
".",
"data_streams",
":",
"# Make a copy so we don't make the changes on a path specification",
"# directly. Otherwis... | Extracts path specification from a file.
Args:
file_entry (dfvfs.FileEntry): file entry that refers to the file.
Yields:
dfvfs.PathSpec: path specification of a file entry found in the file. | [
"Extracts",
"path",
"specification",
"from",
"a",
"file",
"."
] | python | train | 34.083333 |
Erotemic/utool | utool/util_path.py | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_path.py#L308-L368 | def augpath(path, augsuf='', augext='', augpref='', augdir=None, newext=None,
newfname=None, ensure=False, prefix=None, suffix=None):
"""
augments end of path before the extension.
augpath
Args:
path (str):
augsuf (str): augment filename before extension
Returns:
... | [
"def",
"augpath",
"(",
"path",
",",
"augsuf",
"=",
"''",
",",
"augext",
"=",
"''",
",",
"augpref",
"=",
"''",
",",
"augdir",
"=",
"None",
",",
"newext",
"=",
"None",
",",
"newfname",
"=",
"None",
",",
"ensure",
"=",
"False",
",",
"prefix",
"=",
"... | augments end of path before the extension.
augpath
Args:
path (str):
augsuf (str): augment filename before extension
Returns:
str: newpath
Example:
>>> # DISABLE_DOCTEST
>>> from utool.util_path import * # NOQA
>>> path = 'somefile.txt'
>>> au... | [
"augments",
"end",
"of",
"path",
"before",
"the",
"extension",
"."
] | python | train | 27.229508 |
thespacedoctor/rockAtlas | rockAtlas/positions/pyephemPositions.py | https://github.com/thespacedoctor/rockAtlas/blob/062ecaa95ab547efda535aa33165944f13c621de/rockAtlas/positions/pyephemPositions.py#L93-L141 | def get(self, singleSnapshot=False):
"""
*geneate the pyephem positions*
**Key Arguments:**
- ``singleSnapshot`` -- just extract positions for a single pyephem snapshot (used for unit testing)
**Return:**
- ``None``
"""
self.log.info('starting t... | [
"def",
"get",
"(",
"self",
",",
"singleSnapshot",
"=",
"False",
")",
":",
"self",
".",
"log",
".",
"info",
"(",
"'starting the ``get`` method'",
")",
"global",
"xephemOE",
"global",
"tileSide",
"global",
"magLimit",
"# GRAB PARAMETERS FROM SETTINGS FILE",
"tileSide"... | *geneate the pyephem positions*
**Key Arguments:**
- ``singleSnapshot`` -- just extract positions for a single pyephem snapshot (used for unit testing)
**Return:**
- ``None`` | [
"*",
"geneate",
"the",
"pyephem",
"positions",
"*"
] | python | train | 37.510204 |
nicolargo/glances | glances/main.py | https://github.com/nicolargo/glances/blob/5bd4d587a736e0d2b03170b56926841d2a3eb7ee/glances/main.py#L252-L417 | def parse_args(self):
"""Parse command line arguments."""
args = self.init_args().parse_args()
# Load the configuration file, if it exists
self.config = Config(args.conf_file)
# Debug mode
if args.debug:
from logging import DEBUG
logger.setLevel(... | [
"def",
"parse_args",
"(",
"self",
")",
":",
"args",
"=",
"self",
".",
"init_args",
"(",
")",
".",
"parse_args",
"(",
")",
"# Load the configuration file, if it exists",
"self",
".",
"config",
"=",
"Config",
"(",
"args",
".",
"conf_file",
")",
"# Debug mode",
... | Parse command line arguments. | [
"Parse",
"command",
"line",
"arguments",
"."
] | python | train | 36.909639 |
KnowledgeLinks/rdfframework | rdfframework/datasets/jsonquery.py | https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/datasets/jsonquery.py#L14-L63 | def parse_json_qry(qry_str):
""" Parses a json query string into its parts
args:
qry_str: query string
params: variables passed into the string
"""
def param_analyzer(param_list):
rtn_list = []
for param in param_list:
parts = param.strip().split("=")
... | [
"def",
"parse_json_qry",
"(",
"qry_str",
")",
":",
"def",
"param_analyzer",
"(",
"param_list",
")",
":",
"rtn_list",
"=",
"[",
"]",
"for",
"param",
"in",
"param_list",
":",
"parts",
"=",
"param",
".",
"strip",
"(",
")",
".",
"split",
"(",
"\"=\"",
")",... | Parses a json query string into its parts
args:
qry_str: query string
params: variables passed into the string | [
"Parses",
"a",
"json",
"query",
"string",
"into",
"its",
"parts"
] | python | train | 32.4 |
gitpython-developers/GitPython | git/util.py | https://github.com/gitpython-developers/GitPython/blob/1f66e25c25cde2423917ee18c4704fff83b837d1/git/util.py#L573-L590 | def _from_string(cls, string):
"""Create an Actor from a string.
:param string: is the string, which is expected to be in regular git format
John Doe <jdoe@example.com>
:return: Actor """
m = cls.name_email_regex.search(string)
if m:
name, email = m.... | [
"def",
"_from_string",
"(",
"cls",
",",
"string",
")",
":",
"m",
"=",
"cls",
".",
"name_email_regex",
".",
"search",
"(",
"string",
")",
"if",
"m",
":",
"name",
",",
"email",
"=",
"m",
".",
"groups",
"(",
")",
"return",
"Actor",
"(",
"name",
",",
... | Create an Actor from a string.
:param string: is the string, which is expected to be in regular git format
John Doe <jdoe@example.com>
:return: Actor | [
"Create",
"an",
"Actor",
"from",
"a",
"string",
".",
":",
"param",
"string",
":",
"is",
"the",
"string",
"which",
"is",
"expected",
"to",
"be",
"in",
"regular",
"git",
"format"
] | python | train | 33.5 |
saltstack/salt | salt/utils/kickstart.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/kickstart.py#L739-L745 | def parse_updates(rule):
'''
Parse the updates line
'''
rules = shlex.split(rule)
rules.pop(0)
return {'url': rules[0]} if rules else True | [
"def",
"parse_updates",
"(",
"rule",
")",
":",
"rules",
"=",
"shlex",
".",
"split",
"(",
"rule",
")",
"rules",
".",
"pop",
"(",
"0",
")",
"return",
"{",
"'url'",
":",
"rules",
"[",
"0",
"]",
"}",
"if",
"rules",
"else",
"True"
] | Parse the updates line | [
"Parse",
"the",
"updates",
"line"
] | python | train | 22.285714 |
instaloader/instaloader | instaloader/structures.py | https://github.com/instaloader/instaloader/blob/87d877e650cd8020b04b8b51be120599a441fd5b/instaloader/structures.py#L75-L80 | def from_shortcode(cls, context: InstaloaderContext, shortcode: str):
"""Create a post object from a given shortcode"""
# pylint:disable=protected-access
post = cls(context, {'shortcode': shortcode})
post._node = post._full_metadata
return post | [
"def",
"from_shortcode",
"(",
"cls",
",",
"context",
":",
"InstaloaderContext",
",",
"shortcode",
":",
"str",
")",
":",
"# pylint:disable=protected-access",
"post",
"=",
"cls",
"(",
"context",
",",
"{",
"'shortcode'",
":",
"shortcode",
"}",
")",
"post",
".",
... | Create a post object from a given shortcode | [
"Create",
"a",
"post",
"object",
"from",
"a",
"given",
"shortcode"
] | python | train | 46.5 |
closeio/tasktiger | tasktiger/worker.py | https://github.com/closeio/tasktiger/blob/59f893152d6eb4b7f1f62fc4b35aeeca7f26c07a/tasktiger/worker.py#L573-L632 | def _process_queue_tasks(self, queue, queue_lock, task_ids, now, log):
"""Process tasks in queue."""
processed_count = 0
# Get all tasks
serialized_tasks = self.connection.mget([
self._key('task', task_id) for task_id in task_ids
])
# Parse tasks
ta... | [
"def",
"_process_queue_tasks",
"(",
"self",
",",
"queue",
",",
"queue_lock",
",",
"task_ids",
",",
"now",
",",
"log",
")",
":",
"processed_count",
"=",
"0",
"# Get all tasks",
"serialized_tasks",
"=",
"self",
".",
"connection",
".",
"mget",
"(",
"[",
"self",... | Process tasks in queue. | [
"Process",
"tasks",
"in",
"queue",
"."
] | python | train | 37.683333 |
pyhys/minimalmodbus | minimalmodbus.py | https://github.com/pyhys/minimalmodbus/blob/e99f4d74c83258c6039073082955ac9bed3f2155/minimalmodbus.py#L261-L296 | def write_register(self, registeraddress, value, numberOfDecimals=0, functioncode=16, signed=False):
"""Write an integer to one 16-bit register in the slave, possibly scaling it.
The slave register can hold integer values in the range 0 to 65535 ("Unsigned INT16").
Args:
* register... | [
"def",
"write_register",
"(",
"self",
",",
"registeraddress",
",",
"value",
",",
"numberOfDecimals",
"=",
"0",
",",
"functioncode",
"=",
"16",
",",
"signed",
"=",
"False",
")",
":",
"_checkFunctioncode",
"(",
"functioncode",
",",
"[",
"6",
",",
"16",
"]",
... | Write an integer to one 16-bit register in the slave, possibly scaling it.
The slave register can hold integer values in the range 0 to 65535 ("Unsigned INT16").
Args:
* registeraddress (int): The slave register address (use decimal numbers, not hex).
* value (int or float): T... | [
"Write",
"an",
"integer",
"to",
"one",
"16",
"-",
"bit",
"register",
"in",
"the",
"slave",
"possibly",
"scaling",
"it",
"."
] | python | train | 50.583333 |
sdispater/cleo | cleo/application.py | https://github.com/sdispater/cleo/blob/cf44ac2eba2d6435516501e47e5521ee2da9115a/cleo/application.py#L38-L45 | def add(self, command): # type: (BaseCommand) -> Application
"""
Adds a command object.
"""
self.add_command(command.config)
command.set_application(self)
return self | [
"def",
"add",
"(",
"self",
",",
"command",
")",
":",
"# type: (BaseCommand) -> Application",
"self",
".",
"add_command",
"(",
"command",
".",
"config",
")",
"command",
".",
"set_application",
"(",
"self",
")",
"return",
"self"
] | Adds a command object. | [
"Adds",
"a",
"command",
"object",
"."
] | python | train | 26.125 |
googledatalab/pydatalab | google/datalab/bigquery/_table.py | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/bigquery/_table.py#L603-L635 | def to_dataframe(self, start_row=0, max_rows=None):
""" Exports the table to a Pandas dataframe.
Args:
start_row: the row of the table at which to start the export (default 0)
max_rows: an upper limit on the number of rows to export (default None)
Returns:
A Pandas dataframe containing th... | [
"def",
"to_dataframe",
"(",
"self",
",",
"start_row",
"=",
"0",
",",
"max_rows",
"=",
"None",
")",
":",
"fetcher",
"=",
"self",
".",
"_get_row_fetcher",
"(",
"start_row",
"=",
"start_row",
",",
"max_rows",
"=",
"max_rows",
",",
"page_size",
"=",
"self",
... | Exports the table to a Pandas dataframe.
Args:
start_row: the row of the table at which to start the export (default 0)
max_rows: an upper limit on the number of rows to export (default None)
Returns:
A Pandas dataframe containing the table data. | [
"Exports",
"the",
"table",
"to",
"a",
"Pandas",
"dataframe",
"."
] | python | train | 36.272727 |
pantsbuild/pants | src/python/pants/option/global_options.py | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/option/global_options.py#L91-L377 | def register_bootstrap_options(cls, register):
"""Register bootstrap options.
"Bootstrap options" are a small set of options whose values are useful when registering other
options. Therefore we must bootstrap them early, before other options are registered, let
alone parsed.
Bootstrap option value... | [
"def",
"register_bootstrap_options",
"(",
"cls",
",",
"register",
")",
":",
"buildroot",
"=",
"get_buildroot",
"(",
")",
"default_distdir_name",
"=",
"'dist'",
"default_distdir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"buildroot",
",",
"default_distdir_name",
... | Register bootstrap options.
"Bootstrap options" are a small set of options whose values are useful when registering other
options. Therefore we must bootstrap them early, before other options are registered, let
alone parsed.
Bootstrap option values can be interpolated into the config file, and can be... | [
"Register",
"bootstrap",
"options",
"."
] | python | train | 67.463415 |
rackerlabs/fleece | fleece/xray.py | https://github.com/rackerlabs/fleece/blob/42d79dfa0777e99dbb09bc46105449a9be5dbaa9/fleece/xray.py#L322-L334 | def extract_function_metadata(wrapped, instance, args, kwargs, return_value):
"""Stash the `args` and `kwargs` into the metadata of the subsegment."""
LOGGER.debug(
'Extracting function call metadata',
args=args,
kwargs=kwargs,
)
return {
'metadata': {
'args':... | [
"def",
"extract_function_metadata",
"(",
"wrapped",
",",
"instance",
",",
"args",
",",
"kwargs",
",",
"return_value",
")",
":",
"LOGGER",
".",
"debug",
"(",
"'Extracting function call metadata'",
",",
"args",
"=",
"args",
",",
"kwargs",
"=",
"kwargs",
",",
")"... | Stash the `args` and `kwargs` into the metadata of the subsegment. | [
"Stash",
"the",
"args",
"and",
"kwargs",
"into",
"the",
"metadata",
"of",
"the",
"subsegment",
"."
] | python | train | 27.769231 |
mattlong/hermes | hermes/chatroom.py | https://github.com/mattlong/hermes/blob/63a5afcafe90ca99aeb44edeee9ed6f90baae431/hermes/chatroom.py#L65-L76 | def is_member(self, m):
"""Check if a user is a member of the chatroom"""
if not m:
return False
elif isinstance(m, basestring):
jid = m
else:
jid = m['JID']
is_member = len(filter(lambda m: m['JID'] == jid and m.get('STATUS') in ('ACTIVE', 'I... | [
"def",
"is_member",
"(",
"self",
",",
"m",
")",
":",
"if",
"not",
"m",
":",
"return",
"False",
"elif",
"isinstance",
"(",
"m",
",",
"basestring",
")",
":",
"jid",
"=",
"m",
"else",
":",
"jid",
"=",
"m",
"[",
"'JID'",
"]",
"is_member",
"=",
"len",... | Check if a user is a member of the chatroom | [
"Check",
"if",
"a",
"user",
"is",
"a",
"member",
"of",
"the",
"chatroom"
] | python | train | 31.083333 |
marrow/mongo | marrow/mongo/query/query.py | https://github.com/marrow/mongo/blob/2066dc73e281b8a46cb5fc965267d6b8e1b18467/marrow/mongo/query/query.py#L505-L526 | def of_type(self, *kinds):
"""Selects documents if a field is of the correct type.
Document.field.of_type()
Document.field.of_type('string')
Element operator: {$type: self.__foreign__}
Documentation: https://docs.mongodb.org/manual/reference/operator/query/type/#op._S_type
"""
if self._combinin... | [
"def",
"of_type",
"(",
"self",
",",
"*",
"kinds",
")",
":",
"if",
"self",
".",
"_combining",
":",
"# We are a field-compound query fragment, e.g. (Foo.bar & Foo.baz).",
"return",
"reduce",
"(",
"self",
".",
"_combining",
",",
"(",
"q",
".",
"of_type",
"(",
"*",
... | Selects documents if a field is of the correct type.
Document.field.of_type()
Document.field.of_type('string')
Element operator: {$type: self.__foreign__}
Documentation: https://docs.mongodb.org/manual/reference/operator/query/type/#op._S_type | [
"Selects",
"documents",
"if",
"a",
"field",
"is",
"of",
"the",
"correct",
"type",
".",
"Document",
".",
"field",
".",
"of_type",
"()",
"Document",
".",
"field",
".",
"of_type",
"(",
"string",
")",
"Element",
"operator",
":",
"{",
"$type",
":",
"self",
... | python | train | 31.863636 |
biolink/ontobio | ontobio/sparql/sparql_ontology.py | https://github.com/biolink/ontobio/blob/4e512a7831cfe6bc1b32f2c3be2ba41bc5cf7345/ontobio/sparql/sparql_ontology.py#L18-L36 | def extract_subset(self, subset):
"""
Find all nodes in a subset.
We assume the oboInOwl encoding of subsets, and subset IDs are IRIs
"""
# note subsets have an unusual encoding
query = """
prefix oboInOwl: <http://www.geneontology.org/formats/oboInOwl#>... | [
"def",
"extract_subset",
"(",
"self",
",",
"subset",
")",
":",
"# note subsets have an unusual encoding",
"query",
"=",
"\"\"\"\n prefix oboInOwl: <http://www.geneontology.org/formats/oboInOwl#>\n SELECT ?c WHERE {{\n GRAPH <{g}> {{\n ?c oboInOwl:inSubset ?s\n ... | Find all nodes in a subset.
We assume the oboInOwl encoding of subsets, and subset IDs are IRIs | [
"Find",
"all",
"nodes",
"in",
"a",
"subset",
".",
"We",
"assume",
"the",
"oboInOwl",
"encoding",
"of",
"subsets",
"and",
"subset",
"IDs",
"are",
"IRIs"
] | python | train | 30.526316 |
pywbem/pywbem | pywbem/_statistics.py | https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/_statistics.py#L676-L722 | def formatted(self):
# pylint: disable=line-too-long
"""
Return a human readable string with the statistics for this container.
The operations are sorted by decreasing average time.
The three columns for `ServerTime` are included only if the WBEM server
has returned WBEM... | [
"def",
"formatted",
"(",
"self",
")",
":",
"# pylint: disable=line-too-long",
"# noqa: E501",
"# pylint: enable=line-too-long",
"ret",
"=",
"\"Statistics (times in seconds, lengths in Bytes):\\n\"",
"if",
"self",
".",
"enabled",
":",
"snapshot",
"=",
"sorted",
"(",
"self",
... | Return a human readable string with the statistics for this container.
The operations are sorted by decreasing average time.
The three columns for `ServerTime` are included only if the WBEM server
has returned WBEM server response times.
Example if statistics are enabled::
... | [
"Return",
"a",
"human",
"readable",
"string",
"with",
"the",
"statistics",
"for",
"this",
"container",
".",
"The",
"operations",
"are",
"sorted",
"by",
"decreasing",
"average",
"time",
"."
] | python | train | 45.12766 |
JasonKessler/scattertext | scattertext/ScatterChart.py | https://github.com/JasonKessler/scattertext/blob/cacf1f687d218ee8cae3fc05cc901db824bb1b81/scattertext/ScatterChart.py#L145-L181 | def inject_coordinates(self,
x_coords,
y_coords,
rescale_x=None,
rescale_y=None,
original_x=None,
original_y=None):
'''
Inject custom x and y ... | [
"def",
"inject_coordinates",
"(",
"self",
",",
"x_coords",
",",
"y_coords",
",",
"rescale_x",
"=",
"None",
",",
"rescale_y",
"=",
"None",
",",
"original_x",
"=",
"None",
",",
"original_y",
"=",
"None",
")",
":",
"self",
".",
"_verify_coordinates",
"(",
"x_... | Inject custom x and y coordinates for each term into chart.
Parameters
----------
x_coords: array-like
positions on x-axis \in [0,1]
y_coords: array-like
positions on y-axis \in [0,1]
rescale_x: lambda list[0,1]: list[0,1], default identity
Re... | [
"Inject",
"custom",
"x",
"and",
"y",
"coordinates",
"for",
"each",
"term",
"into",
"chart",
"."
] | python | train | 37.351351 |
jtwhite79/pyemu | pyemu/pst/pst_utils.py | https://github.com/jtwhite79/pyemu/blob/c504d8e7a4097cec07655a6318d275739bd8148a/pyemu/pst/pst_utils.py#L151-L187 | def res_from_en(pst,enfile):
"""load ensemble file for residual into a pandas.DataFrame
Parameters
----------
enfile : str
ensemble file name
Returns
-------
pandas.DataFrame : pandas.DataFrame
"""
converters = {"name": str_con, "group": str... | [
"def",
"res_from_en",
"(",
"pst",
",",
"enfile",
")",
":",
"converters",
"=",
"{",
"\"name\"",
":",
"str_con",
",",
"\"group\"",
":",
"str_con",
"}",
"try",
":",
"#substitute ensemble for res, 'base' if there, otherwise mean",
"obs",
"=",
"pst",
".",
"observation_... | load ensemble file for residual into a pandas.DataFrame
Parameters
----------
enfile : str
ensemble file name
Returns
-------
pandas.DataFrame : pandas.DataFrame | [
"load",
"ensemble",
"file",
"for",
"residual",
"into",
"a",
"pandas",
".",
"DataFrame"
] | python | train | 34.351351 |
Azure/msrest-for-python | msrest/serialization.py | https://github.com/Azure/msrest-for-python/blob/0732bc90bdb290e5f58c675ffdd7dbfa9acefc93/msrest/serialization.py#L857-L899 | def serialize_object(self, attr, **kwargs):
"""Serialize a generic object.
This will be handled as a dictionary. If object passed in is not
a basic type (str, int, float, dict, list) it will simply be
cast to str.
:param dict attr: Object to be serialized.
:rtype: dict o... | [
"def",
"serialize_object",
"(",
"self",
",",
"attr",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"attr",
"is",
"None",
":",
"return",
"None",
"if",
"isinstance",
"(",
"attr",
",",
"ET",
".",
"Element",
")",
":",
"return",
"attr",
"obj_type",
"=",
"type"... | Serialize a generic object.
This will be handled as a dictionary. If object passed in is not
a basic type (str, int, float, dict, list) it will simply be
cast to str.
:param dict attr: Object to be serialized.
:rtype: dict or str | [
"Serialize",
"a",
"generic",
"object",
".",
"This",
"will",
"be",
"handled",
"as",
"a",
"dictionary",
".",
"If",
"object",
"passed",
"in",
"is",
"not",
"a",
"basic",
"type",
"(",
"str",
"int",
"float",
"dict",
"list",
")",
"it",
"will",
"simply",
"be",... | python | train | 36.023256 |
kivy/python-for-android | pythonforandroid/bootstraps/common/build/build.py | https://github.com/kivy/python-for-android/blob/8e0e8056bc22e4d5bd3398a6b0301f38ff167933/pythonforandroid/bootstraps/common/build/build.py#L201-L247 | def make_tar(tfn, source_dirs, ignore_path=[], optimize_python=True):
'''
Make a zip file `fn` from the contents of source_dis.
'''
# selector function
def select(fn):
rfn = realpath(fn)
for p in ignore_path:
if p.endswith('/'):
p = p[:-1]
if ... | [
"def",
"make_tar",
"(",
"tfn",
",",
"source_dirs",
",",
"ignore_path",
"=",
"[",
"]",
",",
"optimize_python",
"=",
"True",
")",
":",
"# selector function",
"def",
"select",
"(",
"fn",
")",
":",
"rfn",
"=",
"realpath",
"(",
"fn",
")",
"for",
"p",
"in",
... | Make a zip file `fn` from the contents of source_dis. | [
"Make",
"a",
"zip",
"file",
"fn",
"from",
"the",
"contents",
"of",
"source_dis",
"."
] | python | train | 30.106383 |
UCBerkeleySETI/blimpy | blimpy/utils.py | https://github.com/UCBerkeleySETI/blimpy/blob/b8822d3e3e911944370d84371a91fa0c29e9772e/blimpy/utils.py#L24-L51 | def rebin(d, n_x, n_y=None):
""" Rebin data by averaging bins together
Args:
d (np.array): data
n_x (int): number of bins in x dir to rebin into one
n_y (int): number of bins in y dir to rebin into one
Returns:
d: rebinned data with shape (n_x, n_y)
"""
if d.ndim == 2:
if ... | [
"def",
"rebin",
"(",
"d",
",",
"n_x",
",",
"n_y",
"=",
"None",
")",
":",
"if",
"d",
".",
"ndim",
"==",
"2",
":",
"if",
"n_y",
"is",
"None",
":",
"n_y",
"=",
"1",
"if",
"n_x",
"is",
"None",
":",
"n_x",
"=",
"1",
"d",
"=",
"d",
"[",
":",
... | Rebin data by averaging bins together
Args:
d (np.array): data
n_x (int): number of bins in x dir to rebin into one
n_y (int): number of bins in y dir to rebin into one
Returns:
d: rebinned data with shape (n_x, n_y) | [
"Rebin",
"data",
"by",
"averaging",
"bins",
"together"
] | python | test | 28.25 |
glue-viz/glue-vispy-viewers | glue_vispy_viewers/extern/vispy/gloo/context.py | https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/gloo/context.py#L79-L85 | def forget_canvas(canvas):
""" Forget about the given canvas. Used by the canvas when closed.
"""
cc = [c() for c in canvasses if c() is not None]
while canvas in cc:
cc.remove(canvas)
canvasses[:] = [weakref.ref(c) for c in cc] | [
"def",
"forget_canvas",
"(",
"canvas",
")",
":",
"cc",
"=",
"[",
"c",
"(",
")",
"for",
"c",
"in",
"canvasses",
"if",
"c",
"(",
")",
"is",
"not",
"None",
"]",
"while",
"canvas",
"in",
"cc",
":",
"cc",
".",
"remove",
"(",
"canvas",
")",
"canvasses"... | Forget about the given canvas. Used by the canvas when closed. | [
"Forget",
"about",
"the",
"given",
"canvas",
".",
"Used",
"by",
"the",
"canvas",
"when",
"closed",
"."
] | python | train | 35.714286 |
Alignak-monitoring/alignak | alignak/objects/schedulingitem.py | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/schedulingitem.py#L1316-L1332 | def disable_active_checks(self, checks):
"""Disable active checks for this host/service
Update check in progress with current object information
:param checks: Checks object, to change all checks in progress
:type checks: alignak.objects.check.Checks
:return: None
"""
... | [
"def",
"disable_active_checks",
"(",
"self",
",",
"checks",
")",
":",
"self",
".",
"active_checks_enabled",
"=",
"False",
"for",
"chk_id",
"in",
"self",
".",
"checks_in_progress",
":",
"chk",
"=",
"checks",
"[",
"chk_id",
"]",
"chk",
".",
"status",
"=",
"A... | Disable active checks for this host/service
Update check in progress with current object information
:param checks: Checks object, to change all checks in progress
:type checks: alignak.objects.check.Checks
:return: None | [
"Disable",
"active",
"checks",
"for",
"this",
"host",
"/",
"service",
"Update",
"check",
"in",
"progress",
"with",
"current",
"object",
"information"
] | python | train | 39.588235 |
refenv/cijoe | modules/cij/runner.py | https://github.com/refenv/cijoe/blob/21d7b2ed4ff68e0a1457e7df2db27f6334f1a379/modules/cij/runner.py#L199-L230 | def hooks_setup(trun, parent, hnames=None):
"""
Setup test-hooks
@returns dict of hook filepaths {"enter": [], "exit": []}
"""
hooks = {
"enter": [],
"exit": []
}
if hnames is None: # Nothing to do, just return the struct
return hooks
for hname in hnames:... | [
"def",
"hooks_setup",
"(",
"trun",
",",
"parent",
",",
"hnames",
"=",
"None",
")",
":",
"hooks",
"=",
"{",
"\"enter\"",
":",
"[",
"]",
",",
"\"exit\"",
":",
"[",
"]",
"}",
"if",
"hnames",
"is",
"None",
":",
"# Nothing to do, just return the struct",
"ret... | Setup test-hooks
@returns dict of hook filepaths {"enter": [], "exit": []} | [
"Setup",
"test",
"-",
"hooks"
] | python | valid | 26.71875 |
senseobservationsystems/commonsense-python-lib | senseapi.py | https://github.com/senseobservationsystems/commonsense-python-lib/blob/aac59a1751ef79eb830b3ca1fab6ef2c83931f87/senseapi.py#L744-L761 | def GroupSensorsFind(self, group_id, parameters, filters, namespace = None):
"""
Find sensors in a group based on a number of filters on metatags
@param group_id (int) - Id of the group in which to find sensors
@param namespace (string) - Namespace to use in... | [
"def",
"GroupSensorsFind",
"(",
"self",
",",
"group_id",
",",
"parameters",
",",
"filters",
",",
"namespace",
"=",
"None",
")",
":",
"ns",
"=",
"\"default\"",
"if",
"namespace",
"is",
"None",
"else",
"namespace",
"parameters",
"[",
"'namespace'",
"]",
"=",
... | Find sensors in a group based on a number of filters on metatags
@param group_id (int) - Id of the group in which to find sensors
@param namespace (string) - Namespace to use in filtering on metatags
@param parameters (dictionary) - Dictionary containing additional p... | [
"Find",
"sensors",
"in",
"a",
"group",
"based",
"on",
"a",
"number",
"of",
"filters",
"on",
"metatags"
] | python | train | 55.166667 |
HDI-Project/BTB | btb/tuning/tuner.py | https://github.com/HDI-Project/BTB/blob/7f489ebc5591bd0886652ef743098c022d7f7460/btb/tuning/tuner.py#L44-L50 | def _generate_grid(self):
"""Get the all possible values for each of the tunables."""
grid_axes = []
for _, param in self.tunables:
grid_axes.append(param.get_grid_axis(self.grid_width))
return grid_axes | [
"def",
"_generate_grid",
"(",
"self",
")",
":",
"grid_axes",
"=",
"[",
"]",
"for",
"_",
",",
"param",
"in",
"self",
".",
"tunables",
":",
"grid_axes",
".",
"append",
"(",
"param",
".",
"get_grid_axis",
"(",
"self",
".",
"grid_width",
")",
")",
"return"... | Get the all possible values for each of the tunables. | [
"Get",
"the",
"all",
"possible",
"values",
"for",
"each",
"of",
"the",
"tunables",
"."
] | python | train | 34.571429 |
dhylands/rshell | rshell/main.py | https://github.com/dhylands/rshell/blob/a92a8fa8074ac792241c83c640a51b394667c324/rshell/main.py#L386-L404 | def column_print(fmt, rows, print_func):
"""Prints a formatted list, adjusting the width so everything fits.
fmt contains a single character for each column. < indicates that the
column should be left justified, > indicates that the column should
be right justified. The last column may be a space which ... | [
"def",
"column_print",
"(",
"fmt",
",",
"rows",
",",
"print_func",
")",
":",
"# Figure out the max width of each column",
"num_cols",
"=",
"len",
"(",
"fmt",
")",
"width",
"=",
"[",
"max",
"(",
"0",
"if",
"isinstance",
"(",
"row",
",",
"str",
")",
"else",
... | Prints a formatted list, adjusting the width so everything fits.
fmt contains a single character for each column. < indicates that the
column should be left justified, > indicates that the column should
be right justified. The last column may be a space which implies left
justification and no padding. | [
"Prints",
"a",
"formatted",
"list",
"adjusting",
"the",
"width",
"so",
"everything",
"fits",
".",
"fmt",
"contains",
"a",
"single",
"character",
"for",
"each",
"column",
".",
"<",
"indicates",
"that",
"the",
"column",
"should",
"be",
"left",
"justified",
">"... | python | train | 45 |
chaoss/grimoirelab-perceval | perceval/utils.py | https://github.com/chaoss/grimoirelab-perceval/blob/41c908605e88b7ebc3a536c643fa0f212eaf9e0e/perceval/utils.py#L224-L270 | def xml_to_dict(raw_xml):
"""Convert a XML stream into a dictionary.
This function transforms a xml stream into a dictionary. The
attributes are stored as single elements while child nodes are
stored into lists. The text node is stored using the special
key '__text__'.
This code is based on Wi... | [
"def",
"xml_to_dict",
"(",
"raw_xml",
")",
":",
"def",
"node_to_dict",
"(",
"node",
")",
":",
"d",
"=",
"{",
"}",
"d",
".",
"update",
"(",
"node",
".",
"items",
"(",
")",
")",
"text",
"=",
"getattr",
"(",
"node",
",",
"'text'",
",",
"None",
")",
... | Convert a XML stream into a dictionary.
This function transforms a xml stream into a dictionary. The
attributes are stored as single elements while child nodes are
stored into lists. The text node is stored using the special
key '__text__'.
This code is based on Winston Ewert's solution to this pr... | [
"Convert",
"a",
"XML",
"stream",
"into",
"a",
"dictionary",
"."
] | python | test | 27.191489 |
ktdreyer/treq-kerberos | treq_kerberos/__init__.py | https://github.com/ktdreyer/treq-kerberos/blob/8331867cf2bade6b4f9d6d7035b72679c4eafc28/treq_kerberos/__init__.py#L73-L83 | def negotiate_header(url):
"""
Return the "Authorization" HTTP header value to use for this URL.
"""
hostname = urlparse(url).hostname
_, krb_context = kerberos.authGSSClientInit('HTTP@%s' % hostname)
# authGSSClientStep goes over the network to the KDC (ie blocking).
yield threads.deferToTh... | [
"def",
"negotiate_header",
"(",
"url",
")",
":",
"hostname",
"=",
"urlparse",
"(",
"url",
")",
".",
"hostname",
"_",
",",
"krb_context",
"=",
"kerberos",
".",
"authGSSClientInit",
"(",
"'HTTP@%s'",
"%",
"hostname",
")",
"# authGSSClientStep goes over the network t... | Return the "Authorization" HTTP header value to use for this URL. | [
"Return",
"the",
"Authorization",
"HTTP",
"header",
"value",
"to",
"use",
"for",
"this",
"URL",
"."
] | python | train | 46.818182 |
Phylliade/ikpy | src/ikpy/geometry_utils.py | https://github.com/Phylliade/ikpy/blob/60e36d6163136942bf520d952db17123c658d0b6/src/ikpy/geometry_utils.py#L10-L16 | def Rx_matrix(theta):
"""Rotation matrix around the X axis"""
return np.array([
[1, 0, 0],
[0, np.cos(theta), -np.sin(theta)],
[0, np.sin(theta), np.cos(theta)]
]) | [
"def",
"Rx_matrix",
"(",
"theta",
")",
":",
"return",
"np",
".",
"array",
"(",
"[",
"[",
"1",
",",
"0",
",",
"0",
"]",
",",
"[",
"0",
",",
"np",
".",
"cos",
"(",
"theta",
")",
",",
"-",
"np",
".",
"sin",
"(",
"theta",
")",
"]",
",",
"[",
... | Rotation matrix around the X axis | [
"Rotation",
"matrix",
"around",
"the",
"X",
"axis"
] | python | train | 27.571429 |
aheadley/python-crunchyroll | crunchyroll/subtitles.py | https://github.com/aheadley/python-crunchyroll/blob/9bf2eb644f0d0f3e9dc21b95b8e355c6e2050178/crunchyroll/subtitles.py#L61-L72 | def decrypt(self, encryption_key, iv, encrypted_data):
"""Decrypt encrypted subtitle data
@param int subtitle_id
@param str iv
@param str encrypted_data
@return str
"""
logger.info('Decrypting subtitles with length (%d bytes), key=%r',
len(encrypted_... | [
"def",
"decrypt",
"(",
"self",
",",
"encryption_key",
",",
"iv",
",",
"encrypted_data",
")",
":",
"logger",
".",
"info",
"(",
"'Decrypting subtitles with length (%d bytes), key=%r'",
",",
"len",
"(",
"encrypted_data",
")",
",",
"encryption_key",
")",
"return",
"zl... | Decrypt encrypted subtitle data
@param int subtitle_id
@param str iv
@param str encrypted_data
@return str | [
"Decrypt",
"encrypted",
"subtitle",
"data"
] | python | train | 34.25 |
kkinder/NdbSearchableBase | NdbSearchableBase/SearchableModel.py | https://github.com/kkinder/NdbSearchableBase/blob/4f999336b464704a0929cec135c1f09fb1ddfb7c/NdbSearchableBase/SearchableModel.py#L188-L195 | def _pre_delete_hook(cls, key):
"""
Removes instance from index.
"""
if cls.searching_enabled:
doc_id = cls.search_get_document_id(key)
index = cls.search_get_index()
index.delete(doc_id) | [
"def",
"_pre_delete_hook",
"(",
"cls",
",",
"key",
")",
":",
"if",
"cls",
".",
"searching_enabled",
":",
"doc_id",
"=",
"cls",
".",
"search_get_document_id",
"(",
"key",
")",
"index",
"=",
"cls",
".",
"search_get_index",
"(",
")",
"index",
".",
"delete",
... | Removes instance from index. | [
"Removes",
"instance",
"from",
"index",
"."
] | python | train | 31 |
titusjan/argos | argos/inspector/registry.py | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/inspector/registry.py#L55-L63 | def create(self, collector, tryImport=True):
""" Creates an inspector of the registered and passes the collector to the constructor.
Tries to import the class if tryImport is True.
Raises ImportError if the class could not be imported.
"""
cls = self.getClass(tryImport=tr... | [
"def",
"create",
"(",
"self",
",",
"collector",
",",
"tryImport",
"=",
"True",
")",
":",
"cls",
"=",
"self",
".",
"getClass",
"(",
"tryImport",
"=",
"tryImport",
")",
"if",
"not",
"self",
".",
"successfullyImported",
":",
"raise",
"ImportError",
"(",
"\"... | Creates an inspector of the registered and passes the collector to the constructor.
Tries to import the class if tryImport is True.
Raises ImportError if the class could not be imported. | [
"Creates",
"an",
"inspector",
"of",
"the",
"registered",
"and",
"passes",
"the",
"collector",
"to",
"the",
"constructor",
".",
"Tries",
"to",
"import",
"the",
"class",
"if",
"tryImport",
"is",
"True",
".",
"Raises",
"ImportError",
"if",
"the",
"class",
"coul... | python | train | 53.777778 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.