repo stringlengths 7 54 | path stringlengths 4 192 | url stringlengths 87 284 | code stringlengths 78 104k | code_tokens list | docstring stringlengths 1 46.9k | docstring_tokens list | language stringclasses 1
value | partition stringclasses 3
values |
|---|---|---|---|---|---|---|---|---|
googleapis/google-cloud-python | firestore/google/cloud/firestore_v1beta1/query.py | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/query.py#L377-L429 | def _cursor_helper(self, document_fields, before, start):
"""Set values to be used for a ``start_at`` or ``end_at`` cursor.
The values will later be used in a query protobuf.
When the query is sent to the server, the ``document_fields`` will
be used in the order given by fields set by
... | [
"def",
"_cursor_helper",
"(",
"self",
",",
"document_fields",
",",
"before",
",",
"start",
")",
":",
"if",
"isinstance",
"(",
"document_fields",
",",
"tuple",
")",
":",
"document_fields",
"=",
"list",
"(",
"document_fields",
")",
"elif",
"isinstance",
"(",
"... | Set values to be used for a ``start_at`` or ``end_at`` cursor.
The values will later be used in a query protobuf.
When the query is sent to the server, the ``document_fields`` will
be used in the order given by fields set by
:meth:`~.firestore_v1beta1.query.Query.order_by`.
Ar... | [
"Set",
"values",
"to",
"be",
"used",
"for",
"a",
"start_at",
"or",
"end_at",
"cursor",
"."
] | python | train |
tomplus/kubernetes_asyncio | kubernetes_asyncio/client/api/rbac_authorization_v1_api.py | https://github.com/tomplus/kubernetes_asyncio/blob/f9ab15317ec921409714c7afef11aeb0f579985d/kubernetes_asyncio/client/api/rbac_authorization_v1_api.py#L143-L166 | def create_cluster_role_binding(self, body, **kwargs): # noqa: E501
"""create_cluster_role_binding # noqa: E501
create a ClusterRoleBinding # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>... | [
"def",
"create_cluster_role_binding",
"(",
"self",
",",
"body",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async_req'",
")",
":",
"return",
"self",
".",
... | create_cluster_role_binding # noqa: E501
create a ClusterRoleBinding # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.create_cluster_role_binding(body, async_req=True)
>>> re... | [
"create_cluster_role_binding",
"#",
"noqa",
":",
"E501"
] | python | train |
hadrianl/huobi | huobitrade/service.py | https://github.com/hadrianl/huobi/blob/bbfa2036703ee84a76d5d8e9f89c25fc8a55f2c7/huobitrade/service.py#L729-L747 | def get_last_depth(self, symbol, _type):
"""
获取marketdepth
:param symbol
:param type: 可选值:{ percent10, step0, step1, step2, step3, step4, step5 }
:return:
"""
params = {'symbol': symbol, 'type': _type}
url = u.MARKET_URL + '/market/depth'
def _wr... | [
"def",
"get_last_depth",
"(",
"self",
",",
"symbol",
",",
"_type",
")",
":",
"params",
"=",
"{",
"'symbol'",
":",
"symbol",
",",
"'type'",
":",
"_type",
"}",
"url",
"=",
"u",
".",
"MARKET_URL",
"+",
"'/market/depth'",
"def",
"_wrapper",
"(",
"_func",
"... | 获取marketdepth
:param symbol
:param type: 可选值:{ percent10, step0, step1, step2, step3, step4, step5 }
:return: | [
"获取marketdepth",
":",
"param",
"symbol",
":",
"param",
"type",
":",
"可选值:",
"{",
"percent10",
"step0",
"step1",
"step2",
"step3",
"step4",
"step5",
"}",
":",
"return",
":"
] | python | train |
developmentseed/landsat-util | landsat/mixins.py | https://github.com/developmentseed/landsat-util/blob/92dc81771ddaa64a8a9124a89a6516b52485374b/landsat/mixins.py#L102-L115 | def _print(self, msg, color=None, arrow=False, indent=None):
""" Print the msg with the color provided. """
if color:
msg = colored(msg, color)
if arrow:
msg = colored('===> ', 'blue') + msg
if indent:
msg = (' ' * indent) + msg
print(ms... | [
"def",
"_print",
"(",
"self",
",",
"msg",
",",
"color",
"=",
"None",
",",
"arrow",
"=",
"False",
",",
"indent",
"=",
"None",
")",
":",
"if",
"color",
":",
"msg",
"=",
"colored",
"(",
"msg",
",",
"color",
")",
"if",
"arrow",
":",
"msg",
"=",
"co... | Print the msg with the color provided. | [
"Print",
"the",
"msg",
"with",
"the",
"color",
"provided",
"."
] | python | train |
google/apitools | apitools/gen/util.py | https://github.com/google/apitools/blob/f3745a7ea535aa0e88b0650c16479b696d6fd446/apitools/gen/util.py#L137-L142 | def MethodName(self, name, separator='_'):
"""Generate a valid method name from name."""
if name is None:
return None
name = Names.__ToCamel(name, separator=separator)
return Names.CleanName(name) | [
"def",
"MethodName",
"(",
"self",
",",
"name",
",",
"separator",
"=",
"'_'",
")",
":",
"if",
"name",
"is",
"None",
":",
"return",
"None",
"name",
"=",
"Names",
".",
"__ToCamel",
"(",
"name",
",",
"separator",
"=",
"separator",
")",
"return",
"Names",
... | Generate a valid method name from name. | [
"Generate",
"a",
"valid",
"method",
"name",
"from",
"name",
"."
] | python | train |
Anaconda-Platform/anaconda-client | binstar_client/inspect_package/conda.py | https://github.com/Anaconda-Platform/anaconda-client/blob/b276f0572744c73c184a8b43a897cfa7fc1dc523/binstar_client/inspect_package/conda.py#L59-L77 | def get_subdir(index):
"""
Return the sub-directory given the index dictionary. The return
value is obtained in the following order:
1. when the 'subdir' key exists, it's value is returned
2. if the 'arch' is None, or does not exist, 'noarch' is returned
3. otherwise, the return value is const... | [
"def",
"get_subdir",
"(",
"index",
")",
":",
"try",
":",
"return",
"index",
"[",
"'subdir'",
"]",
"except",
"KeyError",
":",
"arch",
"=",
"index",
".",
"get",
"(",
"'arch'",
")",
"if",
"arch",
"is",
"None",
":",
"return",
"'noarch'",
"intel_map",
"=",
... | Return the sub-directory given the index dictionary. The return
value is obtained in the following order:
1. when the 'subdir' key exists, it's value is returned
2. if the 'arch' is None, or does not exist, 'noarch' is returned
3. otherwise, the return value is constructed from the 'platform' key
... | [
"Return",
"the",
"sub",
"-",
"directory",
"given",
"the",
"index",
"dictionary",
".",
"The",
"return",
"value",
"is",
"obtained",
"in",
"the",
"following",
"order",
":"
] | python | train |
obulpathi/cdn-fastly-python | fastly/__init__.py | https://github.com/obulpathi/cdn-fastly-python/blob/db2564b047e8af4bce72c3b88d6c27d3d0291425/fastly/__init__.py#L402-L414 | def create_domain(self,
service_id,
version_number,
name,
comment=None):
"""Create a domain for a particular service and version."""
body = self._formdata({
"name": name,
"comment": comment,
}, FastlyDomain.FIELDS)
content = self._fetch("/service/%s/version/%d/domain" % (service_id, version_nu... | [
"def",
"create_domain",
"(",
"self",
",",
"service_id",
",",
"version_number",
",",
"name",
",",
"comment",
"=",
"None",
")",
":",
"body",
"=",
"self",
".",
"_formdata",
"(",
"{",
"\"name\"",
":",
"name",
",",
"\"comment\"",
":",
"comment",
",",
"}",
"... | Create a domain for a particular service and version. | [
"Create",
"a",
"domain",
"for",
"a",
"particular",
"service",
"and",
"version",
"."
] | python | train |
sci-bots/serial-device | serial_device/mqtt.py | https://github.com/sci-bots/serial-device/blob/5de1c3fc447ae829b57d80073ec6ac4fba3283c6/serial_device/mqtt.py#L108-L138 | def on_message(self, client, userdata, msg):
'''
Callback for when a ``PUBLISH`` message is received from the broker.
'''
if msg.topic == 'serial_device/refresh_comports':
self.refresh_comports()
return
match = CRE_MANAGER.match(msg.topic)
if matc... | [
"def",
"on_message",
"(",
"self",
",",
"client",
",",
"userdata",
",",
"msg",
")",
":",
"if",
"msg",
".",
"topic",
"==",
"'serial_device/refresh_comports'",
":",
"self",
".",
"refresh_comports",
"(",
")",
"return",
"match",
"=",
"CRE_MANAGER",
".",
"match",
... | Callback for when a ``PUBLISH`` message is received from the broker. | [
"Callback",
"for",
"when",
"a",
"PUBLISH",
"message",
"is",
"received",
"from",
"the",
"broker",
"."
] | python | train |
matllubos/django-is-core | is_core/utils/__init__.py | https://github.com/matllubos/django-is-core/blob/3f87ec56a814738683c732dce5f07e0328c2300d/is_core/utils/__init__.py#L284-L298 | def get_url_from_model_core(request, obj):
"""
Returns object URL from model core.
"""
from is_core.site import get_model_core
model_core = get_model_core(obj.__class__)
if model_core and hasattr(model_core, 'ui_patterns'):
edit_pattern = model_core.ui_patterns.get('detail')
ret... | [
"def",
"get_url_from_model_core",
"(",
"request",
",",
"obj",
")",
":",
"from",
"is_core",
".",
"site",
"import",
"get_model_core",
"model_core",
"=",
"get_model_core",
"(",
"obj",
".",
"__class__",
")",
"if",
"model_core",
"and",
"hasattr",
"(",
"model_core",
... | Returns object URL from model core. | [
"Returns",
"object",
"URL",
"from",
"model",
"core",
"."
] | python | train |
MolSSI-BSE/basis_set_exchange | basis_set_exchange/api.py | https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/api.py#L539-L546 | def has_basis_notes(family, data_dir=None):
'''Check if notes exist for a given basis set
Returns True if they exist, false otherwise
'''
file_path = _basis_notes_path(family, data_dir)
return os.path.isfile(file_path) | [
"def",
"has_basis_notes",
"(",
"family",
",",
"data_dir",
"=",
"None",
")",
":",
"file_path",
"=",
"_basis_notes_path",
"(",
"family",
",",
"data_dir",
")",
"return",
"os",
".",
"path",
".",
"isfile",
"(",
"file_path",
")"
] | Check if notes exist for a given basis set
Returns True if they exist, false otherwise | [
"Check",
"if",
"notes",
"exist",
"for",
"a",
"given",
"basis",
"set"
] | python | train |
AoiKuiyuyou/AoikLiveReload | src/aoiklivereload/aoiklivereload.py | https://github.com/AoiKuiyuyou/AoikLiveReload/blob/0d5adb12118a33749e6690a8165fdb769cff7d5c/src/aoiklivereload/aoiklivereload.py#L263-L315 | def _find_short_paths(self, paths):
"""
Find short paths of given paths.
E.g. if both `/home` and `/home/aoik` exist, only keep `/home`.
:param paths:
Paths.
:return:
Set of short paths.
"""
# Split each path to parts.
# E.g. '/h... | [
"def",
"_find_short_paths",
"(",
"self",
",",
"paths",
")",
":",
"# Split each path to parts.",
"# E.g. '/home/aoik' to ['', 'home', 'aoik']",
"path_parts_s",
"=",
"[",
"path",
".",
"split",
"(",
"os",
".",
"path",
".",
"sep",
")",
"for",
"path",
"in",
"paths",
... | Find short paths of given paths.
E.g. if both `/home` and `/home/aoik` exist, only keep `/home`.
:param paths:
Paths.
:return:
Set of short paths. | [
"Find",
"short",
"paths",
"of",
"given",
"paths",
"."
] | python | train |
CodeReclaimers/neat-python | neat/genome.py | https://github.com/CodeReclaimers/neat-python/blob/e3dbe77c0d776eae41d598e6439e6ac02ab90b18/neat/genome.py#L479-L488 | def connect_fs_neat_nohidden(self, config):
"""
Randomly connect one input to all output nodes
(FS-NEAT without connections to hidden, if any).
Originally connect_fs_neat.
"""
input_id = choice(config.input_keys)
for output_id in config.output_keys:
co... | [
"def",
"connect_fs_neat_nohidden",
"(",
"self",
",",
"config",
")",
":",
"input_id",
"=",
"choice",
"(",
"config",
".",
"input_keys",
")",
"for",
"output_id",
"in",
"config",
".",
"output_keys",
":",
"connection",
"=",
"self",
".",
"create_connection",
"(",
... | Randomly connect one input to all output nodes
(FS-NEAT without connections to hidden, if any).
Originally connect_fs_neat. | [
"Randomly",
"connect",
"one",
"input",
"to",
"all",
"output",
"nodes",
"(",
"FS",
"-",
"NEAT",
"without",
"connections",
"to",
"hidden",
"if",
"any",
")",
".",
"Originally",
"connect_fs_neat",
"."
] | python | train |
pulseenergy/vacation | vacation/transactions.py | https://github.com/pulseenergy/vacation/blob/23c6122590852a5e55d84d366143469af6602839/vacation/transactions.py#L20-L41 | def execute(tokens):
""" Perform the actions described by the input tokens. """
if not validate_rc():
print('Your .vacationrc file has errors!')
echo_vacation_rc()
return
for action, value in tokens:
if action == 'show':
show()
elif action == 'log':
... | [
"def",
"execute",
"(",
"tokens",
")",
":",
"if",
"not",
"validate_rc",
"(",
")",
":",
"print",
"(",
"'Your .vacationrc file has errors!'",
")",
"echo_vacation_rc",
"(",
")",
"return",
"for",
"action",
",",
"value",
"in",
"tokens",
":",
"if",
"action",
"==",
... | Perform the actions described by the input tokens. | [
"Perform",
"the",
"actions",
"described",
"by",
"the",
"input",
"tokens",
"."
] | python | train |
baguette-io/baguette-messaging | farine/mixins.py | https://github.com/baguette-io/baguette-messaging/blob/8d1c4707ea7eace8617fed2d97df2fcc9d0cdee1/farine/mixins.py#L50-L64 | def database(self):
"""
Before the callback is called, initialize the database if needed.
:rtype: None
"""
#1. Initialize
self.callback.im_self.db = sql.setup(self.settings)
if self.callback.im_self.db:
module = '.'.join(self.callback.im_self.__module_... | [
"def",
"database",
"(",
"self",
")",
":",
"#1. Initialize",
"self",
".",
"callback",
".",
"im_self",
".",
"db",
"=",
"sql",
".",
"setup",
"(",
"self",
".",
"settings",
")",
"if",
"self",
".",
"callback",
".",
"im_self",
".",
"db",
":",
"module",
"=",... | Before the callback is called, initialize the database if needed.
:rtype: None | [
"Before",
"the",
"callback",
"is",
"called",
"initialize",
"the",
"database",
"if",
"needed",
".",
":",
"rtype",
":",
"None"
] | python | train |
inveniosoftware/invenio-pages | invenio_pages/admin.py | https://github.com/inveniosoftware/invenio-pages/blob/8d544d72fb4c22b7134c521f435add0abed42544/invenio_pages/admin.py#L64-L69 | def template_exists(form, field):
"""Form validation: check that selected template exists."""
try:
current_app.jinja_env.get_template(field.data)
except TemplateNotFound:
raise ValidationError(_("Template selected does not exist")) | [
"def",
"template_exists",
"(",
"form",
",",
"field",
")",
":",
"try",
":",
"current_app",
".",
"jinja_env",
".",
"get_template",
"(",
"field",
".",
"data",
")",
"except",
"TemplateNotFound",
":",
"raise",
"ValidationError",
"(",
"_",
"(",
"\"Template selected ... | Form validation: check that selected template exists. | [
"Form",
"validation",
":",
"check",
"that",
"selected",
"template",
"exists",
"."
] | python | train |
vsergeev/python-periphery | periphery/serial.py | https://github.com/vsergeev/python-periphery/blob/ff4d535691a1747a76962a3d077d96d224308611/periphery/serial.py#L281-L298 | def input_waiting(self):
"""Query the number of bytes waiting to be read from the serial port.
Returns:
int: number of bytes waiting to be read.
Raises:
SerialError: if an I/O or OS error occurs.
"""
# Get input waiting
buf = array.array('I', [0... | [
"def",
"input_waiting",
"(",
"self",
")",
":",
"# Get input waiting",
"buf",
"=",
"array",
".",
"array",
"(",
"'I'",
",",
"[",
"0",
"]",
")",
"try",
":",
"fcntl",
".",
"ioctl",
"(",
"self",
".",
"_fd",
",",
"termios",
".",
"TIOCINQ",
",",
"buf",
",... | Query the number of bytes waiting to be read from the serial port.
Returns:
int: number of bytes waiting to be read.
Raises:
SerialError: if an I/O or OS error occurs. | [
"Query",
"the",
"number",
"of",
"bytes",
"waiting",
"to",
"be",
"read",
"from",
"the",
"serial",
"port",
"."
] | python | train |
linkhub-sdk/popbill.py | popbill/base.py | https://github.com/linkhub-sdk/popbill.py/blob/68a0dd7f7a937603318e93be321fde73c50b96cc/popbill/base.py#L140-L151 | def getAccessURL(self, CorpNum, UserID):
""" 팝빌 로그인 URL
args
CorpNum : 회원 사업자번호
UserID : 회원 팝빌아이디
return
30초 보안 토큰을 포함한 url
raise
PopbillException
"""
result = self._httpget('/?TG=LOGIN', CorpNum... | [
"def",
"getAccessURL",
"(",
"self",
",",
"CorpNum",
",",
"UserID",
")",
":",
"result",
"=",
"self",
".",
"_httpget",
"(",
"'/?TG=LOGIN'",
",",
"CorpNum",
",",
"UserID",
")",
"return",
"result",
".",
"url"
] | 팝빌 로그인 URL
args
CorpNum : 회원 사업자번호
UserID : 회원 팝빌아이디
return
30초 보안 토큰을 포함한 url
raise
PopbillException | [
"팝빌",
"로그인",
"URL",
"args",
"CorpNum",
":",
"회원",
"사업자번호",
"UserID",
":",
"회원",
"팝빌아이디",
"return",
"30초",
"보안",
"토큰을",
"포함한",
"url",
"raise",
"PopbillException"
] | python | train |
osrg/ryu | ryu/services/protocols/bgp/utils/rtfilter.py | https://github.com/osrg/ryu/blob/6f906e72c92e10bd0264c9b91a2f7bb85b97780c/ryu/services/protocols/bgp/utils/rtfilter.py#L120-L138 | def update_local_rt_nlris(self):
"""Does book-keeping of local RT NLRIs based on all configured VRFs.
Syncs all import RTs and RT NLRIs.
The method should be called when any VRFs are added/removed/changed.
"""
current_conf_import_rts = set()
for vrf in self._vrfs_conf.vr... | [
"def",
"update_local_rt_nlris",
"(",
"self",
")",
":",
"current_conf_import_rts",
"=",
"set",
"(",
")",
"for",
"vrf",
"in",
"self",
".",
"_vrfs_conf",
".",
"vrf_confs",
":",
"current_conf_import_rts",
".",
"update",
"(",
"vrf",
".",
"import_rts",
")",
"removed... | Does book-keeping of local RT NLRIs based on all configured VRFs.
Syncs all import RTs and RT NLRIs.
The method should be called when any VRFs are added/removed/changed. | [
"Does",
"book",
"-",
"keeping",
"of",
"local",
"RT",
"NLRIs",
"based",
"on",
"all",
"configured",
"VRFs",
"."
] | python | train |
gumblex/zhconv | zhconv/zhconv.py | https://github.com/gumblex/zhconv/blob/925c0f9494f3439bc05526e7e89bb5f0ab3d185e/zhconv/zhconv.py#L449-L475 | def main():
"""
Simple stdin/stdout interface.
"""
if len(sys.argv) == 2 and sys.argv[1] in Locales:
locale = sys.argv[1]
convertfunc = convert
elif len(sys.argv) == 3 and sys.argv[1] == '-w' and sys.argv[2] in Locales:
locale = sys.argv[2]
convertfunc = convert_for_m... | [
"def",
"main",
"(",
")",
":",
"if",
"len",
"(",
"sys",
".",
"argv",
")",
"==",
"2",
"and",
"sys",
".",
"argv",
"[",
"1",
"]",
"in",
"Locales",
":",
"locale",
"=",
"sys",
".",
"argv",
"[",
"1",
"]",
"convertfunc",
"=",
"convert",
"elif",
"len",
... | Simple stdin/stdout interface. | [
"Simple",
"stdin",
"/",
"stdout",
"interface",
"."
] | python | train |
tk0miya/tk.phpautodoc | src/phply/phpparse.py | https://github.com/tk0miya/tk.phpautodoc/blob/cf789f64abaf76351485cee231a075227e665fb6/src/phply/phpparse.py#L977-L979 | def p_expr_function(p):
'expr : FUNCTION is_reference LPAREN parameter_list RPAREN lexical_vars LBRACE inner_statement_list RBRACE'
p[0] = ast.Closure(p[4], p[6], p[8], p[2], lineno=p.lineno(1)) | [
"def",
"p_expr_function",
"(",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"ast",
".",
"Closure",
"(",
"p",
"[",
"4",
"]",
",",
"p",
"[",
"6",
"]",
",",
"p",
"[",
"8",
"]",
",",
"p",
"[",
"2",
"]",
",",
"lineno",
"=",
"p",
".",
"lineno",
"(... | expr : FUNCTION is_reference LPAREN parameter_list RPAREN lexical_vars LBRACE inner_statement_list RBRACE | [
"expr",
":",
"FUNCTION",
"is_reference",
"LPAREN",
"parameter_list",
"RPAREN",
"lexical_vars",
"LBRACE",
"inner_statement_list",
"RBRACE"
] | python | train |
albahnsen/CostSensitiveClassification | costcla/probcal/probcal.py | https://github.com/albahnsen/CostSensitiveClassification/blob/75778ae32c70671c0cdde6c4651277b6a8b58871/costcla/probcal/probcal.py#L62-L135 | def fit(self, y, p):
""" Fit the calibration map
Parameters
----------
y_true : array-like of shape = [n_samples]
True class to be used for calibrating the probabilities
y_prob : array-like of shape = [n_samples, 2]
Predicted probabilities to be used for... | [
"def",
"fit",
"(",
"self",
",",
"y",
",",
"p",
")",
":",
"# TODO: Check input",
"if",
"p",
".",
"size",
"!=",
"p",
".",
"shape",
"[",
"0",
"]",
":",
"p",
"=",
"p",
"[",
":",
",",
"1",
"]",
"fpr",
",",
"tpr",
",",
"thresholds",
"=",
"roc_curve... | Fit the calibration map
Parameters
----------
y_true : array-like of shape = [n_samples]
True class to be used for calibrating the probabilities
y_prob : array-like of shape = [n_samples, 2]
Predicted probabilities to be used for calibrating the probabilities
... | [
"Fit",
"the",
"calibration",
"map"
] | python | train |
razorpay/razorpay-python | razorpay/resources/addon.py | https://github.com/razorpay/razorpay-python/blob/5bc63fd8452165a4b54556888492e555222c8afe/razorpay/resources/addon.py#L22-L29 | def delete(self, addon_id, data={}, **kwargs):
"""
Delete addon for given id
Args:
addon_id : Id for which addon object has to be deleted
"""
return super(Addon, self).delete(addon_id, data, **kwargs) | [
"def",
"delete",
"(",
"self",
",",
"addon_id",
",",
"data",
"=",
"{",
"}",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"super",
"(",
"Addon",
",",
"self",
")",
".",
"delete",
"(",
"addon_id",
",",
"data",
",",
"*",
"*",
"kwargs",
")"
] | Delete addon for given id
Args:
addon_id : Id for which addon object has to be deleted | [
"Delete",
"addon",
"for",
"given",
"id"
] | python | train |
blue-yonder/turbodbc | python/turbodbc/cursor.py | https://github.com/blue-yonder/turbodbc/blob/5556625e69244d941a708c69eb2c1e7b37c190b1/python/turbodbc/cursor.py#L265-L278 | def fetchallnumpy(self):
"""
Fetches all rows in the active result set generated with ``execute()`` or
``executemany()``.
:return: An ``OrderedDict`` of *columns*, where the keys of the dictionary
are the column names. The columns are of NumPy's ``MaskedArray``
... | [
"def",
"fetchallnumpy",
"(",
"self",
")",
":",
"from",
"numpy",
".",
"ma",
"import",
"concatenate",
"batches",
"=",
"list",
"(",
"self",
".",
"_numpy_batch_generator",
"(",
")",
")",
"column_names",
"=",
"[",
"description",
"[",
"0",
"]",
"for",
"descripti... | Fetches all rows in the active result set generated with ``execute()`` or
``executemany()``.
:return: An ``OrderedDict`` of *columns*, where the keys of the dictionary
are the column names. The columns are of NumPy's ``MaskedArray``
type, where the optimal data type fo... | [
"Fetches",
"all",
"rows",
"in",
"the",
"active",
"result",
"set",
"generated",
"with",
"execute",
"()",
"or",
"executemany",
"()",
"."
] | python | train |
tensorflow/cleverhans | cleverhans/attack_bundling.py | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attack_bundling.py#L563-L568 | def request_examples(self, attack_config, criteria, run_counts, batch_size):
"""
Returns a numpy array of integer example indices to run in the next batch.
"""
raise NotImplementedError(str(type(self)) +
"needs to implement request_examples") | [
"def",
"request_examples",
"(",
"self",
",",
"attack_config",
",",
"criteria",
",",
"run_counts",
",",
"batch_size",
")",
":",
"raise",
"NotImplementedError",
"(",
"str",
"(",
"type",
"(",
"self",
")",
")",
"+",
"\"needs to implement request_examples\"",
")"
] | Returns a numpy array of integer example indices to run in the next batch. | [
"Returns",
"a",
"numpy",
"array",
"of",
"integer",
"example",
"indices",
"to",
"run",
"in",
"the",
"next",
"batch",
"."
] | python | train |
chemlab/chemlab | chemlab/graphics/qt/qttrajectory.py | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/graphics/qt/qttrajectory.py#L316-L320 | def set_text(self, text):
'''Update the time indicator in the interface.
'''
self.traj_controls.timelabel.setText(self.traj_controls._label_tmp.format(text)) | [
"def",
"set_text",
"(",
"self",
",",
"text",
")",
":",
"self",
".",
"traj_controls",
".",
"timelabel",
".",
"setText",
"(",
"self",
".",
"traj_controls",
".",
"_label_tmp",
".",
"format",
"(",
"text",
")",
")"
] | Update the time indicator in the interface. | [
"Update",
"the",
"time",
"indicator",
"in",
"the",
"interface",
"."
] | python | train |
ioos/compliance-checker | compliance_checker/ioos.py | https://github.com/ioos/compliance-checker/blob/ee89c27b0daade58812489a2da3aa3b6859eafd9/compliance_checker/ioos.py#L133-L146 | def check_variable_attributes(self, ds):
"""
Check IOOS concepts that come from NC variable attributes.
:param netCDF4.Dataset ds: An open netCDF dataset
"""
return [
self._has_var_attr(ds, 'platform', 'long_name', 'Station Long Name'),
self._has_var_attr... | [
"def",
"check_variable_attributes",
"(",
"self",
",",
"ds",
")",
":",
"return",
"[",
"self",
".",
"_has_var_attr",
"(",
"ds",
",",
"'platform'",
",",
"'long_name'",
",",
"'Station Long Name'",
")",
",",
"self",
".",
"_has_var_attr",
"(",
"ds",
",",
"'platfor... | Check IOOS concepts that come from NC variable attributes.
:param netCDF4.Dataset ds: An open netCDF dataset | [
"Check",
"IOOS",
"concepts",
"that",
"come",
"from",
"NC",
"variable",
"attributes",
"."
] | python | train |
Azure/blobxfer | blobxfer/models/upload.py | https://github.com/Azure/blobxfer/blob/3eccbe7530cc6a20ab2d30f9e034b6f021817f34/blobxfer/models/upload.py#L734-L771 | def _compute_total_chunks(self, chunk_size):
# type: (Descriptor, int) -> int
"""Compute total number of chunks for entity
:param Descriptor self: this
:param int chunk_size: chunk size
:rtype: int
:return: num chunks
"""
try:
chunks = int(math... | [
"def",
"_compute_total_chunks",
"(",
"self",
",",
"chunk_size",
")",
":",
"# type: (Descriptor, int) -> int",
"try",
":",
"chunks",
"=",
"int",
"(",
"math",
".",
"ceil",
"(",
"self",
".",
"_ase",
".",
"size",
"/",
"chunk_size",
")",
")",
"except",
"ZeroDivis... | Compute total number of chunks for entity
:param Descriptor self: this
:param int chunk_size: chunk size
:rtype: int
:return: num chunks | [
"Compute",
"total",
"number",
"of",
"chunks",
"for",
"entity",
":",
"param",
"Descriptor",
"self",
":",
"this",
":",
"param",
"int",
"chunk_size",
":",
"chunk",
"size",
":",
"rtype",
":",
"int",
":",
"return",
":",
"num",
"chunks"
] | python | train |
thombashi/thutils | thutils/gfile.py | https://github.com/thombashi/thutils/blob/9eba767cfc26b38cd66b83b99aee0c31b8b90dec/thutils/gfile.py#L149-L163 | def chmod(cls, path, permission_text):
"""
:param str permission_text: "ls -l" style permission string. e.g. -rw-r--r--
"""
try:
check_file_existence(path)
except FileNotFoundError:
_, e, _ = sys.exc_info() # for python 2.5 compatibility
logg... | [
"def",
"chmod",
"(",
"cls",
",",
"path",
",",
"permission_text",
")",
":",
"try",
":",
"check_file_existence",
"(",
"path",
")",
"except",
"FileNotFoundError",
":",
"_",
",",
"e",
",",
"_",
"=",
"sys",
".",
"exc_info",
"(",
")",
"# for python 2.5 compatibi... | :param str permission_text: "ls -l" style permission string. e.g. -rw-r--r-- | [
":",
"param",
"str",
"permission_text",
":",
"ls",
"-",
"l",
"style",
"permission",
"string",
".",
"e",
".",
"g",
".",
"-",
"rw",
"-",
"r",
"--",
"r",
"--"
] | python | train |
Chilipp/psyplot | psyplot/data.py | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/data.py#L4399-L4420 | def remove(self, arr):
"""Removes an array from the list
Parameters
----------
arr: str or :class:`InteractiveBase`
The array name or the data object in this list to remove
Raises
------
ValueError
If no array with the specified array nam... | [
"def",
"remove",
"(",
"self",
",",
"arr",
")",
":",
"name",
"=",
"arr",
"if",
"isinstance",
"(",
"arr",
",",
"six",
".",
"string_types",
")",
"else",
"arr",
".",
"psy",
".",
"arr_name",
"if",
"arr",
"not",
"in",
"self",
":",
"raise",
"ValueError",
... | Removes an array from the list
Parameters
----------
arr: str or :class:`InteractiveBase`
The array name or the data object in this list to remove
Raises
------
ValueError
If no array with the specified array name is in the list | [
"Removes",
"an",
"array",
"from",
"the",
"list"
] | python | train |
KnowledgeLinks/rdfframework | rdfframework/connections/connmanager.py | https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/connections/connmanager.py#L151-L164 | def load(self, conn_list, **kwargs):
""" Takes a list of connections and sets them in the manager
args:
conn_list: list of connection defitions
"""
for conn in conn_list:
conn['delay_check'] = kwargs.get('delay_check', False)
self.set_conn(**conn)
... | [
"def",
"load",
"(",
"self",
",",
"conn_list",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"conn",
"in",
"conn_list",
":",
"conn",
"[",
"'delay_check'",
"]",
"=",
"kwargs",
".",
"get",
"(",
"'delay_check'",
",",
"False",
")",
"self",
".",
"set_conn",
"(... | Takes a list of connections and sets them in the manager
args:
conn_list: list of connection defitions | [
"Takes",
"a",
"list",
"of",
"connections",
"and",
"sets",
"them",
"in",
"the",
"manager"
] | python | train |
wummel/linkchecker | linkcheck/plugins/__init__.py | https://github.com/wummel/linkchecker/blob/c2ce810c3fb00b895a841a7be6b2e78c64e7b042/linkcheck/plugins/__init__.py#L63-L70 | def get_plugin_modules(folders, package='plugins',
parentpackage='linkcheck.dummy'):
"""Get plugin modules for given folders."""
for folder in folders:
for module in loader.get_folder_modules(folder, parentpackage):
yield module
for module in loader.get_package_mod... | [
"def",
"get_plugin_modules",
"(",
"folders",
",",
"package",
"=",
"'plugins'",
",",
"parentpackage",
"=",
"'linkcheck.dummy'",
")",
":",
"for",
"folder",
"in",
"folders",
":",
"for",
"module",
"in",
"loader",
".",
"get_folder_modules",
"(",
"folder",
",",
"par... | Get plugin modules for given folders. | [
"Get",
"plugin",
"modules",
"for",
"given",
"folders",
"."
] | python | train |
Carbonara-Project/Guanciale | guanciale/idblib.py | https://github.com/Carbonara-Project/Guanciale/blob/c239ffac6fb481d09c4071d1de1a09f60dc584ab/guanciale/idblib.py#L895-L906 | def prettyval(self, val):
"""
returns the value in a readable format.
"""
if len(val) == self.wordsize and val[-1:] in (b'\x00', b'\xff'):
return "%x" % struct.unpack("<" + self.fmt, val)
if len(val) == self.wordsize and re.search(b'[\x00-\x08\x0b\x0c\x0e-\x1f]'... | [
"def",
"prettyval",
"(",
"self",
",",
"val",
")",
":",
"if",
"len",
"(",
"val",
")",
"==",
"self",
".",
"wordsize",
"and",
"val",
"[",
"-",
"1",
":",
"]",
"in",
"(",
"b'\\x00'",
",",
"b'\\xff'",
")",
":",
"return",
"\"%x\"",
"%",
"struct",
".",
... | returns the value in a readable format. | [
"returns",
"the",
"value",
"in",
"a",
"readable",
"format",
"."
] | python | train |
batiste/django-page-cms | pages/admin/views.py | https://github.com/batiste/django-page-cms/blob/3c72111eb7c3997a63c462c1776ffd8ce8c50a5d/pages/admin/views.py#L21-L32 | def change_status(request, page_id):
"""
Switch the status of a page.
"""
perm = request.user.has_perm('pages.change_page')
if perm and request.method == 'POST':
page = Page.objects.get(pk=page_id)
page.status = int(request.POST['status'])
page.invalidate()
page.save(... | [
"def",
"change_status",
"(",
"request",
",",
"page_id",
")",
":",
"perm",
"=",
"request",
".",
"user",
".",
"has_perm",
"(",
"'pages.change_page'",
")",
"if",
"perm",
"and",
"request",
".",
"method",
"==",
"'POST'",
":",
"page",
"=",
"Page",
".",
"object... | Switch the status of a page. | [
"Switch",
"the",
"status",
"of",
"a",
"page",
"."
] | python | train |
tensorpack/tensorpack | tensorpack/callbacks/monitor.py | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/callbacks/monitor.py#L302-L314 | def load_existing_json():
"""
Look for an existing json under :meth:`logger.get_logger_dir()` named "stats.json",
and return the loaded list of statistics if found. Returns None otherwise.
"""
dir = logger.get_logger_dir()
fname = os.path.join(dir, JSONWriter.FILENAME)
... | [
"def",
"load_existing_json",
"(",
")",
":",
"dir",
"=",
"logger",
".",
"get_logger_dir",
"(",
")",
"fname",
"=",
"os",
".",
"path",
".",
"join",
"(",
"dir",
",",
"JSONWriter",
".",
"FILENAME",
")",
"if",
"tf",
".",
"gfile",
".",
"Exists",
"(",
"fname... | Look for an existing json under :meth:`logger.get_logger_dir()` named "stats.json",
and return the loaded list of statistics if found. Returns None otherwise. | [
"Look",
"for",
"an",
"existing",
"json",
"under",
":",
"meth",
":",
"logger",
".",
"get_logger_dir",
"()",
"named",
"stats",
".",
"json",
"and",
"return",
"the",
"loaded",
"list",
"of",
"statistics",
"if",
"found",
".",
"Returns",
"None",
"otherwise",
"."
... | python | train |
tensorflow/probability | tensorflow_probability/python/sts/fitting.py | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/sts/fitting.py#L267-L282 | def _minimize_in_graph(build_loss_fn, num_steps=200, optimizer=None):
"""Run an optimizer within the graph to minimize a loss function."""
optimizer = tf.compat.v1.train.AdamOptimizer(
0.1) if optimizer is None else optimizer
def train_loop_body(step):
train_op = optimizer.minimize(
build_loss_... | [
"def",
"_minimize_in_graph",
"(",
"build_loss_fn",
",",
"num_steps",
"=",
"200",
",",
"optimizer",
"=",
"None",
")",
":",
"optimizer",
"=",
"tf",
".",
"compat",
".",
"v1",
".",
"train",
".",
"AdamOptimizer",
"(",
"0.1",
")",
"if",
"optimizer",
"is",
"Non... | Run an optimizer within the graph to minimize a loss function. | [
"Run",
"an",
"optimizer",
"within",
"the",
"graph",
"to",
"minimize",
"a",
"loss",
"function",
"."
] | python | test |
coddingtonbear/django-location | location/migrations/0005_move_user_information.py | https://github.com/coddingtonbear/django-location/blob/5dd65b4e94cb65362d6e903080592b58ce37ff05/location/migrations/0005_move_user_information.py#L19-L24 | def backwards(self, orm):
"Write your backwards methods here."
for instance in orm.LocationSource.objects.all():
for point in instance.points.all():
point.user = instance.user
point.save() | [
"def",
"backwards",
"(",
"self",
",",
"orm",
")",
":",
"for",
"instance",
"in",
"orm",
".",
"LocationSource",
".",
"objects",
".",
"all",
"(",
")",
":",
"for",
"point",
"in",
"instance",
".",
"points",
".",
"all",
"(",
")",
":",
"point",
".",
"user... | Write your backwards methods here. | [
"Write",
"your",
"backwards",
"methods",
"here",
"."
] | python | train |
hovren/crisp | crisp/znccpyr.py | https://github.com/hovren/crisp/blob/65cae19e7cfae5a397859096c9ef666e0f4e7f1b/crisp/znccpyr.py#L73-L103 | def upsample(time_series, scaling_factor):
"""Upsample using linear interpolation
The function uses replication of the value at edges
Parameters
--------------
time_series : ndarray
Input signal
scaling_factor : float
The factor to upsample with
Returns
---... | [
"def",
"upsample",
"(",
"time_series",
",",
"scaling_factor",
")",
":",
"Ns0",
"=",
"np",
".",
"size",
"(",
"time_series",
")",
"Ns",
"=",
"np",
".",
"int",
"(",
"np",
".",
"floor",
"(",
"np",
".",
"size",
"(",
"time_series",
")",
"*",
"scaling_facto... | Upsample using linear interpolation
The function uses replication of the value at edges
Parameters
--------------
time_series : ndarray
Input signal
scaling_factor : float
The factor to upsample with
Returns
--------------
ts_out : ndarray
The ... | [
"Upsample",
"using",
"linear",
"interpolation"
] | python | train |
spencerahill/aospy | aospy/utils/times.py | https://github.com/spencerahill/aospy/blob/2f6e775b9b9956c54af117fdcdce2c87196afb6c/aospy/utils/times.py#L19-L58 | def apply_time_offset(time, years=0, months=0, days=0, hours=0):
"""Apply a specified offset to the given time array.
This is useful for GFDL model output of instantaneous values. For example,
3 hourly data postprocessed to netCDF files spanning 1 year each will
actually have time values that are offs... | [
"def",
"apply_time_offset",
"(",
"time",
",",
"years",
"=",
"0",
",",
"months",
"=",
"0",
",",
"days",
"=",
"0",
",",
"hours",
"=",
"0",
")",
":",
"return",
"(",
"pd",
".",
"to_datetime",
"(",
"time",
".",
"values",
")",
"+",
"pd",
".",
"DateOffs... | Apply a specified offset to the given time array.
This is useful for GFDL model output of instantaneous values. For example,
3 hourly data postprocessed to netCDF files spanning 1 year each will
actually have time values that are offset by 3 hours, such that the first
value is for 1 Jan 03:00 and the ... | [
"Apply",
"a",
"specified",
"offset",
"to",
"the",
"given",
"time",
"array",
"."
] | python | train |
tanghaibao/goatools | goatools/grouper/read_goids.py | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/grouper/read_goids.py#L109-L134 | def _read_txt(self, fin_txt, get_goids_only, exclude_ungrouped):
"""Read GO file. Store results in: section2goids sections_seen. Return goids_fin."""
goids_sec = []
with open(fin_txt) as istrm:
# Lines starting with a GO ID will have that GO ID read and stored.
# * Line... | [
"def",
"_read_txt",
"(",
"self",
",",
"fin_txt",
",",
"get_goids_only",
",",
"exclude_ungrouped",
")",
":",
"goids_sec",
"=",
"[",
"]",
"with",
"open",
"(",
"fin_txt",
")",
"as",
"istrm",
":",
"# Lines starting with a GO ID will have that GO ID read and stored.",
"#... | Read GO file. Store results in: section2goids sections_seen. Return goids_fin. | [
"Read",
"GO",
"file",
".",
"Store",
"results",
"in",
":",
"section2goids",
"sections_seen",
".",
"Return",
"goids_fin",
"."
] | python | train |
streamlink/streamlink | src/streamlink/utils/__init__.py | https://github.com/streamlink/streamlink/blob/c8ed1daff14ac03195870238b9b900c1109dd5c1/src/streamlink/utils/__init__.py#L158-L175 | def search_dict(data, key):
"""
Search for a key in a nested dict, or list of nested dicts, and return the values.
:param data: dict/list to search
:param key: key to find
:return: matches for key
"""
if isinstance(data, dict):
for dkey, value in data.items():
if dkey ==... | [
"def",
"search_dict",
"(",
"data",
",",
"key",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"dict",
")",
":",
"for",
"dkey",
",",
"value",
"in",
"data",
".",
"items",
"(",
")",
":",
"if",
"dkey",
"==",
"key",
":",
"yield",
"value",
"for",
"res... | Search for a key in a nested dict, or list of nested dicts, and return the values.
:param data: dict/list to search
:param key: key to find
:return: matches for key | [
"Search",
"for",
"a",
"key",
"in",
"a",
"nested",
"dict",
"or",
"list",
"of",
"nested",
"dicts",
"and",
"return",
"the",
"values",
"."
] | python | test |
openstack/proliantutils | proliantutils/ilo/ris.py | https://github.com/openstack/proliantutils/blob/86ef3b47b4eca97c221577e3570b0240d6a25f22/proliantutils/ilo/ris.py#L136-L140 | def _get_type(self, obj):
"""Return the type of an object."""
typever = obj['Type']
typesplit = typever.split('.')
return typesplit[0] + '.' + typesplit[1] | [
"def",
"_get_type",
"(",
"self",
",",
"obj",
")",
":",
"typever",
"=",
"obj",
"[",
"'Type'",
"]",
"typesplit",
"=",
"typever",
".",
"split",
"(",
"'.'",
")",
"return",
"typesplit",
"[",
"0",
"]",
"+",
"'.'",
"+",
"typesplit",
"[",
"1",
"]"
] | Return the type of an object. | [
"Return",
"the",
"type",
"of",
"an",
"object",
"."
] | python | train |
JarryShaw/PyPCAPKit | src/protocols/pcap/header.py | https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/protocols/pcap/header.py#L110-L170 | def read_header(self):
"""Read global header of PCAP file.
Structure of global header (C):
typedef struct pcap_hdr_s {
guint32 magic_number; /* magic number */
guint16 version_major; /* major version number */
guint16 version_minor; /* min... | [
"def",
"read_header",
"(",
"self",
")",
":",
"_magn",
"=",
"self",
".",
"_read_fileng",
"(",
"4",
")",
"if",
"_magn",
"==",
"b'\\xd4\\xc3\\xb2\\xa1'",
":",
"lilendian",
"=",
"True",
"self",
".",
"_nsec",
"=",
"False",
"self",
".",
"_byte",
"=",
"'little'... | Read global header of PCAP file.
Structure of global header (C):
typedef struct pcap_hdr_s {
guint32 magic_number; /* magic number */
guint16 version_major; /* major version number */
guint16 version_minor; /* minor version number */
... | [
"Read",
"global",
"header",
"of",
"PCAP",
"file",
"."
] | python | train |
williballenthin/python-evtx | scripts/evtx_filter_records.py | https://github.com/williballenthin/python-evtx/blob/4e9e29544adde64c79ff9b743269ecb18c677eb4/scripts/evtx_filter_records.py#L18-L32 | def xml_records(filename):
"""
If the second return value is not None, then it is an
Exception encountered during parsing. The first return value
will be the XML string.
@type filename str
@rtype: generator of (etree.Element or str), (None or Exception)
"""
with Evtx(filename) as e... | [
"def",
"xml_records",
"(",
"filename",
")",
":",
"with",
"Evtx",
"(",
"filename",
")",
"as",
"evtx",
":",
"for",
"xml",
",",
"record",
"in",
"evtx_file_xml_view",
"(",
"evtx",
".",
"get_file_header",
"(",
")",
")",
":",
"try",
":",
"yield",
"to_lxml",
... | If the second return value is not None, then it is an
Exception encountered during parsing. The first return value
will be the XML string.
@type filename str
@rtype: generator of (etree.Element or str), (None or Exception) | [
"If",
"the",
"second",
"return",
"value",
"is",
"not",
"None",
"then",
"it",
"is",
"an",
"Exception",
"encountered",
"during",
"parsing",
".",
"The",
"first",
"return",
"value",
"will",
"be",
"the",
"XML",
"string",
"."
] | python | train |
awslabs/sockeye | sockeye/vocab.py | https://github.com/awslabs/sockeye/blob/5d64a1ee1ef3cbba17c6d1d94bc061020c43f6ab/sockeye/vocab.py#L301-L308 | def get_ordered_tokens_from_vocab(vocab: Vocab) -> List[str]:
"""
Returns the list of tokens in a vocabulary, ordered by increasing vocabulary id.
:param vocab: Input vocabulary.
:return: List of tokens.
"""
return [token for token, token_id in sorted(vocab.items(), key=lambda i: i[1])] | [
"def",
"get_ordered_tokens_from_vocab",
"(",
"vocab",
":",
"Vocab",
")",
"->",
"List",
"[",
"str",
"]",
":",
"return",
"[",
"token",
"for",
"token",
",",
"token_id",
"in",
"sorted",
"(",
"vocab",
".",
"items",
"(",
")",
",",
"key",
"=",
"lambda",
"i",
... | Returns the list of tokens in a vocabulary, ordered by increasing vocabulary id.
:param vocab: Input vocabulary.
:return: List of tokens. | [
"Returns",
"the",
"list",
"of",
"tokens",
"in",
"a",
"vocabulary",
"ordered",
"by",
"increasing",
"vocabulary",
"id",
"."
] | python | train |
openvax/pyensembl | pyensembl/database.py | https://github.com/openvax/pyensembl/blob/4b995fb72e848206d6fbf11950cf30964cd9b3aa/pyensembl/database.py#L204-L254 | def create(
self,
overwrite=False):
"""
Create the local database (including indexing) if it's not
already set up. If `overwrite` is True, always re-create
the database from scratch.
Returns a connection to the database.
"""
logger.info("C... | [
"def",
"create",
"(",
"self",
",",
"overwrite",
"=",
"False",
")",
":",
"logger",
".",
"info",
"(",
"\"Creating database: %s\"",
",",
"self",
".",
"local_db_path",
")",
"df",
"=",
"self",
".",
"_load_gtf_as_dataframe",
"(",
"usecols",
"=",
"self",
".",
"re... | Create the local database (including indexing) if it's not
already set up. If `overwrite` is True, always re-create
the database from scratch.
Returns a connection to the database. | [
"Create",
"the",
"local",
"database",
"(",
"including",
"indexing",
")",
"if",
"it",
"s",
"not",
"already",
"set",
"up",
".",
"If",
"overwrite",
"is",
"True",
"always",
"re",
"-",
"create",
"the",
"database",
"from",
"scratch",
"."
] | python | train |
clalancette/pycdlib | pycdlib/eltorito.py | https://github.com/clalancette/pycdlib/blob/1e7b77a809e905d67dc71e12d70e850be26b6233/pycdlib/eltorito.py#L594-L614 | def record(self):
# type: () -> bytes
'''
Get a string representing this El Torito section header.
Parameters:
None.
Returns:
A string representing this El Torito section header.
'''
if not self._initialized:
raise pycdlibexception.P... | [
"def",
"record",
"(",
"self",
")",
":",
"# type: () -> bytes",
"if",
"not",
"self",
".",
"_initialized",
":",
"raise",
"pycdlibexception",
".",
"PyCdlibInternalError",
"(",
"'El Torito Section Header not yet initialized'",
")",
"outlist",
"=",
"[",
"struct",
".",
"p... | Get a string representing this El Torito section header.
Parameters:
None.
Returns:
A string representing this El Torito section header. | [
"Get",
"a",
"string",
"representing",
"this",
"El",
"Torito",
"section",
"header",
"."
] | python | train |
GiulioRossetti/dynetx | dynetx/classes/dyngraph.py | https://github.com/GiulioRossetti/dynetx/blob/634e2b38f8950885aebfa079dad7d5e8d7563f1d/dynetx/classes/dyngraph.py#L238-L291 | def interactions_iter(self, nbunch=None, t=None):
"""Return an iterator over the interaction present in a given snapshot.
Edges are returned as tuples
in the order (node, neighbor).
Parameters
----------
nbunch : iterable container, optional (default= all nodes)
... | [
"def",
"interactions_iter",
"(",
"self",
",",
"nbunch",
"=",
"None",
",",
"t",
"=",
"None",
")",
":",
"seen",
"=",
"{",
"}",
"# helper dict to keep track of multiply stored interactions",
"if",
"nbunch",
"is",
"None",
":",
"nodes_nbrs",
"=",
"self",
".",
"_adj... | Return an iterator over the interaction present in a given snapshot.
Edges are returned as tuples
in the order (node, neighbor).
Parameters
----------
nbunch : iterable container, optional (default= all nodes)
A container of nodes. The container will be iterated
... | [
"Return",
"an",
"iterator",
"over",
"the",
"interaction",
"present",
"in",
"a",
"given",
"snapshot",
"."
] | python | train |
bitprophet/spec | spec/cli.py | https://github.com/bitprophet/spec/blob/d9646c5daf8e479937f970d21ebe185ad936a35a/spec/cli.py#L56-L65 | def registerGoodClass(self, class_):
"""
Internal bookkeeping to handle nested classes
"""
# Class itself added to "good" list
self._valid_classes.append(class_)
# Recurse into any inner classes
for name, cls in class_members(class_):
if self.isValidCl... | [
"def",
"registerGoodClass",
"(",
"self",
",",
"class_",
")",
":",
"# Class itself added to \"good\" list",
"self",
".",
"_valid_classes",
".",
"append",
"(",
"class_",
")",
"# Recurse into any inner classes",
"for",
"name",
",",
"cls",
"in",
"class_members",
"(",
"c... | Internal bookkeeping to handle nested classes | [
"Internal",
"bookkeeping",
"to",
"handle",
"nested",
"classes"
] | python | valid |
markovmodel/PyEMMA | pyemma/coordinates/data/_base/_in_memory_mixin.py | https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/coordinates/data/_base/_in_memory_mixin.py#L37-L47 | def _map_to_memory(self, stride=1):
r"""Maps results to memory. Will be stored in attribute :attr:`_Y`."""
self._mapping_to_mem_active = True
try:
self._Y = self.get_output(stride=stride)
from pyemma.coordinates.data import DataInMemory
self._Y_source = DataIn... | [
"def",
"_map_to_memory",
"(",
"self",
",",
"stride",
"=",
"1",
")",
":",
"self",
".",
"_mapping_to_mem_active",
"=",
"True",
"try",
":",
"self",
".",
"_Y",
"=",
"self",
".",
"get_output",
"(",
"stride",
"=",
"stride",
")",
"from",
"pyemma",
".",
"coord... | r"""Maps results to memory. Will be stored in attribute :attr:`_Y`. | [
"r",
"Maps",
"results",
"to",
"memory",
".",
"Will",
"be",
"stored",
"in",
"attribute",
":",
"attr",
":",
"_Y",
"."
] | python | train |
lrq3000/pyFileFixity | pyFileFixity/lib/pathlib2.py | https://github.com/lrq3000/pyFileFixity/blob/fd5ef23bb13835faf1e3baa773619b86a1cc9bdf/pyFileFixity/lib/pathlib2.py#L1314-L1323 | def write_text(self, data, encoding=None, errors=None):
"""
Open the file in text mode, write to it, and close the file.
"""
if not isinstance(data, six.text_type):
raise TypeError(
'data must be %s, not %s' %
(six.text_type.__class__.__name__,... | [
"def",
"write_text",
"(",
"self",
",",
"data",
",",
"encoding",
"=",
"None",
",",
"errors",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"data",
",",
"six",
".",
"text_type",
")",
":",
"raise",
"TypeError",
"(",
"'data must be %s, not %s'",
"%"... | Open the file in text mode, write to it, and close the file. | [
"Open",
"the",
"file",
"in",
"text",
"mode",
"write",
"to",
"it",
"and",
"close",
"the",
"file",
"."
] | python | train |
yahoo/TensorFlowOnSpark | examples/wide_deep/census_dataset.py | https://github.com/yahoo/TensorFlowOnSpark/blob/5e4b6c185ab722fd0104ede0377e1149ea8d6f7c/examples/wide_deep/census_dataset.py#L59-L73 | def _download_and_clean_file(filename, url):
"""Downloads data from url, and makes changes to match the CSV format."""
temp_file, _ = urllib.request.urlretrieve(url)
with tf.gfile.Open(temp_file, 'r') as temp_eval_file:
with tf.gfile.Open(filename, 'w') as eval_file:
for line in temp_eval_file:
... | [
"def",
"_download_and_clean_file",
"(",
"filename",
",",
"url",
")",
":",
"temp_file",
",",
"_",
"=",
"urllib",
".",
"request",
".",
"urlretrieve",
"(",
"url",
")",
"with",
"tf",
".",
"gfile",
".",
"Open",
"(",
"temp_file",
",",
"'r'",
")",
"as",
"temp... | Downloads data from url, and makes changes to match the CSV format. | [
"Downloads",
"data",
"from",
"url",
"and",
"makes",
"changes",
"to",
"match",
"the",
"CSV",
"format",
"."
] | python | train |
django-danceschool/django-danceschool | danceschool/core/views.py | https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/views.py#L150-L159 | def get(self, request, *args, **kwargs):
'''
Invoices can be viewed only if the validation string is provided, unless
the user is logged in and has view_all_invoice permissions
'''
user_has_validation_string = self.get_object().validationString
user_has_permissions = requ... | [
"def",
"get",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"user_has_validation_string",
"=",
"self",
".",
"get_object",
"(",
")",
".",
"validationString",
"user_has_permissions",
"=",
"request",
".",
"user",
".",
"has_... | Invoices can be viewed only if the validation string is provided, unless
the user is logged in and has view_all_invoice permissions | [
"Invoices",
"can",
"be",
"viewed",
"only",
"if",
"the",
"validation",
"string",
"is",
"provided",
"unless",
"the",
"user",
"is",
"logged",
"in",
"and",
"has",
"view_all_invoice",
"permissions"
] | python | train |
sibirrer/lenstronomy | lenstronomy/ImSim/image_model.py | https://github.com/sibirrer/lenstronomy/blob/4edb100a4f3f4fdc4fac9b0032d2b0283d0aa1d6/lenstronomy/ImSim/image_model.py#L178-L185 | def data_response(self):
"""
returns the 1d array of the data element that is fitted for (including masking)
:return: 1d numpy array
"""
d = self.ImageNumerics.image2array(self.Data.data * self.ImageNumerics.mask)
return d | [
"def",
"data_response",
"(",
"self",
")",
":",
"d",
"=",
"self",
".",
"ImageNumerics",
".",
"image2array",
"(",
"self",
".",
"Data",
".",
"data",
"*",
"self",
".",
"ImageNumerics",
".",
"mask",
")",
"return",
"d"
] | returns the 1d array of the data element that is fitted for (including masking)
:return: 1d numpy array | [
"returns",
"the",
"1d",
"array",
"of",
"the",
"data",
"element",
"that",
"is",
"fitted",
"for",
"(",
"including",
"masking",
")"
] | python | train |
xray7224/PyPump | pypump/models/feed.py | https://github.com/xray7224/PyPump/blob/f921f691c39fe021f4fd124b6bc91718c9e49b4a/pypump/models/feed.py#L80-L89 | def get_obj_id(self, item):
""" Get the id of a PumpObject.
:param item: id string or PumpObject
"""
if item is not None:
if isinstance(item, six.string_types):
return item
elif hasattr(item, 'id'):
return item.id | [
"def",
"get_obj_id",
"(",
"self",
",",
"item",
")",
":",
"if",
"item",
"is",
"not",
"None",
":",
"if",
"isinstance",
"(",
"item",
",",
"six",
".",
"string_types",
")",
":",
"return",
"item",
"elif",
"hasattr",
"(",
"item",
",",
"'id'",
")",
":",
"r... | Get the id of a PumpObject.
:param item: id string or PumpObject | [
"Get",
"the",
"id",
"of",
"a",
"PumpObject",
"."
] | python | train |
aws/aws-xray-sdk-python | aws_xray_sdk/core/models/entity.py | https://github.com/aws/aws-xray-sdk-python/blob/707358cd3a516d51f2ebf71cf34f00e8d906a667/aws_xray_sdk/core/models/entity.py#L210-L231 | def add_exception(self, exception, stack, remote=False):
"""
Add an exception to trace entities.
:param Exception exception: the catched exception.
:param list stack: the output from python built-in
`traceback.extract_stack()`.
:param bool remote: If False it means i... | [
"def",
"add_exception",
"(",
"self",
",",
"exception",
",",
"stack",
",",
"remote",
"=",
"False",
")",
":",
"self",
".",
"_check_ended",
"(",
")",
"self",
".",
"add_fault_flag",
"(",
")",
"if",
"hasattr",
"(",
"exception",
",",
"'_recorded'",
")",
":",
... | Add an exception to trace entities.
:param Exception exception: the catched exception.
:param list stack: the output from python built-in
`traceback.extract_stack()`.
:param bool remote: If False it means it's a client error
instead of a downstream service. | [
"Add",
"an",
"exception",
"to",
"trace",
"entities",
"."
] | python | train |
lowandrew/OLCTools | spadespipeline/primer_finder_bbduk.py | https://github.com/lowandrew/OLCTools/blob/88aa90ac85f84d0bbeb03e43c29b0a9d36e4ce2a/spadespipeline/primer_finder_bbduk.py#L166-L199 | def primers(self):
"""
Read in the primer file, and create a properly formatted output file that takes any degenerate bases
into account
"""
with open(self.formattedprimers, 'w') as formatted:
for record in SeqIO.parse(self.primerfile, 'fasta'):
# from... | [
"def",
"primers",
"(",
"self",
")",
":",
"with",
"open",
"(",
"self",
".",
"formattedprimers",
",",
"'w'",
")",
"as",
"formatted",
":",
"for",
"record",
"in",
"SeqIO",
".",
"parse",
"(",
"self",
".",
"primerfile",
",",
"'fasta'",
")",
":",
"# from http... | Read in the primer file, and create a properly formatted output file that takes any degenerate bases
into account | [
"Read",
"in",
"the",
"primer",
"file",
"and",
"create",
"a",
"properly",
"formatted",
"output",
"file",
"that",
"takes",
"any",
"degenerate",
"bases",
"into",
"account"
] | python | train |
abilian/abilian-core | abilian/i18n.py | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/i18n.py#L125-L147 | def country_choices(first=None, default_country_first=True):
"""Return a list of (code, countries), alphabetically sorted on localized
country name.
:param first: Country code to be placed at the top
:param default_country_first:
:type default_country_first: bool
"""
locale = _get_locale()
... | [
"def",
"country_choices",
"(",
"first",
"=",
"None",
",",
"default_country_first",
"=",
"True",
")",
":",
"locale",
"=",
"_get_locale",
"(",
")",
"territories",
"=",
"[",
"(",
"code",
",",
"name",
")",
"for",
"code",
",",
"name",
"in",
"locale",
".",
"... | Return a list of (code, countries), alphabetically sorted on localized
country name.
:param first: Country code to be placed at the top
:param default_country_first:
:type default_country_first: bool | [
"Return",
"a",
"list",
"of",
"(",
"code",
"countries",
")",
"alphabetically",
"sorted",
"on",
"localized",
"country",
"name",
"."
] | python | train |
PmagPy/PmagPy | pmagpy/pmag.py | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/pmagpy/pmag.py#L2281-L2303 | def dodirot(D, I, Dbar, Ibar):
"""
Rotate a direction (declination, inclination) by the difference between
dec=0 and inc = 90 and the provided desired mean direction
Parameters
----------
D : declination to be rotated
I : inclination to be rotated
Dbar : declination of desired mean
... | [
"def",
"dodirot",
"(",
"D",
",",
"I",
",",
"Dbar",
",",
"Ibar",
")",
":",
"d",
",",
"irot",
"=",
"dogeo",
"(",
"D",
",",
"I",
",",
"Dbar",
",",
"90.",
"-",
"Ibar",
")",
"drot",
"=",
"d",
"-",
"180.",
"if",
"drot",
"<",
"360.",
":",
"drot",
... | Rotate a direction (declination, inclination) by the difference between
dec=0 and inc = 90 and the provided desired mean direction
Parameters
----------
D : declination to be rotated
I : inclination to be rotated
Dbar : declination of desired mean
Ibar : inclination of desired mean
Ret... | [
"Rotate",
"a",
"direction",
"(",
"declination",
"inclination",
")",
"by",
"the",
"difference",
"between",
"dec",
"=",
"0",
"and",
"inc",
"=",
"90",
"and",
"the",
"provided",
"desired",
"mean",
"direction"
] | python | train |
limpyd/redis-limpyd-jobs | limpyd_jobs/workers.py | https://github.com/limpyd/redis-limpyd-jobs/blob/264c71029bad4377d6132bf8bb9c55c44f3b03a2/limpyd_jobs/workers.py#L516-L529 | def job_requeue_message(self, job, queue):
"""
Return the message to log when a job is requeued
"""
priority, delayed_until = job.hmget('priority', 'delayed_until')
msg = '[%s|%s|%s] requeued with priority %s'
args = [queue._cached_name, job.pk.get(), job._cached_identif... | [
"def",
"job_requeue_message",
"(",
"self",
",",
"job",
",",
"queue",
")",
":",
"priority",
",",
"delayed_until",
"=",
"job",
".",
"hmget",
"(",
"'priority'",
",",
"'delayed_until'",
")",
"msg",
"=",
"'[%s|%s|%s] requeued with priority %s'",
"args",
"=",
"[",
"... | Return the message to log when a job is requeued | [
"Return",
"the",
"message",
"to",
"log",
"when",
"a",
"job",
"is",
"requeued"
] | python | train |
apple/turicreate | deps/src/boost_1_68_0/libs/metaparse/tools/benchmark/benchmark.py | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/libs/metaparse/tools/benchmark/benchmark.py#L260-L265 | def plot_diagram(config, results, images_dir, out_filename):
"""Plot one diagram"""
img_files = plot_temp_diagrams(config, results, images_dir)
join_images(img_files, out_filename)
for img_file in img_files:
os.remove(img_file) | [
"def",
"plot_diagram",
"(",
"config",
",",
"results",
",",
"images_dir",
",",
"out_filename",
")",
":",
"img_files",
"=",
"plot_temp_diagrams",
"(",
"config",
",",
"results",
",",
"images_dir",
")",
"join_images",
"(",
"img_files",
",",
"out_filename",
")",
"f... | Plot one diagram | [
"Plot",
"one",
"diagram"
] | python | train |
log2timeline/dfvfs | dfvfs/helpers/file_system_searcher.py | https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/helpers/file_system_searcher.py#L149-L160 | def _CheckIsDevice(self, file_entry):
"""Checks the is_device find specification.
Args:
file_entry (FileEntry): file entry.
Returns:
bool: True if the file entry matches the find specification, False if not.
"""
if definitions.FILE_ENTRY_TYPE_DEVICE not in self._file_entry_types:
... | [
"def",
"_CheckIsDevice",
"(",
"self",
",",
"file_entry",
")",
":",
"if",
"definitions",
".",
"FILE_ENTRY_TYPE_DEVICE",
"not",
"in",
"self",
".",
"_file_entry_types",
":",
"return",
"False",
"return",
"file_entry",
".",
"IsDevice",
"(",
")"
] | Checks the is_device find specification.
Args:
file_entry (FileEntry): file entry.
Returns:
bool: True if the file entry matches the find specification, False if not. | [
"Checks",
"the",
"is_device",
"find",
"specification",
"."
] | python | train |
kwikteam/phy | phy/gui/actions.py | https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/gui/actions.py#L200-L246 | def add(self, callback=None, name=None, shortcut=None, alias=None,
docstring=None, menu=None, verbose=True):
"""Add an action with a keyboard shortcut."""
if callback is None:
# Allow to use either add(func) or @add or @add(...).
return partial(self.add, name=name, sh... | [
"def",
"add",
"(",
"self",
",",
"callback",
"=",
"None",
",",
"name",
"=",
"None",
",",
"shortcut",
"=",
"None",
",",
"alias",
"=",
"None",
",",
"docstring",
"=",
"None",
",",
"menu",
"=",
"None",
",",
"verbose",
"=",
"True",
")",
":",
"if",
"cal... | Add an action with a keyboard shortcut. | [
"Add",
"an",
"action",
"with",
"a",
"keyboard",
"shortcut",
"."
] | python | train |
Alignak-monitoring/alignak | alignak/objects/schedulingitem.py | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/schedulingitem.py#L1974-L1995 | def prepare_notification_for_sending(self, notif, contact, macromodulations, timeperiods,
host_ref):
"""Used by scheduler when a notification is ok to be sent (to reactionner).
Here we update the command with status of now, and we add the contact to set of
... | [
"def",
"prepare_notification_for_sending",
"(",
"self",
",",
"notif",
",",
"contact",
",",
"macromodulations",
",",
"timeperiods",
",",
"host_ref",
")",
":",
"if",
"notif",
".",
"status",
"==",
"ACT_STATUS_POLLED",
":",
"self",
".",
"update_notification_command",
... | Used by scheduler when a notification is ok to be sent (to reactionner).
Here we update the command with status of now, and we add the contact to set of
contact we notified. And we raise the log entry
:param notif: notification to send
:type notif: alignak.objects.notification.Notificat... | [
"Used",
"by",
"scheduler",
"when",
"a",
"notification",
"is",
"ok",
"to",
"be",
"sent",
"(",
"to",
"reactionner",
")",
".",
"Here",
"we",
"update",
"the",
"command",
"with",
"status",
"of",
"now",
"and",
"we",
"add",
"the",
"contact",
"to",
"set",
"of"... | python | train |
materialsproject/pymatgen-db | matgendb/builders/incr.py | https://github.com/materialsproject/pymatgen-db/blob/02e4351c2cea431407644f49193e8bf43ed39b9a/matgendb/builders/incr.py#L249-L265 | def update(self):
"""Update the position of the mark in the collection.
:return: this object, for chaining
:rtype: Mark
"""
rec = self._c.find_one({}, {self._fld: 1}, sort=[(self._fld, -1)], limit=1)
if rec is None:
self._pos = self._empty_pos()
elif ... | [
"def",
"update",
"(",
"self",
")",
":",
"rec",
"=",
"self",
".",
"_c",
".",
"find_one",
"(",
"{",
"}",
",",
"{",
"self",
".",
"_fld",
":",
"1",
"}",
",",
"sort",
"=",
"[",
"(",
"self",
".",
"_fld",
",",
"-",
"1",
")",
"]",
",",
"limit",
"... | Update the position of the mark in the collection.
:return: this object, for chaining
:rtype: Mark | [
"Update",
"the",
"position",
"of",
"the",
"mark",
"in",
"the",
"collection",
"."
] | python | train |
Jajcus/pyxmpp2 | pyxmpp2/settings.py | https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/settings.py#L138-L166 | def get(self, key, local_default = None, required = False):
"""Get a parameter value.
If parameter is not set, return `local_default` if it is not `None`
or the PyXMPP global default otherwise.
:Raise `KeyError`: if parameter has no value and no global default
:Return: paramet... | [
"def",
"get",
"(",
"self",
",",
"key",
",",
"local_default",
"=",
"None",
",",
"required",
"=",
"False",
")",
":",
"# pylint: disable-msg=W0221",
"if",
"key",
"in",
"self",
".",
"_settings",
":",
"return",
"self",
".",
"_settings",
"[",
"key",
"]",
"if",... | Get a parameter value.
If parameter is not set, return `local_default` if it is not `None`
or the PyXMPP global default otherwise.
:Raise `KeyError`: if parameter has no value and no global default
:Return: parameter value | [
"Get",
"a",
"parameter",
"value",
"."
] | python | valid |
ricequant/rqalpha | rqalpha/mod/rqalpha_mod_sys_accounts/api/api_stock.py | https://github.com/ricequant/rqalpha/blob/ac40a62d4e7eca9494b4d0a14f46facf5616820c/rqalpha/mod/rqalpha_mod_sys_accounts/api/api_stock.py#L162-L194 | def order_lots(id_or_ins, amount, price=None, style=None):
"""
指定手数发送买/卖单。如有需要落单类型当做一个参量传入,如果忽略掉落单类型,那么默认是市价单(market order)。
:param id_or_ins: 下单标的物
:type id_or_ins: :class:`~Instrument` object | `str`
:param int amount: 下单量, 正数代表买入,负数代表卖出。将会根据一手xx股来向下调整到一手的倍数,比如中国A股就是调整成100股的倍数。
:param float... | [
"def",
"order_lots",
"(",
"id_or_ins",
",",
"amount",
",",
"price",
"=",
"None",
",",
"style",
"=",
"None",
")",
":",
"order_book_id",
"=",
"assure_stock_order_book_id",
"(",
"id_or_ins",
")",
"round_lot",
"=",
"int",
"(",
"Environment",
".",
"get_instance",
... | 指定手数发送买/卖单。如有需要落单类型当做一个参量传入,如果忽略掉落单类型,那么默认是市价单(market order)。
:param id_or_ins: 下单标的物
:type id_or_ins: :class:`~Instrument` object | `str`
:param int amount: 下单量, 正数代表买入,负数代表卖出。将会根据一手xx股来向下调整到一手的倍数,比如中国A股就是调整成100股的倍数。
:param float price: 下单价格,默认为None,表示 :class:`~MarketOrder`, 此参数主要用于简化 `style` 参数。
... | [
"指定手数发送买",
"/",
"卖单。如有需要落单类型当做一个参量传入,如果忽略掉落单类型,那么默认是市价单(market",
"order)。"
] | python | train |
EventTeam/beliefs | src/beliefs/cells/bools.py | https://github.com/EventTeam/beliefs/blob/c07d22b61bebeede74a72800030dde770bf64208/src/beliefs/cells/bools.py#L51-L54 | def entails(self, other):
""" Inverse is_entailed_by """
other = BoolCell.coerce(other)
return other.is_entailed_by(self) | [
"def",
"entails",
"(",
"self",
",",
"other",
")",
":",
"other",
"=",
"BoolCell",
".",
"coerce",
"(",
"other",
")",
"return",
"other",
".",
"is_entailed_by",
"(",
"self",
")"
] | Inverse is_entailed_by | [
"Inverse",
"is_entailed_by"
] | python | train |
estnltk/estnltk | estnltk/syntax/syntax_preprocessing.py | https://github.com/estnltk/estnltk/blob/28ae334a68a0673072febc318635f04da0dcc54a/estnltk/syntax/syntax_preprocessing.py#L280-L297 | def _convert_punctuation( line ):
''' Converts given analysis line if it describes punctuation; Uses the set
of predefined punctuation conversion rules from _punctConversions;
_punctConversions should be a list of lists, where each outer list stands
for a single conversion rule an... | [
"def",
"_convert_punctuation",
"(",
"line",
")",
":",
"for",
"[",
"pattern",
",",
"replacement",
"]",
"in",
"_punctConversions",
":",
"lastline",
"=",
"line",
"line",
"=",
"re",
".",
"sub",
"(",
"pattern",
",",
"replacement",
",",
"line",
")",
"if",
"las... | Converts given analysis line if it describes punctuation; Uses the set
of predefined punctuation conversion rules from _punctConversions;
_punctConversions should be a list of lists, where each outer list stands
for a single conversion rule and inner list contains a pair of elements:
... | [
"Converts",
"given",
"analysis",
"line",
"if",
"it",
"describes",
"punctuation",
";",
"Uses",
"the",
"set",
"of",
"predefined",
"punctuation",
"conversion",
"rules",
"from",
"_punctConversions",
";",
"_punctConversions",
"should",
"be",
"a",
"list",
"of",
"lists",... | python | train |
jahuth/litus | __init__.py | https://github.com/jahuth/litus/blob/712b016ea2dbb1cf0a30bfdbb0a136945a7b7c5e/__init__.py#L543-L559 | def recgen_enumerate(gen,n=tuple(), fix_type_errors=True):
"""
Iterates through generators recursively and flattens them. (see `recgen`)
This function adds a tuple with enumerators on each generator visited.
"""
if not hasattr(gen,'__iter__'):
yield (n,gen)
else:
try:
... | [
"def",
"recgen_enumerate",
"(",
"gen",
",",
"n",
"=",
"tuple",
"(",
")",
",",
"fix_type_errors",
"=",
"True",
")",
":",
"if",
"not",
"hasattr",
"(",
"gen",
",",
"'__iter__'",
")",
":",
"yield",
"(",
"n",
",",
"gen",
")",
"else",
":",
"try",
":",
... | Iterates through generators recursively and flattens them. (see `recgen`)
This function adds a tuple with enumerators on each generator visited. | [
"Iterates",
"through",
"generators",
"recursively",
"and",
"flattens",
"them",
".",
"(",
"see",
"recgen",
")"
] | python | train |
SmokinCaterpillar/pypet | pypet/utils/mpwrappers.py | https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/pypet/utils/mpwrappers.py#L373-L392 | def _req_rep_retry(self, request):
"""Returns response and number of retries"""
retries_left = self.RETRIES
while retries_left:
self._logger.log(1, 'Sending REQ `%s`', request)
self._send_request(request)
socks = dict(self._poll.poll(self.TIMEOUT))
... | [
"def",
"_req_rep_retry",
"(",
"self",
",",
"request",
")",
":",
"retries_left",
"=",
"self",
".",
"RETRIES",
"while",
"retries_left",
":",
"self",
".",
"_logger",
".",
"log",
"(",
"1",
",",
"'Sending REQ `%s`'",
",",
"request",
")",
"self",
".",
"_send_req... | Returns response and number of retries | [
"Returns",
"response",
"and",
"number",
"of",
"retries"
] | python | test |
biolink/ontobio | ontobio/io/gafparser.py | https://github.com/biolink/ontobio/blob/4e512a7831cfe6bc1b32f2c3be2ba41bc5cf7345/ontobio/io/gafparser.py#L73-L362 | def parse_line(self, line):
"""
Parses a single line of a GAF
Return a tuple `(processed_line, associations)`. Typically
there will be a single association, but in some cases there
may be none (invalid line) or multiple (disjunctive clause in
annotation extensions)
... | [
"def",
"parse_line",
"(",
"self",
",",
"line",
")",
":",
"# Returns assocparser.ParseResult",
"parsed",
"=",
"super",
"(",
")",
".",
"validate_line",
"(",
"line",
")",
"if",
"parsed",
":",
"return",
"parsed",
"if",
"self",
".",
"is_header",
"(",
"line",
")... | Parses a single line of a GAF
Return a tuple `(processed_line, associations)`. Typically
there will be a single association, but in some cases there
may be none (invalid line) or multiple (disjunctive clause in
annotation extensions)
Note: most applications will only need to ca... | [
"Parses",
"a",
"single",
"line",
"of",
"a",
"GAF"
] | python | train |
cdgriffith/Reusables | reusables/file_operations.py | https://github.com/cdgriffith/Reusables/blob/bc32f72e4baee7d76a6d58b88fcb23dd635155cd/reusables/file_operations.py#L796-L814 | def safe_filename(filename, replacement="_"):
"""
Replace unsafe filename characters with underscores. Note that this does not
test for "legal" names accepted, but a more restricted set of:
Letters, numbers, spaces, hyphens, underscores and periods.
:param filename: name of a file as a string
:... | [
"def",
"safe_filename",
"(",
"filename",
",",
"replacement",
"=",
"\"_\"",
")",
":",
"if",
"not",
"isinstance",
"(",
"filename",
",",
"str",
")",
":",
"raise",
"TypeError",
"(",
"\"filename must be a string\"",
")",
"if",
"regex",
".",
"path",
".",
"linux",
... | Replace unsafe filename characters with underscores. Note that this does not
test for "legal" names accepted, but a more restricted set of:
Letters, numbers, spaces, hyphens, underscores and periods.
:param filename: name of a file as a string
:param replacement: character to use as a replacement of ba... | [
"Replace",
"unsafe",
"filename",
"characters",
"with",
"underscores",
".",
"Note",
"that",
"this",
"does",
"not",
"test",
"for",
"legal",
"names",
"accepted",
"but",
"a",
"more",
"restricted",
"set",
"of",
":",
"Letters",
"numbers",
"spaces",
"hyphens",
"under... | python | train |
openstack/proliantutils | proliantutils/redfish/resources/system/storage/array_controller.py | https://github.com/openstack/proliantutils/blob/86ef3b47b4eca97c221577e3570b0240d6a25f22/proliantutils/redfish/resources/system/storage/array_controller.py#L74-L80 | def logical_drives_maximum_size_mib(self):
"""Gets the biggest logical drive
:returns the size in MiB.
"""
return utils.max_safe([member.logical_drives.maximum_size_mib
for member in self.get_members()]) | [
"def",
"logical_drives_maximum_size_mib",
"(",
"self",
")",
":",
"return",
"utils",
".",
"max_safe",
"(",
"[",
"member",
".",
"logical_drives",
".",
"maximum_size_mib",
"for",
"member",
"in",
"self",
".",
"get_members",
"(",
")",
"]",
")"
] | Gets the biggest logical drive
:returns the size in MiB. | [
"Gets",
"the",
"biggest",
"logical",
"drive"
] | python | train |
materialsproject/pymatgen | pymatgen/io/abinit/tasks.py | https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/io/abinit/tasks.py#L3209-L3217 | def gsr_path(self):
"""Absolute path of the GSR file. Empty string if file is not present."""
# Lazy property to avoid multiple calls to has_abiext.
try:
return self._gsr_path
except AttributeError:
path = self.outdir.has_abiext("GSR")
if path: self._g... | [
"def",
"gsr_path",
"(",
"self",
")",
":",
"# Lazy property to avoid multiple calls to has_abiext.",
"try",
":",
"return",
"self",
".",
"_gsr_path",
"except",
"AttributeError",
":",
"path",
"=",
"self",
".",
"outdir",
".",
"has_abiext",
"(",
"\"GSR\"",
")",
"if",
... | Absolute path of the GSR file. Empty string if file is not present. | [
"Absolute",
"path",
"of",
"the",
"GSR",
"file",
".",
"Empty",
"string",
"if",
"file",
"is",
"not",
"present",
"."
] | python | train |
Julius2342/pyvlx | old_api/pyvlx/interface.py | https://github.com/Julius2342/pyvlx/blob/ee78e1324bcb1be5b8d1a9d05ab5496b72eae848/old_api/pyvlx/interface.py#L98-L105 | def evaluate_response(json_response):
"""Evaluate rest response."""
if 'errors' in json_response and json_response['errors']:
Interface.evaluate_errors(json_response)
elif 'result' not in json_response:
raise PyVLXException('no element result found in response: {0}'.form... | [
"def",
"evaluate_response",
"(",
"json_response",
")",
":",
"if",
"'errors'",
"in",
"json_response",
"and",
"json_response",
"[",
"'errors'",
"]",
":",
"Interface",
".",
"evaluate_errors",
"(",
"json_response",
")",
"elif",
"'result'",
"not",
"in",
"json_response"... | Evaluate rest response. | [
"Evaluate",
"rest",
"response",
"."
] | python | train |
evolbioinfo/pastml | pastml/acr.py | https://github.com/evolbioinfo/pastml/blob/df8a375841525738383e59548eed3441b07dbd3e/pastml/acr.py#L137-L197 | def reconstruct_ancestral_states(tree, character, states, prediction_method=MPPA, model=F81,
params=None, avg_br_len=None, num_nodes=None, num_tips=None,
force_joint=True):
"""
Reconstructs ancestral states for the given character on the given tr... | [
"def",
"reconstruct_ancestral_states",
"(",
"tree",
",",
"character",
",",
"states",
",",
"prediction_method",
"=",
"MPPA",
",",
"model",
"=",
"F81",
",",
"params",
"=",
"None",
",",
"avg_br_len",
"=",
"None",
",",
"num_nodes",
"=",
"None",
",",
"num_tips",
... | Reconstructs ancestral states for the given character on the given tree.
:param character: character whose ancestral states are to be reconstructed.
:type character: str
:param tree: tree whose ancestral state are to be reconstructed,
annotated with the feature specified as `character` containing n... | [
"Reconstructs",
"ancestral",
"states",
"for",
"the",
"given",
"character",
"on",
"the",
"given",
"tree",
"."
] | python | train |
hydpy-dev/hydpy | hydpy/models/lland/lland_model.py | https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/models/lland/lland_model.py#L1414-L1520 | def calc_qdgz1_qdgz2_v1(self):
"""Seperate total direct flow into a small and a fast component.
Required control parameters:
|A1|
|A2|
Required flux sequence:
|QDGZ|
Calculated state sequences:
|QDGZ1|
|QDGZ2|
Basic equation:
:math:`QDGZ2 = \\frac{(QDGZ-A2)^2... | [
"def",
"calc_qdgz1_qdgz2_v1",
"(",
"self",
")",
":",
"con",
"=",
"self",
".",
"parameters",
".",
"control",
".",
"fastaccess",
"flu",
"=",
"self",
".",
"sequences",
".",
"fluxes",
".",
"fastaccess",
"sta",
"=",
"self",
".",
"sequences",
".",
"states",
".... | Seperate total direct flow into a small and a fast component.
Required control parameters:
|A1|
|A2|
Required flux sequence:
|QDGZ|
Calculated state sequences:
|QDGZ1|
|QDGZ2|
Basic equation:
:math:`QDGZ2 = \\frac{(QDGZ-A2)^2}{QDGZ+A1-A2}`
:math:`QDGZ1 = Q... | [
"Seperate",
"total",
"direct",
"flow",
"into",
"a",
"small",
"and",
"a",
"fast",
"component",
"."
] | python | train |
vintasoftware/django-role-permissions | rolepermissions/checkers.py | https://github.com/vintasoftware/django-role-permissions/blob/28924361e689e994e0c3575e18104a1a5abd8de6/rolepermissions/checkers.py#L38-L49 | def has_object_permission(checker_name, user, obj):
"""Check if a user has permission to perform an action on an object."""
if user and user.is_superuser:
return True
checker = PermissionsManager.retrieve_checker(checker_name)
user_roles = get_user_roles(user)
if not user_roles:
us... | [
"def",
"has_object_permission",
"(",
"checker_name",
",",
"user",
",",
"obj",
")",
":",
"if",
"user",
"and",
"user",
".",
"is_superuser",
":",
"return",
"True",
"checker",
"=",
"PermissionsManager",
".",
"retrieve_checker",
"(",
"checker_name",
")",
"user_roles"... | Check if a user has permission to perform an action on an object. | [
"Check",
"if",
"a",
"user",
"has",
"permission",
"to",
"perform",
"an",
"action",
"on",
"an",
"object",
"."
] | python | train |
PrefPy/prefpy | prefpy/mechanism.py | https://github.com/PrefPy/prefpy/blob/f395ba3782f05684fa5de0cece387a6da9391d02/prefpy/mechanism.py#L1096-L1155 | def coombstoc_winners(self, profile):
"""
Returns an integer list that represents all possible winners of a profile under Coombs rule.
:ivar Profile profile: A Profile object that represents an election profile.
"""
ordering = profile.getOrderVectors()
m = profile.numCan... | [
"def",
"coombstoc_winners",
"(",
"self",
",",
"profile",
")",
":",
"ordering",
"=",
"profile",
".",
"getOrderVectors",
"(",
")",
"m",
"=",
"profile",
".",
"numCands",
"prefcounts",
"=",
"profile",
".",
"getPreferenceCounts",
"(",
")",
"rankmaps",
"=",
"profi... | Returns an integer list that represents all possible winners of a profile under Coombs rule.
:ivar Profile profile: A Profile object that represents an election profile. | [
"Returns",
"an",
"integer",
"list",
"that",
"represents",
"all",
"possible",
"winners",
"of",
"a",
"profile",
"under",
"Coombs",
"rule",
"."
] | python | train |
django-blog-zinnia/cmsplugin-zinnia | cmsplugin_zinnia/menu.py | https://github.com/django-blog-zinnia/cmsplugin-zinnia/blob/7613c0d9ae29affe9ab97527e4b6d5bef124afdc/cmsplugin_zinnia/menu.py#L26-L67 | def get_nodes(self, request):
"""
Return menu's node for entries
"""
nodes = []
archives = []
attributes = {'hidden': HIDE_ENTRY_MENU}
for entry in Entry.published.all():
year = entry.creation_date.strftime('%Y')
month = entry.creation_date... | [
"def",
"get_nodes",
"(",
"self",
",",
"request",
")",
":",
"nodes",
"=",
"[",
"]",
"archives",
"=",
"[",
"]",
"attributes",
"=",
"{",
"'hidden'",
":",
"HIDE_ENTRY_MENU",
"}",
"for",
"entry",
"in",
"Entry",
".",
"published",
".",
"all",
"(",
")",
":",... | Return menu's node for entries | [
"Return",
"menu",
"s",
"node",
"for",
"entries"
] | python | train |
saltstack/salt | salt/grains/core.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/grains/core.py#L2403-L2410 | def saltpath():
'''
Return the path of the salt module
'''
# Provides:
# saltpath
salt_path = os.path.abspath(os.path.join(__file__, os.path.pardir))
return {'saltpath': os.path.dirname(salt_path)} | [
"def",
"saltpath",
"(",
")",
":",
"# Provides:",
"# saltpath",
"salt_path",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"__file__",
",",
"os",
".",
"path",
".",
"pardir",
")",
")",
"return",
"{",
"'saltpath'",
... | Return the path of the salt module | [
"Return",
"the",
"path",
"of",
"the",
"salt",
"module"
] | python | train |
Kozea/cairocffi | cairocffi/pixbuf.py | https://github.com/Kozea/cairocffi/blob/450853add7e32eea20985b6aa5f54d9cb3cd04fe/cairocffi/pixbuf.py#L140-L187 | def pixbuf_to_cairo_slices(pixbuf):
"""Convert from PixBuf to ImageSurface, using slice-based byte swapping.
This method is 2~5x slower than GDK but does not support an alpha channel.
(cairo uses pre-multiplied alpha, but not Pixbuf.)
"""
assert pixbuf.get_colorspace() == gdk_pixbuf.GDK_COLORSPACE... | [
"def",
"pixbuf_to_cairo_slices",
"(",
"pixbuf",
")",
":",
"assert",
"pixbuf",
".",
"get_colorspace",
"(",
")",
"==",
"gdk_pixbuf",
".",
"GDK_COLORSPACE_RGB",
"assert",
"pixbuf",
".",
"get_n_channels",
"(",
")",
"==",
"3",
"assert",
"pixbuf",
".",
"get_bits_per_s... | Convert from PixBuf to ImageSurface, using slice-based byte swapping.
This method is 2~5x slower than GDK but does not support an alpha channel.
(cairo uses pre-multiplied alpha, but not Pixbuf.) | [
"Convert",
"from",
"PixBuf",
"to",
"ImageSurface",
"using",
"slice",
"-",
"based",
"byte",
"swapping",
"."
] | python | train |
mikedh/trimesh | trimesh/path/path.py | https://github.com/mikedh/trimesh/blob/25e059bf6d4caa74f62ffd58ce4f61a90ee4e518/trimesh/path/path.py#L572-L582 | def remove_invalid(self):
"""
Remove entities which declare themselves invalid
Alters
----------
self.entities: shortened
"""
valid = np.array([i.is_valid for i in self.entities],
dtype=np.bool)
self.entities = self.entities[valid... | [
"def",
"remove_invalid",
"(",
"self",
")",
":",
"valid",
"=",
"np",
".",
"array",
"(",
"[",
"i",
".",
"is_valid",
"for",
"i",
"in",
"self",
".",
"entities",
"]",
",",
"dtype",
"=",
"np",
".",
"bool",
")",
"self",
".",
"entities",
"=",
"self",
"."... | Remove entities which declare themselves invalid
Alters
----------
self.entities: shortened | [
"Remove",
"entities",
"which",
"declare",
"themselves",
"invalid"
] | python | train |
PyPSA/PyPSA | pypsa/components.py | https://github.com/PyPSA/PyPSA/blob/46954b1b3c21460550f7104681517065279a53b7/pypsa/components.py#L378-L406 | def set_snapshots(self,snapshots):
"""
Set the snapshots and reindex all time-dependent data.
This will reindex all pandas.Panels of time-dependent data; NaNs are filled
with the default value for that quantity.
Parameters
----------
snapshots : list or pandas.I... | [
"def",
"set_snapshots",
"(",
"self",
",",
"snapshots",
")",
":",
"self",
".",
"snapshots",
"=",
"pd",
".",
"Index",
"(",
"snapshots",
")",
"self",
".",
"snapshot_weightings",
"=",
"self",
".",
"snapshot_weightings",
".",
"reindex",
"(",
"self",
".",
"snaps... | Set the snapshots and reindex all time-dependent data.
This will reindex all pandas.Panels of time-dependent data; NaNs are filled
with the default value for that quantity.
Parameters
----------
snapshots : list or pandas.Index
All time steps.
Returns
... | [
"Set",
"the",
"snapshots",
"and",
"reindex",
"all",
"time",
"-",
"dependent",
"data",
"."
] | python | train |
apache/incubator-mxnet | python/mxnet/autograd.py | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/autograd.py#L70-L79 | def is_recording():
"""Get status on recording/not recording.
Returns
-------
Current state of recording.
"""
curr = ctypes.c_bool()
check_call(_LIB.MXAutogradIsRecording(ctypes.byref(curr)))
return curr.value | [
"def",
"is_recording",
"(",
")",
":",
"curr",
"=",
"ctypes",
".",
"c_bool",
"(",
")",
"check_call",
"(",
"_LIB",
".",
"MXAutogradIsRecording",
"(",
"ctypes",
".",
"byref",
"(",
"curr",
")",
")",
")",
"return",
"curr",
".",
"value"
] | Get status on recording/not recording.
Returns
-------
Current state of recording. | [
"Get",
"status",
"on",
"recording",
"/",
"not",
"recording",
"."
] | python | train |
saltstack/salt | salt/modules/vsphere.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/vsphere.py#L5668-L5696 | def remove_datastore(datastore, service_instance=None):
'''
Removes a datastore. If multiple datastores an error is raised.
datastore
Datastore name
service_instance
Service instance (vim.ServiceInstance) of the vCenter/ESXi host.
Default is None.
.. code-block:: bash
... | [
"def",
"remove_datastore",
"(",
"datastore",
",",
"service_instance",
"=",
"None",
")",
":",
"log",
".",
"trace",
"(",
"'Removing datastore \\'%s\\''",
",",
"datastore",
")",
"target",
"=",
"_get_proxy_target",
"(",
"service_instance",
")",
"datastores",
"=",
"sal... | Removes a datastore. If multiple datastores an error is raised.
datastore
Datastore name
service_instance
Service instance (vim.ServiceInstance) of the vCenter/ESXi host.
Default is None.
.. code-block:: bash
salt '*' vsphere.remove_datastore ds_name | [
"Removes",
"a",
"datastore",
".",
"If",
"multiple",
"datastores",
"an",
"error",
"is",
"raised",
"."
] | python | train |
ctuning/ck | ck/kernel.py | https://github.com/ctuning/ck/blob/7e009814e975f8742790d3106340088a46223714/ck/kernel.py#L2534-L2551 | def save_repo_cache(i):
"""
Input: {}
Output: {
return - return code = 0, if successful
> 0, if error
(error) - error text if return > 0
}
"""
r=save_json_to_file({'json_file':work['dir_cache_repo_uoa'],... | [
"def",
"save_repo_cache",
"(",
"i",
")",
":",
"r",
"=",
"save_json_to_file",
"(",
"{",
"'json_file'",
":",
"work",
"[",
"'dir_cache_repo_uoa'",
"]",
",",
"'dict'",
":",
"cache_repo_uoa",
"}",
")",
"if",
"r",
"[",
"'return'",
"]",
">",
"0",
":",
"return",... | Input: {}
Output: {
return - return code = 0, if successful
> 0, if error
(error) - error text if return > 0
} | [
"Input",
":",
"{}"
] | python | train |
roboogle/gtkmvc3 | gtkmvco/gtkmvc3/adapters/containers.py | https://github.com/roboogle/gtkmvc3/blob/63405fd8d2056be26af49103b13a8d5e57fe4dff/gtkmvco/gtkmvc3/adapters/containers.py#L242-L246 | def _on_prop_changed(self, instance, meth_name, res, args, kwargs):
"""Called by the observation code, we are interested in
__setitem__"""
if not self._itsme and meth_name == "__setitem__": self.update_widget(args[0])
return | [
"def",
"_on_prop_changed",
"(",
"self",
",",
"instance",
",",
"meth_name",
",",
"res",
",",
"args",
",",
"kwargs",
")",
":",
"if",
"not",
"self",
".",
"_itsme",
"and",
"meth_name",
"==",
"\"__setitem__\"",
":",
"self",
".",
"update_widget",
"(",
"args",
... | Called by the observation code, we are interested in
__setitem__ | [
"Called",
"by",
"the",
"observation",
"code",
"we",
"are",
"interested",
"in",
"__setitem__"
] | python | train |
datastax/python-driver | cassandra/cluster.py | https://github.com/datastax/python-driver/blob/30a80d0b798b1f45f8cb77163b1fa791f3e3ca29/cassandra/cluster.py#L1228-L1251 | def set_core_connections_per_host(self, host_distance, core_connections):
"""
Sets the minimum number of connections per Session that will be opened
for each host with :class:`~.HostDistance` equal to `host_distance`.
The default is 2 for :attr:`~HostDistance.LOCAL` and 1 for
:at... | [
"def",
"set_core_connections_per_host",
"(",
"self",
",",
"host_distance",
",",
"core_connections",
")",
":",
"if",
"self",
".",
"protocol_version",
">=",
"3",
":",
"raise",
"UnsupportedOperation",
"(",
"\"Cluster.set_core_connections_per_host() only has an effect \"",
"\"w... | Sets the minimum number of connections per Session that will be opened
for each host with :class:`~.HostDistance` equal to `host_distance`.
The default is 2 for :attr:`~HostDistance.LOCAL` and 1 for
:attr:`~HostDistance.REMOTE`.
Protocol version 1 and 2 are limited in the number of conc... | [
"Sets",
"the",
"minimum",
"number",
"of",
"connections",
"per",
"Session",
"that",
"will",
"be",
"opened",
"for",
"each",
"host",
"with",
":",
"class",
":",
"~",
".",
"HostDistance",
"equal",
"to",
"host_distance",
".",
"The",
"default",
"is",
"2",
"for",
... | python | train |
inspirehep/refextract | refextract/references/engine.py | https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/references/engine.py#L1364-L1375 | def remove_leading_garbage_lines_from_reference_section(ref_sectn):
"""Sometimes, the first lines of the extracted references are completely
blank or email addresses. These must be removed as they are not
references.
@param ref_sectn: (list) of strings - the reference section lines
@retu... | [
"def",
"remove_leading_garbage_lines_from_reference_section",
"(",
"ref_sectn",
")",
":",
"p_email",
"=",
"re",
".",
"compile",
"(",
"ur'^\\s*e\\-?mail'",
",",
"re",
".",
"UNICODE",
")",
"while",
"ref_sectn",
"and",
"(",
"ref_sectn",
"[",
"0",
"]",
".",
"isspace... | Sometimes, the first lines of the extracted references are completely
blank or email addresses. These must be removed as they are not
references.
@param ref_sectn: (list) of strings - the reference section lines
@return: (list) of strings - the reference section without leading
blank... | [
"Sometimes",
"the",
"first",
"lines",
"of",
"the",
"extracted",
"references",
"are",
"completely",
"blank",
"or",
"email",
"addresses",
".",
"These",
"must",
"be",
"removed",
"as",
"they",
"are",
"not",
"references",
"."
] | python | train |
UCL-INGI/INGInious | inginious/frontend/pages/api/tasks.py | https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/pages/api/tasks.py#L30-L103 | def API_GET(self, courseid, taskid=None): # pylint: disable=arguments-differ
"""
List tasks available to the connected client. Returns a dict in the form
::
{
"taskid1":
{
"name": "Name of the course", ... | [
"def",
"API_GET",
"(",
"self",
",",
"courseid",
",",
"taskid",
"=",
"None",
")",
":",
"# pylint: disable=arguments-differ",
"try",
":",
"course",
"=",
"self",
".",
"course_factory",
".",
"get_course",
"(",
"courseid",
")",
"except",
":",
"raise",
"APINotFound"... | List tasks available to the connected client. Returns a dict in the form
::
{
"taskid1":
{
"name": "Name of the course", #the name of the course
"authors": [],
"deadline": ""... | [
"List",
"tasks",
"available",
"to",
"the",
"connected",
"client",
".",
"Returns",
"a",
"dict",
"in",
"the",
"form"
] | python | train |
totalgood/twip | twip/wip/build_pycon_slides.py | https://github.com/totalgood/twip/blob/5c0411d2acfbe5b421841072814c9152591c03f7/twip/wip/build_pycon_slides.py#L25-L59 | def parse_args(args):
"""
Parse command line parameters
:param args: command line parameters as list of strings
:return: command line parameters as :obj:`argparse.Namespace`
"""
parser = argparse.ArgumentParser(
description="Build html reveal.js slides from markdown in docs/ dir")
p... | [
"def",
"parse_args",
"(",
"args",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"\"Build html reveal.js slides from markdown in docs/ dir\"",
")",
"parser",
".",
"add_argument",
"(",
"'-v'",
",",
"'--verbose'",
",",
"help",
"="... | Parse command line parameters
:param args: command line parameters as list of strings
:return: command line parameters as :obj:`argparse.Namespace` | [
"Parse",
"command",
"line",
"parameters"
] | python | train |
sorgerlab/indra | indra/sources/trips/analyze_ekbs.py | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/trips/analyze_ekbs.py#L137-L148 | def check_event_coverage(patterns, event_list):
"""Calculate the ratio of patterns that were extracted."""
proportions = []
for pattern_list in patterns:
proportion = 0
for pattern in pattern_list:
for node in pattern.nodes():
if node in event_list:
... | [
"def",
"check_event_coverage",
"(",
"patterns",
",",
"event_list",
")",
":",
"proportions",
"=",
"[",
"]",
"for",
"pattern_list",
"in",
"patterns",
":",
"proportion",
"=",
"0",
"for",
"pattern",
"in",
"pattern_list",
":",
"for",
"node",
"in",
"pattern",
".",... | Calculate the ratio of patterns that were extracted. | [
"Calculate",
"the",
"ratio",
"of",
"patterns",
"that",
"were",
"extracted",
"."
] | python | train |
angr/angr | angr/analyses/ddg.py | https://github.com/angr/angr/blob/4e2f97d56af5419ee73bdb30482c8dd8ff5f3e40/angr/analyses/ddg.py#L1316-L1331 | def _stmt_graph_add_edge(self, src, dst, **edge_labels):
"""
Add an edge in the statement dependence graph from a program location `src` to another program location `dst`.
:param CodeLocation src: Source node.
:param CodeLocation dst: Destination node.
:param edge_labels: All la... | [
"def",
"_stmt_graph_add_edge",
"(",
"self",
",",
"src",
",",
"dst",
",",
"*",
"*",
"edge_labels",
")",
":",
"# Is that edge already in the graph ?",
"# If at least one is new, then we are not redoing the same path again",
"if",
"src",
"in",
"self",
".",
"_stmt_graph",
"an... | Add an edge in the statement dependence graph from a program location `src` to another program location `dst`.
:param CodeLocation src: Source node.
:param CodeLocation dst: Destination node.
:param edge_labels: All labels associated with the edge.
:returns: None | [
"Add",
"an",
"edge",
"in",
"the",
"statement",
"dependence",
"graph",
"from",
"a",
"program",
"location",
"src",
"to",
"another",
"program",
"location",
"dst",
"."
] | python | train |
python-visualization/folium | folium/map.py | https://github.com/python-visualization/folium/blob/8595240517135d1637ca4cf7cc624045f1d911b3/folium/map.py#L148-L162 | def render(self, **kwargs):
"""Renders the HTML representation of the element."""
for item in self._parent._children.values():
if not isinstance(item, Layer) or not item.control:
continue
key = item.layer_name
if not item.overlay:
self.... | [
"def",
"render",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"item",
"in",
"self",
".",
"_parent",
".",
"_children",
".",
"values",
"(",
")",
":",
"if",
"not",
"isinstance",
"(",
"item",
",",
"Layer",
")",
"or",
"not",
"item",
".",
"co... | Renders the HTML representation of the element. | [
"Renders",
"the",
"HTML",
"representation",
"of",
"the",
"element",
"."
] | python | train |
tensorflow/tensor2tensor | tensor2tensor/models/resnet.py | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/resnet.py#L690-L697 | def resnet_imagenet_34_td_unit_05_05():
"""Set of hyperparameters."""
hp = resnet_imagenet_34()
hp.use_td = "unit"
hp.targeting_rate = 0.5
hp.keep_prob = 0.5
return hp | [
"def",
"resnet_imagenet_34_td_unit_05_05",
"(",
")",
":",
"hp",
"=",
"resnet_imagenet_34",
"(",
")",
"hp",
".",
"use_td",
"=",
"\"unit\"",
"hp",
".",
"targeting_rate",
"=",
"0.5",
"hp",
".",
"keep_prob",
"=",
"0.5",
"return",
"hp"
] | Set of hyperparameters. | [
"Set",
"of",
"hyperparameters",
"."
] | python | train |
proycon/pynlpl | pynlpl/formats/folia.py | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/folia.py#L1357-L1364 | def settext(self, text, cls='current'):
"""Set the text for this element.
Arguments:
text (str): The text
cls (str): The class of the text, defaults to ``current`` (leave this unless you know what you are doing). There may be only one text content element of each class associate... | [
"def",
"settext",
"(",
"self",
",",
"text",
",",
"cls",
"=",
"'current'",
")",
":",
"self",
".",
"replace",
"(",
"TextContent",
",",
"value",
"=",
"text",
",",
"cls",
"=",
"cls",
")"
] | Set the text for this element.
Arguments:
text (str): The text
cls (str): The class of the text, defaults to ``current`` (leave this unless you know what you are doing). There may be only one text content element of each class associated with the element. | [
"Set",
"the",
"text",
"for",
"this",
"element",
"."
] | python | train |
kolypto/py-good | good/schema/compiler.py | https://github.com/kolypto/py-good/blob/192ef19e79f6fd95c1cbd7c378a3074c7ad7a6d4/good/schema/compiler.py#L359-L397 | def _compile_callable(self, schema):
""" Compile callable: wrap exceptions with correct paths """
# Prepare self
self.compiled_type = const.COMPILED_TYPE.CALLABLE
self.name = get_callable_name(schema)
# Error utils
enrich_exception = lambda e, value: e.enrich(
... | [
"def",
"_compile_callable",
"(",
"self",
",",
"schema",
")",
":",
"# Prepare self",
"self",
".",
"compiled_type",
"=",
"const",
".",
"COMPILED_TYPE",
".",
"CALLABLE",
"self",
".",
"name",
"=",
"get_callable_name",
"(",
"schema",
")",
"# Error utils",
"enrich_exc... | Compile callable: wrap exceptions with correct paths | [
"Compile",
"callable",
":",
"wrap",
"exceptions",
"with",
"correct",
"paths"
] | python | train |
saltzm/yadi | yadi/datalog2sql/ast2sql/sql_generator.py | https://github.com/saltzm/yadi/blob/755790167c350e650c1e8b15c6f9209a97be9e42/yadi/datalog2sql/ast2sql/sql_generator.py#L234-L264 | def get_explicit_constraints(self,constraints,var_dict):
'''
Returns SQL representation of an explicit constraint. An explicit
constraint is one of the form Element COMP Element type, explicitly
listed in the conjunctive query. E.G. R(X,Y), Y>2 specifies that R.2 > 2
'''
... | [
"def",
"get_explicit_constraints",
"(",
"self",
",",
"constraints",
",",
"var_dict",
")",
":",
"constraints_strings",
"=",
"[",
"]",
"for",
"constraint",
"in",
"constraints",
":",
"ls",
"=",
"constraint",
".",
"get_left_side",
"(",
")",
"rs",
"=",
"constraint"... | Returns SQL representation of an explicit constraint. An explicit
constraint is one of the form Element COMP Element type, explicitly
listed in the conjunctive query. E.G. R(X,Y), Y>2 specifies that R.2 > 2 | [
"Returns",
"SQL",
"representation",
"of",
"an",
"explicit",
"constraint",
".",
"An",
"explicit",
"constraint",
"is",
"one",
"of",
"the",
"form",
"Element",
"COMP",
"Element",
"type",
"explicitly",
"listed",
"in",
"the",
"conjunctive",
"query",
".",
"E",
".",
... | python | train |
5monkeys/django-bananas | bananas/admin/api/views.py | https://github.com/5monkeys/django-bananas/blob/cfd318c737f6c4580036c13d2acf32bca96654bf/bananas/admin/api/views.py#L103-L117 | def create(self, request):
"""
Change password for logged in django staff user
"""
# TODO: Decorate api with sensitive post parameters as Django admin do?
password_form = PasswordChangeForm(request.user, data=request.data)
if not password_form.is_valid():
ra... | [
"def",
"create",
"(",
"self",
",",
"request",
")",
":",
"# TODO: Decorate api with sensitive post parameters as Django admin do?",
"password_form",
"=",
"PasswordChangeForm",
"(",
"request",
".",
"user",
",",
"data",
"=",
"request",
".",
"data",
")",
"if",
"not",
"p... | Change password for logged in django staff user | [
"Change",
"password",
"for",
"logged",
"in",
"django",
"staff",
"user"
] | python | test |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.