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 |
|---|---|---|---|---|---|---|---|---|---|
iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/msvs.py | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/msvs.py#L1858-L1912 | def solutionEmitter(target, source, env):
"""Sets up the DSW dependencies."""
# todo: Not sure what sets source to what user has passed as target,
# but this is what happens. When that is fixed, we also won't have
# to make the user always append env['MSVSSOLUTIONSUFFIX'] to target.
if source[0] ==... | [
"def",
"solutionEmitter",
"(",
"target",
",",
"source",
",",
"env",
")",
":",
"# todo: Not sure what sets source to what user has passed as target,",
"# but this is what happens. When that is fixed, we also won't have",
"# to make the user always append env['MSVSSOLUTIONSUFFIX'] to target.",... | Sets up the DSW dependencies. | [
"Sets",
"up",
"the",
"DSW",
"dependencies",
"."
] | python | train | 39.709091 |
yyuu/botornado | boto/ec2/connection.py | https://github.com/yyuu/botornado/blob/fffb056f5ff2324d1d5c1304014cfb1d899f602e/boto/ec2/connection.py#L1126-L1154 | def get_all_zones(self, zones=None, filters=None):
"""
Get all Availability Zones associated with the current region.
:type zones: list
:param zones: Optional list of zones. If this list is present,
only the Zones associated with these zone names
... | [
"def",
"get_all_zones",
"(",
"self",
",",
"zones",
"=",
"None",
",",
"filters",
"=",
"None",
")",
":",
"params",
"=",
"{",
"}",
"if",
"zones",
":",
"self",
".",
"build_list_params",
"(",
"params",
",",
"zones",
",",
"'ZoneName'",
")",
"if",
"filters",
... | Get all Availability Zones associated with the current region.
:type zones: list
:param zones: Optional list of zones. If this list is present,
only the Zones associated with these zone names
will be returned.
:type filters: dict
:param filt... | [
"Get",
"all",
"Availability",
"Zones",
"associated",
"with",
"the",
"current",
"region",
"."
] | python | train | 43.241379 |
getpelican/pelican-plugins | filetime_from_git/content_adapter.py | https://github.com/getpelican/pelican-plugins/blob/cfc7a3f224f1743063b034561f89a6a712d13587/filetime_from_git/content_adapter.py#L54-L60 | def get_oldest_commit(self):
'''
Get oldest commit involving this file
:returns: Oldest commit
'''
return self.git.get_commits(self.content.source_path, self.follow)[-1] | [
"def",
"get_oldest_commit",
"(",
"self",
")",
":",
"return",
"self",
".",
"git",
".",
"get_commits",
"(",
"self",
".",
"content",
".",
"source_path",
",",
"self",
".",
"follow",
")",
"[",
"-",
"1",
"]"
] | Get oldest commit involving this file
:returns: Oldest commit | [
"Get",
"oldest",
"commit",
"involving",
"this",
"file"
] | python | train | 29.142857 |
unfoldingWord-dev/python-gogs-client | gogs_client/interface.py | https://github.com/unfoldingWord-dev/python-gogs-client/blob/b7f27f4995abf914c0db8a424760f5b27331939d/gogs_client/interface.py#L447-L460 | def delete_hook(self, auth, username, repo_name, hook_id):
"""
Deletes the hook with id ``hook_id`` for repo with name ``repo_name``
owned by the user with username ``username``.
:param auth.Authentication auth: authentication object
:param str username: username of owner of rep... | [
"def",
"delete_hook",
"(",
"self",
",",
"auth",
",",
"username",
",",
"repo_name",
",",
"hook_id",
")",
":",
"path",
"=",
"\"/repos/{u}/{r}/hooks/{i}\"",
".",
"format",
"(",
"u",
"=",
"username",
",",
"r",
"=",
"repo_name",
",",
"i",
"=",
"hook_id",
")",... | Deletes the hook with id ``hook_id`` for repo with name ``repo_name``
owned by the user with username ``username``.
:param auth.Authentication auth: authentication object
:param str username: username of owner of repository
:param str repo_name: name of repository of hook to delete
... | [
"Deletes",
"the",
"hook",
"with",
"id",
"hook_id",
"for",
"repo",
"with",
"name",
"repo_name",
"owned",
"by",
"the",
"user",
"with",
"username",
"username",
"."
] | python | train | 50.642857 |
xtuml/pyxtuml | xtuml/consistency_check.py | https://github.com/xtuml/pyxtuml/blob/7dd9343b9a0191d1db1887ab9288d0a026608d9a/xtuml/consistency_check.py#L133-L149 | def check_link_integrity(m, link):
'''
Check the model for integrity violations on an association in a particular direction.
'''
res = 0
for inst in link.from_metaclass.select_many():
q_set = list(link.navigate(inst))
if(len(q_set) < 1 and not link.conditional) or (
(len(q... | [
"def",
"check_link_integrity",
"(",
"m",
",",
"link",
")",
":",
"res",
"=",
"0",
"for",
"inst",
"in",
"link",
".",
"from_metaclass",
".",
"select_many",
"(",
")",
":",
"q_set",
"=",
"list",
"(",
"link",
".",
"navigate",
"(",
"inst",
")",
")",
"if",
... | Check the model for integrity violations on an association in a particular direction. | [
"Check",
"the",
"model",
"for",
"integrity",
"violations",
"on",
"an",
"association",
"in",
"a",
"particular",
"direction",
"."
] | python | test | 37.882353 |
pseudonym117/Riot-Watcher | src/riotwatcher/_apis/LolStatusApiV3.py | https://github.com/pseudonym117/Riot-Watcher/blob/21ab12453a0d824d67e30f5514d02a5c5a411dea/src/riotwatcher/_apis/LolStatusApiV3.py#L20-L31 | def shard_data(self, region):
"""
Get League of Legends status for the given shard.
Requests to this API are not counted against the application Rate Limits.
:param string region: the region to execute this request on
:returns: ShardStatus
"""
url, query = LolS... | [
"def",
"shard_data",
"(",
"self",
",",
"region",
")",
":",
"url",
",",
"query",
"=",
"LolStatusApiV3Urls",
".",
"shard_data",
"(",
"region",
"=",
"region",
")",
"return",
"self",
".",
"_raw_request",
"(",
"self",
".",
"shard_data",
".",
"__name__",
",",
... | Get League of Legends status for the given shard.
Requests to this API are not counted against the application Rate Limits.
:param string region: the region to execute this request on
:returns: ShardStatus | [
"Get",
"League",
"of",
"Legends",
"status",
"for",
"the",
"given",
"shard",
"."
] | python | train | 35.666667 |
facebook/pyre-check | client/buck.py | https://github.com/facebook/pyre-check/blob/4a9604d943d28ef20238505a51acfb1f666328d7/client/buck.py#L32-L39 | def build(self, targets: Iterable[str]) -> Iterable[str]:
"""
Shell out to buck to build the targets, then yield the paths to the
link trees.
"""
return generate_source_directories(
targets, build=self._build, prompt=self._prompt
) | [
"def",
"build",
"(",
"self",
",",
"targets",
":",
"Iterable",
"[",
"str",
"]",
")",
"->",
"Iterable",
"[",
"str",
"]",
":",
"return",
"generate_source_directories",
"(",
"targets",
",",
"build",
"=",
"self",
".",
"_build",
",",
"prompt",
"=",
"self",
"... | Shell out to buck to build the targets, then yield the paths to the
link trees. | [
"Shell",
"out",
"to",
"buck",
"to",
"build",
"the",
"targets",
"then",
"yield",
"the",
"paths",
"to",
"the",
"link",
"trees",
"."
] | python | train | 36.5 |
dossier/dossier.web | dossier/web/builder.py | https://github.com/dossier/dossier.web/blob/1cad1cce3c37d3a4e956abc710a2bc1afe16a092/dossier/web/builder.py#L295-L327 | def create_injector(param_name, fun_param_value):
'''Dependency injection with Bottle.
This creates a simple dependency injector that will map
``param_name`` in routes to the value ``fun_param_value()``
each time the route is invoked.
``fun_param_value`` is a closure so that it is lazily evaluated... | [
"def",
"create_injector",
"(",
"param_name",
",",
"fun_param_value",
")",
":",
"class",
"_",
"(",
"object",
")",
":",
"api",
"=",
"2",
"def",
"apply",
"(",
"self",
",",
"callback",
",",
"route",
")",
":",
"if",
"param_name",
"not",
"in",
"inspect",
"."... | Dependency injection with Bottle.
This creates a simple dependency injector that will map
``param_name`` in routes to the value ``fun_param_value()``
each time the route is invoked.
``fun_param_value`` is a closure so that it is lazily evaluated.
This is useful for handling thread local services l... | [
"Dependency",
"injection",
"with",
"Bottle",
"."
] | python | train | 36.515152 |
modin-project/modin | modin/backends/pandas/query_compiler.py | https://github.com/modin-project/modin/blob/5b77d242596560c646b8405340c9ce64acb183cb/modin/backends/pandas/query_compiler.py#L141-L165 | def _prepare_method(self, pandas_func, **kwargs):
"""Prepares methods given various metadata.
Args:
pandas_func: The function to prepare.
Returns
Helper function which handles potential transpose.
"""
if self._is_transposed:
def helper(df, in... | [
"def",
"_prepare_method",
"(",
"self",
",",
"pandas_func",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"_is_transposed",
":",
"def",
"helper",
"(",
"df",
",",
"internal_indices",
"=",
"[",
"]",
")",
":",
"if",
"len",
"(",
"internal_indices",
... | Prepares methods given various metadata.
Args:
pandas_func: The function to prepare.
Returns
Helper function which handles potential transpose. | [
"Prepares",
"methods",
"given",
"various",
"metadata",
".",
"Args",
":",
"pandas_func",
":",
"The",
"function",
"to",
"prepare",
"."
] | python | train | 32.76 |
knagra/farnsworth | base/views.py | https://github.com/knagra/farnsworth/blob/1b6589f0d9fea154f0a1e2231ed906764ed26d26/base/views.py#L803-L959 | def get_updates_view(request):
"""Return a user's updates. AJAX."""
if not request.is_ajax():
raise Http404
if not request.user.is_authenticated():
return HttpResponse(json.dumps(dict()),
content_type="application/json")
try:
user_profile = UserProfi... | [
"def",
"get_updates_view",
"(",
"request",
")",
":",
"if",
"not",
"request",
".",
"is_ajax",
"(",
")",
":",
"raise",
"Http404",
"if",
"not",
"request",
".",
"user",
".",
"is_authenticated",
"(",
")",
":",
"return",
"HttpResponse",
"(",
"json",
".",
"dump... | Return a user's updates. AJAX. | [
"Return",
"a",
"user",
"s",
"updates",
".",
"AJAX",
"."
] | python | train | 37.33758 |
Autodesk/aomi | aomi/filez.py | https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/filez.py#L55-L67 | def freeze_archive(tmp_dir, dest_prefix):
"""Generates a ZIP file of secrets"""
zip_filename = "%s/aomi-blah.zip" % tmp_dir
archive = zipfile.ZipFile(zip_filename, 'w')
for root, _dirnames, filenames in os.walk(dest_prefix):
for filename in filenames:
relative_path = subdir_path(root... | [
"def",
"freeze_archive",
"(",
"tmp_dir",
",",
"dest_prefix",
")",
":",
"zip_filename",
"=",
"\"%s/aomi-blah.zip\"",
"%",
"tmp_dir",
"archive",
"=",
"zipfile",
".",
"ZipFile",
"(",
"zip_filename",
",",
"'w'",
")",
"for",
"root",
",",
"_dirnames",
",",
"filename... | Generates a ZIP file of secrets | [
"Generates",
"a",
"ZIP",
"file",
"of",
"secrets"
] | python | train | 42.846154 |
calmjs/calmjs.parse | src/calmjs/parse/parsers/es5.py | https://github.com/calmjs/calmjs.parse/blob/369f0ee346c5a84c4d5c35a7733a0e63b02eac59/src/calmjs/parse/parsers/es5.py#L332-L340 | def p_array_literal_2(self, p):
"""array_literal : LBRACKET element_list RBRACKET
| LBRACKET element_list COMMA elision_opt RBRACKET
"""
items = p[2]
if len(p) == 6:
items.extend(p[4])
p[0] = self.asttypes.Array(items=items)
p[0].setpo... | [
"def",
"p_array_literal_2",
"(",
"self",
",",
"p",
")",
":",
"items",
"=",
"p",
"[",
"2",
"]",
"if",
"len",
"(",
"p",
")",
"==",
"6",
":",
"items",
".",
"extend",
"(",
"p",
"[",
"4",
"]",
")",
"p",
"[",
"0",
"]",
"=",
"self",
".",
"asttypes... | array_literal : LBRACKET element_list RBRACKET
| LBRACKET element_list COMMA elision_opt RBRACKET | [
"array_literal",
":",
"LBRACKET",
"element_list",
"RBRACKET",
"|",
"LBRACKET",
"element_list",
"COMMA",
"elision_opt",
"RBRACKET"
] | python | train | 35.111111 |
AliLozano/django-messages-extends | messages_extends/storages.py | https://github.com/AliLozano/django-messages-extends/blob/141011981d44a6f28c6e82f9832815423b3b205f/messages_extends/storages.py#L54-L71 | def _get(self, *args, **kwargs):
"""
Gets a single list of messages from all storage backends.
"""
all_messages = []
for storage in self.storages:
messages, all_retrieved = storage._get()
# If the backend hasn't been used, no more retrieval is necessary.
... | [
"def",
"_get",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"all_messages",
"=",
"[",
"]",
"for",
"storage",
"in",
"self",
".",
"storages",
":",
"messages",
",",
"all_retrieved",
"=",
"storage",
".",
"_get",
"(",
")",
"# If the b... | Gets a single list of messages from all storage backends. | [
"Gets",
"a",
"single",
"list",
"of",
"messages",
"from",
"all",
"storage",
"backends",
"."
] | python | train | 37.722222 |
shonenada/flask-rbac | flask_rbac/__init__.py | https://github.com/shonenada/flask-rbac/blob/e085121ff11825114e2d6f8419f0b6de6f9ba476/flask_rbac/__init__.py#L91-L98 | def is_allowed(self, role, method, resource):
"""Check whether role is allowed to access resource
:param role: Role to be checked.
:param method: Method to be checked.
:param resource: View function to be checked.
"""
return (role, method, resource) in self._allowed | [
"def",
"is_allowed",
"(",
"self",
",",
"role",
",",
"method",
",",
"resource",
")",
":",
"return",
"(",
"role",
",",
"method",
",",
"resource",
")",
"in",
"self",
".",
"_allowed"
] | Check whether role is allowed to access resource
:param role: Role to be checked.
:param method: Method to be checked.
:param resource: View function to be checked. | [
"Check",
"whether",
"role",
"is",
"allowed",
"to",
"access",
"resource"
] | python | valid | 38.5 |
howl-anderson/MicroTokenizer | MicroTokenizer/util.py | https://github.com/howl-anderson/MicroTokenizer/blob/41bbe9c31d202b4f751ad5201d343ad1123b42b5/MicroTokenizer/util.py#L405-L419 | def _wrap(text, wrap_max=80, indent=4):
"""Wrap text at given width using textwrap module.
text (unicode): Text to wrap. If it's a Path, it's converted to string.
wrap_max (int): Maximum line length (indent is deducted).
indent (int): Number of spaces for indentation.
RETURNS (unicode): Wrapped tex... | [
"def",
"_wrap",
"(",
"text",
",",
"wrap_max",
"=",
"80",
",",
"indent",
"=",
"4",
")",
":",
"indent",
"=",
"indent",
"*",
"' '",
"wrap_width",
"=",
"wrap_max",
"-",
"len",
"(",
"indent",
")",
"if",
"isinstance",
"(",
"text",
",",
"Path",
")",
":",
... | Wrap text at given width using textwrap module.
text (unicode): Text to wrap. If it's a Path, it's converted to string.
wrap_max (int): Maximum line length (indent is deducted).
indent (int): Number of spaces for indentation.
RETURNS (unicode): Wrapped text. | [
"Wrap",
"text",
"at",
"given",
"width",
"using",
"textwrap",
"module",
"."
] | python | train | 42.6 |
akfullfo/taskforce | taskforce/task.py | https://github.com/akfullfo/taskforce/blob/bc6dd744bd33546447d085dbd18a350532220193/taskforce/task.py#L1336-L1353 | def file_add(self, ev, paths):
"""
Register for file change events. If there is a change to the file, all
registered tasks will be notified with a call t.event(action).
Note that as multiple tasks might register an event on the same
path, each path is mapped to a dict of tasks ... | [
"def",
"file_add",
"(",
"self",
",",
"ev",
",",
"paths",
")",
":",
"log",
"=",
"self",
".",
"_params",
".",
"get",
"(",
"'log'",
",",
"self",
".",
"_discard",
")",
"if",
"not",
"isinstance",
"(",
"paths",
",",
"list",
")",
":",
"paths",
"=",
"[",... | Register for file change events. If there is a change to the file, all
registered tasks will be notified with a call t.event(action).
Note that as multiple tasks might register an event on the same
path, each path is mapped to a dict of tasks pointing at actions.
A task can only regist... | [
"Register",
"for",
"file",
"change",
"events",
".",
"If",
"there",
"is",
"a",
"change",
"to",
"the",
"file",
"all",
"registered",
"tasks",
"will",
"be",
"notified",
"with",
"a",
"call",
"t",
".",
"event",
"(",
"action",
")",
"."
] | python | train | 48 |
joke2k/faker | faker/providers/__init__.py | https://github.com/joke2k/faker/blob/965824b61132e52d92d1a6ce470396dbbe01c96c/faker/providers/__init__.py#L243-L248 | def random_sample(self, elements=('a', 'b', 'c'), length=None):
"""
Returns a list of random unique elements for the specified length.
Multiple occurrences of the same value increase its probability to be in the output.
"""
return self.random_elements(elements, length, unique=Tru... | [
"def",
"random_sample",
"(",
"self",
",",
"elements",
"=",
"(",
"'a'",
",",
"'b'",
",",
"'c'",
")",
",",
"length",
"=",
"None",
")",
":",
"return",
"self",
".",
"random_elements",
"(",
"elements",
",",
"length",
",",
"unique",
"=",
"True",
")"
] | Returns a list of random unique elements for the specified length.
Multiple occurrences of the same value increase its probability to be in the output. | [
"Returns",
"a",
"list",
"of",
"random",
"unique",
"elements",
"for",
"the",
"specified",
"length",
".",
"Multiple",
"occurrences",
"of",
"the",
"same",
"value",
"increase",
"its",
"probability",
"to",
"be",
"in",
"the",
"output",
"."
] | python | train | 52.833333 |
joke2k/faker | faker/cli.py | https://github.com/joke2k/faker/blob/965824b61132e52d92d1a6ce470396dbbe01c96c/faker/cli.py#L127-L264 | def execute(self):
"""
Given the command-line arguments, this creates a parser appropriate
to that command, and runs it.
"""
# retrieve default language from system environment
default_locale = os.environ.get('LANG', 'en_US').split('.')[0]
if default_locale not i... | [
"def",
"execute",
"(",
"self",
")",
":",
"# retrieve default language from system environment",
"default_locale",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'LANG'",
",",
"'en_US'",
")",
".",
"split",
"(",
"'.'",
")",
"[",
"0",
"]",
"if",
"default_locale",
... | Given the command-line arguments, this creates a parser appropriate
to that command, and runs it. | [
"Given",
"the",
"command",
"-",
"line",
"arguments",
"this",
"creates",
"a",
"parser",
"appropriate",
"to",
"that",
"command",
"and",
"runs",
"it",
"."
] | python | train | 37.673913 |
interstar/FSQuery | fsquery/fsquery.py | https://github.com/interstar/FSQuery/blob/5f57dffeefde4f601af98db9f8ba4177c620dbbd/fsquery/fsquery.py#L155-L175 | def walk(self,depth=0,fsNode=None) :
"""Note, this is a filtered walk"""
if not fsNode :
fsNode = FSNode(self.init_path,self.init_path,0)
if fsNode.isdir() :
if self.check_dir(fsNode) :
if self.check_return(fsNode) :
yield ... | [
"def",
"walk",
"(",
"self",
",",
"depth",
"=",
"0",
",",
"fsNode",
"=",
"None",
")",
":",
"if",
"not",
"fsNode",
":",
"fsNode",
"=",
"FSNode",
"(",
"self",
".",
"init_path",
",",
"self",
".",
"init_path",
",",
"0",
")",
"if",
"fsNode",
".",
"isdi... | Note, this is a filtered walk | [
"Note",
"this",
"is",
"a",
"filtered",
"walk"
] | python | train | 38.047619 |
zetaops/zengine | zengine/lib/translation.py | https://github.com/zetaops/zengine/blob/b5bc32d3b37bca799f8985be916f04528ac79e4a/zengine/lib/translation.py#L89-L107 | def install_language(cls, language_code):
"""Install the translations for language specified by `language_code`.
If we don't have translations for this language, then the default language will be used.
If the language specified is already installed, then this is a no-op.
"""
# ... | [
"def",
"install_language",
"(",
"cls",
",",
"language_code",
")",
":",
"# Skip if the language is already installed",
"if",
"language_code",
"==",
"cls",
".",
"language",
":",
"return",
"try",
":",
"cls",
".",
"_active_catalogs",
"=",
"cls",
".",
"_translation_catal... | Install the translations for language specified by `language_code`.
If we don't have translations for this language, then the default language will be used.
If the language specified is already installed, then this is a no-op. | [
"Install",
"the",
"translations",
"for",
"language",
"specified",
"by",
"language_code",
"."
] | python | train | 45.315789 |
erikrose/more-itertools | more_itertools/more.py | https://github.com/erikrose/more-itertools/blob/6a91b4e25c8e12fcf9fc2b53cf8ee0fba293e6f9/more_itertools/more.py#L715-L746 | def substrings_indexes(seq, reverse=False):
"""Yield all substrings and their positions in *seq*
The items yielded will be a tuple of the form ``(substr, i, j)``, where
``substr == seq[i:j]``.
This function only works for iterables that support slicing, such as
``str`` objects.
>>> for item i... | [
"def",
"substrings_indexes",
"(",
"seq",
",",
"reverse",
"=",
"False",
")",
":",
"r",
"=",
"range",
"(",
"1",
",",
"len",
"(",
"seq",
")",
"+",
"1",
")",
"if",
"reverse",
":",
"r",
"=",
"reversed",
"(",
"r",
")",
"return",
"(",
"(",
"seq",
"[",... | Yield all substrings and their positions in *seq*
The items yielded will be a tuple of the form ``(substr, i, j)``, where
``substr == seq[i:j]``.
This function only works for iterables that support slicing, such as
``str`` objects.
>>> for item in substrings_indexes('more'):
... print(item... | [
"Yield",
"all",
"substrings",
"and",
"their",
"positions",
"in",
"*",
"seq",
"*"
] | python | train | 23.9375 |
jic-dtool/dtoolcore | dtoolcore/__init__.py | https://github.com/jic-dtool/dtoolcore/blob/eeb9a924dc8fcf543340653748a7877be1f98e0f/dtoolcore/__init__.py#L492-L524 | def freeze(self, progressbar=None):
"""
Convert :class:`dtoolcore.ProtoDataSet` to :class:`dtoolcore.DataSet`.
"""
# Call the storage broker pre_freeze hook.
self._storage_broker.pre_freeze_hook()
if progressbar:
progressbar.label = "Freezing dataset"
... | [
"def",
"freeze",
"(",
"self",
",",
"progressbar",
"=",
"None",
")",
":",
"# Call the storage broker pre_freeze hook.",
"self",
".",
"_storage_broker",
".",
"pre_freeze_hook",
"(",
")",
"if",
"progressbar",
":",
"progressbar",
".",
"label",
"=",
"\"Freezing dataset\"... | Convert :class:`dtoolcore.ProtoDataSet` to :class:`dtoolcore.DataSet`. | [
"Convert",
":",
"class",
":",
"dtoolcore",
".",
"ProtoDataSet",
"to",
":",
"class",
":",
"dtoolcore",
".",
"DataSet",
"."
] | python | train | 38.30303 |
thebjorn/pydeps | pydeps/mf27.py | https://github.com/thebjorn/pydeps/blob/1e6715b7bea47a40e8042821b57937deaaa0fdc3/pydeps/mf27.py#L553-L588 | def report(self): # pragma: nocover
"""Print a report to stdout, listing the found modules with their
paths, as well as modules that are missing, or seem to be missing.
"""
print()
print(" %-25s %s" % ("Name", "File"))
print(" %-25s %s" % ("----", "----"))
# Pr... | [
"def",
"report",
"(",
"self",
")",
":",
"# pragma: nocover",
"print",
"(",
")",
"print",
"(",
"\" %-25s %s\"",
"%",
"(",
"\"Name\"",
",",
"\"File\"",
")",
")",
"print",
"(",
"\" %-25s %s\"",
"%",
"(",
"\"----\"",
",",
"\"----\"",
")",
")",
"# Print modul... | Print a report to stdout, listing the found modules with their
paths, as well as modules that are missing, or seem to be missing. | [
"Print",
"a",
"report",
"to",
"stdout",
"listing",
"the",
"found",
"modules",
"with",
"their",
"paths",
"as",
"well",
"as",
"modules",
"that",
"are",
"missing",
"or",
"seem",
"to",
"be",
"missing",
"."
] | python | train | 38.222222 |
sphinx-gallery/sphinx-gallery | sphinx_gallery/notebook.py | https://github.com/sphinx-gallery/sphinx-gallery/blob/b0c1f6701bf3f4cef238757e1105cf3686b5e674/sphinx_gallery/notebook.py#L104-L120 | def jupyter_notebook(script_blocks, gallery_conf):
"""Generate a Jupyter notebook file cell-by-cell
Parameters
----------
script_blocks : list
Script execution cells.
gallery_conf : dict
The sphinx-gallery configuration dictionary.
"""
first_cell = gallery_conf.get("first_no... | [
"def",
"jupyter_notebook",
"(",
"script_blocks",
",",
"gallery_conf",
")",
":",
"first_cell",
"=",
"gallery_conf",
".",
"get",
"(",
"\"first_notebook_cell\"",
",",
"\"%matplotlib inline\"",
")",
"work_notebook",
"=",
"jupyter_notebook_skeleton",
"(",
")",
"if",
"first... | Generate a Jupyter notebook file cell-by-cell
Parameters
----------
script_blocks : list
Script execution cells.
gallery_conf : dict
The sphinx-gallery configuration dictionary. | [
"Generate",
"a",
"Jupyter",
"notebook",
"file",
"cell",
"-",
"by",
"-",
"cell"
] | python | train | 31.823529 |
seznam/shelter | shelter/contrib/config/iniconfig.py | https://github.com/seznam/shelter/blob/c652b0ff1cca70158f8fc97d9210c1fa5961ac1c/shelter/contrib/config/iniconfig.py#L138-L183 | def interfaces(self):
"""
Interfaces as a :class:`list`of the
:class:`shelter.core.config.Config.Interface` instances.
"""
if 'interfaces' not in self._cached_values:
self._cached_values['interfaces'] = []
for name, interface in six.iteritems(self.settings... | [
"def",
"interfaces",
"(",
"self",
")",
":",
"if",
"'interfaces'",
"not",
"in",
"self",
".",
"_cached_values",
":",
"self",
".",
"_cached_values",
"[",
"'interfaces'",
"]",
"=",
"[",
"]",
"for",
"name",
",",
"interface",
"in",
"six",
".",
"iteritems",
"("... | Interfaces as a :class:`list`of the
:class:`shelter.core.config.Config.Interface` instances. | [
"Interfaces",
"as",
"a",
":",
"class",
":",
"list",
"of",
"the",
":",
"class",
":",
"shelter",
".",
"core",
".",
"config",
".",
"Config",
".",
"Interface",
"instances",
"."
] | python | train | 43.413043 |
partofthething/ace | ace/model.py | https://github.com/partofthething/ace/blob/1593a49f3c2e845514323e9c36ee253fe77bac3c/ace/model.py#L18-L41 | def read_column_data_from_txt(fname):
"""
Read data from a simple text file.
Format should be just numbers.
First column is the dependent variable. others are independent.
Whitespace delimited.
Returns
-------
x_values : list
List of x columns
y_values : list
list o... | [
"def",
"read_column_data_from_txt",
"(",
"fname",
")",
":",
"datafile",
"=",
"open",
"(",
"fname",
")",
"datarows",
"=",
"[",
"]",
"for",
"line",
"in",
"datafile",
":",
"datarows",
".",
"append",
"(",
"[",
"float",
"(",
"li",
")",
"for",
"li",
"in",
... | Read data from a simple text file.
Format should be just numbers.
First column is the dependent variable. others are independent.
Whitespace delimited.
Returns
-------
x_values : list
List of x columns
y_values : list
list of y values | [
"Read",
"data",
"from",
"a",
"simple",
"text",
"file",
"."
] | python | train | 23.666667 |
estnltk/estnltk | estnltk/mw_verbs/verbchain_detector.py | https://github.com/estnltk/estnltk/blob/28ae334a68a0673072febc318635f04da0dcc54a/estnltk/mw_verbs/verbchain_detector.py#L460-L595 | def detectVerbChainsFromSent( self, sentence, **kwargs):
''' Detect verb chains from given sentence.
Parameters
----------
sentence: list of dict
A list of sentence words, each word in form of a dictionary containing
morphological analysis and clause bou... | [
"def",
"detectVerbChainsFromSent",
"(",
"self",
",",
"sentence",
",",
"*",
"*",
"kwargs",
")",
":",
"# 0) Parse given arguments\r",
"expand2ndTime",
"=",
"False",
"removeOverlapping",
"=",
"True",
"removeSingleAraEi",
"=",
"True",
"breakOnPunctuation",
"=",
"False",
... | Detect verb chains from given sentence.
Parameters
----------
sentence: list of dict
A list of sentence words, each word in form of a dictionary containing
morphological analysis and clause boundary annotations (must have CLAUSE_IDX);
Keyword p... | [
"Detect",
"verb",
"chains",
"from",
"given",
"sentence",
".",
"Parameters",
"----------",
"sentence",
":",
"list",
"of",
"dict",
"A",
"list",
"of",
"sentence",
"words",
"each",
"word",
"in",
"form",
"of",
"a",
"dictionary",
"containing",
"morphological",
"anal... | python | train | 57.492647 |
RLBot/RLBot | src/main/python/rlbot/gui/qt_root.py | https://github.com/RLBot/RLBot/blob/3f9b6bec8b9baf4dcfff0f6cf3103c8744ac6234/src/main/python/rlbot/gui/qt_root.py#L654-L673 | def add_agent(self, overall_index=None, team_index=None):
"""
Creates the agent using self.agent_class and adds it to the index manager.
:param overall_index: The index of the bot in the config file if it already exists.
:param team_index: The index of the team to place the agent in
... | [
"def",
"add_agent",
"(",
"self",
",",
"overall_index",
"=",
"None",
",",
"team_index",
"=",
"None",
")",
":",
"if",
"overall_index",
"is",
"None",
":",
"if",
"not",
"self",
".",
"index_manager",
".",
"has_free_slots",
"(",
")",
":",
"return",
"overall_inde... | Creates the agent using self.agent_class and adds it to the index manager.
:param overall_index: The index of the bot in the config file if it already exists.
:param team_index: The index of the team to place the agent in
:return agent: an Agent (gui_agent) with either given index or a free one,... | [
"Creates",
"the",
"agent",
"using",
"self",
".",
"agent_class",
"and",
"adds",
"it",
"to",
"the",
"index",
"manager",
".",
":",
"param",
"overall_index",
":",
"The",
"index",
"of",
"the",
"bot",
"in",
"the",
"config",
"file",
"if",
"it",
"already",
"exis... | python | train | 49.85 |
coinkite/connectrum | connectrum/client.py | https://github.com/coinkite/connectrum/blob/99948f92cc5c3ecb1a8a70146294014e608e50fc/connectrum/client.py#L161-L173 | async def _keepalive(self):
'''
Keep our connect to server alive forever, with some
pointless traffic.
'''
while self.protocol:
vers = await self.RPC('server.version')
logger.debug("Server version: " + repr(vers))
# Five minutes isn't... | [
"async",
"def",
"_keepalive",
"(",
"self",
")",
":",
"while",
"self",
".",
"protocol",
":",
"vers",
"=",
"await",
"self",
".",
"RPC",
"(",
"'server.version'",
")",
"logger",
".",
"debug",
"(",
"\"Server version: \"",
"+",
"repr",
"(",
"vers",
")",
")",
... | Keep our connect to server alive forever, with some
pointless traffic. | [
"Keep",
"our",
"connect",
"to",
"server",
"alive",
"forever",
"with",
"some",
"pointless",
"traffic",
"."
] | python | train | 38.692308 |
happyleavesaoc/aoc-mgz | mgz/recorded_game/__init__.py | https://github.com/happyleavesaoc/aoc-mgz/blob/13fc379cc062d7640bfa028eed9c0d45d37a7b2b/mgz/recorded_game/__init__.py#L444-L454 | def _set_winning_team(self):
"""Mark the winning team."""
if not self._summary['finished']:
return
for team in self._summary['diplomacy']['teams']:
team['winner'] = False
for player_number in team['player_numbers']:
for player in self._summary[... | [
"def",
"_set_winning_team",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_summary",
"[",
"'finished'",
"]",
":",
"return",
"for",
"team",
"in",
"self",
".",
"_summary",
"[",
"'diplomacy'",
"]",
"[",
"'teams'",
"]",
":",
"team",
"[",
"'winner'",
"]... | Mark the winning team. | [
"Mark",
"the",
"winning",
"team",
"."
] | python | train | 43.090909 |
tchellomello/python-arlo | pyarlo/base_station.py | https://github.com/tchellomello/python-arlo/blob/db70aeb81705309c56ad32bbab1094f6cd146524/pyarlo/base_station.py#L559-L584 | def _decode_sensor_data(properties):
"""Decode, decompress, and parse the data from the history API"""
b64_input = ""
for s in properties.get('payload'):
# pylint: disable=consider-using-join
b64_input += s
decoded = base64.b64decode(b64_input)
data = zli... | [
"def",
"_decode_sensor_data",
"(",
"properties",
")",
":",
"b64_input",
"=",
"\"\"",
"for",
"s",
"in",
"properties",
".",
"get",
"(",
"'payload'",
")",
":",
"# pylint: disable=consider-using-join",
"b64_input",
"+=",
"s",
"decoded",
"=",
"base64",
".",
"b64decod... | Decode, decompress, and parse the data from the history API | [
"Decode",
"decompress",
"and",
"parse",
"the",
"data",
"from",
"the",
"history",
"API"
] | python | train | 35.269231 |
acutesoftware/AIKIF | scripts/examples/document_AIKIF.py | https://github.com/acutesoftware/AIKIF/blob/fcf1582dc5f884b9a4fa7c6e20e9de9d94d21d03/scripts/examples/document_AIKIF.py#L31-L93 | def document_core_programs(p):
"""
Document a subset of core programs with purpose (and intent)
"""
p.comment('programs.py', 'collects list of aikif programs to show progress and allows comments to be added to each file')
p.comment('cls_file_mapping.py', 'uses ontology to get list of files to s... | [
"def",
"document_core_programs",
"(",
"p",
")",
":",
"p",
".",
"comment",
"(",
"'programs.py'",
",",
"'collects list of aikif programs to show progress and allows comments to be added to each file'",
")",
"p",
".",
"comment",
"(",
"'cls_file_mapping.py'",
",",
"'uses ontology... | Document a subset of core programs with purpose (and intent) | [
"Document",
"a",
"subset",
"of",
"core",
"programs",
"with",
"purpose",
"(",
"and",
"intent",
")"
] | python | train | 75.873016 |
fastai/fastai | fastai/callbacks/mlflow.py | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/mlflow.py#L16-L24 | def on_train_begin(self, **kwargs: Any) -> None:
"Prepare MLflow experiment and log params"
self.client = mlflow.tracking.MlflowClient(self.uri)
exp = self.client.get_experiment_by_name(self.exp_name)
self.exp_id = self.client.create_experiment(self.exp_name) if exp is None else exp.expe... | [
"def",
"on_train_begin",
"(",
"self",
",",
"*",
"*",
"kwargs",
":",
"Any",
")",
"->",
"None",
":",
"self",
".",
"client",
"=",
"mlflow",
".",
"tracking",
".",
"MlflowClient",
"(",
"self",
".",
"uri",
")",
"exp",
"=",
"self",
".",
"client",
".",
"ge... | Prepare MLflow experiment and log params | [
"Prepare",
"MLflow",
"experiment",
"and",
"log",
"params"
] | python | train | 58.777778 |
the01/python-paps | paps/si/app/sensorClient.py | https://github.com/the01/python-paps/blob/2dde5a71913e4c7b22901cf05c6ecedd890919c4/paps/si/app/sensorClient.py#L184-L216 | def _do_config_packet(self, packet, ip, port):
"""
Apply config to this instance
:param packet: Packet with config
:type packet: paps.si.app.message.APPMessage
:param ip: Ip of server
:type ip: str
:param port: Port of server
:type port: int
:rtyp... | [
"def",
"_do_config_packet",
"(",
"self",
",",
"packet",
",",
"ip",
",",
"port",
")",
":",
"self",
".",
"debug",
"(",
"\"()\"",
")",
"if",
"packet",
".",
"header",
".",
"device_id",
"!=",
"Id",
".",
"SERVER",
":",
"# Only allow config packets from server",
... | Apply config to this instance
:param packet: Packet with config
:type packet: paps.si.app.message.APPMessage
:param ip: Ip of server
:type ip: str
:param port: Port of server
:type port: int
:rtype: None | [
"Apply",
"config",
"to",
"this",
"instance"
] | python | train | 32.878788 |
Robpol86/libnl | libnl/list_.py | https://github.com/Robpol86/libnl/blob/274e9fdaa39822d06ef70b799ed4a95937a4d923/libnl/list_.py#L101-L121 | def nl_list_for_each_entry_safe(pos, n, head, member):
"""https://github.com/thom311/libnl/blob/libnl3_2_25/include/netlink/list.h#L84.
Positional arguments:
pos -- class instance holding an nl_list_head instance.
n -- class instance holding an nl_list_head instance.
head -- nl_list_head class inst... | [
"def",
"nl_list_for_each_entry_safe",
"(",
"pos",
",",
"n",
",",
"head",
",",
"member",
")",
":",
"pos",
"=",
"nl_list_entry",
"(",
"head",
".",
"next_",
",",
"type",
"(",
"pos",
")",
",",
"member",
")",
"n",
"=",
"nl_list_entry",
"(",
"pos",
".",
"m... | https://github.com/thom311/libnl/blob/libnl3_2_25/include/netlink/list.h#L84.
Positional arguments:
pos -- class instance holding an nl_list_head instance.
n -- class instance holding an nl_list_head instance.
head -- nl_list_head class instance.
member -- attribute (string).
Returns:
Gene... | [
"https",
":",
"//",
"github",
".",
"com",
"/",
"thom311",
"/",
"libnl",
"/",
"blob",
"/",
"libnl3_2_25",
"/",
"include",
"/",
"netlink",
"/",
"list",
".",
"h#L84",
"."
] | python | train | 33.809524 |
ska-sa/montblanc | montblanc/util/ant_uvw.py | https://github.com/ska-sa/montblanc/blob/8a2e742e7500bcc6196489b735f87b233075dd2d/montblanc/util/ant_uvw.py#L86-L121 | def _antenna_uvw(uvw, antenna1, antenna2, chunks, nr_of_antenna):
""" numba implementation of antenna_uvw """
if antenna1.ndim != 1:
raise ValueError("antenna1 shape should be (row,)")
if antenna2.ndim != 1:
raise ValueError("antenna2 shape should be (row,)")
if uvw.ndim != 2 or uvw.s... | [
"def",
"_antenna_uvw",
"(",
"uvw",
",",
"antenna1",
",",
"antenna2",
",",
"chunks",
",",
"nr_of_antenna",
")",
":",
"if",
"antenna1",
".",
"ndim",
"!=",
"1",
":",
"raise",
"ValueError",
"(",
"\"antenna1 shape should be (row,)\"",
")",
"if",
"antenna2",
".",
... | numba implementation of antenna_uvw | [
"numba",
"implementation",
"of",
"antenna_uvw"
] | python | train | 29.694444 |
common-workflow-language/workflow-service | wes_service/cwl_runner.py | https://github.com/common-workflow-language/workflow-service/blob/e879604b65c55546e4f87be1c9df9903a3e0b896/wes_service/cwl_runner.py#L19-L79 | def run(self, request, tempdir, opts):
"""
Constructs a command to run a cwl/json from requests and opts,
runs it, and deposits the outputs in outdir.
Runner:
opts.getopt("runner", default="cwl-runner")
CWL (url):
request["workflow_url"] == a url to a cwl file
... | [
"def",
"run",
"(",
"self",
",",
"request",
",",
"tempdir",
",",
"opts",
")",
":",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"workdir",
",",
"\"request.json\"",
")",
",",
"\"w\"",
")",
"as",
"f",
":",
"json",
".",
"dum... | Constructs a command to run a cwl/json from requests and opts,
runs it, and deposits the outputs in outdir.
Runner:
opts.getopt("runner", default="cwl-runner")
CWL (url):
request["workflow_url"] == a url to a cwl file
or
request["workflow_attachment"] == input c... | [
"Constructs",
"a",
"command",
"to",
"run",
"a",
"cwl",
"/",
"json",
"from",
"requests",
"and",
"opts",
"runs",
"it",
"and",
"deposits",
"the",
"outputs",
"in",
"outdir",
"."
] | python | train | 41.278689 |
apache/spark | python/pyspark/sql/group.py | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/sql/group.py#L66-L116 | def agg(self, *exprs):
"""Compute aggregates and returns the result as a :class:`DataFrame`.
The available aggregate functions can be:
1. built-in aggregation functions, such as `avg`, `max`, `min`, `sum`, `count`
2. group aggregate pandas UDFs, created with :func:`pyspark.sql.functio... | [
"def",
"agg",
"(",
"self",
",",
"*",
"exprs",
")",
":",
"assert",
"exprs",
",",
"\"exprs should not be empty\"",
"if",
"len",
"(",
"exprs",
")",
"==",
"1",
"and",
"isinstance",
"(",
"exprs",
"[",
"0",
"]",
",",
"dict",
")",
":",
"jdf",
"=",
"self",
... | Compute aggregates and returns the result as a :class:`DataFrame`.
The available aggregate functions can be:
1. built-in aggregation functions, such as `avg`, `max`, `min`, `sum`, `count`
2. group aggregate pandas UDFs, created with :func:`pyspark.sql.functions.pandas_udf`
.. note... | [
"Compute",
"aggregates",
"and",
"returns",
"the",
"result",
"as",
"a",
":",
"class",
":",
"DataFrame",
"."
] | python | train | 47.431373 |
danielhrisca/asammdf | asammdf/blocks/utils.py | https://github.com/danielhrisca/asammdf/blob/3c7a1fd19c957ceebe4dcdbb2abf00806c2bdb66/asammdf/blocks/utils.py#L472-L500 | def info_to_datatype_v4(signed, little_endian):
"""map CAN signal to MDF integer types
Parameters
----------
signed : bool
signal is flagged as signed in the CAN database
little_endian : bool
signal is flagged as little endian (Intel) in the CAN database
Returns
-------
... | [
"def",
"info_to_datatype_v4",
"(",
"signed",
",",
"little_endian",
")",
":",
"if",
"signed",
":",
"if",
"little_endian",
":",
"datatype",
"=",
"v4c",
".",
"DATA_TYPE_SIGNED_INTEL",
"else",
":",
"datatype",
"=",
"v4c",
".",
"DATA_TYPE_SIGNED_MOTOROLA",
"else",
":... | map CAN signal to MDF integer types
Parameters
----------
signed : bool
signal is flagged as signed in the CAN database
little_endian : bool
signal is flagged as little endian (Intel) in the CAN database
Returns
-------
datatype : int
integer code for MDF channel da... | [
"map",
"CAN",
"signal",
"to",
"MDF",
"integer",
"types"
] | python | train | 24.137931 |
by46/simplekit | simplekit/docker/repository.py | https://github.com/by46/simplekit/blob/33f3ce6de33accc185e1057f096af41859db5976/simplekit/docker/repository.py#L27-L37 | def image_exists(self, image_name, tag='latest'):
"""
:param image_name:
:return: True the image_name location in docker.neg pos
"""
code, image = self.image_tags(image_name)
if code != httplib.OK:
return False
tag = tag.lower()
retu... | [
"def",
"image_exists",
"(",
"self",
",",
"image_name",
",",
"tag",
"=",
"'latest'",
")",
":",
"code",
",",
"image",
"=",
"self",
".",
"image_tags",
"(",
"image_name",
")",
"if",
"code",
"!=",
"httplib",
".",
"OK",
":",
"return",
"False",
"tag",
"=",
... | :param image_name:
:return: True the image_name location in docker.neg pos | [
":",
"param",
"image_name",
":",
":",
"return",
":",
"True",
"the",
"image_name",
"location",
"in",
"docker",
".",
"neg",
"pos"
] | python | train | 32.181818 |
apache/airflow | airflow/operators/__init__.py | https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/operators/__init__.py#L21-L27 | def _integrate_plugins():
"""Integrate plugins to the context"""
import sys
from airflow.plugins_manager import operators_modules
for operators_module in operators_modules:
sys.modules[operators_module.__name__] = operators_module
globals()[operators_module._name] = operators_module | [
"def",
"_integrate_plugins",
"(",
")",
":",
"import",
"sys",
"from",
"airflow",
".",
"plugins_manager",
"import",
"operators_modules",
"for",
"operators_module",
"in",
"operators_modules",
":",
"sys",
".",
"modules",
"[",
"operators_module",
".",
"__name__",
"]",
... | Integrate plugins to the context | [
"Integrate",
"plugins",
"to",
"the",
"context"
] | python | test | 44.142857 |
mezz64/pyEight | pyeight/user.py | https://github.com/mezz64/pyEight/blob/e557e4e6876f490d0964298e9475d68b64222d4f/pyeight/user.py#L581-L594 | async def update_trend_data(self, startdate, enddate):
"""Update trends data json for specified time period."""
url = '{}/users/{}/trends'.format(API_URL, self.userid)
params = {
'tz': self.device.tzone,
'from': startdate,
'to': enddate
}
... | [
"async",
"def",
"update_trend_data",
"(",
"self",
",",
"startdate",
",",
"enddate",
")",
":",
"url",
"=",
"'{}/users/{}/trends'",
".",
"format",
"(",
"API_URL",
",",
"self",
".",
"userid",
")",
"params",
"=",
"{",
"'tz'",
":",
"self",
".",
"device",
".",... | Update trends data json for specified time period. | [
"Update",
"trends",
"data",
"json",
"for",
"specified",
"time",
"period",
"."
] | python | train | 35.642857 |
oscarbranson/latools | latools/latools.py | https://github.com/oscarbranson/latools/blob/cd25a650cfee318152f234d992708511f7047fbe/latools/latools.py#L2389-L2423 | def filter_off(self, filt=None, analyte=None, samples=None, subset=None, show_status=False):
"""
Turns data filters off for particular analytes and samples.
Parameters
----------
filt : optional, str or array_like
Name, partial name or list of names of filters. Suppo... | [
"def",
"filter_off",
"(",
"self",
",",
"filt",
"=",
"None",
",",
"analyte",
"=",
"None",
",",
"samples",
"=",
"None",
",",
"subset",
"=",
"None",
",",
"show_status",
"=",
"False",
")",
":",
"if",
"samples",
"is",
"not",
"None",
":",
"subset",
"=",
... | Turns data filters off for particular analytes and samples.
Parameters
----------
filt : optional, str or array_like
Name, partial name or list of names of filters. Supports
partial matching. i.e. if 'cluster' is specified, all
filters with 'cluster' in the n... | [
"Turns",
"data",
"filters",
"off",
"for",
"particular",
"analytes",
"and",
"samples",
"."
] | python | test | 33.314286 |
kieferk/dfply | dfply/transform.py | https://github.com/kieferk/dfply/blob/6a858f066602735a90f8b6b85106bc39ceadc282/dfply/transform.py#L64-L101 | def transmute(df, *keep_columns, **kwargs):
"""
Creates columns and then returns those new columns and optionally specified
original columns from the DataFrame.
This works like `mutate`, but designed to discard the original columns used
to create the new ones.
Args:
*keep_columns: Colu... | [
"def",
"transmute",
"(",
"df",
",",
"*",
"keep_columns",
",",
"*",
"*",
"kwargs",
")",
":",
"keep_cols",
"=",
"[",
"]",
"for",
"col",
"in",
"flatten",
"(",
"keep_columns",
")",
":",
"try",
":",
"keep_cols",
".",
"append",
"(",
"col",
".",
"name",
"... | Creates columns and then returns those new columns and optionally specified
original columns from the DataFrame.
This works like `mutate`, but designed to discard the original columns used
to create the new ones.
Args:
*keep_columns: Column labels to keep. Can be string, symbolic, or
... | [
"Creates",
"columns",
"and",
"then",
"returns",
"those",
"new",
"columns",
"and",
"optionally",
"specified",
"original",
"columns",
"from",
"the",
"DataFrame",
"."
] | python | train | 29.473684 |
pbrisk/businessdate | businessdate/basedate.py | https://github.com/pbrisk/businessdate/blob/79a0c5a4e557cbacca82a430403b18413404a9bc/businessdate/basedate.py#L393-L405 | def add_years(date_obj, years_int):
"""
addition of a number of years
:param BaseDateTuple d:
:param int years_int:
:return BaseDatetimeDate:
"""
y, m, d = BaseDateTuple.to_ymd(date_obj)
y += years_int
if not is_leap_year(y) and m == 2:
... | [
"def",
"add_years",
"(",
"date_obj",
",",
"years_int",
")",
":",
"y",
",",
"m",
",",
"d",
"=",
"BaseDateTuple",
".",
"to_ymd",
"(",
"date_obj",
")",
"y",
"+=",
"years_int",
"if",
"not",
"is_leap_year",
"(",
"y",
")",
"and",
"m",
"==",
"2",
":",
"d"... | addition of a number of years
:param BaseDateTuple d:
:param int years_int:
:return BaseDatetimeDate: | [
"addition",
"of",
"a",
"number",
"of",
"years"
] | python | valid | 28.538462 |
ewels/MultiQC | multiqc/modules/samtools/stats.py | https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/samtools/stats.py#L18-L157 | def parse_samtools_stats(self):
""" Find Samtools stats logs and parse their data """
self.samtools_stats = dict()
for f in self.find_log_files('samtools/stats'):
parsed_data = dict()
for line in f['f'].splitlines():
if not line.startswith("SN"):
... | [
"def",
"parse_samtools_stats",
"(",
"self",
")",
":",
"self",
".",
"samtools_stats",
"=",
"dict",
"(",
")",
"for",
"f",
"in",
"self",
".",
"find_log_files",
"(",
"'samtools/stats'",
")",
":",
"parsed_data",
"=",
"dict",
"(",
")",
"for",
"line",
"in",
"f"... | Find Samtools stats logs and parse their data | [
"Find",
"Samtools",
"stats",
"logs",
"and",
"parse",
"their",
"data"
] | python | train | 49.042857 |
sacherjj/array_devices | array_devices/array3710.py | https://github.com/sacherjj/array_devices/blob/ba93a081e555321125ead33cf6fc5197569ef08f/array_devices/array3710.py#L324-L337 | def set_load_power(self, power_watts):
"""
Changes load to power mode and sets power value.
Rounds to nearest 0.1W.
:param power_watts: Power in Watts (0-200)
:return:
"""
new_val = int(round(power_watts * 10))
if not 0 <= new_val <= 2000:
rai... | [
"def",
"set_load_power",
"(",
"self",
",",
"power_watts",
")",
":",
"new_val",
"=",
"int",
"(",
"round",
"(",
"power_watts",
"*",
"10",
")",
")",
"if",
"not",
"0",
"<=",
"new_val",
"<=",
"2000",
":",
"raise",
"ValueError",
"(",
"\"Load Power should be betw... | Changes load to power mode and sets power value.
Rounds to nearest 0.1W.
:param power_watts: Power in Watts (0-200)
:return: | [
"Changes",
"load",
"to",
"power",
"mode",
"and",
"sets",
"power",
"value",
".",
"Rounds",
"to",
"nearest",
"0",
".",
"1W",
"."
] | python | train | 33.785714 |
WoLpH/python-progressbar | progressbar/bar.py | https://github.com/WoLpH/python-progressbar/blob/963617a1bb9d81624ecf31f3457185992cd97bfa/progressbar/bar.py#L105-L109 | def _handle_resize(self, signum=None, frame=None):
'Tries to catch resize signals sent from the terminal.'
w, h = utils.get_terminal_size()
self.term_width = w | [
"def",
"_handle_resize",
"(",
"self",
",",
"signum",
"=",
"None",
",",
"frame",
"=",
"None",
")",
":",
"w",
",",
"h",
"=",
"utils",
".",
"get_terminal_size",
"(",
")",
"self",
".",
"term_width",
"=",
"w"
] | Tries to catch resize signals sent from the terminal. | [
"Tries",
"to",
"catch",
"resize",
"signals",
"sent",
"from",
"the",
"terminal",
"."
] | python | train | 36 |
Jajcus/pyxmpp2 | pyxmpp2/jid.py | https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/jid.py#L305-L316 | def as_unicode(self):
"""Unicode string JID representation.
:return: JID as Unicode string."""
result = self.domain
if self.local:
result = self.local + u'@' + result
if self.resource:
result = result + u'/' + self.resource
if not JID.cache.has_ke... | [
"def",
"as_unicode",
"(",
"self",
")",
":",
"result",
"=",
"self",
".",
"domain",
"if",
"self",
".",
"local",
":",
"result",
"=",
"self",
".",
"local",
"+",
"u'@'",
"+",
"result",
"if",
"self",
".",
"resource",
":",
"result",
"=",
"result",
"+",
"u... | Unicode string JID representation.
:return: JID as Unicode string. | [
"Unicode",
"string",
"JID",
"representation",
"."
] | python | valid | 31.5 |
materialsproject/pymatgen | pymatgen/electronic_structure/bandstructure.py | https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/electronic_structure/bandstructure.py#L842-L885 | def as_dict(self):
"""
Json-serializable dict representation of BandStructureSymmLine.
"""
d = {"@module": self.__class__.__module__,
"@class": self.__class__.__name__,
"lattice_rec": self.lattice_rec.as_dict(), "efermi": self.efermi,
"kpoints": []... | [
"def",
"as_dict",
"(",
"self",
")",
":",
"d",
"=",
"{",
"\"@module\"",
":",
"self",
".",
"__class__",
".",
"__module__",
",",
"\"@class\"",
":",
"self",
".",
"__class__",
".",
"__name__",
",",
"\"lattice_rec\"",
":",
"self",
".",
"lattice_rec",
".",
"as_... | Json-serializable dict representation of BandStructureSymmLine. | [
"Json",
"-",
"serializable",
"dict",
"representation",
"of",
"BandStructureSymmLine",
"."
] | python | train | 49.431818 |
ff0000/scarlet | scarlet/cms/base_views.py | https://github.com/ff0000/scarlet/blob/6c37befd810916a2d7ffff2cdb2dab57bcb6d12e/scarlet/cms/base_views.py#L731-L750 | def get_url_kwargs(self, request_kwargs=None, **kwargs):
"""
If request_kwargs is not specified, self.kwargs is used instead.
If 'object' is one of the kwargs passed. Replaces it with
the value of 'self.slug_field' on the given object.
"""
if not request_kwargs:
... | [
"def",
"get_url_kwargs",
"(",
"self",
",",
"request_kwargs",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"request_kwargs",
":",
"request_kwargs",
"=",
"getattr",
"(",
"self",
",",
"'kwargs'",
",",
"{",
"}",
")",
"kwargs",
"=",
"super",
... | If request_kwargs is not specified, self.kwargs is used instead.
If 'object' is one of the kwargs passed. Replaces it with
the value of 'self.slug_field' on the given object. | [
"If",
"request_kwargs",
"is",
"not",
"specified",
"self",
".",
"kwargs",
"is",
"used",
"instead",
"."
] | python | train | 39.05 |
refenv/cijoe | modules/cij/xlsx.py | https://github.com/refenv/cijoe/blob/21d7b2ed4ff68e0a1457e7df2db27f6334f1a379/modules/cij/xlsx.py#L344-L371 | def sum_data(filter_data, is_bw):
""" caculate sum"""
for index in range(len(filter_data) - 1):
if filter_data[index][0] > filter_data[index + 1][0]:
max_index = index + 1
break
else:
max_index = len(filter_data)
print("max_index: ", max_index + 1)
nu... | [
"def",
"sum_data",
"(",
"filter_data",
",",
"is_bw",
")",
":",
"for",
"index",
"in",
"range",
"(",
"len",
"(",
"filter_data",
")",
"-",
"1",
")",
":",
"if",
"filter_data",
"[",
"index",
"]",
"[",
"0",
"]",
">",
"filter_data",
"[",
"index",
"+",
"1"... | caculate sum | [
"caculate",
"sum"
] | python | valid | 36.285714 |
happyleavesaoc/python-snapcast | snapcast/client/messages.py | https://github.com/happyleavesaoc/python-snapcast/blob/9b3c483358677327c7fd6d0666bf474c19d87f19/snapcast/client/messages.py#L122-L140 | def message(message_type, payload, payload_length):
""" Build a message. """
return packet.build(
Container(
type=message_type,
id=1,
refer=0,
sent=Container(
secs=0,
usecs=0
),
recv=Container(
... | [
"def",
"message",
"(",
"message_type",
",",
"payload",
",",
"payload_length",
")",
":",
"return",
"packet",
".",
"build",
"(",
"Container",
"(",
"type",
"=",
"message_type",
",",
"id",
"=",
"1",
",",
"refer",
"=",
"0",
",",
"sent",
"=",
"Container",
"(... | Build a message. | [
"Build",
"a",
"message",
"."
] | python | train | 23.421053 |
brocade/pynos | pynos/versions/ver_7/ver_7_1_0/yang/brocade_fabric_service.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_7/ver_7_1_0/yang/brocade_fabric_service.py#L355-L372 | def show_portindex_interface_info_output_show_portindex_interface_show_portindex_port_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
show_portindex_interface_info = ET.Element("show_portindex_interface_info")
config = show_portindex_interface_info
... | [
"def",
"show_portindex_interface_info_output_show_portindex_interface_show_portindex_port_type",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"show_portindex_interface_info",
"=",
"ET",
".",
"Element",
"(",... | Auto Generated Code | [
"Auto",
"Generated",
"Code"
] | python | train | 57.944444 |
fabioz/PyDev.Debugger | third_party/pep8/pycodestyle.py | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/third_party/pep8/pycodestyle.py#L791-L806 | def whitespace_around_comma(logical_line):
r"""Avoid extraneous whitespace after a comma or a colon.
Note: these checks are disabled by default
Okay: a = (1, 2)
E241: a = (1, 2)
E242: a = (1,\t2)
"""
line = logical_line
for m in WHITESPACE_AFTER_COMMA_REGEX.finditer(line):
fou... | [
"def",
"whitespace_around_comma",
"(",
"logical_line",
")",
":",
"line",
"=",
"logical_line",
"for",
"m",
"in",
"WHITESPACE_AFTER_COMMA_REGEX",
".",
"finditer",
"(",
"line",
")",
":",
"found",
"=",
"m",
".",
"start",
"(",
")",
"+",
"1",
"if",
"'\\t'",
"in"... | r"""Avoid extraneous whitespace after a comma or a colon.
Note: these checks are disabled by default
Okay: a = (1, 2)
E241: a = (1, 2)
E242: a = (1,\t2) | [
"r",
"Avoid",
"extraneous",
"whitespace",
"after",
"a",
"comma",
"or",
"a",
"colon",
"."
] | python | train | 31.4375 |
T-002/pycast | bin/examples/LivingRoomEnergy/server.py | https://github.com/T-002/pycast/blob/8a53505c6d8367e0ea572e8af768e80b29e1cc41/bin/examples/LivingRoomEnergy/server.py#L43-L51 | def energy_data():
"""
Connects to the database and loads Readings for device 8.
"""
cur = db.cursor().execute("""SELECT timestamp, current FROM Readings""")
original = TimeSeries()
original.initialize_from_sql_cursor(cur)
original.normalize("day", fusionMethod = "sum")
return itty.R... | [
"def",
"energy_data",
"(",
")",
":",
"cur",
"=",
"db",
".",
"cursor",
"(",
")",
".",
"execute",
"(",
"\"\"\"SELECT timestamp, current FROM Readings\"\"\"",
")",
"original",
"=",
"TimeSeries",
"(",
")",
"original",
".",
"initialize_from_sql_cursor",
"(",
"cur",
"... | Connects to the database and loads Readings for device 8. | [
"Connects",
"to",
"the",
"database",
"and",
"loads",
"Readings",
"for",
"device",
"8",
"."
] | python | train | 43.666667 |
synw/dataswim | dataswim/messages.py | https://github.com/synw/dataswim/blob/4a4a53f80daa7cd8e8409d76a19ce07296269da2/dataswim/messages.py#L26-L31 | def status(self, *msg):
"""
Prints a status message
"""
label = colors.yellow("STATUS")
self._msg(label, *msg) | [
"def",
"status",
"(",
"self",
",",
"*",
"msg",
")",
":",
"label",
"=",
"colors",
".",
"yellow",
"(",
"\"STATUS\"",
")",
"self",
".",
"_msg",
"(",
"label",
",",
"*",
"msg",
")"
] | Prints a status message | [
"Prints",
"a",
"status",
"message"
] | python | train | 24.166667 |
anomaly/prestans | prestans/types/array.py | https://github.com/anomaly/prestans/blob/13f5b2467bfd403dcd2d085f15cbf4644044f105/prestans/types/array.py#L112-L121 | def is_scalar(self):
"""
:return:
:rtype: bool
"""
return \
isinstance(self._element_template, Boolean) or \
isinstance(self._element_template, Float) or \
isinstance(self._element_template, Integer) or \
isinstance(self._element_t... | [
"def",
"is_scalar",
"(",
"self",
")",
":",
"return",
"isinstance",
"(",
"self",
".",
"_element_template",
",",
"Boolean",
")",
"or",
"isinstance",
"(",
"self",
".",
"_element_template",
",",
"Float",
")",
"or",
"isinstance",
"(",
"self",
".",
"_element_templ... | :return:
:rtype: bool | [
":",
"return",
":",
":",
"rtype",
":",
"bool"
] | python | train | 32.7 |
chibisov/drf-extensions | docs/backdoc.py | https://github.com/chibisov/drf-extensions/blob/1d28a4b28890eab5cd19e93e042f8590c8c2fb8b/docs/backdoc.py#L1912-L1943 | def toc_html(self):
"""Return the HTML for the current TOC.
This expects the `_toc` attribute to have been set on this instance.
"""
if self._toc is None:
return None
def indent():
return ' ' * (len(h_stack) - 1)
lines = []
h_stack = [0]... | [
"def",
"toc_html",
"(",
"self",
")",
":",
"if",
"self",
".",
"_toc",
"is",
"None",
":",
"return",
"None",
"def",
"indent",
"(",
")",
":",
"return",
"' '",
"*",
"(",
"len",
"(",
"h_stack",
")",
"-",
"1",
")",
"lines",
"=",
"[",
"]",
"h_stack",
... | Return the HTML for the current TOC.
This expects the `_toc` attribute to have been set on this instance. | [
"Return",
"the",
"HTML",
"for",
"the",
"current",
"TOC",
"."
] | python | train | 35.78125 |
Genida/dependenpy | src/dependenpy/finder.py | https://github.com/Genida/dependenpy/blob/df099c17cbe735c990eca9197e39cfc5eb8a4c8e/src/dependenpy/finder.py#L84-L106 | def find(self, package, **kwargs):
"""
Find method.
Args:
package (str): package to find.
**kwargs (): additional keyword arguments.
Returns:
PackageSpec: the PackageSpec corresponding to the package, or None.
"""
if not exists(packag... | [
"def",
"find",
"(",
"self",
",",
"package",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"exists",
"(",
"package",
")",
":",
"return",
"None",
"name",
",",
"path",
"=",
"None",
",",
"None",
"enforce_init",
"=",
"kwargs",
".",
"pop",
"(",
"'enfor... | Find method.
Args:
package (str): package to find.
**kwargs (): additional keyword arguments.
Returns:
PackageSpec: the PackageSpec corresponding to the package, or None. | [
"Find",
"method",
"."
] | python | train | 33.956522 |
chemlab/chemlab | chemlab/graphics/colors.py | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/graphics/colors.py#L182-L194 | def html_to_rgb(colorstring):
""" convert #RRGGBB to an (R, G, B) tuple """
colorstring = colorstring.strip()
if colorstring[0] == '#':
colorstring = colorstring[1:]
if len(colorstring) != 6:
raise ValueError("input #%s is not in #RRGGBB format" % colorstring)
r, g, b = colorstring... | [
"def",
"html_to_rgb",
"(",
"colorstring",
")",
":",
"colorstring",
"=",
"colorstring",
".",
"strip",
"(",
")",
"if",
"colorstring",
"[",
"0",
"]",
"==",
"'#'",
":",
"colorstring",
"=",
"colorstring",
"[",
"1",
":",
"]",
"if",
"len",
"(",
"colorstring",
... | convert #RRGGBB to an (R, G, B) tuple | [
"convert",
"#RRGGBB",
"to",
"an",
"(",
"R",
"G",
"B",
")",
"tuple"
] | python | train | 32.307692 |
JoaoFelipe/ipython-unittest | setup.py | https://github.com/JoaoFelipe/ipython-unittest/blob/2a1708e1fa575ce80e0ee2092d280979c1a77885/setup.py#L7-L13 | def recursive_path(pack, path):
"""Find paths recursively"""
matches = []
for root, _, filenames in os.walk(os.path.join(pack, path)):
for filename in filenames:
matches.append(os.path.join(root, filename)[len(pack) + 1:])
return matches | [
"def",
"recursive_path",
"(",
"pack",
",",
"path",
")",
":",
"matches",
"=",
"[",
"]",
"for",
"root",
",",
"_",
",",
"filenames",
"in",
"os",
".",
"walk",
"(",
"os",
".",
"path",
".",
"join",
"(",
"pack",
",",
"path",
")",
")",
":",
"for",
"fil... | Find paths recursively | [
"Find",
"paths",
"recursively"
] | python | train | 38.142857 |
HazyResearch/pdftotree | pdftotree/utils/img_utils.py | https://github.com/HazyResearch/pdftotree/blob/5890d668b475d5d3058d1d886aafbfd83268c440/pdftotree/utils/img_utils.py#L24-L36 | def lazy_load_font(font_size=default_font_size):
"""
Lazy loading font according to system platform
"""
if font_size not in _font_cache:
if _platform.startswith("darwin"):
font_path = "/Library/Fonts/Arial.ttf"
elif _platform.startswith("linux"):
font_path = "/usr... | [
"def",
"lazy_load_font",
"(",
"font_size",
"=",
"default_font_size",
")",
":",
"if",
"font_size",
"not",
"in",
"_font_cache",
":",
"if",
"_platform",
".",
"startswith",
"(",
"\"darwin\"",
")",
":",
"font_path",
"=",
"\"/Library/Fonts/Arial.ttf\"",
"elif",
"_platfo... | Lazy loading font according to system platform | [
"Lazy",
"loading",
"font",
"according",
"to",
"system",
"platform"
] | python | train | 44.153846 |
hayd/ctox | ctox/main.py | https://github.com/hayd/ctox/blob/6f032488ad67170d57d025a830d7b967075b0d7f/ctox/main.py#L159-L186 | def main(arguments, toxinidir=None):
"ctox: tox with conda."
try: # pragma: no cover
# Exit on broken pipe.
import signal
signal.signal(signal.SIGPIPE, signal.SIG_DFL)
except AttributeError: # pragma: no cover
# SIGPIPE is not available on Windows.
pass
try:
... | [
"def",
"main",
"(",
"arguments",
",",
"toxinidir",
"=",
"None",
")",
":",
"try",
":",
"# pragma: no cover",
"# Exit on broken pipe.",
"import",
"signal",
"signal",
".",
"signal",
"(",
"signal",
".",
"SIGPIPE",
",",
"signal",
".",
"SIG_DFL",
")",
"except",
"A... | ctox: tox with conda. | [
"ctox",
":",
"tox",
"with",
"conda",
"."
] | python | train | 29.75 |
CellProfiler/centrosome | centrosome/neighmovetrack.py | https://github.com/CellProfiler/centrosome/blob/7bd9350a2d4ae1b215b81eabcecfe560bbb1f32a/centrosome/neighmovetrack.py#L267-L275 | def calculate_basic_cost(self, d1, d2):
"""
Calculates assignment cost between two cells.
"""
distance = euclidean_dist(d1.center, d2.center) / self.scale
area_change = 1 - min(d1.area, d2.area) / max(d1.area, d2.area)
return distance + self.parameters_cost_initial["are... | [
"def",
"calculate_basic_cost",
"(",
"self",
",",
"d1",
",",
"d2",
")",
":",
"distance",
"=",
"euclidean_dist",
"(",
"d1",
".",
"center",
",",
"d2",
".",
"center",
")",
"/",
"self",
".",
"scale",
"area_change",
"=",
"1",
"-",
"min",
"(",
"d1",
".",
... | Calculates assignment cost between two cells. | [
"Calculates",
"assignment",
"cost",
"between",
"two",
"cells",
"."
] | python | train | 37.333333 |
tjguk/networkzero | misc/pyconuk2017/robotics/robot/robot.py | https://github.com/tjguk/networkzero/blob/0e3e81d2e9200b25a83ac07741612283599486d7/misc/pyconuk2017/robotics/robot/robot.py#L93-L101 | def do_output(self, *args):
"""Pass a command directly to the current output processor
"""
if args:
action, params = args[0], args[1:]
log.debug("Pass %s directly to output with %s", action, params)
function = getattr(self.output, "do_" + action, None)
... | [
"def",
"do_output",
"(",
"self",
",",
"*",
"args",
")",
":",
"if",
"args",
":",
"action",
",",
"params",
"=",
"args",
"[",
"0",
"]",
",",
"args",
"[",
"1",
":",
"]",
"log",
".",
"debug",
"(",
"\"Pass %s directly to output with %s\"",
",",
"action",
"... | Pass a command directly to the current output processor | [
"Pass",
"a",
"command",
"directly",
"to",
"the",
"current",
"output",
"processor"
] | python | train | 40.333333 |
SUSE-Enceladus/ipa | ipa/ipa_utils.py | https://github.com/SUSE-Enceladus/ipa/blob/0845eed0ea25a27dbb059ad1016105fa60002228/ipa/ipa_utils.py#L271-L305 | def get_ssh_client(ip,
ssh_private_key_file,
ssh_user='root',
port=22,
timeout=600,
wait_period=10):
"""Attempt to establish and test ssh connection."""
if ip in CLIENT_CACHE:
return CLIENT_CACHE[ip]
star... | [
"def",
"get_ssh_client",
"(",
"ip",
",",
"ssh_private_key_file",
",",
"ssh_user",
"=",
"'root'",
",",
"port",
"=",
"22",
",",
"timeout",
"=",
"600",
",",
"wait_period",
"=",
"10",
")",
":",
"if",
"ip",
"in",
"CLIENT_CACHE",
":",
"return",
"CLIENT_CACHE",
... | Attempt to establish and test ssh connection. | [
"Attempt",
"to",
"establish",
"and",
"test",
"ssh",
"connection",
"."
] | python | train | 26.457143 |
jobovy/galpy | galpy/actionAngle/actionAngleStaeckel.py | https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/actionAngle/actionAngleStaeckel.py#L981-L988 | def _JzStaeckelIntegrandSquared(v,E,Lz,I3V,delta,u0,cosh2u0,sinh2u0,
potu0pi2,pot):
#potu0pi2= potentialStaeckel(u0,nu.pi/2.,pot,delta)
"""The J_z integrand: p_v(v)/2/delta^2"""
sin2v= nu.sin(v)**2.
dV= cosh2u0*potu0pi2\
-(sinh2u0+sin2v)*potentialStaeckel(u0,v,pot... | [
"def",
"_JzStaeckelIntegrandSquared",
"(",
"v",
",",
"E",
",",
"Lz",
",",
"I3V",
",",
"delta",
",",
"u0",
",",
"cosh2u0",
",",
"sinh2u0",
",",
"potu0pi2",
",",
"pot",
")",
":",
"#potu0pi2= potentialStaeckel(u0,nu.pi/2.,pot,delta)",
"sin2v",
"=",
"nu",
".",
"... | The J_z integrand: p_v(v)/2/delta^2 | [
"The",
"J_z",
"integrand",
":",
"p_v",
"(",
"v",
")",
"/",
"2",
"/",
"delta^2"
] | python | train | 46.5 |
hobson/aima | aima/csp.py | https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/csp.py#L118-L121 | def prune(self, var, value, removals):
"Rule out var=value."
self.curr_domains[var].remove(value)
if removals is not None: removals.append((var, value)) | [
"def",
"prune",
"(",
"self",
",",
"var",
",",
"value",
",",
"removals",
")",
":",
"self",
".",
"curr_domains",
"[",
"var",
"]",
".",
"remove",
"(",
"value",
")",
"if",
"removals",
"is",
"not",
"None",
":",
"removals",
".",
"append",
"(",
"(",
"var"... | Rule out var=value. | [
"Rule",
"out",
"var",
"=",
"value",
"."
] | python | valid | 43.25 |
CiscoDevNet/webexteamssdk | webexteamssdk/api/messages.py | https://github.com/CiscoDevNet/webexteamssdk/blob/6fc2cc3557e080ba4b2a380664cb2a0532ae45cd/webexteamssdk/api/messages.py#L75-L135 | def list(self, roomId, mentionedPeople=None, before=None,
beforeMessage=None, max=None, **request_parameters):
"""Lists messages in a room.
Each message will include content attachments if present.
The list API sorts the messages in descending order by creation date.
This... | [
"def",
"list",
"(",
"self",
",",
"roomId",
",",
"mentionedPeople",
"=",
"None",
",",
"before",
"=",
"None",
",",
"beforeMessage",
"=",
"None",
",",
"max",
"=",
"None",
",",
"*",
"*",
"request_parameters",
")",
":",
"check_type",
"(",
"roomId",
",",
"ba... | Lists messages in a room.
Each message will include content attachments if present.
The list API sorts the messages in descending order by creation date.
This method supports Webex Teams's implementation of RFC5988 Web
Linking to provide pagination support. It returns a generator
... | [
"Lists",
"messages",
"in",
"a",
"room",
"."
] | python | test | 43.098361 |
tdryer/hangups | docs/generate_proto_docs.py | https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/docs/generate_proto_docs.py#L105-L129 | def generate_enum_doc(enum_descriptor, locations, path, name_prefix=''):
"""Generate doc for an enum.
Args:
enum_descriptor: descriptor_pb2.EnumDescriptorProto instance for enum
to generate docs for.
locations: Dictionary of location paths tuples to
descriptor_pb2.Source... | [
"def",
"generate_enum_doc",
"(",
"enum_descriptor",
",",
"locations",
",",
"path",
",",
"name_prefix",
"=",
"''",
")",
":",
"print",
"(",
"make_subsection",
"(",
"name_prefix",
"+",
"enum_descriptor",
".",
"name",
")",
")",
"location",
"=",
"locations",
"[",
... | Generate doc for an enum.
Args:
enum_descriptor: descriptor_pb2.EnumDescriptorProto instance for enum
to generate docs for.
locations: Dictionary of location paths tuples to
descriptor_pb2.SourceCodeInfo.Location instances.
path: Path tuple to the enum definition.
... | [
"Generate",
"doc",
"for",
"an",
"enum",
"."
] | python | valid | 41.04 |
Frzk/Ellis | ellis/main.py | https://github.com/Frzk/Ellis/blob/39ce8987cbc503354cf1f45927344186a8b18363/ellis/main.py#L20-L26 | def customized_warning(message, category=UserWarning,
filename='', lineno=-1, file=None, line=None):
"""
Customized function to display warnings.
Monkey patch for `warnings.showwarning`.
"""
print("WARNING: {0}".format(message)) | [
"def",
"customized_warning",
"(",
"message",
",",
"category",
"=",
"UserWarning",
",",
"filename",
"=",
"''",
",",
"lineno",
"=",
"-",
"1",
",",
"file",
"=",
"None",
",",
"line",
"=",
"None",
")",
":",
"print",
"(",
"\"WARNING: {0}\"",
".",
"format",
"... | Customized function to display warnings.
Monkey patch for `warnings.showwarning`. | [
"Customized",
"function",
"to",
"display",
"warnings",
".",
"Monkey",
"patch",
"for",
"warnings",
".",
"showwarning",
"."
] | python | train | 37.857143 |
JarryShaw/PyPCAPKit | src/const/ipv4/tos_thr.py | https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/const/ipv4/tos_thr.py#L16-L22 | def get(key, default=-1):
"""Backport support for original codes."""
if isinstance(key, int):
return TOS_THR(key)
if key not in TOS_THR._member_map_:
extend_enum(TOS_THR, key, default)
return TOS_THR[key] | [
"def",
"get",
"(",
"key",
",",
"default",
"=",
"-",
"1",
")",
":",
"if",
"isinstance",
"(",
"key",
",",
"int",
")",
":",
"return",
"TOS_THR",
"(",
"key",
")",
"if",
"key",
"not",
"in",
"TOS_THR",
".",
"_member_map_",
":",
"extend_enum",
"(",
"TOS_T... | Backport support for original codes. | [
"Backport",
"support",
"for",
"original",
"codes",
"."
] | python | train | 36.285714 |
ibelie/typy | typy/google/protobuf/descriptor_pool.py | https://github.com/ibelie/typy/blob/3616845fb91459aacd8df6bf82c5d91f4542bee7/typy/google/protobuf/descriptor_pool.py#L287-L304 | def FindExtensionByName(self, full_name):
"""Loads the named extension descriptor from the pool.
Args:
full_name: The full name of the extension descriptor to load.
Returns:
A FieldDescriptor, describing the named extension.
"""
full_name = _NormalizeFullyQualifiedName(full_name)
m... | [
"def",
"FindExtensionByName",
"(",
"self",
",",
"full_name",
")",
":",
"full_name",
"=",
"_NormalizeFullyQualifiedName",
"(",
"full_name",
")",
"message_name",
",",
"_",
",",
"extension_name",
"=",
"full_name",
".",
"rpartition",
"(",
"'.'",
")",
"try",
":",
"... | Loads the named extension descriptor from the pool.
Args:
full_name: The full name of the extension descriptor to load.
Returns:
A FieldDescriptor, describing the named extension. | [
"Loads",
"the",
"named",
"extension",
"descriptor",
"from",
"the",
"pool",
"."
] | python | valid | 36.5 |
bwohlberg/sporco | sporco/util.py | https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/util.py#L285-L326 | def extractblocks(img, blksz, stpsz=None):
"""Extract blocks from an ndarray signal into an ndarray.
Parameters
----------
img : ndarray or tuple of ndarrays
nd array of images, or tuple of images
blksz : tuple
tuple of block sizes, blocks are taken starting from the first index
o... | [
"def",
"extractblocks",
"(",
"img",
",",
"blksz",
",",
"stpsz",
"=",
"None",
")",
":",
"# See http://stackoverflow.com/questions/16774148 and",
"# sklearn.feature_extraction.image.extract_patches_2d",
"if",
"isinstance",
"(",
"img",
",",
"tuple",
")",
":",
"img",
"=",
... | Extract blocks from an ndarray signal into an ndarray.
Parameters
----------
img : ndarray or tuple of ndarrays
nd array of images, or tuple of images
blksz : tuple
tuple of block sizes, blocks are taken starting from the first index
of img
stpsz : tuple, optional (default None, c... | [
"Extract",
"blocks",
"from",
"an",
"ndarray",
"signal",
"into",
"an",
"ndarray",
"."
] | python | train | 32.404762 |
brocade/pynos | pynos/versions/ver_6/ver_6_0_1/yang/brocade_nameserver.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_6/ver_6_0_1/yang/brocade_nameserver.py#L135-L149 | def get_nameserver_detail_output_show_nameserver_nameserver_fabric_portname(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_nameserver_detail = ET.Element("get_nameserver_detail")
config = get_nameserver_detail
output = ET.SubElement(get_name... | [
"def",
"get_nameserver_detail_output_show_nameserver_nameserver_fabric_portname",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"get_nameserver_detail",
"=",
"ET",
".",
"Element",
"(",
"\"get_nameserver_de... | Auto Generated Code | [
"Auto",
"Generated",
"Code"
] | python | train | 54.8 |
PSPC-SPAC-buyandsell/von_anchor | von_anchor/anchor/holderprover.py | https://github.com/PSPC-SPAC-buyandsell/von_anchor/blob/78ac1de67be42a676274f4bf71fe12f66e72f309/von_anchor/anchor/holderprover.py#L773-L823 | async def get_cred_info_by_id(self, cred_id: str) -> str:
"""
Return cred-info json from wallet by wallet credential identifier.
Raise AbsentCred for no such credential. Raise WalletState if the wallet is closed.
:param cred_id: credential identifier of interest
:return: json w... | [
"async",
"def",
"get_cred_info_by_id",
"(",
"self",
",",
"cred_id",
":",
"str",
")",
"->",
"str",
":",
"LOGGER",
".",
"debug",
"(",
"'HolderProver.get_cred_info_by_id >>> cred_id: %s'",
",",
"cred_id",
")",
"if",
"not",
"self",
".",
"wallet",
".",
"handle",
":... | Return cred-info json from wallet by wallet credential identifier.
Raise AbsentCred for no such credential. Raise WalletState if the wallet is closed.
:param cred_id: credential identifier of interest
:return: json with cred for input credential identifier
:return: cred-info json; i.e... | [
"Return",
"cred",
"-",
"info",
"json",
"from",
"wallet",
"by",
"wallet",
"credential",
"identifier",
"."
] | python | train | 38.647059 |
zenreach/py-era | era.py | https://github.com/zenreach/py-era/blob/73994c82360e65a983c803b1182892e2138320b2/era.py#L262-L272 | def prevweekday(when, weekday, inclusive=True):
"""
Return the date for the most recent day of the week. If inclusive is True (the default) today
may count as the weekday we're looking for.
"""
if isinstance(when, datetime):
when = when.date()
delta = weekday - when.weekday()
if (inc... | [
"def",
"prevweekday",
"(",
"when",
",",
"weekday",
",",
"inclusive",
"=",
"True",
")",
":",
"if",
"isinstance",
"(",
"when",
",",
"datetime",
")",
":",
"when",
"=",
"when",
".",
"date",
"(",
")",
"delta",
"=",
"weekday",
"-",
"when",
".",
"weekday",
... | Return the date for the most recent day of the week. If inclusive is True (the default) today
may count as the weekday we're looking for. | [
"Return",
"the",
"date",
"for",
"the",
"most",
"recent",
"day",
"of",
"the",
"week",
".",
"If",
"inclusive",
"is",
"True",
"(",
"the",
"default",
")",
"today",
"may",
"count",
"as",
"the",
"weekday",
"we",
"re",
"looking",
"for",
"."
] | python | valid | 38.636364 |
255BITS/hyperchamber | hyperchamber/__init__.py | https://github.com/255BITS/hyperchamber/blob/4d5774bde9ea6ce1113f77a069ffc605148482b8/hyperchamber/__init__.py#L24-L31 | def configs(max_configs=1, offset=None, serial=False, create_uuid=True):
"""Generate max configs, each one a dictionary. e.g. [{'x': 1}]
Will also add a config UUID, useful for tracking configs.
You can turn this off by passing create_uuid=False.
"""
global default_selector
return defau... | [
"def",
"configs",
"(",
"max_configs",
"=",
"1",
",",
"offset",
"=",
"None",
",",
"serial",
"=",
"False",
",",
"create_uuid",
"=",
"True",
")",
":",
"global",
"default_selector",
"return",
"default_selector",
".",
"configs",
"(",
"max_configs",
",",
"offset",... | Generate max configs, each one a dictionary. e.g. [{'x': 1}]
Will also add a config UUID, useful for tracking configs.
You can turn this off by passing create_uuid=False. | [
"Generate",
"max",
"configs",
"each",
"one",
"a",
"dictionary",
".",
"e",
".",
"g",
".",
"[",
"{",
"x",
":",
"1",
"}",
"]"
] | python | train | 46.75 |
mlperf/training | rnn_translator/pytorch/seq2seq/inference/inference.py | https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/rnn_translator/pytorch/seq2seq/inference/inference.py#L72-L85 | def build_eval_path(self, epoch, iteration):
"""
Appends index of the current epoch and index of the current iteration
to the name of the file with results.
:param epoch: index of the current epoch
:param iteration: index of the current iteration
"""
if iteration... | [
"def",
"build_eval_path",
"(",
"self",
",",
"epoch",
",",
"iteration",
")",
":",
"if",
"iteration",
"is",
"not",
"None",
":",
"eval_fname",
"=",
"f'eval_epoch_{epoch}_iter_{iteration}'",
"else",
":",
"eval_fname",
"=",
"f'eval_epoch_{epoch}'",
"eval_path",
"=",
"o... | Appends index of the current epoch and index of the current iteration
to the name of the file with results.
:param epoch: index of the current epoch
:param iteration: index of the current iteration | [
"Appends",
"index",
"of",
"the",
"current",
"epoch",
"and",
"index",
"of",
"the",
"current",
"iteration",
"to",
"the",
"name",
"of",
"the",
"file",
"with",
"results",
"."
] | python | train | 37.928571 |
bububa/pyTOP | pyTOP/taobaoke.py | https://github.com/bububa/pyTOP/blob/1e48009bcfe886be392628244b370e6374e1f2b2/pyTOP/taobaoke.py#L120-L133 | def items_convert(self, fields=[], **kwargs):
'''taobao.taobaoke.items.convert 淘客商品转换
淘宝客商品转换'''
request = TOPRequest('taobao.taobaoke.items.convert')
if not fields:
taobaokeItem = TaobaokeItem()
fields = taobaokeItem.fields
request['fields'] = fi... | [
"def",
"items_convert",
"(",
"self",
",",
"fields",
"=",
"[",
"]",
",",
"*",
"*",
"kwargs",
")",
":",
"request",
"=",
"TOPRequest",
"(",
"'taobao.taobaoke.items.convert'",
")",
"if",
"not",
"fields",
":",
"taobaokeItem",
"=",
"TaobaokeItem",
"(",
")",
"fie... | taobao.taobaoke.items.convert 淘客商品转换
淘宝客商品转换 | [
"taobao",
".",
"taobaoke",
".",
"items",
".",
"convert",
"淘客商品转换",
"淘宝客商品转换"
] | python | train | 45.785714 |
kadrlica/pymodeler | pymodeler/parameter.py | https://github.com/kadrlica/pymodeler/blob/f426c01416fd4b8fc3afeeb6d3b5d1cb0cb8f8e3/pymodeler/parameter.py#L613-L618 | def set_free(self, free):
"""Set free/fixed status """
if free is None:
self.__free__ = False
return
self.__free__ = bool(free) | [
"def",
"set_free",
"(",
"self",
",",
"free",
")",
":",
"if",
"free",
"is",
"None",
":",
"self",
".",
"__free__",
"=",
"False",
"return",
"self",
".",
"__free__",
"=",
"bool",
"(",
"free",
")"
] | Set free/fixed status | [
"Set",
"free",
"/",
"fixed",
"status"
] | python | test | 28.333333 |
devassistant/devassistant | devassistant/lang.py | https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/lang.py#L534-L545 | def parse(self, expression):
"""
Evaluates 'expression' and returns it's value(s)
"""
if isinstance(expression, (list, dict)):
return (True if expression else False, expression)
if sys.version_info[0] > 2:
self.next = self.tokenize(expression).__next__
... | [
"def",
"parse",
"(",
"self",
",",
"expression",
")",
":",
"if",
"isinstance",
"(",
"expression",
",",
"(",
"list",
",",
"dict",
")",
")",
":",
"return",
"(",
"True",
"if",
"expression",
"else",
"False",
",",
"expression",
")",
"if",
"sys",
".",
"vers... | Evaluates 'expression' and returns it's value(s) | [
"Evaluates",
"expression",
"and",
"returns",
"it",
"s",
"value",
"(",
"s",
")"
] | python | train | 36.666667 |
tdryer/hangups | hangups/client.py | https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/client.py#L486-L491 | async def create_conversation(self, create_conversation_request):
"""Create a new conversation."""
response = hangouts_pb2.CreateConversationResponse()
await self._pb_request('conversations/createconversation',
create_conversation_request, response)
return ... | [
"async",
"def",
"create_conversation",
"(",
"self",
",",
"create_conversation_request",
")",
":",
"response",
"=",
"hangouts_pb2",
".",
"CreateConversationResponse",
"(",
")",
"await",
"self",
".",
"_pb_request",
"(",
"'conversations/createconversation'",
",",
"create_c... | Create a new conversation. | [
"Create",
"a",
"new",
"conversation",
"."
] | python | valid | 53.833333 |
fhamborg/news-please | newsplease/helper_classes/sub_classes/heuristics_manager.py | https://github.com/fhamborg/news-please/blob/731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9/newsplease/helper_classes/sub_classes/heuristics_manager.py#L69-L110 | def __get_condition(self, url):
"""
Gets the condition for a url and validates it.
:param str url: The url to get the condition for
"""
if self.__heuristics_condition is not None:
return self.__heuristics_condition
if "pass_heuristics_condition" in self.__sit... | [
"def",
"__get_condition",
"(",
"self",
",",
"url",
")",
":",
"if",
"self",
".",
"__heuristics_condition",
"is",
"not",
"None",
":",
"return",
"self",
".",
"__heuristics_condition",
"if",
"\"pass_heuristics_condition\"",
"in",
"self",
".",
"__sites_object",
"[",
... | Gets the condition for a url and validates it.
:param str url: The url to get the condition for | [
"Gets",
"the",
"condition",
"for",
"a",
"url",
"and",
"validates",
"it",
"."
] | python | train | 42.5 |
aio-libs/aioredis | aioredis/commands/string.py | https://github.com/aio-libs/aioredis/blob/e8c33e39558d4cc91cf70dde490d8b330c97dc2e/aioredis/commands/string.py#L234-L244 | def setrange(self, key, offset, value):
"""Overwrite part of a string at key starting at the specified offset.
:raises TypeError: if offset is not int
:raises ValueError: if offset less than 0
"""
if not isinstance(offset, int):
raise TypeError("offset argument must ... | [
"def",
"setrange",
"(",
"self",
",",
"key",
",",
"offset",
",",
"value",
")",
":",
"if",
"not",
"isinstance",
"(",
"offset",
",",
"int",
")",
":",
"raise",
"TypeError",
"(",
"\"offset argument must be int\"",
")",
"if",
"offset",
"<",
"0",
":",
"raise",
... | Overwrite part of a string at key starting at the specified offset.
:raises TypeError: if offset is not int
:raises ValueError: if offset less than 0 | [
"Overwrite",
"part",
"of",
"a",
"string",
"at",
"key",
"starting",
"at",
"the",
"specified",
"offset",
"."
] | python | train | 42.272727 |
materialsproject/pymatgen | pymatgen/transformations/advanced_transformations.py | https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/transformations/advanced_transformations.py#L526-L547 | def satisfies_constraint(self, site):
"""
Checks if a periodic site satisfies the constraint.
"""
if not site.is_ordered:
return False
if self.species_constraints \
and str(site.specie) in self.species_constraints:
satisfies_constraints = ... | [
"def",
"satisfies_constraint",
"(",
"self",
",",
"site",
")",
":",
"if",
"not",
"site",
".",
"is_ordered",
":",
"return",
"False",
"if",
"self",
".",
"species_constraints",
"and",
"str",
"(",
"site",
".",
"specie",
")",
"in",
"self",
".",
"species_constrai... | Checks if a periodic site satisfies the constraint. | [
"Checks",
"if",
"a",
"periodic",
"site",
"satisfies",
"the",
"constraint",
"."
] | python | train | 32.727273 |
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#L4255-L4279 | def patch_namespaced_deployment_scale(self, name, namespace, body, **kwargs): # noqa: E501
"""patch_namespaced_deployment_scale # noqa: E501
partially update scale of the specified Deployment # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronou... | [
"def",
"patch_namespaced_deployment_scale",
"(",
"self",
",",
"name",
",",
"namespace",
",",
"body",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async_req'",... | patch_namespaced_deployment_scale # noqa: E501
partially update scale of the specified Deployment # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.patch_namespaced_deployment_scale(n... | [
"patch_namespaced_deployment_scale",
"#",
"noqa",
":",
"E501"
] | python | train | 62.92 |
iotile/coretools | iotileemulate/iotile/emulate/internal/emulation_loop.py | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/internal/emulation_loop.py#L434-L449 | async def stop_tasks(self, address):
"""Clear all tasks pertaining to a tile.
This coroutine will synchronously cancel all running tasks that were
attached to the given tile and wait for them to stop before returning.
Args:
address (int): The address of the tile we should s... | [
"async",
"def",
"stop_tasks",
"(",
"self",
",",
"address",
")",
":",
"tasks",
"=",
"self",
".",
"_tasks",
".",
"get",
"(",
"address",
",",
"[",
"]",
")",
"for",
"task",
"in",
"tasks",
":",
"task",
".",
"cancel",
"(",
")",
"asyncio",
".",
"gather",
... | Clear all tasks pertaining to a tile.
This coroutine will synchronously cancel all running tasks that were
attached to the given tile and wait for them to stop before returning.
Args:
address (int): The address of the tile we should stop. | [
"Clear",
"all",
"tasks",
"pertaining",
"to",
"a",
"tile",
"."
] | python | train | 31.875 |
carlcarl/grabflickr | grabflickr/grabflickr.py | https://github.com/carlcarl/grabflickr/blob/e9cb2365de80c1819cfd5083c032d0d985f3c614/grabflickr/grabflickr.py#L349-L363 | def _gevent_patch():
"""Patch the modules with gevent
:return: Default is GEVENT. If it not supports gevent then return MULTITHREAD
:rtype: int
"""
try:
assert gevent
assert grequests
except NameError:
logger.warn('gevent not exist, fallback to multiprocess...')
... | [
"def",
"_gevent_patch",
"(",
")",
":",
"try",
":",
"assert",
"gevent",
"assert",
"grequests",
"except",
"NameError",
":",
"logger",
".",
"warn",
"(",
"'gevent not exist, fallback to multiprocess...'",
")",
"return",
"MULTITHREAD",
"else",
":",
"monkey",
".",
"patc... | Patch the modules with gevent
:return: Default is GEVENT. If it not supports gevent then return MULTITHREAD
:rtype: int | [
"Patch",
"the",
"modules",
"with",
"gevent"
] | python | train | 28 |
micha030201/aionationstates | aionationstates/happenings.py | https://github.com/micha030201/aionationstates/blob/dc86b86d994cbab830b69ab8023601c73e778b3a/aionationstates/happenings.py#L437-L457 | async def proposal(self):
"""Get the proposal in question.
Actually just the first proposal with the same name, but the
chance of a collision is tiny.
Returns
-------
awaitable of :class:`aionationstates.Proposal`
The proposal submitted.
Raises
... | [
"async",
"def",
"proposal",
"(",
"self",
")",
":",
"proposals",
"=",
"await",
"aionationstates",
".",
"wa",
".",
"proposals",
"(",
")",
"for",
"proposal",
"in",
"proposals",
":",
"if",
"(",
"proposal",
".",
"name",
"==",
"self",
".",
"proposal_name",
")"... | Get the proposal in question.
Actually just the first proposal with the same name, but the
chance of a collision is tiny.
Returns
-------
awaitable of :class:`aionationstates.Proposal`
The proposal submitted.
Raises
------
aionationstates.No... | [
"Get",
"the",
"proposal",
"in",
"question",
"."
] | python | train | 30.380952 |
materialsproject/pymatgen | pymatgen/analysis/local_env.py | https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/analysis/local_env.py#L487-L507 | def _get_image(structure, site):
"""Private convenience method for get_nn_info,
gives lattice image from provided PeriodicSite and Structure.
Image is defined as displacement from original site in structure to a given site.
i.e. if structure has a site at (-0.1, 1.0, 0.3), then (0.9, 0,... | [
"def",
"_get_image",
"(",
"structure",
",",
"site",
")",
":",
"original_site",
"=",
"structure",
"[",
"NearNeighbors",
".",
"_get_original_site",
"(",
"structure",
",",
"site",
")",
"]",
"image",
"=",
"np",
".",
"around",
"(",
"np",
".",
"subtract",
"(",
... | Private convenience method for get_nn_info,
gives lattice image from provided PeriodicSite and Structure.
Image is defined as displacement from original site in structure to a given site.
i.e. if structure has a site at (-0.1, 1.0, 0.3), then (0.9, 0, 2.3) -> jimage = (1, -1, 2).
Note t... | [
"Private",
"convenience",
"method",
"for",
"get_nn_info",
"gives",
"lattice",
"image",
"from",
"provided",
"PeriodicSite",
"and",
"Structure",
"."
] | python | train | 40.095238 |
awslabs/sockeye | sockeye/utils.py | https://github.com/awslabs/sockeye/blob/5d64a1ee1ef3cbba17c6d1d94bc061020c43f6ab/sockeye/utils.py#L395-L430 | def print_attention_text(attention_matrix: np.ndarray, source_tokens: List[str], target_tokens: List[str],
threshold: float):
"""
Prints the attention matrix to standard out.
:param attention_matrix: The attention matrix.
:param source_tokens: A list of source tokens.
:para... | [
"def",
"print_attention_text",
"(",
"attention_matrix",
":",
"np",
".",
"ndarray",
",",
"source_tokens",
":",
"List",
"[",
"str",
"]",
",",
"target_tokens",
":",
"List",
"[",
"str",
"]",
",",
"threshold",
":",
"float",
")",
":",
"sys",
".",
"stdout",
"."... | Prints the attention matrix to standard out.
:param attention_matrix: The attention matrix.
:param source_tokens: A list of source tokens.
:param target_tokens: A list of target tokens.
:param threshold: The threshold for including an alignment link in the result. | [
"Prints",
"the",
"attention",
"matrix",
"to",
"standard",
"out",
"."
] | python | train | 37.694444 |
ga4gh/ga4gh-server | oidc-provider/simple_op/src/provider/server/server.py | https://github.com/ga4gh/ga4gh-server/blob/1aa18922ef136db8604f6f098cb1732cba6f2a76/oidc-provider/simple_op/src/provider/server/server.py#L107-L126 | def setup_endpoints(provider):
"""Setup the OpenID Connect Provider endpoints."""
app_routing = {}
endpoints = [
AuthorizationEndpoint(
pyoidcMiddleware(provider.authorization_endpoint)),
TokenEndpoint(
pyoidcMiddleware(provider.token_endpoint)),
UserinfoEndpo... | [
"def",
"setup_endpoints",
"(",
"provider",
")",
":",
"app_routing",
"=",
"{",
"}",
"endpoints",
"=",
"[",
"AuthorizationEndpoint",
"(",
"pyoidcMiddleware",
"(",
"provider",
".",
"authorization_endpoint",
")",
")",
",",
"TokenEndpoint",
"(",
"pyoidcMiddleware",
"("... | Setup the OpenID Connect Provider endpoints. | [
"Setup",
"the",
"OpenID",
"Connect",
"Provider",
"endpoints",
"."
] | python | train | 32.5 |
ihmeuw/vivarium | src/vivarium/framework/randomness.py | https://github.com/ihmeuw/vivarium/blob/c5f5d50f775c8bf337d3aae1ff7c57c025a8e258/src/vivarium/framework/randomness.py#L84-L118 | def hash_(self, keys: Index, salt: int = 0) -> pd.Series:
"""Hashes the given index into an integer index in the range [0, self.stride]
Parameters
----------
keys :
The new index to hash.
salt :
An integer used to perturb the hash in a deterministic way. ... | [
"def",
"hash_",
"(",
"self",
",",
"keys",
":",
"Index",
",",
"salt",
":",
"int",
"=",
"0",
")",
"->",
"pd",
".",
"Series",
":",
"key_frame",
"=",
"keys",
".",
"to_frame",
"(",
")",
"new_map",
"=",
"pd",
".",
"Series",
"(",
"0",
",",
"index",
"=... | Hashes the given index into an integer index in the range [0, self.stride]
Parameters
----------
keys :
The new index to hash.
salt :
An integer used to perturb the hash in a deterministic way. Useful
in dealing with collisions.
Returns
... | [
"Hashes",
"the",
"given",
"index",
"into",
"an",
"integer",
"index",
"in",
"the",
"range",
"[",
"0",
"self",
".",
"stride",
"]"
] | python | train | 41.285714 |
saltstack/salt | salt/client/ssh/__init__.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/client/ssh/__init__.py#L945-L955 | def _escape_arg(self, arg):
'''
Properly escape argument to protect special characters from shell
interpretation. This avoids having to do tricky argument quoting.
Effectively just escape all characters in the argument that are not
alphanumeric!
'''
if self.winr... | [
"def",
"_escape_arg",
"(",
"self",
",",
"arg",
")",
":",
"if",
"self",
".",
"winrm",
":",
"return",
"arg",
"return",
"''",
".",
"join",
"(",
"[",
"'\\\\'",
"+",
"char",
"if",
"re",
".",
"match",
"(",
"r'\\W'",
",",
"char",
")",
"else",
"char",
"f... | Properly escape argument to protect special characters from shell
interpretation. This avoids having to do tricky argument quoting.
Effectively just escape all characters in the argument that are not
alphanumeric! | [
"Properly",
"escape",
"argument",
"to",
"protect",
"special",
"characters",
"from",
"shell",
"interpretation",
".",
"This",
"avoids",
"having",
"to",
"do",
"tricky",
"argument",
"quoting",
"."
] | python | train | 38.545455 |
huge-success/sanic | sanic/app.py | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/app.py#L629-L679 | def static(
self,
uri,
file_or_directory,
pattern=r"/?.+",
use_modified_since=True,
use_content_range=False,
stream_large_files=False,
name="static",
host=None,
strict_slashes=None,
content_type=None,
):
"""
Regi... | [
"def",
"static",
"(",
"self",
",",
"uri",
",",
"file_or_directory",
",",
"pattern",
"=",
"r\"/?.+\"",
",",
"use_modified_since",
"=",
"True",
",",
"use_content_range",
"=",
"False",
",",
"stream_large_files",
"=",
"False",
",",
"name",
"=",
"\"static\"",
",",
... | Register a root to serve files from. The input can either be a
file or a directory. This method will enable an easy and simple way
to setup the :class:`Route` necessary to serve the static files.
:param uri: URL path to be used for serving static content
:param file_or_directory: Path f... | [
"Register",
"a",
"root",
"to",
"serve",
"files",
"from",
".",
"The",
"input",
"can",
"either",
"be",
"a",
"file",
"or",
"a",
"directory",
".",
"This",
"method",
"will",
"enable",
"an",
"easy",
"and",
"simple",
"way",
"to",
"setup",
"the",
":",
"class",... | python | train | 38.627451 |
ejeschke/ginga | ginga/util/heaptimer.py | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/util/heaptimer.py#L209-L217 | def remove(self, timer):
"""Remove a timer from the heap, return True if already run"""
with self.lock:
# This is somewhat expensive as we have to heapify.
if timer in self.timers:
self._remove(timer)
return False
else:
... | [
"def",
"remove",
"(",
"self",
",",
"timer",
")",
":",
"with",
"self",
".",
"lock",
":",
"# This is somewhat expensive as we have to heapify.",
"if",
"timer",
"in",
"self",
".",
"timers",
":",
"self",
".",
"_remove",
"(",
"timer",
")",
"return",
"False",
"els... | Remove a timer from the heap, return True if already run | [
"Remove",
"a",
"timer",
"from",
"the",
"heap",
"return",
"True",
"if",
"already",
"run"
] | python | train | 35.888889 |
AguaClara/aguaclara | aguaclara/design/lfom.py | https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/design/lfom.py#L133-L156 | def flow_actual(self, Row_Index_Submerged, N_LFOM_Orifices):
"""Calculates the flow for a given number of submerged rows of orifices
harray is the distance from the water level to the center of the
orifices when the water is at the max level.
Parameters
----------
Row_Ind... | [
"def",
"flow_actual",
"(",
"self",
",",
"Row_Index_Submerged",
",",
"N_LFOM_Orifices",
")",
":",
"flow",
"=",
"0",
"for",
"i",
"in",
"range",
"(",
"Row_Index_Submerged",
"+",
"1",
")",
":",
"flow",
"=",
"flow",
"+",
"(",
"N_LFOM_Orifices",
"[",
"i",
"]",... | Calculates the flow for a given number of submerged rows of orifices
harray is the distance from the water level to the center of the
orifices when the water is at the max level.
Parameters
----------
Row_Index_Submerged: int
The index of the submerged row. All rows bel... | [
"Calculates",
"the",
"flow",
"for",
"a",
"given",
"number",
"of",
"submerged",
"rows",
"of",
"orifices",
"harray",
"is",
"the",
"distance",
"from",
"the",
"water",
"level",
"to",
"the",
"center",
"of",
"the",
"orifices",
"when",
"the",
"water",
"is",
"at",... | python | train | 41.708333 |
modin-project/modin | modin/pandas/__init__.py | https://github.com/modin-project/modin/blob/5b77d242596560c646b8405340c9ce64acb183cb/modin/pandas/__init__.py#L133-L168 | def initialize_ray():
"""Initializes ray based on environment variables and internal defaults."""
if threading.current_thread().name == "MainThread":
plasma_directory = None
object_store_memory = os.environ.get("MODIN_MEMORY", None)
if os.environ.get("MODIN_OUT_OF_CORE", "False").title()... | [
"def",
"initialize_ray",
"(",
")",
":",
"if",
"threading",
".",
"current_thread",
"(",
")",
".",
"name",
"==",
"\"MainThread\"",
":",
"plasma_directory",
"=",
"None",
"object_store_memory",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"\"MODIN_MEMORY\"",
",",
... | Initializes ray based on environment variables and internal defaults. | [
"Initializes",
"ray",
"based",
"on",
"environment",
"variables",
"and",
"internal",
"defaults",
"."
] | python | train | 49.722222 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.