repo stringlengths 7 55 | path stringlengths 4 223 | url stringlengths 87 315 | code stringlengths 75 104k | code_tokens list | docstring stringlengths 1 46.9k | docstring_tokens list | language stringclasses 1
value | partition stringclasses 3
values | avg_line_len float64 7.91 980 |
|---|---|---|---|---|---|---|---|---|---|
RaRe-Technologies/smart_open | smart_open/http.py | https://github.com/RaRe-Technologies/smart_open/blob/2dc8d60f223fc7b00a2000c56362a7bd6cd0850e/smart_open/http.py#L25-L51 | def open(uri, mode, kerberos=False, user=None, password=None):
"""Implement streamed reader from a web site.
Supports Kerberos and Basic HTTP authentication.
Parameters
----------
url: str
The URL to open.
mode: str
The mode to open using.
kerberos: boolean, optional
... | [
"def",
"open",
"(",
"uri",
",",
"mode",
",",
"kerberos",
"=",
"False",
",",
"user",
"=",
"None",
",",
"password",
"=",
"None",
")",
":",
"if",
"mode",
"==",
"'rb'",
":",
"return",
"BufferedInputBase",
"(",
"uri",
",",
"mode",
",",
"kerberos",
"=",
... | Implement streamed reader from a web site.
Supports Kerberos and Basic HTTP authentication.
Parameters
----------
url: str
The URL to open.
mode: str
The mode to open using.
kerberos: boolean, optional
If True, will attempt to use the local Kerberos credentials
user... | [
"Implement",
"streamed",
"reader",
"from",
"a",
"web",
"site",
"."
] | python | train | 30.62963 |
saltstack/salt | salt/modules/glassfish.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/glassfish.py#L112-L123 | def _api_get(path, server=None):
'''
Do a GET request to the API
'''
server = _get_server(server)
response = requests.get(
url=_get_url(server['ssl'], server['url'], server['port'], path),
auth=_get_auth(server['user'], server['password']),
headers=_get_headers(),... | [
"def",
"_api_get",
"(",
"path",
",",
"server",
"=",
"None",
")",
":",
"server",
"=",
"_get_server",
"(",
"server",
")",
"response",
"=",
"requests",
".",
"get",
"(",
"url",
"=",
"_get_url",
"(",
"server",
"[",
"'ssl'",
"]",
",",
"server",
"[",
"'url'... | Do a GET request to the API | [
"Do",
"a",
"GET",
"request",
"to",
"the",
"API"
] | python | train | 31.25 |
MattBroach/DjangoRestMultipleModels | drf_multiple_model/mixins.py | https://github.com/MattBroach/DjangoRestMultipleModels/blob/893969ed38d614a5e2f060e560824fa7c5c49cfd/drf_multiple_model/mixins.py#L68-L79 | def get_empty_results(self):
"""
Because the base result type is different depending on the return structure
(e.g. list for flat, dict for object), `get_result_type` initials the
`results` variable to the proper type
"""
assert self.result_type is not None, (
... | [
"def",
"get_empty_results",
"(",
"self",
")",
":",
"assert",
"self",
".",
"result_type",
"is",
"not",
"None",
",",
"(",
"'{} must specify a `result_type` value or overwrite the '",
"'`get_empty_result` method.'",
".",
"format",
"(",
"self",
".",
"__class__",
".",
"__n... | Because the base result type is different depending on the return structure
(e.g. list for flat, dict for object), `get_result_type` initials the
`results` variable to the proper type | [
"Because",
"the",
"base",
"result",
"type",
"is",
"different",
"depending",
"on",
"the",
"return",
"structure",
"(",
"e",
".",
"g",
".",
"list",
"for",
"flat",
"dict",
"for",
"object",
")",
"get_result_type",
"initials",
"the",
"results",
"variable",
"to",
... | python | train | 40.333333 |
lark-parser/lark | examples/standalone/json_parser.py | https://github.com/lark-parser/lark/blob/a798dec77907e74520dd7e90c7b6a4acc680633a/examples/standalone/json_parser.py#L539-L545 | def v_args(inline=False, meta=False, tree=False):
"A convenience decorator factory, for modifying the behavior of user-supplied visitor methods"
if [tree, meta, inline].count(True) > 1:
raise ValueError("Visitor functions can either accept tree, or meta, or be inlined. These cannot be combined.")
de... | [
"def",
"v_args",
"(",
"inline",
"=",
"False",
",",
"meta",
"=",
"False",
",",
"tree",
"=",
"False",
")",
":",
"if",
"[",
"tree",
",",
"meta",
",",
"inline",
"]",
".",
"count",
"(",
"True",
")",
">",
"1",
":",
"raise",
"ValueError",
"(",
"\"Visito... | A convenience decorator factory, for modifying the behavior of user-supplied visitor methods | [
"A",
"convenience",
"decorator",
"factory",
"for",
"modifying",
"the",
"behavior",
"of",
"user",
"-",
"supplied",
"visitor",
"methods"
] | python | train | 67.428571 |
opereto/pyopereto | pyopereto/client.py | https://github.com/opereto/pyopereto/blob/16ca987738a7e1b82b52b0b099794a74ed557223/pyopereto/client.py#L1197-L1222 | def search_process_log(self, pid, filter={}, start=0, limit=1000):
'''
search_process_log(self, pid, filter={}, start=0, limit=1000)
Search in process logs
:Parameters:
* *pid* (`string`) -- Identifier of an existing process
* *start* (`int`) -- start index to retrieve ... | [
"def",
"search_process_log",
"(",
"self",
",",
"pid",
",",
"filter",
"=",
"{",
"}",
",",
"start",
"=",
"0",
",",
"limit",
"=",
"1000",
")",
":",
"pid",
"=",
"self",
".",
"_get_pid",
"(",
"pid",
")",
"request_data",
"=",
"{",
"'start'",
":",
"start"... | search_process_log(self, pid, filter={}, start=0, limit=1000)
Search in process logs
:Parameters:
* *pid* (`string`) -- Identifier of an existing process
* *start* (`int`) -- start index to retrieve from. Default is 0
* *limit* (`int`) -- maximum number of entities to retrieve.... | [
"search_process_log",
"(",
"self",
"pid",
"filter",
"=",
"{}",
"start",
"=",
"0",
"limit",
"=",
"1000",
")"
] | python | train | 43.076923 |
django-danceschool/django-danceschool | danceschool/core/models.py | https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/models.py#L780-L792 | def get_email_context(self,**kwargs):
''' Overrides EmailRecipientMixin '''
context = super(Event,self).get_email_context(**kwargs)
context.update({
'id': self.id,
'name': self.__str__(),
'title': self.name,
'start': self.firstOccurrenceTime,
... | [
"def",
"get_email_context",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"context",
"=",
"super",
"(",
"Event",
",",
"self",
")",
".",
"get_email_context",
"(",
"*",
"*",
"kwargs",
")",
"context",
".",
"update",
"(",
"{",
"'id'",
":",
"self",
".",... | Overrides EmailRecipientMixin | [
"Overrides",
"EmailRecipientMixin"
] | python | train | 35 |
brocade/pynos | pynos/versions/ver_6/ver_6_0_1/yang/tailf_webui.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_6/ver_6_0_1/yang/tailf_webui.py#L402-L418 | def webui_data_stores_user_profile_saved_query_value(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
webui = ET.SubElement(config, "webui", xmlns="http://tail-f.com/ns/webui")
data_stores = ET.SubElement(webui, "data-stores")
user_profile = ET.Su... | [
"def",
"webui_data_stores_user_profile_saved_query_value",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"webui",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"webui\"",
",",
"xmlns",
"=",... | Auto Generated Code | [
"Auto",
"Generated",
"Code"
] | python | train | 46.882353 |
Parquery/sphinx-icontract | sphinx_icontract/__init__.py | https://github.com/Parquery/sphinx-icontract/blob/92918f23a8ea1873112e9b7446c64cd6f12ee04b/sphinx_icontract/__init__.py#L504-L508 | def process_docstring(app, what, name, obj, options, lines):
"""React to a docstring event and append contracts to it."""
# pylint: disable=unused-argument
# pylint: disable=too-many-arguments
lines.extend(_format_contracts(what=what, obj=obj)) | [
"def",
"process_docstring",
"(",
"app",
",",
"what",
",",
"name",
",",
"obj",
",",
"options",
",",
"lines",
")",
":",
"# pylint: disable=unused-argument",
"# pylint: disable=too-many-arguments",
"lines",
".",
"extend",
"(",
"_format_contracts",
"(",
"what",
"=",
"... | React to a docstring event and append contracts to it. | [
"React",
"to",
"a",
"docstring",
"event",
"and",
"append",
"contracts",
"to",
"it",
"."
] | python | train | 51.2 |
Metatab/metapack | metapack/doc.py | https://github.com/Metatab/metapack/blob/8365f221fbeaa3c0be9091f2eaf3447fd8e2e8d6/metapack/doc.py#L283-L304 | def write_csv(self, path=None):
"""Write CSV file. Sorts the sections before calling the superclass write_csv"""
# Sort the Sections
self.sort_sections(['Root', 'Contacts', 'Documentation', 'References', 'Resources', 'Citations', 'Schema'])
# Sort Terms in the root section
# ... | [
"def",
"write_csv",
"(",
"self",
",",
"path",
"=",
"None",
")",
":",
"# Sort the Sections",
"self",
".",
"sort_sections",
"(",
"[",
"'Root'",
",",
"'Contacts'",
",",
"'Documentation'",
",",
"'References'",
",",
"'Resources'",
",",
"'Citations'",
",",
"'Schema'... | Write CSV file. Sorts the sections before calling the superclass write_csv | [
"Write",
"CSV",
"file",
".",
"Sorts",
"the",
"sections",
"before",
"calling",
"the",
"superclass",
"write_csv"
] | python | train | 29.545455 |
IdentityPython/SATOSA | src/satosa/frontends/saml2.py | https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/frontends/saml2.py#L637-L649 | def _create_state_data(self, context, resp_args, relay_state):
"""
Adds the frontend idp entity id to state
See super class satosa.frontends.saml2.SAMLFrontend#save_state
:type context: satosa.context.Context
:type resp_args: dict[str, str | saml2.samlp.NameIDPolicy]
:ty... | [
"def",
"_create_state_data",
"(",
"self",
",",
"context",
",",
"resp_args",
",",
"relay_state",
")",
":",
"state",
"=",
"super",
"(",
")",
".",
"_create_state_data",
"(",
"context",
",",
"resp_args",
",",
"relay_state",
")",
"state",
"[",
"\"target_entity_id\"... | Adds the frontend idp entity id to state
See super class satosa.frontends.saml2.SAMLFrontend#save_state
:type context: satosa.context.Context
:type resp_args: dict[str, str | saml2.samlp.NameIDPolicy]
:type relay_state: str
:rtype: dict[str, dict[str, str] | str] | [
"Adds",
"the",
"frontend",
"idp",
"entity",
"id",
"to",
"state",
"See",
"super",
"class",
"satosa",
".",
"frontends",
".",
"saml2",
".",
"SAMLFrontend#save_state"
] | python | train | 42.846154 |
gbiggs/rtctree | rtctree/component.py | https://github.com/gbiggs/rtctree/blob/bd725a47ac87c259c8bce06156ccc9ab71111c26/rtctree/component.py#L532-L552 | def activate_in_ec(self, ec_index):
'''Activate this component in an execution context.
@param ec_index The index of the execution context to activate in.
This index is into the total array of contexts, that
is both owned and participating contexts. If th... | [
"def",
"activate_in_ec",
"(",
"self",
",",
"ec_index",
")",
":",
"with",
"self",
".",
"_mutex",
":",
"if",
"ec_index",
">=",
"len",
"(",
"self",
".",
"owned_ecs",
")",
":",
"ec_index",
"-=",
"len",
"(",
"self",
".",
"owned_ecs",
")",
"if",
"ec_index",
... | Activate this component in an execution context.
@param ec_index The index of the execution context to activate in.
This index is into the total array of contexts, that
is both owned and participating contexts. If the value
of ec_index is ... | [
"Activate",
"this",
"component",
"in",
"an",
"execution",
"context",
"."
] | python | train | 46.809524 |
codenerix/django-codenerix | codenerix/views.py | https://github.com/codenerix/django-codenerix/blob/1f5527b352141caaee902b37b2648791a06bd57d/codenerix/views.py#L3316-L3335 | def get_form(self, form_class=None):
'''
Set form groups to the groups specified in the view if defined
'''
formobj = super(GenModify, self).get_form(form_class)
# Set requested group to this form
selfgroups = getattr(self, "form_groups", None)
if selfgroups:
... | [
"def",
"get_form",
"(",
"self",
",",
"form_class",
"=",
"None",
")",
":",
"formobj",
"=",
"super",
"(",
"GenModify",
",",
"self",
")",
".",
"get_form",
"(",
"form_class",
")",
"# Set requested group to this form",
"selfgroups",
"=",
"getattr",
"(",
"self",
"... | Set form groups to the groups specified in the view if defined | [
"Set",
"form",
"groups",
"to",
"the",
"groups",
"specified",
"in",
"the",
"view",
"if",
"defined"
] | python | train | 33.5 |
aio-libs/aioredis | aioredis/commands/set.py | https://github.com/aio-libs/aioredis/blob/e8c33e39558d4cc91cf70dde490d8b330c97dc2e/aioredis/commands/set.py#L46-L51 | def spop(self, key, count=None, *, encoding=_NOTSET):
"""Remove and return one or multiple random members from a set."""
args = [key]
if count is not None:
args.append(count)
return self.execute(b'SPOP', *args, encoding=encoding) | [
"def",
"spop",
"(",
"self",
",",
"key",
",",
"count",
"=",
"None",
",",
"*",
",",
"encoding",
"=",
"_NOTSET",
")",
":",
"args",
"=",
"[",
"key",
"]",
"if",
"count",
"is",
"not",
"None",
":",
"args",
".",
"append",
"(",
"count",
")",
"return",
"... | Remove and return one or multiple random members from a set. | [
"Remove",
"and",
"return",
"one",
"or",
"multiple",
"random",
"members",
"from",
"a",
"set",
"."
] | python | train | 44.666667 |
MacHu-GWU/uszipcode-project | uszipcode/pkg/sqlalchemy_mate/engine_creator.py | https://github.com/MacHu-GWU/uszipcode-project/blob/96282b779a3efb422802de83c48ca284598ba952/uszipcode/pkg/sqlalchemy_mate/engine_creator.py#L143-L151 | def create_postgresql_pypostgresql(username, password, host, port, database, **kwargs): # pragma: no cover
"""
create an engine connected to a postgresql database using pypostgresql.
"""
return create_engine(
_create_postgresql_pypostgresql(
username, password, host, port, database)... | [
"def",
"create_postgresql_pypostgresql",
"(",
"username",
",",
"password",
",",
"host",
",",
"port",
",",
"database",
",",
"*",
"*",
"kwargs",
")",
":",
"# pragma: no cover",
"return",
"create_engine",
"(",
"_create_postgresql_pypostgresql",
"(",
"username",
",",
... | create an engine connected to a postgresql database using pypostgresql. | [
"create",
"an",
"engine",
"connected",
"to",
"a",
"postgresql",
"database",
"using",
"pypostgresql",
"."
] | python | train | 37.333333 |
j0057/github-release | github_release.py | https://github.com/j0057/github-release/blob/5421d1ad3e49eaad50c800e548f889d55e159b9d/github_release.py#L287-L343 | def _update_release_sha(repo_name, tag_name, new_release_sha, dry_run):
"""Update the commit associated with a given release tag.
Since updating a tag commit is not directly possible, this function
does the following steps:
* set the release tag to ``<tag_name>-tmp`` and associate it
with ``new_r... | [
"def",
"_update_release_sha",
"(",
"repo_name",
",",
"tag_name",
",",
"new_release_sha",
",",
"dry_run",
")",
":",
"if",
"new_release_sha",
"is",
"None",
":",
"return",
"refs",
"=",
"get_refs",
"(",
"repo_name",
",",
"tags",
"=",
"True",
",",
"pattern",
"=",... | Update the commit associated with a given release tag.
Since updating a tag commit is not directly possible, this function
does the following steps:
* set the release tag to ``<tag_name>-tmp`` and associate it
with ``new_release_sha``.
* delete tag ``refs/tags/<tag_name>``.
* update the relea... | [
"Update",
"the",
"commit",
"associated",
"with",
"a",
"given",
"release",
"tag",
"."
] | python | train | 36.964912 |
fvdsn/py-xml-escpos | xmlescpos/escpos.py | https://github.com/fvdsn/py-xml-escpos/blob/7f77e039c960d5773fb919aed02ba392dccbc360/xmlescpos/escpos.py#L189-L195 | def start_inline(self,stylestack=None):
""" starts an inline entity with an optional style definition """
self.stack.append('inline')
if self.dirty:
self.escpos._raw(' ')
if stylestack:
self.style(stylestack) | [
"def",
"start_inline",
"(",
"self",
",",
"stylestack",
"=",
"None",
")",
":",
"self",
".",
"stack",
".",
"append",
"(",
"'inline'",
")",
"if",
"self",
".",
"dirty",
":",
"self",
".",
"escpos",
".",
"_raw",
"(",
"' '",
")",
"if",
"stylestack",
":",
... | starts an inline entity with an optional style definition | [
"starts",
"an",
"inline",
"entity",
"with",
"an",
"optional",
"style",
"definition"
] | python | train | 36.857143 |
eyurtsev/FlowCytometryTools | FlowCytometryTools/core/transforms.py | https://github.com/eyurtsev/FlowCytometryTools/blob/4355632508b875273d68c7e2972c17668bcf7b40/FlowCytometryTools/core/transforms.py#L285-L300 | def parse_transform(transform, direction='forward'):
"""
direction : 'forward' | 'inverse'
"""
if hasattr(transform, '__call__'):
tfun = transform
tname = None
elif hasattr(transform, 'lower'):
tname = _get_canonical_name(transform)
if tname is None:
raise... | [
"def",
"parse_transform",
"(",
"transform",
",",
"direction",
"=",
"'forward'",
")",
":",
"if",
"hasattr",
"(",
"transform",
",",
"'__call__'",
")",
":",
"tfun",
"=",
"transform",
"tname",
"=",
"None",
"elif",
"hasattr",
"(",
"transform",
",",
"'lower'",
"... | direction : 'forward' | 'inverse' | [
"direction",
":",
"forward",
"|",
"inverse"
] | python | train | 33.0625 |
uber/rides-python-sdk | uber_rides/client.py | https://github.com/uber/rides-python-sdk/blob/76ecd75ab5235d792ec1010e36eca679ba285127/uber_rides/client.py#L928-L935 | def adapt_meta(self, meta):
"""Convert meta from error response to href and surge_id attributes."""
surge = meta.get('surge_confirmation')
href = surge.get('href')
surge_id = surge.get('surge_confirmation_id')
return href, surge_id | [
"def",
"adapt_meta",
"(",
"self",
",",
"meta",
")",
":",
"surge",
"=",
"meta",
".",
"get",
"(",
"'surge_confirmation'",
")",
"href",
"=",
"surge",
".",
"get",
"(",
"'href'",
")",
"surge_id",
"=",
"surge",
".",
"get",
"(",
"'surge_confirmation_id'",
")",
... | Convert meta from error response to href and surge_id attributes. | [
"Convert",
"meta",
"from",
"error",
"response",
"to",
"href",
"and",
"surge_id",
"attributes",
"."
] | python | train | 33.25 |
smarie/python-autoclass | autoclass/autoprops_.py | https://github.com/smarie/python-autoclass/blob/097098776c69ebc87bc1aeda6997431b29bd583a/autoclass/autoprops_.py#L46-L61 | def autoprops(include=None, # type: Union[str, Tuple[str]]
exclude=None, # type: Union[str, Tuple[str]]
cls=DECORATED):
"""
A decorator to automatically generate all properties getters and setters from the class constructor.
* if a @contract annotation exist on the __init__ met... | [
"def",
"autoprops",
"(",
"include",
"=",
"None",
",",
"# type: Union[str, Tuple[str]]",
"exclude",
"=",
"None",
",",
"# type: Union[str, Tuple[str]]",
"cls",
"=",
"DECORATED",
")",
":",
"return",
"autoprops_decorate",
"(",
"cls",
",",
"include",
"=",
"include",
",... | A decorator to automatically generate all properties getters and setters from the class constructor.
* if a @contract annotation exist on the __init__ method, mentioning a contract for a given parameter, the
parameter contract will be added on the generated setter method
* The user may override the generate... | [
"A",
"decorator",
"to",
"automatically",
"generate",
"all",
"properties",
"getters",
"and",
"setters",
"from",
"the",
"class",
"constructor",
".",
"*",
"if",
"a",
"@contract",
"annotation",
"exist",
"on",
"the",
"__init__",
"method",
"mentioning",
"a",
"contract... | python | train | 64.5625 |
influxdata/influxdb-python | influxdb/influxdb08/client.py | https://github.com/influxdata/influxdb-python/blob/d5d12499f3755199d5eedd8b363450f1cf4073bd/influxdb/influxdb08/client.py#L267-L319 | def write_points(self, data, time_precision='s', *args, **kwargs):
"""Write to multiple time series names.
An example data blob is:
data = [
{
"points": [
[
12
]
],
"name... | [
"def",
"write_points",
"(",
"self",
",",
"data",
",",
"time_precision",
"=",
"'s'",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"list_chunks",
"(",
"l",
",",
"n",
")",
":",
"\"\"\"Yield successive n-sized chunks from l.\"\"\"",
"for",
"i",
... | Write to multiple time series names.
An example data blob is:
data = [
{
"points": [
[
12
]
],
"name": "cpu_load_short",
"columns": [
"value"
... | [
"Write",
"to",
"multiple",
"time",
"series",
"names",
"."
] | python | train | 33.09434 |
grycap/RADL | radl/radl.py | https://github.com/grycap/RADL/blob/03ccabb0313a48a5aa0e20c1f7983fddcb95e9cb/radl/radl.py#L622-L633 | def get_contextualize_items_by_step(self, default=None):
"""Get a dictionary of the contextualize_items grouped by the step or the default value"""
if self.items:
res = {}
for elem in self.items.values():
if elem.num in res:
res[elem.num].appen... | [
"def",
"get_contextualize_items_by_step",
"(",
"self",
",",
"default",
"=",
"None",
")",
":",
"if",
"self",
".",
"items",
":",
"res",
"=",
"{",
"}",
"for",
"elem",
"in",
"self",
".",
"items",
".",
"values",
"(",
")",
":",
"if",
"elem",
".",
"num",
... | Get a dictionary of the contextualize_items grouped by the step or the default value | [
"Get",
"a",
"dictionary",
"of",
"the",
"contextualize_items",
"grouped",
"by",
"the",
"step",
"or",
"the",
"default",
"value"
] | python | train | 37.083333 |
jtwhite79/pyemu | pyemu/utils/pp_utils.py | https://github.com/jtwhite79/pyemu/blob/c504d8e7a4097cec07655a6318d275739bd8148a/pyemu/utils/pp_utils.py#L14-L228 | def setup_pilotpoints_grid(ml=None,sr=None,ibound=None,prefix_dict=None,
every_n_cell=4,
use_ibound_zones=False,
pp_dir='.',tpl_dir='.',
shapename="pp.shp"):
"""setup grid-based pilot points. Uses the ibound... | [
"def",
"setup_pilotpoints_grid",
"(",
"ml",
"=",
"None",
",",
"sr",
"=",
"None",
",",
"ibound",
"=",
"None",
",",
"prefix_dict",
"=",
"None",
",",
"every_n_cell",
"=",
"4",
",",
"use_ibound_zones",
"=",
"False",
",",
"pp_dir",
"=",
"'.'",
",",
"tpl_dir",... | setup grid-based pilot points. Uses the ibound to determine
where to set pilot points. pilot points are given generic ``pp_``
names unless ``prefix_dict`` is passed. Write template files and a
shapefile as well...hopefully this is useful to someone...
Parameters
----------
ml : flopy.mbase
... | [
"setup",
"grid",
"-",
"based",
"pilot",
"points",
".",
"Uses",
"the",
"ibound",
"to",
"determine",
"where",
"to",
"set",
"pilot",
"points",
".",
"pilot",
"points",
"are",
"given",
"generic",
"pp_",
"names",
"unless",
"prefix_dict",
"is",
"passed",
".",
"Wr... | python | train | 42.15814 |
Groundworkstech/pybfd | pybfd/objdump.py | https://github.com/Groundworkstech/pybfd/blob/9e722435929b4ad52212043a6f1e9e9ce60b5d72/pybfd/objdump.py#L254-L341 | def init_parser():
"""Initialize option parser."""
usage = "Usage: %(prog)s <option(s)> <file(s)>"
description = " Display information from object <file(s)>.\n"
description += " At least one of the following switches must be given:"
#
# Create an argument parser and an exclusive group.
#
... | [
"def",
"init_parser",
"(",
")",
":",
"usage",
"=",
"\"Usage: %(prog)s <option(s)> <file(s)>\"",
"description",
"=",
"\" Display information from object <file(s)>.\\n\"",
"description",
"+=",
"\" At least one of the following switches must be given:\"",
"#",
"# Create an argument parser... | Initialize option parser. | [
"Initialize",
"option",
"parser",
"."
] | python | train | 43.795455 |
pazz/alot | alot/db/utils.py | https://github.com/pazz/alot/blob/d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded/alot/db/utils.py#L82-L95 | def get_params(mail, failobj=None, header='content-type', unquote=True):
'''Get Content-Type parameters as dict.
RFC 2045 specifies that parameter names are case-insensitive, so
we normalize them here.
:param mail: :class:`email.message.Message`
:param failobj: object to return if no such header i... | [
"def",
"get_params",
"(",
"mail",
",",
"failobj",
"=",
"None",
",",
"header",
"=",
"'content-type'",
",",
"unquote",
"=",
"True",
")",
":",
"failobj",
"=",
"failobj",
"or",
"[",
"]",
"return",
"{",
"k",
".",
"lower",
"(",
")",
":",
"v",
"for",
"k",... | Get Content-Type parameters as dict.
RFC 2045 specifies that parameter names are case-insensitive, so
we normalize them here.
:param mail: :class:`email.message.Message`
:param failobj: object to return if no such header is found
:param header: the header to search for parameters, default
:par... | [
"Get",
"Content",
"-",
"Type",
"parameters",
"as",
"dict",
"."
] | python | train | 41.571429 |
niemasd/TreeSwift | treeswift/Tree.py | https://github.com/niemasd/TreeSwift/blob/7e0cbc770fcc2ee1194ef7c2a0ab9fb82f089917/treeswift/Tree.py#L1199-L1223 | def read_tree_dendropy(tree):
'''Create a TreeSwift tree from a DendroPy tree
Args:
``tree`` (``dendropy.datamodel.treemodel``): A Dendropy ``Tree`` object
Returns:
``Tree``: A TreeSwift tree created from ``tree``
'''
out = Tree(); d2t = dict()
if not hasattr(tree, 'preorder_no... | [
"def",
"read_tree_dendropy",
"(",
"tree",
")",
":",
"out",
"=",
"Tree",
"(",
")",
"d2t",
"=",
"dict",
"(",
")",
"if",
"not",
"hasattr",
"(",
"tree",
",",
"'preorder_node_iter'",
")",
"or",
"not",
"hasattr",
"(",
"tree",
",",
"'seed_node'",
")",
"or",
... | Create a TreeSwift tree from a DendroPy tree
Args:
``tree`` (``dendropy.datamodel.treemodel``): A Dendropy ``Tree`` object
Returns:
``Tree``: A TreeSwift tree created from ``tree`` | [
"Create",
"a",
"TreeSwift",
"tree",
"from",
"a",
"DendroPy",
"tree"
] | python | train | 36.56 |
ladybug-tools/ladybug | ladybug/datacollection.py | https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/datacollection.py#L618-L632 | def filter_by_conditional_statement(self, statement):
"""Filter the Data Collection based on a conditional statement.
Args:
statement: A conditional statement as a string (e.g. a > 25 and a%5 == 0).
The variable should always be named as 'a' (without quotations).
Re... | [
"def",
"filter_by_conditional_statement",
"(",
"self",
",",
"statement",
")",
":",
"_filt_values",
",",
"_filt_datetimes",
"=",
"self",
".",
"_filter_by_statement",
"(",
"statement",
")",
"collection",
"=",
"HourlyDiscontinuousCollection",
"(",
"self",
".",
"header",
... | Filter the Data Collection based on a conditional statement.
Args:
statement: A conditional statement as a string (e.g. a > 25 and a%5 == 0).
The variable should always be named as 'a' (without quotations).
Return:
A new Data Collection containing only the filte... | [
"Filter",
"the",
"Data",
"Collection",
"based",
"on",
"a",
"conditional",
"statement",
"."
] | python | train | 44 |
scidam/cachepy | crypter.py | https://github.com/scidam/cachepy/blob/680eeb7ff04ec9bb634b71cceb0841abaf2d530e/crypter.py#L45-L58 | def unpadding(s, bs=AES.block_size):
"""Reverse operation to padding (see above).
Parameters
==========
:param s: bytes-like object;
:param bs: encryption block size.
"""
if PY3:
return s[:s[-1] - 96] if len(s) % bs == 0 else ''
else:
return s[:ord(s[-1]) - 96]... | [
"def",
"unpadding",
"(",
"s",
",",
"bs",
"=",
"AES",
".",
"block_size",
")",
":",
"if",
"PY3",
":",
"return",
"s",
"[",
":",
"s",
"[",
"-",
"1",
"]",
"-",
"96",
"]",
"if",
"len",
"(",
"s",
")",
"%",
"bs",
"==",
"0",
"else",
"''",
"else",
... | Reverse operation to padding (see above).
Parameters
==========
:param s: bytes-like object;
:param bs: encryption block size. | [
"Reverse",
"operation",
"to",
"padding",
"(",
"see",
"above",
")",
"."
] | python | train | 23.928571 |
mfussenegger/cr8 | cr8/insert_json.py | https://github.com/mfussenegger/cr8/blob/a37d6049f1f9fee2d0556efae2b7b7f8761bffe8/cr8/insert_json.py#L54-L89 | def insert_json(table=None,
bulk_size=1000,
concurrency=25,
hosts=None,
output_fmt=None):
"""Insert JSON lines fed into stdin into a Crate cluster.
If no hosts are specified the statements will be printed.
Args:
table: Target table na... | [
"def",
"insert_json",
"(",
"table",
"=",
"None",
",",
"bulk_size",
"=",
"1000",
",",
"concurrency",
"=",
"25",
",",
"hosts",
"=",
"None",
",",
"output_fmt",
"=",
"None",
")",
":",
"if",
"not",
"hosts",
":",
"return",
"print_only",
"(",
"table",
")",
... | Insert JSON lines fed into stdin into a Crate cluster.
If no hosts are specified the statements will be printed.
Args:
table: Target table name.
bulk_size: Bulk size of the insert statements.
concurrency: Number of operations to run concurrently.
hosts: hostname:port pairs of t... | [
"Insert",
"JSON",
"lines",
"fed",
"into",
"stdin",
"into",
"a",
"Crate",
"cluster",
"."
] | python | train | 34.583333 |
edibledinos/pwnypack | pwnypack/codec.py | https://github.com/edibledinos/pwnypack/blob/e0a5a8e6ef3f4f1f7e1b91ee379711f4a49cb0e6/pwnypack/codec.py#L440-L458 | def caesar_app(parser, cmd, args): # pragma: no cover
"""
Caesar crypt a value with a key.
"""
parser.add_argument('shift', type=int, help='the shift to apply')
parser.add_argument('value', help='the value to caesar crypt, read from stdin if omitted', nargs='?')
parser.add_argument(
'-... | [
"def",
"caesar_app",
"(",
"parser",
",",
"cmd",
",",
"args",
")",
":",
"# pragma: no cover",
"parser",
".",
"add_argument",
"(",
"'shift'",
",",
"type",
"=",
"int",
",",
"help",
"=",
"'the shift to apply'",
")",
"parser",
".",
"add_argument",
"(",
"'value'",... | Caesar crypt a value with a key. | [
"Caesar",
"crypt",
"a",
"value",
"with",
"a",
"key",
"."
] | python | train | 34.789474 |
coleifer/walrus | walrus/database.py | https://github.com/coleifer/walrus/blob/82bf15a6613487b5b5fefeb488f186d7e0106547/walrus/database.py#L250-L257 | def rate_limit(self, name, limit=5, per=60, debug=False):
"""
Rate limit implementation. Allows up to `limit` of events every `per`
seconds.
See :ref:`rate-limit` for more information.
"""
return RateLimit(self, name, limit, per, debug) | [
"def",
"rate_limit",
"(",
"self",
",",
"name",
",",
"limit",
"=",
"5",
",",
"per",
"=",
"60",
",",
"debug",
"=",
"False",
")",
":",
"return",
"RateLimit",
"(",
"self",
",",
"name",
",",
"limit",
",",
"per",
",",
"debug",
")"
] | Rate limit implementation. Allows up to `limit` of events every `per`
seconds.
See :ref:`rate-limit` for more information. | [
"Rate",
"limit",
"implementation",
".",
"Allows",
"up",
"to",
"limit",
"of",
"events",
"every",
"per",
"seconds",
"."
] | python | train | 34.75 |
quantopian/zipline | zipline/pipeline/loaders/blaze/core.py | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/loaders/blaze/core.py#L337-L362 | def _check_resources(name, expr, resources):
"""Validate that the expression and resources passed match up.
Parameters
----------
name : str
The name of the argument we are checking.
expr : Expr
The potentially bound expr.
resources
The explicitly passed resources to com... | [
"def",
"_check_resources",
"(",
"name",
",",
"expr",
",",
"resources",
")",
":",
"if",
"expr",
"is",
"None",
":",
"return",
"bound",
"=",
"expr",
".",
"_resources",
"(",
")",
"if",
"not",
"bound",
"and",
"resources",
"is",
"None",
":",
"raise",
"ValueE... | Validate that the expression and resources passed match up.
Parameters
----------
name : str
The name of the argument we are checking.
expr : Expr
The potentially bound expr.
resources
The explicitly passed resources to compute expr.
Raises
------
ValueError
... | [
"Validate",
"that",
"the",
"expression",
"and",
"resources",
"passed",
"match",
"up",
"."
] | python | train | 27.923077 |
saltstack/salt | salt/runners/http.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/http.py#L48-L83 | def update_ca_bundle(target=None, source=None, merge_files=None):
'''
Update the local CA bundle file from a URL
.. versionadded:: 2015.5.0
CLI Example:
.. code-block:: bash
salt-run http.update_ca_bundle
salt-run http.update_ca_bundle target=/path/to/cacerts.pem
salt-run... | [
"def",
"update_ca_bundle",
"(",
"target",
"=",
"None",
",",
"source",
"=",
"None",
",",
"merge_files",
"=",
"None",
")",
":",
"return",
"salt",
".",
"utils",
".",
"http",
".",
"update_ca_bundle",
"(",
"target",
",",
"source",
",",
"__opts__",
",",
"merge... | Update the local CA bundle file from a URL
.. versionadded:: 2015.5.0
CLI Example:
.. code-block:: bash
salt-run http.update_ca_bundle
salt-run http.update_ca_bundle target=/path/to/cacerts.pem
salt-run http.update_ca_bundle source=https://example.com/cacerts.pem
If the ``ta... | [
"Update",
"the",
"local",
"CA",
"bundle",
"file",
"from",
"a",
"URL"
] | python | train | 35 |
chrisjsewell/jsonextended | jsonextended/ejson.py | https://github.com/chrisjsewell/jsonextended/blob/c3a7a880cc09789b3c61204265dcbb127be76c8a/jsonextended/ejson.py#L137-L211 | def jkeys(jfile, key_path=None, in_memory=True, ignore_prefix=('.', '_')):
""" get keys for initial json level, or at level after following key_path
Parameters
----------
jfile : str, file_like or path_like
if str, must be existing file or folder,
if file_like, must have 'read' method
... | [
"def",
"jkeys",
"(",
"jfile",
",",
"key_path",
"=",
"None",
",",
"in_memory",
"=",
"True",
",",
"ignore_prefix",
"=",
"(",
"'.'",
",",
"'_'",
")",
")",
":",
"key_path",
"=",
"[",
"]",
"if",
"key_path",
"is",
"None",
"else",
"key_path",
"def",
"eval_f... | get keys for initial json level, or at level after following key_path
Parameters
----------
jfile : str, file_like or path_like
if str, must be existing file or folder,
if file_like, must have 'read' method
if path_like, must have 'iterdir' method (see pathlib.Path)
key_path : l... | [
"get",
"keys",
"for",
"initial",
"json",
"level",
"or",
"at",
"level",
"after",
"following",
"key_path"
] | python | train | 30.92 |
joelfrederico/SciSalt | scisalt/PWFA/beam.py | https://github.com/joelfrederico/SciSalt/blob/7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f/scisalt/PWFA/beam.py#L196-L201 | def beta(self):
"""
Courant-Snyder parameter :math:`\\beta`.
"""
beta = _np.sqrt(self.sx)/self.emit
return beta | [
"def",
"beta",
"(",
"self",
")",
":",
"beta",
"=",
"_np",
".",
"sqrt",
"(",
"self",
".",
"sx",
")",
"/",
"self",
".",
"emit",
"return",
"beta"
] | Courant-Snyder parameter :math:`\\beta`. | [
"Courant",
"-",
"Snyder",
"parameter",
":",
"math",
":",
"\\\\",
"beta",
"."
] | python | valid | 24.333333 |
glottobank/python-newick | src/newick.py | https://github.com/glottobank/python-newick/blob/e8d4d1e4610f271d0f0e5cb86c0e0360b43bd702/src/newick.py#L386-L397 | def load(fp, strip_comments=False, **kw):
"""
Load a list of trees from an open Newick formatted file.
:param fp: open file handle.
:param strip_comments: Flag signaling whether to strip comments enclosed in square \
brackets.
:param kw: Keyword arguments are passed through to `Node.create`.
... | [
"def",
"load",
"(",
"fp",
",",
"strip_comments",
"=",
"False",
",",
"*",
"*",
"kw",
")",
":",
"kw",
"[",
"'strip_comments'",
"]",
"=",
"strip_comments",
"return",
"loads",
"(",
"fp",
".",
"read",
"(",
")",
",",
"*",
"*",
"kw",
")"
] | Load a list of trees from an open Newick formatted file.
:param fp: open file handle.
:param strip_comments: Flag signaling whether to strip comments enclosed in square \
brackets.
:param kw: Keyword arguments are passed through to `Node.create`.
:return: List of Node objects. | [
"Load",
"a",
"list",
"of",
"trees",
"from",
"an",
"open",
"Newick",
"formatted",
"file",
"."
] | python | test | 35.416667 |
HumanCellAtlas/dcp-cli | hca/upload/lib/api_client.py | https://github.com/HumanCellAtlas/dcp-cli/blob/cc70817bc4e50944c709eaae160de0bf7a19f0f3/hca/upload/lib/api_client.py#L214-L225 | def validation_statuses(self, area_uuid):
"""
Get count of validation statuses for all files in upload_area
:param str area_uuid: A RFC4122-compliant ID for the upload area
:return: a dict with key for each state and value being the count of files in that state
:rtype: dict
... | [
"def",
"validation_statuses",
"(",
"self",
",",
"area_uuid",
")",
":",
"path",
"=",
"\"/area/{uuid}/validations\"",
".",
"format",
"(",
"uuid",
"=",
"area_uuid",
")",
"result",
"=",
"self",
".",
"_make_request",
"(",
"'get'",
",",
"path",
")",
"return",
"res... | Get count of validation statuses for all files in upload_area
:param str area_uuid: A RFC4122-compliant ID for the upload area
:return: a dict with key for each state and value being the count of files in that state
:rtype: dict
:raises UploadApiException: if information could not be ob... | [
"Get",
"count",
"of",
"validation",
"statuses",
"for",
"all",
"files",
"in",
"upload_area"
] | python | train | 44.333333 |
user-cont/conu | conu/backend/nspawn/image.py | https://github.com/user-cont/conu/blob/08caae7bb6bdd265b55bb106c3da6a7946a5a352/conu/backend/nspawn/image.py#L256-L271 | def create_snapshot(self, name, tag):
"""
Create new instance of image with snaphot image (it is copied inside class constructuor)
:param name: str - name of image - not used now
:param tag: str - tag for image
:return: NspawnImage instance
"""
source = self.loca... | [
"def",
"create_snapshot",
"(",
"self",
",",
"name",
",",
"tag",
")",
":",
"source",
"=",
"self",
".",
"local_location",
"logger",
".",
"debug",
"(",
"\"Create Snapshot: %s -> %s\"",
"%",
"(",
"source",
",",
"name",
")",
")",
"# FIXME: actually create the snapsho... | Create new instance of image with snaphot image (it is copied inside class constructuor)
:param name: str - name of image - not used now
:param tag: str - tag for image
:return: NspawnImage instance | [
"Create",
"new",
"instance",
"of",
"image",
"with",
"snaphot",
"image",
"(",
"it",
"is",
"copied",
"inside",
"class",
"constructuor",
")"
] | python | train | 39.875 |
Iotic-Labs/py-IoticAgent | src/IoticAgent/IOT/Thing.py | https://github.com/Iotic-Labs/py-IoticAgent/blob/893e8582ad1dacfe32dfc0ee89452bbd6f57d28d/src/IoticAgent/IOT/Thing.py#L223-L251 | def list_tag(self, limit=500, offset=0):
"""List `all` the tags for this Thing
Returns lists of tags, as below
#!python
[
"mytag1",
"mytag2"
"ein_name",
"nochein_name"
]
- OR...
Raises... | [
"def",
"list_tag",
"(",
"self",
",",
"limit",
"=",
"500",
",",
"offset",
"=",
"0",
")",
":",
"evt",
"=",
"self",
".",
"_client",
".",
"_request_entity_tag_list",
"(",
"self",
".",
"__lid",
",",
"limit",
"=",
"limit",
",",
"offset",
"=",
"offset",
")"... | List `all` the tags for this Thing
Returns lists of tags, as below
#!python
[
"mytag1",
"mytag2"
"ein_name",
"nochein_name"
]
- OR...
Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.E... | [
"List",
"all",
"the",
"tags",
"for",
"this",
"Thing"
] | python | train | 32.689655 |
pytroll/pyspectral | rsr_convert_scripts/modis_rsr.py | https://github.com/pytroll/pyspectral/blob/fd296c0e0bdf5364fa180134a1292665d6bc50a3/rsr_convert_scripts/modis_rsr.py#L93-L102 | def _load(self):
"""Load the MODIS RSR data for the band requested"""
if self.is_sw or self.platform_name == 'EOS-Aqua':
scale = 0.001
else:
scale = 1.0
detector = read_modis_response(self.requested_band_filename, scale)
self.rsr = detector
if self... | [
"def",
"_load",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_sw",
"or",
"self",
".",
"platform_name",
"==",
"'EOS-Aqua'",
":",
"scale",
"=",
"0.001",
"else",
":",
"scale",
"=",
"1.0",
"detector",
"=",
"read_modis_response",
"(",
"self",
".",
"requested_... | Load the MODIS RSR data for the band requested | [
"Load",
"the",
"MODIS",
"RSR",
"data",
"for",
"the",
"band",
"requested"
] | python | train | 34.2 |
mitsei/dlkit | dlkit/handcar/repository/managers.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/handcar/repository/managers.py#L1984-L2007 | def get_asset_query_session(self, proxy):
"""Gets an asset query session.
arg proxy (osid.proxy.Proxy): a proxy
return: (osid.repository.AssetQuerySession) - an
AssetQuerySession
raise: OperationFailed - unable to complete request
raise: Unimplemented - sup... | [
"def",
"get_asset_query_session",
"(",
"self",
",",
"proxy",
")",
":",
"if",
"not",
"self",
".",
"supports_asset_query",
"(",
")",
":",
"raise",
"Unimplemented",
"(",
")",
"try",
":",
"from",
".",
"import",
"sessions",
"except",
"ImportError",
":",
"raise",
... | Gets an asset query session.
arg proxy (osid.proxy.Proxy): a proxy
return: (osid.repository.AssetQuerySession) - an
AssetQuerySession
raise: OperationFailed - unable to complete request
raise: Unimplemented - supports_asset_query() is false
compliance: opti... | [
"Gets",
"an",
"asset",
"query",
"session",
"."
] | python | train | 36.791667 |
bennylope/pygeocodio | geocodio/client.py | https://github.com/bennylope/pygeocodio/blob/4c33d3d34f6b63d4b8fe85fe571ae02b9f67d6c3/geocodio/client.py#L47-L63 | def error_response(response):
"""
Raises errors matching the response code
"""
if response.status_code >= 500:
raise exceptions.GeocodioServerError
elif response.status_code == 403:
raise exceptions.GeocodioAuthError
elif response.status_code == 422:
raise exceptions.Ge... | [
"def",
"error_response",
"(",
"response",
")",
":",
"if",
"response",
".",
"status_code",
">=",
"500",
":",
"raise",
"exceptions",
".",
"GeocodioServerError",
"elif",
"response",
".",
"status_code",
"==",
"403",
":",
"raise",
"exceptions",
".",
"GeocodioAuthErro... | Raises errors matching the response code | [
"Raises",
"errors",
"matching",
"the",
"response",
"code"
] | python | train | 28.352941 |
openid/JWTConnect-Python-CryptoJWT | src/cryptojwt/jws/rsa.py | https://github.com/openid/JWTConnect-Python-CryptoJWT/blob/8863cfbfe77ca885084870b234a66b55bd52930c/src/cryptojwt/jws/rsa.py#L14-L29 | def sign(self, msg, key):
"""
Create a signature over a message as defined in RFC7515 using an
RSA key
:param msg: the message.
:type msg: bytes
:returns: bytes, the signature of data.
:rtype: bytes
"""
if not isinstance(key, rsa.RSAPrivateKey):
... | [
"def",
"sign",
"(",
"self",
",",
"msg",
",",
"key",
")",
":",
"if",
"not",
"isinstance",
"(",
"key",
",",
"rsa",
".",
"RSAPrivateKey",
")",
":",
"raise",
"TypeError",
"(",
"\"The key must be an instance of rsa.RSAPrivateKey\"",
")",
"sig",
"=",
"key",
".",
... | Create a signature over a message as defined in RFC7515 using an
RSA key
:param msg: the message.
:type msg: bytes
:returns: bytes, the signature of data.
:rtype: bytes | [
"Create",
"a",
"signature",
"over",
"a",
"message",
"as",
"defined",
"in",
"RFC7515",
"using",
"an",
"RSA",
"key"
] | python | train | 29.5625 |
eyurtsev/FlowCytometryTools | FlowCytometryTools/core/transforms.py | https://github.com/eyurtsev/FlowCytometryTools/blob/4355632508b875273d68c7e2972c17668bcf7b40/FlowCytometryTools/core/transforms.py#L225-L255 | def hlog(x, b=500, r=_display_max, d=_l_mmax):
"""
Base 10 hyperlog transform.
Parameters
----------
x : num | num iterable
values to be transformed.
b : num
Parameter controling the location of the shift
from linear to log transformation.
r : num (default = 10**4)
... | [
"def",
"hlog",
"(",
"x",
",",
"b",
"=",
"500",
",",
"r",
"=",
"_display_max",
",",
"d",
"=",
"_l_mmax",
")",
":",
"hlog_fun",
"=",
"_make_hlog_numeric",
"(",
"b",
",",
"r",
",",
"d",
")",
"if",
"not",
"hasattr",
"(",
"x",
",",
"'__len__'",
")",
... | Base 10 hyperlog transform.
Parameters
----------
x : num | num iterable
values to be transformed.
b : num
Parameter controling the location of the shift
from linear to log transformation.
r : num (default = 10**4)
maximal transformed value.
d : num (default = lo... | [
"Base",
"10",
"hyperlog",
"transform",
"."
] | python | train | 25.741935 |
sdispater/orator | orator/orm/relations/belongs_to_many.py | https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/orm/relations/belongs_to_many.py#L805-L811 | def new_pivot(self, attributes=None, exists=False):
"""
Create a new pivot model instance.
"""
pivot = self._related.new_pivot(self._parent, attributes, self._table, exists)
return pivot.set_pivot_keys(self._foreign_key, self._other_key) | [
"def",
"new_pivot",
"(",
"self",
",",
"attributes",
"=",
"None",
",",
"exists",
"=",
"False",
")",
":",
"pivot",
"=",
"self",
".",
"_related",
".",
"new_pivot",
"(",
"self",
".",
"_parent",
",",
"attributes",
",",
"self",
".",
"_table",
",",
"exists",
... | Create a new pivot model instance. | [
"Create",
"a",
"new",
"pivot",
"model",
"instance",
"."
] | python | train | 38.857143 |
tomplus/kubernetes_asyncio | kubernetes_asyncio/client/api/core_v1_api.py | https://github.com/tomplus/kubernetes_asyncio/blob/f9ab15317ec921409714c7afef11aeb0f579985d/kubernetes_asyncio/client/api/core_v1_api.py#L10527-L10554 | def delete_namespaced_service(self, name, namespace, **kwargs): # noqa: E501
"""delete_namespaced_service # noqa: E501
delete a Service # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> t... | [
"def",
"delete_namespaced_service",
"(",
"self",
",",
"name",
",",
"namespace",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async_req'",
")",
":",
"return"... | delete_namespaced_service # noqa: E501
delete a Service # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.delete_namespaced_service(name, namespace, async_req=True)
>>> result... | [
"delete_namespaced_service",
"#",
"noqa",
":",
"E501"
] | python | train | 94.107143 |
roclark/sportsreference | sportsreference/nfl/boxscore.py | https://github.com/roclark/sportsreference/blob/ea0bae432be76450e137671d2998eb38f962dffd/sportsreference/nfl/boxscore.py#L91-L154 | def dataframe(self):
"""
Returns a ``pandas DataFrame`` containing all other relevant class
properties and values for the specified game.
"""
fields_to_include = {
'completed_passes': self.completed_passes,
'attempted_passes': self.attempted_passes,
... | [
"def",
"dataframe",
"(",
"self",
")",
":",
"fields_to_include",
"=",
"{",
"'completed_passes'",
":",
"self",
".",
"completed_passes",
",",
"'attempted_passes'",
":",
"self",
".",
"attempted_passes",
",",
"'passing_yards'",
":",
"self",
".",
"passing_yards",
",",
... | Returns a ``pandas DataFrame`` containing all other relevant class
properties and values for the specified game. | [
"Returns",
"a",
"pandas",
"DataFrame",
"containing",
"all",
"other",
"relevant",
"class",
"properties",
"and",
"values",
"for",
"the",
"specified",
"game",
"."
] | python | train | 51.5625 |
juju/charm-helpers | charmhelpers/contrib/openstack/ssh_migrations.py | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/ssh_migrations.py#L269-L297 | def ssh_compute_add(public_key, application_name, rid=None, unit=None,
user=None):
"""Add a compute nodes ssh details to local cache.
Collect various hostname variations and add the corresponding host keys to
the local known hosts file. Finally, add the supplied public key to the
au... | [
"def",
"ssh_compute_add",
"(",
"public_key",
",",
"application_name",
",",
"rid",
"=",
"None",
",",
"unit",
"=",
"None",
",",
"user",
"=",
"None",
")",
":",
"relation_data",
"=",
"relation_get",
"(",
"rid",
"=",
"rid",
",",
"unit",
"=",
"unit",
")",
"s... | Add a compute nodes ssh details to local cache.
Collect various hostname variations and add the corresponding host keys to
the local known hosts file. Finally, add the supplied public key to the
authorized_key file.
:param public_key: Public key.
:type public_key: str
:param application_name: ... | [
"Add",
"a",
"compute",
"nodes",
"ssh",
"details",
"to",
"local",
"cache",
"."
] | python | train | 40.793103 |
nfcpy/nfcpy | src/nfc/clf/rcs956.py | https://github.com/nfcpy/nfcpy/blob/6649146d1afdd5e82b2b6b1ea00aa58d50785117/src/nfc/clf/rcs956.py#L282-L320 | def listen_dep(self, target, timeout):
"""Listen *timeout* seconds to become initialized as a DEP Target.
The RC-S956 can be set to listen as a DEP Target for passive
communication mode. Target active communication mode is
disabled by the driver due to performance issues. It is also
... | [
"def",
"listen_dep",
"(",
"self",
",",
"target",
",",
"timeout",
")",
":",
"# The RCS956 internal state machine must be in Mode 0 before",
"# we enter the listen phase. Also the RFConfiguration command",
"# for setting the TO parameter won't work in any other mode.",
"self",
".",
"chip... | Listen *timeout* seconds to become initialized as a DEP Target.
The RC-S956 can be set to listen as a DEP Target for passive
communication mode. Target active communication mode is
disabled by the driver due to performance issues. It is also
not possible to fully control the ATR_RES res... | [
"Listen",
"*",
"timeout",
"*",
"seconds",
"to",
"become",
"initialized",
"as",
"a",
"DEP",
"Target",
"."
] | python | train | 50.384615 |
Kronuz/pyScss | scss/selector.py | https://github.com/Kronuz/pyScss/blob/fb32b317f6e2b4b4aad2b86a74844658ac4aa11e/scss/selector.py#L428-L459 | def substitute(self, target, replacement):
"""Return a list of selectors obtained by replacing the `target`
selector with `replacement`.
Herein lie the guts of the Sass @extend directive.
In general, for a selector ``a X b Y c``, a target ``X Y``, and a
replacement ``q Z``, ret... | [
"def",
"substitute",
"(",
"self",
",",
"target",
",",
"replacement",
")",
":",
"# Find the target in the parent selector, and split it into",
"# before/after",
"p_before",
",",
"p_extras",
",",
"p_after",
"=",
"self",
".",
"break_around",
"(",
"target",
".",
"simple_s... | Return a list of selectors obtained by replacing the `target`
selector with `replacement`.
Herein lie the guts of the Sass @extend directive.
In general, for a selector ``a X b Y c``, a target ``X Y``, and a
replacement ``q Z``, return the selectors ``a q X b Z c`` and ``q a X b
... | [
"Return",
"a",
"list",
"of",
"selectors",
"obtained",
"by",
"replacing",
"the",
"target",
"selector",
"with",
"replacement",
"."
] | python | train | 43.09375 |
saltstack/salt | salt/modules/kubernetesmod.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/kubernetesmod.py#L1148-L1196 | def create_configmap(
name,
namespace,
data,
source=None,
template=None,
saltenv='base',
**kwargs):
'''
Creates the kubernetes configmap as defined by the user.
CLI Examples::
salt 'minion1' kubernetes.create_configmap \
settings ... | [
"def",
"create_configmap",
"(",
"name",
",",
"namespace",
",",
"data",
",",
"source",
"=",
"None",
",",
"template",
"=",
"None",
",",
"saltenv",
"=",
"'base'",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"source",
":",
"data",
"=",
"__read_and_render_yaml_f... | Creates the kubernetes configmap as defined by the user.
CLI Examples::
salt 'minion1' kubernetes.create_configmap \
settings default '{"example.conf": "# example file"}'
salt 'minion2' kubernetes.create_configmap \
name=settings namespace=default data='{"example.conf": "#... | [
"Creates",
"the",
"kubernetes",
"configmap",
"as",
"defined",
"by",
"the",
"user",
"."
] | python | train | 27.734694 |
mdeous/fatbotslim | fatbotslim/irc/bot.py | https://github.com/mdeous/fatbotslim/blob/341595d24454a79caee23750eac271f9d0626c88/fatbotslim/irc/bot.py#L293-L299 | def enable_rights(self):
"""
Enables rights management provided by :class:`fatbotslim.handlers.RightsHandler`.
"""
if self.rights is None:
handler_instance = RightsHandler(self)
self.handlers.insert(len(self.default_handlers), handler_instance) | [
"def",
"enable_rights",
"(",
"self",
")",
":",
"if",
"self",
".",
"rights",
"is",
"None",
":",
"handler_instance",
"=",
"RightsHandler",
"(",
"self",
")",
"self",
".",
"handlers",
".",
"insert",
"(",
"len",
"(",
"self",
".",
"default_handlers",
")",
",",... | Enables rights management provided by :class:`fatbotslim.handlers.RightsHandler`. | [
"Enables",
"rights",
"management",
"provided",
"by",
":",
"class",
":",
"fatbotslim",
".",
"handlers",
".",
"RightsHandler",
"."
] | python | train | 42 |
davgeo/clear | clear/tvfile.py | https://github.com/davgeo/clear/blob/5ec85d27efd28afddfcd4c3f44df17f0115a77aa/clear/tvfile.py#L260-L281 | def GenerateNewFileName(self):
"""
Create new file name from show name, season number, episode number
and episode name in format ShowName.S<NUM>.E<NUM>.EpisodeName.
Returns
----------
string
New file name in format ShowName.S<NUM>.E<NUM>.EpisodeName.
"""
if self.showInfo.showN... | [
"def",
"GenerateNewFileName",
"(",
"self",
")",
":",
"if",
"self",
".",
"showInfo",
".",
"showName",
"is",
"not",
"None",
"and",
"self",
".",
"showInfo",
".",
"seasonNum",
"is",
"not",
"None",
"and",
"self",
".",
"showInfo",
".",
"episodeNum",
"is",
"not... | Create new file name from show name, season number, episode number
and episode name in format ShowName.S<NUM>.E<NUM>.EpisodeName.
Returns
----------
string
New file name in format ShowName.S<NUM>.E<NUM>.EpisodeName. | [
"Create",
"new",
"file",
"name",
"from",
"show",
"name",
"season",
"number",
"episode",
"number",
"and",
"episode",
"name",
"in",
"format",
"ShowName",
".",
"S<NUM",
">",
".",
"E<NUM",
">",
".",
"EpisodeName",
"."
] | python | train | 43.727273 |
s0md3v/Photon | plugins/find_subdomains.py | https://github.com/s0md3v/Photon/blob/6a29f2c9782ea9b3dc090db1774a259033600e39/plugins/find_subdomains.py#L7-L14 | def find_subdomains(domain):
"""Find subdomains according to the TLD."""
result = set()
response = get('https://findsubdomains.com/subdomains-of/' + domain).text
matches = findall(r'(?s)<div class="domains js-domain-name">(.*?)</div>', response)
for match in matches:
result.add(match.replace... | [
"def",
"find_subdomains",
"(",
"domain",
")",
":",
"result",
"=",
"set",
"(",
")",
"response",
"=",
"get",
"(",
"'https://findsubdomains.com/subdomains-of/'",
"+",
"domain",
")",
".",
"text",
"matches",
"=",
"findall",
"(",
"r'(?s)<div class=\"domains js-domain-name... | Find subdomains according to the TLD. | [
"Find",
"subdomains",
"according",
"to",
"the",
"TLD",
"."
] | python | train | 45.625 |
saltstack/salt | salt/modules/cron.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/cron.py#L748-L775 | def set_env(user, name, value=None):
'''
Set up an environment variable in the crontab.
CLI Example:
.. code-block:: bash
salt '*' cron.set_env root MAILTO user@example.com
'''
lst = list_tab(user)
for env in lst['env']:
if name == env['name']:
if value != env[... | [
"def",
"set_env",
"(",
"user",
",",
"name",
",",
"value",
"=",
"None",
")",
":",
"lst",
"=",
"list_tab",
"(",
"user",
")",
"for",
"env",
"in",
"lst",
"[",
"'env'",
"]",
":",
"if",
"name",
"==",
"env",
"[",
"'name'",
"]",
":",
"if",
"value",
"!=... | Set up an environment variable in the crontab.
CLI Example:
.. code-block:: bash
salt '*' cron.set_env root MAILTO user@example.com | [
"Set",
"up",
"an",
"environment",
"variable",
"in",
"the",
"crontab",
"."
] | python | train | 28 |
chovanecm/sacredboard | sacredboard/bootstrap.py | https://github.com/chovanecm/sacredboard/blob/47e1c99e3be3c1b099d3772bc077f5666020eb0b/sacredboard/bootstrap.py#L133-L158 | def add_mongo_config(app, simple_connection_string,
mongo_uri, collection_name):
"""
Configure the application to use MongoDB.
:param app: Flask application
:param simple_connection_string:
Expects host:port:database_name or database_name
Mutally_exc... | [
"def",
"add_mongo_config",
"(",
"app",
",",
"simple_connection_string",
",",
"mongo_uri",
",",
"collection_name",
")",
":",
"if",
"mongo_uri",
"!=",
"(",
"None",
",",
"None",
")",
":",
"add_mongo_config_with_uri",
"(",
"app",
",",
"mongo_uri",
"[",
"0",
"]",
... | Configure the application to use MongoDB.
:param app: Flask application
:param simple_connection_string:
Expects host:port:database_name or database_name
Mutally_exclusive with mongo_uri
:param mongo_uri: Expects mongodb://... as defined
in https://docs.mongo... | [
"Configure",
"the",
"application",
"to",
"use",
"MongoDB",
"."
] | python | train | 45.807692 |
Shopify/shopify_python_api | shopify/resources/refund.py | https://github.com/Shopify/shopify_python_api/blob/88d3ba332fb2cd331f87517a16f2c2d4296cee90/shopify/resources/refund.py#L10-L34 | def calculate(cls, order_id, shipping=None, refund_line_items=None):
"""
Calculates refund transactions based on line items and shipping.
When you want to create a refund, you should first use the calculate
endpoint to generate accurate refund transactions.
Args:
orde... | [
"def",
"calculate",
"(",
"cls",
",",
"order_id",
",",
"shipping",
"=",
"None",
",",
"refund_line_items",
"=",
"None",
")",
":",
"data",
"=",
"{",
"}",
"if",
"shipping",
":",
"data",
"[",
"'shipping'",
"]",
"=",
"shipping",
"data",
"[",
"'refund_line_item... | Calculates refund transactions based on line items and shipping.
When you want to create a refund, you should first use the calculate
endpoint to generate accurate refund transactions.
Args:
order_id: Order ID for which the Refund has to created.
shipping: Specify how much... | [
"Calculates",
"refund",
"transactions",
"based",
"on",
"line",
"items",
"and",
"shipping",
".",
"When",
"you",
"want",
"to",
"create",
"a",
"refund",
"you",
"should",
"first",
"use",
"the",
"calculate",
"endpoint",
"to",
"generate",
"accurate",
"refund",
"tran... | python | train | 38.32 |
elmotec/massedit | massedit.py | https://github.com/elmotec/massedit/blob/57e22787354896d63a8850312314b19aa0308906/massedit.py#L131-L143 | def import_module(module): # pylint: disable=R0201
"""Import module that are needed for the code expr to compile.
Argument:
module (str or list): module(s) to import.
"""
if isinstance(module, list):
all_modules = module
else:
all_modules = [m... | [
"def",
"import_module",
"(",
"module",
")",
":",
"# pylint: disable=R0201",
"if",
"isinstance",
"(",
"module",
",",
"list",
")",
":",
"all_modules",
"=",
"module",
"else",
":",
"all_modules",
"=",
"[",
"module",
"]",
"for",
"mod",
"in",
"all_modules",
":",
... | Import module that are needed for the code expr to compile.
Argument:
module (str or list): module(s) to import. | [
"Import",
"module",
"that",
"are",
"needed",
"for",
"the",
"code",
"expr",
"to",
"compile",
"."
] | python | train | 30.692308 |
PyconUK/ConferenceScheduler | src/conference_scheduler/lp_problem/utils.py | https://github.com/PyconUK/ConferenceScheduler/blob/fb139f0ef2eab5ac8f4919aa4994d94d4e040030/src/conference_scheduler/lp_problem/utils.py#L144-L149 | def _events_with_diff_tag(talk, tag_array):
"""
Return the indices of the events with no tag in common as tag
"""
event_categories = np.nonzero(tag_array[talk])[0]
return np.nonzero(sum(tag_array.transpose()[event_categories]) == 0)[0] | [
"def",
"_events_with_diff_tag",
"(",
"talk",
",",
"tag_array",
")",
":",
"event_categories",
"=",
"np",
".",
"nonzero",
"(",
"tag_array",
"[",
"talk",
"]",
")",
"[",
"0",
"]",
"return",
"np",
".",
"nonzero",
"(",
"sum",
"(",
"tag_array",
".",
"transpose"... | Return the indices of the events with no tag in common as tag | [
"Return",
"the",
"indices",
"of",
"the",
"events",
"with",
"no",
"tag",
"in",
"common",
"as",
"tag"
] | python | train | 41.666667 |
google/grr | appveyor/windows_templates/build_windows_templates.py | https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/appveyor/windows_templates/build_windows_templates.py#L294-L319 | def _CheckInstallSuccess(self):
"""Checks if the installer installed correctly."""
if not os.path.exists(self.install_path):
raise RuntimeError("Install failed, no files at: %s" % self.install_path)
try:
output = subprocess.check_output(["sc", "query", self.service_name])
service_running ... | [
"def",
"_CheckInstallSuccess",
"(",
"self",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"install_path",
")",
":",
"raise",
"RuntimeError",
"(",
"\"Install failed, no files at: %s\"",
"%",
"self",
".",
"install_path",
")",
"try",
... | Checks if the installer installed correctly. | [
"Checks",
"if",
"the",
"installer",
"installed",
"correctly",
"."
] | python | train | 35.807692 |
F483/btctxstore | btctxstore/api.py | https://github.com/F483/btctxstore/blob/5790ace3a3d4c9bcc759e7c931fc4a57d40b6c25/btctxstore/api.py#L225-L230 | def add_nulldata(self, rawtx, hexdata):
"""Writes <hexdata> as new nulldata output to <rawtx>."""
tx = deserialize.unsignedtx(rawtx)
nulldata_txout = deserialize.nulldata_txout(hexdata)
tx = control.add_nulldata_output(tx, nulldata_txout)
return serialize.tx(tx) | [
"def",
"add_nulldata",
"(",
"self",
",",
"rawtx",
",",
"hexdata",
")",
":",
"tx",
"=",
"deserialize",
".",
"unsignedtx",
"(",
"rawtx",
")",
"nulldata_txout",
"=",
"deserialize",
".",
"nulldata_txout",
"(",
"hexdata",
")",
"tx",
"=",
"control",
".",
"add_nu... | Writes <hexdata> as new nulldata output to <rawtx>. | [
"Writes",
"<hexdata",
">",
"as",
"new",
"nulldata",
"output",
"to",
"<rawtx",
">",
"."
] | python | train | 49.5 |
chaoss/grimoirelab-kingarthur | arthur/scheduler.py | https://github.com/chaoss/grimoirelab-kingarthur/blob/9d6a638bee68d5e5c511f045eeebf06340fd3252/arthur/scheduler.py#L369-L399 | def _build_job_arguments(task):
"""Build the set of arguments required for running a job"""
job_args = {}
job_args['qitems'] = Q_STORAGE_ITEMS
job_args['task_id'] = task.task_id
# Backend parameters
job_args['backend'] = task.backend
backend_args = copy.deepcopy... | [
"def",
"_build_job_arguments",
"(",
"task",
")",
":",
"job_args",
"=",
"{",
"}",
"job_args",
"[",
"'qitems'",
"]",
"=",
"Q_STORAGE_ITEMS",
"job_args",
"[",
"'task_id'",
"]",
"=",
"task",
".",
"task_id",
"# Backend parameters",
"job_args",
"[",
"'backend'",
"]"... | Build the set of arguments required for running a job | [
"Build",
"the",
"set",
"of",
"arguments",
"required",
"for",
"running",
"a",
"job"
] | python | test | 32.387097 |
google/grr | grr/server/grr_response_server/databases/mysql.py | https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/databases/mysql.py#L138-L146 | def _CheckDatabaseEncoding(cursor):
"""Enforces a sane UTF-8 encoding for the database."""
cur_character_set = _ReadVariable("character_set_database", cursor)
if cur_character_set != CHARACTER_SET:
raise EncodingEnforcementError(
"Require MySQL character_set_database of {}, got {}."
" To creat... | [
"def",
"_CheckDatabaseEncoding",
"(",
"cursor",
")",
":",
"cur_character_set",
"=",
"_ReadVariable",
"(",
"\"character_set_database\"",
",",
"cursor",
")",
"if",
"cur_character_set",
"!=",
"CHARACTER_SET",
":",
"raise",
"EncodingEnforcementError",
"(",
"\"Require MySQL ch... | Enforces a sane UTF-8 encoding for the database. | [
"Enforces",
"a",
"sane",
"UTF",
"-",
"8",
"encoding",
"for",
"the",
"database",
"."
] | python | train | 56 |
smarie/python-parsyfiles | parsyfiles/converting_core.py | https://github.com/smarie/python-parsyfiles/blob/344b37e1151e8d4e7c2ee49ae09d6568715ae64e/parsyfiles/converting_core.py#L695-L713 | def insert_conversion_steps_at_beginning(self, converters: List[Converter], inplace: bool = False):
"""
Utility method to insert converters at the beginning ofthis chain. If inplace is True, this object is modified
and None is returned. Otherwise, a copy is returned
:param converters: ... | [
"def",
"insert_conversion_steps_at_beginning",
"(",
"self",
",",
"converters",
":",
"List",
"[",
"Converter",
"]",
",",
"inplace",
":",
"bool",
"=",
"False",
")",
":",
"if",
"inplace",
":",
"for",
"converter",
"in",
"reversed",
"(",
"converters",
")",
":",
... | Utility method to insert converters at the beginning ofthis chain. If inplace is True, this object is modified
and None is returned. Otherwise, a copy is returned
:param converters: the list of converters to insert
:param inplace: boolean indicating whether to modify this object (True) or retu... | [
"Utility",
"method",
"to",
"insert",
"converters",
"at",
"the",
"beginning",
"ofthis",
"chain",
".",
"If",
"inplace",
"is",
"True",
"this",
"object",
"is",
"modified",
"and",
"None",
"is",
"returned",
".",
"Otherwise",
"a",
"copy",
"is",
"returned"
] | python | train | 48.789474 |
materialsproject/pymatgen | pymatgen/io/abinit/tasks.py | https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/io/abinit/tasks.py#L3270-L3286 | def inspect(self, **kwargs):
"""
Plot the SCF cycle results with matplotlib.
Returns
`matplotlib` figure, None if some error occurred.
"""
try:
scf_cycle = abiinspect.GroundStateScfCycle.from_file(self.output_file.path)
except IOError:
... | [
"def",
"inspect",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"scf_cycle",
"=",
"abiinspect",
".",
"GroundStateScfCycle",
".",
"from_file",
"(",
"self",
".",
"output_file",
".",
"path",
")",
"except",
"IOError",
":",
"return",
"None",
"if... | Plot the SCF cycle results with matplotlib.
Returns
`matplotlib` figure, None if some error occurred. | [
"Plot",
"the",
"SCF",
"cycle",
"results",
"with",
"matplotlib",
"."
] | python | train | 28.352941 |
thelabnyc/wagtail_blog | blog/wp_xml_parser.py | https://github.com/thelabnyc/wagtail_blog/blob/7e092c02d10ec427c9a2c4b5dcbe910d88c628cf/blog/wp_xml_parser.py#L181-L208 | def translate_wp_comment(self, e):
"""
<wp:comment>
<wp:comment_id>1234</wp:comment_id>
<wp:comment_author><![CDATA[John Doe]]></wp:comment_author>
<wp:comment_author_email><![CDATA[info@adsasd.com]]></wp:comment_author_email>
<wp:comment_author_url>http://myhomepage.com/</wp:c... | [
"def",
"translate_wp_comment",
"(",
"self",
",",
"e",
")",
":",
"comment_dict",
"=",
"{",
"}",
"comment_dict",
"[",
"'ID'",
"]",
"=",
"e",
".",
"find",
"(",
"'./{wp}comment_id'",
")",
".",
"text",
"comment_dict",
"[",
"'date'",
"]",
"=",
"e",
".",
"fin... | <wp:comment>
<wp:comment_id>1234</wp:comment_id>
<wp:comment_author><![CDATA[John Doe]]></wp:comment_author>
<wp:comment_author_email><![CDATA[info@adsasd.com]]></wp:comment_author_email>
<wp:comment_author_url>http://myhomepage.com/</wp:comment_author_url>
<wp:comment_author_IP><![CD... | [
"<wp",
":",
"comment",
">",
"<wp",
":",
"comment_id",
">",
"1234<",
"/",
"wp",
":",
"comment_id",
">",
"<wp",
":",
"comment_author",
">",
"<!",
"[",
"CDATA",
"[",
"John",
"Doe",
"]]",
">",
"<",
"/",
"wp",
":",
"comment_author",
">",
"<wp",
":",
"co... | python | train | 56.571429 |
odlgroup/odl | odl/tomo/backends/astra_cpu.py | https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/tomo/backends/astra_cpu.py#L118-L210 | def astra_cpu_back_projector(proj_data, geometry, reco_space, out=None):
"""Run an ASTRA back-projection on the given data using the CPU.
Parameters
----------
proj_data : `DiscreteLpElement`
Projection data to which the back-projector is applied
geometry : `Geometry`
Geometry defin... | [
"def",
"astra_cpu_back_projector",
"(",
"proj_data",
",",
"geometry",
",",
"reco_space",
",",
"out",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"proj_data",
",",
"DiscreteLpElement",
")",
":",
"raise",
"TypeError",
"(",
"'projection data {!r} is not a ... | Run an ASTRA back-projection on the given data using the CPU.
Parameters
----------
proj_data : `DiscreteLpElement`
Projection data to which the back-projector is applied
geometry : `Geometry`
Geometry defining the tomographic setup
reco_space : `DiscreteLp`
Space to which t... | [
"Run",
"an",
"ASTRA",
"back",
"-",
"projection",
"on",
"the",
"given",
"data",
"using",
"the",
"CPU",
"."
] | python | train | 40.505376 |
google/grr | grr/server/grr_response_server/databases/mysql_flows.py | https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/databases/mysql_flows.py#L69-L75 | def DeleteMessageHandlerRequests(self, requests, cursor=None):
"""Deletes a list of message handler requests from the database."""
query = "DELETE FROM message_handler_requests WHERE request_id IN ({})"
request_ids = set([r.request_id for r in requests])
query = query.format(",".join(["%s"] * len(reque... | [
"def",
"DeleteMessageHandlerRequests",
"(",
"self",
",",
"requests",
",",
"cursor",
"=",
"None",
")",
":",
"query",
"=",
"\"DELETE FROM message_handler_requests WHERE request_id IN ({})\"",
"request_ids",
"=",
"set",
"(",
"[",
"r",
".",
"request_id",
"for",
"r",
"in... | Deletes a list of message handler requests from the database. | [
"Deletes",
"a",
"list",
"of",
"message",
"handler",
"requests",
"from",
"the",
"database",
"."
] | python | train | 51.714286 |
mikedh/trimesh | trimesh/scene/scene.py | https://github.com/mikedh/trimesh/blob/25e059bf6d4caa74f62ffd58ce4f61a90ee4e518/trimesh/scene/scene.py#L528-L549 | def rezero(self):
"""
Move the current scene so that the AABB of the whole
scene is centered at the origin.
Does this by changing the base frame to a new, offset
base frame.
"""
if self.is_empty or np.allclose(self.centroid, 0.0):
# early exit since w... | [
"def",
"rezero",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_empty",
"or",
"np",
".",
"allclose",
"(",
"self",
".",
"centroid",
",",
"0.0",
")",
":",
"# early exit since what we want already exists",
"return",
"# the transformation to move the overall scene to AABB ... | Move the current scene so that the AABB of the whole
scene is centered at the origin.
Does this by changing the base frame to a new, offset
base frame. | [
"Move",
"the",
"current",
"scene",
"so",
"that",
"the",
"AABB",
"of",
"the",
"whole",
"scene",
"is",
"centered",
"at",
"the",
"origin",
"."
] | python | train | 35.090909 |
inveniosoftware/invenio-oaiserver | invenio_oaiserver/models.py | https://github.com/inveniosoftware/invenio-oaiserver/blob/eae765e32bd816ddc5612d4b281caf205518b512/invenio_oaiserver/models.py#L79-L89 | def add_record(self, record):
"""Add a record to the OAISet.
:param record: Record to be added.
:type record: `invenio_records.api.Record` or derivative.
"""
record.setdefault('_oai', {}).setdefault('sets', [])
assert not self.has_record(record)
record['_oai'][... | [
"def",
"add_record",
"(",
"self",
",",
"record",
")",
":",
"record",
".",
"setdefault",
"(",
"'_oai'",
",",
"{",
"}",
")",
".",
"setdefault",
"(",
"'sets'",
",",
"[",
"]",
")",
"assert",
"not",
"self",
".",
"has_record",
"(",
"record",
")",
"record",... | Add a record to the OAISet.
:param record: Record to be added.
:type record: `invenio_records.api.Record` or derivative. | [
"Add",
"a",
"record",
"to",
"the",
"OAISet",
"."
] | python | train | 30.454545 |
materialsproject/pymatgen | pymatgen/io/abinit/nodes.py | https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/io/abinit/nodes.py#L1265-L1271 | def save_lastnode_id():
"""Save the id of the last node created."""
init_counter()
with FileLock(_COUNTER_FILE):
with AtomicFile(_COUNTER_FILE, mode="w") as fh:
fh.write("%d\n" % _COUNTER) | [
"def",
"save_lastnode_id",
"(",
")",
":",
"init_counter",
"(",
")",
"with",
"FileLock",
"(",
"_COUNTER_FILE",
")",
":",
"with",
"AtomicFile",
"(",
"_COUNTER_FILE",
",",
"mode",
"=",
"\"w\"",
")",
"as",
"fh",
":",
"fh",
".",
"write",
"(",
"\"%d\\n\"",
"%"... | Save the id of the last node created. | [
"Save",
"the",
"id",
"of",
"the",
"last",
"node",
"created",
"."
] | python | train | 30.714286 |
datadesk/django-bakery | bakery/management/commands/publish.py | https://github.com/datadesk/django-bakery/blob/e2feb13a66552a388fbcfaaacdd504bba08d3c69/bakery/management/commands/publish.py#L175-L242 | def set_options(self, options):
"""
Configure all the many options we'll need to make this happen.
"""
self.verbosity = int(options.get('verbosity'))
# Will we be gzipping?
self.gzip = getattr(settings, 'BAKERY_GZIP', False)
# And if so what content types will w... | [
"def",
"set_options",
"(",
"self",
",",
"options",
")",
":",
"self",
".",
"verbosity",
"=",
"int",
"(",
"options",
".",
"get",
"(",
"'verbosity'",
")",
")",
"# Will we be gzipping?",
"self",
".",
"gzip",
"=",
"getattr",
"(",
"settings",
",",
"'BAKERY_GZIP'... | Configure all the many options we'll need to make this happen. | [
"Configure",
"all",
"the",
"many",
"options",
"we",
"ll",
"need",
"to",
"make",
"this",
"happen",
"."
] | python | train | 37.529412 |
pyapi-gitlab/pyapi-gitlab | gitlab/__init__.py | https://github.com/pyapi-gitlab/pyapi-gitlab/blob/f74b6fb5c13cecae9524997847e928905cc60acf/gitlab/__init__.py#L672-L687 | def createfork(self, project_id):
"""
Forks a project into the user namespace of the authenticated user.
:param project_id: Project ID to fork
:return: True if succeed
"""
request = requests.post(
'{0}/fork/{1}'.format(self.projects_url, project_id),
... | [
"def",
"createfork",
"(",
"self",
",",
"project_id",
")",
":",
"request",
"=",
"requests",
".",
"post",
"(",
"'{0}/fork/{1}'",
".",
"format",
"(",
"self",
".",
"projects_url",
",",
"project_id",
")",
",",
"timeout",
"=",
"self",
".",
"timeout",
",",
"ver... | Forks a project into the user namespace of the authenticated user.
:param project_id: Project ID to fork
:return: True if succeed | [
"Forks",
"a",
"project",
"into",
"the",
"user",
"namespace",
"of",
"the",
"authenticated",
"user",
"."
] | python | train | 28.625 |
horazont/aioxmpp | aioxmpp/stringprep.py | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/stringprep.py#L55-L70 | def check_against_tables(chars, tables):
"""
Perform a check against the table predicates in `tables`. `tables` must be
a reusable iterable containing characteristic functions of character sets,
that is, functions which return :data:`True` if the character is in the
table.
The function returns ... | [
"def",
"check_against_tables",
"(",
"chars",
",",
"tables",
")",
":",
"for",
"c",
"in",
"chars",
":",
"if",
"any",
"(",
"in_table",
"(",
"c",
")",
"for",
"in_table",
"in",
"tables",
")",
":",
"return",
"c",
"return",
"None"
] | Perform a check against the table predicates in `tables`. `tables` must be
a reusable iterable containing characteristic functions of character sets,
that is, functions which return :data:`True` if the character is in the
table.
The function returns the first character occuring in any of the tables or
... | [
"Perform",
"a",
"check",
"against",
"the",
"table",
"predicates",
"in",
"tables",
".",
"tables",
"must",
"be",
"a",
"reusable",
"iterable",
"containing",
"characteristic",
"functions",
"of",
"character",
"sets",
"that",
"is",
"functions",
"which",
"return",
":",... | python | train | 32.375 |
RiotGames/cloud-inquisitor | backend/cloud_inquisitor/config.py | https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/backend/cloud_inquisitor/config.py#L121-L186 | def set(self, namespace, key, value, description=None):
"""Set (create/update) a configuration item
Args:
namespace (`str`): Namespace for the item
key (`str`): Key of the item
value (`Any`): Value of the type, must by one of `DBCString`, `DBCFloat`, `DBCInt`, `DBCAr... | [
"def",
"set",
"(",
"self",
",",
"namespace",
",",
"key",
",",
"value",
",",
"description",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"DBCChoice",
")",
":",
"vtype",
"=",
"'choice'",
"elif",
"isinstance",
"(",
"value",
",",
"DBCStrin... | Set (create/update) a configuration item
Args:
namespace (`str`): Namespace for the item
key (`str`): Key of the item
value (`Any`): Value of the type, must by one of `DBCString`, `DBCFloat`, `DBCInt`, `DBCArray`, `DBCJSON` or
`bool`
description (`str... | [
"Set",
"(",
"create",
"/",
"update",
")",
"a",
"configuration",
"item"
] | python | train | 27.863636 |
RiotGames/cloud-inquisitor | backend/cloud_inquisitor/plugins/commands/scheduler.py | https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/backend/cloud_inquisitor/plugins/commands/scheduler.py#L59-L79 | def run(self, **kwargs):
"""Execute the scheduler.
Returns:
`None`
"""
if not super().run(**kwargs):
return
if kwargs['list']:
self.log.info('--- List of Scheduler Modules ---')
for name, scheduler in list(self.scheduler_plugins.i... | [
"def",
"run",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"super",
"(",
")",
".",
"run",
"(",
"*",
"*",
"kwargs",
")",
":",
"return",
"if",
"kwargs",
"[",
"'list'",
"]",
":",
"self",
".",
"log",
".",
"info",
"(",
"'--- List of ... | Execute the scheduler.
Returns:
`None` | [
"Execute",
"the",
"scheduler",
"."
] | python | train | 32.142857 |
wmayner/pyphi | pyphi/subsystem.py | https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/subsystem.py#L614-L621 | def phi_cause_mip(self, mechanism, purview):
"""Return the |small_phi| of the cause MIP.
This is the distance between the unpartitioned cause repertoire and the
MIP cause repertoire.
"""
mip = self.cause_mip(mechanism, purview)
return mip.phi if mip else 0 | [
"def",
"phi_cause_mip",
"(",
"self",
",",
"mechanism",
",",
"purview",
")",
":",
"mip",
"=",
"self",
".",
"cause_mip",
"(",
"mechanism",
",",
"purview",
")",
"return",
"mip",
".",
"phi",
"if",
"mip",
"else",
"0"
] | Return the |small_phi| of the cause MIP.
This is the distance between the unpartitioned cause repertoire and the
MIP cause repertoire. | [
"Return",
"the",
"|small_phi|",
"of",
"the",
"cause",
"MIP",
"."
] | python | train | 37.25 |
spyder-ide/spyder | spyder/utils/qthelpers.py | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/qthelpers.py#L216-L225 | def action2button(action, autoraise=True, text_beside_icon=False, parent=None):
"""Create a QToolButton directly from a QAction object"""
if parent is None:
parent = action.parent()
button = QToolButton(parent)
button.setDefaultAction(action)
button.setAutoRaise(autoraise)
if text... | [
"def",
"action2button",
"(",
"action",
",",
"autoraise",
"=",
"True",
",",
"text_beside_icon",
"=",
"False",
",",
"parent",
"=",
"None",
")",
":",
"if",
"parent",
"is",
"None",
":",
"parent",
"=",
"action",
".",
"parent",
"(",
")",
"button",
"=",
"QToo... | Create a QToolButton directly from a QAction object | [
"Create",
"a",
"QToolButton",
"directly",
"from",
"a",
"QAction",
"object"
] | python | train | 40.7 |
TeamHG-Memex/eli5 | eli5/_feature_names.py | https://github.com/TeamHG-Memex/eli5/blob/371b402a0676295c05e582a2dd591f7af476b86b/eli5/_feature_names.py#L161-L179 | def add_feature(self, feature):
# type: (Any) -> int
""" Add a new feature name, return it's index.
"""
# A copy of self.feature_names is always made, because it might be
# "owned" by someone else.
# It's possible to make the copy only at the first call to
# self.... | [
"def",
"add_feature",
"(",
"self",
",",
"feature",
")",
":",
"# type: (Any) -> int",
"# A copy of self.feature_names is always made, because it might be",
"# \"owned\" by someone else.",
"# It's possible to make the copy only at the first call to",
"# self.add_feature to improve performance.... | Add a new feature name, return it's index. | [
"Add",
"a",
"new",
"feature",
"name",
"return",
"it",
"s",
"index",
"."
] | python | train | 43.526316 |
bitesofcode/projexui | projexui/widgets/xviewwidget/xviewwidget.py | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xviewwidget/xviewwidget.py#L179-L202 | def exportProfile(self, filename=''):
"""
Exports the current profile to a file.
:param filename | <str>
"""
if not (filename and isinstance(filename, basestring)):
filename = QtGui.QFileDialog.getSaveFileName(self,
... | [
"def",
"exportProfile",
"(",
"self",
",",
"filename",
"=",
"''",
")",
":",
"if",
"not",
"(",
"filename",
"and",
"isinstance",
"(",
"filename",
",",
"basestring",
")",
")",
":",
"filename",
"=",
"QtGui",
".",
"QFileDialog",
".",
"getSaveFileName",
"(",
"s... | Exports the current profile to a file.
:param filename | <str> | [
"Exports",
"the",
"current",
"profile",
"to",
"a",
"file",
".",
":",
"param",
"filename",
"|",
"<str",
">"
] | python | train | 35.333333 |
mikeboers/MultiMap | multimap.py | https://github.com/mikeboers/MultiMap/blob/0251e5d5df693cc247b4ac5b95adfdd10e3bec04/multimap.py#L379-L397 | def _remove_pairs(self, ids_to_remove):
"""Remove the pairs identified by the given indices into _pairs.
Removes the pair, and updates the _key_ids mapping to be accurate.
Removing the ids from the _key_ids is your own responsibility.
Params:
ids_to_remove -... | [
"def",
"_remove_pairs",
"(",
"self",
",",
"ids_to_remove",
")",
":",
"# Remove them.",
"for",
"i",
"in",
"reversed",
"(",
"ids_to_remove",
")",
":",
"del",
"self",
".",
"_pairs",
"[",
"i",
"]",
"# We use the bisect to tell us how many spots the given index is",
"# s... | Remove the pairs identified by the given indices into _pairs.
Removes the pair, and updates the _key_ids mapping to be accurate.
Removing the ids from the _key_ids is your own responsibility.
Params:
ids_to_remove -- The indices to remove. MUST be sorted. | [
"Remove",
"the",
"pairs",
"identified",
"by",
"the",
"given",
"indices",
"into",
"_pairs",
".",
"Removes",
"the",
"pair",
"and",
"updates",
"the",
"_key_ids",
"mapping",
"to",
"be",
"accurate",
".",
"Removing",
"the",
"ids",
"from",
"the",
"_key_ids",
"is",
... | python | train | 37.684211 |
spyder-ide/spyder | spyder/plugins/variableexplorer/widgets/namespacebrowser.py | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/namespacebrowser.py#L266-L270 | def set_data(self, data):
"""Set data."""
if data != self.editor.model.get_data():
self.editor.set_data(data)
self.editor.adjust_columns() | [
"def",
"set_data",
"(",
"self",
",",
"data",
")",
":",
"if",
"data",
"!=",
"self",
".",
"editor",
".",
"model",
".",
"get_data",
"(",
")",
":",
"self",
".",
"editor",
".",
"set_data",
"(",
"data",
")",
"self",
".",
"editor",
".",
"adjust_columns",
... | Set data. | [
"Set",
"data",
"."
] | python | train | 35.6 |
googledatalab/pydatalab | datalab/stackdriver/commands/_monitoring.py | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/stackdriver/commands/_monitoring.py#L85-L91 | def _list_resource_descriptors(args, _):
"""Lists the resource descriptors in the project."""
project_id = args['project']
pattern = args['type'] or '*'
descriptors = gcm.ResourceDescriptors(project_id=project_id)
dataframe = descriptors.as_dataframe(pattern=pattern)
return _render_dataframe(dataframe) | [
"def",
"_list_resource_descriptors",
"(",
"args",
",",
"_",
")",
":",
"project_id",
"=",
"args",
"[",
"'project'",
"]",
"pattern",
"=",
"args",
"[",
"'type'",
"]",
"or",
"'*'",
"descriptors",
"=",
"gcm",
".",
"ResourceDescriptors",
"(",
"project_id",
"=",
... | Lists the resource descriptors in the project. | [
"Lists",
"the",
"resource",
"descriptors",
"in",
"the",
"project",
"."
] | python | train | 44.142857 |
SheffieldML/GPy | GPy/likelihoods/likelihood.py | https://github.com/SheffieldML/GPy/blob/54c32d79d289d622fb18b898aee65a2a431d90cf/GPy/likelihoods/likelihood.py#L128-L194 | def log_predictive_density(self, y_test, mu_star, var_star, Y_metadata=None):
"""
Calculation of the log predictive density
.. math:
p(y_{*}|D) = p(y_{*}|f_{*})p(f_{*}|\mu_{*}\\sigma^{2}_{*})
:param y_test: test observations (y_{*})
:type y_test: (Nx1) array
... | [
"def",
"log_predictive_density",
"(",
"self",
",",
"y_test",
",",
"mu_star",
",",
"var_star",
",",
"Y_metadata",
"=",
"None",
")",
":",
"assert",
"y_test",
".",
"shape",
"==",
"mu_star",
".",
"shape",
"assert",
"y_test",
".",
"shape",
"==",
"var_star",
"."... | Calculation of the log predictive density
.. math:
p(y_{*}|D) = p(y_{*}|f_{*})p(f_{*}|\mu_{*}\\sigma^{2}_{*})
:param y_test: test observations (y_{*})
:type y_test: (Nx1) array
:param mu_star: predictive mean of gaussian p(f_{*}|mu_{*}, var_{*})
:type mu_star: (Nx1)... | [
"Calculation",
"of",
"the",
"log",
"predictive",
"density"
] | python | train | 40.731343 |
cloudify-cosmo/repex | repex.py | https://github.com/cloudify-cosmo/repex/blob/589e442857fa4a99fa88670d7df1a72f983bbd28/repex.py#L72-L83 | def _import_yaml(config_file_path):
"""Return a configuration object
"""
try:
logger.info('Importing config %s...', config_file_path)
with open(config_file_path) as config_file:
return yaml.safe_load(config_file.read())
except IOError as ex:
raise RepexError('{0}: {1}... | [
"def",
"_import_yaml",
"(",
"config_file_path",
")",
":",
"try",
":",
"logger",
".",
"info",
"(",
"'Importing config %s...'",
",",
"config_file_path",
")",
"with",
"open",
"(",
"config_file_path",
")",
"as",
"config_file",
":",
"return",
"yaml",
".",
"safe_load"... | Return a configuration object | [
"Return",
"a",
"configuration",
"object"
] | python | train | 44.666667 |
broadinstitute/fiss | firecloud/supervisor.py | https://github.com/broadinstitute/fiss/blob/dddf91547479506dbbafb69ec84d44dcc4a94ab4/firecloud/supervisor.py#L12-L39 | def supervise(project, workspace, namespace, workflow,
sample_sets, recovery_file):
""" Supervise submission of jobs from a Firehose-style workflow of workflows"""
# Get arguments
logging.info("Initializing FireCloud Supervisor...")
logging.info("Saving recovery checkpoints to " + recover... | [
"def",
"supervise",
"(",
"project",
",",
"workspace",
",",
"namespace",
",",
"workflow",
",",
"sample_sets",
",",
"recovery_file",
")",
":",
"# Get arguments",
"logging",
".",
"info",
"(",
"\"Initializing FireCloud Supervisor...\"",
")",
"logging",
".",
"info",
"(... | Supervise submission of jobs from a Firehose-style workflow of workflows | [
"Supervise",
"submission",
"of",
"jobs",
"from",
"a",
"Firehose",
"-",
"style",
"workflow",
"of",
"workflows"
] | python | train | 33.607143 |
bsolomon1124/pyfinance | pyfinance/ols.py | https://github.com/bsolomon1124/pyfinance/blob/c95925209a809b4e648e79cbeaf7711d8e5ff1a6/pyfinance/ols.py#L44-L47 | def _confirm_constant(a):
"""Confirm `a` has volumn vector of 1s."""
a = np.asanyarray(a)
return np.isclose(a, 1.0).all(axis=0).any() | [
"def",
"_confirm_constant",
"(",
"a",
")",
":",
"a",
"=",
"np",
".",
"asanyarray",
"(",
"a",
")",
"return",
"np",
".",
"isclose",
"(",
"a",
",",
"1.0",
")",
".",
"all",
"(",
"axis",
"=",
"0",
")",
".",
"any",
"(",
")"
] | Confirm `a` has volumn vector of 1s. | [
"Confirm",
"a",
"has",
"volumn",
"vector",
"of",
"1s",
"."
] | python | train | 36.25 |
rigetti/quantumflow | quantumflow/circuits.py | https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/circuits.py#L359-L369 | def ghz_circuit(qubits: Qubits) -> Circuit:
"""Returns a circuit that prepares a multi-qubit Bell state from the zero
state.
"""
circ = Circuit()
circ += H(qubits[0])
for q0 in range(0, len(qubits)-1):
circ += CNOT(qubits[q0], qubits[q0+1])
return circ | [
"def",
"ghz_circuit",
"(",
"qubits",
":",
"Qubits",
")",
"->",
"Circuit",
":",
"circ",
"=",
"Circuit",
"(",
")",
"circ",
"+=",
"H",
"(",
"qubits",
"[",
"0",
"]",
")",
"for",
"q0",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"qubits",
")",
"-",
"1... | Returns a circuit that prepares a multi-qubit Bell state from the zero
state. | [
"Returns",
"a",
"circuit",
"that",
"prepares",
"a",
"multi",
"-",
"qubit",
"Bell",
"state",
"from",
"the",
"zero",
"state",
"."
] | python | train | 25.454545 |
MIT-LCP/wfdb-python | wfdb/io/annotation.py | https://github.com/MIT-LCP/wfdb-python/blob/cc8c9e9e44f10af961b7a9d8ae03708b31ac8a8c/wfdb/io/annotation.py#L1428-L1468 | def proc_extra_field(label_store, filebytes, bpi, subtype, chan, num, aux_note, update):
"""
Process extra fields belonging to the current annotation.
Potential updated fields: subtype, chan, num, aux_note
"""
# aux_note and sub are reset between annotations. chan and num copy over
# previous v... | [
"def",
"proc_extra_field",
"(",
"label_store",
",",
"filebytes",
",",
"bpi",
",",
"subtype",
",",
"chan",
",",
"num",
",",
"aux_note",
",",
"update",
")",
":",
"# aux_note and sub are reset between annotations. chan and num copy over",
"# previous value if missing.",
"# S... | Process extra fields belonging to the current annotation.
Potential updated fields: subtype, chan, num, aux_note | [
"Process",
"extra",
"fields",
"belonging",
"to",
"the",
"current",
"annotation",
".",
"Potential",
"updated",
"fields",
":",
"subtype",
"chan",
"num",
"aux_note"
] | python | train | 35.439024 |
totalgood/nlpia | src/nlpia/gensim_utils.py | https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/gensim_utils.py#L134-L146 | def get_texts(self):
""" Parse documents from a .txt file assuming 1 document per line, yielding lists of filtered tokens """
with self.getstream() as text_stream:
for i, line in enumerate(text_stream):
line = SMSCorpus.case_normalizer(line)
if self.mask is no... | [
"def",
"get_texts",
"(",
"self",
")",
":",
"with",
"self",
".",
"getstream",
"(",
")",
"as",
"text_stream",
":",
"for",
"i",
",",
"line",
"in",
"enumerate",
"(",
"text_stream",
")",
":",
"line",
"=",
"SMSCorpus",
".",
"case_normalizer",
"(",
"line",
")... | Parse documents from a .txt file assuming 1 document per line, yielding lists of filtered tokens | [
"Parse",
"documents",
"from",
"a",
".",
"txt",
"file",
"assuming",
"1",
"document",
"per",
"line",
"yielding",
"lists",
"of",
"filtered",
"tokens"
] | python | train | 46.615385 |
saulpw/visidata | visidata/clipboard.py | https://github.com/saulpw/visidata/blob/32771e0cea6c24fc7902683d14558391395c591f/visidata/clipboard.py#L79-L90 | def copy(self, value):
'Copy a cell to the system clipboard.'
with tempfile.NamedTemporaryFile() as temp:
with open(temp.name, 'w', encoding=options.encoding) as fp:
fp.write(str(value))
p = subprocess.Popen(
self.command,
stdin=o... | [
"def",
"copy",
"(",
"self",
",",
"value",
")",
":",
"with",
"tempfile",
".",
"NamedTemporaryFile",
"(",
")",
"as",
"temp",
":",
"with",
"open",
"(",
"temp",
".",
"name",
",",
"'w'",
",",
"encoding",
"=",
"options",
".",
"encoding",
")",
"as",
"fp",
... | Copy a cell to the system clipboard. | [
"Copy",
"a",
"cell",
"to",
"the",
"system",
"clipboard",
"."
] | python | train | 35.583333 |
sryza/spark-timeseries | python/sparkts/models/RegressionARIMA.py | https://github.com/sryza/spark-timeseries/blob/280aa887dc08ab114411245268f230fdabb76eec/python/sparkts/models/RegressionARIMA.py#L20-L42 | def fit_model(ts, regressors, method="cochrane-orcutt", optimizationArgs=None, sc=None):
"""
Parameters
----------
ts:
time series to which to fit an ARIMA model as a Numpy array
regressors:
regression matrix as a Numpy array
method:
Regression method. Currently, only "co... | [
"def",
"fit_model",
"(",
"ts",
",",
"regressors",
",",
"method",
"=",
"\"cochrane-orcutt\"",
",",
"optimizationArgs",
"=",
"None",
",",
"sc",
"=",
"None",
")",
":",
"assert",
"sc",
"!=",
"None",
",",
"\"Missing SparkContext\"",
"jvm",
"=",
"sc",
".",
"_jvm... | Parameters
----------
ts:
time series to which to fit an ARIMA model as a Numpy array
regressors:
regression matrix as a Numpy array
method:
Regression method. Currently, only "cochrane-orcutt" is supported.
optimizationArgs:
sc:
The SparkContext, require... | [
"Parameters",
"----------",
"ts",
":",
"time",
"series",
"to",
"which",
"to",
"fit",
"an",
"ARIMA",
"model",
"as",
"a",
"Numpy",
"array",
"regressors",
":",
"regression",
"matrix",
"as",
"a",
"Numpy",
"array",
"method",
":",
"Regression",
"method",
".",
"C... | python | train | 33.173913 |
yvesalexandre/bandicoot | bandicoot/helper/maths.py | https://github.com/yvesalexandre/bandicoot/blob/73a658f6f17331541cf0b1547028db9b70e8d58a/bandicoot/helper/maths.py#L206-L217 | def entropy(data):
"""
Compute the Shannon entropy, a measure of uncertainty.
"""
if len(data) == 0:
return None
n = sum(data)
_op = lambda f: f * math.log(f)
return - sum(_op(float(i) / n) for i in data) | [
"def",
"entropy",
"(",
"data",
")",
":",
"if",
"len",
"(",
"data",
")",
"==",
"0",
":",
"return",
"None",
"n",
"=",
"sum",
"(",
"data",
")",
"_op",
"=",
"lambda",
"f",
":",
"f",
"*",
"math",
".",
"log",
"(",
"f",
")",
"return",
"-",
"sum",
... | Compute the Shannon entropy, a measure of uncertainty. | [
"Compute",
"the",
"Shannon",
"entropy",
"a",
"measure",
"of",
"uncertainty",
"."
] | python | train | 19.333333 |
saltstack/salt | salt/modules/pagerduty.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/pagerduty.py#L37-L51 | def list_services(profile=None, api_key=None):
'''
List services belonging to this account
CLI Example:
salt myminion pagerduty.list_services my-pagerduty-account
'''
return salt.utils.pagerduty.list_items(
'services',
'name',
__salt__['config.option'](profile),
... | [
"def",
"list_services",
"(",
"profile",
"=",
"None",
",",
"api_key",
"=",
"None",
")",
":",
"return",
"salt",
".",
"utils",
".",
"pagerduty",
".",
"list_items",
"(",
"'services'",
",",
"'name'",
",",
"__salt__",
"[",
"'config.option'",
"]",
"(",
"profile",... | List services belonging to this account
CLI Example:
salt myminion pagerduty.list_services my-pagerduty-account | [
"List",
"services",
"belonging",
"to",
"this",
"account"
] | python | train | 23.133333 |
ronaldguillen/wave | wave/relations.py | https://github.com/ronaldguillen/wave/blob/20bb979c917f7634d8257992e6d449dc751256a9/wave/relations.py#L88-L108 | def many_init(cls, *args, **kwargs):
"""
This method handles creating a parent `ManyRelatedField` instance
when the `many=True` keyword argument is passed.
Typically you won't need to override this method.
Note that we're over-cautious in passing most arguments to both parent
... | [
"def",
"many_init",
"(",
"cls",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"list_kwargs",
"=",
"{",
"'child_relation'",
":",
"cls",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"}",
"for",
"key",
"in",
"kwargs",
".",
"keys",
"(",
")"... | This method handles creating a parent `ManyRelatedField` instance
when the `many=True` keyword argument is passed.
Typically you won't need to override this method.
Note that we're over-cautious in passing most arguments to both parent
and child classes in order to try to cover the gen... | [
"This",
"method",
"handles",
"creating",
"a",
"parent",
"ManyRelatedField",
"instance",
"when",
"the",
"many",
"=",
"True",
"keyword",
"argument",
"is",
"passed",
"."
] | python | train | 41.238095 |
sdispater/pendulum | pendulum/date.py | https://github.com/sdispater/pendulum/blob/94d28b0d3cb524ae02361bd1ed7ea03e2e655e4e/pendulum/date.py#L479-L487 | def _end_of_decade(self):
"""
Reset the date to the last day of the decade.
:rtype: Date
"""
year = self.year - self.year % YEARS_PER_DECADE + YEARS_PER_DECADE - 1
return self.set(year, 12, 31) | [
"def",
"_end_of_decade",
"(",
"self",
")",
":",
"year",
"=",
"self",
".",
"year",
"-",
"self",
".",
"year",
"%",
"YEARS_PER_DECADE",
"+",
"YEARS_PER_DECADE",
"-",
"1",
"return",
"self",
".",
"set",
"(",
"year",
",",
"12",
",",
"31",
")"
] | Reset the date to the last day of the decade.
:rtype: Date | [
"Reset",
"the",
"date",
"to",
"the",
"last",
"day",
"of",
"the",
"decade",
"."
] | python | train | 26.111111 |
watchforstock/evohome-client | evohomeclient/__init__.py | https://github.com/watchforstock/evohome-client/blob/f1cb9273e97946d79c0651f00a218abbf7ada53a/evohomeclient/__init__.py#L115-L133 | def temperatures(self, force_refresh=False):
"""Retrieve the current details for each zone. Returns a generator."""
self._populate_full_data(force_refresh)
for device in self.full_data['devices']:
set_point = 0
status = ""
if 'heatSetpoint' in device['thermost... | [
"def",
"temperatures",
"(",
"self",
",",
"force_refresh",
"=",
"False",
")",
":",
"self",
".",
"_populate_full_data",
"(",
"force_refresh",
")",
"for",
"device",
"in",
"self",
".",
"full_data",
"[",
"'devices'",
"]",
":",
"set_point",
"=",
"0",
"status",
"... | Retrieve the current details for each zone. Returns a generator. | [
"Retrieve",
"the",
"current",
"details",
"for",
"each",
"zone",
".",
"Returns",
"a",
"generator",
"."
] | python | train | 53.684211 |
jaraco/irc | irc/client.py | https://github.com/jaraco/irc/blob/571c1f448d5d5bb92bbe2605c33148bf6e698413/irc/client.py#L1172-L1184 | def dcc_connect(self, address, port, dcctype="chat"):
"""Connect to a DCC peer.
Arguments:
address -- IP address of the peer.
port -- Port to connect to.
Returns a DCCConnection instance.
"""
warnings.warn("Use self.dcc(type).connect()", DeprecationWar... | [
"def",
"dcc_connect",
"(",
"self",
",",
"address",
",",
"port",
",",
"dcctype",
"=",
"\"chat\"",
")",
":",
"warnings",
".",
"warn",
"(",
"\"Use self.dcc(type).connect()\"",
",",
"DeprecationWarning",
")",
"return",
"self",
".",
"dcc",
"(",
"dcctype",
")",
".... | Connect to a DCC peer.
Arguments:
address -- IP address of the peer.
port -- Port to connect to.
Returns a DCCConnection instance. | [
"Connect",
"to",
"a",
"DCC",
"peer",
"."
] | python | train | 28.384615 |
JarryShaw/PyPCAPKit | src/protocols/internet/internet.py | https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/protocols/internet/internet.py#L113-L170 | def _import_next_layer(self, proto, length=None, *, version=4, extension=False):
"""Import next layer extractor.
Positional arguments:
* proto -- str, next layer protocol name
* length -- int, valid (not padding) length
Keyword Arguments:
* version -- int, I... | [
"def",
"_import_next_layer",
"(",
"self",
",",
"proto",
",",
"length",
"=",
"None",
",",
"*",
",",
"version",
"=",
"4",
",",
"extension",
"=",
"False",
")",
":",
"if",
"length",
"==",
"0",
":",
"from",
"pcapkit",
".",
"protocols",
".",
"null",
"impor... | Import next layer extractor.
Positional arguments:
* proto -- str, next layer protocol name
* length -- int, valid (not padding) length
Keyword Arguments:
* version -- int, IP version (4 in default)
<keyword> 4 / 6
* extension... | [
"Import",
"next",
"layer",
"extractor",
"."
] | python | train | 42.689655 |
clab/dynet | examples/treelstm/main.py | https://github.com/clab/dynet/blob/21cc62606b74f81bb4b11a9989a6c2bd0caa09c5/examples/treelstm/main.py#L24-L42 | def maybe_download_and_extract():
"""Download and extract processed data and embeddings."""
dest_directory = '.'
filename = DATA_URL.split('/')[-1]
filepath = os.path.join(dest_directory, filename)
if not os.path.exists(filepath):
def _progress(count, block_size, total_size):
sys.stdout.write('\r>> ... | [
"def",
"maybe_download_and_extract",
"(",
")",
":",
"dest_directory",
"=",
"'.'",
"filename",
"=",
"DATA_URL",
".",
"split",
"(",
"'/'",
")",
"[",
"-",
"1",
"]",
"filepath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"dest_directory",
",",
"filename",
")"... | Download and extract processed data and embeddings. | [
"Download",
"and",
"extract",
"processed",
"data",
"and",
"embeddings",
"."
] | python | valid | 43.894737 |
DLR-RM/RAFCON | source/rafcon/gui/models/abstract_state.py | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/models/abstract_state.py#L376-L421 | def action_signal_triggered(self, model, prop_name, info):
"""This method notifies the parent state and child state models about complex actions
"""
msg = info.arg
# print("action_signal_triggered state: ", self.state.state_id, model, prop_name, info)
if msg.action.startswith('sm... | [
"def",
"action_signal_triggered",
"(",
"self",
",",
"model",
",",
"prop_name",
",",
"info",
")",
":",
"msg",
"=",
"info",
".",
"arg",
"# print(\"action_signal_triggered state: \", self.state.state_id, model, prop_name, info)",
"if",
"msg",
".",
"action",
".",
"startswit... | This method notifies the parent state and child state models about complex actions | [
"This",
"method",
"notifies",
"the",
"parent",
"state",
"and",
"child",
"state",
"models",
"about",
"complex",
"actions"
] | python | train | 54.586957 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.