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 |
|---|---|---|---|---|---|---|---|---|---|
Yelp/kafka-utils | kafka_utils/util/__init__.py | https://github.com/Yelp/kafka-utils/blob/cdb4d64308f3079ee0873250bf7b34d0d94eca50/kafka_utils/util/__init__.py#L76-L85 | def positive_nonzero_int(string):
"""Convert string to positive integer greater than zero."""
error_msg = 'Positive non-zero integer required, {string} given.'.format(string=string)
try:
value = int(string)
except ValueError:
raise ArgumentTypeError(error_msg)
if value <= 0:
... | [
"def",
"positive_nonzero_int",
"(",
"string",
")",
":",
"error_msg",
"=",
"'Positive non-zero integer required, {string} given.'",
".",
"format",
"(",
"string",
"=",
"string",
")",
"try",
":",
"value",
"=",
"int",
"(",
"string",
")",
"except",
"ValueError",
":",
... | Convert string to positive integer greater than zero. | [
"Convert",
"string",
"to",
"positive",
"integer",
"greater",
"than",
"zero",
"."
] | python | train | 36.2 |
mozilla/mozdownload | mozdownload/utils.py | https://github.com/mozilla/mozdownload/blob/97796a028455bb5200434562d23b66d5a5eb537b/mozdownload/utils.py#L12-L18 | def urljoin(*fragments):
"""Concatenate multi part strings into urls."""
# Strip possible already existent final slashes of fragments except for the last one
parts = [fragment.rstrip('/') for fragment in fragments[:len(fragments) - 1]]
parts.append(fragments[-1])
return '/'.join(parts) | [
"def",
"urljoin",
"(",
"*",
"fragments",
")",
":",
"# Strip possible already existent final slashes of fragments except for the last one",
"parts",
"=",
"[",
"fragment",
".",
"rstrip",
"(",
"'/'",
")",
"for",
"fragment",
"in",
"fragments",
"[",
":",
"len",
"(",
"fra... | Concatenate multi part strings into urls. | [
"Concatenate",
"multi",
"part",
"strings",
"into",
"urls",
"."
] | python | train | 43 |
AkihikoITOH/capybara | capybara/virtualenv/lib/python2.7/site-packages/werkzeug/wrappers.py | https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/werkzeug/wrappers.py#L370-L380 | def _get_stream_for_parsing(self):
"""This is the same as accessing :attr:`stream` with the difference
that if it finds cached data from calling :meth:`get_data` first it
will create a new stream out of the cached data.
.. versionadded:: 0.9.3
"""
cached_data = getattr(s... | [
"def",
"_get_stream_for_parsing",
"(",
"self",
")",
":",
"cached_data",
"=",
"getattr",
"(",
"self",
",",
"'_cached_data'",
",",
"None",
")",
"if",
"cached_data",
"is",
"not",
"None",
":",
"return",
"BytesIO",
"(",
"cached_data",
")",
"return",
"self",
".",
... | This is the same as accessing :attr:`stream` with the difference
that if it finds cached data from calling :meth:`get_data` first it
will create a new stream out of the cached data.
.. versionadded:: 0.9.3 | [
"This",
"is",
"the",
"same",
"as",
"accessing",
":",
"attr",
":",
"stream",
"with",
"the",
"difference",
"that",
"if",
"it",
"finds",
"cached",
"data",
"from",
"calling",
":",
"meth",
":",
"get_data",
"first",
"it",
"will",
"create",
"a",
"new",
"stream"... | python | test | 39.909091 |
saltstack/salt | salt/states/file.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/file.py#L3068-L3088 | def _get_recurse_set(recurse):
'''
Converse *recurse* definition to a set of strings.
Raises TypeError or ValueError when *recurse* has wrong structure.
'''
if not recurse:
return set()
if not isinstance(recurse, list):
raise TypeError('"recurse" must be formed as a list of stri... | [
"def",
"_get_recurse_set",
"(",
"recurse",
")",
":",
"if",
"not",
"recurse",
":",
"return",
"set",
"(",
")",
"if",
"not",
"isinstance",
"(",
"recurse",
",",
"list",
")",
":",
"raise",
"TypeError",
"(",
"'\"recurse\" must be formed as a list of strings'",
")",
... | Converse *recurse* definition to a set of strings.
Raises TypeError or ValueError when *recurse* has wrong structure. | [
"Converse",
"*",
"recurse",
"*",
"definition",
"to",
"a",
"set",
"of",
"strings",
"."
] | python | train | 41.666667 |
Crunch-io/crunch-cube | src/cr/cube/cube_slice.py | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/cube_slice.py#L552-L564 | def pairwise_indices(self, alpha=0.05, only_larger=True, hs_dims=None):
"""Indices of columns where p < alpha for column-comparison t-tests
Returns an array of tuples of columns that are significant at p<alpha,
from a series of pairwise t-tests.
Argument both_pairs returns indices stri... | [
"def",
"pairwise_indices",
"(",
"self",
",",
"alpha",
"=",
"0.05",
",",
"only_larger",
"=",
"True",
",",
"hs_dims",
"=",
"None",
")",
":",
"return",
"PairwiseSignificance",
"(",
"self",
",",
"alpha",
"=",
"alpha",
",",
"only_larger",
"=",
"only_larger",
",... | Indices of columns where p < alpha for column-comparison t-tests
Returns an array of tuples of columns that are significant at p<alpha,
from a series of pairwise t-tests.
Argument both_pairs returns indices striclty on the test statistic. If
False, however, only the index of values *si... | [
"Indices",
"of",
"columns",
"where",
"p",
"<",
"alpha",
"for",
"column",
"-",
"comparison",
"t",
"-",
"tests"
] | python | train | 45.923077 |
basecrm/basecrm-python | basecrm/http_client.py | https://github.com/basecrm/basecrm-python/blob/7c1cf97dbaba8aeb9ff89f8a54f945a8702349f6/basecrm/http_client.py#L62-L73 | def put(self, url, body=None, **kwargs):
"""
Send a PUT request.
:param str url: Sub URL for the request. You MUST not specify neither base url nor api version prefix.
:param dict body: (optional) Dictionary of body attributes that will be wrapped with envelope and json encoded.
... | [
"def",
"put",
"(",
"self",
",",
"url",
",",
"body",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"request",
"(",
"'put'",
",",
"url",
",",
"body",
"=",
"body",
",",
"*",
"*",
"kwargs",
")"
] | Send a PUT request.
:param str url: Sub URL for the request. You MUST not specify neither base url nor api version prefix.
:param dict body: (optional) Dictionary of body attributes that will be wrapped with envelope and json encoded.
:param dict **kwargs: (optional) Other parameters which are ... | [
"Send",
"a",
"PUT",
"request",
"."
] | python | train | 52.083333 |
jobovy/galpy | galpy/util/bovy_coords.py | https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/util/bovy_coords.py#L906-L950 | def XYZ_to_galcenrect(X,Y,Z,Xsun=1.,Zsun=0.,_extra_rot=True):
"""
NAME:
XYZ_to_galcenrect
PURPOSE:
transform XYZ coordinates (wrt Sun) to rectangular Galactocentric coordinates
INPUT:
X - X
Y - Y
Z - Z
Xsun - cylindrical distance to the GC
... | [
"def",
"XYZ_to_galcenrect",
"(",
"X",
",",
"Y",
",",
"Z",
",",
"Xsun",
"=",
"1.",
",",
"Zsun",
"=",
"0.",
",",
"_extra_rot",
"=",
"True",
")",
":",
"if",
"_extra_rot",
":",
"X",
",",
"Y",
",",
"Z",
"=",
"nu",
".",
"dot",
"(",
"galcen_extra_rot",
... | NAME:
XYZ_to_galcenrect
PURPOSE:
transform XYZ coordinates (wrt Sun) to rectangular Galactocentric coordinates
INPUT:
X - X
Y - Y
Z - Z
Xsun - cylindrical distance to the GC
Zsun - Sun's height above the midplane
_extra_rot= (True) if True... | [
"NAME",
":"
] | python | train | 25.133333 |
svenevs/exhale | exhale/parse.py | https://github.com/svenevs/exhale/blob/fe7644829057af622e467bb529db6c03a830da99/exhale/parse.py#L22-L167 | def walk(textRoot, currentTag, level, prefix=None, postfix=None, unwrapUntilPara=False):
'''
.. note::
This method does not cover all possible input doxygen types! This means that
when an unsupported / unrecognized doxygen tag appears in the xml listing, the
**raw xml will appear on the f... | [
"def",
"walk",
"(",
"textRoot",
",",
"currentTag",
",",
"level",
",",
"prefix",
"=",
"None",
",",
"postfix",
"=",
"None",
",",
"unwrapUntilPara",
"=",
"False",
")",
":",
"if",
"not",
"currentTag",
":",
"return",
"if",
"prefix",
":",
"currentTag",
".",
... | .. note::
This method does not cover all possible input doxygen types! This means that
when an unsupported / unrecognized doxygen tag appears in the xml listing, the
**raw xml will appear on the file page being documented**. This traverser is
greedily designed to work for what testing rev... | [
"..",
"note",
"::"
] | python | train | 42.863014 |
rackerlabs/rackspace-python-neutronclient | neutronclient/v2_0/client.py | https://github.com/rackerlabs/rackspace-python-neutronclient/blob/5a5009a8fe078e3aa1d582176669f1b28ab26bef/neutronclient/v2_0/client.py#L1608-L1613 | def list_dscp_marking_rules(self, policy_id,
retrieve_all=True, **_params):
"""Fetches a list of all DSCP marking rules for the given policy."""
return self.list('dscp_marking_rules',
self.qos_dscp_marking_rules_path % policy_id,
... | [
"def",
"list_dscp_marking_rules",
"(",
"self",
",",
"policy_id",
",",
"retrieve_all",
"=",
"True",
",",
"*",
"*",
"_params",
")",
":",
"return",
"self",
".",
"list",
"(",
"'dscp_marking_rules'",
",",
"self",
".",
"qos_dscp_marking_rules_path",
"%",
"policy_id",
... | Fetches a list of all DSCP marking rules for the given policy. | [
"Fetches",
"a",
"list",
"of",
"all",
"DSCP",
"marking",
"rules",
"for",
"the",
"given",
"policy",
"."
] | python | train | 57.833333 |
inveniosoftware/invenio-deposit | invenio_deposit/api.py | https://github.com/inveniosoftware/invenio-deposit/blob/f243ea1d01ab0a3bc92ade3262d1abdd2bc32447/invenio_deposit/api.py#L204-L206 | def commit(self, *args, **kwargs):
"""Store changes on current instance in database and index it."""
return super(Deposit, self).commit(*args, **kwargs) | [
"def",
"commit",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"super",
"(",
"Deposit",
",",
"self",
")",
".",
"commit",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Store changes on current instance in database and index it. | [
"Store",
"changes",
"on",
"current",
"instance",
"in",
"database",
"and",
"index",
"it",
"."
] | python | valid | 55.333333 |
cltk/cltk | cltk/corpus/arabic/utils/pyarabic/araby.py | https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/corpus/arabic/utils/pyarabic/araby.py#L1068-L1086 | def tokenize(text=""):
"""
Tokenize text into words.
@param text: the input text.
@type text: unicode.
@return: list of words.
@rtype: list.
"""
if text == '':
return []
else:
# split tokens
mylist = TOKEN_PATTERN.split(text)
# don't remove newline \n... | [
"def",
"tokenize",
"(",
"text",
"=",
"\"\"",
")",
":",
"if",
"text",
"==",
"''",
":",
"return",
"[",
"]",
"else",
":",
"# split tokens",
"mylist",
"=",
"TOKEN_PATTERN",
".",
"split",
"(",
"text",
")",
"# don't remove newline \\n",
"mylist",
"=",
"[",
"TO... | Tokenize text into words.
@param text: the input text.
@type text: unicode.
@return: list of words.
@rtype: list. | [
"Tokenize",
"text",
"into",
"words",
"."
] | python | train | 24.421053 |
mental32/spotify.py | spotify/models/player.py | https://github.com/mental32/spotify.py/blob/bb296cac7c3dd289908906b7069bd80f43950515/spotify/models/player.py#L74-L83 | async def pause(self, *, device: Optional[SomeDevice] = None):
"""Pause playback on the user’s account.
Parameters
----------
device : Optional[:obj:`SomeDevice`]
The Device object or id of the device this command is targeting.
If not supplied, the user’s current... | [
"async",
"def",
"pause",
"(",
"self",
",",
"*",
",",
"device",
":",
"Optional",
"[",
"SomeDevice",
"]",
"=",
"None",
")",
":",
"await",
"self",
".",
"_user",
".",
"http",
".",
"pause_playback",
"(",
"device_id",
"=",
"str",
"(",
"device",
")",
")"
] | Pause playback on the user’s account.
Parameters
----------
device : Optional[:obj:`SomeDevice`]
The Device object or id of the device this command is targeting.
If not supplied, the user’s currently active device is the target. | [
"Pause",
"playback",
"on",
"the",
"user’s",
"account",
"."
] | python | test | 42.2 |
kivy/python-for-android | pythonforandroid/recipes/openssl/__init__.py | https://github.com/kivy/python-for-android/blob/8e0e8056bc22e4d5bd3398a6b0301f38ff167933/pythonforandroid/recipes/openssl/__init__.py#L88-L93 | def include_flags(self, arch):
'''Returns a string with the include folders'''
openssl_includes = join(self.get_build_dir(arch.arch), 'include')
return (' -I' + openssl_includes +
' -I' + join(openssl_includes, 'internal') +
' -I' + join(openssl_includes, 'openssl... | [
"def",
"include_flags",
"(",
"self",
",",
"arch",
")",
":",
"openssl_includes",
"=",
"join",
"(",
"self",
".",
"get_build_dir",
"(",
"arch",
".",
"arch",
")",
",",
"'include'",
")",
"return",
"(",
"' -I'",
"+",
"openssl_includes",
"+",
"' -I'",
"+",
"joi... | Returns a string with the include folders | [
"Returns",
"a",
"string",
"with",
"the",
"include",
"folders"
] | python | train | 53 |
Polyconseil/django-cid | cid/locals.py | https://github.com/Polyconseil/django-cid/blob/43415c8bbc91aa03983384072dbc1d2ecdeb2852/cid/locals.py#L15-L28 | def get_cid():
"""Return the currently set correlation id (if any).
If no correlation id has been set and ``CID_GENERATE`` is enabled
in the settings, a new correlation id is set and returned.
FIXME (dbaty): in version 2, just `return getattr(_thread_locals, 'CID', None)`
We want the simplest thin... | [
"def",
"get_cid",
"(",
")",
":",
"cid",
"=",
"getattr",
"(",
"_thread_locals",
",",
"'CID'",
",",
"None",
")",
"if",
"cid",
"is",
"None",
"and",
"getattr",
"(",
"settings",
",",
"'CID_GENERATE'",
",",
"False",
")",
":",
"cid",
"=",
"str",
"(",
"uuid"... | Return the currently set correlation id (if any).
If no correlation id has been set and ``CID_GENERATE`` is enabled
in the settings, a new correlation id is set and returned.
FIXME (dbaty): in version 2, just `return getattr(_thread_locals, 'CID', None)`
We want the simplest thing here and let `genera... | [
"Return",
"the",
"currently",
"set",
"correlation",
"id",
"(",
"if",
"any",
")",
"."
] | python | train | 38.571429 |
crunchyroll/ef-open | efopen/ef_aws_resolver.py | https://github.com/crunchyroll/ef-open/blob/59fff3761af07a59f8f1c1682f2be004bdac15f7/efopen/ef_aws_resolver.py#L199-L216 | def ec2_security_group_security_group_id(self, lookup, default=None):
"""
Args:
lookup: the friendly name of a security group to look up
default: the optional value to return if lookup failed; returns None if not set
Returns:
Security group ID if target found or default/None if no match
... | [
"def",
"ec2_security_group_security_group_id",
"(",
"self",
",",
"lookup",
",",
"default",
"=",
"None",
")",
":",
"try",
":",
"response",
"=",
"EFAwsResolver",
".",
"__CLIENTS",
"[",
"\"ec2\"",
"]",
".",
"describe_security_groups",
"(",
"Filters",
"=",
"[",
"{... | Args:
lookup: the friendly name of a security group to look up
default: the optional value to return if lookup failed; returns None if not set
Returns:
Security group ID if target found or default/None if no match | [
"Args",
":",
"lookup",
":",
"the",
"friendly",
"name",
"of",
"a",
"security",
"group",
"to",
"look",
"up",
"default",
":",
"the",
"optional",
"value",
"to",
"return",
"if",
"lookup",
"failed",
";",
"returns",
"None",
"if",
"not",
"set",
"Returns",
":",
... | python | train | 34.444444 |
pandas-dev/pandas | pandas/core/indexes/base.py | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/base.py#L5393-L5400 | def _trim_front(strings):
"""
Trims zeros and decimal points.
"""
trimmed = strings
while len(strings) > 0 and all(x[0] == ' ' for x in trimmed):
trimmed = [x[1:] for x in trimmed]
return trimmed | [
"def",
"_trim_front",
"(",
"strings",
")",
":",
"trimmed",
"=",
"strings",
"while",
"len",
"(",
"strings",
")",
">",
"0",
"and",
"all",
"(",
"x",
"[",
"0",
"]",
"==",
"' '",
"for",
"x",
"in",
"trimmed",
")",
":",
"trimmed",
"=",
"[",
"x",
"[",
... | Trims zeros and decimal points. | [
"Trims",
"zeros",
"and",
"decimal",
"points",
"."
] | python | train | 27.5 |
edx/edx-enterprise | enterprise/api_client/discovery.py | https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api_client/discovery.py#L331-L345 | def get_program_course_keys(self, program_uuid):
"""
Get a list of the course IDs (not course run IDs) contained in the program.
Arguments:
program_uuid (str): Program UUID in string form
Returns:
list(str): List of course keys in string form that are included i... | [
"def",
"get_program_course_keys",
"(",
"self",
",",
"program_uuid",
")",
":",
"program_details",
"=",
"self",
".",
"get_program_by_uuid",
"(",
"program_uuid",
")",
"if",
"not",
"program_details",
":",
"return",
"[",
"]",
"return",
"[",
"course",
"[",
"'key'",
... | Get a list of the course IDs (not course run IDs) contained in the program.
Arguments:
program_uuid (str): Program UUID in string form
Returns:
list(str): List of course keys in string form that are included in the program | [
"Get",
"a",
"list",
"of",
"the",
"course",
"IDs",
"(",
"not",
"course",
"run",
"IDs",
")",
"contained",
"in",
"the",
"program",
"."
] | python | valid | 35.4 |
Microsoft/nni | tools/nni_trial_tool/hdfsClientUtility.py | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_trial_tool/hdfsClientUtility.py#L69-L91 | def copyDirectoryToHdfs(localDirectory, hdfsDirectory, hdfsClient):
'''Copy directory from local to HDFS'''
if not os.path.exists(localDirectory):
raise Exception('Local Directory does not exist!')
hdfsClient.mkdirs(hdfsDirectory)
result = True
for file in os.listdir(localDirectory):
... | [
"def",
"copyDirectoryToHdfs",
"(",
"localDirectory",
",",
"hdfsDirectory",
",",
"hdfsClient",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"localDirectory",
")",
":",
"raise",
"Exception",
"(",
"'Local Directory does not exist!'",
")",
"hdfsClient... | Copy directory from local to HDFS | [
"Copy",
"directory",
"from",
"local",
"to",
"HDFS"
] | python | train | 51.826087 |
RedisJSON/rejson-py | rejson/client.py | https://github.com/RedisJSON/rejson-py/blob/55f0adf3adc40f5a769e28e541dbbf5377b90ec6/rejson/client.py#L159-L164 | def jsonnumincrby(self, name, path, number):
"""
Increments the numeric (integer or floating point) JSON value under
``path`` at key ``name`` by the provided ``number``
"""
return self.execute_command('JSON.NUMINCRBY', name, str_path(path), self._encode(number)) | [
"def",
"jsonnumincrby",
"(",
"self",
",",
"name",
",",
"path",
",",
"number",
")",
":",
"return",
"self",
".",
"execute_command",
"(",
"'JSON.NUMINCRBY'",
",",
"name",
",",
"str_path",
"(",
"path",
")",
",",
"self",
".",
"_encode",
"(",
"number",
")",
... | Increments the numeric (integer or floating point) JSON value under
``path`` at key ``name`` by the provided ``number`` | [
"Increments",
"the",
"numeric",
"(",
"integer",
"or",
"floating",
"point",
")",
"JSON",
"value",
"under",
"path",
"at",
"key",
"name",
"by",
"the",
"provided",
"number"
] | python | train | 49.5 |
materialsproject/pymatgen | pymatgen/io/abinit/works.py | https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/io/abinit/works.py#L1190-L1232 | def create_tasks(self, wfk_file, scr_input):
"""
Create the SCR tasks and register them in self.
Args:
wfk_file: Path to the ABINIT WFK file to use for the computation of the screening.
scr_input: Input for the screening calculation.
"""
assert len(self) ... | [
"def",
"create_tasks",
"(",
"self",
",",
"wfk_file",
",",
"scr_input",
")",
":",
"assert",
"len",
"(",
"self",
")",
"==",
"0",
"wfk_file",
"=",
"self",
".",
"wfk_file",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"wfk_file",
")",
"# Build a temporary wo... | Create the SCR tasks and register them in self.
Args:
wfk_file: Path to the ABINIT WFK file to use for the computation of the screening.
scr_input: Input for the screening calculation. | [
"Create",
"the",
"SCR",
"tasks",
"and",
"register",
"them",
"in",
"self",
"."
] | python | train | 39.093023 |
log2timeline/dfvfs | dfvfs/vfs/file_system.py | https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/vfs/file_system.py#L82-L103 | def Close(self):
"""Closes the file system.
Raises:
IOError: if the file system object was not opened or the close failed.
OSError: if the file system object was not opened or the close failed.
"""
if not self._is_open:
raise IOError('Not opened.')
if not self._is_cached:
c... | [
"def",
"Close",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_is_open",
":",
"raise",
"IOError",
"(",
"'Not opened.'",
")",
"if",
"not",
"self",
".",
"_is_cached",
":",
"close_file_system",
"=",
"True",
"elif",
"self",
".",
"_resolver_context",
".",
... | Closes the file system.
Raises:
IOError: if the file system object was not opened or the close failed.
OSError: if the file system object was not opened or the close failed. | [
"Closes",
"the",
"file",
"system",
"."
] | python | train | 26.636364 |
pyapi-gitlab/pyapi-gitlab | gitlab/__init__.py | https://github.com/pyapi-gitlab/pyapi-gitlab/blob/f74b6fb5c13cecae9524997847e928905cc60acf/gitlab/__init__.py#L1637-L1653 | def searchproject(self, search, page=1, per_page=20):
"""
Search for projects by name which are accessible to the authenticated user
:param search: Query to search for
:param page: Page number
:param per_page: Records per page
:return: list of results
"""
... | [
"def",
"searchproject",
"(",
"self",
",",
"search",
",",
"page",
"=",
"1",
",",
"per_page",
"=",
"20",
")",
":",
"data",
"=",
"{",
"'page'",
":",
"page",
",",
"'per_page'",
":",
"per_page",
"}",
"request",
"=",
"requests",
".",
"get",
"(",
"\"{0}/{1}... | Search for projects by name which are accessible to the authenticated user
:param search: Query to search for
:param page: Page number
:param per_page: Records per page
:return: list of results | [
"Search",
"for",
"projects",
"by",
"name",
"which",
"are",
"accessible",
"to",
"the",
"authenticated",
"user"
] | python | train | 39 |
apache/spark | python/pyspark/mllib/linalg/distributed.py | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/mllib/linalg/distributed.py#L1051-L1071 | def blocks(self):
"""
The RDD of sub-matrix blocks
((blockRowIndex, blockColIndex), sub-matrix) that form this
distributed matrix.
>>> mat = BlockMatrix(
... sc.parallelize([((0, 0), Matrices.dense(3, 2, [1, 2, 3, 4, 5, 6])),
... ((1, 0), ... | [
"def",
"blocks",
"(",
"self",
")",
":",
"# We use DataFrames for serialization of sub-matrix blocks",
"# from Java, so we first convert the RDD of blocks to a",
"# DataFrame on the Scala/Java side. Then we map each Row in",
"# the DataFrame back to a sub-matrix block on this side.",
"blocks_df",... | The RDD of sub-matrix blocks
((blockRowIndex, blockColIndex), sub-matrix) that form this
distributed matrix.
>>> mat = BlockMatrix(
... sc.parallelize([((0, 0), Matrices.dense(3, 2, [1, 2, 3, 4, 5, 6])),
... ((1, 0), Matrices.dense(3, 2, [7, 8, 9, 10, 11,... | [
"The",
"RDD",
"of",
"sub",
"-",
"matrix",
"blocks",
"((",
"blockRowIndex",
"blockColIndex",
")",
"sub",
"-",
"matrix",
")",
"that",
"form",
"this",
"distributed",
"matrix",
"."
] | python | train | 45.47619 |
spotify/luigi | luigi/contrib/s3.py | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/s3.py#L197-L235 | def remove(self, path, recursive=True):
"""
Remove a file or directory from S3.
:param path: File or directory to remove
:param recursive: Boolean indicator to remove object and children
:return: Boolean indicator denoting success of the removal of 1 or more files
"""
... | [
"def",
"remove",
"(",
"self",
",",
"path",
",",
"recursive",
"=",
"True",
")",
":",
"if",
"not",
"self",
".",
"exists",
"(",
"path",
")",
":",
"logger",
".",
"debug",
"(",
"'Could not delete %s; path does not exist'",
",",
"path",
")",
"return",
"False",
... | Remove a file or directory from S3.
:param path: File or directory to remove
:param recursive: Boolean indicator to remove object and children
:return: Boolean indicator denoting success of the removal of 1 or more files | [
"Remove",
"a",
"file",
"or",
"directory",
"from",
"S3",
".",
":",
"param",
"path",
":",
"File",
"or",
"directory",
"to",
"remove",
":",
"param",
"recursive",
":",
"Boolean",
"indicator",
"to",
"remove",
"object",
"and",
"children",
":",
"return",
":",
"B... | python | train | 42.179487 |
googleapis/google-cloud-python | bigquery/google/cloud/bigquery/client.py | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery/google/cloud/bigquery/client.py#L487-L521 | def update_dataset(self, dataset, fields, retry=DEFAULT_RETRY):
"""Change some fields of a dataset.
Use ``fields`` to specify which fields to update. At least one field
must be provided. If a field is listed in ``fields`` and is ``None`` in
``dataset``, it will be deleted.
If `... | [
"def",
"update_dataset",
"(",
"self",
",",
"dataset",
",",
"fields",
",",
"retry",
"=",
"DEFAULT_RETRY",
")",
":",
"partial",
"=",
"dataset",
".",
"_build_resource",
"(",
"fields",
")",
"if",
"dataset",
".",
"etag",
"is",
"not",
"None",
":",
"headers",
"... | Change some fields of a dataset.
Use ``fields`` to specify which fields to update. At least one field
must be provided. If a field is listed in ``fields`` and is ``None`` in
``dataset``, it will be deleted.
If ``dataset.etag`` is not ``None``, the update will only
succeed if th... | [
"Change",
"some",
"fields",
"of",
"a",
"dataset",
"."
] | python | train | 42.057143 |
gwastro/pycbc | pycbc/tmpltbank/option_utils.py | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/tmpltbank/option_utils.py#L1184-L1206 | def check_ethinca_against_bank_params(ethincaParams, metricParams):
"""
Cross-check the ethinca and bank layout metric calculation parameters
and set the ethinca metric PN order equal to the bank PN order if not
previously set.
Parameters
----------
ethincaParams: instance of ethincaParamet... | [
"def",
"check_ethinca_against_bank_params",
"(",
"ethincaParams",
",",
"metricParams",
")",
":",
"if",
"ethincaParams",
".",
"doEthinca",
":",
"if",
"metricParams",
".",
"f0",
"!=",
"metricParams",
".",
"fLow",
":",
"raise",
"ValueError",
"(",
"\"If calculating ethi... | Cross-check the ethinca and bank layout metric calculation parameters
and set the ethinca metric PN order equal to the bank PN order if not
previously set.
Parameters
----------
ethincaParams: instance of ethincaParameters
metricParams: instance of metricParameters | [
"Cross",
"-",
"check",
"the",
"ethinca",
"and",
"bank",
"layout",
"metric",
"calculation",
"parameters",
"and",
"set",
"the",
"ethinca",
"metric",
"PN",
"order",
"equal",
"to",
"the",
"bank",
"PN",
"order",
"if",
"not",
"previously",
"set",
"."
] | python | train | 42.434783 |
hyperledger/indy-plenum | plenum/common/message_processor.py | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/common/message_processor.py#L18-L30 | def discard(self, msg, reason, logMethod=logging.error, cliOutput=False):
"""
Discard a message and log a reason using the specified `logMethod`.
:param msg: the message to discard
:param reason: the reason why this message is being discarded
:param logMethod: the logging functi... | [
"def",
"discard",
"(",
"self",
",",
"msg",
",",
"reason",
",",
"logMethod",
"=",
"logging",
".",
"error",
",",
"cliOutput",
"=",
"False",
")",
":",
"reason",
"=",
"\"\"",
"if",
"not",
"reason",
"else",
"\" because {}\"",
".",
"format",
"(",
"reason",
"... | Discard a message and log a reason using the specified `logMethod`.
:param msg: the message to discard
:param reason: the reason why this message is being discarded
:param logMethod: the logging function to be used
:param cliOutput: if truthy, informs a CLI that the logged msg should
... | [
"Discard",
"a",
"message",
"and",
"log",
"a",
"reason",
"using",
"the",
"specified",
"logMethod",
"."
] | python | train | 47.384615 |
materialsproject/pymatgen | pymatgen/io/vasp/inputs.py | https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/io/vasp/inputs.py#L1119-L1138 | def automatic_density_by_vol(structure, kppvol, force_gamma=False):
"""
Returns an automatic Kpoint object based on a structure and a kpoint
density per inverse Angstrom^3 of reciprocal cell.
Algorithm:
Same as automatic_density()
Args:
structure (Struct... | [
"def",
"automatic_density_by_vol",
"(",
"structure",
",",
"kppvol",
",",
"force_gamma",
"=",
"False",
")",
":",
"vol",
"=",
"structure",
".",
"lattice",
".",
"reciprocal_lattice",
".",
"volume",
"kppa",
"=",
"kppvol",
"*",
"vol",
"*",
"structure",
".",
"num_... | Returns an automatic Kpoint object based on a structure and a kpoint
density per inverse Angstrom^3 of reciprocal cell.
Algorithm:
Same as automatic_density()
Args:
structure (Structure): Input structure
kppvol (int): Grid density per Angstrom^(-3) of recipr... | [
"Returns",
"an",
"automatic",
"Kpoint",
"object",
"based",
"on",
"a",
"structure",
"and",
"a",
"kpoint",
"density",
"per",
"inverse",
"Angstrom^3",
"of",
"reciprocal",
"cell",
"."
] | python | train | 37 |
dagster-io/dagster | python_modules/dagster/dagster/core/execution.py | https://github.com/dagster-io/dagster/blob/4119f8c773089de64831b1dfb9e168e353d401dc/python_modules/dagster/dagster/core/execution.py#L141-L160 | def result_for_solid(self, name):
'''Get a :py:class:`SolidExecutionResult` for a given solid name.
'''
check.str_param(name, 'name')
if not self.pipeline.has_solid(name):
raise DagsterInvariantViolationError(
'Try to get result for solid {name} in {pipeline}... | [
"def",
"result_for_solid",
"(",
"self",
",",
"name",
")",
":",
"check",
".",
"str_param",
"(",
"name",
",",
"'name'",
")",
"if",
"not",
"self",
".",
"pipeline",
".",
"has_solid",
"(",
"name",
")",
":",
"raise",
"DagsterInvariantViolationError",
"(",
"'Try ... | Get a :py:class:`SolidExecutionResult` for a given solid name. | [
"Get",
"a",
":",
"py",
":",
"class",
":",
"SolidExecutionResult",
"for",
"a",
"given",
"solid",
"name",
"."
] | python | test | 36.1 |
saltstack/salt | salt/modules/zypperpkg.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zypperpkg.py#L214-L228 | def _is_error(self):
'''
Is this is an error code?
:return:
'''
if self.exit_code:
msg = self.SUCCESS_EXIT_CODES.get(self.exit_code)
if msg:
log.info(msg)
msg = self.WARNING_EXIT_CODES.get(self.exit_code)
if msg:
... | [
"def",
"_is_error",
"(",
"self",
")",
":",
"if",
"self",
".",
"exit_code",
":",
"msg",
"=",
"self",
".",
"SUCCESS_EXIT_CODES",
".",
"get",
"(",
"self",
".",
"exit_code",
")",
"if",
"msg",
":",
"log",
".",
"info",
"(",
"msg",
")",
"msg",
"=",
"self"... | Is this is an error code?
:return: | [
"Is",
"this",
"is",
"an",
"error",
"code?"
] | python | train | 29.866667 |
asweigart/pyautogui | pyautogui/__init__.py | https://github.com/asweigart/pyautogui/blob/77524bd47334a89024013fd48e05151c3ac9289a/pyautogui/__init__.py#L1125-L1149 | def displayMousePosition(xOffset=0, yOffset=0):
"""This function is meant to be run from the command line. It will
automatically display the location and RGB of the mouse cursor."""
print('Press Ctrl-C to quit.')
if xOffset != 0 or yOffset != 0:
print('xOffset: %s yOffset: %s' % (xOffset, yOffse... | [
"def",
"displayMousePosition",
"(",
"xOffset",
"=",
"0",
",",
"yOffset",
"=",
"0",
")",
":",
"print",
"(",
"'Press Ctrl-C to quit.'",
")",
"if",
"xOffset",
"!=",
"0",
"or",
"yOffset",
"!=",
"0",
":",
"print",
"(",
"'xOffset: %s yOffset: %s'",
"%",
"(",
"xO... | This function is meant to be run from the command line. It will
automatically display the location and RGB of the mouse cursor. | [
"This",
"function",
"is",
"meant",
"to",
"be",
"run",
"from",
"the",
"command",
"line",
".",
"It",
"will",
"automatically",
"display",
"the",
"location",
"and",
"RGB",
"of",
"the",
"mouse",
"cursor",
"."
] | python | train | 48.12 |
RudolfCardinal/pythonlib | cardinal_pythonlib/wsgi/reverse_proxied_mw.py | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/wsgi/reverse_proxied_mw.py#L241-L255 | def necessary(self) -> bool:
"""
Is any special handling (e.g. the addition of
:class:`ReverseProxiedMiddleware`) necessary for thie config?
"""
return any([
self.trusted_proxy_headers,
self.http_host,
self.remote_addr,
self.script_... | [
"def",
"necessary",
"(",
"self",
")",
"->",
"bool",
":",
"return",
"any",
"(",
"[",
"self",
".",
"trusted_proxy_headers",
",",
"self",
".",
"http_host",
",",
"self",
".",
"remote_addr",
",",
"self",
".",
"script_name",
",",
"self",
".",
"server_name",
",... | Is any special handling (e.g. the addition of
:class:`ReverseProxiedMiddleware`) necessary for thie config? | [
"Is",
"any",
"special",
"handling",
"(",
"e",
".",
"g",
".",
"the",
"addition",
"of",
":",
"class",
":",
"ReverseProxiedMiddleware",
")",
"necessary",
"for",
"thie",
"config?"
] | python | train | 29.8 |
rocky/python3-trepan | trepan/bwprocessor/main.py | https://github.com/rocky/python3-trepan/blob/14e91bc0acce090d67be145b1ac040cab92ac5f3/trepan/bwprocessor/main.py#L410-L445 | def _populate_commands(self):
""" Create an instance of each of the debugger
commands. Commands are found by importing files in the
directory 'command'. Some files are excluded via an array set
in __init__. For each of the remaining files, we import them
and scan for class names... | [
"def",
"_populate_commands",
"(",
"self",
")",
":",
"cmd_instances",
"=",
"[",
"]",
"from",
"trepan",
".",
"bwprocessor",
"import",
"command",
"as",
"Mcommand",
"eval_cmd_template",
"=",
"'command_mod.%s(self)'",
"for",
"mod_name",
"in",
"Mcommand",
".",
"__module... | Create an instance of each of the debugger
commands. Commands are found by importing files in the
directory 'command'. Some files are excluded via an array set
in __init__. For each of the remaining files, we import them
and scan for class names inside those files and for each class
... | [
"Create",
"an",
"instance",
"of",
"each",
"of",
"the",
"debugger",
"commands",
".",
"Commands",
"are",
"found",
"by",
"importing",
"files",
"in",
"the",
"directory",
"command",
".",
"Some",
"files",
"are",
"excluded",
"via",
"an",
"array",
"set",
"in",
"__... | python | test | 45.333333 |
Miserlou/Zappa | zappa/cli.py | https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/zappa/cli.py#L1225-L1258 | def unschedule(self):
"""
Given a a list of scheduled functions,
tear down their regular execution.
"""
# Run even if events are not defined to remove previously existing ones (thus default to []).
events = self.stage_config.get('events', [])
if not isinstance(... | [
"def",
"unschedule",
"(",
"self",
")",
":",
"# Run even if events are not defined to remove previously existing ones (thus default to []).",
"events",
"=",
"self",
".",
"stage_config",
".",
"get",
"(",
"'events'",
",",
"[",
"]",
")",
"if",
"not",
"isinstance",
"(",
"e... | Given a a list of scheduled functions,
tear down their regular execution. | [
"Given",
"a",
"a",
"list",
"of",
"scheduled",
"functions",
"tear",
"down",
"their",
"regular",
"execution",
"."
] | python | train | 41 |
theolind/pymysensors | mysensors/ota.py | https://github.com/theolind/pymysensors/blob/a139ab6e2f6b71ebaf37282f69bfd0f7fe6193b6/mysensors/ota.py#L130-L157 | def respond_fw_config(self, msg):
"""Respond to a firmware config request."""
(req_fw_type,
req_fw_ver,
req_blocks,
req_crc,
bloader_ver) = fw_hex_to_int(msg.payload, 5)
_LOGGER.debug(
'Received firmware config request with firmware type %s, '
... | [
"def",
"respond_fw_config",
"(",
"self",
",",
"msg",
")",
":",
"(",
"req_fw_type",
",",
"req_fw_ver",
",",
"req_blocks",
",",
"req_crc",
",",
"bloader_ver",
")",
"=",
"fw_hex_to_int",
"(",
"msg",
".",
"payload",
",",
"5",
")",
"_LOGGER",
".",
"debug",
"(... | Respond to a firmware config request. | [
"Respond",
"to",
"a",
"firmware",
"config",
"request",
"."
] | python | train | 42.892857 |
SuperCowPowers/workbench | workbench/server/bro/bro_log_reader.py | https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench/server/bro/bro_log_reader.py#L20-L48 | def read_log(self, logfile):
"""The read_log method returns a memory efficient generator for rows in a Bro log.
Usage:
rows = my_bro_reader.read_log(logfile)
for row in rows:
do something with row
Args:
logfile: The Bro Log file.
"""... | [
"def",
"read_log",
"(",
"self",
",",
"logfile",
")",
":",
"# Make sure we're at the beginning",
"logfile",
".",
"seek",
"(",
"0",
")",
"# First parse the header of the bro log",
"field_names",
",",
"_",
"=",
"self",
".",
"_parse_bro_header",
"(",
"logfile",
")",
"... | The read_log method returns a memory efficient generator for rows in a Bro log.
Usage:
rows = my_bro_reader.read_log(logfile)
for row in rows:
do something with row
Args:
logfile: The Bro Log file. | [
"The",
"read_log",
"method",
"returns",
"a",
"memory",
"efficient",
"generator",
"for",
"rows",
"in",
"a",
"Bro",
"log",
"."
] | python | train | 37.206897 |
JukeboxPipeline/jukebox-core | src/jukeboxcore/gui/treemodel.py | https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/gui/treemodel.py#L374-L389 | def set_parent(self, parent):
"""Set the parent of the treeitem
:param parent: parent treeitem
:type parent: :class:`TreeItem` | None
:returns: None
:rtype: None
:raises: None
"""
if self._parent == parent:
return
if self._parent:
... | [
"def",
"set_parent",
"(",
"self",
",",
"parent",
")",
":",
"if",
"self",
".",
"_parent",
"==",
"parent",
":",
"return",
"if",
"self",
".",
"_parent",
":",
"self",
".",
"_parent",
".",
"remove_child",
"(",
"self",
")",
"self",
".",
"_parent",
"=",
"pa... | Set the parent of the treeitem
:param parent: parent treeitem
:type parent: :class:`TreeItem` | None
:returns: None
:rtype: None
:raises: None | [
"Set",
"the",
"parent",
"of",
"the",
"treeitem"
] | python | train | 26.75 |
fastai/fastai | fastai/tabular/transform.py | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/tabular/transform.py#L43-L53 | def add_cyclic_datepart(df:DataFrame, field_name:str, prefix:str=None, drop:bool=True, time:bool=False, add_linear:bool=False):
"Helper function that adds trigonometric date/time features to a date in the column `field_name` of `df`."
make_date(df, field_name)
field = df[field_name]
prefix = ifnone(pref... | [
"def",
"add_cyclic_datepart",
"(",
"df",
":",
"DataFrame",
",",
"field_name",
":",
"str",
",",
"prefix",
":",
"str",
"=",
"None",
",",
"drop",
":",
"bool",
"=",
"True",
",",
"time",
":",
"bool",
"=",
"False",
",",
"add_linear",
":",
"bool",
"=",
"Fal... | Helper function that adds trigonometric date/time features to a date in the column `field_name` of `df`. | [
"Helper",
"function",
"that",
"adds",
"trigonometric",
"date",
"/",
"time",
"features",
"to",
"a",
"date",
"in",
"the",
"column",
"field_name",
"of",
"df",
"."
] | python | train | 65.090909 |
instacart/lore | lore/estimators/naive.py | https://github.com/instacart/lore/blob/0367bde9a52e69162832906acc61e8d65c5ec5d4/lore/estimators/naive.py#L29-L36 | def fit(self, x, y, **kwargs):
"""
Fit a naive model
:param x: Predictors to use for fitting the data (this will not be used in naive models)
:param y: Outcome
"""
self.mean = numpy.mean(y)
return {} | [
"def",
"fit",
"(",
"self",
",",
"x",
",",
"y",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"mean",
"=",
"numpy",
".",
"mean",
"(",
"y",
")",
"return",
"{",
"}"
] | Fit a naive model
:param x: Predictors to use for fitting the data (this will not be used in naive models)
:param y: Outcome | [
"Fit",
"a",
"naive",
"model",
":",
"param",
"x",
":",
"Predictors",
"to",
"use",
"for",
"fitting",
"the",
"data",
"(",
"this",
"will",
"not",
"be",
"used",
"in",
"naive",
"models",
")",
":",
"param",
"y",
":",
"Outcome"
] | python | train | 31 |
bioidiap/bob.ip.facedetect | bob/ip/facedetect/train/TrainingSet.py | https://github.com/bioidiap/bob.ip.facedetect/blob/601da5141ca7302ad36424d1421b33190ba46779/bob/ip/facedetect/train/TrainingSet.py#L441-L457 | def feature_extractor(self):
"""feature_extractor() -> extractor
Returns the feature extractor used to extract the positive and negative features.
This feature extractor is stored to file during the :py:meth:`extract` method ran, so this function reads that file (from the ``feature_directory`` set in the ... | [
"def",
"feature_extractor",
"(",
"self",
")",
":",
"extractor_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"feature_directory",
",",
"\"Extractor.hdf5\"",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"extractor_file",
")",
":",... | feature_extractor() -> extractor
Returns the feature extractor used to extract the positive and negative features.
This feature extractor is stored to file during the :py:meth:`extract` method ran, so this function reads that file (from the ``feature_directory`` set in the constructor) and returns its content... | [
"feature_extractor",
"()",
"-",
">",
"extractor"
] | python | train | 52.823529 |
theosysbio/means | src/means/approximation/mea/raw_to_central.py | https://github.com/theosysbio/means/blob/fe164916a1d84ab2a4fa039871d38ccdf638b1db/src/means/approximation/mea/raw_to_central.py#L12-L65 | def raw_to_central(n_counter, species, k_counter):
"""
Expresses central moments in terms of raw moments (and other central moments).
Based on equation 8 in the paper:
.. math::
\mathbf{M_{x^n}} = \sum_{k_1=0}^{n_1} ... \sum_{k_d=0}^{n_d} \mathbf{{n \choose k}} (-1)^{\mathbf{n-k}} \mu^{\mathbf... | [
"def",
"raw_to_central",
"(",
"n_counter",
",",
"species",
",",
"k_counter",
")",
":",
"# create empty output",
"central_in_terms_of_raw",
"=",
"[",
"]",
"# This loop loops through the ::math::`[n_1, ..., n_d]` vectors of the sums in the beginning of the equation",
"# i.e. :math:`\\s... | Expresses central moments in terms of raw moments (and other central moments).
Based on equation 8 in the paper:
.. math::
\mathbf{M_{x^n}} = \sum_{k_1=0}^{n_1} ... \sum_{k_d=0}^{n_d} \mathbf{{n \choose k}} (-1)^{\mathbf{n-k}} \mu^{\mathbf{n-k}} \langle \mathbf{x^k} \\rangle
The term :math:`\mu^... | [
"Expresses",
"central",
"moments",
"in",
"terms",
"of",
"raw",
"moments",
"(",
"and",
"other",
"central",
"moments",
")",
".",
"Based",
"on",
"equation",
"8",
"in",
"the",
"paper",
":"
] | python | train | 52.12963 |
EconForge/dolo | trash/dolo/misc/symbolic_interactive.py | https://github.com/EconForge/dolo/blob/d91ddf148b009bf79852d9aec70f3a1877e0f79a/trash/dolo/misc/symbolic_interactive.py#L227-L255 | def def_variables(s):
"""
blabla
"""
frame = inspect.currentframe().f_back
try:
if isinstance(s,str):
s = re.split('\s|,', s)
res = []
for t in s:
# skip empty stringG
if not t:
continue
if t.count("@") > 0:
... | [
"def",
"def_variables",
"(",
"s",
")",
":",
"frame",
"=",
"inspect",
".",
"currentframe",
"(",
")",
".",
"f_back",
"try",
":",
"if",
"isinstance",
"(",
"s",
",",
"str",
")",
":",
"s",
"=",
"re",
".",
"split",
"(",
"'\\s|,'",
",",
"s",
")",
"res",... | blabla | [
"blabla"
] | python | train | 26.551724 |
rjdkmr/do_x3dna | dnaMD/dnaMD/dnaEY.py | https://github.com/rjdkmr/do_x3dna/blob/fe910335eefcada76737f9e7cd6f25036cd32ab6/dnaMD/dnaMD/dnaEY.py#L853-L952 | def _calcEnergyBendStretchTwist(self, diff, es, which):
r"""Calculate energy for ``esType='BST'`` using a difference vector.
It is called in :meth:`dnaEY.getGlobalDeformationEnergy` for energy calculation of each frame.
Parameters
----------
diff : numpy.ndarray
Arr... | [
"def",
"_calcEnergyBendStretchTwist",
"(",
"self",
",",
"diff",
",",
"es",
",",
"which",
")",
":",
"if",
"which",
"not",
"in",
"self",
".",
"enGlobalTypes",
":",
"raise",
"ValueError",
"(",
"'{0} is not a supported energy keywords.\\n Use any of the following: \\n {1}'"... | r"""Calculate energy for ``esType='BST'`` using a difference vector.
It is called in :meth:`dnaEY.getGlobalDeformationEnergy` for energy calculation of each frame.
Parameters
----------
diff : numpy.ndarray
Array of difference between minimum and current parameter values.
... | [
"r",
"Calculate",
"energy",
"for",
"esType",
"=",
"BST",
"using",
"a",
"difference",
"vector",
"."
] | python | train | 35.54 |
tompollard/tableone | tableone.py | https://github.com/tompollard/tableone/blob/4a274d3d2f8d16b8eaa0bde030f3da29b876cee8/tableone.py#L675-L700 | def _create_cat_table(self,data):
"""
Create table one for categorical data.
Returns
----------
table : pandas DataFrame
A table summarising the categorical variables.
"""
table = self.cat_describe['t1_summary'].copy()
# add the total count of... | [
"def",
"_create_cat_table",
"(",
"self",
",",
"data",
")",
":",
"table",
"=",
"self",
".",
"cat_describe",
"[",
"'t1_summary'",
"]",
".",
"copy",
"(",
")",
"# add the total count of null values across all levels",
"isnull",
"=",
"data",
"[",
"self",
".",
"_categ... | Create table one for categorical data.
Returns
----------
table : pandas DataFrame
A table summarising the categorical variables. | [
"Create",
"table",
"one",
"for",
"categorical",
"data",
"."
] | python | train | 37.692308 |
BlueBrain/NeuroM | neurom/check/runner.py | https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/check/runner.py#L53-L71 | def run(self, path):
'''Test a bunch of files and return a summary JSON report'''
SEPARATOR = '=' * 40
summary = {}
res = True
for _f in utils.get_files_by_path(path):
L.info(SEPARATOR)
status, summ = self._check_file(_f)
res &= status
... | [
"def",
"run",
"(",
"self",
",",
"path",
")",
":",
"SEPARATOR",
"=",
"'='",
"*",
"40",
"summary",
"=",
"{",
"}",
"res",
"=",
"True",
"for",
"_f",
"in",
"utils",
".",
"get_files_by_path",
"(",
"path",
")",
":",
"L",
".",
"info",
"(",
"SEPARATOR",
"... | Test a bunch of files and return a summary JSON report | [
"Test",
"a",
"bunch",
"of",
"files",
"and",
"return",
"a",
"summary",
"JSON",
"report"
] | python | train | 25.736842 |
wmayner/pyphi | pyphi/partition.py | https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/partition.py#L387-L439 | def mip_bipartitions(mechanism, purview, node_labels=None):
r"""Return an generator of all |small_phi| bipartitions of a mechanism over
a purview.
Excludes all bipartitions where one half is entirely empty, *e.g*::
A ∅
─── ✕ ───
B ∅
is not valid, but ::
A ... | [
"def",
"mip_bipartitions",
"(",
"mechanism",
",",
"purview",
",",
"node_labels",
"=",
"None",
")",
":",
"numerators",
"=",
"bipartition",
"(",
"mechanism",
")",
"denominators",
"=",
"directed_bipartition",
"(",
"purview",
")",
"for",
"n",
",",
"d",
"in",
"pr... | r"""Return an generator of all |small_phi| bipartitions of a mechanism over
a purview.
Excludes all bipartitions where one half is entirely empty, *e.g*::
A ∅
─── ✕ ───
B ∅
is not valid, but ::
A ∅
─── ✕ ───
∅ B
is.
Args:
... | [
"r",
"Return",
"an",
"generator",
"of",
"all",
"|small_phi|",
"bipartitions",
"of",
"a",
"mechanism",
"over",
"a",
"purview",
"."
] | python | train | 26.188679 |
frejanordsiek/GeminiMotorDrive | GeminiMotorDrive/__init__.py | https://github.com/frejanordsiek/GeminiMotorDrive/blob/8de347ffb91228fbfe3832098b4996fa0141d8f1/GeminiMotorDrive/__init__.py#L41-L85 | def get_driver(driver='ASCII_RS232', *args, **keywords):
""" Gets a driver for a Parker Motion Gemini drive.
Gets and connects a particular driver in ``drivers`` to a Parker
Motion Gemini GV-6 or GT-6 servo/stepper motor drive.
The only driver currently supported is the ``'ASCII_RS232'`` driver
wh... | [
"def",
"get_driver",
"(",
"driver",
"=",
"'ASCII_RS232'",
",",
"*",
"args",
",",
"*",
"*",
"keywords",
")",
":",
"if",
"driver",
".",
"upper",
"(",
")",
"==",
"'ASCII_RS232'",
":",
"return",
"drivers",
".",
"ASCII_RS232",
"(",
"*",
"args",
",",
"*",
... | Gets a driver for a Parker Motion Gemini drive.
Gets and connects a particular driver in ``drivers`` to a Parker
Motion Gemini GV-6 or GT-6 servo/stepper motor drive.
The only driver currently supported is the ``'ASCII_RS232'`` driver
which corresponds to ``drivers.ASCII_RS232``.
Parameters
-... | [
"Gets",
"a",
"driver",
"for",
"a",
"Parker",
"Motion",
"Gemini",
"drive",
"."
] | python | train | 31.866667 |
ppb/pursuedpybear | ppb/scenes.py | https://github.com/ppb/pursuedpybear/blob/db3bfaaf86d14b4d1bb9e0b24cc8dc63f29c2191/ppb/scenes.py#L171-L190 | def get(self, *, kind: Type=None, tag: Hashable=None, **kwargs) -> Iterator:
"""
Get an iterator of GameObjects by kind or tag.
kind: Any type. Pass to get a subset of contained GameObjects with the
given type.
tag: Any Hashable object. Pass to get a subset of contained Ga... | [
"def",
"get",
"(",
"self",
",",
"*",
",",
"kind",
":",
"Type",
"=",
"None",
",",
"tag",
":",
"Hashable",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
"->",
"Iterator",
":",
"return",
"self",
".",
"game_objects",
".",
"get",
"(",
"kind",
"=",
"kind"... | Get an iterator of GameObjects by kind or tag.
kind: Any type. Pass to get a subset of contained GameObjects with the
given type.
tag: Any Hashable object. Pass to get a subset of contained GameObjects
with the given tag.
Pass both kind and tag to get objects that ar... | [
"Get",
"an",
"iterator",
"of",
"GameObjects",
"by",
"kind",
"or",
"tag",
"."
] | python | train | 33.1 |
MolSSI-BSE/basis_set_exchange | basis_set_exchange/sort.py | https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/sort.py#L218-L238 | def sort_references_dict(refs):
"""Sorts a reference dictionary into a standard order
The keys of the references are also sorted, and the keys for the data for each
reference are put in a more canonical order.
"""
if _use_odict:
refs_sorted = OrderedDict()
else:
refs_sorted = d... | [
"def",
"sort_references_dict",
"(",
"refs",
")",
":",
"if",
"_use_odict",
":",
"refs_sorted",
"=",
"OrderedDict",
"(",
")",
"else",
":",
"refs_sorted",
"=",
"dict",
"(",
")",
"# We insert this first, That is ok - it will be overwritten",
"# with the sorted version later",... | Sorts a reference dictionary into a standard order
The keys of the references are also sorted, and the keys for the data for each
reference are put in a more canonical order. | [
"Sorts",
"a",
"reference",
"dictionary",
"into",
"a",
"standard",
"order"
] | python | train | 30.904762 |
nedbat/django_coverage_plugin | django_coverage_plugin/plugin.py | https://github.com/nedbat/django_coverage_plugin/blob/0072737c0ea5a1ca6b9f046af4947de191f13804/django_coverage_plugin/plugin.py#L50-L89 | def check_debug():
"""Check that Django's template debugging is enabled.
Django's built-in "template debugging" records information the plugin needs
to do its work. Check that the setting is correct, and raise an exception
if it is not.
Returns True if the debug check was performed, False otherwi... | [
"def",
"check_debug",
"(",
")",
":",
"from",
"django",
".",
"conf",
"import",
"settings",
"if",
"not",
"settings",
".",
"configured",
":",
"return",
"False",
"# I _think_ this check is all that's needed and the 3 \"hasattr\" checks",
"# below can be removed, but it's not clea... | Check that Django's template debugging is enabled.
Django's built-in "template debugging" records information the plugin needs
to do its work. Check that the setting is correct, and raise an exception
if it is not.
Returns True if the debug check was performed, False otherwise | [
"Check",
"that",
"Django",
"s",
"template",
"debugging",
"is",
"enabled",
"."
] | python | train | 35.875 |
bcbio/bcbio-nextgen | bcbio/graph/graph.py | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/graph/graph.py#L140-L155 | def prep_for_graph(data_frame, series=None, delta_series=None, smoothing=None,
outlier_stddev=None):
"""Prepare a dataframe for graphing by calculating deltas for
series that need them, resampling, and removing outliers.
"""
series = series or []
delta_series = delta_series or []
... | [
"def",
"prep_for_graph",
"(",
"data_frame",
",",
"series",
"=",
"None",
",",
"delta_series",
"=",
"None",
",",
"smoothing",
"=",
"None",
",",
"outlier_stddev",
"=",
"None",
")",
":",
"series",
"=",
"series",
"or",
"[",
"]",
"delta_series",
"=",
"delta_seri... | Prepare a dataframe for graphing by calculating deltas for
series that need them, resampling, and removing outliers. | [
"Prepare",
"a",
"dataframe",
"for",
"graphing",
"by",
"calculating",
"deltas",
"for",
"series",
"that",
"need",
"them",
"resampling",
"and",
"removing",
"outliers",
"."
] | python | train | 37.375 |
slickqa/python-client | slickqa/micromodels/fields.py | https://github.com/slickqa/python-client/blob/1d36b4977cd4140d7d24917cab2b3f82b60739c2/slickqa/micromodels/fields.py#L96-L105 | def to_python(self):
"""The string ``'True'`` (case insensitive) will be converted
to ``True``, as will any positive integers.
"""
if isinstance(self.data, str):
return self.data.strip().lower() == 'true'
if isinstance(self.data, int):
return self.data > ... | [
"def",
"to_python",
"(",
"self",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"data",
",",
"str",
")",
":",
"return",
"self",
".",
"data",
".",
"strip",
"(",
")",
".",
"lower",
"(",
")",
"==",
"'true'",
"if",
"isinstance",
"(",
"self",
".",
"d... | The string ``'True'`` (case insensitive) will be converted
to ``True``, as will any positive integers. | [
"The",
"string",
"True",
"(",
"case",
"insensitive",
")",
"will",
"be",
"converted",
"to",
"True",
"as",
"will",
"any",
"positive",
"integers",
"."
] | python | train | 34.3 |
brocade/pynos | pynos/versions/ver_6/ver_6_0_1/yang/brocade_common_def.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_6/ver_6_0_1/yang/brocade_common_def.py#L460-L473 | def ip_hide_ext_community_list_holder_extcommunity_list_ext_community_action(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip = ET.SubElement(config, "ip", xmlns="urn:brocade.com:mgmt:brocade-common-def")
hide_ext_community_list_holder = ET.SubElement(... | [
"def",
"ip_hide_ext_community_list_holder_extcommunity_list_ext_community_action",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"ip",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"ip\"",
",",... | Auto Generated Code | [
"Auto",
"Generated",
"Code"
] | python | train | 64.857143 |
JdeRobot/base | src/drivers/MAVLinkServer/MAVProxy/pymavlink/dialects/v10/matrixpilot.py | https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/pymavlink/dialects/v10/matrixpilot.py#L12333-L12345 | def resource_request_send(self, request_id, uri_type, uri, transfer_type, storage, force_mavlink1=False):
'''
The autopilot is requesting a resource (file, binary, other type of
data)
request_id : Request ID. This ID should be re-used when ... | [
"def",
"resource_request_send",
"(",
"self",
",",
"request_id",
",",
"uri_type",
",",
"uri",
",",
"transfer_type",
",",
"storage",
",",
"force_mavlink1",
"=",
"False",
")",
":",
"return",
"self",
".",
"send",
"(",
"self",
".",
"resource_request_encode",
"(",
... | The autopilot is requesting a resource (file, binary, other type of
data)
request_id : Request ID. This ID should be re-used when sending back URI contents (uint8_t)
uri_type : The type of requested URI. 0 = a file via URL. 1 = a UAVCAN bi... | [
"The",
"autopilot",
"is",
"requesting",
"a",
"resource",
"(",
"file",
"binary",
"other",
"type",
"of",
"data",
")"
] | python | train | 88.230769 |
spyder-ide/conda-manager | conda_manager/api/manager_api.py | https://github.com/spyder-ide/conda-manager/blob/89a2126cbecefc92185cf979347ccac1c5ee5d9d/conda_manager/api/manager_api.py#L239-L244 | def update_repodata(self, channels=None):
"""Update repodata from channels or use condarc channels if None."""
norm_channels = self.conda_get_condarc_channels(channels=channels,
normalize=True)
repodata_urls = self._set_repo_urls_from_chann... | [
"def",
"update_repodata",
"(",
"self",
",",
"channels",
"=",
"None",
")",
":",
"norm_channels",
"=",
"self",
".",
"conda_get_condarc_channels",
"(",
"channels",
"=",
"channels",
",",
"normalize",
"=",
"True",
")",
"repodata_urls",
"=",
"self",
".",
"_set_repo_... | Update repodata from channels or use condarc channels if None. | [
"Update",
"repodata",
"from",
"channels",
"or",
"use",
"condarc",
"channels",
"if",
"None",
"."
] | python | train | 62.333333 |
juicer/juicer | juicer/utils/__init__.py | https://github.com/juicer/juicer/blob/0c9f0fd59e293d45df6b46e81f675d33221c600d/juicer/utils/__init__.py#L70-L83 | def _user_config_file():
"""
Check that the config file is present and readable. If not,
copy a template in place.
"""
config_file = Constants.USER_CONFIG
if os.path.exists(config_file) and os.access(config_file, os.R_OK):
return config_file
elif os.path.exists(config_file) and not o... | [
"def",
"_user_config_file",
"(",
")",
":",
"config_file",
"=",
"Constants",
".",
"USER_CONFIG",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"config_file",
")",
"and",
"os",
".",
"access",
"(",
"config_file",
",",
"os",
".",
"R_OK",
")",
":",
"return",
... | Check that the config file is present and readable. If not,
copy a template in place. | [
"Check",
"that",
"the",
"config",
"file",
"is",
"present",
"and",
"readable",
".",
"If",
"not",
"copy",
"a",
"template",
"in",
"place",
"."
] | python | train | 39.857143 |
BlueBrain/hpcbench | hpcbench/benchmark/ior.py | https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/benchmark/ior.py#L227-L241 | def pre_execute(self, execution, context):
"""Make sure the named directory is created if possible"""
path = self._fspath
if path:
path = path.format(
benchmark=context.benchmark,
api=execution['category'],
**execution.get('metas', {})
... | [
"def",
"pre_execute",
"(",
"self",
",",
"execution",
",",
"context",
")",
":",
"path",
"=",
"self",
".",
"_fspath",
"if",
"path",
":",
"path",
"=",
"path",
".",
"format",
"(",
"benchmark",
"=",
"context",
".",
"benchmark",
",",
"api",
"=",
"execution",... | Make sure the named directory is created if possible | [
"Make",
"sure",
"the",
"named",
"directory",
"is",
"created",
"if",
"possible"
] | python | train | 38.666667 |
chrisrink10/basilisp | src/basilisp/lang/reader.py | https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/lang/reader.py#L1029-L1059 | def read(
stream,
resolver: Resolver = None,
data_readers: DataReaders = None,
eof: Any = EOF,
is_eof_error: bool = False,
) -> Iterable[ReaderForm]:
"""Read the contents of a stream as a Lisp expression.
Callers may optionally specify a namespace resolver, which will be used
to adjudic... | [
"def",
"read",
"(",
"stream",
",",
"resolver",
":",
"Resolver",
"=",
"None",
",",
"data_readers",
":",
"DataReaders",
"=",
"None",
",",
"eof",
":",
"Any",
"=",
"EOF",
",",
"is_eof_error",
":",
"bool",
"=",
"False",
",",
")",
"->",
"Iterable",
"[",
"R... | Read the contents of a stream as a Lisp expression.
Callers may optionally specify a namespace resolver, which will be used
to adjudicate the fully-qualified name of symbols appearing inside of
a syntax quote.
Callers may optionally specify a map of custom data readers that will
be used to resolve... | [
"Read",
"the",
"contents",
"of",
"a",
"stream",
"as",
"a",
"Lisp",
"expression",
"."
] | python | test | 36.774194 |
revelc/pyaccumulo | pyaccumulo/proxy/AccumuloProxy.py | https://github.com/revelc/pyaccumulo/blob/8adcf535bb82ba69c749efce785c9efc487e85de/pyaccumulo/proxy/AccumuloProxy.py#L1393-L1403 | def importDirectory(self, login, tableName, importDir, failureDir, setTime):
"""
Parameters:
- login
- tableName
- importDir
- failureDir
- setTime
"""
self.send_importDirectory(login, tableName, importDir, failureDir, setTime)
self.recv_importDirectory() | [
"def",
"importDirectory",
"(",
"self",
",",
"login",
",",
"tableName",
",",
"importDir",
",",
"failureDir",
",",
"setTime",
")",
":",
"self",
".",
"send_importDirectory",
"(",
"login",
",",
"tableName",
",",
"importDir",
",",
"failureDir",
",",
"setTime",
")... | Parameters:
- login
- tableName
- importDir
- failureDir
- setTime | [
"Parameters",
":",
"-",
"login",
"-",
"tableName",
"-",
"importDir",
"-",
"failureDir",
"-",
"setTime"
] | python | train | 26.363636 |
cloud9ers/gurumate | environment/lib/python2.7/site-packages/IPython/parallel/apps/ipcontrollerapp.py | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/parallel/apps/ipcontrollerapp.py#L234-L266 | def load_config_from_json(self):
"""load config from existing json connector files."""
c = self.config
self.log.debug("loading config from JSON")
# load from engine config
fname = os.path.join(self.profile_dir.security_dir, self.engine_json_file)
self.log.info("loading co... | [
"def",
"load_config_from_json",
"(",
"self",
")",
":",
"c",
"=",
"self",
".",
"config",
"self",
".",
"log",
".",
"debug",
"(",
"\"loading config from JSON\"",
")",
"# load from engine config",
"fname",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
... | load config from existing json connector files. | [
"load",
"config",
"from",
"existing",
"json",
"connector",
"files",
"."
] | python | test | 45.090909 |
stevelittlefish/littlefish | littlefish/attackprotect.py | https://github.com/stevelittlefish/littlefish/blob/6deee7f81fab30716c743efe2e94e786c6e17016/littlefish/attackprotect.py#L61-L80 | def service(self):
"""
Decrease the countdowns, and remove any expired locks. Should be called once every <decrease_every> seconds.
"""
with self.lock:
# Decrement / remove all attempts
for key in list(self.attempts.keys()):
log.debug('Decrementin... | [
"def",
"service",
"(",
"self",
")",
":",
"with",
"self",
".",
"lock",
":",
"# Decrement / remove all attempts",
"for",
"key",
"in",
"list",
"(",
"self",
".",
"attempts",
".",
"keys",
"(",
")",
")",
":",
"log",
".",
"debug",
"(",
"'Decrementing count for %s... | Decrease the countdowns, and remove any expired locks. Should be called once every <decrease_every> seconds. | [
"Decrease",
"the",
"countdowns",
"and",
"remove",
"any",
"expired",
"locks",
".",
"Should",
"be",
"called",
"once",
"every",
"<decrease_every",
">",
"seconds",
"."
] | python | test | 41.55 |
jantman/awslimitchecker | awslimitchecker/runner.py | https://github.com/jantman/awslimitchecker/blob/e50197f70f3d0abcc5cfc7fde6336f548b790e34/awslimitchecker/runner.py#L73-L217 | def parse_args(self, argv):
"""
parse arguments/options
:param argv: argument list to parse, usually ``sys.argv[1:]``
:type argv: list
:returns: parsed arguments
:rtype: :py:class:`argparse.Namespace`
"""
desc = 'Report on AWS service limits and usage via... | [
"def",
"parse_args",
"(",
"self",
",",
"argv",
")",
":",
"desc",
"=",
"'Report on AWS service limits and usage via boto3, optionally '",
"'warn about any services with usage nearing or exceeding their'",
"' limits. For further help, see '",
"'<http://awslimitchecker.readthedocs.org/>'",
... | parse arguments/options
:param argv: argument list to parse, usually ``sys.argv[1:]``
:type argv: list
:returns: parsed arguments
:rtype: :py:class:`argparse.Namespace` | [
"parse",
"arguments",
"/",
"options"
] | python | train | 58.97931 |
cloud-custodian/cloud-custodian | c7n/mu.py | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/mu.py#L133-L152 | def add_directory(self, path, ignore=None):
"""Add ``*.py`` files under the directory ``path`` to the archive.
"""
for root, dirs, files in os.walk(path):
arc_prefix = os.path.relpath(root, os.path.dirname(path))
# py3 remove pyc cache dirs.
if '__pycache__' i... | [
"def",
"add_directory",
"(",
"self",
",",
"path",
",",
"ignore",
"=",
"None",
")",
":",
"for",
"root",
",",
"dirs",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"path",
")",
":",
"arc_prefix",
"=",
"os",
".",
"path",
".",
"relpath",
"(",
"root",
"... | Add ``*.py`` files under the directory ``path`` to the archive. | [
"Add",
"*",
".",
"py",
"files",
"under",
"the",
"directory",
"path",
"to",
"the",
"archive",
"."
] | python | train | 37 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L2084-L2110 | def insert_record(self,
table: str,
fields: Sequence[str],
values: Sequence[Any],
update_on_duplicate_key: bool = False) -> int:
"""Inserts a record into database, table "table", using the list of
fieldnames and the ... | [
"def",
"insert_record",
"(",
"self",
",",
"table",
":",
"str",
",",
"fields",
":",
"Sequence",
"[",
"str",
"]",
",",
"values",
":",
"Sequence",
"[",
"Any",
"]",
",",
"update_on_duplicate_key",
":",
"bool",
"=",
"False",
")",
"->",
"int",
":",
"self",
... | Inserts a record into database, table "table", using the list of
fieldnames and the list of values. Returns the new PK (or None). | [
"Inserts",
"a",
"record",
"into",
"database",
"table",
"table",
"using",
"the",
"list",
"of",
"fieldnames",
"and",
"the",
"list",
"of",
"values",
".",
"Returns",
"the",
"new",
"PK",
"(",
"or",
"None",
")",
"."
] | python | train | 44.481481 |
rackerlabs/simpl | simpl/config.py | https://github.com/rackerlabs/simpl/blob/60ed3336a931cd6a7a7246e60f26165d9dc7c99c/simpl/config.py#L385-L389 | def prog(self):
"""Program name."""
if not self._prog:
self._prog = self._parser.prog
return self._prog | [
"def",
"prog",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_prog",
":",
"self",
".",
"_prog",
"=",
"self",
".",
"_parser",
".",
"prog",
"return",
"self",
".",
"_prog"
] | Program name. | [
"Program",
"name",
"."
] | python | train | 27 |
fracpete/python-weka-wrapper3 | python/weka/core/classes.py | https://github.com/fracpete/python-weka-wrapper3/blob/d850ab1bdb25fbd5a8d86e99f34a397975425838/python/weka/core/classes.py#L1683-L1705 | def from_commandline(cmdline, classname=None):
"""
Creates an OptionHandler based on the provided commandline string.
:param cmdline: the commandline string to use
:type cmdline: str
:param classname: the classname of the wrapper to return other than OptionHandler (in dot-notation)
:type classn... | [
"def",
"from_commandline",
"(",
"cmdline",
",",
"classname",
"=",
"None",
")",
":",
"params",
"=",
"split_options",
"(",
"cmdline",
")",
"cls",
"=",
"params",
"[",
"0",
"]",
"params",
"=",
"params",
"[",
"1",
":",
"]",
"handler",
"=",
"OptionHandler",
... | Creates an OptionHandler based on the provided commandline string.
:param cmdline: the commandline string to use
:type cmdline: str
:param classname: the classname of the wrapper to return other than OptionHandler (in dot-notation)
:type classname: str
:return: the generated option handler instance... | [
"Creates",
"an",
"OptionHandler",
"based",
"on",
"the",
"provided",
"commandline",
"string",
"."
] | python | train | 36.73913 |
nats-io/python-nats | nats/io/client.py | https://github.com/nats-io/python-nats/blob/4a409319c409e7e55ce8377b64b406375c5f455b/nats/io/client.py#L812-L820 | def auto_unsubscribe(self, sid, limit=1):
"""
Sends an UNSUB command to the server. Unsubscribe is one of the basic building
blocks in order to be able to define request/response semantics via pub/sub
by announcing the server limited interest a priori.
"""
if self.is_dra... | [
"def",
"auto_unsubscribe",
"(",
"self",
",",
"sid",
",",
"limit",
"=",
"1",
")",
":",
"if",
"self",
".",
"is_draining",
":",
"raise",
"ErrConnectionDraining",
"yield",
"self",
".",
"_unsubscribe",
"(",
"sid",
",",
"limit",
")"
] | Sends an UNSUB command to the server. Unsubscribe is one of the basic building
blocks in order to be able to define request/response semantics via pub/sub
by announcing the server limited interest a priori. | [
"Sends",
"an",
"UNSUB",
"command",
"to",
"the",
"server",
".",
"Unsubscribe",
"is",
"one",
"of",
"the",
"basic",
"building",
"blocks",
"in",
"order",
"to",
"be",
"able",
"to",
"define",
"request",
"/",
"response",
"semantics",
"via",
"pub",
"/",
"sub",
"... | python | train | 44.666667 |
pydanny/cookiecutter-django | hooks/post_gen_project.py | https://github.com/pydanny/cookiecutter-django/blob/bb9b482e96d1966e20745eeea87a8aa10ed1c861/hooks/post_gen_project.py#L107-L129 | def generate_random_string(
length, using_digits=False, using_ascii_letters=False, using_punctuation=False
):
"""
Example:
opting out for 50 symbol-long, [a-z][A-Z][0-9] string
would yield log_2((26+26+50)^50) ~= 334 bit strength.
"""
if not using_sysrandom:
return None
... | [
"def",
"generate_random_string",
"(",
"length",
",",
"using_digits",
"=",
"False",
",",
"using_ascii_letters",
"=",
"False",
",",
"using_punctuation",
"=",
"False",
")",
":",
"if",
"not",
"using_sysrandom",
":",
"return",
"None",
"symbols",
"=",
"[",
"]",
"if"... | Example:
opting out for 50 symbol-long, [a-z][A-Z][0-9] string
would yield log_2((26+26+50)^50) ~= 334 bit strength. | [
"Example",
":",
"opting",
"out",
"for",
"50",
"symbol",
"-",
"long",
"[",
"a",
"-",
"z",
"]",
"[",
"A",
"-",
"Z",
"]",
"[",
"0",
"-",
"9",
"]",
"string",
"would",
"yield",
"log_2",
"((",
"26",
"+",
"26",
"+",
"50",
")",
"^50",
")",
"~",
"="... | python | test | 33.913043 |
wbond/asn1crypto | asn1crypto/x509.py | https://github.com/wbond/asn1crypto/blob/ecda20176f55d37021cbca1f6da9083a8e491197/asn1crypto/x509.py#L1541-L1565 | def url(self):
"""
:return:
None or a unicode string of the distribution point's URL
"""
if self._url is False:
self._url = None
name = self['distribution_point']
if name.name != 'full_name':
raise ValueError(unwrap(
... | [
"def",
"url",
"(",
"self",
")",
":",
"if",
"self",
".",
"_url",
"is",
"False",
":",
"self",
".",
"_url",
"=",
"None",
"name",
"=",
"self",
"[",
"'distribution_point'",
"]",
"if",
"name",
".",
"name",
"!=",
"'full_name'",
":",
"raise",
"ValueError",
"... | :return:
None or a unicode string of the distribution point's URL | [
":",
"return",
":",
"None",
"or",
"a",
"unicode",
"string",
"of",
"the",
"distribution",
"point",
"s",
"URL"
] | python | train | 32.96 |
Kozea/cairocffi | cairocffi/context.py | https://github.com/Kozea/cairocffi/blob/450853add7e32eea20985b6aa5f54d9cb3cd04fe/cairocffi/context.py#L1456-L1471 | def in_fill(self, x, y):
"""Tests whether the given point is inside the area
that would be affected by a :meth:`fill` operation
given the current path and filling parameters.
Surface dimensions and clipping are not taken into account.
See :meth:`fill`, :meth:`set_fill_rule` and ... | [
"def",
"in_fill",
"(",
"self",
",",
"x",
",",
"y",
")",
":",
"return",
"bool",
"(",
"cairo",
".",
"cairo_in_fill",
"(",
"self",
".",
"_pointer",
",",
"x",
",",
"y",
")",
")"
] | Tests whether the given point is inside the area
that would be affected by a :meth:`fill` operation
given the current path and filling parameters.
Surface dimensions and clipping are not taken into account.
See :meth:`fill`, :meth:`set_fill_rule` and :meth:`fill_preserve`.
:par... | [
"Tests",
"whether",
"the",
"given",
"point",
"is",
"inside",
"the",
"area",
"that",
"would",
"be",
"affected",
"by",
"a",
":",
"meth",
":",
"fill",
"operation",
"given",
"the",
"current",
"path",
"and",
"filling",
"parameters",
".",
"Surface",
"dimensions",
... | python | train | 36.375 |
openvax/mhctools | mhctools/input_file_formats.py | https://github.com/openvax/mhctools/blob/b329b4dccd60fae41296816b8cbfe15d6ca07e67/mhctools/input_file_formats.py#L26-L61 | def create_input_peptides_files(
peptides,
max_peptides_per_file=None,
group_by_length=False):
"""
Creates one or more files containing one peptide per line,
returns names of files.
"""
if group_by_length:
peptide_lengths = {len(p) for p in peptides}
peptide_g... | [
"def",
"create_input_peptides_files",
"(",
"peptides",
",",
"max_peptides_per_file",
"=",
"None",
",",
"group_by_length",
"=",
"False",
")",
":",
"if",
"group_by_length",
":",
"peptide_lengths",
"=",
"{",
"len",
"(",
"p",
")",
"for",
"p",
"in",
"peptides",
"}"... | Creates one or more files containing one peptide per line,
returns names of files. | [
"Creates",
"one",
"or",
"more",
"files",
"containing",
"one",
"peptide",
"per",
"line",
"returns",
"names",
"of",
"files",
"."
] | python | valid | 34.5 |
saltstack/salt | salt/states/esxi.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/esxi.py#L869-L1025 | def syslog_configured(name,
syslog_configs,
firewall=True,
reset_service=True,
reset_syslog_config=False,
reset_configs=None):
'''
Ensures the specified syslog configuration parameters. By default,
... | [
"def",
"syslog_configured",
"(",
"name",
",",
"syslog_configs",
",",
"firewall",
"=",
"True",
",",
"reset_service",
"=",
"True",
",",
"reset_syslog_config",
"=",
"False",
",",
"reset_configs",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
... | Ensures the specified syslog configuration parameters. By default,
this state will reset the syslog service after any new or changed
parameters are set successfully.
name
Name of the state.
syslog_configs
Name of parameter to set (corresponds to the command line switch for
esxc... | [
"Ensures",
"the",
"specified",
"syslog",
"configuration",
"parameters",
".",
"By",
"default",
"this",
"state",
"will",
"reset",
"the",
"syslog",
"service",
"after",
"any",
"new",
"or",
"changed",
"parameters",
"are",
"set",
"successfully",
"."
] | python | train | 40.808917 |
nickmckay/LiPD-utilities | Python/lipd/lpd_noaa.py | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/lpd_noaa.py#L826-L848 | def __get_doi(pub):
"""
Get DOI from this ONE publication entry.
:param dict pub: Single publication entry
:return:
"""
doi = ""
# Doi location: d["pub"][idx]["identifier"][0]["id"]
try:
doi = pub["DOI"][0]["id"]
doi = clean_doi(doi... | [
"def",
"__get_doi",
"(",
"pub",
")",
":",
"doi",
"=",
"\"\"",
"# Doi location: d[\"pub\"][idx][\"identifier\"][0][\"id\"]",
"try",
":",
"doi",
"=",
"pub",
"[",
"\"DOI\"",
"]",
"[",
"0",
"]",
"[",
"\"id\"",
"]",
"doi",
"=",
"clean_doi",
"(",
"doi",
")",
"ex... | Get DOI from this ONE publication entry.
:param dict pub: Single publication entry
:return: | [
"Get",
"DOI",
"from",
"this",
"ONE",
"publication",
"entry",
".",
":",
"param",
"dict",
"pub",
":",
"Single",
"publication",
"entry",
":",
"return",
":"
] | python | train | 32.565217 |
aio-libs/aioredis | aioredis/commands/geo.py | https://github.com/aio-libs/aioredis/blob/e8c33e39558d4cc91cf70dde490d8b330c97dc2e/aioredis/commands/geo.py#L93-L132 | def georadiusbymember(self, key, member, radius, unit='m', *,
with_dist=False, with_hash=False, with_coord=False,
count=None, sort=None, encoding=_NOTSET):
"""Query a sorted set representing a geospatial index to fetch members
matching a given maximum ... | [
"def",
"georadiusbymember",
"(",
"self",
",",
"key",
",",
"member",
",",
"radius",
",",
"unit",
"=",
"'m'",
",",
"*",
",",
"with_dist",
"=",
"False",
",",
"with_hash",
"=",
"False",
",",
"with_coord",
"=",
"False",
",",
"count",
"=",
"None",
",",
"so... | Query a sorted set representing a geospatial index to fetch members
matching a given maximum distance from a member.
Return value follows Redis convention:
* if none of ``WITH*`` flags are set -- list of strings returned:
>>> await redis.georadiusbymember('Sicily', 'Palermo', 200,... | [
"Query",
"a",
"sorted",
"set",
"representing",
"a",
"geospatial",
"index",
"to",
"fetch",
"members",
"matching",
"a",
"given",
"maximum",
"distance",
"from",
"a",
"member",
"."
] | python | train | 43.75 |
bioidiap/gridtk | gridtk/generator.py | https://github.com/bioidiap/gridtk/blob/9e3291b8b50388682908927231b2730db1da147d/gridtk/generator.py#L22-L39 | def _ordered_load(stream, Loader=yaml.Loader,
object_pairs_hook=dict):
'''Loads the contents of the YAML stream into :py:class:`collections.OrderedDict`'s
See: https://stackoverflow.com/questions/5121931/in-python-how-can-you-load-yaml-mappings-as-ordereddicts
'''
class OrderedLoader(Loader): pass
def... | [
"def",
"_ordered_load",
"(",
"stream",
",",
"Loader",
"=",
"yaml",
".",
"Loader",
",",
"object_pairs_hook",
"=",
"dict",
")",
":",
"class",
"OrderedLoader",
"(",
"Loader",
")",
":",
"pass",
"def",
"construct_mapping",
"(",
"loader",
",",
"node",
")",
":",
... | Loads the contents of the YAML stream into :py:class:`collections.OrderedDict`'s
See: https://stackoverflow.com/questions/5121931/in-python-how-can-you-load-yaml-mappings-as-ordereddicts | [
"Loads",
"the",
"contents",
"of",
"the",
"YAML",
"stream",
"into",
":",
"py",
":",
"class",
":",
"collections",
".",
"OrderedDict",
"s"
] | python | train | 32.055556 |
minhhoit/yacms | yacms/pages/admin.py | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/pages/admin.py#L110-L120 | def _maintain_parent(self, request, response):
"""
Maintain the parent ID in the querystring for response_add and
response_change.
"""
location = response._headers.get("location")
parent = request.GET.get("parent")
if parent and location and "?" not in location[1]... | [
"def",
"_maintain_parent",
"(",
"self",
",",
"request",
",",
"response",
")",
":",
"location",
"=",
"response",
".",
"_headers",
".",
"get",
"(",
"\"location\"",
")",
"parent",
"=",
"request",
".",
"GET",
".",
"get",
"(",
"\"parent\"",
")",
"if",
"parent... | Maintain the parent ID in the querystring for response_add and
response_change. | [
"Maintain",
"the",
"parent",
"ID",
"in",
"the",
"querystring",
"for",
"response_add",
"and",
"response_change",
"."
] | python | train | 39.727273 |
Basic-Components/msgpack-rpc-protocol | python/pymprpc/client/sync.py | https://github.com/Basic-Components/msgpack-rpc-protocol/blob/7983ace5d5cfd7214df6803f9b1de458df5fe3b1/python/pymprpc/client/sync.py#L355-L377 | def _make_query(self, ID: str, methodname: str, *args: Any, **kwargs: Any):
"""将调用请求的ID,方法名,参数包装为请求数据.
Parameters:
ID (str): - 任务ID
methodname (str): - 要调用的方法名
args (Any): - 要调用的方法的位置参数
kwargs (Any): - 要调用的方法的关键字参数
Return:
(Dict[str, ... | [
"def",
"_make_query",
"(",
"self",
",",
"ID",
":",
"str",
",",
"methodname",
":",
"str",
",",
"*",
"args",
":",
"Any",
",",
"*",
"*",
"kwargs",
":",
"Any",
")",
":",
"query",
"=",
"{",
"\"MPRPC\"",
":",
"self",
".",
"VERSION",
",",
"\"ID\"",
":",... | 将调用请求的ID,方法名,参数包装为请求数据.
Parameters:
ID (str): - 任务ID
methodname (str): - 要调用的方法名
args (Any): - 要调用的方法的位置参数
kwargs (Any): - 要调用的方法的关键字参数
Return:
(Dict[str, Any]) : - 请求的python字典形式 | [
"将调用请求的ID",
"方法名",
"参数包装为请求数据",
"."
] | python | train | 25.130435 |
Nukesor/pueue | pueue/daemon/daemon.py | https://github.com/Nukesor/pueue/blob/f1d276360454d4dd2738658a13df1e20caa4b926/pueue/daemon/daemon.py#L404-L443 | def pause(self, payload):
"""Start the daemon and all processes or only specific processes."""
# Pause specific processes, if `keys` is given in the payload
if payload.get('keys'):
succeeded = []
failed = []
for key in payload.get('keys'):
succ... | [
"def",
"pause",
"(",
"self",
",",
"payload",
")",
":",
"# Pause specific processes, if `keys` is given in the payload",
"if",
"payload",
".",
"get",
"(",
"'keys'",
")",
":",
"succeeded",
"=",
"[",
"]",
"failed",
"=",
"[",
"]",
"for",
"key",
"in",
"payload",
... | Start the daemon and all processes or only specific processes. | [
"Start",
"the",
"daemon",
"and",
"all",
"processes",
"or",
"only",
"specific",
"processes",
"."
] | python | train | 40 |
rootpy/rootpy | rootpy/plotting/hist.py | https://github.com/rootpy/rootpy/blob/3926935e1f2100d8ba68070c2ab44055d4800f73/rootpy/plotting/hist.py#L1245-L1258 | def get_sum_w2(self, ix, iy=0, iz=0):
"""
Obtain the true number of entries in the bin weighted by w^2
"""
if self.GetSumw2N() == 0:
raise RuntimeError(
"Attempting to access Sumw2 in histogram "
"where weights were not stored")
xl = se... | [
"def",
"get_sum_w2",
"(",
"self",
",",
"ix",
",",
"iy",
"=",
"0",
",",
"iz",
"=",
"0",
")",
":",
"if",
"self",
".",
"GetSumw2N",
"(",
")",
"==",
"0",
":",
"raise",
"RuntimeError",
"(",
"\"Attempting to access Sumw2 in histogram \"",
"\"where weights were not... | Obtain the true number of entries in the bin weighted by w^2 | [
"Obtain",
"the",
"true",
"number",
"of",
"entries",
"in",
"the",
"bin",
"weighted",
"by",
"w^2"
] | python | train | 40.357143 |
saltstack/salt | salt/utils/stringutils.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/stringutils.py#L289-L313 | def human_to_bytes(size):
'''
Given a human-readable byte string (e.g. 2G, 30M),
return the number of bytes. Will return 0 if the argument has
unexpected form.
.. versionadded:: 2018.3.0
'''
sbytes = size[:-1]
unit = size[-1]
if sbytes.isdigit():
sbytes = int(sbytes)
... | [
"def",
"human_to_bytes",
"(",
"size",
")",
":",
"sbytes",
"=",
"size",
"[",
":",
"-",
"1",
"]",
"unit",
"=",
"size",
"[",
"-",
"1",
"]",
"if",
"sbytes",
".",
"isdigit",
"(",
")",
":",
"sbytes",
"=",
"int",
"(",
"sbytes",
")",
"if",
"unit",
"=="... | Given a human-readable byte string (e.g. 2G, 30M),
return the number of bytes. Will return 0 if the argument has
unexpected form.
.. versionadded:: 2018.3.0 | [
"Given",
"a",
"human",
"-",
"readable",
"byte",
"string",
"(",
"e",
".",
"g",
".",
"2G",
"30M",
")",
"return",
"the",
"number",
"of",
"bytes",
".",
"Will",
"return",
"0",
"if",
"the",
"argument",
"has",
"unexpected",
"form",
"."
] | python | train | 24.52 |
saltstack/salt | salt/queues/sqlite_queue.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/queues/sqlite_queue.py#L211-L244 | def pop(queue, quantity=1, is_runner=False):
'''
Pop one or more or all items from the queue return them.
'''
cmd = 'SELECT name FROM {0}'.format(queue)
if quantity != 'all':
try:
quantity = int(quantity)
except ValueError as exc:
error_txt = ('Quantity must b... | [
"def",
"pop",
"(",
"queue",
",",
"quantity",
"=",
"1",
",",
"is_runner",
"=",
"False",
")",
":",
"cmd",
"=",
"'SELECT name FROM {0}'",
".",
"format",
"(",
"queue",
")",
"if",
"quantity",
"!=",
"'all'",
":",
"try",
":",
"quantity",
"=",
"int",
"(",
"q... | Pop one or more or all items from the queue return them. | [
"Pop",
"one",
"or",
"more",
"or",
"all",
"items",
"from",
"the",
"queue",
"return",
"them",
"."
] | python | train | 33.294118 |
ArangoDB-Community/pyArango | pyArango/document.py | https://github.com/ArangoDB-Community/pyArango/blob/dd72e5f6c540e5e148943d615ddf7553bb78ce0b/pyArango/document.py#L59-L80 | def validateField(self, field) :
"""Validatie a field"""
if field not in self.validators and not self.collection._validation['allow_foreign_fields'] :
raise SchemaViolation(self.collection.__class__, field)
if field in self.store:
if isinstance(self.store[field], Documen... | [
"def",
"validateField",
"(",
"self",
",",
"field",
")",
":",
"if",
"field",
"not",
"in",
"self",
".",
"validators",
"and",
"not",
"self",
".",
"collection",
".",
"_validation",
"[",
"'allow_foreign_fields'",
"]",
":",
"raise",
"SchemaViolation",
"(",
"self",... | Validatie a field | [
"Validatie",
"a",
"field"
] | python | train | 49.818182 |
ambitioninc/django-query-builder | querybuilder/query.py | https://github.com/ambitioninc/django-query-builder/blob/113a7d845d3ddc6a45621b9880308e756f87c5bf/querybuilder/query.py#L184-L229 | def get_condition(self):
"""
Determines the condition to be used in the condition part of the join sql.
:return: The condition for the join clause
:rtype: str or None
"""
if self.condition:
return self.condition
if type(self.right_table) is ModelTabl... | [
"def",
"get_condition",
"(",
"self",
")",
":",
"if",
"self",
".",
"condition",
":",
"return",
"self",
".",
"condition",
"if",
"type",
"(",
"self",
".",
"right_table",
")",
"is",
"ModelTable",
"and",
"type",
"(",
"self",
".",
"right_table",
")",
"is",
"... | Determines the condition to be used in the condition part of the join sql.
:return: The condition for the join clause
:rtype: str or None | [
"Determines",
"the",
"condition",
"to",
"be",
"used",
"in",
"the",
"condition",
"part",
"of",
"the",
"join",
"sql",
"."
] | python | train | 44.956522 |
SHTOOLS/SHTOOLS | pyshtools/shclasses/shgravgrid.py | https://github.com/SHTOOLS/SHTOOLS/blob/9a115cf83002df2ddec6b7f41aeb6be688e285de/pyshtools/shclasses/shgravgrid.py#L176-L227 | def plot_theta(self, colorbar=True, cb_orientation='vertical',
cb_label='$g_\\theta$, m s$^{-2}$', ax=None, show=True,
fname=None, **kwargs):
"""
Plot the theta component of the gravity field.
Usage
-----
x.plot_theta([tick_interval, xlabel,... | [
"def",
"plot_theta",
"(",
"self",
",",
"colorbar",
"=",
"True",
",",
"cb_orientation",
"=",
"'vertical'",
",",
"cb_label",
"=",
"'$g_\\\\theta$, m s$^{-2}$'",
",",
"ax",
"=",
"None",
",",
"show",
"=",
"True",
",",
"fname",
"=",
"None",
",",
"*",
"*",
"kw... | Plot the theta component of the gravity field.
Usage
-----
x.plot_theta([tick_interval, xlabel, ylabel, ax, colorbar,
cb_orientation, cb_label, show, fname, **kwargs])
Parameters
----------
tick_interval : list or tuple, optional, default = [30, 30... | [
"Plot",
"the",
"theta",
"component",
"of",
"the",
"gravity",
"field",
"."
] | python | train | 42.653846 |
apple/turicreate | deps/src/boost_1_68_0/tools/build/src/build/project.py | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/build/project.py#L1136-L1142 | def constant(self, name, value):
"""Declare and set a project global constant.
Project global constants are normal variables but should
not be changed. They are applied to every child Jamfile."""
assert is_iterable_typed(name, basestring)
assert is_iterable_typed(value, basestrin... | [
"def",
"constant",
"(",
"self",
",",
"name",
",",
"value",
")",
":",
"assert",
"is_iterable_typed",
"(",
"name",
",",
"basestring",
")",
"assert",
"is_iterable_typed",
"(",
"value",
",",
"basestring",
")",
"self",
".",
"registry",
".",
"current",
"(",
")",... | Declare and set a project global constant.
Project global constants are normal variables but should
not be changed. They are applied to every child Jamfile. | [
"Declare",
"and",
"set",
"a",
"project",
"global",
"constant",
".",
"Project",
"global",
"constants",
"are",
"normal",
"variables",
"but",
"should",
"not",
"be",
"changed",
".",
"They",
"are",
"applied",
"to",
"every",
"child",
"Jamfile",
"."
] | python | train | 53.857143 |
eyeseast/python-tablefu | table_fu/formatting.py | https://github.com/eyeseast/python-tablefu/blob/d8761c1f87e3f89d9b89b0b6b9283fc4738b6676/table_fu/formatting.py#L10-L19 | def _saferound(value, decimal_places):
"""
Rounds a float value off to the desired precision
"""
try:
f = float(value)
except ValueError:
return ''
format = '%%.%df' % decimal_places
return format % f | [
"def",
"_saferound",
"(",
"value",
",",
"decimal_places",
")",
":",
"try",
":",
"f",
"=",
"float",
"(",
"value",
")",
"except",
"ValueError",
":",
"return",
"''",
"format",
"=",
"'%%.%df'",
"%",
"decimal_places",
"return",
"format",
"%",
"f"
] | Rounds a float value off to the desired precision | [
"Rounds",
"a",
"float",
"value",
"off",
"to",
"the",
"desired",
"precision"
] | python | train | 23.5 |
biocore/burrito | burrito/util.py | https://github.com/biocore/burrito/blob/3b1dcc560431cc2b7a4856b99aafe36d32082356/burrito/util.py#L390-L397 | def _absolute(self, path):
""" Convert a filename to an absolute path """
path = FilePath(path)
if isabs(path):
return path
else:
# these are both Path objects, so joining with + is acceptable
return self.WorkingDir + path | [
"def",
"_absolute",
"(",
"self",
",",
"path",
")",
":",
"path",
"=",
"FilePath",
"(",
"path",
")",
"if",
"isabs",
"(",
"path",
")",
":",
"return",
"path",
"else",
":",
"# these are both Path objects, so joining with + is acceptable",
"return",
"self",
".",
"Wo... | Convert a filename to an absolute path | [
"Convert",
"a",
"filename",
"to",
"an",
"absolute",
"path"
] | python | train | 35.375 |
python-cmd2/cmd2 | cmd2/cmd2.py | https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/cmd2/cmd2.py#L2115-L2127 | def default(self, statement: Statement) -> Optional[bool]:
"""Executed when the command given isn't a recognized command implemented by a do_* method.
:param statement: Statement object with parsed input
"""
if self.default_to_shell:
if 'shell' not in self.exclude_from_histo... | [
"def",
"default",
"(",
"self",
",",
"statement",
":",
"Statement",
")",
"->",
"Optional",
"[",
"bool",
"]",
":",
"if",
"self",
".",
"default_to_shell",
":",
"if",
"'shell'",
"not",
"in",
"self",
".",
"exclude_from_history",
":",
"self",
".",
"history",
"... | Executed when the command given isn't a recognized command implemented by a do_* method.
:param statement: Statement object with parsed input | [
"Executed",
"when",
"the",
"command",
"given",
"isn",
"t",
"a",
"recognized",
"command",
"implemented",
"by",
"a",
"do_",
"*",
"method",
"."
] | python | train | 44 |
cltl/KafNafParserPy | KafNafParserPy/constituency_data.py | https://github.com/cltl/KafNafParserPy/blob/9bc32e803c176404b255ba317479b8780ed5f569/KafNafParserPy/constituency_data.py#L308-L317 | def get_terminals_as_list(self):
"""
Iterator that returns all the terminal objects
@rtype: L{Cterminal}
@return: terminal objects as list
"""
terminalList = []
for t_node in self.__get_t_nodes():
terminalList.append(Cterminal(t_node))
return t... | [
"def",
"get_terminals_as_list",
"(",
"self",
")",
":",
"terminalList",
"=",
"[",
"]",
"for",
"t_node",
"in",
"self",
".",
"__get_t_nodes",
"(",
")",
":",
"terminalList",
".",
"append",
"(",
"Cterminal",
"(",
"t_node",
")",
")",
"return",
"terminalList"
] | Iterator that returns all the terminal objects
@rtype: L{Cterminal}
@return: terminal objects as list | [
"Iterator",
"that",
"returns",
"all",
"the",
"terminal",
"objects"
] | python | train | 32.2 |
abingham/docopt-subcommands | docopt_subcommands/__init__.py | https://github.com/abingham/docopt-subcommands/blob/4b5cd75bb8eed01f9405345446ca58e9a29d67ad/docopt_subcommands/__init__.py#L17-L69 | def main(program=None,
version=None,
doc_template=None,
commands=None,
argv=None,
exit_at_end=True):
"""Top-level driver for creating subcommand-based programs.
Args:
program: The name of your program.
version: The version string for your program.
... | [
"def",
"main",
"(",
"program",
"=",
"None",
",",
"version",
"=",
"None",
",",
"doc_template",
"=",
"None",
",",
"commands",
"=",
"None",
",",
"argv",
"=",
"None",
",",
"exit_at_end",
"=",
"True",
")",
":",
"if",
"commands",
"is",
"None",
":",
"if",
... | Top-level driver for creating subcommand-based programs.
Args:
program: The name of your program.
version: The version string for your program.
doc_template: The top-level docstring template for your program. If
`None`, a standard default version is applied.
commands: A ... | [
"Top",
"-",
"level",
"driver",
"for",
"creating",
"subcommand",
"-",
"based",
"programs",
"."
] | python | train | 35.962264 |
numenta/nupic | src/nupic/data/file_record_stream.py | https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/data/file_record_stream.py#L609-L659 | def _updateSequenceInfo(self, r):
"""Keep track of sequence and make sure time goes forward
Check if the current record is the beginning of a new sequence
A new sequence starts in 2 cases:
1. The sequence id changed (if there is a sequence id field)
2. The reset field is 1 (if there is a reset fie... | [
"def",
"_updateSequenceInfo",
"(",
"self",
",",
"r",
")",
":",
"# Get current sequence id (if any)",
"newSequence",
"=",
"False",
"sequenceId",
"=",
"(",
"r",
"[",
"self",
".",
"_sequenceIdIdx",
"]",
"if",
"self",
".",
"_sequenceIdIdx",
"is",
"not",
"None",
"e... | Keep track of sequence and make sure time goes forward
Check if the current record is the beginning of a new sequence
A new sequence starts in 2 cases:
1. The sequence id changed (if there is a sequence id field)
2. The reset field is 1 (if there is a reset field)
Note that if there is no sequenc... | [
"Keep",
"track",
"of",
"sequence",
"and",
"make",
"sure",
"time",
"goes",
"forward"
] | python | valid | 36.137255 |
UCSBarchlab/PyRTL | pyrtl/rtllib/adders.py | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/rtllib/adders.py#L258-L282 | def fast_group_adder(wires_to_add, reducer=wallace_reducer, final_adder=kogge_stone):
"""
A generalization of the carry save adder, this is designed to add many numbers
together in a both area and time efficient manner. Uses a tree reducer
to achieve this performance
:param [WireVector] wires_to_a... | [
"def",
"fast_group_adder",
"(",
"wires_to_add",
",",
"reducer",
"=",
"wallace_reducer",
",",
"final_adder",
"=",
"kogge_stone",
")",
":",
"import",
"math",
"longest_wire_len",
"=",
"max",
"(",
"len",
"(",
"w",
")",
"for",
"w",
"in",
"wires_to_add",
")",
"res... | A generalization of the carry save adder, this is designed to add many numbers
together in a both area and time efficient manner. Uses a tree reducer
to achieve this performance
:param [WireVector] wires_to_add: an array of wirevectors to add
:param reducer: the tree reducer to use
:param final_ad... | [
"A",
"generalization",
"of",
"the",
"carry",
"save",
"adder",
"this",
"is",
"designed",
"to",
"add",
"many",
"numbers",
"together",
"in",
"a",
"both",
"area",
"and",
"time",
"efficient",
"manner",
".",
"Uses",
"a",
"tree",
"reducer",
"to",
"achieve",
"this... | python | train | 39.36 |
DataBiosphere/toil | src/toil/lib/ec2.py | https://github.com/DataBiosphere/toil/blob/a8252277ff814e7bee0971139c2344f88e44b644/src/toil/lib/ec2.py#L240-L255 | def create_ondemand_instances(ec2, image_id, spec, num_instances=1):
"""
Requests the RunInstances EC2 API call but accounts for the race between recently created
instance profiles, IAM roles and an instance creation that refers to them.
:rtype: list[Instance]
"""
instance_type = spec['instance... | [
"def",
"create_ondemand_instances",
"(",
"ec2",
",",
"image_id",
",",
"spec",
",",
"num_instances",
"=",
"1",
")",
":",
"instance_type",
"=",
"spec",
"[",
"'instance_type'",
"]",
"log",
".",
"info",
"(",
"'Creating %s instance(s) ... '",
",",
"instance_type",
")... | Requests the RunInstances EC2 API call but accounts for the race between recently created
instance profiles, IAM roles and an instance creation that refers to them.
:rtype: list[Instance] | [
"Requests",
"the",
"RunInstances",
"EC2",
"API",
"call",
"but",
"accounts",
"for",
"the",
"race",
"between",
"recently",
"created",
"instance",
"profiles",
"IAM",
"roles",
"and",
"an",
"instance",
"creation",
"that",
"refers",
"to",
"them",
"."
] | python | train | 46.25 |
Netflix-Skunkworks/historical | historical/vpc/collector.py | https://github.com/Netflix-Skunkworks/historical/blob/c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a/historical/vpc/collector.py#L44-L75 | def describe_vpc(record):
"""Attempts to describe vpc ids."""
account_id = record['account']
vpc_name = cloudwatch.filter_request_parameters('vpcName', record)
vpc_id = cloudwatch.filter_request_parameters('vpcId', record)
try:
if vpc_id and vpc_name: # pylint: disable=R1705
re... | [
"def",
"describe_vpc",
"(",
"record",
")",
":",
"account_id",
"=",
"record",
"[",
"'account'",
"]",
"vpc_name",
"=",
"cloudwatch",
".",
"filter_request_parameters",
"(",
"'vpcName'",
",",
"record",
")",
"vpc_id",
"=",
"cloudwatch",
".",
"filter_request_parameters"... | Attempts to describe vpc ids. | [
"Attempts",
"to",
"describe",
"vpc",
"ids",
"."
] | python | train | 33.1875 |
saltstack/salt | salt/states/proxy.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/proxy.py#L40-L144 | def managed(name, port, services=None, user=None, password=None, bypass_domains=None, network_service='Ethernet'):
'''
Manages proxy settings for this mininon
name
The proxy server to use
port
The port used by the proxy server
services
A list of the services that should us... | [
"def",
"managed",
"(",
"name",
",",
"port",
",",
"services",
"=",
"None",
",",
"user",
"=",
"None",
",",
"password",
"=",
"None",
",",
"bypass_domains",
"=",
"None",
",",
"network_service",
"=",
"'Ethernet'",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
... | Manages proxy settings for this mininon
name
The proxy server to use
port
The port used by the proxy server
services
A list of the services that should use the given proxy settings, valid services include http, https and ftp.
If no service is given all of the valid service... | [
"Manages",
"proxy",
"settings",
"for",
"this",
"mininon"
] | python | train | 37.933333 |
NASA-AMMOS/AIT-Core | ait/core/cmd.py | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/cmd.py#L347-L375 | def validate(self, cmd, messages=None):
"""Returns True if the given Command is valid, False otherwise.
Validation error messages are appended to an optional messages
array.
"""
valid = True
args = [ arg for arg in cmd.args if arg is not None ]
if self.nargs != ... | [
"def",
"validate",
"(",
"self",
",",
"cmd",
",",
"messages",
"=",
"None",
")",
":",
"valid",
"=",
"True",
"args",
"=",
"[",
"arg",
"for",
"arg",
"in",
"cmd",
".",
"args",
"if",
"arg",
"is",
"not",
"None",
"]",
"if",
"self",
".",
"nargs",
"!=",
... | Returns True if the given Command is valid, False otherwise.
Validation error messages are appended to an optional messages
array. | [
"Returns",
"True",
"if",
"the",
"given",
"Command",
"is",
"valid",
"False",
"otherwise",
".",
"Validation",
"error",
"messages",
"are",
"appended",
"to",
"an",
"optional",
"messages",
"array",
"."
] | python | train | 36.586207 |
DataDog/integrations-core | tokumx/datadog_checks/tokumx/vendor/gridfs/grid_file.py | https://github.com/DataDog/integrations-core/blob/ebd41c873cf9f97a8c51bf9459bc6a7536af8acd/tokumx/datadog_checks/tokumx/vendor/gridfs/grid_file.py#L289-L297 | def close(self):
"""Flush the file and close it.
A closed file cannot be written any more. Calling
:meth:`close` more than once is allowed.
"""
if not self._closed:
self.__flush()
object.__setattr__(self, "_closed", True) | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_closed",
":",
"self",
".",
"__flush",
"(",
")",
"object",
".",
"__setattr__",
"(",
"self",
",",
"\"_closed\"",
",",
"True",
")"
] | Flush the file and close it.
A closed file cannot be written any more. Calling
:meth:`close` more than once is allowed. | [
"Flush",
"the",
"file",
"and",
"close",
"it",
"."
] | python | train | 30.888889 |
VIVelev/PyDojoML | dojo/cluster/mixture/gaussian_mixture_model.py | https://github.com/VIVelev/PyDojoML/blob/773fdce6866aa6decd306a5a85f94129fed816eb/dojo/cluster/mixture/gaussian_mixture_model.py#L100-L107 | def _converged(self, X):
"""Covergence if || likehood - last_likelihood || < tolerance"""
if len(self.responsibilities) < 2:
return False
diff = np.linalg.norm(self.responsibilities[-1] - self.responsibilities[-2])
return diff <= self.tolerance | [
"def",
"_converged",
"(",
"self",
",",
"X",
")",
":",
"if",
"len",
"(",
"self",
".",
"responsibilities",
")",
"<",
"2",
":",
"return",
"False",
"diff",
"=",
"np",
".",
"linalg",
".",
"norm",
"(",
"self",
".",
"responsibilities",
"[",
"-",
"1",
"]",... | Covergence if || likehood - last_likelihood || < tolerance | [
"Covergence",
"if",
"||",
"likehood",
"-",
"last_likelihood",
"||",
"<",
"tolerance"
] | python | train | 35.375 |
linuxsoftware/ls.joyous | ls/joyous/models/events.py | https://github.com/linuxsoftware/ls.joyous/blob/316283140ca5171a68ad3170a5964fdc89be0b56/ls/joyous/models/events.py#L703-L707 | def _getFromTime(self, atDate=None):
"""
Time that the event starts (in the local time zone).
"""
return getLocalTime(self.date, self.time_from, self.tz) | [
"def",
"_getFromTime",
"(",
"self",
",",
"atDate",
"=",
"None",
")",
":",
"return",
"getLocalTime",
"(",
"self",
".",
"date",
",",
"self",
".",
"time_from",
",",
"self",
".",
"tz",
")"
] | Time that the event starts (in the local time zone). | [
"Time",
"that",
"the",
"event",
"starts",
"(",
"in",
"the",
"local",
"time",
"zone",
")",
"."
] | python | train | 36.2 |
manns/pyspread | pyspread/src/actions/_grid_actions.py | https://github.com/manns/pyspread/blob/0e2fd44c2e0f06605efc3058c20a43a8c1f9e7e0/pyspread/src/actions/_grid_actions.py#L723-L735 | def insert_cols(self, col, no_cols=1):
"""Adds no_cols columns before col, appends if col > maxcols
and marks grid as changed
"""
# Mark content as changed
post_command_event(self.main_window, self.ContentChangedMsg)
tab = self.grid.current_table
self.code_ar... | [
"def",
"insert_cols",
"(",
"self",
",",
"col",
",",
"no_cols",
"=",
"1",
")",
":",
"# Mark content as changed",
"post_command_event",
"(",
"self",
".",
"main_window",
",",
"self",
".",
"ContentChangedMsg",
")",
"tab",
"=",
"self",
".",
"grid",
".",
"current_... | Adds no_cols columns before col, appends if col > maxcols
and marks grid as changed | [
"Adds",
"no_cols",
"columns",
"before",
"col",
"appends",
"if",
"col",
">",
"maxcols"
] | python | train | 26.846154 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.