repo stringlengths 7 55 | path stringlengths 4 223 | func_name stringlengths 1 134 | original_string stringlengths 75 104k | language stringclasses 1
value | code stringlengths 75 104k | code_tokens listlengths 19 28.4k | docstring stringlengths 1 46.9k | docstring_tokens listlengths 1 1.97k | sha stringlengths 40 40 | url stringlengths 87 315 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
letuananh/chirptext | chirptext/texttaglib.py | Document.read_ttl | def read_ttl(path):
''' Helper function to read Document in TTL-TXT format (i.e. ${docname}_*.txt)
E.g. Document.read_ttl('~/data/myfile') is the same as Document('myfile', '~/data/').read()
'''
warnings.warn("Document.read_ttl() is deprecated and will be removed in near future. Use read... | python | def read_ttl(path):
''' Helper function to read Document in TTL-TXT format (i.e. ${docname}_*.txt)
E.g. Document.read_ttl('~/data/myfile') is the same as Document('myfile', '~/data/').read()
'''
warnings.warn("Document.read_ttl() is deprecated and will be removed in near future. Use read... | [
"def",
"read_ttl",
"(",
"path",
")",
":",
"warnings",
".",
"warn",
"(",
"\"Document.read_ttl() is deprecated and will be removed in near future. Use read() instead\"",
",",
"DeprecationWarning",
")",
"doc_path",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"path",
")",
... | Helper function to read Document in TTL-TXT format (i.e. ${docname}_*.txt)
E.g. Document.read_ttl('~/data/myfile') is the same as Document('myfile', '~/data/').read() | [
"Helper",
"function",
"to",
"read",
"Document",
"in",
"TTL",
"-",
"TXT",
"format",
"(",
"i",
".",
"e",
".",
"$",
"{",
"docname",
"}",
"_",
"*",
".",
"txt",
")",
"E",
".",
"g",
".",
"Document",
".",
"read_ttl",
"(",
"~",
"/",
"data",
"/",
"myfil... | ce60b47257b272a587c8703ea1f86cd1a45553a7 | https://github.com/letuananh/chirptext/blob/ce60b47257b272a587c8703ea1f86cd1a45553a7/chirptext/texttaglib.py#L647-L654 | train |
letuananh/chirptext | chirptext/texttaglib.py | TxtReader.read | def read(self, doc=None):
''' Read tagged doc from mutliple files (sents, tokens, concepts, links, tags) '''
if not self.sent_stream:
raise Exception("There is no sentence data stream available")
if doc is None:
doc = Document(name=self.doc_name, path=self.doc_path)
... | python | def read(self, doc=None):
''' Read tagged doc from mutliple files (sents, tokens, concepts, links, tags) '''
if not self.sent_stream:
raise Exception("There is no sentence data stream available")
if doc is None:
doc = Document(name=self.doc_name, path=self.doc_path)
... | [
"def",
"read",
"(",
"self",
",",
"doc",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"sent_stream",
":",
"raise",
"Exception",
"(",
"\"There is no sentence data stream available\"",
")",
"if",
"doc",
"is",
"None",
":",
"doc",
"=",
"Document",
"(",
"nam... | Read tagged doc from mutliple files (sents, tokens, concepts, links, tags) | [
"Read",
"tagged",
"doc",
"from",
"mutliple",
"files",
"(",
"sents",
"tokens",
"concepts",
"links",
"tags",
")"
] | ce60b47257b272a587c8703ea1f86cd1a45553a7 | https://github.com/letuananh/chirptext/blob/ce60b47257b272a587c8703ea1f86cd1a45553a7/chirptext/texttaglib.py#L723-L792 | train |
alefnula/tea | tea/console/format.py | format_page | def format_page(text):
"""Format the text for output adding ASCII frame around the text.
Args:
text (str): Text that needs to be formatted.
Returns:
str: Formatted string.
"""
width = max(map(len, text.splitlines()))
page = "+-" + "-" * width + "-+\n"
for line in... | python | def format_page(text):
"""Format the text for output adding ASCII frame around the text.
Args:
text (str): Text that needs to be formatted.
Returns:
str: Formatted string.
"""
width = max(map(len, text.splitlines()))
page = "+-" + "-" * width + "-+\n"
for line in... | [
"def",
"format_page",
"(",
"text",
")",
":",
"width",
"=",
"max",
"(",
"map",
"(",
"len",
",",
"text",
".",
"splitlines",
"(",
")",
")",
")",
"page",
"=",
"\"+-\"",
"+",
"\"-\"",
"*",
"width",
"+",
"\"-+\\n\"",
"for",
"line",
"in",
"text",
".",
"... | Format the text for output adding ASCII frame around the text.
Args:
text (str): Text that needs to be formatted.
Returns:
str: Formatted string. | [
"Format",
"the",
"text",
"for",
"output",
"adding",
"ASCII",
"frame",
"around",
"the",
"text",
".",
"Args",
":",
"text",
"(",
"str",
")",
":",
"Text",
"that",
"needs",
"to",
"be",
"formatted",
".",
"Returns",
":",
"str",
":",
"Formatted",
"string",
"."... | f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3 | https://github.com/alefnula/tea/blob/f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3/tea/console/format.py#L16-L30 | train |
alefnula/tea | tea/console/format.py | table | def table(text):
"""Format the text as a table.
Text in format:
first | second
row 2 col 1 | 4
Will be formatted as::
+-------------+--------+
| first | second |
+-------------+--------+
| row 2 col 1 | 4 |
+-------------+--------+... | python | def table(text):
"""Format the text as a table.
Text in format:
first | second
row 2 col 1 | 4
Will be formatted as::
+-------------+--------+
| first | second |
+-------------+--------+
| row 2 col 1 | 4 |
+-------------+--------+... | [
"def",
"table",
"(",
"text",
")",
":",
"def",
"table_bar",
"(",
"col_lengths",
")",
":",
"return",
"\"+-%s-+%s\"",
"%",
"(",
"\"-+-\"",
".",
"join",
"(",
"[",
"\"-\"",
"*",
"length",
"for",
"length",
"in",
"col_lengths",
"]",
")",
",",
"os",
".",
"li... | Format the text as a table.
Text in format:
first | second
row 2 col 1 | 4
Will be formatted as::
+-------------+--------+
| first | second |
+-------------+--------+
| row 2 col 1 | 4 |
+-------------+--------+
Args:
te... | [
"Format",
"the",
"text",
"as",
"a",
"table",
".",
"Text",
"in",
"format",
":",
"first",
"|",
"second",
"row",
"2",
"col",
"1",
"|",
"4",
"Will",
"be",
"formatted",
"as",
"::",
"+",
"-------------",
"+",
"--------",
"+",
"|",
"first",
"|",
"second",
... | f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3 | https://github.com/alefnula/tea/blob/f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3/tea/console/format.py#L33-L82 | train |
alefnula/tea | tea/console/format.py | print_page | def print_page(text):
"""Format the text and prints it on stdout.
Text is formatted by adding a ASCII frame around it and coloring the text.
Colors can be added to text using color tags, for example:
My [FG_BLUE]blue[NORMAL] text.
My [BG_BLUE]blue background[NORMAL] text.
"""
... | python | def print_page(text):
"""Format the text and prints it on stdout.
Text is formatted by adding a ASCII frame around it and coloring the text.
Colors can be added to text using color tags, for example:
My [FG_BLUE]blue[NORMAL] text.
My [BG_BLUE]blue background[NORMAL] text.
"""
... | [
"def",
"print_page",
"(",
"text",
")",
":",
"color_re",
"=",
"re",
".",
"compile",
"(",
"r\"\\[(?P<color>[FB]G_[A-Z_]+|NORMAL)\\]\"",
")",
"width",
"=",
"max",
"(",
"[",
"len",
"(",
"strip_colors",
"(",
"x",
")",
")",
"for",
"x",
"in",
"text",
".",
"spli... | Format the text and prints it on stdout.
Text is formatted by adding a ASCII frame around it and coloring the text.
Colors can be added to text using color tags, for example:
My [FG_BLUE]blue[NORMAL] text.
My [BG_BLUE]blue background[NORMAL] text. | [
"Format",
"the",
"text",
"and",
"prints",
"it",
"on",
"stdout",
".",
"Text",
"is",
"formatted",
"by",
"adding",
"a",
"ASCII",
"frame",
"around",
"it",
"and",
"coloring",
"the",
"text",
".",
"Colors",
"can",
"be",
"added",
"to",
"text",
"using",
"color",
... | f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3 | https://github.com/alefnula/tea/blob/f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3/tea/console/format.py#L97-L123 | train |
alefnula/tea | tea/console/format.py | wrap_text | def wrap_text(text, width=80):
"""Wrap text lines to maximum *width* characters.
Wrapped text is aligned against the left text border.
Args:
text (str): Text to wrap.
width (int): Maximum number of characters per line.
Returns:
str: Wrapped text.
"""
text =... | python | def wrap_text(text, width=80):
"""Wrap text lines to maximum *width* characters.
Wrapped text is aligned against the left text border.
Args:
text (str): Text to wrap.
width (int): Maximum number of characters per line.
Returns:
str: Wrapped text.
"""
text =... | [
"def",
"wrap_text",
"(",
"text",
",",
"width",
"=",
"80",
")",
":",
"text",
"=",
"re",
".",
"sub",
"(",
"r\"\\s+\"",
",",
"\" \"",
",",
"text",
")",
".",
"strip",
"(",
")",
"wrapper",
"=",
"TextWrapper",
"(",
"width",
"=",
"width",
",",
"break_long... | Wrap text lines to maximum *width* characters.
Wrapped text is aligned against the left text border.
Args:
text (str): Text to wrap.
width (int): Maximum number of characters per line.
Returns:
str: Wrapped text. | [
"Wrap",
"text",
"lines",
"to",
"maximum",
"*",
"width",
"*",
"characters",
".",
"Wrapped",
"text",
"is",
"aligned",
"against",
"the",
"left",
"text",
"border",
".",
"Args",
":",
"text",
"(",
"str",
")",
":",
"Text",
"to",
"wrap",
".",
"width",
"(",
"... | f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3 | https://github.com/alefnula/tea/blob/f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3/tea/console/format.py#L126-L142 | train |
alefnula/tea | tea/console/format.py | rjust_text | def rjust_text(text, width=80, indent=0, subsequent=None):
"""Wrap text and adjust it to right border.
Same as L{wrap_text} with the difference that the text is aligned against
the right text border.
Args:
text (str): Text to wrap and align.
width (int): Maximum number of chara... | python | def rjust_text(text, width=80, indent=0, subsequent=None):
"""Wrap text and adjust it to right border.
Same as L{wrap_text} with the difference that the text is aligned against
the right text border.
Args:
text (str): Text to wrap and align.
width (int): Maximum number of chara... | [
"def",
"rjust_text",
"(",
"text",
",",
"width",
"=",
"80",
",",
"indent",
"=",
"0",
",",
"subsequent",
"=",
"None",
")",
":",
"text",
"=",
"re",
".",
"sub",
"(",
"r\"\\s+\"",
",",
"\" \"",
",",
"text",
")",
".",
"strip",
"(",
")",
"if",
"subseque... | Wrap text and adjust it to right border.
Same as L{wrap_text} with the difference that the text is aligned against
the right text border.
Args:
text (str): Text to wrap and align.
width (int): Maximum number of characters per line.
indent (int): Indentation of the first lin... | [
"Wrap",
"text",
"and",
"adjust",
"it",
"to",
"right",
"border",
".",
"Same",
"as",
"L",
"{",
"wrap_text",
"}",
"with",
"the",
"difference",
"that",
"the",
"text",
"is",
"aligned",
"against",
"the",
"right",
"text",
"border",
".",
"Args",
":",
"text",
"... | f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3 | https://github.com/alefnula/tea/blob/f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3/tea/console/format.py#L145-L168 | train |
alefnula/tea | tea/console/format.py | center_text | def center_text(text, width=80):
"""Center all lines of the text.
It is assumed that all lines width is smaller then B{width}, because the
line width will not be checked.
Args:
text (str): Text to wrap.
width (int): Maximum number of characters per line.
Returns:
... | python | def center_text(text, width=80):
"""Center all lines of the text.
It is assumed that all lines width is smaller then B{width}, because the
line width will not be checked.
Args:
text (str): Text to wrap.
width (int): Maximum number of characters per line.
Returns:
... | [
"def",
"center_text",
"(",
"text",
",",
"width",
"=",
"80",
")",
":",
"centered",
"=",
"[",
"]",
"for",
"line",
"in",
"text",
".",
"splitlines",
"(",
")",
":",
"centered",
".",
"append",
"(",
"line",
".",
"center",
"(",
"width",
")",
")",
"return",... | Center all lines of the text.
It is assumed that all lines width is smaller then B{width}, because the
line width will not be checked.
Args:
text (str): Text to wrap.
width (int): Maximum number of characters per line.
Returns:
str: Centered text. | [
"Center",
"all",
"lines",
"of",
"the",
"text",
".",
"It",
"is",
"assumed",
"that",
"all",
"lines",
"width",
"is",
"smaller",
"then",
"B",
"{",
"width",
"}",
"because",
"the",
"line",
"width",
"will",
"not",
"be",
"checked",
".",
"Args",
":",
"text",
... | f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3 | https://github.com/alefnula/tea/blob/f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3/tea/console/format.py#L171-L187 | train |
RI-imaging/qpimage | qpimage/integrity_check.py | check | def check(qpi_or_h5file, checks=["attributes", "background"]):
"""Checks various properties of a :class:`qpimage.core.QPImage` instance
Parameters
----------
qpi_or_h5file: qpimage.core.QPImage or str
A QPImage object or a path to an hdf5 file
checks: list of str
Which checks to per... | python | def check(qpi_or_h5file, checks=["attributes", "background"]):
"""Checks various properties of a :class:`qpimage.core.QPImage` instance
Parameters
----------
qpi_or_h5file: qpimage.core.QPImage or str
A QPImage object or a path to an hdf5 file
checks: list of str
Which checks to per... | [
"def",
"check",
"(",
"qpi_or_h5file",
",",
"checks",
"=",
"[",
"\"attributes\"",
",",
"\"background\"",
"]",
")",
":",
"if",
"isinstance",
"(",
"checks",
",",
"str",
")",
":",
"checks",
"=",
"[",
"checks",
"]",
"for",
"ch",
"in",
"checks",
":",
"if",
... | Checks various properties of a :class:`qpimage.core.QPImage` instance
Parameters
----------
qpi_or_h5file: qpimage.core.QPImage or str
A QPImage object or a path to an hdf5 file
checks: list of str
Which checks to perform ("attributes" and/or "background")
Raises
------
Int... | [
"Checks",
"various",
"properties",
"of",
"a",
":",
"class",
":",
"qpimage",
".",
"core",
".",
"QPImage",
"instance"
] | 863c0fce5735b4c0ae369f75c0df9a33411b2bb2 | https://github.com/RI-imaging/qpimage/blob/863c0fce5735b4c0ae369f75c0df9a33411b2bb2/qpimage/integrity_check.py#L13-L45 | train |
RI-imaging/qpimage | qpimage/integrity_check.py | check_attributes | def check_attributes(qpi):
"""Check QPimage attributes
Parameters
----------
qpi: qpimage.core.QPImage
Raises
------
IntegrityCheckError
if the check fails
"""
missing_attrs = []
for key in DATA_KEYS:
if key not in qpi.meta:
missing_attrs.append(key)... | python | def check_attributes(qpi):
"""Check QPimage attributes
Parameters
----------
qpi: qpimage.core.QPImage
Raises
------
IntegrityCheckError
if the check fails
"""
missing_attrs = []
for key in DATA_KEYS:
if key not in qpi.meta:
missing_attrs.append(key)... | [
"def",
"check_attributes",
"(",
"qpi",
")",
":",
"missing_attrs",
"=",
"[",
"]",
"for",
"key",
"in",
"DATA_KEYS",
":",
"if",
"key",
"not",
"in",
"qpi",
".",
"meta",
":",
"missing_attrs",
".",
"append",
"(",
"key",
")",
"if",
"missing_attrs",
":",
"msg"... | Check QPimage attributes
Parameters
----------
qpi: qpimage.core.QPImage
Raises
------
IntegrityCheckError
if the check fails | [
"Check",
"QPimage",
"attributes"
] | 863c0fce5735b4c0ae369f75c0df9a33411b2bb2 | https://github.com/RI-imaging/qpimage/blob/863c0fce5735b4c0ae369f75c0df9a33411b2bb2/qpimage/integrity_check.py#L48-L67 | train |
RI-imaging/qpimage | qpimage/integrity_check.py | check_background | def check_background(qpi):
"""Check QPimage background data
Parameters
----------
qpi: qpimage.core.QPImage
Raises
------
IntegrityCheckError
if the check fails
"""
for imdat in [qpi._amp, qpi._pha]:
try:
fit, attrs = imdat.get_bg(key="fit", ret_attrs=Tr... | python | def check_background(qpi):
"""Check QPimage background data
Parameters
----------
qpi: qpimage.core.QPImage
Raises
------
IntegrityCheckError
if the check fails
"""
for imdat in [qpi._amp, qpi._pha]:
try:
fit, attrs = imdat.get_bg(key="fit", ret_attrs=Tr... | [
"def",
"check_background",
"(",
"qpi",
")",
":",
"for",
"imdat",
"in",
"[",
"qpi",
".",
"_amp",
",",
"qpi",
".",
"_pha",
"]",
":",
"try",
":",
"fit",
",",
"attrs",
"=",
"imdat",
".",
"get_bg",
"(",
"key",
"=",
"\"fit\"",
",",
"ret_attrs",
"=",
"T... | Check QPimage background data
Parameters
----------
qpi: qpimage.core.QPImage
Raises
------
IntegrityCheckError
if the check fails | [
"Check",
"QPimage",
"background",
"data"
] | 863c0fce5735b4c0ae369f75c0df9a33411b2bb2 | https://github.com/RI-imaging/qpimage/blob/863c0fce5735b4c0ae369f75c0df9a33411b2bb2/qpimage/integrity_check.py#L70-L115 | train |
RI-imaging/qpimage | qpimage/image_data.py | write_image_dataset | def write_image_dataset(group, key, data, h5dtype=None):
"""Write an image to an hdf5 group as a dataset
This convenience function sets all attributes such that the image
can be visualized with HDFView, sets the compression and fletcher32
filters, and sets the chunk size to the image shape.
Parame... | python | def write_image_dataset(group, key, data, h5dtype=None):
"""Write an image to an hdf5 group as a dataset
This convenience function sets all attributes such that the image
can be visualized with HDFView, sets the compression and fletcher32
filters, and sets the chunk size to the image shape.
Parame... | [
"def",
"write_image_dataset",
"(",
"group",
",",
"key",
",",
"data",
",",
"h5dtype",
"=",
"None",
")",
":",
"if",
"h5dtype",
"is",
"None",
":",
"h5dtype",
"=",
"data",
".",
"dtype",
"if",
"key",
"in",
"group",
":",
"del",
"group",
"[",
"key",
"]",
... | Write an image to an hdf5 group as a dataset
This convenience function sets all attributes such that the image
can be visualized with HDFView, sets the compression and fletcher32
filters, and sets the chunk size to the image shape.
Parameters
----------
group: h5py.Group
HDF5 group to ... | [
"Write",
"an",
"image",
"to",
"an",
"hdf5",
"group",
"as",
"a",
"dataset"
] | 863c0fce5735b4c0ae369f75c0df9a33411b2bb2 | https://github.com/RI-imaging/qpimage/blob/863c0fce5735b4c0ae369f75c0df9a33411b2bb2/qpimage/image_data.py#L326-L369 | train |
RI-imaging/qpimage | qpimage/image_data.py | ImageData.info | def info(self):
"""list of background correction parameters"""
info = []
name = self.__class__.__name__.lower()
# get bg information
for key in VALID_BG_KEYS:
if key in self.h5["bg_data"]:
attrs = self.h5["bg_data"][key].attrs
for akey ... | python | def info(self):
"""list of background correction parameters"""
info = []
name = self.__class__.__name__.lower()
# get bg information
for key in VALID_BG_KEYS:
if key in self.h5["bg_data"]:
attrs = self.h5["bg_data"][key].attrs
for akey ... | [
"def",
"info",
"(",
"self",
")",
":",
"info",
"=",
"[",
"]",
"name",
"=",
"self",
".",
"__class__",
".",
"__name__",
".",
"lower",
"(",
")",
"# get bg information",
"for",
"key",
"in",
"VALID_BG_KEYS",
":",
"if",
"key",
"in",
"self",
".",
"h5",
"[",
... | list of background correction parameters | [
"list",
"of",
"background",
"correction",
"parameters"
] | 863c0fce5735b4c0ae369f75c0df9a33411b2bb2 | https://github.com/RI-imaging/qpimage/blob/863c0fce5735b4c0ae369f75c0df9a33411b2bb2/qpimage/image_data.py#L96-L122 | train |
RI-imaging/qpimage | qpimage/image_data.py | ImageData.del_bg | def del_bg(self, key):
"""Remove the background image data
Parameters
----------
key: str
One of :const:`VALID_BG_KEYS`
"""
if key not in VALID_BG_KEYS:
raise ValueError("Invalid bg key: {}".format(key))
if key in self.h5["bg_data"]:
... | python | def del_bg(self, key):
"""Remove the background image data
Parameters
----------
key: str
One of :const:`VALID_BG_KEYS`
"""
if key not in VALID_BG_KEYS:
raise ValueError("Invalid bg key: {}".format(key))
if key in self.h5["bg_data"]:
... | [
"def",
"del_bg",
"(",
"self",
",",
"key",
")",
":",
"if",
"key",
"not",
"in",
"VALID_BG_KEYS",
":",
"raise",
"ValueError",
"(",
"\"Invalid bg key: {}\"",
".",
"format",
"(",
"key",
")",
")",
"if",
"key",
"in",
"self",
".",
"h5",
"[",
"\"bg_data\"",
"]"... | Remove the background image data
Parameters
----------
key: str
One of :const:`VALID_BG_KEYS` | [
"Remove",
"the",
"background",
"image",
"data"
] | 863c0fce5735b4c0ae369f75c0df9a33411b2bb2 | https://github.com/RI-imaging/qpimage/blob/863c0fce5735b4c0ae369f75c0df9a33411b2bb2/qpimage/image_data.py#L129-L143 | train |
RI-imaging/qpimage | qpimage/image_data.py | ImageData.estimate_bg | def estimate_bg(self, fit_offset="mean", fit_profile="tilt",
border_px=0, from_mask=None, ret_mask=False):
"""Estimate image background
Parameters
----------
fit_profile: str
The type of background profile to fit:
- "offset": offset only
... | python | def estimate_bg(self, fit_offset="mean", fit_profile="tilt",
border_px=0, from_mask=None, ret_mask=False):
"""Estimate image background
Parameters
----------
fit_profile: str
The type of background profile to fit:
- "offset": offset only
... | [
"def",
"estimate_bg",
"(",
"self",
",",
"fit_offset",
"=",
"\"mean\"",
",",
"fit_profile",
"=",
"\"tilt\"",
",",
"border_px",
"=",
"0",
",",
"from_mask",
"=",
"None",
",",
"ret_mask",
"=",
"False",
")",
":",
"# remove existing bg before accessing imdat.image",
"... | Estimate image background
Parameters
----------
fit_profile: str
The type of background profile to fit:
- "offset": offset only
- "poly2o": 2D 2nd order polynomial with mixed terms
- "tilt": 2D linear tilt with offset (default)
fit_offset... | [
"Estimate",
"image",
"background"
] | 863c0fce5735b4c0ae369f75c0df9a33411b2bb2 | https://github.com/RI-imaging/qpimage/blob/863c0fce5735b4c0ae369f75c0df9a33411b2bb2/qpimage/image_data.py#L145-L206 | train |
RI-imaging/qpimage | qpimage/image_data.py | ImageData.get_bg | def get_bg(self, key=None, ret_attrs=False):
"""Get the background data
Parameters
----------
key: None or str
A user-defined key that identifies the background data.
Examples are "data" for experimental data, or "fit"
for an estimated background corr... | python | def get_bg(self, key=None, ret_attrs=False):
"""Get the background data
Parameters
----------
key: None or str
A user-defined key that identifies the background data.
Examples are "data" for experimental data, or "fit"
for an estimated background corr... | [
"def",
"get_bg",
"(",
"self",
",",
"key",
"=",
"None",
",",
"ret_attrs",
"=",
"False",
")",
":",
"if",
"key",
"is",
"None",
":",
"if",
"ret_attrs",
":",
"raise",
"ValueError",
"(",
"\"No attributes for combined background!\"",
")",
"return",
"self",
".",
"... | Get the background data
Parameters
----------
key: None or str
A user-defined key that identifies the background data.
Examples are "data" for experimental data, or "fit"
for an estimated background correction
(see :const:`VALID_BG_KEYS`). If set ... | [
"Get",
"the",
"background",
"data"
] | 863c0fce5735b4c0ae369f75c0df9a33411b2bb2 | https://github.com/RI-imaging/qpimage/blob/863c0fce5735b4c0ae369f75c0df9a33411b2bb2/qpimage/image_data.py#L208-L242 | train |
RI-imaging/qpimage | qpimage/image_data.py | ImageData.set_bg | def set_bg(self, bg, key="data", attrs={}):
"""Set the background data
Parameters
----------
bg: numbers.Real, 2d ndarray, ImageData, or h5py.Dataset
The background data. If `bg` is an `h5py.Dataset` object,
it must exist in the same hdf5 file (a hard link is cre... | python | def set_bg(self, bg, key="data", attrs={}):
"""Set the background data
Parameters
----------
bg: numbers.Real, 2d ndarray, ImageData, or h5py.Dataset
The background data. If `bg` is an `h5py.Dataset` object,
it must exist in the same hdf5 file (a hard link is cre... | [
"def",
"set_bg",
"(",
"self",
",",
"bg",
",",
"key",
"=",
"\"data\"",
",",
"attrs",
"=",
"{",
"}",
")",
":",
"if",
"key",
"not",
"in",
"VALID_BG_KEYS",
":",
"raise",
"ValueError",
"(",
"\"Invalid bg key: {}\"",
".",
"format",
"(",
"key",
")",
")",
"#... | Set the background data
Parameters
----------
bg: numbers.Real, 2d ndarray, ImageData, or h5py.Dataset
The background data. If `bg` is an `h5py.Dataset` object,
it must exist in the same hdf5 file (a hard link is created).
If set to `None`, the data will be r... | [
"Set",
"the",
"background",
"data"
] | 863c0fce5735b4c0ae369f75c0df9a33411b2bb2 | https://github.com/RI-imaging/qpimage/blob/863c0fce5735b4c0ae369f75c0df9a33411b2bb2/qpimage/image_data.py#L244-L283 | train |
RI-imaging/qpimage | qpimage/image_data.py | Amplitude._bg_combine | def _bg_combine(self, bgs):
"""Combine several background amplitude images"""
out = np.ones(self.h5["raw"].shape, dtype=float)
# bg is an h5py.DataSet
for bg in bgs:
out *= bg[:]
return out | python | def _bg_combine(self, bgs):
"""Combine several background amplitude images"""
out = np.ones(self.h5["raw"].shape, dtype=float)
# bg is an h5py.DataSet
for bg in bgs:
out *= bg[:]
return out | [
"def",
"_bg_combine",
"(",
"self",
",",
"bgs",
")",
":",
"out",
"=",
"np",
".",
"ones",
"(",
"self",
".",
"h5",
"[",
"\"raw\"",
"]",
".",
"shape",
",",
"dtype",
"=",
"float",
")",
"# bg is an h5py.DataSet",
"for",
"bg",
"in",
"bgs",
":",
"out",
"*=... | Combine several background amplitude images | [
"Combine",
"several",
"background",
"amplitude",
"images"
] | 863c0fce5735b4c0ae369f75c0df9a33411b2bb2 | https://github.com/RI-imaging/qpimage/blob/863c0fce5735b4c0ae369f75c0df9a33411b2bb2/qpimage/image_data.py#L293-L299 | train |
devoperate/chronos | chronos/helpers.py | git_tags | def git_tags() -> str:
"""
Calls ``git tag -l --sort=-v:refname`` (sorts output) and returns the
output as a UTF-8 encoded string. Raises a NoGitTagsException if the
repository doesn't contain any Git tags.
"""
try:
subprocess.check_call(['git', 'fetch', '--tags'])
except CalledProce... | python | def git_tags() -> str:
"""
Calls ``git tag -l --sort=-v:refname`` (sorts output) and returns the
output as a UTF-8 encoded string. Raises a NoGitTagsException if the
repository doesn't contain any Git tags.
"""
try:
subprocess.check_call(['git', 'fetch', '--tags'])
except CalledProce... | [
"def",
"git_tags",
"(",
")",
"->",
"str",
":",
"try",
":",
"subprocess",
".",
"check_call",
"(",
"[",
"'git'",
",",
"'fetch'",
",",
"'--tags'",
"]",
")",
"except",
"CalledProcessError",
":",
"pass",
"cmd",
"=",
"[",
"'git'",
",",
"'tag'",
",",
"'--list... | Calls ``git tag -l --sort=-v:refname`` (sorts output) and returns the
output as a UTF-8 encoded string. Raises a NoGitTagsException if the
repository doesn't contain any Git tags. | [
"Calls",
"git",
"tag",
"-",
"l",
"--",
"sort",
"=",
"-",
"v",
":",
"refname",
"(",
"sorts",
"output",
")",
"and",
"returns",
"the",
"output",
"as",
"a",
"UTF",
"-",
"8",
"encoded",
"string",
".",
"Raises",
"a",
"NoGitTagsException",
"if",
"the",
"rep... | 5ae6047c4f13db9f5e85a0c72a3dc47f05a8d7bd | https://github.com/devoperate/chronos/blob/5ae6047c4f13db9f5e85a0c72a3dc47f05a8d7bd/chronos/helpers.py#L45-L62 | train |
devoperate/chronos | chronos/helpers.py | git_tag_to_semver | def git_tag_to_semver(git_tag: str) -> SemVer:
"""
:git_tag: A string representation of a Git tag.
Searches a Git tag's string representation for a SemVer, and returns that
as a SemVer object.
"""
pattern = re.compile(r'[0-9]+\.[0-9]+\.[0-9]+$')
match = pattern.search(git_tag)
if match:... | python | def git_tag_to_semver(git_tag: str) -> SemVer:
"""
:git_tag: A string representation of a Git tag.
Searches a Git tag's string representation for a SemVer, and returns that
as a SemVer object.
"""
pattern = re.compile(r'[0-9]+\.[0-9]+\.[0-9]+$')
match = pattern.search(git_tag)
if match:... | [
"def",
"git_tag_to_semver",
"(",
"git_tag",
":",
"str",
")",
"->",
"SemVer",
":",
"pattern",
"=",
"re",
".",
"compile",
"(",
"r'[0-9]+\\.[0-9]+\\.[0-9]+$'",
")",
"match",
"=",
"pattern",
".",
"search",
"(",
"git_tag",
")",
"if",
"match",
":",
"version",
"=... | :git_tag: A string representation of a Git tag.
Searches a Git tag's string representation for a SemVer, and returns that
as a SemVer object. | [
":",
"git_tag",
":",
"A",
"string",
"representation",
"of",
"a",
"Git",
"tag",
"."
] | 5ae6047c4f13db9f5e85a0c72a3dc47f05a8d7bd | https://github.com/devoperate/chronos/blob/5ae6047c4f13db9f5e85a0c72a3dc47f05a8d7bd/chronos/helpers.py#L65-L79 | train |
devoperate/chronos | chronos/helpers.py | last_git_release_tag | def last_git_release_tag(git_tags: str) -> str:
"""
:git_tags: chronos.helpers.git_tags() function output.
Returns the latest Git tag ending with a SemVer as a string.
"""
semver_re = re.compile(r'[0-9]+\.[0-9]+\.[0-9]+$')
str_ver = []
for i in git_tags.split():
if semver_re.search(... | python | def last_git_release_tag(git_tags: str) -> str:
"""
:git_tags: chronos.helpers.git_tags() function output.
Returns the latest Git tag ending with a SemVer as a string.
"""
semver_re = re.compile(r'[0-9]+\.[0-9]+\.[0-9]+$')
str_ver = []
for i in git_tags.split():
if semver_re.search(... | [
"def",
"last_git_release_tag",
"(",
"git_tags",
":",
"str",
")",
"->",
"str",
":",
"semver_re",
"=",
"re",
".",
"compile",
"(",
"r'[0-9]+\\.[0-9]+\\.[0-9]+$'",
")",
"str_ver",
"=",
"[",
"]",
"for",
"i",
"in",
"git_tags",
".",
"split",
"(",
")",
":",
"if"... | :git_tags: chronos.helpers.git_tags() function output.
Returns the latest Git tag ending with a SemVer as a string. | [
":",
"git_tags",
":",
"chronos",
".",
"helpers",
".",
"git_tags",
"()",
"function",
"output",
"."
] | 5ae6047c4f13db9f5e85a0c72a3dc47f05a8d7bd | https://github.com/devoperate/chronos/blob/5ae6047c4f13db9f5e85a0c72a3dc47f05a8d7bd/chronos/helpers.py#L82-L97 | train |
devoperate/chronos | chronos/helpers.py | git_commits_since_last_tag | def git_commits_since_last_tag(last_tag: str) -> dict:
"""
:last_tag: The Git tag that should serve as the starting point for the
commit log lookup.
Calls ``git log <last_tag>.. --format='%H %s'`` and returns the output as a
dict of hash-message pairs.
"""
try:
cmd = ['git', 'log', ... | python | def git_commits_since_last_tag(last_tag: str) -> dict:
"""
:last_tag: The Git tag that should serve as the starting point for the
commit log lookup.
Calls ``git log <last_tag>.. --format='%H %s'`` and returns the output as a
dict of hash-message pairs.
"""
try:
cmd = ['git', 'log', ... | [
"def",
"git_commits_since_last_tag",
"(",
"last_tag",
":",
"str",
")",
"->",
"dict",
":",
"try",
":",
"cmd",
"=",
"[",
"'git'",
",",
"'log'",
",",
"last_tag",
"+",
"'..'",
",",
"\"--format='%H %s'\"",
"]",
"commit_log",
"=",
"subprocess",
".",
"check_output"... | :last_tag: The Git tag that should serve as the starting point for the
commit log lookup.
Calls ``git log <last_tag>.. --format='%H %s'`` and returns the output as a
dict of hash-message pairs. | [
":",
"last_tag",
":",
"The",
"Git",
"tag",
"that",
"should",
"serve",
"as",
"the",
"starting",
"point",
"for",
"the",
"commit",
"log",
"lookup",
"."
] | 5ae6047c4f13db9f5e85a0c72a3dc47f05a8d7bd | https://github.com/devoperate/chronos/blob/5ae6047c4f13db9f5e85a0c72a3dc47f05a8d7bd/chronos/helpers.py#L100-L127 | train |
devoperate/chronos | chronos/helpers.py | parse_commit_log | def parse_commit_log(commit_log: dict) -> str:
"""
:commit_log: chronos.helpers.git_commits_since_last_tag() output.
Parse Git log and return either 'maj', 'min', or 'pat'.
"""
rv = 'pat'
cc_patterns = patterns()
for value in commit_log.values():
if re.search(cc_patterns['feat'], ... | python | def parse_commit_log(commit_log: dict) -> str:
"""
:commit_log: chronos.helpers.git_commits_since_last_tag() output.
Parse Git log and return either 'maj', 'min', or 'pat'.
"""
rv = 'pat'
cc_patterns = patterns()
for value in commit_log.values():
if re.search(cc_patterns['feat'], ... | [
"def",
"parse_commit_log",
"(",
"commit_log",
":",
"dict",
")",
"->",
"str",
":",
"rv",
"=",
"'pat'",
"cc_patterns",
"=",
"patterns",
"(",
")",
"for",
"value",
"in",
"commit_log",
".",
"values",
"(",
")",
":",
"if",
"re",
".",
"search",
"(",
"cc_patter... | :commit_log: chronos.helpers.git_commits_since_last_tag() output.
Parse Git log and return either 'maj', 'min', or 'pat'. | [
":",
"commit_log",
":",
"chronos",
".",
"helpers",
".",
"git_commits_since_last_tag",
"()",
"output",
"."
] | 5ae6047c4f13db9f5e85a0c72a3dc47f05a8d7bd | https://github.com/devoperate/chronos/blob/5ae6047c4f13db9f5e85a0c72a3dc47f05a8d7bd/chronos/helpers.py#L130-L146 | train |
devoperate/chronos | chronos/semver.py | SemVer.from_str | def from_str(cls, version_str: str):
"""
Alternate constructor that accepts a string SemVer.
"""
o = cls()
o.version = version_str
return o | python | def from_str(cls, version_str: str):
"""
Alternate constructor that accepts a string SemVer.
"""
o = cls()
o.version = version_str
return o | [
"def",
"from_str",
"(",
"cls",
",",
"version_str",
":",
"str",
")",
":",
"o",
"=",
"cls",
"(",
")",
"o",
".",
"version",
"=",
"version_str",
"return",
"o"
] | Alternate constructor that accepts a string SemVer. | [
"Alternate",
"constructor",
"that",
"accepts",
"a",
"string",
"SemVer",
"."
] | 5ae6047c4f13db9f5e85a0c72a3dc47f05a8d7bd | https://github.com/devoperate/chronos/blob/5ae6047c4f13db9f5e85a0c72a3dc47f05a8d7bd/chronos/semver.py#L87-L93 | train |
devoperate/chronos | chronos/semver.py | SemVer.major | def major(self, major: int) -> None:
"""
param major
Major version number property. Must be a non-negative integer.
"""
self.filter_negatives(major)
self._major = major | python | def major(self, major: int) -> None:
"""
param major
Major version number property. Must be a non-negative integer.
"""
self.filter_negatives(major)
self._major = major | [
"def",
"major",
"(",
"self",
",",
"major",
":",
"int",
")",
"->",
"None",
":",
"self",
".",
"filter_negatives",
"(",
"major",
")",
"self",
".",
"_major",
"=",
"major"
] | param major
Major version number property. Must be a non-negative integer. | [
"param",
"major"
] | 5ae6047c4f13db9f5e85a0c72a3dc47f05a8d7bd | https://github.com/devoperate/chronos/blob/5ae6047c4f13db9f5e85a0c72a3dc47f05a8d7bd/chronos/semver.py#L103-L110 | train |
devoperate/chronos | chronos/semver.py | SemVer.minor | def minor(self, minor: int) -> None:
"""
param minor
Minor version number property. Must be a non-negative integer.
"""
self.filter_negatives(minor)
self._minor = minor | python | def minor(self, minor: int) -> None:
"""
param minor
Minor version number property. Must be a non-negative integer.
"""
self.filter_negatives(minor)
self._minor = minor | [
"def",
"minor",
"(",
"self",
",",
"minor",
":",
"int",
")",
"->",
"None",
":",
"self",
".",
"filter_negatives",
"(",
"minor",
")",
"self",
".",
"_minor",
"=",
"minor"
] | param minor
Minor version number property. Must be a non-negative integer. | [
"param",
"minor"
] | 5ae6047c4f13db9f5e85a0c72a3dc47f05a8d7bd | https://github.com/devoperate/chronos/blob/5ae6047c4f13db9f5e85a0c72a3dc47f05a8d7bd/chronos/semver.py#L120-L127 | train |
devoperate/chronos | chronos/semver.py | SemVer.patch | def patch(self, patch: int) -> None:
"""
param patch
Patch version number property. Must be a non-negative integer.
"""
self.filter_negatives(patch)
self._patch = patch | python | def patch(self, patch: int) -> None:
"""
param patch
Patch version number property. Must be a non-negative integer.
"""
self.filter_negatives(patch)
self._patch = patch | [
"def",
"patch",
"(",
"self",
",",
"patch",
":",
"int",
")",
"->",
"None",
":",
"self",
".",
"filter_negatives",
"(",
"patch",
")",
"self",
".",
"_patch",
"=",
"patch"
] | param patch
Patch version number property. Must be a non-negative integer. | [
"param",
"patch"
] | 5ae6047c4f13db9f5e85a0c72a3dc47f05a8d7bd | https://github.com/devoperate/chronos/blob/5ae6047c4f13db9f5e85a0c72a3dc47f05a8d7bd/chronos/semver.py#L137-L144 | train |
devoperate/chronos | chronos/semver.py | SemVer.version | def version(self) -> str:
"""
Version version number property. Must be a string consisting of three
non-negative integers delimited by periods (eg. '1.0.1').
"""
version: str = (
str(self._major) + '.' +
str(self._minor) + '.' +
str(self._patch... | python | def version(self) -> str:
"""
Version version number property. Must be a string consisting of three
non-negative integers delimited by periods (eg. '1.0.1').
"""
version: str = (
str(self._major) + '.' +
str(self._minor) + '.' +
str(self._patch... | [
"def",
"version",
"(",
"self",
")",
"->",
"str",
":",
"version",
":",
"str",
"=",
"(",
"str",
"(",
"self",
".",
"_major",
")",
"+",
"'.'",
"+",
"str",
"(",
"self",
".",
"_minor",
")",
"+",
"'.'",
"+",
"str",
"(",
"self",
".",
"_patch",
")",
"... | Version version number property. Must be a string consisting of three
non-negative integers delimited by periods (eg. '1.0.1'). | [
"Version",
"version",
"number",
"property",
".",
"Must",
"be",
"a",
"string",
"consisting",
"of",
"three",
"non",
"-",
"negative",
"integers",
"delimited",
"by",
"periods",
"(",
"eg",
".",
"1",
".",
"0",
".",
"1",
")",
"."
] | 5ae6047c4f13db9f5e85a0c72a3dc47f05a8d7bd | https://github.com/devoperate/chronos/blob/5ae6047c4f13db9f5e85a0c72a3dc47f05a8d7bd/chronos/semver.py#L147-L157 | train |
devoperate/chronos | chronos/semver.py | SemVer.version | def version(self, version_str: str) -> None:
"""
param version
Version version number property. Must be a string consisting of three
non-negative integers delimited by periods (eg. '1.0.1').
"""
ver = []
for i in version_str.split('.'):
ver.append(int... | python | def version(self, version_str: str) -> None:
"""
param version
Version version number property. Must be a string consisting of three
non-negative integers delimited by periods (eg. '1.0.1').
"""
ver = []
for i in version_str.split('.'):
ver.append(int... | [
"def",
"version",
"(",
"self",
",",
"version_str",
":",
"str",
")",
"->",
"None",
":",
"ver",
"=",
"[",
"]",
"for",
"i",
"in",
"version_str",
".",
"split",
"(",
"'.'",
")",
":",
"ver",
".",
"append",
"(",
"int",
"(",
"i",
")",
")",
"self",
".",... | param version
Version version number property. Must be a string consisting of three
non-negative integers delimited by periods (eg. '1.0.1'). | [
"param",
"version"
] | 5ae6047c4f13db9f5e85a0c72a3dc47f05a8d7bd | https://github.com/devoperate/chronos/blob/5ae6047c4f13db9f5e85a0c72a3dc47f05a8d7bd/chronos/semver.py#L160-L171 | train |
RI-imaging/qpimage | qpimage/bg_estimate.py | estimate | def estimate(data, fit_offset="mean", fit_profile="tilt",
border_px=0, from_mask=None, ret_mask=False):
"""Estimate the background value of an image
Parameters
----------
data: np.ndarray
Data from which to compute the background value
fit_profile: str
The type of backg... | python | def estimate(data, fit_offset="mean", fit_profile="tilt",
border_px=0, from_mask=None, ret_mask=False):
"""Estimate the background value of an image
Parameters
----------
data: np.ndarray
Data from which to compute the background value
fit_profile: str
The type of backg... | [
"def",
"estimate",
"(",
"data",
",",
"fit_offset",
"=",
"\"mean\"",
",",
"fit_profile",
"=",
"\"tilt\"",
",",
"border_px",
"=",
"0",
",",
"from_mask",
"=",
"None",
",",
"ret_mask",
"=",
"False",
")",
":",
"if",
"fit_profile",
"not",
"in",
"VALID_FIT_PROFIL... | Estimate the background value of an image
Parameters
----------
data: np.ndarray
Data from which to compute the background value
fit_profile: str
The type of background profile to fit:
- "offset": offset only
- "poly2o": 2D 2nd order polynomial with mixed terms
... | [
"Estimate",
"the",
"background",
"value",
"of",
"an",
"image"
] | 863c0fce5735b4c0ae369f75c0df9a33411b2bb2 | https://github.com/RI-imaging/qpimage/blob/863c0fce5735b4c0ae369f75c0df9a33411b2bb2/qpimage/bg_estimate.py#L11-L100 | train |
RI-imaging/qpimage | qpimage/bg_estimate.py | offset_gaussian | def offset_gaussian(data):
"""Fit a gaussian model to `data` and return its center"""
nbins = 2 * int(np.ceil(np.sqrt(data.size)))
mind, maxd = data.min(), data.max()
drange = (mind - (maxd - mind) / 2, maxd + (maxd - mind) / 2)
histo = np.histogram(data, nbins, density=True, range=drange)
dx = ... | python | def offset_gaussian(data):
"""Fit a gaussian model to `data` and return its center"""
nbins = 2 * int(np.ceil(np.sqrt(data.size)))
mind, maxd = data.min(), data.max()
drange = (mind - (maxd - mind) / 2, maxd + (maxd - mind) / 2)
histo = np.histogram(data, nbins, density=True, range=drange)
dx = ... | [
"def",
"offset_gaussian",
"(",
"data",
")",
":",
"nbins",
"=",
"2",
"*",
"int",
"(",
"np",
".",
"ceil",
"(",
"np",
".",
"sqrt",
"(",
"data",
".",
"size",
")",
")",
")",
"mind",
",",
"maxd",
"=",
"data",
".",
"min",
"(",
")",
",",
"data",
".",... | Fit a gaussian model to `data` and return its center | [
"Fit",
"a",
"gaussian",
"model",
"to",
"data",
"and",
"return",
"its",
"center"
] | 863c0fce5735b4c0ae369f75c0df9a33411b2bb2 | https://github.com/RI-imaging/qpimage/blob/863c0fce5735b4c0ae369f75c0df9a33411b2bb2/qpimage/bg_estimate.py#L103-L116 | train |
RI-imaging/qpimage | qpimage/bg_estimate.py | offset_mode | def offset_mode(data):
"""Compute Mode using a histogram with `sqrt(data.size)` bins"""
nbins = int(np.ceil(np.sqrt(data.size)))
mind, maxd = data.min(), data.max()
histo = np.histogram(data, nbins, density=True, range=(mind, maxd))
dx = abs(histo[1][1] - histo[1][2]) / 2
hx = histo[1][1:] - dx
... | python | def offset_mode(data):
"""Compute Mode using a histogram with `sqrt(data.size)` bins"""
nbins = int(np.ceil(np.sqrt(data.size)))
mind, maxd = data.min(), data.max()
histo = np.histogram(data, nbins, density=True, range=(mind, maxd))
dx = abs(histo[1][1] - histo[1][2]) / 2
hx = histo[1][1:] - dx
... | [
"def",
"offset_mode",
"(",
"data",
")",
":",
"nbins",
"=",
"int",
"(",
"np",
".",
"ceil",
"(",
"np",
".",
"sqrt",
"(",
"data",
".",
"size",
")",
")",
")",
"mind",
",",
"maxd",
"=",
"data",
".",
"min",
"(",
")",
",",
"data",
".",
"max",
"(",
... | Compute Mode using a histogram with `sqrt(data.size)` bins | [
"Compute",
"Mode",
"using",
"a",
"histogram",
"with",
"sqrt",
"(",
"data",
".",
"size",
")",
"bins"
] | 863c0fce5735b4c0ae369f75c0df9a33411b2bb2 | https://github.com/RI-imaging/qpimage/blob/863c0fce5735b4c0ae369f75c0df9a33411b2bb2/qpimage/bg_estimate.py#L119-L128 | train |
RI-imaging/qpimage | qpimage/bg_estimate.py | profile_tilt | def profile_tilt(data, mask):
"""Fit a 2D tilt to `data[mask]`"""
params = lmfit.Parameters()
params.add(name="mx", value=0)
params.add(name="my", value=0)
params.add(name="off", value=np.average(data[mask]))
fr = lmfit.minimize(tilt_residual, params, args=(data, mask))
bg = tilt_model(fr.pa... | python | def profile_tilt(data, mask):
"""Fit a 2D tilt to `data[mask]`"""
params = lmfit.Parameters()
params.add(name="mx", value=0)
params.add(name="my", value=0)
params.add(name="off", value=np.average(data[mask]))
fr = lmfit.minimize(tilt_residual, params, args=(data, mask))
bg = tilt_model(fr.pa... | [
"def",
"profile_tilt",
"(",
"data",
",",
"mask",
")",
":",
"params",
"=",
"lmfit",
".",
"Parameters",
"(",
")",
"params",
".",
"add",
"(",
"name",
"=",
"\"mx\"",
",",
"value",
"=",
"0",
")",
"params",
".",
"add",
"(",
"name",
"=",
"\"my\"",
",",
... | Fit a 2D tilt to `data[mask]` | [
"Fit",
"a",
"2D",
"tilt",
"to",
"data",
"[",
"mask",
"]"
] | 863c0fce5735b4c0ae369f75c0df9a33411b2bb2 | https://github.com/RI-imaging/qpimage/blob/863c0fce5735b4c0ae369f75c0df9a33411b2bb2/qpimage/bg_estimate.py#L131-L139 | train |
RI-imaging/qpimage | qpimage/bg_estimate.py | profile_poly2o | def profile_poly2o(data, mask):
"""Fit a 2D 2nd order polynomial to `data[mask]`"""
# lmfit
params = lmfit.Parameters()
params.add(name="mx", value=0)
params.add(name="my", value=0)
params.add(name="mxy", value=0)
params.add(name="ax", value=0)
params.add(name="ay", value=0)
params.a... | python | def profile_poly2o(data, mask):
"""Fit a 2D 2nd order polynomial to `data[mask]`"""
# lmfit
params = lmfit.Parameters()
params.add(name="mx", value=0)
params.add(name="my", value=0)
params.add(name="mxy", value=0)
params.add(name="ax", value=0)
params.add(name="ay", value=0)
params.a... | [
"def",
"profile_poly2o",
"(",
"data",
",",
"mask",
")",
":",
"# lmfit",
"params",
"=",
"lmfit",
".",
"Parameters",
"(",
")",
"params",
".",
"add",
"(",
"name",
"=",
"\"mx\"",
",",
"value",
"=",
"0",
")",
"params",
".",
"add",
"(",
"name",
"=",
"\"m... | Fit a 2D 2nd order polynomial to `data[mask]` | [
"Fit",
"a",
"2D",
"2nd",
"order",
"polynomial",
"to",
"data",
"[",
"mask",
"]"
] | 863c0fce5735b4c0ae369f75c0df9a33411b2bb2 | https://github.com/RI-imaging/qpimage/blob/863c0fce5735b4c0ae369f75c0df9a33411b2bb2/qpimage/bg_estimate.py#L142-L154 | train |
RI-imaging/qpimage | qpimage/bg_estimate.py | poly2o_model | def poly2o_model(params, shape):
"""lmfit 2nd order polynomial model"""
mx = params["mx"].value
my = params["my"].value
mxy = params["mxy"].value
ax = params["ax"].value
ay = params["ay"].value
off = params["off"].value
bg = np.zeros(shape, dtype=float) + off
x = np.arange(bg.shape[0... | python | def poly2o_model(params, shape):
"""lmfit 2nd order polynomial model"""
mx = params["mx"].value
my = params["my"].value
mxy = params["mxy"].value
ax = params["ax"].value
ay = params["ay"].value
off = params["off"].value
bg = np.zeros(shape, dtype=float) + off
x = np.arange(bg.shape[0... | [
"def",
"poly2o_model",
"(",
"params",
",",
"shape",
")",
":",
"mx",
"=",
"params",
"[",
"\"mx\"",
"]",
".",
"value",
"my",
"=",
"params",
"[",
"\"my\"",
"]",
".",
"value",
"mxy",
"=",
"params",
"[",
"\"mxy\"",
"]",
".",
"value",
"ax",
"=",
"params"... | lmfit 2nd order polynomial model | [
"lmfit",
"2nd",
"order",
"polynomial",
"model"
] | 863c0fce5735b4c0ae369f75c0df9a33411b2bb2 | https://github.com/RI-imaging/qpimage/blob/863c0fce5735b4c0ae369f75c0df9a33411b2bb2/qpimage/bg_estimate.py#L157-L171 | train |
RI-imaging/qpimage | qpimage/bg_estimate.py | poly2o_residual | def poly2o_residual(params, data, mask):
"""lmfit 2nd order polynomial residuals"""
bg = poly2o_model(params, shape=data.shape)
res = (data - bg)[mask]
return res.flatten() | python | def poly2o_residual(params, data, mask):
"""lmfit 2nd order polynomial residuals"""
bg = poly2o_model(params, shape=data.shape)
res = (data - bg)[mask]
return res.flatten() | [
"def",
"poly2o_residual",
"(",
"params",
",",
"data",
",",
"mask",
")",
":",
"bg",
"=",
"poly2o_model",
"(",
"params",
",",
"shape",
"=",
"data",
".",
"shape",
")",
"res",
"=",
"(",
"data",
"-",
"bg",
")",
"[",
"mask",
"]",
"return",
"res",
".",
... | lmfit 2nd order polynomial residuals | [
"lmfit",
"2nd",
"order",
"polynomial",
"residuals"
] | 863c0fce5735b4c0ae369f75c0df9a33411b2bb2 | https://github.com/RI-imaging/qpimage/blob/863c0fce5735b4c0ae369f75c0df9a33411b2bb2/qpimage/bg_estimate.py#L174-L178 | train |
RI-imaging/qpimage | qpimage/bg_estimate.py | tilt_model | def tilt_model(params, shape):
"""lmfit tilt model"""
mx = params["mx"].value
my = params["my"].value
off = params["off"].value
bg = np.zeros(shape, dtype=float) + off
x = np.arange(bg.shape[0]) - bg.shape[0] // 2
y = np.arange(bg.shape[1]) - bg.shape[1] // 2
x = x.reshape(-1, 1)
y =... | python | def tilt_model(params, shape):
"""lmfit tilt model"""
mx = params["mx"].value
my = params["my"].value
off = params["off"].value
bg = np.zeros(shape, dtype=float) + off
x = np.arange(bg.shape[0]) - bg.shape[0] // 2
y = np.arange(bg.shape[1]) - bg.shape[1] // 2
x = x.reshape(-1, 1)
y =... | [
"def",
"tilt_model",
"(",
"params",
",",
"shape",
")",
":",
"mx",
"=",
"params",
"[",
"\"mx\"",
"]",
".",
"value",
"my",
"=",
"params",
"[",
"\"my\"",
"]",
".",
"value",
"off",
"=",
"params",
"[",
"\"off\"",
"]",
".",
"value",
"bg",
"=",
"np",
".... | lmfit tilt model | [
"lmfit",
"tilt",
"model"
] | 863c0fce5735b4c0ae369f75c0df9a33411b2bb2 | https://github.com/RI-imaging/qpimage/blob/863c0fce5735b4c0ae369f75c0df9a33411b2bb2/qpimage/bg_estimate.py#L181-L192 | train |
RI-imaging/qpimage | qpimage/bg_estimate.py | tilt_residual | def tilt_residual(params, data, mask):
"""lmfit tilt residuals"""
bg = tilt_model(params, shape=data.shape)
res = (data - bg)[mask]
return res.flatten() | python | def tilt_residual(params, data, mask):
"""lmfit tilt residuals"""
bg = tilt_model(params, shape=data.shape)
res = (data - bg)[mask]
return res.flatten() | [
"def",
"tilt_residual",
"(",
"params",
",",
"data",
",",
"mask",
")",
":",
"bg",
"=",
"tilt_model",
"(",
"params",
",",
"shape",
"=",
"data",
".",
"shape",
")",
"res",
"=",
"(",
"data",
"-",
"bg",
")",
"[",
"mask",
"]",
"return",
"res",
".",
"fla... | lmfit tilt residuals | [
"lmfit",
"tilt",
"residuals"
] | 863c0fce5735b4c0ae369f75c0df9a33411b2bb2 | https://github.com/RI-imaging/qpimage/blob/863c0fce5735b4c0ae369f75c0df9a33411b2bb2/qpimage/bg_estimate.py#L195-L199 | train |
devoperate/chronos | chronos/cli.py | main | def main(cmd_args: list = None) -> None:
"""
:cmd_args: An optional list of command line arguments.
Main function of chronos CLI tool.
"""
parser = argparse.ArgumentParser(description='Auto-versioning utility.')
subparsers = parser.add_subparsers()
infer_parser = subparsers.add_parser('inf... | python | def main(cmd_args: list = None) -> None:
"""
:cmd_args: An optional list of command line arguments.
Main function of chronos CLI tool.
"""
parser = argparse.ArgumentParser(description='Auto-versioning utility.')
subparsers = parser.add_subparsers()
infer_parser = subparsers.add_parser('inf... | [
"def",
"main",
"(",
"cmd_args",
":",
"list",
"=",
"None",
")",
"->",
"None",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"'Auto-versioning utility.'",
")",
"subparsers",
"=",
"parser",
".",
"add_subparsers",
"(",
")",
"inf... | :cmd_args: An optional list of command line arguments.
Main function of chronos CLI tool. | [
":",
"cmd_args",
":",
"An",
"optional",
"list",
"of",
"command",
"line",
"arguments",
"."
] | 5ae6047c4f13db9f5e85a0c72a3dc47f05a8d7bd | https://github.com/devoperate/chronos/blob/5ae6047c4f13db9f5e85a0c72a3dc47f05a8d7bd/chronos/cli.py#L18-L48 | train |
devoperate/chronos | chronos/cli.py | infer | def infer(args: argparse.Namespace) -> None:
"""
:args: An argparse.Namespace object.
This is the function called when the 'infer' sub-command is passed as an
argument to the CLI.
"""
try:
last_tag = last_git_release_tag(git_tags())
except NoGitTagsException:
print(SemVer(0,... | python | def infer(args: argparse.Namespace) -> None:
"""
:args: An argparse.Namespace object.
This is the function called when the 'infer' sub-command is passed as an
argument to the CLI.
"""
try:
last_tag = last_git_release_tag(git_tags())
except NoGitTagsException:
print(SemVer(0,... | [
"def",
"infer",
"(",
"args",
":",
"argparse",
".",
"Namespace",
")",
"->",
"None",
":",
"try",
":",
"last_tag",
"=",
"last_git_release_tag",
"(",
"git_tags",
"(",
")",
")",
"except",
"NoGitTagsException",
":",
"print",
"(",
"SemVer",
"(",
"0",
",",
"1",
... | :args: An argparse.Namespace object.
This is the function called when the 'infer' sub-command is passed as an
argument to the CLI. | [
":",
"args",
":",
"An",
"argparse",
".",
"Namespace",
"object",
"."
] | 5ae6047c4f13db9f5e85a0c72a3dc47f05a8d7bd | https://github.com/devoperate/chronos/blob/5ae6047c4f13db9f5e85a0c72a3dc47f05a8d7bd/chronos/cli.py#L51-L76 | train |
devoperate/chronos | chronos/cli.py | bump | def bump(args: argparse.Namespace) -> None:
"""
:args: An argparse.Namespace object.
This function is bound to the 'bump' sub-command. It increments the version
integer of the user's choice ('major', 'minor', or 'patch').
"""
try:
last_tag = last_git_release_tag(git_tags())
except N... | python | def bump(args: argparse.Namespace) -> None:
"""
:args: An argparse.Namespace object.
This function is bound to the 'bump' sub-command. It increments the version
integer of the user's choice ('major', 'minor', or 'patch').
"""
try:
last_tag = last_git_release_tag(git_tags())
except N... | [
"def",
"bump",
"(",
"args",
":",
"argparse",
".",
"Namespace",
")",
"->",
"None",
":",
"try",
":",
"last_tag",
"=",
"last_git_release_tag",
"(",
"git_tags",
"(",
")",
")",
"except",
"NoGitTagsException",
":",
"print",
"(",
"SemVer",
"(",
"0",
",",
"1",
... | :args: An argparse.Namespace object.
This function is bound to the 'bump' sub-command. It increments the version
integer of the user's choice ('major', 'minor', or 'patch'). | [
":",
"args",
":",
"An",
"argparse",
".",
"Namespace",
"object",
"."
] | 5ae6047c4f13db9f5e85a0c72a3dc47f05a8d7bd | https://github.com/devoperate/chronos/blob/5ae6047c4f13db9f5e85a0c72a3dc47f05a8d7bd/chronos/cli.py#L91-L111 | train |
RI-imaging/qpimage | qpimage/holo.py | find_sideband | def find_sideband(ft_data, which=+1, copy=True):
"""Find the side band position of a hologram
The hologram is Fourier-transformed and the side band
is determined by finding the maximum amplitude in
Fourier space.
Parameters
----------
ft_data: 2d ndarray
Fourier transform of the ho... | python | def find_sideband(ft_data, which=+1, copy=True):
"""Find the side band position of a hologram
The hologram is Fourier-transformed and the side band
is determined by finding the maximum amplitude in
Fourier space.
Parameters
----------
ft_data: 2d ndarray
Fourier transform of the ho... | [
"def",
"find_sideband",
"(",
"ft_data",
",",
"which",
"=",
"+",
"1",
",",
"copy",
"=",
"True",
")",
":",
"if",
"copy",
":",
"ft_data",
"=",
"ft_data",
".",
"copy",
"(",
")",
"if",
"which",
"not",
"in",
"[",
"+",
"1",
",",
"-",
"1",
"]",
":",
... | Find the side band position of a hologram
The hologram is Fourier-transformed and the side band
is determined by finding the maximum amplitude in
Fourier space.
Parameters
----------
ft_data: 2d ndarray
Fourier transform of the hologram image
which: +1 or -1
which sideband ... | [
"Find",
"the",
"side",
"band",
"position",
"of",
"a",
"hologram"
] | 863c0fce5735b4c0ae369f75c0df9a33411b2bb2 | https://github.com/RI-imaging/qpimage/blob/863c0fce5735b4c0ae369f75c0df9a33411b2bb2/qpimage/holo.py#L5-L58 | train |
RI-imaging/qpimage | qpimage/holo.py | fourier2dpad | def fourier2dpad(data, zero_pad=True):
"""Compute the 2D Fourier transform with zero padding
Parameters
----------
data: 2d fload ndarray
real-valued image data
zero_pad: bool
perform zero-padding to next order of 2
"""
if zero_pad:
# zero padding size is next order ... | python | def fourier2dpad(data, zero_pad=True):
"""Compute the 2D Fourier transform with zero padding
Parameters
----------
data: 2d fload ndarray
real-valued image data
zero_pad: bool
perform zero-padding to next order of 2
"""
if zero_pad:
# zero padding size is next order ... | [
"def",
"fourier2dpad",
"(",
"data",
",",
"zero_pad",
"=",
"True",
")",
":",
"if",
"zero_pad",
":",
"# zero padding size is next order of 2",
"(",
"N",
",",
"M",
")",
"=",
"data",
".",
"shape",
"order",
"=",
"np",
".",
"int",
"(",
"max",
"(",
"64.",
","... | Compute the 2D Fourier transform with zero padding
Parameters
----------
data: 2d fload ndarray
real-valued image data
zero_pad: bool
perform zero-padding to next order of 2 | [
"Compute",
"the",
"2D",
"Fourier",
"transform",
"with",
"zero",
"padding"
] | 863c0fce5735b4c0ae369f75c0df9a33411b2bb2 | https://github.com/RI-imaging/qpimage/blob/863c0fce5735b4c0ae369f75c0df9a33411b2bb2/qpimage/holo.py#L61-L84 | train |
RI-imaging/qpimage | qpimage/holo.py | get_field | def get_field(hologram, sideband=+1, filter_name="disk", filter_size=1 / 3,
subtract_mean=True, zero_pad=True, copy=True):
"""Compute the complex field from a hologram using Fourier analysis
Parameters
----------
hologram: real-valued 2d ndarray
hologram data
sideband: +1, -1,... | python | def get_field(hologram, sideband=+1, filter_name="disk", filter_size=1 / 3,
subtract_mean=True, zero_pad=True, copy=True):
"""Compute the complex field from a hologram using Fourier analysis
Parameters
----------
hologram: real-valued 2d ndarray
hologram data
sideband: +1, -1,... | [
"def",
"get_field",
"(",
"hologram",
",",
"sideband",
"=",
"+",
"1",
",",
"filter_name",
"=",
"\"disk\"",
",",
"filter_size",
"=",
"1",
"/",
"3",
",",
"subtract_mean",
"=",
"True",
",",
"zero_pad",
"=",
"True",
",",
"copy",
"=",
"True",
")",
":",
"if... | Compute the complex field from a hologram using Fourier analysis
Parameters
----------
hologram: real-valued 2d ndarray
hologram data
sideband: +1, -1, or tuple of (float, float)
specifies the location of the sideband:
- +1: sideband in the upper half in Fourier space,
... | [
"Compute",
"the",
"complex",
"field",
"from",
"a",
"hologram",
"using",
"Fourier",
"analysis"
] | 863c0fce5735b4c0ae369f75c0df9a33411b2bb2 | https://github.com/RI-imaging/qpimage/blob/863c0fce5735b4c0ae369f75c0df9a33411b2bb2/qpimage/holo.py#L87-L219 | train |
RI-imaging/qpimage | qpimage/core.py | copyh5 | def copyh5(inh5, outh5):
"""Recursively copy all hdf5 data from one group to another
Data from links is copied.
Parameters
----------
inh5: str, h5py.File, or h5py.Group
The input hdf5 data. This can be either a file name or
an hdf5 object.
outh5: str, h5py.File, h5py.Group, or... | python | def copyh5(inh5, outh5):
"""Recursively copy all hdf5 data from one group to another
Data from links is copied.
Parameters
----------
inh5: str, h5py.File, or h5py.Group
The input hdf5 data. This can be either a file name or
an hdf5 object.
outh5: str, h5py.File, h5py.Group, or... | [
"def",
"copyh5",
"(",
"inh5",
",",
"outh5",
")",
":",
"if",
"not",
"isinstance",
"(",
"inh5",
",",
"h5py",
".",
"Group",
")",
":",
"inh5",
"=",
"h5py",
".",
"File",
"(",
"inh5",
",",
"mode",
"=",
"\"r\"",
")",
"if",
"outh5",
"is",
"None",
":",
... | Recursively copy all hdf5 data from one group to another
Data from links is copied.
Parameters
----------
inh5: str, h5py.File, or h5py.Group
The input hdf5 data. This can be either a file name or
an hdf5 object.
outh5: str, h5py.File, h5py.Group, or None
The output hdf5 da... | [
"Recursively",
"copy",
"all",
"hdf5",
"data",
"from",
"one",
"group",
"to",
"another"
] | 863c0fce5735b4c0ae369f75c0df9a33411b2bb2 | https://github.com/RI-imaging/qpimage/blob/863c0fce5735b4c0ae369f75c0df9a33411b2bb2/qpimage/core.py#L597-L655 | train |
RI-imaging/qpimage | qpimage/core.py | QPImage._conv_which_data | def _conv_which_data(which_data):
"""Convert which data to string or tuple
This function improves user convenience,
as `which_data` may be of several types
(str, ,str with spaces and commas, list, tuple) which
is internally handled by this method.
"""
if isinstan... | python | def _conv_which_data(which_data):
"""Convert which data to string or tuple
This function improves user convenience,
as `which_data` may be of several types
(str, ,str with spaces and commas, list, tuple) which
is internally handled by this method.
"""
if isinstan... | [
"def",
"_conv_which_data",
"(",
"which_data",
")",
":",
"if",
"isinstance",
"(",
"which_data",
",",
"str",
")",
":",
"which_data",
"=",
"which_data",
".",
"lower",
"(",
")",
".",
"strip",
"(",
")",
"if",
"which_data",
".",
"count",
"(",
"\",\"",
")",
"... | Convert which data to string or tuple
This function improves user convenience,
as `which_data` may be of several types
(str, ,str with spaces and commas, list, tuple) which
is internally handled by this method. | [
"Convert",
"which",
"data",
"to",
"string",
"or",
"tuple"
] | 863c0fce5735b4c0ae369f75c0df9a33411b2bb2 | https://github.com/RI-imaging/qpimage/blob/863c0fce5735b4c0ae369f75c0df9a33411b2bb2/qpimage/core.py#L208-L237 | train |
RI-imaging/qpimage | qpimage/core.py | QPImage._get_amp_pha | def _get_amp_pha(self, data, which_data):
"""Convert input data to phase and amplitude
Parameters
----------
data: 2d ndarray (float or complex) or list
The experimental data (see `which_data`)
which_data: str
String or comma-separated list of strings ind... | python | def _get_amp_pha(self, data, which_data):
"""Convert input data to phase and amplitude
Parameters
----------
data: 2d ndarray (float or complex) or list
The experimental data (see `which_data`)
which_data: str
String or comma-separated list of strings ind... | [
"def",
"_get_amp_pha",
"(",
"self",
",",
"data",
",",
"which_data",
")",
":",
"which_data",
"=",
"QPImage",
".",
"_conv_which_data",
"(",
"which_data",
")",
"if",
"which_data",
"not",
"in",
"VALID_INPUT_DATA",
":",
"msg",
"=",
"\"`which_data` must be one of {}!\""... | Convert input data to phase and amplitude
Parameters
----------
data: 2d ndarray (float or complex) or list
The experimental data (see `which_data`)
which_data: str
String or comma-separated list of strings indicating
the order and type of input data.... | [
"Convert",
"input",
"data",
"to",
"phase",
"and",
"amplitude"
] | 863c0fce5735b4c0ae369f75c0df9a33411b2bb2 | https://github.com/RI-imaging/qpimage/blob/863c0fce5735b4c0ae369f75c0df9a33411b2bb2/qpimage/core.py#L239-L294 | train |
RI-imaging/qpimage | qpimage/core.py | QPImage.info | def info(self):
"""list of tuples with QPImage meta data"""
info = []
# meta data
meta = self.meta
for key in meta:
info.append((key, self.meta[key]))
# background correction
for imdat in [self._amp, self._pha]:
info += imdat.info
r... | python | def info(self):
"""list of tuples with QPImage meta data"""
info = []
# meta data
meta = self.meta
for key in meta:
info.append((key, self.meta[key]))
# background correction
for imdat in [self._amp, self._pha]:
info += imdat.info
r... | [
"def",
"info",
"(",
"self",
")",
":",
"info",
"=",
"[",
"]",
"# meta data",
"meta",
"=",
"self",
".",
"meta",
"for",
"key",
"in",
"meta",
":",
"info",
".",
"append",
"(",
"(",
"key",
",",
"self",
".",
"meta",
"[",
"key",
"]",
")",
")",
"# backg... | list of tuples with QPImage meta data | [
"list",
"of",
"tuples",
"with",
"QPImage",
"meta",
"data"
] | 863c0fce5735b4c0ae369f75c0df9a33411b2bb2 | https://github.com/RI-imaging/qpimage/blob/863c0fce5735b4c0ae369f75c0df9a33411b2bb2/qpimage/core.py#L322-L332 | train |
RI-imaging/qpimage | qpimage/core.py | QPImage.clear_bg | def clear_bg(self, which_data=("amplitude", "phase"), keys="fit"):
"""Clear background correction
Parameters
----------
which_data: str or list of str
From which type of data to remove the background
information. The list contains either "amplitude",
... | python | def clear_bg(self, which_data=("amplitude", "phase"), keys="fit"):
"""Clear background correction
Parameters
----------
which_data: str or list of str
From which type of data to remove the background
information. The list contains either "amplitude",
... | [
"def",
"clear_bg",
"(",
"self",
",",
"which_data",
"=",
"(",
"\"amplitude\"",
",",
"\"phase\"",
")",
",",
"keys",
"=",
"\"fit\"",
")",
":",
"which_data",
"=",
"QPImage",
".",
"_conv_which_data",
"(",
"which_data",
")",
"if",
"isinstance",
"(",
"keys",
",",... | Clear background correction
Parameters
----------
which_data: str or list of str
From which type of data to remove the background
information. The list contains either "amplitude",
"phase", or both.
keys: str or list of str
Which type of b... | [
"Clear",
"background",
"correction"
] | 863c0fce5735b4c0ae369f75c0df9a33411b2bb2 | https://github.com/RI-imaging/qpimage/blob/863c0fce5735b4c0ae369f75c0df9a33411b2bb2/qpimage/core.py#L359-L392 | train |
RI-imaging/qpimage | qpimage/core.py | QPImage.compute_bg | def compute_bg(self, which_data="phase",
fit_offset="mean", fit_profile="tilt",
border_m=0, border_perc=0, border_px=0,
from_mask=None, ret_mask=False):
"""Compute background correction
Parameters
----------
which_data: str or lis... | python | def compute_bg(self, which_data="phase",
fit_offset="mean", fit_profile="tilt",
border_m=0, border_perc=0, border_px=0,
from_mask=None, ret_mask=False):
"""Compute background correction
Parameters
----------
which_data: str or lis... | [
"def",
"compute_bg",
"(",
"self",
",",
"which_data",
"=",
"\"phase\"",
",",
"fit_offset",
"=",
"\"mean\"",
",",
"fit_profile",
"=",
"\"tilt\"",
",",
"border_m",
"=",
"0",
",",
"border_perc",
"=",
"0",
",",
"border_px",
"=",
"0",
",",
"from_mask",
"=",
"N... | Compute background correction
Parameters
----------
which_data: str or list of str
From which type of data to remove the background
information. The list contains either "amplitude",
"phase", or both.
fit_profile: str
The type of backgroun... | [
"Compute",
"background",
"correction"
] | 863c0fce5735b4c0ae369f75c0df9a33411b2bb2 | https://github.com/RI-imaging/qpimage/blob/863c0fce5735b4c0ae369f75c0df9a33411b2bb2/qpimage/core.py#L394-L494 | train |
RI-imaging/qpimage | qpimage/core.py | QPImage.copy | def copy(self, h5file=None):
"""Create a copy of the current instance
This is done by recursively copying the underlying hdf5 data.
Parameters
----------
h5file: str, h5py.File, h5py.Group, or None
see `QPImage.__init__`
"""
h5 = copyh5(self.h5, h5fi... | python | def copy(self, h5file=None):
"""Create a copy of the current instance
This is done by recursively copying the underlying hdf5 data.
Parameters
----------
h5file: str, h5py.File, h5py.Group, or None
see `QPImage.__init__`
"""
h5 = copyh5(self.h5, h5fi... | [
"def",
"copy",
"(",
"self",
",",
"h5file",
"=",
"None",
")",
":",
"h5",
"=",
"copyh5",
"(",
"self",
".",
"h5",
",",
"h5file",
")",
"return",
"QPImage",
"(",
"h5file",
"=",
"h5",
",",
"h5dtype",
"=",
"self",
".",
"h5dtype",
")"
] | Create a copy of the current instance
This is done by recursively copying the underlying hdf5 data.
Parameters
----------
h5file: str, h5py.File, h5py.Group, or None
see `QPImage.__init__` | [
"Create",
"a",
"copy",
"of",
"the",
"current",
"instance"
] | 863c0fce5735b4c0ae369f75c0df9a33411b2bb2 | https://github.com/RI-imaging/qpimage/blob/863c0fce5735b4c0ae369f75c0df9a33411b2bb2/qpimage/core.py#L496-L507 | train |
RI-imaging/qpimage | qpimage/core.py | QPImage.refocus | def refocus(self, distance, method="helmholtz", h5file=None, h5mode="a"):
"""Compute a numerically refocused QPImage
Parameters
----------
distance: float
Focusing distance [m]
method: str
Refocusing method, one of ["helmholtz","fresnel"]
h5file: ... | python | def refocus(self, distance, method="helmholtz", h5file=None, h5mode="a"):
"""Compute a numerically refocused QPImage
Parameters
----------
distance: float
Focusing distance [m]
method: str
Refocusing method, one of ["helmholtz","fresnel"]
h5file: ... | [
"def",
"refocus",
"(",
"self",
",",
"distance",
",",
"method",
"=",
"\"helmholtz\"",
",",
"h5file",
"=",
"None",
",",
"h5mode",
"=",
"\"a\"",
")",
":",
"field2",
"=",
"nrefocus",
".",
"refocus",
"(",
"field",
"=",
"self",
".",
"field",
",",
"d",
"=",... | Compute a numerically refocused QPImage
Parameters
----------
distance: float
Focusing distance [m]
method: str
Refocusing method, one of ["helmholtz","fresnel"]
h5file: str, h5py.Group, h5py.File, or None
A path to an hdf5 data file where the... | [
"Compute",
"a",
"numerically",
"refocused",
"QPImage"
] | 863c0fce5735b4c0ae369f75c0df9a33411b2bb2 | https://github.com/RI-imaging/qpimage/blob/863c0fce5735b4c0ae369f75c0df9a33411b2bb2/qpimage/core.py#L509-L564 | train |
RI-imaging/qpimage | qpimage/core.py | QPImage.set_bg_data | def set_bg_data(self, bg_data, which_data=None):
"""Set background amplitude and phase data
Parameters
----------
bg_data: 2d ndarray (float or complex), list, QPImage, or `None`
The background data (must be same type as `data`).
If set to `None`, the background ... | python | def set_bg_data(self, bg_data, which_data=None):
"""Set background amplitude and phase data
Parameters
----------
bg_data: 2d ndarray (float or complex), list, QPImage, or `None`
The background data (must be same type as `data`).
If set to `None`, the background ... | [
"def",
"set_bg_data",
"(",
"self",
",",
"bg_data",
",",
"which_data",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"bg_data",
",",
"QPImage",
")",
":",
"if",
"which_data",
"is",
"not",
"None",
":",
"msg",
"=",
"\"`which_data` must not be set if `bg_data` is... | Set background amplitude and phase data
Parameters
----------
bg_data: 2d ndarray (float or complex), list, QPImage, or `None`
The background data (must be same type as `data`).
If set to `None`, the background data is reset.
which_data: str
String or... | [
"Set",
"background",
"amplitude",
"and",
"phase",
"data"
] | 863c0fce5735b4c0ae369f75c0df9a33411b2bb2 | https://github.com/RI-imaging/qpimage/blob/863c0fce5735b4c0ae369f75c0df9a33411b2bb2/qpimage/core.py#L566-L594 | train |
RI-imaging/qpimage | qpimage/series.py | QPSeries.add_qpimage | def add_qpimage(self, qpi, identifier=None, bg_from_idx=None):
"""Add a QPImage instance to the QPSeries
Parameters
----------
qpi: qpimage.QPImage
The QPImage that is added to the series
identifier: str
Identifier key for `qpi`
bg_from_idx: int o... | python | def add_qpimage(self, qpi, identifier=None, bg_from_idx=None):
"""Add a QPImage instance to the QPSeries
Parameters
----------
qpi: qpimage.QPImage
The QPImage that is added to the series
identifier: str
Identifier key for `qpi`
bg_from_idx: int o... | [
"def",
"add_qpimage",
"(",
"self",
",",
"qpi",
",",
"identifier",
"=",
"None",
",",
"bg_from_idx",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"qpi",
",",
"QPImage",
")",
":",
"raise",
"ValueError",
"(",
"\"`fli` must be instance of QPImage!\"",
"... | Add a QPImage instance to the QPSeries
Parameters
----------
qpi: qpimage.QPImage
The QPImage that is added to the series
identifier: str
Identifier key for `qpi`
bg_from_idx: int or None
Use the background data from the data stored in this in... | [
"Add",
"a",
"QPImage",
"instance",
"to",
"the",
"QPSeries"
] | 863c0fce5735b4c0ae369f75c0df9a33411b2bb2 | https://github.com/RI-imaging/qpimage/blob/863c0fce5735b4c0ae369f75c0df9a33411b2bb2/qpimage/series.py#L130-L168 | train |
RI-imaging/qpimage | qpimage/series.py | QPSeries.get_qpimage | def get_qpimage(self, index):
"""Return a single QPImage of the series
Parameters
----------
index: int or str
Index or identifier of the QPImage
Notes
-----
Instead of ``qps.get_qpimage(index)``, it is possible
to use the short-hand ``qps[in... | python | def get_qpimage(self, index):
"""Return a single QPImage of the series
Parameters
----------
index: int or str
Index or identifier of the QPImage
Notes
-----
Instead of ``qps.get_qpimage(index)``, it is possible
to use the short-hand ``qps[in... | [
"def",
"get_qpimage",
"(",
"self",
",",
"index",
")",
":",
"if",
"isinstance",
"(",
"index",
",",
"str",
")",
":",
"# search for the identifier",
"for",
"ii",
"in",
"range",
"(",
"len",
"(",
"self",
")",
")",
":",
"qpi",
"=",
"self",
"[",
"ii",
"]",
... | Return a single QPImage of the series
Parameters
----------
index: int or str
Index or identifier of the QPImage
Notes
-----
Instead of ``qps.get_qpimage(index)``, it is possible
to use the short-hand ``qps[index]``. | [
"Return",
"a",
"single",
"QPImage",
"of",
"the",
"series"
] | 863c0fce5735b4c0ae369f75c0df9a33411b2bb2 | https://github.com/RI-imaging/qpimage/blob/863c0fce5735b4c0ae369f75c0df9a33411b2bb2/qpimage/series.py#L170-L208 | train |
Parquery/icontract | precommit.py | main | def main() -> int:
""""
Main routine
"""
parser = argparse.ArgumentParser()
parser.add_argument(
"--overwrite",
help="Overwrites the unformatted source files with the well-formatted code in place. "
"If not set, an exception is raised if any of the files do not conform to the... | python | def main() -> int:
""""
Main routine
"""
parser = argparse.ArgumentParser()
parser.add_argument(
"--overwrite",
help="Overwrites the unformatted source files with the well-formatted code in place. "
"If not set, an exception is raised if any of the files do not conform to the... | [
"def",
"main",
"(",
")",
"->",
"int",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
")",
"parser",
".",
"add_argument",
"(",
"\"--overwrite\"",
",",
"help",
"=",
"\"Overwrites the unformatted source files with the well-formatted code in place. \"",
"\"If n... | Main routine | [
"Main",
"routine"
] | 846e3187869a9ba790e9b893c98e5055e1cce274 | https://github.com/Parquery/icontract/blob/846e3187869a9ba790e9b893c98e5055e1cce274/precommit.py#L10-L72 | train |
Parquery/icontract | icontract/_metaclass.py | _collapse_invariants | def _collapse_invariants(bases: List[type], namespace: MutableMapping[str, Any]) -> None:
"""Collect invariants from the bases and merge them with the invariants in the namespace."""
invariants = [] # type: List[Contract]
# Add invariants of the bases
for base in bases:
if hasattr(base, "__inv... | python | def _collapse_invariants(bases: List[type], namespace: MutableMapping[str, Any]) -> None:
"""Collect invariants from the bases and merge them with the invariants in the namespace."""
invariants = [] # type: List[Contract]
# Add invariants of the bases
for base in bases:
if hasattr(base, "__inv... | [
"def",
"_collapse_invariants",
"(",
"bases",
":",
"List",
"[",
"type",
"]",
",",
"namespace",
":",
"MutableMapping",
"[",
"str",
",",
"Any",
"]",
")",
"->",
"None",
":",
"invariants",
"=",
"[",
"]",
"# type: List[Contract]",
"# Add invariants of the bases",
"f... | Collect invariants from the bases and merge them with the invariants in the namespace. | [
"Collect",
"invariants",
"from",
"the",
"bases",
"and",
"merge",
"them",
"with",
"the",
"invariants",
"in",
"the",
"namespace",
"."
] | 846e3187869a9ba790e9b893c98e5055e1cce274 | https://github.com/Parquery/icontract/blob/846e3187869a9ba790e9b893c98e5055e1cce274/icontract/_metaclass.py#L16-L31 | train |
Parquery/icontract | icontract/_metaclass.py | _collapse_preconditions | def _collapse_preconditions(base_preconditions: List[List[Contract]], bases_have_func: bool,
preconditions: List[List[Contract]], func: Callable[..., Any]) -> List[List[Contract]]:
"""
Collapse function preconditions with the preconditions collected from the base classes.
:param... | python | def _collapse_preconditions(base_preconditions: List[List[Contract]], bases_have_func: bool,
preconditions: List[List[Contract]], func: Callable[..., Any]) -> List[List[Contract]]:
"""
Collapse function preconditions with the preconditions collected from the base classes.
:param... | [
"def",
"_collapse_preconditions",
"(",
"base_preconditions",
":",
"List",
"[",
"List",
"[",
"Contract",
"]",
"]",
",",
"bases_have_func",
":",
"bool",
",",
"preconditions",
":",
"List",
"[",
"List",
"[",
"Contract",
"]",
"]",
",",
"func",
":",
"Callable",
... | Collapse function preconditions with the preconditions collected from the base classes.
:param base_preconditions: preconditions collected from the base classes (grouped by base class)
:param bases_have_func: True if one of the base classes has the function
:param preconditions: preconditions of the functi... | [
"Collapse",
"function",
"preconditions",
"with",
"the",
"preconditions",
"collected",
"from",
"the",
"base",
"classes",
"."
] | 846e3187869a9ba790e9b893c98e5055e1cce274 | https://github.com/Parquery/icontract/blob/846e3187869a9ba790e9b893c98e5055e1cce274/icontract/_metaclass.py#L34-L51 | train |
Parquery/icontract | icontract/_metaclass.py | _collapse_snapshots | def _collapse_snapshots(base_snapshots: List[Snapshot], snapshots: List[Snapshot]) -> List[Snapshot]:
"""
Collapse snapshots of pre-invocation values with the snapshots collected from the base classes.
:param base_snapshots: snapshots collected from the base classes
:param snapshots: snapshots of the f... | python | def _collapse_snapshots(base_snapshots: List[Snapshot], snapshots: List[Snapshot]) -> List[Snapshot]:
"""
Collapse snapshots of pre-invocation values with the snapshots collected from the base classes.
:param base_snapshots: snapshots collected from the base classes
:param snapshots: snapshots of the f... | [
"def",
"_collapse_snapshots",
"(",
"base_snapshots",
":",
"List",
"[",
"Snapshot",
"]",
",",
"snapshots",
":",
"List",
"[",
"Snapshot",
"]",
")",
"->",
"List",
"[",
"Snapshot",
"]",
":",
"seen_names",
"=",
"set",
"(",
")",
"# type: Set[str]",
"collapsed",
... | Collapse snapshots of pre-invocation values with the snapshots collected from the base classes.
:param base_snapshots: snapshots collected from the base classes
:param snapshots: snapshots of the function (before the collapse)
:return: collapsed sequence of snapshots | [
"Collapse",
"snapshots",
"of",
"pre",
"-",
"invocation",
"values",
"with",
"the",
"snapshots",
"collected",
"from",
"the",
"base",
"classes",
"."
] | 846e3187869a9ba790e9b893c98e5055e1cce274 | https://github.com/Parquery/icontract/blob/846e3187869a9ba790e9b893c98e5055e1cce274/icontract/_metaclass.py#L54-L73 | train |
Parquery/icontract | icontract/_metaclass.py | _collapse_postconditions | def _collapse_postconditions(base_postconditions: List[Contract], postconditions: List[Contract]) -> List[Contract]:
"""
Collapse function postconditions with the postconditions collected from the base classes.
:param base_postconditions: postconditions collected from the base classes
:param postcondit... | python | def _collapse_postconditions(base_postconditions: List[Contract], postconditions: List[Contract]) -> List[Contract]:
"""
Collapse function postconditions with the postconditions collected from the base classes.
:param base_postconditions: postconditions collected from the base classes
:param postcondit... | [
"def",
"_collapse_postconditions",
"(",
"base_postconditions",
":",
"List",
"[",
"Contract",
"]",
",",
"postconditions",
":",
"List",
"[",
"Contract",
"]",
")",
"->",
"List",
"[",
"Contract",
"]",
":",
"return",
"base_postconditions",
"+",
"postconditions"
] | Collapse function postconditions with the postconditions collected from the base classes.
:param base_postconditions: postconditions collected from the base classes
:param postconditions: postconditions of the function (before the collapse)
:return: collapsed sequence of postconditions | [
"Collapse",
"function",
"postconditions",
"with",
"the",
"postconditions",
"collected",
"from",
"the",
"base",
"classes",
"."
] | 846e3187869a9ba790e9b893c98e5055e1cce274 | https://github.com/Parquery/icontract/blob/846e3187869a9ba790e9b893c98e5055e1cce274/icontract/_metaclass.py#L76-L84 | train |
Parquery/icontract | icontract/_metaclass.py | _decorate_namespace_function | def _decorate_namespace_function(bases: List[type], namespace: MutableMapping[str, Any], key: str) -> None:
"""Collect preconditions and postconditions from the bases and decorate the function at the ``key``."""
# pylint: disable=too-many-branches
# pylint: disable=too-many-locals
value = namespace[key... | python | def _decorate_namespace_function(bases: List[type], namespace: MutableMapping[str, Any], key: str) -> None:
"""Collect preconditions and postconditions from the bases and decorate the function at the ``key``."""
# pylint: disable=too-many-branches
# pylint: disable=too-many-locals
value = namespace[key... | [
"def",
"_decorate_namespace_function",
"(",
"bases",
":",
"List",
"[",
"type",
"]",
",",
"namespace",
":",
"MutableMapping",
"[",
"str",
",",
"Any",
"]",
",",
"key",
":",
"str",
")",
"->",
"None",
":",
"# pylint: disable=too-many-branches",
"# pylint: disable=to... | Collect preconditions and postconditions from the bases and decorate the function at the ``key``. | [
"Collect",
"preconditions",
"and",
"postconditions",
"from",
"the",
"bases",
"and",
"decorate",
"the",
"function",
"at",
"the",
"key",
"."
] | 846e3187869a9ba790e9b893c98e5055e1cce274 | https://github.com/Parquery/icontract/blob/846e3187869a9ba790e9b893c98e5055e1cce274/icontract/_metaclass.py#L87-L169 | train |
Parquery/icontract | icontract/_metaclass.py | _decorate_namespace_property | def _decorate_namespace_property(bases: List[type], namespace: MutableMapping[str, Any], key: str) -> None:
"""Collect contracts for all getters/setters/deleters corresponding to ``key`` and decorate them."""
# pylint: disable=too-many-locals
# pylint: disable=too-many-branches
# pylint: disable=too-man... | python | def _decorate_namespace_property(bases: List[type], namespace: MutableMapping[str, Any], key: str) -> None:
"""Collect contracts for all getters/setters/deleters corresponding to ``key`` and decorate them."""
# pylint: disable=too-many-locals
# pylint: disable=too-many-branches
# pylint: disable=too-man... | [
"def",
"_decorate_namespace_property",
"(",
"bases",
":",
"List",
"[",
"type",
"]",
",",
"namespace",
":",
"MutableMapping",
"[",
"str",
",",
"Any",
"]",
",",
"key",
":",
"str",
")",
"->",
"None",
":",
"# pylint: disable=too-many-locals",
"# pylint: disable=too-... | Collect contracts for all getters/setters/deleters corresponding to ``key`` and decorate them. | [
"Collect",
"contracts",
"for",
"all",
"getters",
"/",
"setters",
"/",
"deleters",
"corresponding",
"to",
"key",
"and",
"decorate",
"them",
"."
] | 846e3187869a9ba790e9b893c98e5055e1cce274 | https://github.com/Parquery/icontract/blob/846e3187869a9ba790e9b893c98e5055e1cce274/icontract/_metaclass.py#L172-L268 | train |
Parquery/icontract | icontract/_metaclass.py | _dbc_decorate_namespace | def _dbc_decorate_namespace(bases: List[type], namespace: MutableMapping[str, Any]) -> None:
"""
Collect invariants, preconditions and postconditions from the bases and decorate all the methods.
Instance methods are simply replaced with the decorated function/ Properties, class methods and static methods a... | python | def _dbc_decorate_namespace(bases: List[type], namespace: MutableMapping[str, Any]) -> None:
"""
Collect invariants, preconditions and postconditions from the bases and decorate all the methods.
Instance methods are simply replaced with the decorated function/ Properties, class methods and static methods a... | [
"def",
"_dbc_decorate_namespace",
"(",
"bases",
":",
"List",
"[",
"type",
"]",
",",
"namespace",
":",
"MutableMapping",
"[",
"str",
",",
"Any",
"]",
")",
"->",
"None",
":",
"_collapse_invariants",
"(",
"bases",
"=",
"bases",
",",
"namespace",
"=",
"namespa... | Collect invariants, preconditions and postconditions from the bases and decorate all the methods.
Instance methods are simply replaced with the decorated function/ Properties, class methods and static methods are
overridden with new instances of ``property``, ``classmethod`` and ``staticmethod``, respectively. | [
"Collect",
"invariants",
"preconditions",
"and",
"postconditions",
"from",
"the",
"bases",
"and",
"decorate",
"all",
"the",
"methods",
"."
] | 846e3187869a9ba790e9b893c98e5055e1cce274 | https://github.com/Parquery/icontract/blob/846e3187869a9ba790e9b893c98e5055e1cce274/icontract/_metaclass.py#L271-L289 | train |
Parquery/icontract | icontract/_represent.py | _representable | def _representable(value: Any) -> bool:
"""
Check whether we want to represent the value in the error message on contract breach.
We do not want to represent classes, methods, modules and functions.
:param value: value related to an AST node
:return: True if we want to represent it in the violatio... | python | def _representable(value: Any) -> bool:
"""
Check whether we want to represent the value in the error message on contract breach.
We do not want to represent classes, methods, modules and functions.
:param value: value related to an AST node
:return: True if we want to represent it in the violatio... | [
"def",
"_representable",
"(",
"value",
":",
"Any",
")",
"->",
"bool",
":",
"return",
"not",
"inspect",
".",
"isclass",
"(",
"value",
")",
"and",
"not",
"inspect",
".",
"isfunction",
"(",
"value",
")",
"and",
"not",
"inspect",
".",
"ismethod",
"(",
"val... | Check whether we want to represent the value in the error message on contract breach.
We do not want to represent classes, methods, modules and functions.
:param value: value related to an AST node
:return: True if we want to represent it in the violation error | [
"Check",
"whether",
"we",
"want",
"to",
"represent",
"the",
"value",
"in",
"the",
"error",
"message",
"on",
"contract",
"breach",
"."
] | 846e3187869a9ba790e9b893c98e5055e1cce274 | https://github.com/Parquery/icontract/blob/846e3187869a9ba790e9b893c98e5055e1cce274/icontract/_represent.py#L21-L31 | train |
Parquery/icontract | icontract/_represent.py | inspect_decorator | def inspect_decorator(lines: List[str], lineno: int, filename: str) -> DecoratorInspection:
"""
Parse the file in which the decorator is called and figure out the corresponding call AST node.
:param lines: lines of the source file corresponding to the decorator call
:param lineno: line index (starting ... | python | def inspect_decorator(lines: List[str], lineno: int, filename: str) -> DecoratorInspection:
"""
Parse the file in which the decorator is called and figure out the corresponding call AST node.
:param lines: lines of the source file corresponding to the decorator call
:param lineno: line index (starting ... | [
"def",
"inspect_decorator",
"(",
"lines",
":",
"List",
"[",
"str",
"]",
",",
"lineno",
":",
"int",
",",
"filename",
":",
"str",
")",
"->",
"DecoratorInspection",
":",
"if",
"lineno",
"<",
"0",
"or",
"lineno",
">=",
"len",
"(",
"lines",
")",
":",
"rai... | Parse the file in which the decorator is called and figure out the corresponding call AST node.
:param lines: lines of the source file corresponding to the decorator call
:param lineno: line index (starting with 0) of one of the lines in the decorator call
:param filename: name of the file where decorator ... | [
"Parse",
"the",
"file",
"in",
"which",
"the",
"decorator",
"is",
"called",
"and",
"figure",
"out",
"the",
"corresponding",
"call",
"AST",
"node",
"."
] | 846e3187869a9ba790e9b893c98e5055e1cce274 | https://github.com/Parquery/icontract/blob/846e3187869a9ba790e9b893c98e5055e1cce274/icontract/_represent.py#L183-L245 | train |
Parquery/icontract | icontract/_represent.py | find_lambda_condition | def find_lambda_condition(decorator_inspection: DecoratorInspection) -> Optional[ConditionLambdaInspection]:
"""
Inspect the decorator and extract the condition as lambda.
If the condition is not given as a lambda function, return None.
"""
call_node = decorator_inspection.node
lambda_node = N... | python | def find_lambda_condition(decorator_inspection: DecoratorInspection) -> Optional[ConditionLambdaInspection]:
"""
Inspect the decorator and extract the condition as lambda.
If the condition is not given as a lambda function, return None.
"""
call_node = decorator_inspection.node
lambda_node = N... | [
"def",
"find_lambda_condition",
"(",
"decorator_inspection",
":",
"DecoratorInspection",
")",
"->",
"Optional",
"[",
"ConditionLambdaInspection",
"]",
":",
"call_node",
"=",
"decorator_inspection",
".",
"node",
"lambda_node",
"=",
"None",
"# type: Optional[ast.Lambda]",
"... | Inspect the decorator and extract the condition as lambda.
If the condition is not given as a lambda function, return None. | [
"Inspect",
"the",
"decorator",
"and",
"extract",
"the",
"condition",
"as",
"lambda",
"."
] | 846e3187869a9ba790e9b893c98e5055e1cce274 | https://github.com/Parquery/icontract/blob/846e3187869a9ba790e9b893c98e5055e1cce274/icontract/_represent.py#L248-L280 | train |
Parquery/icontract | icontract/_represent.py | repr_values | def repr_values(condition: Callable[..., bool], lambda_inspection: Optional[ConditionLambdaInspection],
condition_kwargs: Mapping[str, Any], a_repr: reprlib.Repr) -> List[str]:
# pylint: disable=too-many-locals
"""
Represent function arguments and frame values in the error message on contrac... | python | def repr_values(condition: Callable[..., bool], lambda_inspection: Optional[ConditionLambdaInspection],
condition_kwargs: Mapping[str, Any], a_repr: reprlib.Repr) -> List[str]:
# pylint: disable=too-many-locals
"""
Represent function arguments and frame values in the error message on contrac... | [
"def",
"repr_values",
"(",
"condition",
":",
"Callable",
"[",
"...",
",",
"bool",
"]",
",",
"lambda_inspection",
":",
"Optional",
"[",
"ConditionLambdaInspection",
"]",
",",
"condition_kwargs",
":",
"Mapping",
"[",
"str",
",",
"Any",
"]",
",",
"a_repr",
":",... | Represent function arguments and frame values in the error message on contract breach.
:param condition: condition function of the contract
:param lambda_inspection:
inspected lambda AST node corresponding to the condition function (None if the condition was not given as a
lambda function)
... | [
"Represent",
"function",
"arguments",
"and",
"frame",
"values",
"in",
"the",
"error",
"message",
"on",
"contract",
"breach",
"."
] | 846e3187869a9ba790e9b893c98e5055e1cce274 | https://github.com/Parquery/icontract/blob/846e3187869a9ba790e9b893c98e5055e1cce274/icontract/_represent.py#L283-L351 | train |
Parquery/icontract | icontract/_represent.py | generate_message | def generate_message(contract: Contract, condition_kwargs: Mapping[str, Any]) -> str:
"""Generate the message upon contract violation."""
# pylint: disable=protected-access
parts = [] # type: List[str]
if contract.location is not None:
parts.append("{}:\n".format(contract.location))
if co... | python | def generate_message(contract: Contract, condition_kwargs: Mapping[str, Any]) -> str:
"""Generate the message upon contract violation."""
# pylint: disable=protected-access
parts = [] # type: List[str]
if contract.location is not None:
parts.append("{}:\n".format(contract.location))
if co... | [
"def",
"generate_message",
"(",
"contract",
":",
"Contract",
",",
"condition_kwargs",
":",
"Mapping",
"[",
"str",
",",
"Any",
"]",
")",
"->",
"str",
":",
"# pylint: disable=protected-access",
"parts",
"=",
"[",
"]",
"# type: List[str]",
"if",
"contract",
".",
... | Generate the message upon contract violation. | [
"Generate",
"the",
"message",
"upon",
"contract",
"violation",
"."
] | 846e3187869a9ba790e9b893c98e5055e1cce274 | https://github.com/Parquery/icontract/blob/846e3187869a9ba790e9b893c98e5055e1cce274/icontract/_represent.py#L354-L405 | train |
Parquery/icontract | icontract/_represent.py | Visitor.visit_Name | def visit_Name(self, node: ast.Name) -> None:
"""
Resolve the name from the variable look-up and the built-ins.
Due to possible branching (e.g., If-expressions), some nodes might lack the recomputed values. These nodes
are ignored.
"""
if node in self._recomputed_values:... | python | def visit_Name(self, node: ast.Name) -> None:
"""
Resolve the name from the variable look-up and the built-ins.
Due to possible branching (e.g., If-expressions), some nodes might lack the recomputed values. These nodes
are ignored.
"""
if node in self._recomputed_values:... | [
"def",
"visit_Name",
"(",
"self",
",",
"node",
":",
"ast",
".",
"Name",
")",
"->",
"None",
":",
"if",
"node",
"in",
"self",
".",
"_recomputed_values",
":",
"value",
"=",
"self",
".",
"_recomputed_values",
"[",
"node",
"]",
"# Check if it is a non-built-in",
... | Resolve the name from the variable look-up and the built-ins.
Due to possible branching (e.g., If-expressions), some nodes might lack the recomputed values. These nodes
are ignored. | [
"Resolve",
"the",
"name",
"from",
"the",
"variable",
"look",
"-",
"up",
"and",
"the",
"built",
"-",
"ins",
"."
] | 846e3187869a9ba790e9b893c98e5055e1cce274 | https://github.com/Parquery/icontract/blob/846e3187869a9ba790e9b893c98e5055e1cce274/icontract/_represent.py#L57-L78 | train |
Parquery/icontract | icontract/_represent.py | Visitor.visit_Attribute | def visit_Attribute(self, node: ast.Attribute) -> None:
"""Represent the attribute by dumping its source code."""
if node in self._recomputed_values:
value = self._recomputed_values[node]
if _representable(value=value):
text = self._atok.get_text(node)
... | python | def visit_Attribute(self, node: ast.Attribute) -> None:
"""Represent the attribute by dumping its source code."""
if node in self._recomputed_values:
value = self._recomputed_values[node]
if _representable(value=value):
text = self._atok.get_text(node)
... | [
"def",
"visit_Attribute",
"(",
"self",
",",
"node",
":",
"ast",
".",
"Attribute",
")",
"->",
"None",
":",
"if",
"node",
"in",
"self",
".",
"_recomputed_values",
":",
"value",
"=",
"self",
".",
"_recomputed_values",
"[",
"node",
"]",
"if",
"_representable",... | Represent the attribute by dumping its source code. | [
"Represent",
"the",
"attribute",
"by",
"dumping",
"its",
"source",
"code",
"."
] | 846e3187869a9ba790e9b893c98e5055e1cce274 | https://github.com/Parquery/icontract/blob/846e3187869a9ba790e9b893c98e5055e1cce274/icontract/_represent.py#L80-L89 | train |
Parquery/icontract | icontract/_represent.py | Visitor.visit_Call | def visit_Call(self, node: ast.Call) -> None:
"""Represent the call by dumping its source code."""
if node in self._recomputed_values:
value = self._recomputed_values[node]
text = self._atok.get_text(node)
self.reprs[text] = value
self.generic_visit(node=nod... | python | def visit_Call(self, node: ast.Call) -> None:
"""Represent the call by dumping its source code."""
if node in self._recomputed_values:
value = self._recomputed_values[node]
text = self._atok.get_text(node)
self.reprs[text] = value
self.generic_visit(node=nod... | [
"def",
"visit_Call",
"(",
"self",
",",
"node",
":",
"ast",
".",
"Call",
")",
"->",
"None",
":",
"if",
"node",
"in",
"self",
".",
"_recomputed_values",
":",
"value",
"=",
"self",
".",
"_recomputed_values",
"[",
"node",
"]",
"text",
"=",
"self",
".",
"... | Represent the call by dumping its source code. | [
"Represent",
"the",
"call",
"by",
"dumping",
"its",
"source",
"code",
"."
] | 846e3187869a9ba790e9b893c98e5055e1cce274 | https://github.com/Parquery/icontract/blob/846e3187869a9ba790e9b893c98e5055e1cce274/icontract/_represent.py#L91-L99 | train |
Parquery/icontract | icontract/_represent.py | Visitor.visit_ListComp | def visit_ListComp(self, node: ast.ListComp) -> None:
"""Represent the list comprehension by dumping its source code."""
if node in self._recomputed_values:
value = self._recomputed_values[node]
text = self._atok.get_text(node)
self.reprs[text] = value
self.... | python | def visit_ListComp(self, node: ast.ListComp) -> None:
"""Represent the list comprehension by dumping its source code."""
if node in self._recomputed_values:
value = self._recomputed_values[node]
text = self._atok.get_text(node)
self.reprs[text] = value
self.... | [
"def",
"visit_ListComp",
"(",
"self",
",",
"node",
":",
"ast",
".",
"ListComp",
")",
"->",
"None",
":",
"if",
"node",
"in",
"self",
".",
"_recomputed_values",
":",
"value",
"=",
"self",
".",
"_recomputed_values",
"[",
"node",
"]",
"text",
"=",
"self",
... | Represent the list comprehension by dumping its source code. | [
"Represent",
"the",
"list",
"comprehension",
"by",
"dumping",
"its",
"source",
"code",
"."
] | 846e3187869a9ba790e9b893c98e5055e1cce274 | https://github.com/Parquery/icontract/blob/846e3187869a9ba790e9b893c98e5055e1cce274/icontract/_represent.py#L101-L109 | train |
Parquery/icontract | icontract/_represent.py | Visitor.visit_DictComp | def visit_DictComp(self, node: ast.DictComp) -> None:
"""Represent the dictionary comprehension by dumping its source code."""
if node in self._recomputed_values:
value = self._recomputed_values[node]
text = self._atok.get_text(node)
self.reprs[text] = value
... | python | def visit_DictComp(self, node: ast.DictComp) -> None:
"""Represent the dictionary comprehension by dumping its source code."""
if node in self._recomputed_values:
value = self._recomputed_values[node]
text = self._atok.get_text(node)
self.reprs[text] = value
... | [
"def",
"visit_DictComp",
"(",
"self",
",",
"node",
":",
"ast",
".",
"DictComp",
")",
"->",
"None",
":",
"if",
"node",
"in",
"self",
".",
"_recomputed_values",
":",
"value",
"=",
"self",
".",
"_recomputed_values",
"[",
"node",
"]",
"text",
"=",
"self",
... | Represent the dictionary comprehension by dumping its source code. | [
"Represent",
"the",
"dictionary",
"comprehension",
"by",
"dumping",
"its",
"source",
"code",
"."
] | 846e3187869a9ba790e9b893c98e5055e1cce274 | https://github.com/Parquery/icontract/blob/846e3187869a9ba790e9b893c98e5055e1cce274/icontract/_represent.py#L121-L129 | train |
Parquery/icontract | icontract/_checkers.py | _walk_decorator_stack | def _walk_decorator_stack(func: CallableT) -> Iterable['CallableT']:
"""
Iterate through the stack of decorated functions until the original function.
Assume that all decorators used functools.update_wrapper.
"""
while hasattr(func, "__wrapped__"):
yield func
func = getattr(func, "... | python | def _walk_decorator_stack(func: CallableT) -> Iterable['CallableT']:
"""
Iterate through the stack of decorated functions until the original function.
Assume that all decorators used functools.update_wrapper.
"""
while hasattr(func, "__wrapped__"):
yield func
func = getattr(func, "... | [
"def",
"_walk_decorator_stack",
"(",
"func",
":",
"CallableT",
")",
"->",
"Iterable",
"[",
"'CallableT'",
"]",
":",
"while",
"hasattr",
"(",
"func",
",",
"\"__wrapped__\"",
")",
":",
"yield",
"func",
"func",
"=",
"getattr",
"(",
"func",
",",
"\"__wrapped__\"... | Iterate through the stack of decorated functions until the original function.
Assume that all decorators used functools.update_wrapper. | [
"Iterate",
"through",
"the",
"stack",
"of",
"decorated",
"functions",
"until",
"the",
"original",
"function",
"."
] | 846e3187869a9ba790e9b893c98e5055e1cce274 | https://github.com/Parquery/icontract/blob/846e3187869a9ba790e9b893c98e5055e1cce274/icontract/_checkers.py#L17-L28 | train |
Parquery/icontract | icontract/_checkers.py | find_checker | def find_checker(func: CallableT) -> Optional[CallableT]:
"""Iterate through the decorator stack till we find the contract checker."""
contract_checker = None # type: Optional[CallableT]
for a_wrapper in _walk_decorator_stack(func):
if hasattr(a_wrapper, "__preconditions__") or hasattr(a_wrapper, "... | python | def find_checker(func: CallableT) -> Optional[CallableT]:
"""Iterate through the decorator stack till we find the contract checker."""
contract_checker = None # type: Optional[CallableT]
for a_wrapper in _walk_decorator_stack(func):
if hasattr(a_wrapper, "__preconditions__") or hasattr(a_wrapper, "... | [
"def",
"find_checker",
"(",
"func",
":",
"CallableT",
")",
"->",
"Optional",
"[",
"CallableT",
"]",
":",
"contract_checker",
"=",
"None",
"# type: Optional[CallableT]",
"for",
"a_wrapper",
"in",
"_walk_decorator_stack",
"(",
"func",
")",
":",
"if",
"hasattr",
"(... | Iterate through the decorator stack till we find the contract checker. | [
"Iterate",
"through",
"the",
"decorator",
"stack",
"till",
"we",
"find",
"the",
"contract",
"checker",
"."
] | 846e3187869a9ba790e9b893c98e5055e1cce274 | https://github.com/Parquery/icontract/blob/846e3187869a9ba790e9b893c98e5055e1cce274/icontract/_checkers.py#L31-L38 | train |
Parquery/icontract | icontract/_checkers.py | _kwargs_from_call | def _kwargs_from_call(param_names: List[str], kwdefaults: Dict[str, Any], args: Tuple[Any, ...],
kwargs: Dict[str, Any]) -> MutableMapping[str, Any]:
"""
Inspect the input values received at the wrapper for the actual function call.
:param param_names: parameter (*i.e.* argument) name... | python | def _kwargs_from_call(param_names: List[str], kwdefaults: Dict[str, Any], args: Tuple[Any, ...],
kwargs: Dict[str, Any]) -> MutableMapping[str, Any]:
"""
Inspect the input values received at the wrapper for the actual function call.
:param param_names: parameter (*i.e.* argument) name... | [
"def",
"_kwargs_from_call",
"(",
"param_names",
":",
"List",
"[",
"str",
"]",
",",
"kwdefaults",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
",",
"args",
":",
"Tuple",
"[",
"Any",
",",
"...",
"]",
",",
"kwargs",
":",
"Dict",
"[",
"str",
",",
"Any",
... | Inspect the input values received at the wrapper for the actual function call.
:param param_names: parameter (*i.e.* argument) names of the original (decorated) function
:param kwdefaults: default argument values of the original function
:param args: arguments supplied to the call
:param kwargs: keywor... | [
"Inspect",
"the",
"input",
"values",
"received",
"at",
"the",
"wrapper",
"for",
"the",
"actual",
"function",
"call",
"."
] | 846e3187869a9ba790e9b893c98e5055e1cce274 | https://github.com/Parquery/icontract/blob/846e3187869a9ba790e9b893c98e5055e1cce274/icontract/_checkers.py#L41-L66 | train |
Parquery/icontract | icontract/_checkers.py | _assert_precondition | def _assert_precondition(contract: Contract, resolved_kwargs: Mapping[str, Any]) -> None:
"""
Assert that the contract holds as a precondition.
:param contract: contract to be verified
:param resolved_kwargs: resolved keyword arguments (including the default values)
:return:
"""
# Check tha... | python | def _assert_precondition(contract: Contract, resolved_kwargs: Mapping[str, Any]) -> None:
"""
Assert that the contract holds as a precondition.
:param contract: contract to be verified
:param resolved_kwargs: resolved keyword arguments (including the default values)
:return:
"""
# Check tha... | [
"def",
"_assert_precondition",
"(",
"contract",
":",
"Contract",
",",
"resolved_kwargs",
":",
"Mapping",
"[",
"str",
",",
"Any",
"]",
")",
"->",
"None",
":",
"# Check that all arguments to the condition function have been set.",
"missing_args",
"=",
"[",
"arg_name",
"... | Assert that the contract holds as a precondition.
:param contract: contract to be verified
:param resolved_kwargs: resolved keyword arguments (including the default values)
:return: | [
"Assert",
"that",
"the",
"contract",
"holds",
"as",
"a",
"precondition",
"."
] | 846e3187869a9ba790e9b893c98e5055e1cce274 | https://github.com/Parquery/icontract/blob/846e3187869a9ba790e9b893c98e5055e1cce274/icontract/_checkers.py#L69-L120 | train |
Parquery/icontract | icontract/_checkers.py | _assert_invariant | def _assert_invariant(contract: Contract, instance: Any) -> None:
"""Assert that the contract holds as a class invariant given the instance of the class."""
if 'self' in contract.condition_arg_set:
check = contract.condition(self=instance)
else:
check = contract.condition()
if not check... | python | def _assert_invariant(contract: Contract, instance: Any) -> None:
"""Assert that the contract holds as a class invariant given the instance of the class."""
if 'self' in contract.condition_arg_set:
check = contract.condition(self=instance)
else:
check = contract.condition()
if not check... | [
"def",
"_assert_invariant",
"(",
"contract",
":",
"Contract",
",",
"instance",
":",
"Any",
")",
"->",
"None",
":",
"if",
"'self'",
"in",
"contract",
".",
"condition_arg_set",
":",
"check",
"=",
"contract",
".",
"condition",
"(",
"self",
"=",
"instance",
")... | Assert that the contract holds as a class invariant given the instance of the class. | [
"Assert",
"that",
"the",
"contract",
"holds",
"as",
"a",
"class",
"invariant",
"given",
"the",
"instance",
"of",
"the",
"class",
"."
] | 846e3187869a9ba790e9b893c98e5055e1cce274 | https://github.com/Parquery/icontract/blob/846e3187869a9ba790e9b893c98e5055e1cce274/icontract/_checkers.py#L123-L150 | train |
Parquery/icontract | icontract/_checkers.py | _capture_snapshot | def _capture_snapshot(a_snapshot: Snapshot, resolved_kwargs: Mapping[str, Any]) -> Any:
"""
Capture the snapshot from the keyword arguments resolved before the function call (including the default values).
:param a_snapshot: snapshot to be captured
:param resolved_kwargs: resolved keyword arguments (in... | python | def _capture_snapshot(a_snapshot: Snapshot, resolved_kwargs: Mapping[str, Any]) -> Any:
"""
Capture the snapshot from the keyword arguments resolved before the function call (including the default values).
:param a_snapshot: snapshot to be captured
:param resolved_kwargs: resolved keyword arguments (in... | [
"def",
"_capture_snapshot",
"(",
"a_snapshot",
":",
"Snapshot",
",",
"resolved_kwargs",
":",
"Mapping",
"[",
"str",
",",
"Any",
"]",
")",
"->",
"Any",
":",
"if",
"a_snapshot",
".",
"arg",
"is",
"not",
"None",
":",
"if",
"a_snapshot",
".",
"arg",
"not",
... | Capture the snapshot from the keyword arguments resolved before the function call (including the default values).
:param a_snapshot: snapshot to be captured
:param resolved_kwargs: resolved keyword arguments (including the default values)
:return: captured value | [
"Capture",
"the",
"snapshot",
"from",
"the",
"keyword",
"arguments",
"resolved",
"before",
"the",
"function",
"call",
"(",
"including",
"the",
"default",
"values",
")",
"."
] | 846e3187869a9ba790e9b893c98e5055e1cce274 | https://github.com/Parquery/icontract/blob/846e3187869a9ba790e9b893c98e5055e1cce274/icontract/_checkers.py#L153-L171 | train |
Parquery/icontract | icontract/_checkers.py | decorate_with_checker | def decorate_with_checker(func: CallableT) -> CallableT:
"""Decorate the function with a checker that verifies the preconditions and postconditions."""
assert not hasattr(func, "__preconditions__"), \
"Expected func to have no list of preconditions (there should be only a single contract checker per fun... | python | def decorate_with_checker(func: CallableT) -> CallableT:
"""Decorate the function with a checker that verifies the preconditions and postconditions."""
assert not hasattr(func, "__preconditions__"), \
"Expected func to have no list of preconditions (there should be only a single contract checker per fun... | [
"def",
"decorate_with_checker",
"(",
"func",
":",
"CallableT",
")",
"->",
"CallableT",
":",
"assert",
"not",
"hasattr",
"(",
"func",
",",
"\"__preconditions__\"",
")",
",",
"\"Expected func to have no list of preconditions (there should be only a single contract checker per fun... | Decorate the function with a checker that verifies the preconditions and postconditions. | [
"Decorate",
"the",
"function",
"with",
"a",
"checker",
"that",
"verifies",
"the",
"preconditions",
"and",
"postconditions",
"."
] | 846e3187869a9ba790e9b893c98e5055e1cce274 | https://github.com/Parquery/icontract/blob/846e3187869a9ba790e9b893c98e5055e1cce274/icontract/_checkers.py#L252-L346 | train |
Parquery/icontract | icontract/_checkers.py | _find_self | def _find_self(param_names: List[str], args: Tuple[Any, ...], kwargs: Dict[str, Any]) -> Any:
"""Find the instance of ``self`` in the arguments."""
instance_i = param_names.index("self")
if instance_i < len(args):
instance = args[instance_i]
else:
instance = kwargs["self"]
return in... | python | def _find_self(param_names: List[str], args: Tuple[Any, ...], kwargs: Dict[str, Any]) -> Any:
"""Find the instance of ``self`` in the arguments."""
instance_i = param_names.index("self")
if instance_i < len(args):
instance = args[instance_i]
else:
instance = kwargs["self"]
return in... | [
"def",
"_find_self",
"(",
"param_names",
":",
"List",
"[",
"str",
"]",
",",
"args",
":",
"Tuple",
"[",
"Any",
",",
"...",
"]",
",",
"kwargs",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
")",
"->",
"Any",
":",
"instance_i",
"=",
"param_names",
".",
... | Find the instance of ``self`` in the arguments. | [
"Find",
"the",
"instance",
"of",
"self",
"in",
"the",
"arguments",
"."
] | 846e3187869a9ba790e9b893c98e5055e1cce274 | https://github.com/Parquery/icontract/blob/846e3187869a9ba790e9b893c98e5055e1cce274/icontract/_checkers.py#L349-L357 | train |
Parquery/icontract | icontract/_checkers.py | _decorate_with_invariants | def _decorate_with_invariants(func: CallableT, is_init: bool) -> CallableT:
"""
Decorate the function ``func`` of the class ``cls`` with invariant checks.
If the function has been already decorated with invariant checks, the function returns immediately.
:param func: function to be wrapped
:param ... | python | def _decorate_with_invariants(func: CallableT, is_init: bool) -> CallableT:
"""
Decorate the function ``func`` of the class ``cls`` with invariant checks.
If the function has been already decorated with invariant checks, the function returns immediately.
:param func: function to be wrapped
:param ... | [
"def",
"_decorate_with_invariants",
"(",
"func",
":",
"CallableT",
",",
"is_init",
":",
"bool",
")",
"->",
"CallableT",
":",
"if",
"_already_decorated_with_invariants",
"(",
"func",
"=",
"func",
")",
":",
"return",
"func",
"sign",
"=",
"inspect",
".",
"signatu... | Decorate the function ``func`` of the class ``cls`` with invariant checks.
If the function has been already decorated with invariant checks, the function returns immediately.
:param func: function to be wrapped
:param is_init: True if the ``func`` is __init__
:return: function wrapped with invariant c... | [
"Decorate",
"the",
"function",
"func",
"of",
"the",
"class",
"cls",
"with",
"invariant",
"checks",
"."
] | 846e3187869a9ba790e9b893c98e5055e1cce274 | https://github.com/Parquery/icontract/blob/846e3187869a9ba790e9b893c98e5055e1cce274/icontract/_checkers.py#L360-L407 | train |
Parquery/icontract | icontract/_checkers.py | _already_decorated_with_invariants | def _already_decorated_with_invariants(func: CallableT) -> bool:
"""Check if the function has been already decorated with an invariant check by going through its decorator stack."""
already_decorated = False
for a_decorator in _walk_decorator_stack(func=func):
if getattr(a_decorator, "__is_invariant... | python | def _already_decorated_with_invariants(func: CallableT) -> bool:
"""Check if the function has been already decorated with an invariant check by going through its decorator stack."""
already_decorated = False
for a_decorator in _walk_decorator_stack(func=func):
if getattr(a_decorator, "__is_invariant... | [
"def",
"_already_decorated_with_invariants",
"(",
"func",
":",
"CallableT",
")",
"->",
"bool",
":",
"already_decorated",
"=",
"False",
"for",
"a_decorator",
"in",
"_walk_decorator_stack",
"(",
"func",
"=",
"func",
")",
":",
"if",
"getattr",
"(",
"a_decorator",
"... | Check if the function has been already decorated with an invariant check by going through its decorator stack. | [
"Check",
"if",
"the",
"function",
"has",
"been",
"already",
"decorated",
"with",
"an",
"invariant",
"check",
"by",
"going",
"through",
"its",
"decorator",
"stack",
"."
] | 846e3187869a9ba790e9b893c98e5055e1cce274 | https://github.com/Parquery/icontract/blob/846e3187869a9ba790e9b893c98e5055e1cce274/icontract/_checkers.py#L417-L425 | train |
Parquery/icontract | icontract/_checkers.py | add_invariant_checks | def add_invariant_checks(cls: type) -> None:
"""Decorate each of the class functions with invariant checks if not already decorated."""
# Candidates for the decoration as list of (name, dir() value)
init_name_func = None # type: Optional[Tuple[str, Callable[..., None]]]
names_funcs = [] # type: List[T... | python | def add_invariant_checks(cls: type) -> None:
"""Decorate each of the class functions with invariant checks if not already decorated."""
# Candidates for the decoration as list of (name, dir() value)
init_name_func = None # type: Optional[Tuple[str, Callable[..., None]]]
names_funcs = [] # type: List[T... | [
"def",
"add_invariant_checks",
"(",
"cls",
":",
"type",
")",
"->",
"None",
":",
"# Candidates for the decoration as list of (name, dir() value)",
"init_name_func",
"=",
"None",
"# type: Optional[Tuple[str, Callable[..., None]]]",
"names_funcs",
"=",
"[",
"]",
"# type: List[Tupl... | Decorate each of the class functions with invariant checks if not already decorated. | [
"Decorate",
"each",
"of",
"the",
"class",
"functions",
"with",
"invariant",
"checks",
"if",
"not",
"already",
"decorated",
"."
] | 846e3187869a9ba790e9b893c98e5055e1cce274 | https://github.com/Parquery/icontract/blob/846e3187869a9ba790e9b893c98e5055e1cce274/icontract/_checkers.py#L428-L486 | train |
Parquery/icontract | benchmarks/import_cost/measure.py | main | def main() -> None:
""""Execute the main routine."""
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--module", help="name of the module to import",
choices=[
"functions_100_with_no_contract",
"functi... | python | def main() -> None:
""""Execute the main routine."""
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--module", help="name of the module to import",
choices=[
"functions_100_with_no_contract",
"functi... | [
"def",
"main",
"(",
")",
"->",
"None",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"__doc__",
")",
"parser",
".",
"add_argument",
"(",
"\"--module\"",
",",
"help",
"=",
"\"name of the module to import\"",
",",
"choices",
"="... | Execute the main routine. | [
"Execute",
"the",
"main",
"routine",
"."
] | 846e3187869a9ba790e9b893c98e5055e1cce274 | https://github.com/Parquery/icontract/blob/846e3187869a9ba790e9b893c98e5055e1cce274/benchmarks/import_cost/measure.py#L13-L114 | train |
Parquery/icontract | benchmarks/import_cost/runme.py | main | def main() -> None:
""""Execute the main routine."""
modules = [
"functions_100_with_no_contract",
"functions_100_with_1_contract",
"functions_100_with_5_contracts",
"functions_100_with_10_contracts",
"functions_100_with_1_disabled_contract",
"functions_100_with... | python | def main() -> None:
""""Execute the main routine."""
modules = [
"functions_100_with_no_contract",
"functions_100_with_1_contract",
"functions_100_with_5_contracts",
"functions_100_with_10_contracts",
"functions_100_with_1_disabled_contract",
"functions_100_with... | [
"def",
"main",
"(",
")",
"->",
"None",
":",
"modules",
"=",
"[",
"\"functions_100_with_no_contract\"",
",",
"\"functions_100_with_1_contract\"",
",",
"\"functions_100_with_5_contracts\"",
",",
"\"functions_100_with_10_contracts\"",
",",
"\"functions_100_with_1_disabled_contract\"... | Execute the main routine. | [
"Execute",
"the",
"main",
"routine",
"."
] | 846e3187869a9ba790e9b893c98e5055e1cce274 | https://github.com/Parquery/icontract/blob/846e3187869a9ba790e9b893c98e5055e1cce274/benchmarks/import_cost/runme.py#L10-L42 | train |
Parquery/icontract | benchmarks/import_cost/generate.py | main | def main() -> None:
""""Execute the main routine."""
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--outdir", help="output directory", default=os.path.dirname(__file__))
args = parser.parse_args()
outdir = pathlib.Path(args.outdir)
if not outdir.exists():
ra... | python | def main() -> None:
""""Execute the main routine."""
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--outdir", help="output directory", default=os.path.dirname(__file__))
args = parser.parse_args()
outdir = pathlib.Path(args.outdir)
if not outdir.exists():
ra... | [
"def",
"main",
"(",
")",
"->",
"None",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"__doc__",
")",
"parser",
".",
"add_argument",
"(",
"\"--outdir\"",
",",
"help",
"=",
"\"output directory\"",
",",
"default",
"=",
"os",
... | Execute the main routine. | [
"Execute",
"the",
"main",
"routine",
"."
] | 846e3187869a9ba790e9b893c98e5055e1cce274 | https://github.com/Parquery/icontract/blob/846e3187869a9ba790e9b893c98e5055e1cce274/benchmarks/import_cost/generate.py#L60-L108 | train |
Parquery/icontract | icontract/_recompute.py | Visitor.visit_Num | def visit_Num(self, node: ast.Num) -> Union[int, float]:
"""Recompute the value as the number at the node."""
result = node.n
self.recomputed_values[node] = result
return result | python | def visit_Num(self, node: ast.Num) -> Union[int, float]:
"""Recompute the value as the number at the node."""
result = node.n
self.recomputed_values[node] = result
return result | [
"def",
"visit_Num",
"(",
"self",
",",
"node",
":",
"ast",
".",
"Num",
")",
"->",
"Union",
"[",
"int",
",",
"float",
"]",
":",
"result",
"=",
"node",
".",
"n",
"self",
".",
"recomputed_values",
"[",
"node",
"]",
"=",
"result",
"return",
"result"
] | Recompute the value as the number at the node. | [
"Recompute",
"the",
"value",
"as",
"the",
"number",
"at",
"the",
"node",
"."
] | 846e3187869a9ba790e9b893c98e5055e1cce274 | https://github.com/Parquery/icontract/blob/846e3187869a9ba790e9b893c98e5055e1cce274/icontract/_recompute.py#L48-L53 | train |
Parquery/icontract | icontract/_recompute.py | Visitor.visit_Str | def visit_Str(self, node: ast.Str) -> str:
"""Recompute the value as the string at the node."""
result = node.s
self.recomputed_values[node] = result
return result | python | def visit_Str(self, node: ast.Str) -> str:
"""Recompute the value as the string at the node."""
result = node.s
self.recomputed_values[node] = result
return result | [
"def",
"visit_Str",
"(",
"self",
",",
"node",
":",
"ast",
".",
"Str",
")",
"->",
"str",
":",
"result",
"=",
"node",
".",
"s",
"self",
".",
"recomputed_values",
"[",
"node",
"]",
"=",
"result",
"return",
"result"
] | Recompute the value as the string at the node. | [
"Recompute",
"the",
"value",
"as",
"the",
"string",
"at",
"the",
"node",
"."
] | 846e3187869a9ba790e9b893c98e5055e1cce274 | https://github.com/Parquery/icontract/blob/846e3187869a9ba790e9b893c98e5055e1cce274/icontract/_recompute.py#L55-L60 | train |
Parquery/icontract | icontract/_recompute.py | Visitor.visit_Bytes | def visit_Bytes(self, node: ast.Bytes) -> bytes:
"""Recompute the value as the bytes at the node."""
result = node.s
self.recomputed_values[node] = result
return node.s | python | def visit_Bytes(self, node: ast.Bytes) -> bytes:
"""Recompute the value as the bytes at the node."""
result = node.s
self.recomputed_values[node] = result
return node.s | [
"def",
"visit_Bytes",
"(",
"self",
",",
"node",
":",
"ast",
".",
"Bytes",
")",
"->",
"bytes",
":",
"result",
"=",
"node",
".",
"s",
"self",
".",
"recomputed_values",
"[",
"node",
"]",
"=",
"result",
"return",
"node",
".",
"s"
] | Recompute the value as the bytes at the node. | [
"Recompute",
"the",
"value",
"as",
"the",
"bytes",
"at",
"the",
"node",
"."
] | 846e3187869a9ba790e9b893c98e5055e1cce274 | https://github.com/Parquery/icontract/blob/846e3187869a9ba790e9b893c98e5055e1cce274/icontract/_recompute.py#L62-L67 | train |
Parquery/icontract | icontract/_recompute.py | Visitor.visit_List | def visit_List(self, node: ast.List) -> List[Any]:
"""Visit the elements and assemble the results into a list."""
if isinstance(node.ctx, ast.Store):
raise NotImplementedError("Can not compute the value of a Store on a list")
result = [self.visit(node=elt) for elt in node.elts]
... | python | def visit_List(self, node: ast.List) -> List[Any]:
"""Visit the elements and assemble the results into a list."""
if isinstance(node.ctx, ast.Store):
raise NotImplementedError("Can not compute the value of a Store on a list")
result = [self.visit(node=elt) for elt in node.elts]
... | [
"def",
"visit_List",
"(",
"self",
",",
"node",
":",
"ast",
".",
"List",
")",
"->",
"List",
"[",
"Any",
"]",
":",
"if",
"isinstance",
"(",
"node",
".",
"ctx",
",",
"ast",
".",
"Store",
")",
":",
"raise",
"NotImplementedError",
"(",
"\"Can not compute th... | Visit the elements and assemble the results into a list. | [
"Visit",
"the",
"elements",
"and",
"assemble",
"the",
"results",
"into",
"a",
"list",
"."
] | 846e3187869a9ba790e9b893c98e5055e1cce274 | https://github.com/Parquery/icontract/blob/846e3187869a9ba790e9b893c98e5055e1cce274/icontract/_recompute.py#L69-L77 | train |
Parquery/icontract | icontract/_recompute.py | Visitor.visit_Tuple | def visit_Tuple(self, node: ast.Tuple) -> Tuple[Any, ...]:
"""Visit the elements and assemble the results into a tuple."""
if isinstance(node.ctx, ast.Store):
raise NotImplementedError("Can not compute the value of a Store on a tuple")
result = tuple(self.visit(node=elt) for elt in ... | python | def visit_Tuple(self, node: ast.Tuple) -> Tuple[Any, ...]:
"""Visit the elements and assemble the results into a tuple."""
if isinstance(node.ctx, ast.Store):
raise NotImplementedError("Can not compute the value of a Store on a tuple")
result = tuple(self.visit(node=elt) for elt in ... | [
"def",
"visit_Tuple",
"(",
"self",
",",
"node",
":",
"ast",
".",
"Tuple",
")",
"->",
"Tuple",
"[",
"Any",
",",
"...",
"]",
":",
"if",
"isinstance",
"(",
"node",
".",
"ctx",
",",
"ast",
".",
"Store",
")",
":",
"raise",
"NotImplementedError",
"(",
"\... | Visit the elements and assemble the results into a tuple. | [
"Visit",
"the",
"elements",
"and",
"assemble",
"the",
"results",
"into",
"a",
"tuple",
"."
] | 846e3187869a9ba790e9b893c98e5055e1cce274 | https://github.com/Parquery/icontract/blob/846e3187869a9ba790e9b893c98e5055e1cce274/icontract/_recompute.py#L79-L87 | train |
Parquery/icontract | icontract/_recompute.py | Visitor.visit_Set | def visit_Set(self, node: ast.Set) -> Set[Any]:
"""Visit the elements and assemble the results into a set."""
result = set(self.visit(node=elt) for elt in node.elts)
self.recomputed_values[node] = result
return result | python | def visit_Set(self, node: ast.Set) -> Set[Any]:
"""Visit the elements and assemble the results into a set."""
result = set(self.visit(node=elt) for elt in node.elts)
self.recomputed_values[node] = result
return result | [
"def",
"visit_Set",
"(",
"self",
",",
"node",
":",
"ast",
".",
"Set",
")",
"->",
"Set",
"[",
"Any",
"]",
":",
"result",
"=",
"set",
"(",
"self",
".",
"visit",
"(",
"node",
"=",
"elt",
")",
"for",
"elt",
"in",
"node",
".",
"elts",
")",
"self",
... | Visit the elements and assemble the results into a set. | [
"Visit",
"the",
"elements",
"and",
"assemble",
"the",
"results",
"into",
"a",
"set",
"."
] | 846e3187869a9ba790e9b893c98e5055e1cce274 | https://github.com/Parquery/icontract/blob/846e3187869a9ba790e9b893c98e5055e1cce274/icontract/_recompute.py#L89-L94 | train |
Parquery/icontract | icontract/_recompute.py | Visitor.visit_Dict | def visit_Dict(self, node: ast.Dict) -> Dict[Any, Any]:
"""Visit keys and values and assemble a dictionary with the results."""
recomputed_dict = dict() # type: Dict[Any, Any]
for key, val in zip(node.keys, node.values):
recomputed_dict[self.visit(node=key)] = self.visit(node=val)
... | python | def visit_Dict(self, node: ast.Dict) -> Dict[Any, Any]:
"""Visit keys and values and assemble a dictionary with the results."""
recomputed_dict = dict() # type: Dict[Any, Any]
for key, val in zip(node.keys, node.values):
recomputed_dict[self.visit(node=key)] = self.visit(node=val)
... | [
"def",
"visit_Dict",
"(",
"self",
",",
"node",
":",
"ast",
".",
"Dict",
")",
"->",
"Dict",
"[",
"Any",
",",
"Any",
"]",
":",
"recomputed_dict",
"=",
"dict",
"(",
")",
"# type: Dict[Any, Any]",
"for",
"key",
",",
"val",
"in",
"zip",
"(",
"node",
".",
... | Visit keys and values and assemble a dictionary with the results. | [
"Visit",
"keys",
"and",
"values",
"and",
"assemble",
"a",
"dictionary",
"with",
"the",
"results",
"."
] | 846e3187869a9ba790e9b893c98e5055e1cce274 | https://github.com/Parquery/icontract/blob/846e3187869a9ba790e9b893c98e5055e1cce274/icontract/_recompute.py#L96-L103 | train |
Parquery/icontract | icontract/_recompute.py | Visitor.visit_NameConstant | def visit_NameConstant(self, node: ast.NameConstant) -> Any:
"""Forward the node value as a result."""
self.recomputed_values[node] = node.value
return node.value | python | def visit_NameConstant(self, node: ast.NameConstant) -> Any:
"""Forward the node value as a result."""
self.recomputed_values[node] = node.value
return node.value | [
"def",
"visit_NameConstant",
"(",
"self",
",",
"node",
":",
"ast",
".",
"NameConstant",
")",
"->",
"Any",
":",
"self",
".",
"recomputed_values",
"[",
"node",
"]",
"=",
"node",
".",
"value",
"return",
"node",
".",
"value"
] | Forward the node value as a result. | [
"Forward",
"the",
"node",
"value",
"as",
"a",
"result",
"."
] | 846e3187869a9ba790e9b893c98e5055e1cce274 | https://github.com/Parquery/icontract/blob/846e3187869a9ba790e9b893c98e5055e1cce274/icontract/_recompute.py#L105-L108 | train |
Parquery/icontract | icontract/_recompute.py | Visitor.visit_Name | def visit_Name(self, node: ast.Name) -> Any:
"""Load the variable by looking it up in the variable look-up and in the built-ins."""
if not isinstance(node.ctx, ast.Load):
raise NotImplementedError("Can only compute a value of Load on a name {}, but got context: {}".format(
no... | python | def visit_Name(self, node: ast.Name) -> Any:
"""Load the variable by looking it up in the variable look-up and in the built-ins."""
if not isinstance(node.ctx, ast.Load):
raise NotImplementedError("Can only compute a value of Load on a name {}, but got context: {}".format(
no... | [
"def",
"visit_Name",
"(",
"self",
",",
"node",
":",
"ast",
".",
"Name",
")",
"->",
"Any",
":",
"if",
"not",
"isinstance",
"(",
"node",
".",
"ctx",
",",
"ast",
".",
"Load",
")",
":",
"raise",
"NotImplementedError",
"(",
"\"Can only compute a value of Load o... | Load the variable by looking it up in the variable look-up and in the built-ins. | [
"Load",
"the",
"variable",
"by",
"looking",
"it",
"up",
"in",
"the",
"variable",
"look",
"-",
"up",
"and",
"in",
"the",
"built",
"-",
"ins",
"."
] | 846e3187869a9ba790e9b893c98e5055e1cce274 | https://github.com/Parquery/icontract/blob/846e3187869a9ba790e9b893c98e5055e1cce274/icontract/_recompute.py#L110-L130 | train |
Parquery/icontract | icontract/_recompute.py | Visitor.visit_Expr | def visit_Expr(self, node: ast.Expr) -> Any:
"""Visit the node's ``value``."""
result = self.visit(node=node.value)
self.recomputed_values[node] = result
return result | python | def visit_Expr(self, node: ast.Expr) -> Any:
"""Visit the node's ``value``."""
result = self.visit(node=node.value)
self.recomputed_values[node] = result
return result | [
"def",
"visit_Expr",
"(",
"self",
",",
"node",
":",
"ast",
".",
"Expr",
")",
"->",
"Any",
":",
"result",
"=",
"self",
".",
"visit",
"(",
"node",
"=",
"node",
".",
"value",
")",
"self",
".",
"recomputed_values",
"[",
"node",
"]",
"=",
"result",
"ret... | Visit the node's ``value``. | [
"Visit",
"the",
"node",
"s",
"value",
"."
] | 846e3187869a9ba790e9b893c98e5055e1cce274 | https://github.com/Parquery/icontract/blob/846e3187869a9ba790e9b893c98e5055e1cce274/icontract/_recompute.py#L132-L137 | train |
Parquery/icontract | icontract/_recompute.py | Visitor.visit_UnaryOp | def visit_UnaryOp(self, node: ast.UnaryOp) -> Any:
"""Visit the node operand and apply the operation on the result."""
if isinstance(node.op, ast.UAdd):
result = +self.visit(node=node.operand)
elif isinstance(node.op, ast.USub):
result = -self.visit(node=node.operand)
... | python | def visit_UnaryOp(self, node: ast.UnaryOp) -> Any:
"""Visit the node operand and apply the operation on the result."""
if isinstance(node.op, ast.UAdd):
result = +self.visit(node=node.operand)
elif isinstance(node.op, ast.USub):
result = -self.visit(node=node.operand)
... | [
"def",
"visit_UnaryOp",
"(",
"self",
",",
"node",
":",
"ast",
".",
"UnaryOp",
")",
"->",
"Any",
":",
"if",
"isinstance",
"(",
"node",
".",
"op",
",",
"ast",
".",
"UAdd",
")",
":",
"result",
"=",
"+",
"self",
".",
"visit",
"(",
"node",
"=",
"node"... | Visit the node operand and apply the operation on the result. | [
"Visit",
"the",
"node",
"operand",
"and",
"apply",
"the",
"operation",
"on",
"the",
"result",
"."
] | 846e3187869a9ba790e9b893c98e5055e1cce274 | https://github.com/Parquery/icontract/blob/846e3187869a9ba790e9b893c98e5055e1cce274/icontract/_recompute.py#L139-L153 | train |
Parquery/icontract | icontract/_recompute.py | Visitor.visit_BinOp | def visit_BinOp(self, node: ast.BinOp) -> Any:
"""Recursively visit the left and right operand, respectively, and apply the operation on the results."""
# pylint: disable=too-many-branches
left = self.visit(node=node.left)
right = self.visit(node=node.right)
if isinstance(node.o... | python | def visit_BinOp(self, node: ast.BinOp) -> Any:
"""Recursively visit the left and right operand, respectively, and apply the operation on the results."""
# pylint: disable=too-many-branches
left = self.visit(node=node.left)
right = self.visit(node=node.right)
if isinstance(node.o... | [
"def",
"visit_BinOp",
"(",
"self",
",",
"node",
":",
"ast",
".",
"BinOp",
")",
"->",
"Any",
":",
"# pylint: disable=too-many-branches",
"left",
"=",
"self",
".",
"visit",
"(",
"node",
"=",
"node",
".",
"left",
")",
"right",
"=",
"self",
".",
"visit",
"... | Recursively visit the left and right operand, respectively, and apply the operation on the results. | [
"Recursively",
"visit",
"the",
"left",
"and",
"right",
"operand",
"respectively",
"and",
"apply",
"the",
"operation",
"on",
"the",
"results",
"."
] | 846e3187869a9ba790e9b893c98e5055e1cce274 | https://github.com/Parquery/icontract/blob/846e3187869a9ba790e9b893c98e5055e1cce274/icontract/_recompute.py#L155-L191 | train |
Parquery/icontract | icontract/_recompute.py | Visitor.visit_BoolOp | def visit_BoolOp(self, node: ast.BoolOp) -> Any:
"""Recursively visit the operands and apply the operation on them."""
values = [self.visit(value_node) for value_node in node.values]
if isinstance(node.op, ast.And):
result = functools.reduce(lambda left, right: left and right, value... | python | def visit_BoolOp(self, node: ast.BoolOp) -> Any:
"""Recursively visit the operands and apply the operation on them."""
values = [self.visit(value_node) for value_node in node.values]
if isinstance(node.op, ast.And):
result = functools.reduce(lambda left, right: left and right, value... | [
"def",
"visit_BoolOp",
"(",
"self",
",",
"node",
":",
"ast",
".",
"BoolOp",
")",
"->",
"Any",
":",
"values",
"=",
"[",
"self",
".",
"visit",
"(",
"value_node",
")",
"for",
"value_node",
"in",
"node",
".",
"values",
"]",
"if",
"isinstance",
"(",
"node... | Recursively visit the operands and apply the operation on them. | [
"Recursively",
"visit",
"the",
"operands",
"and",
"apply",
"the",
"operation",
"on",
"them",
"."
] | 846e3187869a9ba790e9b893c98e5055e1cce274 | https://github.com/Parquery/icontract/blob/846e3187869a9ba790e9b893c98e5055e1cce274/icontract/_recompute.py#L193-L205 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.