repository_name stringlengths 7 55 | func_path_in_repository stringlengths 4 223 | func_name stringlengths 1 134 | whole_func_string stringlengths 75 104k | language stringclasses 1
value | func_code_string stringlengths 75 104k | func_code_tokens listlengths 19 28.4k | func_documentation_string stringlengths 1 46.9k | func_documentation_tokens listlengths 1 1.97k | split_name stringclasses 1
value | func_code_url stringlengths 87 315 |
|---|---|---|---|---|---|---|---|---|---|---|
sanger-pathogens/pymummer | pymummer/nucmer.py | Runner.run | def run(self):
'''
Change to a temp directory
Run bash script containing commands
Place results in specified output file
Clean up temp directory
'''
qry = os.path.abspath(self.qry)
ref = os.path.abspath(self.ref)
outfile = os.path.abspath(self.outf... | python | def run(self):
'''
Change to a temp directory
Run bash script containing commands
Place results in specified output file
Clean up temp directory
'''
qry = os.path.abspath(self.qry)
ref = os.path.abspath(self.ref)
outfile = os.path.abspath(self.outf... | [
"def",
"run",
"(",
"self",
")",
":",
"qry",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"self",
".",
"qry",
")",
"ref",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"self",
".",
"ref",
")",
"outfile",
"=",
"os",
".",
"path",
".",
"abspath",
... | Change to a temp directory
Run bash script containing commands
Place results in specified output file
Clean up temp directory | [
"Change",
"to",
"a",
"temp",
"directory",
"Run",
"bash",
"script",
"containing",
"commands",
"Place",
"results",
"in",
"specified",
"output",
"file",
"Clean",
"up",
"temp",
"directory"
] | train | https://github.com/sanger-pathogens/pymummer/blob/fd97bccfbae62719a7247473d73dd6733d4fa903/pymummer/nucmer.py#L129-L146 |
sanger-pathogens/pymummer | pymummer/variant.py | Variant.update_indel | def update_indel(self, nucmer_snp):
'''Indels are reported over multiple lines, 1 base insertion or deletion per line. This method extends the current variant by 1 base if it's an indel and adjacent to the new SNP and returns True. If the current variant is a SNP, does nothing and returns False'''
new_v... | python | def update_indel(self, nucmer_snp):
'''Indels are reported over multiple lines, 1 base insertion or deletion per line. This method extends the current variant by 1 base if it's an indel and adjacent to the new SNP and returns True. If the current variant is a SNP, does nothing and returns False'''
new_v... | [
"def",
"update_indel",
"(",
"self",
",",
"nucmer_snp",
")",
":",
"new_variant",
"=",
"Variant",
"(",
"nucmer_snp",
")",
"if",
"self",
".",
"var_type",
"not",
"in",
"[",
"INS",
",",
"DEL",
"]",
"or",
"self",
".",
"var_type",
"!=",
"new_variant",
".",
"v... | Indels are reported over multiple lines, 1 base insertion or deletion per line. This method extends the current variant by 1 base if it's an indel and adjacent to the new SNP and returns True. If the current variant is a SNP, does nothing and returns False | [
"Indels",
"are",
"reported",
"over",
"multiple",
"lines",
"1",
"base",
"insertion",
"or",
"deletion",
"per",
"line",
".",
"This",
"method",
"extends",
"the",
"current",
"variant",
"by",
"1",
"base",
"if",
"it",
"s",
"an",
"indel",
"and",
"adjacent",
"to",
... | train | https://github.com/sanger-pathogens/pymummer/blob/fd97bccfbae62719a7247473d73dd6733d4fa903/pymummer/variant.py#L62-L84 |
sanger-pathogens/pymummer | pymummer/coords_file.py | reader | def reader(fname):
'''Helper function to open the results file (coords file) and create alignment objects with the values in it'''
f = pyfastaq.utils.open_file_read(fname)
for line in f:
if line.startswith('[') or (not '\t' in line):
continue
yield alignment.Alignment(line)
... | python | def reader(fname):
'''Helper function to open the results file (coords file) and create alignment objects with the values in it'''
f = pyfastaq.utils.open_file_read(fname)
for line in f:
if line.startswith('[') or (not '\t' in line):
continue
yield alignment.Alignment(line)
... | [
"def",
"reader",
"(",
"fname",
")",
":",
"f",
"=",
"pyfastaq",
".",
"utils",
".",
"open_file_read",
"(",
"fname",
")",
"for",
"line",
"in",
"f",
":",
"if",
"line",
".",
"startswith",
"(",
"'['",
")",
"or",
"(",
"not",
"'\\t'",
"in",
"line",
")",
... | Helper function to open the results file (coords file) and create alignment objects with the values in it | [
"Helper",
"function",
"to",
"open",
"the",
"results",
"file",
"(",
"coords",
"file",
")",
"and",
"create",
"alignment",
"objects",
"with",
"the",
"values",
"in",
"it"
] | train | https://github.com/sanger-pathogens/pymummer/blob/fd97bccfbae62719a7247473d73dd6733d4fa903/pymummer/coords_file.py#L6-L16 |
sanger-pathogens/pymummer | pymummer/coords_file.py | convert_to_msp_crunch | def convert_to_msp_crunch(infile, outfile, ref_fai=None, qry_fai=None):
'''Converts a coords file to a file in MSPcrunch format (for use with ACT, most likely).
ACT ignores sequence names in the crunch file, and just looks at the numbers.
To make a compatible file, the coords all must be shifted appro... | python | def convert_to_msp_crunch(infile, outfile, ref_fai=None, qry_fai=None):
'''Converts a coords file to a file in MSPcrunch format (for use with ACT, most likely).
ACT ignores sequence names in the crunch file, and just looks at the numbers.
To make a compatible file, the coords all must be shifted appro... | [
"def",
"convert_to_msp_crunch",
"(",
"infile",
",",
"outfile",
",",
"ref_fai",
"=",
"None",
",",
"qry_fai",
"=",
"None",
")",
":",
"fai_files",
"=",
"{",
"ref_fai",
",",
"qry_fai",
"}",
"if",
"None",
"in",
"fai_files",
"and",
"len",
"(",
"fai_files",
")"... | Converts a coords file to a file in MSPcrunch format (for use with ACT, most likely).
ACT ignores sequence names in the crunch file, and just looks at the numbers.
To make a compatible file, the coords all must be shifted appropriately, which
can be done by providing both the ref_fai and qry_fai op... | [
"Converts",
"a",
"coords",
"file",
"to",
"a",
"file",
"in",
"MSPcrunch",
"format",
"(",
"for",
"use",
"with",
"ACT",
"most",
"likely",
")",
".",
"ACT",
"ignores",
"sequence",
"names",
"in",
"the",
"crunch",
"file",
"and",
"just",
"looks",
"at",
"the",
... | train | https://github.com/sanger-pathogens/pymummer/blob/fd97bccfbae62719a7247473d73dd6733d4fa903/pymummer/coords_file.py#L19-L47 |
anandtiwarics/python-burp-rest-api | PyBurprestapi/burpscanner.py | BurpApi._request | def _request(self, method, url, params=None, headers=None, data=None):
"""Common handler for all the HTTP requests."""
if not params:
params = {}
# set default headers
if not headers:
headers = {
'accept': '*/*'
}
if method... | python | def _request(self, method, url, params=None, headers=None, data=None):
"""Common handler for all the HTTP requests."""
if not params:
params = {}
# set default headers
if not headers:
headers = {
'accept': '*/*'
}
if method... | [
"def",
"_request",
"(",
"self",
",",
"method",
",",
"url",
",",
"params",
"=",
"None",
",",
"headers",
"=",
"None",
",",
"data",
"=",
"None",
")",
":",
"if",
"not",
"params",
":",
"params",
"=",
"{",
"}",
"# set default headers",
"if",
"not",
"header... | Common handler for all the HTTP requests. | [
"Common",
"handler",
"for",
"all",
"the",
"HTTP",
"requests",
"."
] | train | https://github.com/anandtiwarics/python-burp-rest-api/blob/1b3fb263ef1d006e181b838ea017ac2abbd68a30/PyBurprestapi/burpscanner.py#L55-L98 |
sloria/sphinx-issues | sphinx_issues.py | user_role | def user_role(name, rawtext, text, lineno, inliner, options=None, content=None):
"""Sphinx role for linking to a user profile. Defaults to linking to
Github profiles, but the profile URIS can be configured via the
``issues_user_uri`` config value.
Examples: ::
:user:`sloria`
Anchor text a... | python | def user_role(name, rawtext, text, lineno, inliner, options=None, content=None):
"""Sphinx role for linking to a user profile. Defaults to linking to
Github profiles, but the profile URIS can be configured via the
``issues_user_uri`` config value.
Examples: ::
:user:`sloria`
Anchor text a... | [
"def",
"user_role",
"(",
"name",
",",
"rawtext",
",",
"text",
",",
"lineno",
",",
"inliner",
",",
"options",
"=",
"None",
",",
"content",
"=",
"None",
")",
":",
"options",
"=",
"options",
"or",
"{",
"}",
"content",
"=",
"content",
"or",
"[",
"]",
"... | Sphinx role for linking to a user profile. Defaults to linking to
Github profiles, but the profile URIS can be configured via the
``issues_user_uri`` config value.
Examples: ::
:user:`sloria`
Anchor text also works: ::
:user:`Steven Loria <sloria>` | [
"Sphinx",
"role",
"for",
"linking",
"to",
"a",
"user",
"profile",
".",
"Defaults",
"to",
"linking",
"to",
"Github",
"profiles",
"but",
"the",
"profile",
"URIS",
"can",
"be",
"configured",
"via",
"the",
"issues_user_uri",
"config",
"value",
"."
] | train | https://github.com/sloria/sphinx-issues/blob/0a9597472645dc728c2aef12e0653aabfdb68ab2/sphinx_issues.py#L13-L43 |
sloria/sphinx-issues | sphinx_issues.py | cve_role | def cve_role(name, rawtext, text, lineno, inliner, options=None, content=None):
"""Sphinx role for linking to a CVE on https://cve.mitre.org.
Examples: ::
:cve:`CVE-2018-17175`
"""
options = options or {}
content = content or []
has_explicit_title, title, target = split_explicit_title... | python | def cve_role(name, rawtext, text, lineno, inliner, options=None, content=None):
"""Sphinx role for linking to a CVE on https://cve.mitre.org.
Examples: ::
:cve:`CVE-2018-17175`
"""
options = options or {}
content = content or []
has_explicit_title, title, target = split_explicit_title... | [
"def",
"cve_role",
"(",
"name",
",",
"rawtext",
",",
"text",
",",
"lineno",
",",
"inliner",
",",
"options",
"=",
"None",
",",
"content",
"=",
"None",
")",
":",
"options",
"=",
"options",
"or",
"{",
"}",
"content",
"=",
"content",
"or",
"[",
"]",
"h... | Sphinx role for linking to a CVE on https://cve.mitre.org.
Examples: ::
:cve:`CVE-2018-17175` | [
"Sphinx",
"role",
"for",
"linking",
"to",
"a",
"CVE",
"on",
"https",
":",
"//",
"cve",
".",
"mitre",
".",
"org",
"."
] | train | https://github.com/sloria/sphinx-issues/blob/0a9597472645dc728c2aef12e0653aabfdb68ab2/sphinx_issues.py#L46-L63 |
adamnovak/tsv | tsv.py | TsvWriter.list_line | def list_line(self, line):
"""
Write the given iterable of values (line) to the file as items on the
same line. Any argument that stringifies to a string legal as a TSV data
item can be written.
Does not copy the line or build a big string in memory.
"""
... | python | def list_line(self, line):
"""
Write the given iterable of values (line) to the file as items on the
same line. Any argument that stringifies to a string legal as a TSV data
item can be written.
Does not copy the line or build a big string in memory.
"""
... | [
"def",
"list_line",
"(",
"self",
",",
"line",
")",
":",
"if",
"len",
"(",
"line",
")",
"==",
"0",
":",
"return",
"self",
".",
"stream",
".",
"write",
"(",
"str",
"(",
"line",
"[",
"0",
"]",
")",
")",
"for",
"item",
"in",
"line",
"[",
"1",
":"... | Write the given iterable of values (line) to the file as items on the
same line. Any argument that stringifies to a string legal as a TSV data
item can be written.
Does not copy the line or build a big string in memory. | [
"Write",
"the",
"given",
"iterable",
"of",
"values",
"(",
"line",
")",
"to",
"the",
"file",
"as",
"items",
"on",
"the",
"same",
"line",
".",
"Any",
"argument",
"that",
"stringifies",
"to",
"a",
"string",
"legal",
"as",
"a",
"TSV",
"data",
"item",
"can"... | train | https://github.com/adamnovak/tsv/blob/379189e9da4c1b65d0587bb32f3b51e6a7c936c8/tsv.py#L42-L60 |
michaelstepner/pandoc-mustache | pandoc_mustache/pandoc_mustache.py | prepare | def prepare(doc):
""" Parse metadata to obtain list of mustache templates,
then load those templates.
"""
doc.mustache_files = doc.get_metadata('mustache')
if isinstance(doc.mustache_files, basestring): # process single YAML value stored as string
if not doc.mustache_files:
... | python | def prepare(doc):
""" Parse metadata to obtain list of mustache templates,
then load those templates.
"""
doc.mustache_files = doc.get_metadata('mustache')
if isinstance(doc.mustache_files, basestring): # process single YAML value stored as string
if not doc.mustache_files:
... | [
"def",
"prepare",
"(",
"doc",
")",
":",
"doc",
".",
"mustache_files",
"=",
"doc",
".",
"get_metadata",
"(",
"'mustache'",
")",
"if",
"isinstance",
"(",
"doc",
".",
"mustache_files",
",",
"basestring",
")",
":",
"# process single YAML value stored as string",
"if... | Parse metadata to obtain list of mustache templates,
then load those templates. | [
"Parse",
"metadata",
"to",
"obtain",
"list",
"of",
"mustache",
"templates",
"then",
"load",
"those",
"templates",
"."
] | train | https://github.com/michaelstepner/pandoc-mustache/blob/52d71190d134964596e7f8e109564452e916b3fc/pandoc_mustache/pandoc_mustache.py#L8-L26 |
michaelstepner/pandoc-mustache | pandoc_mustache/pandoc_mustache.py | action | def action(elem, doc):
""" Apply combined mustache template to all strings in document.
"""
if type(elem) == Str and doc.mhash is not None:
elem.text = doc.mrenderer.render(elem.text, doc.mhash)
return elem | python | def action(elem, doc):
""" Apply combined mustache template to all strings in document.
"""
if type(elem) == Str and doc.mhash is not None:
elem.text = doc.mrenderer.render(elem.text, doc.mhash)
return elem | [
"def",
"action",
"(",
"elem",
",",
"doc",
")",
":",
"if",
"type",
"(",
"elem",
")",
"==",
"Str",
"and",
"doc",
".",
"mhash",
"is",
"not",
"None",
":",
"elem",
".",
"text",
"=",
"doc",
".",
"mrenderer",
".",
"render",
"(",
"elem",
".",
"text",
"... | Apply combined mustache template to all strings in document. | [
"Apply",
"combined",
"mustache",
"template",
"to",
"all",
"strings",
"in",
"document",
"."
] | train | https://github.com/michaelstepner/pandoc-mustache/blob/52d71190d134964596e7f8e109564452e916b3fc/pandoc_mustache/pandoc_mustache.py#L28-L33 |
jpadilla/django-rest-framework-jsonp | rest_framework_jsonp/renderers.py | JSONPRenderer.get_callback | def get_callback(self, renderer_context):
"""
Determine the name of the callback to wrap around the json output.
"""
request = renderer_context.get('request', None)
params = request and get_query_params(request) or {}
return params.get(self.callback_parameter, self.defaul... | python | def get_callback(self, renderer_context):
"""
Determine the name of the callback to wrap around the json output.
"""
request = renderer_context.get('request', None)
params = request and get_query_params(request) or {}
return params.get(self.callback_parameter, self.defaul... | [
"def",
"get_callback",
"(",
"self",
",",
"renderer_context",
")",
":",
"request",
"=",
"renderer_context",
".",
"get",
"(",
"'request'",
",",
"None",
")",
"params",
"=",
"request",
"and",
"get_query_params",
"(",
"request",
")",
"or",
"{",
"}",
"return",
"... | Determine the name of the callback to wrap around the json output. | [
"Determine",
"the",
"name",
"of",
"the",
"callback",
"to",
"wrap",
"around",
"the",
"json",
"output",
"."
] | train | https://github.com/jpadilla/django-rest-framework-jsonp/blob/64e91d451206a815b98d4b4a4e27e705104ad06e/rest_framework_jsonp/renderers.py#L23-L29 |
jpadilla/django-rest-framework-jsonp | rest_framework_jsonp/renderers.py | JSONPRenderer.render | def render(self, data, accepted_media_type=None, renderer_context=None):
"""
Renders into jsonp, wrapping the json output in a callback function.
Clients may set the callback function name using a query parameter
on the URL, for example: ?callback=exampleCallbackName
"""
... | python | def render(self, data, accepted_media_type=None, renderer_context=None):
"""
Renders into jsonp, wrapping the json output in a callback function.
Clients may set the callback function name using a query parameter
on the URL, for example: ?callback=exampleCallbackName
"""
... | [
"def",
"render",
"(",
"self",
",",
"data",
",",
"accepted_media_type",
"=",
"None",
",",
"renderer_context",
"=",
"None",
")",
":",
"renderer_context",
"=",
"renderer_context",
"or",
"{",
"}",
"callback",
"=",
"self",
".",
"get_callback",
"(",
"renderer_contex... | Renders into jsonp, wrapping the json output in a callback function.
Clients may set the callback function name using a query parameter
on the URL, for example: ?callback=exampleCallbackName | [
"Renders",
"into",
"jsonp",
"wrapping",
"the",
"json",
"output",
"in",
"a",
"callback",
"function",
"."
] | train | https://github.com/jpadilla/django-rest-framework-jsonp/blob/64e91d451206a815b98d4b4a4e27e705104ad06e/rest_framework_jsonp/renderers.py#L31-L42 |
3ll3d00d/vibe | backend/src/analyser/resources/timeseries.py | TimeSeries.get | def get(self, measurementId):
"""
Analyses the measurement with the given parameters
:param measurementId:
:return:
"""
logger.info('Loading raw data for ' + measurementId)
measurement = self._measurementController.getMeasurement(measurementId, MeasurementStatus.C... | python | def get(self, measurementId):
"""
Analyses the measurement with the given parameters
:param measurementId:
:return:
"""
logger.info('Loading raw data for ' + measurementId)
measurement = self._measurementController.getMeasurement(measurementId, MeasurementStatus.C... | [
"def",
"get",
"(",
"self",
",",
"measurementId",
")",
":",
"logger",
".",
"info",
"(",
"'Loading raw data for '",
"+",
"measurementId",
")",
"measurement",
"=",
"self",
".",
"_measurementController",
".",
"getMeasurement",
"(",
"measurementId",
",",
"MeasurementSt... | Analyses the measurement with the given parameters
:param measurementId:
:return: | [
"Analyses",
"the",
"measurement",
"with",
"the",
"given",
"parameters",
":",
"param",
"measurementId",
":",
":",
"return",
":"
] | train | https://github.com/3ll3d00d/vibe/blob/124b029f13ac746723e92cb47e9cb56edd2e54b5/backend/src/analyser/resources/timeseries.py#L13-L47 |
fitnr/convertdate | convertdate/iso.py | to_jd | def to_jd(year, week, day):
'''Return Julian day count of given ISO year, week, and day'''
return day + n_weeks(SUN, gregorian.to_jd(year - 1, 12, 28), week) | python | def to_jd(year, week, day):
'''Return Julian day count of given ISO year, week, and day'''
return day + n_weeks(SUN, gregorian.to_jd(year - 1, 12, 28), week) | [
"def",
"to_jd",
"(",
"year",
",",
"week",
",",
"day",
")",
":",
"return",
"day",
"+",
"n_weeks",
"(",
"SUN",
",",
"gregorian",
".",
"to_jd",
"(",
"year",
"-",
"1",
",",
"12",
",",
"28",
")",
",",
"week",
")"
] | Return Julian day count of given ISO year, week, and day | [
"Return",
"Julian",
"day",
"count",
"of",
"given",
"ISO",
"year",
"week",
"and",
"day"
] | train | https://github.com/fitnr/convertdate/blob/e920f168a87f99183b0aa7290d6c3af222582d43/convertdate/iso.py#L24-L26 |
fitnr/convertdate | convertdate/iso.py | from_jd | def from_jd(jd):
'''Return tuple of ISO (year, week, day) for Julian day'''
year = gregorian.from_jd(jd)[0]
day = jwday(jd) + 1
dayofyear = ordinal.from_jd(jd)[1]
week = trunc((dayofyear - day + 10) / 7)
# Reset year
if week < 1:
week = weeks_per_year(year - 1)
year = year ... | python | def from_jd(jd):
'''Return tuple of ISO (year, week, day) for Julian day'''
year = gregorian.from_jd(jd)[0]
day = jwday(jd) + 1
dayofyear = ordinal.from_jd(jd)[1]
week = trunc((dayofyear - day + 10) / 7)
# Reset year
if week < 1:
week = weeks_per_year(year - 1)
year = year ... | [
"def",
"from_jd",
"(",
"jd",
")",
":",
"year",
"=",
"gregorian",
".",
"from_jd",
"(",
"jd",
")",
"[",
"0",
"]",
"day",
"=",
"jwday",
"(",
"jd",
")",
"+",
"1",
"dayofyear",
"=",
"ordinal",
".",
"from_jd",
"(",
"jd",
")",
"[",
"1",
"]",
"week",
... | Return tuple of ISO (year, week, day) for Julian day | [
"Return",
"tuple",
"of",
"ISO",
"(",
"year",
"week",
"day",
")",
"for",
"Julian",
"day"
] | train | https://github.com/fitnr/convertdate/blob/e920f168a87f99183b0aa7290d6c3af222582d43/convertdate/iso.py#L29-L47 |
fitnr/convertdate | convertdate/iso.py | weeks_per_year | def weeks_per_year(year):
'''Number of ISO weeks in a year'''
# 53 weeks: any year starting on Thursday and any leap year starting on Wednesday
jan1 = jwday(gregorian.to_jd(year, 1, 1))
if jan1 == THU or (jan1 == WED and isleap(year)):
return 53
else:
return 52 | python | def weeks_per_year(year):
'''Number of ISO weeks in a year'''
# 53 weeks: any year starting on Thursday and any leap year starting on Wednesday
jan1 = jwday(gregorian.to_jd(year, 1, 1))
if jan1 == THU or (jan1 == WED and isleap(year)):
return 53
else:
return 52 | [
"def",
"weeks_per_year",
"(",
"year",
")",
":",
"# 53 weeks: any year starting on Thursday and any leap year starting on Wednesday",
"jan1",
"=",
"jwday",
"(",
"gregorian",
".",
"to_jd",
"(",
"year",
",",
"1",
",",
"1",
")",
")",
"if",
"jan1",
"==",
"THU",
"or",
... | Number of ISO weeks in a year | [
"Number",
"of",
"ISO",
"weeks",
"in",
"a",
"year"
] | train | https://github.com/fitnr/convertdate/blob/e920f168a87f99183b0aa7290d6c3af222582d43/convertdate/iso.py#L50-L58 |
spacetelescope/stsci.tools | lib/stsci/tools/readgeis.py | stsci | def stsci(hdulist):
"""For STScI GEIS files, need to do extra steps."""
instrument = hdulist[0].header.get('INSTRUME', '')
# Update extension header keywords
if instrument in ("WFPC2", "FOC"):
rootname = hdulist[0].header.get('ROOTNAME', '')
filetype = hdulist[0].header.get('FILETYPE',... | python | def stsci(hdulist):
"""For STScI GEIS files, need to do extra steps."""
instrument = hdulist[0].header.get('INSTRUME', '')
# Update extension header keywords
if instrument in ("WFPC2", "FOC"):
rootname = hdulist[0].header.get('ROOTNAME', '')
filetype = hdulist[0].header.get('FILETYPE',... | [
"def",
"stsci",
"(",
"hdulist",
")",
":",
"instrument",
"=",
"hdulist",
"[",
"0",
"]",
".",
"header",
".",
"get",
"(",
"'INSTRUME'",
",",
"''",
")",
"# Update extension header keywords",
"if",
"instrument",
"in",
"(",
"\"WFPC2\"",
",",
"\"FOC\"",
")",
":",... | For STScI GEIS files, need to do extra steps. | [
"For",
"STScI",
"GEIS",
"files",
"need",
"to",
"do",
"extra",
"steps",
"."
] | train | https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/readgeis.py#L79-L97 |
spacetelescope/stsci.tools | lib/stsci/tools/readgeis.py | stsci2 | def stsci2(hdulist, filename):
"""For STScI GEIS files, need to do extra steps."""
# Write output file name to the primary header
instrument = hdulist[0].header.get('INSTRUME', '')
if instrument in ("WFPC2", "FOC"):
hdulist[0].header['FILENAME'] = filename | python | def stsci2(hdulist, filename):
"""For STScI GEIS files, need to do extra steps."""
# Write output file name to the primary header
instrument = hdulist[0].header.get('INSTRUME', '')
if instrument in ("WFPC2", "FOC"):
hdulist[0].header['FILENAME'] = filename | [
"def",
"stsci2",
"(",
"hdulist",
",",
"filename",
")",
":",
"# Write output file name to the primary header",
"instrument",
"=",
"hdulist",
"[",
"0",
"]",
".",
"header",
".",
"get",
"(",
"'INSTRUME'",
",",
"''",
")",
"if",
"instrument",
"in",
"(",
"\"WFPC2\"",... | For STScI GEIS files, need to do extra steps. | [
"For",
"STScI",
"GEIS",
"files",
"need",
"to",
"do",
"extra",
"steps",
"."
] | train | https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/readgeis.py#L100-L106 |
spacetelescope/stsci.tools | lib/stsci/tools/readgeis.py | readgeis | def readgeis(input):
"""Input GEIS files "input" will be read and a HDUList object will
be returned.
The user can use the writeto method to write the HDUList object to
a FITS file.
"""
global dat
cardLen = fits.Card.length
# input file(s) must be of the form *.??h and *.??d
... | python | def readgeis(input):
"""Input GEIS files "input" will be read and a HDUList object will
be returned.
The user can use the writeto method to write the HDUList object to
a FITS file.
"""
global dat
cardLen = fits.Card.length
# input file(s) must be of the form *.??h and *.??d
... | [
"def",
"readgeis",
"(",
"input",
")",
":",
"global",
"dat",
"cardLen",
"=",
"fits",
".",
"Card",
".",
"length",
"# input file(s) must be of the form *.??h and *.??d",
"if",
"input",
"[",
"-",
"1",
"]",
"!=",
"'h'",
"or",
"input",
"[",
"-",
"4",
"]",
"!=",
... | Input GEIS files "input" will be read and a HDUList object will
be returned.
The user can use the writeto method to write the HDUList object to
a FITS file. | [
"Input",
"GEIS",
"files",
"input",
"will",
"be",
"read",
"and",
"a",
"HDUList",
"object",
"will",
"be",
"returned",
"."
] | train | https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/readgeis.py#L109-L320 |
spacetelescope/stsci.tools | lib/stsci/tools/readgeis.py | parse_path | def parse_path(f1, f2):
"""Parse two input arguments and return two lists of file names"""
import glob
# if second argument is missing or is a wild card, point it
# to the current directory
f2 = f2.strip()
if f2 == '' or f2 == '*':
f2 = './'
# if the first argument is a directory... | python | def parse_path(f1, f2):
"""Parse two input arguments and return two lists of file names"""
import glob
# if second argument is missing or is a wild card, point it
# to the current directory
f2 = f2.strip()
if f2 == '' or f2 == '*':
f2 = './'
# if the first argument is a directory... | [
"def",
"parse_path",
"(",
"f1",
",",
"f2",
")",
":",
"import",
"glob",
"# if second argument is missing or is a wild card, point it",
"# to the current directory",
"f2",
"=",
"f2",
".",
"strip",
"(",
")",
"if",
"f2",
"==",
"''",
"or",
"f2",
"==",
"'*'",
":",
"... | Parse two input arguments and return two lists of file names | [
"Parse",
"two",
"input",
"arguments",
"and",
"return",
"two",
"lists",
"of",
"file",
"names"
] | train | https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/readgeis.py#L322-L363 |
spacetelescope/stsci.tools | lib/stsci/tools/parseinput.py | parseinput | def parseinput(inputlist,outputname=None, atfile=None):
"""
Recursively parse user input based upon the irafglob
program and construct a list of files that need to be processed.
This program addresses the following deficiencies of the irafglob program::
parseinput can extract filenames from asso... | python | def parseinput(inputlist,outputname=None, atfile=None):
"""
Recursively parse user input based upon the irafglob
program and construct a list of files that need to be processed.
This program addresses the following deficiencies of the irafglob program::
parseinput can extract filenames from asso... | [
"def",
"parseinput",
"(",
"inputlist",
",",
"outputname",
"=",
"None",
",",
"atfile",
"=",
"None",
")",
":",
"# Initalize some variables",
"files",
"=",
"[",
"]",
"# list used to store names of input files",
"newoutputname",
"=",
"outputname",
"# Outputname returned to ... | Recursively parse user input based upon the irafglob
program and construct a list of files that need to be processed.
This program addresses the following deficiencies of the irafglob program::
parseinput can extract filenames from association tables
Returns
-------
This program will return... | [
"Recursively",
"parse",
"user",
"input",
"based",
"upon",
"the",
"irafglob",
"program",
"and",
"construct",
"a",
"list",
"of",
"files",
"that",
"need",
"to",
"be",
"processed",
".",
"This",
"program",
"addresses",
"the",
"following",
"deficiencies",
"of",
"the... | train | https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/parseinput.py#L31-L134 |
spacetelescope/stsci.tools | lib/stsci/tools/parseinput.py | checkASN | def checkASN(filename):
"""
Determine if the filename provided to the function belongs to
an association.
Parameters
----------
filename: string
Returns
-------
validASN : boolean value
"""
# Extract the file extn type:
extnType = filename[filename.rfind('_')+1:filena... | python | def checkASN(filename):
"""
Determine if the filename provided to the function belongs to
an association.
Parameters
----------
filename: string
Returns
-------
validASN : boolean value
"""
# Extract the file extn type:
extnType = filename[filename.rfind('_')+1:filena... | [
"def",
"checkASN",
"(",
"filename",
")",
":",
"# Extract the file extn type:",
"extnType",
"=",
"filename",
"[",
"filename",
".",
"rfind",
"(",
"'_'",
")",
"+",
"1",
":",
"filename",
".",
"rfind",
"(",
"'.'",
")",
"]",
"# Determine if this extn name is valid for... | Determine if the filename provided to the function belongs to
an association.
Parameters
----------
filename: string
Returns
-------
validASN : boolean value | [
"Determine",
"if",
"the",
"filename",
"provided",
"to",
"the",
"function",
"belongs",
"to",
"an",
"association",
"."
] | train | https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/parseinput.py#L137-L158 |
spacetelescope/stsci.tools | lib/stsci/tools/parseinput.py | countinputs | def countinputs(inputlist):
"""
Determine the number of inputfiles provided by the user and the
number of those files that are association tables
Parameters
----------
inputlist : string
the user input
Returns
-------
numInputs: int
number of inputs provided by th... | python | def countinputs(inputlist):
"""
Determine the number of inputfiles provided by the user and the
number of those files that are association tables
Parameters
----------
inputlist : string
the user input
Returns
-------
numInputs: int
number of inputs provided by th... | [
"def",
"countinputs",
"(",
"inputlist",
")",
":",
"# Initialize return values",
"numInputs",
"=",
"0",
"numASNfiles",
"=",
"0",
"# User irafglob to count the number of inputfiles",
"files",
"=",
"irafglob",
"(",
"inputlist",
",",
"atfile",
"=",
"None",
")",
"# Use the... | Determine the number of inputfiles provided by the user and the
number of those files that are association tables
Parameters
----------
inputlist : string
the user input
Returns
-------
numInputs: int
number of inputs provided by the user
numASNfiles: int
numb... | [
"Determine",
"the",
"number",
"of",
"inputfiles",
"provided",
"by",
"the",
"user",
"and",
"the",
"number",
"of",
"those",
"files",
"that",
"are",
"association",
"tables"
] | train | https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/parseinput.py#L185-L218 |
adeel/timed | timed/client.py | summary | def summary(logfile, time_format):
"show a summary of all projects"
def output(summary):
width = max([len(p[0]) for p in summary]) + 3
print '\n'.join([
"%s%s%s" % (p[0], ' ' * (width - len(p[0])),
colored(minutes_to_txt(p[1]), 'red')) for p in summary])
output(server.summarize(read(logfil... | python | def summary(logfile, time_format):
"show a summary of all projects"
def output(summary):
width = max([len(p[0]) for p in summary]) + 3
print '\n'.join([
"%s%s%s" % (p[0], ' ' * (width - len(p[0])),
colored(minutes_to_txt(p[1]), 'red')) for p in summary])
output(server.summarize(read(logfil... | [
"def",
"summary",
"(",
"logfile",
",",
"time_format",
")",
":",
"def",
"output",
"(",
"summary",
")",
":",
"width",
"=",
"max",
"(",
"[",
"len",
"(",
"p",
"[",
"0",
"]",
")",
"for",
"p",
"in",
"summary",
"]",
")",
"+",
"3",
"print",
"'\\n'",
".... | show a summary of all projects | [
"show",
"a",
"summary",
"of",
"all",
"projects"
] | train | https://github.com/adeel/timed/blob/9f85e004de491cd4863d31b09991a1e2591b1b66/timed/client.py#L21-L30 |
adeel/timed | timed/client.py | status | def status(logfile, time_format):
"show current status"
try:
r = read(logfile, time_format)[-1]
if r[1][1]:
return summary(logfile, time_format)
else:
print "working on %s" % colored(r[0], attrs=['bold'])
print " since %s" % colored(
server.date_to_txt(r[1][0], time_format... | python | def status(logfile, time_format):
"show current status"
try:
r = read(logfile, time_format)[-1]
if r[1][1]:
return summary(logfile, time_format)
else:
print "working on %s" % colored(r[0], attrs=['bold'])
print " since %s" % colored(
server.date_to_txt(r[1][0], time_format... | [
"def",
"status",
"(",
"logfile",
",",
"time_format",
")",
":",
"try",
":",
"r",
"=",
"read",
"(",
"logfile",
",",
"time_format",
")",
"[",
"-",
"1",
"]",
"if",
"r",
"[",
"1",
"]",
"[",
"1",
"]",
":",
"return",
"summary",
"(",
"logfile",
",",
"t... | show current status | [
"show",
"current",
"status"
] | train | https://github.com/adeel/timed/blob/9f85e004de491cd4863d31b09991a1e2591b1b66/timed/client.py#L34-L49 |
adeel/timed | timed/client.py | start | def start(project, logfile, time_format):
"start tracking for <project>"
records = read(logfile, time_format)
if records and not records[-1][1][1]:
print "error: there is a project already active"
return
write(server.start(project, records), logfile, time_format)
print "starting work on %s" % color... | python | def start(project, logfile, time_format):
"start tracking for <project>"
records = read(logfile, time_format)
if records and not records[-1][1][1]:
print "error: there is a project already active"
return
write(server.start(project, records), logfile, time_format)
print "starting work on %s" % color... | [
"def",
"start",
"(",
"project",
",",
"logfile",
",",
"time_format",
")",
":",
"records",
"=",
"read",
"(",
"logfile",
",",
"time_format",
")",
"if",
"records",
"and",
"not",
"records",
"[",
"-",
"1",
"]",
"[",
"1",
"]",
"[",
"1",
"]",
":",
"print",... | start tracking for <project> | [
"start",
"tracking",
"for",
"<project",
">"
] | train | https://github.com/adeel/timed/blob/9f85e004de491cd4863d31b09991a1e2591b1b66/timed/client.py#L52-L63 |
adeel/timed | timed/client.py | stop | def stop(logfile, time_format):
"stop tracking for the active project"
def save_and_output(records):
records = server.stop(records)
write(records, logfile, time_format)
def output(r):
print "worked on %s" % colored(r[0], attrs=['bold'])
print " from %s" % colored(
server.date_t... | python | def stop(logfile, time_format):
"stop tracking for the active project"
def save_and_output(records):
records = server.stop(records)
write(records, logfile, time_format)
def output(r):
print "worked on %s" % colored(r[0], attrs=['bold'])
print " from %s" % colored(
server.date_t... | [
"def",
"stop",
"(",
"logfile",
",",
"time_format",
")",
":",
"def",
"save_and_output",
"(",
"records",
")",
":",
"records",
"=",
"server",
".",
"stop",
"(",
"records",
")",
"write",
"(",
"records",
",",
"logfile",
",",
"time_format",
")",
"def",
"output"... | stop tracking for the active project | [
"stop",
"tracking",
"for",
"the",
"active",
"project"
] | train | https://github.com/adeel/timed/blob/9f85e004de491cd4863d31b09991a1e2591b1b66/timed/client.py#L66-L84 |
adeel/timed | timed/client.py | parse | def parse(logfile, time_format):
"parses a stream with text formatted as a Timed logfile and shows a summary"
records = [server.record_from_txt(line, only_elapsed=True,
time_format=time_format) for line in sys.stdin.readlines()]
# TODO: make this code better.
def output(summary):
width = max([len(p[0]... | python | def parse(logfile, time_format):
"parses a stream with text formatted as a Timed logfile and shows a summary"
records = [server.record_from_txt(line, only_elapsed=True,
time_format=time_format) for line in sys.stdin.readlines()]
# TODO: make this code better.
def output(summary):
width = max([len(p[0]... | [
"def",
"parse",
"(",
"logfile",
",",
"time_format",
")",
":",
"records",
"=",
"[",
"server",
".",
"record_from_txt",
"(",
"line",
",",
"only_elapsed",
"=",
"True",
",",
"time_format",
"=",
"time_format",
")",
"for",
"line",
"in",
"sys",
".",
"stdin",
"."... | parses a stream with text formatted as a Timed logfile and shows a summary | [
"parses",
"a",
"stream",
"with",
"text",
"formatted",
"as",
"a",
"Timed",
"logfile",
"and",
"shows",
"a",
"summary"
] | train | https://github.com/adeel/timed/blob/9f85e004de491cd4863d31b09991a1e2591b1b66/timed/client.py#L87-L100 |
adeel/timed | timed/client.py | projects | def projects(logfile, time_format):
"prints a newline-separated list of all projects"
print '\n'.join(server.list_projects(read(logfile, time_format))) | python | def projects(logfile, time_format):
"prints a newline-separated list of all projects"
print '\n'.join(server.list_projects(read(logfile, time_format))) | [
"def",
"projects",
"(",
"logfile",
",",
"time_format",
")",
":",
"print",
"'\\n'",
".",
"join",
"(",
"server",
".",
"list_projects",
"(",
"read",
"(",
"logfile",
",",
"time_format",
")",
")",
")"
] | prints a newline-separated list of all projects | [
"prints",
"a",
"newline",
"-",
"separated",
"list",
"of",
"all",
"projects"
] | train | https://github.com/adeel/timed/blob/9f85e004de491cd4863d31b09991a1e2591b1b66/timed/client.py#L103-L106 |
spacetelescope/stsci.tools | lib/stsci/tools/fileutil.py | getLTime | def getLTime():
"""Returns a formatted string with the current local time."""
_ltime = _time.localtime(_time.time())
tlm_str = _time.strftime('%H:%M:%S (%d/%m/%Y)', _ltime)
return tlm_str | python | def getLTime():
"""Returns a formatted string with the current local time."""
_ltime = _time.localtime(_time.time())
tlm_str = _time.strftime('%H:%M:%S (%d/%m/%Y)', _ltime)
return tlm_str | [
"def",
"getLTime",
"(",
")",
":",
"_ltime",
"=",
"_time",
".",
"localtime",
"(",
"_time",
".",
"time",
"(",
")",
")",
"tlm_str",
"=",
"_time",
".",
"strftime",
"(",
"'%H:%M:%S (%d/%m/%Y)'",
",",
"_ltime",
")",
"return",
"tlm_str"
] | Returns a formatted string with the current local time. | [
"Returns",
"a",
"formatted",
"string",
"with",
"the",
"current",
"local",
"time",
"."
] | train | https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/fileutil.py#L154-L159 |
spacetelescope/stsci.tools | lib/stsci/tools/fileutil.py | getDate | def getDate():
"""Returns a formatted string with the current date."""
_ltime = _time.localtime(_time.time())
date_str = _time.strftime('%Y-%m-%dT%H:%M:%S',_ltime)
return date_str | python | def getDate():
"""Returns a formatted string with the current date."""
_ltime = _time.localtime(_time.time())
date_str = _time.strftime('%Y-%m-%dT%H:%M:%S',_ltime)
return date_str | [
"def",
"getDate",
"(",
")",
":",
"_ltime",
"=",
"_time",
".",
"localtime",
"(",
"_time",
".",
"time",
"(",
")",
")",
"date_str",
"=",
"_time",
".",
"strftime",
"(",
"'%Y-%m-%dT%H:%M:%S'",
",",
"_ltime",
")",
"return",
"date_str"
] | Returns a formatted string with the current date. | [
"Returns",
"a",
"formatted",
"string",
"with",
"the",
"current",
"date",
"."
] | train | https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/fileutil.py#L162-L168 |
spacetelescope/stsci.tools | lib/stsci/tools/fileutil.py | convertDate | def convertDate(date):
"""Convert DATE string into a decimal year."""
d, t = date.split('T')
return decimal_date(d, timeobs=t) | python | def convertDate(date):
"""Convert DATE string into a decimal year."""
d, t = date.split('T')
return decimal_date(d, timeobs=t) | [
"def",
"convertDate",
"(",
"date",
")",
":",
"d",
",",
"t",
"=",
"date",
".",
"split",
"(",
"'T'",
")",
"return",
"decimal_date",
"(",
"d",
",",
"timeobs",
"=",
"t",
")"
] | Convert DATE string into a decimal year. | [
"Convert",
"DATE",
"string",
"into",
"a",
"decimal",
"year",
"."
] | train | https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/fileutil.py#L171-L175 |
spacetelescope/stsci.tools | lib/stsci/tools/fileutil.py | decimal_date | def decimal_date(dateobs, timeobs=None):
"""Convert DATE-OBS (and optional TIME-OBS) into a decimal year."""
year, month, day = dateobs.split('-')
if timeobs is not None:
hr, min, sec = timeobs.split(':')
else:
hr, min, sec = 0, 0, 0
rdate = datetime.datetime(int(year), int(month),... | python | def decimal_date(dateobs, timeobs=None):
"""Convert DATE-OBS (and optional TIME-OBS) into a decimal year."""
year, month, day = dateobs.split('-')
if timeobs is not None:
hr, min, sec = timeobs.split(':')
else:
hr, min, sec = 0, 0, 0
rdate = datetime.datetime(int(year), int(month),... | [
"def",
"decimal_date",
"(",
"dateobs",
",",
"timeobs",
"=",
"None",
")",
":",
"year",
",",
"month",
",",
"day",
"=",
"dateobs",
".",
"split",
"(",
"'-'",
")",
"if",
"timeobs",
"is",
"not",
"None",
":",
"hr",
",",
"min",
",",
"sec",
"=",
"timeobs",
... | Convert DATE-OBS (and optional TIME-OBS) into a decimal year. | [
"Convert",
"DATE",
"-",
"OBS",
"(",
"and",
"optional",
"TIME",
"-",
"OBS",
")",
"into",
"a",
"decimal",
"year",
"."
] | train | https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/fileutil.py#L178-L193 |
spacetelescope/stsci.tools | lib/stsci/tools/fileutil.py | interpretDQvalue | def interpretDQvalue(input):
"""
Converts an integer 'input' into its component bit values as a list of
power of 2 integers.
For example, the bit value 1027 would return [1, 2, 1024]
"""
nbits = 16
# We will only support integer values up to 2**128
for iexp in [16, 32, 64, 128]:
... | python | def interpretDQvalue(input):
"""
Converts an integer 'input' into its component bit values as a list of
power of 2 integers.
For example, the bit value 1027 would return [1, 2, 1024]
"""
nbits = 16
# We will only support integer values up to 2**128
for iexp in [16, 32, 64, 128]:
... | [
"def",
"interpretDQvalue",
"(",
"input",
")",
":",
"nbits",
"=",
"16",
"# We will only support integer values up to 2**128",
"for",
"iexp",
"in",
"[",
"16",
",",
"32",
",",
"64",
",",
"128",
"]",
":",
"# Find out whether the input value is less than 2**iexp",
"if",
... | Converts an integer 'input' into its component bit values as a list of
power of 2 integers.
For example, the bit value 1027 would return [1, 2, 1024] | [
"Converts",
"an",
"integer",
"input",
"into",
"its",
"component",
"bit",
"values",
"as",
"a",
"list",
"of",
"power",
"of",
"2",
"integers",
"."
] | train | https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/fileutil.py#L196-L229 |
spacetelescope/stsci.tools | lib/stsci/tools/fileutil.py | isFits | def isFits(input):
"""
Returns
--------
isFits: tuple
An ``(isfits, fitstype)`` tuple. The values of ``isfits`` and
``fitstype`` are specified as:
- ``isfits``: True|False
- ``fitstype``: if True, one of 'waiver', 'mef', 'simple'; if False, None
Notes
-----
... | python | def isFits(input):
"""
Returns
--------
isFits: tuple
An ``(isfits, fitstype)`` tuple. The values of ``isfits`` and
``fitstype`` are specified as:
- ``isfits``: True|False
- ``fitstype``: if True, one of 'waiver', 'mef', 'simple'; if False, None
Notes
-----
... | [
"def",
"isFits",
"(",
"input",
")",
":",
"isfits",
"=",
"False",
"fitstype",
"=",
"None",
"names",
"=",
"[",
"'fits'",
",",
"'fit'",
",",
"'FITS'",
",",
"'FIT'",
"]",
"#determine if input is a fits file based on extension",
"# Only check type of FITS file if filename ... | Returns
--------
isFits: tuple
An ``(isfits, fitstype)`` tuple. The values of ``isfits`` and
``fitstype`` are specified as:
- ``isfits``: True|False
- ``fitstype``: if True, one of 'waiver', 'mef', 'simple'; if False, None
Notes
-----
Input images which do not ha... | [
"Returns",
"--------",
"isFits",
":",
"tuple",
"An",
"(",
"isfits",
"fitstype",
")",
"tuple",
".",
"The",
"values",
"of",
"isfits",
"and",
"fitstype",
"are",
"specified",
"as",
":"
] | train | https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/fileutil.py#L232-L289 |
spacetelescope/stsci.tools | lib/stsci/tools/fileutil.py | verifyWriteMode | def verifyWriteMode(files):
"""
Checks whether files are writable. It is up to the calling routine to raise
an Exception, if desired.
This function returns True, if all files are writable and False, if any are
not writable. In addition, for all files found to not be writable, it will
print out... | python | def verifyWriteMode(files):
"""
Checks whether files are writable. It is up to the calling routine to raise
an Exception, if desired.
This function returns True, if all files are writable and False, if any are
not writable. In addition, for all files found to not be writable, it will
print out... | [
"def",
"verifyWriteMode",
"(",
"files",
")",
":",
"# Start by insuring that input is a list of filenames,",
"# if only a single filename has been given as input,",
"# convert it to a list with len == 1.",
"if",
"not",
"isinstance",
"(",
"files",
",",
"list",
")",
":",
"files",
... | Checks whether files are writable. It is up to the calling routine to raise
an Exception, if desired.
This function returns True, if all files are writable and False, if any are
not writable. In addition, for all files found to not be writable, it will
print out the list of names of affected files. | [
"Checks",
"whether",
"files",
"are",
"writable",
".",
"It",
"is",
"up",
"to",
"the",
"calling",
"routine",
"to",
"raise",
"an",
"Exception",
"if",
"desired",
"."
] | train | https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/fileutil.py#L308-L343 |
spacetelescope/stsci.tools | lib/stsci/tools/fileutil.py | getFilterNames | def getFilterNames(header, filternames=None):
"""
Returns a comma-separated string of filter names extracted from the input
header (PyFITS header object). This function has been hard-coded to
support the following instruments:
ACS, WFPC2, STIS
This function relies on the 'INSTRUME' keywor... | python | def getFilterNames(header, filternames=None):
"""
Returns a comma-separated string of filter names extracted from the input
header (PyFITS header object). This function has been hard-coded to
support the following instruments:
ACS, WFPC2, STIS
This function relies on the 'INSTRUME' keywor... | [
"def",
"getFilterNames",
"(",
"header",
",",
"filternames",
"=",
"None",
")",
":",
"# Define the keyword names for each instrument",
"_keydict",
"=",
"{",
"'ACS'",
":",
"[",
"'FILTER1'",
",",
"'FILTER2'",
"]",
",",
"'WFPC2'",
":",
"[",
"'FILTNAM1'",
",",
"'FILTN... | Returns a comma-separated string of filter names extracted from the input
header (PyFITS header object). This function has been hard-coded to
support the following instruments:
ACS, WFPC2, STIS
This function relies on the 'INSTRUME' keyword to define what instrument
has been used to generate ... | [
"Returns",
"a",
"comma",
"-",
"separated",
"string",
"of",
"filter",
"names",
"extracted",
"from",
"the",
"input",
"header",
"(",
"PyFITS",
"header",
"object",
")",
".",
"This",
"function",
"has",
"been",
"hard",
"-",
"coded",
"to",
"support",
"the",
"foll... | train | https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/fileutil.py#L346-L397 |
spacetelescope/stsci.tools | lib/stsci/tools/fileutil.py | buildNewRootname | def buildNewRootname(filename, extn=None, extlist=None):
"""
Build rootname for a new file.
Use 'extn' for new filename if given, does NOT append a suffix/extension at
all.
Does NOT check to see if it exists already. Will ALWAYS return a new
filename.
"""
# Search known suffixes to r... | python | def buildNewRootname(filename, extn=None, extlist=None):
"""
Build rootname for a new file.
Use 'extn' for new filename if given, does NOT append a suffix/extension at
all.
Does NOT check to see if it exists already. Will ALWAYS return a new
filename.
"""
# Search known suffixes to r... | [
"def",
"buildNewRootname",
"(",
"filename",
",",
"extn",
"=",
"None",
",",
"extlist",
"=",
"None",
")",
":",
"# Search known suffixes to replace ('_crj.fits',...)",
"_extlist",
"=",
"copy",
".",
"deepcopy",
"(",
"EXTLIST",
")",
"# Also, add a default where '_dth.fits' r... | Build rootname for a new file.
Use 'extn' for new filename if given, does NOT append a suffix/extension at
all.
Does NOT check to see if it exists already. Will ALWAYS return a new
filename. | [
"Build",
"rootname",
"for",
"a",
"new",
"file",
"."
] | train | https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/fileutil.py#L400-L436 |
spacetelescope/stsci.tools | lib/stsci/tools/fileutil.py | buildRootname | def buildRootname(filename, ext=None):
"""
Build a new rootname for an existing file and given extension.
Any user supplied extensions to use for searching for file need to be
provided as a list of extensions.
Examples
--------
::
>>> rootname = buildRootname(filename, ext=['_dth... | python | def buildRootname(filename, ext=None):
"""
Build a new rootname for an existing file and given extension.
Any user supplied extensions to use for searching for file need to be
provided as a list of extensions.
Examples
--------
::
>>> rootname = buildRootname(filename, ext=['_dth... | [
"def",
"buildRootname",
"(",
"filename",
",",
"ext",
"=",
"None",
")",
":",
"if",
"filename",
"in",
"[",
"''",
",",
"' '",
",",
"None",
"]",
":",
"return",
"None",
"fpath",
",",
"fname",
"=",
"os",
".",
"path",
".",
"split",
"(",
"filename",
")",
... | Build a new rootname for an existing file and given extension.
Any user supplied extensions to use for searching for file need to be
provided as a list of extensions.
Examples
--------
::
>>> rootname = buildRootname(filename, ext=['_dth.fits']) # doctest: +SKIP | [
"Build",
"a",
"new",
"rootname",
"for",
"an",
"existing",
"file",
"and",
"given",
"extension",
"."
] | train | https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/fileutil.py#L439-L530 |
spacetelescope/stsci.tools | lib/stsci/tools/fileutil.py | getKeyword | def getKeyword(filename, keyword, default=None, handle=None):
"""
General, write-safe method for returning a keyword value from the header of
a IRAF recognized image.
Returns the value as a string.
"""
# Insure that there is at least 1 extension specified...
if filename.find('[') < 0:
... | python | def getKeyword(filename, keyword, default=None, handle=None):
"""
General, write-safe method for returning a keyword value from the header of
a IRAF recognized image.
Returns the value as a string.
"""
# Insure that there is at least 1 extension specified...
if filename.find('[') < 0:
... | [
"def",
"getKeyword",
"(",
"filename",
",",
"keyword",
",",
"default",
"=",
"None",
",",
"handle",
"=",
"None",
")",
":",
"# Insure that there is at least 1 extension specified...",
"if",
"filename",
".",
"find",
"(",
"'['",
")",
"<",
"0",
":",
"filename",
"+="... | General, write-safe method for returning a keyword value from the header of
a IRAF recognized image.
Returns the value as a string. | [
"General",
"write",
"-",
"safe",
"method",
"for",
"returning",
"a",
"keyword",
"value",
"from",
"the",
"header",
"of",
"a",
"IRAF",
"recognized",
"image",
"."
] | train | https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/fileutil.py#L533-L598 |
spacetelescope/stsci.tools | lib/stsci/tools/fileutil.py | getHeader | def getHeader(filename, handle=None):
"""
Return a copy of the PRIMARY header, along with any group/extension header
for this filename specification.
"""
_fname, _extn = parseFilename(filename)
# Allow the user to provide an already opened PyFITS object
# to derive the header from...
#
... | python | def getHeader(filename, handle=None):
"""
Return a copy of the PRIMARY header, along with any group/extension header
for this filename specification.
"""
_fname, _extn = parseFilename(filename)
# Allow the user to provide an already opened PyFITS object
# to derive the header from...
#
... | [
"def",
"getHeader",
"(",
"filename",
",",
"handle",
"=",
"None",
")",
":",
"_fname",
",",
"_extn",
"=",
"parseFilename",
"(",
"filename",
")",
"# Allow the user to provide an already opened PyFITS object",
"# to derive the header from...",
"#",
"if",
"not",
"handle",
... | Return a copy of the PRIMARY header, along with any group/extension header
for this filename specification. | [
"Return",
"a",
"copy",
"of",
"the",
"PRIMARY",
"header",
"along",
"with",
"any",
"group",
"/",
"extension",
"header",
"for",
"this",
"filename",
"specification",
"."
] | train | https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/fileutil.py#L601-L640 |
spacetelescope/stsci.tools | lib/stsci/tools/fileutil.py | updateKeyword | def updateKeyword(filename, key, value,show=yes):
"""Add/update keyword to header with given value."""
_fname, _extn = parseFilename(filename)
# Open image whether it is FITS or GEIS
_fimg = openImage(_fname, mode='update')
# Address the correct header
_hdr = getExtn(_fimg, _extn).header
... | python | def updateKeyword(filename, key, value,show=yes):
"""Add/update keyword to header with given value."""
_fname, _extn = parseFilename(filename)
# Open image whether it is FITS or GEIS
_fimg = openImage(_fname, mode='update')
# Address the correct header
_hdr = getExtn(_fimg, _extn).header
... | [
"def",
"updateKeyword",
"(",
"filename",
",",
"key",
",",
"value",
",",
"show",
"=",
"yes",
")",
":",
"_fname",
",",
"_extn",
"=",
"parseFilename",
"(",
"filename",
")",
"# Open image whether it is FITS or GEIS",
"_fimg",
"=",
"openImage",
"(",
"_fname",
",",
... | Add/update keyword to header with given value. | [
"Add",
"/",
"update",
"keyword",
"to",
"header",
"with",
"given",
"value",
"."
] | train | https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/fileutil.py#L643-L664 |
spacetelescope/stsci.tools | lib/stsci/tools/fileutil.py | buildFITSName | def buildFITSName(geisname):
"""Build a new FITS filename for a GEIS input image."""
# User wants to make a FITS copy and update it...
_indx = geisname.rfind('.')
_fitsname = geisname[:_indx] + '_' + geisname[_indx + 1:-1] + 'h.fits'
return _fitsname | python | def buildFITSName(geisname):
"""Build a new FITS filename for a GEIS input image."""
# User wants to make a FITS copy and update it...
_indx = geisname.rfind('.')
_fitsname = geisname[:_indx] + '_' + geisname[_indx + 1:-1] + 'h.fits'
return _fitsname | [
"def",
"buildFITSName",
"(",
"geisname",
")",
":",
"# User wants to make a FITS copy and update it...",
"_indx",
"=",
"geisname",
".",
"rfind",
"(",
"'.'",
")",
"_fitsname",
"=",
"geisname",
"[",
":",
"_indx",
"]",
"+",
"'_'",
"+",
"geisname",
"[",
"_indx",
"+... | Build a new FITS filename for a GEIS input image. | [
"Build",
"a",
"new",
"FITS",
"filename",
"for",
"a",
"GEIS",
"input",
"image",
"."
] | train | https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/fileutil.py#L667-L674 |
spacetelescope/stsci.tools | lib/stsci/tools/fileutil.py | openImage | def openImage(filename, mode='readonly', memmap=False, writefits=True,
clobber=True, fitsname=None):
"""
Opens file and returns PyFITS object. Works on both FITS and GEIS
formatted images.
Notes
-----
If a GEIS or waivered FITS image is used as input, it will convert it to a
... | python | def openImage(filename, mode='readonly', memmap=False, writefits=True,
clobber=True, fitsname=None):
"""
Opens file and returns PyFITS object. Works on both FITS and GEIS
formatted images.
Notes
-----
If a GEIS or waivered FITS image is used as input, it will convert it to a
... | [
"def",
"openImage",
"(",
"filename",
",",
"mode",
"=",
"'readonly'",
",",
"memmap",
"=",
"False",
",",
"writefits",
"=",
"True",
",",
"clobber",
"=",
"True",
",",
"fitsname",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"filename",
",",
"fits... | Opens file and returns PyFITS object. Works on both FITS and GEIS
formatted images.
Notes
-----
If a GEIS or waivered FITS image is used as input, it will convert it to a
MEF object and only if ``writefits = True`` will write it out to a file. If
``fitsname = None``, the name used to write out... | [
"Opens",
"file",
"and",
"returns",
"PyFITS",
"object",
".",
"Works",
"on",
"both",
"FITS",
"and",
"GEIS",
"formatted",
"images",
"."
] | train | https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/fileutil.py#L677-L823 |
spacetelescope/stsci.tools | lib/stsci/tools/fileutil.py | parseFilename | def parseFilename(filename):
"""
Parse out filename from any specified extensions.
Returns rootname and string version of extension name.
"""
# Parse out any extension specified in filename
_indx = filename.find('[')
if _indx > 0:
# Read extension name provided
_fname = fil... | python | def parseFilename(filename):
"""
Parse out filename from any specified extensions.
Returns rootname and string version of extension name.
"""
# Parse out any extension specified in filename
_indx = filename.find('[')
if _indx > 0:
# Read extension name provided
_fname = fil... | [
"def",
"parseFilename",
"(",
"filename",
")",
":",
"# Parse out any extension specified in filename",
"_indx",
"=",
"filename",
".",
"find",
"(",
"'['",
")",
"if",
"_indx",
">",
"0",
":",
"# Read extension name provided",
"_fname",
"=",
"filename",
"[",
":",
"_ind... | Parse out filename from any specified extensions.
Returns rootname and string version of extension name. | [
"Parse",
"out",
"filename",
"from",
"any",
"specified",
"extensions",
"."
] | train | https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/fileutil.py#L826-L843 |
spacetelescope/stsci.tools | lib/stsci/tools/fileutil.py | parseExtn | def parseExtn(extn=None):
"""
Parse a string representing a qualified fits extension name as in the
output of `parseFilename` and return a tuple ``(str(extname),
int(extver))``, which can be passed to `astropy.io.fits` functions using
the 'ext' kw.
Default return is the first extension in a fit... | python | def parseExtn(extn=None):
"""
Parse a string representing a qualified fits extension name as in the
output of `parseFilename` and return a tuple ``(str(extname),
int(extver))``, which can be passed to `astropy.io.fits` functions using
the 'ext' kw.
Default return is the first extension in a fit... | [
"def",
"parseExtn",
"(",
"extn",
"=",
"None",
")",
":",
"if",
"not",
"extn",
":",
"return",
"(",
"''",
",",
"0",
")",
"try",
":",
"lext",
"=",
"extn",
".",
"split",
"(",
"','",
")",
"except",
":",
"return",
"(",
"''",
",",
"1",
")",
"if",
"le... | Parse a string representing a qualified fits extension name as in the
output of `parseFilename` and return a tuple ``(str(extname),
int(extver))``, which can be passed to `astropy.io.fits` functions using
the 'ext' kw.
Default return is the first extension in a fits file.
Examples
--------
... | [
"Parse",
"a",
"string",
"representing",
"a",
"qualified",
"fits",
"extension",
"name",
"as",
"in",
"the",
"output",
"of",
"parseFilename",
"and",
"return",
"a",
"tuple",
"(",
"str",
"(",
"extname",
")",
"int",
"(",
"extver",
"))",
"which",
"can",
"be",
"... | train | https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/fileutil.py#L846-L882 |
spacetelescope/stsci.tools | lib/stsci/tools/fileutil.py | countExtn | def countExtn(fimg, extname='SCI'):
"""
Return the number of 'extname' extensions, defaulting to counting the
number of SCI extensions.
"""
closefits = False
if isinstance(fimg, string_types):
fimg = fits.open(fimg)
closefits = True
n = 0
for e in fimg:
if 'extn... | python | def countExtn(fimg, extname='SCI'):
"""
Return the number of 'extname' extensions, defaulting to counting the
number of SCI extensions.
"""
closefits = False
if isinstance(fimg, string_types):
fimg = fits.open(fimg)
closefits = True
n = 0
for e in fimg:
if 'extn... | [
"def",
"countExtn",
"(",
"fimg",
",",
"extname",
"=",
"'SCI'",
")",
":",
"closefits",
"=",
"False",
"if",
"isinstance",
"(",
"fimg",
",",
"string_types",
")",
":",
"fimg",
"=",
"fits",
".",
"open",
"(",
"fimg",
")",
"closefits",
"=",
"True",
"n",
"="... | Return the number of 'extname' extensions, defaulting to counting the
number of SCI extensions. | [
"Return",
"the",
"number",
"of",
"extname",
"extensions",
"defaulting",
"to",
"counting",
"the",
"number",
"of",
"SCI",
"extensions",
"."
] | train | https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/fileutil.py#L885-L904 |
spacetelescope/stsci.tools | lib/stsci/tools/fileutil.py | getExtn | def getExtn(fimg, extn=None):
"""
Returns the PyFITS extension corresponding to extension specified in
filename.
Defaults to returning the first extension with data or the primary
extension, if none have data. If a non-existent extension has been
specified, it raises a `KeyError` exception.
... | python | def getExtn(fimg, extn=None):
"""
Returns the PyFITS extension corresponding to extension specified in
filename.
Defaults to returning the first extension with data or the primary
extension, if none have data. If a non-existent extension has been
specified, it raises a `KeyError` exception.
... | [
"def",
"getExtn",
"(",
"fimg",
",",
"extn",
"=",
"None",
")",
":",
"# If no extension is provided, search for first extension",
"# in FITS file with data associated with it.",
"if",
"extn",
"is",
"None",
":",
"# Set up default to point to PRIMARY extension.",
"_extn",
"=",
"f... | Returns the PyFITS extension corresponding to extension specified in
filename.
Defaults to returning the first extension with data or the primary
extension, if none have data. If a non-existent extension has been
specified, it raises a `KeyError` exception. | [
"Returns",
"the",
"PyFITS",
"extension",
"corresponding",
"to",
"extension",
"specified",
"in",
"filename",
"."
] | train | https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/fileutil.py#L907-L992 |
spacetelescope/stsci.tools | lib/stsci/tools/fileutil.py | findFile | def findFile(input):
"""Search a directory for full filename with optional path."""
# If no input name is provided, default to returning 'no'(FALSE)
if not input:
return no
# We use 'osfn' here to insure that any IRAF variables are
# expanded out before splitting out the path...
_fdir,... | python | def findFile(input):
"""Search a directory for full filename with optional path."""
# If no input name is provided, default to returning 'no'(FALSE)
if not input:
return no
# We use 'osfn' here to insure that any IRAF variables are
# expanded out before splitting out the path...
_fdir,... | [
"def",
"findFile",
"(",
"input",
")",
":",
"# If no input name is provided, default to returning 'no'(FALSE)",
"if",
"not",
"input",
":",
"return",
"no",
"# We use 'osfn' here to insure that any IRAF variables are",
"# expanded out before splitting out the path...",
"_fdir",
",",
"... | Search a directory for full filename with optional path. | [
"Search",
"a",
"directory",
"for",
"full",
"filename",
"with",
"optional",
"path",
"."
] | train | https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/fileutil.py#L1001-L1058 |
spacetelescope/stsci.tools | lib/stsci/tools/fileutil.py | checkFileExists | def checkFileExists(filename, directory=None):
"""
Checks to see if file specified exists in current or specified directory.
Default is current directory. Returns 1 if it exists, 0 if not found.
"""
if directory is not None:
fname = os.path.join(directory,filename)
else:
fname... | python | def checkFileExists(filename, directory=None):
"""
Checks to see if file specified exists in current or specified directory.
Default is current directory. Returns 1 if it exists, 0 if not found.
"""
if directory is not None:
fname = os.path.join(directory,filename)
else:
fname... | [
"def",
"checkFileExists",
"(",
"filename",
",",
"directory",
"=",
"None",
")",
":",
"if",
"directory",
"is",
"not",
"None",
":",
"fname",
"=",
"os",
".",
"path",
".",
"join",
"(",
"directory",
",",
"filename",
")",
"else",
":",
"fname",
"=",
"filename"... | Checks to see if file specified exists in current or specified directory.
Default is current directory. Returns 1 if it exists, 0 if not found. | [
"Checks",
"to",
"see",
"if",
"file",
"specified",
"exists",
"in",
"current",
"or",
"specified",
"directory",
"."
] | train | https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/fileutil.py#L1061-L1073 |
spacetelescope/stsci.tools | lib/stsci/tools/fileutil.py | copyFile | def copyFile(input, output, replace=None):
"""Copy a file whole from input to output."""
_found = findFile(output)
if not _found or (_found and replace):
shutil.copy2(input, output) | python | def copyFile(input, output, replace=None):
"""Copy a file whole from input to output."""
_found = findFile(output)
if not _found or (_found and replace):
shutil.copy2(input, output) | [
"def",
"copyFile",
"(",
"input",
",",
"output",
",",
"replace",
"=",
"None",
")",
":",
"_found",
"=",
"findFile",
"(",
"output",
")",
"if",
"not",
"_found",
"or",
"(",
"_found",
"and",
"replace",
")",
":",
"shutil",
".",
"copy2",
"(",
"input",
",",
... | Copy a file whole from input to output. | [
"Copy",
"a",
"file",
"whole",
"from",
"input",
"to",
"output",
"."
] | train | https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/fileutil.py#L1076-L1081 |
spacetelescope/stsci.tools | lib/stsci/tools/fileutil.py | removeFile | def removeFile(inlist):
"""
Utility function for deleting a list of files or a single file.
This function will automatically delete both files of a GEIS image, just
like 'iraf.imdelete'.
"""
if not isinstance(inlist, string_types):
# We do have a list, so delete all filenames in list.
... | python | def removeFile(inlist):
"""
Utility function for deleting a list of files or a single file.
This function will automatically delete both files of a GEIS image, just
like 'iraf.imdelete'.
"""
if not isinstance(inlist, string_types):
# We do have a list, so delete all filenames in list.
... | [
"def",
"removeFile",
"(",
"inlist",
")",
":",
"if",
"not",
"isinstance",
"(",
"inlist",
",",
"string_types",
")",
":",
"# We do have a list, so delete all filenames in list.",
"# Treat like a list of full filenames",
"_ldir",
"=",
"os",
".",
"listdir",
"(",
"'.'",
")"... | Utility function for deleting a list of files or a single file.
This function will automatically delete both files of a GEIS image, just
like 'iraf.imdelete'. | [
"Utility",
"function",
"for",
"deleting",
"a",
"list",
"of",
"files",
"or",
"a",
"single",
"file",
"."
] | train | https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/fileutil.py#L1111-L1138 |
spacetelescope/stsci.tools | lib/stsci/tools/fileutil.py | findKeywordExtn | def findKeywordExtn(ft, keyword, value=None):
"""
This function will return the index of the extension in a multi-extension
FITS file which contains the desired keyword with the given value.
"""
i = 0
extnum = -1
# Search through all the extensions in the FITS object
for chip in ft:
... | python | def findKeywordExtn(ft, keyword, value=None):
"""
This function will return the index of the extension in a multi-extension
FITS file which contains the desired keyword with the given value.
"""
i = 0
extnum = -1
# Search through all the extensions in the FITS object
for chip in ft:
... | [
"def",
"findKeywordExtn",
"(",
"ft",
",",
"keyword",
",",
"value",
"=",
"None",
")",
":",
"i",
"=",
"0",
"extnum",
"=",
"-",
"1",
"# Search through all the extensions in the FITS object",
"for",
"chip",
"in",
"ft",
":",
"hdr",
"=",
"chip",
".",
"header",
"... | This function will return the index of the extension in a multi-extension
FITS file which contains the desired keyword with the given value. | [
"This",
"function",
"will",
"return",
"the",
"index",
"of",
"the",
"extension",
"in",
"a",
"multi",
"-",
"extension",
"FITS",
"file",
"which",
"contains",
"the",
"desired",
"keyword",
"with",
"the",
"given",
"value",
"."
] | train | https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/fileutil.py#L1141-L1166 |
spacetelescope/stsci.tools | lib/stsci/tools/fileutil.py | findExtname | def findExtname(fimg, extname, extver=None):
"""
Returns the list number of the extension corresponding to EXTNAME given.
"""
i = 0
extnum = None
for chip in fimg:
hdr = chip.header
if 'EXTNAME' in hdr:
if hdr['EXTNAME'].strip() == extname.upper():
if... | python | def findExtname(fimg, extname, extver=None):
"""
Returns the list number of the extension corresponding to EXTNAME given.
"""
i = 0
extnum = None
for chip in fimg:
hdr = chip.header
if 'EXTNAME' in hdr:
if hdr['EXTNAME'].strip() == extname.upper():
if... | [
"def",
"findExtname",
"(",
"fimg",
",",
"extname",
",",
"extver",
"=",
"None",
")",
":",
"i",
"=",
"0",
"extnum",
"=",
"None",
"for",
"chip",
"in",
"fimg",
":",
"hdr",
"=",
"chip",
".",
"header",
"if",
"'EXTNAME'",
"in",
"hdr",
":",
"if",
"hdr",
... | Returns the list number of the extension corresponding to EXTNAME given. | [
"Returns",
"the",
"list",
"number",
"of",
"the",
"extension",
"corresponding",
"to",
"EXTNAME",
"given",
"."
] | train | https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/fileutil.py#L1169-L1184 |
spacetelescope/stsci.tools | lib/stsci/tools/fileutil.py | rAsciiLine | def rAsciiLine(ifile):
"""Returns the next non-blank line in an ASCII file."""
_line = ifile.readline().strip()
while len(_line) == 0:
_line = ifile.readline().strip()
return _line | python | def rAsciiLine(ifile):
"""Returns the next non-blank line in an ASCII file."""
_line = ifile.readline().strip()
while len(_line) == 0:
_line = ifile.readline().strip()
return _line | [
"def",
"rAsciiLine",
"(",
"ifile",
")",
":",
"_line",
"=",
"ifile",
".",
"readline",
"(",
")",
".",
"strip",
"(",
")",
"while",
"len",
"(",
"_line",
")",
"==",
"0",
":",
"_line",
"=",
"ifile",
".",
"readline",
"(",
")",
".",
"strip",
"(",
")",
... | Returns the next non-blank line in an ASCII file. | [
"Returns",
"the",
"next",
"non",
"-",
"blank",
"line",
"in",
"an",
"ASCII",
"file",
"."
] | train | https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/fileutil.py#L1187-L1193 |
spacetelescope/stsci.tools | lib/stsci/tools/fileutil.py | listVars | def listVars(prefix="", equals="\t= ", **kw):
"""List IRAF variables."""
keylist = getVarList()
if len(keylist) == 0:
print('No IRAF variables defined')
else:
keylist.sort()
for word in keylist:
print("%s%s%s%s" % (prefix, word, equals, envget(word))) | python | def listVars(prefix="", equals="\t= ", **kw):
"""List IRAF variables."""
keylist = getVarList()
if len(keylist) == 0:
print('No IRAF variables defined')
else:
keylist.sort()
for word in keylist:
print("%s%s%s%s" % (prefix, word, equals, envget(word))) | [
"def",
"listVars",
"(",
"prefix",
"=",
"\"\"",
",",
"equals",
"=",
"\"\\t= \"",
",",
"*",
"*",
"kw",
")",
":",
"keylist",
"=",
"getVarList",
"(",
")",
"if",
"len",
"(",
"keylist",
")",
"==",
"0",
":",
"print",
"(",
"'No IRAF variables defined'",
")",
... | List IRAF variables. | [
"List",
"IRAF",
"variables",
"."
] | train | https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/fileutil.py#L1279-L1288 |
spacetelescope/stsci.tools | lib/stsci/tools/fileutil.py | untranslateName | def untranslateName(s):
"""Undo Python conversion of CL parameter or variable name."""
s = s.replace('DOT', '.')
s = s.replace('DOLLAR', '$')
# delete 'PY' at start of name components
if s[:2] == 'PY': s = s[2:]
s = s.replace('.PY', '.')
return s | python | def untranslateName(s):
"""Undo Python conversion of CL parameter or variable name."""
s = s.replace('DOT', '.')
s = s.replace('DOLLAR', '$')
# delete 'PY' at start of name components
if s[:2] == 'PY': s = s[2:]
s = s.replace('.PY', '.')
return s | [
"def",
"untranslateName",
"(",
"s",
")",
":",
"s",
"=",
"s",
".",
"replace",
"(",
"'DOT'",
",",
"'.'",
")",
"s",
"=",
"s",
".",
"replace",
"(",
"'DOLLAR'",
",",
"'$'",
")",
"# delete 'PY' at start of name components",
"if",
"s",
"[",
":",
"2",
"]",
"... | Undo Python conversion of CL parameter or variable name. | [
"Undo",
"Python",
"conversion",
"of",
"CL",
"parameter",
"or",
"variable",
"name",
"."
] | train | https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/fileutil.py#L1291-L1299 |
spacetelescope/stsci.tools | lib/stsci/tools/fileutil.py | envget | def envget(var, default=None):
"""Get value of IRAF or OS environment variable."""
if 'pyraf' in sys.modules:
#ONLY if pyraf is already loaded, import iraf into the namespace
from pyraf import iraf
else:
# else set iraf to None so it knows to not use iraf's environment
iraf ... | python | def envget(var, default=None):
"""Get value of IRAF or OS environment variable."""
if 'pyraf' in sys.modules:
#ONLY if pyraf is already loaded, import iraf into the namespace
from pyraf import iraf
else:
# else set iraf to None so it knows to not use iraf's environment
iraf ... | [
"def",
"envget",
"(",
"var",
",",
"default",
"=",
"None",
")",
":",
"if",
"'pyraf'",
"in",
"sys",
".",
"modules",
":",
"#ONLY if pyraf is already loaded, import iraf into the namespace",
"from",
"pyraf",
"import",
"iraf",
"else",
":",
"# else set iraf to None so it kn... | Get value of IRAF or OS environment variable. | [
"Get",
"value",
"of",
"IRAF",
"or",
"OS",
"environment",
"variable",
"."
] | train | https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/fileutil.py#L1302-L1333 |
spacetelescope/stsci.tools | lib/stsci/tools/fileutil.py | osfn | def osfn(filename):
"""Convert IRAF virtual path name to OS pathname."""
# Try to emulate the CL version closely:
#
# - expands IRAF virtual file names
# - strips blanks around path components
# - if no slashes or relative paths, return relative pathname
# - otherwise return absolute pathna... | python | def osfn(filename):
"""Convert IRAF virtual path name to OS pathname."""
# Try to emulate the CL version closely:
#
# - expands IRAF virtual file names
# - strips blanks around path components
# - if no slashes or relative paths, return relative pathname
# - otherwise return absolute pathna... | [
"def",
"osfn",
"(",
"filename",
")",
":",
"# Try to emulate the CL version closely:",
"#",
"# - expands IRAF virtual file names",
"# - strips blanks around path components",
"# - if no slashes or relative paths, return relative pathname",
"# - otherwise return absolute pathname",
"if",
"fi... | Convert IRAF virtual path name to OS pathname. | [
"Convert",
"IRAF",
"virtual",
"path",
"name",
"to",
"OS",
"pathname",
"."
] | train | https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/fileutil.py#L1336-L1361 |
spacetelescope/stsci.tools | lib/stsci/tools/fileutil.py | defvar | def defvar(varname):
"""Returns true if CL variable is defined."""
if 'pyraf' in sys.modules:
#ONLY if pyraf is already loaded, import iraf into the namespace
from pyraf import iraf
else:
# else set iraf to None so it knows to not use iraf's environment
iraf = None
if i... | python | def defvar(varname):
"""Returns true if CL variable is defined."""
if 'pyraf' in sys.modules:
#ONLY if pyraf is already loaded, import iraf into the namespace
from pyraf import iraf
else:
# else set iraf to None so it knows to not use iraf's environment
iraf = None
if i... | [
"def",
"defvar",
"(",
"varname",
")",
":",
"if",
"'pyraf'",
"in",
"sys",
".",
"modules",
":",
"#ONLY if pyraf is already loaded, import iraf into the namespace",
"from",
"pyraf",
"import",
"iraf",
"else",
":",
"# else set iraf to None so it knows to not use iraf's environment... | Returns true if CL variable is defined. | [
"Returns",
"true",
"if",
"CL",
"variable",
"is",
"defined",
"."
] | train | https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/fileutil.py#L1364-L1378 |
spacetelescope/stsci.tools | lib/stsci/tools/fileutil.py | set | def set(*args, **kw):
"""Set IRAF environment variables."""
if len(args) == 0:
if len(kw) != 0:
# normal case is only keyword,value pairs
for keyword, value in kw.items():
keyword = untranslateName(keyword)
svalue = str(value)
_var... | python | def set(*args, **kw):
"""Set IRAF environment variables."""
if len(args) == 0:
if len(kw) != 0:
# normal case is only keyword,value pairs
for keyword, value in kw.items():
keyword = untranslateName(keyword)
svalue = str(value)
_var... | [
"def",
"set",
"(",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"if",
"len",
"(",
"args",
")",
"==",
"0",
":",
"if",
"len",
"(",
"kw",
")",
"!=",
"0",
":",
"# normal case is only keyword,value pairs",
"for",
"keyword",
",",
"value",
"in",
"kw",
".",... | Set IRAF environment variables. | [
"Set",
"IRAF",
"environment",
"variables",
"."
] | train | https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/fileutil.py#L1388-L1412 |
spacetelescope/stsci.tools | lib/stsci/tools/fileutil.py | show | def show(*args, **kw):
"""Print value of IRAF or OS environment variables."""
if len(kw):
raise TypeError('unexpected keyword argument: %r' % list(kw))
if args:
for arg in args:
print(envget(arg))
else:
# print them all
listVars(prefix=" ", equals="=") | python | def show(*args, **kw):
"""Print value of IRAF or OS environment variables."""
if len(kw):
raise TypeError('unexpected keyword argument: %r' % list(kw))
if args:
for arg in args:
print(envget(arg))
else:
# print them all
listVars(prefix=" ", equals="=") | [
"def",
"show",
"(",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"if",
"len",
"(",
"kw",
")",
":",
"raise",
"TypeError",
"(",
"'unexpected keyword argument: %r'",
"%",
"list",
"(",
"kw",
")",
")",
"if",
"args",
":",
"for",
"arg",
"in",
"args",
":",
... | Print value of IRAF or OS environment variables. | [
"Print",
"value",
"of",
"IRAF",
"or",
"OS",
"environment",
"variables",
"."
] | train | https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/fileutil.py#L1419-L1430 |
spacetelescope/stsci.tools | lib/stsci/tools/fileutil.py | unset | def unset(*args, **kw):
"""
Unset IRAF environment variables.
This is not a standard IRAF task, but it is obviously useful. It makes the
resulting variables undefined. It silently ignores variables that are not
defined. It does not change the os environment variables.
"""
if len(kw) != ... | python | def unset(*args, **kw):
"""
Unset IRAF environment variables.
This is not a standard IRAF task, but it is obviously useful. It makes the
resulting variables undefined. It silently ignores variables that are not
defined. It does not change the os environment variables.
"""
if len(kw) != ... | [
"def",
"unset",
"(",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"if",
"len",
"(",
"kw",
")",
"!=",
"0",
":",
"raise",
"SyntaxError",
"(",
"\"unset requires a list of variable names\"",
")",
"for",
"arg",
"in",
"args",
":",
"if",
"arg",
"in",
"_varDict... | Unset IRAF environment variables.
This is not a standard IRAF task, but it is obviously useful. It makes the
resulting variables undefined. It silently ignores variables that are not
defined. It does not change the os environment variables. | [
"Unset",
"IRAF",
"environment",
"variables",
"."
] | train | https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/fileutil.py#L1433-L1447 |
spacetelescope/stsci.tools | lib/stsci/tools/fileutil.py | Expand | def Expand(instring, noerror=0):
"""
Expand a string with embedded IRAF variables (IRAF virtual filename).
Allows comma-separated lists. Also uses os.path.expanduser to replace '~'
symbols.
Set the noerror flag to silently replace undefined variables with just the
variable name or null (so Ex... | python | def Expand(instring, noerror=0):
"""
Expand a string with embedded IRAF variables (IRAF virtual filename).
Allows comma-separated lists. Also uses os.path.expanduser to replace '~'
symbols.
Set the noerror flag to silently replace undefined variables with just the
variable name or null (so Ex... | [
"def",
"Expand",
"(",
"instring",
",",
"noerror",
"=",
"0",
")",
":",
"# call _expand1 for each entry in comma-separated list",
"wordlist",
"=",
"instring",
".",
"split",
"(",
"\",\"",
")",
"outlist",
"=",
"[",
"]",
"for",
"word",
"in",
"wordlist",
":",
"outli... | Expand a string with embedded IRAF variables (IRAF virtual filename).
Allows comma-separated lists. Also uses os.path.expanduser to replace '~'
symbols.
Set the noerror flag to silently replace undefined variables with just the
variable name or null (so Expand('abc$def') = 'abcdef' and
Expand('(a... | [
"Expand",
"a",
"string",
"with",
"embedded",
"IRAF",
"variables",
"(",
"IRAF",
"virtual",
"filename",
")",
"."
] | train | https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/fileutil.py#L1478-L1496 |
spacetelescope/stsci.tools | lib/stsci/tools/fileutil.py | _expand1 | def _expand1(instring, noerror):
"""Expand a string with embedded IRAF variables (IRAF virtual filename)."""
# first expand names in parentheses
# note this works on nested names too, expanding from the
# inside out (just like IRAF)
mm = __re_var_paren.search(instring)
while mm is not None:
... | python | def _expand1(instring, noerror):
"""Expand a string with embedded IRAF variables (IRAF virtual filename)."""
# first expand names in parentheses
# note this works on nested names too, expanding from the
# inside out (just like IRAF)
mm = __re_var_paren.search(instring)
while mm is not None:
... | [
"def",
"_expand1",
"(",
"instring",
",",
"noerror",
")",
":",
"# first expand names in parentheses",
"# note this works on nested names too, expanding from the",
"# inside out (just like IRAF)",
"mm",
"=",
"__re_var_paren",
".",
"search",
"(",
"instring",
")",
"while",
"mm",
... | Expand a string with embedded IRAF variables (IRAF virtual filename). | [
"Expand",
"a",
"string",
"with",
"embedded",
"IRAF",
"variables",
"(",
"IRAF",
"virtual",
"filename",
")",
"."
] | train | https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/fileutil.py#L1499-L1535 |
fitnr/convertdate | convertdate/julian.py | legal_date | def legal_date(year, month, day):
'''Check if this is a legal date in the Julian calendar'''
daysinmonth = month_length(year, month)
if not (0 < day <= daysinmonth):
raise ValueError("Month {} doesn't have a day {}".format(month, day))
return True | python | def legal_date(year, month, day):
'''Check if this is a legal date in the Julian calendar'''
daysinmonth = month_length(year, month)
if not (0 < day <= daysinmonth):
raise ValueError("Month {} doesn't have a day {}".format(month, day))
return True | [
"def",
"legal_date",
"(",
"year",
",",
"month",
",",
"day",
")",
":",
"daysinmonth",
"=",
"month_length",
"(",
"year",
",",
"month",
")",
"if",
"not",
"(",
"0",
"<",
"day",
"<=",
"daysinmonth",
")",
":",
"raise",
"ValueError",
"(",
"\"Month {} doesn't ha... | Check if this is a legal date in the Julian calendar | [
"Check",
"if",
"this",
"is",
"a",
"legal",
"date",
"in",
"the",
"Julian",
"calendar"
] | train | https://github.com/fitnr/convertdate/blob/e920f168a87f99183b0aa7290d6c3af222582d43/convertdate/julian.py#L42-L49 |
fitnr/convertdate | convertdate/julian.py | from_jd | def from_jd(jd):
'''Calculate Julian calendar date from Julian day'''
jd += 0.5
z = trunc(jd)
a = z
b = a + 1524
c = trunc((b - 122.1) / 365.25)
d = trunc(365.25 * c)
e = trunc((b - d) / 30.6001)
if trunc(e < 14):
month = e - 1
else:
month = e - 13
if trun... | python | def from_jd(jd):
'''Calculate Julian calendar date from Julian day'''
jd += 0.5
z = trunc(jd)
a = z
b = a + 1524
c = trunc((b - 122.1) / 365.25)
d = trunc(365.25 * c)
e = trunc((b - d) / 30.6001)
if trunc(e < 14):
month = e - 1
else:
month = e - 13
if trun... | [
"def",
"from_jd",
"(",
"jd",
")",
":",
"jd",
"+=",
"0.5",
"z",
"=",
"trunc",
"(",
"jd",
")",
"a",
"=",
"z",
"b",
"=",
"a",
"+",
"1524",
"c",
"=",
"trunc",
"(",
"(",
"b",
"-",
"122.1",
")",
"/",
"365.25",
")",
"d",
"=",
"trunc",
"(",
"365.... | Calculate Julian calendar date from Julian day | [
"Calculate",
"Julian",
"calendar",
"date",
"from",
"Julian",
"day"
] | train | https://github.com/fitnr/convertdate/blob/e920f168a87f99183b0aa7290d6c3af222582d43/convertdate/julian.py#L52-L76 |
fitnr/convertdate | convertdate/julian.py | to_jd | def to_jd(year, month, day):
'''Convert to Julian day using astronomical years (0 = 1 BC, -1 = 2 BC)'''
legal_date(year, month, day)
# Algorithm as given in Meeus, Astronomical Algorithms, Chapter 7, page 61
if month <= 2:
year -= 1
month += 12
return (trunc((365.25 * (year + 471... | python | def to_jd(year, month, day):
'''Convert to Julian day using astronomical years (0 = 1 BC, -1 = 2 BC)'''
legal_date(year, month, day)
# Algorithm as given in Meeus, Astronomical Algorithms, Chapter 7, page 61
if month <= 2:
year -= 1
month += 12
return (trunc((365.25 * (year + 471... | [
"def",
"to_jd",
"(",
"year",
",",
"month",
",",
"day",
")",
":",
"legal_date",
"(",
"year",
",",
"month",
",",
"day",
")",
"# Algorithm as given in Meeus, Astronomical Algorithms, Chapter 7, page 61",
"if",
"month",
"<=",
"2",
":",
"year",
"-=",
"1",
"month",
... | Convert to Julian day using astronomical years (0 = 1 BC, -1 = 2 BC) | [
"Convert",
"to",
"Julian",
"day",
"using",
"astronomical",
"years",
"(",
"0",
"=",
"1",
"BC",
"-",
"1",
"=",
"2",
"BC",
")"
] | train | https://github.com/fitnr/convertdate/blob/e920f168a87f99183b0aa7290d6c3af222582d43/convertdate/julian.py#L79-L90 |
fitnr/convertdate | convertdate/hebrew.py | delay_1 | def delay_1(year):
'''Test for delay of start of new year and to avoid'''
# Sunday, Wednesday, and Friday as start of the new year.
months = trunc(((235 * year) - 234) / 19)
parts = 12084 + (13753 * months)
day = trunc((months * 29) + parts / 25920)
if ((3 * (day + 1)) % 7) < 3:
day += ... | python | def delay_1(year):
'''Test for delay of start of new year and to avoid'''
# Sunday, Wednesday, and Friday as start of the new year.
months = trunc(((235 * year) - 234) / 19)
parts = 12084 + (13753 * months)
day = trunc((months * 29) + parts / 25920)
if ((3 * (day + 1)) % 7) < 3:
day += ... | [
"def",
"delay_1",
"(",
"year",
")",
":",
"# Sunday, Wednesday, and Friday as start of the new year.",
"months",
"=",
"trunc",
"(",
"(",
"(",
"235",
"*",
"year",
")",
"-",
"234",
")",
"/",
"19",
")",
"parts",
"=",
"12084",
"+",
"(",
"13753",
"*",
"months",
... | Test for delay of start of new year and to avoid | [
"Test",
"for",
"delay",
"of",
"start",
"of",
"new",
"year",
"and",
"to",
"avoid"
] | train | https://github.com/fitnr/convertdate/blob/e920f168a87f99183b0aa7290d6c3af222582d43/convertdate/hebrew.py#L46-L56 |
fitnr/convertdate | convertdate/hebrew.py | delay_2 | def delay_2(year):
'''Check for delay in start of new year due to length of adjacent years'''
last = delay_1(year - 1)
present = delay_1(year)
next_ = delay_1(year + 1)
if next_ - present == 356:
return 2
elif present - last == 382:
return 1
else:
return 0 | python | def delay_2(year):
'''Check for delay in start of new year due to length of adjacent years'''
last = delay_1(year - 1)
present = delay_1(year)
next_ = delay_1(year + 1)
if next_ - present == 356:
return 2
elif present - last == 382:
return 1
else:
return 0 | [
"def",
"delay_2",
"(",
"year",
")",
":",
"last",
"=",
"delay_1",
"(",
"year",
"-",
"1",
")",
"present",
"=",
"delay_1",
"(",
"year",
")",
"next_",
"=",
"delay_1",
"(",
"year",
"+",
"1",
")",
"if",
"next_",
"-",
"present",
"==",
"356",
":",
"retur... | Check for delay in start of new year due to length of adjacent years | [
"Check",
"for",
"delay",
"in",
"start",
"of",
"new",
"year",
"due",
"to",
"length",
"of",
"adjacent",
"years"
] | train | https://github.com/fitnr/convertdate/blob/e920f168a87f99183b0aa7290d6c3af222582d43/convertdate/hebrew.py#L59-L71 |
fitnr/convertdate | convertdate/hebrew.py | month_days | def month_days(year, month):
'''How many days are in a given month of a given year'''
if month > 13:
raise ValueError("Incorrect month index")
# First of all, dispose of fixed-length 29 day months
if month in (IYYAR, TAMMUZ, ELUL, TEVETH, VEADAR):
return 29
# If it's not a leap yea... | python | def month_days(year, month):
'''How many days are in a given month of a given year'''
if month > 13:
raise ValueError("Incorrect month index")
# First of all, dispose of fixed-length 29 day months
if month in (IYYAR, TAMMUZ, ELUL, TEVETH, VEADAR):
return 29
# If it's not a leap yea... | [
"def",
"month_days",
"(",
"year",
",",
"month",
")",
":",
"if",
"month",
">",
"13",
":",
"raise",
"ValueError",
"(",
"\"Incorrect month index\"",
")",
"# First of all, dispose of fixed-length 29 day months",
"if",
"month",
"in",
"(",
"IYYAR",
",",
"TAMMUZ",
",",
... | How many days are in a given month of a given year | [
"How",
"many",
"days",
"are",
"in",
"a",
"given",
"month",
"of",
"a",
"given",
"year"
] | train | https://github.com/fitnr/convertdate/blob/e920f168a87f99183b0aa7290d6c3af222582d43/convertdate/hebrew.py#L79-L101 |
spacetelescope/stsci.tools | lib/stsci/tools/swapgeis.py | byteswap | def byteswap(input,output=None,clobber=True):
"""Input GEIS files "input" will be read and converted to a new GEIS file
whose byte-order has been swapped from its original state.
Parameters
----------
input - str
Full filename with path of input GEIS image header file
output - str
... | python | def byteswap(input,output=None,clobber=True):
"""Input GEIS files "input" will be read and converted to a new GEIS file
whose byte-order has been swapped from its original state.
Parameters
----------
input - str
Full filename with path of input GEIS image header file
output - str
... | [
"def",
"byteswap",
"(",
"input",
",",
"output",
"=",
"None",
",",
"clobber",
"=",
"True",
")",
":",
"global",
"dat",
"cardLen",
"=",
"fits",
".",
"Card",
".",
"length",
"# input file(s) must be of the form *.??h and *.??d",
"if",
"input",
"[",
"-",
"1",
"]",... | Input GEIS files "input" will be read and converted to a new GEIS file
whose byte-order has been swapped from its original state.
Parameters
----------
input - str
Full filename with path of input GEIS image header file
output - str
Full filename with path of output GEIS image head... | [
"Input",
"GEIS",
"files",
"input",
"will",
"be",
"read",
"and",
"converted",
"to",
"a",
"new",
"GEIS",
"file",
"whose",
"byte",
"-",
"order",
"has",
"been",
"swapped",
"from",
"its",
"original",
"state",
"."
] | train | https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/swapgeis.py#L92-L515 |
3ll3d00d/vibe | backend/src/recorder/common/accelerometer.py | Accelerometer.start | def start(self, measurementId, durationInSeconds=None):
"""
Initialises the device if required then enters a read loop taking data from the provider and passing it to the
handler. It will continue until either breakRead is true or the duration (if provided) has passed.
:return:
... | python | def start(self, measurementId, durationInSeconds=None):
"""
Initialises the device if required then enters a read loop taking data from the provider and passing it to the
handler. It will continue until either breakRead is true or the duration (if provided) has passed.
:return:
... | [
"def",
"start",
"(",
"self",
",",
"measurementId",
",",
"durationInSeconds",
"=",
"None",
")",
":",
"logger",
".",
"info",
"(",
"\">> measurement \"",
"+",
"measurementId",
"+",
"(",
"(",
"\" for \"",
"+",
"str",
"(",
"durationInSeconds",
")",
")",
"if",
"... | Initialises the device if required then enters a read loop taking data from the provider and passing it to the
handler. It will continue until either breakRead is true or the duration (if provided) has passed.
:return: | [
"Initialises",
"the",
"device",
"if",
"required",
"then",
"enters",
"a",
"read",
"loop",
"taking",
"data",
"from",
"the",
"provider",
"and",
"passing",
"it",
"to",
"the",
"handler",
".",
"It",
"will",
"continue",
"until",
"either",
"breakRead",
"is",
"true",... | train | https://github.com/3ll3d00d/vibe/blob/124b029f13ac746723e92cb47e9cb56edd2e54b5/backend/src/recorder/common/accelerometer.py#L66-L115 |
3ll3d00d/vibe | backend/src/analyser/resources/target.py | Target.get | def get(self, targetId):
"""
Yields the analysed wav data.
:param targetId:
:return:
"""
result = self._targetController.analyse(targetId)
if result:
if len(result) == 2:
if result[1] == 404:
return result
... | python | def get(self, targetId):
"""
Yields the analysed wav data.
:param targetId:
:return:
"""
result = self._targetController.analyse(targetId)
if result:
if len(result) == 2:
if result[1] == 404:
return result
... | [
"def",
"get",
"(",
"self",
",",
"targetId",
")",
":",
"result",
"=",
"self",
".",
"_targetController",
".",
"analyse",
"(",
"targetId",
")",
"if",
"result",
":",
"if",
"len",
"(",
"result",
")",
"==",
"2",
":",
"if",
"result",
"[",
"1",
"]",
"==",
... | Yields the analysed wav data.
:param targetId:
:return: | [
"Yields",
"the",
"analysed",
"wav",
"data",
".",
":",
"param",
"targetId",
":",
":",
"return",
":"
] | train | https://github.com/3ll3d00d/vibe/blob/124b029f13ac746723e92cb47e9cb56edd2e54b5/backend/src/analyser/resources/target.py#L13-L29 |
3ll3d00d/vibe | backend/src/analyser/resources/target.py | Target.put | def put(self, targetId):
"""
stores a new target.
:param targetId: the target to store.
:return:
"""
json = request.get_json()
if 'hinge' in json:
logger.info('Storing target ' + targetId)
if self._targetController.storeFromHinge(targetId, ... | python | def put(self, targetId):
"""
stores a new target.
:param targetId: the target to store.
:return:
"""
json = request.get_json()
if 'hinge' in json:
logger.info('Storing target ' + targetId)
if self._targetController.storeFromHinge(targetId, ... | [
"def",
"put",
"(",
"self",
",",
"targetId",
")",
":",
"json",
"=",
"request",
".",
"get_json",
"(",
")",
"if",
"'hinge'",
"in",
"json",
":",
"logger",
".",
"info",
"(",
"'Storing target '",
"+",
"targetId",
")",
"if",
"self",
".",
"_targetController",
... | stores a new target.
:param targetId: the target to store.
:return: | [
"stores",
"a",
"new",
"target",
".",
":",
"param",
"targetId",
":",
"the",
"target",
"to",
"store",
".",
":",
"return",
":"
] | train | https://github.com/3ll3d00d/vibe/blob/124b029f13ac746723e92cb47e9cb56edd2e54b5/backend/src/analyser/resources/target.py#L31-L46 |
fitnr/convertdate | convertdate/julianday.py | to_datetime | def to_datetime(jdc):
'''Return a datetime for the input floating point Julian Day Count'''
year, month, day = gregorian.from_jd(jdc)
# in jdc: 0.0 = noon, 0.5 = midnight
# the 0.5 changes it to 0.0 = midnight, 0.5 = noon
frac = (jdc + 0.5) % 1
hours = int(24 * frac)
mfrac = frac * 24 - h... | python | def to_datetime(jdc):
'''Return a datetime for the input floating point Julian Day Count'''
year, month, day = gregorian.from_jd(jdc)
# in jdc: 0.0 = noon, 0.5 = midnight
# the 0.5 changes it to 0.0 = midnight, 0.5 = noon
frac = (jdc + 0.5) % 1
hours = int(24 * frac)
mfrac = frac * 24 - h... | [
"def",
"to_datetime",
"(",
"jdc",
")",
":",
"year",
",",
"month",
",",
"day",
"=",
"gregorian",
".",
"from_jd",
"(",
"jdc",
")",
"# in jdc: 0.0 = noon, 0.5 = midnight",
"# the 0.5 changes it to 0.0 = midnight, 0.5 = noon",
"frac",
"=",
"(",
"jdc",
"+",
"0.5",
")",... | Return a datetime for the input floating point Julian Day Count | [
"Return",
"a",
"datetime",
"for",
"the",
"input",
"floating",
"point",
"Julian",
"Day",
"Count"
] | train | https://github.com/fitnr/convertdate/blob/e920f168a87f99183b0aa7290d6c3af222582d43/convertdate/julianday.py#L16-L37 |
silverlogic/djangorestframework-expander | expander/parse_qs.py | dict_from_qs | def dict_from_qs(qs):
''' Slightly introverted parser for lists of dot-notation nested fields
i.e. "period.di,period.fhr" => {"period": {"di": {}, "fhr": {}}}
'''
entries = qs.split(',') if qs.strip() else []
entries = [entry.strip() for entry in entries]
def _dict_from_qs(line, d):
... | python | def dict_from_qs(qs):
''' Slightly introverted parser for lists of dot-notation nested fields
i.e. "period.di,period.fhr" => {"period": {"di": {}, "fhr": {}}}
'''
entries = qs.split(',') if qs.strip() else []
entries = [entry.strip() for entry in entries]
def _dict_from_qs(line, d):
... | [
"def",
"dict_from_qs",
"(",
"qs",
")",
":",
"entries",
"=",
"qs",
".",
"split",
"(",
"','",
")",
"if",
"qs",
".",
"strip",
"(",
")",
"else",
"[",
"]",
"entries",
"=",
"[",
"entry",
".",
"strip",
"(",
")",
"for",
"entry",
"in",
"entries",
"]",
"... | Slightly introverted parser for lists of dot-notation nested fields
i.e. "period.di,period.fhr" => {"period": {"di": {}, "fhr": {}}} | [
"Slightly",
"introverted",
"parser",
"for",
"lists",
"of",
"dot",
"-",
"notation",
"nested",
"fields",
"i",
".",
"e",
".",
"period",
".",
"di",
"period",
".",
"fhr",
"=",
">",
"{",
"period",
":",
"{",
"di",
":",
"{}",
"fhr",
":",
"{}",
"}}"
] | train | https://github.com/silverlogic/djangorestframework-expander/blob/b1cf60c7076169cbd6ad65350841c86080564f97/expander/parse_qs.py#L5-L26 |
silverlogic/djangorestframework-expander | expander/parse_qs.py | qs_from_dict | def qs_from_dict(qsdict, prefix=""):
''' Same as dict_from_qs, but in reverse
i.e. {"period": {"di": {}, "fhr": {}}} => "period.di,period.fhr"
'''
prefix = prefix + '.' if prefix else ""
def descend(qsd):
for key, val in sorted(qsd.items()):
if val:
yield qs_... | python | def qs_from_dict(qsdict, prefix=""):
''' Same as dict_from_qs, but in reverse
i.e. {"period": {"di": {}, "fhr": {}}} => "period.di,period.fhr"
'''
prefix = prefix + '.' if prefix else ""
def descend(qsd):
for key, val in sorted(qsd.items()):
if val:
yield qs_... | [
"def",
"qs_from_dict",
"(",
"qsdict",
",",
"prefix",
"=",
"\"\"",
")",
":",
"prefix",
"=",
"prefix",
"+",
"'.'",
"if",
"prefix",
"else",
"\"\"",
"def",
"descend",
"(",
"qsd",
")",
":",
"for",
"key",
",",
"val",
"in",
"sorted",
"(",
"qsd",
".",
"ite... | Same as dict_from_qs, but in reverse
i.e. {"period": {"di": {}, "fhr": {}}} => "period.di,period.fhr" | [
"Same",
"as",
"dict_from_qs",
"but",
"in",
"reverse",
"i",
".",
"e",
".",
"{",
"period",
":",
"{",
"di",
":",
"{}",
"fhr",
":",
"{}",
"}}",
"=",
">",
"period",
".",
"di",
"period",
".",
"fhr"
] | train | https://github.com/silverlogic/djangorestframework-expander/blob/b1cf60c7076169cbd6ad65350841c86080564f97/expander/parse_qs.py#L29-L41 |
flukso/tmpo-py | tmpo/__init__.py | dbcon | def dbcon(func):
"""Set up connection before executing function, commit and close connection
afterwards. Unless a connection already has been created."""
@wraps(func)
def wrapper(*args, **kwargs):
self = args[0]
if self.dbcon is None:
# set up connection
self.dbco... | python | def dbcon(func):
"""Set up connection before executing function, commit and close connection
afterwards. Unless a connection already has been created."""
@wraps(func)
def wrapper(*args, **kwargs):
self = args[0]
if self.dbcon is None:
# set up connection
self.dbco... | [
"def",
"dbcon",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
"=",
"args",
"[",
"0",
"]",
"if",
"self",
".",
"dbcon",
"is",
"None",
":",
"# set up connection"... | Set up connection before executing function, commit and close connection
afterwards. Unless a connection already has been created. | [
"Set",
"up",
"connection",
"before",
"executing",
"function",
"commit",
"and",
"close",
"connection",
"afterwards",
".",
"Unless",
"a",
"connection",
"already",
"has",
"been",
"created",
"."
] | train | https://github.com/flukso/tmpo-py/blob/3c99e3d123bc985a6fba2558922b29430d2a0a94/tmpo/__init__.py#L142-L175 |
flukso/tmpo-py | tmpo/__init__.py | Session.add | def add(self, sid, token):
"""
Add new sensor to the database
Parameters
----------
sid : str
SensorId
token : str
"""
try:
self.dbcur.execute(SQL_SENSOR_INS, (sid, token))
except sqlite3.IntegrityError: # sensor entry exi... | python | def add(self, sid, token):
"""
Add new sensor to the database
Parameters
----------
sid : str
SensorId
token : str
"""
try:
self.dbcur.execute(SQL_SENSOR_INS, (sid, token))
except sqlite3.IntegrityError: # sensor entry exi... | [
"def",
"add",
"(",
"self",
",",
"sid",
",",
"token",
")",
":",
"try",
":",
"self",
".",
"dbcur",
".",
"execute",
"(",
"SQL_SENSOR_INS",
",",
"(",
"sid",
",",
"token",
")",
")",
"except",
"sqlite3",
".",
"IntegrityError",
":",
"# sensor entry exists",
"... | Add new sensor to the database
Parameters
----------
sid : str
SensorId
token : str | [
"Add",
"new",
"sensor",
"to",
"the",
"database"
] | train | https://github.com/flukso/tmpo-py/blob/3c99e3d123bc985a6fba2558922b29430d2a0a94/tmpo/__init__.py#L213-L226 |
flukso/tmpo-py | tmpo/__init__.py | Session.remove | def remove(self, sid):
"""
Remove sensor from the database
Parameters
----------
sid : str
SensorID
"""
self.dbcur.execute(SQL_SENSOR_DEL, (sid,))
self.dbcur.execute(SQL_TMPO_DEL, (sid,)) | python | def remove(self, sid):
"""
Remove sensor from the database
Parameters
----------
sid : str
SensorID
"""
self.dbcur.execute(SQL_SENSOR_DEL, (sid,))
self.dbcur.execute(SQL_TMPO_DEL, (sid,)) | [
"def",
"remove",
"(",
"self",
",",
"sid",
")",
":",
"self",
".",
"dbcur",
".",
"execute",
"(",
"SQL_SENSOR_DEL",
",",
"(",
"sid",
",",
")",
")",
"self",
".",
"dbcur",
".",
"execute",
"(",
"SQL_TMPO_DEL",
",",
"(",
"sid",
",",
")",
")"
] | Remove sensor from the database
Parameters
----------
sid : str
SensorID | [
"Remove",
"sensor",
"from",
"the",
"database"
] | train | https://github.com/flukso/tmpo-py/blob/3c99e3d123bc985a6fba2558922b29430d2a0a94/tmpo/__init__.py#L229-L239 |
flukso/tmpo-py | tmpo/__init__.py | Session.sync | def sync(self, *sids):
"""
Synchronise data
Parameters
----------
sids : list of str
SensorIDs to sync
Optional, leave empty to sync everything
"""
if sids == ():
sids = [sid for (sid,) in self.dbcur.execute(SQL_SENSOR_ALL)]
... | python | def sync(self, *sids):
"""
Synchronise data
Parameters
----------
sids : list of str
SensorIDs to sync
Optional, leave empty to sync everything
"""
if sids == ():
sids = [sid for (sid,) in self.dbcur.execute(SQL_SENSOR_ALL)]
... | [
"def",
"sync",
"(",
"self",
",",
"*",
"sids",
")",
":",
"if",
"sids",
"==",
"(",
")",
":",
"sids",
"=",
"[",
"sid",
"for",
"(",
"sid",
",",
")",
"in",
"self",
".",
"dbcur",
".",
"execute",
"(",
"SQL_SENSOR_ALL",
")",
"]",
"for",
"sid",
"in",
... | Synchronise data
Parameters
----------
sids : list of str
SensorIDs to sync
Optional, leave empty to sync everything | [
"Synchronise",
"data"
] | train | https://github.com/flukso/tmpo-py/blob/3c99e3d123bc985a6fba2558922b29430d2a0a94/tmpo/__init__.py#L254-L277 |
flukso/tmpo-py | tmpo/__init__.py | Session.list | def list(self, *sids):
"""
List all tmpo-blocks in the database
Parameters
----------
sids : list of str
SensorID's for which to list blocks
Optional, leave empty to get them all
Returns
-------
list[list[tuple]]
"""
... | python | def list(self, *sids):
"""
List all tmpo-blocks in the database
Parameters
----------
sids : list of str
SensorID's for which to list blocks
Optional, leave empty to get them all
Returns
-------
list[list[tuple]]
"""
... | [
"def",
"list",
"(",
"self",
",",
"*",
"sids",
")",
":",
"if",
"sids",
"==",
"(",
")",
":",
"sids",
"=",
"[",
"sid",
"for",
"(",
"sid",
",",
")",
"in",
"self",
".",
"dbcur",
".",
"execute",
"(",
"SQL_SENSOR_ALL",
")",
"]",
"slist",
"=",
"[",
"... | List all tmpo-blocks in the database
Parameters
----------
sids : list of str
SensorID's for which to list blocks
Optional, leave empty to get them all
Returns
-------
list[list[tuple]] | [
"List",
"all",
"tmpo",
"-",
"blocks",
"in",
"the",
"database"
] | train | https://github.com/flukso/tmpo-py/blob/3c99e3d123bc985a6fba2558922b29430d2a0a94/tmpo/__init__.py#L280-L304 |
flukso/tmpo-py | tmpo/__init__.py | Session.series | def series(self, sid, recycle_id=None, head=None, tail=None,
datetime=True):
"""
Create data Series
Parameters
----------
sid : str
recycle_id : optional
head : int | pandas.Timestamp, optional
Start of the interval
default ... | python | def series(self, sid, recycle_id=None, head=None, tail=None,
datetime=True):
"""
Create data Series
Parameters
----------
sid : str
recycle_id : optional
head : int | pandas.Timestamp, optional
Start of the interval
default ... | [
"def",
"series",
"(",
"self",
",",
"sid",
",",
"recycle_id",
"=",
"None",
",",
"head",
"=",
"None",
",",
"tail",
"=",
"None",
",",
"datetime",
"=",
"True",
")",
":",
"if",
"head",
"is",
"None",
":",
"head",
"=",
"0",
"else",
":",
"head",
"=",
"... | Create data Series
Parameters
----------
sid : str
recycle_id : optional
head : int | pandas.Timestamp, optional
Start of the interval
default earliest available
tail : int | pandas.Timestamp, optional
End of the interval
d... | [
"Create",
"data",
"Series"
] | train | https://github.com/flukso/tmpo-py/blob/3c99e3d123bc985a6fba2558922b29430d2a0a94/tmpo/__init__.py#L307-L357 |
flukso/tmpo-py | tmpo/__init__.py | Session.dataframe | def dataframe(self, sids, head=0, tail=EPOCHS_MAX, datetime=True):
"""
Create data frame
Parameters
----------
sids : list[str]
head : int | pandas.Timestamp, optional
Start of the interval
default earliest available
tail : int | pandas.Ti... | python | def dataframe(self, sids, head=0, tail=EPOCHS_MAX, datetime=True):
"""
Create data frame
Parameters
----------
sids : list[str]
head : int | pandas.Timestamp, optional
Start of the interval
default earliest available
tail : int | pandas.Ti... | [
"def",
"dataframe",
"(",
"self",
",",
"sids",
",",
"head",
"=",
"0",
",",
"tail",
"=",
"EPOCHS_MAX",
",",
"datetime",
"=",
"True",
")",
":",
"if",
"head",
"is",
"None",
":",
"head",
"=",
"0",
"else",
":",
"head",
"=",
"self",
".",
"_2epochs",
"("... | Create data frame
Parameters
----------
sids : list[str]
head : int | pandas.Timestamp, optional
Start of the interval
default earliest available
tail : int | pandas.Timestamp, optional
End of the interval
default max epoch
... | [
"Create",
"data",
"frame"
] | train | https://github.com/flukso/tmpo-py/blob/3c99e3d123bc985a6fba2558922b29430d2a0a94/tmpo/__init__.py#L360-L396 |
flukso/tmpo-py | tmpo/__init__.py | Session.first_timestamp | def first_timestamp(self, sid, epoch=False):
"""
Get the first available timestamp for a sensor
Parameters
----------
sid : str
SensorID
epoch : bool
default False
If True return as epoch
If False return as pd.Timestamp
... | python | def first_timestamp(self, sid, epoch=False):
"""
Get the first available timestamp for a sensor
Parameters
----------
sid : str
SensorID
epoch : bool
default False
If True return as epoch
If False return as pd.Timestamp
... | [
"def",
"first_timestamp",
"(",
"self",
",",
"sid",
",",
"epoch",
"=",
"False",
")",
":",
"first_block",
"=",
"self",
".",
"dbcur",
".",
"execute",
"(",
"SQL_TMPO_FIRST",
",",
"(",
"sid",
",",
")",
")",
".",
"fetchone",
"(",
")",
"if",
"first_block",
... | Get the first available timestamp for a sensor
Parameters
----------
sid : str
SensorID
epoch : bool
default False
If True return as epoch
If False return as pd.Timestamp
Returns
-------
pd.Timestamp | int | [
"Get",
"the",
"first",
"available",
"timestamp",
"for",
"a",
"sensor"
] | train | https://github.com/flukso/tmpo-py/blob/3c99e3d123bc985a6fba2558922b29430d2a0a94/tmpo/__init__.py#L399-L424 |
flukso/tmpo-py | tmpo/__init__.py | Session.last_timestamp | def last_timestamp(self, sid, epoch=False):
"""
Get the theoretical last timestamp for a sensor
Parameters
----------
sid : str
SensorID
epoch : bool
default False
If True return as epoch
If False return as pd.Timestamp
... | python | def last_timestamp(self, sid, epoch=False):
"""
Get the theoretical last timestamp for a sensor
Parameters
----------
sid : str
SensorID
epoch : bool
default False
If True return as epoch
If False return as pd.Timestamp
... | [
"def",
"last_timestamp",
"(",
"self",
",",
"sid",
",",
"epoch",
"=",
"False",
")",
":",
"timestamp",
",",
"value",
"=",
"self",
".",
"last_datapoint",
"(",
"sid",
",",
"epoch",
")",
"return",
"timestamp"
] | Get the theoretical last timestamp for a sensor
Parameters
----------
sid : str
SensorID
epoch : bool
default False
If True return as epoch
If False return as pd.Timestamp
Returns
-------
pd.Timestamp | int | [
"Get",
"the",
"theoretical",
"last",
"timestamp",
"for",
"a",
"sensor"
] | train | https://github.com/flukso/tmpo-py/blob/3c99e3d123bc985a6fba2558922b29430d2a0a94/tmpo/__init__.py#L426-L444 |
flukso/tmpo-py | tmpo/__init__.py | Session.last_datapoint | def last_datapoint(self, sid, epoch=False):
"""
Parameters
----------
sid : str
SensorId
epoch : bool
default False
If True return as epoch
If False return as pd.Timestamp
Returns
-------
pd.Timestamp | int,... | python | def last_datapoint(self, sid, epoch=False):
"""
Parameters
----------
sid : str
SensorId
epoch : bool
default False
If True return as epoch
If False return as pd.Timestamp
Returns
-------
pd.Timestamp | int,... | [
"def",
"last_datapoint",
"(",
"self",
",",
"sid",
",",
"epoch",
"=",
"False",
")",
":",
"block",
"=",
"self",
".",
"_last_block",
"(",
"sid",
")",
"if",
"block",
"is",
"None",
":",
"return",
"None",
",",
"None",
"header",
"=",
"block",
"[",
"'h'",
... | Parameters
----------
sid : str
SensorId
epoch : bool
default False
If True return as epoch
If False return as pd.Timestamp
Returns
-------
pd.Timestamp | int, float | [
"Parameters",
"----------",
"sid",
":",
"str",
"SensorId",
"epoch",
":",
"bool",
"default",
"False",
"If",
"True",
"return",
"as",
"epoch",
"If",
"False",
"return",
"as",
"pd",
".",
"Timestamp"
] | train | https://github.com/flukso/tmpo-py/blob/3c99e3d123bc985a6fba2558922b29430d2a0a94/tmpo/__init__.py#L446-L472 |
flukso/tmpo-py | tmpo/__init__.py | Session._npdelta | def _npdelta(self, a, delta):
"""Numpy: Modifying Array Values
http://docs.scipy.org/doc/numpy/reference/arrays.nditer.html"""
for x in np.nditer(a, op_flags=["readwrite"]):
delta += x
x[...] = delta
return a | python | def _npdelta(self, a, delta):
"""Numpy: Modifying Array Values
http://docs.scipy.org/doc/numpy/reference/arrays.nditer.html"""
for x in np.nditer(a, op_flags=["readwrite"]):
delta += x
x[...] = delta
return a | [
"def",
"_npdelta",
"(",
"self",
",",
"a",
",",
"delta",
")",
":",
"for",
"x",
"in",
"np",
".",
"nditer",
"(",
"a",
",",
"op_flags",
"=",
"[",
"\"readwrite\"",
"]",
")",
":",
"delta",
"+=",
"x",
"x",
"[",
"...",
"]",
"=",
"delta",
"return",
"a"
... | Numpy: Modifying Array Values
http://docs.scipy.org/doc/numpy/reference/arrays.nditer.html | [
"Numpy",
":",
"Modifying",
"Array",
"Values",
"http",
":",
"//",
"docs",
".",
"scipy",
".",
"org",
"/",
"doc",
"/",
"numpy",
"/",
"reference",
"/",
"arrays",
".",
"nditer",
".",
"html"
] | train | https://github.com/flukso/tmpo-py/blob/3c99e3d123bc985a6fba2558922b29430d2a0a94/tmpo/__init__.py#L522-L528 |
spacetelescope/stsci.tools | lib/stsci/tools/vtor_checks.py | sigStrToKwArgsDict | def sigStrToKwArgsDict(checkFuncSig):
""" Take a check function signature (string), and parse it to get a dict
of the keyword args and their values. """
p1 = checkFuncSig.find('(')
p2 = checkFuncSig.rfind(')')
assert p1 > 0 and p2 > 0 and p2 > p1, "Invalid signature: "+checkFuncSig
argParts ... | python | def sigStrToKwArgsDict(checkFuncSig):
""" Take a check function signature (string), and parse it to get a dict
of the keyword args and their values. """
p1 = checkFuncSig.find('(')
p2 = checkFuncSig.rfind(')')
assert p1 > 0 and p2 > 0 and p2 > p1, "Invalid signature: "+checkFuncSig
argParts ... | [
"def",
"sigStrToKwArgsDict",
"(",
"checkFuncSig",
")",
":",
"p1",
"=",
"checkFuncSig",
".",
"find",
"(",
"'('",
")",
"p2",
"=",
"checkFuncSig",
".",
"rfind",
"(",
"')'",
")",
"assert",
"p1",
">",
"0",
"and",
"p2",
">",
"0",
"and",
"p2",
">",
"p1",
... | Take a check function signature (string), and parse it to get a dict
of the keyword args and their values. | [
"Take",
"a",
"check",
"function",
"signature",
"(",
"string",
")",
"and",
"parse",
"it",
"to",
"get",
"a",
"dict",
"of",
"the",
"keyword",
"args",
"and",
"their",
"values",
"."
] | train | https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/vtor_checks.py#L18-L40 |
spacetelescope/stsci.tools | lib/stsci/tools/vtor_checks.py | separateKeywords | def separateKeywords(kwArgsDict):
""" Look through the keywords passed and separate the special ones we
have added from the legal/standard ones. Return both sets as two
dicts (in a tuple), as (standardKws, ourKws) """
standardKws = {}
ourKws = {}
for k in kwArgsDict:
if k in STA... | python | def separateKeywords(kwArgsDict):
""" Look through the keywords passed and separate the special ones we
have added from the legal/standard ones. Return both sets as two
dicts (in a tuple), as (standardKws, ourKws) """
standardKws = {}
ourKws = {}
for k in kwArgsDict:
if k in STA... | [
"def",
"separateKeywords",
"(",
"kwArgsDict",
")",
":",
"standardKws",
"=",
"{",
"}",
"ourKws",
"=",
"{",
"}",
"for",
"k",
"in",
"kwArgsDict",
":",
"if",
"k",
"in",
"STANDARD_KEYS",
":",
"standardKws",
"[",
"k",
"]",
"=",
"kwArgsDict",
"[",
"k",
"]",
... | Look through the keywords passed and separate the special ones we
have added from the legal/standard ones. Return both sets as two
dicts (in a tuple), as (standardKws, ourKws) | [
"Look",
"through",
"the",
"keywords",
"passed",
"and",
"separate",
"the",
"special",
"ones",
"we",
"have",
"added",
"from",
"the",
"legal",
"/",
"standard",
"ones",
".",
"Return",
"both",
"sets",
"as",
"two",
"dicts",
"(",
"in",
"a",
"tuple",
")",
"as",
... | train | https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/vtor_checks.py#L43-L54 |
spacetelescope/stsci.tools | lib/stsci/tools/vtor_checks.py | addKwdArgsToSig | def addKwdArgsToSig(sigStr, kwArgsDict):
""" Alter the passed function signature string to add the given kewords """
retval = sigStr
if len(kwArgsDict) > 0:
retval = retval.strip(' ,)') # open up the r.h.s. for more args
for k in kwArgsDict:
if retval[-1] != '(': retval += ", "
... | python | def addKwdArgsToSig(sigStr, kwArgsDict):
""" Alter the passed function signature string to add the given kewords """
retval = sigStr
if len(kwArgsDict) > 0:
retval = retval.strip(' ,)') # open up the r.h.s. for more args
for k in kwArgsDict:
if retval[-1] != '(': retval += ", "
... | [
"def",
"addKwdArgsToSig",
"(",
"sigStr",
",",
"kwArgsDict",
")",
":",
"retval",
"=",
"sigStr",
"if",
"len",
"(",
"kwArgsDict",
")",
">",
"0",
":",
"retval",
"=",
"retval",
".",
"strip",
"(",
"' ,)'",
")",
"# open up the r.h.s. for more args",
"for",
"k",
"... | Alter the passed function signature string to add the given kewords | [
"Alter",
"the",
"passed",
"function",
"signature",
"string",
"to",
"add",
"the",
"given",
"kewords"
] | train | https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/vtor_checks.py#L57-L67 |
spacetelescope/stsci.tools | lib/stsci/tools/gfit.py | _gauss_funct | def _gauss_funct(p, fjac=None, x=None, y=None, err=None,
weights=None):
"""
Defines the gaussian function to be used as the model.
"""
if p[2] != 0.0:
Z = (x - p[1]) / p[2]
model = p[0] * np.e ** (-Z ** 2 / 2.0)
else:
model = np.zeros(np.size(x))
statu... | python | def _gauss_funct(p, fjac=None, x=None, y=None, err=None,
weights=None):
"""
Defines the gaussian function to be used as the model.
"""
if p[2] != 0.0:
Z = (x - p[1]) / p[2]
model = p[0] * np.e ** (-Z ** 2 / 2.0)
else:
model = np.zeros(np.size(x))
statu... | [
"def",
"_gauss_funct",
"(",
"p",
",",
"fjac",
"=",
"None",
",",
"x",
"=",
"None",
",",
"y",
"=",
"None",
",",
"err",
"=",
"None",
",",
"weights",
"=",
"None",
")",
":",
"if",
"p",
"[",
"2",
"]",
"!=",
"0.0",
":",
"Z",
"=",
"(",
"x",
"-",
... | Defines the gaussian function to be used as the model. | [
"Defines",
"the",
"gaussian",
"function",
"to",
"be",
"used",
"as",
"the",
"model",
"."
] | train | https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/gfit.py#L27-L51 |
spacetelescope/stsci.tools | lib/stsci/tools/gfit.py | gfit1d | def gfit1d(y, x=None, err=None, weights=None, par=None, parinfo=None,
maxiter=200, quiet=0):
"""
Return the gaussian fit as an object.
Parameters
----------
y: 1D Numpy array
The data to be fitted
x: 1D Numpy array
(optional) The x values of the y array. x and y m... | python | def gfit1d(y, x=None, err=None, weights=None, par=None, parinfo=None,
maxiter=200, quiet=0):
"""
Return the gaussian fit as an object.
Parameters
----------
y: 1D Numpy array
The data to be fitted
x: 1D Numpy array
(optional) The x values of the y array. x and y m... | [
"def",
"gfit1d",
"(",
"y",
",",
"x",
"=",
"None",
",",
"err",
"=",
"None",
",",
"weights",
"=",
"None",
",",
"par",
"=",
"None",
",",
"parinfo",
"=",
"None",
",",
"maxiter",
"=",
"200",
",",
"quiet",
"=",
"0",
")",
":",
"y",
"=",
"y",
".",
... | Return the gaussian fit as an object.
Parameters
----------
y: 1D Numpy array
The data to be fitted
x: 1D Numpy array
(optional) The x values of the y array. x and y must
have the same shape.
err: 1D Numpy array
(optional) 1D array with measurement errors, must b... | [
"Return",
"the",
"gaussian",
"fit",
"as",
"an",
"object",
"."
] | train | https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/gfit.py#L54-L133 |
fridiculous/django-estimators | estimators/models/base.py | HashableFileQuerySet.filter | def filter(self, *args, **kwargs):
"""filter lets django managers use `objects.filter` on a hashable object."""
obj = kwargs.pop(self.object_property_name, None)
if obj is not None:
kwargs['object_hash'] = self.model._compute_hash(obj)
return super().filter(*args, **kwargs) | python | def filter(self, *args, **kwargs):
"""filter lets django managers use `objects.filter` on a hashable object."""
obj = kwargs.pop(self.object_property_name, None)
if obj is not None:
kwargs['object_hash'] = self.model._compute_hash(obj)
return super().filter(*args, **kwargs) | [
"def",
"filter",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"obj",
"=",
"kwargs",
".",
"pop",
"(",
"self",
".",
"object_property_name",
",",
"None",
")",
"if",
"obj",
"is",
"not",
"None",
":",
"kwargs",
"[",
"'object_hash'",
... | filter lets django managers use `objects.filter` on a hashable object. | [
"filter",
"lets",
"django",
"managers",
"use",
"objects",
".",
"filter",
"on",
"a",
"hashable",
"object",
"."
] | train | https://github.com/fridiculous/django-estimators/blob/5dd72694dab6725335214543a59104c4de504037/estimators/models/base.py#L23-L28 |
fridiculous/django-estimators | estimators/models/base.py | HashableFileQuerySet._extract_model_params | def _extract_model_params(self, defaults, **kwargs):
"""this method allows django managers use `objects.get_or_create` and
`objects.update_or_create` on a hashable object.
"""
obj = kwargs.pop(self.object_property_name, None)
if obj is not None:
kwargs['object_hash'] ... | python | def _extract_model_params(self, defaults, **kwargs):
"""this method allows django managers use `objects.get_or_create` and
`objects.update_or_create` on a hashable object.
"""
obj = kwargs.pop(self.object_property_name, None)
if obj is not None:
kwargs['object_hash'] ... | [
"def",
"_extract_model_params",
"(",
"self",
",",
"defaults",
",",
"*",
"*",
"kwargs",
")",
":",
"obj",
"=",
"kwargs",
".",
"pop",
"(",
"self",
".",
"object_property_name",
",",
"None",
")",
"if",
"obj",
"is",
"not",
"None",
":",
"kwargs",
"[",
"'objec... | this method allows django managers use `objects.get_or_create` and
`objects.update_or_create` on a hashable object. | [
"this",
"method",
"allows",
"django",
"managers",
"use",
"objects",
".",
"get_or_create",
"and",
"objects",
".",
"update_or_create",
"on",
"a",
"hashable",
"object",
"."
] | train | https://github.com/fridiculous/django-estimators/blob/5dd72694dab6725335214543a59104c4de504037/estimators/models/base.py#L30-L41 |
fridiculous/django-estimators | estimators/models/base.py | HashableFileMixin.persist | def persist(self):
"""a private method that persists an estimator object to the filesystem"""
if self.object_hash:
data = dill.dumps(self.object_property)
f = ContentFile(data)
self.object_file.save(self.object_hash, f, save=False)
f.close()
se... | python | def persist(self):
"""a private method that persists an estimator object to the filesystem"""
if self.object_hash:
data = dill.dumps(self.object_property)
f = ContentFile(data)
self.object_file.save(self.object_hash, f, save=False)
f.close()
se... | [
"def",
"persist",
"(",
"self",
")",
":",
"if",
"self",
".",
"object_hash",
":",
"data",
"=",
"dill",
".",
"dumps",
"(",
"self",
".",
"object_property",
")",
"f",
"=",
"ContentFile",
"(",
"data",
")",
"self",
".",
"object_file",
".",
"save",
"(",
"sel... | a private method that persists an estimator object to the filesystem | [
"a",
"private",
"method",
"that",
"persists",
"an",
"estimator",
"object",
"to",
"the",
"filesystem"
] | train | https://github.com/fridiculous/django-estimators/blob/5dd72694dab6725335214543a59104c4de504037/estimators/models/base.py#L99-L107 |
fridiculous/django-estimators | estimators/models/base.py | HashableFileMixin.load | def load(self):
"""a private method that loads an estimator object from the filesystem"""
if self.is_file_persisted:
self.object_file.open()
temp = dill.loads(self.object_file.read())
self.set_object(temp)
self.object_file.close() | python | def load(self):
"""a private method that loads an estimator object from the filesystem"""
if self.is_file_persisted:
self.object_file.open()
temp = dill.loads(self.object_file.read())
self.set_object(temp)
self.object_file.close() | [
"def",
"load",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_file_persisted",
":",
"self",
".",
"object_file",
".",
"open",
"(",
")",
"temp",
"=",
"dill",
".",
"loads",
"(",
"self",
".",
"object_file",
".",
"read",
"(",
")",
")",
"self",
".",
"set_... | a private method that loads an estimator object from the filesystem | [
"a",
"private",
"method",
"that",
"loads",
"an",
"estimator",
"object",
"from",
"the",
"filesystem"
] | train | https://github.com/fridiculous/django-estimators/blob/5dd72694dab6725335214543a59104c4de504037/estimators/models/base.py#L109-L115 |
fridiculous/django-estimators | estimators/models/base.py | HashableFileMixin.create_from_file | def create_from_file(cls, filename):
"""Return an Estimator object given the path of the file, relative to the MEDIA_ROOT"""
obj = cls()
obj.object_file = filename
obj.load()
return obj | python | def create_from_file(cls, filename):
"""Return an Estimator object given the path of the file, relative to the MEDIA_ROOT"""
obj = cls()
obj.object_file = filename
obj.load()
return obj | [
"def",
"create_from_file",
"(",
"cls",
",",
"filename",
")",
":",
"obj",
"=",
"cls",
"(",
")",
"obj",
".",
"object_file",
"=",
"filename",
"obj",
".",
"load",
"(",
")",
"return",
"obj"
] | Return an Estimator object given the path of the file, relative to the MEDIA_ROOT | [
"Return",
"an",
"Estimator",
"object",
"given",
"the",
"path",
"of",
"the",
"file",
"relative",
"to",
"the",
"MEDIA_ROOT"
] | train | https://github.com/fridiculous/django-estimators/blob/5dd72694dab6725335214543a59104c4de504037/estimators/models/base.py#L128-L133 |
spacetelescope/stsci.tools | lib/stsci/tools/cfgpars.py | getAppDir | def getAppDir():
""" Return our application dir. Create it if it doesn't exist. """
# Be sure the resource dir exists
theDir = os.path.expanduser('~/.')+APP_NAME.lower()
if not os.path.exists(theDir):
try:
os.mkdir(theDir)
except OSError:
print('Could not create ... | python | def getAppDir():
""" Return our application dir. Create it if it doesn't exist. """
# Be sure the resource dir exists
theDir = os.path.expanduser('~/.')+APP_NAME.lower()
if not os.path.exists(theDir):
try:
os.mkdir(theDir)
except OSError:
print('Could not create ... | [
"def",
"getAppDir",
"(",
")",
":",
"# Be sure the resource dir exists",
"theDir",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"'~/.'",
")",
"+",
"APP_NAME",
".",
"lower",
"(",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"theDir",
")",
... | Return our application dir. Create it if it doesn't exist. | [
"Return",
"our",
"application",
"dir",
".",
"Create",
"it",
"if",
"it",
"doesn",
"t",
"exist",
"."
] | train | https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/cfgpars.py#L32-L42 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.