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 |
|---|---|---|---|---|---|---|---|---|---|
saulpw/visidata | visidata/vdtui.py | https://github.com/saulpw/visidata/blob/32771e0cea6c24fc7902683d14558391395c591f/visidata/vdtui.py#L1089-L1132 | def exec_command(self, cmd, args='', vdglobals=None, keystrokes=None):
"Execute `cmd` tuple with `vdglobals` as globals and this sheet's attributes as locals. Returns True if user cancelled."
global sheet
sheet = vd.sheets[0]
if not cmd:
debug('no command "%s"' % keystrokes... | [
"def",
"exec_command",
"(",
"self",
",",
"cmd",
",",
"args",
"=",
"''",
",",
"vdglobals",
"=",
"None",
",",
"keystrokes",
"=",
"None",
")",
":",
"global",
"sheet",
"sheet",
"=",
"vd",
".",
"sheets",
"[",
"0",
"]",
"if",
"not",
"cmd",
":",
"debug",
... | Execute `cmd` tuple with `vdglobals` as globals and this sheet's attributes as locals. Returns True if user cancelled. | [
"Execute",
"cmd",
"tuple",
"with",
"vdglobals",
"as",
"globals",
"and",
"this",
"sheet",
"s",
"attributes",
"as",
"locals",
".",
"Returns",
"True",
"if",
"user",
"cancelled",
"."
] | python | train | 28 |
sergei-maertens/django-systemjs | systemjs/jspm.py | https://github.com/sergei-maertens/django-systemjs/blob/efd4a3862a39d9771609a25a5556f36023cf6e5c/systemjs/jspm.py#L33-L56 | def find_systemjs_location():
"""
Figure out where `jspm_packages/system.js` will be put by JSPM.
"""
location = os.path.abspath(os.path.dirname(locate_package_json()))
conf = parse_package_json()
if 'jspm' in conf:
conf = conf['jspm']
try:
conf = conf['directories']
ex... | [
"def",
"find_systemjs_location",
"(",
")",
":",
"location",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"locate_package_json",
"(",
")",
")",
")",
"conf",
"=",
"parse_package_json",
"(",
")",
"if",
"'jspm'",
"in",... | Figure out where `jspm_packages/system.js` will be put by JSPM. | [
"Figure",
"out",
"where",
"jspm_packages",
"/",
"system",
".",
"js",
"will",
"be",
"put",
"by",
"JSPM",
"."
] | python | test | 43.375 |
coopernurse/barrister | barrister/runtime.py | https://github.com/coopernurse/barrister/blob/0471b1d98d3327ba381684db496ec94c79c20848/barrister/runtime.py#L937-L946 | def function(self, func_name):
"""
Returns the Function instance associated with the given func_name, or raises a
RpcException if no function matches.
"""
if self.functions.has_key(func_name):
return self.functions[func_name]
else:
raise RpcExcepti... | [
"def",
"function",
"(",
"self",
",",
"func_name",
")",
":",
"if",
"self",
".",
"functions",
".",
"has_key",
"(",
"func_name",
")",
":",
"return",
"self",
".",
"functions",
"[",
"func_name",
"]",
"else",
":",
"raise",
"RpcException",
"(",
"ERR_METHOD_NOT_FO... | Returns the Function instance associated with the given func_name, or raises a
RpcException if no function matches. | [
"Returns",
"the",
"Function",
"instance",
"associated",
"with",
"the",
"given",
"func_name",
"or",
"raises",
"a",
"RpcException",
"if",
"no",
"function",
"matches",
"."
] | python | train | 41.9 |
saltstack/salt | salt/modules/postgres.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/postgres.py#L1996-L2053 | def schema_remove(dbname, name,
user=None,
db_user=None, db_password=None,
db_host=None, db_port=None):
'''
Removes a schema from the Postgres server.
CLI Example:
.. code-block:: bash
salt '*' postgres.schema_remove dbname schemaname
... | [
"def",
"schema_remove",
"(",
"dbname",
",",
"name",
",",
"user",
"=",
"None",
",",
"db_user",
"=",
"None",
",",
"db_password",
"=",
"None",
",",
"db_host",
"=",
"None",
",",
"db_port",
"=",
"None",
")",
":",
"# check if schema exists",
"if",
"not",
"sche... | Removes a schema from the Postgres server.
CLI Example:
.. code-block:: bash
salt '*' postgres.schema_remove dbname schemaname
dbname
Database name we work on
schemaname
The schema's name we'll remove
user
System user all operations should be performed on behalf... | [
"Removes",
"a",
"schema",
"from",
"the",
"Postgres",
"server",
"."
] | python | train | 27.12069 |
tradenity/python-sdk | tradenity/resources/table_rate_shipping.py | https://github.com/tradenity/python-sdk/blob/d13fbe23f4d6ff22554c6d8d2deaf209371adaf1/tradenity/resources/table_rate_shipping.py#L660-L680 | def get_table_rate_shipping_by_id(cls, table_rate_shipping_id, **kwargs):
"""Find TableRateShipping
Return single instance of TableRateShipping by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> th... | [
"def",
"get_table_rate_shipping_by_id",
"(",
"cls",
",",
"table_rate_shipping_id",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async'",
")",
":",
"return",
"cls",
".",
"_g... | Find TableRateShipping
Return single instance of TableRateShipping by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.get_table_rate_shipping_by_id(table_rate_shipping_id, async=True)
... | [
"Find",
"TableRateShipping"
] | python | train | 47.619048 |
eventifyio/eventify | eventify/drivers/crossbar.py | https://github.com/eventifyio/eventify/blob/0e519964a56bd07a879b266f21f177749c63aaed/eventify/drivers/crossbar.py#L199-L235 | def reconnect(self):
"""
Handle reconnect logic if connection
to crossbar is lost
"""
connect_attempt = 0
max_retries = self.config['max_reconnect_retries']
logging.info('attempting to reconnect to crossbar')
runner = self.setup_runner()
while True... | [
"def",
"reconnect",
"(",
"self",
")",
":",
"connect_attempt",
"=",
"0",
"max_retries",
"=",
"self",
".",
"config",
"[",
"'max_reconnect_retries'",
"]",
"logging",
".",
"info",
"(",
"'attempting to reconnect to crossbar'",
")",
"runner",
"=",
"self",
".",
"setup_... | Handle reconnect logic if connection
to crossbar is lost | [
"Handle",
"reconnect",
"logic",
"if",
"connection",
"to",
"crossbar",
"is",
"lost"
] | python | train | 37.459459 |
Infinidat/infi.instruct | src/infi/instruct/base.py | https://github.com/Infinidat/infi.instruct/blob/93b1ab725cfd8d13227960dbf9e3ca1e7f9eebe8/src/infi/instruct/base.py#L124-L135 | def create_from_string(self, string, context=EMPTY_CONTEXT, *args, **kwargs):
"""
Deserializes a new instance from a string.
This is a convenience method that creates a StringIO object and calls create_instance_from_stream().
"""
if not PY2 and not isinstance(string, bytes):
... | [
"def",
"create_from_string",
"(",
"self",
",",
"string",
",",
"context",
"=",
"EMPTY_CONTEXT",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"PY2",
"and",
"not",
"isinstance",
"(",
"string",
",",
"bytes",
")",
":",
"raise",
"TypeErr... | Deserializes a new instance from a string.
This is a convenience method that creates a StringIO object and calls create_instance_from_stream(). | [
"Deserializes",
"a",
"new",
"instance",
"from",
"a",
"string",
".",
"This",
"is",
"a",
"convenience",
"method",
"that",
"creates",
"a",
"StringIO",
"object",
"and",
"calls",
"create_instance_from_stream",
"()",
"."
] | python | valid | 44.333333 |
Opentrons/opentrons | api/src/opentrons/legacy_api/modules/tempdeck.py | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/legacy_api/modules/tempdeck.py#L145-L154 | def disconnect(self):
'''
Disconnect from the serial port
'''
if self._poll_stop_event:
self._poll_stop_event.set()
if self._driver:
if self.status != 'idle':
self.deactivate()
self._driver.disconnect() | [
"def",
"disconnect",
"(",
"self",
")",
":",
"if",
"self",
".",
"_poll_stop_event",
":",
"self",
".",
"_poll_stop_event",
".",
"set",
"(",
")",
"if",
"self",
".",
"_driver",
":",
"if",
"self",
".",
"status",
"!=",
"'idle'",
":",
"self",
".",
"deactivate... | Disconnect from the serial port | [
"Disconnect",
"from",
"the",
"serial",
"port"
] | python | train | 28.5 |
mozillazg/baidu-pcs-python-sdk | baidupcs/api.py | https://github.com/mozillazg/baidu-pcs-python-sdk/blob/12fe3f13b2ecda8f8bdcc5334c876e934776a5cc/baidupcs/api.py#L328-L354 | def move(self, from_path, to_path, **kwargs):
"""移动单个文件或目录.
:param from_path: 源文件/目录在网盘中的路径(包括文件名)。
.. warning::
* 路径长度限制为1000;
* 径中不能包含以下字符:``\\\\ ? | " > < : *``;
* 文件名或路径名开头结尾不能是 ``.`... | [
"def",
"move",
"(",
"self",
",",
"from_path",
",",
"to_path",
",",
"*",
"*",
"kwargs",
")",
":",
"data",
"=",
"{",
"'from'",
":",
"from_path",
",",
"'to'",
":",
"to_path",
",",
"}",
"return",
"self",
".",
"_request",
"(",
"'file'",
",",
"'move'",
"... | 移动单个文件或目录.
:param from_path: 源文件/目录在网盘中的路径(包括文件名)。
.. warning::
* 路径长度限制为1000;
* 径中不能包含以下字符:``\\\\ ? | " > < : *``;
* 文件名或路径名开头结尾不能是 ``.``
或空白字符,空白字符包括:
... | [
"移动单个文件或目录",
"."
] | python | train | 35.407407 |
awslabs/aws-shell | awsshell/app.py | https://github.com/awslabs/aws-shell/blob/8950f03d9d720879890af6c11537b8f9789ce5a9/awsshell/app.py#L167-L185 | def handle_cmd(self, command, application):
"""Handle running a given dot command from a user.
:type command: str
:param command: The full dot command string, e.g. ``.edit``,
of ``.profile prod``.
:type application: AWSShell
:param application: The application objec... | [
"def",
"handle_cmd",
"(",
"self",
",",
"command",
",",
"application",
")",
":",
"parts",
"=",
"command",
".",
"split",
"(",
")",
"cmd_name",
"=",
"parts",
"[",
"0",
"]",
"[",
"1",
":",
"]",
"if",
"cmd_name",
"not",
"in",
"self",
".",
"HANDLER_CLASSES... | Handle running a given dot command from a user.
:type command: str
:param command: The full dot command string, e.g. ``.edit``,
of ``.profile prod``.
:type application: AWSShell
:param application: The application object. | [
"Handle",
"running",
"a",
"given",
"dot",
"command",
"from",
"a",
"user",
"."
] | python | train | 34.526316 |
saltstack/salt | salt/utils/smb.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/smb.py#L281-L295 | def put_str(content, path, share='C$', conn=None, host=None, username=None, password=None):
'''
Wrapper around impacket.smbconnection.putFile() that allows a string to be
uploaded, without first writing it as a local file
'''
if HAS_SMBPROTOCOL:
return _put_str_smbprotocol(
conte... | [
"def",
"put_str",
"(",
"content",
",",
"path",
",",
"share",
"=",
"'C$'",
",",
"conn",
"=",
"None",
",",
"host",
"=",
"None",
",",
"username",
"=",
"None",
",",
"password",
"=",
"None",
")",
":",
"if",
"HAS_SMBPROTOCOL",
":",
"return",
"_put_str_smbpro... | Wrapper around impacket.smbconnection.putFile() that allows a string to be
uploaded, without first writing it as a local file | [
"Wrapper",
"around",
"impacket",
".",
"smbconnection",
".",
"putFile",
"()",
"that",
"allows",
"a",
"string",
"to",
"be",
"uploaded",
"without",
"first",
"writing",
"it",
"as",
"a",
"local",
"file"
] | python | train | 42.266667 |
sdispater/orator | orator/orm/relations/relation.py | https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/orm/relations/relation.py#L77-L83 | def touch(self):
"""
Touch all of the related models for the relationship.
"""
column = self.get_related().get_updated_at_column()
self.raw_update({column: self.get_related().fresh_timestamp()}) | [
"def",
"touch",
"(",
"self",
")",
":",
"column",
"=",
"self",
".",
"get_related",
"(",
")",
".",
"get_updated_at_column",
"(",
")",
"self",
".",
"raw_update",
"(",
"{",
"column",
":",
"self",
".",
"get_related",
"(",
")",
".",
"fresh_timestamp",
"(",
"... | Touch all of the related models for the relationship. | [
"Touch",
"all",
"of",
"the",
"related",
"models",
"for",
"the",
"relationship",
"."
] | python | train | 32.714286 |
angr/angr | angr/sim_manager.py | https://github.com/angr/angr/blob/4e2f97d56af5419ee73bdb30482c8dd8ff5f3e40/angr/sim_manager.py#L193-L211 | def remove_technique(self, tech):
"""
Remove an exploration technique from a list of active techniques.
:param tech: An ExplorationTechnique object.
:type tech: ExplorationTechnique
"""
if not isinstance(tech, ExplorationTechnique):
raise SimulationMan... | [
"def",
"remove_technique",
"(",
"self",
",",
"tech",
")",
":",
"if",
"not",
"isinstance",
"(",
"tech",
",",
"ExplorationTechnique",
")",
":",
"raise",
"SimulationManagerError",
"def",
"_is_overriden",
"(",
"name",
")",
":",
"return",
"getattr",
"(",
"tech",
... | Remove an exploration technique from a list of active techniques.
:param tech: An ExplorationTechnique object.
:type tech: ExplorationTechnique | [
"Remove",
"an",
"exploration",
"technique",
"from",
"a",
"list",
"of",
"active",
"techniques",
"."
] | python | train | 37.736842 |
hyperledger/indy-plenum | common/version.py | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/common/version.py#L39-L47 | def cmp(cls, v1: 'VersionBase', v2: 'VersionBase') -> int:
""" Compares two instances. """
# TODO types checking
if v1._version > v2._version:
return 1
elif v1._version == v2._version:
return 0
else:
return -1 | [
"def",
"cmp",
"(",
"cls",
",",
"v1",
":",
"'VersionBase'",
",",
"v2",
":",
"'VersionBase'",
")",
"->",
"int",
":",
"# TODO types checking",
"if",
"v1",
".",
"_version",
">",
"v2",
".",
"_version",
":",
"return",
"1",
"elif",
"v1",
".",
"_version",
"=="... | Compares two instances. | [
"Compares",
"two",
"instances",
"."
] | python | train | 30.777778 |
isislovecruft/python-gnupg | pretty_bad_protocol/_util.py | https://github.com/isislovecruft/python-gnupg/blob/784571449032e811587249743e183fc5e908a673/pretty_bad_protocol/_util.py#L447-L471 | def _is_file(filename):
"""Check that the size of the thing which is supposed to be a filename has
size greater than zero, without following symbolic links or using
:func:os.path.isfile.
:param filename: An object to check.
:rtype: bool
:returns: True if **filename** is file-like, False otherwi... | [
"def",
"_is_file",
"(",
"filename",
")",
":",
"try",
":",
"statinfo",
"=",
"os",
".",
"lstat",
"(",
"filename",
")",
"log",
".",
"debug",
"(",
"\"lstat(%r) with type=%s gave us %r\"",
"%",
"(",
"repr",
"(",
"filename",
")",
",",
"type",
"(",
"filename",
... | Check that the size of the thing which is supposed to be a filename has
size greater than zero, without following symbolic links or using
:func:os.path.isfile.
:param filename: An object to check.
:rtype: bool
:returns: True if **filename** is file-like, False otherwise. | [
"Check",
"that",
"the",
"size",
"of",
"the",
"thing",
"which",
"is",
"supposed",
"to",
"be",
"a",
"filename",
"has",
"size",
"greater",
"than",
"zero",
"without",
"following",
"symbolic",
"links",
"or",
"using",
":",
"func",
":",
"os",
".",
"path",
".",
... | python | train | 35.64 |
DataDog/integrations-core | openstack_controller/datadog_checks/openstack_controller/openstack_controller.py | https://github.com/DataDog/integrations-core/blob/ebd41c873cf9f97a8c51bf9459bc6a7536af8acd/openstack_controller/datadog_checks/openstack_controller/openstack_controller.py#L181-L186 | def _parse_uptime_string(self, uptime):
""" Parse u' 16:53:48 up 1 day, 21:34, 3 users, load average: 0.04, 0.14, 0.19\n' """
uptime = uptime.strip()
load_averages = uptime[uptime.find('load average:') :].split(':')[1].strip().split(',')
load_averages = [float(load_avg) for load_avg in... | [
"def",
"_parse_uptime_string",
"(",
"self",
",",
"uptime",
")",
":",
"uptime",
"=",
"uptime",
".",
"strip",
"(",
")",
"load_averages",
"=",
"uptime",
"[",
"uptime",
".",
"find",
"(",
"'load average:'",
")",
":",
"]",
".",
"split",
"(",
"':'",
")",
"[",... | Parse u' 16:53:48 up 1 day, 21:34, 3 users, load average: 0.04, 0.14, 0.19\n' | [
"Parse",
"u",
"16",
":",
"53",
":",
"48",
"up",
"1",
"day",
"21",
":",
"34",
"3",
"users",
"load",
"average",
":",
"0",
".",
"04",
"0",
".",
"14",
"0",
".",
"19",
"\\",
"n"
] | python | train | 59.833333 |
taleinat/fuzzysearch | src/fuzzysearch/substitutions_only.py | https://github.com/taleinat/fuzzysearch/blob/04be1b4490de92601400be5ecc999003ff2f621f/src/fuzzysearch/substitutions_only.py#L37-L62 | def find_near_matches_substitutions(subsequence, sequence, max_substitutions):
"""Find near-matches of the subsequence in the sequence.
This chooses a suitable fuzzy search implementation according to the given
parameters.
Returns a list of fuzzysearch.Match objects describing the matching parts
o... | [
"def",
"find_near_matches_substitutions",
"(",
"subsequence",
",",
"sequence",
",",
"max_substitutions",
")",
":",
"_check_arguments",
"(",
"subsequence",
",",
"sequence",
",",
"max_substitutions",
")",
"if",
"max_substitutions",
"==",
"0",
":",
"return",
"[",
"Matc... | Find near-matches of the subsequence in the sequence.
This chooses a suitable fuzzy search implementation according to the given
parameters.
Returns a list of fuzzysearch.Match objects describing the matching parts
of the sequence. | [
"Find",
"near",
"-",
"matches",
"of",
"the",
"subsequence",
"in",
"the",
"sequence",
"."
] | python | train | 33.769231 |
pymoca/pymoca | src/pymoca/backends/xml/model.py | https://github.com/pymoca/pymoca/blob/14b5eb7425e96689de6cc5c10f400895d586a978/src/pymoca/backends/xml/model.py#L174-L186 | def split_dae_alg(eqs: SYM, dx: SYM) -> Dict[str, SYM]:
"""Split equations into differential algebraic and algebraic only"""
dae = []
alg = []
for eq in ca.vertsplit(eqs):
if ca.depends_on(eq, dx):
dae.append(eq)
else:
alg.append(eq)
return {
'dae': ca... | [
"def",
"split_dae_alg",
"(",
"eqs",
":",
"SYM",
",",
"dx",
":",
"SYM",
")",
"->",
"Dict",
"[",
"str",
",",
"SYM",
"]",
":",
"dae",
"=",
"[",
"]",
"alg",
"=",
"[",
"]",
"for",
"eq",
"in",
"ca",
".",
"vertsplit",
"(",
"eqs",
")",
":",
"if",
"... | Split equations into differential algebraic and algebraic only | [
"Split",
"equations",
"into",
"differential",
"algebraic",
"and",
"algebraic",
"only"
] | python | train | 27.769231 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/schema.py | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/schema.py#L79-L84 | def get_view_names(engine: Engine) -> List[str]:
"""
Returns a list of database view names from the :class:`Engine`.
"""
insp = Inspector.from_engine(engine)
return insp.get_view_names() | [
"def",
"get_view_names",
"(",
"engine",
":",
"Engine",
")",
"->",
"List",
"[",
"str",
"]",
":",
"insp",
"=",
"Inspector",
".",
"from_engine",
"(",
"engine",
")",
"return",
"insp",
".",
"get_view_names",
"(",
")"
] | Returns a list of database view names from the :class:`Engine`. | [
"Returns",
"a",
"list",
"of",
"database",
"view",
"names",
"from",
"the",
":",
"class",
":",
"Engine",
"."
] | python | train | 33.5 |
google/grumpy | third_party/stdlib/_abcoll.py | https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/_abcoll.py#L669-L673 | def reverse(self):
'S.reverse() -- reverse *IN PLACE*'
n = len(self)
for i in range(n//2):
self[i], self[n-i-1] = self[n-i-1], self[i] | [
"def",
"reverse",
"(",
"self",
")",
":",
"n",
"=",
"len",
"(",
"self",
")",
"for",
"i",
"in",
"range",
"(",
"n",
"//",
"2",
")",
":",
"self",
"[",
"i",
"]",
",",
"self",
"[",
"n",
"-",
"i",
"-",
"1",
"]",
"=",
"self",
"[",
"n",
"-",
"i"... | S.reverse() -- reverse *IN PLACE* | [
"S",
".",
"reverse",
"()",
"--",
"reverse",
"*",
"IN",
"PLACE",
"*"
] | python | valid | 33.2 |
PredixDev/predixpy | predix/data/timeseries.py | https://github.com/PredixDev/predixpy/blob/a0cb34cf40f716229351bb6d90d6ecace958c81f/predix/data/timeseries.py#L399-L420 | def _send_to_timeseries(self, message):
"""
Establish or reuse socket connection and send
the given message to the timeseries service.
"""
logging.debug("MESSAGE=" + str(message))
result = None
try:
ws = self._get_websocket()
ws.send(json.... | [
"def",
"_send_to_timeseries",
"(",
"self",
",",
"message",
")",
":",
"logging",
".",
"debug",
"(",
"\"MESSAGE=\"",
"+",
"str",
"(",
"message",
")",
")",
"result",
"=",
"None",
"try",
":",
"ws",
"=",
"self",
".",
"_get_websocket",
"(",
")",
"ws",
".",
... | Establish or reuse socket connection and send
the given message to the timeseries service. | [
"Establish",
"or",
"reuse",
"socket",
"connection",
"and",
"send",
"the",
"given",
"message",
"to",
"the",
"timeseries",
"service",
"."
] | python | train | 32.272727 |
zagaran/mongolia | mongolia/database_object.py | https://github.com/zagaran/mongolia/blob/82c499345f0a8610c7289545e19f5f633e8a81c0/mongolia/database_object.py#L146-L168 | def exists(cls, query=None, path=None, **kwargs):
"""
Like __init__ but simply returns a boolean as to whether or not the
object exists, rather than returning the whole object.
NOTE: if you pass in a single argument to exists, this will
match against ID_KEY.
... | [
"def",
"exists",
"(",
"cls",
",",
"query",
"=",
"None",
",",
"path",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"query",
"is",
"None",
"and",
"len",
"(",
"kwargs",
")",
">",
"0",
":",
"query",
"=",
"kwargs",
"if",
"query",
"is",
"Non... | Like __init__ but simply returns a boolean as to whether or not the
object exists, rather than returning the whole object.
NOTE: if you pass in a single argument to exists, this will
match against ID_KEY.
@param query: a dictionary specifying key-value pairs that the re... | [
"Like",
"__init__",
"but",
"simply",
"returns",
"a",
"boolean",
"as",
"to",
"whether",
"or",
"not",
"the",
"object",
"exists",
"rather",
"than",
"returning",
"the",
"whole",
"object",
".",
"NOTE",
":",
"if",
"you",
"pass",
"in",
"a",
"single",
"argument",
... | python | train | 44.043478 |
foxx/python-helpful | helpful.py | https://github.com/foxx/python-helpful/blob/e31ad9bdf45051d8b9a0d1808d214e2293c3bbed/helpful.py#L567-L572 | def random_date_between(start_date, end_date):
"""Return random date between start/end"""
assert isinstance(start_date, datetime.date)
delta_secs = int((end_date - start_date).total_seconds())
delta = datetime.timedelta(seconds=random.randint(0, delta_secs))
return (start_date + delta) | [
"def",
"random_date_between",
"(",
"start_date",
",",
"end_date",
")",
":",
"assert",
"isinstance",
"(",
"start_date",
",",
"datetime",
".",
"date",
")",
"delta_secs",
"=",
"int",
"(",
"(",
"end_date",
"-",
"start_date",
")",
".",
"total_seconds",
"(",
")",
... | Return random date between start/end | [
"Return",
"random",
"date",
"between",
"start",
"/",
"end"
] | python | train | 50.166667 |
brocade/pynos | pynos/versions/ver_7/ver_7_1_0/yang/brocade_snmp.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_7/ver_7_1_0/yang/brocade_snmp.py#L201-L213 | def snmp_server_user_ipv6_acl(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
snmp_server = ET.SubElement(config, "snmp-server", xmlns="urn:brocade.com:mgmt:brocade-snmp")
user = ET.SubElement(snmp_server, "user")
username_key = ET.SubElement(use... | [
"def",
"snmp_server_user_ipv6_acl",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"snmp_server",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"snmp-server\"",
",",
"xmlns",
"=",
"\"urn:b... | Auto Generated Code | [
"Auto",
"Generated",
"Code"
] | python | train | 43.230769 |
brutasse/graphite-api | graphite_api/render/datalib.py | https://github.com/brutasse/graphite-api/blob/0886b7adcf985a1e8bcb084f6dd1dc166a3f3dff/graphite_api/render/datalib.py#L117-L133 | def add_data(self, path, time_info, data, exprs):
"""
Stores data before it can be put into a time series
"""
# Dont add if empty
if not nonempty(data):
for d in self.data[path]:
if nonempty(d['values']):
return
# Add data ... | [
"def",
"add_data",
"(",
"self",
",",
"path",
",",
"time_info",
",",
"data",
",",
"exprs",
")",
":",
"# Dont add if empty",
"if",
"not",
"nonempty",
"(",
"data",
")",
":",
"for",
"d",
"in",
"self",
".",
"data",
"[",
"path",
"]",
":",
"if",
"nonempty",... | Stores data before it can be put into a time series | [
"Stores",
"data",
"before",
"it",
"can",
"be",
"put",
"into",
"a",
"time",
"series"
] | python | train | 28.470588 |
saltstack/salt | salt/cloud/clouds/digitalocean.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/digitalocean.py#L186-L194 | def list_nodes_full(call=None, for_output=True):
'''
Return a list of the VMs that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or --function.'
)
return _list_nodes(full=True, for_output=for_o... | [
"def",
"list_nodes_full",
"(",
"call",
"=",
"None",
",",
"for_output",
"=",
"True",
")",
":",
"if",
"call",
"==",
"'action'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The list_nodes_full function must be called with -f or --function.'",
")",
"return",
"_list_nodes",
... | Return a list of the VMs that are on the provider | [
"Return",
"a",
"list",
"of",
"the",
"VMs",
"that",
"are",
"on",
"the",
"provider"
] | python | train | 35.333333 |
psphere-project/psphere | psphere/soap.py | https://github.com/psphere-project/psphere/blob/83a252e037c3d6e4f18bcd37380998bc9535e591/psphere/soap.py#L48-L53 | def create(client, _type, **kwargs):
"""Create a suds object of the requested _type."""
obj = client.factory.create("ns0:%s" % _type)
for key, value in kwargs.items():
setattr(obj, key, value)
return obj | [
"def",
"create",
"(",
"client",
",",
"_type",
",",
"*",
"*",
"kwargs",
")",
":",
"obj",
"=",
"client",
".",
"factory",
".",
"create",
"(",
"\"ns0:%s\"",
"%",
"_type",
")",
"for",
"key",
",",
"value",
"in",
"kwargs",
".",
"items",
"(",
")",
":",
"... | Create a suds object of the requested _type. | [
"Create",
"a",
"suds",
"object",
"of",
"the",
"requested",
"_type",
"."
] | python | train | 37 |
openearth/bmi-python | bmi/wrapper.py | https://github.com/openearth/bmi-python/blob/2f53f24d45515eb0711c2d28ddd6c1582045248f/bmi/wrapper.py#L552-L560 | def get_current_time(self):
"""
returns current time of simulation
"""
current_time = c_double()
self.library.get_current_time.argtypes = [POINTER(c_double)]
self.library.get_current_time.restype = None
self.library.get_current_time(byref(current_time))
re... | [
"def",
"get_current_time",
"(",
"self",
")",
":",
"current_time",
"=",
"c_double",
"(",
")",
"self",
".",
"library",
".",
"get_current_time",
".",
"argtypes",
"=",
"[",
"POINTER",
"(",
"c_double",
")",
"]",
"self",
".",
"library",
".",
"get_current_time",
... | returns current time of simulation | [
"returns",
"current",
"time",
"of",
"simulation"
] | python | train | 37.222222 |
deepmind/sonnet | sonnet/python/modules/gated_rnn.py | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/gated_rnn.py#L816-L920 | def _build(self, inputs, prev_state, is_training=None, test_local_stats=True):
"""Connects the LSTM module into the graph.
If this is not the first time the module has been connected to the graph,
the Tensors provided as inputs and state must have the same final
dimension, in order for the existing var... | [
"def",
"_build",
"(",
"self",
",",
"inputs",
",",
"prev_state",
",",
"is_training",
"=",
"None",
",",
"test_local_stats",
"=",
"True",
")",
":",
"if",
"is_training",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Boolean is_training flag must be explicitly spec... | Connects the LSTM module into the graph.
If this is not the first time the module has been connected to the graph,
the Tensors provided as inputs and state must have the same final
dimension, in order for the existing variables to be the correct size for
their corresponding multiplications. The batch s... | [
"Connects",
"the",
"LSTM",
"module",
"into",
"the",
"graph",
"."
] | python | train | 44.67619 |
tnkteja/myhelp | virtualEnvironment/lib/python2.7/site-packages/coverage/cmdline.py | https://github.com/tnkteja/myhelp/blob/fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb/virtualEnvironment/lib/python2.7/site-packages/coverage/cmdline.py#L199-L204 | def add_action(self, dash, dashdash, action_code):
"""Add a specialized option that is the action to execute."""
option = self.add_option(dash, dashdash, action='callback',
callback=self._append_action
)
option.action_code = action_code | [
"def",
"add_action",
"(",
"self",
",",
"dash",
",",
"dashdash",
",",
"action_code",
")",
":",
"option",
"=",
"self",
".",
"add_option",
"(",
"dash",
",",
"dashdash",
",",
"action",
"=",
"'callback'",
",",
"callback",
"=",
"self",
".",
"_append_action",
"... | Add a specialized option that is the action to execute. | [
"Add",
"a",
"specialized",
"option",
"that",
"is",
"the",
"action",
"to",
"execute",
"."
] | python | test | 46.5 |
GetRektByMe/Raitonoberu | Raitonoberu/raitonoberu.py | https://github.com/GetRektByMe/Raitonoberu/blob/c35f83cb1c5268b7e641146bc8c6139fbc10e20f/Raitonoberu/raitonoberu.py#L20-L38 | async def get_search_page(self, term: str):
"""Get search page.
This function will get the first link from the search term we do on term and then
it will return the link we want to parse from.
:param term: Light Novel to Search For
"""
# Uses the BASEURL and also builds... | [
"async",
"def",
"get_search_page",
"(",
"self",
",",
"term",
":",
"str",
")",
":",
"# Uses the BASEURL and also builds link for the page we want using the term given",
"params",
"=",
"{",
"'s'",
":",
"term",
",",
"'post_type'",
":",
"'seriesplan'",
"}",
"async",
"with... | Get search page.
This function will get the first link from the search term we do on term and then
it will return the link we want to parse from.
:param term: Light Novel to Search For | [
"Get",
"search",
"page",
"."
] | python | train | 47.473684 |
JoMingyu/TourAPI | tourapi/api.py | https://github.com/JoMingyu/TourAPI/blob/d4b2a6415e01efaa0ddddd55126e2f4ae9d19d33/tourapi/api.py#L140-L323 | def get_detail_intro(self, content_id):
"""
Inquire detail introduction
:param content_id: Content ID to inquire
:type content_id: str
:rtype: dict
"""
content_type_id = self.get_detail_common(content_id)['content_type_id']
# Get content type id
... | [
"def",
"get_detail_intro",
"(",
"self",
",",
"content_id",
")",
":",
"content_type_id",
"=",
"self",
".",
"get_detail_common",
"(",
"content_id",
")",
"[",
"'content_type_id'",
"]",
"# Get content type id",
"resp",
"=",
"json",
".",
"loads",
"(",
"urlopen",
"(",... | Inquire detail introduction
:param content_id: Content ID to inquire
:type content_id: str
:rtype: dict | [
"Inquire",
"detail",
"introduction"
] | python | train | 43.858696 |
Miserlou/Zappa | zappa/core.py | https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/zappa/core.py#L975-L1000 | def copy_on_s3(self, src_file_name, dst_file_name, bucket_name):
"""
Copies src file to destination within a bucket.
"""
try:
self.s3_client.head_bucket(Bucket=bucket_name)
except botocore.exceptions.ClientError as e: # pragma: no cover
# If a client erro... | [
"def",
"copy_on_s3",
"(",
"self",
",",
"src_file_name",
",",
"dst_file_name",
",",
"bucket_name",
")",
":",
"try",
":",
"self",
".",
"s3_client",
".",
"head_bucket",
"(",
"Bucket",
"=",
"bucket_name",
")",
"except",
"botocore",
".",
"exceptions",
".",
"Clien... | Copies src file to destination within a bucket. | [
"Copies",
"src",
"file",
"to",
"destination",
"within",
"a",
"bucket",
"."
] | python | train | 35.269231 |
XuShaohua/bcloud | bcloud/pcs.py | https://github.com/XuShaohua/bcloud/blob/4b54e0fdccf2b3013285fef05c97354cfa31697b/bcloud/pcs.py#L296-L353 | def get_share_uk_and_shareid(cookie, url):
'''从共享链接中提示uk和shareid.
如果共享文件需要输入密码, 就会将need_pwd设为True
如果成功, 返回(need_pwd, uk, shareid)
如果失败, 就返回None
目前支持的链接格式有:
* http://pan.baidu.com/wap/link?uk=202032639&shareid=420754&third=0
* http://pan.baidu.com/share/link?uk=202032639&shareid=420754
... | [
"def",
"get_share_uk_and_shareid",
"(",
"cookie",
",",
"url",
")",
":",
"def",
"parse_share_uk",
"(",
"content",
")",
":",
"'''代码片段如下:\n\n yunData.SHARE_ID = \"677200861\";\n yunData.SHARE_UK = \"1295729848\";\n '''",
"uk_reg",
"=",
"re",
".",
"compile",
... | 从共享链接中提示uk和shareid.
如果共享文件需要输入密码, 就会将need_pwd设为True
如果成功, 返回(need_pwd, uk, shareid)
如果失败, 就返回None
目前支持的链接格式有:
* http://pan.baidu.com/wap/link?uk=202032639&shareid=420754&third=0
* http://pan.baidu.com/share/link?uk=202032639&shareid=420754
* http://pan.baidu.com/s/1i3iQY48 | [
"从共享链接中提示uk和shareid",
"."
] | python | train | 32.103448 |
jkenlooper/chill | src/chill/app.py | https://github.com/jkenlooper/chill/blob/35360c17c2a3b769ecb5406c6dabcf4cc70bd76f/src/chill/app.py#L36-L42 | def send_theme_file(self, filename):
"""
Function used to send static theme files from the theme folder to the browser.
"""
cache_timeout = self.get_send_file_max_age(filename)
return send_from_directory(self.config['THEME_STATIC_FOLDER'], filename,
... | [
"def",
"send_theme_file",
"(",
"self",
",",
"filename",
")",
":",
"cache_timeout",
"=",
"self",
".",
"get_send_file_max_age",
"(",
"filename",
")",
"return",
"send_from_directory",
"(",
"self",
".",
"config",
"[",
"'THEME_STATIC_FOLDER'",
"]",
",",
"filename",
"... | Function used to send static theme files from the theme folder to the browser. | [
"Function",
"used",
"to",
"send",
"static",
"theme",
"files",
"from",
"the",
"theme",
"folder",
"to",
"the",
"browser",
"."
] | python | train | 49.571429 |
SBRG/ssbio | ssbio/protein/sequence/utils/fasta.py | https://github.com/SBRG/ssbio/blob/e9449e64ffc1a1f5ad07e5849aa12a650095f8a2/ssbio/protein/sequence/utils/fasta.py#L93-L109 | def load_fasta_file_as_dict_of_seqs(filename):
"""Load a FASTA file and return the sequences as a dict of {ID: sequence string}
Args:
filename (str): Path to the FASTA file to load
Returns:
dict: Dictionary of IDs to their sequence strings
"""
results = {}
records = load_fast... | [
"def",
"load_fasta_file_as_dict_of_seqs",
"(",
"filename",
")",
":",
"results",
"=",
"{",
"}",
"records",
"=",
"load_fasta_file",
"(",
"filename",
")",
"for",
"r",
"in",
"records",
":",
"results",
"[",
"r",
".",
"id",
"]",
"=",
"str",
"(",
"r",
".",
"s... | Load a FASTA file and return the sequences as a dict of {ID: sequence string}
Args:
filename (str): Path to the FASTA file to load
Returns:
dict: Dictionary of IDs to their sequence strings | [
"Load",
"a",
"FASTA",
"file",
"and",
"return",
"the",
"sequences",
"as",
"a",
"dict",
"of",
"{",
"ID",
":",
"sequence",
"string",
"}"
] | python | train | 23.352941 |
getpelican/pelican-plugins | plantuml/plantuml_rst.py | https://github.com/getpelican/pelican-plugins/blob/cfc7a3f224f1743063b034561f89a6a712d13587/plantuml/plantuml_rst.py#L61-L85 | def pelican_init(pelicanobj):
global global_siteurl
global_siteurl = pelicanobj.settings['SITEURL']
""" Prepare configurations for the MD plugin """
try:
import markdown
from .plantuml_md import PlantUMLMarkdownExtension
except:
# Markdown not available
logger.debug... | [
"def",
"pelican_init",
"(",
"pelicanobj",
")",
":",
"global",
"global_siteurl",
"global_siteurl",
"=",
"pelicanobj",
".",
"settings",
"[",
"'SITEURL'",
"]",
"try",
":",
"import",
"markdown",
"from",
".",
"plantuml_md",
"import",
"PlantUMLMarkdownExtension",
"except"... | Prepare configurations for the MD plugin | [
"Prepare",
"configurations",
"for",
"the",
"MD",
"plugin"
] | python | train | 39.88 |
Kozea/cairocffi | cairocffi/surfaces.py | https://github.com/Kozea/cairocffi/blob/450853add7e32eea20985b6aa5f54d9cb3cd04fe/cairocffi/surfaces.py#L710-L715 | def create_for_data(cls, data, format, width, height, stride=None):
"""Same as ``ImageSurface(format, width, height, data, stride)``.
Exists for compatibility with pycairo.
"""
return cls(format, width, height, data, stride) | [
"def",
"create_for_data",
"(",
"cls",
",",
"data",
",",
"format",
",",
"width",
",",
"height",
",",
"stride",
"=",
"None",
")",
":",
"return",
"cls",
"(",
"format",
",",
"width",
",",
"height",
",",
"data",
",",
"stride",
")"
] | Same as ``ImageSurface(format, width, height, data, stride)``.
Exists for compatibility with pycairo. | [
"Same",
"as",
"ImageSurface",
"(",
"format",
"width",
"height",
"data",
"stride",
")",
".",
"Exists",
"for",
"compatibility",
"with",
"pycairo",
"."
] | python | train | 42 |
exosite-labs/pyonep | pyonep/onep.py | https://github.com/exosite-labs/pyonep/blob/d27b621b00688a542e0adcc01f3e3354c05238a1/pyonep/onep.py#L488-L499 | def usage(self, auth, resource, metric, starttime, endtime, defer=False):
""" Returns metric usage for client and its subhierarchy.
Args:
auth: <cik> for authentication
resource: ResourceID
metrics: Metric to measure (as string), it may be an entity or consumable.
... | [
"def",
"usage",
"(",
"self",
",",
"auth",
",",
"resource",
",",
"metric",
",",
"starttime",
",",
"endtime",
",",
"defer",
"=",
"False",
")",
":",
"return",
"self",
".",
"_call",
"(",
"'usage'",
",",
"auth",
",",
"[",
"resource",
",",
"metric",
",",
... | Returns metric usage for client and its subhierarchy.
Args:
auth: <cik> for authentication
resource: ResourceID
metrics: Metric to measure (as string), it may be an entity or consumable.
starttime: Start time of window to measure useage (format is ___).
... | [
"Returns",
"metric",
"usage",
"for",
"client",
"and",
"its",
"subhierarchy",
"."
] | python | train | 48.833333 |
neurodata/ndio | ndio/ramon/__init__.py | https://github.com/neurodata/ndio/blob/792dd5816bc770b05a3db2f4327da42ff6253531/ndio/ramon/__init__.py#L152-L174 | def to_dict(ramons, flatten=False):
"""
Converts a RAMON object list to a JSON-style dictionary. Useful for going
from an array of RAMONs to a dictionary, indexed by ID.
Arguments:
ramons (RAMON[]): A list of RAMON objects
flatten (boolean: False): Not implemented
Returns:
... | [
"def",
"to_dict",
"(",
"ramons",
",",
"flatten",
"=",
"False",
")",
":",
"if",
"type",
"(",
"ramons",
")",
"is",
"not",
"list",
":",
"ramons",
"=",
"[",
"ramons",
"]",
"out_ramons",
"=",
"{",
"}",
"for",
"r",
"in",
"ramons",
":",
"out_ramons",
"[",... | Converts a RAMON object list to a JSON-style dictionary. Useful for going
from an array of RAMONs to a dictionary, indexed by ID.
Arguments:
ramons (RAMON[]): A list of RAMON objects
flatten (boolean: False): Not implemented
Returns:
dict: A python dictionary of RAMON objects. | [
"Converts",
"a",
"RAMON",
"object",
"list",
"to",
"a",
"JSON",
"-",
"style",
"dictionary",
".",
"Useful",
"for",
"going",
"from",
"an",
"array",
"of",
"RAMONs",
"to",
"a",
"dictionary",
"indexed",
"by",
"ID",
"."
] | python | test | 26.869565 |
globocom/GloboNetworkAPI-client-python | networkapiclient/OptionVIP.py | https://github.com/globocom/GloboNetworkAPI-client-python/blob/cf34f913da48d9abbf750114f5d2ac4b2dde137d/networkapiclient/OptionVIP.py#L63-L91 | def alter(self, id_option_vip, tipo_opcao, nome_opcao_txt):
"""Change Option VIP from by the identifier.
:param id_option_vip: Identifier of the Option VIP. Integer value and greater than zero.
:param tipo_opcao: Type. String with a maximum of 50 characters and respect [a-zA-Z\_-]
:para... | [
"def",
"alter",
"(",
"self",
",",
"id_option_vip",
",",
"tipo_opcao",
",",
"nome_opcao_txt",
")",
":",
"if",
"not",
"is_valid_int_param",
"(",
"id_option_vip",
")",
":",
"raise",
"InvalidParameterError",
"(",
"u'The identifier of Option VIP is invalid or was not informed.... | Change Option VIP from by the identifier.
:param id_option_vip: Identifier of the Option VIP. Integer value and greater than zero.
:param tipo_opcao: Type. String with a maximum of 50 characters and respect [a-zA-Z\_-]
:param nome_opcao_txt: Name Option. String with a maximum of 50 characters a... | [
"Change",
"Option",
"VIP",
"from",
"by",
"the",
"identifier",
"."
] | python | train | 44.413793 |
globocom/GloboNetworkAPI-client-python | networkapiclient/Filter.py | https://github.com/globocom/GloboNetworkAPI-client-python/blob/cf34f913da48d9abbf750114f5d2ac4b2dde137d/networkapiclient/Filter.py#L59-L82 | def add(self, name, description):
"""Inserts a new Filter and returns its identifier.
:param name: Name. String with a maximum of 100 characters and respect [a-zA-Z\_-]
:param description: Description. String with a maximum of 200 characters and respect [a-zA-Z\_-]
:return: Following d... | [
"def",
"add",
"(",
"self",
",",
"name",
",",
"description",
")",
":",
"filter_map",
"=",
"dict",
"(",
")",
"filter_map",
"[",
"'name'",
"]",
"=",
"name",
"filter_map",
"[",
"'description'",
"]",
"=",
"description",
"code",
",",
"xml",
"=",
"self",
".",... | Inserts a new Filter and returns its identifier.
:param name: Name. String with a maximum of 100 characters and respect [a-zA-Z\_-]
:param description: Description. String with a maximum of 200 characters and respect [a-zA-Z\_-]
:return: Following dictionary:
::
{'filter'... | [
"Inserts",
"a",
"new",
"Filter",
"and",
"returns",
"its",
"identifier",
"."
] | python | train | 37.625 |
raamana/mrivis | mrivis/base.py | https://github.com/raamana/mrivis/blob/199ad096b8a1d825f69109e7218a81b2f1cec756/mrivis/base.py#L737-L760 | def save(self, annot=None, output_path=None):
"""Saves the collage to disk as an image.
Parameters
-----------
annot : str
text to annotate the figure with a super title
output_path : str
path to save the figure to.
Note: any spaces in the f... | [
"def",
"save",
"(",
"self",
",",
"annot",
"=",
"None",
",",
"output_path",
"=",
"None",
")",
":",
"if",
"annot",
"is",
"not",
"None",
":",
"self",
".",
"fig",
".",
"suptitle",
"(",
"annot",
",",
"backgroundcolor",
"=",
"'black'",
",",
"color",
"=",
... | Saves the collage to disk as an image.
Parameters
-----------
annot : str
text to annotate the figure with a super title
output_path : str
path to save the figure to.
Note: any spaces in the filename will be replace with ``_`` | [
"Saves",
"the",
"collage",
"to",
"disk",
"as",
"an",
"image",
"."
] | python | train | 33.333333 |
materials-data-facility/toolbox | mdf_toolbox/search_helper.py | https://github.com/materials-data-facility/toolbox/blob/2a4ac2b6a892238263008efa6a5f3923d9a83505/mdf_toolbox/search_helper.py#L197-L210 | def _term(self, term):
"""Add a term to the query.
Arguments:
term (str): The term to add.
Returns:
SearchHelper: Self
"""
# All terms must be strings for Elasticsearch
term = str(term)
if term:
self.__query["q"] += term
... | [
"def",
"_term",
"(",
"self",
",",
"term",
")",
":",
"# All terms must be strings for Elasticsearch",
"term",
"=",
"str",
"(",
"term",
")",
"if",
"term",
":",
"self",
".",
"__query",
"[",
"\"q\"",
"]",
"+=",
"term",
"return",
"self"
] | Add a term to the query.
Arguments:
term (str): The term to add.
Returns:
SearchHelper: Self | [
"Add",
"a",
"term",
"to",
"the",
"query",
"."
] | python | train | 22.928571 |
webadmin87/midnight | midnight_main/templatetags/midnight_main.py | https://github.com/webadmin87/midnight/blob/b60b3b257b4d633550b82a692f3ea3756c62a0a9/midnight_main/templatetags/midnight_main.py#L172-L193 | def search_simple_form(context, **kwargs):
"""
Форма поиска
Пример использования::
{% search_simple_form %}
:param context: контекст
:param kwargs: html атрибуты формы
:return:
"""
data = kwargs
if 'action' in data:
del data['action']
if 'method' in data:
... | [
"def",
"search_simple_form",
"(",
"context",
",",
"*",
"*",
"kwargs",
")",
":",
"data",
"=",
"kwargs",
"if",
"'action'",
"in",
"data",
":",
"del",
"data",
"[",
"'action'",
"]",
"if",
"'method'",
"in",
"data",
":",
"del",
"data",
"[",
"'method'",
"]",
... | Форма поиска
Пример использования::
{% search_simple_form %}
:param context: контекст
:param kwargs: html атрибуты формы
:return: | [
"Форма",
"поиска"
] | python | train | 18 |
Gandi/gandi.cli | gandi/cli/modules/iaas.py | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/modules/iaas.py#L342-L357 | def check_can_migrate(cls, resource):
"""Check if virtual machine can be migrated to another datacenter."""
vm_id = cls.usable_id(resource)
result = cls.call('hosting.vm.can_migrate', vm_id)
if not result['can_migrate']:
if result['matched']:
matched = result... | [
"def",
"check_can_migrate",
"(",
"cls",
",",
"resource",
")",
":",
"vm_id",
"=",
"cls",
".",
"usable_id",
"(",
"resource",
")",
"result",
"=",
"cls",
".",
"call",
"(",
"'hosting.vm.can_migrate'",
",",
"vm_id",
")",
"if",
"not",
"result",
"[",
"'can_migrate... | Check if virtual machine can be migrated to another datacenter. | [
"Check",
"if",
"virtual",
"machine",
"can",
"be",
"migrated",
"to",
"another",
"datacenter",
"."
] | python | train | 40.5625 |
rgs1/zk_shell | zk_shell/xclient.py | https://github.com/rgs1/zk_shell/blob/bbf34fdfcf1f81100e2a5816fad8af6afc782a54/zk_shell/xclient.py#L82-L85 | def create(self, path, value=b"", acl=None, ephemeral=False,
sequence=False):
""" wrapper that handles encoding (yay Py3k) """
super(XTransactionRequest, self).create(path, to_bytes(value), acl, ephemeral, sequence) | [
"def",
"create",
"(",
"self",
",",
"path",
",",
"value",
"=",
"b\"\"",
",",
"acl",
"=",
"None",
",",
"ephemeral",
"=",
"False",
",",
"sequence",
"=",
"False",
")",
":",
"super",
"(",
"XTransactionRequest",
",",
"self",
")",
".",
"create",
"(",
"path"... | wrapper that handles encoding (yay Py3k) | [
"wrapper",
"that",
"handles",
"encoding",
"(",
"yay",
"Py3k",
")"
] | python | train | 60.75 |
talentpair/featurevectormatrix | featurevectormatrix/__init__.py | https://github.com/talentpair/featurevectormatrix/blob/1327026f7e46138947ba55433c11a85bca1adc5d/featurevectormatrix/__init__.py#L51-L59 | def _update_internal_column_state(self, column_names):
""" Update the internal state with some (possibly) new columns
:param column_names: an iterable which contains new column names
"""
for k in column_names:
if k not in self._column_name_idx:
self._column_n... | [
"def",
"_update_internal_column_state",
"(",
"self",
",",
"column_names",
")",
":",
"for",
"k",
"in",
"column_names",
":",
"if",
"k",
"not",
"in",
"self",
".",
"_column_name_idx",
":",
"self",
".",
"_column_name_idx",
"[",
"k",
"]",
"=",
"len",
"(",
"self"... | Update the internal state with some (possibly) new columns
:param column_names: an iterable which contains new column names | [
"Update",
"the",
"internal",
"state",
"with",
"some",
"(",
"possibly",
")",
"new",
"columns"
] | python | train | 44.555556 |
ska-sa/katcp-python | katcp/core.py | https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/core.py#L389-L408 | def request(cls, name, *args, **kwargs):
"""Helper method for creating request messages.
Parameters
----------
name : str
The name of the message.
args : list of strings
The message arguments.
Keyword arguments
-----------------
m... | [
"def",
"request",
"(",
"cls",
",",
"name",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"mid",
"=",
"kwargs",
".",
"pop",
"(",
"'mid'",
",",
"None",
")",
"if",
"len",
"(",
"kwargs",
")",
">",
"0",
":",
"raise",
"TypeError",
"(",
"'Inval... | Helper method for creating request messages.
Parameters
----------
name : str
The name of the message.
args : list of strings
The message arguments.
Keyword arguments
-----------------
mid : str or None
Message ID to use or No... | [
"Helper",
"method",
"for",
"creating",
"request",
"messages",
"."
] | python | train | 29.15 |
joshspeagle/dynesty | dynesty/bounding.py | https://github.com/joshspeagle/dynesty/blob/9e482aafeb5cf84bedb896fa6f07a761d917983e/dynesty/bounding.py#L102-L118 | def samples(self, nsamples, rstate=None):
"""
Draw `nsamples` samples randomly distributed within the unit cube.
Returns
-------
x : `~numpy.ndarray` with shape (nsamples, ndim)
A collection of coordinates within the unit cube.
"""
if rstate is None... | [
"def",
"samples",
"(",
"self",
",",
"nsamples",
",",
"rstate",
"=",
"None",
")",
":",
"if",
"rstate",
"is",
"None",
":",
"rstate",
"=",
"np",
".",
"random",
"xs",
"=",
"np",
".",
"array",
"(",
"[",
"self",
".",
"sample",
"(",
"rstate",
"=",
"rsta... | Draw `nsamples` samples randomly distributed within the unit cube.
Returns
-------
x : `~numpy.ndarray` with shape (nsamples, ndim)
A collection of coordinates within the unit cube. | [
"Draw",
"nsamples",
"samples",
"randomly",
"distributed",
"within",
"the",
"unit",
"cube",
"."
] | python | train | 25.470588 |
aio-libs/aioredis | aioredis/commands/string.py | https://github.com/aio-libs/aioredis/blob/e8c33e39558d4cc91cf70dde490d8b330c97dc2e/aioredis/commands/string.py#L167-L175 | def psetex(self, key, milliseconds, value):
"""Set the value and expiration in milliseconds of a key.
:raises TypeError: if milliseconds is not int
"""
if not isinstance(milliseconds, int):
raise TypeError("milliseconds argument must be int")
fut = self.execute(b'PSE... | [
"def",
"psetex",
"(",
"self",
",",
"key",
",",
"milliseconds",
",",
"value",
")",
":",
"if",
"not",
"isinstance",
"(",
"milliseconds",
",",
"int",
")",
":",
"raise",
"TypeError",
"(",
"\"milliseconds argument must be int\"",
")",
"fut",
"=",
"self",
".",
"... | Set the value and expiration in milliseconds of a key.
:raises TypeError: if milliseconds is not int | [
"Set",
"the",
"value",
"and",
"expiration",
"in",
"milliseconds",
"of",
"a",
"key",
"."
] | python | train | 41.222222 |
brandon-rhodes/python-jplephem | jplephem/ephem.py | https://github.com/brandon-rhodes/python-jplephem/blob/48c99ce40c627e24c95479d8845e312ea168f567/jplephem/ephem.py#L70-L94 | def position_and_velocity(self, name, tdb, tdb2=0.0):
"""[DEPRECATED] Compute the position and velocity of `name` at ``tdb [+ tdb2]``.
The position and velocity are returned in a 2-tuple::
([x y z], [xdot ydot zdot])
The barycentric dynamical time `tdb` argument should be a float.... | [
"def",
"position_and_velocity",
"(",
"self",
",",
"name",
",",
"tdb",
",",
"tdb2",
"=",
"0.0",
")",
":",
"bundle",
"=",
"self",
".",
"compute_bundle",
"(",
"name",
",",
"tdb",
",",
"tdb2",
")",
"position",
"=",
"self",
".",
"position_from_bundle",
"(",
... | [DEPRECATED] Compute the position and velocity of `name` at ``tdb [+ tdb2]``.
The position and velocity are returned in a 2-tuple::
([x y z], [xdot ydot zdot])
The barycentric dynamical time `tdb` argument should be a float.
If there are many dates you want computed, then make `td... | [
"[",
"DEPRECATED",
"]",
"Compute",
"the",
"position",
"and",
"velocity",
"of",
"name",
"at",
"tdb",
"[",
"+",
"tdb2",
"]",
"."
] | python | test | 44.12 |
sanger-pathogens/circlator | circlator/clean.py | https://github.com/sanger-pathogens/circlator/blob/a4befb8c9dbbcd4b3ad1899a95aa3e689d58b638/circlator/clean.py#L206-L217 | def _longest_contig(self, contig_set, contig_lengths):
'''Returns the name of the longest contig, from the set of names contig_set. contig_lengths
is expected to be a dictionary of contig name => length.'''
longest_name = None
max_length = -1
for name in contig_set:
... | [
"def",
"_longest_contig",
"(",
"self",
",",
"contig_set",
",",
"contig_lengths",
")",
":",
"longest_name",
"=",
"None",
"max_length",
"=",
"-",
"1",
"for",
"name",
"in",
"contig_set",
":",
"if",
"contig_lengths",
"[",
"name",
"]",
">",
"max_length",
":",
"... | Returns the name of the longest contig, from the set of names contig_set. contig_lengths
is expected to be a dictionary of contig name => length. | [
"Returns",
"the",
"name",
"of",
"the",
"longest",
"contig",
"from",
"the",
"set",
"of",
"names",
"contig_set",
".",
"contig_lengths",
"is",
"expected",
"to",
"be",
"a",
"dictionary",
"of",
"contig",
"name",
"=",
">",
"length",
"."
] | python | train | 44.5 |
allenai/allennlp | scripts/convert_openie_to_conll.py | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/scripts/convert_openie_to_conll.py#L79-L109 | def split_predicate(ex: Extraction) -> Extraction:
"""
Ensure single word predicate
by adding "before-predicate" and "after-predicate"
arguments.
"""
rel_toks = ex.toks[char_to_word_index(ex.rel.span[0], ex.sent) \
: char_to_word_index(ex.rel.span[1], ex.sent) + 1]
if ... | [
"def",
"split_predicate",
"(",
"ex",
":",
"Extraction",
")",
"->",
"Extraction",
":",
"rel_toks",
"=",
"ex",
".",
"toks",
"[",
"char_to_word_index",
"(",
"ex",
".",
"rel",
".",
"span",
"[",
"0",
"]",
",",
"ex",
".",
"sent",
")",
":",
"char_to_word_inde... | Ensure single word predicate
by adding "before-predicate" and "after-predicate"
arguments. | [
"Ensure",
"single",
"word",
"predicate",
"by",
"adding",
"before",
"-",
"predicate",
"and",
"after",
"-",
"predicate",
"arguments",
"."
] | python | train | 32.193548 |
apple/turicreate | deps/src/boost_1_68_0/tools/build/src/tools/common.py | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/tools/common.py#L285-L320 | def get_invocation_command_nodefault(
toolset, tool, user_provided_command=[], additional_paths=[], path_last=False):
"""
A helper rule to get the command to invoke some tool. If
'user-provided-command' is not given, tries to find binary named 'tool' in
PATH and in the passed 'additional... | [
"def",
"get_invocation_command_nodefault",
"(",
"toolset",
",",
"tool",
",",
"user_provided_command",
"=",
"[",
"]",
",",
"additional_paths",
"=",
"[",
"]",
",",
"path_last",
"=",
"False",
")",
":",
"assert",
"isinstance",
"(",
"toolset",
",",
"basestring",
")... | A helper rule to get the command to invoke some tool. If
'user-provided-command' is not given, tries to find binary named 'tool' in
PATH and in the passed 'additional-path'. Otherwise, verifies that the first
element of 'user-provided-command' is an existing program.
This rule returns t... | [
"A",
"helper",
"rule",
"to",
"get",
"the",
"command",
"to",
"invoke",
"some",
"tool",
".",
"If",
"user",
"-",
"provided",
"-",
"command",
"is",
"not",
"given",
"tries",
"to",
"find",
"binary",
"named",
"tool",
"in",
"PATH",
"and",
"in",
"the",
"passed"... | python | train | 47.722222 |
wandb/client | wandb/vendor/prompt_toolkit/interface.py | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/interface.py#L1098-L1124 | def _write(self, data):
"""
Note: print()-statements cause to multiple write calls.
(write('line') and write('\n')). Of course we don't want to call
`run_in_terminal` for every individual call, because that's too
expensive, and as long as the newline hasn't been... | [
"def",
"_write",
"(",
"self",
",",
"data",
")",
":",
"if",
"'\\n'",
"in",
"data",
":",
"# When there is a newline in the data, write everything before the",
"# newline, including the newline itself.",
"before",
",",
"after",
"=",
"data",
".",
"rsplit",
"(",
"'\\n'",
"... | Note: print()-statements cause to multiple write calls.
(write('line') and write('\n')). Of course we don't want to call
`run_in_terminal` for every individual call, because that's too
expensive, and as long as the newline hasn't been written, the
text itself is a... | [
"Note",
":",
"print",
"()",
"-",
"statements",
"cause",
"to",
"multiple",
"write",
"calls",
".",
"(",
"write",
"(",
"line",
")",
"and",
"write",
"(",
"\\",
"n",
"))",
".",
"Of",
"course",
"we",
"don",
"t",
"want",
"to",
"call",
"run_in_terminal",
"fo... | python | train | 43.259259 |
pazz/urwidtrees | urwidtrees/widgets.py | https://github.com/pazz/urwidtrees/blob/d1fa38ce4f37db00bdfc574b856023b5db4c7ead/urwidtrees/widgets.py#L233-L238 | def focus_next(self):
"""move focus to next position (DFO)"""
w, focuspos = self.get_focus()
next = self._tree.next_position(focuspos)
if next is not None:
self.set_focus(next) | [
"def",
"focus_next",
"(",
"self",
")",
":",
"w",
",",
"focuspos",
"=",
"self",
".",
"get_focus",
"(",
")",
"next",
"=",
"self",
".",
"_tree",
".",
"next_position",
"(",
"focuspos",
")",
"if",
"next",
"is",
"not",
"None",
":",
"self",
".",
"set_focus"... | move focus to next position (DFO) | [
"move",
"focus",
"to",
"next",
"position",
"(",
"DFO",
")"
] | python | train | 35.833333 |
glue-viz/glue-vispy-viewers | glue_vispy_viewers/extern/vispy/scene/cameras/turntable.py | https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/scene/cameras/turntable.py#L140-L150 | def _dist_to_trans(self, dist):
"""Convert mouse x, y movement into x, y, z translations"""
rae = np.array([self.roll, self.azimuth, self.elevation]) * np.pi / 180
sro, saz, sel = np.sin(rae)
cro, caz, cel = np.cos(rae)
dx = (+ dist[0] * (cro * caz + sro * sel * saz)
... | [
"def",
"_dist_to_trans",
"(",
"self",
",",
"dist",
")",
":",
"rae",
"=",
"np",
".",
"array",
"(",
"[",
"self",
".",
"roll",
",",
"self",
".",
"azimuth",
",",
"self",
".",
"elevation",
"]",
")",
"*",
"np",
".",
"pi",
"/",
"180",
"sro",
",",
"saz... | Convert mouse x, y movement into x, y, z translations | [
"Convert",
"mouse",
"x",
"y",
"movement",
"into",
"x",
"y",
"z",
"translations"
] | python | train | 50.181818 |
jazzband/django-model-utils | model_utils/managers.py | https://github.com/jazzband/django-model-utils/blob/d557c4253312774a7c2f14bcd02675e9ac2ea05f/model_utils/managers.py#L295-L303 | def get_queryset(self):
"""
Return queryset limited to not removed entries.
"""
kwargs = {'model': self.model, 'using': self._db}
if hasattr(self, '_hints'):
kwargs['hints'] = self._hints
return self._queryset_class(**kwargs).filter(is_removed=False) | [
"def",
"get_queryset",
"(",
"self",
")",
":",
"kwargs",
"=",
"{",
"'model'",
":",
"self",
".",
"model",
",",
"'using'",
":",
"self",
".",
"_db",
"}",
"if",
"hasattr",
"(",
"self",
",",
"'_hints'",
")",
":",
"kwargs",
"[",
"'hints'",
"]",
"=",
"self... | Return queryset limited to not removed entries. | [
"Return",
"queryset",
"limited",
"to",
"not",
"removed",
"entries",
"."
] | python | train | 33.666667 |
saltstack/salt | salt/states/pagerduty_service.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/pagerduty_service.py#L101-L126 | def _diff(state_data, resource_object):
'''helper method to compare salt state info with the PagerDuty API json structure,
and determine if we need to update.
returns the dict to pass to the PD API to perform the update, or empty dict if no update.
'''
objects_differ = None
for k, v in state_d... | [
"def",
"_diff",
"(",
"state_data",
",",
"resource_object",
")",
":",
"objects_differ",
"=",
"None",
"for",
"k",
",",
"v",
"in",
"state_data",
"[",
"'service'",
"]",
".",
"items",
"(",
")",
":",
"if",
"k",
"==",
"'escalation_policy_id'",
":",
"resource_valu... | helper method to compare salt state info with the PagerDuty API json structure,
and determine if we need to update.
returns the dict to pass to the PD API to perform the update, or empty dict if no update. | [
"helper",
"method",
"to",
"compare",
"salt",
"state",
"info",
"with",
"the",
"PagerDuty",
"API",
"json",
"structure",
"and",
"determine",
"if",
"we",
"need",
"to",
"update",
"."
] | python | train | 38.230769 |
Spinmob/spinmob | _pylab_colormap.py | https://github.com/Spinmob/spinmob/blob/f037f5df07f194bcd4a01f4d9916e57b9e8fb45a/_pylab_colormap.py#L64-L96 | def load_colormap(self, name=None):
"""
Loads a colormap of the supplied name. None means used the internal
name. (See self.get_name())
"""
if name == None: name = self.get_name()
if name == "" or not type(name)==str: return "Error: Bad name."
# assemble the pat... | [
"def",
"load_colormap",
"(",
"self",
",",
"name",
"=",
"None",
")",
":",
"if",
"name",
"==",
"None",
":",
"name",
"=",
"self",
".",
"get_name",
"(",
")",
"if",
"name",
"==",
"\"\"",
"or",
"not",
"type",
"(",
"name",
")",
"==",
"str",
":",
"return... | Loads a colormap of the supplied name. None means used the internal
name. (See self.get_name()) | [
"Loads",
"a",
"colormap",
"of",
"the",
"supplied",
"name",
".",
"None",
"means",
"used",
"the",
"internal",
"name",
".",
"(",
"See",
"self",
".",
"get_name",
"()",
")"
] | python | train | 28.575758 |
michal-stuglik/django-blastplus | blastplus/features/record.py | https://github.com/michal-stuglik/django-blastplus/blob/4f5e15fb9f8069c3bed5f8fd941c4b9891daad4b/blastplus/features/record.py#L119-L121 | def get_id(self):
"""Returns unique id of an alignment. """
return hash(str(self.title) + str(self.best_score()) + str(self.hit_def)) | [
"def",
"get_id",
"(",
"self",
")",
":",
"return",
"hash",
"(",
"str",
"(",
"self",
".",
"title",
")",
"+",
"str",
"(",
"self",
".",
"best_score",
"(",
")",
")",
"+",
"str",
"(",
"self",
".",
"hit_def",
")",
")"
] | Returns unique id of an alignment. | [
"Returns",
"unique",
"id",
"of",
"an",
"alignment",
"."
] | python | train | 49.333333 |
pandas-dev/pandas | pandas/core/internals/blocks.py | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/internals/blocks.py#L1119-L1143 | def _interpolate_with_fill(self, method='pad', axis=0, inplace=False,
limit=None, fill_value=None, coerce=False,
downcast=None):
""" fillna but using the interpolate machinery """
inplace = validate_bool_kwarg(inplace, 'inplace')
# ... | [
"def",
"_interpolate_with_fill",
"(",
"self",
",",
"method",
"=",
"'pad'",
",",
"axis",
"=",
"0",
",",
"inplace",
"=",
"False",
",",
"limit",
"=",
"None",
",",
"fill_value",
"=",
"None",
",",
"coerce",
"=",
"False",
",",
"downcast",
"=",
"None",
")",
... | fillna but using the interpolate machinery | [
"fillna",
"but",
"using",
"the",
"interpolate",
"machinery"
] | python | train | 43.6 |
PrefPy/prefpy | prefpy/mov.py | https://github.com/PrefPy/prefpy/blob/f395ba3782f05684fa5de0cece387a6da9391d02/prefpy/mov.py#L400-L446 | def AppMoVCopeland(profile, alpha=0.5):
"""
Returns an integer that is equal to the margin of victory of the election profile, that is,
the smallest number k such that changing k votes can change the winners.
:ivar Profile profile: A Profile object that represents an election profile.
"""
# Cu... | [
"def",
"AppMoVCopeland",
"(",
"profile",
",",
"alpha",
"=",
"0.5",
")",
":",
"# Currently, we expect the profile to contain complete ordering over candidates.",
"elecType",
"=",
"profile",
".",
"getElecType",
"(",
")",
"if",
"elecType",
"!=",
"\"soc\"",
"and",
"elecType... | Returns an integer that is equal to the margin of victory of the election profile, that is,
the smallest number k such that changing k votes can change the winners.
:ivar Profile profile: A Profile object that represents an election profile. | [
"Returns",
"an",
"integer",
"that",
"is",
"equal",
"to",
"the",
"margin",
"of",
"victory",
"of",
"the",
"election",
"profile",
"that",
"is",
"the",
"smallest",
"number",
"k",
"such",
"that",
"changing",
"k",
"votes",
"can",
"change",
"the",
"winners",
"."
... | python | train | 37.234043 |
alimanfoo/csvvalidator | csvvalidator.py | https://github.com/alimanfoo/csvvalidator/blob/50a86eefdc549c48f65a91a5c0a66099010ee65d/csvvalidator.py#L508-L515 | def _init_unique_sets(self):
"""Initialise sets used for uniqueness checking."""
ks = dict()
for t in self._unique_checks:
key = t[0]
ks[key] = set() # empty set
return ks | [
"def",
"_init_unique_sets",
"(",
"self",
")",
":",
"ks",
"=",
"dict",
"(",
")",
"for",
"t",
"in",
"self",
".",
"_unique_checks",
":",
"key",
"=",
"t",
"[",
"0",
"]",
"ks",
"[",
"key",
"]",
"=",
"set",
"(",
")",
"# empty set",
"return",
"ks"
] | Initialise sets used for uniqueness checking. | [
"Initialise",
"sets",
"used",
"for",
"uniqueness",
"checking",
"."
] | python | valid | 27.625 |
Shoobx/xmldiff | xmldiff/_diff_match_patch_py2.py | https://github.com/Shoobx/xmldiff/blob/ec7835bce9ba69ff4ce03ab6c11397183b6f8411/xmldiff/_diff_match_patch_py2.py#L1354-L1368 | def match_alphabet(self, pattern):
"""Initialise the alphabet for the Bitap algorithm.
Args:
pattern: The text to encode.
Returns:
Hash of character locations.
"""
s = {}
for char in pattern:
s[char] = 0
for i in xrange(len(pattern)):
s[pattern[i]] |= 1 << (len(patt... | [
"def",
"match_alphabet",
"(",
"self",
",",
"pattern",
")",
":",
"s",
"=",
"{",
"}",
"for",
"char",
"in",
"pattern",
":",
"s",
"[",
"char",
"]",
"=",
"0",
"for",
"i",
"in",
"xrange",
"(",
"len",
"(",
"pattern",
")",
")",
":",
"s",
"[",
"pattern"... | Initialise the alphabet for the Bitap algorithm.
Args:
pattern: The text to encode.
Returns:
Hash of character locations. | [
"Initialise",
"the",
"alphabet",
"for",
"the",
"Bitap",
"algorithm",
"."
] | python | train | 22.133333 |
alberanid/python-iplib | iplib.py | https://github.com/alberanid/python-iplib/blob/488b56fe57ad836b27feec9e76f51883db28faa6/iplib.py#L150-L158 | def is_dec(ip):
"""Return true if the IP address is in decimal notation."""
try:
dec = int(str(ip))
except ValueError:
return False
if dec > 4294967295 or dec < 0:
return False
return True | [
"def",
"is_dec",
"(",
"ip",
")",
":",
"try",
":",
"dec",
"=",
"int",
"(",
"str",
"(",
"ip",
")",
")",
"except",
"ValueError",
":",
"return",
"False",
"if",
"dec",
">",
"4294967295",
"or",
"dec",
"<",
"0",
":",
"return",
"False",
"return",
"True"
] | Return true if the IP address is in decimal notation. | [
"Return",
"true",
"if",
"the",
"IP",
"address",
"is",
"in",
"decimal",
"notation",
"."
] | python | valid | 24.888889 |
Cadasta/cadasta-workertoolbox | cadasta/workertoolbox/conf.py | https://github.com/Cadasta/cadasta-workertoolbox/blob/e17cf376538cee0b32c7a21afd5319e3549b954f/cadasta/workertoolbox/conf.py#L202-L210 | def _generate_queues(queues, exchange, platform_queue):
""" Queues known by this worker """
return set([
Queue('celery', exchange, routing_key='celery'),
Queue(platform_queue, exchange, routing_key='#'),
] + [
Queue(q_name, exchange, routing_key=q_name)
... | [
"def",
"_generate_queues",
"(",
"queues",
",",
"exchange",
",",
"platform_queue",
")",
":",
"return",
"set",
"(",
"[",
"Queue",
"(",
"'celery'",
",",
"exchange",
",",
"routing_key",
"=",
"'celery'",
")",
",",
"Queue",
"(",
"platform_queue",
",",
"exchange",
... | Queues known by this worker | [
"Queues",
"known",
"by",
"this",
"worker"
] | python | train | 38.777778 |
timknip/pyswf | swf/stream.py | https://github.com/timknip/pyswf/blob/3740cc80d7650156831e728ea0d408819e5671eb/swf/stream.py#L384-L387 | def readFILTERLIST(self):
""" Read a length-prefixed list of FILTERs """
number = self.readUI8()
return [self.readFILTER() for _ in range(number)] | [
"def",
"readFILTERLIST",
"(",
"self",
")",
":",
"number",
"=",
"self",
".",
"readUI8",
"(",
")",
"return",
"[",
"self",
".",
"readFILTER",
"(",
")",
"for",
"_",
"in",
"range",
"(",
"number",
")",
"]"
] | Read a length-prefixed list of FILTERs | [
"Read",
"a",
"length",
"-",
"prefixed",
"list",
"of",
"FILTERs"
] | python | train | 41.75 |
opennode/waldur-core | waldur_core/core/permissions.py | https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/core/permissions.py#L61-L75 | def get_permission_checks(self, request, view):
"""
Get permission checks that will be executed for current action.
"""
if view.action is None:
return []
# if permissions are defined for view directly - use them.
if hasattr(view, view.action + '_permissions'):... | [
"def",
"get_permission_checks",
"(",
"self",
",",
"request",
",",
"view",
")",
":",
"if",
"view",
".",
"action",
"is",
"None",
":",
"return",
"[",
"]",
"# if permissions are defined for view directly - use them.",
"if",
"hasattr",
"(",
"view",
",",
"view",
".",
... | Get permission checks that will be executed for current action. | [
"Get",
"permission",
"checks",
"that",
"will",
"be",
"executed",
"for",
"current",
"action",
"."
] | python | train | 50.266667 |
apache/airflow | airflow/contrib/hooks/gcp_natural_language_hook.py | https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/gcp_natural_language_hook.py#L56-L80 | def analyze_entities(self, document, encoding_type=None, retry=None, timeout=None, metadata=None):
"""
Finds named entities in the text along with entity types,
salience, mentions for each entity, and other properties.
:param document: Input document.
If a dict is provided, ... | [
"def",
"analyze_entities",
"(",
"self",
",",
"document",
",",
"encoding_type",
"=",
"None",
",",
"retry",
"=",
"None",
",",
"timeout",
"=",
"None",
",",
"metadata",
"=",
"None",
")",
":",
"client",
"=",
"self",
".",
"get_conn",
"(",
")",
"return",
"cli... | Finds named entities in the text along with entity types,
salience, mentions for each entity, and other properties.
:param document: Input document.
If a dict is provided, it must be of the same form as the protobuf message Document
:type document: dict or class google.cloud.languag... | [
"Finds",
"named",
"entities",
"in",
"the",
"text",
"along",
"with",
"entity",
"types",
"salience",
"mentions",
"for",
"each",
"entity",
"and",
"other",
"properties",
"."
] | python | test | 55.4 |
Qiskit/qiskit-terra | qiskit/providers/basicaer/qasm_simulator.py | https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/providers/basicaer/qasm_simulator.py#L325-L332 | def _get_statevector(self):
"""Return the current statevector in JSON Result spec format"""
vec = np.reshape(self._statevector, 2 ** self._number_of_qubits)
# Expand complex numbers
vec = np.stack([vec.real, vec.imag], axis=1)
# Truncate small values
vec[abs(vec) < self._... | [
"def",
"_get_statevector",
"(",
"self",
")",
":",
"vec",
"=",
"np",
".",
"reshape",
"(",
"self",
".",
"_statevector",
",",
"2",
"**",
"self",
".",
"_number_of_qubits",
")",
"# Expand complex numbers",
"vec",
"=",
"np",
".",
"stack",
"(",
"[",
"vec",
".",... | Return the current statevector in JSON Result spec format | [
"Return",
"the",
"current",
"statevector",
"in",
"JSON",
"Result",
"spec",
"format"
] | python | test | 44.125 |
luckydonald/pytgbot | code_generation/output/pytgbot/bot.py | https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/pytgbot/bot.py#L2090-L2122 | def get_chat_administrators(self, chat_id):
"""
Use this method to get a list of administrators in a chat. On success, returns an Array of ChatMember objects that contains information about all chat administrators except other bots. If the chat is a group or a supergroup and no administrators were appoi... | [
"def",
"get_chat_administrators",
"(",
"self",
",",
"chat_id",
")",
":",
"assert_type_or_raise",
"(",
"chat_id",
",",
"(",
"int",
",",
"unicode_type",
")",
",",
"parameter_name",
"=",
"\"chat_id\"",
")",
"result",
"=",
"self",
".",
"do",
"(",
"\"getChatAdminis... | Use this method to get a list of administrators in a chat. On success, returns an Array of ChatMember objects that contains information about all chat administrators except other bots. If the chat is a group or a supergroup and no administrators were appointed, only the creator will be returned.
https://core.t... | [
"Use",
"this",
"method",
"to",
"get",
"a",
"list",
"of",
"administrators",
"in",
"a",
"chat",
".",
"On",
"success",
"returns",
"an",
"Array",
"of",
"ChatMember",
"objects",
"that",
"contains",
"information",
"about",
"all",
"chat",
"administrators",
"except",
... | python | train | 50.121212 |
singularityhub/singularity-python | singularity/analysis/reproduce/utils.py | https://github.com/singularityhub/singularity-python/blob/498c3433724b332f7493fec632d8daf479f47b82/singularity/analysis/reproduce/utils.py#L116-L127 | def delete_image_tar(file_obj, tar):
'''delete image tar will close a file object (if extracted into
memory) or delete from the file system (if saved to disk)'''
try:
file_obj.close()
except:
tar.close()
if os.path.exists(file_obj):
os.remove(file_obj)
deleted = True
... | [
"def",
"delete_image_tar",
"(",
"file_obj",
",",
"tar",
")",
":",
"try",
":",
"file_obj",
".",
"close",
"(",
")",
"except",
":",
"tar",
".",
"close",
"(",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"file_obj",
")",
":",
"os",
".",
"remove",
... | delete image tar will close a file object (if extracted into
memory) or delete from the file system (if saved to disk) | [
"delete",
"image",
"tar",
"will",
"close",
"a",
"file",
"object",
"(",
"if",
"extracted",
"into",
"memory",
")",
"or",
"delete",
"from",
"the",
"file",
"system",
"(",
"if",
"saved",
"to",
"disk",
")"
] | python | train | 31.166667 |
saltstack/salt | salt/modules/schedule.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/schedule.py#L598-L650 | def enable_job(name, **kwargs):
'''
Enable a job in the minion's schedule
CLI Example:
.. code-block:: bash
salt '*' schedule.enable_job job1
'''
ret = {'comment': [],
'result': True}
if not name:
ret['comment'] = 'Job name is required.'
ret['result'] ... | [
"def",
"enable_job",
"(",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"{",
"'comment'",
":",
"[",
"]",
",",
"'result'",
":",
"True",
"}",
"if",
"not",
"name",
":",
"ret",
"[",
"'comment'",
"]",
"=",
"'Job name is required.'",
"ret",
"[",
... | Enable a job in the minion's schedule
CLI Example:
.. code-block:: bash
salt '*' schedule.enable_job job1 | [
"Enable",
"a",
"job",
"in",
"the",
"minion",
"s",
"schedule"
] | python | train | 38.90566 |
vadimk2016/v-vk-api | v_vk_api/utils.py | https://github.com/vadimk2016/v-vk-api/blob/ef5656e09944b5319a1f573cfb7b022f3d31c0cf/v_vk_api/utils.py#L8-L20 | def get_base_url(html: str) -> str:
"""
Search for login url from VK login page
"""
forms = BeautifulSoup(html, 'html.parser').find_all('form')
if not forms:
raise VVKBaseUrlException('Form for login not found')
elif len(forms) > 1:
raise VVKBaseUrlException('More than one login ... | [
"def",
"get_base_url",
"(",
"html",
":",
"str",
")",
"->",
"str",
":",
"forms",
"=",
"BeautifulSoup",
"(",
"html",
",",
"'html.parser'",
")",
".",
"find_all",
"(",
"'form'",
")",
"if",
"not",
"forms",
":",
"raise",
"VVKBaseUrlException",
"(",
"'Form for lo... | Search for login url from VK login page | [
"Search",
"for",
"login",
"url",
"from",
"VK",
"login",
"page"
] | python | train | 35.461538 |
iopipe/iopipe-python | iopipe/report.py | https://github.com/iopipe/iopipe-python/blob/4eb653977341bc67f8b1b87aedb3aaaefc25af61/iopipe/report.py#L119-L136 | def retain_error(self, error, frame=None):
"""
Adds details of an error to the report.
:param error: The error exception to add to the report.
"""
if frame is None:
stack = traceback.format_exc()
self.labels.add("@iopipe/error")
else:
... | [
"def",
"retain_error",
"(",
"self",
",",
"error",
",",
"frame",
"=",
"None",
")",
":",
"if",
"frame",
"is",
"None",
":",
"stack",
"=",
"traceback",
".",
"format_exc",
"(",
")",
"self",
".",
"labels",
".",
"add",
"(",
"\"@iopipe/error\"",
")",
"else",
... | Adds details of an error to the report.
:param error: The error exception to add to the report. | [
"Adds",
"details",
"of",
"an",
"error",
"to",
"the",
"report",
"."
] | python | train | 32.277778 |
hanguokai/youku | youku/youku_shows.py | https://github.com/hanguokai/youku/blob/b2df060c7dccfad990bcfa289fff68bb77d1e69b/youku/youku_shows.py#L33-L43 | def find_shows_by_ids(self, show_ids):
"""doc: http://open.youku.com/docs/doc?id=60
"""
url = 'https://openapi.youku.com/v2/shows/show_batch.json'
params = {
'client_id': self.client_id,
'show_ids': show_ids
}
r = requests.get(url, params=params)
... | [
"def",
"find_shows_by_ids",
"(",
"self",
",",
"show_ids",
")",
":",
"url",
"=",
"'https://openapi.youku.com/v2/shows/show_batch.json'",
"params",
"=",
"{",
"'client_id'",
":",
"self",
".",
"client_id",
",",
"'show_ids'",
":",
"show_ids",
"}",
"r",
"=",
"requests",... | doc: http://open.youku.com/docs/doc?id=60 | [
"doc",
":",
"http",
":",
"//",
"open",
".",
"youku",
".",
"com",
"/",
"docs",
"/",
"doc?id",
"=",
"60"
] | python | train | 32.272727 |
Erotemic/utool | utool/util_cache.py | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_cache.py#L425-L529 | def make_utool_json_encoder(allow_pickle=False):
"""
References:
http://stackoverflow.com/questions/8230315/python-sets-are
http://stackoverflow.com/questions/11561932/why-does-json
https://github.com/jsonpickle/jsonpickle
http://stackoverflow.com/questions/24369666/typeerror-b1
... | [
"def",
"make_utool_json_encoder",
"(",
"allow_pickle",
"=",
"False",
")",
":",
"import",
"utool",
"as",
"ut",
"PYOBJECT_TAG",
"=",
"'__PYTHON_OBJECT__'",
"UUID_TAG",
"=",
"'__UUID__'",
"SLICE_TAG",
"=",
"'__SLICE__'",
"def",
"decode_pickle",
"(",
"text",
")",
":",... | References:
http://stackoverflow.com/questions/8230315/python-sets-are
http://stackoverflow.com/questions/11561932/why-does-json
https://github.com/jsonpickle/jsonpickle
http://stackoverflow.com/questions/24369666/typeerror-b1
http://stackoverflow.com/questions/30469575/how-to-pi... | [
"References",
":",
"http",
":",
"//",
"stackoverflow",
".",
"com",
"/",
"questions",
"/",
"8230315",
"/",
"python",
"-",
"sets",
"-",
"are",
"http",
":",
"//",
"stackoverflow",
".",
"com",
"/",
"questions",
"/",
"11561932",
"/",
"why",
"-",
"does",
"-"... | python | train | 33.809524 |
openstack/networking-cisco | networking_cisco/apps/saf/server/services/firewall/native/fabric_setup_base.py | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/apps/saf/server/services/firewall/native/fabric_setup_base.py#L1304-L1317 | def delete_dcnm_in_nwk(self, tenant_id, fw_dict, is_fw_virt=False):
"""Delete the DCNM In Network and store the result in DB. """
tenant_name = fw_dict.get('tenant_name')
ret = self._delete_service_nwk(tenant_id, tenant_name, 'in')
if ret:
res = fw_const.DCNM_IN_NETWORK_DEL_S... | [
"def",
"delete_dcnm_in_nwk",
"(",
"self",
",",
"tenant_id",
",",
"fw_dict",
",",
"is_fw_virt",
"=",
"False",
")",
":",
"tenant_name",
"=",
"fw_dict",
".",
"get",
"(",
"'tenant_name'",
")",
"ret",
"=",
"self",
".",
"_delete_service_nwk",
"(",
"tenant_id",
","... | Delete the DCNM In Network and store the result in DB. | [
"Delete",
"the",
"DCNM",
"In",
"Network",
"and",
"store",
"the",
"result",
"in",
"DB",
"."
] | python | train | 47.142857 |
mtomwing/purplex | purplex/grammar.py | https://github.com/mtomwing/purplex/blob/4072109e1d4395826983cd9d95ead2c1dfc1184e/purplex/grammar.py#L132-L158 | def _compute_follow(self):
"""Computes the FOLLOW set for every non-terminal in the grammar.
Tenatively based on _compute_follow in PLY.
"""
self._follow[self.start_symbol].add(END_OF_INPUT)
while True:
changed = False
for nonterminal, productions in se... | [
"def",
"_compute_follow",
"(",
"self",
")",
":",
"self",
".",
"_follow",
"[",
"self",
".",
"start_symbol",
"]",
".",
"add",
"(",
"END_OF_INPUT",
")",
"while",
"True",
":",
"changed",
"=",
"False",
"for",
"nonterminal",
",",
"productions",
"in",
"self",
"... | Computes the FOLLOW set for every non-terminal in the grammar.
Tenatively based on _compute_follow in PLY. | [
"Computes",
"the",
"FOLLOW",
"set",
"for",
"every",
"non",
"-",
"terminal",
"in",
"the",
"grammar",
"."
] | python | valid | 37.814815 |
spyder-ide/spyder | spyder/plugins/console/plugin.py | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/console/plugin.py#L200-L220 | def exception_occurred(self, text, is_traceback):
"""
Exception ocurred in the internal console.
Show a QDialog or the internal console to warn the user.
"""
# Skip errors without traceback or dismiss
if (not is_traceback and self.error_dlg is None) or self.dismis... | [
"def",
"exception_occurred",
"(",
"self",
",",
"text",
",",
"is_traceback",
")",
":",
"# Skip errors without traceback or dismiss\r",
"if",
"(",
"not",
"is_traceback",
"and",
"self",
".",
"error_dlg",
"is",
"None",
")",
"or",
"self",
".",
"dismiss_error",
":",
"... | Exception ocurred in the internal console.
Show a QDialog or the internal console to warn the user. | [
"Exception",
"ocurred",
"in",
"the",
"internal",
"console",
".",
"Show",
"a",
"QDialog",
"or",
"the",
"internal",
"console",
"to",
"warn",
"the",
"user",
"."
] | python | train | 43.619048 |
jantman/awslimitchecker | awslimitchecker/services/vpc.py | https://github.com/jantman/awslimitchecker/blob/e50197f70f3d0abcc5cfc7fde6336f548b790e34/awslimitchecker/services/vpc.py#L216-L228 | def _find_usage_network_interfaces(self):
"""find usage of network interfaces"""
enis = paginate_dict(
self.conn.describe_network_interfaces,
alc_marker_path=['NextToken'],
alc_data_path=['NetworkInterfaces'],
alc_marker_param='NextToken'
)
... | [
"def",
"_find_usage_network_interfaces",
"(",
"self",
")",
":",
"enis",
"=",
"paginate_dict",
"(",
"self",
".",
"conn",
".",
"describe_network_interfaces",
",",
"alc_marker_path",
"=",
"[",
"'NextToken'",
"]",
",",
"alc_data_path",
"=",
"[",
"'NetworkInterfaces'",
... | find usage of network interfaces | [
"find",
"usage",
"of",
"network",
"interfaces"
] | python | train | 36.769231 |
Kane610/deconz | pydeconz/__init__.py | https://github.com/Kane610/deconz/blob/8a9498dbbc8c168d4a081173ad6c3b1e17fffdf6/pydeconz/__init__.py#L132-L143 | def async_session_handler(self, signal: str) -> None:
"""Signalling from websocket.
data - new data available for processing.
state - network state has changed.
"""
if signal == 'data':
self.async_event_handler(self.websocket.data)
elif signal == 'state... | [
"def",
"async_session_handler",
"(",
"self",
",",
"signal",
":",
"str",
")",
"->",
"None",
":",
"if",
"signal",
"==",
"'data'",
":",
"self",
".",
"async_event_handler",
"(",
"self",
".",
"websocket",
".",
"data",
")",
"elif",
"signal",
"==",
"'state'",
"... | Signalling from websocket.
data - new data available for processing.
state - network state has changed. | [
"Signalling",
"from",
"websocket",
"."
] | python | train | 39.583333 |
Gr1N/copypaste | copypaste/win.py | https://github.com/Gr1N/copypaste/blob/7d515d1d31db5ae686378b60e4c8717d7f6834de/copypaste/win.py#L14-L20 | def copy(string):
"""Copy given string into system clipboard.
"""
win32clipboard.OpenClipboard()
win32clipboard.EmptyClipboard()
win32clipboard.SetClipboardText(string)
win32clipboard.CloseClipboard() | [
"def",
"copy",
"(",
"string",
")",
":",
"win32clipboard",
".",
"OpenClipboard",
"(",
")",
"win32clipboard",
".",
"EmptyClipboard",
"(",
")",
"win32clipboard",
".",
"SetClipboardText",
"(",
"string",
")",
"win32clipboard",
".",
"CloseClipboard",
"(",
")"
] | Copy given string into system clipboard. | [
"Copy",
"given",
"string",
"into",
"system",
"clipboard",
"."
] | python | train | 31.142857 |
bunq/sdk_python | bunq/sdk/model/generated/endpoint.py | https://github.com/bunq/sdk_python/blob/da6c9b83e6d83ee8062617f53c6eb7293c0d863d/bunq/sdk/model/generated/endpoint.py#L10002-L10031 | def is_all_field_none(self):
"""
:rtype: bool
"""
if self._id_ is not None:
return False
if self._created is not None:
return False
if self._updated is not None:
return False
if self._action is not None:
return F... | [
"def",
"is_all_field_none",
"(",
"self",
")",
":",
"if",
"self",
".",
"_id_",
"is",
"not",
"None",
":",
"return",
"False",
"if",
"self",
".",
"_created",
"is",
"not",
"None",
":",
"return",
"False",
"if",
"self",
".",
"_updated",
"is",
"not",
"None",
... | :rtype: bool | [
":",
"rtype",
":",
"bool"
] | python | train | 19.433333 |
inasafe/inasafe | safe/report/expressions/map_report.py | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/report/expressions/map_report.py#L256-L274 | def name_of_the_nearest_place(feature, parent):
"""If the impact layer has a distance field, it will return the name
of the nearest place.
e.g. name_of_the_nearest_place() -> Tokyo
"""
_ = feature, parent # NOQA
layer = exposure_summary_layer()
if not layer:
return None
index... | [
"def",
"name_of_the_nearest_place",
"(",
"feature",
",",
"parent",
")",
":",
"_",
"=",
"feature",
",",
"parent",
"# NOQA",
"layer",
"=",
"exposure_summary_layer",
"(",
")",
"if",
"not",
"layer",
":",
"return",
"None",
"index",
"=",
"layer",
".",
"fields",
... | If the impact layer has a distance field, it will return the name
of the nearest place.
e.g. name_of_the_nearest_place() -> Tokyo | [
"If",
"the",
"impact",
"layer",
"has",
"a",
"distance",
"field",
"it",
"will",
"return",
"the",
"name",
"of",
"the",
"nearest",
"place",
"."
] | python | train | 25.263158 |
pgjones/quart | quart/app.py | https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/app.py#L1557-L1574 | async def dispatch_request(
self, request_context: Optional[RequestContext]=None,
) -> ResponseReturnValue:
"""Dispatch the request to the view function.
Arguments:
request_context: The request context, optional as Flask
omits this argument.
"""
r... | [
"async",
"def",
"dispatch_request",
"(",
"self",
",",
"request_context",
":",
"Optional",
"[",
"RequestContext",
"]",
"=",
"None",
",",
")",
"->",
"ResponseReturnValue",
":",
"request_",
"=",
"(",
"request_context",
"or",
"_request_ctx_stack",
".",
"top",
")",
... | Dispatch the request to the view function.
Arguments:
request_context: The request context, optional as Flask
omits this argument. | [
"Dispatch",
"the",
"request",
"to",
"the",
"view",
"function",
"."
] | python | train | 40.555556 |
PMBio/limix-backup | limix/deprecated/archive/qtl_old.py | https://github.com/PMBio/limix-backup/blob/1e201fdb5c694d0d5506f207f3de65d8ef66146c/limix/deprecated/archive/qtl_old.py#L552-L582 | def phenSpecificEffects(snps,pheno1,pheno2,K=None,covs=None,test='lrt'):
"""
Univariate fixed effects interaction test for phenotype specific SNP effects
Args:
snps: [N x S] SP.array of S SNPs for N individuals (test SNPs)
pheno1: [N x 1] SP.array of 1 phenotype for N individuals
... | [
"def",
"phenSpecificEffects",
"(",
"snps",
",",
"pheno1",
",",
"pheno2",
",",
"K",
"=",
"None",
",",
"covs",
"=",
"None",
",",
"test",
"=",
"'lrt'",
")",
":",
"N",
"=",
"snps",
".",
"shape",
"[",
"0",
"]",
"if",
"K",
"is",
"None",
":",
"K",
"="... | Univariate fixed effects interaction test for phenotype specific SNP effects
Args:
snps: [N x S] SP.array of S SNPs for N individuals (test SNPs)
pheno1: [N x 1] SP.array of 1 phenotype for N individuals
pheno2: [N x 1] SP.array of 1 phenotype for N individuals
K: [N x N] SP.... | [
"Univariate",
"fixed",
"effects",
"interaction",
"test",
"for",
"phenotype",
"specific",
"SNP",
"effects"
] | python | train | 45.16129 |
djgagne/hagelslag | hagelslag/util/munkres.py | https://github.com/djgagne/hagelslag/blob/6fb6c3df90bf4867e13a97d3460b14471d107df1/hagelslag/util/munkres.py#L639-L650 | def __find_prime_in_row(self, row):
"""
Find the first prime element in the specified row. Returns
the column index, or -1 if no starred element was found.
"""
col = -1
for j in range(self.n):
if self.marked[row][j] == 2:
col = j
... | [
"def",
"__find_prime_in_row",
"(",
"self",
",",
"row",
")",
":",
"col",
"=",
"-",
"1",
"for",
"j",
"in",
"range",
"(",
"self",
".",
"n",
")",
":",
"if",
"self",
".",
"marked",
"[",
"row",
"]",
"[",
"j",
"]",
"==",
"2",
":",
"col",
"=",
"j",
... | Find the first prime element in the specified row. Returns
the column index, or -1 if no starred element was found. | [
"Find",
"the",
"first",
"prime",
"element",
"in",
"the",
"specified",
"row",
".",
"Returns",
"the",
"column",
"index",
"or",
"-",
"1",
"if",
"no",
"starred",
"element",
"was",
"found",
"."
] | python | train | 28 |
fhcrc/seqmagick | seqmagick/transform.py | https://github.com/fhcrc/seqmagick/blob/1642bb87ba5c171fbd307f9da0f8a0ee1d69d5ed/seqmagick/transform.py#L158-L174 | def isolate_region(sequences, start, end, gap_char='-'):
"""
Replace regions before and after start:end with gap chars
"""
# Check arguments
if end <= start:
raise ValueError("start of slice must precede end ({0} !> {1})".format(
end, start))
for sequence in sequences:
... | [
"def",
"isolate_region",
"(",
"sequences",
",",
"start",
",",
"end",
",",
"gap_char",
"=",
"'-'",
")",
":",
"# Check arguments",
"if",
"end",
"<=",
"start",
":",
"raise",
"ValueError",
"(",
"\"start of slice must precede end ({0} !> {1})\"",
".",
"format",
"(",
... | Replace regions before and after start:end with gap chars | [
"Replace",
"regions",
"before",
"and",
"after",
"start",
":",
"end",
"with",
"gap",
"chars"
] | python | train | 32.823529 |
tomplus/kubernetes_asyncio | kubernetes_asyncio/client/api/extensions_v1beta1_api.py | https://github.com/tomplus/kubernetes_asyncio/blob/f9ab15317ec921409714c7afef11aeb0f579985d/kubernetes_asyncio/client/api/extensions_v1beta1_api.py#L8371-L8394 | def replace_pod_security_policy(self, name, body, **kwargs): # noqa: E501
"""replace_pod_security_policy # noqa: E501
replace the specified PodSecurityPolicy # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_... | [
"def",
"replace_pod_security_policy",
"(",
"self",
",",
"name",
",",
"body",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async_req'",
")",
":",
"return",
... | replace_pod_security_policy # noqa: E501
replace the specified PodSecurityPolicy # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.replace_pod_security_policy(name, body, async_req=Tr... | [
"replace_pod_security_policy",
"#",
"noqa",
":",
"E501"
] | python | train | 59.583333 |
collab-project/django-admin-footer | admin_footer/__init__.py | https://github.com/collab-project/django-admin-footer/blob/55d5b7a4b168fa56f39664091af06820236057c6/admin_footer/__init__.py#L23-L34 | def get_version(version=None):
"""
Return full version nr, inc. rc, beta etc tags.
For example: `2.0.0a1`
:rtype: str
"""
v = version or __version__
if len(v) == 4:
return '{0}{1}'.format(short_version(v), v[3])
return short_version(v) | [
"def",
"get_version",
"(",
"version",
"=",
"None",
")",
":",
"v",
"=",
"version",
"or",
"__version__",
"if",
"len",
"(",
"v",
")",
"==",
"4",
":",
"return",
"'{0}{1}'",
".",
"format",
"(",
"short_version",
"(",
"v",
")",
",",
"v",
"[",
"3",
"]",
... | Return full version nr, inc. rc, beta etc tags.
For example: `2.0.0a1`
:rtype: str | [
"Return",
"full",
"version",
"nr",
"inc",
".",
"rc",
"beta",
"etc",
"tags",
"."
] | python | test | 22.166667 |
inspirehep/plotextractor | plotextractor/converter.py | https://github.com/inspirehep/plotextractor/blob/12a65350fb9f32d496f9ea57908d9a2771b20474/plotextractor/converter.py#L129-L171 | def convert_images(image_list, image_format="png", timeout=20):
"""Convert images from list of images to given format, if needed.
Figure out the types of the images that were extracted from
the tarball and determine how to convert them into PNG.
:param: image_list ([string, string, ...]): the list of ... | [
"def",
"convert_images",
"(",
"image_list",
",",
"image_format",
"=",
"\"png\"",
",",
"timeout",
"=",
"20",
")",
":",
"png_output_contains",
"=",
"'PNG image'",
"image_mapping",
"=",
"{",
"}",
"for",
"image_file",
"in",
"image_list",
":",
"if",
"os",
".",
"p... | Convert images from list of images to given format, if needed.
Figure out the types of the images that were extracted from
the tarball and determine how to convert them into PNG.
:param: image_list ([string, string, ...]): the list of image files
extracted from the tarball in step 1
:param: im... | [
"Convert",
"images",
"from",
"list",
"of",
"images",
"to",
"given",
"format",
"if",
"needed",
"."
] | python | train | 40.837209 |
pazz/urwidtrees | urwidtrees/widgets.py | https://github.com/pazz/urwidtrees/blob/d1fa38ce4f37db00bdfc574b856023b5db4c7ead/urwidtrees/widgets.py#L178-L186 | def collapse_all(self):
"""
Collapse all positions; works only if the underlying tree allows it.
"""
if implementsCollapseAPI(self._tree):
self._tree.collapse_all()
self.set_focus(self._tree.root)
self._walker.clear_cache()
self.refresh() | [
"def",
"collapse_all",
"(",
"self",
")",
":",
"if",
"implementsCollapseAPI",
"(",
"self",
".",
"_tree",
")",
":",
"self",
".",
"_tree",
".",
"collapse_all",
"(",
")",
"self",
".",
"set_focus",
"(",
"self",
".",
"_tree",
".",
"root",
")",
"self",
".",
... | Collapse all positions; works only if the underlying tree allows it. | [
"Collapse",
"all",
"positions",
";",
"works",
"only",
"if",
"the",
"underlying",
"tree",
"allows",
"it",
"."
] | python | train | 34.444444 |
susam/ice | ice.py | https://github.com/susam/ice/blob/532e685c504ea96f9e42833594585159ac1d2068/ice.py#L835-L849 | def content_type(self):
"""Return the value of Content-Type header field.
The value for the Content-Type header field is determined from
the :attr:`media_type` and :attr:`charset` data attributes.
Returns:
str: Value of Content-Type header field
"""
if (self.m... | [
"def",
"content_type",
"(",
"self",
")",
":",
"if",
"(",
"self",
".",
"media_type",
"is",
"not",
"None",
"and",
"self",
".",
"media_type",
".",
"startswith",
"(",
"'text/'",
")",
"and",
"self",
".",
"charset",
"is",
"not",
"None",
")",
":",
"return",
... | Return the value of Content-Type header field.
The value for the Content-Type header field is determined from
the :attr:`media_type` and :attr:`charset` data attributes.
Returns:
str: Value of Content-Type header field | [
"Return",
"the",
"value",
"of",
"Content",
"-",
"Type",
"header",
"field",
"."
] | python | test | 35.733333 |
JdeRobot/base | src/drivers/MAVLinkServer/MAVProxy/modules/mavproxy_dataflash_logger.py | https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/modules/mavproxy_dataflash_logger.py#L82-L96 | def new_log_filepath(self):
'''returns a filepath to a log which does not currently exist and is suitable for DF logging'''
lastlog_filename = os.path.join(self.dataflash_dir,'LASTLOG.TXT')
if os.path.exists(lastlog_filename) and os.stat(lastlog_filename).st_size != 0:
fh = open(last... | [
"def",
"new_log_filepath",
"(",
"self",
")",
":",
"lastlog_filename",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"dataflash_dir",
",",
"'LASTLOG.TXT'",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"lastlog_filename",
")",
"and",
"os",
".... | returns a filepath to a log which does not currently exist and is suitable for DF logging | [
"returns",
"a",
"filepath",
"to",
"a",
"log",
"which",
"does",
"not",
"currently",
"exist",
"and",
"is",
"suitable",
"for",
"DF",
"logging"
] | python | train | 42.8 |
IBM/pyxcli | pyxcli/client.py | https://github.com/IBM/pyxcli/blob/7d8ece1dcc16f50246740a447aa81b94a0dbced4/pyxcli/client.py#L331-L341 | def get_remote_client(self, target_name, user=None, password=None):
"""
Returns a new client for the remote target. This is a lightweight
client that only uses different credentials and shares the transport
with the underlying client
"""
if user:
base = self.g... | [
"def",
"get_remote_client",
"(",
"self",
",",
"target_name",
",",
"user",
"=",
"None",
",",
"password",
"=",
"None",
")",
":",
"if",
"user",
":",
"base",
"=",
"self",
".",
"get_user_client",
"(",
"user",
",",
"password",
",",
"populate",
"=",
"False",
... | Returns a new client for the remote target. This is a lightweight
client that only uses different credentials and shares the transport
with the underlying client | [
"Returns",
"a",
"new",
"client",
"for",
"the",
"remote",
"target",
".",
"This",
"is",
"a",
"lightweight",
"client",
"that",
"only",
"uses",
"different",
"credentials",
"and",
"shares",
"the",
"transport",
"with",
"the",
"underlying",
"client"
] | python | train | 42.818182 |
crs4/pydoop | pydoop/hdfs/__init__.py | https://github.com/crs4/pydoop/blob/f375be2a06f9c67eaae3ce6f605195dbca143b2b/pydoop/hdfs/__init__.py#L146-L159 | def load(hdfs_path, **kwargs):
"""\
Read the content of ``hdfs_path`` and return it.
Keyword arguments are passed to :func:`open`. The `"mode"` kwarg
must be readonly.
"""
m, _ = common.parse_mode(kwargs.get("mode", "r"))
if m != "r":
raise ValueError("opening mode must be readonly"... | [
"def",
"load",
"(",
"hdfs_path",
",",
"*",
"*",
"kwargs",
")",
":",
"m",
",",
"_",
"=",
"common",
".",
"parse_mode",
"(",
"kwargs",
".",
"get",
"(",
"\"mode\"",
",",
"\"r\"",
")",
")",
"if",
"m",
"!=",
"\"r\"",
":",
"raise",
"ValueError",
"(",
"\... | \
Read the content of ``hdfs_path`` and return it.
Keyword arguments are passed to :func:`open`. The `"mode"` kwarg
must be readonly. | [
"\\",
"Read",
"the",
"content",
"of",
"hdfs_path",
"and",
"return",
"it",
"."
] | python | train | 29.214286 |
Chilipp/psyplot | psyplot/project.py | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/project.py#L1953-L1973 | def _add_data(self, plotter_cls, *args, **kwargs):
"""
Add new plots to the project
Parameters
----------
%(ProjectPlotter._add_data.parameters.no_filename_or_obj)s
Other Parameters
----------------
%(ProjectPlotter._add_data.other_parameters)s
... | [
"def",
"_add_data",
"(",
"self",
",",
"plotter_cls",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# this method is just a shortcut to the :meth:`Project._add_data`",
"# method but is reimplemented by subclasses as the",
"# :class:`DatasetPlotter` or the :class:`DataArrayPl... | Add new plots to the project
Parameters
----------
%(ProjectPlotter._add_data.parameters.no_filename_or_obj)s
Other Parameters
----------------
%(ProjectPlotter._add_data.other_parameters)s
Returns
-------
%(ProjectPlotter._add_data.returns)s | [
"Add",
"new",
"plots",
"to",
"the",
"project"
] | python | train | 34.571429 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.