repo
stringlengths 7
55
| path
stringlengths 4
127
| func_name
stringlengths 1
88
| original_string
stringlengths 75
19.8k
| language
stringclasses 1
value | code
stringlengths 75
19.8k
| code_tokens
sequence | docstring
stringlengths 3
17.3k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 87
242
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
suurjaak/InputScope | inputscope/conf.py | defaults | def defaults(values={}):
"""Returns a once-assembled dict of this module's storable attributes."""
if values: return values
save_types = basestring, int, float, tuple, list, dict, type(None)
for k, v in globals().items():
if isinstance(v, save_types) and not k.startswith("_"): values[k] = v
return values | python | def defaults(values={}):
"""Returns a once-assembled dict of this module's storable attributes."""
if values: return values
save_types = basestring, int, float, tuple, list, dict, type(None)
for k, v in globals().items():
if isinstance(v, save_types) and not k.startswith("_"): values[k] = v
return values | [
"def",
"defaults",
"(",
"values",
"=",
"{",
"}",
")",
":",
"if",
"values",
":",
"return",
"values",
"save_types",
"=",
"basestring",
",",
"int",
",",
"float",
",",
"tuple",
",",
"list",
",",
"dict",
",",
"type",
"(",
"None",
")",
"for",
"k",
",",
"v",
"in",
"globals",
"(",
")",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"v",
",",
"save_types",
")",
"and",
"not",
"k",
".",
"startswith",
"(",
"\"_\"",
")",
":",
"values",
"[",
"k",
"]",
"=",
"v",
"return",
"values"
] | Returns a once-assembled dict of this module's storable attributes. | [
"Returns",
"a",
"once",
"-",
"assembled",
"dict",
"of",
"this",
"module",
"s",
"storable",
"attributes",
"."
] | 245ff045163a1995e8cd5ac558d0a93024eb86eb | https://github.com/suurjaak/InputScope/blob/245ff045163a1995e8cd5ac558d0a93024eb86eb/inputscope/conf.py#L297-L303 | train |
Phyks/libbmc | libbmc/papers/tearpages.py | fix_pdf | def fix_pdf(pdf_file, destination):
"""
Fix malformed pdf files when data are present after '%%EOF'
..note ::
Originally from sciunto, https://github.com/sciunto/tear-pages
:param pdfFile: PDF filepath
:param destination: destination
"""
tmp = tempfile.NamedTemporaryFile()
with open(tmp.name, 'wb') as output:
with open(pdf_file, "rb") as fh:
for line in fh:
output.write(line)
if b'%%EOF' in line:
break
shutil.copy(tmp.name, destination) | python | def fix_pdf(pdf_file, destination):
"""
Fix malformed pdf files when data are present after '%%EOF'
..note ::
Originally from sciunto, https://github.com/sciunto/tear-pages
:param pdfFile: PDF filepath
:param destination: destination
"""
tmp = tempfile.NamedTemporaryFile()
with open(tmp.name, 'wb') as output:
with open(pdf_file, "rb") as fh:
for line in fh:
output.write(line)
if b'%%EOF' in line:
break
shutil.copy(tmp.name, destination) | [
"def",
"fix_pdf",
"(",
"pdf_file",
",",
"destination",
")",
":",
"tmp",
"=",
"tempfile",
".",
"NamedTemporaryFile",
"(",
")",
"with",
"open",
"(",
"tmp",
".",
"name",
",",
"'wb'",
")",
"as",
"output",
":",
"with",
"open",
"(",
"pdf_file",
",",
"\"rb\"",
")",
"as",
"fh",
":",
"for",
"line",
"in",
"fh",
":",
"output",
".",
"write",
"(",
"line",
")",
"if",
"b'%%EOF'",
"in",
"line",
":",
"break",
"shutil",
".",
"copy",
"(",
"tmp",
".",
"name",
",",
"destination",
")"
] | Fix malformed pdf files when data are present after '%%EOF'
..note ::
Originally from sciunto, https://github.com/sciunto/tear-pages
:param pdfFile: PDF filepath
:param destination: destination | [
"Fix",
"malformed",
"pdf",
"files",
"when",
"data",
"are",
"present",
"after",
"%%EOF"
] | 9ef1a29d2514157d1edd6c13ecbd61b07ae9315e | https://github.com/Phyks/libbmc/blob/9ef1a29d2514157d1edd6c13ecbd61b07ae9315e/libbmc/papers/tearpages.py#L24-L42 | train |
Phyks/libbmc | libbmc/papers/tearpages.py | tearpage_backend | def tearpage_backend(filename, teared_pages=None):
"""
Copy filename to a tempfile, write pages to filename except the teared one.
..note ::
Adapted from sciunto's code, https://github.com/sciunto/tear-pages
:param filename: PDF filepath
:param teared_pages: Numbers of the pages to tear. Default to first page \
only.
"""
# Handle default argument
if teared_pages is None:
teared_pages = [0]
# Copy the pdf to a tmp file
with tempfile.NamedTemporaryFile() as tmp:
# Copy the input file to tmp
shutil.copy(filename, tmp.name)
# Read the copied pdf
# TODO: Use with syntax
try:
input_file = PdfFileReader(open(tmp.name, 'rb'))
except PdfReadError:
fix_pdf(filename, tmp.name)
input_file = PdfFileReader(open(tmp.name, 'rb'))
# Seek for the number of pages
num_pages = input_file.getNumPages()
# Write pages excepted the first one
output_file = PdfFileWriter()
for i in range(num_pages):
if i in teared_pages:
continue
output_file.addPage(input_file.getPage(i))
tmp.close()
outputStream = open(filename, "wb")
output_file.write(outputStream) | python | def tearpage_backend(filename, teared_pages=None):
"""
Copy filename to a tempfile, write pages to filename except the teared one.
..note ::
Adapted from sciunto's code, https://github.com/sciunto/tear-pages
:param filename: PDF filepath
:param teared_pages: Numbers of the pages to tear. Default to first page \
only.
"""
# Handle default argument
if teared_pages is None:
teared_pages = [0]
# Copy the pdf to a tmp file
with tempfile.NamedTemporaryFile() as tmp:
# Copy the input file to tmp
shutil.copy(filename, tmp.name)
# Read the copied pdf
# TODO: Use with syntax
try:
input_file = PdfFileReader(open(tmp.name, 'rb'))
except PdfReadError:
fix_pdf(filename, tmp.name)
input_file = PdfFileReader(open(tmp.name, 'rb'))
# Seek for the number of pages
num_pages = input_file.getNumPages()
# Write pages excepted the first one
output_file = PdfFileWriter()
for i in range(num_pages):
if i in teared_pages:
continue
output_file.addPage(input_file.getPage(i))
tmp.close()
outputStream = open(filename, "wb")
output_file.write(outputStream) | [
"def",
"tearpage_backend",
"(",
"filename",
",",
"teared_pages",
"=",
"None",
")",
":",
"# Handle default argument",
"if",
"teared_pages",
"is",
"None",
":",
"teared_pages",
"=",
"[",
"0",
"]",
"# Copy the pdf to a tmp file",
"with",
"tempfile",
".",
"NamedTemporaryFile",
"(",
")",
"as",
"tmp",
":",
"# Copy the input file to tmp",
"shutil",
".",
"copy",
"(",
"filename",
",",
"tmp",
".",
"name",
")",
"# Read the copied pdf",
"# TODO: Use with syntax",
"try",
":",
"input_file",
"=",
"PdfFileReader",
"(",
"open",
"(",
"tmp",
".",
"name",
",",
"'rb'",
")",
")",
"except",
"PdfReadError",
":",
"fix_pdf",
"(",
"filename",
",",
"tmp",
".",
"name",
")",
"input_file",
"=",
"PdfFileReader",
"(",
"open",
"(",
"tmp",
".",
"name",
",",
"'rb'",
")",
")",
"# Seek for the number of pages",
"num_pages",
"=",
"input_file",
".",
"getNumPages",
"(",
")",
"# Write pages excepted the first one",
"output_file",
"=",
"PdfFileWriter",
"(",
")",
"for",
"i",
"in",
"range",
"(",
"num_pages",
")",
":",
"if",
"i",
"in",
"teared_pages",
":",
"continue",
"output_file",
".",
"addPage",
"(",
"input_file",
".",
"getPage",
"(",
"i",
")",
")",
"tmp",
".",
"close",
"(",
")",
"outputStream",
"=",
"open",
"(",
"filename",
",",
"\"wb\"",
")",
"output_file",
".",
"write",
"(",
"outputStream",
")"
] | Copy filename to a tempfile, write pages to filename except the teared one.
..note ::
Adapted from sciunto's code, https://github.com/sciunto/tear-pages
:param filename: PDF filepath
:param teared_pages: Numbers of the pages to tear. Default to first page \
only. | [
"Copy",
"filename",
"to",
"a",
"tempfile",
"write",
"pages",
"to",
"filename",
"except",
"the",
"teared",
"one",
"."
] | 9ef1a29d2514157d1edd6c13ecbd61b07ae9315e | https://github.com/Phyks/libbmc/blob/9ef1a29d2514157d1edd6c13ecbd61b07ae9315e/libbmc/papers/tearpages.py#L45-L85 | train |
Phyks/libbmc | libbmc/papers/tearpages.py | tearpage_needed | def tearpage_needed(bibtex):
"""
Check whether a given paper needs some pages to be teared or not.
:params bibtex: The bibtex entry associated to the paper, to guess \
whether tearing is needed.
:returns: A list of pages to tear.
"""
for publisher in BAD_JOURNALS:
if publisher in bibtex.get("journal", "").lower():
# Bad journal is found, add pages to tear
return BAD_JOURNALS[publisher]
# If no bad journals are found, return an empty list
return [] | python | def tearpage_needed(bibtex):
"""
Check whether a given paper needs some pages to be teared or not.
:params bibtex: The bibtex entry associated to the paper, to guess \
whether tearing is needed.
:returns: A list of pages to tear.
"""
for publisher in BAD_JOURNALS:
if publisher in bibtex.get("journal", "").lower():
# Bad journal is found, add pages to tear
return BAD_JOURNALS[publisher]
# If no bad journals are found, return an empty list
return [] | [
"def",
"tearpage_needed",
"(",
"bibtex",
")",
":",
"for",
"publisher",
"in",
"BAD_JOURNALS",
":",
"if",
"publisher",
"in",
"bibtex",
".",
"get",
"(",
"\"journal\"",
",",
"\"\"",
")",
".",
"lower",
"(",
")",
":",
"# Bad journal is found, add pages to tear",
"return",
"BAD_JOURNALS",
"[",
"publisher",
"]",
"# If no bad journals are found, return an empty list",
"return",
"[",
"]"
] | Check whether a given paper needs some pages to be teared or not.
:params bibtex: The bibtex entry associated to the paper, to guess \
whether tearing is needed.
:returns: A list of pages to tear. | [
"Check",
"whether",
"a",
"given",
"paper",
"needs",
"some",
"pages",
"to",
"be",
"teared",
"or",
"not",
"."
] | 9ef1a29d2514157d1edd6c13ecbd61b07ae9315e | https://github.com/Phyks/libbmc/blob/9ef1a29d2514157d1edd6c13ecbd61b07ae9315e/libbmc/papers/tearpages.py#L88-L102 | train |
Phyks/libbmc | libbmc/papers/tearpages.py | tearpage | def tearpage(filename, bibtex=None, force=None):
"""
Tear some pages of the file if needed.
:params filename: Path to the file to handle.
:params bibtex: BibTeX dict associated to this file, as the one given by \
``bibtexparser``. (Mandatory if force is not specified)
:params force: If a list of integers, force the tearing of the \
specified pages. (Optional)
:returns: A boolean indicating whether the file has been teared or not. \
Side effect is tearing the necessary pages from the file.
"""
# Fetch pages to tear
pages_to_tear = []
if force is not None:
pages_to_tear = force
elif bibtex is not None:
pages_to_tear = tearpage_needed(bibtex)
if len(pages_to_tear) > 0:
# If tearing is needed, do it and return True
tearpage_backend(filename, teared_pages=pages_to_tear)
return True
# Else, simply return False
return False | python | def tearpage(filename, bibtex=None, force=None):
"""
Tear some pages of the file if needed.
:params filename: Path to the file to handle.
:params bibtex: BibTeX dict associated to this file, as the one given by \
``bibtexparser``. (Mandatory if force is not specified)
:params force: If a list of integers, force the tearing of the \
specified pages. (Optional)
:returns: A boolean indicating whether the file has been teared or not. \
Side effect is tearing the necessary pages from the file.
"""
# Fetch pages to tear
pages_to_tear = []
if force is not None:
pages_to_tear = force
elif bibtex is not None:
pages_to_tear = tearpage_needed(bibtex)
if len(pages_to_tear) > 0:
# If tearing is needed, do it and return True
tearpage_backend(filename, teared_pages=pages_to_tear)
return True
# Else, simply return False
return False | [
"def",
"tearpage",
"(",
"filename",
",",
"bibtex",
"=",
"None",
",",
"force",
"=",
"None",
")",
":",
"# Fetch pages to tear",
"pages_to_tear",
"=",
"[",
"]",
"if",
"force",
"is",
"not",
"None",
":",
"pages_to_tear",
"=",
"force",
"elif",
"bibtex",
"is",
"not",
"None",
":",
"pages_to_tear",
"=",
"tearpage_needed",
"(",
"bibtex",
")",
"if",
"len",
"(",
"pages_to_tear",
")",
">",
"0",
":",
"# If tearing is needed, do it and return True",
"tearpage_backend",
"(",
"filename",
",",
"teared_pages",
"=",
"pages_to_tear",
")",
"return",
"True",
"# Else, simply return False",
"return",
"False"
] | Tear some pages of the file if needed.
:params filename: Path to the file to handle.
:params bibtex: BibTeX dict associated to this file, as the one given by \
``bibtexparser``. (Mandatory if force is not specified)
:params force: If a list of integers, force the tearing of the \
specified pages. (Optional)
:returns: A boolean indicating whether the file has been teared or not. \
Side effect is tearing the necessary pages from the file. | [
"Tear",
"some",
"pages",
"of",
"the",
"file",
"if",
"needed",
"."
] | 9ef1a29d2514157d1edd6c13ecbd61b07ae9315e | https://github.com/Phyks/libbmc/blob/9ef1a29d2514157d1edd6c13ecbd61b07ae9315e/libbmc/papers/tearpages.py#L105-L130 | train |
theiviaxx/python-perforce | perforce/api.py | edit | def edit(filename, connection=None):
"""Checks out a file into the default changelist
:param filename: File to check out
:type filename: str
:param connection: Connection object to use
:type connection: :py:class:`Connection`
"""
c = connection or connect()
rev = c.ls(filename)
if rev:
rev[0].edit() | python | def edit(filename, connection=None):
"""Checks out a file into the default changelist
:param filename: File to check out
:type filename: str
:param connection: Connection object to use
:type connection: :py:class:`Connection`
"""
c = connection or connect()
rev = c.ls(filename)
if rev:
rev[0].edit() | [
"def",
"edit",
"(",
"filename",
",",
"connection",
"=",
"None",
")",
":",
"c",
"=",
"connection",
"or",
"connect",
"(",
")",
"rev",
"=",
"c",
".",
"ls",
"(",
"filename",
")",
"if",
"rev",
":",
"rev",
"[",
"0",
"]",
".",
"edit",
"(",
")"
] | Checks out a file into the default changelist
:param filename: File to check out
:type filename: str
:param connection: Connection object to use
:type connection: :py:class:`Connection` | [
"Checks",
"out",
"a",
"file",
"into",
"the",
"default",
"changelist"
] | 01a3b01fe5949126fa0097d9a8ad386887823b5a | https://github.com/theiviaxx/python-perforce/blob/01a3b01fe5949126fa0097d9a8ad386887823b5a/perforce/api.py#L28-L39 | train |
theiviaxx/python-perforce | perforce/api.py | sync | def sync(filename, connection=None):
"""Syncs a file
:param filename: File to check out
:type filename: str
:param connection: Connection object to use
:type connection: :py:class:`Connection`
"""
c = connection or connect()
rev = c.ls(filename)
if rev:
rev[0].sync() | python | def sync(filename, connection=None):
"""Syncs a file
:param filename: File to check out
:type filename: str
:param connection: Connection object to use
:type connection: :py:class:`Connection`
"""
c = connection or connect()
rev = c.ls(filename)
if rev:
rev[0].sync() | [
"def",
"sync",
"(",
"filename",
",",
"connection",
"=",
"None",
")",
":",
"c",
"=",
"connection",
"or",
"connect",
"(",
")",
"rev",
"=",
"c",
".",
"ls",
"(",
"filename",
")",
"if",
"rev",
":",
"rev",
"[",
"0",
"]",
".",
"sync",
"(",
")"
] | Syncs a file
:param filename: File to check out
:type filename: str
:param connection: Connection object to use
:type connection: :py:class:`Connection` | [
"Syncs",
"a",
"file"
] | 01a3b01fe5949126fa0097d9a8ad386887823b5a | https://github.com/theiviaxx/python-perforce/blob/01a3b01fe5949126fa0097d9a8ad386887823b5a/perforce/api.py#L42-L53 | train |
theiviaxx/python-perforce | perforce/api.py | open | def open(filename, connection=None):
"""Edits or Adds a filename ensuring the file is in perforce and editable
:param filename: File to check out
:type filename: str
:param connection: Connection object to use
:type connection: :py:class:`Connection`
"""
c = connection or connect()
res = c.ls(filename)
if res and res[0].revision:
res[0].edit()
else:
c.add(filename) | python | def open(filename, connection=None):
"""Edits or Adds a filename ensuring the file is in perforce and editable
:param filename: File to check out
:type filename: str
:param connection: Connection object to use
:type connection: :py:class:`Connection`
"""
c = connection or connect()
res = c.ls(filename)
if res and res[0].revision:
res[0].edit()
else:
c.add(filename) | [
"def",
"open",
"(",
"filename",
",",
"connection",
"=",
"None",
")",
":",
"c",
"=",
"connection",
"or",
"connect",
"(",
")",
"res",
"=",
"c",
".",
"ls",
"(",
"filename",
")",
"if",
"res",
"and",
"res",
"[",
"0",
"]",
".",
"revision",
":",
"res",
"[",
"0",
"]",
".",
"edit",
"(",
")",
"else",
":",
"c",
".",
"add",
"(",
"filename",
")"
] | Edits or Adds a filename ensuring the file is in perforce and editable
:param filename: File to check out
:type filename: str
:param connection: Connection object to use
:type connection: :py:class:`Connection` | [
"Edits",
"or",
"Adds",
"a",
"filename",
"ensuring",
"the",
"file",
"is",
"in",
"perforce",
"and",
"editable"
] | 01a3b01fe5949126fa0097d9a8ad386887823b5a | https://github.com/theiviaxx/python-perforce/blob/01a3b01fe5949126fa0097d9a8ad386887823b5a/perforce/api.py#L81-L94 | train |
Phyks/libbmc | libbmc/repositories/arxiv.py | is_valid | def is_valid(arxiv_id):
"""
Check that a given arXiv ID is a valid one.
:param arxiv_id: The arXiv ID to be checked.
:returns: Boolean indicating whether the arXiv ID is valid or not.
>>> is_valid('1506.06690')
True
>>> is_valid('1506.06690v1')
True
>>> is_valid('arXiv:1506.06690')
True
>>> is_valid('arXiv:1506.06690v1')
True
>>> is_valid('arxiv:1506.06690')
True
>>> is_valid('arxiv:1506.06690v1')
True
>>> is_valid('math.GT/0309136')
True
>>> is_valid('abcdf')
False
>>> is_valid('bar1506.06690foo')
False
>>> is_valid('mare.GG/0309136')
False
"""
match = REGEX.match(arxiv_id)
return (match is not None) and (match.group(0) == arxiv_id) | python | def is_valid(arxiv_id):
"""
Check that a given arXiv ID is a valid one.
:param arxiv_id: The arXiv ID to be checked.
:returns: Boolean indicating whether the arXiv ID is valid or not.
>>> is_valid('1506.06690')
True
>>> is_valid('1506.06690v1')
True
>>> is_valid('arXiv:1506.06690')
True
>>> is_valid('arXiv:1506.06690v1')
True
>>> is_valid('arxiv:1506.06690')
True
>>> is_valid('arxiv:1506.06690v1')
True
>>> is_valid('math.GT/0309136')
True
>>> is_valid('abcdf')
False
>>> is_valid('bar1506.06690foo')
False
>>> is_valid('mare.GG/0309136')
False
"""
match = REGEX.match(arxiv_id)
return (match is not None) and (match.group(0) == arxiv_id) | [
"def",
"is_valid",
"(",
"arxiv_id",
")",
":",
"match",
"=",
"REGEX",
".",
"match",
"(",
"arxiv_id",
")",
"return",
"(",
"match",
"is",
"not",
"None",
")",
"and",
"(",
"match",
".",
"group",
"(",
"0",
")",
"==",
"arxiv_id",
")"
] | Check that a given arXiv ID is a valid one.
:param arxiv_id: The arXiv ID to be checked.
:returns: Boolean indicating whether the arXiv ID is valid or not.
>>> is_valid('1506.06690')
True
>>> is_valid('1506.06690v1')
True
>>> is_valid('arXiv:1506.06690')
True
>>> is_valid('arXiv:1506.06690v1')
True
>>> is_valid('arxiv:1506.06690')
True
>>> is_valid('arxiv:1506.06690v1')
True
>>> is_valid('math.GT/0309136')
True
>>> is_valid('abcdf')
False
>>> is_valid('bar1506.06690foo')
False
>>> is_valid('mare.GG/0309136')
False | [
"Check",
"that",
"a",
"given",
"arXiv",
"ID",
"is",
"a",
"valid",
"one",
"."
] | 9ef1a29d2514157d1edd6c13ecbd61b07ae9315e | https://github.com/Phyks/libbmc/blob/9ef1a29d2514157d1edd6c13ecbd61b07ae9315e/libbmc/repositories/arxiv.py#L235-L273 | train |
Phyks/libbmc | libbmc/repositories/arxiv.py | get_bibtex | def get_bibtex(arxiv_id):
"""
Get a BibTeX entry for a given arXiv ID.
.. note::
Using awesome https://pypi.python.org/pypi/arxiv2bib/ module.
:param arxiv_id: The canonical arXiv id to get BibTeX from.
:returns: A BibTeX string or ``None``.
>>> get_bibtex('1506.06690')
"@article{1506.06690v2,\\nAuthor = {Lucas Verney and Lev Pitaevskii and Sandro Stringari},\\nTitle = {Hybridization of first and second sound in a weakly-interacting Bose gas},\\nEprint = {1506.06690v2},\\nDOI = {10.1209/0295-5075/111/40005},\\nArchivePrefix = {arXiv},\\nPrimaryClass = {cond-mat.quant-gas},\\nAbstract = {Using Landau's theory of two-fluid hydrodynamics we investigate the sound\\nmodes propagating in a uniform weakly-interacting superfluid Bose gas for\\nvalues of temperature, up to the critical point. In order to evaluate the\\nrelevant thermodynamic functions needed to solve the hydrodynamic equations,\\nincluding the temperature dependence of the superfluid density, we use\\nBogoliubov theory at low temperatures and the results of a perturbative\\napproach based on Beliaev diagrammatic technique at higher temperatures.\\nSpecial focus is given on the hybridization phenomenon between first and second\\nsound which occurs at low temperatures of the order of the interaction energy\\nand we discuss explicitly the behavior of the two sound velocities near the\\nhybridization point.},\\nYear = {2015},\\nMonth = {Jun},\\nUrl = {http://arxiv.org/abs/1506.06690v2},\\nFile = {1506.06690v2.pdf}\\n}"
>>> get_bibtex('1506.06690v1')
"@article{1506.06690v1,\\nAuthor = {Lucas Verney and Lev Pitaevskii and Sandro Stringari},\\nTitle = {Hybridization of first and second sound in a weakly-interacting Bose gas},\\nEprint = {1506.06690v1},\\nDOI = {10.1209/0295-5075/111/40005},\\nArchivePrefix = {arXiv},\\nPrimaryClass = {cond-mat.quant-gas},\\nAbstract = {Using Landau's theory of two-fluid hydrodynamics we investigate the sound\\nmodes propagating in a uniform weakly-interacting superfluid Bose gas for\\nvalues of temperature, up to the critical point. In order to evaluate the\\nrelevant thermodynamic functions needed to solve the hydrodynamic equations,\\nincluding the temperature dependence of the superfluid density, we use\\nBogoliubov theory at low temperatures and the results of a perturbative\\napproach based on Beliaev diagrammatic technique at higher temperatures.\\nSpecial focus is given on the hybridization phenomenon between first and second\\nsound which occurs at low temperatures of the order of the interaction energy\\nand we discuss explicitly the behavior of the two sound velocities near the\\nhybridization point.},\\nYear = {2015},\\nMonth = {Jun},\\nUrl = {http://arxiv.org/abs/1506.06690v1},\\nFile = {1506.06690v1.pdf}\\n}"
"""
# Fetch bibtex using arxiv2bib module
try:
bibtex = arxiv2bib.arxiv2bib([arxiv_id])
except HTTPError:
bibtex = []
for bib in bibtex:
if isinstance(bib, arxiv2bib.ReferenceErrorInfo):
continue
else:
# Return fetched bibtex
return bib.bibtex()
# An error occurred, return None
return None | python | def get_bibtex(arxiv_id):
"""
Get a BibTeX entry for a given arXiv ID.
.. note::
Using awesome https://pypi.python.org/pypi/arxiv2bib/ module.
:param arxiv_id: The canonical arXiv id to get BibTeX from.
:returns: A BibTeX string or ``None``.
>>> get_bibtex('1506.06690')
"@article{1506.06690v2,\\nAuthor = {Lucas Verney and Lev Pitaevskii and Sandro Stringari},\\nTitle = {Hybridization of first and second sound in a weakly-interacting Bose gas},\\nEprint = {1506.06690v2},\\nDOI = {10.1209/0295-5075/111/40005},\\nArchivePrefix = {arXiv},\\nPrimaryClass = {cond-mat.quant-gas},\\nAbstract = {Using Landau's theory of two-fluid hydrodynamics we investigate the sound\\nmodes propagating in a uniform weakly-interacting superfluid Bose gas for\\nvalues of temperature, up to the critical point. In order to evaluate the\\nrelevant thermodynamic functions needed to solve the hydrodynamic equations,\\nincluding the temperature dependence of the superfluid density, we use\\nBogoliubov theory at low temperatures and the results of a perturbative\\napproach based on Beliaev diagrammatic technique at higher temperatures.\\nSpecial focus is given on the hybridization phenomenon between first and second\\nsound which occurs at low temperatures of the order of the interaction energy\\nand we discuss explicitly the behavior of the two sound velocities near the\\nhybridization point.},\\nYear = {2015},\\nMonth = {Jun},\\nUrl = {http://arxiv.org/abs/1506.06690v2},\\nFile = {1506.06690v2.pdf}\\n}"
>>> get_bibtex('1506.06690v1')
"@article{1506.06690v1,\\nAuthor = {Lucas Verney and Lev Pitaevskii and Sandro Stringari},\\nTitle = {Hybridization of first and second sound in a weakly-interacting Bose gas},\\nEprint = {1506.06690v1},\\nDOI = {10.1209/0295-5075/111/40005},\\nArchivePrefix = {arXiv},\\nPrimaryClass = {cond-mat.quant-gas},\\nAbstract = {Using Landau's theory of two-fluid hydrodynamics we investigate the sound\\nmodes propagating in a uniform weakly-interacting superfluid Bose gas for\\nvalues of temperature, up to the critical point. In order to evaluate the\\nrelevant thermodynamic functions needed to solve the hydrodynamic equations,\\nincluding the temperature dependence of the superfluid density, we use\\nBogoliubov theory at low temperatures and the results of a perturbative\\napproach based on Beliaev diagrammatic technique at higher temperatures.\\nSpecial focus is given on the hybridization phenomenon between first and second\\nsound which occurs at low temperatures of the order of the interaction energy\\nand we discuss explicitly the behavior of the two sound velocities near the\\nhybridization point.},\\nYear = {2015},\\nMonth = {Jun},\\nUrl = {http://arxiv.org/abs/1506.06690v1},\\nFile = {1506.06690v1.pdf}\\n}"
"""
# Fetch bibtex using arxiv2bib module
try:
bibtex = arxiv2bib.arxiv2bib([arxiv_id])
except HTTPError:
bibtex = []
for bib in bibtex:
if isinstance(bib, arxiv2bib.ReferenceErrorInfo):
continue
else:
# Return fetched bibtex
return bib.bibtex()
# An error occurred, return None
return None | [
"def",
"get_bibtex",
"(",
"arxiv_id",
")",
":",
"# Fetch bibtex using arxiv2bib module",
"try",
":",
"bibtex",
"=",
"arxiv2bib",
".",
"arxiv2bib",
"(",
"[",
"arxiv_id",
"]",
")",
"except",
"HTTPError",
":",
"bibtex",
"=",
"[",
"]",
"for",
"bib",
"in",
"bibtex",
":",
"if",
"isinstance",
"(",
"bib",
",",
"arxiv2bib",
".",
"ReferenceErrorInfo",
")",
":",
"continue",
"else",
":",
"# Return fetched bibtex",
"return",
"bib",
".",
"bibtex",
"(",
")",
"# An error occurred, return None",
"return",
"None"
] | Get a BibTeX entry for a given arXiv ID.
.. note::
Using awesome https://pypi.python.org/pypi/arxiv2bib/ module.
:param arxiv_id: The canonical arXiv id to get BibTeX from.
:returns: A BibTeX string or ``None``.
>>> get_bibtex('1506.06690')
"@article{1506.06690v2,\\nAuthor = {Lucas Verney and Lev Pitaevskii and Sandro Stringari},\\nTitle = {Hybridization of first and second sound in a weakly-interacting Bose gas},\\nEprint = {1506.06690v2},\\nDOI = {10.1209/0295-5075/111/40005},\\nArchivePrefix = {arXiv},\\nPrimaryClass = {cond-mat.quant-gas},\\nAbstract = {Using Landau's theory of two-fluid hydrodynamics we investigate the sound\\nmodes propagating in a uniform weakly-interacting superfluid Bose gas for\\nvalues of temperature, up to the critical point. In order to evaluate the\\nrelevant thermodynamic functions needed to solve the hydrodynamic equations,\\nincluding the temperature dependence of the superfluid density, we use\\nBogoliubov theory at low temperatures and the results of a perturbative\\napproach based on Beliaev diagrammatic technique at higher temperatures.\\nSpecial focus is given on the hybridization phenomenon between first and second\\nsound which occurs at low temperatures of the order of the interaction energy\\nand we discuss explicitly the behavior of the two sound velocities near the\\nhybridization point.},\\nYear = {2015},\\nMonth = {Jun},\\nUrl = {http://arxiv.org/abs/1506.06690v2},\\nFile = {1506.06690v2.pdf}\\n}"
>>> get_bibtex('1506.06690v1')
"@article{1506.06690v1,\\nAuthor = {Lucas Verney and Lev Pitaevskii and Sandro Stringari},\\nTitle = {Hybridization of first and second sound in a weakly-interacting Bose gas},\\nEprint = {1506.06690v1},\\nDOI = {10.1209/0295-5075/111/40005},\\nArchivePrefix = {arXiv},\\nPrimaryClass = {cond-mat.quant-gas},\\nAbstract = {Using Landau's theory of two-fluid hydrodynamics we investigate the sound\\nmodes propagating in a uniform weakly-interacting superfluid Bose gas for\\nvalues of temperature, up to the critical point. In order to evaluate the\\nrelevant thermodynamic functions needed to solve the hydrodynamic equations,\\nincluding the temperature dependence of the superfluid density, we use\\nBogoliubov theory at low temperatures and the results of a perturbative\\napproach based on Beliaev diagrammatic technique at higher temperatures.\\nSpecial focus is given on the hybridization phenomenon between first and second\\nsound which occurs at low temperatures of the order of the interaction energy\\nand we discuss explicitly the behavior of the two sound velocities near the\\nhybridization point.},\\nYear = {2015},\\nMonth = {Jun},\\nUrl = {http://arxiv.org/abs/1506.06690v1},\\nFile = {1506.06690v1.pdf}\\n}" | [
"Get",
"a",
"BibTeX",
"entry",
"for",
"a",
"given",
"arXiv",
"ID",
"."
] | 9ef1a29d2514157d1edd6c13ecbd61b07ae9315e | https://github.com/Phyks/libbmc/blob/9ef1a29d2514157d1edd6c13ecbd61b07ae9315e/libbmc/repositories/arxiv.py#L276-L306 | train |
Phyks/libbmc | libbmc/repositories/arxiv.py | extract_from_text | def extract_from_text(text):
"""
Extract arXiv IDs from a text.
:param text: The text to extract arXiv IDs from.
:returns: A list of matching arXiv IDs, in canonical form.
>>> sorted(extract_from_text('1506.06690 1506.06690v1 arXiv:1506.06690 arXiv:1506.06690v1 arxiv:1506.06690 arxiv:1506.06690v1 math.GT/0309136 abcdf bar1506.06690foo mare.GG/0309136'))
['1506.06690', '1506.06690v1', 'math.GT/0309136']
"""
# Remove the leading "arxiv:".
return tools.remove_duplicates([re.sub("arxiv:", "", i[0],
flags=re.IGNORECASE)
for i in REGEX.findall(text) if i[0] != '']) | python | def extract_from_text(text):
"""
Extract arXiv IDs from a text.
:param text: The text to extract arXiv IDs from.
:returns: A list of matching arXiv IDs, in canonical form.
>>> sorted(extract_from_text('1506.06690 1506.06690v1 arXiv:1506.06690 arXiv:1506.06690v1 arxiv:1506.06690 arxiv:1506.06690v1 math.GT/0309136 abcdf bar1506.06690foo mare.GG/0309136'))
['1506.06690', '1506.06690v1', 'math.GT/0309136']
"""
# Remove the leading "arxiv:".
return tools.remove_duplicates([re.sub("arxiv:", "", i[0],
flags=re.IGNORECASE)
for i in REGEX.findall(text) if i[0] != '']) | [
"def",
"extract_from_text",
"(",
"text",
")",
":",
"# Remove the leading \"arxiv:\".",
"return",
"tools",
".",
"remove_duplicates",
"(",
"[",
"re",
".",
"sub",
"(",
"\"arxiv:\"",
",",
"\"\"",
",",
"i",
"[",
"0",
"]",
",",
"flags",
"=",
"re",
".",
"IGNORECASE",
")",
"for",
"i",
"in",
"REGEX",
".",
"findall",
"(",
"text",
")",
"if",
"i",
"[",
"0",
"]",
"!=",
"''",
"]",
")"
] | Extract arXiv IDs from a text.
:param text: The text to extract arXiv IDs from.
:returns: A list of matching arXiv IDs, in canonical form.
>>> sorted(extract_from_text('1506.06690 1506.06690v1 arXiv:1506.06690 arXiv:1506.06690v1 arxiv:1506.06690 arxiv:1506.06690v1 math.GT/0309136 abcdf bar1506.06690foo mare.GG/0309136'))
['1506.06690', '1506.06690v1', 'math.GT/0309136'] | [
"Extract",
"arXiv",
"IDs",
"from",
"a",
"text",
"."
] | 9ef1a29d2514157d1edd6c13ecbd61b07ae9315e | https://github.com/Phyks/libbmc/blob/9ef1a29d2514157d1edd6c13ecbd61b07ae9315e/libbmc/repositories/arxiv.py#L309-L322 | train |
Phyks/libbmc | libbmc/repositories/arxiv.py | from_doi | def from_doi(doi):
"""
Get the arXiv eprint id for a given DOI.
.. note::
Uses arXiv API. Will not return anything if arXiv is not aware of the
associated DOI.
:param doi: The DOI of the resource to look for.
:returns: The arXiv eprint id, or ``None`` if not found.
>>> from_doi('10.1209/0295-5075/111/40005')
# Note: Test do not pass due to an arXiv API bug.
'1506.06690'
"""
try:
request = requests.get("http://export.arxiv.org/api/query",
params={
"search_query": "doi:%s" % (doi,),
"max_results": 1
})
request.raise_for_status()
except RequestException:
return None
root = xml.etree.ElementTree.fromstring(request.content)
for entry in root.iter("{http://www.w3.org/2005/Atom}entry"):
arxiv_id = entry.find("{http://www.w3.org/2005/Atom}id").text
# arxiv_id is an arXiv full URL. We only want the id which is the last
# URL component.
return arxiv_id.split("/")[-1]
return None | python | def from_doi(doi):
"""
Get the arXiv eprint id for a given DOI.
.. note::
Uses arXiv API. Will not return anything if arXiv is not aware of the
associated DOI.
:param doi: The DOI of the resource to look for.
:returns: The arXiv eprint id, or ``None`` if not found.
>>> from_doi('10.1209/0295-5075/111/40005')
# Note: Test do not pass due to an arXiv API bug.
'1506.06690'
"""
try:
request = requests.get("http://export.arxiv.org/api/query",
params={
"search_query": "doi:%s" % (doi,),
"max_results": 1
})
request.raise_for_status()
except RequestException:
return None
root = xml.etree.ElementTree.fromstring(request.content)
for entry in root.iter("{http://www.w3.org/2005/Atom}entry"):
arxiv_id = entry.find("{http://www.w3.org/2005/Atom}id").text
# arxiv_id is an arXiv full URL. We only want the id which is the last
# URL component.
return arxiv_id.split("/")[-1]
return None | [
"def",
"from_doi",
"(",
"doi",
")",
":",
"try",
":",
"request",
"=",
"requests",
".",
"get",
"(",
"\"http://export.arxiv.org/api/query\"",
",",
"params",
"=",
"{",
"\"search_query\"",
":",
"\"doi:%s\"",
"%",
"(",
"doi",
",",
")",
",",
"\"max_results\"",
":",
"1",
"}",
")",
"request",
".",
"raise_for_status",
"(",
")",
"except",
"RequestException",
":",
"return",
"None",
"root",
"=",
"xml",
".",
"etree",
".",
"ElementTree",
".",
"fromstring",
"(",
"request",
".",
"content",
")",
"for",
"entry",
"in",
"root",
".",
"iter",
"(",
"\"{http://www.w3.org/2005/Atom}entry\"",
")",
":",
"arxiv_id",
"=",
"entry",
".",
"find",
"(",
"\"{http://www.w3.org/2005/Atom}id\"",
")",
".",
"text",
"# arxiv_id is an arXiv full URL. We only want the id which is the last",
"# URL component.",
"return",
"arxiv_id",
".",
"split",
"(",
"\"/\"",
")",
"[",
"-",
"1",
"]",
"return",
"None"
] | Get the arXiv eprint id for a given DOI.
.. note::
Uses arXiv API. Will not return anything if arXiv is not aware of the
associated DOI.
:param doi: The DOI of the resource to look for.
:returns: The arXiv eprint id, or ``None`` if not found.
>>> from_doi('10.1209/0295-5075/111/40005')
# Note: Test do not pass due to an arXiv API bug.
'1506.06690' | [
"Get",
"the",
"arXiv",
"eprint",
"id",
"for",
"a",
"given",
"DOI",
"."
] | 9ef1a29d2514157d1edd6c13ecbd61b07ae9315e | https://github.com/Phyks/libbmc/blob/9ef1a29d2514157d1edd6c13ecbd61b07ae9315e/libbmc/repositories/arxiv.py#L366-L397 | train |
Phyks/libbmc | libbmc/repositories/arxiv.py | get_sources | def get_sources(arxiv_id):
"""
Download sources on arXiv for a given preprint.
.. note::
Bulk download of sources from arXiv is not permitted by their API. \
You should have a look at http://arxiv.org/help/bulk_data_s3.
:param eprint: The arXiv id (e.g. ``1401.2910`` or ``1401.2910v1``) in a \
canonical form.
:returns: A ``TarFile`` object of the sources of the arXiv preprint or \
``None``.
"""
try:
request = requests.get(ARXIV_EPRINT_URL.format(arxiv_id=arxiv_id))
request.raise_for_status()
file_object = io.BytesIO(request.content)
return tarfile.open(fileobj=file_object)
except (RequestException, AssertionError, tarfile.TarError):
return None | python | def get_sources(arxiv_id):
"""
Download sources on arXiv for a given preprint.
.. note::
Bulk download of sources from arXiv is not permitted by their API. \
You should have a look at http://arxiv.org/help/bulk_data_s3.
:param eprint: The arXiv id (e.g. ``1401.2910`` or ``1401.2910v1``) in a \
canonical form.
:returns: A ``TarFile`` object of the sources of the arXiv preprint or \
``None``.
"""
try:
request = requests.get(ARXIV_EPRINT_URL.format(arxiv_id=arxiv_id))
request.raise_for_status()
file_object = io.BytesIO(request.content)
return tarfile.open(fileobj=file_object)
except (RequestException, AssertionError, tarfile.TarError):
return None | [
"def",
"get_sources",
"(",
"arxiv_id",
")",
":",
"try",
":",
"request",
"=",
"requests",
".",
"get",
"(",
"ARXIV_EPRINT_URL",
".",
"format",
"(",
"arxiv_id",
"=",
"arxiv_id",
")",
")",
"request",
".",
"raise_for_status",
"(",
")",
"file_object",
"=",
"io",
".",
"BytesIO",
"(",
"request",
".",
"content",
")",
"return",
"tarfile",
".",
"open",
"(",
"fileobj",
"=",
"file_object",
")",
"except",
"(",
"RequestException",
",",
"AssertionError",
",",
"tarfile",
".",
"TarError",
")",
":",
"return",
"None"
] | Download sources on arXiv for a given preprint.
.. note::
Bulk download of sources from arXiv is not permitted by their API. \
You should have a look at http://arxiv.org/help/bulk_data_s3.
:param eprint: The arXiv id (e.g. ``1401.2910`` or ``1401.2910v1``) in a \
canonical form.
:returns: A ``TarFile`` object of the sources of the arXiv preprint or \
``None``. | [
"Download",
"sources",
"on",
"arXiv",
"for",
"a",
"given",
"preprint",
"."
] | 9ef1a29d2514157d1edd6c13ecbd61b07ae9315e | https://github.com/Phyks/libbmc/blob/9ef1a29d2514157d1edd6c13ecbd61b07ae9315e/libbmc/repositories/arxiv.py#L435-L455 | train |
crm416/semantic | semantic/dates.py | extractDates | def extractDates(inp, tz=None, now=None):
"""Extract semantic date information from an input string.
This is a convenience method which would only be used if
you'd rather not initialize a DateService object.
Args:
inp (str): The input string to be parsed.
tz: An optional Pytz timezone. All datetime objects returned will
be relative to the supplied timezone, or timezone-less if none
is supplied.
now: The time to which all returned datetime objects should be
relative. For example, if the text is "In 5 hours", the
datetime returned will be now + datetime.timedelta(hours=5).
Uses datetime.datetime.now() if none is supplied.
Returns:
A list of datetime objects extracted from input.
"""
service = DateService(tz=tz, now=now)
return service.extractDates(inp) | python | def extractDates(inp, tz=None, now=None):
"""Extract semantic date information from an input string.
This is a convenience method which would only be used if
you'd rather not initialize a DateService object.
Args:
inp (str): The input string to be parsed.
tz: An optional Pytz timezone. All datetime objects returned will
be relative to the supplied timezone, or timezone-less if none
is supplied.
now: The time to which all returned datetime objects should be
relative. For example, if the text is "In 5 hours", the
datetime returned will be now + datetime.timedelta(hours=5).
Uses datetime.datetime.now() if none is supplied.
Returns:
A list of datetime objects extracted from input.
"""
service = DateService(tz=tz, now=now)
return service.extractDates(inp) | [
"def",
"extractDates",
"(",
"inp",
",",
"tz",
"=",
"None",
",",
"now",
"=",
"None",
")",
":",
"service",
"=",
"DateService",
"(",
"tz",
"=",
"tz",
",",
"now",
"=",
"now",
")",
"return",
"service",
".",
"extractDates",
"(",
"inp",
")"
] | Extract semantic date information from an input string.
This is a convenience method which would only be used if
you'd rather not initialize a DateService object.
Args:
inp (str): The input string to be parsed.
tz: An optional Pytz timezone. All datetime objects returned will
be relative to the supplied timezone, or timezone-less if none
is supplied.
now: The time to which all returned datetime objects should be
relative. For example, if the text is "In 5 hours", the
datetime returned will be now + datetime.timedelta(hours=5).
Uses datetime.datetime.now() if none is supplied.
Returns:
A list of datetime objects extracted from input. | [
"Extract",
"semantic",
"date",
"information",
"from",
"an",
"input",
"string",
".",
"This",
"is",
"a",
"convenience",
"method",
"which",
"would",
"only",
"be",
"used",
"if",
"you",
"d",
"rather",
"not",
"initialize",
"a",
"DateService",
"object",
"."
] | 46deb8fefb3ea58aad2fedc8d0d62f3ee254b8fe | https://github.com/crm416/semantic/blob/46deb8fefb3ea58aad2fedc8d0d62f3ee254b8fe/semantic/dates.py#L476-L495 | train |
crm416/semantic | semantic/dates.py | DateService.extractTimes | def extractTimes(self, inp):
"""Extracts time-related information from an input string.
Ignores any information related to the specific date, focusing
on the time-of-day.
Args:
inp (str): Input string to be parsed.
Returns:
A list of datetime objects containing the extracted times from the
input snippet, or an empty list if none found.
"""
def handleMatch(time):
relative = False
if not time:
return None
# Default times: 8am, 12pm, 7pm
elif time.group(1) == 'morning':
h = 8
m = 0
elif time.group(1) == 'afternoon':
h = 12
m = 0
elif time.group(1) == 'evening':
h = 19
m = 0
elif time.group(4) and time.group(5):
h, m = 0, 0
# Extract hours difference
converter = NumberService()
try:
diff = converter.parse(time.group(4))
except:
return None
if time.group(5) == 'hours':
h += diff
else:
m += diff
# Extract minutes difference
if time.group(6):
converter = NumberService()
try:
diff = converter.parse(time.group(7))
except:
return None
if time.group(8) == 'hours':
h += diff
else:
m += diff
relative = True
else:
# Convert from "HH:MM pm" format
t = time.group(2)
h, m = int(t.split(':')[0]) % 12, int(t.split(':')[1])
try:
if time.group(3) == 'pm':
h += 12
except IndexError:
pass
if relative:
return self.now + datetime.timedelta(hours=h, minutes=m)
else:
return datetime.datetime(
self.now.year, self.now.month, self.now.day, h, m
)
inp = self._preprocess(inp)
return [handleMatch(time) for time in self._timeRegex.finditer(inp)] | python | def extractTimes(self, inp):
"""Extracts time-related information from an input string.
Ignores any information related to the specific date, focusing
on the time-of-day.
Args:
inp (str): Input string to be parsed.
Returns:
A list of datetime objects containing the extracted times from the
input snippet, or an empty list if none found.
"""
def handleMatch(time):
relative = False
if not time:
return None
# Default times: 8am, 12pm, 7pm
elif time.group(1) == 'morning':
h = 8
m = 0
elif time.group(1) == 'afternoon':
h = 12
m = 0
elif time.group(1) == 'evening':
h = 19
m = 0
elif time.group(4) and time.group(5):
h, m = 0, 0
# Extract hours difference
converter = NumberService()
try:
diff = converter.parse(time.group(4))
except:
return None
if time.group(5) == 'hours':
h += diff
else:
m += diff
# Extract minutes difference
if time.group(6):
converter = NumberService()
try:
diff = converter.parse(time.group(7))
except:
return None
if time.group(8) == 'hours':
h += diff
else:
m += diff
relative = True
else:
# Convert from "HH:MM pm" format
t = time.group(2)
h, m = int(t.split(':')[0]) % 12, int(t.split(':')[1])
try:
if time.group(3) == 'pm':
h += 12
except IndexError:
pass
if relative:
return self.now + datetime.timedelta(hours=h, minutes=m)
else:
return datetime.datetime(
self.now.year, self.now.month, self.now.day, h, m
)
inp = self._preprocess(inp)
return [handleMatch(time) for time in self._timeRegex.finditer(inp)] | [
"def",
"extractTimes",
"(",
"self",
",",
"inp",
")",
":",
"def",
"handleMatch",
"(",
"time",
")",
":",
"relative",
"=",
"False",
"if",
"not",
"time",
":",
"return",
"None",
"# Default times: 8am, 12pm, 7pm",
"elif",
"time",
".",
"group",
"(",
"1",
")",
"==",
"'morning'",
":",
"h",
"=",
"8",
"m",
"=",
"0",
"elif",
"time",
".",
"group",
"(",
"1",
")",
"==",
"'afternoon'",
":",
"h",
"=",
"12",
"m",
"=",
"0",
"elif",
"time",
".",
"group",
"(",
"1",
")",
"==",
"'evening'",
":",
"h",
"=",
"19",
"m",
"=",
"0",
"elif",
"time",
".",
"group",
"(",
"4",
")",
"and",
"time",
".",
"group",
"(",
"5",
")",
":",
"h",
",",
"m",
"=",
"0",
",",
"0",
"# Extract hours difference",
"converter",
"=",
"NumberService",
"(",
")",
"try",
":",
"diff",
"=",
"converter",
".",
"parse",
"(",
"time",
".",
"group",
"(",
"4",
")",
")",
"except",
":",
"return",
"None",
"if",
"time",
".",
"group",
"(",
"5",
")",
"==",
"'hours'",
":",
"h",
"+=",
"diff",
"else",
":",
"m",
"+=",
"diff",
"# Extract minutes difference",
"if",
"time",
".",
"group",
"(",
"6",
")",
":",
"converter",
"=",
"NumberService",
"(",
")",
"try",
":",
"diff",
"=",
"converter",
".",
"parse",
"(",
"time",
".",
"group",
"(",
"7",
")",
")",
"except",
":",
"return",
"None",
"if",
"time",
".",
"group",
"(",
"8",
")",
"==",
"'hours'",
":",
"h",
"+=",
"diff",
"else",
":",
"m",
"+=",
"diff",
"relative",
"=",
"True",
"else",
":",
"# Convert from \"HH:MM pm\" format",
"t",
"=",
"time",
".",
"group",
"(",
"2",
")",
"h",
",",
"m",
"=",
"int",
"(",
"t",
".",
"split",
"(",
"':'",
")",
"[",
"0",
"]",
")",
"%",
"12",
",",
"int",
"(",
"t",
".",
"split",
"(",
"':'",
")",
"[",
"1",
"]",
")",
"try",
":",
"if",
"time",
".",
"group",
"(",
"3",
")",
"==",
"'pm'",
":",
"h",
"+=",
"12",
"except",
"IndexError",
":",
"pass",
"if",
"relative",
":",
"return",
"self",
".",
"now",
"+",
"datetime",
".",
"timedelta",
"(",
"hours",
"=",
"h",
",",
"minutes",
"=",
"m",
")",
"else",
":",
"return",
"datetime",
".",
"datetime",
"(",
"self",
".",
"now",
".",
"year",
",",
"self",
".",
"now",
".",
"month",
",",
"self",
".",
"now",
".",
"day",
",",
"h",
",",
"m",
")",
"inp",
"=",
"self",
".",
"_preprocess",
"(",
"inp",
")",
"return",
"[",
"handleMatch",
"(",
"time",
")",
"for",
"time",
"in",
"self",
".",
"_timeRegex",
".",
"finditer",
"(",
"inp",
")",
"]"
] | Extracts time-related information from an input string.
Ignores any information related to the specific date, focusing
on the time-of-day.
Args:
inp (str): Input string to be parsed.
Returns:
A list of datetime objects containing the extracted times from the
input snippet, or an empty list if none found. | [
"Extracts",
"time",
"-",
"related",
"information",
"from",
"an",
"input",
"string",
".",
"Ignores",
"any",
"information",
"related",
"to",
"the",
"specific",
"date",
"focusing",
"on",
"the",
"time",
"-",
"of",
"-",
"day",
"."
] | 46deb8fefb3ea58aad2fedc8d0d62f3ee254b8fe | https://github.com/crm416/semantic/blob/46deb8fefb3ea58aad2fedc8d0d62f3ee254b8fe/semantic/dates.py#L263-L339 | train |
crm416/semantic | semantic/dates.py | DateService.extractDates | def extractDates(self, inp):
"""Extract semantic date information from an input string.
In effect, runs both parseDay and parseTime on the input
string and merges the results to produce a comprehensive
datetime object.
Args:
inp (str): Input string to be parsed.
Returns:
A list of datetime objects containing the extracted dates from the
input snippet, or an empty list if not found.
"""
def merge(param):
day, time = param
if not (day or time):
return None
if not day:
return time
if not time:
return day
return datetime.datetime(
day.year, day.month, day.day, time.hour, time.minute
)
days = self.extractDays(inp)
times = self.extractTimes(inp)
return map(merge, zip_longest(days, times, fillvalue=None)) | python | def extractDates(self, inp):
"""Extract semantic date information from an input string.
In effect, runs both parseDay and parseTime on the input
string and merges the results to produce a comprehensive
datetime object.
Args:
inp (str): Input string to be parsed.
Returns:
A list of datetime objects containing the extracted dates from the
input snippet, or an empty list if not found.
"""
def merge(param):
day, time = param
if not (day or time):
return None
if not day:
return time
if not time:
return day
return datetime.datetime(
day.year, day.month, day.day, time.hour, time.minute
)
days = self.extractDays(inp)
times = self.extractTimes(inp)
return map(merge, zip_longest(days, times, fillvalue=None)) | [
"def",
"extractDates",
"(",
"self",
",",
"inp",
")",
":",
"def",
"merge",
"(",
"param",
")",
":",
"day",
",",
"time",
"=",
"param",
"if",
"not",
"(",
"day",
"or",
"time",
")",
":",
"return",
"None",
"if",
"not",
"day",
":",
"return",
"time",
"if",
"not",
"time",
":",
"return",
"day",
"return",
"datetime",
".",
"datetime",
"(",
"day",
".",
"year",
",",
"day",
".",
"month",
",",
"day",
".",
"day",
",",
"time",
".",
"hour",
",",
"time",
".",
"minute",
")",
"days",
"=",
"self",
".",
"extractDays",
"(",
"inp",
")",
"times",
"=",
"self",
".",
"extractTimes",
"(",
"inp",
")",
"return",
"map",
"(",
"merge",
",",
"zip_longest",
"(",
"days",
",",
"times",
",",
"fillvalue",
"=",
"None",
")",
")"
] | Extract semantic date information from an input string.
In effect, runs both parseDay and parseTime on the input
string and merges the results to produce a comprehensive
datetime object.
Args:
inp (str): Input string to be parsed.
Returns:
A list of datetime objects containing the extracted dates from the
input snippet, or an empty list if not found. | [
"Extract",
"semantic",
"date",
"information",
"from",
"an",
"input",
"string",
".",
"In",
"effect",
"runs",
"both",
"parseDay",
"and",
"parseTime",
"on",
"the",
"input",
"string",
"and",
"merges",
"the",
"results",
"to",
"produce",
"a",
"comprehensive",
"datetime",
"object",
"."
] | 46deb8fefb3ea58aad2fedc8d0d62f3ee254b8fe | https://github.com/crm416/semantic/blob/46deb8fefb3ea58aad2fedc8d0d62f3ee254b8fe/semantic/dates.py#L349-L378 | train |
crm416/semantic | semantic/dates.py | DateService.extractDate | def extractDate(self, inp):
"""Returns the first date found in the input string, or None if not
found."""
dates = self.extractDates(inp)
for date in dates:
return date
return None | python | def extractDate(self, inp):
"""Returns the first date found in the input string, or None if not
found."""
dates = self.extractDates(inp)
for date in dates:
return date
return None | [
"def",
"extractDate",
"(",
"self",
",",
"inp",
")",
":",
"dates",
"=",
"self",
".",
"extractDates",
"(",
"inp",
")",
"for",
"date",
"in",
"dates",
":",
"return",
"date",
"return",
"None"
] | Returns the first date found in the input string, or None if not
found. | [
"Returns",
"the",
"first",
"date",
"found",
"in",
"the",
"input",
"string",
"or",
"None",
"if",
"not",
"found",
"."
] | 46deb8fefb3ea58aad2fedc8d0d62f3ee254b8fe | https://github.com/crm416/semantic/blob/46deb8fefb3ea58aad2fedc8d0d62f3ee254b8fe/semantic/dates.py#L380-L386 | train |
crm416/semantic | semantic/dates.py | DateService.convertDay | def convertDay(self, day, prefix="", weekday=False):
"""Convert a datetime object representing a day into a human-ready
string that can be read, spoken aloud, etc.
Args:
day (datetime.date): A datetime object to be converted into text.
prefix (str): An optional argument that prefixes the converted
string. For example, if prefix="in", you'd receive "in two
days", rather than "two days", while the method would still
return "tomorrow" (rather than "in tomorrow").
weekday (bool): An optional argument that returns "Monday, Oct. 1"
if True, rather than "Oct. 1".
Returns:
A string representation of the input day, ignoring any time-related
information.
"""
def sameDay(d1, d2):
d = d1.day == d2.day
m = d1.month == d2.month
y = d1.year == d2.year
return d and m and y
tom = self.now + datetime.timedelta(days=1)
if sameDay(day, self.now):
return "today"
elif sameDay(day, tom):
return "tomorrow"
if weekday:
dayString = day.strftime("%A, %B %d")
else:
dayString = day.strftime("%B %d")
# Ex) Remove '0' from 'August 03'
if not int(dayString[-2]):
dayString = dayString[:-2] + dayString[-1]
return prefix + " " + dayString | python | def convertDay(self, day, prefix="", weekday=False):
"""Convert a datetime object representing a day into a human-ready
string that can be read, spoken aloud, etc.
Args:
day (datetime.date): A datetime object to be converted into text.
prefix (str): An optional argument that prefixes the converted
string. For example, if prefix="in", you'd receive "in two
days", rather than "two days", while the method would still
return "tomorrow" (rather than "in tomorrow").
weekday (bool): An optional argument that returns "Monday, Oct. 1"
if True, rather than "Oct. 1".
Returns:
A string representation of the input day, ignoring any time-related
information.
"""
def sameDay(d1, d2):
d = d1.day == d2.day
m = d1.month == d2.month
y = d1.year == d2.year
return d and m and y
tom = self.now + datetime.timedelta(days=1)
if sameDay(day, self.now):
return "today"
elif sameDay(day, tom):
return "tomorrow"
if weekday:
dayString = day.strftime("%A, %B %d")
else:
dayString = day.strftime("%B %d")
# Ex) Remove '0' from 'August 03'
if not int(dayString[-2]):
dayString = dayString[:-2] + dayString[-1]
return prefix + " " + dayString | [
"def",
"convertDay",
"(",
"self",
",",
"day",
",",
"prefix",
"=",
"\"\"",
",",
"weekday",
"=",
"False",
")",
":",
"def",
"sameDay",
"(",
"d1",
",",
"d2",
")",
":",
"d",
"=",
"d1",
".",
"day",
"==",
"d2",
".",
"day",
"m",
"=",
"d1",
".",
"month",
"==",
"d2",
".",
"month",
"y",
"=",
"d1",
".",
"year",
"==",
"d2",
".",
"year",
"return",
"d",
"and",
"m",
"and",
"y",
"tom",
"=",
"self",
".",
"now",
"+",
"datetime",
".",
"timedelta",
"(",
"days",
"=",
"1",
")",
"if",
"sameDay",
"(",
"day",
",",
"self",
".",
"now",
")",
":",
"return",
"\"today\"",
"elif",
"sameDay",
"(",
"day",
",",
"tom",
")",
":",
"return",
"\"tomorrow\"",
"if",
"weekday",
":",
"dayString",
"=",
"day",
".",
"strftime",
"(",
"\"%A, %B %d\"",
")",
"else",
":",
"dayString",
"=",
"day",
".",
"strftime",
"(",
"\"%B %d\"",
")",
"# Ex) Remove '0' from 'August 03'",
"if",
"not",
"int",
"(",
"dayString",
"[",
"-",
"2",
"]",
")",
":",
"dayString",
"=",
"dayString",
"[",
":",
"-",
"2",
"]",
"+",
"dayString",
"[",
"-",
"1",
"]",
"return",
"prefix",
"+",
"\" \"",
"+",
"dayString"
] | Convert a datetime object representing a day into a human-ready
string that can be read, spoken aloud, etc.
Args:
day (datetime.date): A datetime object to be converted into text.
prefix (str): An optional argument that prefixes the converted
string. For example, if prefix="in", you'd receive "in two
days", rather than "two days", while the method would still
return "tomorrow" (rather than "in tomorrow").
weekday (bool): An optional argument that returns "Monday, Oct. 1"
if True, rather than "Oct. 1".
Returns:
A string representation of the input day, ignoring any time-related
information. | [
"Convert",
"a",
"datetime",
"object",
"representing",
"a",
"day",
"into",
"a",
"human",
"-",
"ready",
"string",
"that",
"can",
"be",
"read",
"spoken",
"aloud",
"etc",
"."
] | 46deb8fefb3ea58aad2fedc8d0d62f3ee254b8fe | https://github.com/crm416/semantic/blob/46deb8fefb3ea58aad2fedc8d0d62f3ee254b8fe/semantic/dates.py#L388-L427 | train |
crm416/semantic | semantic/dates.py | DateService.convertTime | def convertTime(self, time):
"""Convert a datetime object representing a time into a human-ready
string that can be read, spoken aloud, etc.
Args:
time (datetime.date): A datetime object to be converted into text.
Returns:
A string representation of the input time, ignoring any day-related
information.
"""
# if ':00', ignore reporting minutes
m_format = ""
if time.minute:
m_format = ":%M"
timeString = time.strftime("%I" + m_format + " %p")
# if '07:30', cast to '7:30'
if not int(timeString[0]):
timeString = timeString[1:]
return timeString | python | def convertTime(self, time):
"""Convert a datetime object representing a time into a human-ready
string that can be read, spoken aloud, etc.
Args:
time (datetime.date): A datetime object to be converted into text.
Returns:
A string representation of the input time, ignoring any day-related
information.
"""
# if ':00', ignore reporting minutes
m_format = ""
if time.minute:
m_format = ":%M"
timeString = time.strftime("%I" + m_format + " %p")
# if '07:30', cast to '7:30'
if not int(timeString[0]):
timeString = timeString[1:]
return timeString | [
"def",
"convertTime",
"(",
"self",
",",
"time",
")",
":",
"# if ':00', ignore reporting minutes",
"m_format",
"=",
"\"\"",
"if",
"time",
".",
"minute",
":",
"m_format",
"=",
"\":%M\"",
"timeString",
"=",
"time",
".",
"strftime",
"(",
"\"%I\"",
"+",
"m_format",
"+",
"\" %p\"",
")",
"# if '07:30', cast to '7:30'",
"if",
"not",
"int",
"(",
"timeString",
"[",
"0",
"]",
")",
":",
"timeString",
"=",
"timeString",
"[",
"1",
":",
"]",
"return",
"timeString"
] | Convert a datetime object representing a time into a human-ready
string that can be read, spoken aloud, etc.
Args:
time (datetime.date): A datetime object to be converted into text.
Returns:
A string representation of the input time, ignoring any day-related
information. | [
"Convert",
"a",
"datetime",
"object",
"representing",
"a",
"time",
"into",
"a",
"human",
"-",
"ready",
"string",
"that",
"can",
"be",
"read",
"spoken",
"aloud",
"etc",
"."
] | 46deb8fefb3ea58aad2fedc8d0d62f3ee254b8fe | https://github.com/crm416/semantic/blob/46deb8fefb3ea58aad2fedc8d0d62f3ee254b8fe/semantic/dates.py#L429-L451 | train |
crm416/semantic | semantic/dates.py | DateService.convertDate | def convertDate(self, date, prefix="", weekday=False):
"""Convert a datetime object representing into a human-ready
string that can be read, spoken aloud, etc. In effect, runs
both convertDay and convertTime on the input, merging the results.
Args:
date (datetime.date): A datetime object to be converted into text.
prefix (str): An optional argument that prefixes the converted
string. For example, if prefix="in", you'd receive "in two
days", rather than "two days", while the method would still
return "tomorrow" (rather than "in tomorrow").
weekday (bool): An optional argument that returns "Monday, Oct. 1"
if True, rather than "Oct. 1".
Returns:
A string representation of the input day and time.
"""
dayString = self.convertDay(
date, prefix=prefix, weekday=weekday)
timeString = self.convertTime(date)
return dayString + " at " + timeString | python | def convertDate(self, date, prefix="", weekday=False):
"""Convert a datetime object representing into a human-ready
string that can be read, spoken aloud, etc. In effect, runs
both convertDay and convertTime on the input, merging the results.
Args:
date (datetime.date): A datetime object to be converted into text.
prefix (str): An optional argument that prefixes the converted
string. For example, if prefix="in", you'd receive "in two
days", rather than "two days", while the method would still
return "tomorrow" (rather than "in tomorrow").
weekday (bool): An optional argument that returns "Monday, Oct. 1"
if True, rather than "Oct. 1".
Returns:
A string representation of the input day and time.
"""
dayString = self.convertDay(
date, prefix=prefix, weekday=weekday)
timeString = self.convertTime(date)
return dayString + " at " + timeString | [
"def",
"convertDate",
"(",
"self",
",",
"date",
",",
"prefix",
"=",
"\"\"",
",",
"weekday",
"=",
"False",
")",
":",
"dayString",
"=",
"self",
".",
"convertDay",
"(",
"date",
",",
"prefix",
"=",
"prefix",
",",
"weekday",
"=",
"weekday",
")",
"timeString",
"=",
"self",
".",
"convertTime",
"(",
"date",
")",
"return",
"dayString",
"+",
"\" at \"",
"+",
"timeString"
] | Convert a datetime object representing into a human-ready
string that can be read, spoken aloud, etc. In effect, runs
both convertDay and convertTime on the input, merging the results.
Args:
date (datetime.date): A datetime object to be converted into text.
prefix (str): An optional argument that prefixes the converted
string. For example, if prefix="in", you'd receive "in two
days", rather than "two days", while the method would still
return "tomorrow" (rather than "in tomorrow").
weekday (bool): An optional argument that returns "Monday, Oct. 1"
if True, rather than "Oct. 1".
Returns:
A string representation of the input day and time. | [
"Convert",
"a",
"datetime",
"object",
"representing",
"into",
"a",
"human",
"-",
"ready",
"string",
"that",
"can",
"be",
"read",
"spoken",
"aloud",
"etc",
".",
"In",
"effect",
"runs",
"both",
"convertDay",
"and",
"convertTime",
"on",
"the",
"input",
"merging",
"the",
"results",
"."
] | 46deb8fefb3ea58aad2fedc8d0d62f3ee254b8fe | https://github.com/crm416/semantic/blob/46deb8fefb3ea58aad2fedc8d0d62f3ee254b8fe/semantic/dates.py#L453-L473 | train |
SandstoneHPC/sandstone-ide | sandstone/lib/filesystem/handlers.py | FilesystemHandler._move | def _move(self):
"""
Called during a PUT request where the action specifies
a move operation. Returns resource URI of the destination file.
"""
newpath = self.action['newpath']
try:
self.fs.move(self.fp,newpath)
except OSError:
raise tornado.web.HTTPError(400)
return newpath | python | def _move(self):
"""
Called during a PUT request where the action specifies
a move operation. Returns resource URI of the destination file.
"""
newpath = self.action['newpath']
try:
self.fs.move(self.fp,newpath)
except OSError:
raise tornado.web.HTTPError(400)
return newpath | [
"def",
"_move",
"(",
"self",
")",
":",
"newpath",
"=",
"self",
".",
"action",
"[",
"'newpath'",
"]",
"try",
":",
"self",
".",
"fs",
".",
"move",
"(",
"self",
".",
"fp",
",",
"newpath",
")",
"except",
"OSError",
":",
"raise",
"tornado",
".",
"web",
".",
"HTTPError",
"(",
"400",
")",
"return",
"newpath"
] | Called during a PUT request where the action specifies
a move operation. Returns resource URI of the destination file. | [
"Called",
"during",
"a",
"PUT",
"request",
"where",
"the",
"action",
"specifies",
"a",
"move",
"operation",
".",
"Returns",
"resource",
"URI",
"of",
"the",
"destination",
"file",
"."
] | 7a47947fb07281c3e3018042863dc67e7e56dc04 | https://github.com/SandstoneHPC/sandstone-ide/blob/7a47947fb07281c3e3018042863dc67e7e56dc04/sandstone/lib/filesystem/handlers.py#L32-L42 | train |
SandstoneHPC/sandstone-ide | sandstone/lib/filesystem/handlers.py | FilesystemHandler._copy | def _copy(self):
"""
Called during a PUT request where the action specifies
a copy operation. Returns resource URI of the new file.
"""
copypath = self.action['copypath']
try:
self.fs.copy(self.fp,copypath)
except OSError:
raise tornado.web.HTTPError(400)
return copypath | python | def _copy(self):
"""
Called during a PUT request where the action specifies
a copy operation. Returns resource URI of the new file.
"""
copypath = self.action['copypath']
try:
self.fs.copy(self.fp,copypath)
except OSError:
raise tornado.web.HTTPError(400)
return copypath | [
"def",
"_copy",
"(",
"self",
")",
":",
"copypath",
"=",
"self",
".",
"action",
"[",
"'copypath'",
"]",
"try",
":",
"self",
".",
"fs",
".",
"copy",
"(",
"self",
".",
"fp",
",",
"copypath",
")",
"except",
"OSError",
":",
"raise",
"tornado",
".",
"web",
".",
"HTTPError",
"(",
"400",
")",
"return",
"copypath"
] | Called during a PUT request where the action specifies
a copy operation. Returns resource URI of the new file. | [
"Called",
"during",
"a",
"PUT",
"request",
"where",
"the",
"action",
"specifies",
"a",
"copy",
"operation",
".",
"Returns",
"resource",
"URI",
"of",
"the",
"new",
"file",
"."
] | 7a47947fb07281c3e3018042863dc67e7e56dc04 | https://github.com/SandstoneHPC/sandstone-ide/blob/7a47947fb07281c3e3018042863dc67e7e56dc04/sandstone/lib/filesystem/handlers.py#L44-L54 | train |
SandstoneHPC/sandstone-ide | sandstone/lib/filesystem/handlers.py | FilesystemHandler._rename | def _rename(self):
"""
Called during a PUT request where the action specifies
a rename operation. Returns resource URI of the renamed file.
"""
newname = self.action['newname']
try:
newpath = self.fs.rename(self.fp,newname)
except OSError:
raise tornado.web.HTTPError(400)
return newpath | python | def _rename(self):
"""
Called during a PUT request where the action specifies
a rename operation. Returns resource URI of the renamed file.
"""
newname = self.action['newname']
try:
newpath = self.fs.rename(self.fp,newname)
except OSError:
raise tornado.web.HTTPError(400)
return newpath | [
"def",
"_rename",
"(",
"self",
")",
":",
"newname",
"=",
"self",
".",
"action",
"[",
"'newname'",
"]",
"try",
":",
"newpath",
"=",
"self",
".",
"fs",
".",
"rename",
"(",
"self",
".",
"fp",
",",
"newname",
")",
"except",
"OSError",
":",
"raise",
"tornado",
".",
"web",
".",
"HTTPError",
"(",
"400",
")",
"return",
"newpath"
] | Called during a PUT request where the action specifies
a rename operation. Returns resource URI of the renamed file. | [
"Called",
"during",
"a",
"PUT",
"request",
"where",
"the",
"action",
"specifies",
"a",
"rename",
"operation",
".",
"Returns",
"resource",
"URI",
"of",
"the",
"renamed",
"file",
"."
] | 7a47947fb07281c3e3018042863dc67e7e56dc04 | https://github.com/SandstoneHPC/sandstone-ide/blob/7a47947fb07281c3e3018042863dc67e7e56dc04/sandstone/lib/filesystem/handlers.py#L56-L66 | train |
SandstoneHPC/sandstone-ide | sandstone/lib/filesystem/handlers.py | FilesystemHandler.get | def get(self):
"""
Return details for the filesystem, including configured volumes.
"""
res = self.fs.get_filesystem_details()
res = res.to_dict()
self.write(res) | python | def get(self):
"""
Return details for the filesystem, including configured volumes.
"""
res = self.fs.get_filesystem_details()
res = res.to_dict()
self.write(res) | [
"def",
"get",
"(",
"self",
")",
":",
"res",
"=",
"self",
".",
"fs",
".",
"get_filesystem_details",
"(",
")",
"res",
"=",
"res",
".",
"to_dict",
"(",
")",
"self",
".",
"write",
"(",
"res",
")"
] | Return details for the filesystem, including configured volumes. | [
"Return",
"details",
"for",
"the",
"filesystem",
"including",
"configured",
"volumes",
"."
] | 7a47947fb07281c3e3018042863dc67e7e56dc04 | https://github.com/SandstoneHPC/sandstone-ide/blob/7a47947fb07281c3e3018042863dc67e7e56dc04/sandstone/lib/filesystem/handlers.py#L69-L75 | train |
SandstoneHPC/sandstone-ide | sandstone/lib/filesystem/handlers.py | FilesystemHandler.put | def put(self):
"""
Provides move, copy, and rename functionality. An action must be
specified when calling this method.
"""
self.fp = self.get_body_argument('filepath')
self.action = self.get_body_argument('action')
try:
ptype = self.fs.get_type_from_path(self.fp)
except OSError:
raise tornado.web.HTTPError(404)
if ptype == 'directory':
self.handler_name = 'filesystem:directories-details'
else:
self.handler_name = 'filesystem:files-details'
if self.action['action'] == 'move':
newpath = self._move()
self.write({'filepath':newpath})
elif self.action['action'] == 'copy':
newpath = self._copy()
self.write({'filepath':newpath})
elif self.action['action'] == 'rename':
newpath = self._rename()
self.write({'filepath':newpath})
else:
raise tornado.web.HTTPError(400) | python | def put(self):
"""
Provides move, copy, and rename functionality. An action must be
specified when calling this method.
"""
self.fp = self.get_body_argument('filepath')
self.action = self.get_body_argument('action')
try:
ptype = self.fs.get_type_from_path(self.fp)
except OSError:
raise tornado.web.HTTPError(404)
if ptype == 'directory':
self.handler_name = 'filesystem:directories-details'
else:
self.handler_name = 'filesystem:files-details'
if self.action['action'] == 'move':
newpath = self._move()
self.write({'filepath':newpath})
elif self.action['action'] == 'copy':
newpath = self._copy()
self.write({'filepath':newpath})
elif self.action['action'] == 'rename':
newpath = self._rename()
self.write({'filepath':newpath})
else:
raise tornado.web.HTTPError(400) | [
"def",
"put",
"(",
"self",
")",
":",
"self",
".",
"fp",
"=",
"self",
".",
"get_body_argument",
"(",
"'filepath'",
")",
"self",
".",
"action",
"=",
"self",
".",
"get_body_argument",
"(",
"'action'",
")",
"try",
":",
"ptype",
"=",
"self",
".",
"fs",
".",
"get_type_from_path",
"(",
"self",
".",
"fp",
")",
"except",
"OSError",
":",
"raise",
"tornado",
".",
"web",
".",
"HTTPError",
"(",
"404",
")",
"if",
"ptype",
"==",
"'directory'",
":",
"self",
".",
"handler_name",
"=",
"'filesystem:directories-details'",
"else",
":",
"self",
".",
"handler_name",
"=",
"'filesystem:files-details'",
"if",
"self",
".",
"action",
"[",
"'action'",
"]",
"==",
"'move'",
":",
"newpath",
"=",
"self",
".",
"_move",
"(",
")",
"self",
".",
"write",
"(",
"{",
"'filepath'",
":",
"newpath",
"}",
")",
"elif",
"self",
".",
"action",
"[",
"'action'",
"]",
"==",
"'copy'",
":",
"newpath",
"=",
"self",
".",
"_copy",
"(",
")",
"self",
".",
"write",
"(",
"{",
"'filepath'",
":",
"newpath",
"}",
")",
"elif",
"self",
".",
"action",
"[",
"'action'",
"]",
"==",
"'rename'",
":",
"newpath",
"=",
"self",
".",
"_rename",
"(",
")",
"self",
".",
"write",
"(",
"{",
"'filepath'",
":",
"newpath",
"}",
")",
"else",
":",
"raise",
"tornado",
".",
"web",
".",
"HTTPError",
"(",
"400",
")"
] | Provides move, copy, and rename functionality. An action must be
specified when calling this method. | [
"Provides",
"move",
"copy",
"and",
"rename",
"functionality",
".",
"An",
"action",
"must",
"be",
"specified",
"when",
"calling",
"this",
"method",
"."
] | 7a47947fb07281c3e3018042863dc67e7e56dc04 | https://github.com/SandstoneHPC/sandstone-ide/blob/7a47947fb07281c3e3018042863dc67e7e56dc04/sandstone/lib/filesystem/handlers.py#L78-L105 | train |
SandstoneHPC/sandstone-ide | sandstone/lib/filesystem/handlers.py | FilewatcherCreateHandler.post | def post(self, *args):
"""
Start a new filewatcher at the specified path.
"""
filepath = self.get_body_argument('filepath')
if not self.fs.exists(filepath):
raise tornado.web.HTTPError(404)
Filewatcher.add_directory_to_watch(filepath)
self.write({'msg':'Watcher added for {}'.format(filepath)}) | python | def post(self, *args):
"""
Start a new filewatcher at the specified path.
"""
filepath = self.get_body_argument('filepath')
if not self.fs.exists(filepath):
raise tornado.web.HTTPError(404)
Filewatcher.add_directory_to_watch(filepath)
self.write({'msg':'Watcher added for {}'.format(filepath)}) | [
"def",
"post",
"(",
"self",
",",
"*",
"args",
")",
":",
"filepath",
"=",
"self",
".",
"get_body_argument",
"(",
"'filepath'",
")",
"if",
"not",
"self",
".",
"fs",
".",
"exists",
"(",
"filepath",
")",
":",
"raise",
"tornado",
".",
"web",
".",
"HTTPError",
"(",
"404",
")",
"Filewatcher",
".",
"add_directory_to_watch",
"(",
"filepath",
")",
"self",
".",
"write",
"(",
"{",
"'msg'",
":",
"'Watcher added for {}'",
".",
"format",
"(",
"filepath",
")",
"}",
")"
] | Start a new filewatcher at the specified path. | [
"Start",
"a",
"new",
"filewatcher",
"at",
"the",
"specified",
"path",
"."
] | 7a47947fb07281c3e3018042863dc67e7e56dc04 | https://github.com/SandstoneHPC/sandstone-ide/blob/7a47947fb07281c3e3018042863dc67e7e56dc04/sandstone/lib/filesystem/handlers.py#L113-L122 | train |
SandstoneHPC/sandstone-ide | sandstone/lib/filesystem/handlers.py | FilewatcherDeleteHandler.delete | def delete(self, filepath):
"""
Stop and delete the specified filewatcher.
"""
Filewatcher.remove_directory_to_watch(filepath)
self.write({'msg':'Watcher deleted for {}'.format(filepath)}) | python | def delete(self, filepath):
"""
Stop and delete the specified filewatcher.
"""
Filewatcher.remove_directory_to_watch(filepath)
self.write({'msg':'Watcher deleted for {}'.format(filepath)}) | [
"def",
"delete",
"(",
"self",
",",
"filepath",
")",
":",
"Filewatcher",
".",
"remove_directory_to_watch",
"(",
"filepath",
")",
"self",
".",
"write",
"(",
"{",
"'msg'",
":",
"'Watcher deleted for {}'",
".",
"format",
"(",
"filepath",
")",
"}",
")"
] | Stop and delete the specified filewatcher. | [
"Stop",
"and",
"delete",
"the",
"specified",
"filewatcher",
"."
] | 7a47947fb07281c3e3018042863dc67e7e56dc04 | https://github.com/SandstoneHPC/sandstone-ide/blob/7a47947fb07281c3e3018042863dc67e7e56dc04/sandstone/lib/filesystem/handlers.py#L129-L134 | train |
SandstoneHPC/sandstone-ide | sandstone/lib/filesystem/handlers.py | FileHandler.get | def get(self, filepath):
"""
Get file details for the specified file.
"""
try:
res = self.fs.get_file_details(filepath)
res = res.to_dict()
self.write(res)
except OSError:
raise tornado.web.HTTPError(404) | python | def get(self, filepath):
"""
Get file details for the specified file.
"""
try:
res = self.fs.get_file_details(filepath)
res = res.to_dict()
self.write(res)
except OSError:
raise tornado.web.HTTPError(404) | [
"def",
"get",
"(",
"self",
",",
"filepath",
")",
":",
"try",
":",
"res",
"=",
"self",
".",
"fs",
".",
"get_file_details",
"(",
"filepath",
")",
"res",
"=",
"res",
".",
"to_dict",
"(",
")",
"self",
".",
"write",
"(",
"res",
")",
"except",
"OSError",
":",
"raise",
"tornado",
".",
"web",
".",
"HTTPError",
"(",
"404",
")"
] | Get file details for the specified file. | [
"Get",
"file",
"details",
"for",
"the",
"specified",
"file",
"."
] | 7a47947fb07281c3e3018042863dc67e7e56dc04 | https://github.com/SandstoneHPC/sandstone-ide/blob/7a47947fb07281c3e3018042863dc67e7e56dc04/sandstone/lib/filesystem/handlers.py#L144-L153 | train |
SandstoneHPC/sandstone-ide | sandstone/lib/filesystem/handlers.py | FileHandler.put | def put(self, filepath):
"""
Change the group or permissions of the specified file. Action
must be specified when calling this method.
"""
action = self.get_body_argument('action')
if action['action'] == 'update_group':
newgrp = action['group']
try:
self.fs.update_group(filepath,newgrp)
self.write({'msg':'Updated group for {}'.format(filepath)})
except OSError:
raise tornado.web.HTTPError(404)
elif action['action'] == 'update_permissions':
newperms = action['permissions']
try:
self.fs.update_permissions(filepath,newperms)
self.write({'msg':'Updated permissions for {}'.format(filepath)})
except OSError:
raise tornado.web.HTTPError(404)
else:
raise tornado.web.HTTPError(400) | python | def put(self, filepath):
"""
Change the group or permissions of the specified file. Action
must be specified when calling this method.
"""
action = self.get_body_argument('action')
if action['action'] == 'update_group':
newgrp = action['group']
try:
self.fs.update_group(filepath,newgrp)
self.write({'msg':'Updated group for {}'.format(filepath)})
except OSError:
raise tornado.web.HTTPError(404)
elif action['action'] == 'update_permissions':
newperms = action['permissions']
try:
self.fs.update_permissions(filepath,newperms)
self.write({'msg':'Updated permissions for {}'.format(filepath)})
except OSError:
raise tornado.web.HTTPError(404)
else:
raise tornado.web.HTTPError(400) | [
"def",
"put",
"(",
"self",
",",
"filepath",
")",
":",
"action",
"=",
"self",
".",
"get_body_argument",
"(",
"'action'",
")",
"if",
"action",
"[",
"'action'",
"]",
"==",
"'update_group'",
":",
"newgrp",
"=",
"action",
"[",
"'group'",
"]",
"try",
":",
"self",
".",
"fs",
".",
"update_group",
"(",
"filepath",
",",
"newgrp",
")",
"self",
".",
"write",
"(",
"{",
"'msg'",
":",
"'Updated group for {}'",
".",
"format",
"(",
"filepath",
")",
"}",
")",
"except",
"OSError",
":",
"raise",
"tornado",
".",
"web",
".",
"HTTPError",
"(",
"404",
")",
"elif",
"action",
"[",
"'action'",
"]",
"==",
"'update_permissions'",
":",
"newperms",
"=",
"action",
"[",
"'permissions'",
"]",
"try",
":",
"self",
".",
"fs",
".",
"update_permissions",
"(",
"filepath",
",",
"newperms",
")",
"self",
".",
"write",
"(",
"{",
"'msg'",
":",
"'Updated permissions for {}'",
".",
"format",
"(",
"filepath",
")",
"}",
")",
"except",
"OSError",
":",
"raise",
"tornado",
".",
"web",
".",
"HTTPError",
"(",
"404",
")",
"else",
":",
"raise",
"tornado",
".",
"web",
".",
"HTTPError",
"(",
"400",
")"
] | Change the group or permissions of the specified file. Action
must be specified when calling this method. | [
"Change",
"the",
"group",
"or",
"permissions",
"of",
"the",
"specified",
"file",
".",
"Action",
"must",
"be",
"specified",
"when",
"calling",
"this",
"method",
"."
] | 7a47947fb07281c3e3018042863dc67e7e56dc04 | https://github.com/SandstoneHPC/sandstone-ide/blob/7a47947fb07281c3e3018042863dc67e7e56dc04/sandstone/lib/filesystem/handlers.py#L156-L178 | train |
SandstoneHPC/sandstone-ide | sandstone/lib/filesystem/handlers.py | FileHandler.delete | def delete(self, filepath):
"""
Delete the specified file.
"""
try:
self.fs.delete(filepath)
self.write({'msg':'File deleted at {}'.format(filepath)})
except OSError:
raise tornado.web.HTTPError(404) | python | def delete(self, filepath):
"""
Delete the specified file.
"""
try:
self.fs.delete(filepath)
self.write({'msg':'File deleted at {}'.format(filepath)})
except OSError:
raise tornado.web.HTTPError(404) | [
"def",
"delete",
"(",
"self",
",",
"filepath",
")",
":",
"try",
":",
"self",
".",
"fs",
".",
"delete",
"(",
"filepath",
")",
"self",
".",
"write",
"(",
"{",
"'msg'",
":",
"'File deleted at {}'",
".",
"format",
"(",
"filepath",
")",
"}",
")",
"except",
"OSError",
":",
"raise",
"tornado",
".",
"web",
".",
"HTTPError",
"(",
"404",
")"
] | Delete the specified file. | [
"Delete",
"the",
"specified",
"file",
"."
] | 7a47947fb07281c3e3018042863dc67e7e56dc04 | https://github.com/SandstoneHPC/sandstone-ide/blob/7a47947fb07281c3e3018042863dc67e7e56dc04/sandstone/lib/filesystem/handlers.py#L181-L189 | train |
SandstoneHPC/sandstone-ide | sandstone/lib/filesystem/handlers.py | DirectoryCreateHandler.post | def post(self):
"""
Create a new directory at the specified path.
"""
filepath = self.get_body_argument('filepath')
try:
self.fs.create_directory(filepath)
encoded_filepath = tornado.escape.url_escape(filepath,plus=True)
resource_uri = self.reverse_url('filesystem:directories-details', encoded_filepath)
self.write({'uri':resource_uri})
except OSError:
raise tornado.web.HTTPError(404) | python | def post(self):
"""
Create a new directory at the specified path.
"""
filepath = self.get_body_argument('filepath')
try:
self.fs.create_directory(filepath)
encoded_filepath = tornado.escape.url_escape(filepath,plus=True)
resource_uri = self.reverse_url('filesystem:directories-details', encoded_filepath)
self.write({'uri':resource_uri})
except OSError:
raise tornado.web.HTTPError(404) | [
"def",
"post",
"(",
"self",
")",
":",
"filepath",
"=",
"self",
".",
"get_body_argument",
"(",
"'filepath'",
")",
"try",
":",
"self",
".",
"fs",
".",
"create_directory",
"(",
"filepath",
")",
"encoded_filepath",
"=",
"tornado",
".",
"escape",
".",
"url_escape",
"(",
"filepath",
",",
"plus",
"=",
"True",
")",
"resource_uri",
"=",
"self",
".",
"reverse_url",
"(",
"'filesystem:directories-details'",
",",
"encoded_filepath",
")",
"self",
".",
"write",
"(",
"{",
"'uri'",
":",
"resource_uri",
"}",
")",
"except",
"OSError",
":",
"raise",
"tornado",
".",
"web",
".",
"HTTPError",
"(",
"404",
")"
] | Create a new directory at the specified path. | [
"Create",
"a",
"new",
"directory",
"at",
"the",
"specified",
"path",
"."
] | 7a47947fb07281c3e3018042863dc67e7e56dc04 | https://github.com/SandstoneHPC/sandstone-ide/blob/7a47947fb07281c3e3018042863dc67e7e56dc04/sandstone/lib/filesystem/handlers.py#L255-L267 | train |
SandstoneHPC/sandstone-ide | sandstone/lib/filesystem/handlers.py | FileContentsHandler.get | def get(self, filepath):
"""
Get the contents of the specified file.
"""
exists = self.fs.exists(filepath)
if exists:
mime = magic.Magic(mime=True)
mime_type = mime.from_file(filepath)
if mime_type in self.unsupported_types:
self.set_status(204)
return
else:
contents = self.fs.read_file(filepath)
self.write({'filepath':filepath,'contents': contents})
else:
raise tornado.web.HTTPError(404) | python | def get(self, filepath):
"""
Get the contents of the specified file.
"""
exists = self.fs.exists(filepath)
if exists:
mime = magic.Magic(mime=True)
mime_type = mime.from_file(filepath)
if mime_type in self.unsupported_types:
self.set_status(204)
return
else:
contents = self.fs.read_file(filepath)
self.write({'filepath':filepath,'contents': contents})
else:
raise tornado.web.HTTPError(404) | [
"def",
"get",
"(",
"self",
",",
"filepath",
")",
":",
"exists",
"=",
"self",
".",
"fs",
".",
"exists",
"(",
"filepath",
")",
"if",
"exists",
":",
"mime",
"=",
"magic",
".",
"Magic",
"(",
"mime",
"=",
"True",
")",
"mime_type",
"=",
"mime",
".",
"from_file",
"(",
"filepath",
")",
"if",
"mime_type",
"in",
"self",
".",
"unsupported_types",
":",
"self",
".",
"set_status",
"(",
"204",
")",
"return",
"else",
":",
"contents",
"=",
"self",
".",
"fs",
".",
"read_file",
"(",
"filepath",
")",
"self",
".",
"write",
"(",
"{",
"'filepath'",
":",
"filepath",
",",
"'contents'",
":",
"contents",
"}",
")",
"else",
":",
"raise",
"tornado",
".",
"web",
".",
"HTTPError",
"(",
"404",
")"
] | Get the contents of the specified file. | [
"Get",
"the",
"contents",
"of",
"the",
"specified",
"file",
"."
] | 7a47947fb07281c3e3018042863dc67e7e56dc04 | https://github.com/SandstoneHPC/sandstone-ide/blob/7a47947fb07281c3e3018042863dc67e7e56dc04/sandstone/lib/filesystem/handlers.py#L277-L292 | train |
SandstoneHPC/sandstone-ide | sandstone/lib/filesystem/handlers.py | FileContentsHandler.post | def post(self, filepath):
"""
Write the given contents to the specified file. This is not
an append, all file contents will be replaced by the contents
given.
"""
try:
content = self.get_body_argument('content')
self.fs.write_file(filepath, content)
self.write({'msg': 'Updated file at {}'.format(filepath)})
except OSError:
raise tornado.web.HTTPError(404) | python | def post(self, filepath):
"""
Write the given contents to the specified file. This is not
an append, all file contents will be replaced by the contents
given.
"""
try:
content = self.get_body_argument('content')
self.fs.write_file(filepath, content)
self.write({'msg': 'Updated file at {}'.format(filepath)})
except OSError:
raise tornado.web.HTTPError(404) | [
"def",
"post",
"(",
"self",
",",
"filepath",
")",
":",
"try",
":",
"content",
"=",
"self",
".",
"get_body_argument",
"(",
"'content'",
")",
"self",
".",
"fs",
".",
"write_file",
"(",
"filepath",
",",
"content",
")",
"self",
".",
"write",
"(",
"{",
"'msg'",
":",
"'Updated file at {}'",
".",
"format",
"(",
"filepath",
")",
"}",
")",
"except",
"OSError",
":",
"raise",
"tornado",
".",
"web",
".",
"HTTPError",
"(",
"404",
")"
] | Write the given contents to the specified file. This is not
an append, all file contents will be replaced by the contents
given. | [
"Write",
"the",
"given",
"contents",
"to",
"the",
"specified",
"file",
".",
"This",
"is",
"not",
"an",
"append",
"all",
"file",
"contents",
"will",
"be",
"replaced",
"by",
"the",
"contents",
"given",
"."
] | 7a47947fb07281c3e3018042863dc67e7e56dc04 | https://github.com/SandstoneHPC/sandstone-ide/blob/7a47947fb07281c3e3018042863dc67e7e56dc04/sandstone/lib/filesystem/handlers.py#L295-L306 | train |
SandstoneHPC/sandstone-ide | sandstone/lib/filesystem/handlers.py | FileDownloadHandler.get_content | def get_content(self, start=None, end=None):
"""
Retrieve the content of the requested resource which is located
at the given absolute path.
This method should either return a byte string or an iterator
of byte strings. The latter is preferred for large files
as it helps reduce memory fragmentation.
"""
with open(self.filepath, "rb") as file:
if start is not None:
file.seek(start)
if end is not None:
remaining = end - (start or 0)
else:
remaining = None
while True:
chunk_size = 64 * 1024
if remaining is not None and remaining < chunk_size:
chunk_size = remaining
chunk = file.read(chunk_size)
if chunk:
if remaining is not None:
remaining -= len(chunk)
yield chunk
else:
if remaining is not None:
assert remaining == 0
return | python | def get_content(self, start=None, end=None):
"""
Retrieve the content of the requested resource which is located
at the given absolute path.
This method should either return a byte string or an iterator
of byte strings. The latter is preferred for large files
as it helps reduce memory fragmentation.
"""
with open(self.filepath, "rb") as file:
if start is not None:
file.seek(start)
if end is not None:
remaining = end - (start or 0)
else:
remaining = None
while True:
chunk_size = 64 * 1024
if remaining is not None and remaining < chunk_size:
chunk_size = remaining
chunk = file.read(chunk_size)
if chunk:
if remaining is not None:
remaining -= len(chunk)
yield chunk
else:
if remaining is not None:
assert remaining == 0
return | [
"def",
"get_content",
"(",
"self",
",",
"start",
"=",
"None",
",",
"end",
"=",
"None",
")",
":",
"with",
"open",
"(",
"self",
".",
"filepath",
",",
"\"rb\"",
")",
"as",
"file",
":",
"if",
"start",
"is",
"not",
"None",
":",
"file",
".",
"seek",
"(",
"start",
")",
"if",
"end",
"is",
"not",
"None",
":",
"remaining",
"=",
"end",
"-",
"(",
"start",
"or",
"0",
")",
"else",
":",
"remaining",
"=",
"None",
"while",
"True",
":",
"chunk_size",
"=",
"64",
"*",
"1024",
"if",
"remaining",
"is",
"not",
"None",
"and",
"remaining",
"<",
"chunk_size",
":",
"chunk_size",
"=",
"remaining",
"chunk",
"=",
"file",
".",
"read",
"(",
"chunk_size",
")",
"if",
"chunk",
":",
"if",
"remaining",
"is",
"not",
"None",
":",
"remaining",
"-=",
"len",
"(",
"chunk",
")",
"yield",
"chunk",
"else",
":",
"if",
"remaining",
"is",
"not",
"None",
":",
"assert",
"remaining",
"==",
"0",
"return"
] | Retrieve the content of the requested resource which is located
at the given absolute path.
This method should either return a byte string or an iterator
of byte strings. The latter is preferred for large files
as it helps reduce memory fragmentation. | [
"Retrieve",
"the",
"content",
"of",
"the",
"requested",
"resource",
"which",
"is",
"located",
"at",
"the",
"given",
"absolute",
"path",
".",
"This",
"method",
"should",
"either",
"return",
"a",
"byte",
"string",
"or",
"an",
"iterator",
"of",
"byte",
"strings",
".",
"The",
"latter",
"is",
"preferred",
"for",
"large",
"files",
"as",
"it",
"helps",
"reduce",
"memory",
"fragmentation",
"."
] | 7a47947fb07281c3e3018042863dc67e7e56dc04 | https://github.com/SandstoneHPC/sandstone-ide/blob/7a47947fb07281c3e3018042863dc67e7e56dc04/sandstone/lib/filesystem/handlers.py#L387-L414 | train |
SandstoneHPC/sandstone-ide | sandstone/lib/filesystem/handlers.py | FileDownloadHandler.set_headers | def set_headers(self):
"""
Sets the content headers on the response.
"""
self.set_header("Accept-Ranges", "bytes")
content_type = self.get_content_type()
if content_type:
self.set_header("Content-Type", content_type) | python | def set_headers(self):
"""
Sets the content headers on the response.
"""
self.set_header("Accept-Ranges", "bytes")
content_type = self.get_content_type()
if content_type:
self.set_header("Content-Type", content_type) | [
"def",
"set_headers",
"(",
"self",
")",
":",
"self",
".",
"set_header",
"(",
"\"Accept-Ranges\"",
",",
"\"bytes\"",
")",
"content_type",
"=",
"self",
".",
"get_content_type",
"(",
")",
"if",
"content_type",
":",
"self",
".",
"set_header",
"(",
"\"Content-Type\"",
",",
"content_type",
")"
] | Sets the content headers on the response. | [
"Sets",
"the",
"content",
"headers",
"on",
"the",
"response",
"."
] | 7a47947fb07281c3e3018042863dc67e7e56dc04 | https://github.com/SandstoneHPC/sandstone-ide/blob/7a47947fb07281c3e3018042863dc67e7e56dc04/sandstone/lib/filesystem/handlers.py#L416-L424 | train |
useblocks/groundwork | groundwork/patterns/gw_shared_objects_pattern.py | SharedObjectsListPlugin.__deactivate_shared_objects | def __deactivate_shared_objects(self, plugin, *args, **kwargs):
"""
Callback, which gets executed, if the signal "plugin_deactivate_post" was send by the plugin.
"""
shared_objects = self.get()
for shared_object in shared_objects.keys():
self.unregister(shared_object) | python | def __deactivate_shared_objects(self, plugin, *args, **kwargs):
"""
Callback, which gets executed, if the signal "plugin_deactivate_post" was send by the plugin.
"""
shared_objects = self.get()
for shared_object in shared_objects.keys():
self.unregister(shared_object) | [
"def",
"__deactivate_shared_objects",
"(",
"self",
",",
"plugin",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"shared_objects",
"=",
"self",
".",
"get",
"(",
")",
"for",
"shared_object",
"in",
"shared_objects",
".",
"keys",
"(",
")",
":",
"self",
".",
"unregister",
"(",
"shared_object",
")"
] | Callback, which gets executed, if the signal "plugin_deactivate_post" was send by the plugin. | [
"Callback",
"which",
"gets",
"executed",
"if",
"the",
"signal",
"plugin_deactivate_post",
"was",
"send",
"by",
"the",
"plugin",
"."
] | d34fce43f54246ca4db0f7b89e450dcdc847c68c | https://github.com/useblocks/groundwork/blob/d34fce43f54246ca4db0f7b89e450dcdc847c68c/groundwork/patterns/gw_shared_objects_pattern.py#L59-L65 | train |
useblocks/groundwork | groundwork/patterns/gw_shared_objects_pattern.py | SharedObjectsListPlugin.get | def get(self, name=None):
"""
Returns requested shared objects, which were registered by the current plugin.
If access to objects of other plugins are needed, use :func:`access` or perform get on application level::
my_app.shared_objects.get(name="...")
:param name: Name of a request shared object
:type name: str or None
"""
return self.app.shared_objects.get(name, self.plugin) | python | def get(self, name=None):
"""
Returns requested shared objects, which were registered by the current plugin.
If access to objects of other plugins are needed, use :func:`access` or perform get on application level::
my_app.shared_objects.get(name="...")
:param name: Name of a request shared object
:type name: str or None
"""
return self.app.shared_objects.get(name, self.plugin) | [
"def",
"get",
"(",
"self",
",",
"name",
"=",
"None",
")",
":",
"return",
"self",
".",
"app",
".",
"shared_objects",
".",
"get",
"(",
"name",
",",
"self",
".",
"plugin",
")"
] | Returns requested shared objects, which were registered by the current plugin.
If access to objects of other plugins are needed, use :func:`access` or perform get on application level::
my_app.shared_objects.get(name="...")
:param name: Name of a request shared object
:type name: str or None | [
"Returns",
"requested",
"shared",
"objects",
"which",
"were",
"registered",
"by",
"the",
"current",
"plugin",
"."
] | d34fce43f54246ca4db0f7b89e450dcdc847c68c | https://github.com/useblocks/groundwork/blob/d34fce43f54246ca4db0f7b89e450dcdc847c68c/groundwork/patterns/gw_shared_objects_pattern.py#L89-L100 | train |
useblocks/groundwork | groundwork/patterns/gw_shared_objects_pattern.py | SharedObjectsListApplication.get | def get(self, name=None, plugin=None):
"""
Returns requested shared objects.
:param name: Name of a request shared object
:type name: str or None
:param plugin: Plugin, which has registered the requested shared object
:type plugin: GwBasePattern instance or None
"""
if plugin is not None:
if name is None:
shared_objects_list = {}
for key in self._shared_objects.keys():
if self._shared_objects[key].plugin == plugin:
shared_objects_list[key] = self._shared_objects[key]
return shared_objects_list
else:
if name in self._shared_objects.keys():
if self._shared_objects[name].plugin == plugin:
return self._shared_objects[name]
else:
return None
else:
return None
else:
if name is None:
return self._shared_objects
else:
if name in self._shared_objects.keys():
return self._shared_objects[name]
else:
return None | python | def get(self, name=None, plugin=None):
"""
Returns requested shared objects.
:param name: Name of a request shared object
:type name: str or None
:param plugin: Plugin, which has registered the requested shared object
:type plugin: GwBasePattern instance or None
"""
if plugin is not None:
if name is None:
shared_objects_list = {}
for key in self._shared_objects.keys():
if self._shared_objects[key].plugin == plugin:
shared_objects_list[key] = self._shared_objects[key]
return shared_objects_list
else:
if name in self._shared_objects.keys():
if self._shared_objects[name].plugin == plugin:
return self._shared_objects[name]
else:
return None
else:
return None
else:
if name is None:
return self._shared_objects
else:
if name in self._shared_objects.keys():
return self._shared_objects[name]
else:
return None | [
"def",
"get",
"(",
"self",
",",
"name",
"=",
"None",
",",
"plugin",
"=",
"None",
")",
":",
"if",
"plugin",
"is",
"not",
"None",
":",
"if",
"name",
"is",
"None",
":",
"shared_objects_list",
"=",
"{",
"}",
"for",
"key",
"in",
"self",
".",
"_shared_objects",
".",
"keys",
"(",
")",
":",
"if",
"self",
".",
"_shared_objects",
"[",
"key",
"]",
".",
"plugin",
"==",
"plugin",
":",
"shared_objects_list",
"[",
"key",
"]",
"=",
"self",
".",
"_shared_objects",
"[",
"key",
"]",
"return",
"shared_objects_list",
"else",
":",
"if",
"name",
"in",
"self",
".",
"_shared_objects",
".",
"keys",
"(",
")",
":",
"if",
"self",
".",
"_shared_objects",
"[",
"name",
"]",
".",
"plugin",
"==",
"plugin",
":",
"return",
"self",
".",
"_shared_objects",
"[",
"name",
"]",
"else",
":",
"return",
"None",
"else",
":",
"return",
"None",
"else",
":",
"if",
"name",
"is",
"None",
":",
"return",
"self",
".",
"_shared_objects",
"else",
":",
"if",
"name",
"in",
"self",
".",
"_shared_objects",
".",
"keys",
"(",
")",
":",
"return",
"self",
".",
"_shared_objects",
"[",
"name",
"]",
"else",
":",
"return",
"None"
] | Returns requested shared objects.
:param name: Name of a request shared object
:type name: str or None
:param plugin: Plugin, which has registered the requested shared object
:type plugin: GwBasePattern instance or None | [
"Returns",
"requested",
"shared",
"objects",
"."
] | d34fce43f54246ca4db0f7b89e450dcdc847c68c | https://github.com/useblocks/groundwork/blob/d34fce43f54246ca4db0f7b89e450dcdc847c68c/groundwork/patterns/gw_shared_objects_pattern.py#L127-L158 | train |
useblocks/groundwork | groundwork/patterns/gw_shared_objects_pattern.py | SharedObjectsListApplication.unregister | def unregister(self, shared_object):
"""
Unregisters an existing shared object, so that this shared object is no longer available.
This function is mainly used during plugin deactivation.
:param shared_object: Name of the shared_object
"""
if shared_object not in self._shared_objects.keys():
self.log.warning("Can not unregister shared object %s" % shared_object)
else:
del (self._shared_objects[shared_object])
self.log.debug("Shared object %s got unregistered" % shared_object) | python | def unregister(self, shared_object):
"""
Unregisters an existing shared object, so that this shared object is no longer available.
This function is mainly used during plugin deactivation.
:param shared_object: Name of the shared_object
"""
if shared_object not in self._shared_objects.keys():
self.log.warning("Can not unregister shared object %s" % shared_object)
else:
del (self._shared_objects[shared_object])
self.log.debug("Shared object %s got unregistered" % shared_object) | [
"def",
"unregister",
"(",
"self",
",",
"shared_object",
")",
":",
"if",
"shared_object",
"not",
"in",
"self",
".",
"_shared_objects",
".",
"keys",
"(",
")",
":",
"self",
".",
"log",
".",
"warning",
"(",
"\"Can not unregister shared object %s\"",
"%",
"shared_object",
")",
"else",
":",
"del",
"(",
"self",
".",
"_shared_objects",
"[",
"shared_object",
"]",
")",
"self",
".",
"log",
".",
"debug",
"(",
"\"Shared object %s got unregistered\"",
"%",
"shared_object",
")"
] | Unregisters an existing shared object, so that this shared object is no longer available.
This function is mainly used during plugin deactivation.
:param shared_object: Name of the shared_object | [
"Unregisters",
"an",
"existing",
"shared",
"object",
"so",
"that",
"this",
"shared",
"object",
"is",
"no",
"longer",
"available",
"."
] | d34fce43f54246ca4db0f7b89e450dcdc847c68c | https://github.com/useblocks/groundwork/blob/d34fce43f54246ca4db0f7b89e450dcdc847c68c/groundwork/patterns/gw_shared_objects_pattern.py#L193-L205 | train |
useblocks/groundwork | groundwork/plugins/gw_signals_info.py | GwSignalsInfo.list_signals | def list_signals(self):
"""
Prints a list of all registered signals. Including description and plugin name.
"""
print("Signal list")
print("***********\n")
for key, signal in self.app.signals.signals.items():
print("%s (%s)\n %s\n" % (signal.name, signal.plugin.name, signal.description)) | python | def list_signals(self):
"""
Prints a list of all registered signals. Including description and plugin name.
"""
print("Signal list")
print("***********\n")
for key, signal in self.app.signals.signals.items():
print("%s (%s)\n %s\n" % (signal.name, signal.plugin.name, signal.description)) | [
"def",
"list_signals",
"(",
"self",
")",
":",
"print",
"(",
"\"Signal list\"",
")",
"print",
"(",
"\"***********\\n\"",
")",
"for",
"key",
",",
"signal",
"in",
"self",
".",
"app",
".",
"signals",
".",
"signals",
".",
"items",
"(",
")",
":",
"print",
"(",
"\"%s (%s)\\n %s\\n\"",
"%",
"(",
"signal",
".",
"name",
",",
"signal",
".",
"plugin",
".",
"name",
",",
"signal",
".",
"description",
")",
")"
] | Prints a list of all registered signals. Including description and plugin name. | [
"Prints",
"a",
"list",
"of",
"all",
"registered",
"signals",
".",
"Including",
"description",
"and",
"plugin",
"name",
"."
] | d34fce43f54246ca4db0f7b89e450dcdc847c68c | https://github.com/useblocks/groundwork/blob/d34fce43f54246ca4db0f7b89e450dcdc847c68c/groundwork/plugins/gw_signals_info.py#L73-L80 | train |
useblocks/groundwork | groundwork/plugins/gw_signals_info.py | GwSignalsInfo.list_receivers | def list_receivers(self):
"""
Prints a list of all registered receivers. Including signal, plugin name and description.
"""
print("Receiver list")
print("*************\n")
for key, receiver in self.app.signals.receivers.items():
print("%s <-- %s (%s):\n %s\n" % (receiver.name,
receiver.signal,
receiver.plugin.name,
receiver.description)) | python | def list_receivers(self):
"""
Prints a list of all registered receivers. Including signal, plugin name and description.
"""
print("Receiver list")
print("*************\n")
for key, receiver in self.app.signals.receivers.items():
print("%s <-- %s (%s):\n %s\n" % (receiver.name,
receiver.signal,
receiver.plugin.name,
receiver.description)) | [
"def",
"list_receivers",
"(",
"self",
")",
":",
"print",
"(",
"\"Receiver list\"",
")",
"print",
"(",
"\"*************\\n\"",
")",
"for",
"key",
",",
"receiver",
"in",
"self",
".",
"app",
".",
"signals",
".",
"receivers",
".",
"items",
"(",
")",
":",
"print",
"(",
"\"%s <-- %s (%s):\\n %s\\n\"",
"%",
"(",
"receiver",
".",
"name",
",",
"receiver",
".",
"signal",
",",
"receiver",
".",
"plugin",
".",
"name",
",",
"receiver",
".",
"description",
")",
")"
] | Prints a list of all registered receivers. Including signal, plugin name and description. | [
"Prints",
"a",
"list",
"of",
"all",
"registered",
"receivers",
".",
"Including",
"signal",
"plugin",
"name",
"and",
"description",
"."
] | d34fce43f54246ca4db0f7b89e450dcdc847c68c | https://github.com/useblocks/groundwork/blob/d34fce43f54246ca4db0f7b89e450dcdc847c68c/groundwork/plugins/gw_signals_info.py#L82-L92 | train |
jenisys/parse_type | bin/toxcmd.py | toxcmd_main | def toxcmd_main(args=None):
"""Command util with subcommands for tox environments."""
usage = "USAGE: %(prog)s [OPTIONS] COMMAND args..."
if args is None:
args = sys.argv[1:]
# -- STEP: Build command-line parser.
parser = argparse.ArgumentParser(description=inspect.getdoc(toxcmd_main),
formatter_class=FORMATTER_CLASS)
common_parser = parser.add_argument_group("Common options")
common_parser.add_argument("--version", action="version", version=VERSION)
subparsers = parser.add_subparsers(help="commands")
for command in discover_commands():
command_parser = subparsers.add_parser(command.name,
usage=command.usage,
description=command.description,
help=command.short_description,
formatter_class=FORMATTER_CLASS)
command_parser.set_defaults(func=command)
command.setup_parser(command_parser)
command.parser = command_parser
# -- STEP: Process command-line and run command.
options = parser.parse_args(args)
command_function = options.func
return command_function(options) | python | def toxcmd_main(args=None):
"""Command util with subcommands for tox environments."""
usage = "USAGE: %(prog)s [OPTIONS] COMMAND args..."
if args is None:
args = sys.argv[1:]
# -- STEP: Build command-line parser.
parser = argparse.ArgumentParser(description=inspect.getdoc(toxcmd_main),
formatter_class=FORMATTER_CLASS)
common_parser = parser.add_argument_group("Common options")
common_parser.add_argument("--version", action="version", version=VERSION)
subparsers = parser.add_subparsers(help="commands")
for command in discover_commands():
command_parser = subparsers.add_parser(command.name,
usage=command.usage,
description=command.description,
help=command.short_description,
formatter_class=FORMATTER_CLASS)
command_parser.set_defaults(func=command)
command.setup_parser(command_parser)
command.parser = command_parser
# -- STEP: Process command-line and run command.
options = parser.parse_args(args)
command_function = options.func
return command_function(options) | [
"def",
"toxcmd_main",
"(",
"args",
"=",
"None",
")",
":",
"usage",
"=",
"\"USAGE: %(prog)s [OPTIONS] COMMAND args...\"",
"if",
"args",
"is",
"None",
":",
"args",
"=",
"sys",
".",
"argv",
"[",
"1",
":",
"]",
"# -- STEP: Build command-line parser.",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"inspect",
".",
"getdoc",
"(",
"toxcmd_main",
")",
",",
"formatter_class",
"=",
"FORMATTER_CLASS",
")",
"common_parser",
"=",
"parser",
".",
"add_argument_group",
"(",
"\"Common options\"",
")",
"common_parser",
".",
"add_argument",
"(",
"\"--version\"",
",",
"action",
"=",
"\"version\"",
",",
"version",
"=",
"VERSION",
")",
"subparsers",
"=",
"parser",
".",
"add_subparsers",
"(",
"help",
"=",
"\"commands\"",
")",
"for",
"command",
"in",
"discover_commands",
"(",
")",
":",
"command_parser",
"=",
"subparsers",
".",
"add_parser",
"(",
"command",
".",
"name",
",",
"usage",
"=",
"command",
".",
"usage",
",",
"description",
"=",
"command",
".",
"description",
",",
"help",
"=",
"command",
".",
"short_description",
",",
"formatter_class",
"=",
"FORMATTER_CLASS",
")",
"command_parser",
".",
"set_defaults",
"(",
"func",
"=",
"command",
")",
"command",
".",
"setup_parser",
"(",
"command_parser",
")",
"command",
".",
"parser",
"=",
"command_parser",
"# -- STEP: Process command-line and run command.",
"options",
"=",
"parser",
".",
"parse_args",
"(",
"args",
")",
"command_function",
"=",
"options",
".",
"func",
"return",
"command_function",
"(",
"options",
")"
] | Command util with subcommands for tox environments. | [
"Command",
"util",
"with",
"subcommands",
"for",
"tox",
"environments",
"."
] | 7cad3a67a5ca725cb786da31f656fd473084289f | https://github.com/jenisys/parse_type/blob/7cad3a67a5ca725cb786da31f656fd473084289f/bin/toxcmd.py#L220-L245 | train |
go-macaroon-bakery/py-macaroon-bakery | macaroonbakery/bakery/_discharge.py | discharge | def discharge(ctx, id, caveat, key, checker, locator):
''' Creates a macaroon to discharge a third party caveat.
The given parameters specify the caveat and how it should be checked.
The condition implicit in the caveat is checked for validity using checker.
If it is valid, a new macaroon is returned which discharges the caveat.
The macaroon is created with a version derived from the version that was
used to encode the id.
:param id: (bytes) holds the id to give to the discharge macaroon.
If Caveat is empty, then the id also holds the encrypted third party
caveat.
:param caveat: (bytes) holds the encrypted third party caveat.
If this is None, id will be used.
:param key: holds the key to use to decrypt the third party caveat
information and to encrypt any additional third party caveats returned by
the caveat checker.
:param checker: used to check the third party caveat, and may also return
further caveats to be added to the discharge macaroon.
:param locator: used to information on third parties referred to by third
party caveats returned by the Checker.
'''
caveat_id_prefix = []
if caveat is None:
# The caveat information is encoded in the id itself.
caveat = id
else:
# We've been given an explicit id, so when extra third party
# caveats are added, use that id as the prefix
# for any more ids.
caveat_id_prefix = id
cav_info = decode_caveat(key, caveat)
cav_info = ThirdPartyCaveatInfo(
condition=cav_info.condition,
first_party_public_key=cav_info.first_party_public_key,
third_party_key_pair=cav_info.third_party_key_pair,
root_key=cav_info.root_key,
caveat=cav_info.caveat,
version=cav_info.version,
id=id,
namespace=cav_info.namespace
)
# Note that we don't check the error - we allow the
# third party checker to see even caveats that we can't
# understand.
try:
cond, arg = checkers.parse_caveat(cav_info.condition)
except ValueError as exc:
raise VerificationError(exc.args[0])
if cond == checkers.COND_NEED_DECLARED:
cav_info = cav_info._replace(condition=arg)
caveats = _check_need_declared(ctx, cav_info, checker)
else:
caveats = checker.check_third_party_caveat(ctx, cav_info)
# Note that the discharge macaroon does not need to
# be stored persistently. Indeed, it would be a problem if
# we did, because then the macaroon could potentially be used
# for normal authorization with the third party.
m = Macaroon(
cav_info.root_key,
id,
'',
cav_info.version,
cav_info.namespace,
)
m._caveat_id_prefix = caveat_id_prefix
if caveats is not None:
for cav in caveats:
m.add_caveat(cav, key, locator)
return m | python | def discharge(ctx, id, caveat, key, checker, locator):
''' Creates a macaroon to discharge a third party caveat.
The given parameters specify the caveat and how it should be checked.
The condition implicit in the caveat is checked for validity using checker.
If it is valid, a new macaroon is returned which discharges the caveat.
The macaroon is created with a version derived from the version that was
used to encode the id.
:param id: (bytes) holds the id to give to the discharge macaroon.
If Caveat is empty, then the id also holds the encrypted third party
caveat.
:param caveat: (bytes) holds the encrypted third party caveat.
If this is None, id will be used.
:param key: holds the key to use to decrypt the third party caveat
information and to encrypt any additional third party caveats returned by
the caveat checker.
:param checker: used to check the third party caveat, and may also return
further caveats to be added to the discharge macaroon.
:param locator: used to information on third parties referred to by third
party caveats returned by the Checker.
'''
caveat_id_prefix = []
if caveat is None:
# The caveat information is encoded in the id itself.
caveat = id
else:
# We've been given an explicit id, so when extra third party
# caveats are added, use that id as the prefix
# for any more ids.
caveat_id_prefix = id
cav_info = decode_caveat(key, caveat)
cav_info = ThirdPartyCaveatInfo(
condition=cav_info.condition,
first_party_public_key=cav_info.first_party_public_key,
third_party_key_pair=cav_info.third_party_key_pair,
root_key=cav_info.root_key,
caveat=cav_info.caveat,
version=cav_info.version,
id=id,
namespace=cav_info.namespace
)
# Note that we don't check the error - we allow the
# third party checker to see even caveats that we can't
# understand.
try:
cond, arg = checkers.parse_caveat(cav_info.condition)
except ValueError as exc:
raise VerificationError(exc.args[0])
if cond == checkers.COND_NEED_DECLARED:
cav_info = cav_info._replace(condition=arg)
caveats = _check_need_declared(ctx, cav_info, checker)
else:
caveats = checker.check_third_party_caveat(ctx, cav_info)
# Note that the discharge macaroon does not need to
# be stored persistently. Indeed, it would be a problem if
# we did, because then the macaroon could potentially be used
# for normal authorization with the third party.
m = Macaroon(
cav_info.root_key,
id,
'',
cav_info.version,
cav_info.namespace,
)
m._caveat_id_prefix = caveat_id_prefix
if caveats is not None:
for cav in caveats:
m.add_caveat(cav, key, locator)
return m | [
"def",
"discharge",
"(",
"ctx",
",",
"id",
",",
"caveat",
",",
"key",
",",
"checker",
",",
"locator",
")",
":",
"caveat_id_prefix",
"=",
"[",
"]",
"if",
"caveat",
"is",
"None",
":",
"# The caveat information is encoded in the id itself.",
"caveat",
"=",
"id",
"else",
":",
"# We've been given an explicit id, so when extra third party",
"# caveats are added, use that id as the prefix",
"# for any more ids.",
"caveat_id_prefix",
"=",
"id",
"cav_info",
"=",
"decode_caveat",
"(",
"key",
",",
"caveat",
")",
"cav_info",
"=",
"ThirdPartyCaveatInfo",
"(",
"condition",
"=",
"cav_info",
".",
"condition",
",",
"first_party_public_key",
"=",
"cav_info",
".",
"first_party_public_key",
",",
"third_party_key_pair",
"=",
"cav_info",
".",
"third_party_key_pair",
",",
"root_key",
"=",
"cav_info",
".",
"root_key",
",",
"caveat",
"=",
"cav_info",
".",
"caveat",
",",
"version",
"=",
"cav_info",
".",
"version",
",",
"id",
"=",
"id",
",",
"namespace",
"=",
"cav_info",
".",
"namespace",
")",
"# Note that we don't check the error - we allow the",
"# third party checker to see even caveats that we can't",
"# understand.",
"try",
":",
"cond",
",",
"arg",
"=",
"checkers",
".",
"parse_caveat",
"(",
"cav_info",
".",
"condition",
")",
"except",
"ValueError",
"as",
"exc",
":",
"raise",
"VerificationError",
"(",
"exc",
".",
"args",
"[",
"0",
"]",
")",
"if",
"cond",
"==",
"checkers",
".",
"COND_NEED_DECLARED",
":",
"cav_info",
"=",
"cav_info",
".",
"_replace",
"(",
"condition",
"=",
"arg",
")",
"caveats",
"=",
"_check_need_declared",
"(",
"ctx",
",",
"cav_info",
",",
"checker",
")",
"else",
":",
"caveats",
"=",
"checker",
".",
"check_third_party_caveat",
"(",
"ctx",
",",
"cav_info",
")",
"# Note that the discharge macaroon does not need to",
"# be stored persistently. Indeed, it would be a problem if",
"# we did, because then the macaroon could potentially be used",
"# for normal authorization with the third party.",
"m",
"=",
"Macaroon",
"(",
"cav_info",
".",
"root_key",
",",
"id",
",",
"''",
",",
"cav_info",
".",
"version",
",",
"cav_info",
".",
"namespace",
",",
")",
"m",
".",
"_caveat_id_prefix",
"=",
"caveat_id_prefix",
"if",
"caveats",
"is",
"not",
"None",
":",
"for",
"cav",
"in",
"caveats",
":",
"m",
".",
"add_caveat",
"(",
"cav",
",",
"key",
",",
"locator",
")",
"return",
"m"
] | Creates a macaroon to discharge a third party caveat.
The given parameters specify the caveat and how it should be checked.
The condition implicit in the caveat is checked for validity using checker.
If it is valid, a new macaroon is returned which discharges the caveat.
The macaroon is created with a version derived from the version that was
used to encode the id.
:param id: (bytes) holds the id to give to the discharge macaroon.
If Caveat is empty, then the id also holds the encrypted third party
caveat.
:param caveat: (bytes) holds the encrypted third party caveat.
If this is None, id will be used.
:param key: holds the key to use to decrypt the third party caveat
information and to encrypt any additional third party caveats returned by
the caveat checker.
:param checker: used to check the third party caveat, and may also return
further caveats to be added to the discharge macaroon.
:param locator: used to information on third parties referred to by third
party caveats returned by the Checker. | [
"Creates",
"a",
"macaroon",
"to",
"discharge",
"a",
"third",
"party",
"caveat",
"."
] | 63ce1ef1dabe816eb8aaec48fbb46761c34ddf77 | https://github.com/go-macaroon-bakery/py-macaroon-bakery/blob/63ce1ef1dabe816eb8aaec48fbb46761c34ddf77/macaroonbakery/bakery/_discharge.py#L116-L187 | train |
go-macaroon-bakery/py-macaroon-bakery | macaroonbakery/bakery/_discharge.py | local_third_party_caveat | def local_third_party_caveat(key, version):
''' Returns a third-party caveat that, when added to a macaroon with
add_caveat, results in a caveat with the location "local", encrypted with
the given PublicKey.
This can be automatically discharged by discharge_all passing a local key.
'''
if version >= VERSION_2:
loc = 'local {} {}'.format(version, key)
else:
loc = 'local {}'.format(key)
return checkers.Caveat(location=loc, condition='') | python | def local_third_party_caveat(key, version):
''' Returns a third-party caveat that, when added to a macaroon with
add_caveat, results in a caveat with the location "local", encrypted with
the given PublicKey.
This can be automatically discharged by discharge_all passing a local key.
'''
if version >= VERSION_2:
loc = 'local {} {}'.format(version, key)
else:
loc = 'local {}'.format(key)
return checkers.Caveat(location=loc, condition='') | [
"def",
"local_third_party_caveat",
"(",
"key",
",",
"version",
")",
":",
"if",
"version",
">=",
"VERSION_2",
":",
"loc",
"=",
"'local {} {}'",
".",
"format",
"(",
"version",
",",
"key",
")",
"else",
":",
"loc",
"=",
"'local {}'",
".",
"format",
"(",
"key",
")",
"return",
"checkers",
".",
"Caveat",
"(",
"location",
"=",
"loc",
",",
"condition",
"=",
"''",
")"
] | Returns a third-party caveat that, when added to a macaroon with
add_caveat, results in a caveat with the location "local", encrypted with
the given PublicKey.
This can be automatically discharged by discharge_all passing a local key. | [
"Returns",
"a",
"third",
"-",
"party",
"caveat",
"that",
"when",
"added",
"to",
"a",
"macaroon",
"with",
"add_caveat",
"results",
"in",
"a",
"caveat",
"with",
"the",
"location",
"local",
"encrypted",
"with",
"the",
"given",
"PublicKey",
".",
"This",
"can",
"be",
"automatically",
"discharged",
"by",
"discharge_all",
"passing",
"a",
"local",
"key",
"."
] | 63ce1ef1dabe816eb8aaec48fbb46761c34ddf77 | https://github.com/go-macaroon-bakery/py-macaroon-bakery/blob/63ce1ef1dabe816eb8aaec48fbb46761c34ddf77/macaroonbakery/bakery/_discharge.py#L234-L244 | train |
go-macaroon-bakery/py-macaroon-bakery | macaroonbakery/checkers/_namespace.py | deserialize_namespace | def deserialize_namespace(data):
''' Deserialize a Namespace object.
:param data: bytes or str
:return: namespace
'''
if isinstance(data, bytes):
data = data.decode('utf-8')
kvs = data.split()
uri_to_prefix = {}
for kv in kvs:
i = kv.rfind(':')
if i == -1:
raise ValueError('no colon in namespace '
'field {}'.format(repr(kv)))
uri, prefix = kv[0:i], kv[i + 1:]
if not is_valid_schema_uri(uri):
# Currently this can't happen because the only invalid URIs
# are those which contain a space
raise ValueError(
'invalid URI {} in namespace '
'field {}'.format(repr(uri), repr(kv)))
if not is_valid_prefix(prefix):
raise ValueError(
'invalid prefix {} in namespace field'
' {}'.format(repr(prefix), repr(kv)))
if uri in uri_to_prefix:
raise ValueError(
'duplicate URI {} in '
'namespace {}'.format(repr(uri), repr(data)))
uri_to_prefix[uri] = prefix
return Namespace(uri_to_prefix) | python | def deserialize_namespace(data):
''' Deserialize a Namespace object.
:param data: bytes or str
:return: namespace
'''
if isinstance(data, bytes):
data = data.decode('utf-8')
kvs = data.split()
uri_to_prefix = {}
for kv in kvs:
i = kv.rfind(':')
if i == -1:
raise ValueError('no colon in namespace '
'field {}'.format(repr(kv)))
uri, prefix = kv[0:i], kv[i + 1:]
if not is_valid_schema_uri(uri):
# Currently this can't happen because the only invalid URIs
# are those which contain a space
raise ValueError(
'invalid URI {} in namespace '
'field {}'.format(repr(uri), repr(kv)))
if not is_valid_prefix(prefix):
raise ValueError(
'invalid prefix {} in namespace field'
' {}'.format(repr(prefix), repr(kv)))
if uri in uri_to_prefix:
raise ValueError(
'duplicate URI {} in '
'namespace {}'.format(repr(uri), repr(data)))
uri_to_prefix[uri] = prefix
return Namespace(uri_to_prefix) | [
"def",
"deserialize_namespace",
"(",
"data",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"bytes",
")",
":",
"data",
"=",
"data",
".",
"decode",
"(",
"'utf-8'",
")",
"kvs",
"=",
"data",
".",
"split",
"(",
")",
"uri_to_prefix",
"=",
"{",
"}",
"for",
"kv",
"in",
"kvs",
":",
"i",
"=",
"kv",
".",
"rfind",
"(",
"':'",
")",
"if",
"i",
"==",
"-",
"1",
":",
"raise",
"ValueError",
"(",
"'no colon in namespace '",
"'field {}'",
".",
"format",
"(",
"repr",
"(",
"kv",
")",
")",
")",
"uri",
",",
"prefix",
"=",
"kv",
"[",
"0",
":",
"i",
"]",
",",
"kv",
"[",
"i",
"+",
"1",
":",
"]",
"if",
"not",
"is_valid_schema_uri",
"(",
"uri",
")",
":",
"# Currently this can't happen because the only invalid URIs",
"# are those which contain a space",
"raise",
"ValueError",
"(",
"'invalid URI {} in namespace '",
"'field {}'",
".",
"format",
"(",
"repr",
"(",
"uri",
")",
",",
"repr",
"(",
"kv",
")",
")",
")",
"if",
"not",
"is_valid_prefix",
"(",
"prefix",
")",
":",
"raise",
"ValueError",
"(",
"'invalid prefix {} in namespace field'",
"' {}'",
".",
"format",
"(",
"repr",
"(",
"prefix",
")",
",",
"repr",
"(",
"kv",
")",
")",
")",
"if",
"uri",
"in",
"uri_to_prefix",
":",
"raise",
"ValueError",
"(",
"'duplicate URI {} in '",
"'namespace {}'",
".",
"format",
"(",
"repr",
"(",
"uri",
")",
",",
"repr",
"(",
"data",
")",
")",
")",
"uri_to_prefix",
"[",
"uri",
"]",
"=",
"prefix",
"return",
"Namespace",
"(",
"uri_to_prefix",
")"
] | Deserialize a Namespace object.
:param data: bytes or str
:return: namespace | [
"Deserialize",
"a",
"Namespace",
"object",
"."
] | 63ce1ef1dabe816eb8aaec48fbb46761c34ddf77 | https://github.com/go-macaroon-bakery/py-macaroon-bakery/blob/63ce1ef1dabe816eb8aaec48fbb46761c34ddf77/macaroonbakery/checkers/_namespace.py#L134-L165 | train |
go-macaroon-bakery/py-macaroon-bakery | macaroonbakery/checkers/_namespace.py | Namespace.serialize_text | def serialize_text(self):
'''Returns a serialized form of the Namepace.
All the elements in the namespace are sorted by
URI, joined to the associated prefix with a colon and
separated with spaces.
:return: bytes
'''
if self._uri_to_prefix is None or len(self._uri_to_prefix) == 0:
return b''
od = collections.OrderedDict(sorted(self._uri_to_prefix.items()))
data = []
for uri in od:
data.append(uri + ':' + od[uri])
return ' '.join(data).encode('utf-8') | python | def serialize_text(self):
'''Returns a serialized form of the Namepace.
All the elements in the namespace are sorted by
URI, joined to the associated prefix with a colon and
separated with spaces.
:return: bytes
'''
if self._uri_to_prefix is None or len(self._uri_to_prefix) == 0:
return b''
od = collections.OrderedDict(sorted(self._uri_to_prefix.items()))
data = []
for uri in od:
data.append(uri + ':' + od[uri])
return ' '.join(data).encode('utf-8') | [
"def",
"serialize_text",
"(",
"self",
")",
":",
"if",
"self",
".",
"_uri_to_prefix",
"is",
"None",
"or",
"len",
"(",
"self",
".",
"_uri_to_prefix",
")",
"==",
"0",
":",
"return",
"b''",
"od",
"=",
"collections",
".",
"OrderedDict",
"(",
"sorted",
"(",
"self",
".",
"_uri_to_prefix",
".",
"items",
"(",
")",
")",
")",
"data",
"=",
"[",
"]",
"for",
"uri",
"in",
"od",
":",
"data",
".",
"append",
"(",
"uri",
"+",
"':'",
"+",
"od",
"[",
"uri",
"]",
")",
"return",
"' '",
".",
"join",
"(",
"data",
")",
".",
"encode",
"(",
"'utf-8'",
")"
] | Returns a serialized form of the Namepace.
All the elements in the namespace are sorted by
URI, joined to the associated prefix with a colon and
separated with spaces.
:return: bytes | [
"Returns",
"a",
"serialized",
"form",
"of",
"the",
"Namepace",
"."
] | 63ce1ef1dabe816eb8aaec48fbb46761c34ddf77 | https://github.com/go-macaroon-bakery/py-macaroon-bakery/blob/63ce1ef1dabe816eb8aaec48fbb46761c34ddf77/macaroonbakery/checkers/_namespace.py#L33-L47 | train |
go-macaroon-bakery/py-macaroon-bakery | macaroonbakery/checkers/_namespace.py | Namespace.register | def register(self, uri, prefix):
'''Registers the given URI and associates it with the given prefix.
If the URI has already been registered, this is a no-op.
:param uri: string
:param prefix: string
'''
if not is_valid_schema_uri(uri):
raise KeyError(
'cannot register invalid URI {} (prefix {})'.format(
uri, prefix))
if not is_valid_prefix(prefix):
raise ValueError(
'cannot register invalid prefix %q for URI %q'.format(
prefix, uri))
if self._uri_to_prefix.get(uri) is None:
self._uri_to_prefix[uri] = prefix | python | def register(self, uri, prefix):
'''Registers the given URI and associates it with the given prefix.
If the URI has already been registered, this is a no-op.
:param uri: string
:param prefix: string
'''
if not is_valid_schema_uri(uri):
raise KeyError(
'cannot register invalid URI {} (prefix {})'.format(
uri, prefix))
if not is_valid_prefix(prefix):
raise ValueError(
'cannot register invalid prefix %q for URI %q'.format(
prefix, uri))
if self._uri_to_prefix.get(uri) is None:
self._uri_to_prefix[uri] = prefix | [
"def",
"register",
"(",
"self",
",",
"uri",
",",
"prefix",
")",
":",
"if",
"not",
"is_valid_schema_uri",
"(",
"uri",
")",
":",
"raise",
"KeyError",
"(",
"'cannot register invalid URI {} (prefix {})'",
".",
"format",
"(",
"uri",
",",
"prefix",
")",
")",
"if",
"not",
"is_valid_prefix",
"(",
"prefix",
")",
":",
"raise",
"ValueError",
"(",
"'cannot register invalid prefix %q for URI %q'",
".",
"format",
"(",
"prefix",
",",
"uri",
")",
")",
"if",
"self",
".",
"_uri_to_prefix",
".",
"get",
"(",
"uri",
")",
"is",
"None",
":",
"self",
".",
"_uri_to_prefix",
"[",
"uri",
"]",
"=",
"prefix"
] | Registers the given URI and associates it with the given prefix.
If the URI has already been registered, this is a no-op.
:param uri: string
:param prefix: string | [
"Registers",
"the",
"given",
"URI",
"and",
"associates",
"it",
"with",
"the",
"given",
"prefix",
"."
] | 63ce1ef1dabe816eb8aaec48fbb46761c34ddf77 | https://github.com/go-macaroon-bakery/py-macaroon-bakery/blob/63ce1ef1dabe816eb8aaec48fbb46761c34ddf77/macaroonbakery/checkers/_namespace.py#L49-L66 | train |
go-macaroon-bakery/py-macaroon-bakery | macaroonbakery/checkers/_auth_context.py | AuthContext.with_value | def with_value(self, key, val):
''' Return a copy of the AuthContext object with the given key and
value added.
'''
new_dict = dict(self._dict)
new_dict[key] = val
return AuthContext(new_dict) | python | def with_value(self, key, val):
''' Return a copy of the AuthContext object with the given key and
value added.
'''
new_dict = dict(self._dict)
new_dict[key] = val
return AuthContext(new_dict) | [
"def",
"with_value",
"(",
"self",
",",
"key",
",",
"val",
")",
":",
"new_dict",
"=",
"dict",
"(",
"self",
".",
"_dict",
")",
"new_dict",
"[",
"key",
"]",
"=",
"val",
"return",
"AuthContext",
"(",
"new_dict",
")"
] | Return a copy of the AuthContext object with the given key and
value added. | [
"Return",
"a",
"copy",
"of",
"the",
"AuthContext",
"object",
"with",
"the",
"given",
"key",
"and",
"value",
"added",
"."
] | 63ce1ef1dabe816eb8aaec48fbb46761c34ddf77 | https://github.com/go-macaroon-bakery/py-macaroon-bakery/blob/63ce1ef1dabe816eb8aaec48fbb46761c34ddf77/macaroonbakery/checkers/_auth_context.py#L19-L25 | train |
jenisys/parse_type | parse_type/cardinality.py | Cardinality.make_pattern | def make_pattern(self, pattern, listsep=','):
"""Make pattern for a data type with the specified cardinality.
.. code-block:: python
yes_no_pattern = r"yes|no"
many_yes_no = Cardinality.one_or_more.make_pattern(yes_no_pattern)
:param pattern: Regular expression for type (as string).
:param listsep: List separator for multiple items (as string, optional)
:return: Regular expression pattern for type with cardinality.
"""
if self is Cardinality.one:
return pattern
elif self is Cardinality.zero_or_one:
return self.schema % pattern
else:
return self.schema % (pattern, listsep, pattern) | python | def make_pattern(self, pattern, listsep=','):
"""Make pattern for a data type with the specified cardinality.
.. code-block:: python
yes_no_pattern = r"yes|no"
many_yes_no = Cardinality.one_or_more.make_pattern(yes_no_pattern)
:param pattern: Regular expression for type (as string).
:param listsep: List separator for multiple items (as string, optional)
:return: Regular expression pattern for type with cardinality.
"""
if self is Cardinality.one:
return pattern
elif self is Cardinality.zero_or_one:
return self.schema % pattern
else:
return self.schema % (pattern, listsep, pattern) | [
"def",
"make_pattern",
"(",
"self",
",",
"pattern",
",",
"listsep",
"=",
"','",
")",
":",
"if",
"self",
"is",
"Cardinality",
".",
"one",
":",
"return",
"pattern",
"elif",
"self",
"is",
"Cardinality",
".",
"zero_or_one",
":",
"return",
"self",
".",
"schema",
"%",
"pattern",
"else",
":",
"return",
"self",
".",
"schema",
"%",
"(",
"pattern",
",",
"listsep",
",",
"pattern",
")"
] | Make pattern for a data type with the specified cardinality.
.. code-block:: python
yes_no_pattern = r"yes|no"
many_yes_no = Cardinality.one_or_more.make_pattern(yes_no_pattern)
:param pattern: Regular expression for type (as string).
:param listsep: List separator for multiple items (as string, optional)
:return: Regular expression pattern for type with cardinality. | [
"Make",
"pattern",
"for",
"a",
"data",
"type",
"with",
"the",
"specified",
"cardinality",
"."
] | 7cad3a67a5ca725cb786da31f656fd473084289f | https://github.com/jenisys/parse_type/blob/7cad3a67a5ca725cb786da31f656fd473084289f/parse_type/cardinality.py#L48-L65 | train |
jenisys/parse_type | parse_type/cardinality.py | TypeBuilder.with_cardinality | def with_cardinality(cls, cardinality, converter, pattern=None,
listsep=','):
"""Creates a type converter for the specified cardinality
by using the type converter for T.
:param cardinality: Cardinality to use (0..1, 0..*, 1..*).
:param converter: Type converter (function) for data type T.
:param pattern: Regexp pattern for an item (=converter.pattern).
:return: type-converter for optional<T> (T or None).
"""
if cardinality is Cardinality.one:
return converter
# -- NORMAL-CASE
builder_func = getattr(cls, "with_%s" % cardinality.name)
if cardinality is Cardinality.zero_or_one:
return builder_func(converter, pattern)
else:
# -- MANY CASE: 0..*, 1..*
return builder_func(converter, pattern, listsep=listsep) | python | def with_cardinality(cls, cardinality, converter, pattern=None,
listsep=','):
"""Creates a type converter for the specified cardinality
by using the type converter for T.
:param cardinality: Cardinality to use (0..1, 0..*, 1..*).
:param converter: Type converter (function) for data type T.
:param pattern: Regexp pattern for an item (=converter.pattern).
:return: type-converter for optional<T> (T or None).
"""
if cardinality is Cardinality.one:
return converter
# -- NORMAL-CASE
builder_func = getattr(cls, "with_%s" % cardinality.name)
if cardinality is Cardinality.zero_or_one:
return builder_func(converter, pattern)
else:
# -- MANY CASE: 0..*, 1..*
return builder_func(converter, pattern, listsep=listsep) | [
"def",
"with_cardinality",
"(",
"cls",
",",
"cardinality",
",",
"converter",
",",
"pattern",
"=",
"None",
",",
"listsep",
"=",
"','",
")",
":",
"if",
"cardinality",
"is",
"Cardinality",
".",
"one",
":",
"return",
"converter",
"# -- NORMAL-CASE",
"builder_func",
"=",
"getattr",
"(",
"cls",
",",
"\"with_%s\"",
"%",
"cardinality",
".",
"name",
")",
"if",
"cardinality",
"is",
"Cardinality",
".",
"zero_or_one",
":",
"return",
"builder_func",
"(",
"converter",
",",
"pattern",
")",
"else",
":",
"# -- MANY CASE: 0..*, 1..*",
"return",
"builder_func",
"(",
"converter",
",",
"pattern",
",",
"listsep",
"=",
"listsep",
")"
] | Creates a type converter for the specified cardinality
by using the type converter for T.
:param cardinality: Cardinality to use (0..1, 0..*, 1..*).
:param converter: Type converter (function) for data type T.
:param pattern: Regexp pattern for an item (=converter.pattern).
:return: type-converter for optional<T> (T or None). | [
"Creates",
"a",
"type",
"converter",
"for",
"the",
"specified",
"cardinality",
"by",
"using",
"the",
"type",
"converter",
"for",
"T",
"."
] | 7cad3a67a5ca725cb786da31f656fd473084289f | https://github.com/jenisys/parse_type/blob/7cad3a67a5ca725cb786da31f656fd473084289f/parse_type/cardinality.py#L95-L113 | train |
jenisys/parse_type | parse_type/cardinality.py | TypeBuilder.with_zero_or_one | def with_zero_or_one(cls, converter, pattern=None):
"""Creates a type converter for a T with 0..1 times
by using the type converter for one item of T.
:param converter: Type converter (function) for data type T.
:param pattern: Regexp pattern for an item (=converter.pattern).
:return: type-converter for optional<T> (T or None).
"""
cardinality = Cardinality.zero_or_one
if not pattern:
pattern = getattr(converter, "pattern", cls.default_pattern)
optional_pattern = cardinality.make_pattern(pattern)
group_count = cardinality.compute_group_count(pattern)
def convert_optional(text, m=None):
if text:
text = text.strip()
if not text:
return None
return converter(text)
convert_optional.pattern = optional_pattern
# OLD: convert_optional.group_count = group_count
convert_optional.regex_group_count = group_count
return convert_optional | python | def with_zero_or_one(cls, converter, pattern=None):
"""Creates a type converter for a T with 0..1 times
by using the type converter for one item of T.
:param converter: Type converter (function) for data type T.
:param pattern: Regexp pattern for an item (=converter.pattern).
:return: type-converter for optional<T> (T or None).
"""
cardinality = Cardinality.zero_or_one
if not pattern:
pattern = getattr(converter, "pattern", cls.default_pattern)
optional_pattern = cardinality.make_pattern(pattern)
group_count = cardinality.compute_group_count(pattern)
def convert_optional(text, m=None):
if text:
text = text.strip()
if not text:
return None
return converter(text)
convert_optional.pattern = optional_pattern
# OLD: convert_optional.group_count = group_count
convert_optional.regex_group_count = group_count
return convert_optional | [
"def",
"with_zero_or_one",
"(",
"cls",
",",
"converter",
",",
"pattern",
"=",
"None",
")",
":",
"cardinality",
"=",
"Cardinality",
".",
"zero_or_one",
"if",
"not",
"pattern",
":",
"pattern",
"=",
"getattr",
"(",
"converter",
",",
"\"pattern\"",
",",
"cls",
".",
"default_pattern",
")",
"optional_pattern",
"=",
"cardinality",
".",
"make_pattern",
"(",
"pattern",
")",
"group_count",
"=",
"cardinality",
".",
"compute_group_count",
"(",
"pattern",
")",
"def",
"convert_optional",
"(",
"text",
",",
"m",
"=",
"None",
")",
":",
"if",
"text",
":",
"text",
"=",
"text",
".",
"strip",
"(",
")",
"if",
"not",
"text",
":",
"return",
"None",
"return",
"converter",
"(",
"text",
")",
"convert_optional",
".",
"pattern",
"=",
"optional_pattern",
"# OLD: convert_optional.group_count = group_count",
"convert_optional",
".",
"regex_group_count",
"=",
"group_count",
"return",
"convert_optional"
] | Creates a type converter for a T with 0..1 times
by using the type converter for one item of T.
:param converter: Type converter (function) for data type T.
:param pattern: Regexp pattern for an item (=converter.pattern).
:return: type-converter for optional<T> (T or None). | [
"Creates",
"a",
"type",
"converter",
"for",
"a",
"T",
"with",
"0",
"..",
"1",
"times",
"by",
"using",
"the",
"type",
"converter",
"for",
"one",
"item",
"of",
"T",
"."
] | 7cad3a67a5ca725cb786da31f656fd473084289f | https://github.com/jenisys/parse_type/blob/7cad3a67a5ca725cb786da31f656fd473084289f/parse_type/cardinality.py#L116-L139 | train |
suurjaak/InputScope | inputscope/webui.py | server_static | def server_static(filepath):
"""Handler for serving static files."""
mimetype = "image/svg+xml" if filepath.endswith(".svg") else "auto"
return bottle.static_file(filepath, root=conf.StaticPath, mimetype=mimetype) | python | def server_static(filepath):
"""Handler for serving static files."""
mimetype = "image/svg+xml" if filepath.endswith(".svg") else "auto"
return bottle.static_file(filepath, root=conf.StaticPath, mimetype=mimetype) | [
"def",
"server_static",
"(",
"filepath",
")",
":",
"mimetype",
"=",
"\"image/svg+xml\"",
"if",
"filepath",
".",
"endswith",
"(",
"\".svg\"",
")",
"else",
"\"auto\"",
"return",
"bottle",
".",
"static_file",
"(",
"filepath",
",",
"root",
"=",
"conf",
".",
"StaticPath",
",",
"mimetype",
"=",
"mimetype",
")"
] | Handler for serving static files. | [
"Handler",
"for",
"serving",
"static",
"files",
"."
] | 245ff045163a1995e8cd5ac558d0a93024eb86eb | https://github.com/suurjaak/InputScope/blob/245ff045163a1995e8cd5ac558d0a93024eb86eb/inputscope/webui.py#L32-L35 | train |
suurjaak/InputScope | inputscope/webui.py | mouse | def mouse(table, day=None):
"""Handler for showing mouse statistics for specified type and day."""
where = (("day", day),) if day else ()
events = db.fetch(table, where=where, order="day")
for e in events: e["dt"] = datetime.datetime.fromtimestamp(e["stamp"])
stats, positions, events = stats_mouse(events, table)
days, input = db.fetch("counts", order="day", type=table), "mouse"
return bottle.template("heatmap.tpl", locals(), conf=conf) | python | def mouse(table, day=None):
"""Handler for showing mouse statistics for specified type and day."""
where = (("day", day),) if day else ()
events = db.fetch(table, where=where, order="day")
for e in events: e["dt"] = datetime.datetime.fromtimestamp(e["stamp"])
stats, positions, events = stats_mouse(events, table)
days, input = db.fetch("counts", order="day", type=table), "mouse"
return bottle.template("heatmap.tpl", locals(), conf=conf) | [
"def",
"mouse",
"(",
"table",
",",
"day",
"=",
"None",
")",
":",
"where",
"=",
"(",
"(",
"\"day\"",
",",
"day",
")",
",",
")",
"if",
"day",
"else",
"(",
")",
"events",
"=",
"db",
".",
"fetch",
"(",
"table",
",",
"where",
"=",
"where",
",",
"order",
"=",
"\"day\"",
")",
"for",
"e",
"in",
"events",
":",
"e",
"[",
"\"dt\"",
"]",
"=",
"datetime",
".",
"datetime",
".",
"fromtimestamp",
"(",
"e",
"[",
"\"stamp\"",
"]",
")",
"stats",
",",
"positions",
",",
"events",
"=",
"stats_mouse",
"(",
"events",
",",
"table",
")",
"days",
",",
"input",
"=",
"db",
".",
"fetch",
"(",
"\"counts\"",
",",
"order",
"=",
"\"day\"",
",",
"type",
"=",
"table",
")",
",",
"\"mouse\"",
"return",
"bottle",
".",
"template",
"(",
"\"heatmap.tpl\"",
",",
"locals",
"(",
")",
",",
"conf",
"=",
"conf",
")"
] | Handler for showing mouse statistics for specified type and day. | [
"Handler",
"for",
"showing",
"mouse",
"statistics",
"for",
"specified",
"type",
"and",
"day",
"."
] | 245ff045163a1995e8cd5ac558d0a93024eb86eb | https://github.com/suurjaak/InputScope/blob/245ff045163a1995e8cd5ac558d0a93024eb86eb/inputscope/webui.py#L40-L47 | train |
suurjaak/InputScope | inputscope/webui.py | keyboard | def keyboard(table, day=None):
"""Handler for showing the keyboard statistics page."""
cols, group = "realkey AS key, COUNT(*) AS count", "realkey"
where = (("day", day),) if day else ()
counts_display = counts = db.fetch(table, cols, where, group, "count DESC")
if "combos" == table:
counts_display = db.fetch(table, "key, COUNT(*) AS count", where,
"key", "count DESC")
events = db.fetch(table, where=where, order="stamp")
for e in events: e["dt"] = datetime.datetime.fromtimestamp(e["stamp"])
stats, collatedevents = stats_keyboard(events, table)
days, input = db.fetch("counts", order="day", type=table), "keyboard"
return bottle.template("heatmap.tpl", locals(), conf=conf) | python | def keyboard(table, day=None):
"""Handler for showing the keyboard statistics page."""
cols, group = "realkey AS key, COUNT(*) AS count", "realkey"
where = (("day", day),) if day else ()
counts_display = counts = db.fetch(table, cols, where, group, "count DESC")
if "combos" == table:
counts_display = db.fetch(table, "key, COUNT(*) AS count", where,
"key", "count DESC")
events = db.fetch(table, where=where, order="stamp")
for e in events: e["dt"] = datetime.datetime.fromtimestamp(e["stamp"])
stats, collatedevents = stats_keyboard(events, table)
days, input = db.fetch("counts", order="day", type=table), "keyboard"
return bottle.template("heatmap.tpl", locals(), conf=conf) | [
"def",
"keyboard",
"(",
"table",
",",
"day",
"=",
"None",
")",
":",
"cols",
",",
"group",
"=",
"\"realkey AS key, COUNT(*) AS count\"",
",",
"\"realkey\"",
"where",
"=",
"(",
"(",
"\"day\"",
",",
"day",
")",
",",
")",
"if",
"day",
"else",
"(",
")",
"counts_display",
"=",
"counts",
"=",
"db",
".",
"fetch",
"(",
"table",
",",
"cols",
",",
"where",
",",
"group",
",",
"\"count DESC\"",
")",
"if",
"\"combos\"",
"==",
"table",
":",
"counts_display",
"=",
"db",
".",
"fetch",
"(",
"table",
",",
"\"key, COUNT(*) AS count\"",
",",
"where",
",",
"\"key\"",
",",
"\"count DESC\"",
")",
"events",
"=",
"db",
".",
"fetch",
"(",
"table",
",",
"where",
"=",
"where",
",",
"order",
"=",
"\"stamp\"",
")",
"for",
"e",
"in",
"events",
":",
"e",
"[",
"\"dt\"",
"]",
"=",
"datetime",
".",
"datetime",
".",
"fromtimestamp",
"(",
"e",
"[",
"\"stamp\"",
"]",
")",
"stats",
",",
"collatedevents",
"=",
"stats_keyboard",
"(",
"events",
",",
"table",
")",
"days",
",",
"input",
"=",
"db",
".",
"fetch",
"(",
"\"counts\"",
",",
"order",
"=",
"\"day\"",
",",
"type",
"=",
"table",
")",
",",
"\"keyboard\"",
"return",
"bottle",
".",
"template",
"(",
"\"heatmap.tpl\"",
",",
"locals",
"(",
")",
",",
"conf",
"=",
"conf",
")"
] | Handler for showing the keyboard statistics page. | [
"Handler",
"for",
"showing",
"the",
"keyboard",
"statistics",
"page",
"."
] | 245ff045163a1995e8cd5ac558d0a93024eb86eb | https://github.com/suurjaak/InputScope/blob/245ff045163a1995e8cd5ac558d0a93024eb86eb/inputscope/webui.py#L52-L64 | train |
suurjaak/InputScope | inputscope/webui.py | inputindex | def inputindex(input):
"""Handler for showing keyboard or mouse page with day and total links."""
stats = {}
countminmax = "SUM(count) AS count, MIN(day) AS first, MAX(day) AS last"
tables = ("moves", "clicks", "scrolls") if "mouse" == input else ("keys", "combos")
for table in tables:
stats[table] = db.fetchone("counts", countminmax, type=table)
stats[table]["days"] = db.fetch("counts", order="day DESC", type=table)
return bottle.template("input.tpl", locals(), conf=conf) | python | def inputindex(input):
"""Handler for showing keyboard or mouse page with day and total links."""
stats = {}
countminmax = "SUM(count) AS count, MIN(day) AS first, MAX(day) AS last"
tables = ("moves", "clicks", "scrolls") if "mouse" == input else ("keys", "combos")
for table in tables:
stats[table] = db.fetchone("counts", countminmax, type=table)
stats[table]["days"] = db.fetch("counts", order="day DESC", type=table)
return bottle.template("input.tpl", locals(), conf=conf) | [
"def",
"inputindex",
"(",
"input",
")",
":",
"stats",
"=",
"{",
"}",
"countminmax",
"=",
"\"SUM(count) AS count, MIN(day) AS first, MAX(day) AS last\"",
"tables",
"=",
"(",
"\"moves\"",
",",
"\"clicks\"",
",",
"\"scrolls\"",
")",
"if",
"\"mouse\"",
"==",
"input",
"else",
"(",
"\"keys\"",
",",
"\"combos\"",
")",
"for",
"table",
"in",
"tables",
":",
"stats",
"[",
"table",
"]",
"=",
"db",
".",
"fetchone",
"(",
"\"counts\"",
",",
"countminmax",
",",
"type",
"=",
"table",
")",
"stats",
"[",
"table",
"]",
"[",
"\"days\"",
"]",
"=",
"db",
".",
"fetch",
"(",
"\"counts\"",
",",
"order",
"=",
"\"day DESC\"",
",",
"type",
"=",
"table",
")",
"return",
"bottle",
".",
"template",
"(",
"\"input.tpl\"",
",",
"locals",
"(",
")",
",",
"conf",
"=",
"conf",
")"
] | Handler for showing keyboard or mouse page with day and total links. | [
"Handler",
"for",
"showing",
"keyboard",
"or",
"mouse",
"page",
"with",
"day",
"and",
"total",
"links",
"."
] | 245ff045163a1995e8cd5ac558d0a93024eb86eb | https://github.com/suurjaak/InputScope/blob/245ff045163a1995e8cd5ac558d0a93024eb86eb/inputscope/webui.py#L68-L76 | train |
suurjaak/InputScope | inputscope/webui.py | index | def index():
"""Handler for showing the GUI index page."""
stats = dict((k, {"count": 0}) for k, tt in conf.InputTables)
countminmax = "SUM(count) AS count, MIN(day) AS first, MAX(day) AS last"
for input, table in [(x, t) for x, tt in conf.InputTables for t in tt]:
row = db.fetchone("counts", countminmax, type=table)
if not row["count"]: continue # for input, table
stats[input]["count"] += row["count"]
for func, key in [(min, "first"), (max, "last")]:
stats[input][key] = (row[key] if key not in stats[input]
else func(stats[input][key], row[key]))
return bottle.template("index.tpl", locals(), conf=conf) | python | def index():
"""Handler for showing the GUI index page."""
stats = dict((k, {"count": 0}) for k, tt in conf.InputTables)
countminmax = "SUM(count) AS count, MIN(day) AS first, MAX(day) AS last"
for input, table in [(x, t) for x, tt in conf.InputTables for t in tt]:
row = db.fetchone("counts", countminmax, type=table)
if not row["count"]: continue # for input, table
stats[input]["count"] += row["count"]
for func, key in [(min, "first"), (max, "last")]:
stats[input][key] = (row[key] if key not in stats[input]
else func(stats[input][key], row[key]))
return bottle.template("index.tpl", locals(), conf=conf) | [
"def",
"index",
"(",
")",
":",
"stats",
"=",
"dict",
"(",
"(",
"k",
",",
"{",
"\"count\"",
":",
"0",
"}",
")",
"for",
"k",
",",
"tt",
"in",
"conf",
".",
"InputTables",
")",
"countminmax",
"=",
"\"SUM(count) AS count, MIN(day) AS first, MAX(day) AS last\"",
"for",
"input",
",",
"table",
"in",
"[",
"(",
"x",
",",
"t",
")",
"for",
"x",
",",
"tt",
"in",
"conf",
".",
"InputTables",
"for",
"t",
"in",
"tt",
"]",
":",
"row",
"=",
"db",
".",
"fetchone",
"(",
"\"counts\"",
",",
"countminmax",
",",
"type",
"=",
"table",
")",
"if",
"not",
"row",
"[",
"\"count\"",
"]",
":",
"continue",
"# for input, table\r",
"stats",
"[",
"input",
"]",
"[",
"\"count\"",
"]",
"+=",
"row",
"[",
"\"count\"",
"]",
"for",
"func",
",",
"key",
"in",
"[",
"(",
"min",
",",
"\"first\"",
")",
",",
"(",
"max",
",",
"\"last\"",
")",
"]",
":",
"stats",
"[",
"input",
"]",
"[",
"key",
"]",
"=",
"(",
"row",
"[",
"key",
"]",
"if",
"key",
"not",
"in",
"stats",
"[",
"input",
"]",
"else",
"func",
"(",
"stats",
"[",
"input",
"]",
"[",
"key",
"]",
",",
"row",
"[",
"key",
"]",
")",
")",
"return",
"bottle",
".",
"template",
"(",
"\"index.tpl\"",
",",
"locals",
"(",
")",
",",
"conf",
"=",
"conf",
")"
] | Handler for showing the GUI index page. | [
"Handler",
"for",
"showing",
"the",
"GUI",
"index",
"page",
"."
] | 245ff045163a1995e8cd5ac558d0a93024eb86eb | https://github.com/suurjaak/InputScope/blob/245ff045163a1995e8cd5ac558d0a93024eb86eb/inputscope/webui.py#L80-L91 | train |
suurjaak/InputScope | inputscope/webui.py | stats_keyboard | def stats_keyboard(events, table):
"""Return statistics and collated events for keyboard events."""
if len(events) < 2: return [], []
deltas, prev_dt = [], None
sessions, session = [], None
UNBROKEN_DELTA = datetime.timedelta(seconds=conf.KeyboardSessionMaxDelta)
blank = collections.defaultdict(lambda: collections.defaultdict(int))
collated = [blank.copy()] # [{dt, keys: {key: count}}]
for e in events:
if prev_dt:
if (prev_dt.second != e["dt"].second
or prev_dt.minute != e["dt"].minute or prev_dt.hour != e["dt"].hour):
collated.append(blank.copy())
delta = e["dt"] - prev_dt
deltas.append(delta)
if delta > UNBROKEN_DELTA:
session = None
else:
if not session:
session = []
sessions.append(session)
session.append(delta)
collated[-1]["dt"] = e["dt"]
collated[-1]["keys"][e["realkey"]] += 1
prev_dt = e["dt"]
longest_session = max(sessions + [[datetime.timedelta()]], key=lambda x: sum(x, datetime.timedelta()))
stats = [
("Average interval between combos",
sum(deltas, datetime.timedelta()) / len(deltas)),
] if "combos" == table else [
("Keys per hour",
int(3600 * len(events) / timedelta_seconds(events[-1]["dt"] - events[0]["dt"]))),
("Average interval between keys",
sum(deltas, datetime.timedelta()) / len(deltas)),
("Typing sessions (key interval < %ss)" % UNBROKEN_DELTA.seconds,
len(sessions)),
("Average keys in session",
sum(len(x) + 1 for x in sessions) / len(sessions)),
("Average session duration", sum((sum(x, datetime.timedelta())
for x in sessions), datetime.timedelta()) / len(sessions)),
("Longest session duration",
sum(longest_session, datetime.timedelta())),
("Keys in longest session",
len(longest_session) + 1),
("Most keys in session",
max(len(x) + 1 for x in sessions)),
]
return stats, collated | python | def stats_keyboard(events, table):
"""Return statistics and collated events for keyboard events."""
if len(events) < 2: return [], []
deltas, prev_dt = [], None
sessions, session = [], None
UNBROKEN_DELTA = datetime.timedelta(seconds=conf.KeyboardSessionMaxDelta)
blank = collections.defaultdict(lambda: collections.defaultdict(int))
collated = [blank.copy()] # [{dt, keys: {key: count}}]
for e in events:
if prev_dt:
if (prev_dt.second != e["dt"].second
or prev_dt.minute != e["dt"].minute or prev_dt.hour != e["dt"].hour):
collated.append(blank.copy())
delta = e["dt"] - prev_dt
deltas.append(delta)
if delta > UNBROKEN_DELTA:
session = None
else:
if not session:
session = []
sessions.append(session)
session.append(delta)
collated[-1]["dt"] = e["dt"]
collated[-1]["keys"][e["realkey"]] += 1
prev_dt = e["dt"]
longest_session = max(sessions + [[datetime.timedelta()]], key=lambda x: sum(x, datetime.timedelta()))
stats = [
("Average interval between combos",
sum(deltas, datetime.timedelta()) / len(deltas)),
] if "combos" == table else [
("Keys per hour",
int(3600 * len(events) / timedelta_seconds(events[-1]["dt"] - events[0]["dt"]))),
("Average interval between keys",
sum(deltas, datetime.timedelta()) / len(deltas)),
("Typing sessions (key interval < %ss)" % UNBROKEN_DELTA.seconds,
len(sessions)),
("Average keys in session",
sum(len(x) + 1 for x in sessions) / len(sessions)),
("Average session duration", sum((sum(x, datetime.timedelta())
for x in sessions), datetime.timedelta()) / len(sessions)),
("Longest session duration",
sum(longest_session, datetime.timedelta())),
("Keys in longest session",
len(longest_session) + 1),
("Most keys in session",
max(len(x) + 1 for x in sessions)),
]
return stats, collated | [
"def",
"stats_keyboard",
"(",
"events",
",",
"table",
")",
":",
"if",
"len",
"(",
"events",
")",
"<",
"2",
":",
"return",
"[",
"]",
",",
"[",
"]",
"deltas",
",",
"prev_dt",
"=",
"[",
"]",
",",
"None",
"sessions",
",",
"session",
"=",
"[",
"]",
",",
"None",
"UNBROKEN_DELTA",
"=",
"datetime",
".",
"timedelta",
"(",
"seconds",
"=",
"conf",
".",
"KeyboardSessionMaxDelta",
")",
"blank",
"=",
"collections",
".",
"defaultdict",
"(",
"lambda",
":",
"collections",
".",
"defaultdict",
"(",
"int",
")",
")",
"collated",
"=",
"[",
"blank",
".",
"copy",
"(",
")",
"]",
"# [{dt, keys: {key: count}}]\r",
"for",
"e",
"in",
"events",
":",
"if",
"prev_dt",
":",
"if",
"(",
"prev_dt",
".",
"second",
"!=",
"e",
"[",
"\"dt\"",
"]",
".",
"second",
"or",
"prev_dt",
".",
"minute",
"!=",
"e",
"[",
"\"dt\"",
"]",
".",
"minute",
"or",
"prev_dt",
".",
"hour",
"!=",
"e",
"[",
"\"dt\"",
"]",
".",
"hour",
")",
":",
"collated",
".",
"append",
"(",
"blank",
".",
"copy",
"(",
")",
")",
"delta",
"=",
"e",
"[",
"\"dt\"",
"]",
"-",
"prev_dt",
"deltas",
".",
"append",
"(",
"delta",
")",
"if",
"delta",
">",
"UNBROKEN_DELTA",
":",
"session",
"=",
"None",
"else",
":",
"if",
"not",
"session",
":",
"session",
"=",
"[",
"]",
"sessions",
".",
"append",
"(",
"session",
")",
"session",
".",
"append",
"(",
"delta",
")",
"collated",
"[",
"-",
"1",
"]",
"[",
"\"dt\"",
"]",
"=",
"e",
"[",
"\"dt\"",
"]",
"collated",
"[",
"-",
"1",
"]",
"[",
"\"keys\"",
"]",
"[",
"e",
"[",
"\"realkey\"",
"]",
"]",
"+=",
"1",
"prev_dt",
"=",
"e",
"[",
"\"dt\"",
"]",
"longest_session",
"=",
"max",
"(",
"sessions",
"+",
"[",
"[",
"datetime",
".",
"timedelta",
"(",
")",
"]",
"]",
",",
"key",
"=",
"lambda",
"x",
":",
"sum",
"(",
"x",
",",
"datetime",
".",
"timedelta",
"(",
")",
")",
")",
"stats",
"=",
"[",
"(",
"\"Average interval between combos\"",
",",
"sum",
"(",
"deltas",
",",
"datetime",
".",
"timedelta",
"(",
")",
")",
"/",
"len",
"(",
"deltas",
")",
")",
",",
"]",
"if",
"\"combos\"",
"==",
"table",
"else",
"[",
"(",
"\"Keys per hour\"",
",",
"int",
"(",
"3600",
"*",
"len",
"(",
"events",
")",
"/",
"timedelta_seconds",
"(",
"events",
"[",
"-",
"1",
"]",
"[",
"\"dt\"",
"]",
"-",
"events",
"[",
"0",
"]",
"[",
"\"dt\"",
"]",
")",
")",
")",
",",
"(",
"\"Average interval between keys\"",
",",
"sum",
"(",
"deltas",
",",
"datetime",
".",
"timedelta",
"(",
")",
")",
"/",
"len",
"(",
"deltas",
")",
")",
",",
"(",
"\"Typing sessions (key interval < %ss)\"",
"%",
"UNBROKEN_DELTA",
".",
"seconds",
",",
"len",
"(",
"sessions",
")",
")",
",",
"(",
"\"Average keys in session\"",
",",
"sum",
"(",
"len",
"(",
"x",
")",
"+",
"1",
"for",
"x",
"in",
"sessions",
")",
"/",
"len",
"(",
"sessions",
")",
")",
",",
"(",
"\"Average session duration\"",
",",
"sum",
"(",
"(",
"sum",
"(",
"x",
",",
"datetime",
".",
"timedelta",
"(",
")",
")",
"for",
"x",
"in",
"sessions",
")",
",",
"datetime",
".",
"timedelta",
"(",
")",
")",
"/",
"len",
"(",
"sessions",
")",
")",
",",
"(",
"\"Longest session duration\"",
",",
"sum",
"(",
"longest_session",
",",
"datetime",
".",
"timedelta",
"(",
")",
")",
")",
",",
"(",
"\"Keys in longest session\"",
",",
"len",
"(",
"longest_session",
")",
"+",
"1",
")",
",",
"(",
"\"Most keys in session\"",
",",
"max",
"(",
"len",
"(",
"x",
")",
"+",
"1",
"for",
"x",
"in",
"sessions",
")",
")",
",",
"]",
"return",
"stats",
",",
"collated"
] | Return statistics and collated events for keyboard events. | [
"Return",
"statistics",
"and",
"collated",
"events",
"for",
"keyboard",
"events",
"."
] | 245ff045163a1995e8cd5ac558d0a93024eb86eb | https://github.com/suurjaak/InputScope/blob/245ff045163a1995e8cd5ac558d0a93024eb86eb/inputscope/webui.py#L94-L141 | train |
suurjaak/InputScope | inputscope/webui.py | timedelta_seconds | def timedelta_seconds(timedelta):
"""Returns the total timedelta duration in seconds."""
return (timedelta.total_seconds() if hasattr(timedelta, "total_seconds")
else timedelta.days * 24 * 3600 + timedelta.seconds +
timedelta.microseconds / 1000000.) | python | def timedelta_seconds(timedelta):
"""Returns the total timedelta duration in seconds."""
return (timedelta.total_seconds() if hasattr(timedelta, "total_seconds")
else timedelta.days * 24 * 3600 + timedelta.seconds +
timedelta.microseconds / 1000000.) | [
"def",
"timedelta_seconds",
"(",
"timedelta",
")",
":",
"return",
"(",
"timedelta",
".",
"total_seconds",
"(",
")",
"if",
"hasattr",
"(",
"timedelta",
",",
"\"total_seconds\"",
")",
"else",
"timedelta",
".",
"days",
"*",
"24",
"*",
"3600",
"+",
"timedelta",
".",
"seconds",
"+",
"timedelta",
".",
"microseconds",
"/",
"1000000.",
")"
] | Returns the total timedelta duration in seconds. | [
"Returns",
"the",
"total",
"timedelta",
"duration",
"in",
"seconds",
"."
] | 245ff045163a1995e8cd5ac558d0a93024eb86eb | https://github.com/suurjaak/InputScope/blob/245ff045163a1995e8cd5ac558d0a93024eb86eb/inputscope/webui.py#L203-L207 | train |
suurjaak/InputScope | inputscope/webui.py | init | def init():
"""Initialize configuration and web application."""
global app
if app: return app
conf.init(), db.init(conf.DbPath, conf.DbStatements)
bottle.TEMPLATE_PATH.insert(0, conf.TemplatePath)
app = bottle.default_app()
bottle.BaseTemplate.defaults.update(get_url=app.get_url)
return app | python | def init():
"""Initialize configuration and web application."""
global app
if app: return app
conf.init(), db.init(conf.DbPath, conf.DbStatements)
bottle.TEMPLATE_PATH.insert(0, conf.TemplatePath)
app = bottle.default_app()
bottle.BaseTemplate.defaults.update(get_url=app.get_url)
return app | [
"def",
"init",
"(",
")",
":",
"global",
"app",
"if",
"app",
":",
"return",
"app",
"conf",
".",
"init",
"(",
")",
",",
"db",
".",
"init",
"(",
"conf",
".",
"DbPath",
",",
"conf",
".",
"DbStatements",
")",
"bottle",
".",
"TEMPLATE_PATH",
".",
"insert",
"(",
"0",
",",
"conf",
".",
"TemplatePath",
")",
"app",
"=",
"bottle",
".",
"default_app",
"(",
")",
"bottle",
".",
"BaseTemplate",
".",
"defaults",
".",
"update",
"(",
"get_url",
"=",
"app",
".",
"get_url",
")",
"return",
"app"
] | Initialize configuration and web application. | [
"Initialize",
"configuration",
"and",
"web",
"application",
"."
] | 245ff045163a1995e8cd5ac558d0a93024eb86eb | https://github.com/suurjaak/InputScope/blob/245ff045163a1995e8cd5ac558d0a93024eb86eb/inputscope/webui.py#L210-L219 | train |
suurjaak/InputScope | inputscope/webui.py | start | def start():
"""Starts the web server."""
global app
bottle.run(app, host=conf.WebHost, port=conf.WebPort,
debug=conf.WebAutoReload, reloader=conf.WebAutoReload,
quiet=conf.WebQuiet) | python | def start():
"""Starts the web server."""
global app
bottle.run(app, host=conf.WebHost, port=conf.WebPort,
debug=conf.WebAutoReload, reloader=conf.WebAutoReload,
quiet=conf.WebQuiet) | [
"def",
"start",
"(",
")",
":",
"global",
"app",
"bottle",
".",
"run",
"(",
"app",
",",
"host",
"=",
"conf",
".",
"WebHost",
",",
"port",
"=",
"conf",
".",
"WebPort",
",",
"debug",
"=",
"conf",
".",
"WebAutoReload",
",",
"reloader",
"=",
"conf",
".",
"WebAutoReload",
",",
"quiet",
"=",
"conf",
".",
"WebQuiet",
")"
] | Starts the web server. | [
"Starts",
"the",
"web",
"server",
"."
] | 245ff045163a1995e8cd5ac558d0a93024eb86eb | https://github.com/suurjaak/InputScope/blob/245ff045163a1995e8cd5ac558d0a93024eb86eb/inputscope/webui.py#L222-L227 | train |
Phyks/libbmc | libbmc/fetcher.py | download | def download(url, proxies=None):
"""
Download a PDF or DJVU document from a url, eventually using proxies.
:params url: The URL to the PDF/DJVU document to fetch.
:params proxies: An optional list of proxies to use. Proxies will be \
used sequentially. Proxies should be a list of proxy strings. \
Do not forget to include ``""`` (empty string) in the list if \
you want to try direct fetching without any proxy.
:returns: A tuple of the raw content of the downloaded data and its \
associated content-type. Returns ``(None, None)`` if it was \
unable to download the document.
>>> download("http://arxiv.org/pdf/1312.4006.pdf") # doctest: +SKIP
"""
# Handle default argument
if proxies is None:
proxies = [""]
# Loop over all available connections
for proxy in proxies:
# Handle no proxy case
if proxy == "":
socket.socket = DEFAULT_SOCKET
# Handle SOCKS proxy
elif proxy.startswith('socks'):
if proxy[5] == '4':
proxy_type = socks.SOCKS4
else:
proxy_type = socks.SOCKS5
proxy = proxy[proxy.find('://') + 3:]
try:
proxy, port = proxy.split(':')
except ValueError:
port = None
socks.set_default_proxy(proxy_type, proxy, port)
socket.socket = socks.socksocket
# Handle generic HTTP proxy
else:
try:
proxy, port = proxy.split(':')
except ValueError:
port = None
socks.set_default_proxy(socks.HTTP, proxy, port)
socket.socket = socks.socksocket
downloaded = _download_helper(url)
if downloaded is not None:
return downloaded
# In case of running out of proxies, return (None, None)
return (None, None) | python | def download(url, proxies=None):
"""
Download a PDF or DJVU document from a url, eventually using proxies.
:params url: The URL to the PDF/DJVU document to fetch.
:params proxies: An optional list of proxies to use. Proxies will be \
used sequentially. Proxies should be a list of proxy strings. \
Do not forget to include ``""`` (empty string) in the list if \
you want to try direct fetching without any proxy.
:returns: A tuple of the raw content of the downloaded data and its \
associated content-type. Returns ``(None, None)`` if it was \
unable to download the document.
>>> download("http://arxiv.org/pdf/1312.4006.pdf") # doctest: +SKIP
"""
# Handle default argument
if proxies is None:
proxies = [""]
# Loop over all available connections
for proxy in proxies:
# Handle no proxy case
if proxy == "":
socket.socket = DEFAULT_SOCKET
# Handle SOCKS proxy
elif proxy.startswith('socks'):
if proxy[5] == '4':
proxy_type = socks.SOCKS4
else:
proxy_type = socks.SOCKS5
proxy = proxy[proxy.find('://') + 3:]
try:
proxy, port = proxy.split(':')
except ValueError:
port = None
socks.set_default_proxy(proxy_type, proxy, port)
socket.socket = socks.socksocket
# Handle generic HTTP proxy
else:
try:
proxy, port = proxy.split(':')
except ValueError:
port = None
socks.set_default_proxy(socks.HTTP, proxy, port)
socket.socket = socks.socksocket
downloaded = _download_helper(url)
if downloaded is not None:
return downloaded
# In case of running out of proxies, return (None, None)
return (None, None) | [
"def",
"download",
"(",
"url",
",",
"proxies",
"=",
"None",
")",
":",
"# Handle default argument",
"if",
"proxies",
"is",
"None",
":",
"proxies",
"=",
"[",
"\"\"",
"]",
"# Loop over all available connections",
"for",
"proxy",
"in",
"proxies",
":",
"# Handle no proxy case",
"if",
"proxy",
"==",
"\"\"",
":",
"socket",
".",
"socket",
"=",
"DEFAULT_SOCKET",
"# Handle SOCKS proxy",
"elif",
"proxy",
".",
"startswith",
"(",
"'socks'",
")",
":",
"if",
"proxy",
"[",
"5",
"]",
"==",
"'4'",
":",
"proxy_type",
"=",
"socks",
".",
"SOCKS4",
"else",
":",
"proxy_type",
"=",
"socks",
".",
"SOCKS5",
"proxy",
"=",
"proxy",
"[",
"proxy",
".",
"find",
"(",
"'://'",
")",
"+",
"3",
":",
"]",
"try",
":",
"proxy",
",",
"port",
"=",
"proxy",
".",
"split",
"(",
"':'",
")",
"except",
"ValueError",
":",
"port",
"=",
"None",
"socks",
".",
"set_default_proxy",
"(",
"proxy_type",
",",
"proxy",
",",
"port",
")",
"socket",
".",
"socket",
"=",
"socks",
".",
"socksocket",
"# Handle generic HTTP proxy",
"else",
":",
"try",
":",
"proxy",
",",
"port",
"=",
"proxy",
".",
"split",
"(",
"':'",
")",
"except",
"ValueError",
":",
"port",
"=",
"None",
"socks",
".",
"set_default_proxy",
"(",
"socks",
".",
"HTTP",
",",
"proxy",
",",
"port",
")",
"socket",
".",
"socket",
"=",
"socks",
".",
"socksocket",
"downloaded",
"=",
"_download_helper",
"(",
"url",
")",
"if",
"downloaded",
"is",
"not",
"None",
":",
"return",
"downloaded",
"# In case of running out of proxies, return (None, None)",
"return",
"(",
"None",
",",
"None",
")"
] | Download a PDF or DJVU document from a url, eventually using proxies.
:params url: The URL to the PDF/DJVU document to fetch.
:params proxies: An optional list of proxies to use. Proxies will be \
used sequentially. Proxies should be a list of proxy strings. \
Do not forget to include ``""`` (empty string) in the list if \
you want to try direct fetching without any proxy.
:returns: A tuple of the raw content of the downloaded data and its \
associated content-type. Returns ``(None, None)`` if it was \
unable to download the document.
>>> download("http://arxiv.org/pdf/1312.4006.pdf") # doctest: +SKIP | [
"Download",
"a",
"PDF",
"or",
"DJVU",
"document",
"from",
"a",
"url",
"eventually",
"using",
"proxies",
"."
] | 9ef1a29d2514157d1edd6c13ecbd61b07ae9315e | https://github.com/Phyks/libbmc/blob/9ef1a29d2514157d1edd6c13ecbd61b07ae9315e/libbmc/fetcher.py#L80-L132 | train |
jenisys/parse_type | parse_type/parse_util.py | Field.make_format | def make_format(format_spec):
"""Build format string from a format specification.
:param format_spec: Format specification (as FormatSpec object).
:return: Composed format (as string).
"""
fill = ''
align = ''
zero = ''
width = format_spec.width
if format_spec.align:
align = format_spec.align[0]
if format_spec.fill:
fill = format_spec.fill[0]
if format_spec.zero:
zero = '0'
precision_part = ""
if format_spec.precision:
precision_part = ".%s" % format_spec.precision
# -- FORMAT-SPEC: [[fill]align][0][width][.precision][type]
return "%s%s%s%s%s%s" % (fill, align, zero, width,
precision_part, format_spec.type) | python | def make_format(format_spec):
"""Build format string from a format specification.
:param format_spec: Format specification (as FormatSpec object).
:return: Composed format (as string).
"""
fill = ''
align = ''
zero = ''
width = format_spec.width
if format_spec.align:
align = format_spec.align[0]
if format_spec.fill:
fill = format_spec.fill[0]
if format_spec.zero:
zero = '0'
precision_part = ""
if format_spec.precision:
precision_part = ".%s" % format_spec.precision
# -- FORMAT-SPEC: [[fill]align][0][width][.precision][type]
return "%s%s%s%s%s%s" % (fill, align, zero, width,
precision_part, format_spec.type) | [
"def",
"make_format",
"(",
"format_spec",
")",
":",
"fill",
"=",
"''",
"align",
"=",
"''",
"zero",
"=",
"''",
"width",
"=",
"format_spec",
".",
"width",
"if",
"format_spec",
".",
"align",
":",
"align",
"=",
"format_spec",
".",
"align",
"[",
"0",
"]",
"if",
"format_spec",
".",
"fill",
":",
"fill",
"=",
"format_spec",
".",
"fill",
"[",
"0",
"]",
"if",
"format_spec",
".",
"zero",
":",
"zero",
"=",
"'0'",
"precision_part",
"=",
"\"\"",
"if",
"format_spec",
".",
"precision",
":",
"precision_part",
"=",
"\".%s\"",
"%",
"format_spec",
".",
"precision",
"# -- FORMAT-SPEC: [[fill]align][0][width][.precision][type]",
"return",
"\"%s%s%s%s%s%s\"",
"%",
"(",
"fill",
",",
"align",
",",
"zero",
",",
"width",
",",
"precision_part",
",",
"format_spec",
".",
"type",
")"
] | Build format string from a format specification.
:param format_spec: Format specification (as FormatSpec object).
:return: Composed format (as string). | [
"Build",
"format",
"string",
"from",
"a",
"format",
"specification",
"."
] | 7cad3a67a5ca725cb786da31f656fd473084289f | https://github.com/jenisys/parse_type/blob/7cad3a67a5ca725cb786da31f656fd473084289f/parse_type/parse_util.py#L78-L101 | train |
jenisys/parse_type | parse_type/parse_util.py | FieldParser.extract_fields | def extract_fields(cls, schema):
"""Extract fields in a parse expression schema.
:param schema: Parse expression schema/format to use (as string).
:return: Generator for fields in schema (as Field objects).
"""
# -- BASED-ON: parse.Parser._generate_expression()
for part in parse.PARSE_RE.split(schema):
if not part or part == '{{' or part == '}}':
continue
elif part[0] == '{':
# this will be a braces-delimited field to handle
yield cls.parse(part) | python | def extract_fields(cls, schema):
"""Extract fields in a parse expression schema.
:param schema: Parse expression schema/format to use (as string).
:return: Generator for fields in schema (as Field objects).
"""
# -- BASED-ON: parse.Parser._generate_expression()
for part in parse.PARSE_RE.split(schema):
if not part or part == '{{' or part == '}}':
continue
elif part[0] == '{':
# this will be a braces-delimited field to handle
yield cls.parse(part) | [
"def",
"extract_fields",
"(",
"cls",
",",
"schema",
")",
":",
"# -- BASED-ON: parse.Parser._generate_expression()",
"for",
"part",
"in",
"parse",
".",
"PARSE_RE",
".",
"split",
"(",
"schema",
")",
":",
"if",
"not",
"part",
"or",
"part",
"==",
"'{{'",
"or",
"part",
"==",
"'}}'",
":",
"continue",
"elif",
"part",
"[",
"0",
"]",
"==",
"'{'",
":",
"# this will be a braces-delimited field to handle",
"yield",
"cls",
".",
"parse",
"(",
"part",
")"
] | Extract fields in a parse expression schema.
:param schema: Parse expression schema/format to use (as string).
:return: Generator for fields in schema (as Field objects). | [
"Extract",
"fields",
"in",
"a",
"parse",
"expression",
"schema",
"."
] | 7cad3a67a5ca725cb786da31f656fd473084289f | https://github.com/jenisys/parse_type/blob/7cad3a67a5ca725cb786da31f656fd473084289f/parse_type/parse_util.py#L175-L187 | train |
dbarsam/python-vsgen | vsgen/util/logger.py | VSGLogger._registerHandler | def _registerHandler(self, handler):
"""
Registers a handler.
:param handler: A handler object.
"""
self._logger.addHandler(handler)
self._handlers.append(handler) | python | def _registerHandler(self, handler):
"""
Registers a handler.
:param handler: A handler object.
"""
self._logger.addHandler(handler)
self._handlers.append(handler) | [
"def",
"_registerHandler",
"(",
"self",
",",
"handler",
")",
":",
"self",
".",
"_logger",
".",
"addHandler",
"(",
"handler",
")",
"self",
".",
"_handlers",
".",
"append",
"(",
"handler",
")"
] | Registers a handler.
:param handler: A handler object. | [
"Registers",
"a",
"handler",
"."
] | 640191bb018a1ff7d7b7a4982e0d3c1a423ba878 | https://github.com/dbarsam/python-vsgen/blob/640191bb018a1ff7d7b7a4982e0d3c1a423ba878/vsgen/util/logger.py#L80-L87 | train |
dbarsam/python-vsgen | vsgen/util/logger.py | VSGLogger._unregisterHandler | def _unregisterHandler(self, handler, shutdown=True):
"""
Unregisters the logging handler.
:param handler: A handler previously registered with this loggger.
:param shutdown: Flag to shutdown the handler.
"""
if handler in self._handlers:
self._handlers.remove(handler)
self._logger.removeHandler(handler)
if shutdown:
try:
handler.close()
except KeyError:
# Depending on the Python version, it's possible for this call
# to fail most likely because some logging module objects get
# garbage collected before the VSGLogger object is.
pass | python | def _unregisterHandler(self, handler, shutdown=True):
"""
Unregisters the logging handler.
:param handler: A handler previously registered with this loggger.
:param shutdown: Flag to shutdown the handler.
"""
if handler in self._handlers:
self._handlers.remove(handler)
self._logger.removeHandler(handler)
if shutdown:
try:
handler.close()
except KeyError:
# Depending on the Python version, it's possible for this call
# to fail most likely because some logging module objects get
# garbage collected before the VSGLogger object is.
pass | [
"def",
"_unregisterHandler",
"(",
"self",
",",
"handler",
",",
"shutdown",
"=",
"True",
")",
":",
"if",
"handler",
"in",
"self",
".",
"_handlers",
":",
"self",
".",
"_handlers",
".",
"remove",
"(",
"handler",
")",
"self",
".",
"_logger",
".",
"removeHandler",
"(",
"handler",
")",
"if",
"shutdown",
":",
"try",
":",
"handler",
".",
"close",
"(",
")",
"except",
"KeyError",
":",
"# Depending on the Python version, it's possible for this call",
"# to fail most likely because some logging module objects get",
"# garbage collected before the VSGLogger object is.",
"pass"
] | Unregisters the logging handler.
:param handler: A handler previously registered with this loggger.
:param shutdown: Flag to shutdown the handler. | [
"Unregisters",
"the",
"logging",
"handler",
"."
] | 640191bb018a1ff7d7b7a4982e0d3c1a423ba878 | https://github.com/dbarsam/python-vsgen/blob/640191bb018a1ff7d7b7a4982e0d3c1a423ba878/vsgen/util/logger.py#L89-L106 | train |
dbarsam/python-vsgen | vsgen/util/logger.py | VSGLogger.getLogger | def getLogger(cls, name=None):
"""
Retrieves the Python native logger
:param name: The name of the logger instance in the VSG namespace (VSG.<name>); a None value will use the VSG root.
:return: The instacne of the Python logger object.
"""
return logging.getLogger("{0}.{1}".format(cls.BASENAME, name) if name else cls.BASENAME) | python | def getLogger(cls, name=None):
"""
Retrieves the Python native logger
:param name: The name of the logger instance in the VSG namespace (VSG.<name>); a None value will use the VSG root.
:return: The instacne of the Python logger object.
"""
return logging.getLogger("{0}.{1}".format(cls.BASENAME, name) if name else cls.BASENAME) | [
"def",
"getLogger",
"(",
"cls",
",",
"name",
"=",
"None",
")",
":",
"return",
"logging",
".",
"getLogger",
"(",
"\"{0}.{1}\"",
".",
"format",
"(",
"cls",
".",
"BASENAME",
",",
"name",
")",
"if",
"name",
"else",
"cls",
".",
"BASENAME",
")"
] | Retrieves the Python native logger
:param name: The name of the logger instance in the VSG namespace (VSG.<name>); a None value will use the VSG root.
:return: The instacne of the Python logger object. | [
"Retrieves",
"the",
"Python",
"native",
"logger"
] | 640191bb018a1ff7d7b7a4982e0d3c1a423ba878 | https://github.com/dbarsam/python-vsgen/blob/640191bb018a1ff7d7b7a4982e0d3c1a423ba878/vsgen/util/logger.py#L109-L116 | train |
dbarsam/python-vsgen | vsgen/util/logger.py | VSGLogger.debug | def debug(cls, name, message, *args):
"""
Convenience function to log a message at the DEBUG level.
:param name: The name of the logger instance in the VSG namespace (VSG.<name>)
:param message: A message format string.
:param args: The arguments that are are merged into msg using the string formatting operator.
:..note: The native logger's `kwargs` are not used in this function.
"""
cls.getLogger(name).debug(message, *args) | python | def debug(cls, name, message, *args):
"""
Convenience function to log a message at the DEBUG level.
:param name: The name of the logger instance in the VSG namespace (VSG.<name>)
:param message: A message format string.
:param args: The arguments that are are merged into msg using the string formatting operator.
:..note: The native logger's `kwargs` are not used in this function.
"""
cls.getLogger(name).debug(message, *args) | [
"def",
"debug",
"(",
"cls",
",",
"name",
",",
"message",
",",
"*",
"args",
")",
":",
"cls",
".",
"getLogger",
"(",
"name",
")",
".",
"debug",
"(",
"message",
",",
"*",
"args",
")"
] | Convenience function to log a message at the DEBUG level.
:param name: The name of the logger instance in the VSG namespace (VSG.<name>)
:param message: A message format string.
:param args: The arguments that are are merged into msg using the string formatting operator.
:..note: The native logger's `kwargs` are not used in this function. | [
"Convenience",
"function",
"to",
"log",
"a",
"message",
"at",
"the",
"DEBUG",
"level",
"."
] | 640191bb018a1ff7d7b7a4982e0d3c1a423ba878 | https://github.com/dbarsam/python-vsgen/blob/640191bb018a1ff7d7b7a4982e0d3c1a423ba878/vsgen/util/logger.py#L119-L128 | train |
dbarsam/python-vsgen | vsgen/util/logger.py | VSGLogger.info | def info(cls, name, message, *args):
"""
Convenience function to log a message at the INFO level.
:param name: The name of the logger instance in the VSG namespace (VSG.<name>)
:param message: A message format string.
:param args: The arguments that are are merged into msg using the string formatting operator.
:..note: The native logger's `kwargs` are not used in this function.
"""
cls.getLogger(name).info(message, *args) | python | def info(cls, name, message, *args):
"""
Convenience function to log a message at the INFO level.
:param name: The name of the logger instance in the VSG namespace (VSG.<name>)
:param message: A message format string.
:param args: The arguments that are are merged into msg using the string formatting operator.
:..note: The native logger's `kwargs` are not used in this function.
"""
cls.getLogger(name).info(message, *args) | [
"def",
"info",
"(",
"cls",
",",
"name",
",",
"message",
",",
"*",
"args",
")",
":",
"cls",
".",
"getLogger",
"(",
"name",
")",
".",
"info",
"(",
"message",
",",
"*",
"args",
")"
] | Convenience function to log a message at the INFO level.
:param name: The name of the logger instance in the VSG namespace (VSG.<name>)
:param message: A message format string.
:param args: The arguments that are are merged into msg using the string formatting operator.
:..note: The native logger's `kwargs` are not used in this function. | [
"Convenience",
"function",
"to",
"log",
"a",
"message",
"at",
"the",
"INFO",
"level",
"."
] | 640191bb018a1ff7d7b7a4982e0d3c1a423ba878 | https://github.com/dbarsam/python-vsgen/blob/640191bb018a1ff7d7b7a4982e0d3c1a423ba878/vsgen/util/logger.py#L131-L140 | train |
dbarsam/python-vsgen | vsgen/util/logger.py | VSGLogger.warning | def warning(cls, name, message, *args):
"""
Convenience function to log a message at the WARNING level.
:param name: The name of the logger instance in the VSG namespace (VSG.<name>)
:param message: A message format string.
:param args: The arguments that are are merged into msg using the string formatting operator.
:..note: The native logger's `kwargs` are not used in this function.
"""
cls.getLogger(name).warning(message, *args) | python | def warning(cls, name, message, *args):
"""
Convenience function to log a message at the WARNING level.
:param name: The name of the logger instance in the VSG namespace (VSG.<name>)
:param message: A message format string.
:param args: The arguments that are are merged into msg using the string formatting operator.
:..note: The native logger's `kwargs` are not used in this function.
"""
cls.getLogger(name).warning(message, *args) | [
"def",
"warning",
"(",
"cls",
",",
"name",
",",
"message",
",",
"*",
"args",
")",
":",
"cls",
".",
"getLogger",
"(",
"name",
")",
".",
"warning",
"(",
"message",
",",
"*",
"args",
")"
] | Convenience function to log a message at the WARNING level.
:param name: The name of the logger instance in the VSG namespace (VSG.<name>)
:param message: A message format string.
:param args: The arguments that are are merged into msg using the string formatting operator.
:..note: The native logger's `kwargs` are not used in this function. | [
"Convenience",
"function",
"to",
"log",
"a",
"message",
"at",
"the",
"WARNING",
"level",
"."
] | 640191bb018a1ff7d7b7a4982e0d3c1a423ba878 | https://github.com/dbarsam/python-vsgen/blob/640191bb018a1ff7d7b7a4982e0d3c1a423ba878/vsgen/util/logger.py#L143-L152 | train |
dbarsam/python-vsgen | vsgen/util/logger.py | VSGLogger.error | def error(cls, name, message, *args):
"""
Convenience function to log a message at the ERROR level.
:param name: The name of the logger instance in the VSG namespace (VSG.<name>)
:param message: A message format string.
:param args: The arguments that are are merged into msg using the string formatting operator.
:..note: The native logger's `kwargs` are not used in this function.
"""
cls.getLogger(name).error(message, *args) | python | def error(cls, name, message, *args):
"""
Convenience function to log a message at the ERROR level.
:param name: The name of the logger instance in the VSG namespace (VSG.<name>)
:param message: A message format string.
:param args: The arguments that are are merged into msg using the string formatting operator.
:..note: The native logger's `kwargs` are not used in this function.
"""
cls.getLogger(name).error(message, *args) | [
"def",
"error",
"(",
"cls",
",",
"name",
",",
"message",
",",
"*",
"args",
")",
":",
"cls",
".",
"getLogger",
"(",
"name",
")",
".",
"error",
"(",
"message",
",",
"*",
"args",
")"
] | Convenience function to log a message at the ERROR level.
:param name: The name of the logger instance in the VSG namespace (VSG.<name>)
:param message: A message format string.
:param args: The arguments that are are merged into msg using the string formatting operator.
:..note: The native logger's `kwargs` are not used in this function. | [
"Convenience",
"function",
"to",
"log",
"a",
"message",
"at",
"the",
"ERROR",
"level",
"."
] | 640191bb018a1ff7d7b7a4982e0d3c1a423ba878 | https://github.com/dbarsam/python-vsgen/blob/640191bb018a1ff7d7b7a4982e0d3c1a423ba878/vsgen/util/logger.py#L155-L164 | train |
dbarsam/python-vsgen | vsgen/util/logger.py | VSGLogger.critical | def critical(cls, name, message, *args):
"""
Convenience function to log a message at the CRITICAL level.
:param name: The name of the logger instance in the VSG namespace (VSG.<name>)
:param message: A message format string.
:param args: The arguments that are are merged into msg using the string formatting operator.
:..note: The native logger's `kwargs` are not used in this function.
"""
cls.getLogger(name).critical(message, *args) | python | def critical(cls, name, message, *args):
"""
Convenience function to log a message at the CRITICAL level.
:param name: The name of the logger instance in the VSG namespace (VSG.<name>)
:param message: A message format string.
:param args: The arguments that are are merged into msg using the string formatting operator.
:..note: The native logger's `kwargs` are not used in this function.
"""
cls.getLogger(name).critical(message, *args) | [
"def",
"critical",
"(",
"cls",
",",
"name",
",",
"message",
",",
"*",
"args",
")",
":",
"cls",
".",
"getLogger",
"(",
"name",
")",
".",
"critical",
"(",
"message",
",",
"*",
"args",
")"
] | Convenience function to log a message at the CRITICAL level.
:param name: The name of the logger instance in the VSG namespace (VSG.<name>)
:param message: A message format string.
:param args: The arguments that are are merged into msg using the string formatting operator.
:..note: The native logger's `kwargs` are not used in this function. | [
"Convenience",
"function",
"to",
"log",
"a",
"message",
"at",
"the",
"CRITICAL",
"level",
"."
] | 640191bb018a1ff7d7b7a4982e0d3c1a423ba878 | https://github.com/dbarsam/python-vsgen/blob/640191bb018a1ff7d7b7a4982e0d3c1a423ba878/vsgen/util/logger.py#L167-L176 | train |
dbarsam/python-vsgen | vsgen/util/logger.py | VSGLogger.exception | def exception(cls, name, message, *args):
"""
Convenience function to log a message at the ERROR level with additonal exception information.
:param name: The name of the logger instance in the VSG namespace (VSG.<name>)
:param message: A message format string.
:param args: The arguments that are are merged into msg using the string formatting operator.
:..note: This method should only be called from an exception handler.
"""
cls.getLogger(name).exception(message, *args) | python | def exception(cls, name, message, *args):
"""
Convenience function to log a message at the ERROR level with additonal exception information.
:param name: The name of the logger instance in the VSG namespace (VSG.<name>)
:param message: A message format string.
:param args: The arguments that are are merged into msg using the string formatting operator.
:..note: This method should only be called from an exception handler.
"""
cls.getLogger(name).exception(message, *args) | [
"def",
"exception",
"(",
"cls",
",",
"name",
",",
"message",
",",
"*",
"args",
")",
":",
"cls",
".",
"getLogger",
"(",
"name",
")",
".",
"exception",
"(",
"message",
",",
"*",
"args",
")"
] | Convenience function to log a message at the ERROR level with additonal exception information.
:param name: The name of the logger instance in the VSG namespace (VSG.<name>)
:param message: A message format string.
:param args: The arguments that are are merged into msg using the string formatting operator.
:..note: This method should only be called from an exception handler. | [
"Convenience",
"function",
"to",
"log",
"a",
"message",
"at",
"the",
"ERROR",
"level",
"with",
"additonal",
"exception",
"information",
"."
] | 640191bb018a1ff7d7b7a4982e0d3c1a423ba878 | https://github.com/dbarsam/python-vsgen/blob/640191bb018a1ff7d7b7a4982e0d3c1a423ba878/vsgen/util/logger.py#L179-L188 | train |
go-macaroon-bakery/py-macaroon-bakery | macaroonbakery/bakery/_checker.py | AuthChecker.allow | def allow(self, ctx, ops):
''' Checks that the authorizer's request is authorized to
perform all the given operations. Note that allow does not check
first party caveats - if there is more than one macaroon that may
authorize the request, it will choose the first one that does
regardless.
If all the operations are allowed, an AuthInfo is returned holding
details of the decision and any first party caveats that must be
checked before actually executing any operation.
If operations include LOGIN_OP, the request should contain an
authentication macaroon proving the client's identity. Once an
authentication macaroon is chosen, it will be used for all other
authorization requests.
If an operation was not allowed, an exception will be raised which may
be:
- DischargeRequiredError holding the operations that remain to
be authorized in order to allow authorization to proceed
- PermissionDenied when no operations can be authorized and there's
no third party to discharge macaroons for.
@param ctx AuthContext
@param ops an array of Op
:return: an AuthInfo object.
'''
auth_info, _ = self.allow_any(ctx, ops)
return auth_info | python | def allow(self, ctx, ops):
''' Checks that the authorizer's request is authorized to
perform all the given operations. Note that allow does not check
first party caveats - if there is more than one macaroon that may
authorize the request, it will choose the first one that does
regardless.
If all the operations are allowed, an AuthInfo is returned holding
details of the decision and any first party caveats that must be
checked before actually executing any operation.
If operations include LOGIN_OP, the request should contain an
authentication macaroon proving the client's identity. Once an
authentication macaroon is chosen, it will be used for all other
authorization requests.
If an operation was not allowed, an exception will be raised which may
be:
- DischargeRequiredError holding the operations that remain to
be authorized in order to allow authorization to proceed
- PermissionDenied when no operations can be authorized and there's
no third party to discharge macaroons for.
@param ctx AuthContext
@param ops an array of Op
:return: an AuthInfo object.
'''
auth_info, _ = self.allow_any(ctx, ops)
return auth_info | [
"def",
"allow",
"(",
"self",
",",
"ctx",
",",
"ops",
")",
":",
"auth_info",
",",
"_",
"=",
"self",
".",
"allow_any",
"(",
"ctx",
",",
"ops",
")",
"return",
"auth_info"
] | Checks that the authorizer's request is authorized to
perform all the given operations. Note that allow does not check
first party caveats - if there is more than one macaroon that may
authorize the request, it will choose the first one that does
regardless.
If all the operations are allowed, an AuthInfo is returned holding
details of the decision and any first party caveats that must be
checked before actually executing any operation.
If operations include LOGIN_OP, the request should contain an
authentication macaroon proving the client's identity. Once an
authentication macaroon is chosen, it will be used for all other
authorization requests.
If an operation was not allowed, an exception will be raised which may
be:
- DischargeRequiredError holding the operations that remain to
be authorized in order to allow authorization to proceed
- PermissionDenied when no operations can be authorized and there's
no third party to discharge macaroons for.
@param ctx AuthContext
@param ops an array of Op
:return: an AuthInfo object. | [
"Checks",
"that",
"the",
"authorizer",
"s",
"request",
"is",
"authorized",
"to",
"perform",
"all",
"the",
"given",
"operations",
".",
"Note",
"that",
"allow",
"does",
"not",
"check",
"first",
"party",
"caveats",
"-",
"if",
"there",
"is",
"more",
"than",
"one",
"macaroon",
"that",
"may",
"authorize",
"the",
"request",
"it",
"will",
"choose",
"the",
"first",
"one",
"that",
"does",
"regardless",
"."
] | 63ce1ef1dabe816eb8aaec48fbb46761c34ddf77 | https://github.com/go-macaroon-bakery/py-macaroon-bakery/blob/63ce1ef1dabe816eb8aaec48fbb46761c34ddf77/macaroonbakery/bakery/_checker.py#L183-L212 | train |
go-macaroon-bakery/py-macaroon-bakery | macaroonbakery/bakery/_checker.py | AuthChecker.allow_any | def allow_any(self, ctx, ops):
''' like allow except that it will authorize as many of the
operations as possible without requiring any to be authorized. If all
the operations succeeded, the array will be nil.
If any the operations failed, the returned error will be the same
that allow would return and each element in the returned slice will
hold whether its respective operation was allowed.
If all the operations succeeded, the returned slice will be None.
The returned AuthInfo will always be non-None.
The LOGIN_OP operation is treated specially - it is always required if
present in ops.
@param ctx AuthContext
@param ops an array of Op
:return: an AuthInfo object and the auth used as an array of int.
'''
authed, used = self._allow_any(ctx, ops)
return self._new_auth_info(used), authed | python | def allow_any(self, ctx, ops):
''' like allow except that it will authorize as many of the
operations as possible without requiring any to be authorized. If all
the operations succeeded, the array will be nil.
If any the operations failed, the returned error will be the same
that allow would return and each element in the returned slice will
hold whether its respective operation was allowed.
If all the operations succeeded, the returned slice will be None.
The returned AuthInfo will always be non-None.
The LOGIN_OP operation is treated specially - it is always required if
present in ops.
@param ctx AuthContext
@param ops an array of Op
:return: an AuthInfo object and the auth used as an array of int.
'''
authed, used = self._allow_any(ctx, ops)
return self._new_auth_info(used), authed | [
"def",
"allow_any",
"(",
"self",
",",
"ctx",
",",
"ops",
")",
":",
"authed",
",",
"used",
"=",
"self",
".",
"_allow_any",
"(",
"ctx",
",",
"ops",
")",
"return",
"self",
".",
"_new_auth_info",
"(",
"used",
")",
",",
"authed"
] | like allow except that it will authorize as many of the
operations as possible without requiring any to be authorized. If all
the operations succeeded, the array will be nil.
If any the operations failed, the returned error will be the same
that allow would return and each element in the returned slice will
hold whether its respective operation was allowed.
If all the operations succeeded, the returned slice will be None.
The returned AuthInfo will always be non-None.
The LOGIN_OP operation is treated specially - it is always required if
present in ops.
@param ctx AuthContext
@param ops an array of Op
:return: an AuthInfo object and the auth used as an array of int. | [
"like",
"allow",
"except",
"that",
"it",
"will",
"authorize",
"as",
"many",
"of",
"the",
"operations",
"as",
"possible",
"without",
"requiring",
"any",
"to",
"be",
"authorized",
".",
"If",
"all",
"the",
"operations",
"succeeded",
"the",
"array",
"will",
"be",
"nil",
"."
] | 63ce1ef1dabe816eb8aaec48fbb46761c34ddf77 | https://github.com/go-macaroon-bakery/py-macaroon-bakery/blob/63ce1ef1dabe816eb8aaec48fbb46761c34ddf77/macaroonbakery/bakery/_checker.py#L214-L234 | train |
go-macaroon-bakery/py-macaroon-bakery | macaroonbakery/bakery/_checker.py | AuthChecker.allow_capability | def allow_capability(self, ctx, ops):
'''Checks that the user is allowed to perform all the
given operations. If not, a discharge error will be raised.
If allow_capability succeeds, it returns a list of first party caveat
conditions that must be applied to any macaroon granting capability
to execute the operations. Those caveat conditions will not
include any declarations contained in login macaroons - the
caller must be careful not to mint a macaroon associated
with the LOGIN_OP operation unless they add the expected
declaration caveat too - in general, clients should not create
capabilities that grant LOGIN_OP rights.
The operations must include at least one non-LOGIN_OP operation.
'''
nops = 0
for op in ops:
if op != LOGIN_OP:
nops += 1
if nops == 0:
raise ValueError('no non-login operations required in capability')
_, used = self._allow_any(ctx, ops)
squasher = _CaveatSquasher()
for i, is_used in enumerate(used):
if not is_used:
continue
for cond in self._conditions[i]:
squasher.add(cond)
return squasher.final() | python | def allow_capability(self, ctx, ops):
'''Checks that the user is allowed to perform all the
given operations. If not, a discharge error will be raised.
If allow_capability succeeds, it returns a list of first party caveat
conditions that must be applied to any macaroon granting capability
to execute the operations. Those caveat conditions will not
include any declarations contained in login macaroons - the
caller must be careful not to mint a macaroon associated
with the LOGIN_OP operation unless they add the expected
declaration caveat too - in general, clients should not create
capabilities that grant LOGIN_OP rights.
The operations must include at least one non-LOGIN_OP operation.
'''
nops = 0
for op in ops:
if op != LOGIN_OP:
nops += 1
if nops == 0:
raise ValueError('no non-login operations required in capability')
_, used = self._allow_any(ctx, ops)
squasher = _CaveatSquasher()
for i, is_used in enumerate(used):
if not is_used:
continue
for cond in self._conditions[i]:
squasher.add(cond)
return squasher.final() | [
"def",
"allow_capability",
"(",
"self",
",",
"ctx",
",",
"ops",
")",
":",
"nops",
"=",
"0",
"for",
"op",
"in",
"ops",
":",
"if",
"op",
"!=",
"LOGIN_OP",
":",
"nops",
"+=",
"1",
"if",
"nops",
"==",
"0",
":",
"raise",
"ValueError",
"(",
"'no non-login operations required in capability'",
")",
"_",
",",
"used",
"=",
"self",
".",
"_allow_any",
"(",
"ctx",
",",
"ops",
")",
"squasher",
"=",
"_CaveatSquasher",
"(",
")",
"for",
"i",
",",
"is_used",
"in",
"enumerate",
"(",
"used",
")",
":",
"if",
"not",
"is_used",
":",
"continue",
"for",
"cond",
"in",
"self",
".",
"_conditions",
"[",
"i",
"]",
":",
"squasher",
".",
"add",
"(",
"cond",
")",
"return",
"squasher",
".",
"final",
"(",
")"
] | Checks that the user is allowed to perform all the
given operations. If not, a discharge error will be raised.
If allow_capability succeeds, it returns a list of first party caveat
conditions that must be applied to any macaroon granting capability
to execute the operations. Those caveat conditions will not
include any declarations contained in login macaroons - the
caller must be careful not to mint a macaroon associated
with the LOGIN_OP operation unless they add the expected
declaration caveat too - in general, clients should not create
capabilities that grant LOGIN_OP rights.
The operations must include at least one non-LOGIN_OP operation. | [
"Checks",
"that",
"the",
"user",
"is",
"allowed",
"to",
"perform",
"all",
"the",
"given",
"operations",
".",
"If",
"not",
"a",
"discharge",
"error",
"will",
"be",
"raised",
".",
"If",
"allow_capability",
"succeeds",
"it",
"returns",
"a",
"list",
"of",
"first",
"party",
"caveat",
"conditions",
"that",
"must",
"be",
"applied",
"to",
"any",
"macaroon",
"granting",
"capability",
"to",
"execute",
"the",
"operations",
".",
"Those",
"caveat",
"conditions",
"will",
"not",
"include",
"any",
"declarations",
"contained",
"in",
"login",
"macaroons",
"-",
"the",
"caller",
"must",
"be",
"careful",
"not",
"to",
"mint",
"a",
"macaroon",
"associated",
"with",
"the",
"LOGIN_OP",
"operation",
"unless",
"they",
"add",
"the",
"expected",
"declaration",
"caveat",
"too",
"-",
"in",
"general",
"clients",
"should",
"not",
"create",
"capabilities",
"that",
"grant",
"LOGIN_OP",
"rights",
"."
] | 63ce1ef1dabe816eb8aaec48fbb46761c34ddf77 | https://github.com/go-macaroon-bakery/py-macaroon-bakery/blob/63ce1ef1dabe816eb8aaec48fbb46761c34ddf77/macaroonbakery/bakery/_checker.py#L317-L345 | train |
useblocks/groundwork | groundwork/patterns/gw_recipes_pattern.py | RecipesListPlugin.register | def register(self, name, path, description, final_words=None):
"""
Registers a new recipe in the context of the current plugin.
:param name: Name of the recipe
:param path: Absolute path of the recipe folder
:param description: A meaningful description of the recipe
:param final_words: A string, which gets printed after the recipe was build.
"""
return self.__app.recipes.register(name, path, self._plugin, description, final_words) | python | def register(self, name, path, description, final_words=None):
"""
Registers a new recipe in the context of the current plugin.
:param name: Name of the recipe
:param path: Absolute path of the recipe folder
:param description: A meaningful description of the recipe
:param final_words: A string, which gets printed after the recipe was build.
"""
return self.__app.recipes.register(name, path, self._plugin, description, final_words) | [
"def",
"register",
"(",
"self",
",",
"name",
",",
"path",
",",
"description",
",",
"final_words",
"=",
"None",
")",
":",
"return",
"self",
".",
"__app",
".",
"recipes",
".",
"register",
"(",
"name",
",",
"path",
",",
"self",
".",
"_plugin",
",",
"description",
",",
"final_words",
")"
] | Registers a new recipe in the context of the current plugin.
:param name: Name of the recipe
:param path: Absolute path of the recipe folder
:param description: A meaningful description of the recipe
:param final_words: A string, which gets printed after the recipe was build. | [
"Registers",
"a",
"new",
"recipe",
"in",
"the",
"context",
"of",
"the",
"current",
"plugin",
"."
] | d34fce43f54246ca4db0f7b89e450dcdc847c68c | https://github.com/useblocks/groundwork/blob/d34fce43f54246ca4db0f7b89e450dcdc847c68c/groundwork/patterns/gw_recipes_pattern.py#L63-L72 | train |
useblocks/groundwork | groundwork/patterns/gw_recipes_pattern.py | RecipesListPlugin.get | def get(self, name=None):
"""
Gets a list of all recipes, which are registered by the current plugin.
If a name is provided, only the requested recipe is returned or None.
:param: name: Name of the recipe
"""
return self.__app.recipes.get(name, self._plugin) | python | def get(self, name=None):
"""
Gets a list of all recipes, which are registered by the current plugin.
If a name is provided, only the requested recipe is returned or None.
:param: name: Name of the recipe
"""
return self.__app.recipes.get(name, self._plugin) | [
"def",
"get",
"(",
"self",
",",
"name",
"=",
"None",
")",
":",
"return",
"self",
".",
"__app",
".",
"recipes",
".",
"get",
"(",
"name",
",",
"self",
".",
"_plugin",
")"
] | Gets a list of all recipes, which are registered by the current plugin.
If a name is provided, only the requested recipe is returned or None.
:param: name: Name of the recipe | [
"Gets",
"a",
"list",
"of",
"all",
"recipes",
"which",
"are",
"registered",
"by",
"the",
"current",
"plugin",
".",
"If",
"a",
"name",
"is",
"provided",
"only",
"the",
"requested",
"recipe",
"is",
"returned",
"or",
"None",
"."
] | d34fce43f54246ca4db0f7b89e450dcdc847c68c | https://github.com/useblocks/groundwork/blob/d34fce43f54246ca4db0f7b89e450dcdc847c68c/groundwork/patterns/gw_recipes_pattern.py#L82-L89 | train |
useblocks/groundwork | groundwork/patterns/gw_recipes_pattern.py | RecipesListPlugin.build | def build(self, recipe):
"""
Builds a recipe
:param recipe: Name of the recipe to build.
"""
return self.__app.recipes.build(recipe, self._plugin) | python | def build(self, recipe):
"""
Builds a recipe
:param recipe: Name of the recipe to build.
"""
return self.__app.recipes.build(recipe, self._plugin) | [
"def",
"build",
"(",
"self",
",",
"recipe",
")",
":",
"return",
"self",
".",
"__app",
".",
"recipes",
".",
"build",
"(",
"recipe",
",",
"self",
".",
"_plugin",
")"
] | Builds a recipe
:param recipe: Name of the recipe to build. | [
"Builds",
"a",
"recipe"
] | d34fce43f54246ca4db0f7b89e450dcdc847c68c | https://github.com/useblocks/groundwork/blob/d34fce43f54246ca4db0f7b89e450dcdc847c68c/groundwork/patterns/gw_recipes_pattern.py#L91-L97 | train |
useblocks/groundwork | groundwork/patterns/gw_recipes_pattern.py | RecipesListApplication.register | def register(self, name, path, plugin, description=None, final_words=None):
"""
Registers a new recipe.
"""
if name in self.recipes.keys():
raise RecipeExistsException("Recipe %s was already registered by %s" %
(name, self.recipes["name"].plugin.name))
self.recipes[name] = Recipe(name, path, plugin, description, final_words)
self.__log.debug("Recipe %s registered by %s" % (name, plugin.name))
return self.recipes[name] | python | def register(self, name, path, plugin, description=None, final_words=None):
"""
Registers a new recipe.
"""
if name in self.recipes.keys():
raise RecipeExistsException("Recipe %s was already registered by %s" %
(name, self.recipes["name"].plugin.name))
self.recipes[name] = Recipe(name, path, plugin, description, final_words)
self.__log.debug("Recipe %s registered by %s" % (name, plugin.name))
return self.recipes[name] | [
"def",
"register",
"(",
"self",
",",
"name",
",",
"path",
",",
"plugin",
",",
"description",
"=",
"None",
",",
"final_words",
"=",
"None",
")",
":",
"if",
"name",
"in",
"self",
".",
"recipes",
".",
"keys",
"(",
")",
":",
"raise",
"RecipeExistsException",
"(",
"\"Recipe %s was already registered by %s\"",
"%",
"(",
"name",
",",
"self",
".",
"recipes",
"[",
"\"name\"",
"]",
".",
"plugin",
".",
"name",
")",
")",
"self",
".",
"recipes",
"[",
"name",
"]",
"=",
"Recipe",
"(",
"name",
",",
"path",
",",
"plugin",
",",
"description",
",",
"final_words",
")",
"self",
".",
"__log",
".",
"debug",
"(",
"\"Recipe %s registered by %s\"",
"%",
"(",
"name",
",",
"plugin",
".",
"name",
")",
")",
"return",
"self",
".",
"recipes",
"[",
"name",
"]"
] | Registers a new recipe. | [
"Registers",
"a",
"new",
"recipe",
"."
] | d34fce43f54246ca4db0f7b89e450dcdc847c68c | https://github.com/useblocks/groundwork/blob/d34fce43f54246ca4db0f7b89e450dcdc847c68c/groundwork/patterns/gw_recipes_pattern.py#L113-L123 | train |
useblocks/groundwork | groundwork/patterns/gw_recipes_pattern.py | RecipesListApplication.unregister | def unregister(self, recipe):
"""
Unregisters an existing recipe, so that this recipe is no longer available.
This function is mainly used during plugin deactivation.
:param recipe: Name of the recipe
"""
if recipe not in self.recipes.keys():
self.__log.warning("Can not unregister recipe %s" % recipe)
else:
del (self.recipes[recipe])
self.__log.debug("Recipe %s got unregistered" % recipe) | python | def unregister(self, recipe):
"""
Unregisters an existing recipe, so that this recipe is no longer available.
This function is mainly used during plugin deactivation.
:param recipe: Name of the recipe
"""
if recipe not in self.recipes.keys():
self.__log.warning("Can not unregister recipe %s" % recipe)
else:
del (self.recipes[recipe])
self.__log.debug("Recipe %s got unregistered" % recipe) | [
"def",
"unregister",
"(",
"self",
",",
"recipe",
")",
":",
"if",
"recipe",
"not",
"in",
"self",
".",
"recipes",
".",
"keys",
"(",
")",
":",
"self",
".",
"__log",
".",
"warning",
"(",
"\"Can not unregister recipe %s\"",
"%",
"recipe",
")",
"else",
":",
"del",
"(",
"self",
".",
"recipes",
"[",
"recipe",
"]",
")",
"self",
".",
"__log",
".",
"debug",
"(",
"\"Recipe %s got unregistered\"",
"%",
"recipe",
")"
] | Unregisters an existing recipe, so that this recipe is no longer available.
This function is mainly used during plugin deactivation.
:param recipe: Name of the recipe | [
"Unregisters",
"an",
"existing",
"recipe",
"so",
"that",
"this",
"recipe",
"is",
"no",
"longer",
"available",
"."
] | d34fce43f54246ca4db0f7b89e450dcdc847c68c | https://github.com/useblocks/groundwork/blob/d34fce43f54246ca4db0f7b89e450dcdc847c68c/groundwork/patterns/gw_recipes_pattern.py#L125-L137 | train |
useblocks/groundwork | groundwork/patterns/gw_recipes_pattern.py | RecipesListApplication.get | def get(self, recipe=None, plugin=None):
"""
Get one or more recipes.
:param recipe: Name of the recipe
:type recipe: str
:param plugin: Plugin object, under which the recipe was registered
:type plugin: GwBasePattern
"""
if plugin is not None:
if recipe is None:
recipes_list = {}
for key in self.recipes.keys():
if self.recipes[key].plugin == plugin:
recipes_list[key] = self.recipes[key]
return recipes_list
else:
if recipe in self.recipes.keys():
if self.recipes[recipe].plugin == plugin:
return self.recipes[recipe]
else:
return None
else:
return None
else:
if recipe is None:
return self.recipes
else:
if recipe in self.recipes.keys():
return self.recipes[recipe]
else:
return None | python | def get(self, recipe=None, plugin=None):
"""
Get one or more recipes.
:param recipe: Name of the recipe
:type recipe: str
:param plugin: Plugin object, under which the recipe was registered
:type plugin: GwBasePattern
"""
if plugin is not None:
if recipe is None:
recipes_list = {}
for key in self.recipes.keys():
if self.recipes[key].plugin == plugin:
recipes_list[key] = self.recipes[key]
return recipes_list
else:
if recipe in self.recipes.keys():
if self.recipes[recipe].plugin == plugin:
return self.recipes[recipe]
else:
return None
else:
return None
else:
if recipe is None:
return self.recipes
else:
if recipe in self.recipes.keys():
return self.recipes[recipe]
else:
return None | [
"def",
"get",
"(",
"self",
",",
"recipe",
"=",
"None",
",",
"plugin",
"=",
"None",
")",
":",
"if",
"plugin",
"is",
"not",
"None",
":",
"if",
"recipe",
"is",
"None",
":",
"recipes_list",
"=",
"{",
"}",
"for",
"key",
"in",
"self",
".",
"recipes",
".",
"keys",
"(",
")",
":",
"if",
"self",
".",
"recipes",
"[",
"key",
"]",
".",
"plugin",
"==",
"plugin",
":",
"recipes_list",
"[",
"key",
"]",
"=",
"self",
".",
"recipes",
"[",
"key",
"]",
"return",
"recipes_list",
"else",
":",
"if",
"recipe",
"in",
"self",
".",
"recipes",
".",
"keys",
"(",
")",
":",
"if",
"self",
".",
"recipes",
"[",
"recipe",
"]",
".",
"plugin",
"==",
"plugin",
":",
"return",
"self",
".",
"recipes",
"[",
"recipe",
"]",
"else",
":",
"return",
"None",
"else",
":",
"return",
"None",
"else",
":",
"if",
"recipe",
"is",
"None",
":",
"return",
"self",
".",
"recipes",
"else",
":",
"if",
"recipe",
"in",
"self",
".",
"recipes",
".",
"keys",
"(",
")",
":",
"return",
"self",
".",
"recipes",
"[",
"recipe",
"]",
"else",
":",
"return",
"None"
] | Get one or more recipes.
:param recipe: Name of the recipe
:type recipe: str
:param plugin: Plugin object, under which the recipe was registered
:type plugin: GwBasePattern | [
"Get",
"one",
"or",
"more",
"recipes",
"."
] | d34fce43f54246ca4db0f7b89e450dcdc847c68c | https://github.com/useblocks/groundwork/blob/d34fce43f54246ca4db0f7b89e450dcdc847c68c/groundwork/patterns/gw_recipes_pattern.py#L139-L170 | train |
useblocks/groundwork | groundwork/patterns/gw_recipes_pattern.py | RecipesListApplication.build | def build(self, recipe, plugin=None):
"""
Execute a recipe and creates new folder and files.
:param recipe: Name of the recipe
:param plugin: Name of the plugin, to which the recipe must belong.
"""
if recipe not in self.recipes.keys():
raise RecipeMissingException("Recipe %s unknown." % recipe)
recipe_obj = self.recipes[recipe]
if plugin is not None:
if recipe_obj.plugin != plugin:
raise RecipeWrongPluginException("The requested recipe does not belong to the given plugin. Use"
"the app object, to retrieve the requested recipe: "
"my_app.recipes.get(%s)" % recipe)
recipe_obj.build() | python | def build(self, recipe, plugin=None):
"""
Execute a recipe and creates new folder and files.
:param recipe: Name of the recipe
:param plugin: Name of the plugin, to which the recipe must belong.
"""
if recipe not in self.recipes.keys():
raise RecipeMissingException("Recipe %s unknown." % recipe)
recipe_obj = self.recipes[recipe]
if plugin is not None:
if recipe_obj.plugin != plugin:
raise RecipeWrongPluginException("The requested recipe does not belong to the given plugin. Use"
"the app object, to retrieve the requested recipe: "
"my_app.recipes.get(%s)" % recipe)
recipe_obj.build() | [
"def",
"build",
"(",
"self",
",",
"recipe",
",",
"plugin",
"=",
"None",
")",
":",
"if",
"recipe",
"not",
"in",
"self",
".",
"recipes",
".",
"keys",
"(",
")",
":",
"raise",
"RecipeMissingException",
"(",
"\"Recipe %s unknown.\"",
"%",
"recipe",
")",
"recipe_obj",
"=",
"self",
".",
"recipes",
"[",
"recipe",
"]",
"if",
"plugin",
"is",
"not",
"None",
":",
"if",
"recipe_obj",
".",
"plugin",
"!=",
"plugin",
":",
"raise",
"RecipeWrongPluginException",
"(",
"\"The requested recipe does not belong to the given plugin. Use\"",
"\"the app object, to retrieve the requested recipe: \"",
"\"my_app.recipes.get(%s)\"",
"%",
"recipe",
")",
"recipe_obj",
".",
"build",
"(",
")"
] | Execute a recipe and creates new folder and files.
:param recipe: Name of the recipe
:param plugin: Name of the plugin, to which the recipe must belong. | [
"Execute",
"a",
"recipe",
"and",
"creates",
"new",
"folder",
"and",
"files",
"."
] | d34fce43f54246ca4db0f7b89e450dcdc847c68c | https://github.com/useblocks/groundwork/blob/d34fce43f54246ca4db0f7b89e450dcdc847c68c/groundwork/patterns/gw_recipes_pattern.py#L172-L190 | train |
useblocks/groundwork | groundwork/patterns/gw_recipes_pattern.py | Recipe.build | def build(self, output_dir=None, **kwargs):
"""
Buildes the recipe and creates needed folder and files.
May ask the user for some parameter inputs.
:param output_dir: Path, where the recipe shall be build. Default is the current working directory
:return: location of the installed recipe
"""
if output_dir is None:
output_dir = os.getcwd()
target = cookiecutter(self.path, output_dir=output_dir, **kwargs)
if self.final_words is not None and len(self.final_words) > 0:
print("")
print(self.final_words)
return target | python | def build(self, output_dir=None, **kwargs):
"""
Buildes the recipe and creates needed folder and files.
May ask the user for some parameter inputs.
:param output_dir: Path, where the recipe shall be build. Default is the current working directory
:return: location of the installed recipe
"""
if output_dir is None:
output_dir = os.getcwd()
target = cookiecutter(self.path, output_dir=output_dir, **kwargs)
if self.final_words is not None and len(self.final_words) > 0:
print("")
print(self.final_words)
return target | [
"def",
"build",
"(",
"self",
",",
"output_dir",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"output_dir",
"is",
"None",
":",
"output_dir",
"=",
"os",
".",
"getcwd",
"(",
")",
"target",
"=",
"cookiecutter",
"(",
"self",
".",
"path",
",",
"output_dir",
"=",
"output_dir",
",",
"*",
"*",
"kwargs",
")",
"if",
"self",
".",
"final_words",
"is",
"not",
"None",
"and",
"len",
"(",
"self",
".",
"final_words",
")",
">",
"0",
":",
"print",
"(",
"\"\"",
")",
"print",
"(",
"self",
".",
"final_words",
")",
"return",
"target"
] | Buildes the recipe and creates needed folder and files.
May ask the user for some parameter inputs.
:param output_dir: Path, where the recipe shall be build. Default is the current working directory
:return: location of the installed recipe | [
"Buildes",
"the",
"recipe",
"and",
"creates",
"needed",
"folder",
"and",
"files",
".",
"May",
"ask",
"the",
"user",
"for",
"some",
"parameter",
"inputs",
"."
] | d34fce43f54246ca4db0f7b89e450dcdc847c68c | https://github.com/useblocks/groundwork/blob/d34fce43f54246ca4db0f7b89e450dcdc847c68c/groundwork/patterns/gw_recipes_pattern.py#L213-L229 | train |
acutesoftware/AIKIF | aikif/lib/cls_context.py | where_am_i | def where_am_i():
"""
high level function that can estimate where user is based
on predefined setups.
"""
locations = {'Work':0, 'Home':0}
for ssid in scan_for_ssids():
#print('checking scanned_ssid ', ssid)
for l in logged_ssids:
#print('checking logged_ssid ', l)
if l['name'] == ssid:
locations[l['location']] += 1
#print('MATCH')
print('Where Am I: SSIDS Matching Home = ', locations['Home'], ' SSIDs matching Work = ', locations['Work'])
return max(locations.keys(), key=lambda k: locations[k]) | python | def where_am_i():
"""
high level function that can estimate where user is based
on predefined setups.
"""
locations = {'Work':0, 'Home':0}
for ssid in scan_for_ssids():
#print('checking scanned_ssid ', ssid)
for l in logged_ssids:
#print('checking logged_ssid ', l)
if l['name'] == ssid:
locations[l['location']] += 1
#print('MATCH')
print('Where Am I: SSIDS Matching Home = ', locations['Home'], ' SSIDs matching Work = ', locations['Work'])
return max(locations.keys(), key=lambda k: locations[k]) | [
"def",
"where_am_i",
"(",
")",
":",
"locations",
"=",
"{",
"'Work'",
":",
"0",
",",
"'Home'",
":",
"0",
"}",
"for",
"ssid",
"in",
"scan_for_ssids",
"(",
")",
":",
"#print('checking scanned_ssid ', ssid)",
"for",
"l",
"in",
"logged_ssids",
":",
"#print('checking logged_ssid ', l)",
"if",
"l",
"[",
"'name'",
"]",
"==",
"ssid",
":",
"locations",
"[",
"l",
"[",
"'location'",
"]",
"]",
"+=",
"1",
"#print('MATCH')",
"print",
"(",
"'Where Am I: SSIDS Matching Home = '",
",",
"locations",
"[",
"'Home'",
"]",
",",
"' SSIDs matching Work = '",
",",
"locations",
"[",
"'Work'",
"]",
")",
"return",
"max",
"(",
"locations",
".",
"keys",
"(",
")",
",",
"key",
"=",
"lambda",
"k",
":",
"locations",
"[",
"k",
"]",
")"
] | high level function that can estimate where user is based
on predefined setups. | [
"high",
"level",
"function",
"that",
"can",
"estimate",
"where",
"user",
"is",
"based",
"on",
"predefined",
"setups",
"."
] | fcf1582dc5f884b9a4fa7c6e20e9de9d94d21d03 | https://github.com/acutesoftware/AIKIF/blob/fcf1582dc5f884b9a4fa7c6e20e9de9d94d21d03/aikif/lib/cls_context.py#L54-L69 | train |
acutesoftware/AIKIF | aikif/lib/cls_context.py | Context.summarise | def summarise(self):
"""
extrapolate a human readable summary of the contexts
"""
res = ''
if self.user == 'Developer':
if self.host == 'Home PC':
res += 'At Home'
else:
res += 'Away from PC'
elif self.user == 'User' and self.host == 'Home PC':
res += 'Remote desktop into home PC'
res += '\n'
res += self.transport
return res | python | def summarise(self):
"""
extrapolate a human readable summary of the contexts
"""
res = ''
if self.user == 'Developer':
if self.host == 'Home PC':
res += 'At Home'
else:
res += 'Away from PC'
elif self.user == 'User' and self.host == 'Home PC':
res += 'Remote desktop into home PC'
res += '\n'
res += self.transport
return res | [
"def",
"summarise",
"(",
"self",
")",
":",
"res",
"=",
"''",
"if",
"self",
".",
"user",
"==",
"'Developer'",
":",
"if",
"self",
".",
"host",
"==",
"'Home PC'",
":",
"res",
"+=",
"'At Home'",
"else",
":",
"res",
"+=",
"'Away from PC'",
"elif",
"self",
".",
"user",
"==",
"'User'",
"and",
"self",
".",
"host",
"==",
"'Home PC'",
":",
"res",
"+=",
"'Remote desktop into home PC'",
"res",
"+=",
"'\\n'",
"res",
"+=",
"self",
".",
"transport",
"return",
"res"
] | extrapolate a human readable summary of the contexts | [
"extrapolate",
"a",
"human",
"readable",
"summary",
"of",
"the",
"contexts"
] | fcf1582dc5f884b9a4fa7c6e20e9de9d94d21d03 | https://github.com/acutesoftware/AIKIF/blob/fcf1582dc5f884b9a4fa7c6e20e9de9d94d21d03/aikif/lib/cls_context.py#L127-L141 | train |
acutesoftware/AIKIF | aikif/lib/cls_context.py | Context.get_host | def get_host(self):
"""
returns the host computer running this program
"""
import socket
host_name = socket.gethostname()
for h in hosts:
if h['name'] == host_name:
return h['type'], h['name']
return dict(type='Unknown', name=host_name) | python | def get_host(self):
"""
returns the host computer running this program
"""
import socket
host_name = socket.gethostname()
for h in hosts:
if h['name'] == host_name:
return h['type'], h['name']
return dict(type='Unknown', name=host_name) | [
"def",
"get_host",
"(",
"self",
")",
":",
"import",
"socket",
"host_name",
"=",
"socket",
".",
"gethostname",
"(",
")",
"for",
"h",
"in",
"hosts",
":",
"if",
"h",
"[",
"'name'",
"]",
"==",
"host_name",
":",
"return",
"h",
"[",
"'type'",
"]",
",",
"h",
"[",
"'name'",
"]",
"return",
"dict",
"(",
"type",
"=",
"'Unknown'",
",",
"name",
"=",
"host_name",
")"
] | returns the host computer running this program | [
"returns",
"the",
"host",
"computer",
"running",
"this",
"program"
] | fcf1582dc5f884b9a4fa7c6e20e9de9d94d21d03 | https://github.com/acutesoftware/AIKIF/blob/fcf1582dc5f884b9a4fa7c6e20e9de9d94d21d03/aikif/lib/cls_context.py#L162-L171 | train |
acutesoftware/AIKIF | aikif/lib/cls_context.py | Context.get_user | def get_user(self):
"""
returns the username on this computer
"""
for name in ('LOGNAME', 'USER', 'LNAME', 'USERNAME'):
user = os.environ.get(name)
if user:
break
for u in users:
if u['name'] == user:
return u['type'], u['name'] | python | def get_user(self):
"""
returns the username on this computer
"""
for name in ('LOGNAME', 'USER', 'LNAME', 'USERNAME'):
user = os.environ.get(name)
if user:
break
for u in users:
if u['name'] == user:
return u['type'], u['name'] | [
"def",
"get_user",
"(",
"self",
")",
":",
"for",
"name",
"in",
"(",
"'LOGNAME'",
",",
"'USER'",
",",
"'LNAME'",
",",
"'USERNAME'",
")",
":",
"user",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"name",
")",
"if",
"user",
":",
"break",
"for",
"u",
"in",
"users",
":",
"if",
"u",
"[",
"'name'",
"]",
"==",
"user",
":",
"return",
"u",
"[",
"'type'",
"]",
",",
"u",
"[",
"'name'",
"]"
] | returns the username on this computer | [
"returns",
"the",
"username",
"on",
"this",
"computer"
] | fcf1582dc5f884b9a4fa7c6e20e9de9d94d21d03 | https://github.com/acutesoftware/AIKIF/blob/fcf1582dc5f884b9a4fa7c6e20e9de9d94d21d03/aikif/lib/cls_context.py#L173-L183 | train |
acutesoftware/AIKIF | aikif/lib/cls_context.py | Context.get_host_usage | def get_host_usage(self):
"""
get details of CPU, RAM usage of this PC
"""
import psutil
process_names = [proc.name for proc in psutil.process_iter()]
cpu_pct = psutil.cpu_percent(interval=1)
mem = psutil.virtual_memory()
return str(cpu_pct), str(len(process_names)), str(mem.available), str(mem.total) | python | def get_host_usage(self):
"""
get details of CPU, RAM usage of this PC
"""
import psutil
process_names = [proc.name for proc in psutil.process_iter()]
cpu_pct = psutil.cpu_percent(interval=1)
mem = psutil.virtual_memory()
return str(cpu_pct), str(len(process_names)), str(mem.available), str(mem.total) | [
"def",
"get_host_usage",
"(",
"self",
")",
":",
"import",
"psutil",
"process_names",
"=",
"[",
"proc",
".",
"name",
"for",
"proc",
"in",
"psutil",
".",
"process_iter",
"(",
")",
"]",
"cpu_pct",
"=",
"psutil",
".",
"cpu_percent",
"(",
"interval",
"=",
"1",
")",
"mem",
"=",
"psutil",
".",
"virtual_memory",
"(",
")",
"return",
"str",
"(",
"cpu_pct",
")",
",",
"str",
"(",
"len",
"(",
"process_names",
")",
")",
",",
"str",
"(",
"mem",
".",
"available",
")",
",",
"str",
"(",
"mem",
".",
"total",
")"
] | get details of CPU, RAM usage of this PC | [
"get",
"details",
"of",
"CPU",
"RAM",
"usage",
"of",
"this",
"PC"
] | fcf1582dc5f884b9a4fa7c6e20e9de9d94d21d03 | https://github.com/acutesoftware/AIKIF/blob/fcf1582dc5f884b9a4fa7c6e20e9de9d94d21d03/aikif/lib/cls_context.py#L229-L237 | train |
Nachtfeuer/pipeline | spline/components/config.py | ShellConfig.schema | def schema():
"""Provide schema for shell configuration."""
return Schema({
'script': And(Or(type(' '), type(u' ')), len),
Optional('title', default=''): str,
Optional('model', default={}): {Optional(And(str, len)): object},
Optional('env', default={}): {Optional(And(str, len)): And(str, len)},
Optional('item', default=None): object,
Optional('dry_run', default=False): bool,
Optional('debug', default=False): bool,
Optional('strict', default=False): bool,
Optional('variables', default={}): {
Optional(And(Or(type(' '), type(u' ')), len, Regex(r'([a-zA-Z][_a-zA-Z]*)'))):
Or(type(' '), type(u' '))
},
Optional('temporary_scripts_path', default=''): Or(type(''), type(u'')),
Optional('internal', default=False): bool
}) | python | def schema():
"""Provide schema for shell configuration."""
return Schema({
'script': And(Or(type(' '), type(u' ')), len),
Optional('title', default=''): str,
Optional('model', default={}): {Optional(And(str, len)): object},
Optional('env', default={}): {Optional(And(str, len)): And(str, len)},
Optional('item', default=None): object,
Optional('dry_run', default=False): bool,
Optional('debug', default=False): bool,
Optional('strict', default=False): bool,
Optional('variables', default={}): {
Optional(And(Or(type(' '), type(u' ')), len, Regex(r'([a-zA-Z][_a-zA-Z]*)'))):
Or(type(' '), type(u' '))
},
Optional('temporary_scripts_path', default=''): Or(type(''), type(u'')),
Optional('internal', default=False): bool
}) | [
"def",
"schema",
"(",
")",
":",
"return",
"Schema",
"(",
"{",
"'script'",
":",
"And",
"(",
"Or",
"(",
"type",
"(",
"' '",
")",
",",
"type",
"(",
"u' '",
")",
")",
",",
"len",
")",
",",
"Optional",
"(",
"'title'",
",",
"default",
"=",
"''",
")",
":",
"str",
",",
"Optional",
"(",
"'model'",
",",
"default",
"=",
"{",
"}",
")",
":",
"{",
"Optional",
"(",
"And",
"(",
"str",
",",
"len",
")",
")",
":",
"object",
"}",
",",
"Optional",
"(",
"'env'",
",",
"default",
"=",
"{",
"}",
")",
":",
"{",
"Optional",
"(",
"And",
"(",
"str",
",",
"len",
")",
")",
":",
"And",
"(",
"str",
",",
"len",
")",
"}",
",",
"Optional",
"(",
"'item'",
",",
"default",
"=",
"None",
")",
":",
"object",
",",
"Optional",
"(",
"'dry_run'",
",",
"default",
"=",
"False",
")",
":",
"bool",
",",
"Optional",
"(",
"'debug'",
",",
"default",
"=",
"False",
")",
":",
"bool",
",",
"Optional",
"(",
"'strict'",
",",
"default",
"=",
"False",
")",
":",
"bool",
",",
"Optional",
"(",
"'variables'",
",",
"default",
"=",
"{",
"}",
")",
":",
"{",
"Optional",
"(",
"And",
"(",
"Or",
"(",
"type",
"(",
"' '",
")",
",",
"type",
"(",
"u' '",
")",
")",
",",
"len",
",",
"Regex",
"(",
"r'([a-zA-Z][_a-zA-Z]*)'",
")",
")",
")",
":",
"Or",
"(",
"type",
"(",
"' '",
")",
",",
"type",
"(",
"u' '",
")",
")",
"}",
",",
"Optional",
"(",
"'temporary_scripts_path'",
",",
"default",
"=",
"''",
")",
":",
"Or",
"(",
"type",
"(",
"''",
")",
",",
"type",
"(",
"u''",
")",
")",
",",
"Optional",
"(",
"'internal'",
",",
"default",
"=",
"False",
")",
":",
"bool",
"}",
")"
] | Provide schema for shell configuration. | [
"Provide",
"schema",
"for",
"shell",
"configuration",
"."
] | 04ca18c4e95e4349532bb45b768206393e1f2c13 | https://github.com/Nachtfeuer/pipeline/blob/04ca18c4e95e4349532bb45b768206393e1f2c13/spline/components/config.py#L29-L46 | train |
acutesoftware/AIKIF | aikif/project.py | Projects.get_by_name | def get_by_name(self, name):
""" returns an object Project which matches name """
for p in self.project_list:
if p.nme == name:
return p
return None | python | def get_by_name(self, name):
""" returns an object Project which matches name """
for p in self.project_list:
if p.nme == name:
return p
return None | [
"def",
"get_by_name",
"(",
"self",
",",
"name",
")",
":",
"for",
"p",
"in",
"self",
".",
"project_list",
":",
"if",
"p",
".",
"nme",
"==",
"name",
":",
"return",
"p",
"return",
"None"
] | returns an object Project which matches name | [
"returns",
"an",
"object",
"Project",
"which",
"matches",
"name"
] | fcf1582dc5f884b9a4fa7c6e20e9de9d94d21d03 | https://github.com/acutesoftware/AIKIF/blob/fcf1582dc5f884b9a4fa7c6e20e9de9d94d21d03/aikif/project.py#L35-L40 | train |
acutesoftware/AIKIF | aikif/project.py | Project.execute_tasks | def execute_tasks(self):
"""
run execute on all tasks IFF prior task is successful
"""
for t in self.tasks:
print('RUNNING ' + str(t.task_id) + ' = ' + t.name)
t.execute()
if t.success != '__IGNORE__RESULT__':
print(t)
print('TASK RESULT :', t.result, ' but success = ' , t.success )
if t.result != t.success:
#raise Exception('Project execution failed at task ' + str(t.task_id) + ' = ' + t.name)
print('ABORTING TASK EXECUTION SEQUENCE' + str(t.task_id) + ' = ' + t.name)
break | python | def execute_tasks(self):
"""
run execute on all tasks IFF prior task is successful
"""
for t in self.tasks:
print('RUNNING ' + str(t.task_id) + ' = ' + t.name)
t.execute()
if t.success != '__IGNORE__RESULT__':
print(t)
print('TASK RESULT :', t.result, ' but success = ' , t.success )
if t.result != t.success:
#raise Exception('Project execution failed at task ' + str(t.task_id) + ' = ' + t.name)
print('ABORTING TASK EXECUTION SEQUENCE' + str(t.task_id) + ' = ' + t.name)
break | [
"def",
"execute_tasks",
"(",
"self",
")",
":",
"for",
"t",
"in",
"self",
".",
"tasks",
":",
"print",
"(",
"'RUNNING '",
"+",
"str",
"(",
"t",
".",
"task_id",
")",
"+",
"' = '",
"+",
"t",
".",
"name",
")",
"t",
".",
"execute",
"(",
")",
"if",
"t",
".",
"success",
"!=",
"'__IGNORE__RESULT__'",
":",
"print",
"(",
"t",
")",
"print",
"(",
"'TASK RESULT :'",
",",
"t",
".",
"result",
",",
"' but success = '",
",",
"t",
".",
"success",
")",
"if",
"t",
".",
"result",
"!=",
"t",
".",
"success",
":",
"#raise Exception('Project execution failed at task ' + str(t.task_id) + ' = ' + t.name)",
"print",
"(",
"'ABORTING TASK EXECUTION SEQUENCE'",
"+",
"str",
"(",
"t",
".",
"task_id",
")",
"+",
"' = '",
"+",
"t",
".",
"name",
")",
"break"
] | run execute on all tasks IFF prior task is successful | [
"run",
"execute",
"on",
"all",
"tasks",
"IFF",
"prior",
"task",
"is",
"successful"
] | fcf1582dc5f884b9a4fa7c6e20e9de9d94d21d03 | https://github.com/acutesoftware/AIKIF/blob/fcf1582dc5f884b9a4fa7c6e20e9de9d94d21d03/aikif/project.py#L132-L145 | train |
acutesoftware/AIKIF | aikif/project.py | Project.build_report | def build_report(self, op_file, tpe='md'):
"""
create a report showing all project details
"""
if tpe == 'md':
res = self.get_report_md()
elif tpe == 'rst':
res = self.get_report_rst()
elif tpe == 'html':
res = self.get_report_html()
else:
res = 'Unknown report type passed to project.build_report'
with open(op_file, 'w') as f:
f.write(res) | python | def build_report(self, op_file, tpe='md'):
"""
create a report showing all project details
"""
if tpe == 'md':
res = self.get_report_md()
elif tpe == 'rst':
res = self.get_report_rst()
elif tpe == 'html':
res = self.get_report_html()
else:
res = 'Unknown report type passed to project.build_report'
with open(op_file, 'w') as f:
f.write(res) | [
"def",
"build_report",
"(",
"self",
",",
"op_file",
",",
"tpe",
"=",
"'md'",
")",
":",
"if",
"tpe",
"==",
"'md'",
":",
"res",
"=",
"self",
".",
"get_report_md",
"(",
")",
"elif",
"tpe",
"==",
"'rst'",
":",
"res",
"=",
"self",
".",
"get_report_rst",
"(",
")",
"elif",
"tpe",
"==",
"'html'",
":",
"res",
"=",
"self",
".",
"get_report_html",
"(",
")",
"else",
":",
"res",
"=",
"'Unknown report type passed to project.build_report'",
"with",
"open",
"(",
"op_file",
",",
"'w'",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"res",
")"
] | create a report showing all project details | [
"create",
"a",
"report",
"showing",
"all",
"project",
"details"
] | fcf1582dc5f884b9a4fa7c6e20e9de9d94d21d03 | https://github.com/acutesoftware/AIKIF/blob/fcf1582dc5f884b9a4fa7c6e20e9de9d94d21d03/aikif/project.py#L149-L163 | train |
acutesoftware/AIKIF | aikif/project.py | Project.get_report_rst | def get_report_rst(self):
"""
formats the project into a report in RST format
"""
res = ''
res += '-----------------------------------\n'
res += self.nme + '\n'
res += '-----------------------------------\n\n'
res += self.desc + '\n'
res += self.fldr + '\n\n'
res += '.. contents:: \n\n\n'
res += 'Overview\n' + '===========================================\n\n'
res += 'This document contains details on the project ' + self.nme + '\n\n'
for d in self.details:
res += ' - ' + d[0] + ' = ' + d[1] + '\n\n'
res += '\nTABLES\n' + '===========================================\n\n'
for t in self.datatables:
res += t.name + '\n'
res += '-------------------------\n\n'
res += t.format_rst() + '\n\n'
return res | python | def get_report_rst(self):
"""
formats the project into a report in RST format
"""
res = ''
res += '-----------------------------------\n'
res += self.nme + '\n'
res += '-----------------------------------\n\n'
res += self.desc + '\n'
res += self.fldr + '\n\n'
res += '.. contents:: \n\n\n'
res += 'Overview\n' + '===========================================\n\n'
res += 'This document contains details on the project ' + self.nme + '\n\n'
for d in self.details:
res += ' - ' + d[0] + ' = ' + d[1] + '\n\n'
res += '\nTABLES\n' + '===========================================\n\n'
for t in self.datatables:
res += t.name + '\n'
res += '-------------------------\n\n'
res += t.format_rst() + '\n\n'
return res | [
"def",
"get_report_rst",
"(",
"self",
")",
":",
"res",
"=",
"''",
"res",
"+=",
"'-----------------------------------\\n'",
"res",
"+=",
"self",
".",
"nme",
"+",
"'\\n'",
"res",
"+=",
"'-----------------------------------\\n\\n'",
"res",
"+=",
"self",
".",
"desc",
"+",
"'\\n'",
"res",
"+=",
"self",
".",
"fldr",
"+",
"'\\n\\n'",
"res",
"+=",
"'.. contents:: \\n\\n\\n'",
"res",
"+=",
"'Overview\\n'",
"+",
"'===========================================\\n\\n'",
"res",
"+=",
"'This document contains details on the project '",
"+",
"self",
".",
"nme",
"+",
"'\\n\\n'",
"for",
"d",
"in",
"self",
".",
"details",
":",
"res",
"+=",
"' - '",
"+",
"d",
"[",
"0",
"]",
"+",
"' = '",
"+",
"d",
"[",
"1",
"]",
"+",
"'\\n\\n'",
"res",
"+=",
"'\\nTABLES\\n'",
"+",
"'===========================================\\n\\n'",
"for",
"t",
"in",
"self",
".",
"datatables",
":",
"res",
"+=",
"t",
".",
"name",
"+",
"'\\n'",
"res",
"+=",
"'-------------------------\\n\\n'",
"res",
"+=",
"t",
".",
"format_rst",
"(",
")",
"+",
"'\\n\\n'",
"return",
"res"
] | formats the project into a report in RST format | [
"formats",
"the",
"project",
"into",
"a",
"report",
"in",
"RST",
"format"
] | fcf1582dc5f884b9a4fa7c6e20e9de9d94d21d03 | https://github.com/acutesoftware/AIKIF/blob/fcf1582dc5f884b9a4fa7c6e20e9de9d94d21d03/aikif/project.py#L165-L193 | train |
acutesoftware/AIKIF | aikif/project.py | Project.get_report_html | def get_report_html(self):
"""
formats the project into a report in MD format - WARNING - tables missing BR
"""
res = '<h2>Project:' + self.nme + '</h2>'
res += '<p>' + self.desc + '</p>'
res += '<p>' + self.fldr + '</p>'
res += '<BR><h3>TABLES</h3>'
for t in self.datatables:
res += '<b>' + t.name + '<b><BR>'
res += '<p>' + str(t) + '</p>'
return res | python | def get_report_html(self):
"""
formats the project into a report in MD format - WARNING - tables missing BR
"""
res = '<h2>Project:' + self.nme + '</h2>'
res += '<p>' + self.desc + '</p>'
res += '<p>' + self.fldr + '</p>'
res += '<BR><h3>TABLES</h3>'
for t in self.datatables:
res += '<b>' + t.name + '<b><BR>'
res += '<p>' + str(t) + '</p>'
return res | [
"def",
"get_report_html",
"(",
"self",
")",
":",
"res",
"=",
"'<h2>Project:'",
"+",
"self",
".",
"nme",
"+",
"'</h2>'",
"res",
"+=",
"'<p>'",
"+",
"self",
".",
"desc",
"+",
"'</p>'",
"res",
"+=",
"'<p>'",
"+",
"self",
".",
"fldr",
"+",
"'</p>'",
"res",
"+=",
"'<BR><h3>TABLES</h3>'",
"for",
"t",
"in",
"self",
".",
"datatables",
":",
"res",
"+=",
"'<b>'",
"+",
"t",
".",
"name",
"+",
"'<b><BR>'",
"res",
"+=",
"'<p>'",
"+",
"str",
"(",
"t",
")",
"+",
"'</p>'",
"return",
"res"
] | formats the project into a report in MD format - WARNING - tables missing BR | [
"formats",
"the",
"project",
"into",
"a",
"report",
"in",
"MD",
"format",
"-",
"WARNING",
"-",
"tables",
"missing",
"BR"
] | fcf1582dc5f884b9a4fa7c6e20e9de9d94d21d03 | https://github.com/acutesoftware/AIKIF/blob/fcf1582dc5f884b9a4fa7c6e20e9de9d94d21d03/aikif/project.py#L213-L226 | train |
acutesoftware/AIKIF | aikif/project.py | Task.add_param | def add_param(self, param_key, param_val):
"""
adds parameters as key value pairs
"""
self.params.append([param_key, param_val])
if param_key == '__success_test':
self.success = param_val | python | def add_param(self, param_key, param_val):
"""
adds parameters as key value pairs
"""
self.params.append([param_key, param_val])
if param_key == '__success_test':
self.success = param_val | [
"def",
"add_param",
"(",
"self",
",",
"param_key",
",",
"param_val",
")",
":",
"self",
".",
"params",
".",
"append",
"(",
"[",
"param_key",
",",
"param_val",
"]",
")",
"if",
"param_key",
"==",
"'__success_test'",
":",
"self",
".",
"success",
"=",
"param_val"
] | adds parameters as key value pairs | [
"adds",
"parameters",
"as",
"key",
"value",
"pairs"
] | fcf1582dc5f884b9a4fa7c6e20e9de9d94d21d03 | https://github.com/acutesoftware/AIKIF/blob/fcf1582dc5f884b9a4fa7c6e20e9de9d94d21d03/aikif/project.py#L257-L263 | train |
acutesoftware/AIKIF | aikif/project.py | Task.execute | def execute(self):
"""
executes all automatic tasks in order of task id
"""
func_params = []
exec_str = self.func.__name__ + '('
for p in self.params:
if p[0][0:2] != '__': # ignore custom param names
exec_str += p[0] + '="' + self._force_str(p[1]) + '", '
func_params.append(p[1])
exec_str = exec_str[:-2]
exec_str += ') # task' + str(self.task_id) + ': ' + self.name
self.result = self.func(*func_params)
print(exec_str + ' loaded ', self.result) | python | def execute(self):
"""
executes all automatic tasks in order of task id
"""
func_params = []
exec_str = self.func.__name__ + '('
for p in self.params:
if p[0][0:2] != '__': # ignore custom param names
exec_str += p[0] + '="' + self._force_str(p[1]) + '", '
func_params.append(p[1])
exec_str = exec_str[:-2]
exec_str += ') # task' + str(self.task_id) + ': ' + self.name
self.result = self.func(*func_params)
print(exec_str + ' loaded ', self.result) | [
"def",
"execute",
"(",
"self",
")",
":",
"func_params",
"=",
"[",
"]",
"exec_str",
"=",
"self",
".",
"func",
".",
"__name__",
"+",
"'('",
"for",
"p",
"in",
"self",
".",
"params",
":",
"if",
"p",
"[",
"0",
"]",
"[",
"0",
":",
"2",
"]",
"!=",
"'__'",
":",
"# ignore custom param names",
"exec_str",
"+=",
"p",
"[",
"0",
"]",
"+",
"'=\"'",
"+",
"self",
".",
"_force_str",
"(",
"p",
"[",
"1",
"]",
")",
"+",
"'\", '",
"func_params",
".",
"append",
"(",
"p",
"[",
"1",
"]",
")",
"exec_str",
"=",
"exec_str",
"[",
":",
"-",
"2",
"]",
"exec_str",
"+=",
"') # task'",
"+",
"str",
"(",
"self",
".",
"task_id",
")",
"+",
"': '",
"+",
"self",
".",
"name",
"self",
".",
"result",
"=",
"self",
".",
"func",
"(",
"*",
"func_params",
")",
"print",
"(",
"exec_str",
"+",
"' loaded '",
",",
"self",
".",
"result",
")"
] | executes all automatic tasks in order of task id | [
"executes",
"all",
"automatic",
"tasks",
"in",
"order",
"of",
"task",
"id"
] | fcf1582dc5f884b9a4fa7c6e20e9de9d94d21d03 | https://github.com/acutesoftware/AIKIF/blob/fcf1582dc5f884b9a4fa7c6e20e9de9d94d21d03/aikif/project.py#L265-L280 | train |
cox-labs/perseuspy | perseuspy/io/perseus/matrix.py | create_column_index | def create_column_index(annotations):
"""
Create a pd.MultiIndex using the column names and any categorical rows.
Note that also non-main columns will be assigned a default category ''.
"""
_column_index = OrderedDict({'Column Name' : annotations['Column Name']})
categorical_rows = annotation_rows('C:', annotations)
_column_index.update(categorical_rows)
numerical_rows = {name: [float(x) if x != '' else float('NaN') for x in values]
for name, values in annotation_rows('N:', annotations).items()} # to floats
_column_index.update(numerical_rows)
column_index = pd.MultiIndex.from_tuples(list(zip(*_column_index.values())), names=list(_column_index.keys()))
if len(column_index.names) == 1:
# flatten single-level index
name = column_index.names[0]
column_index = column_index.get_level_values(name)
return column_index | python | def create_column_index(annotations):
"""
Create a pd.MultiIndex using the column names and any categorical rows.
Note that also non-main columns will be assigned a default category ''.
"""
_column_index = OrderedDict({'Column Name' : annotations['Column Name']})
categorical_rows = annotation_rows('C:', annotations)
_column_index.update(categorical_rows)
numerical_rows = {name: [float(x) if x != '' else float('NaN') for x in values]
for name, values in annotation_rows('N:', annotations).items()} # to floats
_column_index.update(numerical_rows)
column_index = pd.MultiIndex.from_tuples(list(zip(*_column_index.values())), names=list(_column_index.keys()))
if len(column_index.names) == 1:
# flatten single-level index
name = column_index.names[0]
column_index = column_index.get_level_values(name)
return column_index | [
"def",
"create_column_index",
"(",
"annotations",
")",
":",
"_column_index",
"=",
"OrderedDict",
"(",
"{",
"'Column Name'",
":",
"annotations",
"[",
"'Column Name'",
"]",
"}",
")",
"categorical_rows",
"=",
"annotation_rows",
"(",
"'C:'",
",",
"annotations",
")",
"_column_index",
".",
"update",
"(",
"categorical_rows",
")",
"numerical_rows",
"=",
"{",
"name",
":",
"[",
"float",
"(",
"x",
")",
"if",
"x",
"!=",
"''",
"else",
"float",
"(",
"'NaN'",
")",
"for",
"x",
"in",
"values",
"]",
"for",
"name",
",",
"values",
"in",
"annotation_rows",
"(",
"'N:'",
",",
"annotations",
")",
".",
"items",
"(",
")",
"}",
"# to floats",
"_column_index",
".",
"update",
"(",
"numerical_rows",
")",
"column_index",
"=",
"pd",
".",
"MultiIndex",
".",
"from_tuples",
"(",
"list",
"(",
"zip",
"(",
"*",
"_column_index",
".",
"values",
"(",
")",
")",
")",
",",
"names",
"=",
"list",
"(",
"_column_index",
".",
"keys",
"(",
")",
")",
")",
"if",
"len",
"(",
"column_index",
".",
"names",
")",
"==",
"1",
":",
"# flatten single-level index",
"name",
"=",
"column_index",
".",
"names",
"[",
"0",
"]",
"column_index",
"=",
"column_index",
".",
"get_level_values",
"(",
"name",
")",
"return",
"column_index"
] | Create a pd.MultiIndex using the column names and any categorical rows.
Note that also non-main columns will be assigned a default category ''. | [
"Create",
"a",
"pd",
".",
"MultiIndex",
"using",
"the",
"column",
"names",
"and",
"any",
"categorical",
"rows",
".",
"Note",
"that",
"also",
"non",
"-",
"main",
"columns",
"will",
"be",
"assigned",
"a",
"default",
"category",
"."
] | 3809c1bd46512605f9e7ca7f97e026e4940ed604 | https://github.com/cox-labs/perseuspy/blob/3809c1bd46512605f9e7ca7f97e026e4940ed604/perseuspy/io/perseus/matrix.py#L61-L77 | train |
cox-labs/perseuspy | perseuspy/io/perseus/matrix.py | read_perseus | def read_perseus(path_or_file, **kwargs):
"""
Read a Perseus-formatted matrix into a pd.DataFrame.
Annotation rows will be converted into a multi-index.
By monkey-patching the returned pd.DataFrame a `to_perseus`
method for exporting the pd.DataFrame is made available.
:param path_or_file: File path or file-like object
:param kwargs: Keyword arguments passed as-is to pandas.read_csv
:returns: The parsed data frame
"""
annotations = read_annotations(path_or_file, separator)
column_index = create_column_index(annotations)
if 'usecols' in kwargs:
usecols = kwargs['usecols']
if type(usecols[0]) is str:
usecols = sorted([list(column_index).index(x) for x in usecols])
column_index = column_index[usecols]
kwargs['dtype'] = dict(kwargs.get('dtype', {}), **annotations.get('dtype', {}))
kwargs['converters'] = dict(kwargs.get('converters', {}), **annotations.get('converters', {}))
df = pd.read_csv(path_or_file, sep=separator, comment='#', **kwargs)
df.columns = column_index
return df | python | def read_perseus(path_or_file, **kwargs):
"""
Read a Perseus-formatted matrix into a pd.DataFrame.
Annotation rows will be converted into a multi-index.
By monkey-patching the returned pd.DataFrame a `to_perseus`
method for exporting the pd.DataFrame is made available.
:param path_or_file: File path or file-like object
:param kwargs: Keyword arguments passed as-is to pandas.read_csv
:returns: The parsed data frame
"""
annotations = read_annotations(path_or_file, separator)
column_index = create_column_index(annotations)
if 'usecols' in kwargs:
usecols = kwargs['usecols']
if type(usecols[0]) is str:
usecols = sorted([list(column_index).index(x) for x in usecols])
column_index = column_index[usecols]
kwargs['dtype'] = dict(kwargs.get('dtype', {}), **annotations.get('dtype', {}))
kwargs['converters'] = dict(kwargs.get('converters', {}), **annotations.get('converters', {}))
df = pd.read_csv(path_or_file, sep=separator, comment='#', **kwargs)
df.columns = column_index
return df | [
"def",
"read_perseus",
"(",
"path_or_file",
",",
"*",
"*",
"kwargs",
")",
":",
"annotations",
"=",
"read_annotations",
"(",
"path_or_file",
",",
"separator",
")",
"column_index",
"=",
"create_column_index",
"(",
"annotations",
")",
"if",
"'usecols'",
"in",
"kwargs",
":",
"usecols",
"=",
"kwargs",
"[",
"'usecols'",
"]",
"if",
"type",
"(",
"usecols",
"[",
"0",
"]",
")",
"is",
"str",
":",
"usecols",
"=",
"sorted",
"(",
"[",
"list",
"(",
"column_index",
")",
".",
"index",
"(",
"x",
")",
"for",
"x",
"in",
"usecols",
"]",
")",
"column_index",
"=",
"column_index",
"[",
"usecols",
"]",
"kwargs",
"[",
"'dtype'",
"]",
"=",
"dict",
"(",
"kwargs",
".",
"get",
"(",
"'dtype'",
",",
"{",
"}",
")",
",",
"*",
"*",
"annotations",
".",
"get",
"(",
"'dtype'",
",",
"{",
"}",
")",
")",
"kwargs",
"[",
"'converters'",
"]",
"=",
"dict",
"(",
"kwargs",
".",
"get",
"(",
"'converters'",
",",
"{",
"}",
")",
",",
"*",
"*",
"annotations",
".",
"get",
"(",
"'converters'",
",",
"{",
"}",
")",
")",
"df",
"=",
"pd",
".",
"read_csv",
"(",
"path_or_file",
",",
"sep",
"=",
"separator",
",",
"comment",
"=",
"'#'",
",",
"*",
"*",
"kwargs",
")",
"df",
".",
"columns",
"=",
"column_index",
"return",
"df"
] | Read a Perseus-formatted matrix into a pd.DataFrame.
Annotation rows will be converted into a multi-index.
By monkey-patching the returned pd.DataFrame a `to_perseus`
method for exporting the pd.DataFrame is made available.
:param path_or_file: File path or file-like object
:param kwargs: Keyword arguments passed as-is to pandas.read_csv
:returns: The parsed data frame | [
"Read",
"a",
"Perseus",
"-",
"formatted",
"matrix",
"into",
"a",
"pd",
".",
"DataFrame",
".",
"Annotation",
"rows",
"will",
"be",
"converted",
"into",
"a",
"multi",
"-",
"index",
"."
] | 3809c1bd46512605f9e7ca7f97e026e4940ed604 | https://github.com/cox-labs/perseuspy/blob/3809c1bd46512605f9e7ca7f97e026e4940ed604/perseuspy/io/perseus/matrix.py#L79-L102 | train |
cox-labs/perseuspy | perseuspy/io/perseus/matrix.py | to_perseus | def to_perseus(df, path_or_file, main_columns=None,
separator=separator,
convert_bool_to_category=True,
numerical_annotation_rows = set([])):
"""
Save pd.DataFrame to Perseus text format.
:param df: pd.DataFrame.
:param path_or_file: File name or file-like object.
:param main_columns: Main columns. Will be infered if set to None. All numeric columns up-until the first non-numeric column are considered main columns.
:param separator: For separating fields, default='\t'.
:param covert_bool_to_category: Convert bool columns of True/False to category columns '+'/'', default=True.
:param numerical_annotation_rows: Set of column names to be interpreted as numerical annotation rows, default=set([]).
"""
_df = df.copy()
if not _df.columns.name:
_df.columns.name = 'Column Name'
column_names = _df.columns.get_level_values('Column Name')
annotations = {}
main_columns = _infer_main_columns(_df) if main_columns is None else main_columns
annotations['Type'] = ['E' if column_names[i] in main_columns else dtype_to_perseus(dtype)
for i, dtype in enumerate(_df.dtypes)]
# detect multi-numeric columns
for i, column in enumerate(_df.columns):
valid_values = [value for value in _df[column] if value is not None]
if len(valid_values) > 0 and all(type(value) is list for value in valid_values):
annotations['Type'][i] = 'M'
_df[column] = _df[column].apply(lambda xs: ';'.join(str(x) for x in xs))
if convert_bool_to_category:
for i, column in enumerate(_df.columns):
if _df.dtypes[i] is np.dtype('bool'):
values = _df[column].values
_df[column][values] = '+'
_df[column][~values] = ''
annotation_row_names = set(_df.columns.names) - {'Column Name'}
for name in annotation_row_names:
annotation_type = 'N' if name in numerical_annotation_rows else 'C'
annotations['{}:{}'.format(annotation_type, name)] = _df.columns.get_level_values(name)
with PathOrFile(path_or_file, 'w') as f:
f.write(separator.join(column_names) + '\n')
for name, values in annotations.items():
f.write('#!{{{name}}}{values}\n'.format(name=name, values=separator.join([str(x) for x in values])))
_df.to_csv(f, header=None, index=False, sep=separator) | python | def to_perseus(df, path_or_file, main_columns=None,
separator=separator,
convert_bool_to_category=True,
numerical_annotation_rows = set([])):
"""
Save pd.DataFrame to Perseus text format.
:param df: pd.DataFrame.
:param path_or_file: File name or file-like object.
:param main_columns: Main columns. Will be infered if set to None. All numeric columns up-until the first non-numeric column are considered main columns.
:param separator: For separating fields, default='\t'.
:param covert_bool_to_category: Convert bool columns of True/False to category columns '+'/'', default=True.
:param numerical_annotation_rows: Set of column names to be interpreted as numerical annotation rows, default=set([]).
"""
_df = df.copy()
if not _df.columns.name:
_df.columns.name = 'Column Name'
column_names = _df.columns.get_level_values('Column Name')
annotations = {}
main_columns = _infer_main_columns(_df) if main_columns is None else main_columns
annotations['Type'] = ['E' if column_names[i] in main_columns else dtype_to_perseus(dtype)
for i, dtype in enumerate(_df.dtypes)]
# detect multi-numeric columns
for i, column in enumerate(_df.columns):
valid_values = [value for value in _df[column] if value is not None]
if len(valid_values) > 0 and all(type(value) is list for value in valid_values):
annotations['Type'][i] = 'M'
_df[column] = _df[column].apply(lambda xs: ';'.join(str(x) for x in xs))
if convert_bool_to_category:
for i, column in enumerate(_df.columns):
if _df.dtypes[i] is np.dtype('bool'):
values = _df[column].values
_df[column][values] = '+'
_df[column][~values] = ''
annotation_row_names = set(_df.columns.names) - {'Column Name'}
for name in annotation_row_names:
annotation_type = 'N' if name in numerical_annotation_rows else 'C'
annotations['{}:{}'.format(annotation_type, name)] = _df.columns.get_level_values(name)
with PathOrFile(path_or_file, 'w') as f:
f.write(separator.join(column_names) + '\n')
for name, values in annotations.items():
f.write('#!{{{name}}}{values}\n'.format(name=name, values=separator.join([str(x) for x in values])))
_df.to_csv(f, header=None, index=False, sep=separator) | [
"def",
"to_perseus",
"(",
"df",
",",
"path_or_file",
",",
"main_columns",
"=",
"None",
",",
"separator",
"=",
"separator",
",",
"convert_bool_to_category",
"=",
"True",
",",
"numerical_annotation_rows",
"=",
"set",
"(",
"[",
"]",
")",
")",
":",
"_df",
"=",
"df",
".",
"copy",
"(",
")",
"if",
"not",
"_df",
".",
"columns",
".",
"name",
":",
"_df",
".",
"columns",
".",
"name",
"=",
"'Column Name'",
"column_names",
"=",
"_df",
".",
"columns",
".",
"get_level_values",
"(",
"'Column Name'",
")",
"annotations",
"=",
"{",
"}",
"main_columns",
"=",
"_infer_main_columns",
"(",
"_df",
")",
"if",
"main_columns",
"is",
"None",
"else",
"main_columns",
"annotations",
"[",
"'Type'",
"]",
"=",
"[",
"'E'",
"if",
"column_names",
"[",
"i",
"]",
"in",
"main_columns",
"else",
"dtype_to_perseus",
"(",
"dtype",
")",
"for",
"i",
",",
"dtype",
"in",
"enumerate",
"(",
"_df",
".",
"dtypes",
")",
"]",
"# detect multi-numeric columns",
"for",
"i",
",",
"column",
"in",
"enumerate",
"(",
"_df",
".",
"columns",
")",
":",
"valid_values",
"=",
"[",
"value",
"for",
"value",
"in",
"_df",
"[",
"column",
"]",
"if",
"value",
"is",
"not",
"None",
"]",
"if",
"len",
"(",
"valid_values",
")",
">",
"0",
"and",
"all",
"(",
"type",
"(",
"value",
")",
"is",
"list",
"for",
"value",
"in",
"valid_values",
")",
":",
"annotations",
"[",
"'Type'",
"]",
"[",
"i",
"]",
"=",
"'M'",
"_df",
"[",
"column",
"]",
"=",
"_df",
"[",
"column",
"]",
".",
"apply",
"(",
"lambda",
"xs",
":",
"';'",
".",
"join",
"(",
"str",
"(",
"x",
")",
"for",
"x",
"in",
"xs",
")",
")",
"if",
"convert_bool_to_category",
":",
"for",
"i",
",",
"column",
"in",
"enumerate",
"(",
"_df",
".",
"columns",
")",
":",
"if",
"_df",
".",
"dtypes",
"[",
"i",
"]",
"is",
"np",
".",
"dtype",
"(",
"'bool'",
")",
":",
"values",
"=",
"_df",
"[",
"column",
"]",
".",
"values",
"_df",
"[",
"column",
"]",
"[",
"values",
"]",
"=",
"'+'",
"_df",
"[",
"column",
"]",
"[",
"~",
"values",
"]",
"=",
"''",
"annotation_row_names",
"=",
"set",
"(",
"_df",
".",
"columns",
".",
"names",
")",
"-",
"{",
"'Column Name'",
"}",
"for",
"name",
"in",
"annotation_row_names",
":",
"annotation_type",
"=",
"'N'",
"if",
"name",
"in",
"numerical_annotation_rows",
"else",
"'C'",
"annotations",
"[",
"'{}:{}'",
".",
"format",
"(",
"annotation_type",
",",
"name",
")",
"]",
"=",
"_df",
".",
"columns",
".",
"get_level_values",
"(",
"name",
")",
"with",
"PathOrFile",
"(",
"path_or_file",
",",
"'w'",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"separator",
".",
"join",
"(",
"column_names",
")",
"+",
"'\\n'",
")",
"for",
"name",
",",
"values",
"in",
"annotations",
".",
"items",
"(",
")",
":",
"f",
".",
"write",
"(",
"'#!{{{name}}}{values}\\n'",
".",
"format",
"(",
"name",
"=",
"name",
",",
"values",
"=",
"separator",
".",
"join",
"(",
"[",
"str",
"(",
"x",
")",
"for",
"x",
"in",
"values",
"]",
")",
")",
")",
"_df",
".",
"to_csv",
"(",
"f",
",",
"header",
"=",
"None",
",",
"index",
"=",
"False",
",",
"sep",
"=",
"separator",
")"
] | Save pd.DataFrame to Perseus text format.
:param df: pd.DataFrame.
:param path_or_file: File name or file-like object.
:param main_columns: Main columns. Will be infered if set to None. All numeric columns up-until the first non-numeric column are considered main columns.
:param separator: For separating fields, default='\t'.
:param covert_bool_to_category: Convert bool columns of True/False to category columns '+'/'', default=True.
:param numerical_annotation_rows: Set of column names to be interpreted as numerical annotation rows, default=set([]). | [
"Save",
"pd",
".",
"DataFrame",
"to",
"Perseus",
"text",
"format",
"."
] | 3809c1bd46512605f9e7ca7f97e026e4940ed604 | https://github.com/cox-labs/perseuspy/blob/3809c1bd46512605f9e7ca7f97e026e4940ed604/perseuspy/io/perseus/matrix.py#L105-L147 | train |
acutesoftware/AIKIF | aikif/web_app/page_search.py | get_page | def get_page(search_text):
"""
formats the entire search result in a table output
"""
lst = search_aikif(search_text)
txt = '<table class="as-table as-table-zebra as-table-horizontal">'
for result in lst:
txt += '<TR><TD>' + result + '</TD></TR>'
txt += '</TABLE>\n\n'
return txt | python | def get_page(search_text):
"""
formats the entire search result in a table output
"""
lst = search_aikif(search_text)
txt = '<table class="as-table as-table-zebra as-table-horizontal">'
for result in lst:
txt += '<TR><TD>' + result + '</TD></TR>'
txt += '</TABLE>\n\n'
return txt | [
"def",
"get_page",
"(",
"search_text",
")",
":",
"lst",
"=",
"search_aikif",
"(",
"search_text",
")",
"txt",
"=",
"'<table class=\"as-table as-table-zebra as-table-horizontal\">'",
"for",
"result",
"in",
"lst",
":",
"txt",
"+=",
"'<TR><TD>'",
"+",
"result",
"+",
"'</TD></TR>'",
"txt",
"+=",
"'</TABLE>\\n\\n'",
"return",
"txt"
] | formats the entire search result in a table output | [
"formats",
"the",
"entire",
"search",
"result",
"in",
"a",
"table",
"output"
] | fcf1582dc5f884b9a4fa7c6e20e9de9d94d21d03 | https://github.com/acutesoftware/AIKIF/blob/fcf1582dc5f884b9a4fa7c6e20e9de9d94d21d03/aikif/web_app/page_search.py#L12-L21 | train |
Subsets and Splits