repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1 value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
brechtm/rinohtype | doc/build.py | help | def help():
"""List all targets"""
print("Please use '{} <target>' where <target> is one of"
.format(sys.argv[0]))
width = max(len(name) for name in TARGETS)
for name, target in TARGETS.items():
print(' {name:{width}} {descr}'.format(name=name, width=width,
descr=target.__doc__)) | python | def help():
"""List all targets"""
print("Please use '{} <target>' where <target> is one of"
.format(sys.argv[0]))
width = max(len(name) for name in TARGETS)
for name, target in TARGETS.items():
print(' {name:{width}} {descr}'.format(name=name, width=width,
descr=target.__doc__)) | [
"def",
"help",
"(",
")",
":",
"print",
"(",
"\"Please use '{} <target>' where <target> is one of\"",
".",
"format",
"(",
"sys",
".",
"argv",
"[",
"0",
"]",
")",
")",
"width",
"=",
"max",
"(",
"len",
"(",
"name",
")",
"for",
"name",
"in",
"TARGETS",
")",
... | List all targets | [
"List",
"all",
"targets"
] | 40a63c4e5ad7550f62b6860f1812cb67cafb9dc7 | https://github.com/brechtm/rinohtype/blob/40a63c4e5ad7550f62b6860f1812cb67cafb9dc7/doc/build.py#L253-L260 | train | 31,300 |
brechtm/rinohtype | src/rinoh/font/__init__.py | Typeface.fonts | def fonts(self):
"""Generator yielding all fonts of this typeface
Yields:
Font: the next font in this typeface
"""
for width in (w for w in FontWidth if w in self):
for slant in (s for s in FontSlant if s in self[width]):
for weight in (w for w in FontWeight
if w in self[width][slant]):
yield self[width][slant][weight] | python | def fonts(self):
"""Generator yielding all fonts of this typeface
Yields:
Font: the next font in this typeface
"""
for width in (w for w in FontWidth if w in self):
for slant in (s for s in FontSlant if s in self[width]):
for weight in (w for w in FontWeight
if w in self[width][slant]):
yield self[width][slant][weight] | [
"def",
"fonts",
"(",
"self",
")",
":",
"for",
"width",
"in",
"(",
"w",
"for",
"w",
"in",
"FontWidth",
"if",
"w",
"in",
"self",
")",
":",
"for",
"slant",
"in",
"(",
"s",
"for",
"s",
"in",
"FontSlant",
"if",
"s",
"in",
"self",
"[",
"width",
"]",
... | Generator yielding all fonts of this typeface
Yields:
Font: the next font in this typeface | [
"Generator",
"yielding",
"all",
"fonts",
"of",
"this",
"typeface"
] | 40a63c4e5ad7550f62b6860f1812cb67cafb9dc7 | https://github.com/brechtm/rinohtype/blob/40a63c4e5ad7550f62b6860f1812cb67cafb9dc7/src/rinoh/font/__init__.py#L194-L205 | train | 31,301 |
brechtm/rinohtype | src/rinoh/font/__init__.py | Typeface.get_font | def get_font(self, weight='medium', slant='upright', width='normal'):
"""Return the font matching or closest to the given style
If a font with the given weight, slant and width is available, return
it. Otherwise, return the font that is closest in style.
Args:
weight (FontWeight): weight of the font
slant (FontSlant): slant of the font
width (FontWidth): width of the font
Returns:
Font: the requested font
"""
def find_closest_style(style, styles, alternatives):
try:
return style, styles[style]
except KeyError:
for option in alternatives[style]:
try:
return option, styles[option]
except KeyError:
continue
def find_closest_weight(weight, weights):
index = FontWeight.values.index(weight)
min_distance = len(FontWeight.values)
closest = None
for i, option in enumerate(FontWeight.values):
if option in weights and abs(index - i) < min_distance:
min_distance = abs(index - i)
closest = option
return closest, weights[closest]
available_width, slants = find_closest_style(width, self,
FontWidth.alternatives)
available_slant, weights = find_closest_style(slant, slants,
FontSlant.alternatives)
available_weight, font = find_closest_weight(weight, weights)
if (available_width != width or available_slant != slant or
available_weight != weight):
warn('{} does not include a {} {} {} font. Falling back to {} {} '
'{}'.format(self.name, width, weight, slant, available_width,
available_weight, available_slant))
return font | python | def get_font(self, weight='medium', slant='upright', width='normal'):
"""Return the font matching or closest to the given style
If a font with the given weight, slant and width is available, return
it. Otherwise, return the font that is closest in style.
Args:
weight (FontWeight): weight of the font
slant (FontSlant): slant of the font
width (FontWidth): width of the font
Returns:
Font: the requested font
"""
def find_closest_style(style, styles, alternatives):
try:
return style, styles[style]
except KeyError:
for option in alternatives[style]:
try:
return option, styles[option]
except KeyError:
continue
def find_closest_weight(weight, weights):
index = FontWeight.values.index(weight)
min_distance = len(FontWeight.values)
closest = None
for i, option in enumerate(FontWeight.values):
if option in weights and abs(index - i) < min_distance:
min_distance = abs(index - i)
closest = option
return closest, weights[closest]
available_width, slants = find_closest_style(width, self,
FontWidth.alternatives)
available_slant, weights = find_closest_style(slant, slants,
FontSlant.alternatives)
available_weight, font = find_closest_weight(weight, weights)
if (available_width != width or available_slant != slant or
available_weight != weight):
warn('{} does not include a {} {} {} font. Falling back to {} {} '
'{}'.format(self.name, width, weight, slant, available_width,
available_weight, available_slant))
return font | [
"def",
"get_font",
"(",
"self",
",",
"weight",
"=",
"'medium'",
",",
"slant",
"=",
"'upright'",
",",
"width",
"=",
"'normal'",
")",
":",
"def",
"find_closest_style",
"(",
"style",
",",
"styles",
",",
"alternatives",
")",
":",
"try",
":",
"return",
"style... | Return the font matching or closest to the given style
If a font with the given weight, slant and width is available, return
it. Otherwise, return the font that is closest in style.
Args:
weight (FontWeight): weight of the font
slant (FontSlant): slant of the font
width (FontWidth): width of the font
Returns:
Font: the requested font | [
"Return",
"the",
"font",
"matching",
"or",
"closest",
"to",
"the",
"given",
"style"
] | 40a63c4e5ad7550f62b6860f1812cb67cafb9dc7 | https://github.com/brechtm/rinohtype/blob/40a63c4e5ad7550f62b6860f1812cb67cafb9dc7/src/rinoh/font/__init__.py#L207-L253 | train | 31,302 |
brechtm/rinohtype | src/rinoh/style.py | StyleSheet.get_selector | def get_selector(self, name):
"""Find a selector mapped to a style in this or a base style sheet.
Args:
name (str): a style name
Returns:
:class:`.Selector`: the selector mapped to the style `name`
Raises:
KeyError: if the style `name` was not found in this or a base
style sheet
"""
try:
return self.matcher.by_name[name]
except (AttributeError, KeyError):
if self.base is not None:
return self.base.get_selector(name)
else:
raise KeyError("No selector found for style '{}'".format(name)) | python | def get_selector(self, name):
"""Find a selector mapped to a style in this or a base style sheet.
Args:
name (str): a style name
Returns:
:class:`.Selector`: the selector mapped to the style `name`
Raises:
KeyError: if the style `name` was not found in this or a base
style sheet
"""
try:
return self.matcher.by_name[name]
except (AttributeError, KeyError):
if self.base is not None:
return self.base.get_selector(name)
else:
raise KeyError("No selector found for style '{}'".format(name)) | [
"def",
"get_selector",
"(",
"self",
",",
"name",
")",
":",
"try",
":",
"return",
"self",
".",
"matcher",
".",
"by_name",
"[",
"name",
"]",
"except",
"(",
"AttributeError",
",",
"KeyError",
")",
":",
"if",
"self",
".",
"base",
"is",
"not",
"None",
":"... | Find a selector mapped to a style in this or a base style sheet.
Args:
name (str): a style name
Returns:
:class:`.Selector`: the selector mapped to the style `name`
Raises:
KeyError: if the style `name` was not found in this or a base
style sheet | [
"Find",
"a",
"selector",
"mapped",
"to",
"a",
"style",
"in",
"this",
"or",
"a",
"base",
"style",
"sheet",
"."
] | 40a63c4e5ad7550f62b6860f1812cb67cafb9dc7 | https://github.com/brechtm/rinohtype/blob/40a63c4e5ad7550f62b6860f1812cb67cafb9dc7/src/rinoh/style.py#L761-L782 | train | 31,303 |
brechtm/rinohtype | src/rinoh/style.py | CharIterator.match | def match(self, chars):
"""Return all next characters that are listed in `chars` as a string"""
start_index = self.next_index
for char in self:
if char not in chars:
self.next_index -= 1
break
return self[start_index:self.next_index] | python | def match(self, chars):
"""Return all next characters that are listed in `chars` as a string"""
start_index = self.next_index
for char in self:
if char not in chars:
self.next_index -= 1
break
return self[start_index:self.next_index] | [
"def",
"match",
"(",
"self",
",",
"chars",
")",
":",
"start_index",
"=",
"self",
".",
"next_index",
"for",
"char",
"in",
"self",
":",
"if",
"char",
"not",
"in",
"chars",
":",
"self",
".",
"next_index",
"-=",
"1",
"break",
"return",
"self",
"[",
"star... | Return all next characters that are listed in `chars` as a string | [
"Return",
"all",
"next",
"characters",
"that",
"are",
"listed",
"in",
"chars",
"as",
"a",
"string"
] | 40a63c4e5ad7550f62b6860f1812cb67cafb9dc7 | https://github.com/brechtm/rinohtype/blob/40a63c4e5ad7550f62b6860f1812cb67cafb9dc7/src/rinoh/style.py#L983-L990 | train | 31,304 |
brechtm/rinohtype | src/rinoh/backend/pdf/xobject/purepng.py | _rel_import | def _rel_import(module, tgt):
"""Using relative import in both Python 2 and Python 3"""
try:
exec("from ." + module + " import " + tgt, globals(), locals())
except SyntaxError:
# On Python < 2.5 relative import cause syntax error
exec("from " + module + " import " + tgt, globals(), locals())
except (ValueError, SystemError):
# relative import in non-package, try absolute
exec("from " + module + " import " + tgt, globals(), locals())
return eval(tgt) | python | def _rel_import(module, tgt):
"""Using relative import in both Python 2 and Python 3"""
try:
exec("from ." + module + " import " + tgt, globals(), locals())
except SyntaxError:
# On Python < 2.5 relative import cause syntax error
exec("from " + module + " import " + tgt, globals(), locals())
except (ValueError, SystemError):
# relative import in non-package, try absolute
exec("from " + module + " import " + tgt, globals(), locals())
return eval(tgt) | [
"def",
"_rel_import",
"(",
"module",
",",
"tgt",
")",
":",
"try",
":",
"exec",
"(",
"\"from .\"",
"+",
"module",
"+",
"\" import \"",
"+",
"tgt",
",",
"globals",
"(",
")",
",",
"locals",
"(",
")",
")",
"except",
"SyntaxError",
":",
"# On Python < 2.5 rel... | Using relative import in both Python 2 and Python 3 | [
"Using",
"relative",
"import",
"in",
"both",
"Python",
"2",
"and",
"Python",
"3"
] | 40a63c4e5ad7550f62b6860f1812cb67cafb9dc7 | https://github.com/brechtm/rinohtype/blob/40a63c4e5ad7550f62b6860f1812cb67cafb9dc7/src/rinoh/backend/pdf/xobject/purepng.py#L207-L217 | train | 31,305 |
brechtm/rinohtype | src/rinoh/backend/pdf/xobject/purepng.py | peekiter | def peekiter(iterable):
"""Return first row and also iterable with same items as original"""
it = iter(iterable)
one = next(it)
def gen():
"""Generator that returns first and proxy other items from source"""
yield one
while True:
yield next(it)
return (one, gen()) | python | def peekiter(iterable):
"""Return first row and also iterable with same items as original"""
it = iter(iterable)
one = next(it)
def gen():
"""Generator that returns first and proxy other items from source"""
yield one
while True:
yield next(it)
return (one, gen()) | [
"def",
"peekiter",
"(",
"iterable",
")",
":",
"it",
"=",
"iter",
"(",
"iterable",
")",
"one",
"=",
"next",
"(",
"it",
")",
"def",
"gen",
"(",
")",
":",
"\"\"\"Generator that returns first and proxy other items from source\"\"\"",
"yield",
"one",
"while",
"True",... | Return first row and also iterable with same items as original | [
"Return",
"first",
"row",
"and",
"also",
"iterable",
"with",
"same",
"items",
"as",
"original"
] | 40a63c4e5ad7550f62b6860f1812cb67cafb9dc7 | https://github.com/brechtm/rinohtype/blob/40a63c4e5ad7550f62b6860f1812cb67cafb9dc7/src/rinoh/backend/pdf/xobject/purepng.py#L321-L331 | train | 31,306 |
brechtm/rinohtype | src/rinoh/backend/pdf/xobject/purepng.py | check_sizes | def check_sizes(size, width, height):
"""
Check that these arguments, in supplied, are consistent.
Return a (width, height) pair.
"""
if not size:
return width, height
if len(size) != 2:
raise ValueError(
"size argument should be a pair (width, height)")
if width is not None and width != size[0]:
raise ValueError(
"size[0] (%r) and width (%r) should match when both are used."
% (size[0], width))
if height is not None and height != size[1]:
raise ValueError(
"size[1] (%r) and height (%r) should match when both are used."
% (size[1], height))
return size | python | def check_sizes(size, width, height):
"""
Check that these arguments, in supplied, are consistent.
Return a (width, height) pair.
"""
if not size:
return width, height
if len(size) != 2:
raise ValueError(
"size argument should be a pair (width, height)")
if width is not None and width != size[0]:
raise ValueError(
"size[0] (%r) and width (%r) should match when both are used."
% (size[0], width))
if height is not None and height != size[1]:
raise ValueError(
"size[1] (%r) and height (%r) should match when both are used."
% (size[1], height))
return size | [
"def",
"check_sizes",
"(",
"size",
",",
"width",
",",
"height",
")",
":",
"if",
"not",
"size",
":",
"return",
"width",
",",
"height",
"if",
"len",
"(",
"size",
")",
"!=",
"2",
":",
"raise",
"ValueError",
"(",
"\"size argument should be a pair (width, height)... | Check that these arguments, in supplied, are consistent.
Return a (width, height) pair. | [
"Check",
"that",
"these",
"arguments",
"in",
"supplied",
"are",
"consistent",
"."
] | 40a63c4e5ad7550f62b6860f1812cb67cafb9dc7 | https://github.com/brechtm/rinohtype/blob/40a63c4e5ad7550f62b6860f1812cb67cafb9dc7/src/rinoh/backend/pdf/xobject/purepng.py#L364-L384 | train | 31,307 |
brechtm/rinohtype | src/rinoh/backend/pdf/xobject/purepng.py | check_color | def check_color(c, greyscale, which):
"""
Checks that a colour argument is the right form.
Returns the colour
(which, if it's a bar integer, is "corrected" to a 1-tuple).
For transparent or background options.
"""
if c is None:
return c
if greyscale:
try:
len(c)
except TypeError:
c = (c,)
if len(c) != 1:
raise ValueError("%s for greyscale must be 1-tuple" %
which)
if not isinteger(c[0]):
raise ValueError(
"%s colour for greyscale must be integer" % which)
else:
if not (len(c) == 3 and
isinteger(c[0]) and
isinteger(c[1]) and
isinteger(c[2])):
raise ValueError(
"%s colour must be a triple of integers" % which)
return c | python | def check_color(c, greyscale, which):
"""
Checks that a colour argument is the right form.
Returns the colour
(which, if it's a bar integer, is "corrected" to a 1-tuple).
For transparent or background options.
"""
if c is None:
return c
if greyscale:
try:
len(c)
except TypeError:
c = (c,)
if len(c) != 1:
raise ValueError("%s for greyscale must be 1-tuple" %
which)
if not isinteger(c[0]):
raise ValueError(
"%s colour for greyscale must be integer" % which)
else:
if not (len(c) == 3 and
isinteger(c[0]) and
isinteger(c[1]) and
isinteger(c[2])):
raise ValueError(
"%s colour must be a triple of integers" % which)
return c | [
"def",
"check_color",
"(",
"c",
",",
"greyscale",
",",
"which",
")",
":",
"if",
"c",
"is",
"None",
":",
"return",
"c",
"if",
"greyscale",
":",
"try",
":",
"len",
"(",
"c",
")",
"except",
"TypeError",
":",
"c",
"=",
"(",
"c",
",",
")",
"if",
"le... | Checks that a colour argument is the right form.
Returns the colour
(which, if it's a bar integer, is "corrected" to a 1-tuple).
For transparent or background options. | [
"Checks",
"that",
"a",
"colour",
"argument",
"is",
"the",
"right",
"form",
"."
] | 40a63c4e5ad7550f62b6860f1812cb67cafb9dc7 | https://github.com/brechtm/rinohtype/blob/40a63c4e5ad7550f62b6860f1812cb67cafb9dc7/src/rinoh/backend/pdf/xobject/purepng.py#L387-L415 | train | 31,308 |
brechtm/rinohtype | src/rinoh/backend/pdf/xobject/purepng.py | check_time | def check_time(value):
"""Convert time from most popular representations to datetime"""
if value is None:
return None
if isinstance(value, (time.struct_time, tuple)):
return value
if isinstance(value, datetime.datetime):
return value.timetuple()
if isinstance(value, datetime.date):
res = datetime.datetime.utcnow()
res.replace(year=value.year, month=value.month, day=value.day)
return res.timetuple()
if isinstance(value, datetime.time):
return datetime.datetime.combine(datetime.date.today(),
value).timetuple()
if isinteger(value):
# Handle integer as timestamp
return time.gmtime(value)
if isinstance(value, basestring):
if value.lower() == 'now':
return time.gmtime()
# TODO: parsinng some popular strings
raise ValueError("Unsupported time representation:" + repr(value)) | python | def check_time(value):
"""Convert time from most popular representations to datetime"""
if value is None:
return None
if isinstance(value, (time.struct_time, tuple)):
return value
if isinstance(value, datetime.datetime):
return value.timetuple()
if isinstance(value, datetime.date):
res = datetime.datetime.utcnow()
res.replace(year=value.year, month=value.month, day=value.day)
return res.timetuple()
if isinstance(value, datetime.time):
return datetime.datetime.combine(datetime.date.today(),
value).timetuple()
if isinteger(value):
# Handle integer as timestamp
return time.gmtime(value)
if isinstance(value, basestring):
if value.lower() == 'now':
return time.gmtime()
# TODO: parsinng some popular strings
raise ValueError("Unsupported time representation:" + repr(value)) | [
"def",
"check_time",
"(",
"value",
")",
":",
"if",
"value",
"is",
"None",
":",
"return",
"None",
"if",
"isinstance",
"(",
"value",
",",
"(",
"time",
".",
"struct_time",
",",
"tuple",
")",
")",
":",
"return",
"value",
"if",
"isinstance",
"(",
"value",
... | Convert time from most popular representations to datetime | [
"Convert",
"time",
"from",
"most",
"popular",
"representations",
"to",
"datetime"
] | 40a63c4e5ad7550f62b6860f1812cb67cafb9dc7 | https://github.com/brechtm/rinohtype/blob/40a63c4e5ad7550f62b6860f1812cb67cafb9dc7/src/rinoh/backend/pdf/xobject/purepng.py#L418-L440 | train | 31,309 |
brechtm/rinohtype | src/rinoh/backend/pdf/xobject/purepng.py | try_greyscale | def try_greyscale(pixels, alpha=False, dirty_alpha=True):
"""
Check if flatboxed RGB `pixels` could be converted to greyscale
If could - return iterator with greyscale pixels,
otherwise return `False` constant
"""
planes = 3 + bool(alpha)
res = list()
apix = list()
for row in pixels:
green = row[1::planes]
if alpha:
apix.append(row[4:planes])
if (green != row[0::planes] or green != row[2::planes]):
return False
else:
res.append(green)
if alpha:
return MergedPlanes(res, 1, apix, 1)
else:
return res | python | def try_greyscale(pixels, alpha=False, dirty_alpha=True):
"""
Check if flatboxed RGB `pixels` could be converted to greyscale
If could - return iterator with greyscale pixels,
otherwise return `False` constant
"""
planes = 3 + bool(alpha)
res = list()
apix = list()
for row in pixels:
green = row[1::planes]
if alpha:
apix.append(row[4:planes])
if (green != row[0::planes] or green != row[2::planes]):
return False
else:
res.append(green)
if alpha:
return MergedPlanes(res, 1, apix, 1)
else:
return res | [
"def",
"try_greyscale",
"(",
"pixels",
",",
"alpha",
"=",
"False",
",",
"dirty_alpha",
"=",
"True",
")",
":",
"planes",
"=",
"3",
"+",
"bool",
"(",
"alpha",
")",
"res",
"=",
"list",
"(",
")",
"apix",
"=",
"list",
"(",
")",
"for",
"row",
"in",
"pi... | Check if flatboxed RGB `pixels` could be converted to greyscale
If could - return iterator with greyscale pixels,
otherwise return `False` constant | [
"Check",
"if",
"flatboxed",
"RGB",
"pixels",
"could",
"be",
"converted",
"to",
"greyscale"
] | 40a63c4e5ad7550f62b6860f1812cb67cafb9dc7 | https://github.com/brechtm/rinohtype/blob/40a63c4e5ad7550f62b6860f1812cb67cafb9dc7/src/rinoh/backend/pdf/xobject/purepng.py#L456-L477 | train | 31,310 |
brechtm/rinohtype | src/rinoh/backend/pdf/xobject/purepng.py | adapt_sum | def adapt_sum(line, cfg, filter_obj):
"""Determine best filter by sum of all row values"""
lines = filter_obj.filter_all(line)
res_s = [sum(it) for it in lines]
r = res_s.index(min(res_s))
return lines[r] | python | def adapt_sum(line, cfg, filter_obj):
"""Determine best filter by sum of all row values"""
lines = filter_obj.filter_all(line)
res_s = [sum(it) for it in lines]
r = res_s.index(min(res_s))
return lines[r] | [
"def",
"adapt_sum",
"(",
"line",
",",
"cfg",
",",
"filter_obj",
")",
":",
"lines",
"=",
"filter_obj",
".",
"filter_all",
"(",
"line",
")",
"res_s",
"=",
"[",
"sum",
"(",
"it",
")",
"for",
"it",
"in",
"lines",
"]",
"r",
"=",
"res_s",
".",
"index",
... | Determine best filter by sum of all row values | [
"Determine",
"best",
"filter",
"by",
"sum",
"of",
"all",
"row",
"values"
] | 40a63c4e5ad7550f62b6860f1812cb67cafb9dc7 | https://github.com/brechtm/rinohtype/blob/40a63c4e5ad7550f62b6860f1812cb67cafb9dc7/src/rinoh/backend/pdf/xobject/purepng.py#L1780-L1785 | train | 31,311 |
brechtm/rinohtype | src/rinoh/backend/pdf/xobject/purepng.py | adapt_entropy | def adapt_entropy(line, cfg, filter_obj):
"""Determine best filter by dispersion of row values"""
lines = filter_obj.filter_all(line)
res_c = [len(set(it)) for it in lines]
r = res_c.index(min(res_c))
return lines[r] | python | def adapt_entropy(line, cfg, filter_obj):
"""Determine best filter by dispersion of row values"""
lines = filter_obj.filter_all(line)
res_c = [len(set(it)) for it in lines]
r = res_c.index(min(res_c))
return lines[r] | [
"def",
"adapt_entropy",
"(",
"line",
",",
"cfg",
",",
"filter_obj",
")",
":",
"lines",
"=",
"filter_obj",
".",
"filter_all",
"(",
"line",
")",
"res_c",
"=",
"[",
"len",
"(",
"set",
"(",
"it",
")",
")",
"for",
"it",
"in",
"lines",
"]",
"r",
"=",
"... | Determine best filter by dispersion of row values | [
"Determine",
"best",
"filter",
"by",
"dispersion",
"of",
"row",
"values"
] | 40a63c4e5ad7550f62b6860f1812cb67cafb9dc7 | https://github.com/brechtm/rinohtype/blob/40a63c4e5ad7550f62b6860f1812cb67cafb9dc7/src/rinoh/backend/pdf/xobject/purepng.py#L1789-L1794 | train | 31,312 |
brechtm/rinohtype | src/rinoh/backend/pdf/xobject/purepng.py | BaseFilter.__do_filter_sub | def __do_filter_sub(self, scanline, result):
"""Sub filter."""
ai = 0
for i in range(self.fu, len(result)):
x = scanline[i]
a = scanline[ai]
result[i] = (x - a) & 0xff
ai += 1 | python | def __do_filter_sub(self, scanline, result):
"""Sub filter."""
ai = 0
for i in range(self.fu, len(result)):
x = scanline[i]
a = scanline[ai]
result[i] = (x - a) & 0xff
ai += 1 | [
"def",
"__do_filter_sub",
"(",
"self",
",",
"scanline",
",",
"result",
")",
":",
"ai",
"=",
"0",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"fu",
",",
"len",
"(",
"result",
")",
")",
":",
"x",
"=",
"scanline",
"[",
"i",
"]",
"a",
"=",
"scanli... | Sub filter. | [
"Sub",
"filter",
"."
] | 40a63c4e5ad7550f62b6860f1812cb67cafb9dc7 | https://github.com/brechtm/rinohtype/blob/40a63c4e5ad7550f62b6860f1812cb67cafb9dc7/src/rinoh/backend/pdf/xobject/purepng.py#L529-L536 | train | 31,313 |
brechtm/rinohtype | src/rinoh/backend/pdf/xobject/purepng.py | BaseFilter.__do_filter_up | def __do_filter_up(self, scanline, result):
"""Up filter."""
previous = self.prev
for i in range(len(result)):
x = scanline[i]
b = previous[i]
result[i] = (x - b) & 0xff | python | def __do_filter_up(self, scanline, result):
"""Up filter."""
previous = self.prev
for i in range(len(result)):
x = scanline[i]
b = previous[i]
result[i] = (x - b) & 0xff | [
"def",
"__do_filter_up",
"(",
"self",
",",
"scanline",
",",
"result",
")",
":",
"previous",
"=",
"self",
".",
"prev",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"result",
")",
")",
":",
"x",
"=",
"scanline",
"[",
"i",
"]",
"b",
"=",
"previous",
... | Up filter. | [
"Up",
"filter",
"."
] | 40a63c4e5ad7550f62b6860f1812cb67cafb9dc7 | https://github.com/brechtm/rinohtype/blob/40a63c4e5ad7550f62b6860f1812cb67cafb9dc7/src/rinoh/backend/pdf/xobject/purepng.py#L546-L552 | train | 31,314 |
brechtm/rinohtype | src/rinoh/backend/pdf/xobject/purepng.py | BaseFilter.__undo_filter_average | def __undo_filter_average(self, scanline):
"""Undo average filter."""
ai = -self.fu
previous = self.prev
for i in range(len(scanline)):
x = scanline[i]
if ai < 0:
a = 0
else:
a = scanline[ai] # result
b = previous[i]
scanline[i] = (x + ((a + b) >> 1)) & 0xff # result
ai += 1 | python | def __undo_filter_average(self, scanline):
"""Undo average filter."""
ai = -self.fu
previous = self.prev
for i in range(len(scanline)):
x = scanline[i]
if ai < 0:
a = 0
else:
a = scanline[ai] # result
b = previous[i]
scanline[i] = (x + ((a + b) >> 1)) & 0xff # result
ai += 1 | [
"def",
"__undo_filter_average",
"(",
"self",
",",
"scanline",
")",
":",
"ai",
"=",
"-",
"self",
".",
"fu",
"previous",
"=",
"self",
".",
"prev",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"scanline",
")",
")",
":",
"x",
"=",
"scanline",
"[",
"i",
... | Undo average filter. | [
"Undo",
"average",
"filter",
"."
] | 40a63c4e5ad7550f62b6860f1812cb67cafb9dc7 | https://github.com/brechtm/rinohtype/blob/40a63c4e5ad7550f62b6860f1812cb67cafb9dc7/src/rinoh/backend/pdf/xobject/purepng.py#L554-L566 | train | 31,315 |
brechtm/rinohtype | src/rinoh/backend/pdf/xobject/purepng.py | BaseFilter.undo_filter | def undo_filter(self, filter_type, line):
"""
Undo the filter for a scanline.
`scanline` is a sequence of bytes that does not include
the initial filter type byte.
The scanline will have the effects of filtering removed.
Scanline modified inplace and also returned as result.
"""
assert 0 <= filter_type <= 4
# For the first line of a pass, synthesize a dummy previous line.
if self.prev is None:
self.prev = newBarray(len(line))
# Also it's possible to switch some filters to easier
if filter_type == 2: # "up"
filter_type = 0
elif filter_type == 4: # "paeth"
filter_type = 1
# Call appropriate filter algorithm.
# 0 - do nothing
if filter_type == 1:
self.__undo_filter_sub(line)
elif filter_type == 2:
self.__undo_filter_up(line)
elif filter_type == 3:
self.__undo_filter_average(line)
elif filter_type == 4:
self.__undo_filter_paeth(line)
# This will not work writing cython attributes from python
# Only 'cython from cython' or 'python from python'
self.prev[:] = line[:]
return line | python | def undo_filter(self, filter_type, line):
"""
Undo the filter for a scanline.
`scanline` is a sequence of bytes that does not include
the initial filter type byte.
The scanline will have the effects of filtering removed.
Scanline modified inplace and also returned as result.
"""
assert 0 <= filter_type <= 4
# For the first line of a pass, synthesize a dummy previous line.
if self.prev is None:
self.prev = newBarray(len(line))
# Also it's possible to switch some filters to easier
if filter_type == 2: # "up"
filter_type = 0
elif filter_type == 4: # "paeth"
filter_type = 1
# Call appropriate filter algorithm.
# 0 - do nothing
if filter_type == 1:
self.__undo_filter_sub(line)
elif filter_type == 2:
self.__undo_filter_up(line)
elif filter_type == 3:
self.__undo_filter_average(line)
elif filter_type == 4:
self.__undo_filter_paeth(line)
# This will not work writing cython attributes from python
# Only 'cython from cython' or 'python from python'
self.prev[:] = line[:]
return line | [
"def",
"undo_filter",
"(",
"self",
",",
"filter_type",
",",
"line",
")",
":",
"assert",
"0",
"<=",
"filter_type",
"<=",
"4",
"# For the first line of a pass, synthesize a dummy previous line.",
"if",
"self",
".",
"prev",
"is",
"None",
":",
"self",
".",
"prev",
"... | Undo the filter for a scanline.
`scanline` is a sequence of bytes that does not include
the initial filter type byte.
The scanline will have the effects of filtering removed.
Scanline modified inplace and also returned as result. | [
"Undo",
"the",
"filter",
"for",
"a",
"scanline",
"."
] | 40a63c4e5ad7550f62b6860f1812cb67cafb9dc7 | https://github.com/brechtm/rinohtype/blob/40a63c4e5ad7550f62b6860f1812cb67cafb9dc7/src/rinoh/backend/pdf/xobject/purepng.py#L631-L665 | train | 31,316 |
brechtm/rinohtype | src/rinoh/backend/pdf/xobject/purepng.py | BaseFilter._filter_scanline | def _filter_scanline(self, filter_type, line, result):
"""
Apply a scanline filter to a scanline.
`filter_type` specifies the filter type (0 to 4)
'line` specifies the current (unfiltered) scanline as a sequence
of bytes;
"""
assert 0 <= filter_type < 5
if self.prev is None:
# We're on the first line. Some of the filters can be reduced
# to simpler cases which makes handling the line "off the top"
# of the image simpler. "up" becomes "none"; "paeth" becomes
# "left" (non-trivial, but true). "average" needs to be handled
# specially.
if filter_type == 2: # "up"
filter_type = 0
elif filter_type == 3:
self.prev = newBarray(len(line))
elif filter_type == 4: # "paeth"
filter_type = 1
if filter_type == 1:
self.__do_filter_sub(line, result)
elif filter_type == 2:
self.__do_filter_up(line, result)
elif filter_type == 3:
self.__do_filter_average(line, result)
elif filter_type == 4:
self.__do_filter_paeth(line, result) | python | def _filter_scanline(self, filter_type, line, result):
"""
Apply a scanline filter to a scanline.
`filter_type` specifies the filter type (0 to 4)
'line` specifies the current (unfiltered) scanline as a sequence
of bytes;
"""
assert 0 <= filter_type < 5
if self.prev is None:
# We're on the first line. Some of the filters can be reduced
# to simpler cases which makes handling the line "off the top"
# of the image simpler. "up" becomes "none"; "paeth" becomes
# "left" (non-trivial, but true). "average" needs to be handled
# specially.
if filter_type == 2: # "up"
filter_type = 0
elif filter_type == 3:
self.prev = newBarray(len(line))
elif filter_type == 4: # "paeth"
filter_type = 1
if filter_type == 1:
self.__do_filter_sub(line, result)
elif filter_type == 2:
self.__do_filter_up(line, result)
elif filter_type == 3:
self.__do_filter_average(line, result)
elif filter_type == 4:
self.__do_filter_paeth(line, result) | [
"def",
"_filter_scanline",
"(",
"self",
",",
"filter_type",
",",
"line",
",",
"result",
")",
":",
"assert",
"0",
"<=",
"filter_type",
"<",
"5",
"if",
"self",
".",
"prev",
"is",
"None",
":",
"# We're on the first line. Some of the filters can be reduced",
"# to si... | Apply a scanline filter to a scanline.
`filter_type` specifies the filter type (0 to 4)
'line` specifies the current (unfiltered) scanline as a sequence
of bytes; | [
"Apply",
"a",
"scanline",
"filter",
"to",
"a",
"scanline",
"."
] | 40a63c4e5ad7550f62b6860f1812cb67cafb9dc7 | https://github.com/brechtm/rinohtype/blob/40a63c4e5ad7550f62b6860f1812cb67cafb9dc7/src/rinoh/backend/pdf/xobject/purepng.py#L667-L696 | train | 31,317 |
brechtm/rinohtype | src/rinoh/backend/pdf/xobject/purepng.py | BaseFilter.convert_la_to_rgba | def convert_la_to_rgba(self, row, result):
"""Convert a grayscale image with alpha to RGBA."""
for i in range(len(row) // 3):
for j in range(3):
result[(4 * i) + j] = row[2 * i]
result[(4 * i) + 3] = row[(2 * i) + 1] | python | def convert_la_to_rgba(self, row, result):
"""Convert a grayscale image with alpha to RGBA."""
for i in range(len(row) // 3):
for j in range(3):
result[(4 * i) + j] = row[2 * i]
result[(4 * i) + 3] = row[(2 * i) + 1] | [
"def",
"convert_la_to_rgba",
"(",
"self",
",",
"row",
",",
"result",
")",
":",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"row",
")",
"//",
"3",
")",
":",
"for",
"j",
"in",
"range",
"(",
"3",
")",
":",
"result",
"[",
"(",
"4",
"*",
"i",
")",... | Convert a grayscale image with alpha to RGBA. | [
"Convert",
"a",
"grayscale",
"image",
"with",
"alpha",
"to",
"RGBA",
"."
] | 40a63c4e5ad7550f62b6860f1812cb67cafb9dc7 | https://github.com/brechtm/rinohtype/blob/40a63c4e5ad7550f62b6860f1812cb67cafb9dc7/src/rinoh/backend/pdf/xobject/purepng.py#L700-L705 | train | 31,318 |
brechtm/rinohtype | src/rinoh/backend/pdf/xobject/purepng.py | BaseFilter.convert_l_to_rgba | def convert_l_to_rgba(self, row, result):
"""
Convert a grayscale image to RGBA.
This method assumes the alpha channel in result is already
correctly initialized.
"""
for i in range(len(row) // 3):
for j in range(3):
result[(4 * i) + j] = row[i] | python | def convert_l_to_rgba(self, row, result):
"""
Convert a grayscale image to RGBA.
This method assumes the alpha channel in result is already
correctly initialized.
"""
for i in range(len(row) // 3):
for j in range(3):
result[(4 * i) + j] = row[i] | [
"def",
"convert_l_to_rgba",
"(",
"self",
",",
"row",
",",
"result",
")",
":",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"row",
")",
"//",
"3",
")",
":",
"for",
"j",
"in",
"range",
"(",
"3",
")",
":",
"result",
"[",
"(",
"4",
"*",
"i",
")",
... | Convert a grayscale image to RGBA.
This method assumes the alpha channel in result is already
correctly initialized. | [
"Convert",
"a",
"grayscale",
"image",
"to",
"RGBA",
"."
] | 40a63c4e5ad7550f62b6860f1812cb67cafb9dc7 | https://github.com/brechtm/rinohtype/blob/40a63c4e5ad7550f62b6860f1812cb67cafb9dc7/src/rinoh/backend/pdf/xobject/purepng.py#L707-L716 | train | 31,319 |
brechtm/rinohtype | src/rinoh/backend/pdf/xobject/purepng.py | BaseFilter.convert_rgb_to_rgba | def convert_rgb_to_rgba(self, row, result):
"""
Convert an RGB image to RGBA.
This method assumes the alpha channel in result is already
correctly initialized.
"""
for i in range(len(row) // 3):
for j in range(3):
result[(4 * i) + j] = row[(3 * i) + j] | python | def convert_rgb_to_rgba(self, row, result):
"""
Convert an RGB image to RGBA.
This method assumes the alpha channel in result is already
correctly initialized.
"""
for i in range(len(row) // 3):
for j in range(3):
result[(4 * i) + j] = row[(3 * i) + j] | [
"def",
"convert_rgb_to_rgba",
"(",
"self",
",",
"row",
",",
"result",
")",
":",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"row",
")",
"//",
"3",
")",
":",
"for",
"j",
"in",
"range",
"(",
"3",
")",
":",
"result",
"[",
"(",
"4",
"*",
"i",
")"... | Convert an RGB image to RGBA.
This method assumes the alpha channel in result is already
correctly initialized. | [
"Convert",
"an",
"RGB",
"image",
"to",
"RGBA",
"."
] | 40a63c4e5ad7550f62b6860f1812cb67cafb9dc7 | https://github.com/brechtm/rinohtype/blob/40a63c4e5ad7550f62b6860f1812cb67cafb9dc7/src/rinoh/backend/pdf/xobject/purepng.py#L718-L727 | train | 31,320 |
brechtm/rinohtype | src/rinoh/backend/pdf/xobject/purepng.py | Writer.set_icc_profile | def set_icc_profile(self, profile=None, name='ICC Profile'):
"""
Add ICC Profile.
Prefered way is tuple (`profile_name`, `profile_bytes`), but only
bytes with name as separate argument is also supported.
"""
if isinstance(profile, (basestring, bytes)):
icc_profile = [name, profile]
# TODO: more check
else:
icc_profile = profile
if not icc_profile[0]:
raise Error("ICC profile should have a name")
elif not isinstance(icc_profile[0], bytes):
icc_profile[0] = strtobytes(icc_profile[0])
self.icc_profile = icc_profile | python | def set_icc_profile(self, profile=None, name='ICC Profile'):
"""
Add ICC Profile.
Prefered way is tuple (`profile_name`, `profile_bytes`), but only
bytes with name as separate argument is also supported.
"""
if isinstance(profile, (basestring, bytes)):
icc_profile = [name, profile]
# TODO: more check
else:
icc_profile = profile
if not icc_profile[0]:
raise Error("ICC profile should have a name")
elif not isinstance(icc_profile[0], bytes):
icc_profile[0] = strtobytes(icc_profile[0])
self.icc_profile = icc_profile | [
"def",
"set_icc_profile",
"(",
"self",
",",
"profile",
"=",
"None",
",",
"name",
"=",
"'ICC Profile'",
")",
":",
"if",
"isinstance",
"(",
"profile",
",",
"(",
"basestring",
",",
"bytes",
")",
")",
":",
"icc_profile",
"=",
"[",
"name",
",",
"profile",
"... | Add ICC Profile.
Prefered way is tuple (`profile_name`, `profile_bytes`), but only
bytes with name as separate argument is also supported. | [
"Add",
"ICC",
"Profile",
"."
] | 40a63c4e5ad7550f62b6860f1812cb67cafb9dc7 | https://github.com/brechtm/rinohtype/blob/40a63c4e5ad7550f62b6860f1812cb67cafb9dc7/src/rinoh/backend/pdf/xobject/purepng.py#L980-L997 | train | 31,321 |
brechtm/rinohtype | src/rinoh/backend/pdf/xobject/purepng.py | Writer.set_text | def set_text(self, text=None, **kwargs):
"""
Add textual information passed as dictionary.
All pairs in dictionary will be written, but keys should be latin-1;
registered keywords could be used as arguments.
When called more than once overwrite exist data.
"""
if text is None:
text = {}
text.update(popdict(kwargs, _registered_kw))
if 'Creation Time' in text and\
not isinstance(text['Creation Time'], (basestring, bytes)):
text['Creation Time'] = datetime.datetime(
*(check_time(text['Creation Time'])[:6])).isoformat()
self.text = text | python | def set_text(self, text=None, **kwargs):
"""
Add textual information passed as dictionary.
All pairs in dictionary will be written, but keys should be latin-1;
registered keywords could be used as arguments.
When called more than once overwrite exist data.
"""
if text is None:
text = {}
text.update(popdict(kwargs, _registered_kw))
if 'Creation Time' in text and\
not isinstance(text['Creation Time'], (basestring, bytes)):
text['Creation Time'] = datetime.datetime(
*(check_time(text['Creation Time'])[:6])).isoformat()
self.text = text | [
"def",
"set_text",
"(",
"self",
",",
"text",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"text",
"is",
"None",
":",
"text",
"=",
"{",
"}",
"text",
".",
"update",
"(",
"popdict",
"(",
"kwargs",
",",
"_registered_kw",
")",
")",
"if",
"'Cr... | Add textual information passed as dictionary.
All pairs in dictionary will be written, but keys should be latin-1;
registered keywords could be used as arguments.
When called more than once overwrite exist data. | [
"Add",
"textual",
"information",
"passed",
"as",
"dictionary",
"."
] | 40a63c4e5ad7550f62b6860f1812cb67cafb9dc7 | https://github.com/brechtm/rinohtype/blob/40a63c4e5ad7550f62b6860f1812cb67cafb9dc7/src/rinoh/backend/pdf/xobject/purepng.py#L999-L1015 | train | 31,322 |
brechtm/rinohtype | src/rinoh/backend/pdf/xobject/purepng.py | Writer.set_modification_time | def set_modification_time(self, modification_time=True):
"""
Add time to be written as last modification time
When called after initialisation configure to use
time of writing file
"""
if (isinstance(modification_time, basestring) and
modification_time.lower() == 'write') or\
modification_time is True:
self.modification_time = True
else:
self.modification_time = check_time(modification_time) | python | def set_modification_time(self, modification_time=True):
"""
Add time to be written as last modification time
When called after initialisation configure to use
time of writing file
"""
if (isinstance(modification_time, basestring) and
modification_time.lower() == 'write') or\
modification_time is True:
self.modification_time = True
else:
self.modification_time = check_time(modification_time) | [
"def",
"set_modification_time",
"(",
"self",
",",
"modification_time",
"=",
"True",
")",
":",
"if",
"(",
"isinstance",
"(",
"modification_time",
",",
"basestring",
")",
"and",
"modification_time",
".",
"lower",
"(",
")",
"==",
"'write'",
")",
"or",
"modificati... | Add time to be written as last modification time
When called after initialisation configure to use
time of writing file | [
"Add",
"time",
"to",
"be",
"written",
"as",
"last",
"modification",
"time"
] | 40a63c4e5ad7550f62b6860f1812cb67cafb9dc7 | https://github.com/brechtm/rinohtype/blob/40a63c4e5ad7550f62b6860f1812cb67cafb9dc7/src/rinoh/backend/pdf/xobject/purepng.py#L1042-L1054 | train | 31,323 |
brechtm/rinohtype | src/rinoh/backend/pdf/xobject/purepng.py | Writer.set_resolution | def set_resolution(self, resolution=None):
"""
Add physical pixel dimensions
`resolution` supposed two be tuple of two parameterts: pixels per unit
and unit type; unit type may be omitted
pixels per unit could be simple integer or tuple of (ppu_x, ppu_y)
Also possible to use all three parameters im row
* resolution = ((1, 4), ) # wide pixels (4:1) without unit specifier
* resolution = (300, 'inch') # 300dpi in both dimensions
* resolution = (4, 1, 0) # tall pixels (1:4) without unit specifier
"""
if resolution is None:
self.resolution = None
return
# All in row
if len(resolution) == 3:
resolution = ((resolution[0], resolution[1]), resolution[2])
# Ensure length and convert all false to 0 (no unit)
if len(resolution) == 1 or not resolution[1]:
resolution = (resolution[0], 0)
# Single dimension
if isinstance(resolution[0], float) or isinteger(resolution[0]):
resolution = ((resolution[0], resolution[0]), resolution[1])
# Unit conversion
if resolution[1] in (1, 'm', 'meter'):
resolution = (resolution[0], 1)
elif resolution[1] in ('i', 'in', 'inch'):
resolution = ((int(resolution[0][0] / 0.0254 + 0.5),
int(resolution[0][1] / 0.0254 + 0.5)), 1)
elif resolution[1] in ('cm', 'centimeter'):
resolution = ((resolution[0][0] * 100,
resolution[0][1] * 100), 1)
self.resolution = resolution | python | def set_resolution(self, resolution=None):
"""
Add physical pixel dimensions
`resolution` supposed two be tuple of two parameterts: pixels per unit
and unit type; unit type may be omitted
pixels per unit could be simple integer or tuple of (ppu_x, ppu_y)
Also possible to use all three parameters im row
* resolution = ((1, 4), ) # wide pixels (4:1) without unit specifier
* resolution = (300, 'inch') # 300dpi in both dimensions
* resolution = (4, 1, 0) # tall pixels (1:4) without unit specifier
"""
if resolution is None:
self.resolution = None
return
# All in row
if len(resolution) == 3:
resolution = ((resolution[0], resolution[1]), resolution[2])
# Ensure length and convert all false to 0 (no unit)
if len(resolution) == 1 or not resolution[1]:
resolution = (resolution[0], 0)
# Single dimension
if isinstance(resolution[0], float) or isinteger(resolution[0]):
resolution = ((resolution[0], resolution[0]), resolution[1])
# Unit conversion
if resolution[1] in (1, 'm', 'meter'):
resolution = (resolution[0], 1)
elif resolution[1] in ('i', 'in', 'inch'):
resolution = ((int(resolution[0][0] / 0.0254 + 0.5),
int(resolution[0][1] / 0.0254 + 0.5)), 1)
elif resolution[1] in ('cm', 'centimeter'):
resolution = ((resolution[0][0] * 100,
resolution[0][1] * 100), 1)
self.resolution = resolution | [
"def",
"set_resolution",
"(",
"self",
",",
"resolution",
"=",
"None",
")",
":",
"if",
"resolution",
"is",
"None",
":",
"self",
".",
"resolution",
"=",
"None",
"return",
"# All in row",
"if",
"len",
"(",
"resolution",
")",
"==",
"3",
":",
"resolution",
"=... | Add physical pixel dimensions
`resolution` supposed two be tuple of two parameterts: pixels per unit
and unit type; unit type may be omitted
pixels per unit could be simple integer or tuple of (ppu_x, ppu_y)
Also possible to use all three parameters im row
* resolution = ((1, 4), ) # wide pixels (4:1) without unit specifier
* resolution = (300, 'inch') # 300dpi in both dimensions
* resolution = (4, 1, 0) # tall pixels (1:4) without unit specifier | [
"Add",
"physical",
"pixel",
"dimensions"
] | 40a63c4e5ad7550f62b6860f1812cb67cafb9dc7 | https://github.com/brechtm/rinohtype/blob/40a63c4e5ad7550f62b6860f1812cb67cafb9dc7/src/rinoh/backend/pdf/xobject/purepng.py#L1056-L1090 | train | 31,324 |
brechtm/rinohtype | src/rinoh/backend/pdf/xobject/purepng.py | Writer.set_rendering_intent | def set_rendering_intent(self, rendering_intent):
"""Set rendering intent variant for sRGB chunk"""
if rendering_intent not in (None,
PERCEPTUAL,
RELATIVE_COLORIMETRIC,
SATURATION,
ABSOLUTE_COLORIMETRIC):
raise FormatError('Unknown redering intent')
self.rendering_intent = rendering_intent | python | def set_rendering_intent(self, rendering_intent):
"""Set rendering intent variant for sRGB chunk"""
if rendering_intent not in (None,
PERCEPTUAL,
RELATIVE_COLORIMETRIC,
SATURATION,
ABSOLUTE_COLORIMETRIC):
raise FormatError('Unknown redering intent')
self.rendering_intent = rendering_intent | [
"def",
"set_rendering_intent",
"(",
"self",
",",
"rendering_intent",
")",
":",
"if",
"rendering_intent",
"not",
"in",
"(",
"None",
",",
"PERCEPTUAL",
",",
"RELATIVE_COLORIMETRIC",
",",
"SATURATION",
",",
"ABSOLUTE_COLORIMETRIC",
")",
":",
"raise",
"FormatError",
"... | Set rendering intent variant for sRGB chunk | [
"Set",
"rendering",
"intent",
"variant",
"for",
"sRGB",
"chunk"
] | 40a63c4e5ad7550f62b6860f1812cb67cafb9dc7 | https://github.com/brechtm/rinohtype/blob/40a63c4e5ad7550f62b6860f1812cb67cafb9dc7/src/rinoh/backend/pdf/xobject/purepng.py#L1092-L1100 | train | 31,325 |
brechtm/rinohtype | src/rinoh/backend/pdf/xobject/purepng.py | Writer.set_white_point | def set_white_point(self, white_point, point2=None):
"""Set white point part of cHRM chunk"""
if isinstance(white_point, float) and isinstance(point2, float):
white_point = (white_point, point2)
self.white_point = white_point | python | def set_white_point(self, white_point, point2=None):
"""Set white point part of cHRM chunk"""
if isinstance(white_point, float) and isinstance(point2, float):
white_point = (white_point, point2)
self.white_point = white_point | [
"def",
"set_white_point",
"(",
"self",
",",
"white_point",
",",
"point2",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"white_point",
",",
"float",
")",
"and",
"isinstance",
"(",
"point2",
",",
"float",
")",
":",
"white_point",
"=",
"(",
"white_point",
... | Set white point part of cHRM chunk | [
"Set",
"white",
"point",
"part",
"of",
"cHRM",
"chunk"
] | 40a63c4e5ad7550f62b6860f1812cb67cafb9dc7 | https://github.com/brechtm/rinohtype/blob/40a63c4e5ad7550f62b6860f1812cb67cafb9dc7/src/rinoh/backend/pdf/xobject/purepng.py#L1102-L1106 | train | 31,326 |
brechtm/rinohtype | src/rinoh/backend/pdf/xobject/purepng.py | Writer.set_rgb_points | def set_rgb_points(self, rgb_points, *args):
"""Set rgb points part of cHRM chunk"""
if not args:
self.rgb_points = rgb_points
# separate tuples
elif len(args) == 2:
self.rgb_points = (rgb_points, args[0], args[1])
# separate numbers
elif len(args) == 5:
self.rgb_points = ((rgb_points, args[0]),
(args[1], args[2]),
(args[3], args[4])) | python | def set_rgb_points(self, rgb_points, *args):
"""Set rgb points part of cHRM chunk"""
if not args:
self.rgb_points = rgb_points
# separate tuples
elif len(args) == 2:
self.rgb_points = (rgb_points, args[0], args[1])
# separate numbers
elif len(args) == 5:
self.rgb_points = ((rgb_points, args[0]),
(args[1], args[2]),
(args[3], args[4])) | [
"def",
"set_rgb_points",
"(",
"self",
",",
"rgb_points",
",",
"*",
"args",
")",
":",
"if",
"not",
"args",
":",
"self",
".",
"rgb_points",
"=",
"rgb_points",
"# separate tuples",
"elif",
"len",
"(",
"args",
")",
"==",
"2",
":",
"self",
".",
"rgb_points",
... | Set rgb points part of cHRM chunk | [
"Set",
"rgb",
"points",
"part",
"of",
"cHRM",
"chunk"
] | 40a63c4e5ad7550f62b6860f1812cb67cafb9dc7 | https://github.com/brechtm/rinohtype/blob/40a63c4e5ad7550f62b6860f1812cb67cafb9dc7/src/rinoh/backend/pdf/xobject/purepng.py#L1108-L1119 | train | 31,327 |
brechtm/rinohtype | src/rinoh/backend/pdf/xobject/purepng.py | Writer.__write_palette | def __write_palette(self, outfile):
"""
Write``PLTE`` and if necessary a ``tRNS`` chunk to.
This method should be called only from ``write_idat`` method
or chunk order will be ruined.
"""
# We must have true bitdepth within palette to use sBIT with palette
# if self.pixbitdepth != 8:
# write_chunk(outfile, 'sBIT',
# bytearray_to_bytes(bytearray((self.pixbitdepth,) * 3)))
p = bytearray()
t = bytearray()
for x in self.palette:
p.extend(x[0:3])
if len(x) > 3:
t.append(x[3])
write_chunk(outfile, 'PLTE', bytearray_to_bytes(p))
if t:
# tRNS chunk is optional. Only needed if palette entries
# have alpha.
write_chunk(outfile, 'tRNS', bytearray_to_bytes(t)) | python | def __write_palette(self, outfile):
"""
Write``PLTE`` and if necessary a ``tRNS`` chunk to.
This method should be called only from ``write_idat`` method
or chunk order will be ruined.
"""
# We must have true bitdepth within palette to use sBIT with palette
# if self.pixbitdepth != 8:
# write_chunk(outfile, 'sBIT',
# bytearray_to_bytes(bytearray((self.pixbitdepth,) * 3)))
p = bytearray()
t = bytearray()
for x in self.palette:
p.extend(x[0:3])
if len(x) > 3:
t.append(x[3])
write_chunk(outfile, 'PLTE', bytearray_to_bytes(p))
if t:
# tRNS chunk is optional. Only needed if palette entries
# have alpha.
write_chunk(outfile, 'tRNS', bytearray_to_bytes(t)) | [
"def",
"__write_palette",
"(",
"self",
",",
"outfile",
")",
":",
"# We must have true bitdepth within palette to use sBIT with palette",
"# if self.pixbitdepth != 8:",
"# write_chunk(outfile, 'sBIT',",
"# bytearray_to_bytes(bytearray((self.pixbitdepth,) * 3)))",
"p",
"=",
... | Write``PLTE`` and if necessary a ``tRNS`` chunk to.
This method should be called only from ``write_idat`` method
or chunk order will be ruined. | [
"Write",
"PLTE",
"and",
"if",
"necessary",
"a",
"tRNS",
"chunk",
"to",
"."
] | 40a63c4e5ad7550f62b6860f1812cb67cafb9dc7 | https://github.com/brechtm/rinohtype/blob/40a63c4e5ad7550f62b6860f1812cb67cafb9dc7/src/rinoh/backend/pdf/xobject/purepng.py#L1121-L1144 | train | 31,328 |
brechtm/rinohtype | src/rinoh/backend/pdf/xobject/purepng.py | Writer.__write_text | def __write_text(self, outfile):
"""
Write text information into file
This method should be called only from ``write_idat`` method
or chunk order will be ruined.
"""
for k, v in self.text.items():
if not isinstance(v, bytes):
try:
international = False
v = v.encode('latin-1')
except UnicodeEncodeError:
international = True
v = v.encode('utf-8')
else:
international = False
if not isinstance(k, bytes):
k = strtobytes(k)
if international:
# No compress, language tag or translated keyword for now
write_chunk(outfile, 'iTXt', k + zerobyte +
zerobyte + zerobyte +
zerobyte + zerobyte + v)
else:
write_chunk(outfile, 'tEXt', k + zerobyte + v) | python | def __write_text(self, outfile):
"""
Write text information into file
This method should be called only from ``write_idat`` method
or chunk order will be ruined.
"""
for k, v in self.text.items():
if not isinstance(v, bytes):
try:
international = False
v = v.encode('latin-1')
except UnicodeEncodeError:
international = True
v = v.encode('utf-8')
else:
international = False
if not isinstance(k, bytes):
k = strtobytes(k)
if international:
# No compress, language tag or translated keyword for now
write_chunk(outfile, 'iTXt', k + zerobyte +
zerobyte + zerobyte +
zerobyte + zerobyte + v)
else:
write_chunk(outfile, 'tEXt', k + zerobyte + v) | [
"def",
"__write_text",
"(",
"self",
",",
"outfile",
")",
":",
"for",
"k",
",",
"v",
"in",
"self",
".",
"text",
".",
"items",
"(",
")",
":",
"if",
"not",
"isinstance",
"(",
"v",
",",
"bytes",
")",
":",
"try",
":",
"international",
"=",
"False",
"v... | Write text information into file
This method should be called only from ``write_idat`` method
or chunk order will be ruined. | [
"Write",
"text",
"information",
"into",
"file"
] | 40a63c4e5ad7550f62b6860f1812cb67cafb9dc7 | https://github.com/brechtm/rinohtype/blob/40a63c4e5ad7550f62b6860f1812cb67cafb9dc7/src/rinoh/backend/pdf/xobject/purepng.py#L1191-L1216 | train | 31,329 |
brechtm/rinohtype | src/rinoh/backend/pdf/xobject/purepng.py | Writer.write_idat | def write_idat(self, outfile, idat_sequence):
"""
Write png with IDAT to file
`idat_sequence` should be iterable that produce IDAT chunks
compatible with `Writer` configuration.
"""
# http://www.w3.org/TR/PNG/#5PNG-file-signature
outfile.write(png_signature)
color_type = 4 * self.alpha + 2 * (not self.greyscale) +\
bool(self.palette)
# http://www.w3.org/TR/PNG/#11IHDR
write_chunk(outfile, 'IHDR',
struct.pack("!2I5B", self.width, self.height,
self.bitdepth, color_type,
0, 0, self.interlace))
# See :chunk:order
self.__write_srgb(outfile)
# See :chunk:order
# http://www.w3.org/TR/PNG/#11sBIT
if not self.palette and self.pixbitdepth != self.bitdepth:
# Write sBIT of palette within __write_palette
# TODO: support different bitdepth per plane
write_chunk(outfile, 'sBIT',
struct.pack('%dB' % self.planes,
*[self.pixbitdepth] * self.planes))
# :chunk:order: Without a palette (PLTE chunk), ordering is
# relatively relaxed. With one, gamma info must precede PLTE
# chunk which must precede tRNS and bKGD.
# See http://www.w3.org/TR/PNG/#5ChunkOrdering
if self.palette:
self.__write_palette(outfile)
# http://www.w3.org/TR/PNG/#11tRNS
if self.transparent is not None:
if self.greyscale:
write_chunk(outfile, 'tRNS',
struct.pack("!1H", *self.transparent))
else:
write_chunk(outfile, 'tRNS',
struct.pack("!3H", *self.transparent))
# http://www.w3.org/TR/PNG/#11bKGD
if self.background is not None:
if self.greyscale:
write_chunk(outfile, 'bKGD',
struct.pack("!1H", *self.background))
else:
write_chunk(outfile, 'bKGD',
struct.pack("!3H", *self.background))
# http://www.w3.org/TR/PNG/#11pHYs
if self.resolution is not None:
write_chunk(outfile, 'pHYs',
struct.pack("!IIB",
self.resolution[0][0],
self.resolution[0][1],
self.resolution[1]))
# http://www.w3.org/TR/PNG/#11tIME
if self.modification_time is not None:
if self.modification_time is True:
self.modification_time = check_time('now')
write_chunk(outfile, 'tIME',
struct.pack("!H5B", *(self.modification_time[:6])))
# http://www.w3.org/TR/PNG/#11textinfo
if self.text:
self.__write_text(outfile)
for idat in idat_sequence:
write_chunk(outfile, 'IDAT', idat)
# http://www.w3.org/TR/PNG/#11IEND
write_chunk(outfile, 'IEND') | python | def write_idat(self, outfile, idat_sequence):
"""
Write png with IDAT to file
`idat_sequence` should be iterable that produce IDAT chunks
compatible with `Writer` configuration.
"""
# http://www.w3.org/TR/PNG/#5PNG-file-signature
outfile.write(png_signature)
color_type = 4 * self.alpha + 2 * (not self.greyscale) +\
bool(self.palette)
# http://www.w3.org/TR/PNG/#11IHDR
write_chunk(outfile, 'IHDR',
struct.pack("!2I5B", self.width, self.height,
self.bitdepth, color_type,
0, 0, self.interlace))
# See :chunk:order
self.__write_srgb(outfile)
# See :chunk:order
# http://www.w3.org/TR/PNG/#11sBIT
if not self.palette and self.pixbitdepth != self.bitdepth:
# Write sBIT of palette within __write_palette
# TODO: support different bitdepth per plane
write_chunk(outfile, 'sBIT',
struct.pack('%dB' % self.planes,
*[self.pixbitdepth] * self.planes))
# :chunk:order: Without a palette (PLTE chunk), ordering is
# relatively relaxed. With one, gamma info must precede PLTE
# chunk which must precede tRNS and bKGD.
# See http://www.w3.org/TR/PNG/#5ChunkOrdering
if self.palette:
self.__write_palette(outfile)
# http://www.w3.org/TR/PNG/#11tRNS
if self.transparent is not None:
if self.greyscale:
write_chunk(outfile, 'tRNS',
struct.pack("!1H", *self.transparent))
else:
write_chunk(outfile, 'tRNS',
struct.pack("!3H", *self.transparent))
# http://www.w3.org/TR/PNG/#11bKGD
if self.background is not None:
if self.greyscale:
write_chunk(outfile, 'bKGD',
struct.pack("!1H", *self.background))
else:
write_chunk(outfile, 'bKGD',
struct.pack("!3H", *self.background))
# http://www.w3.org/TR/PNG/#11pHYs
if self.resolution is not None:
write_chunk(outfile, 'pHYs',
struct.pack("!IIB",
self.resolution[0][0],
self.resolution[0][1],
self.resolution[1]))
# http://www.w3.org/TR/PNG/#11tIME
if self.modification_time is not None:
if self.modification_time is True:
self.modification_time = check_time('now')
write_chunk(outfile, 'tIME',
struct.pack("!H5B", *(self.modification_time[:6])))
# http://www.w3.org/TR/PNG/#11textinfo
if self.text:
self.__write_text(outfile)
for idat in idat_sequence:
write_chunk(outfile, 'IDAT', idat)
# http://www.w3.org/TR/PNG/#11IEND
write_chunk(outfile, 'IEND') | [
"def",
"write_idat",
"(",
"self",
",",
"outfile",
",",
"idat_sequence",
")",
":",
"# http://www.w3.org/TR/PNG/#5PNG-file-signature",
"outfile",
".",
"write",
"(",
"png_signature",
")",
"color_type",
"=",
"4",
"*",
"self",
".",
"alpha",
"+",
"2",
"*",
"(",
"not... | Write png with IDAT to file
`idat_sequence` should be iterable that produce IDAT chunks
compatible with `Writer` configuration. | [
"Write",
"png",
"with",
"IDAT",
"to",
"file"
] | 40a63c4e5ad7550f62b6860f1812cb67cafb9dc7 | https://github.com/brechtm/rinohtype/blob/40a63c4e5ad7550f62b6860f1812cb67cafb9dc7/src/rinoh/backend/pdf/xobject/purepng.py#L1314-L1384 | train | 31,330 |
brechtm/rinohtype | src/rinoh/backend/pdf/xobject/purepng.py | Writer.comp_idat | def comp_idat(self, idat):
"""Generator that produce compressed IDAT chunks from IDAT data"""
# http://www.w3.org/TR/PNG/#11IDAT
if self.compression is not None:
compressor = zlib.compressobj(self.compression)
else:
compressor = zlib.compressobj()
for dat in idat:
compressed = compressor.compress(dat)
if len(compressed):
yield compressed
flushed = compressor.flush()
if len(flushed):
yield flushed | python | def comp_idat(self, idat):
"""Generator that produce compressed IDAT chunks from IDAT data"""
# http://www.w3.org/TR/PNG/#11IDAT
if self.compression is not None:
compressor = zlib.compressobj(self.compression)
else:
compressor = zlib.compressobj()
for dat in idat:
compressed = compressor.compress(dat)
if len(compressed):
yield compressed
flushed = compressor.flush()
if len(flushed):
yield flushed | [
"def",
"comp_idat",
"(",
"self",
",",
"idat",
")",
":",
"# http://www.w3.org/TR/PNG/#11IDAT",
"if",
"self",
".",
"compression",
"is",
"not",
"None",
":",
"compressor",
"=",
"zlib",
".",
"compressobj",
"(",
"self",
".",
"compression",
")",
"else",
":",
"compr... | Generator that produce compressed IDAT chunks from IDAT data | [
"Generator",
"that",
"produce",
"compressed",
"IDAT",
"chunks",
"from",
"IDAT",
"data"
] | 40a63c4e5ad7550f62b6860f1812cb67cafb9dc7 | https://github.com/brechtm/rinohtype/blob/40a63c4e5ad7550f62b6860f1812cb67cafb9dc7/src/rinoh/backend/pdf/xobject/purepng.py#L1386-L1399 | train | 31,331 |
brechtm/rinohtype | src/rinoh/backend/pdf/xobject/purepng.py | Writer.idat | def idat(self, rows, packed=False):
"""Generator that produce uncompressed IDAT data from rows"""
# http://www.w3.org/TR/PNG/#11IDAT
filt = Filter(self.bitdepth * self.planes,
self.interlace, self.height)
data = bytearray()
def byteextend(rowbytes):
"""Default extending data with bytes. Applying filter"""
data.extend(filt.do_filter(self.filter_type, rowbytes))
# Choose an extend function based on the bitdepth. The extend
# function packs/decomposes the pixel values into bytes and
# stuffs them onto the data array.
if self.bitdepth == 8 or packed:
extend = byteextend
elif self.bitdepth == 16:
def extend(sl):
"""Decompose into bytes before byteextend"""
fmt = '!%dH' % len(sl)
byteextend(bytearray(struct.pack(fmt, *sl)))
else:
# Pack into bytes
assert self.bitdepth < 8
# samples per byte
spb = 8 // self.bitdepth
def extend(sl):
"""Pack into bytes before byteextend"""
a = bytearray(sl)
# Adding padding bytes so we can group into a whole
# number of spb-tuples.
l = float(len(a))
extra = math.ceil(l / float(spb)) * spb - l
a.extend([0] * int(extra))
# Pack into bytes
l = group(a, spb)
l = [reduce(lambda x, y: (x << self.bitdepth) + y, e)
for e in l]
byteextend(l)
# Build the first row, testing mostly to see if we need to
# changed the extend function to cope with NumPy integer types
# (they cause our ordinary definition of extend to fail, so we
# wrap it). See
# http://code.google.com/p/pypng/issues/detail?id=44
enumrows = enumerate(rows)
del rows
# :todo: Certain exceptions in the call to ``.next()`` or the
# following try would indicate no row data supplied.
# Should catch.
i, row = next(enumrows)
try:
# If this fails...
extend(row)
except:
# ... try a version that converts the values to int first.
# Not only does this work for the (slightly broken) NumPy
# types, there are probably lots of other, unknown, "nearly"
# int types it works for.
def wrapmapint(f):
return lambda sl: f([int(x) for x in sl])
extend = wrapmapint(extend)
del wrapmapint
extend(row)
for i, row in enumrows:
extend(row)
if len(data) > self.chunk_limit:
yield bytearray_to_bytes(data)
# Because of our very witty definition of ``extend``,
# above, we must re-use the same ``data`` object. Hence
# we use ``del`` to empty this one, rather than create a
# fresh one (which would be my natural FP instinct).
del data[:]
if len(data):
yield bytearray_to_bytes(data)
self.irows = i + 1 | python | def idat(self, rows, packed=False):
"""Generator that produce uncompressed IDAT data from rows"""
# http://www.w3.org/TR/PNG/#11IDAT
filt = Filter(self.bitdepth * self.planes,
self.interlace, self.height)
data = bytearray()
def byteextend(rowbytes):
"""Default extending data with bytes. Applying filter"""
data.extend(filt.do_filter(self.filter_type, rowbytes))
# Choose an extend function based on the bitdepth. The extend
# function packs/decomposes the pixel values into bytes and
# stuffs them onto the data array.
if self.bitdepth == 8 or packed:
extend = byteextend
elif self.bitdepth == 16:
def extend(sl):
"""Decompose into bytes before byteextend"""
fmt = '!%dH' % len(sl)
byteextend(bytearray(struct.pack(fmt, *sl)))
else:
# Pack into bytes
assert self.bitdepth < 8
# samples per byte
spb = 8 // self.bitdepth
def extend(sl):
"""Pack into bytes before byteextend"""
a = bytearray(sl)
# Adding padding bytes so we can group into a whole
# number of spb-tuples.
l = float(len(a))
extra = math.ceil(l / float(spb)) * spb - l
a.extend([0] * int(extra))
# Pack into bytes
l = group(a, spb)
l = [reduce(lambda x, y: (x << self.bitdepth) + y, e)
for e in l]
byteextend(l)
# Build the first row, testing mostly to see if we need to
# changed the extend function to cope with NumPy integer types
# (they cause our ordinary definition of extend to fail, so we
# wrap it). See
# http://code.google.com/p/pypng/issues/detail?id=44
enumrows = enumerate(rows)
del rows
# :todo: Certain exceptions in the call to ``.next()`` or the
# following try would indicate no row data supplied.
# Should catch.
i, row = next(enumrows)
try:
# If this fails...
extend(row)
except:
# ... try a version that converts the values to int first.
# Not only does this work for the (slightly broken) NumPy
# types, there are probably lots of other, unknown, "nearly"
# int types it works for.
def wrapmapint(f):
return lambda sl: f([int(x) for x in sl])
extend = wrapmapint(extend)
del wrapmapint
extend(row)
for i, row in enumrows:
extend(row)
if len(data) > self.chunk_limit:
yield bytearray_to_bytes(data)
# Because of our very witty definition of ``extend``,
# above, we must re-use the same ``data`` object. Hence
# we use ``del`` to empty this one, rather than create a
# fresh one (which would be my natural FP instinct).
del data[:]
if len(data):
yield bytearray_to_bytes(data)
self.irows = i + 1 | [
"def",
"idat",
"(",
"self",
",",
"rows",
",",
"packed",
"=",
"False",
")",
":",
"# http://www.w3.org/TR/PNG/#11IDAT",
"filt",
"=",
"Filter",
"(",
"self",
".",
"bitdepth",
"*",
"self",
".",
"planes",
",",
"self",
".",
"interlace",
",",
"self",
".",
"heigh... | Generator that produce uncompressed IDAT data from rows | [
"Generator",
"that",
"produce",
"uncompressed",
"IDAT",
"data",
"from",
"rows"
] | 40a63c4e5ad7550f62b6860f1812cb67cafb9dc7 | https://github.com/brechtm/rinohtype/blob/40a63c4e5ad7550f62b6860f1812cb67cafb9dc7/src/rinoh/backend/pdf/xobject/purepng.py#L1401-L1479 | train | 31,332 |
brechtm/rinohtype | src/rinoh/backend/pdf/xobject/purepng.py | Writer.write_packed | def write_packed(self, outfile, rows):
"""
Write PNG file to `outfile`.
The pixel data comes from `rows` which should be in boxed row
packed format. Each row should be a sequence of packed bytes.
Technically, this method does work for interlaced images but it
is best avoided. For interlaced images, the rows should be
presented in the order that they appear in the file.
This method should not be used when the source image bit depth
is not one naturally supported by PNG; the bit depth should be
1, 2, 4, 8, or 16.
"""
return self.write_passes(outfile, rows, packed=True) | python | def write_packed(self, outfile, rows):
"""
Write PNG file to `outfile`.
The pixel data comes from `rows` which should be in boxed row
packed format. Each row should be a sequence of packed bytes.
Technically, this method does work for interlaced images but it
is best avoided. For interlaced images, the rows should be
presented in the order that they appear in the file.
This method should not be used when the source image bit depth
is not one naturally supported by PNG; the bit depth should be
1, 2, 4, 8, or 16.
"""
return self.write_passes(outfile, rows, packed=True) | [
"def",
"write_packed",
"(",
"self",
",",
"outfile",
",",
"rows",
")",
":",
"return",
"self",
".",
"write_passes",
"(",
"outfile",
",",
"rows",
",",
"packed",
"=",
"True",
")"
] | Write PNG file to `outfile`.
The pixel data comes from `rows` which should be in boxed row
packed format. Each row should be a sequence of packed bytes.
Technically, this method does work for interlaced images but it
is best avoided. For interlaced images, the rows should be
presented in the order that they appear in the file.
This method should not be used when the source image bit depth
is not one naturally supported by PNG; the bit depth should be
1, 2, 4, 8, or 16. | [
"Write",
"PNG",
"file",
"to",
"outfile",
"."
] | 40a63c4e5ad7550f62b6860f1812cb67cafb9dc7 | https://github.com/brechtm/rinohtype/blob/40a63c4e5ad7550f62b6860f1812cb67cafb9dc7/src/rinoh/backend/pdf/xobject/purepng.py#L1492-L1507 | train | 31,333 |
brechtm/rinohtype | src/rinoh/backend/pdf/xobject/purepng.py | MergedPlanes.newarray | def newarray(self, length, value=0):
"""Initialise empty row"""
if self.bitdepth > 8:
return array('H', [value] * length)
else:
return bytearray([value] * length) | python | def newarray(self, length, value=0):
"""Initialise empty row"""
if self.bitdepth > 8:
return array('H', [value] * length)
else:
return bytearray([value] * length) | [
"def",
"newarray",
"(",
"self",
",",
"length",
",",
"value",
"=",
"0",
")",
":",
"if",
"self",
".",
"bitdepth",
">",
"8",
":",
"return",
"array",
"(",
"'H'",
",",
"[",
"value",
"]",
"*",
"length",
")",
"else",
":",
"return",
"bytearray",
"(",
"["... | Initialise empty row | [
"Initialise",
"empty",
"row"
] | 40a63c4e5ad7550f62b6860f1812cb67cafb9dc7 | https://github.com/brechtm/rinohtype/blob/40a63c4e5ad7550f62b6860f1812cb67cafb9dc7/src/rinoh/backend/pdf/xobject/purepng.py#L1604-L1609 | train | 31,334 |
brechtm/rinohtype | src/rinoh/backend/pdf/xobject/purepng.py | MergedPlanes.rigthgen | def rigthgen(self, value=0):
"""Generate rows to fill right pixels in int mode"""
while True:
yield self.newarray(self.nplanes_right * self.width, value) | python | def rigthgen(self, value=0):
"""Generate rows to fill right pixels in int mode"""
while True:
yield self.newarray(self.nplanes_right * self.width, value) | [
"def",
"rigthgen",
"(",
"self",
",",
"value",
"=",
"0",
")",
":",
"while",
"True",
":",
"yield",
"self",
".",
"newarray",
"(",
"self",
".",
"nplanes_right",
"*",
"self",
".",
"width",
",",
"value",
")"
] | Generate rows to fill right pixels in int mode | [
"Generate",
"rows",
"to",
"fill",
"right",
"pixels",
"in",
"int",
"mode"
] | 40a63c4e5ad7550f62b6860f1812cb67cafb9dc7 | https://github.com/brechtm/rinohtype/blob/40a63c4e5ad7550f62b6860f1812cb67cafb9dc7/src/rinoh/backend/pdf/xobject/purepng.py#L1611-L1614 | train | 31,335 |
brechtm/rinohtype | src/rinoh/backend/pdf/xobject/purepng.py | MergedPlanes.next | def next(self):
"""Generate merged row, consuming rows of original iterstors"""
left = next(self.seq_left)
if self.width is None:
self.width = len(left) / self.nplanes_left
if self.bitdepth is None:
# Detect bitdepth
if hasattr(left, 'itemsize'): # array
self.bitdepth = left.itemsize * 8
elif isinstance(left, (bytes, bytearray)): # bytearray
self.bitdepth = 8
else:
raise Error("Unknown bitdepth for merging planes")
right = next(self.seq_right)
rowlength = self.nplanes_res * self.width
new = self.newarray(rowlength)
if type(left) == type(right) == type(new):
# slice assignment
for i in range(self.nplanes_left):
new[i::self.nplanes_res] = left[i::self.nplanes_left]
for i in range(self.nplanes_right):
i_ = i + self.nplanes_left
new[i_::self.nplanes_res] = right[i::self.nplanes_right]
else:
for i in range(self.nplanes_left):
for j in range(self.width):
new[(i * self.nplanes_res) + j] =\
left[(i * self.nplanes_left) + j]
for i in range(self.nplanes_right):
i_ = i + self.nplanes_left
for j in range(self.width):
new[(i_ * self.nplanes_res) + j] =\
right[(i * self.nplanes_right) + j]
return new | python | def next(self):
"""Generate merged row, consuming rows of original iterstors"""
left = next(self.seq_left)
if self.width is None:
self.width = len(left) / self.nplanes_left
if self.bitdepth is None:
# Detect bitdepth
if hasattr(left, 'itemsize'): # array
self.bitdepth = left.itemsize * 8
elif isinstance(left, (bytes, bytearray)): # bytearray
self.bitdepth = 8
else:
raise Error("Unknown bitdepth for merging planes")
right = next(self.seq_right)
rowlength = self.nplanes_res * self.width
new = self.newarray(rowlength)
if type(left) == type(right) == type(new):
# slice assignment
for i in range(self.nplanes_left):
new[i::self.nplanes_res] = left[i::self.nplanes_left]
for i in range(self.nplanes_right):
i_ = i + self.nplanes_left
new[i_::self.nplanes_res] = right[i::self.nplanes_right]
else:
for i in range(self.nplanes_left):
for j in range(self.width):
new[(i * self.nplanes_res) + j] =\
left[(i * self.nplanes_left) + j]
for i in range(self.nplanes_right):
i_ = i + self.nplanes_left
for j in range(self.width):
new[(i_ * self.nplanes_res) + j] =\
right[(i * self.nplanes_right) + j]
return new | [
"def",
"next",
"(",
"self",
")",
":",
"left",
"=",
"next",
"(",
"self",
".",
"seq_left",
")",
"if",
"self",
".",
"width",
"is",
"None",
":",
"self",
".",
"width",
"=",
"len",
"(",
"left",
")",
"/",
"self",
".",
"nplanes_left",
"if",
"self",
".",
... | Generate merged row, consuming rows of original iterstors | [
"Generate",
"merged",
"row",
"consuming",
"rows",
"of",
"original",
"iterstors"
] | 40a63c4e5ad7550f62b6860f1812cb67cafb9dc7 | https://github.com/brechtm/rinohtype/blob/40a63c4e5ad7550f62b6860f1812cb67cafb9dc7/src/rinoh/backend/pdf/xobject/purepng.py#L1616-L1649 | train | 31,336 |
brechtm/rinohtype | src/rinoh/backend/pdf/xobject/purepng.py | Filter.filter_all | def filter_all(self, line):
"""Doing all filters for specified line
return filtered lines as list
For using with adaptive filters
"""
lines = [None] * 5
for filter_type in range(5): # range save more than 'optimised' order
res = copyBarray(line)
self._filter_scanline(filter_type, line, res)
res.insert(0, filter_type)
lines[filter_type] = res
return lines | python | def filter_all(self, line):
"""Doing all filters for specified line
return filtered lines as list
For using with adaptive filters
"""
lines = [None] * 5
for filter_type in range(5): # range save more than 'optimised' order
res = copyBarray(line)
self._filter_scanline(filter_type, line, res)
res.insert(0, filter_type)
lines[filter_type] = res
return lines | [
"def",
"filter_all",
"(",
"self",
",",
"line",
")",
":",
"lines",
"=",
"[",
"None",
"]",
"*",
"5",
"for",
"filter_type",
"in",
"range",
"(",
"5",
")",
":",
"# range save more than 'optimised' order",
"res",
"=",
"copyBarray",
"(",
"line",
")",
"self",
".... | Doing all filters for specified line
return filtered lines as list
For using with adaptive filters | [
"Doing",
"all",
"filters",
"for",
"specified",
"line"
] | 40a63c4e5ad7550f62b6860f1812cb67cafb9dc7 | https://github.com/brechtm/rinohtype/blob/40a63c4e5ad7550f62b6860f1812cb67cafb9dc7/src/rinoh/backend/pdf/xobject/purepng.py#L1691-L1703 | train | 31,337 |
brechtm/rinohtype | src/rinoh/backend/pdf/xobject/purepng.py | Filter.do_filter | def do_filter(self, filter_type, line):
"""
Applying filter, caring about prev line, interlacing etc.
`filter_type` may be integer to apply basic filter or
adaptive strategy with dict
(`name` is reqired field, others may tune strategy)
"""
# Recall that filtering algorithms are applied to bytes,
# not to pixels, regardless of the bit depth or colour type
# of the image.
line = bytearray(line)
if isinstance(filter_type, int):
res = bytearray(line)
self._filter_scanline(filter_type, line, res)
res.insert(0, filter_type) # Add filter type as the first byte
else:
res = self.adaptive_filter(filter_type, line)
self.prev = line
if self.restarts:
self.restarts[0] -= 1
if self.restarts[0] == 0:
del self.restarts[0]
self.prev = None
return res | python | def do_filter(self, filter_type, line):
"""
Applying filter, caring about prev line, interlacing etc.
`filter_type` may be integer to apply basic filter or
adaptive strategy with dict
(`name` is reqired field, others may tune strategy)
"""
# Recall that filtering algorithms are applied to bytes,
# not to pixels, regardless of the bit depth or colour type
# of the image.
line = bytearray(line)
if isinstance(filter_type, int):
res = bytearray(line)
self._filter_scanline(filter_type, line, res)
res.insert(0, filter_type) # Add filter type as the first byte
else:
res = self.adaptive_filter(filter_type, line)
self.prev = line
if self.restarts:
self.restarts[0] -= 1
if self.restarts[0] == 0:
del self.restarts[0]
self.prev = None
return res | [
"def",
"do_filter",
"(",
"self",
",",
"filter_type",
",",
"line",
")",
":",
"# Recall that filtering algorithms are applied to bytes,",
"# not to pixels, regardless of the bit depth or colour type",
"# of the image.",
"line",
"=",
"bytearray",
"(",
"line",
")",
"if",
"isinsta... | Applying filter, caring about prev line, interlacing etc.
`filter_type` may be integer to apply basic filter or
adaptive strategy with dict
(`name` is reqired field, others may tune strategy) | [
"Applying",
"filter",
"caring",
"about",
"prev",
"line",
"interlacing",
"etc",
"."
] | 40a63c4e5ad7550f62b6860f1812cb67cafb9dc7 | https://github.com/brechtm/rinohtype/blob/40a63c4e5ad7550f62b6860f1812cb67cafb9dc7/src/rinoh/backend/pdf/xobject/purepng.py#L1734-L1759 | train | 31,338 |
brechtm/rinohtype | src/rinoh/backend/pdf/xobject/purepng.py | _readable.read | def read(self, n):
"""Read `n` chars from buffer"""
r = self.buf[self.offset:self.offset + n]
if isinstance(r, array):
r = r.tostring()
self.offset += n
return r | python | def read(self, n):
"""Read `n` chars from buffer"""
r = self.buf[self.offset:self.offset + n]
if isinstance(r, array):
r = r.tostring()
self.offset += n
return r | [
"def",
"read",
"(",
"self",
",",
"n",
")",
":",
"r",
"=",
"self",
".",
"buf",
"[",
"self",
".",
"offset",
":",
"self",
".",
"offset",
"+",
"n",
"]",
"if",
"isinstance",
"(",
"r",
",",
"array",
")",
":",
"r",
"=",
"r",
".",
"tostring",
"(",
... | Read `n` chars from buffer | [
"Read",
"n",
"chars",
"from",
"buffer"
] | 40a63c4e5ad7550f62b6860f1812cb67cafb9dc7 | https://github.com/brechtm/rinohtype/blob/40a63c4e5ad7550f62b6860f1812cb67cafb9dc7/src/rinoh/backend/pdf/xobject/purepng.py#L2071-L2077 | train | 31,339 |
brechtm/rinohtype | src/rinoh/backend/pdf/xobject/purepng.py | Reader.chunk | def chunk(self, seek=None, lenient=False):
"""
Read the next PNG chunk from the input file
returns a (*chunk_type*, *data*) tuple. *chunk_type* is the chunk's
type as a byte string (all PNG chunk types are 4 bytes long).
*data* is the chunk's data content, as a byte string.
If the optional `seek` argument is
specified then it will keep reading chunks until it either runs
out of file or finds the chunk_type specified by the argument. Note
that in general the order of chunks in PNGs is unspecified, so
using `seek` can cause you to miss chunks.
If the optional `lenient` argument evaluates to `True`,
checksum failures will raise warnings rather than exceptions.
"""
self.validate_signature()
while True:
# http://www.w3.org/TR/PNG/#5Chunk-layout
if not self.atchunk:
self.atchunk = self.chunklentype()
length, chunk_type = self.atchunk
self.atchunk = None
data = self.file.read(length)
if len(data) != length:
raise ChunkError('Chunk %s too short for required %i octets.'
% (chunk_type, length))
checksum = self.file.read(4)
if len(checksum) != 4:
raise ChunkError('Chunk %s too short for checksum.',
chunk_type)
if seek and chunk_type != seek:
continue
verify = zlib.crc32(strtobytes(chunk_type))
verify = zlib.crc32(data, verify)
# Whether the output from zlib.crc32 is signed or not varies
# according to hideous implementation details, see
# http://bugs.python.org/issue1202 .
# We coerce it to be positive here (in a way which works on
# Python 2.3 and older).
verify &= 2**32 - 1
verify = struct.pack('!I', verify)
if checksum != verify:
(a, ) = struct.unpack('!I', checksum)
(b, ) = struct.unpack('!I', verify)
message = "Checksum error in %s chunk: 0x%08X != 0x%08X." %\
(chunk_type, a, b)
if lenient:
warnings.warn(message, RuntimeWarning)
else:
raise ChunkError(message)
return chunk_type, data | python | def chunk(self, seek=None, lenient=False):
"""
Read the next PNG chunk from the input file
returns a (*chunk_type*, *data*) tuple. *chunk_type* is the chunk's
type as a byte string (all PNG chunk types are 4 bytes long).
*data* is the chunk's data content, as a byte string.
If the optional `seek` argument is
specified then it will keep reading chunks until it either runs
out of file or finds the chunk_type specified by the argument. Note
that in general the order of chunks in PNGs is unspecified, so
using `seek` can cause you to miss chunks.
If the optional `lenient` argument evaluates to `True`,
checksum failures will raise warnings rather than exceptions.
"""
self.validate_signature()
while True:
# http://www.w3.org/TR/PNG/#5Chunk-layout
if not self.atchunk:
self.atchunk = self.chunklentype()
length, chunk_type = self.atchunk
self.atchunk = None
data = self.file.read(length)
if len(data) != length:
raise ChunkError('Chunk %s too short for required %i octets.'
% (chunk_type, length))
checksum = self.file.read(4)
if len(checksum) != 4:
raise ChunkError('Chunk %s too short for checksum.',
chunk_type)
if seek and chunk_type != seek:
continue
verify = zlib.crc32(strtobytes(chunk_type))
verify = zlib.crc32(data, verify)
# Whether the output from zlib.crc32 is signed or not varies
# according to hideous implementation details, see
# http://bugs.python.org/issue1202 .
# We coerce it to be positive here (in a way which works on
# Python 2.3 and older).
verify &= 2**32 - 1
verify = struct.pack('!I', verify)
if checksum != verify:
(a, ) = struct.unpack('!I', checksum)
(b, ) = struct.unpack('!I', verify)
message = "Checksum error in %s chunk: 0x%08X != 0x%08X." %\
(chunk_type, a, b)
if lenient:
warnings.warn(message, RuntimeWarning)
else:
raise ChunkError(message)
return chunk_type, data | [
"def",
"chunk",
"(",
"self",
",",
"seek",
"=",
"None",
",",
"lenient",
"=",
"False",
")",
":",
"self",
".",
"validate_signature",
"(",
")",
"while",
"True",
":",
"# http://www.w3.org/TR/PNG/#5Chunk-layout",
"if",
"not",
"self",
".",
"atchunk",
":",
"self",
... | Read the next PNG chunk from the input file
returns a (*chunk_type*, *data*) tuple. *chunk_type* is the chunk's
type as a byte string (all PNG chunk types are 4 bytes long).
*data* is the chunk's data content, as a byte string.
If the optional `seek` argument is
specified then it will keep reading chunks until it either runs
out of file or finds the chunk_type specified by the argument. Note
that in general the order of chunks in PNGs is unspecified, so
using `seek` can cause you to miss chunks.
If the optional `lenient` argument evaluates to `True`,
checksum failures will raise warnings rather than exceptions. | [
"Read",
"the",
"next",
"PNG",
"chunk",
"from",
"the",
"input",
"file"
] | 40a63c4e5ad7550f62b6860f1812cb67cafb9dc7 | https://github.com/brechtm/rinohtype/blob/40a63c4e5ad7550f62b6860f1812cb67cafb9dc7/src/rinoh/backend/pdf/xobject/purepng.py#L2136-L2188 | train | 31,340 |
brechtm/rinohtype | src/rinoh/backend/pdf/xobject/purepng.py | Reader.deinterlace | def deinterlace(self, raw):
"""
Read raw pixel data, undo filters, deinterlace, and flatten.
Return in flat row flat pixel format.
"""
# Values per row (of the target image)
vpr = self.width * self.planes
# Make a result array, and make it big enough. Interleaving
# writes to the output array randomly (well, not quite), so the
# entire output array must be in memory.
if self.bitdepth > 8:
a = newHarray(vpr * self.height)
else:
a = newBarray(vpr * self.height)
source_offset = 0
filt = Filter(self.bitdepth * self.planes)
for xstart, ystart, xstep, ystep in _adam7:
if xstart >= self.width:
continue
# The previous (reconstructed) scanline. None at the
# beginning of a pass to indicate that there is no previous
# line.
filt.prev = None
# Pixels per row (reduced pass image)
ppr = int(math.ceil((self.width-xstart)/float(xstep)))
# Row size in bytes for this pass.
row_size = int(math.ceil(self.psize * ppr))
for y in range(ystart, self.height, ystep):
filter_type = raw[source_offset]
scanline = raw[source_offset + 1:source_offset + row_size + 1]
source_offset += (row_size + 1)
if filter_type not in (0, 1, 2, 3, 4):
raise FormatError('Invalid PNG Filter Type.'
' See http://www.w3.org/TR/2003/REC-PNG-20031110/#9Filters .')
filt.undo_filter(filter_type, scanline)
# Convert so that there is one element per pixel value
flat = self.serialtoflat(scanline, ppr)
end_offset = (y + 1) * vpr
if xstep == 1:
# Last pass (0, 1, 1, 2))
assert xstart == 0
offset = y * vpr
a[offset:end_offset] = flat
else:
offset = y * vpr + xstart * self.planes
for i in range(self.planes):
a[offset + i:end_offset:self.planes * xstep] = \
flat[i::self.planes]
return a | python | def deinterlace(self, raw):
"""
Read raw pixel data, undo filters, deinterlace, and flatten.
Return in flat row flat pixel format.
"""
# Values per row (of the target image)
vpr = self.width * self.planes
# Make a result array, and make it big enough. Interleaving
# writes to the output array randomly (well, not quite), so the
# entire output array must be in memory.
if self.bitdepth > 8:
a = newHarray(vpr * self.height)
else:
a = newBarray(vpr * self.height)
source_offset = 0
filt = Filter(self.bitdepth * self.planes)
for xstart, ystart, xstep, ystep in _adam7:
if xstart >= self.width:
continue
# The previous (reconstructed) scanline. None at the
# beginning of a pass to indicate that there is no previous
# line.
filt.prev = None
# Pixels per row (reduced pass image)
ppr = int(math.ceil((self.width-xstart)/float(xstep)))
# Row size in bytes for this pass.
row_size = int(math.ceil(self.psize * ppr))
for y in range(ystart, self.height, ystep):
filter_type = raw[source_offset]
scanline = raw[source_offset + 1:source_offset + row_size + 1]
source_offset += (row_size + 1)
if filter_type not in (0, 1, 2, 3, 4):
raise FormatError('Invalid PNG Filter Type.'
' See http://www.w3.org/TR/2003/REC-PNG-20031110/#9Filters .')
filt.undo_filter(filter_type, scanline)
# Convert so that there is one element per pixel value
flat = self.serialtoflat(scanline, ppr)
end_offset = (y + 1) * vpr
if xstep == 1:
# Last pass (0, 1, 1, 2))
assert xstart == 0
offset = y * vpr
a[offset:end_offset] = flat
else:
offset = y * vpr + xstart * self.planes
for i in range(self.planes):
a[offset + i:end_offset:self.planes * xstep] = \
flat[i::self.planes]
return a | [
"def",
"deinterlace",
"(",
"self",
",",
"raw",
")",
":",
"# Values per row (of the target image)",
"vpr",
"=",
"self",
".",
"width",
"*",
"self",
".",
"planes",
"# Make a result array, and make it big enough. Interleaving",
"# writes to the output array randomly (well, not qui... | Read raw pixel data, undo filters, deinterlace, and flatten.
Return in flat row flat pixel format. | [
"Read",
"raw",
"pixel",
"data",
"undo",
"filters",
"deinterlace",
"and",
"flatten",
"."
] | 40a63c4e5ad7550f62b6860f1812cb67cafb9dc7 | https://github.com/brechtm/rinohtype/blob/40a63c4e5ad7550f62b6860f1812cb67cafb9dc7/src/rinoh/backend/pdf/xobject/purepng.py#L2200-L2250 | train | 31,341 |
brechtm/rinohtype | src/rinoh/backend/pdf/xobject/purepng.py | Reader.iterboxed | def iterboxed(self, rows):
"""
Iterator that yields each scanline in boxed row flat pixel format.
`rows` should be an iterator that yields the bytes of
each row in turn.
"""
def asvalues(raw):
"""
Convert a row of raw bytes into a flat row.
Result may or may not share with argument
"""
if self.bitdepth == 8:
return raw
if self.bitdepth == 16:
raw = bytearray_to_bytes(raw)
return array('H', struct.unpack('!%dH' % (len(raw) // 2), raw))
assert self.bitdepth < 8
width = self.width
# Samples per byte
spb = 8 // self.bitdepth
out = newBarray()
mask = 2 ** self.bitdepth - 1
# reversed range(spb)
shifts = [self.bitdepth * it for it in range(spb - 1, -1, -1)]
for o in raw:
out.extend([mask & (o >> i) for i in shifts])
return out[:width]
return map(asvalues, rows) | python | def iterboxed(self, rows):
"""
Iterator that yields each scanline in boxed row flat pixel format.
`rows` should be an iterator that yields the bytes of
each row in turn.
"""
def asvalues(raw):
"""
Convert a row of raw bytes into a flat row.
Result may or may not share with argument
"""
if self.bitdepth == 8:
return raw
if self.bitdepth == 16:
raw = bytearray_to_bytes(raw)
return array('H', struct.unpack('!%dH' % (len(raw) // 2), raw))
assert self.bitdepth < 8
width = self.width
# Samples per byte
spb = 8 // self.bitdepth
out = newBarray()
mask = 2 ** self.bitdepth - 1
# reversed range(spb)
shifts = [self.bitdepth * it for it in range(spb - 1, -1, -1)]
for o in raw:
out.extend([mask & (o >> i) for i in shifts])
return out[:width]
return map(asvalues, rows) | [
"def",
"iterboxed",
"(",
"self",
",",
"rows",
")",
":",
"def",
"asvalues",
"(",
"raw",
")",
":",
"\"\"\"\n Convert a row of raw bytes into a flat row.\n\n Result may or may not share with argument\n \"\"\"",
"if",
"self",
".",
"bitdepth",
"==",
... | Iterator that yields each scanline in boxed row flat pixel format.
`rows` should be an iterator that yields the bytes of
each row in turn. | [
"Iterator",
"that",
"yields",
"each",
"scanline",
"in",
"boxed",
"row",
"flat",
"pixel",
"format",
"."
] | 40a63c4e5ad7550f62b6860f1812cb67cafb9dc7 | https://github.com/brechtm/rinohtype/blob/40a63c4e5ad7550f62b6860f1812cb67cafb9dc7/src/rinoh/backend/pdf/xobject/purepng.py#L2252-L2282 | train | 31,342 |
brechtm/rinohtype | src/rinoh/backend/pdf/xobject/purepng.py | Reader.iterstraight | def iterstraight(self, raw):
"""
Iterator that undoes the effect of filtering
Yields each row in serialised format (as a sequence of bytes).
Assumes input is straightlaced. `raw` should be an iterable
that yields the raw bytes in chunks of arbitrary size.
"""
# length of row, in bytes (with filter)
rb_1 = self.row_bytes + 1
a = bytearray()
filt = Filter(self.bitdepth * self.planes)
for some in raw:
a.extend(some)
offset = 0
while len(a) >= rb_1 + offset:
filter_type = a[offset]
if filter_type not in (0, 1, 2, 3, 4):
raise FormatError('Invalid PNG Filter Type.'
' See http://www.w3.org/TR/2003/REC-PNG-20031110/#9Filters .')
scanline = a[offset + 1:offset + rb_1]
filt.undo_filter(filter_type, scanline)
yield scanline
offset += rb_1
del a[:offset]
if len(a) != 0:
# :file:format We get here with a file format error:
# when the available bytes (after decompressing) do not
# pack into exact rows.
raise FormatError(
'Wrong size for decompressed IDAT chunk.')
assert len(a) == 0 | python | def iterstraight(self, raw):
"""
Iterator that undoes the effect of filtering
Yields each row in serialised format (as a sequence of bytes).
Assumes input is straightlaced. `raw` should be an iterable
that yields the raw bytes in chunks of arbitrary size.
"""
# length of row, in bytes (with filter)
rb_1 = self.row_bytes + 1
a = bytearray()
filt = Filter(self.bitdepth * self.planes)
for some in raw:
a.extend(some)
offset = 0
while len(a) >= rb_1 + offset:
filter_type = a[offset]
if filter_type not in (0, 1, 2, 3, 4):
raise FormatError('Invalid PNG Filter Type.'
' See http://www.w3.org/TR/2003/REC-PNG-20031110/#9Filters .')
scanline = a[offset + 1:offset + rb_1]
filt.undo_filter(filter_type, scanline)
yield scanline
offset += rb_1
del a[:offset]
if len(a) != 0:
# :file:format We get here with a file format error:
# when the available bytes (after decompressing) do not
# pack into exact rows.
raise FormatError(
'Wrong size for decompressed IDAT chunk.')
assert len(a) == 0 | [
"def",
"iterstraight",
"(",
"self",
",",
"raw",
")",
":",
"# length of row, in bytes (with filter)",
"rb_1",
"=",
"self",
".",
"row_bytes",
"+",
"1",
"a",
"=",
"bytearray",
"(",
")",
"filt",
"=",
"Filter",
"(",
"self",
".",
"bitdepth",
"*",
"self",
".",
... | Iterator that undoes the effect of filtering
Yields each row in serialised format (as a sequence of bytes).
Assumes input is straightlaced. `raw` should be an iterable
that yields the raw bytes in chunks of arbitrary size. | [
"Iterator",
"that",
"undoes",
"the",
"effect",
"of",
"filtering"
] | 40a63c4e5ad7550f62b6860f1812cb67cafb9dc7 | https://github.com/brechtm/rinohtype/blob/40a63c4e5ad7550f62b6860f1812cb67cafb9dc7/src/rinoh/backend/pdf/xobject/purepng.py#L2309-L2341 | train | 31,343 |
brechtm/rinohtype | src/rinoh/backend/pdf/xobject/purepng.py | Reader.preamble | def preamble(self, lenient=False):
"""
Extract the image metadata
Extract the image metadata by reading the initial part of
the PNG file up to the start of the ``IDAT`` chunk. All the
chunks that precede the ``IDAT`` chunk are read and either
processed for metadata or discarded.
If the optional `lenient` argument evaluates to `True`, checksum
failures will raise warnings rather than exceptions.
"""
self.validate_signature()
while True:
if not self.atchunk:
self.atchunk = self.chunklentype()
if self.atchunk is None:
raise FormatError(
'This PNG file has no IDAT chunks.')
if self.atchunk[1] == 'IDAT':
return
self.process_chunk(lenient=lenient) | python | def preamble(self, lenient=False):
"""
Extract the image metadata
Extract the image metadata by reading the initial part of
the PNG file up to the start of the ``IDAT`` chunk. All the
chunks that precede the ``IDAT`` chunk are read and either
processed for metadata or discarded.
If the optional `lenient` argument evaluates to `True`, checksum
failures will raise warnings rather than exceptions.
"""
self.validate_signature()
while True:
if not self.atchunk:
self.atchunk = self.chunklentype()
if self.atchunk is None:
raise FormatError(
'This PNG file has no IDAT chunks.')
if self.atchunk[1] == 'IDAT':
return
self.process_chunk(lenient=lenient) | [
"def",
"preamble",
"(",
"self",
",",
"lenient",
"=",
"False",
")",
":",
"self",
".",
"validate_signature",
"(",
")",
"while",
"True",
":",
"if",
"not",
"self",
".",
"atchunk",
":",
"self",
".",
"atchunk",
"=",
"self",
".",
"chunklentype",
"(",
")",
"... | Extract the image metadata
Extract the image metadata by reading the initial part of
the PNG file up to the start of the ``IDAT`` chunk. All the
chunks that precede the ``IDAT`` chunk are read and either
processed for metadata or discarded.
If the optional `lenient` argument evaluates to `True`, checksum
failures will raise warnings rather than exceptions. | [
"Extract",
"the",
"image",
"metadata"
] | 40a63c4e5ad7550f62b6860f1812cb67cafb9dc7 | https://github.com/brechtm/rinohtype/blob/40a63c4e5ad7550f62b6860f1812cb67cafb9dc7/src/rinoh/backend/pdf/xobject/purepng.py#L2351-L2372 | train | 31,344 |
brechtm/rinohtype | src/rinoh/backend/pdf/xobject/purepng.py | Reader.idat | def idat(self, lenient=False):
"""Iterator that yields all the ``IDAT`` chunks as strings."""
while True:
try:
chunk_type, data = self.chunk(lenient=lenient)
except ValueError:
e = sys.exc_info()[1]
raise ChunkError(e.args[0])
if chunk_type == 'IEND':
# http://www.w3.org/TR/PNG/#11IEND
break
if chunk_type != 'IDAT':
continue
# chunk_type == 'IDAT'
# http://www.w3.org/TR/PNG/#11IDAT
if self.colormap and not self.plte:
warnings.warn("PLTE chunk is required before IDAT chunk")
yield data | python | def idat(self, lenient=False):
"""Iterator that yields all the ``IDAT`` chunks as strings."""
while True:
try:
chunk_type, data = self.chunk(lenient=lenient)
except ValueError:
e = sys.exc_info()[1]
raise ChunkError(e.args[0])
if chunk_type == 'IEND':
# http://www.w3.org/TR/PNG/#11IEND
break
if chunk_type != 'IDAT':
continue
# chunk_type == 'IDAT'
# http://www.w3.org/TR/PNG/#11IDAT
if self.colormap and not self.plte:
warnings.warn("PLTE chunk is required before IDAT chunk")
yield data | [
"def",
"idat",
"(",
"self",
",",
"lenient",
"=",
"False",
")",
":",
"while",
"True",
":",
"try",
":",
"chunk_type",
",",
"data",
"=",
"self",
".",
"chunk",
"(",
"lenient",
"=",
"lenient",
")",
"except",
"ValueError",
":",
"e",
"=",
"sys",
".",
"exc... | Iterator that yields all the ``IDAT`` chunks as strings. | [
"Iterator",
"that",
"yields",
"all",
"the",
"IDAT",
"chunks",
"as",
"strings",
"."
] | 40a63c4e5ad7550f62b6860f1812cb67cafb9dc7 | https://github.com/brechtm/rinohtype/blob/40a63c4e5ad7550f62b6860f1812cb67cafb9dc7/src/rinoh/backend/pdf/xobject/purepng.py#L2592-L2609 | train | 31,345 |
brechtm/rinohtype | src/rinoh/backend/pdf/xobject/purepng.py | Reader.idatdecomp | def idatdecomp(self, lenient=False, max_length=0):
"""Iterator that yields decompressed ``IDAT`` strings."""
# Currently, with no max_length paramter to decompress, this
# routine will do one yield per IDAT chunk. So not very
# incremental.
d = zlib.decompressobj()
# Each IDAT chunk is passed to the decompressor, then any
# remaining state is decompressed out.
for data in self.idat(lenient):
# :todo: add a max_length argument here to limit output
# size.
yield bytearray(d.decompress(data))
yield bytearray(d.flush()) | python | def idatdecomp(self, lenient=False, max_length=0):
"""Iterator that yields decompressed ``IDAT`` strings."""
# Currently, with no max_length paramter to decompress, this
# routine will do one yield per IDAT chunk. So not very
# incremental.
d = zlib.decompressobj()
# Each IDAT chunk is passed to the decompressor, then any
# remaining state is decompressed out.
for data in self.idat(lenient):
# :todo: add a max_length argument here to limit output
# size.
yield bytearray(d.decompress(data))
yield bytearray(d.flush()) | [
"def",
"idatdecomp",
"(",
"self",
",",
"lenient",
"=",
"False",
",",
"max_length",
"=",
"0",
")",
":",
"# Currently, with no max_length paramter to decompress, this",
"# routine will do one yield per IDAT chunk. So not very",
"# incremental.",
"d",
"=",
"zlib",
".",
"decom... | Iterator that yields decompressed ``IDAT`` strings. | [
"Iterator",
"that",
"yields",
"decompressed",
"IDAT",
"strings",
"."
] | 40a63c4e5ad7550f62b6860f1812cb67cafb9dc7 | https://github.com/brechtm/rinohtype/blob/40a63c4e5ad7550f62b6860f1812cb67cafb9dc7/src/rinoh/backend/pdf/xobject/purepng.py#L2611-L2623 | train | 31,346 |
brechtm/rinohtype | src/rinoh/backend/pdf/xobject/purepng.py | Reader.read | def read(self, lenient=False):
"""
Read the PNG file and decode it.
Returns (`width`, `height`, `pixels`, `metadata`).
May use excessive memory.
`pixels` are returned in boxed row flat pixel format.
If the optional `lenient` argument evaluates to True,
checksum failures will raise warnings rather than exceptions.
"""
self.preamble(lenient=lenient)
raw = self.idatdecomp(lenient)
if self.interlace:
raw = bytearray(itertools.chain(*raw))
arraycode = 'BH'[self.bitdepth > 8]
# Like :meth:`group` but producing an array.array object for
# each row.
pixels = map(lambda *row: array(arraycode, row),
*[iter(self.deinterlace(raw))]*self.width*self.planes)
else:
pixels = self.iterboxed(self.iterstraight(raw))
meta = dict()
for attr in 'greyscale alpha planes bitdepth interlace'.split():
meta[attr] = getattr(self, attr)
meta['size'] = (self.width, self.height)
for attr in ('gamma', 'transparent', 'background', 'last_mod_time',
'icc_profile', 'resolution', 'text',
'rendering_intent', 'white_point', 'rgb_points'):
a = getattr(self, attr, None)
if a is not None:
meta[attr] = a
if self.plte:
meta['palette'] = self.palette()
return self.width, self.height, pixels, meta | python | def read(self, lenient=False):
"""
Read the PNG file and decode it.
Returns (`width`, `height`, `pixels`, `metadata`).
May use excessive memory.
`pixels` are returned in boxed row flat pixel format.
If the optional `lenient` argument evaluates to True,
checksum failures will raise warnings rather than exceptions.
"""
self.preamble(lenient=lenient)
raw = self.idatdecomp(lenient)
if self.interlace:
raw = bytearray(itertools.chain(*raw))
arraycode = 'BH'[self.bitdepth > 8]
# Like :meth:`group` but producing an array.array object for
# each row.
pixels = map(lambda *row: array(arraycode, row),
*[iter(self.deinterlace(raw))]*self.width*self.planes)
else:
pixels = self.iterboxed(self.iterstraight(raw))
meta = dict()
for attr in 'greyscale alpha planes bitdepth interlace'.split():
meta[attr] = getattr(self, attr)
meta['size'] = (self.width, self.height)
for attr in ('gamma', 'transparent', 'background', 'last_mod_time',
'icc_profile', 'resolution', 'text',
'rendering_intent', 'white_point', 'rgb_points'):
a = getattr(self, attr, None)
if a is not None:
meta[attr] = a
if self.plte:
meta['palette'] = self.palette()
return self.width, self.height, pixels, meta | [
"def",
"read",
"(",
"self",
",",
"lenient",
"=",
"False",
")",
":",
"self",
".",
"preamble",
"(",
"lenient",
"=",
"lenient",
")",
"raw",
"=",
"self",
".",
"idatdecomp",
"(",
"lenient",
")",
"if",
"self",
".",
"interlace",
":",
"raw",
"=",
"bytearray"... | Read the PNG file and decode it.
Returns (`width`, `height`, `pixels`, `metadata`).
May use excessive memory.
`pixels` are returned in boxed row flat pixel format.
If the optional `lenient` argument evaluates to True,
checksum failures will raise warnings rather than exceptions. | [
"Read",
"the",
"PNG",
"file",
"and",
"decode",
"it",
"."
] | 40a63c4e5ad7550f62b6860f1812cb67cafb9dc7 | https://github.com/brechtm/rinohtype/blob/40a63c4e5ad7550f62b6860f1812cb67cafb9dc7/src/rinoh/backend/pdf/xobject/purepng.py#L2625-L2662 | train | 31,347 |
brechtm/rinohtype | src/rinoh/backend/pdf/xobject/purepng.py | Reader.read_flat | def read_flat(self):
"""
Read a PNG file and decode it into flat row flat pixel format.
Returns (*width*, *height*, *pixels*, *metadata*).
May use excessive memory.
`pixels` are returned in flat row flat pixel format.
See also the :meth:`read` method which returns pixels in the
more stream-friendly boxed row flat pixel format.
"""
x, y, pixel, meta = self.read()
arraycode = 'BH'[meta['bitdepth'] > 8]
pixel = array(arraycode, itertools.chain(*pixel))
return x, y, pixel, meta | python | def read_flat(self):
"""
Read a PNG file and decode it into flat row flat pixel format.
Returns (*width*, *height*, *pixels*, *metadata*).
May use excessive memory.
`pixels` are returned in flat row flat pixel format.
See also the :meth:`read` method which returns pixels in the
more stream-friendly boxed row flat pixel format.
"""
x, y, pixel, meta = self.read()
arraycode = 'BH'[meta['bitdepth'] > 8]
pixel = array(arraycode, itertools.chain(*pixel))
return x, y, pixel, meta | [
"def",
"read_flat",
"(",
"self",
")",
":",
"x",
",",
"y",
",",
"pixel",
",",
"meta",
"=",
"self",
".",
"read",
"(",
")",
"arraycode",
"=",
"'BH'",
"[",
"meta",
"[",
"'bitdepth'",
"]",
">",
"8",
"]",
"pixel",
"=",
"array",
"(",
"arraycode",
",",
... | Read a PNG file and decode it into flat row flat pixel format.
Returns (*width*, *height*, *pixels*, *metadata*).
May use excessive memory.
`pixels` are returned in flat row flat pixel format.
See also the :meth:`read` method which returns pixels in the
more stream-friendly boxed row flat pixel format. | [
"Read",
"a",
"PNG",
"file",
"and",
"decode",
"it",
"into",
"flat",
"row",
"flat",
"pixel",
"format",
"."
] | 40a63c4e5ad7550f62b6860f1812cb67cafb9dc7 | https://github.com/brechtm/rinohtype/blob/40a63c4e5ad7550f62b6860f1812cb67cafb9dc7/src/rinoh/backend/pdf/xobject/purepng.py#L2664-L2680 | train | 31,348 |
brechtm/rinohtype | src/rinoh/backend/pdf/xobject/purepng.py | Reader.asRGB | def asRGB(self):
"""
Return image as RGB pixels.
RGB colour images are passed through unchanged;
greyscales are expanded into RGB triplets
(there is a small speed overhead for doing this).
An alpha channel in the source image will raise an exception.
The return values are as for the :meth:`read` method
except that the *metadata* reflect the returned pixels, not the
source image. In particular, for this method
``metadata['greyscale']`` will be ``False``.
"""
width, height, pixels, meta = self.asDirect()
if meta['alpha']:
raise Error("will not convert image with alpha channel to RGB")
if not meta['greyscale']:
return width, height, pixels, meta
meta['greyscale'] = False
newarray = (newBarray, newHarray)[meta['bitdepth'] > 8]
def iterrgb():
for row in pixels:
a = newarray(3 * width)
for i in range(3):
a[i::3] = row
yield a
return width, height, iterrgb(), meta | python | def asRGB(self):
"""
Return image as RGB pixels.
RGB colour images are passed through unchanged;
greyscales are expanded into RGB triplets
(there is a small speed overhead for doing this).
An alpha channel in the source image will raise an exception.
The return values are as for the :meth:`read` method
except that the *metadata* reflect the returned pixels, not the
source image. In particular, for this method
``metadata['greyscale']`` will be ``False``.
"""
width, height, pixels, meta = self.asDirect()
if meta['alpha']:
raise Error("will not convert image with alpha channel to RGB")
if not meta['greyscale']:
return width, height, pixels, meta
meta['greyscale'] = False
newarray = (newBarray, newHarray)[meta['bitdepth'] > 8]
def iterrgb():
for row in pixels:
a = newarray(3 * width)
for i in range(3):
a[i::3] = row
yield a
return width, height, iterrgb(), meta | [
"def",
"asRGB",
"(",
"self",
")",
":",
"width",
",",
"height",
",",
"pixels",
",",
"meta",
"=",
"self",
".",
"asDirect",
"(",
")",
"if",
"meta",
"[",
"'alpha'",
"]",
":",
"raise",
"Error",
"(",
"\"will not convert image with alpha channel to RGB\"",
")",
"... | Return image as RGB pixels.
RGB colour images are passed through unchanged;
greyscales are expanded into RGB triplets
(there is a small speed overhead for doing this).
An alpha channel in the source image will raise an exception.
The return values are as for the :meth:`read` method
except that the *metadata* reflect the returned pixels, not the
source image. In particular, for this method
``metadata['greyscale']`` will be ``False``. | [
"Return",
"image",
"as",
"RGB",
"pixels",
"."
] | 40a63c4e5ad7550f62b6860f1812cb67cafb9dc7 | https://github.com/brechtm/rinohtype/blob/40a63c4e5ad7550f62b6860f1812cb67cafb9dc7/src/rinoh/backend/pdf/xobject/purepng.py#L2893-L2922 | train | 31,349 |
brechtm/rinohtype | src/rinoh/backend/pdf/xobject/purepng.py | Reader.asRGBA | def asRGBA(self):
"""
Return image as RGBA pixels.
Greyscales are expanded into RGB triplets;
an alpha channel is synthesized if necessary.
The return values are as for the :meth:`read` method
except that the *metadata* reflect the returned pixels, not the
source image. In particular, for this method
``metadata['greyscale']`` will be ``False``, and
``metadata['alpha']`` will be ``True``.
"""
width, height, pixels, meta = self.asDirect()
if meta['alpha'] and not meta['greyscale']:
return width, height, pixels, meta
maxval = 2**meta['bitdepth'] - 1
if meta['bitdepth'] > 8:
def newarray():
return array('H', [maxval] * 4 * width)
else:
def newarray():
return bytearray([maxval] * 4 * width)
# Not best way, but we have only array of bytes accelerated now
if meta['bitdepth'] <= 8:
filt = BaseFilter()
else:
filt = iBaseFilter()
if meta['alpha'] and meta['greyscale']:
# LA to RGBA
def convert():
for row in pixels:
# Create a fresh target row, then copy L channel
# into first three target channels, and A channel
# into fourth channel.
a = newarray()
filt.convert_la_to_rgba(row, a)
yield a
elif meta['greyscale']:
# L to RGBA
def convert():
for row in pixels:
a = newarray()
filt.convert_l_to_rgba(row, a)
yield a
else:
assert not meta['alpha'] and not meta['greyscale']
# RGB to RGBA
def convert():
for row in pixels:
a = newarray()
filt.convert_rgb_to_rgba(row, a)
yield a
meta['alpha'] = True
meta['greyscale'] = False
return width, height, convert(), meta | python | def asRGBA(self):
"""
Return image as RGBA pixels.
Greyscales are expanded into RGB triplets;
an alpha channel is synthesized if necessary.
The return values are as for the :meth:`read` method
except that the *metadata* reflect the returned pixels, not the
source image. In particular, for this method
``metadata['greyscale']`` will be ``False``, and
``metadata['alpha']`` will be ``True``.
"""
width, height, pixels, meta = self.asDirect()
if meta['alpha'] and not meta['greyscale']:
return width, height, pixels, meta
maxval = 2**meta['bitdepth'] - 1
if meta['bitdepth'] > 8:
def newarray():
return array('H', [maxval] * 4 * width)
else:
def newarray():
return bytearray([maxval] * 4 * width)
# Not best way, but we have only array of bytes accelerated now
if meta['bitdepth'] <= 8:
filt = BaseFilter()
else:
filt = iBaseFilter()
if meta['alpha'] and meta['greyscale']:
# LA to RGBA
def convert():
for row in pixels:
# Create a fresh target row, then copy L channel
# into first three target channels, and A channel
# into fourth channel.
a = newarray()
filt.convert_la_to_rgba(row, a)
yield a
elif meta['greyscale']:
# L to RGBA
def convert():
for row in pixels:
a = newarray()
filt.convert_l_to_rgba(row, a)
yield a
else:
assert not meta['alpha'] and not meta['greyscale']
# RGB to RGBA
def convert():
for row in pixels:
a = newarray()
filt.convert_rgb_to_rgba(row, a)
yield a
meta['alpha'] = True
meta['greyscale'] = False
return width, height, convert(), meta | [
"def",
"asRGBA",
"(",
"self",
")",
":",
"width",
",",
"height",
",",
"pixels",
",",
"meta",
"=",
"self",
".",
"asDirect",
"(",
")",
"if",
"meta",
"[",
"'alpha'",
"]",
"and",
"not",
"meta",
"[",
"'greyscale'",
"]",
":",
"return",
"width",
",",
"heig... | Return image as RGBA pixels.
Greyscales are expanded into RGB triplets;
an alpha channel is synthesized if necessary.
The return values are as for the :meth:`read` method
except that the *metadata* reflect the returned pixels, not the
source image. In particular, for this method
``metadata['greyscale']`` will be ``False``, and
``metadata['alpha']`` will be ``True``. | [
"Return",
"image",
"as",
"RGBA",
"pixels",
"."
] | 40a63c4e5ad7550f62b6860f1812cb67cafb9dc7 | https://github.com/brechtm/rinohtype/blob/40a63c4e5ad7550f62b6860f1812cb67cafb9dc7/src/rinoh/backend/pdf/xobject/purepng.py#L2924-L2981 | train | 31,350 |
brechtm/rinohtype | src/rinoh/backend/pdf/xobject/png.py | chromaticity_to_XYZ | def chromaticity_to_XYZ(white, red, green, blue):
"""From the "CalRGB Color Spaces" section of "PDF Reference", 6th ed."""
xW, yW = white
xR, yR = red
xG, yG = green
xB, yB = blue
R = G = B = 1.0
z = yW * ((xG - xB) * yR - (xR - xB) * yG + (xR - xG) * yB)
YA = yR / R * ((xG - xB) * yW - (xW - xB) * yG + (xW - xG) * yB) / z
XA = YA * xR / yR
ZA = YA * ((1 - xR) / yR - 1)
YB = - yG / G * ((xR - xB) * yW - (xW - xB) * yR + (xW - xR) * yB) / z
XB = YB * xG / yG
ZB = YB * ((1 - xG) / yG - 1)
YC = yB / B * ((xR - xG) * yW - (xW - xG) * yR + (xW - xR) * yG) / z
XC = YC * xB / yB
ZC = YC * ((1 - xB) / yB - 1)
XW = XA * R + XB * G + XC * B
YW = YA * R + YB * G + YC * B
ZW = ZA * R + ZB * G + ZC * B
return (XW, YW, ZW), (XA, YA, ZA), (XB, YB, ZB), (XC, YC, ZC) | python | def chromaticity_to_XYZ(white, red, green, blue):
"""From the "CalRGB Color Spaces" section of "PDF Reference", 6th ed."""
xW, yW = white
xR, yR = red
xG, yG = green
xB, yB = blue
R = G = B = 1.0
z = yW * ((xG - xB) * yR - (xR - xB) * yG + (xR - xG) * yB)
YA = yR / R * ((xG - xB) * yW - (xW - xB) * yG + (xW - xG) * yB) / z
XA = YA * xR / yR
ZA = YA * ((1 - xR) / yR - 1)
YB = - yG / G * ((xR - xB) * yW - (xW - xB) * yR + (xW - xR) * yB) / z
XB = YB * xG / yG
ZB = YB * ((1 - xG) / yG - 1)
YC = yB / B * ((xR - xG) * yW - (xW - xG) * yR + (xW - xR) * yG) / z
XC = YC * xB / yB
ZC = YC * ((1 - xB) / yB - 1)
XW = XA * R + XB * G + XC * B
YW = YA * R + YB * G + YC * B
ZW = ZA * R + ZB * G + ZC * B
return (XW, YW, ZW), (XA, YA, ZA), (XB, YB, ZB), (XC, YC, ZC) | [
"def",
"chromaticity_to_XYZ",
"(",
"white",
",",
"red",
",",
"green",
",",
"blue",
")",
":",
"xW",
",",
"yW",
"=",
"white",
"xR",
",",
"yR",
"=",
"red",
"xG",
",",
"yG",
"=",
"green",
"xB",
",",
"yB",
"=",
"blue",
"R",
"=",
"G",
"=",
"B",
"="... | From the "CalRGB Color Spaces" section of "PDF Reference", 6th ed. | [
"From",
"the",
"CalRGB",
"Color",
"Spaces",
"section",
"of",
"PDF",
"Reference",
"6th",
"ed",
"."
] | 40a63c4e5ad7550f62b6860f1812cb67cafb9dc7 | https://github.com/brechtm/rinohtype/blob/40a63c4e5ad7550f62b6860f1812cb67cafb9dc7/src/rinoh/backend/pdf/xobject/png.py#L200-L222 | train | 31,351 |
uktrade/directory-client-core | directory_client_core/helpers.py | fallback | def fallback(cache):
"""
Caches content retrieved by the client, thus allowing the cached
content to be used later if the live content cannot be retrieved.
"""
log_filter = ThrottlingFilter(cache=cache)
logger.filters = []
logger.addFilter(log_filter)
def get_cache_response(cache_key):
content = cache.get(cache_key)
if content:
response = CacheResponse()
response.__setstate__({
'status_code': 200,
'_content': content,
})
return response
def get_cache_control(etag_cache_key):
etag = cache.get(etag_cache_key)
if etag:
return ETagCacheControl(etag)
def closure(func):
@wraps(func)
def wrapper(client, url, params={}, *args, **kwargs):
cache_key = canonicalize_url(url + '?' + urlencode(params))
etag_cache_key = 'etag-' + cache_key
try:
remote_response = func(
client,
url=url,
params=params,
cache_control=get_cache_control(etag_cache_key),
*args,
**kwargs,
)
except RequestException:
# Failed to create the request e.g., the remote server is down,
# perhaps a timeout occurred, or even connection closed by
# remote, etc.
response = get_cache_response(cache_key)
if response:
logger.error(MESSAGE_CACHE_HIT, extra={'url': url})
else:
raise
else:
log_context = {
'status_code': remote_response.status_code, 'url': url
}
if remote_response.status_code == 404:
logger.error(MESSAGE_NOT_FOUND, extra=log_context)
return LiveResponse.from_response(remote_response)
elif remote_response.status_code == 304:
response = get_cache_response(cache_key)
elif not remote_response.ok:
# Successfully requested the content, but the response is
# not OK (e.g., 500, 403, etc)
response = get_cache_response(cache_key)
if response:
logger.error(MESSAGE_CACHE_HIT, extra=log_context)
else:
logger.exception(MESSAGE_CACHE_MISS, extra=log_context)
response = FailureResponse.from_response(
remote_response
)
else:
cache.set_many({
cache_key: remote_response.content,
etag_cache_key: remote_response.headers.get('ETag'),
}, settings.DIRECTORY_CLIENT_CORE_CACHE_EXPIRE_SECONDS)
response = LiveResponse.from_response(remote_response)
return response
return wrapper
return closure | python | def fallback(cache):
"""
Caches content retrieved by the client, thus allowing the cached
content to be used later if the live content cannot be retrieved.
"""
log_filter = ThrottlingFilter(cache=cache)
logger.filters = []
logger.addFilter(log_filter)
def get_cache_response(cache_key):
content = cache.get(cache_key)
if content:
response = CacheResponse()
response.__setstate__({
'status_code': 200,
'_content': content,
})
return response
def get_cache_control(etag_cache_key):
etag = cache.get(etag_cache_key)
if etag:
return ETagCacheControl(etag)
def closure(func):
@wraps(func)
def wrapper(client, url, params={}, *args, **kwargs):
cache_key = canonicalize_url(url + '?' + urlencode(params))
etag_cache_key = 'etag-' + cache_key
try:
remote_response = func(
client,
url=url,
params=params,
cache_control=get_cache_control(etag_cache_key),
*args,
**kwargs,
)
except RequestException:
# Failed to create the request e.g., the remote server is down,
# perhaps a timeout occurred, or even connection closed by
# remote, etc.
response = get_cache_response(cache_key)
if response:
logger.error(MESSAGE_CACHE_HIT, extra={'url': url})
else:
raise
else:
log_context = {
'status_code': remote_response.status_code, 'url': url
}
if remote_response.status_code == 404:
logger.error(MESSAGE_NOT_FOUND, extra=log_context)
return LiveResponse.from_response(remote_response)
elif remote_response.status_code == 304:
response = get_cache_response(cache_key)
elif not remote_response.ok:
# Successfully requested the content, but the response is
# not OK (e.g., 500, 403, etc)
response = get_cache_response(cache_key)
if response:
logger.error(MESSAGE_CACHE_HIT, extra=log_context)
else:
logger.exception(MESSAGE_CACHE_MISS, extra=log_context)
response = FailureResponse.from_response(
remote_response
)
else:
cache.set_many({
cache_key: remote_response.content,
etag_cache_key: remote_response.headers.get('ETag'),
}, settings.DIRECTORY_CLIENT_CORE_CACHE_EXPIRE_SECONDS)
response = LiveResponse.from_response(remote_response)
return response
return wrapper
return closure | [
"def",
"fallback",
"(",
"cache",
")",
":",
"log_filter",
"=",
"ThrottlingFilter",
"(",
"cache",
"=",
"cache",
")",
"logger",
".",
"filters",
"=",
"[",
"]",
"logger",
".",
"addFilter",
"(",
"log_filter",
")",
"def",
"get_cache_response",
"(",
"cache_key",
"... | Caches content retrieved by the client, thus allowing the cached
content to be used later if the live content cannot be retrieved. | [
"Caches",
"content",
"retrieved",
"by",
"the",
"client",
"thus",
"allowing",
"the",
"cached",
"content",
"to",
"be",
"used",
"later",
"if",
"the",
"live",
"content",
"cannot",
"be",
"retrieved",
"."
] | 5196340a73117a27d9efb88d701dbdc7cdc90502 | https://github.com/uktrade/directory-client-core/blob/5196340a73117a27d9efb88d701dbdc7cdc90502/directory_client_core/helpers.py#L77-L154 | train | 31,352 |
uktrade/directory-client-core | directory_client_core/base.py | AbstractAPIClient.build_url | def build_url(base_url, partial_url):
"""
Makes sure the URL is built properly.
>>> urllib.parse.urljoin('https://test.com/1/', '2/3')
https://test.com/1/2/3
>>> urllib.parse.urljoin('https://test.com/1/', '/2/3')
https://test.com/2/3
>>> urllib.parse.urljoin('https://test.com/1', '2/3')
https://test.com/2/3'
"""
if not base_url.endswith('/'):
base_url += '/'
if partial_url.startswith('/'):
partial_url = partial_url[1:]
return urlparse.urljoin(base_url, partial_url) | python | def build_url(base_url, partial_url):
"""
Makes sure the URL is built properly.
>>> urllib.parse.urljoin('https://test.com/1/', '2/3')
https://test.com/1/2/3
>>> urllib.parse.urljoin('https://test.com/1/', '/2/3')
https://test.com/2/3
>>> urllib.parse.urljoin('https://test.com/1', '2/3')
https://test.com/2/3'
"""
if not base_url.endswith('/'):
base_url += '/'
if partial_url.startswith('/'):
partial_url = partial_url[1:]
return urlparse.urljoin(base_url, partial_url) | [
"def",
"build_url",
"(",
"base_url",
",",
"partial_url",
")",
":",
"if",
"not",
"base_url",
".",
"endswith",
"(",
"'/'",
")",
":",
"base_url",
"+=",
"'/'",
"if",
"partial_url",
".",
"startswith",
"(",
"'/'",
")",
":",
"partial_url",
"=",
"partial_url",
"... | Makes sure the URL is built properly.
>>> urllib.parse.urljoin('https://test.com/1/', '2/3')
https://test.com/1/2/3
>>> urllib.parse.urljoin('https://test.com/1/', '/2/3')
https://test.com/2/3
>>> urllib.parse.urljoin('https://test.com/1', '2/3')
https://test.com/2/3' | [
"Makes",
"sure",
"the",
"URL",
"is",
"built",
"properly",
"."
] | 5196340a73117a27d9efb88d701dbdc7cdc90502 | https://github.com/uktrade/directory-client-core/blob/5196340a73117a27d9efb88d701dbdc7cdc90502/directory_client_core/base.py#L93-L109 | train | 31,353 |
sam-cox/pytides | pytides/tide.py | Tide.form_number | def form_number(self):
"""
Returns the model's form number, a helpful heuristic for classifying tides.
"""
k1, o1, m2, s2 = (
np.extract(self.model['constituent'] == c, self.model['amplitude'])
for c in [constituent._K1, constituent._O1, constituent._M2, constituent._S2]
)
return (k1+o1)/(m2+s2) | python | def form_number(self):
"""
Returns the model's form number, a helpful heuristic for classifying tides.
"""
k1, o1, m2, s2 = (
np.extract(self.model['constituent'] == c, self.model['amplitude'])
for c in [constituent._K1, constituent._O1, constituent._M2, constituent._S2]
)
return (k1+o1)/(m2+s2) | [
"def",
"form_number",
"(",
"self",
")",
":",
"k1",
",",
"o1",
",",
"m2",
",",
"s2",
"=",
"(",
"np",
".",
"extract",
"(",
"self",
".",
"model",
"[",
"'constituent'",
"]",
"==",
"c",
",",
"self",
".",
"model",
"[",
"'amplitude'",
"]",
")",
"for",
... | Returns the model's form number, a helpful heuristic for classifying tides. | [
"Returns",
"the",
"model",
"s",
"form",
"number",
"a",
"helpful",
"heuristic",
"for",
"classifying",
"tides",
"."
] | 63a2507299002f1979ea55a17a82561158d685f7 | https://github.com/sam-cox/pytides/blob/63a2507299002f1979ea55a17a82561158d685f7/pytides/tide.py#L136-L144 | train | 31,354 |
sam-cox/pytides | pytides/tide.py | Tide.normalize | def normalize(self):
"""
Adapt self.model so that amplitudes are positive and phases are in [0,360) as per convention
"""
for i, (_, amplitude, phase) in enumerate(self.model):
if amplitude < 0:
self.model['amplitude'][i] = -amplitude
self.model['phase'][i] = phase + 180.0
self.model['phase'][i] = np.mod(self.model['phase'][i], 360.0) | python | def normalize(self):
"""
Adapt self.model so that amplitudes are positive and phases are in [0,360) as per convention
"""
for i, (_, amplitude, phase) in enumerate(self.model):
if amplitude < 0:
self.model['amplitude'][i] = -amplitude
self.model['phase'][i] = phase + 180.0
self.model['phase'][i] = np.mod(self.model['phase'][i], 360.0) | [
"def",
"normalize",
"(",
"self",
")",
":",
"for",
"i",
",",
"(",
"_",
",",
"amplitude",
",",
"phase",
")",
"in",
"enumerate",
"(",
"self",
".",
"model",
")",
":",
"if",
"amplitude",
"<",
"0",
":",
"self",
".",
"model",
"[",
"'amplitude'",
"]",
"[... | Adapt self.model so that amplitudes are positive and phases are in [0,360) as per convention | [
"Adapt",
"self",
".",
"model",
"so",
"that",
"amplitudes",
"are",
"positive",
"and",
"phases",
"are",
"in",
"[",
"0",
"360",
")",
"as",
"per",
"convention"
] | 63a2507299002f1979ea55a17a82561158d685f7 | https://github.com/sam-cox/pytides/blob/63a2507299002f1979ea55a17a82561158d685f7/pytides/tide.py#L260-L268 | train | 31,355 |
pyupio/dparse | dparse/vendor/toml.py | _unescape | def _unescape(v):
"""Unescape characters in a TOML string."""
i = 0
backslash = False
while i < len(v):
if backslash:
backslash = False
if v[i] in _escapes:
v = v[:i - 1] + _escape_to_escapedchars[v[i]] + v[i + 1:]
elif v[i] == '\\':
v = v[:i - 1] + v[i:]
elif v[i] == 'u' or v[i] == 'U':
i += 1
else:
raise TomlDecodeError("Reserved escape sequence used")
continue
elif v[i] == '\\':
backslash = True
i += 1
return v | python | def _unescape(v):
"""Unescape characters in a TOML string."""
i = 0
backslash = False
while i < len(v):
if backslash:
backslash = False
if v[i] in _escapes:
v = v[:i - 1] + _escape_to_escapedchars[v[i]] + v[i + 1:]
elif v[i] == '\\':
v = v[:i - 1] + v[i:]
elif v[i] == 'u' or v[i] == 'U':
i += 1
else:
raise TomlDecodeError("Reserved escape sequence used")
continue
elif v[i] == '\\':
backslash = True
i += 1
return v | [
"def",
"_unescape",
"(",
"v",
")",
":",
"i",
"=",
"0",
"backslash",
"=",
"False",
"while",
"i",
"<",
"len",
"(",
"v",
")",
":",
"if",
"backslash",
":",
"backslash",
"=",
"False",
"if",
"v",
"[",
"i",
"]",
"in",
"_escapes",
":",
"v",
"=",
"v",
... | Unescape characters in a TOML string. | [
"Unescape",
"characters",
"in",
"a",
"TOML",
"string",
"."
] | 0cd5aa7eb1f78c39da78b6c63dde6b49a1732cd2 | https://github.com/pyupio/dparse/blob/0cd5aa7eb1f78c39da78b6c63dde6b49a1732cd2/dparse/vendor/toml.py#L560-L579 | train | 31,356 |
pyupio/dparse | dparse/parser.py | RequirementsTXTParser.parse | def parse(self):
"""
Parses a requirements.txt-like file
"""
index_server = None
for num, line in enumerate(self.iter_lines()):
line = line.rstrip()
if not line:
continue
if line.startswith('#'):
# comments are lines that start with # only
continue
if line.startswith('-i') or \
line.startswith('--index-url') or \
line.startswith('--extra-index-url'):
# this file is using a private index server, try to parse it
index_server = self.parse_index_server(line)
continue
elif self.obj.path and (line.startswith('-r') or line.startswith('--requirement')):
self.obj.resolved_files.append(self.resolve_file(self.obj.path, line))
elif line.startswith('-f') or line.startswith('--find-links') or \
line.startswith('--no-index') or line.startswith('--allow-external') or \
line.startswith('--allow-unverified') or line.startswith('-Z') or \
line.startswith('--always-unzip'):
continue
elif self.is_marked_line(line):
continue
else:
try:
parseable_line = line
# multiline requirements are not parseable
if "\\" in line:
parseable_line = line.replace("\\", "")
for next_line in self.iter_lines(num + 1):
parseable_line += next_line.strip().replace("\\", "")
line += "\n" + next_line
if "\\" in next_line:
continue
break
# ignore multiline requirements if they are marked
if self.is_marked_line(parseable_line):
continue
hashes = []
if "--hash" in parseable_line:
parseable_line, hashes = Parser.parse_hashes(parseable_line)
req = RequirementsTXTLineParser.parse(parseable_line)
if req:
req.hashes = hashes
req.index_server = index_server
# replace the requirements line with the 'real' line
req.line = line
self.obj.dependencies.append(req)
except ValueError:
continue | python | def parse(self):
"""
Parses a requirements.txt-like file
"""
index_server = None
for num, line in enumerate(self.iter_lines()):
line = line.rstrip()
if not line:
continue
if line.startswith('#'):
# comments are lines that start with # only
continue
if line.startswith('-i') or \
line.startswith('--index-url') or \
line.startswith('--extra-index-url'):
# this file is using a private index server, try to parse it
index_server = self.parse_index_server(line)
continue
elif self.obj.path and (line.startswith('-r') or line.startswith('--requirement')):
self.obj.resolved_files.append(self.resolve_file(self.obj.path, line))
elif line.startswith('-f') or line.startswith('--find-links') or \
line.startswith('--no-index') or line.startswith('--allow-external') or \
line.startswith('--allow-unverified') or line.startswith('-Z') or \
line.startswith('--always-unzip'):
continue
elif self.is_marked_line(line):
continue
else:
try:
parseable_line = line
# multiline requirements are not parseable
if "\\" in line:
parseable_line = line.replace("\\", "")
for next_line in self.iter_lines(num + 1):
parseable_line += next_line.strip().replace("\\", "")
line += "\n" + next_line
if "\\" in next_line:
continue
break
# ignore multiline requirements if they are marked
if self.is_marked_line(parseable_line):
continue
hashes = []
if "--hash" in parseable_line:
parseable_line, hashes = Parser.parse_hashes(parseable_line)
req = RequirementsTXTLineParser.parse(parseable_line)
if req:
req.hashes = hashes
req.index_server = index_server
# replace the requirements line with the 'real' line
req.line = line
self.obj.dependencies.append(req)
except ValueError:
continue | [
"def",
"parse",
"(",
"self",
")",
":",
"index_server",
"=",
"None",
"for",
"num",
",",
"line",
"in",
"enumerate",
"(",
"self",
".",
"iter_lines",
"(",
")",
")",
":",
"line",
"=",
"line",
".",
"rstrip",
"(",
")",
"if",
"not",
"line",
":",
"continue"... | Parses a requirements.txt-like file | [
"Parses",
"a",
"requirements",
".",
"txt",
"-",
"like",
"file"
] | 0cd5aa7eb1f78c39da78b6c63dde6b49a1732cd2 | https://github.com/pyupio/dparse/blob/0cd5aa7eb1f78c39da78b6c63dde6b49a1732cd2/dparse/parser.py#L221-L278 | train | 31,357 |
hynek/environ_config | src/environ/_environ_config.py | _format_help_dicts | def _format_help_dicts(help_dicts, display_defaults=False):
"""
Format the output of _generate_help_dicts into a str
"""
help_strs = []
for help_dict in help_dicts:
help_str = "%s (%s" % (
help_dict["var_name"],
"Required" if help_dict["required"] else "Optional",
)
if help_dict.get("default") and display_defaults:
help_str += ", Default=%s)" % help_dict["default"]
else:
help_str += ")"
if help_dict.get("help_str"):
help_str += ": %s" % help_dict["help_str"]
help_strs.append(help_str)
return "\n".join(help_strs) | python | def _format_help_dicts(help_dicts, display_defaults=False):
"""
Format the output of _generate_help_dicts into a str
"""
help_strs = []
for help_dict in help_dicts:
help_str = "%s (%s" % (
help_dict["var_name"],
"Required" if help_dict["required"] else "Optional",
)
if help_dict.get("default") and display_defaults:
help_str += ", Default=%s)" % help_dict["default"]
else:
help_str += ")"
if help_dict.get("help_str"):
help_str += ": %s" % help_dict["help_str"]
help_strs.append(help_str)
return "\n".join(help_strs) | [
"def",
"_format_help_dicts",
"(",
"help_dicts",
",",
"display_defaults",
"=",
"False",
")",
":",
"help_strs",
"=",
"[",
"]",
"for",
"help_dict",
"in",
"help_dicts",
":",
"help_str",
"=",
"\"%s (%s\"",
"%",
"(",
"help_dict",
"[",
"\"var_name\"",
"]",
",",
"\"... | Format the output of _generate_help_dicts into a str | [
"Format",
"the",
"output",
"of",
"_generate_help_dicts",
"into",
"a",
"str"
] | d61c0822bf0b6516932534e0496bd3f360a3e5e2 | https://github.com/hynek/environ_config/blob/d61c0822bf0b6516932534e0496bd3f360a3e5e2/src/environ/_environ_config.py#L135-L153 | train | 31,358 |
hynek/environ_config | src/environ/_environ_config.py | _generate_help_dicts | def _generate_help_dicts(config_cls, _prefix=None):
"""
Generate dictionaries for use in building help strings.
Every dictionary includes the keys...
var_name: The env var that should be set to populate the value.
required: A bool, True if the var is required, False if it's optional.
Conditionally, the following are included...
default: Included if an optional variable has a default set
help_str: Included if the var uses the help kwarg to provide additional
context for the value.
Conditional key inclusion is meant to differentiate between exclusion
vs explicitly setting a value to None.
"""
help_dicts = []
if _prefix is None:
_prefix = config_cls._prefix
for a in attr.fields(config_cls):
try:
ce = a.metadata[CNF_KEY]
except KeyError:
continue
if ce.sub_cls is None: # Base case for "leaves".
if ce.name is None:
var_name = "_".join((_prefix, a.name)).upper()
else:
var_name = ce.name
req = ce.default == RAISE
help_dict = {"var_name": var_name, "required": req}
if not req:
help_dict["default"] = ce.default
if ce.help is not None:
help_dict["help_str"] = ce.help
help_dicts.append(help_dict)
else: # Construct the new prefix and recurse.
help_dicts += _generate_help_dicts(
ce.sub_cls, _prefix="_".join((_prefix, a.name)).upper()
)
return help_dicts | python | def _generate_help_dicts(config_cls, _prefix=None):
"""
Generate dictionaries for use in building help strings.
Every dictionary includes the keys...
var_name: The env var that should be set to populate the value.
required: A bool, True if the var is required, False if it's optional.
Conditionally, the following are included...
default: Included if an optional variable has a default set
help_str: Included if the var uses the help kwarg to provide additional
context for the value.
Conditional key inclusion is meant to differentiate between exclusion
vs explicitly setting a value to None.
"""
help_dicts = []
if _prefix is None:
_prefix = config_cls._prefix
for a in attr.fields(config_cls):
try:
ce = a.metadata[CNF_KEY]
except KeyError:
continue
if ce.sub_cls is None: # Base case for "leaves".
if ce.name is None:
var_name = "_".join((_prefix, a.name)).upper()
else:
var_name = ce.name
req = ce.default == RAISE
help_dict = {"var_name": var_name, "required": req}
if not req:
help_dict["default"] = ce.default
if ce.help is not None:
help_dict["help_str"] = ce.help
help_dicts.append(help_dict)
else: # Construct the new prefix and recurse.
help_dicts += _generate_help_dicts(
ce.sub_cls, _prefix="_".join((_prefix, a.name)).upper()
)
return help_dicts | [
"def",
"_generate_help_dicts",
"(",
"config_cls",
",",
"_prefix",
"=",
"None",
")",
":",
"help_dicts",
"=",
"[",
"]",
"if",
"_prefix",
"is",
"None",
":",
"_prefix",
"=",
"config_cls",
".",
"_prefix",
"for",
"a",
"in",
"attr",
".",
"fields",
"(",
"config_... | Generate dictionaries for use in building help strings.
Every dictionary includes the keys...
var_name: The env var that should be set to populate the value.
required: A bool, True if the var is required, False if it's optional.
Conditionally, the following are included...
default: Included if an optional variable has a default set
help_str: Included if the var uses the help kwarg to provide additional
context for the value.
Conditional key inclusion is meant to differentiate between exclusion
vs explicitly setting a value to None. | [
"Generate",
"dictionaries",
"for",
"use",
"in",
"building",
"help",
"strings",
"."
] | d61c0822bf0b6516932534e0496bd3f360a3e5e2 | https://github.com/hynek/environ_config/blob/d61c0822bf0b6516932534e0496bd3f360a3e5e2/src/environ/_environ_config.py#L156-L198 | train | 31,359 |
hynek/environ_config | src/environ/_environ_config.py | generate_help | def generate_help(config_cls, **kwargs):
"""
Autogenerate a help string for a config class.
If a callable is provided via the "formatter" kwarg it
will be provided with the help dictionaries as an argument
and any other kwargs provided to this function. That callable
should return the help text string.
"""
try:
formatter = kwargs.pop("formatter")
except KeyError:
formatter = _format_help_dicts
help_dicts = _generate_help_dicts(config_cls)
return formatter(help_dicts, **kwargs) | python | def generate_help(config_cls, **kwargs):
"""
Autogenerate a help string for a config class.
If a callable is provided via the "formatter" kwarg it
will be provided with the help dictionaries as an argument
and any other kwargs provided to this function. That callable
should return the help text string.
"""
try:
formatter = kwargs.pop("formatter")
except KeyError:
formatter = _format_help_dicts
help_dicts = _generate_help_dicts(config_cls)
return formatter(help_dicts, **kwargs) | [
"def",
"generate_help",
"(",
"config_cls",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"formatter",
"=",
"kwargs",
".",
"pop",
"(",
"\"formatter\"",
")",
"except",
"KeyError",
":",
"formatter",
"=",
"_format_help_dicts",
"help_dicts",
"=",
"_generate_help_d... | Autogenerate a help string for a config class.
If a callable is provided via the "formatter" kwarg it
will be provided with the help dictionaries as an argument
and any other kwargs provided to this function. That callable
should return the help text string. | [
"Autogenerate",
"a",
"help",
"string",
"for",
"a",
"config",
"class",
"."
] | d61c0822bf0b6516932534e0496bd3f360a3e5e2 | https://github.com/hynek/environ_config/blob/d61c0822bf0b6516932534e0496bd3f360a3e5e2/src/environ/_environ_config.py#L201-L215 | train | 31,360 |
yceruto/django-ajax | django_ajax/shortcuts.py | render_to_json | def render_to_json(response, request=None, **kwargs):
"""
Creates the main structure and returns the JSON response.
"""
# determine the status code
if hasattr(response, 'status_code'):
status_code = response.status_code
elif issubclass(type(response), Http404):
status_code = 404
elif issubclass(type(response), Exception):
status_code = 500
logger.exception(str(response), extra={'request': request})
if settings.DEBUG:
import sys
reporter = ExceptionReporter(None, *sys.exc_info())
text = reporter.get_traceback_text()
response = HttpResponseServerError(text, content_type='text/plain')
else:
response = HttpResponseServerError("An error occured while processing an AJAX request.", content_type='text/plain')
else:
status_code = 200
# creating main structure
data = {
'status': status_code,
'statusText': REASON_PHRASES.get(status_code, 'UNKNOWN STATUS CODE'),
'content': response
}
return JSONResponse(data, **kwargs) | python | def render_to_json(response, request=None, **kwargs):
"""
Creates the main structure and returns the JSON response.
"""
# determine the status code
if hasattr(response, 'status_code'):
status_code = response.status_code
elif issubclass(type(response), Http404):
status_code = 404
elif issubclass(type(response), Exception):
status_code = 500
logger.exception(str(response), extra={'request': request})
if settings.DEBUG:
import sys
reporter = ExceptionReporter(None, *sys.exc_info())
text = reporter.get_traceback_text()
response = HttpResponseServerError(text, content_type='text/plain')
else:
response = HttpResponseServerError("An error occured while processing an AJAX request.", content_type='text/plain')
else:
status_code = 200
# creating main structure
data = {
'status': status_code,
'statusText': REASON_PHRASES.get(status_code, 'UNKNOWN STATUS CODE'),
'content': response
}
return JSONResponse(data, **kwargs) | [
"def",
"render_to_json",
"(",
"response",
",",
"request",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# determine the status code",
"if",
"hasattr",
"(",
"response",
",",
"'status_code'",
")",
":",
"status_code",
"=",
"response",
".",
"status_code",
"elif... | Creates the main structure and returns the JSON response. | [
"Creates",
"the",
"main",
"structure",
"and",
"returns",
"the",
"JSON",
"response",
"."
] | d5af47c0e65571d4729f48781c0b41886b926221 | https://github.com/yceruto/django-ajax/blob/d5af47c0e65571d4729f48781c0b41886b926221/django_ajax/shortcuts.py#L79-L109 | train | 31,361 |
yceruto/django-ajax | django_ajax/mixin.py | AJAXMixin.dispatch | def dispatch(self, request, *args, **kwargs):
"""
Using ajax decorator
"""
ajax_kwargs = {'mandatory': self.ajax_mandatory}
if self.json_encoder:
ajax_kwargs['cls'] = self.json_encoder
return ajax(**ajax_kwargs)(super(
AJAXMixin, self).dispatch)(request, *args, **kwargs) | python | def dispatch(self, request, *args, **kwargs):
"""
Using ajax decorator
"""
ajax_kwargs = {'mandatory': self.ajax_mandatory}
if self.json_encoder:
ajax_kwargs['cls'] = self.json_encoder
return ajax(**ajax_kwargs)(super(
AJAXMixin, self).dispatch)(request, *args, **kwargs) | [
"def",
"dispatch",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"ajax_kwargs",
"=",
"{",
"'mandatory'",
":",
"self",
".",
"ajax_mandatory",
"}",
"if",
"self",
".",
"json_encoder",
":",
"ajax_kwargs",
"[",
"'cls'",
"... | Using ajax decorator | [
"Using",
"ajax",
"decorator"
] | d5af47c0e65571d4729f48781c0b41886b926221 | https://github.com/yceruto/django-ajax/blob/d5af47c0e65571d4729f48781c0b41886b926221/django_ajax/mixin.py#L17-L26 | train | 31,362 |
ioos/compliance-checker | compliance_checker/protocols/opendap.py | is_opendap | def is_opendap(url):
'''
Returns True if the URL is a valid OPeNDAP URL
:param str url: URL for a remote OPeNDAP endpoint
'''
# If the server replies to a Data Attribute Structure request
if url.endswith('#fillmismatch'):
das_url = url.replace('#fillmismatch', '.das')
else:
das_url = url + '.das'
response = requests.get(das_url, allow_redirects=True)
if 'xdods-server' in response.headers:
return True
# Check if it is an access restricted ESGF thredds service
if response.status_code == 401 and \
'text/html' in response.headers['content-type'] and \
'The following URL requires authentication:' in response.text:
return True
return False | python | def is_opendap(url):
'''
Returns True if the URL is a valid OPeNDAP URL
:param str url: URL for a remote OPeNDAP endpoint
'''
# If the server replies to a Data Attribute Structure request
if url.endswith('#fillmismatch'):
das_url = url.replace('#fillmismatch', '.das')
else:
das_url = url + '.das'
response = requests.get(das_url, allow_redirects=True)
if 'xdods-server' in response.headers:
return True
# Check if it is an access restricted ESGF thredds service
if response.status_code == 401 and \
'text/html' in response.headers['content-type'] and \
'The following URL requires authentication:' in response.text:
return True
return False | [
"def",
"is_opendap",
"(",
"url",
")",
":",
"# If the server replies to a Data Attribute Structure request",
"if",
"url",
".",
"endswith",
"(",
"'#fillmismatch'",
")",
":",
"das_url",
"=",
"url",
".",
"replace",
"(",
"'#fillmismatch'",
",",
"'.das'",
")",
"else",
"... | Returns True if the URL is a valid OPeNDAP URL
:param str url: URL for a remote OPeNDAP endpoint | [
"Returns",
"True",
"if",
"the",
"URL",
"is",
"a",
"valid",
"OPeNDAP",
"URL"
] | ee89c27b0daade58812489a2da3aa3b6859eafd9 | https://github.com/ioos/compliance-checker/blob/ee89c27b0daade58812489a2da3aa3b6859eafd9/compliance_checker/protocols/opendap.py#L10-L29 | train | 31,363 |
ioos/compliance-checker | compliance_checker/util.py | datetime_is_iso | def datetime_is_iso(date_str):
"""Attempts to parse a date formatted in ISO 8601 format"""
try:
if len(date_str) > 10:
dt = isodate.parse_datetime(date_str)
else:
dt = isodate.parse_date(date_str)
return True, []
except: # Any error qualifies as not ISO format
return False, ['Datetime provided is not in a valid ISO 8601 format'] | python | def datetime_is_iso(date_str):
"""Attempts to parse a date formatted in ISO 8601 format"""
try:
if len(date_str) > 10:
dt = isodate.parse_datetime(date_str)
else:
dt = isodate.parse_date(date_str)
return True, []
except: # Any error qualifies as not ISO format
return False, ['Datetime provided is not in a valid ISO 8601 format'] | [
"def",
"datetime_is_iso",
"(",
"date_str",
")",
":",
"try",
":",
"if",
"len",
"(",
"date_str",
")",
">",
"10",
":",
"dt",
"=",
"isodate",
".",
"parse_datetime",
"(",
"date_str",
")",
"else",
":",
"dt",
"=",
"isodate",
".",
"parse_date",
"(",
"date_str"... | Attempts to parse a date formatted in ISO 8601 format | [
"Attempts",
"to",
"parse",
"a",
"date",
"formatted",
"in",
"ISO",
"8601",
"format"
] | ee89c27b0daade58812489a2da3aa3b6859eafd9 | https://github.com/ioos/compliance-checker/blob/ee89c27b0daade58812489a2da3aa3b6859eafd9/compliance_checker/util.py#L16-L25 | train | 31,364 |
ioos/compliance-checker | compliance_checker/protocols/cdl.py | is_cdl | def is_cdl(filename):
'''
Quick check for .cdl ascii file
Example:
netcdf sample_file {
dimensions:
name_strlen = 7 ;
time = 96 ;
variables:
float lat ;
lat:units = "degrees_north" ;
lat:standard_name = "latitude" ;
lat:long_name = "station latitude" ;
etc...
:param str filename: Absolute path of file to check
:param str data: First chuck of data from file to check
'''
if os.path.splitext(filename)[-1] != '.cdl':
return False
with open(filename, 'rb') as f:
data = f.read(32)
if data.startswith(b'netcdf') or b'dimensions' in data:
return True
return False | python | def is_cdl(filename):
'''
Quick check for .cdl ascii file
Example:
netcdf sample_file {
dimensions:
name_strlen = 7 ;
time = 96 ;
variables:
float lat ;
lat:units = "degrees_north" ;
lat:standard_name = "latitude" ;
lat:long_name = "station latitude" ;
etc...
:param str filename: Absolute path of file to check
:param str data: First chuck of data from file to check
'''
if os.path.splitext(filename)[-1] != '.cdl':
return False
with open(filename, 'rb') as f:
data = f.read(32)
if data.startswith(b'netcdf') or b'dimensions' in data:
return True
return False | [
"def",
"is_cdl",
"(",
"filename",
")",
":",
"if",
"os",
".",
"path",
".",
"splitext",
"(",
"filename",
")",
"[",
"-",
"1",
"]",
"!=",
"'.cdl'",
":",
"return",
"False",
"with",
"open",
"(",
"filename",
",",
"'rb'",
")",
"as",
"f",
":",
"data",
"="... | Quick check for .cdl ascii file
Example:
netcdf sample_file {
dimensions:
name_strlen = 7 ;
time = 96 ;
variables:
float lat ;
lat:units = "degrees_north" ;
lat:standard_name = "latitude" ;
lat:long_name = "station latitude" ;
etc...
:param str filename: Absolute path of file to check
:param str data: First chuck of data from file to check | [
"Quick",
"check",
"for",
".",
"cdl",
"ascii",
"file"
] | ee89c27b0daade58812489a2da3aa3b6859eafd9 | https://github.com/ioos/compliance-checker/blob/ee89c27b0daade58812489a2da3aa3b6859eafd9/compliance_checker/protocols/cdl.py#L8-L34 | train | 31,365 |
ioos/compliance-checker | compliance_checker/runner.py | ComplianceChecker.run_checker | def run_checker(cls, ds_loc, checker_names, verbose, criteria,
skip_checks=None, output_filename='-',
output_format=['text']):
"""
Static check runner.
@param ds_loc Dataset location (url or file)
@param checker_names List of string names to run, should match keys of checkers dict (empty list means run all)
@param verbose Verbosity of the output (0, 1, 2)
@param criteria Determines failure (lenient, normal, strict)
@param output_filename Path to the file for output
@param skip_checks Names of checks to skip
@param output_format Format of the output(s)
@returns If the tests failed (based on the criteria)
"""
all_groups = []
cs = CheckSuite()
# using OrderedDict is important here to preserve the order
# of multiple datasets which may be passed in
score_dict = OrderedDict()
if not isinstance(ds_loc, six.string_types):
locs = ds_loc
# if single dataset, put in list
else:
locs = [ds_loc]
# Make sure output format is a list
if isinstance(output_format, six.string_types):
output_format = [output_format]
for loc in locs: # loop through each dataset and run specified checks
ds = cs.load_dataset(loc)
score_groups = cs.run(ds, skip_checks, *checker_names)
for group in score_groups.values():
all_groups.append(group[0])
# TODO: consider wrapping in a proper context manager instead
if hasattr(ds, 'close'):
ds.close()
if not score_groups:
raise ValueError("No checks found, please check the name of the checker(s) and that they are installed")
else:
score_dict[loc] = score_groups
# define a score limit to truncate the ouput to the strictness level
# specified by the user
if criteria == 'normal':
limit = 2
elif criteria == 'strict':
limit = 1
elif criteria == 'lenient':
limit = 3
for out_fmt in output_format:
if out_fmt == 'text':
if output_filename == '-':
cls.stdout_output(cs, score_dict, verbose, limit)
# need to redirect output from stdout since print functions are
# presently used to generate the standard report output
else:
if len(output_format) > 1:
# Update file name if needed
output_filename = '{}.txt'.format(os.path.splitext(output_filename)[0])
with io.open(output_filename, 'w', encoding='utf-8') as f:
with stdout_redirector(f):
cls.stdout_output(cs, score_dict, verbose, limit)
elif out_fmt == 'html':
# Update file name if needed
if len(output_format) > 1 and output_filename != '-':
output_filename = '{}.html'.format(os.path.splitext(output_filename)[0])
cls.html_output(cs, score_dict, output_filename, ds_loc, limit)
elif out_fmt in {'json', 'json_new'}:
# Update file name if needed
if len(output_format) > 1 and output_filename != '-':
output_filename = '{}.json'.format(os.path.splitext(output_filename)[0])
cls.json_output(cs, score_dict, output_filename, ds_loc, limit,
out_fmt)
else:
raise TypeError('Invalid format %s' % out_fmt)
errors_occurred = cls.check_errors(score_groups, verbose)
return (all(cs.passtree(groups, limit) for groups in all_groups),
errors_occurred) | python | def run_checker(cls, ds_loc, checker_names, verbose, criteria,
skip_checks=None, output_filename='-',
output_format=['text']):
"""
Static check runner.
@param ds_loc Dataset location (url or file)
@param checker_names List of string names to run, should match keys of checkers dict (empty list means run all)
@param verbose Verbosity of the output (0, 1, 2)
@param criteria Determines failure (lenient, normal, strict)
@param output_filename Path to the file for output
@param skip_checks Names of checks to skip
@param output_format Format of the output(s)
@returns If the tests failed (based on the criteria)
"""
all_groups = []
cs = CheckSuite()
# using OrderedDict is important here to preserve the order
# of multiple datasets which may be passed in
score_dict = OrderedDict()
if not isinstance(ds_loc, six.string_types):
locs = ds_loc
# if single dataset, put in list
else:
locs = [ds_loc]
# Make sure output format is a list
if isinstance(output_format, six.string_types):
output_format = [output_format]
for loc in locs: # loop through each dataset and run specified checks
ds = cs.load_dataset(loc)
score_groups = cs.run(ds, skip_checks, *checker_names)
for group in score_groups.values():
all_groups.append(group[0])
# TODO: consider wrapping in a proper context manager instead
if hasattr(ds, 'close'):
ds.close()
if not score_groups:
raise ValueError("No checks found, please check the name of the checker(s) and that they are installed")
else:
score_dict[loc] = score_groups
# define a score limit to truncate the ouput to the strictness level
# specified by the user
if criteria == 'normal':
limit = 2
elif criteria == 'strict':
limit = 1
elif criteria == 'lenient':
limit = 3
for out_fmt in output_format:
if out_fmt == 'text':
if output_filename == '-':
cls.stdout_output(cs, score_dict, verbose, limit)
# need to redirect output from stdout since print functions are
# presently used to generate the standard report output
else:
if len(output_format) > 1:
# Update file name if needed
output_filename = '{}.txt'.format(os.path.splitext(output_filename)[0])
with io.open(output_filename, 'w', encoding='utf-8') as f:
with stdout_redirector(f):
cls.stdout_output(cs, score_dict, verbose, limit)
elif out_fmt == 'html':
# Update file name if needed
if len(output_format) > 1 and output_filename != '-':
output_filename = '{}.html'.format(os.path.splitext(output_filename)[0])
cls.html_output(cs, score_dict, output_filename, ds_loc, limit)
elif out_fmt in {'json', 'json_new'}:
# Update file name if needed
if len(output_format) > 1 and output_filename != '-':
output_filename = '{}.json'.format(os.path.splitext(output_filename)[0])
cls.json_output(cs, score_dict, output_filename, ds_loc, limit,
out_fmt)
else:
raise TypeError('Invalid format %s' % out_fmt)
errors_occurred = cls.check_errors(score_groups, verbose)
return (all(cs.passtree(groups, limit) for groups in all_groups),
errors_occurred) | [
"def",
"run_checker",
"(",
"cls",
",",
"ds_loc",
",",
"checker_names",
",",
"verbose",
",",
"criteria",
",",
"skip_checks",
"=",
"None",
",",
"output_filename",
"=",
"'-'",
",",
"output_format",
"=",
"[",
"'text'",
"]",
")",
":",
"all_groups",
"=",
"[",
... | Static check runner.
@param ds_loc Dataset location (url or file)
@param checker_names List of string names to run, should match keys of checkers dict (empty list means run all)
@param verbose Verbosity of the output (0, 1, 2)
@param criteria Determines failure (lenient, normal, strict)
@param output_filename Path to the file for output
@param skip_checks Names of checks to skip
@param output_format Format of the output(s)
@returns If the tests failed (based on the criteria) | [
"Static",
"check",
"runner",
"."
] | ee89c27b0daade58812489a2da3aa3b6859eafd9 | https://github.com/ioos/compliance-checker/blob/ee89c27b0daade58812489a2da3aa3b6859eafd9/compliance_checker/runner.py#L35-L123 | train | 31,366 |
ioos/compliance-checker | compliance_checker/runner.py | ComplianceChecker.stdout_output | def stdout_output(cls, cs, score_dict, verbose, limit):
'''
Calls output routine to display results in terminal, including scoring.
Goes to verbose function if called by user.
@param cs Compliance Checker Suite
@param score_dict Dict with dataset name as key, list of results as
value
@param verbose Integer value for verbosity level
@param limit The degree of strictness, 1 being the strictest, and going up from there.
'''
for ds, score_groups in six.iteritems(score_dict):
for checker, rpair in six.iteritems(score_groups):
groups, errors = rpair
score_list, points, out_of = cs.standard_output(ds, limit,
checker,
groups)
# send list of grouped result objects to stdout & reasoning_routine
cs.standard_output_generation(groups, limit, points, out_of,
check=checker)
return groups | python | def stdout_output(cls, cs, score_dict, verbose, limit):
'''
Calls output routine to display results in terminal, including scoring.
Goes to verbose function if called by user.
@param cs Compliance Checker Suite
@param score_dict Dict with dataset name as key, list of results as
value
@param verbose Integer value for verbosity level
@param limit The degree of strictness, 1 being the strictest, and going up from there.
'''
for ds, score_groups in six.iteritems(score_dict):
for checker, rpair in six.iteritems(score_groups):
groups, errors = rpair
score_list, points, out_of = cs.standard_output(ds, limit,
checker,
groups)
# send list of grouped result objects to stdout & reasoning_routine
cs.standard_output_generation(groups, limit, points, out_of,
check=checker)
return groups | [
"def",
"stdout_output",
"(",
"cls",
",",
"cs",
",",
"score_dict",
",",
"verbose",
",",
"limit",
")",
":",
"for",
"ds",
",",
"score_groups",
"in",
"six",
".",
"iteritems",
"(",
"score_dict",
")",
":",
"for",
"checker",
",",
"rpair",
"in",
"six",
".",
... | Calls output routine to display results in terminal, including scoring.
Goes to verbose function if called by user.
@param cs Compliance Checker Suite
@param score_dict Dict with dataset name as key, list of results as
value
@param verbose Integer value for verbosity level
@param limit The degree of strictness, 1 being the strictest, and going up from there. | [
"Calls",
"output",
"routine",
"to",
"display",
"results",
"in",
"terminal",
"including",
"scoring",
".",
"Goes",
"to",
"verbose",
"function",
"if",
"called",
"by",
"user",
"."
] | ee89c27b0daade58812489a2da3aa3b6859eafd9 | https://github.com/ioos/compliance-checker/blob/ee89c27b0daade58812489a2da3aa3b6859eafd9/compliance_checker/runner.py#L126-L147 | train | 31,367 |
ioos/compliance-checker | compliance_checker/ioos.py | IOOSNCCheck.check_time_period | def check_time_period(self, ds):
"""
Check that time period attributes are both set.
"""
start = self.std_check(ds, 'time_coverage_start')
end = self.std_check(ds, 'time_coverage_end')
msgs = []
count = 2
if not start:
count -= 1
msgs.append("Attr 'time_coverage_start' is missing")
if not end:
count -= 1
msgs.append("Attr 'time_coverage_end' is missing")
return Result(BaseCheck.HIGH, (count, 2), 'time coverage start/end', msgs) | python | def check_time_period(self, ds):
"""
Check that time period attributes are both set.
"""
start = self.std_check(ds, 'time_coverage_start')
end = self.std_check(ds, 'time_coverage_end')
msgs = []
count = 2
if not start:
count -= 1
msgs.append("Attr 'time_coverage_start' is missing")
if not end:
count -= 1
msgs.append("Attr 'time_coverage_end' is missing")
return Result(BaseCheck.HIGH, (count, 2), 'time coverage start/end', msgs) | [
"def",
"check_time_period",
"(",
"self",
",",
"ds",
")",
":",
"start",
"=",
"self",
".",
"std_check",
"(",
"ds",
",",
"'time_coverage_start'",
")",
"end",
"=",
"self",
".",
"std_check",
"(",
"ds",
",",
"'time_coverage_end'",
")",
"msgs",
"=",
"[",
"]",
... | Check that time period attributes are both set. | [
"Check",
"that",
"time",
"period",
"attributes",
"are",
"both",
"set",
"."
] | ee89c27b0daade58812489a2da3aa3b6859eafd9 | https://github.com/ioos/compliance-checker/blob/ee89c27b0daade58812489a2da3aa3b6859eafd9/compliance_checker/ioos.py#L57-L73 | train | 31,368 |
ioos/compliance-checker | compliance_checker/ioos.py | IOOSNCCheck.check_station_location_lat | def check_station_location_lat(self, ds):
"""
Checks station lat attributes are set
"""
gmin = self.std_check(ds, 'geospatial_lat_min')
gmax = self.std_check(ds, 'geospatial_lat_max')
msgs = []
count = 2
if not gmin:
count -= 1
msgs.append("Attr 'geospatial_lat_min' is missing")
if not gmax:
count -= 1
msgs.append("Attr 'geospatial_lat_max' is missing")
return Result(BaseCheck.HIGH, (count, 2), 'geospatial lat min/max', msgs) | python | def check_station_location_lat(self, ds):
"""
Checks station lat attributes are set
"""
gmin = self.std_check(ds, 'geospatial_lat_min')
gmax = self.std_check(ds, 'geospatial_lat_max')
msgs = []
count = 2
if not gmin:
count -= 1
msgs.append("Attr 'geospatial_lat_min' is missing")
if not gmax:
count -= 1
msgs.append("Attr 'geospatial_lat_max' is missing")
return Result(BaseCheck.HIGH, (count, 2), 'geospatial lat min/max', msgs) | [
"def",
"check_station_location_lat",
"(",
"self",
",",
"ds",
")",
":",
"gmin",
"=",
"self",
".",
"std_check",
"(",
"ds",
",",
"'geospatial_lat_min'",
")",
"gmax",
"=",
"self",
".",
"std_check",
"(",
"ds",
",",
"'geospatial_lat_max'",
")",
"msgs",
"=",
"[",... | Checks station lat attributes are set | [
"Checks",
"station",
"lat",
"attributes",
"are",
"set"
] | ee89c27b0daade58812489a2da3aa3b6859eafd9 | https://github.com/ioos/compliance-checker/blob/ee89c27b0daade58812489a2da3aa3b6859eafd9/compliance_checker/ioos.py#L75-L91 | train | 31,369 |
ioos/compliance-checker | compliance_checker/ioos.py | IOOS0_1Check.check_global_attributes | def check_global_attributes(self, ds):
"""
Check all global NC attributes for existence.
:param netCDF4.Dataset ds: An open netCDF dataset
"""
return [
self._has_attr(ds, 'acknowledgement', 'Platform Sponsor'),
self._has_attr(ds, 'publisher_email', 'Station Publisher Email'),
self._has_attr(ds, 'publisher_email', 'Service Contact Email', BaseCheck.MEDIUM),
self._has_attr(ds, 'institution', 'Service Provider Name', BaseCheck.MEDIUM),
self._has_attr(ds, 'publisher_name', 'Service Contact Name', BaseCheck.MEDIUM),
self._has_attr(ds, 'Conventions', 'Data Format Template Version', BaseCheck.MEDIUM),
self._has_attr(ds, 'publisher_name', 'Station Publisher Name', BaseCheck.HIGH),
] | python | def check_global_attributes(self, ds):
"""
Check all global NC attributes for existence.
:param netCDF4.Dataset ds: An open netCDF dataset
"""
return [
self._has_attr(ds, 'acknowledgement', 'Platform Sponsor'),
self._has_attr(ds, 'publisher_email', 'Station Publisher Email'),
self._has_attr(ds, 'publisher_email', 'Service Contact Email', BaseCheck.MEDIUM),
self._has_attr(ds, 'institution', 'Service Provider Name', BaseCheck.MEDIUM),
self._has_attr(ds, 'publisher_name', 'Service Contact Name', BaseCheck.MEDIUM),
self._has_attr(ds, 'Conventions', 'Data Format Template Version', BaseCheck.MEDIUM),
self._has_attr(ds, 'publisher_name', 'Station Publisher Name', BaseCheck.HIGH),
] | [
"def",
"check_global_attributes",
"(",
"self",
",",
"ds",
")",
":",
"return",
"[",
"self",
".",
"_has_attr",
"(",
"ds",
",",
"'acknowledgement'",
",",
"'Platform Sponsor'",
")",
",",
"self",
".",
"_has_attr",
"(",
"ds",
",",
"'publisher_email'",
",",
"'Stati... | Check all global NC attributes for existence.
:param netCDF4.Dataset ds: An open netCDF dataset | [
"Check",
"all",
"global",
"NC",
"attributes",
"for",
"existence",
"."
] | ee89c27b0daade58812489a2da3aa3b6859eafd9 | https://github.com/ioos/compliance-checker/blob/ee89c27b0daade58812489a2da3aa3b6859eafd9/compliance_checker/ioos.py#L117-L131 | train | 31,370 |
ioos/compliance-checker | compliance_checker/ioos.py | IOOS0_1Check.check_variable_attributes | def check_variable_attributes(self, ds):
"""
Check IOOS concepts that come from NC variable attributes.
:param netCDF4.Dataset ds: An open netCDF dataset
"""
return [
self._has_var_attr(ds, 'platform', 'long_name', 'Station Long Name'),
self._has_var_attr(ds, 'platform', 'short_name', 'Station Short Name'),
self._has_var_attr(ds, 'platform', 'source', 'Platform Type'),
self._has_var_attr(ds, 'platform', 'ioos_name', 'Station ID'),
self._has_var_attr(ds, 'platform', 'wmo_id', 'Station WMO ID'),
self._has_var_attr(ds, 'platform', 'comment', 'Station Description'),
] | python | def check_variable_attributes(self, ds):
"""
Check IOOS concepts that come from NC variable attributes.
:param netCDF4.Dataset ds: An open netCDF dataset
"""
return [
self._has_var_attr(ds, 'platform', 'long_name', 'Station Long Name'),
self._has_var_attr(ds, 'platform', 'short_name', 'Station Short Name'),
self._has_var_attr(ds, 'platform', 'source', 'Platform Type'),
self._has_var_attr(ds, 'platform', 'ioos_name', 'Station ID'),
self._has_var_attr(ds, 'platform', 'wmo_id', 'Station WMO ID'),
self._has_var_attr(ds, 'platform', 'comment', 'Station Description'),
] | [
"def",
"check_variable_attributes",
"(",
"self",
",",
"ds",
")",
":",
"return",
"[",
"self",
".",
"_has_var_attr",
"(",
"ds",
",",
"'platform'",
",",
"'long_name'",
",",
"'Station Long Name'",
")",
",",
"self",
".",
"_has_var_attr",
"(",
"ds",
",",
"'platfor... | Check IOOS concepts that come from NC variable attributes.
:param netCDF4.Dataset ds: An open netCDF dataset | [
"Check",
"IOOS",
"concepts",
"that",
"come",
"from",
"NC",
"variable",
"attributes",
"."
] | ee89c27b0daade58812489a2da3aa3b6859eafd9 | https://github.com/ioos/compliance-checker/blob/ee89c27b0daade58812489a2da3aa3b6859eafd9/compliance_checker/ioos.py#L133-L146 | train | 31,371 |
ioos/compliance-checker | compliance_checker/ioos.py | IOOS0_1Check.check_variable_names | def check_variable_names(self, ds):
"""
Ensures all variables have a standard_name set.
"""
msgs = []
count = 0
for k, v in ds.variables.items():
if 'standard_name' in v.ncattrs():
count += 1
else:
msgs.append("Variable '{}' missing standard_name attr".format(k))
return Result(BaseCheck.MEDIUM, (count, len(ds.variables)), 'Variable Names', msgs) | python | def check_variable_names(self, ds):
"""
Ensures all variables have a standard_name set.
"""
msgs = []
count = 0
for k, v in ds.variables.items():
if 'standard_name' in v.ncattrs():
count += 1
else:
msgs.append("Variable '{}' missing standard_name attr".format(k))
return Result(BaseCheck.MEDIUM, (count, len(ds.variables)), 'Variable Names', msgs) | [
"def",
"check_variable_names",
"(",
"self",
",",
"ds",
")",
":",
"msgs",
"=",
"[",
"]",
"count",
"=",
"0",
"for",
"k",
",",
"v",
"in",
"ds",
".",
"variables",
".",
"items",
"(",
")",
":",
"if",
"'standard_name'",
"in",
"v",
".",
"ncattrs",
"(",
"... | Ensures all variables have a standard_name set. | [
"Ensures",
"all",
"variables",
"have",
"a",
"standard_name",
"set",
"."
] | ee89c27b0daade58812489a2da3aa3b6859eafd9 | https://github.com/ioos/compliance-checker/blob/ee89c27b0daade58812489a2da3aa3b6859eafd9/compliance_checker/ioos.py#L148-L161 | train | 31,372 |
ioos/compliance-checker | compliance_checker/ioos.py | IOOS0_1Check.check_altitude_units | def check_altitude_units(self, ds):
"""
If there's a variable named z, it must have units.
@TODO: this is duplicated with check_variable_units
:param netCDF4.Dataset ds: An open netCDF dataset
"""
if 'z' in ds.variables:
msgs = []
val = 'units' in ds.variables['z'].ncattrs()
if not val:
msgs.append("Variable 'z' has no units attr")
return Result(BaseCheck.LOW, val, 'Altitude Units', msgs)
return Result(BaseCheck.LOW, (0, 0), 'Altitude Units', ["Dataset has no 'z' variable"]) | python | def check_altitude_units(self, ds):
"""
If there's a variable named z, it must have units.
@TODO: this is duplicated with check_variable_units
:param netCDF4.Dataset ds: An open netCDF dataset
"""
if 'z' in ds.variables:
msgs = []
val = 'units' in ds.variables['z'].ncattrs()
if not val:
msgs.append("Variable 'z' has no units attr")
return Result(BaseCheck.LOW, val, 'Altitude Units', msgs)
return Result(BaseCheck.LOW, (0, 0), 'Altitude Units', ["Dataset has no 'z' variable"]) | [
"def",
"check_altitude_units",
"(",
"self",
",",
"ds",
")",
":",
"if",
"'z'",
"in",
"ds",
".",
"variables",
":",
"msgs",
"=",
"[",
"]",
"val",
"=",
"'units'",
"in",
"ds",
".",
"variables",
"[",
"'z'",
"]",
".",
"ncattrs",
"(",
")",
"if",
"not",
"... | If there's a variable named z, it must have units.
@TODO: this is duplicated with check_variable_units
:param netCDF4.Dataset ds: An open netCDF dataset | [
"If",
"there",
"s",
"a",
"variable",
"named",
"z",
"it",
"must",
"have",
"units",
"."
] | ee89c27b0daade58812489a2da3aa3b6859eafd9 | https://github.com/ioos/compliance-checker/blob/ee89c27b0daade58812489a2da3aa3b6859eafd9/compliance_checker/ioos.py#L163-L177 | train | 31,373 |
ioos/compliance-checker | compliance_checker/ioos.py | IOOS1_1Check.check_platform_variables | def check_platform_variables(self, ds):
'''
The value of platform attribute should be set to another variable which
contains the details of the platform. There can be multiple platforms
involved depending on if all the instances of the featureType in the
collection share the same platform or not. If multiple platforms are
involved, a variable should be defined for each platform and referenced
from the geophysical variable in a space separated string.
:param netCDF4.Dataset ds: An open netCDF dataset
'''
platform_names = getattr(ds, 'platform', '').split(' ')
val = all(platform_name in ds.variables for platform_name in platform_names)
msgs = []
if not val:
msgs = [('The value of "platform" global attribute should be set to another variable '
'which contains the details of the platform. If multiple platforms are '
'involved, a variable should be defined for each platform and referenced '
'from the geophysical variable in a space separated string.')]
return [Result(BaseCheck.HIGH, val, 'platform variables', msgs)] | python | def check_platform_variables(self, ds):
'''
The value of platform attribute should be set to another variable which
contains the details of the platform. There can be multiple platforms
involved depending on if all the instances of the featureType in the
collection share the same platform or not. If multiple platforms are
involved, a variable should be defined for each platform and referenced
from the geophysical variable in a space separated string.
:param netCDF4.Dataset ds: An open netCDF dataset
'''
platform_names = getattr(ds, 'platform', '').split(' ')
val = all(platform_name in ds.variables for platform_name in platform_names)
msgs = []
if not val:
msgs = [('The value of "platform" global attribute should be set to another variable '
'which contains the details of the platform. If multiple platforms are '
'involved, a variable should be defined for each platform and referenced '
'from the geophysical variable in a space separated string.')]
return [Result(BaseCheck.HIGH, val, 'platform variables', msgs)] | [
"def",
"check_platform_variables",
"(",
"self",
",",
"ds",
")",
":",
"platform_names",
"=",
"getattr",
"(",
"ds",
",",
"'platform'",
",",
"''",
")",
".",
"split",
"(",
"' '",
")",
"val",
"=",
"all",
"(",
"platform_name",
"in",
"ds",
".",
"variables",
"... | The value of platform attribute should be set to another variable which
contains the details of the platform. There can be multiple platforms
involved depending on if all the instances of the featureType in the
collection share the same platform or not. If multiple platforms are
involved, a variable should be defined for each platform and referenced
from the geophysical variable in a space separated string.
:param netCDF4.Dataset ds: An open netCDF dataset | [
"The",
"value",
"of",
"platform",
"attribute",
"should",
"be",
"set",
"to",
"another",
"variable",
"which",
"contains",
"the",
"details",
"of",
"the",
"platform",
".",
"There",
"can",
"be",
"multiple",
"platforms",
"involved",
"depending",
"on",
"if",
"all",
... | ee89c27b0daade58812489a2da3aa3b6859eafd9 | https://github.com/ioos/compliance-checker/blob/ee89c27b0daade58812489a2da3aa3b6859eafd9/compliance_checker/ioos.py#L267-L286 | train | 31,374 |
ioos/compliance-checker | compliance_checker/ioos.py | IOOS1_1Check.check_geophysical_vars_fill_value | def check_geophysical_vars_fill_value(self, ds):
'''
Check that geophysical variables contain fill values.
:param netCDF4.Dataset ds: An open netCDF dataset
'''
results = []
for geo_var in get_geophysical_variables(ds):
results.append(
self._has_var_attr(ds, geo_var, '_FillValue', '_FillValue', BaseCheck.MEDIUM),
)
return results | python | def check_geophysical_vars_fill_value(self, ds):
'''
Check that geophysical variables contain fill values.
:param netCDF4.Dataset ds: An open netCDF dataset
'''
results = []
for geo_var in get_geophysical_variables(ds):
results.append(
self._has_var_attr(ds, geo_var, '_FillValue', '_FillValue', BaseCheck.MEDIUM),
)
return results | [
"def",
"check_geophysical_vars_fill_value",
"(",
"self",
",",
"ds",
")",
":",
"results",
"=",
"[",
"]",
"for",
"geo_var",
"in",
"get_geophysical_variables",
"(",
"ds",
")",
":",
"results",
".",
"append",
"(",
"self",
".",
"_has_var_attr",
"(",
"ds",
",",
"... | Check that geophysical variables contain fill values.
:param netCDF4.Dataset ds: An open netCDF dataset | [
"Check",
"that",
"geophysical",
"variables",
"contain",
"fill",
"values",
"."
] | ee89c27b0daade58812489a2da3aa3b6859eafd9 | https://github.com/ioos/compliance-checker/blob/ee89c27b0daade58812489a2da3aa3b6859eafd9/compliance_checker/ioos.py#L311-L322 | train | 31,375 |
ioos/compliance-checker | compliance_checker/ioos.py | IOOS1_1Check.check_geophysical_vars_standard_name | def check_geophysical_vars_standard_name(self, ds):
'''
Check that geophysical variables contain standard names.
:param netCDF4.Dataset ds: An open netCDF dataset
'''
results = []
for geo_var in get_geophysical_variables(ds):
results.append(
self._has_var_attr(ds, geo_var, 'standard_name', 'geophysical variables standard_name'),
)
return results | python | def check_geophysical_vars_standard_name(self, ds):
'''
Check that geophysical variables contain standard names.
:param netCDF4.Dataset ds: An open netCDF dataset
'''
results = []
for geo_var in get_geophysical_variables(ds):
results.append(
self._has_var_attr(ds, geo_var, 'standard_name', 'geophysical variables standard_name'),
)
return results | [
"def",
"check_geophysical_vars_standard_name",
"(",
"self",
",",
"ds",
")",
":",
"results",
"=",
"[",
"]",
"for",
"geo_var",
"in",
"get_geophysical_variables",
"(",
"ds",
")",
":",
"results",
".",
"append",
"(",
"self",
".",
"_has_var_attr",
"(",
"ds",
",",
... | Check that geophysical variables contain standard names.
:param netCDF4.Dataset ds: An open netCDF dataset | [
"Check",
"that",
"geophysical",
"variables",
"contain",
"standard",
"names",
"."
] | ee89c27b0daade58812489a2da3aa3b6859eafd9 | https://github.com/ioos/compliance-checker/blob/ee89c27b0daade58812489a2da3aa3b6859eafd9/compliance_checker/ioos.py#L324-L335 | train | 31,376 |
ioos/compliance-checker | compliance_checker/cfutil.py | is_dimensionless_standard_name | def is_dimensionless_standard_name(xml_tree, standard_name):
'''
Returns True if the units for the associated standard name are
dimensionless. Dimensionless standard names include those that have no
units and units that are defined as constant units in the CF standard name
table i.e. '1', or '1e-3'.
'''
# standard_name must be string, so if it is not, it is *wrong* by default
if not isinstance(standard_name, basestring):
return False
found_standard_name = xml_tree.find(".//entry[@id='{}']".format(standard_name))
if found_standard_name is not None:
canonical_units = found_standard_name.find('canonical_units')
# so far, standard name XML table includes
# 1 and 1e-3 for constant units, but expanding to valid udunits
# prefixes to be on the safe side
# taken from CF Table 3.1 of valid UDUnits prefixes
dimless_units = r'1(?:e-?(?:1|2|3|6|9|12|15|18|21|24))?$'
return canonical_units is None or re.match(dimless_units,
canonical_units.text)
# if the standard name is not found, assume we need units for the time being
else:
return False | python | def is_dimensionless_standard_name(xml_tree, standard_name):
'''
Returns True if the units for the associated standard name are
dimensionless. Dimensionless standard names include those that have no
units and units that are defined as constant units in the CF standard name
table i.e. '1', or '1e-3'.
'''
# standard_name must be string, so if it is not, it is *wrong* by default
if not isinstance(standard_name, basestring):
return False
found_standard_name = xml_tree.find(".//entry[@id='{}']".format(standard_name))
if found_standard_name is not None:
canonical_units = found_standard_name.find('canonical_units')
# so far, standard name XML table includes
# 1 and 1e-3 for constant units, but expanding to valid udunits
# prefixes to be on the safe side
# taken from CF Table 3.1 of valid UDUnits prefixes
dimless_units = r'1(?:e-?(?:1|2|3|6|9|12|15|18|21|24))?$'
return canonical_units is None or re.match(dimless_units,
canonical_units.text)
# if the standard name is not found, assume we need units for the time being
else:
return False | [
"def",
"is_dimensionless_standard_name",
"(",
"xml_tree",
",",
"standard_name",
")",
":",
"# standard_name must be string, so if it is not, it is *wrong* by default",
"if",
"not",
"isinstance",
"(",
"standard_name",
",",
"basestring",
")",
":",
"return",
"False",
"found_stand... | Returns True if the units for the associated standard name are
dimensionless. Dimensionless standard names include those that have no
units and units that are defined as constant units in the CF standard name
table i.e. '1', or '1e-3'. | [
"Returns",
"True",
"if",
"the",
"units",
"for",
"the",
"associated",
"standard",
"name",
"are",
"dimensionless",
".",
"Dimensionless",
"standard",
"names",
"include",
"those",
"that",
"have",
"no",
"units",
"and",
"units",
"that",
"are",
"defined",
"as",
"cons... | ee89c27b0daade58812489a2da3aa3b6859eafd9 | https://github.com/ioos/compliance-checker/blob/ee89c27b0daade58812489a2da3aa3b6859eafd9/compliance_checker/cfutil.py#L110-L132 | train | 31,377 |
ioos/compliance-checker | compliance_checker/cfutil.py | is_unitless | def is_unitless(ds, variable):
'''
Returns true if the variable is unitless
Note units of '1' are considered whole numbers or parts but still represent
physical units and not the absence of units.
:param netCDF4.Dataset ds: An open netCDF dataset
:param str variable: Name of the variable
'''
units = getattr(ds.variables[variable], 'units', None)
return units is None or units == '' | python | def is_unitless(ds, variable):
'''
Returns true if the variable is unitless
Note units of '1' are considered whole numbers or parts but still represent
physical units and not the absence of units.
:param netCDF4.Dataset ds: An open netCDF dataset
:param str variable: Name of the variable
'''
units = getattr(ds.variables[variable], 'units', None)
return units is None or units == '' | [
"def",
"is_unitless",
"(",
"ds",
",",
"variable",
")",
":",
"units",
"=",
"getattr",
"(",
"ds",
".",
"variables",
"[",
"variable",
"]",
",",
"'units'",
",",
"None",
")",
"return",
"units",
"is",
"None",
"or",
"units",
"==",
"''"
] | Returns true if the variable is unitless
Note units of '1' are considered whole numbers or parts but still represent
physical units and not the absence of units.
:param netCDF4.Dataset ds: An open netCDF dataset
:param str variable: Name of the variable | [
"Returns",
"true",
"if",
"the",
"variable",
"is",
"unitless"
] | ee89c27b0daade58812489a2da3aa3b6859eafd9 | https://github.com/ioos/compliance-checker/blob/ee89c27b0daade58812489a2da3aa3b6859eafd9/compliance_checker/cfutil.py#L152-L163 | train | 31,378 |
ioos/compliance-checker | compliance_checker/cfutil.py | get_cell_boundary_map | def get_cell_boundary_map(ds):
'''
Returns a dictionary mapping a variable to its boundary variable. The
returned dictionary maps a string variable name to the name of the boundary
variable.
:param netCDF4.Dataset nc: netCDF dataset
'''
boundary_map = {}
for variable in ds.get_variables_by_attributes(bounds=lambda x: x is not None):
if variable.bounds in ds.variables:
boundary_map[variable.name] = variable.bounds
return boundary_map | python | def get_cell_boundary_map(ds):
'''
Returns a dictionary mapping a variable to its boundary variable. The
returned dictionary maps a string variable name to the name of the boundary
variable.
:param netCDF4.Dataset nc: netCDF dataset
'''
boundary_map = {}
for variable in ds.get_variables_by_attributes(bounds=lambda x: x is not None):
if variable.bounds in ds.variables:
boundary_map[variable.name] = variable.bounds
return boundary_map | [
"def",
"get_cell_boundary_map",
"(",
"ds",
")",
":",
"boundary_map",
"=",
"{",
"}",
"for",
"variable",
"in",
"ds",
".",
"get_variables_by_attributes",
"(",
"bounds",
"=",
"lambda",
"x",
":",
"x",
"is",
"not",
"None",
")",
":",
"if",
"variable",
".",
"bou... | Returns a dictionary mapping a variable to its boundary variable. The
returned dictionary maps a string variable name to the name of the boundary
variable.
:param netCDF4.Dataset nc: netCDF dataset | [
"Returns",
"a",
"dictionary",
"mapping",
"a",
"variable",
"to",
"its",
"boundary",
"variable",
".",
"The",
"returned",
"dictionary",
"maps",
"a",
"string",
"variable",
"name",
"to",
"the",
"name",
"of",
"the",
"boundary",
"variable",
"."
] | ee89c27b0daade58812489a2da3aa3b6859eafd9 | https://github.com/ioos/compliance-checker/blob/ee89c27b0daade58812489a2da3aa3b6859eafd9/compliance_checker/cfutil.py#L309-L321 | train | 31,379 |
ioos/compliance-checker | compliance_checker/cfutil.py | get_cell_boundary_variables | def get_cell_boundary_variables(ds):
'''
Returns a list of variable names for variables that represent cell
boundaries through the `bounds` attribute
:param netCDF4.Dataset nc: netCDF dataset
'''
boundary_variables = []
has_bounds = ds.get_variables_by_attributes(bounds=lambda x: x is not None)
for var in has_bounds:
if var.bounds in ds.variables:
boundary_variables.append(var.bounds)
return boundary_variables | python | def get_cell_boundary_variables(ds):
'''
Returns a list of variable names for variables that represent cell
boundaries through the `bounds` attribute
:param netCDF4.Dataset nc: netCDF dataset
'''
boundary_variables = []
has_bounds = ds.get_variables_by_attributes(bounds=lambda x: x is not None)
for var in has_bounds:
if var.bounds in ds.variables:
boundary_variables.append(var.bounds)
return boundary_variables | [
"def",
"get_cell_boundary_variables",
"(",
"ds",
")",
":",
"boundary_variables",
"=",
"[",
"]",
"has_bounds",
"=",
"ds",
".",
"get_variables_by_attributes",
"(",
"bounds",
"=",
"lambda",
"x",
":",
"x",
"is",
"not",
"None",
")",
"for",
"var",
"in",
"has_bound... | Returns a list of variable names for variables that represent cell
boundaries through the `bounds` attribute
:param netCDF4.Dataset nc: netCDF dataset | [
"Returns",
"a",
"list",
"of",
"variable",
"names",
"for",
"variables",
"that",
"represent",
"cell",
"boundaries",
"through",
"the",
"bounds",
"attribute"
] | ee89c27b0daade58812489a2da3aa3b6859eafd9 | https://github.com/ioos/compliance-checker/blob/ee89c27b0daade58812489a2da3aa3b6859eafd9/compliance_checker/cfutil.py#L324-L336 | train | 31,380 |
ioos/compliance-checker | compliance_checker/cfutil.py | get_geophysical_variables | def get_geophysical_variables(ds):
'''
Returns a list of variable names for the variables detected as geophysical
variables.
:param netCDF4.Dataset nc: An open netCDF dataset
'''
parameters = []
for variable in ds.variables:
if is_geophysical(ds, variable):
parameters.append(variable)
return parameters | python | def get_geophysical_variables(ds):
'''
Returns a list of variable names for the variables detected as geophysical
variables.
:param netCDF4.Dataset nc: An open netCDF dataset
'''
parameters = []
for variable in ds.variables:
if is_geophysical(ds, variable):
parameters.append(variable)
return parameters | [
"def",
"get_geophysical_variables",
"(",
"ds",
")",
":",
"parameters",
"=",
"[",
"]",
"for",
"variable",
"in",
"ds",
".",
"variables",
":",
"if",
"is_geophysical",
"(",
"ds",
",",
"variable",
")",
":",
"parameters",
".",
"append",
"(",
"variable",
")",
"... | Returns a list of variable names for the variables detected as geophysical
variables.
:param netCDF4.Dataset nc: An open netCDF dataset | [
"Returns",
"a",
"list",
"of",
"variable",
"names",
"for",
"the",
"variables",
"detected",
"as",
"geophysical",
"variables",
"."
] | ee89c27b0daade58812489a2da3aa3b6859eafd9 | https://github.com/ioos/compliance-checker/blob/ee89c27b0daade58812489a2da3aa3b6859eafd9/compliance_checker/cfutil.py#L339-L351 | train | 31,381 |
ioos/compliance-checker | compliance_checker/cfutil.py | get_z_variables | def get_z_variables(nc):
'''
Returns a list of all variables matching definitions for Z
:param netcdf4.dataset nc: an open netcdf dataset object
'''
z_variables = []
# Vertical coordinates will be identifiable by units of pressure or the
# presence of the positive attribute with a value of up/down
# optionally, the vertical type may be indicated by providing the
# standard_name attribute or axis='Z'
total_coords = get_coordinate_variables(nc) + get_auxiliary_coordinate_variables(nc)
for coord_name in total_coords:
if coord_name in z_variables:
continue
coord_var = nc.variables[coord_name]
units = getattr(coord_var, 'units', None)
positive = getattr(coord_var, 'positive', None)
standard_name = getattr(coord_var, 'standard_name', None)
axis = getattr(coord_var, 'axis', None)
# If there are no units, we can't identify it as a vertical coordinate
# by checking pressure or positive
if units is not None:
if units_convertible(units, 'bar'):
z_variables.append(coord_name)
elif isinstance(positive, basestring):
if positive.lower() in ['up', 'down']:
z_variables.append(coord_name)
# if axis='Z' we're good
if coord_name not in z_variables and axis == 'Z':
z_variables.append(coord_name)
if coord_name not in z_variables and standard_name in ('depth', 'height', 'altitude'):
z_variables.append(coord_name)
if coord_name not in z_variables and standard_name in DIMENSIONLESS_VERTICAL_COORDINATES:
z_variables.append(coord_name)
return z_variables | python | def get_z_variables(nc):
'''
Returns a list of all variables matching definitions for Z
:param netcdf4.dataset nc: an open netcdf dataset object
'''
z_variables = []
# Vertical coordinates will be identifiable by units of pressure or the
# presence of the positive attribute with a value of up/down
# optionally, the vertical type may be indicated by providing the
# standard_name attribute or axis='Z'
total_coords = get_coordinate_variables(nc) + get_auxiliary_coordinate_variables(nc)
for coord_name in total_coords:
if coord_name in z_variables:
continue
coord_var = nc.variables[coord_name]
units = getattr(coord_var, 'units', None)
positive = getattr(coord_var, 'positive', None)
standard_name = getattr(coord_var, 'standard_name', None)
axis = getattr(coord_var, 'axis', None)
# If there are no units, we can't identify it as a vertical coordinate
# by checking pressure or positive
if units is not None:
if units_convertible(units, 'bar'):
z_variables.append(coord_name)
elif isinstance(positive, basestring):
if positive.lower() in ['up', 'down']:
z_variables.append(coord_name)
# if axis='Z' we're good
if coord_name not in z_variables and axis == 'Z':
z_variables.append(coord_name)
if coord_name not in z_variables and standard_name in ('depth', 'height', 'altitude'):
z_variables.append(coord_name)
if coord_name not in z_variables and standard_name in DIMENSIONLESS_VERTICAL_COORDINATES:
z_variables.append(coord_name)
return z_variables | [
"def",
"get_z_variables",
"(",
"nc",
")",
":",
"z_variables",
"=",
"[",
"]",
"# Vertical coordinates will be identifiable by units of pressure or the",
"# presence of the positive attribute with a value of up/down",
"# optionally, the vertical type may be indicated by providing the",
"# st... | Returns a list of all variables matching definitions for Z
:param netcdf4.dataset nc: an open netcdf dataset object | [
"Returns",
"a",
"list",
"of",
"all",
"variables",
"matching",
"definitions",
"for",
"Z"
] | ee89c27b0daade58812489a2da3aa3b6859eafd9 | https://github.com/ioos/compliance-checker/blob/ee89c27b0daade58812489a2da3aa3b6859eafd9/compliance_checker/cfutil.py#L383-L421 | train | 31,382 |
ioos/compliance-checker | compliance_checker/cfutil.py | get_latitude_variables | def get_latitude_variables(nc):
'''
Returns a list of all variables matching definitions for latitude
:param netcdf4.dataset nc: an open netcdf dataset object
'''
latitude_variables = []
# standard_name takes precedence
for variable in nc.get_variables_by_attributes(standard_name="latitude"):
latitude_variables.append(variable.name)
# Then axis
for variable in nc.get_variables_by_attributes(axis='Y'):
if variable.name not in latitude_variables:
latitude_variables.append(variable.name)
check_fn = partial(attr_membership, value_set=VALID_LAT_UNITS,
modifier_fn=lambda s: s.lower())
for variable in nc.get_variables_by_attributes(units=check_fn):
if variable.name not in latitude_variables:
latitude_variables.append(variable.name)
return latitude_variables | python | def get_latitude_variables(nc):
'''
Returns a list of all variables matching definitions for latitude
:param netcdf4.dataset nc: an open netcdf dataset object
'''
latitude_variables = []
# standard_name takes precedence
for variable in nc.get_variables_by_attributes(standard_name="latitude"):
latitude_variables.append(variable.name)
# Then axis
for variable in nc.get_variables_by_attributes(axis='Y'):
if variable.name not in latitude_variables:
latitude_variables.append(variable.name)
check_fn = partial(attr_membership, value_set=VALID_LAT_UNITS,
modifier_fn=lambda s: s.lower())
for variable in nc.get_variables_by_attributes(units=check_fn):
if variable.name not in latitude_variables:
latitude_variables.append(variable.name)
return latitude_variables | [
"def",
"get_latitude_variables",
"(",
"nc",
")",
":",
"latitude_variables",
"=",
"[",
"]",
"# standard_name takes precedence",
"for",
"variable",
"in",
"nc",
".",
"get_variables_by_attributes",
"(",
"standard_name",
"=",
"\"latitude\"",
")",
":",
"latitude_variables",
... | Returns a list of all variables matching definitions for latitude
:param netcdf4.dataset nc: an open netcdf dataset object | [
"Returns",
"a",
"list",
"of",
"all",
"variables",
"matching",
"definitions",
"for",
"latitude"
] | ee89c27b0daade58812489a2da3aa3b6859eafd9 | https://github.com/ioos/compliance-checker/blob/ee89c27b0daade58812489a2da3aa3b6859eafd9/compliance_checker/cfutil.py#L437-L459 | train | 31,383 |
ioos/compliance-checker | compliance_checker/cfutil.py | get_true_latitude_variables | def get_true_latitude_variables(nc):
'''
Returns a list of variables defining true latitude.
CF Chapter 4 refers to latitude as a coordinate variable that can also be
used in non-standard coordinate systems like rotated pole and other
projections. Chapter 5 refers to a concept of true latitude where the
variabe defines latitude in a standard projection.
True latitude, for lack of a better definition, is simply latitude where
the standard_name is latitude or the units are degrees_north.
:param netCDF4.Dataset nc: An open netCDF dataset
'''
lats = get_latitude_variables(nc)
true_lats = []
for lat in lats:
standard_name = getattr(nc.variables[lat], "standard_name", None)
units = getattr(nc.variables[lat], "units", None)
if standard_name == 'latitude':
true_lats.append(lat)
elif isinstance(units, basestring) and units.lower() in VALID_LAT_UNITS:
true_lats.append(lat)
return true_lats | python | def get_true_latitude_variables(nc):
'''
Returns a list of variables defining true latitude.
CF Chapter 4 refers to latitude as a coordinate variable that can also be
used in non-standard coordinate systems like rotated pole and other
projections. Chapter 5 refers to a concept of true latitude where the
variabe defines latitude in a standard projection.
True latitude, for lack of a better definition, is simply latitude where
the standard_name is latitude or the units are degrees_north.
:param netCDF4.Dataset nc: An open netCDF dataset
'''
lats = get_latitude_variables(nc)
true_lats = []
for lat in lats:
standard_name = getattr(nc.variables[lat], "standard_name", None)
units = getattr(nc.variables[lat], "units", None)
if standard_name == 'latitude':
true_lats.append(lat)
elif isinstance(units, basestring) and units.lower() in VALID_LAT_UNITS:
true_lats.append(lat)
return true_lats | [
"def",
"get_true_latitude_variables",
"(",
"nc",
")",
":",
"lats",
"=",
"get_latitude_variables",
"(",
"nc",
")",
"true_lats",
"=",
"[",
"]",
"for",
"lat",
"in",
"lats",
":",
"standard_name",
"=",
"getattr",
"(",
"nc",
".",
"variables",
"[",
"lat",
"]",
... | Returns a list of variables defining true latitude.
CF Chapter 4 refers to latitude as a coordinate variable that can also be
used in non-standard coordinate systems like rotated pole and other
projections. Chapter 5 refers to a concept of true latitude where the
variabe defines latitude in a standard projection.
True latitude, for lack of a better definition, is simply latitude where
the standard_name is latitude or the units are degrees_north.
:param netCDF4.Dataset nc: An open netCDF dataset | [
"Returns",
"a",
"list",
"of",
"variables",
"defining",
"true",
"latitude",
"."
] | ee89c27b0daade58812489a2da3aa3b6859eafd9 | https://github.com/ioos/compliance-checker/blob/ee89c27b0daade58812489a2da3aa3b6859eafd9/compliance_checker/cfutil.py#L462-L485 | train | 31,384 |
ioos/compliance-checker | compliance_checker/cfutil.py | get_longitude_variables | def get_longitude_variables(nc):
'''
Returns a list of all variables matching definitions for longitude
:param netcdf4.dataset nc: an open netcdf dataset object
'''
longitude_variables = []
# standard_name takes precedence
for variable in nc.get_variables_by_attributes(standard_name="longitude"):
longitude_variables.append(variable.name)
# Then axis
for variable in nc.get_variables_by_attributes(axis='X'):
if variable.name not in longitude_variables:
longitude_variables.append(variable.name)
check_fn = partial(attr_membership, value_set=VALID_LON_UNITS,
modifier_fn=lambda s: s.lower())
for variable in nc.get_variables_by_attributes(units=check_fn):
if variable.name not in longitude_variables:
longitude_variables.append(variable.name)
return longitude_variables | python | def get_longitude_variables(nc):
'''
Returns a list of all variables matching definitions for longitude
:param netcdf4.dataset nc: an open netcdf dataset object
'''
longitude_variables = []
# standard_name takes precedence
for variable in nc.get_variables_by_attributes(standard_name="longitude"):
longitude_variables.append(variable.name)
# Then axis
for variable in nc.get_variables_by_attributes(axis='X'):
if variable.name not in longitude_variables:
longitude_variables.append(variable.name)
check_fn = partial(attr_membership, value_set=VALID_LON_UNITS,
modifier_fn=lambda s: s.lower())
for variable in nc.get_variables_by_attributes(units=check_fn):
if variable.name not in longitude_variables:
longitude_variables.append(variable.name)
return longitude_variables | [
"def",
"get_longitude_variables",
"(",
"nc",
")",
":",
"longitude_variables",
"=",
"[",
"]",
"# standard_name takes precedence",
"for",
"variable",
"in",
"nc",
".",
"get_variables_by_attributes",
"(",
"standard_name",
"=",
"\"longitude\"",
")",
":",
"longitude_variables... | Returns a list of all variables matching definitions for longitude
:param netcdf4.dataset nc: an open netcdf dataset object | [
"Returns",
"a",
"list",
"of",
"all",
"variables",
"matching",
"definitions",
"for",
"longitude"
] | ee89c27b0daade58812489a2da3aa3b6859eafd9 | https://github.com/ioos/compliance-checker/blob/ee89c27b0daade58812489a2da3aa3b6859eafd9/compliance_checker/cfutil.py#L501-L523 | train | 31,385 |
ioos/compliance-checker | compliance_checker/cfutil.py | get_true_longitude_variables | def get_true_longitude_variables(nc):
'''
Returns a list of variables defining true longitude.
CF Chapter 4 refers to longitude as a coordinate variable that can also be
used in non-standard coordinate systems like rotated pole and other
projections. Chapter 5 refers to a concept of true longitude where the
variabe defines longitude in a standard projection.
True longitude, for lack of a better definition, is simply longitude where
the standard_name is longitude or the units are degrees_north.
:param netCDF4.Dataset nc: An open netCDF dataset
'''
lons = get_longitude_variables(nc)
true_lons = []
for lon in lons:
standard_name = getattr(nc.variables[lon], "standard_name", None)
units = getattr(nc.variables[lon], "units", None)
if standard_name == 'longitude':
true_lons.append(lon)
elif isinstance(units, basestring) and units.lower() in VALID_LON_UNITS:
true_lons.append(lon)
return true_lons | python | def get_true_longitude_variables(nc):
'''
Returns a list of variables defining true longitude.
CF Chapter 4 refers to longitude as a coordinate variable that can also be
used in non-standard coordinate systems like rotated pole and other
projections. Chapter 5 refers to a concept of true longitude where the
variabe defines longitude in a standard projection.
True longitude, for lack of a better definition, is simply longitude where
the standard_name is longitude or the units are degrees_north.
:param netCDF4.Dataset nc: An open netCDF dataset
'''
lons = get_longitude_variables(nc)
true_lons = []
for lon in lons:
standard_name = getattr(nc.variables[lon], "standard_name", None)
units = getattr(nc.variables[lon], "units", None)
if standard_name == 'longitude':
true_lons.append(lon)
elif isinstance(units, basestring) and units.lower() in VALID_LON_UNITS:
true_lons.append(lon)
return true_lons | [
"def",
"get_true_longitude_variables",
"(",
"nc",
")",
":",
"lons",
"=",
"get_longitude_variables",
"(",
"nc",
")",
"true_lons",
"=",
"[",
"]",
"for",
"lon",
"in",
"lons",
":",
"standard_name",
"=",
"getattr",
"(",
"nc",
".",
"variables",
"[",
"lon",
"]",
... | Returns a list of variables defining true longitude.
CF Chapter 4 refers to longitude as a coordinate variable that can also be
used in non-standard coordinate systems like rotated pole and other
projections. Chapter 5 refers to a concept of true longitude where the
variabe defines longitude in a standard projection.
True longitude, for lack of a better definition, is simply longitude where
the standard_name is longitude or the units are degrees_north.
:param netCDF4.Dataset nc: An open netCDF dataset | [
"Returns",
"a",
"list",
"of",
"variables",
"defining",
"true",
"longitude",
"."
] | ee89c27b0daade58812489a2da3aa3b6859eafd9 | https://github.com/ioos/compliance-checker/blob/ee89c27b0daade58812489a2da3aa3b6859eafd9/compliance_checker/cfutil.py#L526-L549 | train | 31,386 |
ioos/compliance-checker | compliance_checker/cfutil.py | get_platform_variables | def get_platform_variables(ds):
'''
Returns a list of platform variable NAMES
:param netCDF4.Dataset ds: An open netCDF4 Dataset
'''
candidates = []
for variable in ds.variables:
platform = getattr(ds.variables[variable], 'platform', '')
if platform and platform in ds.variables:
if platform not in candidates:
candidates.append(platform)
platform = getattr(ds, 'platform', '')
if platform and platform in ds.variables:
if platform not in candidates:
candidates.append(platform)
return candidates | python | def get_platform_variables(ds):
'''
Returns a list of platform variable NAMES
:param netCDF4.Dataset ds: An open netCDF4 Dataset
'''
candidates = []
for variable in ds.variables:
platform = getattr(ds.variables[variable], 'platform', '')
if platform and platform in ds.variables:
if platform not in candidates:
candidates.append(platform)
platform = getattr(ds, 'platform', '')
if platform and platform in ds.variables:
if platform not in candidates:
candidates.append(platform)
return candidates | [
"def",
"get_platform_variables",
"(",
"ds",
")",
":",
"candidates",
"=",
"[",
"]",
"for",
"variable",
"in",
"ds",
".",
"variables",
":",
"platform",
"=",
"getattr",
"(",
"ds",
".",
"variables",
"[",
"variable",
"]",
",",
"'platform'",
",",
"''",
")",
"... | Returns a list of platform variable NAMES
:param netCDF4.Dataset ds: An open netCDF4 Dataset | [
"Returns",
"a",
"list",
"of",
"platform",
"variable",
"NAMES"
] | ee89c27b0daade58812489a2da3aa3b6859eafd9 | https://github.com/ioos/compliance-checker/blob/ee89c27b0daade58812489a2da3aa3b6859eafd9/compliance_checker/cfutil.py#L552-L569 | train | 31,387 |
ioos/compliance-checker | compliance_checker/cfutil.py | get_instrument_variables | def get_instrument_variables(ds):
'''
Returns a list of instrument variables
:param netCDF4.Dataset ds: An open netCDF4 Dataset
'''
candidates = []
for variable in ds.variables:
instrument = getattr(ds.variables[variable], 'instrument', '')
if instrument and instrument in ds.variables:
if instrument not in candidates:
candidates.append(instrument)
instrument = getattr(ds, 'instrument', '')
if instrument and instrument in ds.variables:
if instrument not in candidates:
candidates.append(instrument)
return candidates | python | def get_instrument_variables(ds):
'''
Returns a list of instrument variables
:param netCDF4.Dataset ds: An open netCDF4 Dataset
'''
candidates = []
for variable in ds.variables:
instrument = getattr(ds.variables[variable], 'instrument', '')
if instrument and instrument in ds.variables:
if instrument not in candidates:
candidates.append(instrument)
instrument = getattr(ds, 'instrument', '')
if instrument and instrument in ds.variables:
if instrument not in candidates:
candidates.append(instrument)
return candidates | [
"def",
"get_instrument_variables",
"(",
"ds",
")",
":",
"candidates",
"=",
"[",
"]",
"for",
"variable",
"in",
"ds",
".",
"variables",
":",
"instrument",
"=",
"getattr",
"(",
"ds",
".",
"variables",
"[",
"variable",
"]",
",",
"'instrument'",
",",
"''",
")... | Returns a list of instrument variables
:param netCDF4.Dataset ds: An open netCDF4 Dataset | [
"Returns",
"a",
"list",
"of",
"instrument",
"variables"
] | ee89c27b0daade58812489a2da3aa3b6859eafd9 | https://github.com/ioos/compliance-checker/blob/ee89c27b0daade58812489a2da3aa3b6859eafd9/compliance_checker/cfutil.py#L572-L589 | train | 31,388 |
ioos/compliance-checker | compliance_checker/cfutil.py | get_time_variables | def get_time_variables(ds):
'''
Returns a list of variables describing the time coordinate
:param netCDF4.Dataset ds: An open netCDF4 Dataset
'''
time_variables = set()
for variable in ds.get_variables_by_attributes(standard_name='time'):
time_variables.add(variable.name)
for variable in ds.get_variables_by_attributes(axis='T'):
if variable.name not in time_variables:
time_variables.add(variable.name)
regx = r'^(?:day|d|hour|hr|h|minute|min|second|s)s? since .*$'
for variable in ds.get_variables_by_attributes(units=lambda x: isinstance(x, basestring)):
if re.match(regx, variable.units) and variable.name not in time_variables:
time_variables.add(variable.name)
return time_variables | python | def get_time_variables(ds):
'''
Returns a list of variables describing the time coordinate
:param netCDF4.Dataset ds: An open netCDF4 Dataset
'''
time_variables = set()
for variable in ds.get_variables_by_attributes(standard_name='time'):
time_variables.add(variable.name)
for variable in ds.get_variables_by_attributes(axis='T'):
if variable.name not in time_variables:
time_variables.add(variable.name)
regx = r'^(?:day|d|hour|hr|h|minute|min|second|s)s? since .*$'
for variable in ds.get_variables_by_attributes(units=lambda x: isinstance(x, basestring)):
if re.match(regx, variable.units) and variable.name not in time_variables:
time_variables.add(variable.name)
return time_variables | [
"def",
"get_time_variables",
"(",
"ds",
")",
":",
"time_variables",
"=",
"set",
"(",
")",
"for",
"variable",
"in",
"ds",
".",
"get_variables_by_attributes",
"(",
"standard_name",
"=",
"'time'",
")",
":",
"time_variables",
".",
"add",
"(",
"variable",
".",
"n... | Returns a list of variables describing the time coordinate
:param netCDF4.Dataset ds: An open netCDF4 Dataset | [
"Returns",
"a",
"list",
"of",
"variables",
"describing",
"the",
"time",
"coordinate"
] | ee89c27b0daade58812489a2da3aa3b6859eafd9 | https://github.com/ioos/compliance-checker/blob/ee89c27b0daade58812489a2da3aa3b6859eafd9/compliance_checker/cfutil.py#L623-L642 | train | 31,389 |
ioos/compliance-checker | compliance_checker/cfutil.py | get_axis_variables | def get_axis_variables(ds):
'''
Returns a list of variables that define an axis of the dataset
:param netCDF4.Dataset ds: An open netCDF4 Dataset
'''
axis_variables = []
for ncvar in ds.get_variables_by_attributes(axis=lambda x: x is not None):
axis_variables.append(ncvar.name)
return axis_variables | python | def get_axis_variables(ds):
'''
Returns a list of variables that define an axis of the dataset
:param netCDF4.Dataset ds: An open netCDF4 Dataset
'''
axis_variables = []
for ncvar in ds.get_variables_by_attributes(axis=lambda x: x is not None):
axis_variables.append(ncvar.name)
return axis_variables | [
"def",
"get_axis_variables",
"(",
"ds",
")",
":",
"axis_variables",
"=",
"[",
"]",
"for",
"ncvar",
"in",
"ds",
".",
"get_variables_by_attributes",
"(",
"axis",
"=",
"lambda",
"x",
":",
"x",
"is",
"not",
"None",
")",
":",
"axis_variables",
".",
"append",
... | Returns a list of variables that define an axis of the dataset
:param netCDF4.Dataset ds: An open netCDF4 Dataset | [
"Returns",
"a",
"list",
"of",
"variables",
"that",
"define",
"an",
"axis",
"of",
"the",
"dataset"
] | ee89c27b0daade58812489a2da3aa3b6859eafd9 | https://github.com/ioos/compliance-checker/blob/ee89c27b0daade58812489a2da3aa3b6859eafd9/compliance_checker/cfutil.py#L645-L654 | train | 31,390 |
ioos/compliance-checker | compliance_checker/cfutil.py | get_climatology_variable | def get_climatology_variable(ds):
'''
Returns the variable describing climatology bounds if it exists.
Climatology variables are similar to cell boundary variables that describe
the climatology bounds.
See Example 7.8 in CF 1.6
:param netCDF4.Dataset ds: An open netCDF4 Dataset
:rtype: str or None
'''
time = get_time_variable(ds)
# If there's no time dimension there's no climatology bounds
if not time:
return None
# Climatology variable is simply whatever time points to under the
# `climatology` attribute.
if hasattr(ds.variables[time], 'climatology'):
if ds.variables[time].climatology in ds.variables:
return ds.variables[time].climatology
return None | python | def get_climatology_variable(ds):
'''
Returns the variable describing climatology bounds if it exists.
Climatology variables are similar to cell boundary variables that describe
the climatology bounds.
See Example 7.8 in CF 1.6
:param netCDF4.Dataset ds: An open netCDF4 Dataset
:rtype: str or None
'''
time = get_time_variable(ds)
# If there's no time dimension there's no climatology bounds
if not time:
return None
# Climatology variable is simply whatever time points to under the
# `climatology` attribute.
if hasattr(ds.variables[time], 'climatology'):
if ds.variables[time].climatology in ds.variables:
return ds.variables[time].climatology
return None | [
"def",
"get_climatology_variable",
"(",
"ds",
")",
":",
"time",
"=",
"get_time_variable",
"(",
"ds",
")",
"# If there's no time dimension there's no climatology bounds",
"if",
"not",
"time",
":",
"return",
"None",
"# Climatology variable is simply whatever time points to under ... | Returns the variable describing climatology bounds if it exists.
Climatology variables are similar to cell boundary variables that describe
the climatology bounds.
See Example 7.8 in CF 1.6
:param netCDF4.Dataset ds: An open netCDF4 Dataset
:rtype: str or None | [
"Returns",
"the",
"variable",
"describing",
"climatology",
"bounds",
"if",
"it",
"exists",
"."
] | ee89c27b0daade58812489a2da3aa3b6859eafd9 | https://github.com/ioos/compliance-checker/blob/ee89c27b0daade58812489a2da3aa3b6859eafd9/compliance_checker/cfutil.py#L657-L678 | train | 31,391 |
ioos/compliance-checker | compliance_checker/cfutil.py | get_flag_variables | def get_flag_variables(ds):
'''
Returns a list of variables that are defined as flag variables
:param netCDF4.Dataset ds: An open netCDF4 Dataset
'''
flag_variables = []
for name, ncvar in ds.variables.items():
standard_name = getattr(ncvar, 'standard_name', None)
if isinstance(standard_name, basestring) and 'status_flag' in standard_name:
flag_variables.append(name)
elif hasattr(ncvar, 'flag_meanings'):
flag_variables.append(name)
return flag_variables | python | def get_flag_variables(ds):
'''
Returns a list of variables that are defined as flag variables
:param netCDF4.Dataset ds: An open netCDF4 Dataset
'''
flag_variables = []
for name, ncvar in ds.variables.items():
standard_name = getattr(ncvar, 'standard_name', None)
if isinstance(standard_name, basestring) and 'status_flag' in standard_name:
flag_variables.append(name)
elif hasattr(ncvar, 'flag_meanings'):
flag_variables.append(name)
return flag_variables | [
"def",
"get_flag_variables",
"(",
"ds",
")",
":",
"flag_variables",
"=",
"[",
"]",
"for",
"name",
",",
"ncvar",
"in",
"ds",
".",
"variables",
".",
"items",
"(",
")",
":",
"standard_name",
"=",
"getattr",
"(",
"ncvar",
",",
"'standard_name'",
",",
"None",... | Returns a list of variables that are defined as flag variables
:param netCDF4.Dataset ds: An open netCDF4 Dataset | [
"Returns",
"a",
"list",
"of",
"variables",
"that",
"are",
"defined",
"as",
"flag",
"variables"
] | ee89c27b0daade58812489a2da3aa3b6859eafd9 | https://github.com/ioos/compliance-checker/blob/ee89c27b0daade58812489a2da3aa3b6859eafd9/compliance_checker/cfutil.py#L681-L694 | train | 31,392 |
ioos/compliance-checker | compliance_checker/cfutil.py | get_grid_mapping_variables | def get_grid_mapping_variables(ds):
'''
Returns a list of grid mapping variables
:param netCDF4.Dataset ds: An open netCDF4 Dataset
'''
grid_mapping_variables = []
for ncvar in ds.get_variables_by_attributes(grid_mapping=lambda x: x is not None):
if ncvar.grid_mapping in ds.variables:
grid_mapping_variables.append(ncvar.grid_mapping)
return grid_mapping_variables | python | def get_grid_mapping_variables(ds):
'''
Returns a list of grid mapping variables
:param netCDF4.Dataset ds: An open netCDF4 Dataset
'''
grid_mapping_variables = []
for ncvar in ds.get_variables_by_attributes(grid_mapping=lambda x: x is not None):
if ncvar.grid_mapping in ds.variables:
grid_mapping_variables.append(ncvar.grid_mapping)
return grid_mapping_variables | [
"def",
"get_grid_mapping_variables",
"(",
"ds",
")",
":",
"grid_mapping_variables",
"=",
"[",
"]",
"for",
"ncvar",
"in",
"ds",
".",
"get_variables_by_attributes",
"(",
"grid_mapping",
"=",
"lambda",
"x",
":",
"x",
"is",
"not",
"None",
")",
":",
"if",
"ncvar"... | Returns a list of grid mapping variables
:param netCDF4.Dataset ds: An open netCDF4 Dataset | [
"Returns",
"a",
"list",
"of",
"grid",
"mapping",
"variables"
] | ee89c27b0daade58812489a2da3aa3b6859eafd9 | https://github.com/ioos/compliance-checker/blob/ee89c27b0daade58812489a2da3aa3b6859eafd9/compliance_checker/cfutil.py#L697-L707 | train | 31,393 |
ioos/compliance-checker | compliance_checker/cfutil.py | get_axis_map | def get_axis_map(ds, variable):
'''
Returns an axis_map dictionary that contains an axis key and the coordinate
names as values.
For example::
{'X': ['longitude'], 'Y': ['latitude'], 'T': ['time']}
The axis C is for compressed coordinates like a reduced grid, and U is for
unknown axis. This can sometimes be physical quantities representing a
continuous discrete axis, like temperature or density.
:param netCDF4.Dataset nc: An open netCDF dataset
:param str variable: Variable name
'''
all_coords = get_coordinate_variables(ds) + get_auxiliary_coordinate_variables(ds)
latitudes = get_latitude_variables(ds)
longitudes = get_longitude_variables(ds)
times = get_time_variables(ds)
heights = get_z_variables(ds)
coordinates = getattr(ds.variables[variable], "coordinates", None)
if not isinstance(coordinates, basestring):
coordinates = ''
# For example
# {'x': ['longitude'], 'y': ['latitude'], 't': ['time']}
axis_map = defaultdict(list)
for coord_name in all_coords:
if is_compression_coordinate(ds, coord_name):
axis = 'C'
elif coord_name in times:
axis = 'T'
elif coord_name in longitudes:
axis = 'X'
elif coord_name in latitudes:
axis = 'Y'
elif coord_name in heights:
axis = 'Z'
else:
axis = 'U'
if coord_name in ds.variables[variable].dimensions:
if coord_name not in axis_map[axis]:
axis_map[axis].append(coord_name)
elif coord_name in coordinates:
if coord_name not in axis_map[axis]:
axis_map[axis].append(coord_name)
return axis_map | python | def get_axis_map(ds, variable):
'''
Returns an axis_map dictionary that contains an axis key and the coordinate
names as values.
For example::
{'X': ['longitude'], 'Y': ['latitude'], 'T': ['time']}
The axis C is for compressed coordinates like a reduced grid, and U is for
unknown axis. This can sometimes be physical quantities representing a
continuous discrete axis, like temperature or density.
:param netCDF4.Dataset nc: An open netCDF dataset
:param str variable: Variable name
'''
all_coords = get_coordinate_variables(ds) + get_auxiliary_coordinate_variables(ds)
latitudes = get_latitude_variables(ds)
longitudes = get_longitude_variables(ds)
times = get_time_variables(ds)
heights = get_z_variables(ds)
coordinates = getattr(ds.variables[variable], "coordinates", None)
if not isinstance(coordinates, basestring):
coordinates = ''
# For example
# {'x': ['longitude'], 'y': ['latitude'], 't': ['time']}
axis_map = defaultdict(list)
for coord_name in all_coords:
if is_compression_coordinate(ds, coord_name):
axis = 'C'
elif coord_name in times:
axis = 'T'
elif coord_name in longitudes:
axis = 'X'
elif coord_name in latitudes:
axis = 'Y'
elif coord_name in heights:
axis = 'Z'
else:
axis = 'U'
if coord_name in ds.variables[variable].dimensions:
if coord_name not in axis_map[axis]:
axis_map[axis].append(coord_name)
elif coord_name in coordinates:
if coord_name not in axis_map[axis]:
axis_map[axis].append(coord_name)
return axis_map | [
"def",
"get_axis_map",
"(",
"ds",
",",
"variable",
")",
":",
"all_coords",
"=",
"get_coordinate_variables",
"(",
"ds",
")",
"+",
"get_auxiliary_coordinate_variables",
"(",
"ds",
")",
"latitudes",
"=",
"get_latitude_variables",
"(",
"ds",
")",
"longitudes",
"=",
... | Returns an axis_map dictionary that contains an axis key and the coordinate
names as values.
For example::
{'X': ['longitude'], 'Y': ['latitude'], 'T': ['time']}
The axis C is for compressed coordinates like a reduced grid, and U is for
unknown axis. This can sometimes be physical quantities representing a
continuous discrete axis, like temperature or density.
:param netCDF4.Dataset nc: An open netCDF dataset
:param str variable: Variable name | [
"Returns",
"an",
"axis_map",
"dictionary",
"that",
"contains",
"an",
"axis",
"key",
"and",
"the",
"coordinate",
"names",
"as",
"values",
"."
] | ee89c27b0daade58812489a2da3aa3b6859eafd9 | https://github.com/ioos/compliance-checker/blob/ee89c27b0daade58812489a2da3aa3b6859eafd9/compliance_checker/cfutil.py#L711-L762 | train | 31,394 |
ioos/compliance-checker | compliance_checker/cfutil.py | is_coordinate_variable | def is_coordinate_variable(ds, variable):
'''
Returns True if the variable is a coordinate variable
:param netCDF4.Dataset nc: An open netCDF dataset
:param str variable: Variable name
'''
if variable not in ds.variables:
return False
return ds.variables[variable].dimensions == (variable,) | python | def is_coordinate_variable(ds, variable):
'''
Returns True if the variable is a coordinate variable
:param netCDF4.Dataset nc: An open netCDF dataset
:param str variable: Variable name
'''
if variable not in ds.variables:
return False
return ds.variables[variable].dimensions == (variable,) | [
"def",
"is_coordinate_variable",
"(",
"ds",
",",
"variable",
")",
":",
"if",
"variable",
"not",
"in",
"ds",
".",
"variables",
":",
"return",
"False",
"return",
"ds",
".",
"variables",
"[",
"variable",
"]",
".",
"dimensions",
"==",
"(",
"variable",
",",
"... | Returns True if the variable is a coordinate variable
:param netCDF4.Dataset nc: An open netCDF dataset
:param str variable: Variable name | [
"Returns",
"True",
"if",
"the",
"variable",
"is",
"a",
"coordinate",
"variable"
] | ee89c27b0daade58812489a2da3aa3b6859eafd9 | https://github.com/ioos/compliance-checker/blob/ee89c27b0daade58812489a2da3aa3b6859eafd9/compliance_checker/cfutil.py#L765-L774 | train | 31,395 |
ioos/compliance-checker | compliance_checker/cfutil.py | is_compression_coordinate | def is_compression_coordinate(ds, variable):
'''
Returns True if the variable is a coordinate variable that defines a
compression scheme.
:param netCDF4.Dataset nc: An open netCDF dataset
:param str variable: Variable name
'''
# Must be a coordinate variable
if not is_coordinate_variable(ds, variable):
return False
# must have a string attribute compress
compress = getattr(ds.variables[variable], 'compress', None)
if not isinstance(compress, basestring):
return False
if not compress:
return False
# This should never happen or be allowed
if variable in compress:
return False
# Must point to dimensions
for dim in compress.split():
if dim not in ds.dimensions:
return False
return True | python | def is_compression_coordinate(ds, variable):
'''
Returns True if the variable is a coordinate variable that defines a
compression scheme.
:param netCDF4.Dataset nc: An open netCDF dataset
:param str variable: Variable name
'''
# Must be a coordinate variable
if not is_coordinate_variable(ds, variable):
return False
# must have a string attribute compress
compress = getattr(ds.variables[variable], 'compress', None)
if not isinstance(compress, basestring):
return False
if not compress:
return False
# This should never happen or be allowed
if variable in compress:
return False
# Must point to dimensions
for dim in compress.split():
if dim not in ds.dimensions:
return False
return True | [
"def",
"is_compression_coordinate",
"(",
"ds",
",",
"variable",
")",
":",
"# Must be a coordinate variable",
"if",
"not",
"is_coordinate_variable",
"(",
"ds",
",",
"variable",
")",
":",
"return",
"False",
"# must have a string attribute compress",
"compress",
"=",
"geta... | Returns True if the variable is a coordinate variable that defines a
compression scheme.
:param netCDF4.Dataset nc: An open netCDF dataset
:param str variable: Variable name | [
"Returns",
"True",
"if",
"the",
"variable",
"is",
"a",
"coordinate",
"variable",
"that",
"defines",
"a",
"compression",
"scheme",
"."
] | ee89c27b0daade58812489a2da3aa3b6859eafd9 | https://github.com/ioos/compliance-checker/blob/ee89c27b0daade58812489a2da3aa3b6859eafd9/compliance_checker/cfutil.py#L777-L801 | train | 31,396 |
ioos/compliance-checker | compliance_checker/cfutil.py | coordinate_dimension_matrix | def coordinate_dimension_matrix(nc):
'''
Returns a dictionary of coordinates mapped to their dimensions
:param netCDF4.Dataset nc: An open netCDF dataset
'''
retval = {}
x = get_lon_variable(nc)
if x:
retval['x'] = nc.variables[x].dimensions
y = get_lat_variable(nc)
if y:
retval['y'] = nc.variables[y].dimensions
z = get_z_variable(nc)
if z:
retval['z'] = nc.variables[z].dimensions
t = get_time_variable(nc)
if t:
retval['t'] = nc.variables[t].dimensions
return retval | python | def coordinate_dimension_matrix(nc):
'''
Returns a dictionary of coordinates mapped to their dimensions
:param netCDF4.Dataset nc: An open netCDF dataset
'''
retval = {}
x = get_lon_variable(nc)
if x:
retval['x'] = nc.variables[x].dimensions
y = get_lat_variable(nc)
if y:
retval['y'] = nc.variables[y].dimensions
z = get_z_variable(nc)
if z:
retval['z'] = nc.variables[z].dimensions
t = get_time_variable(nc)
if t:
retval['t'] = nc.variables[t].dimensions
return retval | [
"def",
"coordinate_dimension_matrix",
"(",
"nc",
")",
":",
"retval",
"=",
"{",
"}",
"x",
"=",
"get_lon_variable",
"(",
"nc",
")",
"if",
"x",
":",
"retval",
"[",
"'x'",
"]",
"=",
"nc",
".",
"variables",
"[",
"x",
"]",
".",
"dimensions",
"y",
"=",
"g... | Returns a dictionary of coordinates mapped to their dimensions
:param netCDF4.Dataset nc: An open netCDF dataset | [
"Returns",
"a",
"dictionary",
"of",
"coordinates",
"mapped",
"to",
"their",
"dimensions"
] | ee89c27b0daade58812489a2da3aa3b6859eafd9 | https://github.com/ioos/compliance-checker/blob/ee89c27b0daade58812489a2da3aa3b6859eafd9/compliance_checker/cfutil.py#L804-L825 | train | 31,397 |
ioos/compliance-checker | compliance_checker/cfutil.py | is_point | def is_point(nc, variable):
'''
Returns true if the variable is a point feature type
:param netCDF4.Dataset nc: An open netCDF dataset
:param str variable: name of the variable to check
'''
# x(o), y(o), z(o), t(o)
# X(o)
dims = nc.variables[variable].dimensions
cmatrix = coordinate_dimension_matrix(nc)
first_coord = None
if 't' in cmatrix:
first_coord = cmatrix['t']
if len(cmatrix['t']) > 1:
return False
if 'x' in cmatrix:
if first_coord is None:
first_coord = cmatrix['x']
if first_coord != cmatrix['x']:
return False
if len(cmatrix['x']) > 1:
return False
if 'y' in cmatrix:
if first_coord is None:
first_coord = cmatrix['y']
if first_coord != cmatrix['y']:
return False
if len(cmatrix['y']) > 1:
return False
if 'z' in cmatrix:
if first_coord is None:
first_coord = cmatrix['z']
if first_coord != cmatrix['z']:
return False
if len(cmatrix['z']) > 1:
return False
if first_coord and dims != first_coord:
return False
# Point is indistinguishable from trajectories where the instance dimension
# is implied (scalar)
traj_ids = nc.get_variables_by_attributes(cf_role="trajectory_id")
if traj_ids:
return False
return True | python | def is_point(nc, variable):
'''
Returns true if the variable is a point feature type
:param netCDF4.Dataset nc: An open netCDF dataset
:param str variable: name of the variable to check
'''
# x(o), y(o), z(o), t(o)
# X(o)
dims = nc.variables[variable].dimensions
cmatrix = coordinate_dimension_matrix(nc)
first_coord = None
if 't' in cmatrix:
first_coord = cmatrix['t']
if len(cmatrix['t']) > 1:
return False
if 'x' in cmatrix:
if first_coord is None:
first_coord = cmatrix['x']
if first_coord != cmatrix['x']:
return False
if len(cmatrix['x']) > 1:
return False
if 'y' in cmatrix:
if first_coord is None:
first_coord = cmatrix['y']
if first_coord != cmatrix['y']:
return False
if len(cmatrix['y']) > 1:
return False
if 'z' in cmatrix:
if first_coord is None:
first_coord = cmatrix['z']
if first_coord != cmatrix['z']:
return False
if len(cmatrix['z']) > 1:
return False
if first_coord and dims != first_coord:
return False
# Point is indistinguishable from trajectories where the instance dimension
# is implied (scalar)
traj_ids = nc.get_variables_by_attributes(cf_role="trajectory_id")
if traj_ids:
return False
return True | [
"def",
"is_point",
"(",
"nc",
",",
"variable",
")",
":",
"# x(o), y(o), z(o), t(o)",
"# X(o)",
"dims",
"=",
"nc",
".",
"variables",
"[",
"variable",
"]",
".",
"dimensions",
"cmatrix",
"=",
"coordinate_dimension_matrix",
"(",
"nc",
")",
"first_coord",
"=",
"Non... | Returns true if the variable is a point feature type
:param netCDF4.Dataset nc: An open netCDF dataset
:param str variable: name of the variable to check | [
"Returns",
"true",
"if",
"the",
"variable",
"is",
"a",
"point",
"feature",
"type"
] | ee89c27b0daade58812489a2da3aa3b6859eafd9 | https://github.com/ioos/compliance-checker/blob/ee89c27b0daade58812489a2da3aa3b6859eafd9/compliance_checker/cfutil.py#L828-L875 | train | 31,398 |
ioos/compliance-checker | compliance_checker/cfutil.py | is_cf_trajectory | def is_cf_trajectory(nc, variable):
'''
Returns true if the variable is a CF trajectory feature type
:param netCDF4.Dataset nc: An open netCDF dataset
:param str variable: name of the variable to check
'''
# x(i, o), y(i, o), z(i, o), t(i, o)
# X(i, o)
dims = nc.variables[variable].dimensions
cmatrix = coordinate_dimension_matrix(nc)
for req in ('x', 'y', 't'):
if req not in cmatrix:
return False
if len(cmatrix['x']) != 2:
return False
if cmatrix['x'] != cmatrix['y']:
return False
if cmatrix['x'] != cmatrix['t']:
return False
if 'z' in cmatrix and cmatrix['x'] != cmatrix['z']:
return False
if dims == cmatrix['x']:
return True
return False | python | def is_cf_trajectory(nc, variable):
'''
Returns true if the variable is a CF trajectory feature type
:param netCDF4.Dataset nc: An open netCDF dataset
:param str variable: name of the variable to check
'''
# x(i, o), y(i, o), z(i, o), t(i, o)
# X(i, o)
dims = nc.variables[variable].dimensions
cmatrix = coordinate_dimension_matrix(nc)
for req in ('x', 'y', 't'):
if req not in cmatrix:
return False
if len(cmatrix['x']) != 2:
return False
if cmatrix['x'] != cmatrix['y']:
return False
if cmatrix['x'] != cmatrix['t']:
return False
if 'z' in cmatrix and cmatrix['x'] != cmatrix['z']:
return False
if dims == cmatrix['x']:
return True
return False | [
"def",
"is_cf_trajectory",
"(",
"nc",
",",
"variable",
")",
":",
"# x(i, o), y(i, o), z(i, o), t(i, o)",
"# X(i, o)",
"dims",
"=",
"nc",
".",
"variables",
"[",
"variable",
"]",
".",
"dimensions",
"cmatrix",
"=",
"coordinate_dimension_matrix",
"(",
"nc",
")",
"for"... | Returns true if the variable is a CF trajectory feature type
:param netCDF4.Dataset nc: An open netCDF dataset
:param str variable: name of the variable to check | [
"Returns",
"true",
"if",
"the",
"variable",
"is",
"a",
"CF",
"trajectory",
"feature",
"type"
] | ee89c27b0daade58812489a2da3aa3b6859eafd9 | https://github.com/ioos/compliance-checker/blob/ee89c27b0daade58812489a2da3aa3b6859eafd9/compliance_checker/cfutil.py#L984-L1009 | train | 31,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.