repo stringlengths 7 54 | path stringlengths 4 192 | url stringlengths 87 284 | code stringlengths 78 104k | code_tokens list | docstring stringlengths 1 46.9k | docstring_tokens list | language stringclasses 1
value | partition stringclasses 3
values |
|---|---|---|---|---|---|---|---|---|
rameshg87/pyremotevbox | pyremotevbox/ZSI/wstools/Utility.py | https://github.com/rameshg87/pyremotevbox/blob/123dffff27da57c8faa3ac1dd4c68b1cf4558b1a/pyremotevbox/ZSI/wstools/Utility.py#L251-L260 | def GetSOAPEnvUri(self, version):
"""Return the appropriate SOAP envelope uri for a given
human-friendly SOAP version string (e.g. '1.1')."""
attrname = 'NS_SOAP_ENV_%s' % join(split(version, '.'), '_')
value = getattr(self, attrname, None)
if value is not None:
re... | [
"def",
"GetSOAPEnvUri",
"(",
"self",
",",
"version",
")",
":",
"attrname",
"=",
"'NS_SOAP_ENV_%s'",
"%",
"join",
"(",
"split",
"(",
"version",
",",
"'.'",
")",
",",
"'_'",
")",
"value",
"=",
"getattr",
"(",
"self",
",",
"attrname",
",",
"None",
")",
... | Return the appropriate SOAP envelope uri for a given
human-friendly SOAP version string (e.g. '1.1'). | [
"Return",
"the",
"appropriate",
"SOAP",
"envelope",
"uri",
"for",
"a",
"given",
"human",
"-",
"friendly",
"SOAP",
"version",
"string",
"(",
"e",
".",
"g",
".",
"1",
".",
"1",
")",
"."
] | python | train |
crazy-canux/arguspy | arguspy/http_requests.py | https://github.com/crazy-canux/arguspy/blob/e9486b5df61978a990d56bf43de35f3a4cdefcc3/arguspy/http_requests.py#L61-L67 | def close(self):
"""Close the http/https connect."""
try:
self.response.close()
self.logger.debug("close connect succeed.")
except Exception as e:
self.unknown("close connect error: %s" % e) | [
"def",
"close",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"response",
".",
"close",
"(",
")",
"self",
".",
"logger",
".",
"debug",
"(",
"\"close connect succeed.\"",
")",
"except",
"Exception",
"as",
"e",
":",
"self",
".",
"unknown",
"(",
"\"clos... | Close the http/https connect. | [
"Close",
"the",
"http",
"/",
"https",
"connect",
"."
] | python | valid |
logston/py3s3 | py3s3/storage.py | https://github.com/logston/py3s3/blob/1910ca60c53a53d839d6f7b09c05b555f3bfccf4/py3s3/storage.py#L261-L274 | def _get_content_type(self, file):
"""
Return content type of file. If file does not
have a content type, make a guess.
"""
if file.mimetype:
return file.mimetype
# get file extension
_, extension = os.path.splitext(file.name)
extension = exte... | [
"def",
"_get_content_type",
"(",
"self",
",",
"file",
")",
":",
"if",
"file",
".",
"mimetype",
":",
"return",
"file",
".",
"mimetype",
"# get file extension",
"_",
",",
"extension",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"file",
".",
"name",
")",
... | Return content type of file. If file does not
have a content type, make a guess. | [
"Return",
"content",
"type",
"of",
"file",
".",
"If",
"file",
"does",
"not",
"have",
"a",
"content",
"type",
"make",
"a",
"guess",
"."
] | python | train |
biocore/burrito | burrito/util.py | https://github.com/biocore/burrito/blob/3b1dcc560431cc2b7a4856b99aafe36d32082356/burrito/util.py#L399-L421 | def _get_base_command(self):
""" Returns the full command string
input_arg: the argument to the command which represents the input
to the program, this will be a string, either
representing input or a filename to get input from
tI"""
command_parts = ... | [
"def",
"_get_base_command",
"(",
"self",
")",
":",
"command_parts",
"=",
"[",
"]",
"# Append a change directory to the beginning of the command to change",
"# to self.WorkingDir before running the command",
"# WorkingDir should be in quotes -- filenames might contain spaces",
"cd_command",... | Returns the full command string
input_arg: the argument to the command which represents the input
to the program, this will be a string, either
representing input or a filename to get input from
tI | [
"Returns",
"the",
"full",
"command",
"string"
] | python | train |
cthoyt/ols-client | src/ols_client/client.py | https://github.com/cthoyt/ols-client/blob/8c6bb54888675652d25324184967392d00d128fc/src/ols_client/client.py#L93-L107 | def suggest(self, name, ontology=None):
"""Suggest terms from an optional list of ontologies
:param str name:
:param list[str] ontology:
:rtype: dict
.. seealso:: https://www.ebi.ac.uk/ols/docs/api#_suggest_term
"""
params = {'q': name}
if ontology:
... | [
"def",
"suggest",
"(",
"self",
",",
"name",
",",
"ontology",
"=",
"None",
")",
":",
"params",
"=",
"{",
"'q'",
":",
"name",
"}",
"if",
"ontology",
":",
"params",
"[",
"'ontology'",
"]",
"=",
"','",
".",
"join",
"(",
"ontology",
")",
"response",
"="... | Suggest terms from an optional list of ontologies
:param str name:
:param list[str] ontology:
:rtype: dict
.. seealso:: https://www.ebi.ac.uk/ols/docs/api#_suggest_term | [
"Suggest",
"terms",
"from",
"an",
"optional",
"list",
"of",
"ontologies"
] | python | test |
googleapis/oauth2client | oauth2client/_helpers.py | https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/_helpers.py#L182-L202 | def parse_unique_urlencoded(content):
"""Parses unique key-value parameters from urlencoded content.
Args:
content: string, URL-encoded key-value pairs.
Returns:
dict, The key-value pairs from ``content``.
Raises:
ValueError: if one of the keys is repeated.
"""
urlenco... | [
"def",
"parse_unique_urlencoded",
"(",
"content",
")",
":",
"urlencoded_params",
"=",
"urllib",
".",
"parse",
".",
"parse_qs",
"(",
"content",
")",
"params",
"=",
"{",
"}",
"for",
"key",
",",
"value",
"in",
"six",
".",
"iteritems",
"(",
"urlencoded_params",
... | Parses unique key-value parameters from urlencoded content.
Args:
content: string, URL-encoded key-value pairs.
Returns:
dict, The key-value pairs from ``content``.
Raises:
ValueError: if one of the keys is repeated. | [
"Parses",
"unique",
"key",
"-",
"value",
"parameters",
"from",
"urlencoded",
"content",
"."
] | python | valid |
nschloe/matplotlib2tikz | matplotlib2tikz/line2d.py | https://github.com/nschloe/matplotlib2tikz/blob/ac5daca6f38b834d757f6c6ae6cc34121956f46b/matplotlib2tikz/line2d.py#L147-L182 | def _mpl_marker2pgfp_marker(data, mpl_marker, marker_face_color):
"""Translates a marker style of matplotlib to the corresponding style
in PGFPlots.
"""
# try default list
try:
pgfplots_marker = _MP_MARKER2PGF_MARKER[mpl_marker]
except KeyError:
pass
else:
if (marker_... | [
"def",
"_mpl_marker2pgfp_marker",
"(",
"data",
",",
"mpl_marker",
",",
"marker_face_color",
")",
":",
"# try default list",
"try",
":",
"pgfplots_marker",
"=",
"_MP_MARKER2PGF_MARKER",
"[",
"mpl_marker",
"]",
"except",
"KeyError",
":",
"pass",
"else",
":",
"if",
"... | Translates a marker style of matplotlib to the corresponding style
in PGFPlots. | [
"Translates",
"a",
"marker",
"style",
"of",
"matplotlib",
"to",
"the",
"corresponding",
"style",
"in",
"PGFPlots",
"."
] | python | train |
madsbk/lrcloud | lrcloud/__main__.py | https://github.com/madsbk/lrcloud/blob/8d99be3e1abdf941642e9a1c86b7d775dc373c0b/lrcloud/__main__.py#L271-L369 | def cmd_normal(args):
"""Normal procedure:
* Pull from cloud (if necessary)
* Run Lightroom
* Push to cloud
"""
logging.info("cmd_normal")
(lcat, ccat) = (args.local_catalog, args.cloud_catalog)
(lmeta, cmeta) = ("%s.lrcloud"%lcat, "%s.lrcloud"%ccat)
if not isfile(lcat)... | [
"def",
"cmd_normal",
"(",
"args",
")",
":",
"logging",
".",
"info",
"(",
"\"cmd_normal\"",
")",
"(",
"lcat",
",",
"ccat",
")",
"=",
"(",
"args",
".",
"local_catalog",
",",
"args",
".",
"cloud_catalog",
")",
"(",
"lmeta",
",",
"cmeta",
")",
"=",
"(",
... | Normal procedure:
* Pull from cloud (if necessary)
* Run Lightroom
* Push to cloud | [
"Normal",
"procedure",
":",
"*",
"Pull",
"from",
"cloud",
"(",
"if",
"necessary",
")",
"*",
"Run",
"Lightroom",
"*",
"Push",
"to",
"cloud"
] | python | valid |
ucsb-cs-education/hairball | hairball/plugins/blocks.py | https://github.com/ucsb-cs-education/hairball/blob/c6da8971f8a34e88ce401d36b51431715e1dff5b/hairball/plugins/blocks.py#L67-L71 | def finalize(self):
"""Output the number of instances that contained dead code."""
if self.total_instances > 1:
print('{} of {} instances contained dead code.'
.format(self.dead_code_instances, self.total_instances)) | [
"def",
"finalize",
"(",
"self",
")",
":",
"if",
"self",
".",
"total_instances",
">",
"1",
":",
"print",
"(",
"'{} of {} instances contained dead code.'",
".",
"format",
"(",
"self",
".",
"dead_code_instances",
",",
"self",
".",
"total_instances",
")",
")"
] | Output the number of instances that contained dead code. | [
"Output",
"the",
"number",
"of",
"instances",
"that",
"contained",
"dead",
"code",
"."
] | python | train |
Becksteinlab/GromacsWrapper | gromacs/core.py | https://github.com/Becksteinlab/GromacsWrapper/blob/d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9/gromacs/core.py#L301-L322 | def transform_args(self, *args, **kwargs):
"""Transform arguments and return them as a list suitable for Popen."""
options = []
for option,value in kwargs.items():
if not option.startswith('-'):
# heuristic for turning key=val pairs into options
# (fai... | [
"def",
"transform_args",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"options",
"=",
"[",
"]",
"for",
"option",
",",
"value",
"in",
"kwargs",
".",
"items",
"(",
")",
":",
"if",
"not",
"option",
".",
"startswith",
"(",
"'-'",
... | Transform arguments and return them as a list suitable for Popen. | [
"Transform",
"arguments",
"and",
"return",
"them",
"as",
"a",
"list",
"suitable",
"for",
"Popen",
"."
] | python | valid |
Dentosal/python-sc2 | sc2/client.py | https://github.com/Dentosal/python-sc2/blob/608bd25f04e89d39cef68b40101d8e9a8a7f1634/sc2/client.py#L197-L230 | async def query_pathings(self, zipped_list: List[List[Union[Unit, Point2, Point3]]]) -> List[Union[float, int]]:
""" Usage: await self.query_pathings([[unit1, target2], [unit2, target2]])
-> returns [distance1, distance2]
Caution: returns 0 when path not found
Might merge this function w... | [
"async",
"def",
"query_pathings",
"(",
"self",
",",
"zipped_list",
":",
"List",
"[",
"List",
"[",
"Union",
"[",
"Unit",
",",
"Point2",
",",
"Point3",
"]",
"]",
"]",
")",
"->",
"List",
"[",
"Union",
"[",
"float",
",",
"int",
"]",
"]",
":",
"assert",... | Usage: await self.query_pathings([[unit1, target2], [unit2, target2]])
-> returns [distance1, distance2]
Caution: returns 0 when path not found
Might merge this function with the function above | [
"Usage",
":",
"await",
"self",
".",
"query_pathings",
"(",
"[[",
"unit1",
"target2",
"]",
"[",
"unit2",
"target2",
"]]",
")",
"-",
">",
"returns",
"[",
"distance1",
"distance2",
"]",
"Caution",
":",
"returns",
"0",
"when",
"path",
"not",
"found",
"Might"... | python | train |
kronok/django-google-analytics-reporter | google_analytics_reporter/tracking.py | https://github.com/kronok/django-google-analytics-reporter/blob/cca5fb0920ec68cfe03069cedf53fb4c6440cc11/google_analytics_reporter/tracking.py#L53-L64 | def get_payload(self, *args, **kwargs):
"""Receive all passed in args, kwargs, and combine them together with any required params"""
if not kwargs:
kwargs = self.default_params
else:
kwargs.update(self.default_params)
for item in args:
if isinstance(it... | [
"def",
"get_payload",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"kwargs",
":",
"kwargs",
"=",
"self",
".",
"default_params",
"else",
":",
"kwargs",
".",
"update",
"(",
"self",
".",
"default_params",
")",
"for",
"i... | Receive all passed in args, kwargs, and combine them together with any required params | [
"Receive",
"all",
"passed",
"in",
"args",
"kwargs",
"and",
"combine",
"them",
"together",
"with",
"any",
"required",
"params"
] | python | train |
mrcagney/gtfstk | gtfstk/shapes.py | https://github.com/mrcagney/gtfstk/blob/c91494e6fefc02523889655a0dc92d1c0eee8d03/gtfstk/shapes.py#L213-L247 | def geometrize_shapes(
shapes: DataFrame, *, use_utm: bool = False
) -> DataFrame:
"""
Given a GTFS shapes DataFrame, convert it to a GeoPandas
GeoDataFrame and return the result.
The result has a ``'geometry'`` column of WGS84 LineStrings
instead of the columns ``'shape_pt_sequence'``, ``'shape... | [
"def",
"geometrize_shapes",
"(",
"shapes",
":",
"DataFrame",
",",
"*",
",",
"use_utm",
":",
"bool",
"=",
"False",
")",
"->",
"DataFrame",
":",
"import",
"geopandas",
"as",
"gpd",
"f",
"=",
"shapes",
".",
"copy",
"(",
")",
".",
"sort_values",
"(",
"[",
... | Given a GTFS shapes DataFrame, convert it to a GeoPandas
GeoDataFrame and return the result.
The result has a ``'geometry'`` column of WGS84 LineStrings
instead of the columns ``'shape_pt_sequence'``, ``'shape_pt_lon'``,
``'shape_pt_lat'``, and ``'shape_dist_traveled'``.
If ``use_utm``, then use loc... | [
"Given",
"a",
"GTFS",
"shapes",
"DataFrame",
"convert",
"it",
"to",
"a",
"GeoPandas",
"GeoDataFrame",
"and",
"return",
"the",
"result",
".",
"The",
"result",
"has",
"a",
"geometry",
"column",
"of",
"WGS84",
"LineStrings",
"instead",
"of",
"the",
"columns",
"... | python | train |
Jarn/jarn.viewdoc | jarn/viewdoc/viewdoc.py | https://github.com/Jarn/jarn.viewdoc/blob/59ae82fd1658889c41096c1d8c08dcb1047dc349/jarn/viewdoc/viewdoc.py#L463-L507 | def parse_options(self, args, depth=0):
"""Parse command line options.
"""
style_names = tuple(self.defaults.known_styles)
style_opts = tuple('--'+x for x in style_names)
try:
options, remaining_args = getopt.gnu_getopt(args, 'b:c:hls:v',
('help', 'st... | [
"def",
"parse_options",
"(",
"self",
",",
"args",
",",
"depth",
"=",
"0",
")",
":",
"style_names",
"=",
"tuple",
"(",
"self",
".",
"defaults",
".",
"known_styles",
")",
"style_opts",
"=",
"tuple",
"(",
"'--'",
"+",
"x",
"for",
"x",
"in",
"style_names",... | Parse command line options. | [
"Parse",
"command",
"line",
"options",
"."
] | python | train |
knagra/farnsworth | base/redirects.py | https://github.com/knagra/farnsworth/blob/1b6589f0d9fea154f0a1e2231ed906764ed26d26/base/redirects.py#L23-L32 | def red_home(request, message=None):
'''
Convenience function for redirecting users who don't have access to a page to the home page.
Parameters:
request - the request in the calling function
message - a message from the caller function
'''
if message:
messages.add_message(re... | [
"def",
"red_home",
"(",
"request",
",",
"message",
"=",
"None",
")",
":",
"if",
"message",
":",
"messages",
".",
"add_message",
"(",
"request",
",",
"messages",
".",
"ERROR",
",",
"message",
")",
"return",
"HttpResponseRedirect",
"(",
"reverse",
"(",
"'hom... | Convenience function for redirecting users who don't have access to a page to the home page.
Parameters:
request - the request in the calling function
message - a message from the caller function | [
"Convenience",
"function",
"for",
"redirecting",
"users",
"who",
"don",
"t",
"have",
"access",
"to",
"a",
"page",
"to",
"the",
"home",
"page",
".",
"Parameters",
":",
"request",
"-",
"the",
"request",
"in",
"the",
"calling",
"function",
"message",
"-",
"a"... | python | train |
saltstack/salt | salt/utils/master.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/master.py#L625-L635 | def secure(self):
'''
secure the sockets for root-only access
'''
log.debug('ConCache securing sockets')
if os.path.exists(self.cache_sock):
os.chmod(self.cache_sock, 0o600)
if os.path.exists(self.update_sock):
os.chmod(self.update_sock, 0o600)
... | [
"def",
"secure",
"(",
"self",
")",
":",
"log",
".",
"debug",
"(",
"'ConCache securing sockets'",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"cache_sock",
")",
":",
"os",
".",
"chmod",
"(",
"self",
".",
"cache_sock",
",",
"0o600",
... | secure the sockets for root-only access | [
"secure",
"the",
"sockets",
"for",
"root",
"-",
"only",
"access"
] | python | train |
googledatalab/pydatalab | google/datalab/storage/_bucket.py | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/storage/_bucket.py#L215-L233 | def contains(self, name):
"""Checks if the specified bucket exists.
Args:
name: the name of the bucket to lookup.
Returns:
True if the bucket exists; False otherwise.
Raises:
Exception if there was an error requesting information about the bucket.
"""
try:
self._api.buck... | [
"def",
"contains",
"(",
"self",
",",
"name",
")",
":",
"try",
":",
"self",
".",
"_api",
".",
"buckets_get",
"(",
"name",
")",
"except",
"google",
".",
"datalab",
".",
"utils",
".",
"RequestException",
"as",
"e",
":",
"if",
"e",
".",
"status",
"==",
... | Checks if the specified bucket exists.
Args:
name: the name of the bucket to lookup.
Returns:
True if the bucket exists; False otherwise.
Raises:
Exception if there was an error requesting information about the bucket. | [
"Checks",
"if",
"the",
"specified",
"bucket",
"exists",
"."
] | python | train |
onicagroup/runway | runway/util.py | https://github.com/onicagroup/runway/blob/3f3549ec3bf6e39b9f27d9738a1847f3a4369e7f/runway/util.py#L165-L179 | def fix_windows_command_list(commands):
# type: (List[str]) -> List[str]
"""Return command list with working Windows commands.
npm on windows is npm.cmd, which will blow up
subprocess.check_call(['npm', '...'])
Similar issues arise when calling python apps like pipenv that will have
a windows-... | [
"def",
"fix_windows_command_list",
"(",
"commands",
")",
":",
"# type: (List[str]) -> List[str]",
"fully_qualified_cmd_path",
"=",
"which",
"(",
"commands",
"[",
"0",
"]",
")",
"if",
"fully_qualified_cmd_path",
"and",
"(",
"not",
"which",
"(",
"commands",
"[",
"0",
... | Return command list with working Windows commands.
npm on windows is npm.cmd, which will blow up
subprocess.check_call(['npm', '...'])
Similar issues arise when calling python apps like pipenv that will have
a windows-only suffix applied to them | [
"Return",
"command",
"list",
"with",
"working",
"Windows",
"commands",
"."
] | python | train |
gitpython-developers/GitPython | git/refs/log.py | https://github.com/gitpython-developers/GitPython/blob/1f66e25c25cde2423917ee18c4704fff83b837d1/git/refs/log.py#L239-L252 | def to_file(self, filepath):
"""Write the contents of the reflog instance to a file at the given filepath.
:param filepath: path to file, parent directories are assumed to exist"""
lfd = LockedFD(filepath)
assure_directory_exists(filepath, is_file=True)
fp = lfd.open(write=True,... | [
"def",
"to_file",
"(",
"self",
",",
"filepath",
")",
":",
"lfd",
"=",
"LockedFD",
"(",
"filepath",
")",
"assure_directory_exists",
"(",
"filepath",
",",
"is_file",
"=",
"True",
")",
"fp",
"=",
"lfd",
".",
"open",
"(",
"write",
"=",
"True",
",",
"stream... | Write the contents of the reflog instance to a file at the given filepath.
:param filepath: path to file, parent directories are assumed to exist | [
"Write",
"the",
"contents",
"of",
"the",
"reflog",
"instance",
"to",
"a",
"file",
"at",
"the",
"given",
"filepath",
".",
":",
"param",
"filepath",
":",
"path",
"to",
"file",
"parent",
"directories",
"are",
"assumed",
"to",
"exist"
] | python | train |
gwastro/pycbc | pycbc/io/record.py | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/io/record.py#L1822-L1825 | def spin_sx(self):
"""Returns the x-component of the spin of the secondary mass."""
return conversions.secondary_spin(self.mass1, self.mass2, self.spin1x,
self.spin2x) | [
"def",
"spin_sx",
"(",
"self",
")",
":",
"return",
"conversions",
".",
"secondary_spin",
"(",
"self",
".",
"mass1",
",",
"self",
".",
"mass2",
",",
"self",
".",
"spin1x",
",",
"self",
".",
"spin2x",
")"
] | Returns the x-component of the spin of the secondary mass. | [
"Returns",
"the",
"x",
"-",
"component",
"of",
"the",
"spin",
"of",
"the",
"secondary",
"mass",
"."
] | python | train |
twoolie/NBT | nbt/region.py | https://github.com/twoolie/NBT/blob/b06dd6cc8117d2788da1d8416e642d58bad45762/nbt/region.py#L618-L707 | def write_blockdata(self, x, z, data, compression=COMPRESSION_ZLIB):
"""
Compress the data, write it to file, and add pointers in the header so it
can be found as chunk(x,z).
"""
if compression == COMPRESSION_GZIP:
# Python 3.1 and earlier do not yet support `data = ... | [
"def",
"write_blockdata",
"(",
"self",
",",
"x",
",",
"z",
",",
"data",
",",
"compression",
"=",
"COMPRESSION_ZLIB",
")",
":",
"if",
"compression",
"==",
"COMPRESSION_GZIP",
":",
"# Python 3.1 and earlier do not yet support `data = gzip.compress(data)`.",
"compressed_file... | Compress the data, write it to file, and add pointers in the header so it
can be found as chunk(x,z). | [
"Compress",
"the",
"data",
"write",
"it",
"to",
"file",
"and",
"add",
"pointers",
"in",
"the",
"header",
"so",
"it",
"can",
"be",
"found",
"as",
"chunk",
"(",
"x",
"z",
")",
"."
] | python | train |
rfarley3/Kibana | kibana/mapping.py | https://github.com/rfarley3/Kibana/blob/3df1e13be18edfb39ec173d8d2bbe9e90be61022/kibana/mapping.py#L181-L192 | def get_index_mappings(self, index):
"""Converts all index's doc_types to .kibana"""
fields_arr = []
for (key, val) in iteritems(index):
# self.pr_dbg("\tdoc_type: %s" % key)
doc_mapping = self.get_doc_type_mappings(index[key])
# self.pr_dbg("\tdoc_mapping: %s... | [
"def",
"get_index_mappings",
"(",
"self",
",",
"index",
")",
":",
"fields_arr",
"=",
"[",
"]",
"for",
"(",
"key",
",",
"val",
")",
"in",
"iteritems",
"(",
"index",
")",
":",
"# self.pr_dbg(\"\\tdoc_type: %s\" % key)",
"doc_mapping",
"=",
"self",
".",
"get_do... | Converts all index's doc_types to .kibana | [
"Converts",
"all",
"index",
"s",
"doc_types",
"to",
".",
"kibana"
] | python | train |
gccxml/pygccxml | pygccxml/declarations/pattern_parser.py | https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/pattern_parser.py#L203-L210 | def normalize(self, decl_string, arg_separator=None):
"""implementation details"""
if not self.has_pattern(decl_string):
return decl_string
name, args = self.split(decl_string)
for i, arg in enumerate(args):
args[i] = self.normalize(arg)
return self.join(n... | [
"def",
"normalize",
"(",
"self",
",",
"decl_string",
",",
"arg_separator",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"has_pattern",
"(",
"decl_string",
")",
":",
"return",
"decl_string",
"name",
",",
"args",
"=",
"self",
".",
"split",
"(",
"decl_s... | implementation details | [
"implementation",
"details"
] | python | train |
Shizmob/pydle | pydle/client.py | https://github.com/Shizmob/pydle/blob/7ec7d65d097318ed0bcdc5d8401470287d8c7cf7/pydle/client.py#L365-L373 | async def handle_forever(self):
""" Handle data forever. """
while self.connected:
data = await self.connection.recv()
if not data:
if self.connected:
await self.disconnect(expected=False)
break
await self.on_data(da... | [
"async",
"def",
"handle_forever",
"(",
"self",
")",
":",
"while",
"self",
".",
"connected",
":",
"data",
"=",
"await",
"self",
".",
"connection",
".",
"recv",
"(",
")",
"if",
"not",
"data",
":",
"if",
"self",
".",
"connected",
":",
"await",
"self",
"... | Handle data forever. | [
"Handle",
"data",
"forever",
"."
] | python | train |
wkentaro/pytorch-fcn | torchfcn/ext/fcn.berkeleyvision.org/siftflow_layers.py | https://github.com/wkentaro/pytorch-fcn/blob/97189cbccb2c9b8bd776b356a1fd4b6c03f67d79/torchfcn/ext/fcn.berkeleyvision.org/siftflow_layers.py#L107-L122 | def load_label(self, idx, label_type=None):
"""
Load label image as 1 x height x width integer array of label indices.
The leading singleton dimension is required by the loss.
"""
if label_type == 'semantic':
label = scipy.io.loadmat('{}/SemanticLabels/spatial_envelop... | [
"def",
"load_label",
"(",
"self",
",",
"idx",
",",
"label_type",
"=",
"None",
")",
":",
"if",
"label_type",
"==",
"'semantic'",
":",
"label",
"=",
"scipy",
".",
"io",
".",
"loadmat",
"(",
"'{}/SemanticLabels/spatial_envelope_256x256_static_8outdoorcategories/{}.mat'... | Load label image as 1 x height x width integer array of label indices.
The leading singleton dimension is required by the loss. | [
"Load",
"label",
"image",
"as",
"1",
"x",
"height",
"x",
"width",
"integer",
"array",
"of",
"label",
"indices",
".",
"The",
"leading",
"singleton",
"dimension",
"is",
"required",
"by",
"the",
"loss",
"."
] | python | train |
JarryShaw/PyPCAPKit | src/utilities/validations.py | https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/utilities/validations.py#L66-L73 | def number_check(*args, func=None):
"""Check if arguments are numbers."""
func = func or inspect.stack()[2][3]
for var in args:
if not isinstance(var, numbers.Number):
name = type(var).__name__
raise DigitError(
f'Function {func} expected number, {name} got in... | [
"def",
"number_check",
"(",
"*",
"args",
",",
"func",
"=",
"None",
")",
":",
"func",
"=",
"func",
"or",
"inspect",
".",
"stack",
"(",
")",
"[",
"2",
"]",
"[",
"3",
"]",
"for",
"var",
"in",
"args",
":",
"if",
"not",
"isinstance",
"(",
"var",
","... | Check if arguments are numbers. | [
"Check",
"if",
"arguments",
"are",
"numbers",
"."
] | python | train |
fossasia/knittingpattern | knittingpattern/Instruction.py | https://github.com/fossasia/knittingpattern/blob/8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027/knittingpattern/Instruction.py#L260-L270 | def transfer_to_row(self, new_row):
"""Transfer this instruction to a new row.
:param knittingpattern.Row.Row new_row: the new row the instruction is
in.
"""
if new_row != self._row:
index = self.get_index_in_row()
if index is not None:
... | [
"def",
"transfer_to_row",
"(",
"self",
",",
"new_row",
")",
":",
"if",
"new_row",
"!=",
"self",
".",
"_row",
":",
"index",
"=",
"self",
".",
"get_index_in_row",
"(",
")",
"if",
"index",
"is",
"not",
"None",
":",
"self",
".",
"_row",
".",
"instructions"... | Transfer this instruction to a new row.
:param knittingpattern.Row.Row new_row: the new row the instruction is
in. | [
"Transfer",
"this",
"instruction",
"to",
"a",
"new",
"row",
"."
] | python | valid |
roclark/sportsreference | sportsreference/nba/teams.py | https://github.com/roclark/sportsreference/blob/ea0bae432be76450e137671d2998eb38f962dffd/sportsreference/nba/teams.py#L114-L177 | def dataframe(self):
"""
Returns a pandas DataFrame containing all other class properties and
values. The index for the DataFrame is the string abbreviation of the
team, such as 'DET'.
"""
fields_to_include = {
'abbreviation': self.abbreviation,
'a... | [
"def",
"dataframe",
"(",
"self",
")",
":",
"fields_to_include",
"=",
"{",
"'abbreviation'",
":",
"self",
".",
"abbreviation",
",",
"'assists'",
":",
"self",
".",
"assists",
",",
"'blocks'",
":",
"self",
".",
"blocks",
",",
"'defensive_rebounds'",
":",
"self"... | Returns a pandas DataFrame containing all other class properties and
values. The index for the DataFrame is the string abbreviation of the
team, such as 'DET'. | [
"Returns",
"a",
"pandas",
"DataFrame",
"containing",
"all",
"other",
"class",
"properties",
"and",
"values",
".",
"The",
"index",
"for",
"the",
"DataFrame",
"is",
"the",
"string",
"abbreviation",
"of",
"the",
"team",
"such",
"as",
"DET",
"."
] | python | train |
pjuren/pyokit | src/pyokit/io/genomeAlignment.py | https://github.com/pjuren/pyokit/blob/fddae123b5d817daa39496183f19c000d9c3791f/src/pyokit/io/genomeAlignment.py#L297-L306 | def _build_index(maf_strm, ref_spec):
"""Build an index for a MAF genome alig file and return StringIO of it."""
idx_strm = StringIO.StringIO()
bound_iter = functools.partial(genome_alignment_iterator,
reference_species=ref_spec)
hash_func = JustInTimeGenomeAlignmentBlock.build_... | [
"def",
"_build_index",
"(",
"maf_strm",
",",
"ref_spec",
")",
":",
"idx_strm",
"=",
"StringIO",
".",
"StringIO",
"(",
")",
"bound_iter",
"=",
"functools",
".",
"partial",
"(",
"genome_alignment_iterator",
",",
"reference_species",
"=",
"ref_spec",
")",
"hash_fun... | Build an index for a MAF genome alig file and return StringIO of it. | [
"Build",
"an",
"index",
"for",
"a",
"MAF",
"genome",
"alig",
"file",
"and",
"return",
"StringIO",
"of",
"it",
"."
] | python | train |
geelweb/geelweb-django-contactform | src/geelweb/django/contactform/views.py | https://github.com/geelweb/geelweb-django-contactform/blob/9c5934e0877f61c3ddeca48569836703e1d6344a/src/geelweb/django/contactform/views.py#L12-L29 | def contact(request):
"""Displays the contact form and sends the email"""
form = ContactForm(request.POST or None)
if form.is_valid():
subject = form.cleaned_data['subject']
message = form.cleaned_data['message']
sender = form.cleaned_data['sender']
cc_myself = form.cleaned_d... | [
"def",
"contact",
"(",
"request",
")",
":",
"form",
"=",
"ContactForm",
"(",
"request",
".",
"POST",
"or",
"None",
")",
"if",
"form",
".",
"is_valid",
"(",
")",
":",
"subject",
"=",
"form",
".",
"cleaned_data",
"[",
"'subject'",
"]",
"message",
"=",
... | Displays the contact form and sends the email | [
"Displays",
"the",
"contact",
"form",
"and",
"sends",
"the",
"email"
] | python | valid |
mrahnis/drapery | drapery/cli/drape.py | https://github.com/mrahnis/drapery/blob/c0c0906fb5ff846cf591cb9fe8a9eaee68e8820c/drapery/cli/drape.py#L21-L67 | def cli(source_f, raster_f, output, verbose):
"""
Converts 2D geometries to 3D using GEOS sample through fiona.
\b
Example:
drape point.shp elevation.tif -o point_z.shp
"""
with fiona.open(source_f, 'r') as source:
source_driver = source.driver
source_crs = source.crs
... | [
"def",
"cli",
"(",
"source_f",
",",
"raster_f",
",",
"output",
",",
"verbose",
")",
":",
"with",
"fiona",
".",
"open",
"(",
"source_f",
",",
"'r'",
")",
"as",
"source",
":",
"source_driver",
"=",
"source",
".",
"driver",
"source_crs",
"=",
"source",
".... | Converts 2D geometries to 3D using GEOS sample through fiona.
\b
Example:
drape point.shp elevation.tif -o point_z.shp | [
"Converts",
"2D",
"geometries",
"to",
"3D",
"using",
"GEOS",
"sample",
"through",
"fiona",
"."
] | python | train |
zomux/deepy | deepy/networks/network.py | https://github.com/zomux/deepy/blob/090fbad22a08a809b12951cd0d4984f5bd432698/deepy/networks/network.py#L166-L179 | def setup_variables(self):
"""
Set up variables.
"""
if self.input_tensor:
if type(self.input_tensor) == int:
x = dim_to_var(self.input_tensor, name="x")
else:
x = self.input_tensor
else:
x = T.matrix('x')
... | [
"def",
"setup_variables",
"(",
"self",
")",
":",
"if",
"self",
".",
"input_tensor",
":",
"if",
"type",
"(",
"self",
".",
"input_tensor",
")",
"==",
"int",
":",
"x",
"=",
"dim_to_var",
"(",
"self",
".",
"input_tensor",
",",
"name",
"=",
"\"x\"",
")",
... | Set up variables. | [
"Set",
"up",
"variables",
"."
] | python | test |
Fizzadar/pydocs | pydocs/__init__.py | https://github.com/Fizzadar/pydocs/blob/72713201dc4cf40335f9c3d380c9111b23c2c38b/pydocs/__init__.py#L16-L26 | def _parse_module_list(module_list):
'''Loop through all the modules and parse them.'''
for module_meta in module_list:
name = module_meta['module']
# Import & parse module
module = import_module(name)
output = parse_module(module)
# Assign to meta.content
modul... | [
"def",
"_parse_module_list",
"(",
"module_list",
")",
":",
"for",
"module_meta",
"in",
"module_list",
":",
"name",
"=",
"module_meta",
"[",
"'module'",
"]",
"# Import & parse module",
"module",
"=",
"import_module",
"(",
"name",
")",
"output",
"=",
"parse_module",... | Loop through all the modules and parse them. | [
"Loop",
"through",
"all",
"the",
"modules",
"and",
"parse",
"them",
"."
] | python | train |
openstack/quark | quark/drivers/ironic_driver.py | https://github.com/openstack/quark/blob/1112e6a66917d3e98e44cb7b33b107fd5a74bb2e/quark/drivers/ironic_driver.py#L290-L367 | def create_port(self, context, network_id, port_id, **kwargs):
"""Create a port.
:param context: neutron api request context.
:param network_id: neutron network id.
:param port_id: neutron port id.
:param kwargs:
required keys - device_id: neutron port device_id (ins... | [
"def",
"create_port",
"(",
"self",
",",
"context",
",",
"network_id",
",",
"port_id",
",",
"*",
"*",
"kwargs",
")",
":",
"LOG",
".",
"info",
"(",
"\"create_port %s %s %s\"",
"%",
"(",
"context",
".",
"tenant_id",
",",
"network_id",
",",
"port_id",
")",
"... | Create a port.
:param context: neutron api request context.
:param network_id: neutron network id.
:param port_id: neutron port id.
:param kwargs:
required keys - device_id: neutron port device_id (instance_id)
instance_node_id: nova hypervisor ho... | [
"Create",
"a",
"port",
"."
] | python | valid |
secdev/scapy | scapy/automaton.py | https://github.com/secdev/scapy/blob/3ffe757c184017dd46464593a8f80f85abc1e79a/scapy/automaton.py#L129-L134 | def _timeout_thread(self, remain):
"""Timeout before releasing every thing, if nothing was returned"""
time.sleep(remain)
if not self._ended:
self._ended = True
self._release_all() | [
"def",
"_timeout_thread",
"(",
"self",
",",
"remain",
")",
":",
"time",
".",
"sleep",
"(",
"remain",
")",
"if",
"not",
"self",
".",
"_ended",
":",
"self",
".",
"_ended",
"=",
"True",
"self",
".",
"_release_all",
"(",
")"
] | Timeout before releasing every thing, if nothing was returned | [
"Timeout",
"before",
"releasing",
"every",
"thing",
"if",
"nothing",
"was",
"returned"
] | python | train |
PyCQA/astroid | astroid/brain/brain_builtin_inference.py | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/brain/brain_builtin_inference.py#L121-L147 | def register_builtin_transform(transform, builtin_name):
"""Register a new transform function for the given *builtin_name*.
The transform function must accept two parameters, a node and
an optional context.
"""
def _transform_wrapper(node, context=None):
result = transform(node, context=co... | [
"def",
"register_builtin_transform",
"(",
"transform",
",",
"builtin_name",
")",
":",
"def",
"_transform_wrapper",
"(",
"node",
",",
"context",
"=",
"None",
")",
":",
"result",
"=",
"transform",
"(",
"node",
",",
"context",
"=",
"context",
")",
"if",
"result... | Register a new transform function for the given *builtin_name*.
The transform function must accept two parameters, a node and
an optional context. | [
"Register",
"a",
"new",
"transform",
"function",
"for",
"the",
"given",
"*",
"builtin_name",
"*",
"."
] | python | train |
Phyks/libbmc | libbmc/doi.py | https://github.com/Phyks/libbmc/blob/9ef1a29d2514157d1edd6c13ecbd61b07ae9315e/libbmc/doi.py#L188-L209 | def get_bibtex(doi):
"""
Get a BibTeX entry for a given DOI.
.. note::
Adapted from https://gist.github.com/jrsmith3/5513926.
:param doi: The canonical DOI to get BibTeX from.
:returns: A BibTeX string or ``None``.
>>> get_bibtex('10.1209/0295-5075/111/40005')
'@article{Verney_20... | [
"def",
"get_bibtex",
"(",
"doi",
")",
":",
"try",
":",
"request",
"=",
"requests",
".",
"get",
"(",
"to_url",
"(",
"doi",
")",
",",
"headers",
"=",
"{",
"\"accept\"",
":",
"\"application/x-bibtex\"",
"}",
")",
"request",
".",
"raise_for_status",
"(",
")"... | Get a BibTeX entry for a given DOI.
.. note::
Adapted from https://gist.github.com/jrsmith3/5513926.
:param doi: The canonical DOI to get BibTeX from.
:returns: A BibTeX string or ``None``.
>>> get_bibtex('10.1209/0295-5075/111/40005')
'@article{Verney_2015,\\n\\tdoi = {10.1209/0295-5075... | [
"Get",
"a",
"BibTeX",
"entry",
"for",
"a",
"given",
"DOI",
"."
] | python | train |
decryptus/sonicprobe | sonicprobe/libs/pworkerpool.py | https://github.com/decryptus/sonicprobe/blob/72f73f3a40d2982d79ad68686e36aa31d94b76f8/sonicprobe/libs/pworkerpool.py#L170-L178 | def set_max_workers(self, nb):
"""
Set the maximum workers to create.
"""
self.count_lock.acquire()
self.shared['max_workers'] = nb
if self.shared['workers'] > self.shared['max_workers']:
self.kill(self.shared['workers'] - self.shared['max_workers'])
s... | [
"def",
"set_max_workers",
"(",
"self",
",",
"nb",
")",
":",
"self",
".",
"count_lock",
".",
"acquire",
"(",
")",
"self",
".",
"shared",
"[",
"'max_workers'",
"]",
"=",
"nb",
"if",
"self",
".",
"shared",
"[",
"'workers'",
"]",
">",
"self",
".",
"share... | Set the maximum workers to create. | [
"Set",
"the",
"maximum",
"workers",
"to",
"create",
"."
] | python | train |
geomet/geomet | geomet/wkt.py | https://github.com/geomet/geomet/blob/b82d7118113ab723751eba3de5df98c368423c2b/geomet/wkt.py#L57-L100 | def dumps(obj, decimals=16):
"""
Dump a GeoJSON-like `dict` to a WKT string.
"""
try:
geom_type = obj['type']
exporter = _dumps_registry.get(geom_type)
if exporter is None:
_unsupported_geom_type(geom_type)
# Check for empty cases
if geom_type == 'Ge... | [
"def",
"dumps",
"(",
"obj",
",",
"decimals",
"=",
"16",
")",
":",
"try",
":",
"geom_type",
"=",
"obj",
"[",
"'type'",
"]",
"exporter",
"=",
"_dumps_registry",
".",
"get",
"(",
"geom_type",
")",
"if",
"exporter",
"is",
"None",
":",
"_unsupported_geom_type... | Dump a GeoJSON-like `dict` to a WKT string. | [
"Dump",
"a",
"GeoJSON",
"-",
"like",
"dict",
"to",
"a",
"WKT",
"string",
"."
] | python | train |
quantopian/pyfolio | pyfolio/perf_attrib.py | https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/perf_attrib.py#L419-L468 | def plot_factor_contribution_to_perf(
perf_attrib_data,
ax=None,
title='Cumulative common returns attribution',
):
"""
Plot each factor's contribution to performance.
Parameters
----------
perf_attrib_data : pd.DataFrame
df with factors, common returns, and specific ... | [
"def",
"plot_factor_contribution_to_perf",
"(",
"perf_attrib_data",
",",
"ax",
"=",
"None",
",",
"title",
"=",
"'Cumulative common returns attribution'",
",",
")",
":",
"if",
"ax",
"is",
"None",
":",
"ax",
"=",
"plt",
".",
"gca",
"(",
")",
"factors_to_plot",
"... | Plot each factor's contribution to performance.
Parameters
----------
perf_attrib_data : pd.DataFrame
df with factors, common returns, and specific returns as columns,
and datetimes as index
- Example:
momentum reversal common_returns specific_returns
... | [
"Plot",
"each",
"factor",
"s",
"contribution",
"to",
"performance",
"."
] | python | valid |
Stewori/pytypes | pytypes/typechecker.py | https://github.com/Stewori/pytypes/blob/b814d38709e84c0e0825caf8b721c20eb5a8ab3b/pytypes/typechecker.py#L1167-L1172 | def check_argument_types(cllable = None, call_args = None, clss = None, caller_level = 0):
"""Can be called from within a function or method to apply typechecking to
the arguments that were passed in by the caller. Checking is applied w.r.t.
type hints of the function or method hosting the call to check_arg... | [
"def",
"check_argument_types",
"(",
"cllable",
"=",
"None",
",",
"call_args",
"=",
"None",
",",
"clss",
"=",
"None",
",",
"caller_level",
"=",
"0",
")",
":",
"return",
"_check_caller_type",
"(",
"False",
",",
"cllable",
",",
"call_args",
",",
"clss",
",",
... | Can be called from within a function or method to apply typechecking to
the arguments that were passed in by the caller. Checking is applied w.r.t.
type hints of the function or method hosting the call to check_argument_types. | [
"Can",
"be",
"called",
"from",
"within",
"a",
"function",
"or",
"method",
"to",
"apply",
"typechecking",
"to",
"the",
"arguments",
"that",
"were",
"passed",
"in",
"by",
"the",
"caller",
".",
"Checking",
"is",
"applied",
"w",
".",
"r",
".",
"t",
".",
"t... | python | train |
gabrielelanaro/chemview | chemview/viewer.py | https://github.com/gabrielelanaro/chemview/blob/2c9768dd23db99e59e27adff2a953bb8ee795fa3/chemview/viewer.py#L312-L335 | def cartoon(self, cmap=None):
'''Display a protein secondary structure as a pymol-like cartoon representation.
:param cmap: is a dictionary that maps the secondary type
(H=helix, E=sheet, C=coil) to a hexadecimal color (0xffffff for white)
'''
# Parse secondary struc... | [
"def",
"cartoon",
"(",
"self",
",",
"cmap",
"=",
"None",
")",
":",
"# Parse secondary structure",
"top",
"=",
"self",
".",
"topology",
"geom",
"=",
"gg",
".",
"GeomProteinCartoon",
"(",
"gg",
".",
"Aes",
"(",
"xyz",
"=",
"self",
".",
"coordinates",
",",
... | Display a protein secondary structure as a pymol-like cartoon representation.
:param cmap: is a dictionary that maps the secondary type
(H=helix, E=sheet, C=coil) to a hexadecimal color (0xffffff for white) | [
"Display",
"a",
"protein",
"secondary",
"structure",
"as",
"a",
"pymol",
"-",
"like",
"cartoon",
"representation",
"."
] | python | train |
mitsei/dlkit | dlkit/json_/grading/managers.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/grading/managers.py#L1718-L1735 | def get_gradebook_hierarchy_design_session(self, proxy):
"""Gets the session designing gradebook hierarchies.
arg: proxy (osid.proxy.Proxy): a proxy
return: (osid.grading.GradebookHierarchyDesignSession) - a
``GradebookHierarchyDesignSession``
raise: NullArgument - `... | [
"def",
"get_gradebook_hierarchy_design_session",
"(",
"self",
",",
"proxy",
")",
":",
"if",
"not",
"self",
".",
"supports_gradebook_hierarchy_design",
"(",
")",
":",
"raise",
"errors",
".",
"Unimplemented",
"(",
")",
"# pylint: disable=no-member",
"return",
"sessions"... | Gets the session designing gradebook hierarchies.
arg: proxy (osid.proxy.Proxy): a proxy
return: (osid.grading.GradebookHierarchyDesignSession) - a
``GradebookHierarchyDesignSession``
raise: NullArgument - ``proxy`` is ``null``
raise: OperationFailed - unable to com... | [
"Gets",
"the",
"session",
"designing",
"gradebook",
"hierarchies",
"."
] | python | train |
rigetti/grove | grove/measurements/estimation.py | https://github.com/rigetti/grove/blob/dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3/grove/measurements/estimation.py#L37-L55 | def get_rotation_program(pauli_term: PauliTerm) -> Program:
"""
Generate a rotation program so that the pauli term is diagonal.
:param pauli_term: The Pauli term used to generate diagonalizing one-qubit rotations.
:return: The rotation program.
"""
meas_basis_change = Program()
for index, g... | [
"def",
"get_rotation_program",
"(",
"pauli_term",
":",
"PauliTerm",
")",
"->",
"Program",
":",
"meas_basis_change",
"=",
"Program",
"(",
")",
"for",
"index",
",",
"gate",
"in",
"pauli_term",
":",
"if",
"gate",
"==",
"'X'",
":",
"meas_basis_change",
".",
"ins... | Generate a rotation program so that the pauli term is diagonal.
:param pauli_term: The Pauli term used to generate diagonalizing one-qubit rotations.
:return: The rotation program. | [
"Generate",
"a",
"rotation",
"program",
"so",
"that",
"the",
"pauli",
"term",
"is",
"diagonal",
"."
] | python | train |
ioos/compliance-checker | compliance_checker/acdd.py | https://github.com/ioos/compliance-checker/blob/ee89c27b0daade58812489a2da3aa3b6859eafd9/compliance_checker/acdd.py#L566-L582 | def verify_convention_version(self, ds):
"""
Verify that the version in the Conventions field is correct
"""
try:
for convention in getattr(ds, "Conventions", '').replace(' ', '').split(','):
if convention == 'ACDD-' + self._cc_spec_version:
... | [
"def",
"verify_convention_version",
"(",
"self",
",",
"ds",
")",
":",
"try",
":",
"for",
"convention",
"in",
"getattr",
"(",
"ds",
",",
"\"Conventions\"",
",",
"''",
")",
".",
"replace",
"(",
"' '",
",",
"''",
")",
".",
"split",
"(",
"','",
")",
":",... | Verify that the version in the Conventions field is correct | [
"Verify",
"that",
"the",
"version",
"in",
"the",
"Conventions",
"field",
"is",
"correct"
] | python | train |
mitsei/dlkit | dlkit/json_/commenting/sessions.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/commenting/sessions.py#L2654-L2681 | def get_book_nodes(self, book_id, ancestor_levels, descendant_levels, include_siblings):
"""Gets a portion of the hierarchy for the given book.
arg: book_id (osid.id.Id): the ``Id`` to query
arg: ancestor_levels (cardinal): the maximum number of
ancestor levels to include.... | [
"def",
"get_book_nodes",
"(",
"self",
",",
"book_id",
",",
"ancestor_levels",
",",
"descendant_levels",
",",
"include_siblings",
")",
":",
"# Implemented from template for",
"# osid.resource.BinHierarchySession.get_bin_nodes",
"return",
"objects",
".",
"BookNode",
"(",
"sel... | Gets a portion of the hierarchy for the given book.
arg: book_id (osid.id.Id): the ``Id`` to query
arg: ancestor_levels (cardinal): the maximum number of
ancestor levels to include. A value of 0 returns no
parents in the node.
arg: descendant_levels (car... | [
"Gets",
"a",
"portion",
"of",
"the",
"hierarchy",
"for",
"the",
"given",
"book",
"."
] | python | train |
joshspeagle/dynesty | dynesty/nestedsamplers.py | https://github.com/joshspeagle/dynesty/blob/9e482aafeb5cf84bedb896fa6f07a761d917983e/dynesty/nestedsamplers.py#L346-L362 | def update(self, pointvol):
"""Update the bounding ellipsoid using the current set of
live points."""
# Check if we should use the provided pool for updating.
if self.use_pool_update:
pool = self.pool
else:
pool = None
# Update the ellipsoid.
... | [
"def",
"update",
"(",
"self",
",",
"pointvol",
")",
":",
"# Check if we should use the provided pool for updating.",
"if",
"self",
".",
"use_pool_update",
":",
"pool",
"=",
"self",
".",
"pool",
"else",
":",
"pool",
"=",
"None",
"# Update the ellipsoid.",
"self",
"... | Update the bounding ellipsoid using the current set of
live points. | [
"Update",
"the",
"bounding",
"ellipsoid",
"using",
"the",
"current",
"set",
"of",
"live",
"points",
"."
] | python | train |
Cadene/pretrained-models.pytorch | pretrainedmodels/models/polynet.py | https://github.com/Cadene/pretrained-models.pytorch/blob/021d97897c9aa76ec759deff43d341c4fd45d7ba/pretrainedmodels/models/polynet.py#L461-L480 | def polynet(num_classes=1000, pretrained='imagenet'):
"""PolyNet architecture from the paper
'PolyNet: A Pursuit of Structural Diversity in Very Deep Networks'
https://arxiv.org/abs/1611.05725
"""
if pretrained:
settings = pretrained_settings['polynet'][pretrained]
assert num_classes... | [
"def",
"polynet",
"(",
"num_classes",
"=",
"1000",
",",
"pretrained",
"=",
"'imagenet'",
")",
":",
"if",
"pretrained",
":",
"settings",
"=",
"pretrained_settings",
"[",
"'polynet'",
"]",
"[",
"pretrained",
"]",
"assert",
"num_classes",
"==",
"settings",
"[",
... | PolyNet architecture from the paper
'PolyNet: A Pursuit of Structural Diversity in Very Deep Networks'
https://arxiv.org/abs/1611.05725 | [
"PolyNet",
"architecture",
"from",
"the",
"paper",
"PolyNet",
":",
"A",
"Pursuit",
"of",
"Structural",
"Diversity",
"in",
"Very",
"Deep",
"Networks",
"https",
":",
"//",
"arxiv",
".",
"org",
"/",
"abs",
"/",
"1611",
".",
"05725"
] | python | train |
inasafe/inasafe | safe/common/parameters/default_value_parameter_widget.py | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/common/parameters/default_value_parameter_widget.py#L77-L97 | def get_parameter(self):
"""Obtain list parameter object from the current widget state.
:returns: A DefaultValueParameter from the current state of widget
:rtype: DefaultValueParameter
"""
radio_button_checked_id = self.input_button_group.checkedId()
# No radio button ch... | [
"def",
"get_parameter",
"(",
"self",
")",
":",
"radio_button_checked_id",
"=",
"self",
".",
"input_button_group",
".",
"checkedId",
"(",
")",
"# No radio button checked, then default value = None",
"if",
"radio_button_checked_id",
"==",
"-",
"1",
":",
"self",
".",
"_p... | Obtain list parameter object from the current widget state.
:returns: A DefaultValueParameter from the current state of widget
:rtype: DefaultValueParameter | [
"Obtain",
"list",
"parameter",
"object",
"from",
"the",
"current",
"widget",
"state",
"."
] | python | train |
tomislater/RandomWords | random_words/random_words.py | https://github.com/tomislater/RandomWords/blob/601aa48732d3c389f4c17ba0ed98ffe0e4821d78/random_words/random_words.py#L48-L55 | def load_nicknames(self, file):
"""
Load dict from file for random nicknames.
:param str file: filename
"""
with open(os.path.join(main_dir, file + '.dat'), 'r') as f:
self.nicknames = json.load(f) | [
"def",
"load_nicknames",
"(",
"self",
",",
"file",
")",
":",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"main_dir",
",",
"file",
"+",
"'.dat'",
")",
",",
"'r'",
")",
"as",
"f",
":",
"self",
".",
"nicknames",
"=",
"json",
".",
"load... | Load dict from file for random nicknames.
:param str file: filename | [
"Load",
"dict",
"from",
"file",
"for",
"random",
"nicknames",
"."
] | python | train |
tensorflow/lucid | lucid/optvis/objectives.py | https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/optvis/objectives.py#L165-L170 | def channel(layer, n_channel, batch=None):
"""Visualize a single channel"""
if batch is None:
return lambda T: tf.reduce_mean(T(layer)[..., n_channel])
else:
return lambda T: tf.reduce_mean(T(layer)[batch, ..., n_channel]) | [
"def",
"channel",
"(",
"layer",
",",
"n_channel",
",",
"batch",
"=",
"None",
")",
":",
"if",
"batch",
"is",
"None",
":",
"return",
"lambda",
"T",
":",
"tf",
".",
"reduce_mean",
"(",
"T",
"(",
"layer",
")",
"[",
"...",
",",
"n_channel",
"]",
")",
... | Visualize a single channel | [
"Visualize",
"a",
"single",
"channel"
] | python | train |
kentwait/nxsim | nxsim/simulation.py | https://github.com/kentwait/nxsim/blob/88090d8099e574bc6fd1d24734cfa205ecce4c1d/nxsim/simulation.py#L57-L85 | def run_trial(self, trial_id=0):
"""Run a single trial of the simulation
Parameters
----------
trial_id : int
"""
# Set-up trial environment and graph
self.env = NetworkEnvironment(self.G.copy(), initial_time=0, **self.environment_params)
# self.G = self.... | [
"def",
"run_trial",
"(",
"self",
",",
"trial_id",
"=",
"0",
")",
":",
"# Set-up trial environment and graph",
"self",
".",
"env",
"=",
"NetworkEnvironment",
"(",
"self",
".",
"G",
".",
"copy",
"(",
")",
",",
"initial_time",
"=",
"0",
",",
"*",
"*",
"self... | Run a single trial of the simulation
Parameters
----------
trial_id : int | [
"Run",
"a",
"single",
"trial",
"of",
"the",
"simulation"
] | python | train |
bitesofcode/projexui | projexui/widgets/xviewwidget/xviewprofiletoolbar.py | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xviewwidget/xviewprofiletoolbar.py#L329-L339 | def profiles(self):
"""
Returns a list of profiles for this toolbar.
:return <projexui.widgets.xviewwidget.XViewProfile>
"""
output = []
for act in self.actions():
if ( isinstance(act, XViewProfileAction) ):
output.append(... | [
"def",
"profiles",
"(",
"self",
")",
":",
"output",
"=",
"[",
"]",
"for",
"act",
"in",
"self",
".",
"actions",
"(",
")",
":",
"if",
"(",
"isinstance",
"(",
"act",
",",
"XViewProfileAction",
")",
")",
":",
"output",
".",
"append",
"(",
"act",
".",
... | Returns a list of profiles for this toolbar.
:return <projexui.widgets.xviewwidget.XViewProfile> | [
"Returns",
"a",
"list",
"of",
"profiles",
"for",
"this",
"toolbar",
".",
":",
"return",
"<projexui",
".",
"widgets",
".",
"xviewwidget",
".",
"XViewProfile",
">"
] | python | train |
jazzband/django-model-utils | model_utils/tracker.py | https://github.com/jazzband/django-model-utils/blob/d557c4253312774a7c2f14bcd02675e9ac2ea05f/model_utils/tracker.py#L270-L277 | def has_changed(self, field):
"""Returns ``True`` if field has changed from currently saved value"""
if not self.instance.pk:
return True
elif field in self.saved_data:
return self.previous(field) != self.get_field_value(field)
else:
raise FieldError('... | [
"def",
"has_changed",
"(",
"self",
",",
"field",
")",
":",
"if",
"not",
"self",
".",
"instance",
".",
"pk",
":",
"return",
"True",
"elif",
"field",
"in",
"self",
".",
"saved_data",
":",
"return",
"self",
".",
"previous",
"(",
"field",
")",
"!=",
"sel... | Returns ``True`` if field has changed from currently saved value | [
"Returns",
"True",
"if",
"field",
"has",
"changed",
"from",
"currently",
"saved",
"value"
] | python | train |
mlperf/training | image_classification/tensorflow/official/resnet/resnet_run_loop.py | https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/image_classification/tensorflow/official/resnet/resnet_run_loop.py#L130-L218 | def learning_rate_with_decay(
batch_size, batch_denom, num_images, boundary_epochs, decay_rates,
base_lr=0.1, enable_lars=False):
"""Get a learning rate that decays step-wise as training progresses.
Args:
batch_size: the number of examples processed in each training batch.
batch_denom: this value w... | [
"def",
"learning_rate_with_decay",
"(",
"batch_size",
",",
"batch_denom",
",",
"num_images",
",",
"boundary_epochs",
",",
"decay_rates",
",",
"base_lr",
"=",
"0.1",
",",
"enable_lars",
"=",
"False",
")",
":",
"initial_learning_rate",
"=",
"base_lr",
"*",
"batch_si... | Get a learning rate that decays step-wise as training progresses.
Args:
batch_size: the number of examples processed in each training batch.
batch_denom: this value will be used to scale the base learning rate.
`0.1 * batch size` is divided by this number, such that when
batch_denom == batch_size... | [
"Get",
"a",
"learning",
"rate",
"that",
"decays",
"step",
"-",
"wise",
"as",
"training",
"progresses",
"."
] | python | train |
matthiask/django-cte-forest | cte_forest/query.py | https://github.com/matthiask/django-cte-forest/blob/7bff29d69eddfcf214e9cf61647c91d28655619c/cte_forest/query.py#L227-L246 | def get_compiler(self, using=None, connection=None):
""" Overrides the Query method get_compiler in order to return
an instance of the above custom compiler.
"""
# Copy the body of this method from Django except the final
# return statement. We will ignore code coverage for t... | [
"def",
"get_compiler",
"(",
"self",
",",
"using",
"=",
"None",
",",
"connection",
"=",
"None",
")",
":",
"# Copy the body of this method from Django except the final",
"# return statement. We will ignore code coverage for this.",
"if",
"using",
"is",
"None",
"and",
"connect... | Overrides the Query method get_compiler in order to return
an instance of the above custom compiler. | [
"Overrides",
"the",
"Query",
"method",
"get_compiler",
"in",
"order",
"to",
"return",
"an",
"instance",
"of",
"the",
"above",
"custom",
"compiler",
"."
] | python | train |
pyGrowler/Growler | growler/http/response.py | https://github.com/pyGrowler/Growler/blob/90c923ff204f28b86a01d741224987a22f69540f/growler/http/response.py#L377-L396 | def stringify(self, use_bytes=False):
"""
Returns representation of headers as a valid HTTP header string. This
is called by __str__.
Args:
use_bytes (bool): Returns a bytes object instead of a str.
"""
def _str_value(value):
if isinstance(value, ... | [
"def",
"stringify",
"(",
"self",
",",
"use_bytes",
"=",
"False",
")",
":",
"def",
"_str_value",
"(",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"value",
"=",
"(",
"self",
".",
"EOL",
"+",
"... | Returns representation of headers as a valid HTTP header string. This
is called by __str__.
Args:
use_bytes (bool): Returns a bytes object instead of a str. | [
"Returns",
"representation",
"of",
"headers",
"as",
"a",
"valid",
"HTTP",
"header",
"string",
".",
"This",
"is",
"called",
"by",
"__str__",
"."
] | python | train |
wglass/lighthouse | lighthouse/log/cli.py | https://github.com/wglass/lighthouse/blob/f4ce6550895acc31e433ede0c05d366718a3ffe5/lighthouse/log/cli.py#L39-L57 | def create_thread_color_cycle():
"""
Generates a never-ending cycle of colors to choose from for individual
threads.
If color is not available, a cycle that repeats None every time is
returned instead.
"""
if not color_available:
return itertools.cycle([None])
return itertools.... | [
"def",
"create_thread_color_cycle",
"(",
")",
":",
"if",
"not",
"color_available",
":",
"return",
"itertools",
".",
"cycle",
"(",
"[",
"None",
"]",
")",
"return",
"itertools",
".",
"cycle",
"(",
"(",
"colorama",
".",
"Fore",
".",
"CYAN",
",",
"colorama",
... | Generates a never-ending cycle of colors to choose from for individual
threads.
If color is not available, a cycle that repeats None every time is
returned instead. | [
"Generates",
"a",
"never",
"-",
"ending",
"cycle",
"of",
"colors",
"to",
"choose",
"from",
"for",
"individual",
"threads",
"."
] | python | train |
requests/requests-oauthlib | requests_oauthlib/oauth2_session.py | https://github.com/requests/requests-oauthlib/blob/800976faab3b827a42fa1cb80f13fcc03961d2c9/requests_oauthlib/oauth2_session.py#L175-L363 | def fetch_token(
self,
token_url,
code=None,
authorization_response=None,
body="",
auth=None,
username=None,
password=None,
method="POST",
force_querystring=False,
timeout=None,
headers=None,
verify=True,
pro... | [
"def",
"fetch_token",
"(",
"self",
",",
"token_url",
",",
"code",
"=",
"None",
",",
"authorization_response",
"=",
"None",
",",
"body",
"=",
"\"\"",
",",
"auth",
"=",
"None",
",",
"username",
"=",
"None",
",",
"password",
"=",
"None",
",",
"method",
"=... | Generic method for fetching an access token from the token endpoint.
If you are using the MobileApplicationClient you will want to use
`token_from_fragment` instead of `fetch_token`.
The current implementation enforces the RFC guidelines.
:param token_url: Token endpoint URL, must use... | [
"Generic",
"method",
"for",
"fetching",
"an",
"access",
"token",
"from",
"the",
"token",
"endpoint",
"."
] | python | valid |
inveniosoftware/invenio-migrator | invenio_migrator/legacy/utils.py | https://github.com/inveniosoftware/invenio-migrator/blob/6902c6968a39b747d15e32363f43b7dffe2622c2/invenio_migrator/legacy/utils.py#L60-L68 | def init_app_context():
"""Initialize app context for Invenio 2.x."""
try:
from invenio.base.factory import create_app
app = create_app()
app.test_request_context('/').push()
app.preprocess_request()
except ImportError:
pass | [
"def",
"init_app_context",
"(",
")",
":",
"try",
":",
"from",
"invenio",
".",
"base",
".",
"factory",
"import",
"create_app",
"app",
"=",
"create_app",
"(",
")",
"app",
".",
"test_request_context",
"(",
"'/'",
")",
".",
"push",
"(",
")",
"app",
".",
"p... | Initialize app context for Invenio 2.x. | [
"Initialize",
"app",
"context",
"for",
"Invenio",
"2",
".",
"x",
"."
] | python | test |
standage/tag | tag/feature.py | https://github.com/standage/tag/blob/94686adf57115cea1c5235e99299e691f80ba10b/tag/feature.py#L468-L489 | def get_attribute(self, attrkey, as_string=False, as_list=False):
"""
Get the value of an attribute.
By default, returns a string for ID and attributes with a single value,
and a list of strings for attributes with multiple values. The
`as_string` and `as_list` options can be us... | [
"def",
"get_attribute",
"(",
"self",
",",
"attrkey",
",",
"as_string",
"=",
"False",
",",
"as_list",
"=",
"False",
")",
":",
"assert",
"not",
"as_string",
"or",
"not",
"as_list",
"if",
"attrkey",
"not",
"in",
"self",
".",
"_attrs",
":",
"return",
"None",... | Get the value of an attribute.
By default, returns a string for ID and attributes with a single value,
and a list of strings for attributes with multiple values. The
`as_string` and `as_list` options can be used to force the function to
return values as a string (comma-separated in case... | [
"Get",
"the",
"value",
"of",
"an",
"attribute",
"."
] | python | train |
thomasdelaet/python-velbus | velbus/controller.py | https://github.com/thomasdelaet/python-velbus/blob/af2f8af43f1a24bf854eff9f3126fd7b5c41b3dd/velbus/controller.py#L167-L173 | def sync_clock(self):
"""
This will send all the needed messages to sync the cloc
"""
self.send(velbus.SetRealtimeClock())
self.send(velbus.SetDate())
self.send(velbus.SetDaylightSaving()) | [
"def",
"sync_clock",
"(",
"self",
")",
":",
"self",
".",
"send",
"(",
"velbus",
".",
"SetRealtimeClock",
"(",
")",
")",
"self",
".",
"send",
"(",
"velbus",
".",
"SetDate",
"(",
")",
")",
"self",
".",
"send",
"(",
"velbus",
".",
"SetDaylightSaving",
"... | This will send all the needed messages to sync the cloc | [
"This",
"will",
"send",
"all",
"the",
"needed",
"messages",
"to",
"sync",
"the",
"cloc"
] | python | train |
sorgerlab/indra | indra/sources/biopax/processor.py | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/biopax/processor.py#L58-L69 | def save_model(self, file_name=None):
"""Save the BioPAX model object in an OWL file.
Parameters
----------
file_name : Optional[str]
The name of the OWL file to save the model in.
"""
if file_name is None:
logger.error('Missing file name')
... | [
"def",
"save_model",
"(",
"self",
",",
"file_name",
"=",
"None",
")",
":",
"if",
"file_name",
"is",
"None",
":",
"logger",
".",
"error",
"(",
"'Missing file name'",
")",
"return",
"pcc",
".",
"model_to_owl",
"(",
"self",
".",
"model",
",",
"file_name",
"... | Save the BioPAX model object in an OWL file.
Parameters
----------
file_name : Optional[str]
The name of the OWL file to save the model in. | [
"Save",
"the",
"BioPAX",
"model",
"object",
"in",
"an",
"OWL",
"file",
"."
] | python | train |
tgbugs/pyontutils | pyontutils/hierarchies.py | https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/pyontutils/hierarchies.py#L43-L45 | def tcsort(item): # FIXME SUCH WOW SO INEFFICIENT O_O
""" get len of transitive closure assume type items is tree... """
return len(item[1]) + sum(tcsort(kv) for kv in item[1].items()) | [
"def",
"tcsort",
"(",
"item",
")",
":",
"# FIXME SUCH WOW SO INEFFICIENT O_O",
"return",
"len",
"(",
"item",
"[",
"1",
"]",
")",
"+",
"sum",
"(",
"tcsort",
"(",
"kv",
")",
"for",
"kv",
"in",
"item",
"[",
"1",
"]",
".",
"items",
"(",
")",
")"
] | get len of transitive closure assume type items is tree... | [
"get",
"len",
"of",
"transitive",
"closure",
"assume",
"type",
"items",
"is",
"tree",
"..."
] | python | train |
manjitkumar/drf-url-filters | filters/validations.py | https://github.com/manjitkumar/drf-url-filters/blob/ebac358729bcd9aa70537247b2ccd6005f5678c1/filters/validations.py#L13-L32 | def IntegerLike(msg=None):
'''
Checks whether a value is:
- int, or
- long, or
- float without a fractional part, or
- str or unicode composed only of digits
'''
def fn(value):
if not any([
isinstance(value, numbers.Integral),
(isinstance(v... | [
"def",
"IntegerLike",
"(",
"msg",
"=",
"None",
")",
":",
"def",
"fn",
"(",
"value",
")",
":",
"if",
"not",
"any",
"(",
"[",
"isinstance",
"(",
"value",
",",
"numbers",
".",
"Integral",
")",
",",
"(",
"isinstance",
"(",
"value",
",",
"float",
")",
... | Checks whether a value is:
- int, or
- long, or
- float without a fractional part, or
- str or unicode composed only of digits | [
"Checks",
"whether",
"a",
"value",
"is",
":",
"-",
"int",
"or",
"-",
"long",
"or",
"-",
"float",
"without",
"a",
"fractional",
"part",
"or",
"-",
"str",
"or",
"unicode",
"composed",
"only",
"of",
"digits"
] | python | train |
varikin/Tigre | tigre/tigre.py | https://github.com/varikin/Tigre/blob/6ffac1de52f087cf92cbf368997b336c35a0e3c0/tigre/tigre.py#L87-L106 | def sync_folder(self, path, bucket):
"""Syncs a local directory with an S3 bucket.
Currently does not delete files from S3 that are not in the local directory.
path: The path to the directory to sync to S3
bucket: The name of the bucket on S3
"""
bucket = self.conn... | [
"def",
"sync_folder",
"(",
"self",
",",
"path",
",",
"bucket",
")",
":",
"bucket",
"=",
"self",
".",
"conn",
".",
"get_bucket",
"(",
"bucket",
")",
"local_files",
"=",
"self",
".",
"_get_local_files",
"(",
"path",
")",
"s3_files",
"=",
"self",
".",
"_g... | Syncs a local directory with an S3 bucket.
Currently does not delete files from S3 that are not in the local directory.
path: The path to the directory to sync to S3
bucket: The name of the bucket on S3 | [
"Syncs",
"a",
"local",
"directory",
"with",
"an",
"S3",
"bucket",
".",
"Currently",
"does",
"not",
"delete",
"files",
"from",
"S3",
"that",
"are",
"not",
"in",
"the",
"local",
"directory",
"."
] | python | test |
The-Politico/politico-civic-geography | geography/models/division.py | https://github.com/The-Politico/politico-civic-geography/blob/032b3ee773b50b65cfe672f230dda772df0f89e0/geography/models/division.py#L70-L82 | def save(self, *args, **kwargs):
"""
**uid**: :code:`division:{parentuid}_{levelcode}-{code}`
"""
slug = "{}:{}".format(self.level.uid, self.code)
if self.parent:
self.uid = "{}_{}".format(self.parent.uid, slug)
else:
self.uid = slug
self.s... | [
"def",
"save",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"slug",
"=",
"\"{}:{}\"",
".",
"format",
"(",
"self",
".",
"level",
".",
"uid",
",",
"self",
".",
"code",
")",
"if",
"self",
".",
"parent",
":",
"self",
".",
"uid"... | **uid**: :code:`division:{parentuid}_{levelcode}-{code}` | [
"**",
"uid",
"**",
":",
":",
"code",
":",
"division",
":",
"{",
"parentuid",
"}",
"_",
"{",
"levelcode",
"}",
"-",
"{",
"code",
"}"
] | python | train |
dade-ai/snipy | snipy/io/fileutil.py | https://github.com/dade-ai/snipy/blob/408520867179f99b3158b57520e2619f3fecd69b/snipy/io/fileutil.py#L261-L268 | def listfolder(p):
"""
generator of list folder in the path.
folders only
"""
for entry in scandir.scandir(p):
if entry.is_dir():
yield entry.name | [
"def",
"listfolder",
"(",
"p",
")",
":",
"for",
"entry",
"in",
"scandir",
".",
"scandir",
"(",
"p",
")",
":",
"if",
"entry",
".",
"is_dir",
"(",
")",
":",
"yield",
"entry",
".",
"name"
] | generator of list folder in the path.
folders only | [
"generator",
"of",
"list",
"folder",
"in",
"the",
"path",
".",
"folders",
"only"
] | python | valid |
gplepage/gvar | examples/pendulum-clock.py | https://github.com/gplepage/gvar/blob/d6671697319eb6280de3793c9a1c2b616c6f2ae0/examples/pendulum-clock.py#L46-L56 | def find_period(y, Tapprox):
""" Find oscillation period of y(t).
Parameter Tapprox is the approximate period. The code finds the time
between 0.7 * Tapprox and 1.3 * Tapprox where y(t)[1] = d/dt theta(t)
vanishes. This is the period.
"""
def dtheta_dt(t):
""" vanishes when dtheta/dt = ... | [
"def",
"find_period",
"(",
"y",
",",
"Tapprox",
")",
":",
"def",
"dtheta_dt",
"(",
"t",
")",
":",
"\"\"\" vanishes when dtheta/dt = 0 \"\"\"",
"return",
"y",
"(",
"t",
")",
"[",
"1",
"]",
"return",
"gv",
".",
"root",
".",
"refine",
"(",
"dtheta_dt",
",",... | Find oscillation period of y(t).
Parameter Tapprox is the approximate period. The code finds the time
between 0.7 * Tapprox and 1.3 * Tapprox where y(t)[1] = d/dt theta(t)
vanishes. This is the period. | [
"Find",
"oscillation",
"period",
"of",
"y",
"(",
"t",
")",
"."
] | python | train |
materialsproject/pymatgen | pymatgen/io/abinit/flows.py | https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/io/abinit/flows.py#L633-L646 | def iflat_tasks_wti(self, status=None, op="==", nids=None):
"""
Generator to iterate over all the tasks of the `Flow`.
Yields:
(task, work_index, task_index)
If status is not None, only the tasks whose status satisfies
the condition (task.status op status) are selec... | [
"def",
"iflat_tasks_wti",
"(",
"self",
",",
"status",
"=",
"None",
",",
"op",
"=",
"\"==\"",
",",
"nids",
"=",
"None",
")",
":",
"return",
"self",
".",
"_iflat_tasks_wti",
"(",
"status",
"=",
"status",
",",
"op",
"=",
"op",
",",
"nids",
"=",
"nids",
... | Generator to iterate over all the tasks of the `Flow`.
Yields:
(task, work_index, task_index)
If status is not None, only the tasks whose status satisfies
the condition (task.status op status) are selected
status can be either one of the flags defined in the :class:`Task` c... | [
"Generator",
"to",
"iterate",
"over",
"all",
"the",
"tasks",
"of",
"the",
"Flow",
".",
"Yields",
":"
] | python | train |
T-002/pycast | pycast/common/matrix.py | https://github.com/T-002/pycast/blob/8a53505c6d8367e0ea572e8af768e80b29e1cc41/pycast/common/matrix.py#L236-L251 | def to_multi_dim_timeseries(self):
"""Return a TimeSeries with the values of :py:obj:`self`
The index of the row is used for the timestamp
:return: Return a new MultiDimensionalTimeSeries with the values
of the Matrix
:rtype: MultiDimensionalTimeSeries
... | [
"def",
"to_multi_dim_timeseries",
"(",
"self",
")",
":",
"ts",
"=",
"MultiDimensionalTimeSeries",
"(",
"dimensions",
"=",
"self",
".",
"get_width",
"(",
")",
")",
"for",
"row",
"in",
"xrange",
"(",
"self",
".",
"get_height",
"(",
")",
")",
":",
"newEntry",... | Return a TimeSeries with the values of :py:obj:`self`
The index of the row is used for the timestamp
:return: Return a new MultiDimensionalTimeSeries with the values
of the Matrix
:rtype: MultiDimensionalTimeSeries | [
"Return",
"a",
"TimeSeries",
"with",
"the",
"values",
"of",
":",
"py",
":",
"obj",
":",
"self"
] | python | train |
romanz/trezor-agent | libagent/gpg/keyring.py | https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/gpg/keyring.py#L243-L249 | def export_public_keys(env=None, sp=subprocess):
"""Export all GPG public keys."""
args = gpg_command(['--export'])
result = check_output(args=args, env=env, sp=sp)
if not result:
raise KeyError('No GPG public keys found at env: {!r}'.format(env))
return result | [
"def",
"export_public_keys",
"(",
"env",
"=",
"None",
",",
"sp",
"=",
"subprocess",
")",
":",
"args",
"=",
"gpg_command",
"(",
"[",
"'--export'",
"]",
")",
"result",
"=",
"check_output",
"(",
"args",
"=",
"args",
",",
"env",
"=",
"env",
",",
"sp",
"=... | Export all GPG public keys. | [
"Export",
"all",
"GPG",
"public",
"keys",
"."
] | python | train |
PiotrDabkowski/Js2Py | js2py/base.py | https://github.com/PiotrDabkowski/Js2Py/blob/c0fa43f5679cf91ca8986c5747fcb07a433dc584/js2py/base.py#L357-L427 | def put(self, prop, val, op=None): #external use!
'''Just like in js: self.prop op= val
for example when op is '+' it will be self.prop+=val
op can be either None for simple assignment or one of:
* / % + - << >> & ^ |'''
if self.Class == 'Undefined' or self.Class == 'Nu... | [
"def",
"put",
"(",
"self",
",",
"prop",
",",
"val",
",",
"op",
"=",
"None",
")",
":",
"#external use!",
"if",
"self",
".",
"Class",
"==",
"'Undefined'",
"or",
"self",
".",
"Class",
"==",
"'Null'",
":",
"raise",
"MakeError",
"(",
"'TypeError'",
",",
"... | Just like in js: self.prop op= val
for example when op is '+' it will be self.prop+=val
op can be either None for simple assignment or one of:
* / % + - << >> & ^ | | [
"Just",
"like",
"in",
"js",
":",
"self",
".",
"prop",
"op",
"=",
"val",
"for",
"example",
"when",
"op",
"is",
"+",
"it",
"will",
"be",
"self",
".",
"prop",
"+",
"=",
"val",
"op",
"can",
"be",
"either",
"None",
"for",
"simple",
"assignment",
"or",
... | python | valid |
apple/turicreate | src/unity/python/turicreate/toolkits/regression/linear_regression.py | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/regression/linear_regression.py#L519-L564 | def predict(self, dataset, missing_value_action='auto'):
"""
Return target value predictions for ``dataset``, using the trained
linear regression model. This method can be used to get fitted values
for the model by inputting the training dataset.
Parameters
----------
... | [
"def",
"predict",
"(",
"self",
",",
"dataset",
",",
"missing_value_action",
"=",
"'auto'",
")",
":",
"return",
"super",
"(",
"LinearRegression",
",",
"self",
")",
".",
"predict",
"(",
"dataset",
",",
"missing_value_action",
"=",
"missing_value_action",
")"
] | Return target value predictions for ``dataset``, using the trained
linear regression model. This method can be used to get fitted values
for the model by inputting the training dataset.
Parameters
----------
dataset : SFrame | pandas.Dataframe
Dataset of new observat... | [
"Return",
"target",
"value",
"predictions",
"for",
"dataset",
"using",
"the",
"trained",
"linear",
"regression",
"model",
".",
"This",
"method",
"can",
"be",
"used",
"to",
"get",
"fitted",
"values",
"for",
"the",
"model",
"by",
"inputting",
"the",
"training",
... | python | train |
inasafe/inasafe | safe/utilities/metadata.py | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/utilities/metadata.py#L183-L247 | def read_iso19115_metadata(layer_uri, keyword=None, version_35=False):
"""Retrieve keywords from a metadata object
:param layer_uri: Uri to layer.
:type layer_uri: basestring
:param keyword: The key of keyword that want to be read. If None, return
all keywords in dictionary.
:type keyword:... | [
"def",
"read_iso19115_metadata",
"(",
"layer_uri",
",",
"keyword",
"=",
"None",
",",
"version_35",
"=",
"False",
")",
":",
"xml_uri",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"layer_uri",
")",
"[",
"0",
"]",
"+",
"'.xml'",
"# Remove the prefix for local... | Retrieve keywords from a metadata object
:param layer_uri: Uri to layer.
:type layer_uri: basestring
:param keyword: The key of keyword that want to be read. If None, return
all keywords in dictionary.
:type keyword: basestring
:returns: Dictionary of keywords or value of key as string.
... | [
"Retrieve",
"keywords",
"from",
"a",
"metadata",
"object"
] | python | train |
open-mmlab/mmcv | mmcv/image/transforms/geometry.py | https://github.com/open-mmlab/mmcv/blob/0d77f61450aab4dde8b8585a577cc496acb95d7f/mmcv/image/transforms/geometry.py#L112-L163 | def imcrop(img, bboxes, scale=1.0, pad_fill=None):
"""Crop image patches.
3 steps: scale the bboxes -> clip bboxes -> crop and pad.
Args:
img (ndarray): Image to be cropped.
bboxes (ndarray): Shape (k, 4) or (4, ), location of cropped bboxes.
scale (float, optional): Scale ratio of... | [
"def",
"imcrop",
"(",
"img",
",",
"bboxes",
",",
"scale",
"=",
"1.0",
",",
"pad_fill",
"=",
"None",
")",
":",
"chn",
"=",
"1",
"if",
"img",
".",
"ndim",
"==",
"2",
"else",
"img",
".",
"shape",
"[",
"2",
"]",
"if",
"pad_fill",
"is",
"not",
"None... | Crop image patches.
3 steps: scale the bboxes -> clip bboxes -> crop and pad.
Args:
img (ndarray): Image to be cropped.
bboxes (ndarray): Shape (k, 4) or (4, ), location of cropped bboxes.
scale (float, optional): Scale ratio of bboxes, the default value
1.0 means no paddin... | [
"Crop",
"image",
"patches",
"."
] | python | test |
iterative/dvc | dvc/utils/__init__.py | https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/utils/__init__.py#L83-L105 | def dict_filter(d, exclude=[]):
"""
Exclude specified keys from a nested dict
"""
if isinstance(d, list):
ret = []
for e in d:
ret.append(dict_filter(e, exclude))
return ret
elif isinstance(d, dict):
ret = {}
for k, v in d.items():
if ... | [
"def",
"dict_filter",
"(",
"d",
",",
"exclude",
"=",
"[",
"]",
")",
":",
"if",
"isinstance",
"(",
"d",
",",
"list",
")",
":",
"ret",
"=",
"[",
"]",
"for",
"e",
"in",
"d",
":",
"ret",
".",
"append",
"(",
"dict_filter",
"(",
"e",
",",
"exclude",
... | Exclude specified keys from a nested dict | [
"Exclude",
"specified",
"keys",
"from",
"a",
"nested",
"dict"
] | python | train |
cloud9ers/gurumate | environment/lib/python2.7/site-packages/IPython/core/inputsplitter.py | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/inputsplitter.py#L338-L391 | def push(self, lines):
"""Push one or more lines of input.
This stores the given lines and returns a status code indicating
whether the code forms a complete Python block or not.
Any exceptions generated in compilation are swallowed, but if an
exception was produced, the method... | [
"def",
"push",
"(",
"self",
",",
"lines",
")",
":",
"if",
"self",
".",
"input_mode",
"==",
"'cell'",
":",
"self",
".",
"reset",
"(",
")",
"self",
".",
"_store",
"(",
"lines",
")",
"source",
"=",
"self",
".",
"source",
"# Before calling _compile(), reset ... | Push one or more lines of input.
This stores the given lines and returns a status code indicating
whether the code forms a complete Python block or not.
Any exceptions generated in compilation are swallowed, but if an
exception was produced, the method returns True.
Parameters... | [
"Push",
"one",
"or",
"more",
"lines",
"of",
"input",
"."
] | python | test |
dhylands/rshell | rshell/main.py | https://github.com/dhylands/rshell/blob/a92a8fa8074ac792241c83c640a51b394667c324/rshell/main.py#L1080-L1109 | def send_file_to_host(src_filename, dst_file, filesize):
"""Function which runs on the pyboard. Matches up with recv_file_from_remote."""
import sys
import ubinascii
try:
with open(src_filename, 'rb') as src_file:
bytes_remaining = filesize
if HAS_BUFFER:
... | [
"def",
"send_file_to_host",
"(",
"src_filename",
",",
"dst_file",
",",
"filesize",
")",
":",
"import",
"sys",
"import",
"ubinascii",
"try",
":",
"with",
"open",
"(",
"src_filename",
",",
"'rb'",
")",
"as",
"src_file",
":",
"bytes_remaining",
"=",
"filesize",
... | Function which runs on the pyboard. Matches up with recv_file_from_remote. | [
"Function",
"which",
"runs",
"on",
"the",
"pyboard",
".",
"Matches",
"up",
"with",
"recv_file_from_remote",
"."
] | python | train |
un33k/django-toolware | toolware/templatetags/rounder.py | https://github.com/un33k/django-toolware/blob/973f3e003dc38b812897dab88455bee37dcaf931/toolware/templatetags/rounder.py#L10-L34 | def roundplus(number):
"""
given an number, this fuction rounds the number as the following examples:
87 -> 87, 100 -> 100+, 188 -> 100+, 999 -> 900+, 1001 -> 1000+, ...etc
"""
num = str(number)
if not num.isdigit():
return num
num = str(number)
digits = len(num)
rounded = '... | [
"def",
"roundplus",
"(",
"number",
")",
":",
"num",
"=",
"str",
"(",
"number",
")",
"if",
"not",
"num",
".",
"isdigit",
"(",
")",
":",
"return",
"num",
"num",
"=",
"str",
"(",
"number",
")",
"digits",
"=",
"len",
"(",
"num",
")",
"rounded",
"=",
... | given an number, this fuction rounds the number as the following examples:
87 -> 87, 100 -> 100+, 188 -> 100+, 999 -> 900+, 1001 -> 1000+, ...etc | [
"given",
"an",
"number",
"this",
"fuction",
"rounds",
"the",
"number",
"as",
"the",
"following",
"examples",
":",
"87",
"-",
">",
"87",
"100",
"-",
">",
"100",
"+",
"188",
"-",
">",
"100",
"+",
"999",
"-",
">",
"900",
"+",
"1001",
"-",
">",
"1000... | python | test |
sirfoga/pyhal | hal/cvs/gits.py | https://github.com/sirfoga/pyhal/blob/4394d8a1f7e45bea28a255ec390f4962ee64d33a/hal/cvs/gits.py#L135-L147 | def get_version(self, diff_to_increase_ratio):
"""Gets version
:param diff_to_increase_ratio: Ratio to convert number of changes into
:return: Version of this code, based on commits diffs
"""
diffs = self.get_diff_amounts()
version = Version()
for diff in diffs:... | [
"def",
"get_version",
"(",
"self",
",",
"diff_to_increase_ratio",
")",
":",
"diffs",
"=",
"self",
".",
"get_diff_amounts",
"(",
")",
"version",
"=",
"Version",
"(",
")",
"for",
"diff",
"in",
"diffs",
":",
"version",
".",
"increase_by_changes",
"(",
"diff",
... | Gets version
:param diff_to_increase_ratio: Ratio to convert number of changes into
:return: Version of this code, based on commits diffs | [
"Gets",
"version"
] | python | train |
llllllllll/codetransformer | codetransformer/decompiler/_343.py | https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/decompiler/_343.py#L1344-L1352 | def _binop_handler(nodetype):
"""
Factory function for binary operator handlers.
"""
def _handler(toplevel, stack_builders):
right = make_expr(stack_builders)
left = make_expr(stack_builders)
return ast.BinOp(left=left, op=nodetype(), right=right)
return _handler | [
"def",
"_binop_handler",
"(",
"nodetype",
")",
":",
"def",
"_handler",
"(",
"toplevel",
",",
"stack_builders",
")",
":",
"right",
"=",
"make_expr",
"(",
"stack_builders",
")",
"left",
"=",
"make_expr",
"(",
"stack_builders",
")",
"return",
"ast",
".",
"BinOp... | Factory function for binary operator handlers. | [
"Factory",
"function",
"for",
"binary",
"operator",
"handlers",
"."
] | python | train |
spacetelescope/stsci.tools | lib/stsci/tools/convertlog.py | https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/convertlog.py#L53-L112 | def convert(input, width=132, output=None, keep=False):
"""Input ASCII trailer file "input" will be read.
The contents will then be written out to a FITS file in the same format
as used by 'stwfits' from IRAF.
Parameters
===========
input : str
Filename of input ASCII trailer file
... | [
"def",
"convert",
"(",
"input",
",",
"width",
"=",
"132",
",",
"output",
"=",
"None",
",",
"keep",
"=",
"False",
")",
":",
"# open input trailer file",
"trl",
"=",
"open",
"(",
"input",
")",
"# process all lines",
"lines",
"=",
"np",
".",
"array",
"(",
... | Input ASCII trailer file "input" will be read.
The contents will then be written out to a FITS file in the same format
as used by 'stwfits' from IRAF.
Parameters
===========
input : str
Filename of input ASCII trailer file
width : int
Number of characters wide to use for defin... | [
"Input",
"ASCII",
"trailer",
"file",
"input",
"will",
"be",
"read",
"."
] | python | train |
crodjer/paster | paster/services.py | https://github.com/crodjer/paster/blob/0cd7230074850ba74e80c740a8bc2502645dd743/paster/services.py#L63-L74 | def list_syntax(self):
'''
Prints a list of available syntax for the current paste service
'''
syntax_list = ['Available syntax for %s:' %(self)]
logging.info(syntax_list[0])
for key in self.SYNTAX_DICT.keys():
syntax = '\t%-20s%-30s' %(key, self.SYNTAX_DICT[k... | [
"def",
"list_syntax",
"(",
"self",
")",
":",
"syntax_list",
"=",
"[",
"'Available syntax for %s:'",
"%",
"(",
"self",
")",
"]",
"logging",
".",
"info",
"(",
"syntax_list",
"[",
"0",
"]",
")",
"for",
"key",
"in",
"self",
".",
"SYNTAX_DICT",
".",
"keys",
... | Prints a list of available syntax for the current paste service | [
"Prints",
"a",
"list",
"of",
"available",
"syntax",
"for",
"the",
"current",
"paste",
"service"
] | python | train |
OSSOS/MOP | src/ossos/core/ossos/parsers.py | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/parsers.py#L23-L41 | def ossos_release_parser(table=False, data_release=parameters.RELEASE_VERSION):
"""
extra fun as this is space-separated so using CSV parsers is not an option
"""
names = ['cl', 'p', 'j', 'k', 'sh', 'object', 'mag', 'e_mag', 'Filt', 'Hsur', 'dist', 'e_dist', 'Nobs',
'time', 'av_xres', 'av_y... | [
"def",
"ossos_release_parser",
"(",
"table",
"=",
"False",
",",
"data_release",
"=",
"parameters",
".",
"RELEASE_VERSION",
")",
":",
"names",
"=",
"[",
"'cl'",
",",
"'p'",
",",
"'j'",
",",
"'k'",
",",
"'sh'",
",",
"'object'",
",",
"'mag'",
",",
"'e_mag'"... | extra fun as this is space-separated so using CSV parsers is not an option | [
"extra",
"fun",
"as",
"this",
"is",
"space",
"-",
"separated",
"so",
"using",
"CSV",
"parsers",
"is",
"not",
"an",
"option"
] | python | train |
rbuffat/pyepw | pyepw/epw.py | https://github.com/rbuffat/pyepw/blob/373d4d3c8386c8d35789f086ac5f6018c2711745/pyepw/epw.py#L6011-L6039 | def relative_humidity(self, value=999):
"""Corresponds to IDD Field `relative_humidity`
Args:
value (int): value for IDD Field `relative_humidity`
value >= 0
value <= 110
Missing value: 999
if `value` is None it will not be che... | [
"def",
"relative_humidity",
"(",
"self",
",",
"value",
"=",
"999",
")",
":",
"if",
"value",
"is",
"not",
"None",
":",
"try",
":",
"value",
"=",
"int",
"(",
"value",
")",
"except",
"ValueError",
":",
"raise",
"ValueError",
"(",
"'value {} need to be of type... | Corresponds to IDD Field `relative_humidity`
Args:
value (int): value for IDD Field `relative_humidity`
value >= 0
value <= 110
Missing value: 999
if `value` is None it will not be checked against the
specification and ... | [
"Corresponds",
"to",
"IDD",
"Field",
"relative_humidity"
] | python | train |
PythonSanSebastian/docstamp | docstamp/qrcode.py | https://github.com/PythonSanSebastian/docstamp/blob/b43808f2e15351b0b2f0b7eade9c7ef319c9e646/docstamp/qrcode.py#L10-L41 | def save_into_qrcode(text, out_filepath, color='', box_size=10, pixel_size=1850):
""" Save `text` in a qrcode svg image file.
Parameters
----------
text: str
The string to be codified in the QR image.
out_filepath: str
Path to the output file
color: str
A RGB color exp... | [
"def",
"save_into_qrcode",
"(",
"text",
",",
"out_filepath",
",",
"color",
"=",
"''",
",",
"box_size",
"=",
"10",
",",
"pixel_size",
"=",
"1850",
")",
":",
"try",
":",
"qr",
"=",
"qrcode",
".",
"QRCode",
"(",
"version",
"=",
"1",
",",
"error_correction... | Save `text` in a qrcode svg image file.
Parameters
----------
text: str
The string to be codified in the QR image.
out_filepath: str
Path to the output file
color: str
A RGB color expressed in 6 hexadecimal values.
box_size: scalar
Size of the QR code boxes. | [
"Save",
"text",
"in",
"a",
"qrcode",
"svg",
"image",
"file",
"."
] | python | test |
renatopp/liac-arff | arff.py | https://github.com/renatopp/liac-arff/blob/6771f4cdd13d0eca74d3ebbaa6290297dd0a381d/arff.py#L968-L976 | def encode(self, obj):
'''Encodes a given object to an ARFF file.
:param obj: the object containing the ARFF information.
:return: the ARFF file as an unicode string.
'''
data = [row for row in self.iter_encode(obj)]
return u'\n'.join(data) | [
"def",
"encode",
"(",
"self",
",",
"obj",
")",
":",
"data",
"=",
"[",
"row",
"for",
"row",
"in",
"self",
".",
"iter_encode",
"(",
"obj",
")",
"]",
"return",
"u'\\n'",
".",
"join",
"(",
"data",
")"
] | Encodes a given object to an ARFF file.
:param obj: the object containing the ARFF information.
:return: the ARFF file as an unicode string. | [
"Encodes",
"a",
"given",
"object",
"to",
"an",
"ARFF",
"file",
"."
] | python | train |
rkhleics/wagtailmenus | wagtailmenus/models/mixins.py | https://github.com/rkhleics/wagtailmenus/blob/a41f240bed0d362e0d4dd4ef04a230f2b1827a93/wagtailmenus/models/mixins.py#L21-L56 | def _get_specified_sub_menu_template_name(self, level):
"""
Called by get_sub_menu_template(). Iterates through the various ways in
which developers can specify potential sub menu templates for a menu,
and returns the name of the most suitable template for the
``current_level``. ... | [
"def",
"_get_specified_sub_menu_template_name",
"(",
"self",
",",
"level",
")",
":",
"ideal_index",
"=",
"level",
"-",
"2",
"return",
"self",
".",
"_option_vals",
".",
"sub_menu_template_name",
"or",
"get_item_by_index_or_last_item",
"(",
"self",
".",
"_option_vals",
... | Called by get_sub_menu_template(). Iterates through the various ways in
which developers can specify potential sub menu templates for a menu,
and returns the name of the most suitable template for the
``current_level``. Values are checked in the following order:
1. The ``sub_menu_templ... | [
"Called",
"by",
"get_sub_menu_template",
"()",
".",
"Iterates",
"through",
"the",
"various",
"ways",
"in",
"which",
"developers",
"can",
"specify",
"potential",
"sub",
"menu",
"templates",
"for",
"a",
"menu",
"and",
"returns",
"the",
"name",
"of",
"the",
"most... | python | train |
gwastro/pycbc | pycbc/workflow/segment.py | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/workflow/segment.py#L1325-L1393 | def file_needs_generating(file_path, cp, tags=None):
"""
This job tests the file location and determines if the file should be
generated now or if an error should be raised. This uses the
generate_segment_files variable, global to this module, which is described
above and in the documentation.
... | [
"def",
"file_needs_generating",
"(",
"file_path",
",",
"cp",
",",
"tags",
"=",
"None",
")",
":",
"if",
"tags",
"is",
"None",
":",
"tags",
"=",
"[",
"]",
"if",
"cp",
".",
"has_option_tags",
"(",
"\"workflow-segments\"",
",",
"\"segments-generate-segment-files\"... | This job tests the file location and determines if the file should be
generated now or if an error should be raised. This uses the
generate_segment_files variable, global to this module, which is described
above and in the documentation.
Parameters
-----------
file_path : path
Location ... | [
"This",
"job",
"tests",
"the",
"file",
"location",
"and",
"determines",
"if",
"the",
"file",
"should",
"be",
"generated",
"now",
"or",
"if",
"an",
"error",
"should",
"be",
"raised",
".",
"This",
"uses",
"the",
"generate_segment_files",
"variable",
"global",
... | python | train |
mushkevych/scheduler | synergy/scheduler/tree.py | https://github.com/mushkevych/scheduler/blob/6740331360f49083c208085fb5a60ce80ebf418b/synergy/scheduler/tree.py#L78-L106 | def _get_next_child_node(self, parent):
"""
Iterates among children of the given parent and looks for a suitable node to process
In case given parent has no suitable nodes, a younger parent will be found
and the logic will be repeated for him
"""
children_keys... | [
"def",
"_get_next_child_node",
"(",
"self",
",",
"parent",
")",
":",
"children_keys",
"=",
"list",
"(",
"parent",
".",
"children",
")",
"sorted_keys",
"=",
"sorted",
"(",
"children_keys",
")",
"for",
"key",
"in",
"sorted_keys",
":",
"node",
"=",
"parent",
... | Iterates among children of the given parent and looks for a suitable node to process
In case given parent has no suitable nodes, a younger parent will be found
and the logic will be repeated for him | [
"Iterates",
"among",
"children",
"of",
"the",
"given",
"parent",
"and",
"looks",
"for",
"a",
"suitable",
"node",
"to",
"process",
"In",
"case",
"given",
"parent",
"has",
"no",
"suitable",
"nodes",
"a",
"younger",
"parent",
"will",
"be",
"found",
"and",
"th... | python | train |
adafruit/Adafruit_CircuitPython_OneWire | adafruit_onewire/bus.py | https://github.com/adafruit/Adafruit_CircuitPython_OneWire/blob/113ca99b9087f7031f0b46a963472ad106520f9b/adafruit_onewire/bus.py#L126-L141 | def write(self, buf, *, start=0, end=None):
"""
Write the bytes from ``buf`` to the device.
If ``start`` or ``end`` is provided, then the buffer will be sliced
as if ``buffer[start:end]``. This will not cause an allocation like
``buffer[start:end]`` will so it saves memory.
... | [
"def",
"write",
"(",
"self",
",",
"buf",
",",
"*",
",",
"start",
"=",
"0",
",",
"end",
"=",
"None",
")",
":",
"if",
"end",
"is",
"None",
":",
"end",
"=",
"len",
"(",
"buf",
")",
"for",
"i",
"in",
"range",
"(",
"start",
",",
"end",
")",
":",... | Write the bytes from ``buf`` to the device.
If ``start`` or ``end`` is provided, then the buffer will be sliced
as if ``buffer[start:end]``. This will not cause an allocation like
``buffer[start:end]`` will so it saves memory.
:param bytearray buf: buffer containing the bytes to write
... | [
"Write",
"the",
"bytes",
"from",
"buf",
"to",
"the",
"device",
"."
] | python | train |
dopefishh/pympi | pympi/Elan.py | https://github.com/dopefishh/pympi/blob/79c747cde45b5ba203ed93154d8c123ac9c3ef56/pympi/Elan.py#L436-L464 | def create_gaps_and_overlaps_tier(self, tier1, tier2, tier_name=None,
maxlen=-1, fast=False):
"""Create a tier with the gaps and overlaps of the annotations.
For types see :func:`get_gaps_and_overlaps`
:param str tier1: Name of the first tier.
:para... | [
"def",
"create_gaps_and_overlaps_tier",
"(",
"self",
",",
"tier1",
",",
"tier2",
",",
"tier_name",
"=",
"None",
",",
"maxlen",
"=",
"-",
"1",
",",
"fast",
"=",
"False",
")",
":",
"if",
"tier_name",
"is",
"None",
":",
"tier_name",
"=",
"'{}_{}_ftos'",
"."... | Create a tier with the gaps and overlaps of the annotations.
For types see :func:`get_gaps_and_overlaps`
:param str tier1: Name of the first tier.
:param str tier2: Name of the second tier.
:param str tier_name: Name of the new tier, if ``None`` the name will
... | [
"Create",
"a",
"tier",
"with",
"the",
"gaps",
"and",
"overlaps",
"of",
"the",
"annotations",
".",
"For",
"types",
"see",
":",
"func",
":",
"get_gaps_and_overlaps"
] | python | test |
cisco-sas/kitty | kitty/data/data_manager.py | https://github.com/cisco-sas/kitty/blob/cb0760989dcdfe079e43ac574d872d0b18953a32/kitty/data/data_manager.py#L290-L300 | def _create_table(self):
'''
create the current table if not exists
'''
self._cursor.execute('''
CREATE TABLE IF NOT EXISTS %(name)s ( %(fields)s )
''' % {
'name': self._name,
'fields': ','.join('%s %s' % (k, v) for (k, v) in self._fields)
... | [
"def",
"_create_table",
"(",
"self",
")",
":",
"self",
".",
"_cursor",
".",
"execute",
"(",
"'''\n CREATE TABLE IF NOT EXISTS %(name)s ( %(fields)s )\n '''",
"%",
"{",
"'name'",
":",
"self",
".",
"_name",
",",
"'fields'",
":",
"','",
".",
"join",
... | create the current table if not exists | [
"create",
"the",
"current",
"table",
"if",
"not",
"exists"
] | python | train |
GNS3/gns3-server | gns3server/controller/compute.py | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/compute.py#L376-L388 | def http_query(self, method, path, data=None, dont_connect=False, **kwargs):
"""
:param dont_connect: If true do not reconnect if not connected
"""
if not self._connected and not dont_connect:
if self._id == "vm" and not self._controller.gns3vm.running:
yield... | [
"def",
"http_query",
"(",
"self",
",",
"method",
",",
"path",
",",
"data",
"=",
"None",
",",
"dont_connect",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"self",
".",
"_connected",
"and",
"not",
"dont_connect",
":",
"if",
"self",
"."... | :param dont_connect: If true do not reconnect if not connected | [
":",
"param",
"dont_connect",
":",
"If",
"true",
"do",
"not",
"reconnect",
"if",
"not",
"connected"
] | python | train |
theelous3/asks | asks/request_object.py | https://github.com/theelous3/asks/blob/ea522ea971ecb031d488a6301dc2718516cadcd6/asks/request_object.py#L427-L460 | def _dict_to_query(data, params=True, base_query=False):
'''
Turns python dicts in to valid body-queries or queries for use directly
in the request url. Unlike the stdlib quote() and it's variations,
this also works on iterables like lists which are normally not valid.
The use o... | [
"def",
"_dict_to_query",
"(",
"data",
",",
"params",
"=",
"True",
",",
"base_query",
"=",
"False",
")",
":",
"query",
"=",
"[",
"]",
"for",
"k",
",",
"v",
"in",
"data",
".",
"items",
"(",
")",
":",
"if",
"v",
"is",
"None",
":",
"continue",
"if",
... | Turns python dicts in to valid body-queries or queries for use directly
in the request url. Unlike the stdlib quote() and it's variations,
this also works on iterables like lists which are normally not valid.
The use of lists in this manner is not a great idea unless
the server supports... | [
"Turns",
"python",
"dicts",
"in",
"to",
"valid",
"body",
"-",
"queries",
"or",
"queries",
"for",
"use",
"directly",
"in",
"the",
"request",
"url",
".",
"Unlike",
"the",
"stdlib",
"quote",
"()",
"and",
"it",
"s",
"variations",
"this",
"also",
"works",
"on... | python | train |
inasafe/inasafe | safe/definitions/utilities.py | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/definitions/utilities.py#L380-L393 | def all_default_fields():
"""Helper to retrieve all fields which has default value.
:returns: List of default fields.
:rtype: list
"""
default_fields = []
for item in dir(fields):
if not item.startswith("__"):
var = getattr(definitions, item)
if isinstance(var, d... | [
"def",
"all_default_fields",
"(",
")",
":",
"default_fields",
"=",
"[",
"]",
"for",
"item",
"in",
"dir",
"(",
"fields",
")",
":",
"if",
"not",
"item",
".",
"startswith",
"(",
"\"__\"",
")",
":",
"var",
"=",
"getattr",
"(",
"definitions",
",",
"item",
... | Helper to retrieve all fields which has default value.
:returns: List of default fields.
:rtype: list | [
"Helper",
"to",
"retrieve",
"all",
"fields",
"which",
"has",
"default",
"value",
"."
] | python | train |
berkerpeksag/astor | astor/node_util.py | https://github.com/berkerpeksag/astor/blob/d9e893eb49d9eb2e30779680f90cd632c30e0ba1/astor/node_util.py#L61-L92 | def dump_tree(node, name=None, initial_indent='', indentation=' ',
maxline=120, maxmerged=80,
# Runtime optimization
iter_node=iter_node, special=ast.AST,
list=list, isinstance=isinstance, type=type, len=len):
"""Dumps an AST or similar structure:
-... | [
"def",
"dump_tree",
"(",
"node",
",",
"name",
"=",
"None",
",",
"initial_indent",
"=",
"''",
",",
"indentation",
"=",
"' '",
",",
"maxline",
"=",
"120",
",",
"maxmerged",
"=",
"80",
",",
"# Runtime optimization",
"iter_node",
"=",
"iter_node",
",",
"spe... | Dumps an AST or similar structure:
- Pretty-prints with indentation
- Doesn't print line/column/ctx info | [
"Dumps",
"an",
"AST",
"or",
"similar",
"structure",
":"
] | python | train |
robdmc/behold | behold/logger.py | https://github.com/robdmc/behold/blob/ac1b7707e2d7472a50d837dda78be1e23af8fce5/behold/logger.py#L519-L528 | def is_true(self, item=None):
"""
If you are filtering on object values, you need to pass that object here.
"""
if item:
values = [item]
else:
values = []
self._get_item_and_att_names(*values)
return self._passes_all | [
"def",
"is_true",
"(",
"self",
",",
"item",
"=",
"None",
")",
":",
"if",
"item",
":",
"values",
"=",
"[",
"item",
"]",
"else",
":",
"values",
"=",
"[",
"]",
"self",
".",
"_get_item_and_att_names",
"(",
"*",
"values",
")",
"return",
"self",
".",
"_p... | If you are filtering on object values, you need to pass that object here. | [
"If",
"you",
"are",
"filtering",
"on",
"object",
"values",
"you",
"need",
"to",
"pass",
"that",
"object",
"here",
"."
] | python | train |
ansible/tower-cli | tower_cli/resources/role.py | https://github.com/ansible/tower-cli/blob/a2b151fed93c47725018d3034848cb3a1814bed7/tower_cli/resources/role.py#L203-L209 | def set_display_columns(self, set_true=[], set_false=[]):
"""Add or remove columns from the output."""
for i in range(len(self.fields)):
if self.fields[i].name in set_true:
self.fields[i].display = True
elif self.fields[i].name in set_false:
self.f... | [
"def",
"set_display_columns",
"(",
"self",
",",
"set_true",
"=",
"[",
"]",
",",
"set_false",
"=",
"[",
"]",
")",
":",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"fields",
")",
")",
":",
"if",
"self",
".",
"fields",
"[",
"i",
"]",
... | Add or remove columns from the output. | [
"Add",
"or",
"remove",
"columns",
"from",
"the",
"output",
"."
] | python | valid |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.