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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
amzn/ion-python | amazon/ion/reader_text.py | _exponent_handler_factory | def _exponent_handler_factory(ion_type, exp_chars, parse_func, first_char=None):
"""Generates a handler co-routine which tokenizes an numeric exponent.
Args:
ion_type (IonType): The type of the value with this exponent.
exp_chars (sequence): The set of ordinals of the legal exponent characters for this component.
parse_func (callable): Called upon ending the numeric value. Accepts the current token value and returns a
thunk that lazily parses the token.
first_char (Optional[int]): The ordinal of the character that should be appended instead of the character that
occurs first in this component. This is useful for preparing the token for parsing in the case where a
particular character is peculiar to the Ion format (e.g. 'd' to denote the exponent of a decimal value
should be replaced with 'e' for compatibility with python's Decimal type).
"""
def transition(prev, c, ctx, trans):
if c in _SIGN and prev in exp_chars:
ctx.value.append(c)
else:
_illegal_character(c, ctx)
return trans
illegal = exp_chars + _SIGN
return _numeric_handler_factory(_DIGITS, transition, lambda c, ctx: c in exp_chars, illegal, parse_func,
illegal_at_end=illegal, ion_type=ion_type, first_char=first_char) | python | def _exponent_handler_factory(ion_type, exp_chars, parse_func, first_char=None):
"""Generates a handler co-routine which tokenizes an numeric exponent.
Args:
ion_type (IonType): The type of the value with this exponent.
exp_chars (sequence): The set of ordinals of the legal exponent characters for this component.
parse_func (callable): Called upon ending the numeric value. Accepts the current token value and returns a
thunk that lazily parses the token.
first_char (Optional[int]): The ordinal of the character that should be appended instead of the character that
occurs first in this component. This is useful for preparing the token for parsing in the case where a
particular character is peculiar to the Ion format (e.g. 'd' to denote the exponent of a decimal value
should be replaced with 'e' for compatibility with python's Decimal type).
"""
def transition(prev, c, ctx, trans):
if c in _SIGN and prev in exp_chars:
ctx.value.append(c)
else:
_illegal_character(c, ctx)
return trans
illegal = exp_chars + _SIGN
return _numeric_handler_factory(_DIGITS, transition, lambda c, ctx: c in exp_chars, illegal, parse_func,
illegal_at_end=illegal, ion_type=ion_type, first_char=first_char) | [
"def",
"_exponent_handler_factory",
"(",
"ion_type",
",",
"exp_chars",
",",
"parse_func",
",",
"first_char",
"=",
"None",
")",
":",
"def",
"transition",
"(",
"prev",
",",
"c",
",",
"ctx",
",",
"trans",
")",
":",
"if",
"c",
"in",
"_SIGN",
"and",
"prev",
"in",
"exp_chars",
":",
"ctx",
".",
"value",
".",
"append",
"(",
"c",
")",
"else",
":",
"_illegal_character",
"(",
"c",
",",
"ctx",
")",
"return",
"trans",
"illegal",
"=",
"exp_chars",
"+",
"_SIGN",
"return",
"_numeric_handler_factory",
"(",
"_DIGITS",
",",
"transition",
",",
"lambda",
"c",
",",
"ctx",
":",
"c",
"in",
"exp_chars",
",",
"illegal",
",",
"parse_func",
",",
"illegal_at_end",
"=",
"illegal",
",",
"ion_type",
"=",
"ion_type",
",",
"first_char",
"=",
"first_char",
")"
] | Generates a handler co-routine which tokenizes an numeric exponent.
Args:
ion_type (IonType): The type of the value with this exponent.
exp_chars (sequence): The set of ordinals of the legal exponent characters for this component.
parse_func (callable): Called upon ending the numeric value. Accepts the current token value and returns a
thunk that lazily parses the token.
first_char (Optional[int]): The ordinal of the character that should be appended instead of the character that
occurs first in this component. This is useful for preparing the token for parsing in the case where a
particular character is peculiar to the Ion format (e.g. 'd' to denote the exponent of a decimal value
should be replaced with 'e' for compatibility with python's Decimal type). | [
"Generates",
"a",
"handler",
"co",
"-",
"routine",
"which",
"tokenizes",
"an",
"numeric",
"exponent",
"."
] | 0b21fa3ba7755f55f745e4aa970d86343b82449d | https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/reader_text.py#L711-L732 | train | 233,800 |
amzn/ion-python | amazon/ion/reader_text.py | _coefficient_handler_factory | def _coefficient_handler_factory(trans_table, parse_func, assertion=lambda c, ctx: True,
ion_type=None, append_first_if_not=None):
"""Generates a handler co-routine which tokenizes a numeric coefficient.
Args:
trans_table (dict): lookup table for the handler for the next component of this numeric token, given the
ordinal of the first character in that component.
parse_func (callable): Called upon ending the numeric value. Accepts the current token value and returns a
thunk that lazily parses the token.
assertion (callable): Accepts the first character's ordinal and the current context. Returns True if this is
a legal start to the component.
ion_type (Optional[IonType]): The type of the value if it were to end on this coefficient.
append_first_if_not (Optional[int]): The ordinal of a character that should not be appended to the token if
it occurs first in this component (e.g. an underscore in many cases).
"""
def transition(prev, c, ctx, trans):
if prev == _UNDERSCORE:
_illegal_character(c, ctx, 'Underscore before %s.' % (_chr(c),))
return ctx.immediate_transition(trans_table[c](c, ctx))
return _numeric_handler_factory(_DIGITS, transition, assertion, (_DOT,), parse_func,
ion_type=ion_type, append_first_if_not=append_first_if_not) | python | def _coefficient_handler_factory(trans_table, parse_func, assertion=lambda c, ctx: True,
ion_type=None, append_first_if_not=None):
"""Generates a handler co-routine which tokenizes a numeric coefficient.
Args:
trans_table (dict): lookup table for the handler for the next component of this numeric token, given the
ordinal of the first character in that component.
parse_func (callable): Called upon ending the numeric value. Accepts the current token value and returns a
thunk that lazily parses the token.
assertion (callable): Accepts the first character's ordinal and the current context. Returns True if this is
a legal start to the component.
ion_type (Optional[IonType]): The type of the value if it were to end on this coefficient.
append_first_if_not (Optional[int]): The ordinal of a character that should not be appended to the token if
it occurs first in this component (e.g. an underscore in many cases).
"""
def transition(prev, c, ctx, trans):
if prev == _UNDERSCORE:
_illegal_character(c, ctx, 'Underscore before %s.' % (_chr(c),))
return ctx.immediate_transition(trans_table[c](c, ctx))
return _numeric_handler_factory(_DIGITS, transition, assertion, (_DOT,), parse_func,
ion_type=ion_type, append_first_if_not=append_first_if_not) | [
"def",
"_coefficient_handler_factory",
"(",
"trans_table",
",",
"parse_func",
",",
"assertion",
"=",
"lambda",
"c",
",",
"ctx",
":",
"True",
",",
"ion_type",
"=",
"None",
",",
"append_first_if_not",
"=",
"None",
")",
":",
"def",
"transition",
"(",
"prev",
",",
"c",
",",
"ctx",
",",
"trans",
")",
":",
"if",
"prev",
"==",
"_UNDERSCORE",
":",
"_illegal_character",
"(",
"c",
",",
"ctx",
",",
"'Underscore before %s.'",
"%",
"(",
"_chr",
"(",
"c",
")",
",",
")",
")",
"return",
"ctx",
".",
"immediate_transition",
"(",
"trans_table",
"[",
"c",
"]",
"(",
"c",
",",
"ctx",
")",
")",
"return",
"_numeric_handler_factory",
"(",
"_DIGITS",
",",
"transition",
",",
"assertion",
",",
"(",
"_DOT",
",",
")",
",",
"parse_func",
",",
"ion_type",
"=",
"ion_type",
",",
"append_first_if_not",
"=",
"append_first_if_not",
")"
] | Generates a handler co-routine which tokenizes a numeric coefficient.
Args:
trans_table (dict): lookup table for the handler for the next component of this numeric token, given the
ordinal of the first character in that component.
parse_func (callable): Called upon ending the numeric value. Accepts the current token value and returns a
thunk that lazily parses the token.
assertion (callable): Accepts the first character's ordinal and the current context. Returns True if this is
a legal start to the component.
ion_type (Optional[IonType]): The type of the value if it were to end on this coefficient.
append_first_if_not (Optional[int]): The ordinal of a character that should not be appended to the token if
it occurs first in this component (e.g. an underscore in many cases). | [
"Generates",
"a",
"handler",
"co",
"-",
"routine",
"which",
"tokenizes",
"a",
"numeric",
"coefficient",
"."
] | 0b21fa3ba7755f55f745e4aa970d86343b82449d | https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/reader_text.py#L739-L759 | train | 233,801 |
amzn/ion-python | amazon/ion/reader_text.py | _radix_int_handler_factory | def _radix_int_handler_factory(radix_indicators, charset, parse_func):
"""Generates a handler co-routine which tokenizes a integer of a particular radix.
Args:
radix_indicators (sequence): The set of ordinals of characters that indicate the radix of this int.
charset (sequence): Set of ordinals of legal characters for this radix.
parse_func (callable): Called upon ending the numeric value. Accepts the current token value and returns a
thunk that lazily parses the token.
"""
def assertion(c, ctx):
return c in radix_indicators and \
((len(ctx.value) == 1 and ctx.value[0] == _ZERO) or
(len(ctx.value) == 2 and ctx.value[0] == _MINUS and ctx.value[1] == _ZERO)) and \
ctx.ion_type == IonType.INT
return _numeric_handler_factory(charset, lambda prev, c, ctx, trans: _illegal_character(c, ctx),
assertion, radix_indicators, parse_func, illegal_at_end=radix_indicators) | python | def _radix_int_handler_factory(radix_indicators, charset, parse_func):
"""Generates a handler co-routine which tokenizes a integer of a particular radix.
Args:
radix_indicators (sequence): The set of ordinals of characters that indicate the radix of this int.
charset (sequence): Set of ordinals of legal characters for this radix.
parse_func (callable): Called upon ending the numeric value. Accepts the current token value and returns a
thunk that lazily parses the token.
"""
def assertion(c, ctx):
return c in radix_indicators and \
((len(ctx.value) == 1 and ctx.value[0] == _ZERO) or
(len(ctx.value) == 2 and ctx.value[0] == _MINUS and ctx.value[1] == _ZERO)) and \
ctx.ion_type == IonType.INT
return _numeric_handler_factory(charset, lambda prev, c, ctx, trans: _illegal_character(c, ctx),
assertion, radix_indicators, parse_func, illegal_at_end=radix_indicators) | [
"def",
"_radix_int_handler_factory",
"(",
"radix_indicators",
",",
"charset",
",",
"parse_func",
")",
":",
"def",
"assertion",
"(",
"c",
",",
"ctx",
")",
":",
"return",
"c",
"in",
"radix_indicators",
"and",
"(",
"(",
"len",
"(",
"ctx",
".",
"value",
")",
"==",
"1",
"and",
"ctx",
".",
"value",
"[",
"0",
"]",
"==",
"_ZERO",
")",
"or",
"(",
"len",
"(",
"ctx",
".",
"value",
")",
"==",
"2",
"and",
"ctx",
".",
"value",
"[",
"0",
"]",
"==",
"_MINUS",
"and",
"ctx",
".",
"value",
"[",
"1",
"]",
"==",
"_ZERO",
")",
")",
"and",
"ctx",
".",
"ion_type",
"==",
"IonType",
".",
"INT",
"return",
"_numeric_handler_factory",
"(",
"charset",
",",
"lambda",
"prev",
",",
"c",
",",
"ctx",
",",
"trans",
":",
"_illegal_character",
"(",
"c",
",",
"ctx",
")",
",",
"assertion",
",",
"radix_indicators",
",",
"parse_func",
",",
"illegal_at_end",
"=",
"radix_indicators",
")"
] | Generates a handler co-routine which tokenizes a integer of a particular radix.
Args:
radix_indicators (sequence): The set of ordinals of characters that indicate the radix of this int.
charset (sequence): Set of ordinals of legal characters for this radix.
parse_func (callable): Called upon ending the numeric value. Accepts the current token value and returns a
thunk that lazily parses the token. | [
"Generates",
"a",
"handler",
"co",
"-",
"routine",
"which",
"tokenizes",
"a",
"integer",
"of",
"a",
"particular",
"radix",
"."
] | 0b21fa3ba7755f55f745e4aa970d86343b82449d | https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/reader_text.py#L785-L800 | train | 233,802 |
amzn/ion-python | amazon/ion/reader_text.py | _timestamp_zero_start_handler | def _timestamp_zero_start_handler(c, ctx):
"""Handles numeric values that start with a zero followed by another digit. This is either a timestamp or an
error.
"""
val = ctx.value
ctx.set_ion_type(IonType.TIMESTAMP)
if val[0] == _MINUS:
_illegal_character(c, ctx, 'Negative year not allowed.')
val.append(c)
c, self = yield
trans = ctx.immediate_transition(self)
while True:
if c in _TIMESTAMP_YEAR_DELIMITERS:
trans = ctx.immediate_transition(_timestamp_handler(c, ctx))
elif c in _DIGITS:
val.append(c)
else:
_illegal_character(c, ctx)
c, _ = yield trans | python | def _timestamp_zero_start_handler(c, ctx):
"""Handles numeric values that start with a zero followed by another digit. This is either a timestamp or an
error.
"""
val = ctx.value
ctx.set_ion_type(IonType.TIMESTAMP)
if val[0] == _MINUS:
_illegal_character(c, ctx, 'Negative year not allowed.')
val.append(c)
c, self = yield
trans = ctx.immediate_transition(self)
while True:
if c in _TIMESTAMP_YEAR_DELIMITERS:
trans = ctx.immediate_transition(_timestamp_handler(c, ctx))
elif c in _DIGITS:
val.append(c)
else:
_illegal_character(c, ctx)
c, _ = yield trans | [
"def",
"_timestamp_zero_start_handler",
"(",
"c",
",",
"ctx",
")",
":",
"val",
"=",
"ctx",
".",
"value",
"ctx",
".",
"set_ion_type",
"(",
"IonType",
".",
"TIMESTAMP",
")",
"if",
"val",
"[",
"0",
"]",
"==",
"_MINUS",
":",
"_illegal_character",
"(",
"c",
",",
"ctx",
",",
"'Negative year not allowed.'",
")",
"val",
".",
"append",
"(",
"c",
")",
"c",
",",
"self",
"=",
"yield",
"trans",
"=",
"ctx",
".",
"immediate_transition",
"(",
"self",
")",
"while",
"True",
":",
"if",
"c",
"in",
"_TIMESTAMP_YEAR_DELIMITERS",
":",
"trans",
"=",
"ctx",
".",
"immediate_transition",
"(",
"_timestamp_handler",
"(",
"c",
",",
"ctx",
")",
")",
"elif",
"c",
"in",
"_DIGITS",
":",
"val",
".",
"append",
"(",
"c",
")",
"else",
":",
"_illegal_character",
"(",
"c",
",",
"ctx",
")",
"c",
",",
"_",
"=",
"yield",
"trans"
] | Handles numeric values that start with a zero followed by another digit. This is either a timestamp or an
error. | [
"Handles",
"numeric",
"values",
"that",
"start",
"with",
"a",
"zero",
"followed",
"by",
"another",
"digit",
".",
"This",
"is",
"either",
"a",
"timestamp",
"or",
"an",
"error",
"."
] | 0b21fa3ba7755f55f745e4aa970d86343b82449d | https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/reader_text.py#L808-L826 | train | 233,803 |
amzn/ion-python | amazon/ion/reader_text.py | _parse_timestamp | def _parse_timestamp(tokens):
"""Parses each token in the given `_TimestampTokens` and marshals the numeric components into a `Timestamp`."""
def parse():
precision = TimestampPrecision.YEAR
off_hour = tokens[_TimestampState.OFF_HOUR]
off_minutes = tokens[_TimestampState.OFF_MINUTE]
microsecond = None
fraction_digits = None
if off_hour is not None:
assert off_minutes is not None
off_sign = -1 if _MINUS in off_hour else 1
off_hour = int(off_hour)
off_minutes = int(off_minutes) * off_sign
if off_sign == -1 and off_hour == 0 and off_minutes == 0:
# -00:00 (unknown UTC offset) is a naive datetime.
off_hour = None
off_minutes = None
else:
assert off_minutes is None
year = tokens[_TimestampState.YEAR]
assert year is not None
year = int(year)
month = tokens[_TimestampState.MONTH]
if month is None:
month = 1
else:
month = int(month)
precision = TimestampPrecision.MONTH
day = tokens[_TimestampState.DAY]
if day is None:
day = 1
else:
day = int(day)
precision = TimestampPrecision.DAY
hour = tokens[_TimestampState.HOUR]
minute = tokens[_TimestampState.MINUTE]
if hour is None:
assert minute is None
hour = 0
minute = 0
else:
assert minute is not None
hour = int(hour)
minute = int(minute)
precision = TimestampPrecision.MINUTE
second = tokens[_TimestampState.SECOND]
if second is None:
second = 0
else:
second = int(second)
precision = TimestampPrecision.SECOND
fraction = tokens[_TimestampState.FRACTIONAL]
if fraction is not None:
fraction_digits = len(fraction)
if fraction_digits > MICROSECOND_PRECISION:
for digit in fraction[MICROSECOND_PRECISION:]:
if digit != _ZERO:
raise ValueError('Only six significant digits supported in timestamp fractional. Found %s.'
% (fraction,))
fraction_digits = MICROSECOND_PRECISION
fraction = fraction[0:MICROSECOND_PRECISION]
else:
fraction.extend(_ZEROS[MICROSECOND_PRECISION - fraction_digits])
microsecond = int(fraction)
return timestamp(
year, month, day,
hour, minute, second, microsecond,
off_hour, off_minutes,
precision=precision, fractional_precision=fraction_digits
)
return parse | python | def _parse_timestamp(tokens):
"""Parses each token in the given `_TimestampTokens` and marshals the numeric components into a `Timestamp`."""
def parse():
precision = TimestampPrecision.YEAR
off_hour = tokens[_TimestampState.OFF_HOUR]
off_minutes = tokens[_TimestampState.OFF_MINUTE]
microsecond = None
fraction_digits = None
if off_hour is not None:
assert off_minutes is not None
off_sign = -1 if _MINUS in off_hour else 1
off_hour = int(off_hour)
off_minutes = int(off_minutes) * off_sign
if off_sign == -1 and off_hour == 0 and off_minutes == 0:
# -00:00 (unknown UTC offset) is a naive datetime.
off_hour = None
off_minutes = None
else:
assert off_minutes is None
year = tokens[_TimestampState.YEAR]
assert year is not None
year = int(year)
month = tokens[_TimestampState.MONTH]
if month is None:
month = 1
else:
month = int(month)
precision = TimestampPrecision.MONTH
day = tokens[_TimestampState.DAY]
if day is None:
day = 1
else:
day = int(day)
precision = TimestampPrecision.DAY
hour = tokens[_TimestampState.HOUR]
minute = tokens[_TimestampState.MINUTE]
if hour is None:
assert minute is None
hour = 0
minute = 0
else:
assert minute is not None
hour = int(hour)
minute = int(minute)
precision = TimestampPrecision.MINUTE
second = tokens[_TimestampState.SECOND]
if second is None:
second = 0
else:
second = int(second)
precision = TimestampPrecision.SECOND
fraction = tokens[_TimestampState.FRACTIONAL]
if fraction is not None:
fraction_digits = len(fraction)
if fraction_digits > MICROSECOND_PRECISION:
for digit in fraction[MICROSECOND_PRECISION:]:
if digit != _ZERO:
raise ValueError('Only six significant digits supported in timestamp fractional. Found %s.'
% (fraction,))
fraction_digits = MICROSECOND_PRECISION
fraction = fraction[0:MICROSECOND_PRECISION]
else:
fraction.extend(_ZEROS[MICROSECOND_PRECISION - fraction_digits])
microsecond = int(fraction)
return timestamp(
year, month, day,
hour, minute, second, microsecond,
off_hour, off_minutes,
precision=precision, fractional_precision=fraction_digits
)
return parse | [
"def",
"_parse_timestamp",
"(",
"tokens",
")",
":",
"def",
"parse",
"(",
")",
":",
"precision",
"=",
"TimestampPrecision",
".",
"YEAR",
"off_hour",
"=",
"tokens",
"[",
"_TimestampState",
".",
"OFF_HOUR",
"]",
"off_minutes",
"=",
"tokens",
"[",
"_TimestampState",
".",
"OFF_MINUTE",
"]",
"microsecond",
"=",
"None",
"fraction_digits",
"=",
"None",
"if",
"off_hour",
"is",
"not",
"None",
":",
"assert",
"off_minutes",
"is",
"not",
"None",
"off_sign",
"=",
"-",
"1",
"if",
"_MINUS",
"in",
"off_hour",
"else",
"1",
"off_hour",
"=",
"int",
"(",
"off_hour",
")",
"off_minutes",
"=",
"int",
"(",
"off_minutes",
")",
"*",
"off_sign",
"if",
"off_sign",
"==",
"-",
"1",
"and",
"off_hour",
"==",
"0",
"and",
"off_minutes",
"==",
"0",
":",
"# -00:00 (unknown UTC offset) is a naive datetime.",
"off_hour",
"=",
"None",
"off_minutes",
"=",
"None",
"else",
":",
"assert",
"off_minutes",
"is",
"None",
"year",
"=",
"tokens",
"[",
"_TimestampState",
".",
"YEAR",
"]",
"assert",
"year",
"is",
"not",
"None",
"year",
"=",
"int",
"(",
"year",
")",
"month",
"=",
"tokens",
"[",
"_TimestampState",
".",
"MONTH",
"]",
"if",
"month",
"is",
"None",
":",
"month",
"=",
"1",
"else",
":",
"month",
"=",
"int",
"(",
"month",
")",
"precision",
"=",
"TimestampPrecision",
".",
"MONTH",
"day",
"=",
"tokens",
"[",
"_TimestampState",
".",
"DAY",
"]",
"if",
"day",
"is",
"None",
":",
"day",
"=",
"1",
"else",
":",
"day",
"=",
"int",
"(",
"day",
")",
"precision",
"=",
"TimestampPrecision",
".",
"DAY",
"hour",
"=",
"tokens",
"[",
"_TimestampState",
".",
"HOUR",
"]",
"minute",
"=",
"tokens",
"[",
"_TimestampState",
".",
"MINUTE",
"]",
"if",
"hour",
"is",
"None",
":",
"assert",
"minute",
"is",
"None",
"hour",
"=",
"0",
"minute",
"=",
"0",
"else",
":",
"assert",
"minute",
"is",
"not",
"None",
"hour",
"=",
"int",
"(",
"hour",
")",
"minute",
"=",
"int",
"(",
"minute",
")",
"precision",
"=",
"TimestampPrecision",
".",
"MINUTE",
"second",
"=",
"tokens",
"[",
"_TimestampState",
".",
"SECOND",
"]",
"if",
"second",
"is",
"None",
":",
"second",
"=",
"0",
"else",
":",
"second",
"=",
"int",
"(",
"second",
")",
"precision",
"=",
"TimestampPrecision",
".",
"SECOND",
"fraction",
"=",
"tokens",
"[",
"_TimestampState",
".",
"FRACTIONAL",
"]",
"if",
"fraction",
"is",
"not",
"None",
":",
"fraction_digits",
"=",
"len",
"(",
"fraction",
")",
"if",
"fraction_digits",
">",
"MICROSECOND_PRECISION",
":",
"for",
"digit",
"in",
"fraction",
"[",
"MICROSECOND_PRECISION",
":",
"]",
":",
"if",
"digit",
"!=",
"_ZERO",
":",
"raise",
"ValueError",
"(",
"'Only six significant digits supported in timestamp fractional. Found %s.'",
"%",
"(",
"fraction",
",",
")",
")",
"fraction_digits",
"=",
"MICROSECOND_PRECISION",
"fraction",
"=",
"fraction",
"[",
"0",
":",
"MICROSECOND_PRECISION",
"]",
"else",
":",
"fraction",
".",
"extend",
"(",
"_ZEROS",
"[",
"MICROSECOND_PRECISION",
"-",
"fraction_digits",
"]",
")",
"microsecond",
"=",
"int",
"(",
"fraction",
")",
"return",
"timestamp",
"(",
"year",
",",
"month",
",",
"day",
",",
"hour",
",",
"minute",
",",
"second",
",",
"microsecond",
",",
"off_hour",
",",
"off_minutes",
",",
"precision",
"=",
"precision",
",",
"fractional_precision",
"=",
"fraction_digits",
")",
"return",
"parse"
] | Parses each token in the given `_TimestampTokens` and marshals the numeric components into a `Timestamp`. | [
"Parses",
"each",
"token",
"in",
"the",
"given",
"_TimestampTokens",
"and",
"marshals",
"the",
"numeric",
"components",
"into",
"a",
"Timestamp",
"."
] | 0b21fa3ba7755f55f745e4aa970d86343b82449d | https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/reader_text.py#L870-L946 | train | 233,804 |
amzn/ion-python | amazon/ion/reader_text.py | _comment_handler | def _comment_handler(c, ctx, whence):
"""Handles comments. Upon completion of the comment, immediately transitions back to `whence`."""
assert c == _SLASH
c, self = yield
if c == _SLASH:
ctx.set_line_comment()
block_comment = False
elif c == _ASTERISK:
if ctx.line_comment:
# This happens when a block comment immediately follows a line comment.
ctx.set_line_comment(False)
block_comment = True
else:
_illegal_character(c, ctx, 'Illegal character sequence "/%s".' % (_chr(c),))
done = False
prev = None
trans = ctx.immediate_transition(self)
while not done:
c, _ = yield trans
if block_comment:
if prev == _ASTERISK and c == _SLASH:
done = True
prev = c
else:
if c in _NEWLINES or BufferQueue.is_eof(c):
done = True
yield ctx.set_self_delimiting(True).immediate_transition(whence) | python | def _comment_handler(c, ctx, whence):
"""Handles comments. Upon completion of the comment, immediately transitions back to `whence`."""
assert c == _SLASH
c, self = yield
if c == _SLASH:
ctx.set_line_comment()
block_comment = False
elif c == _ASTERISK:
if ctx.line_comment:
# This happens when a block comment immediately follows a line comment.
ctx.set_line_comment(False)
block_comment = True
else:
_illegal_character(c, ctx, 'Illegal character sequence "/%s".' % (_chr(c),))
done = False
prev = None
trans = ctx.immediate_transition(self)
while not done:
c, _ = yield trans
if block_comment:
if prev == _ASTERISK and c == _SLASH:
done = True
prev = c
else:
if c in _NEWLINES or BufferQueue.is_eof(c):
done = True
yield ctx.set_self_delimiting(True).immediate_transition(whence) | [
"def",
"_comment_handler",
"(",
"c",
",",
"ctx",
",",
"whence",
")",
":",
"assert",
"c",
"==",
"_SLASH",
"c",
",",
"self",
"=",
"yield",
"if",
"c",
"==",
"_SLASH",
":",
"ctx",
".",
"set_line_comment",
"(",
")",
"block_comment",
"=",
"False",
"elif",
"c",
"==",
"_ASTERISK",
":",
"if",
"ctx",
".",
"line_comment",
":",
"# This happens when a block comment immediately follows a line comment.",
"ctx",
".",
"set_line_comment",
"(",
"False",
")",
"block_comment",
"=",
"True",
"else",
":",
"_illegal_character",
"(",
"c",
",",
"ctx",
",",
"'Illegal character sequence \"/%s\".'",
"%",
"(",
"_chr",
"(",
"c",
")",
",",
")",
")",
"done",
"=",
"False",
"prev",
"=",
"None",
"trans",
"=",
"ctx",
".",
"immediate_transition",
"(",
"self",
")",
"while",
"not",
"done",
":",
"c",
",",
"_",
"=",
"yield",
"trans",
"if",
"block_comment",
":",
"if",
"prev",
"==",
"_ASTERISK",
"and",
"c",
"==",
"_SLASH",
":",
"done",
"=",
"True",
"prev",
"=",
"c",
"else",
":",
"if",
"c",
"in",
"_NEWLINES",
"or",
"BufferQueue",
".",
"is_eof",
"(",
"c",
")",
":",
"done",
"=",
"True",
"yield",
"ctx",
".",
"set_self_delimiting",
"(",
"True",
")",
".",
"immediate_transition",
"(",
"whence",
")"
] | Handles comments. Upon completion of the comment, immediately transitions back to `whence`. | [
"Handles",
"comments",
".",
"Upon",
"completion",
"of",
"the",
"comment",
"immediately",
"transitions",
"back",
"to",
"whence",
"."
] | 0b21fa3ba7755f55f745e4aa970d86343b82449d | https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/reader_text.py#L1033-L1059 | train | 233,805 |
amzn/ion-python | amazon/ion/reader_text.py | _sexp_slash_handler | def _sexp_slash_handler(c, ctx, whence=None, pending_event=None):
"""Handles the special case of a forward-slash within an s-expression. This is either an operator or a
comment.
"""
assert c == _SLASH
if whence is None:
whence = ctx.whence
c, self = yield
ctx.queue.unread(c)
if c == _ASTERISK or c == _SLASH:
yield ctx.immediate_transition(_comment_handler(_SLASH, ctx, whence))
else:
if pending_event is not None:
# Since this is the start of a new value and not a comment, the pending event must be emitted.
assert pending_event.event is not None
yield _CompositeTransition(pending_event, ctx, partial(_operator_symbol_handler, _SLASH))
yield ctx.immediate_transition(_operator_symbol_handler(_SLASH, ctx)) | python | def _sexp_slash_handler(c, ctx, whence=None, pending_event=None):
"""Handles the special case of a forward-slash within an s-expression. This is either an operator or a
comment.
"""
assert c == _SLASH
if whence is None:
whence = ctx.whence
c, self = yield
ctx.queue.unread(c)
if c == _ASTERISK or c == _SLASH:
yield ctx.immediate_transition(_comment_handler(_SLASH, ctx, whence))
else:
if pending_event is not None:
# Since this is the start of a new value and not a comment, the pending event must be emitted.
assert pending_event.event is not None
yield _CompositeTransition(pending_event, ctx, partial(_operator_symbol_handler, _SLASH))
yield ctx.immediate_transition(_operator_symbol_handler(_SLASH, ctx)) | [
"def",
"_sexp_slash_handler",
"(",
"c",
",",
"ctx",
",",
"whence",
"=",
"None",
",",
"pending_event",
"=",
"None",
")",
":",
"assert",
"c",
"==",
"_SLASH",
"if",
"whence",
"is",
"None",
":",
"whence",
"=",
"ctx",
".",
"whence",
"c",
",",
"self",
"=",
"yield",
"ctx",
".",
"queue",
".",
"unread",
"(",
"c",
")",
"if",
"c",
"==",
"_ASTERISK",
"or",
"c",
"==",
"_SLASH",
":",
"yield",
"ctx",
".",
"immediate_transition",
"(",
"_comment_handler",
"(",
"_SLASH",
",",
"ctx",
",",
"whence",
")",
")",
"else",
":",
"if",
"pending_event",
"is",
"not",
"None",
":",
"# Since this is the start of a new value and not a comment, the pending event must be emitted.",
"assert",
"pending_event",
".",
"event",
"is",
"not",
"None",
"yield",
"_CompositeTransition",
"(",
"pending_event",
",",
"ctx",
",",
"partial",
"(",
"_operator_symbol_handler",
",",
"_SLASH",
")",
")",
"yield",
"ctx",
".",
"immediate_transition",
"(",
"_operator_symbol_handler",
"(",
"_SLASH",
",",
"ctx",
")",
")"
] | Handles the special case of a forward-slash within an s-expression. This is either an operator or a
comment. | [
"Handles",
"the",
"special",
"case",
"of",
"a",
"forward",
"-",
"slash",
"within",
"an",
"s",
"-",
"expression",
".",
"This",
"is",
"either",
"an",
"operator",
"or",
"a",
"comment",
"."
] | 0b21fa3ba7755f55f745e4aa970d86343b82449d | https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/reader_text.py#L1063-L1079 | train | 233,806 |
amzn/ion-python | amazon/ion/reader_text.py | _typed_null_handler | def _typed_null_handler(c, ctx):
"""Handles typed null values. Entered once `null.` has been found."""
assert c == _DOT
c, self = yield
nxt = _NULL_STARTS
i = 0
length = None
done = False
trans = ctx.immediate_transition(self)
while True:
if done:
if _ends_value(c) or (ctx.container.ion_type is IonType.SEXP and c in _OPERATORS):
trans = ctx.event_transition(IonEvent, IonEventType.SCALAR, nxt.ion_type, None)
else:
_illegal_character(c, ctx, 'Illegal null type.')
elif length is None:
if c not in nxt:
_illegal_character(c, ctx, 'Illegal null type.')
nxt = nxt[c]
if isinstance(nxt, _NullSequence):
length = len(nxt.sequence)
else:
if c != nxt[i]:
_illegal_character(c, ctx, 'Illegal null type.')
i += 1
done = i == length
c, _ = yield trans | python | def _typed_null_handler(c, ctx):
"""Handles typed null values. Entered once `null.` has been found."""
assert c == _DOT
c, self = yield
nxt = _NULL_STARTS
i = 0
length = None
done = False
trans = ctx.immediate_transition(self)
while True:
if done:
if _ends_value(c) or (ctx.container.ion_type is IonType.SEXP and c in _OPERATORS):
trans = ctx.event_transition(IonEvent, IonEventType.SCALAR, nxt.ion_type, None)
else:
_illegal_character(c, ctx, 'Illegal null type.')
elif length is None:
if c not in nxt:
_illegal_character(c, ctx, 'Illegal null type.')
nxt = nxt[c]
if isinstance(nxt, _NullSequence):
length = len(nxt.sequence)
else:
if c != nxt[i]:
_illegal_character(c, ctx, 'Illegal null type.')
i += 1
done = i == length
c, _ = yield trans | [
"def",
"_typed_null_handler",
"(",
"c",
",",
"ctx",
")",
":",
"assert",
"c",
"==",
"_DOT",
"c",
",",
"self",
"=",
"yield",
"nxt",
"=",
"_NULL_STARTS",
"i",
"=",
"0",
"length",
"=",
"None",
"done",
"=",
"False",
"trans",
"=",
"ctx",
".",
"immediate_transition",
"(",
"self",
")",
"while",
"True",
":",
"if",
"done",
":",
"if",
"_ends_value",
"(",
"c",
")",
"or",
"(",
"ctx",
".",
"container",
".",
"ion_type",
"is",
"IonType",
".",
"SEXP",
"and",
"c",
"in",
"_OPERATORS",
")",
":",
"trans",
"=",
"ctx",
".",
"event_transition",
"(",
"IonEvent",
",",
"IonEventType",
".",
"SCALAR",
",",
"nxt",
".",
"ion_type",
",",
"None",
")",
"else",
":",
"_illegal_character",
"(",
"c",
",",
"ctx",
",",
"'Illegal null type.'",
")",
"elif",
"length",
"is",
"None",
":",
"if",
"c",
"not",
"in",
"nxt",
":",
"_illegal_character",
"(",
"c",
",",
"ctx",
",",
"'Illegal null type.'",
")",
"nxt",
"=",
"nxt",
"[",
"c",
"]",
"if",
"isinstance",
"(",
"nxt",
",",
"_NullSequence",
")",
":",
"length",
"=",
"len",
"(",
"nxt",
".",
"sequence",
")",
"else",
":",
"if",
"c",
"!=",
"nxt",
"[",
"i",
"]",
":",
"_illegal_character",
"(",
"c",
",",
"ctx",
",",
"'Illegal null type.'",
")",
"i",
"+=",
"1",
"done",
"=",
"i",
"==",
"length",
"c",
",",
"_",
"=",
"yield",
"trans"
] | Handles typed null values. Entered once `null.` has been found. | [
"Handles",
"typed",
"null",
"values",
".",
"Entered",
"once",
"null",
".",
"has",
"been",
"found",
"."
] | 0b21fa3ba7755f55f745e4aa970d86343b82449d | https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/reader_text.py#L1192-L1218 | train | 233,807 |
amzn/ion-python | amazon/ion/reader_text.py | _inf_or_operator_handler_factory | def _inf_or_operator_handler_factory(c_start, is_delegate=True):
"""Generates handler co-routines for values that may be `+inf` or `-inf`.
Args:
c_start (int): The ordinal of the character that starts this token (either `+` or `-`).
is_delegate (bool): True if a different handler began processing this token; otherwise, False. This will only
be true for `-inf`, because it is not the only value that can start with `-`; `+inf` is the only value
(outside of a s-expression) that can start with `+`.
"""
@coroutine
def inf_or_operator_handler(c, ctx):
next_ctx = None
if not is_delegate:
ctx.value.append(c_start)
c, self = yield
else:
assert ctx.value[0] == c_start
assert c not in _DIGITS
ctx.queue.unread(c)
next_ctx = ctx
_, self = yield
assert c == _
maybe_inf = True
ctx.set_ion_type(IonType.FLOAT)
match_index = 0
trans = ctx.immediate_transition(self)
while True:
if maybe_inf:
if match_index < len(_INF_SUFFIX):
maybe_inf = c == _INF_SUFFIX[match_index]
else:
if _ends_value(c) or (ctx.container.ion_type is IonType.SEXP and c in _OPERATORS):
yield ctx.event_transition(
IonEvent, IonEventType.SCALAR, IonType.FLOAT, c_start == _MINUS and _NEG_INF or _POS_INF
)
else:
maybe_inf = False
if maybe_inf:
match_index += 1
else:
ctx.set_unicode()
if match_index > 0:
next_ctx = ctx.derive_child_context(ctx.whence)
for ch in _INF_SUFFIX[0:match_index]:
next_ctx.value.append(ch)
break
c, self = yield trans
if ctx.container is not _C_SEXP:
_illegal_character(c, next_ctx is None and ctx or next_ctx,
'Illegal character following %s.' % (_chr(c_start),))
if match_index == 0:
if c in _OPERATORS:
yield ctx.immediate_transition(_operator_symbol_handler(c, ctx))
yield ctx.event_transition(IonEvent, IonEventType.SCALAR, IonType.SYMBOL, ctx.value.as_symbol())
yield _CompositeTransition(
ctx.event_transition(IonEvent, IonEventType.SCALAR, IonType.SYMBOL, ctx.value.as_symbol()),
ctx,
partial(_unquoted_symbol_handler, c),
next_ctx
)
return inf_or_operator_handler | python | def _inf_or_operator_handler_factory(c_start, is_delegate=True):
"""Generates handler co-routines for values that may be `+inf` or `-inf`.
Args:
c_start (int): The ordinal of the character that starts this token (either `+` or `-`).
is_delegate (bool): True if a different handler began processing this token; otherwise, False. This will only
be true for `-inf`, because it is not the only value that can start with `-`; `+inf` is the only value
(outside of a s-expression) that can start with `+`.
"""
@coroutine
def inf_or_operator_handler(c, ctx):
next_ctx = None
if not is_delegate:
ctx.value.append(c_start)
c, self = yield
else:
assert ctx.value[0] == c_start
assert c not in _DIGITS
ctx.queue.unread(c)
next_ctx = ctx
_, self = yield
assert c == _
maybe_inf = True
ctx.set_ion_type(IonType.FLOAT)
match_index = 0
trans = ctx.immediate_transition(self)
while True:
if maybe_inf:
if match_index < len(_INF_SUFFIX):
maybe_inf = c == _INF_SUFFIX[match_index]
else:
if _ends_value(c) or (ctx.container.ion_type is IonType.SEXP and c in _OPERATORS):
yield ctx.event_transition(
IonEvent, IonEventType.SCALAR, IonType.FLOAT, c_start == _MINUS and _NEG_INF or _POS_INF
)
else:
maybe_inf = False
if maybe_inf:
match_index += 1
else:
ctx.set_unicode()
if match_index > 0:
next_ctx = ctx.derive_child_context(ctx.whence)
for ch in _INF_SUFFIX[0:match_index]:
next_ctx.value.append(ch)
break
c, self = yield trans
if ctx.container is not _C_SEXP:
_illegal_character(c, next_ctx is None and ctx or next_ctx,
'Illegal character following %s.' % (_chr(c_start),))
if match_index == 0:
if c in _OPERATORS:
yield ctx.immediate_transition(_operator_symbol_handler(c, ctx))
yield ctx.event_transition(IonEvent, IonEventType.SCALAR, IonType.SYMBOL, ctx.value.as_symbol())
yield _CompositeTransition(
ctx.event_transition(IonEvent, IonEventType.SCALAR, IonType.SYMBOL, ctx.value.as_symbol()),
ctx,
partial(_unquoted_symbol_handler, c),
next_ctx
)
return inf_or_operator_handler | [
"def",
"_inf_or_operator_handler_factory",
"(",
"c_start",
",",
"is_delegate",
"=",
"True",
")",
":",
"@",
"coroutine",
"def",
"inf_or_operator_handler",
"(",
"c",
",",
"ctx",
")",
":",
"next_ctx",
"=",
"None",
"if",
"not",
"is_delegate",
":",
"ctx",
".",
"value",
".",
"append",
"(",
"c_start",
")",
"c",
",",
"self",
"=",
"yield",
"else",
":",
"assert",
"ctx",
".",
"value",
"[",
"0",
"]",
"==",
"c_start",
"assert",
"c",
"not",
"in",
"_DIGITS",
"ctx",
".",
"queue",
".",
"unread",
"(",
"c",
")",
"next_ctx",
"=",
"ctx",
"_",
",",
"self",
"=",
"yield",
"assert",
"c",
"==",
"_",
"maybe_inf",
"=",
"True",
"ctx",
".",
"set_ion_type",
"(",
"IonType",
".",
"FLOAT",
")",
"match_index",
"=",
"0",
"trans",
"=",
"ctx",
".",
"immediate_transition",
"(",
"self",
")",
"while",
"True",
":",
"if",
"maybe_inf",
":",
"if",
"match_index",
"<",
"len",
"(",
"_INF_SUFFIX",
")",
":",
"maybe_inf",
"=",
"c",
"==",
"_INF_SUFFIX",
"[",
"match_index",
"]",
"else",
":",
"if",
"_ends_value",
"(",
"c",
")",
"or",
"(",
"ctx",
".",
"container",
".",
"ion_type",
"is",
"IonType",
".",
"SEXP",
"and",
"c",
"in",
"_OPERATORS",
")",
":",
"yield",
"ctx",
".",
"event_transition",
"(",
"IonEvent",
",",
"IonEventType",
".",
"SCALAR",
",",
"IonType",
".",
"FLOAT",
",",
"c_start",
"==",
"_MINUS",
"and",
"_NEG_INF",
"or",
"_POS_INF",
")",
"else",
":",
"maybe_inf",
"=",
"False",
"if",
"maybe_inf",
":",
"match_index",
"+=",
"1",
"else",
":",
"ctx",
".",
"set_unicode",
"(",
")",
"if",
"match_index",
">",
"0",
":",
"next_ctx",
"=",
"ctx",
".",
"derive_child_context",
"(",
"ctx",
".",
"whence",
")",
"for",
"ch",
"in",
"_INF_SUFFIX",
"[",
"0",
":",
"match_index",
"]",
":",
"next_ctx",
".",
"value",
".",
"append",
"(",
"ch",
")",
"break",
"c",
",",
"self",
"=",
"yield",
"trans",
"if",
"ctx",
".",
"container",
"is",
"not",
"_C_SEXP",
":",
"_illegal_character",
"(",
"c",
",",
"next_ctx",
"is",
"None",
"and",
"ctx",
"or",
"next_ctx",
",",
"'Illegal character following %s.'",
"%",
"(",
"_chr",
"(",
"c_start",
")",
",",
")",
")",
"if",
"match_index",
"==",
"0",
":",
"if",
"c",
"in",
"_OPERATORS",
":",
"yield",
"ctx",
".",
"immediate_transition",
"(",
"_operator_symbol_handler",
"(",
"c",
",",
"ctx",
")",
")",
"yield",
"ctx",
".",
"event_transition",
"(",
"IonEvent",
",",
"IonEventType",
".",
"SCALAR",
",",
"IonType",
".",
"SYMBOL",
",",
"ctx",
".",
"value",
".",
"as_symbol",
"(",
")",
")",
"yield",
"_CompositeTransition",
"(",
"ctx",
".",
"event_transition",
"(",
"IonEvent",
",",
"IonEventType",
".",
"SCALAR",
",",
"IonType",
".",
"SYMBOL",
",",
"ctx",
".",
"value",
".",
"as_symbol",
"(",
")",
")",
",",
"ctx",
",",
"partial",
"(",
"_unquoted_symbol_handler",
",",
"c",
")",
",",
"next_ctx",
")",
"return",
"inf_or_operator_handler"
] | Generates handler co-routines for values that may be `+inf` or `-inf`.
Args:
c_start (int): The ordinal of the character that starts this token (either `+` or `-`).
is_delegate (bool): True if a different handler began processing this token; otherwise, False. This will only
be true for `-inf`, because it is not the only value that can start with `-`; `+inf` is the only value
(outside of a s-expression) that can start with `+`. | [
"Generates",
"handler",
"co",
"-",
"routines",
"for",
"values",
"that",
"may",
"be",
"+",
"inf",
"or",
"-",
"inf",
"."
] | 0b21fa3ba7755f55f745e4aa970d86343b82449d | https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/reader_text.py#L1305-L1365 | train | 233,808 |
amzn/ion-python | amazon/ion/reader_text.py | _operator_symbol_handler | def _operator_symbol_handler(c, ctx):
"""Handles operator symbol values within s-expressions."""
assert c in _OPERATORS
ctx.set_unicode()
val = ctx.value
val.append(c)
c, self = yield
trans = ctx.immediate_transition(self)
while c in _OPERATORS:
val.append(c)
c, _ = yield trans
yield ctx.event_transition(IonEvent, IonEventType.SCALAR, IonType.SYMBOL, val.as_symbol()) | python | def _operator_symbol_handler(c, ctx):
"""Handles operator symbol values within s-expressions."""
assert c in _OPERATORS
ctx.set_unicode()
val = ctx.value
val.append(c)
c, self = yield
trans = ctx.immediate_transition(self)
while c in _OPERATORS:
val.append(c)
c, _ = yield trans
yield ctx.event_transition(IonEvent, IonEventType.SCALAR, IonType.SYMBOL, val.as_symbol()) | [
"def",
"_operator_symbol_handler",
"(",
"c",
",",
"ctx",
")",
":",
"assert",
"c",
"in",
"_OPERATORS",
"ctx",
".",
"set_unicode",
"(",
")",
"val",
"=",
"ctx",
".",
"value",
"val",
".",
"append",
"(",
"c",
")",
"c",
",",
"self",
"=",
"yield",
"trans",
"=",
"ctx",
".",
"immediate_transition",
"(",
"self",
")",
"while",
"c",
"in",
"_OPERATORS",
":",
"val",
".",
"append",
"(",
"c",
")",
"c",
",",
"_",
"=",
"yield",
"trans",
"yield",
"ctx",
".",
"event_transition",
"(",
"IonEvent",
",",
"IonEventType",
".",
"SCALAR",
",",
"IonType",
".",
"SYMBOL",
",",
"val",
".",
"as_symbol",
"(",
")",
")"
] | Handles operator symbol values within s-expressions. | [
"Handles",
"operator",
"symbol",
"values",
"within",
"s",
"-",
"expressions",
"."
] | 0b21fa3ba7755f55f745e4aa970d86343b82449d | https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/reader_text.py#L1373-L1384 | train | 233,809 |
amzn/ion-python | amazon/ion/reader_text.py | _symbol_token_end | def _symbol_token_end(c, ctx, is_field_name, value=None):
"""Returns a transition which ends the current symbol token."""
if value is None:
value = ctx.value
if is_field_name or c in _SYMBOL_TOKEN_TERMINATORS or ctx.quoted_text:
# This might be an annotation or a field name. Mark it as self-delimiting because a symbol token termination
# character has been found.
ctx.set_self_delimiting(ctx.quoted_text).set_pending_symbol(value).set_quoted_text(False)
trans = ctx.immediate_transition(ctx.whence)
else:
trans = ctx.event_transition(IonEvent, IonEventType.SCALAR, IonType.SYMBOL, _as_symbol(value))
return trans | python | def _symbol_token_end(c, ctx, is_field_name, value=None):
"""Returns a transition which ends the current symbol token."""
if value is None:
value = ctx.value
if is_field_name or c in _SYMBOL_TOKEN_TERMINATORS or ctx.quoted_text:
# This might be an annotation or a field name. Mark it as self-delimiting because a symbol token termination
# character has been found.
ctx.set_self_delimiting(ctx.quoted_text).set_pending_symbol(value).set_quoted_text(False)
trans = ctx.immediate_transition(ctx.whence)
else:
trans = ctx.event_transition(IonEvent, IonEventType.SCALAR, IonType.SYMBOL, _as_symbol(value))
return trans | [
"def",
"_symbol_token_end",
"(",
"c",
",",
"ctx",
",",
"is_field_name",
",",
"value",
"=",
"None",
")",
":",
"if",
"value",
"is",
"None",
":",
"value",
"=",
"ctx",
".",
"value",
"if",
"is_field_name",
"or",
"c",
"in",
"_SYMBOL_TOKEN_TERMINATORS",
"or",
"ctx",
".",
"quoted_text",
":",
"# This might be an annotation or a field name. Mark it as self-delimiting because a symbol token termination",
"# character has been found.",
"ctx",
".",
"set_self_delimiting",
"(",
"ctx",
".",
"quoted_text",
")",
".",
"set_pending_symbol",
"(",
"value",
")",
".",
"set_quoted_text",
"(",
"False",
")",
"trans",
"=",
"ctx",
".",
"immediate_transition",
"(",
"ctx",
".",
"whence",
")",
"else",
":",
"trans",
"=",
"ctx",
".",
"event_transition",
"(",
"IonEvent",
",",
"IonEventType",
".",
"SCALAR",
",",
"IonType",
".",
"SYMBOL",
",",
"_as_symbol",
"(",
"value",
")",
")",
"return",
"trans"
] | Returns a transition which ends the current symbol token. | [
"Returns",
"a",
"transition",
"which",
"ends",
"the",
"current",
"symbol",
"token",
"."
] | 0b21fa3ba7755f55f745e4aa970d86343b82449d | https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/reader_text.py#L1387-L1398 | train | 233,810 |
amzn/ion-python | amazon/ion/reader_text.py | _unquoted_symbol_handler | def _unquoted_symbol_handler(c, ctx, is_field_name=False):
"""Handles identifier symbol tokens. If in an s-expression, these may be followed without whitespace by
operators.
"""
in_sexp = ctx.container.ion_type is IonType.SEXP
ctx.set_unicode()
if c not in _IDENTIFIER_CHARACTERS:
if in_sexp and c in _OPERATORS:
c_next, _ = yield
ctx.queue.unread(c_next)
assert ctx.value
yield _CompositeTransition(
ctx.event_transition(IonEvent, IonEventType.SCALAR, IonType.SYMBOL, ctx.value.as_symbol()),
ctx,
partial(_operator_symbol_handler, c)
)
_illegal_character(c, ctx.set_ion_type(IonType.SYMBOL))
val = ctx.value
val.append(c)
prev = c
c, self = yield
trans = ctx.immediate_transition(self)
while True:
if c not in _WHITESPACE:
if prev in _WHITESPACE or _ends_value(c) or c == _COLON or (in_sexp and c in _OPERATORS):
break
if c not in _IDENTIFIER_CHARACTERS:
_illegal_character(c, ctx.set_ion_type(IonType.SYMBOL))
val.append(c)
prev = c
c, _ = yield trans
yield _symbol_token_end(c, ctx, is_field_name) | python | def _unquoted_symbol_handler(c, ctx, is_field_name=False):
"""Handles identifier symbol tokens. If in an s-expression, these may be followed without whitespace by
operators.
"""
in_sexp = ctx.container.ion_type is IonType.SEXP
ctx.set_unicode()
if c not in _IDENTIFIER_CHARACTERS:
if in_sexp and c in _OPERATORS:
c_next, _ = yield
ctx.queue.unread(c_next)
assert ctx.value
yield _CompositeTransition(
ctx.event_transition(IonEvent, IonEventType.SCALAR, IonType.SYMBOL, ctx.value.as_symbol()),
ctx,
partial(_operator_symbol_handler, c)
)
_illegal_character(c, ctx.set_ion_type(IonType.SYMBOL))
val = ctx.value
val.append(c)
prev = c
c, self = yield
trans = ctx.immediate_transition(self)
while True:
if c not in _WHITESPACE:
if prev in _WHITESPACE or _ends_value(c) or c == _COLON or (in_sexp and c in _OPERATORS):
break
if c not in _IDENTIFIER_CHARACTERS:
_illegal_character(c, ctx.set_ion_type(IonType.SYMBOL))
val.append(c)
prev = c
c, _ = yield trans
yield _symbol_token_end(c, ctx, is_field_name) | [
"def",
"_unquoted_symbol_handler",
"(",
"c",
",",
"ctx",
",",
"is_field_name",
"=",
"False",
")",
":",
"in_sexp",
"=",
"ctx",
".",
"container",
".",
"ion_type",
"is",
"IonType",
".",
"SEXP",
"ctx",
".",
"set_unicode",
"(",
")",
"if",
"c",
"not",
"in",
"_IDENTIFIER_CHARACTERS",
":",
"if",
"in_sexp",
"and",
"c",
"in",
"_OPERATORS",
":",
"c_next",
",",
"_",
"=",
"yield",
"ctx",
".",
"queue",
".",
"unread",
"(",
"c_next",
")",
"assert",
"ctx",
".",
"value",
"yield",
"_CompositeTransition",
"(",
"ctx",
".",
"event_transition",
"(",
"IonEvent",
",",
"IonEventType",
".",
"SCALAR",
",",
"IonType",
".",
"SYMBOL",
",",
"ctx",
".",
"value",
".",
"as_symbol",
"(",
")",
")",
",",
"ctx",
",",
"partial",
"(",
"_operator_symbol_handler",
",",
"c",
")",
")",
"_illegal_character",
"(",
"c",
",",
"ctx",
".",
"set_ion_type",
"(",
"IonType",
".",
"SYMBOL",
")",
")",
"val",
"=",
"ctx",
".",
"value",
"val",
".",
"append",
"(",
"c",
")",
"prev",
"=",
"c",
"c",
",",
"self",
"=",
"yield",
"trans",
"=",
"ctx",
".",
"immediate_transition",
"(",
"self",
")",
"while",
"True",
":",
"if",
"c",
"not",
"in",
"_WHITESPACE",
":",
"if",
"prev",
"in",
"_WHITESPACE",
"or",
"_ends_value",
"(",
"c",
")",
"or",
"c",
"==",
"_COLON",
"or",
"(",
"in_sexp",
"and",
"c",
"in",
"_OPERATORS",
")",
":",
"break",
"if",
"c",
"not",
"in",
"_IDENTIFIER_CHARACTERS",
":",
"_illegal_character",
"(",
"c",
",",
"ctx",
".",
"set_ion_type",
"(",
"IonType",
".",
"SYMBOL",
")",
")",
"val",
".",
"append",
"(",
"c",
")",
"prev",
"=",
"c",
"c",
",",
"_",
"=",
"yield",
"trans",
"yield",
"_symbol_token_end",
"(",
"c",
",",
"ctx",
",",
"is_field_name",
")"
] | Handles identifier symbol tokens. If in an s-expression, these may be followed without whitespace by
operators. | [
"Handles",
"identifier",
"symbol",
"tokens",
".",
"If",
"in",
"an",
"s",
"-",
"expression",
"these",
"may",
"be",
"followed",
"without",
"whitespace",
"by",
"operators",
"."
] | 0b21fa3ba7755f55f745e4aa970d86343b82449d | https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/reader_text.py#L1402-L1433 | train | 233,811 |
amzn/ion-python | amazon/ion/reader_text.py | _single_quote_handler_factory | def _single_quote_handler_factory(on_single_quote, on_other):
"""Generates handlers used for classifying tokens that begin with one or more single quotes.
Args:
on_single_quote (callable): Called when another single quote is found. Accepts the current character's ordinal,
the current context, and True if the token is a field name; returns a Transition.
on_other (callable): Called when any character other than a single quote is found. Accepts the current
character's ordinal, the current context, and True if the token is a field name; returns a Transition.
"""
@coroutine
def single_quote_handler(c, ctx, is_field_name=False):
assert c == _SINGLE_QUOTE
c, self = yield
if c == _SINGLE_QUOTE and not _is_escaped(c):
yield on_single_quote(c, ctx, is_field_name)
else:
ctx.set_unicode(quoted_text=True)
yield on_other(c, ctx, is_field_name)
return single_quote_handler | python | def _single_quote_handler_factory(on_single_quote, on_other):
"""Generates handlers used for classifying tokens that begin with one or more single quotes.
Args:
on_single_quote (callable): Called when another single quote is found. Accepts the current character's ordinal,
the current context, and True if the token is a field name; returns a Transition.
on_other (callable): Called when any character other than a single quote is found. Accepts the current
character's ordinal, the current context, and True if the token is a field name; returns a Transition.
"""
@coroutine
def single_quote_handler(c, ctx, is_field_name=False):
assert c == _SINGLE_QUOTE
c, self = yield
if c == _SINGLE_QUOTE and not _is_escaped(c):
yield on_single_quote(c, ctx, is_field_name)
else:
ctx.set_unicode(quoted_text=True)
yield on_other(c, ctx, is_field_name)
return single_quote_handler | [
"def",
"_single_quote_handler_factory",
"(",
"on_single_quote",
",",
"on_other",
")",
":",
"@",
"coroutine",
"def",
"single_quote_handler",
"(",
"c",
",",
"ctx",
",",
"is_field_name",
"=",
"False",
")",
":",
"assert",
"c",
"==",
"_SINGLE_QUOTE",
"c",
",",
"self",
"=",
"yield",
"if",
"c",
"==",
"_SINGLE_QUOTE",
"and",
"not",
"_is_escaped",
"(",
"c",
")",
":",
"yield",
"on_single_quote",
"(",
"c",
",",
"ctx",
",",
"is_field_name",
")",
"else",
":",
"ctx",
".",
"set_unicode",
"(",
"quoted_text",
"=",
"True",
")",
"yield",
"on_other",
"(",
"c",
",",
"ctx",
",",
"is_field_name",
")",
"return",
"single_quote_handler"
] | Generates handlers used for classifying tokens that begin with one or more single quotes.
Args:
on_single_quote (callable): Called when another single quote is found. Accepts the current character's ordinal,
the current context, and True if the token is a field name; returns a Transition.
on_other (callable): Called when any character other than a single quote is found. Accepts the current
character's ordinal, the current context, and True if the token is a field name; returns a Transition. | [
"Generates",
"handlers",
"used",
"for",
"classifying",
"tokens",
"that",
"begin",
"with",
"one",
"or",
"more",
"single",
"quotes",
"."
] | 0b21fa3ba7755f55f745e4aa970d86343b82449d | https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/reader_text.py#L1615-L1633 | train | 233,812 |
amzn/ion-python | amazon/ion/reader_text.py | _struct_or_lob_handler | def _struct_or_lob_handler(c, ctx):
"""Handles tokens that begin with an open brace."""
assert c == _OPEN_BRACE
c, self = yield
yield ctx.immediate_transition(_STRUCT_OR_LOB_TABLE[c](c, ctx)) | python | def _struct_or_lob_handler(c, ctx):
"""Handles tokens that begin with an open brace."""
assert c == _OPEN_BRACE
c, self = yield
yield ctx.immediate_transition(_STRUCT_OR_LOB_TABLE[c](c, ctx)) | [
"def",
"_struct_or_lob_handler",
"(",
"c",
",",
"ctx",
")",
":",
"assert",
"c",
"==",
"_OPEN_BRACE",
"c",
",",
"self",
"=",
"yield",
"yield",
"ctx",
".",
"immediate_transition",
"(",
"_STRUCT_OR_LOB_TABLE",
"[",
"c",
"]",
"(",
"c",
",",
"ctx",
")",
")"
] | Handles tokens that begin with an open brace. | [
"Handles",
"tokens",
"that",
"begin",
"with",
"an",
"open",
"brace",
"."
] | 0b21fa3ba7755f55f745e4aa970d86343b82449d | https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/reader_text.py#L1651-L1655 | train | 233,813 |
amzn/ion-python | amazon/ion/reader_text.py | _lob_start_handler | def _lob_start_handler(c, ctx):
"""Handles tokens that begin with two open braces."""
assert c == _OPEN_BRACE
c, self = yield
trans = ctx.immediate_transition(self)
quotes = 0
while True:
if c in _WHITESPACE:
if quotes > 0:
_illegal_character(c, ctx)
elif c == _DOUBLE_QUOTE:
if quotes > 0:
_illegal_character(c, ctx)
ctx.set_ion_type(IonType.CLOB).set_unicode(quoted_text=True)
yield ctx.immediate_transition(_short_string_handler(c, ctx))
elif c == _SINGLE_QUOTE:
if not quotes:
ctx.set_ion_type(IonType.CLOB).set_unicode(quoted_text=True)
quotes += 1
if quotes == 3:
yield ctx.immediate_transition(_long_string_handler(c, ctx))
else:
yield ctx.immediate_transition(_blob_end_handler(c, ctx))
c, _ = yield trans | python | def _lob_start_handler(c, ctx):
"""Handles tokens that begin with two open braces."""
assert c == _OPEN_BRACE
c, self = yield
trans = ctx.immediate_transition(self)
quotes = 0
while True:
if c in _WHITESPACE:
if quotes > 0:
_illegal_character(c, ctx)
elif c == _DOUBLE_QUOTE:
if quotes > 0:
_illegal_character(c, ctx)
ctx.set_ion_type(IonType.CLOB).set_unicode(quoted_text=True)
yield ctx.immediate_transition(_short_string_handler(c, ctx))
elif c == _SINGLE_QUOTE:
if not quotes:
ctx.set_ion_type(IonType.CLOB).set_unicode(quoted_text=True)
quotes += 1
if quotes == 3:
yield ctx.immediate_transition(_long_string_handler(c, ctx))
else:
yield ctx.immediate_transition(_blob_end_handler(c, ctx))
c, _ = yield trans | [
"def",
"_lob_start_handler",
"(",
"c",
",",
"ctx",
")",
":",
"assert",
"c",
"==",
"_OPEN_BRACE",
"c",
",",
"self",
"=",
"yield",
"trans",
"=",
"ctx",
".",
"immediate_transition",
"(",
"self",
")",
"quotes",
"=",
"0",
"while",
"True",
":",
"if",
"c",
"in",
"_WHITESPACE",
":",
"if",
"quotes",
">",
"0",
":",
"_illegal_character",
"(",
"c",
",",
"ctx",
")",
"elif",
"c",
"==",
"_DOUBLE_QUOTE",
":",
"if",
"quotes",
">",
"0",
":",
"_illegal_character",
"(",
"c",
",",
"ctx",
")",
"ctx",
".",
"set_ion_type",
"(",
"IonType",
".",
"CLOB",
")",
".",
"set_unicode",
"(",
"quoted_text",
"=",
"True",
")",
"yield",
"ctx",
".",
"immediate_transition",
"(",
"_short_string_handler",
"(",
"c",
",",
"ctx",
")",
")",
"elif",
"c",
"==",
"_SINGLE_QUOTE",
":",
"if",
"not",
"quotes",
":",
"ctx",
".",
"set_ion_type",
"(",
"IonType",
".",
"CLOB",
")",
".",
"set_unicode",
"(",
"quoted_text",
"=",
"True",
")",
"quotes",
"+=",
"1",
"if",
"quotes",
"==",
"3",
":",
"yield",
"ctx",
".",
"immediate_transition",
"(",
"_long_string_handler",
"(",
"c",
",",
"ctx",
")",
")",
"else",
":",
"yield",
"ctx",
".",
"immediate_transition",
"(",
"_blob_end_handler",
"(",
"c",
",",
"ctx",
")",
")",
"c",
",",
"_",
"=",
"yield",
"trans"
] | Handles tokens that begin with two open braces. | [
"Handles",
"tokens",
"that",
"begin",
"with",
"two",
"open",
"braces",
"."
] | 0b21fa3ba7755f55f745e4aa970d86343b82449d | https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/reader_text.py#L1677-L1700 | train | 233,814 |
amzn/ion-python | amazon/ion/reader_text.py | _lob_end_handler_factory | def _lob_end_handler_factory(ion_type, action, validate=lambda c, ctx, action_res: None):
"""Generates handlers for the end of blob or clob values.
Args:
ion_type (IonType): The type of this lob (either blob or clob).
action (callable): Called for each non-whitespace, non-closing brace character encountered before the end of
the lob. Accepts the current character's ordinal, the current context, the previous character's ordinal,
the result of the previous call to ``action`` (if any), and True if this is the first call to ``action``.
Returns any state that will be needed by subsequent calls to ``action``. For blobs, this should validate
the character is valid base64; for clobs, this should ensure there are no illegal characters (e.g. comments)
between the end of the data and the end of the clob.
validate (Optional[callable]): Called once the second closing brace has been found. Accepts the current
character's ordinal, the current context, and the result of the last call to ``action``; raises an error
if this is not a valid lob value.
"""
assert ion_type is IonType.BLOB or ion_type is IonType.CLOB
@coroutine
def lob_end_handler(c, ctx):
val = ctx.value
prev = c
action_res = None
if c != _CLOSE_BRACE and c not in _WHITESPACE:
action_res = action(c, ctx, prev, action_res, True)
c, self = yield
trans = ctx.immediate_transition(self)
while True:
if c in _WHITESPACE:
if prev == _CLOSE_BRACE:
_illegal_character(c, ctx.set_ion_type(ion_type), 'Expected }.')
elif c == _CLOSE_BRACE:
if prev == _CLOSE_BRACE:
validate(c, ctx, action_res)
break
else:
action_res = action(c, ctx, prev, action_res, False)
prev = c
c, _ = yield trans
ctx.set_self_delimiting(True) # Lob values are self-delimiting (they are terminated by '}}').
yield ctx.event_transition(IonThunkEvent, IonEventType.SCALAR, ion_type, _parse_lob(ion_type, val))
return lob_end_handler | python | def _lob_end_handler_factory(ion_type, action, validate=lambda c, ctx, action_res: None):
"""Generates handlers for the end of blob or clob values.
Args:
ion_type (IonType): The type of this lob (either blob or clob).
action (callable): Called for each non-whitespace, non-closing brace character encountered before the end of
the lob. Accepts the current character's ordinal, the current context, the previous character's ordinal,
the result of the previous call to ``action`` (if any), and True if this is the first call to ``action``.
Returns any state that will be needed by subsequent calls to ``action``. For blobs, this should validate
the character is valid base64; for clobs, this should ensure there are no illegal characters (e.g. comments)
between the end of the data and the end of the clob.
validate (Optional[callable]): Called once the second closing brace has been found. Accepts the current
character's ordinal, the current context, and the result of the last call to ``action``; raises an error
if this is not a valid lob value.
"""
assert ion_type is IonType.BLOB or ion_type is IonType.CLOB
@coroutine
def lob_end_handler(c, ctx):
val = ctx.value
prev = c
action_res = None
if c != _CLOSE_BRACE and c not in _WHITESPACE:
action_res = action(c, ctx, prev, action_res, True)
c, self = yield
trans = ctx.immediate_transition(self)
while True:
if c in _WHITESPACE:
if prev == _CLOSE_BRACE:
_illegal_character(c, ctx.set_ion_type(ion_type), 'Expected }.')
elif c == _CLOSE_BRACE:
if prev == _CLOSE_BRACE:
validate(c, ctx, action_res)
break
else:
action_res = action(c, ctx, prev, action_res, False)
prev = c
c, _ = yield trans
ctx.set_self_delimiting(True) # Lob values are self-delimiting (they are terminated by '}}').
yield ctx.event_transition(IonThunkEvent, IonEventType.SCALAR, ion_type, _parse_lob(ion_type, val))
return lob_end_handler | [
"def",
"_lob_end_handler_factory",
"(",
"ion_type",
",",
"action",
",",
"validate",
"=",
"lambda",
"c",
",",
"ctx",
",",
"action_res",
":",
"None",
")",
":",
"assert",
"ion_type",
"is",
"IonType",
".",
"BLOB",
"or",
"ion_type",
"is",
"IonType",
".",
"CLOB",
"@",
"coroutine",
"def",
"lob_end_handler",
"(",
"c",
",",
"ctx",
")",
":",
"val",
"=",
"ctx",
".",
"value",
"prev",
"=",
"c",
"action_res",
"=",
"None",
"if",
"c",
"!=",
"_CLOSE_BRACE",
"and",
"c",
"not",
"in",
"_WHITESPACE",
":",
"action_res",
"=",
"action",
"(",
"c",
",",
"ctx",
",",
"prev",
",",
"action_res",
",",
"True",
")",
"c",
",",
"self",
"=",
"yield",
"trans",
"=",
"ctx",
".",
"immediate_transition",
"(",
"self",
")",
"while",
"True",
":",
"if",
"c",
"in",
"_WHITESPACE",
":",
"if",
"prev",
"==",
"_CLOSE_BRACE",
":",
"_illegal_character",
"(",
"c",
",",
"ctx",
".",
"set_ion_type",
"(",
"ion_type",
")",
",",
"'Expected }.'",
")",
"elif",
"c",
"==",
"_CLOSE_BRACE",
":",
"if",
"prev",
"==",
"_CLOSE_BRACE",
":",
"validate",
"(",
"c",
",",
"ctx",
",",
"action_res",
")",
"break",
"else",
":",
"action_res",
"=",
"action",
"(",
"c",
",",
"ctx",
",",
"prev",
",",
"action_res",
",",
"False",
")",
"prev",
"=",
"c",
"c",
",",
"_",
"=",
"yield",
"trans",
"ctx",
".",
"set_self_delimiting",
"(",
"True",
")",
"# Lob values are self-delimiting (they are terminated by '}}').",
"yield",
"ctx",
".",
"event_transition",
"(",
"IonThunkEvent",
",",
"IonEventType",
".",
"SCALAR",
",",
"ion_type",
",",
"_parse_lob",
"(",
"ion_type",
",",
"val",
")",
")",
"return",
"lob_end_handler"
] | Generates handlers for the end of blob or clob values.
Args:
ion_type (IonType): The type of this lob (either blob or clob).
action (callable): Called for each non-whitespace, non-closing brace character encountered before the end of
the lob. Accepts the current character's ordinal, the current context, the previous character's ordinal,
the result of the previous call to ``action`` (if any), and True if this is the first call to ``action``.
Returns any state that will be needed by subsequent calls to ``action``. For blobs, this should validate
the character is valid base64; for clobs, this should ensure there are no illegal characters (e.g. comments)
between the end of the data and the end of the clob.
validate (Optional[callable]): Called once the second closing brace has been found. Accepts the current
character's ordinal, the current context, and the result of the last call to ``action``; raises an error
if this is not a valid lob value. | [
"Generates",
"handlers",
"for",
"the",
"end",
"of",
"blob",
"or",
"clob",
"values",
"."
] | 0b21fa3ba7755f55f745e4aa970d86343b82449d | https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/reader_text.py#L1703-L1743 | train | 233,815 |
amzn/ion-python | amazon/ion/reader_text.py | _blob_end_handler_factory | def _blob_end_handler_factory():
"""Generates the handler for the end of a blob value. This includes the base-64 data and the two closing braces."""
def expand_res(res):
if res is None:
return 0, 0
return res
def action(c, ctx, prev, res, is_first):
num_digits, num_pads = expand_res(res)
if c in _BASE64_DIGITS:
if prev == _CLOSE_BRACE or prev == _BASE64_PAD:
_illegal_character(c, ctx.set_ion_type(IonType.BLOB))
num_digits += 1
elif c == _BASE64_PAD:
if prev == _CLOSE_BRACE:
_illegal_character(c, ctx.set_ion_type(IonType.BLOB))
num_pads += 1
else:
_illegal_character(c, ctx.set_ion_type(IonType.BLOB))
ctx.value.append(c)
return num_digits, num_pads
def validate(c, ctx, res):
num_digits, num_pads = expand_res(res)
if num_pads > 3 or (num_digits + num_pads) % 4 != 0:
_illegal_character(c, ctx, 'Incorrect number of pad characters (%d) for a blob of %d base-64 digits.'
% (num_pads, num_digits))
return _lob_end_handler_factory(IonType.BLOB, action, validate) | python | def _blob_end_handler_factory():
"""Generates the handler for the end of a blob value. This includes the base-64 data and the two closing braces."""
def expand_res(res):
if res is None:
return 0, 0
return res
def action(c, ctx, prev, res, is_first):
num_digits, num_pads = expand_res(res)
if c in _BASE64_DIGITS:
if prev == _CLOSE_BRACE or prev == _BASE64_PAD:
_illegal_character(c, ctx.set_ion_type(IonType.BLOB))
num_digits += 1
elif c == _BASE64_PAD:
if prev == _CLOSE_BRACE:
_illegal_character(c, ctx.set_ion_type(IonType.BLOB))
num_pads += 1
else:
_illegal_character(c, ctx.set_ion_type(IonType.BLOB))
ctx.value.append(c)
return num_digits, num_pads
def validate(c, ctx, res):
num_digits, num_pads = expand_res(res)
if num_pads > 3 or (num_digits + num_pads) % 4 != 0:
_illegal_character(c, ctx, 'Incorrect number of pad characters (%d) for a blob of %d base-64 digits.'
% (num_pads, num_digits))
return _lob_end_handler_factory(IonType.BLOB, action, validate) | [
"def",
"_blob_end_handler_factory",
"(",
")",
":",
"def",
"expand_res",
"(",
"res",
")",
":",
"if",
"res",
"is",
"None",
":",
"return",
"0",
",",
"0",
"return",
"res",
"def",
"action",
"(",
"c",
",",
"ctx",
",",
"prev",
",",
"res",
",",
"is_first",
")",
":",
"num_digits",
",",
"num_pads",
"=",
"expand_res",
"(",
"res",
")",
"if",
"c",
"in",
"_BASE64_DIGITS",
":",
"if",
"prev",
"==",
"_CLOSE_BRACE",
"or",
"prev",
"==",
"_BASE64_PAD",
":",
"_illegal_character",
"(",
"c",
",",
"ctx",
".",
"set_ion_type",
"(",
"IonType",
".",
"BLOB",
")",
")",
"num_digits",
"+=",
"1",
"elif",
"c",
"==",
"_BASE64_PAD",
":",
"if",
"prev",
"==",
"_CLOSE_BRACE",
":",
"_illegal_character",
"(",
"c",
",",
"ctx",
".",
"set_ion_type",
"(",
"IonType",
".",
"BLOB",
")",
")",
"num_pads",
"+=",
"1",
"else",
":",
"_illegal_character",
"(",
"c",
",",
"ctx",
".",
"set_ion_type",
"(",
"IonType",
".",
"BLOB",
")",
")",
"ctx",
".",
"value",
".",
"append",
"(",
"c",
")",
"return",
"num_digits",
",",
"num_pads",
"def",
"validate",
"(",
"c",
",",
"ctx",
",",
"res",
")",
":",
"num_digits",
",",
"num_pads",
"=",
"expand_res",
"(",
"res",
")",
"if",
"num_pads",
">",
"3",
"or",
"(",
"num_digits",
"+",
"num_pads",
")",
"%",
"4",
"!=",
"0",
":",
"_illegal_character",
"(",
"c",
",",
"ctx",
",",
"'Incorrect number of pad characters (%d) for a blob of %d base-64 digits.'",
"%",
"(",
"num_pads",
",",
"num_digits",
")",
")",
"return",
"_lob_end_handler_factory",
"(",
"IonType",
".",
"BLOB",
",",
"action",
",",
"validate",
")"
] | Generates the handler for the end of a blob value. This includes the base-64 data and the two closing braces. | [
"Generates",
"the",
"handler",
"for",
"the",
"end",
"of",
"a",
"blob",
"value",
".",
"This",
"includes",
"the",
"base",
"-",
"64",
"data",
"and",
"the",
"two",
"closing",
"braces",
"."
] | 0b21fa3ba7755f55f745e4aa970d86343b82449d | https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/reader_text.py#L1746-L1774 | train | 233,816 |
amzn/ion-python | amazon/ion/reader_text.py | _clob_end_handler_factory | def _clob_end_handler_factory():
"""Generates the handler for the end of a clob value. This includes anything from the data's closing quote through
the second closing brace.
"""
def action(c, ctx, prev, res, is_first):
if is_first and ctx.is_self_delimiting and c == _DOUBLE_QUOTE:
assert c is prev
return res
_illegal_character(c, ctx)
return _lob_end_handler_factory(IonType.CLOB, action) | python | def _clob_end_handler_factory():
"""Generates the handler for the end of a clob value. This includes anything from the data's closing quote through
the second closing brace.
"""
def action(c, ctx, prev, res, is_first):
if is_first and ctx.is_self_delimiting and c == _DOUBLE_QUOTE:
assert c is prev
return res
_illegal_character(c, ctx)
return _lob_end_handler_factory(IonType.CLOB, action) | [
"def",
"_clob_end_handler_factory",
"(",
")",
":",
"def",
"action",
"(",
"c",
",",
"ctx",
",",
"prev",
",",
"res",
",",
"is_first",
")",
":",
"if",
"is_first",
"and",
"ctx",
".",
"is_self_delimiting",
"and",
"c",
"==",
"_DOUBLE_QUOTE",
":",
"assert",
"c",
"is",
"prev",
"return",
"res",
"_illegal_character",
"(",
"c",
",",
"ctx",
")",
"return",
"_lob_end_handler_factory",
"(",
"IonType",
".",
"CLOB",
",",
"action",
")"
] | Generates the handler for the end of a clob value. This includes anything from the data's closing quote through
the second closing brace. | [
"Generates",
"the",
"handler",
"for",
"the",
"end",
"of",
"a",
"clob",
"value",
".",
"This",
"includes",
"anything",
"from",
"the",
"data",
"s",
"closing",
"quote",
"through",
"the",
"second",
"closing",
"brace",
"."
] | 0b21fa3ba7755f55f745e4aa970d86343b82449d | https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/reader_text.py#L1779-L1789 | train | 233,817 |
amzn/ion-python | amazon/ion/reader_text.py | _container_start_handler_factory | def _container_start_handler_factory(ion_type, before_yield=lambda c, ctx: None):
"""Generates handlers for tokens that begin with container start characters.
Args:
ion_type (IonType): The type of this container.
before_yield (Optional[callable]): Called at initialization. Accepts the first character's ordinal and the
current context; performs any necessary initialization actions.
"""
assert ion_type.is_container
@coroutine
def container_start_handler(c, ctx):
before_yield(c, ctx)
yield
yield ctx.event_transition(IonEvent, IonEventType.CONTAINER_START, ion_type, value=None)
return container_start_handler | python | def _container_start_handler_factory(ion_type, before_yield=lambda c, ctx: None):
"""Generates handlers for tokens that begin with container start characters.
Args:
ion_type (IonType): The type of this container.
before_yield (Optional[callable]): Called at initialization. Accepts the first character's ordinal and the
current context; performs any necessary initialization actions.
"""
assert ion_type.is_container
@coroutine
def container_start_handler(c, ctx):
before_yield(c, ctx)
yield
yield ctx.event_transition(IonEvent, IonEventType.CONTAINER_START, ion_type, value=None)
return container_start_handler | [
"def",
"_container_start_handler_factory",
"(",
"ion_type",
",",
"before_yield",
"=",
"lambda",
"c",
",",
"ctx",
":",
"None",
")",
":",
"assert",
"ion_type",
".",
"is_container",
"@",
"coroutine",
"def",
"container_start_handler",
"(",
"c",
",",
"ctx",
")",
":",
"before_yield",
"(",
"c",
",",
"ctx",
")",
"yield",
"yield",
"ctx",
".",
"event_transition",
"(",
"IonEvent",
",",
"IonEventType",
".",
"CONTAINER_START",
",",
"ion_type",
",",
"value",
"=",
"None",
")",
"return",
"container_start_handler"
] | Generates handlers for tokens that begin with container start characters.
Args:
ion_type (IonType): The type of this container.
before_yield (Optional[callable]): Called at initialization. Accepts the first character's ordinal and the
current context; performs any necessary initialization actions. | [
"Generates",
"handlers",
"for",
"tokens",
"that",
"begin",
"with",
"container",
"start",
"characters",
"."
] | 0b21fa3ba7755f55f745e4aa970d86343b82449d | https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/reader_text.py#L1801-L1816 | train | 233,818 |
amzn/ion-python | amazon/ion/reader_text.py | _skip_trampoline | def _skip_trampoline(handler):
"""Intercepts events from container handlers, emitting them only if they should not be skipped."""
data_event, self = (yield None)
delegate = handler
event = None
depth = 0
while True:
def pass_through():
_trans = delegate.send(Transition(data_event, delegate))
return _trans, _trans.delegate, _trans.event
if data_event is not None and data_event.type is ReadEventType.SKIP:
while True:
trans, delegate, event = pass_through()
if event is not None:
if event.event_type is IonEventType.CONTAINER_END and event.depth <= depth:
break
if event is None or event.event_type is IonEventType.INCOMPLETE:
data_event, _ = yield Transition(event, self)
else:
trans, delegate, event = pass_through()
if event is not None and (event.event_type is IonEventType.CONTAINER_START or
event.event_type is IonEventType.CONTAINER_END):
depth = event.depth
data_event, _ = yield Transition(event, self) | python | def _skip_trampoline(handler):
"""Intercepts events from container handlers, emitting them only if they should not be skipped."""
data_event, self = (yield None)
delegate = handler
event = None
depth = 0
while True:
def pass_through():
_trans = delegate.send(Transition(data_event, delegate))
return _trans, _trans.delegate, _trans.event
if data_event is not None and data_event.type is ReadEventType.SKIP:
while True:
trans, delegate, event = pass_through()
if event is not None:
if event.event_type is IonEventType.CONTAINER_END and event.depth <= depth:
break
if event is None or event.event_type is IonEventType.INCOMPLETE:
data_event, _ = yield Transition(event, self)
else:
trans, delegate, event = pass_through()
if event is not None and (event.event_type is IonEventType.CONTAINER_START or
event.event_type is IonEventType.CONTAINER_END):
depth = event.depth
data_event, _ = yield Transition(event, self) | [
"def",
"_skip_trampoline",
"(",
"handler",
")",
":",
"data_event",
",",
"self",
"=",
"(",
"yield",
"None",
")",
"delegate",
"=",
"handler",
"event",
"=",
"None",
"depth",
"=",
"0",
"while",
"True",
":",
"def",
"pass_through",
"(",
")",
":",
"_trans",
"=",
"delegate",
".",
"send",
"(",
"Transition",
"(",
"data_event",
",",
"delegate",
")",
")",
"return",
"_trans",
",",
"_trans",
".",
"delegate",
",",
"_trans",
".",
"event",
"if",
"data_event",
"is",
"not",
"None",
"and",
"data_event",
".",
"type",
"is",
"ReadEventType",
".",
"SKIP",
":",
"while",
"True",
":",
"trans",
",",
"delegate",
",",
"event",
"=",
"pass_through",
"(",
")",
"if",
"event",
"is",
"not",
"None",
":",
"if",
"event",
".",
"event_type",
"is",
"IonEventType",
".",
"CONTAINER_END",
"and",
"event",
".",
"depth",
"<=",
"depth",
":",
"break",
"if",
"event",
"is",
"None",
"or",
"event",
".",
"event_type",
"is",
"IonEventType",
".",
"INCOMPLETE",
":",
"data_event",
",",
"_",
"=",
"yield",
"Transition",
"(",
"event",
",",
"self",
")",
"else",
":",
"trans",
",",
"delegate",
",",
"event",
"=",
"pass_through",
"(",
")",
"if",
"event",
"is",
"not",
"None",
"and",
"(",
"event",
".",
"event_type",
"is",
"IonEventType",
".",
"CONTAINER_START",
"or",
"event",
".",
"event_type",
"is",
"IonEventType",
".",
"CONTAINER_END",
")",
":",
"depth",
"=",
"event",
".",
"depth",
"data_event",
",",
"_",
"=",
"yield",
"Transition",
"(",
"event",
",",
"self",
")"
] | Intercepts events from container handlers, emitting them only if they should not be skipped. | [
"Intercepts",
"events",
"from",
"container",
"handlers",
"emitting",
"them",
"only",
"if",
"they",
"should",
"not",
"be",
"skipped",
"."
] | 0b21fa3ba7755f55f745e4aa970d86343b82449d | https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/reader_text.py#L2152-L2176 | train | 233,819 |
amzn/ion-python | amazon/ion/reader_text.py | _next_code_point_handler | def _next_code_point_handler(whence, ctx):
"""Retrieves the next code point from within a quoted string or symbol."""
data_event, self = yield
queue = ctx.queue
unicode_escapes_allowed = ctx.ion_type is not IonType.CLOB
escaped_newline = False
escape_sequence = b''
low_surrogate_required = False
while True:
if len(queue) == 0:
yield ctx.read_data_event(self)
queue_iter = iter(queue)
code_point_generator = _next_code_point_iter(queue, queue_iter)
code_point = next(code_point_generator)
if code_point == _BACKSLASH:
escape_sequence += six.int2byte(_BACKSLASH)
num_digits = None
while True:
if len(queue) == 0:
yield ctx.read_data_event(self)
code_point = next(queue_iter)
if six.indexbytes(escape_sequence, -1) == _BACKSLASH:
if code_point == _ord(b'u') and unicode_escapes_allowed:
# 4-digit unicode escapes, plus '\u' for each surrogate
num_digits = 12 if low_surrogate_required else 6
low_surrogate_required = False
elif low_surrogate_required:
_illegal_character(code_point, ctx,
'Unpaired high surrogate escape sequence %s.' % (escape_sequence,))
elif code_point == _ord(b'x'):
num_digits = 4 # 2-digit hex escapes
elif code_point == _ord(b'U') and unicode_escapes_allowed:
num_digits = 10 # 8-digit unicode escapes
elif code_point in _COMMON_ESCAPES:
if code_point == _SLASH or code_point == _QUESTION_MARK:
escape_sequence = b'' # Drop the \. Python does not recognize these as escapes.
escape_sequence += six.int2byte(code_point)
break
elif code_point in _NEWLINES:
escaped_newline = True
break
else:
# This is a backslash followed by an invalid escape character. This is illegal.
_illegal_character(code_point, ctx, 'Invalid escape sequence \\%s.' % (_chr(code_point),))
escape_sequence += six.int2byte(code_point)
else:
if code_point not in _HEX_DIGITS:
_illegal_character(code_point, ctx,
'Non-hex character %s found in unicode escape.' % (_chr(code_point),))
escape_sequence += six.int2byte(code_point)
if len(escape_sequence) == num_digits:
break
if not escaped_newline:
decoded_escape_sequence = escape_sequence.decode('unicode-escape')
cp_iter = _next_code_point_iter(decoded_escape_sequence, iter(decoded_escape_sequence), to_int=ord)
code_point = next(cp_iter)
if code_point is None:
# This is a high surrogate. Restart the loop to gather the low surrogate.
low_surrogate_required = True
continue
code_point = CodePoint(code_point)
code_point.char = decoded_escape_sequence
code_point.is_escaped = True
ctx.set_code_point(code_point)
yield Transition(None, whence)
elif low_surrogate_required:
_illegal_character(code_point, ctx, 'Unpaired high surrogate escape sequence %s.' % (escape_sequence,))
if code_point == _CARRIAGE_RETURN:
# Normalize all newlines (\r, \n, and \r\n) to \n .
if len(queue) == 0:
yield ctx.read_data_event(self)
code_point = next(queue_iter)
if code_point != _NEWLINE:
queue.unread(code_point)
code_point = _NEWLINE
while code_point is None:
yield ctx.read_data_event(self)
code_point = next(code_point_generator)
if escaped_newline:
code_point = CodePoint(code_point)
code_point.char = _ESCAPED_NEWLINE
code_point.is_escaped = True
ctx.set_code_point(code_point)
yield Transition(None, whence) | python | def _next_code_point_handler(whence, ctx):
"""Retrieves the next code point from within a quoted string or symbol."""
data_event, self = yield
queue = ctx.queue
unicode_escapes_allowed = ctx.ion_type is not IonType.CLOB
escaped_newline = False
escape_sequence = b''
low_surrogate_required = False
while True:
if len(queue) == 0:
yield ctx.read_data_event(self)
queue_iter = iter(queue)
code_point_generator = _next_code_point_iter(queue, queue_iter)
code_point = next(code_point_generator)
if code_point == _BACKSLASH:
escape_sequence += six.int2byte(_BACKSLASH)
num_digits = None
while True:
if len(queue) == 0:
yield ctx.read_data_event(self)
code_point = next(queue_iter)
if six.indexbytes(escape_sequence, -1) == _BACKSLASH:
if code_point == _ord(b'u') and unicode_escapes_allowed:
# 4-digit unicode escapes, plus '\u' for each surrogate
num_digits = 12 if low_surrogate_required else 6
low_surrogate_required = False
elif low_surrogate_required:
_illegal_character(code_point, ctx,
'Unpaired high surrogate escape sequence %s.' % (escape_sequence,))
elif code_point == _ord(b'x'):
num_digits = 4 # 2-digit hex escapes
elif code_point == _ord(b'U') and unicode_escapes_allowed:
num_digits = 10 # 8-digit unicode escapes
elif code_point in _COMMON_ESCAPES:
if code_point == _SLASH or code_point == _QUESTION_MARK:
escape_sequence = b'' # Drop the \. Python does not recognize these as escapes.
escape_sequence += six.int2byte(code_point)
break
elif code_point in _NEWLINES:
escaped_newline = True
break
else:
# This is a backslash followed by an invalid escape character. This is illegal.
_illegal_character(code_point, ctx, 'Invalid escape sequence \\%s.' % (_chr(code_point),))
escape_sequence += six.int2byte(code_point)
else:
if code_point not in _HEX_DIGITS:
_illegal_character(code_point, ctx,
'Non-hex character %s found in unicode escape.' % (_chr(code_point),))
escape_sequence += six.int2byte(code_point)
if len(escape_sequence) == num_digits:
break
if not escaped_newline:
decoded_escape_sequence = escape_sequence.decode('unicode-escape')
cp_iter = _next_code_point_iter(decoded_escape_sequence, iter(decoded_escape_sequence), to_int=ord)
code_point = next(cp_iter)
if code_point is None:
# This is a high surrogate. Restart the loop to gather the low surrogate.
low_surrogate_required = True
continue
code_point = CodePoint(code_point)
code_point.char = decoded_escape_sequence
code_point.is_escaped = True
ctx.set_code_point(code_point)
yield Transition(None, whence)
elif low_surrogate_required:
_illegal_character(code_point, ctx, 'Unpaired high surrogate escape sequence %s.' % (escape_sequence,))
if code_point == _CARRIAGE_RETURN:
# Normalize all newlines (\r, \n, and \r\n) to \n .
if len(queue) == 0:
yield ctx.read_data_event(self)
code_point = next(queue_iter)
if code_point != _NEWLINE:
queue.unread(code_point)
code_point = _NEWLINE
while code_point is None:
yield ctx.read_data_event(self)
code_point = next(code_point_generator)
if escaped_newline:
code_point = CodePoint(code_point)
code_point.char = _ESCAPED_NEWLINE
code_point.is_escaped = True
ctx.set_code_point(code_point)
yield Transition(None, whence) | [
"def",
"_next_code_point_handler",
"(",
"whence",
",",
"ctx",
")",
":",
"data_event",
",",
"self",
"=",
"yield",
"queue",
"=",
"ctx",
".",
"queue",
"unicode_escapes_allowed",
"=",
"ctx",
".",
"ion_type",
"is",
"not",
"IonType",
".",
"CLOB",
"escaped_newline",
"=",
"False",
"escape_sequence",
"=",
"b''",
"low_surrogate_required",
"=",
"False",
"while",
"True",
":",
"if",
"len",
"(",
"queue",
")",
"==",
"0",
":",
"yield",
"ctx",
".",
"read_data_event",
"(",
"self",
")",
"queue_iter",
"=",
"iter",
"(",
"queue",
")",
"code_point_generator",
"=",
"_next_code_point_iter",
"(",
"queue",
",",
"queue_iter",
")",
"code_point",
"=",
"next",
"(",
"code_point_generator",
")",
"if",
"code_point",
"==",
"_BACKSLASH",
":",
"escape_sequence",
"+=",
"six",
".",
"int2byte",
"(",
"_BACKSLASH",
")",
"num_digits",
"=",
"None",
"while",
"True",
":",
"if",
"len",
"(",
"queue",
")",
"==",
"0",
":",
"yield",
"ctx",
".",
"read_data_event",
"(",
"self",
")",
"code_point",
"=",
"next",
"(",
"queue_iter",
")",
"if",
"six",
".",
"indexbytes",
"(",
"escape_sequence",
",",
"-",
"1",
")",
"==",
"_BACKSLASH",
":",
"if",
"code_point",
"==",
"_ord",
"(",
"b'u'",
")",
"and",
"unicode_escapes_allowed",
":",
"# 4-digit unicode escapes, plus '\\u' for each surrogate",
"num_digits",
"=",
"12",
"if",
"low_surrogate_required",
"else",
"6",
"low_surrogate_required",
"=",
"False",
"elif",
"low_surrogate_required",
":",
"_illegal_character",
"(",
"code_point",
",",
"ctx",
",",
"'Unpaired high surrogate escape sequence %s.'",
"%",
"(",
"escape_sequence",
",",
")",
")",
"elif",
"code_point",
"==",
"_ord",
"(",
"b'x'",
")",
":",
"num_digits",
"=",
"4",
"# 2-digit hex escapes",
"elif",
"code_point",
"==",
"_ord",
"(",
"b'U'",
")",
"and",
"unicode_escapes_allowed",
":",
"num_digits",
"=",
"10",
"# 8-digit unicode escapes",
"elif",
"code_point",
"in",
"_COMMON_ESCAPES",
":",
"if",
"code_point",
"==",
"_SLASH",
"or",
"code_point",
"==",
"_QUESTION_MARK",
":",
"escape_sequence",
"=",
"b''",
"# Drop the \\. Python does not recognize these as escapes.",
"escape_sequence",
"+=",
"six",
".",
"int2byte",
"(",
"code_point",
")",
"break",
"elif",
"code_point",
"in",
"_NEWLINES",
":",
"escaped_newline",
"=",
"True",
"break",
"else",
":",
"# This is a backslash followed by an invalid escape character. This is illegal.",
"_illegal_character",
"(",
"code_point",
",",
"ctx",
",",
"'Invalid escape sequence \\\\%s.'",
"%",
"(",
"_chr",
"(",
"code_point",
")",
",",
")",
")",
"escape_sequence",
"+=",
"six",
".",
"int2byte",
"(",
"code_point",
")",
"else",
":",
"if",
"code_point",
"not",
"in",
"_HEX_DIGITS",
":",
"_illegal_character",
"(",
"code_point",
",",
"ctx",
",",
"'Non-hex character %s found in unicode escape.'",
"%",
"(",
"_chr",
"(",
"code_point",
")",
",",
")",
")",
"escape_sequence",
"+=",
"six",
".",
"int2byte",
"(",
"code_point",
")",
"if",
"len",
"(",
"escape_sequence",
")",
"==",
"num_digits",
":",
"break",
"if",
"not",
"escaped_newline",
":",
"decoded_escape_sequence",
"=",
"escape_sequence",
".",
"decode",
"(",
"'unicode-escape'",
")",
"cp_iter",
"=",
"_next_code_point_iter",
"(",
"decoded_escape_sequence",
",",
"iter",
"(",
"decoded_escape_sequence",
")",
",",
"to_int",
"=",
"ord",
")",
"code_point",
"=",
"next",
"(",
"cp_iter",
")",
"if",
"code_point",
"is",
"None",
":",
"# This is a high surrogate. Restart the loop to gather the low surrogate.",
"low_surrogate_required",
"=",
"True",
"continue",
"code_point",
"=",
"CodePoint",
"(",
"code_point",
")",
"code_point",
".",
"char",
"=",
"decoded_escape_sequence",
"code_point",
".",
"is_escaped",
"=",
"True",
"ctx",
".",
"set_code_point",
"(",
"code_point",
")",
"yield",
"Transition",
"(",
"None",
",",
"whence",
")",
"elif",
"low_surrogate_required",
":",
"_illegal_character",
"(",
"code_point",
",",
"ctx",
",",
"'Unpaired high surrogate escape sequence %s.'",
"%",
"(",
"escape_sequence",
",",
")",
")",
"if",
"code_point",
"==",
"_CARRIAGE_RETURN",
":",
"# Normalize all newlines (\\r, \\n, and \\r\\n) to \\n .",
"if",
"len",
"(",
"queue",
")",
"==",
"0",
":",
"yield",
"ctx",
".",
"read_data_event",
"(",
"self",
")",
"code_point",
"=",
"next",
"(",
"queue_iter",
")",
"if",
"code_point",
"!=",
"_NEWLINE",
":",
"queue",
".",
"unread",
"(",
"code_point",
")",
"code_point",
"=",
"_NEWLINE",
"while",
"code_point",
"is",
"None",
":",
"yield",
"ctx",
".",
"read_data_event",
"(",
"self",
")",
"code_point",
"=",
"next",
"(",
"code_point_generator",
")",
"if",
"escaped_newline",
":",
"code_point",
"=",
"CodePoint",
"(",
"code_point",
")",
"code_point",
".",
"char",
"=",
"_ESCAPED_NEWLINE",
"code_point",
".",
"is_escaped",
"=",
"True",
"ctx",
".",
"set_code_point",
"(",
"code_point",
")",
"yield",
"Transition",
"(",
"None",
",",
"whence",
")"
] | Retrieves the next code point from within a quoted string or symbol. | [
"Retrieves",
"the",
"next",
"code",
"point",
"from",
"within",
"a",
"quoted",
"string",
"or",
"symbol",
"."
] | 0b21fa3ba7755f55f745e4aa970d86343b82449d | https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/reader_text.py#L2183-L2266 | train | 233,820 |
amzn/ion-python | amazon/ion/reader_text.py | _HandlerContext.read_data_event | def read_data_event(self, whence, complete=False, can_flush=False):
"""Creates a transition to a co-routine for retrieving data as bytes.
Args:
whence (Coroutine): The co-routine to return to after the data is satisfied.
complete (Optional[bool]): True if STREAM_END should be emitted if no bytes are read or
available; False if INCOMPLETE should be emitted in that case.
can_flush (Optional[bool]): True if NEXT may be requested after INCOMPLETE is emitted as a result of this
data request.
"""
return Transition(None, _read_data_handler(whence, self, complete, can_flush)) | python | def read_data_event(self, whence, complete=False, can_flush=False):
"""Creates a transition to a co-routine for retrieving data as bytes.
Args:
whence (Coroutine): The co-routine to return to after the data is satisfied.
complete (Optional[bool]): True if STREAM_END should be emitted if no bytes are read or
available; False if INCOMPLETE should be emitted in that case.
can_flush (Optional[bool]): True if NEXT may be requested after INCOMPLETE is emitted as a result of this
data request.
"""
return Transition(None, _read_data_handler(whence, self, complete, can_flush)) | [
"def",
"read_data_event",
"(",
"self",
",",
"whence",
",",
"complete",
"=",
"False",
",",
"can_flush",
"=",
"False",
")",
":",
"return",
"Transition",
"(",
"None",
",",
"_read_data_handler",
"(",
"whence",
",",
"self",
",",
"complete",
",",
"can_flush",
")",
")"
] | Creates a transition to a co-routine for retrieving data as bytes.
Args:
whence (Coroutine): The co-routine to return to after the data is satisfied.
complete (Optional[bool]): True if STREAM_END should be emitted if no bytes are read or
available; False if INCOMPLETE should be emitted in that case.
can_flush (Optional[bool]): True if NEXT may be requested after INCOMPLETE is emitted as a result of this
data request. | [
"Creates",
"a",
"transition",
"to",
"a",
"co",
"-",
"routine",
"for",
"retrieving",
"data",
"as",
"bytes",
"."
] | 0b21fa3ba7755f55f745e4aa970d86343b82449d | https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/reader_text.py#L369-L379 | train | 233,821 |
amzn/ion-python | amazon/ion/reader_text.py | _HandlerContext.set_unicode | def set_unicode(self, quoted_text=False):
"""Converts the context's ``value`` to a sequence of unicode code points for holding text tokens, indicating
whether the text is quoted.
"""
if isinstance(self.value, CodePointArray):
assert self.quoted_text == quoted_text
return self
self.value = CodePointArray(self.value)
self.quoted_text = quoted_text
self.line_comment = False
return self | python | def set_unicode(self, quoted_text=False):
"""Converts the context's ``value`` to a sequence of unicode code points for holding text tokens, indicating
whether the text is quoted.
"""
if isinstance(self.value, CodePointArray):
assert self.quoted_text == quoted_text
return self
self.value = CodePointArray(self.value)
self.quoted_text = quoted_text
self.line_comment = False
return self | [
"def",
"set_unicode",
"(",
"self",
",",
"quoted_text",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"value",
",",
"CodePointArray",
")",
":",
"assert",
"self",
".",
"quoted_text",
"==",
"quoted_text",
"return",
"self",
"self",
".",
"value",
"=",
"CodePointArray",
"(",
"self",
".",
"value",
")",
"self",
".",
"quoted_text",
"=",
"quoted_text",
"self",
".",
"line_comment",
"=",
"False",
"return",
"self"
] | Converts the context's ``value`` to a sequence of unicode code points for holding text tokens, indicating
whether the text is quoted. | [
"Converts",
"the",
"context",
"s",
"value",
"to",
"a",
"sequence",
"of",
"unicode",
"code",
"points",
"for",
"holding",
"text",
"tokens",
"indicating",
"whether",
"the",
"text",
"is",
"quoted",
"."
] | 0b21fa3ba7755f55f745e4aa970d86343b82449d | https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/reader_text.py#L388-L398 | train | 233,822 |
amzn/ion-python | amazon/ion/reader_text.py | _HandlerContext.set_quoted_text | def set_quoted_text(self, quoted_text):
"""Sets the context's ``quoted_text`` flag. Useful when entering and exiting quoted text tokens."""
self.quoted_text = quoted_text
self.line_comment = False
return self | python | def set_quoted_text(self, quoted_text):
"""Sets the context's ``quoted_text`` flag. Useful when entering and exiting quoted text tokens."""
self.quoted_text = quoted_text
self.line_comment = False
return self | [
"def",
"set_quoted_text",
"(",
"self",
",",
"quoted_text",
")",
":",
"self",
".",
"quoted_text",
"=",
"quoted_text",
"self",
".",
"line_comment",
"=",
"False",
"return",
"self"
] | Sets the context's ``quoted_text`` flag. Useful when entering and exiting quoted text tokens. | [
"Sets",
"the",
"context",
"s",
"quoted_text",
"flag",
".",
"Useful",
"when",
"entering",
"and",
"exiting",
"quoted",
"text",
"tokens",
"."
] | 0b21fa3ba7755f55f745e4aa970d86343b82449d | https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/reader_text.py#L400-L404 | train | 233,823 |
amzn/ion-python | amazon/ion/reader_text.py | _HandlerContext.derive_container_context | def derive_container_context(self, ion_type, whence):
"""Derives a container context as a child of the current context."""
if ion_type is IonType.STRUCT:
container = _C_STRUCT
elif ion_type is IonType.LIST:
container = _C_LIST
elif ion_type is IonType.SEXP:
container = _C_SEXP
else:
raise TypeError('Cannot derive container context for non-container type %s.' % (ion_type.name,))
return _HandlerContext(
container=container,
queue=self.queue,
field_name=self.field_name,
annotations=self.annotations,
depth=self.depth + 1,
whence=whence,
value=None, # containers don't have a value
ion_type=ion_type,
pending_symbol=None
) | python | def derive_container_context(self, ion_type, whence):
"""Derives a container context as a child of the current context."""
if ion_type is IonType.STRUCT:
container = _C_STRUCT
elif ion_type is IonType.LIST:
container = _C_LIST
elif ion_type is IonType.SEXP:
container = _C_SEXP
else:
raise TypeError('Cannot derive container context for non-container type %s.' % (ion_type.name,))
return _HandlerContext(
container=container,
queue=self.queue,
field_name=self.field_name,
annotations=self.annotations,
depth=self.depth + 1,
whence=whence,
value=None, # containers don't have a value
ion_type=ion_type,
pending_symbol=None
) | [
"def",
"derive_container_context",
"(",
"self",
",",
"ion_type",
",",
"whence",
")",
":",
"if",
"ion_type",
"is",
"IonType",
".",
"STRUCT",
":",
"container",
"=",
"_C_STRUCT",
"elif",
"ion_type",
"is",
"IonType",
".",
"LIST",
":",
"container",
"=",
"_C_LIST",
"elif",
"ion_type",
"is",
"IonType",
".",
"SEXP",
":",
"container",
"=",
"_C_SEXP",
"else",
":",
"raise",
"TypeError",
"(",
"'Cannot derive container context for non-container type %s.'",
"%",
"(",
"ion_type",
".",
"name",
",",
")",
")",
"return",
"_HandlerContext",
"(",
"container",
"=",
"container",
",",
"queue",
"=",
"self",
".",
"queue",
",",
"field_name",
"=",
"self",
".",
"field_name",
",",
"annotations",
"=",
"self",
".",
"annotations",
",",
"depth",
"=",
"self",
".",
"depth",
"+",
"1",
",",
"whence",
"=",
"whence",
",",
"value",
"=",
"None",
",",
"# containers don't have a value",
"ion_type",
"=",
"ion_type",
",",
"pending_symbol",
"=",
"None",
")"
] | Derives a container context as a child of the current context. | [
"Derives",
"a",
"container",
"context",
"as",
"a",
"child",
"of",
"the",
"current",
"context",
"."
] | 0b21fa3ba7755f55f745e4aa970d86343b82449d | https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/reader_text.py#L421-L441 | train | 233,824 |
amzn/ion-python | amazon/ion/reader_text.py | _HandlerContext.derive_child_context | def derive_child_context(self, whence):
"""Derives a scalar context as a child of the current context."""
return _HandlerContext(
container=self.container,
queue=self.queue,
field_name=None,
annotations=None,
depth=self.depth,
whence=whence,
value=bytearray(), # children start without a value
ion_type=None,
pending_symbol=None
) | python | def derive_child_context(self, whence):
"""Derives a scalar context as a child of the current context."""
return _HandlerContext(
container=self.container,
queue=self.queue,
field_name=None,
annotations=None,
depth=self.depth,
whence=whence,
value=bytearray(), # children start without a value
ion_type=None,
pending_symbol=None
) | [
"def",
"derive_child_context",
"(",
"self",
",",
"whence",
")",
":",
"return",
"_HandlerContext",
"(",
"container",
"=",
"self",
".",
"container",
",",
"queue",
"=",
"self",
".",
"queue",
",",
"field_name",
"=",
"None",
",",
"annotations",
"=",
"None",
",",
"depth",
"=",
"self",
".",
"depth",
",",
"whence",
"=",
"whence",
",",
"value",
"=",
"bytearray",
"(",
")",
",",
"# children start without a value",
"ion_type",
"=",
"None",
",",
"pending_symbol",
"=",
"None",
")"
] | Derives a scalar context as a child of the current context. | [
"Derives",
"a",
"scalar",
"context",
"as",
"a",
"child",
"of",
"the",
"current",
"context",
"."
] | 0b21fa3ba7755f55f745e4aa970d86343b82449d | https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/reader_text.py#L455-L467 | train | 233,825 |
amzn/ion-python | amazon/ion/reader_text.py | _HandlerContext.set_ion_type | def set_ion_type(self, ion_type):
"""Sets context to the given IonType."""
if ion_type is self.ion_type:
return self
self.ion_type = ion_type
self.line_comment = False
return self | python | def set_ion_type(self, ion_type):
"""Sets context to the given IonType."""
if ion_type is self.ion_type:
return self
self.ion_type = ion_type
self.line_comment = False
return self | [
"def",
"set_ion_type",
"(",
"self",
",",
"ion_type",
")",
":",
"if",
"ion_type",
"is",
"self",
".",
"ion_type",
":",
"return",
"self",
"self",
".",
"ion_type",
"=",
"ion_type",
"self",
".",
"line_comment",
"=",
"False",
"return",
"self"
] | Sets context to the given IonType. | [
"Sets",
"context",
"to",
"the",
"given",
"IonType",
"."
] | 0b21fa3ba7755f55f745e4aa970d86343b82449d | https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/reader_text.py#L474-L480 | train | 233,826 |
amzn/ion-python | amazon/ion/reader_text.py | _HandlerContext.set_annotation | def set_annotation(self):
"""Appends the context's ``pending_symbol`` to its ``annotations`` sequence."""
assert self.pending_symbol is not None
assert not self.value
annotations = (_as_symbol(self.pending_symbol, is_symbol_value=False),) # pending_symbol becomes an annotation
self.annotations = annotations if not self.annotations else self.annotations + annotations
self.ion_type = None
self.pending_symbol = None # reset pending symbol
self.quoted_text = False
self.line_comment = False
self.is_self_delimiting = False
return self | python | def set_annotation(self):
"""Appends the context's ``pending_symbol`` to its ``annotations`` sequence."""
assert self.pending_symbol is not None
assert not self.value
annotations = (_as_symbol(self.pending_symbol, is_symbol_value=False),) # pending_symbol becomes an annotation
self.annotations = annotations if not self.annotations else self.annotations + annotations
self.ion_type = None
self.pending_symbol = None # reset pending symbol
self.quoted_text = False
self.line_comment = False
self.is_self_delimiting = False
return self | [
"def",
"set_annotation",
"(",
"self",
")",
":",
"assert",
"self",
".",
"pending_symbol",
"is",
"not",
"None",
"assert",
"not",
"self",
".",
"value",
"annotations",
"=",
"(",
"_as_symbol",
"(",
"self",
".",
"pending_symbol",
",",
"is_symbol_value",
"=",
"False",
")",
",",
")",
"# pending_symbol becomes an annotation",
"self",
".",
"annotations",
"=",
"annotations",
"if",
"not",
"self",
".",
"annotations",
"else",
"self",
".",
"annotations",
"+",
"annotations",
"self",
".",
"ion_type",
"=",
"None",
"self",
".",
"pending_symbol",
"=",
"None",
"# reset pending symbol",
"self",
".",
"quoted_text",
"=",
"False",
"self",
".",
"line_comment",
"=",
"False",
"self",
".",
"is_self_delimiting",
"=",
"False",
"return",
"self"
] | Appends the context's ``pending_symbol`` to its ``annotations`` sequence. | [
"Appends",
"the",
"context",
"s",
"pending_symbol",
"to",
"its",
"annotations",
"sequence",
"."
] | 0b21fa3ba7755f55f745e4aa970d86343b82449d | https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/reader_text.py#L482-L493 | train | 233,827 |
amzn/ion-python | amazon/ion/reader_text.py | _HandlerContext.set_field_name | def set_field_name(self):
"""Sets the context's ``pending_symbol`` as its ``field_name``."""
assert self.pending_symbol is not None
assert not self.value
self.field_name = _as_symbol(self.pending_symbol, is_symbol_value=False) # pending_symbol becomes field name
self.pending_symbol = None # reset pending symbol
self.quoted_text = False
self.line_comment = False
self.is_self_delimiting = False
return self | python | def set_field_name(self):
"""Sets the context's ``pending_symbol`` as its ``field_name``."""
assert self.pending_symbol is not None
assert not self.value
self.field_name = _as_symbol(self.pending_symbol, is_symbol_value=False) # pending_symbol becomes field name
self.pending_symbol = None # reset pending symbol
self.quoted_text = False
self.line_comment = False
self.is_self_delimiting = False
return self | [
"def",
"set_field_name",
"(",
"self",
")",
":",
"assert",
"self",
".",
"pending_symbol",
"is",
"not",
"None",
"assert",
"not",
"self",
".",
"value",
"self",
".",
"field_name",
"=",
"_as_symbol",
"(",
"self",
".",
"pending_symbol",
",",
"is_symbol_value",
"=",
"False",
")",
"# pending_symbol becomes field name",
"self",
".",
"pending_symbol",
"=",
"None",
"# reset pending symbol",
"self",
".",
"quoted_text",
"=",
"False",
"self",
".",
"line_comment",
"=",
"False",
"self",
".",
"is_self_delimiting",
"=",
"False",
"return",
"self"
] | Sets the context's ``pending_symbol`` as its ``field_name``. | [
"Sets",
"the",
"context",
"s",
"pending_symbol",
"as",
"its",
"field_name",
"."
] | 0b21fa3ba7755f55f745e4aa970d86343b82449d | https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/reader_text.py#L495-L504 | train | 233,828 |
amzn/ion-python | amazon/ion/reader_text.py | _HandlerContext.set_pending_symbol | def set_pending_symbol(self, pending_symbol=None):
"""Sets the context's ``pending_symbol`` with the given unicode sequence and resets the context's ``value``.
If the input is None, an empty :class:`CodePointArray` is used.
"""
if pending_symbol is None:
pending_symbol = CodePointArray()
self.value = bytearray() # reset value
self.pending_symbol = pending_symbol
self.line_comment = False
return self | python | def set_pending_symbol(self, pending_symbol=None):
"""Sets the context's ``pending_symbol`` with the given unicode sequence and resets the context's ``value``.
If the input is None, an empty :class:`CodePointArray` is used.
"""
if pending_symbol is None:
pending_symbol = CodePointArray()
self.value = bytearray() # reset value
self.pending_symbol = pending_symbol
self.line_comment = False
return self | [
"def",
"set_pending_symbol",
"(",
"self",
",",
"pending_symbol",
"=",
"None",
")",
":",
"if",
"pending_symbol",
"is",
"None",
":",
"pending_symbol",
"=",
"CodePointArray",
"(",
")",
"self",
".",
"value",
"=",
"bytearray",
"(",
")",
"# reset value",
"self",
".",
"pending_symbol",
"=",
"pending_symbol",
"self",
".",
"line_comment",
"=",
"False",
"return",
"self"
] | Sets the context's ``pending_symbol`` with the given unicode sequence and resets the context's ``value``.
If the input is None, an empty :class:`CodePointArray` is used. | [
"Sets",
"the",
"context",
"s",
"pending_symbol",
"with",
"the",
"given",
"unicode",
"sequence",
"and",
"resets",
"the",
"context",
"s",
"value",
"."
] | 0b21fa3ba7755f55f745e4aa970d86343b82449d | https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/reader_text.py#L506-L516 | train | 233,829 |
amzn/ion-python | amazon/ion/writer_binary_raw_fields.py | _write_base | def _write_base(buf, value, bits_per_octet, end_bit=0, sign_bit=0, is_signed=False):
"""Write a field to the provided buffer.
Args:
buf (Sequence): The buffer into which the UInt will be written
in the form of integer octets.
value (int): The value to write as a UInt.
bits_per_octet (int): The number of value bits (i.e. exclusive of the end bit, but
inclusive of the sign bit, if applicable) per octet.
end_bit (Optional[int]): The end bit mask.
sign_bit (Optional[int]): The sign bit mask.
Returns:
int: The number of octets written.
"""
if value == 0:
buf.append(sign_bit | end_bit)
return 1
num_bits = bit_length(value)
num_octets = num_bits // bits_per_octet
# 'remainder' is the number of value bits in the first octet.
remainder = num_bits % bits_per_octet
if remainder != 0 or is_signed:
# If signed, the first octet has one fewer bit available, requiring another octet.
num_octets += 1
else:
# This ensures that unsigned values that fit exactly are not shifted too far.
remainder = bits_per_octet
for i in range(num_octets):
octet = 0
if i == 0:
octet |= sign_bit
if i == num_octets - 1:
octet |= end_bit
# 'remainder' is used for alignment such that only the first octet
# may contain insignificant zeros.
octet |= ((value >> (num_bits - (remainder + bits_per_octet * i))) & _OCTET_MASKS[bits_per_octet])
buf.append(octet)
return num_octets | python | def _write_base(buf, value, bits_per_octet, end_bit=0, sign_bit=0, is_signed=False):
"""Write a field to the provided buffer.
Args:
buf (Sequence): The buffer into which the UInt will be written
in the form of integer octets.
value (int): The value to write as a UInt.
bits_per_octet (int): The number of value bits (i.e. exclusive of the end bit, but
inclusive of the sign bit, if applicable) per octet.
end_bit (Optional[int]): The end bit mask.
sign_bit (Optional[int]): The sign bit mask.
Returns:
int: The number of octets written.
"""
if value == 0:
buf.append(sign_bit | end_bit)
return 1
num_bits = bit_length(value)
num_octets = num_bits // bits_per_octet
# 'remainder' is the number of value bits in the first octet.
remainder = num_bits % bits_per_octet
if remainder != 0 or is_signed:
# If signed, the first octet has one fewer bit available, requiring another octet.
num_octets += 1
else:
# This ensures that unsigned values that fit exactly are not shifted too far.
remainder = bits_per_octet
for i in range(num_octets):
octet = 0
if i == 0:
octet |= sign_bit
if i == num_octets - 1:
octet |= end_bit
# 'remainder' is used for alignment such that only the first octet
# may contain insignificant zeros.
octet |= ((value >> (num_bits - (remainder + bits_per_octet * i))) & _OCTET_MASKS[bits_per_octet])
buf.append(octet)
return num_octets | [
"def",
"_write_base",
"(",
"buf",
",",
"value",
",",
"bits_per_octet",
",",
"end_bit",
"=",
"0",
",",
"sign_bit",
"=",
"0",
",",
"is_signed",
"=",
"False",
")",
":",
"if",
"value",
"==",
"0",
":",
"buf",
".",
"append",
"(",
"sign_bit",
"|",
"end_bit",
")",
"return",
"1",
"num_bits",
"=",
"bit_length",
"(",
"value",
")",
"num_octets",
"=",
"num_bits",
"//",
"bits_per_octet",
"# 'remainder' is the number of value bits in the first octet.",
"remainder",
"=",
"num_bits",
"%",
"bits_per_octet",
"if",
"remainder",
"!=",
"0",
"or",
"is_signed",
":",
"# If signed, the first octet has one fewer bit available, requiring another octet.",
"num_octets",
"+=",
"1",
"else",
":",
"# This ensures that unsigned values that fit exactly are not shifted too far.",
"remainder",
"=",
"bits_per_octet",
"for",
"i",
"in",
"range",
"(",
"num_octets",
")",
":",
"octet",
"=",
"0",
"if",
"i",
"==",
"0",
":",
"octet",
"|=",
"sign_bit",
"if",
"i",
"==",
"num_octets",
"-",
"1",
":",
"octet",
"|=",
"end_bit",
"# 'remainder' is used for alignment such that only the first octet",
"# may contain insignificant zeros.",
"octet",
"|=",
"(",
"(",
"value",
">>",
"(",
"num_bits",
"-",
"(",
"remainder",
"+",
"bits_per_octet",
"*",
"i",
")",
")",
")",
"&",
"_OCTET_MASKS",
"[",
"bits_per_octet",
"]",
")",
"buf",
".",
"append",
"(",
"octet",
")",
"return",
"num_octets"
] | Write a field to the provided buffer.
Args:
buf (Sequence): The buffer into which the UInt will be written
in the form of integer octets.
value (int): The value to write as a UInt.
bits_per_octet (int): The number of value bits (i.e. exclusive of the end bit, but
inclusive of the sign bit, if applicable) per octet.
end_bit (Optional[int]): The end bit mask.
sign_bit (Optional[int]): The sign bit mask.
Returns:
int: The number of octets written. | [
"Write",
"a",
"field",
"to",
"the",
"provided",
"buffer",
"."
] | 0b21fa3ba7755f55f745e4aa970d86343b82449d | https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/writer_binary_raw_fields.py#L147-L185 | train | 233,830 |
amzn/ion-python | amazon/ion/util.py | record | def record(*fields):
"""Constructs a type that can be extended to create immutable, value types.
Examples:
A typical declaration looks like::
class MyRecord(record('a', ('b', 1))):
pass
The above would make a sub-class of ``collections.namedtuple`` that was named ``MyRecord`` with
a constructor that had the ``b`` field set to 1 by default.
Note:
This uses meta-class machinery to rewrite the inheritance hierarchy.
This is done in order to make sure that the underlying ``namedtuple`` instance is
bound to the right type name and to make sure that the synthetic class that is generated
to enable this machinery is not enabled for sub-classes of a user's record class.
Args:
fields (list[str | (str, any)]): A sequence of str or pairs that
"""
@six.add_metaclass(_RecordMetaClass)
class RecordType(object):
_record_sentinel = True
_record_fields = fields
return RecordType | python | def record(*fields):
"""Constructs a type that can be extended to create immutable, value types.
Examples:
A typical declaration looks like::
class MyRecord(record('a', ('b', 1))):
pass
The above would make a sub-class of ``collections.namedtuple`` that was named ``MyRecord`` with
a constructor that had the ``b`` field set to 1 by default.
Note:
This uses meta-class machinery to rewrite the inheritance hierarchy.
This is done in order to make sure that the underlying ``namedtuple`` instance is
bound to the right type name and to make sure that the synthetic class that is generated
to enable this machinery is not enabled for sub-classes of a user's record class.
Args:
fields (list[str | (str, any)]): A sequence of str or pairs that
"""
@six.add_metaclass(_RecordMetaClass)
class RecordType(object):
_record_sentinel = True
_record_fields = fields
return RecordType | [
"def",
"record",
"(",
"*",
"fields",
")",
":",
"@",
"six",
".",
"add_metaclass",
"(",
"_RecordMetaClass",
")",
"class",
"RecordType",
"(",
"object",
")",
":",
"_record_sentinel",
"=",
"True",
"_record_fields",
"=",
"fields",
"return",
"RecordType"
] | Constructs a type that can be extended to create immutable, value types.
Examples:
A typical declaration looks like::
class MyRecord(record('a', ('b', 1))):
pass
The above would make a sub-class of ``collections.namedtuple`` that was named ``MyRecord`` with
a constructor that had the ``b`` field set to 1 by default.
Note:
This uses meta-class machinery to rewrite the inheritance hierarchy.
This is done in order to make sure that the underlying ``namedtuple`` instance is
bound to the right type name and to make sure that the synthetic class that is generated
to enable this machinery is not enabled for sub-classes of a user's record class.
Args:
fields (list[str | (str, any)]): A sequence of str or pairs that | [
"Constructs",
"a",
"type",
"that",
"can",
"be",
"extended",
"to",
"create",
"immutable",
"value",
"types",
"."
] | 0b21fa3ba7755f55f745e4aa970d86343b82449d | https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/util.py#L137-L163 | train | 233,831 |
amzn/ion-python | amazon/ion/util.py | coroutine | def coroutine(func):
"""Wraps a PEP-342 enhanced generator in a way that avoids boilerplate of the "priming" call to ``next``.
Args:
func (Callable): The function constructing a generator to decorate.
Returns:
Callable: The decorated generator.
"""
def wrapper(*args, **kwargs):
gen = func(*args, **kwargs)
val = next(gen)
if val != None:
raise TypeError('Unexpected value from start of coroutine')
return gen
wrapper.__name__ = func.__name__
wrapper.__doc__ = func.__doc__
return wrapper | python | def coroutine(func):
"""Wraps a PEP-342 enhanced generator in a way that avoids boilerplate of the "priming" call to ``next``.
Args:
func (Callable): The function constructing a generator to decorate.
Returns:
Callable: The decorated generator.
"""
def wrapper(*args, **kwargs):
gen = func(*args, **kwargs)
val = next(gen)
if val != None:
raise TypeError('Unexpected value from start of coroutine')
return gen
wrapper.__name__ = func.__name__
wrapper.__doc__ = func.__doc__
return wrapper | [
"def",
"coroutine",
"(",
"func",
")",
":",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"gen",
"=",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"val",
"=",
"next",
"(",
"gen",
")",
"if",
"val",
"!=",
"None",
":",
"raise",
"TypeError",
"(",
"'Unexpected value from start of coroutine'",
")",
"return",
"gen",
"wrapper",
".",
"__name__",
"=",
"func",
".",
"__name__",
"wrapper",
".",
"__doc__",
"=",
"func",
".",
"__doc__",
"return",
"wrapper"
] | Wraps a PEP-342 enhanced generator in a way that avoids boilerplate of the "priming" call to ``next``.
Args:
func (Callable): The function constructing a generator to decorate.
Returns:
Callable: The decorated generator. | [
"Wraps",
"a",
"PEP",
"-",
"342",
"enhanced",
"generator",
"in",
"a",
"way",
"that",
"avoids",
"boilerplate",
"of",
"the",
"priming",
"call",
"to",
"next",
"."
] | 0b21fa3ba7755f55f745e4aa970d86343b82449d | https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/util.py#L166-L183 | train | 233,832 |
amzn/ion-python | amazon/ion/core.py | IonEvent.derive_field_name | def derive_field_name(self, field_name):
"""Derives a new event from this one setting the ``field_name`` attribute.
Args:
field_name (Union[amazon.ion.symbols.SymbolToken, unicode]): The field name to set.
Returns:
IonEvent: The newly generated event.
"""
cls = type(self)
# We use ordinals to avoid thunk materialization.
return cls(
self[0],
self[1],
self[2],
field_name,
self[4],
self[5]
) | python | def derive_field_name(self, field_name):
"""Derives a new event from this one setting the ``field_name`` attribute.
Args:
field_name (Union[amazon.ion.symbols.SymbolToken, unicode]): The field name to set.
Returns:
IonEvent: The newly generated event.
"""
cls = type(self)
# We use ordinals to avoid thunk materialization.
return cls(
self[0],
self[1],
self[2],
field_name,
self[4],
self[5]
) | [
"def",
"derive_field_name",
"(",
"self",
",",
"field_name",
")",
":",
"cls",
"=",
"type",
"(",
"self",
")",
"# We use ordinals to avoid thunk materialization.",
"return",
"cls",
"(",
"self",
"[",
"0",
"]",
",",
"self",
"[",
"1",
"]",
",",
"self",
"[",
"2",
"]",
",",
"field_name",
",",
"self",
"[",
"4",
"]",
",",
"self",
"[",
"5",
"]",
")"
] | Derives a new event from this one setting the ``field_name`` attribute.
Args:
field_name (Union[amazon.ion.symbols.SymbolToken, unicode]): The field name to set.
Returns:
IonEvent: The newly generated event. | [
"Derives",
"a",
"new",
"event",
"from",
"this",
"one",
"setting",
"the",
"field_name",
"attribute",
"."
] | 0b21fa3ba7755f55f745e4aa970d86343b82449d | https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/core.py#L163-L180 | train | 233,833 |
amzn/ion-python | amazon/ion/core.py | IonEvent.derive_annotations | def derive_annotations(self, annotations):
"""Derives a new event from this one setting the ``annotations`` attribute.
Args:
annotations: (Sequence[Union[amazon.ion.symbols.SymbolToken, unicode]]):
The annotations associated with the derived event.
Returns:
IonEvent: The newly generated event.
"""
cls = type(self)
# We use ordinals to avoid thunk materialization.
return cls(
self[0],
self[1],
self[2],
self[3],
annotations,
self[5]
) | python | def derive_annotations(self, annotations):
"""Derives a new event from this one setting the ``annotations`` attribute.
Args:
annotations: (Sequence[Union[amazon.ion.symbols.SymbolToken, unicode]]):
The annotations associated with the derived event.
Returns:
IonEvent: The newly generated event.
"""
cls = type(self)
# We use ordinals to avoid thunk materialization.
return cls(
self[0],
self[1],
self[2],
self[3],
annotations,
self[5]
) | [
"def",
"derive_annotations",
"(",
"self",
",",
"annotations",
")",
":",
"cls",
"=",
"type",
"(",
"self",
")",
"# We use ordinals to avoid thunk materialization.",
"return",
"cls",
"(",
"self",
"[",
"0",
"]",
",",
"self",
"[",
"1",
"]",
",",
"self",
"[",
"2",
"]",
",",
"self",
"[",
"3",
"]",
",",
"annotations",
",",
"self",
"[",
"5",
"]",
")"
] | Derives a new event from this one setting the ``annotations`` attribute.
Args:
annotations: (Sequence[Union[amazon.ion.symbols.SymbolToken, unicode]]):
The annotations associated with the derived event.
Returns:
IonEvent: The newly generated event. | [
"Derives",
"a",
"new",
"event",
"from",
"this",
"one",
"setting",
"the",
"annotations",
"attribute",
"."
] | 0b21fa3ba7755f55f745e4aa970d86343b82449d | https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/core.py#L182-L201 | train | 233,834 |
amzn/ion-python | amazon/ion/core.py | IonEvent.derive_value | def derive_value(self, value):
"""Derives a new event from this one setting the ``value`` attribute.
Args:
value: (any):
The value associated with the derived event.
Returns:
IonEvent: The newly generated non-thunk event.
"""
return IonEvent(
self.event_type,
self.ion_type,
value,
self.field_name,
self.annotations,
self.depth
) | python | def derive_value(self, value):
"""Derives a new event from this one setting the ``value`` attribute.
Args:
value: (any):
The value associated with the derived event.
Returns:
IonEvent: The newly generated non-thunk event.
"""
return IonEvent(
self.event_type,
self.ion_type,
value,
self.field_name,
self.annotations,
self.depth
) | [
"def",
"derive_value",
"(",
"self",
",",
"value",
")",
":",
"return",
"IonEvent",
"(",
"self",
".",
"event_type",
",",
"self",
".",
"ion_type",
",",
"value",
",",
"self",
".",
"field_name",
",",
"self",
".",
"annotations",
",",
"self",
".",
"depth",
")"
] | Derives a new event from this one setting the ``value`` attribute.
Args:
value: (any):
The value associated with the derived event.
Returns:
IonEvent: The newly generated non-thunk event. | [
"Derives",
"a",
"new",
"event",
"from",
"this",
"one",
"setting",
"the",
"value",
"attribute",
"."
] | 0b21fa3ba7755f55f745e4aa970d86343b82449d | https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/core.py#L203-L220 | train | 233,835 |
amzn/ion-python | amazon/ion/core.py | IonEvent.derive_depth | def derive_depth(self, depth):
"""Derives a new event from this one setting the ``depth`` attribute.
Args:
depth: (int):
The annotations associated with the derived event.
Returns:
IonEvent: The newly generated event.
"""
cls = type(self)
# We use ordinals to avoid thunk materialization.
return cls(
self[0],
self[1],
self[2],
self[3],
self[4],
depth
) | python | def derive_depth(self, depth):
"""Derives a new event from this one setting the ``depth`` attribute.
Args:
depth: (int):
The annotations associated with the derived event.
Returns:
IonEvent: The newly generated event.
"""
cls = type(self)
# We use ordinals to avoid thunk materialization.
return cls(
self[0],
self[1],
self[2],
self[3],
self[4],
depth
) | [
"def",
"derive_depth",
"(",
"self",
",",
"depth",
")",
":",
"cls",
"=",
"type",
"(",
"self",
")",
"# We use ordinals to avoid thunk materialization.",
"return",
"cls",
"(",
"self",
"[",
"0",
"]",
",",
"self",
"[",
"1",
"]",
",",
"self",
"[",
"2",
"]",
",",
"self",
"[",
"3",
"]",
",",
"self",
"[",
"4",
"]",
",",
"depth",
")"
] | Derives a new event from this one setting the ``depth`` attribute.
Args:
depth: (int):
The annotations associated with the derived event.
Returns:
IonEvent: The newly generated event. | [
"Derives",
"a",
"new",
"event",
"from",
"this",
"one",
"setting",
"the",
"depth",
"attribute",
"."
] | 0b21fa3ba7755f55f745e4aa970d86343b82449d | https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/core.py#L222-L241 | train | 233,836 |
amzn/ion-python | amazon/ion/core.py | Timestamp.adjust_from_utc_fields | def adjust_from_utc_fields(*args, **kwargs):
"""Constructs a timestamp from UTC fields adjusted to the local offset if given."""
raw_ts = Timestamp(*args, **kwargs)
offset = raw_ts.utcoffset()
if offset is None or offset == timedelta():
return raw_ts
# XXX This returns a datetime, not a Timestamp (which has our precision if defined)
adjusted = raw_ts + offset
if raw_ts.precision is None:
# No precision means we can just return a regular datetime
return adjusted
return Timestamp(
adjusted.year,
adjusted.month,
adjusted.day,
adjusted.hour,
adjusted.minute,
adjusted.second,
adjusted.microsecond,
raw_ts.tzinfo,
precision=raw_ts.precision,
fractional_precision=raw_ts.fractional_precision
) | python | def adjust_from_utc_fields(*args, **kwargs):
"""Constructs a timestamp from UTC fields adjusted to the local offset if given."""
raw_ts = Timestamp(*args, **kwargs)
offset = raw_ts.utcoffset()
if offset is None or offset == timedelta():
return raw_ts
# XXX This returns a datetime, not a Timestamp (which has our precision if defined)
adjusted = raw_ts + offset
if raw_ts.precision is None:
# No precision means we can just return a regular datetime
return adjusted
return Timestamp(
adjusted.year,
adjusted.month,
adjusted.day,
adjusted.hour,
adjusted.minute,
adjusted.second,
adjusted.microsecond,
raw_ts.tzinfo,
precision=raw_ts.precision,
fractional_precision=raw_ts.fractional_precision
) | [
"def",
"adjust_from_utc_fields",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"raw_ts",
"=",
"Timestamp",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"offset",
"=",
"raw_ts",
".",
"utcoffset",
"(",
")",
"if",
"offset",
"is",
"None",
"or",
"offset",
"==",
"timedelta",
"(",
")",
":",
"return",
"raw_ts",
"# XXX This returns a datetime, not a Timestamp (which has our precision if defined)",
"adjusted",
"=",
"raw_ts",
"+",
"offset",
"if",
"raw_ts",
".",
"precision",
"is",
"None",
":",
"# No precision means we can just return a regular datetime",
"return",
"adjusted",
"return",
"Timestamp",
"(",
"adjusted",
".",
"year",
",",
"adjusted",
".",
"month",
",",
"adjusted",
".",
"day",
",",
"adjusted",
".",
"hour",
",",
"adjusted",
".",
"minute",
",",
"adjusted",
".",
"second",
",",
"adjusted",
".",
"microsecond",
",",
"raw_ts",
".",
"tzinfo",
",",
"precision",
"=",
"raw_ts",
".",
"precision",
",",
"fractional_precision",
"=",
"raw_ts",
".",
"fractional_precision",
")"
] | Constructs a timestamp from UTC fields adjusted to the local offset if given. | [
"Constructs",
"a",
"timestamp",
"from",
"UTC",
"fields",
"adjusted",
"to",
"the",
"local",
"offset",
"if",
"given",
"."
] | 0b21fa3ba7755f55f745e4aa970d86343b82449d | https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/core.py#L410-L434 | train | 233,837 |
amzn/ion-python | amazon/ion/writer_text.py | raw_writer | def raw_writer(indent=None):
"""Returns a raw text writer co-routine.
Yields:
DataEvent: serialization events to write out
Receives :class:`amazon.ion.core.IonEvent` or ``None`` when the co-routine yields
``HAS_PENDING`` :class:`WriteEventType` events.
"""
is_whitespace_str = isinstance(indent, str) and re.search(r'\A\s*\Z', indent, re.M) is not None
if not (indent is None or is_whitespace_str):
raise ValueError('The indent parameter must either be None or a string containing only whitespace')
indent_bytes = six.b(indent) if isinstance(indent, str) else indent
return writer_trampoline(_raw_writer_coroutine(indent=indent_bytes)) | python | def raw_writer(indent=None):
"""Returns a raw text writer co-routine.
Yields:
DataEvent: serialization events to write out
Receives :class:`amazon.ion.core.IonEvent` or ``None`` when the co-routine yields
``HAS_PENDING`` :class:`WriteEventType` events.
"""
is_whitespace_str = isinstance(indent, str) and re.search(r'\A\s*\Z', indent, re.M) is not None
if not (indent is None or is_whitespace_str):
raise ValueError('The indent parameter must either be None or a string containing only whitespace')
indent_bytes = six.b(indent) if isinstance(indent, str) else indent
return writer_trampoline(_raw_writer_coroutine(indent=indent_bytes)) | [
"def",
"raw_writer",
"(",
"indent",
"=",
"None",
")",
":",
"is_whitespace_str",
"=",
"isinstance",
"(",
"indent",
",",
"str",
")",
"and",
"re",
".",
"search",
"(",
"r'\\A\\s*\\Z'",
",",
"indent",
",",
"re",
".",
"M",
")",
"is",
"not",
"None",
"if",
"not",
"(",
"indent",
"is",
"None",
"or",
"is_whitespace_str",
")",
":",
"raise",
"ValueError",
"(",
"'The indent parameter must either be None or a string containing only whitespace'",
")",
"indent_bytes",
"=",
"six",
".",
"b",
"(",
"indent",
")",
"if",
"isinstance",
"(",
"indent",
",",
"str",
")",
"else",
"indent",
"return",
"writer_trampoline",
"(",
"_raw_writer_coroutine",
"(",
"indent",
"=",
"indent_bytes",
")",
")"
] | Returns a raw text writer co-routine.
Yields:
DataEvent: serialization events to write out
Receives :class:`amazon.ion.core.IonEvent` or ``None`` when the co-routine yields
``HAS_PENDING`` :class:`WriteEventType` events. | [
"Returns",
"a",
"raw",
"text",
"writer",
"co",
"-",
"routine",
"."
] | 0b21fa3ba7755f55f745e4aa970d86343b82449d | https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/writer_text.py#L433-L449 | train | 233,838 |
amzn/ion-python | amazon/ion/writer.py | writer_trampoline | def writer_trampoline(start):
"""Provides the co-routine trampoline for a writer state machine.
The given co-routine is a state machine that yields :class:`Transition` and takes
a :class:`Transition` with a :class:`amazon.ion.core.IonEvent` and the co-routine itself.
Notes:
A writer delimits its logical flush points with ``WriteEventType.COMPLETE``, depending
on the configuration, a user may need to send an ``IonEventType.STREAM_END`` to
force this to occur.
Args:
start: The writer co-routine to initially delegate to.
Yields:
DataEvent: the result of serialization.
Receives :class:`amazon.ion.core.IonEvent` to serialize into :class:`DataEvent`.
"""
trans = Transition(None, start)
while True:
ion_event = (yield trans.event)
if trans.event is None:
if ion_event is None:
raise TypeError('Cannot start Writer with no event')
else:
if trans.event.type is WriteEventType.HAS_PENDING and ion_event is not None:
raise TypeError('Writer expected to receive no event: %r' % (ion_event,))
if trans.event.type is not WriteEventType.HAS_PENDING and ion_event is None:
raise TypeError('Writer expected to receive event')
if ion_event is not None and ion_event.event_type is IonEventType.INCOMPLETE:
raise TypeError('Writer cannot receive INCOMPLETE event')
trans = trans.delegate.send(Transition(ion_event, trans.delegate)) | python | def writer_trampoline(start):
"""Provides the co-routine trampoline for a writer state machine.
The given co-routine is a state machine that yields :class:`Transition` and takes
a :class:`Transition` with a :class:`amazon.ion.core.IonEvent` and the co-routine itself.
Notes:
A writer delimits its logical flush points with ``WriteEventType.COMPLETE``, depending
on the configuration, a user may need to send an ``IonEventType.STREAM_END`` to
force this to occur.
Args:
start: The writer co-routine to initially delegate to.
Yields:
DataEvent: the result of serialization.
Receives :class:`amazon.ion.core.IonEvent` to serialize into :class:`DataEvent`.
"""
trans = Transition(None, start)
while True:
ion_event = (yield trans.event)
if trans.event is None:
if ion_event is None:
raise TypeError('Cannot start Writer with no event')
else:
if trans.event.type is WriteEventType.HAS_PENDING and ion_event is not None:
raise TypeError('Writer expected to receive no event: %r' % (ion_event,))
if trans.event.type is not WriteEventType.HAS_PENDING and ion_event is None:
raise TypeError('Writer expected to receive event')
if ion_event is not None and ion_event.event_type is IonEventType.INCOMPLETE:
raise TypeError('Writer cannot receive INCOMPLETE event')
trans = trans.delegate.send(Transition(ion_event, trans.delegate)) | [
"def",
"writer_trampoline",
"(",
"start",
")",
":",
"trans",
"=",
"Transition",
"(",
"None",
",",
"start",
")",
"while",
"True",
":",
"ion_event",
"=",
"(",
"yield",
"trans",
".",
"event",
")",
"if",
"trans",
".",
"event",
"is",
"None",
":",
"if",
"ion_event",
"is",
"None",
":",
"raise",
"TypeError",
"(",
"'Cannot start Writer with no event'",
")",
"else",
":",
"if",
"trans",
".",
"event",
".",
"type",
"is",
"WriteEventType",
".",
"HAS_PENDING",
"and",
"ion_event",
"is",
"not",
"None",
":",
"raise",
"TypeError",
"(",
"'Writer expected to receive no event: %r'",
"%",
"(",
"ion_event",
",",
")",
")",
"if",
"trans",
".",
"event",
".",
"type",
"is",
"not",
"WriteEventType",
".",
"HAS_PENDING",
"and",
"ion_event",
"is",
"None",
":",
"raise",
"TypeError",
"(",
"'Writer expected to receive event'",
")",
"if",
"ion_event",
"is",
"not",
"None",
"and",
"ion_event",
".",
"event_type",
"is",
"IonEventType",
".",
"INCOMPLETE",
":",
"raise",
"TypeError",
"(",
"'Writer cannot receive INCOMPLETE event'",
")",
"trans",
"=",
"trans",
".",
"delegate",
".",
"send",
"(",
"Transition",
"(",
"ion_event",
",",
"trans",
".",
"delegate",
")",
")"
] | Provides the co-routine trampoline for a writer state machine.
The given co-routine is a state machine that yields :class:`Transition` and takes
a :class:`Transition` with a :class:`amazon.ion.core.IonEvent` and the co-routine itself.
Notes:
A writer delimits its logical flush points with ``WriteEventType.COMPLETE``, depending
on the configuration, a user may need to send an ``IonEventType.STREAM_END`` to
force this to occur.
Args:
start: The writer co-routine to initially delegate to.
Yields:
DataEvent: the result of serialization.
Receives :class:`amazon.ion.core.IonEvent` to serialize into :class:`DataEvent`. | [
"Provides",
"the",
"co",
"-",
"routine",
"trampoline",
"for",
"a",
"writer",
"state",
"machine",
"."
] | 0b21fa3ba7755f55f745e4aa970d86343b82449d | https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/writer.py#L79-L111 | train | 233,839 |
amzn/ion-python | amazon/ion/writer.py | _drain | def _drain(writer, ion_event):
"""Drain the writer of its pending write events.
Args:
writer (Coroutine): A writer co-routine.
ion_event (amazon.ion.core.IonEvent): The first event to apply to the writer.
Yields:
DataEvent: Yields each pending data event.
"""
result_event = _WRITE_EVENT_HAS_PENDING_EMPTY
while result_event.type is WriteEventType.HAS_PENDING:
result_event = writer.send(ion_event)
ion_event = None
yield result_event | python | def _drain(writer, ion_event):
"""Drain the writer of its pending write events.
Args:
writer (Coroutine): A writer co-routine.
ion_event (amazon.ion.core.IonEvent): The first event to apply to the writer.
Yields:
DataEvent: Yields each pending data event.
"""
result_event = _WRITE_EVENT_HAS_PENDING_EMPTY
while result_event.type is WriteEventType.HAS_PENDING:
result_event = writer.send(ion_event)
ion_event = None
yield result_event | [
"def",
"_drain",
"(",
"writer",
",",
"ion_event",
")",
":",
"result_event",
"=",
"_WRITE_EVENT_HAS_PENDING_EMPTY",
"while",
"result_event",
".",
"type",
"is",
"WriteEventType",
".",
"HAS_PENDING",
":",
"result_event",
"=",
"writer",
".",
"send",
"(",
"ion_event",
")",
"ion_event",
"=",
"None",
"yield",
"result_event"
] | Drain the writer of its pending write events.
Args:
writer (Coroutine): A writer co-routine.
ion_event (amazon.ion.core.IonEvent): The first event to apply to the writer.
Yields:
DataEvent: Yields each pending data event. | [
"Drain",
"the",
"writer",
"of",
"its",
"pending",
"write",
"events",
"."
] | 0b21fa3ba7755f55f745e4aa970d86343b82449d | https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/writer.py#L117-L131 | train | 233,840 |
amzn/ion-python | amazon/ion/writer.py | blocking_writer | def blocking_writer(writer, output):
"""Provides an implementation of using the writer co-routine with a file-like object.
Args:
writer (Coroutine): A writer co-routine.
output (BaseIO): The file-like object to pipe events to.
Yields:
WriteEventType: Yields when no events are pending.
Receives :class:`amazon.ion.core.IonEvent` to write to the ``output``.
"""
result_type = None
while True:
ion_event = (yield result_type)
for result_event in _drain(writer, ion_event):
output.write(result_event.data)
result_type = result_event.type | python | def blocking_writer(writer, output):
"""Provides an implementation of using the writer co-routine with a file-like object.
Args:
writer (Coroutine): A writer co-routine.
output (BaseIO): The file-like object to pipe events to.
Yields:
WriteEventType: Yields when no events are pending.
Receives :class:`amazon.ion.core.IonEvent` to write to the ``output``.
"""
result_type = None
while True:
ion_event = (yield result_type)
for result_event in _drain(writer, ion_event):
output.write(result_event.data)
result_type = result_event.type | [
"def",
"blocking_writer",
"(",
"writer",
",",
"output",
")",
":",
"result_type",
"=",
"None",
"while",
"True",
":",
"ion_event",
"=",
"(",
"yield",
"result_type",
")",
"for",
"result_event",
"in",
"_drain",
"(",
"writer",
",",
"ion_event",
")",
":",
"output",
".",
"write",
"(",
"result_event",
".",
"data",
")",
"result_type",
"=",
"result_event",
".",
"type"
] | Provides an implementation of using the writer co-routine with a file-like object.
Args:
writer (Coroutine): A writer co-routine.
output (BaseIO): The file-like object to pipe events to.
Yields:
WriteEventType: Yields when no events are pending.
Receives :class:`amazon.ion.core.IonEvent` to write to the ``output``. | [
"Provides",
"an",
"implementation",
"of",
"using",
"the",
"writer",
"co",
"-",
"routine",
"with",
"a",
"file",
"-",
"like",
"object",
"."
] | 0b21fa3ba7755f55f745e4aa970d86343b82449d | https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/writer.py#L135-L152 | train | 233,841 |
amzn/ion-python | amazon/ion/simple_types.py | _IonNature.from_event | def from_event(cls, ion_event):
"""Constructs the given native extension from the properties of an event.
Args:
ion_event (IonEvent): The event to construct the native value from.
"""
if ion_event.value is not None:
args, kwargs = cls._to_constructor_args(ion_event.value)
else:
# if value is None (i.e. this is a container event), args must be empty or initialization of the
# underlying container will fail.
args, kwargs = (), {}
value = cls(*args, **kwargs)
value.ion_event = ion_event
value.ion_type = ion_event.ion_type
value.ion_annotations = ion_event.annotations
return value | python | def from_event(cls, ion_event):
"""Constructs the given native extension from the properties of an event.
Args:
ion_event (IonEvent): The event to construct the native value from.
"""
if ion_event.value is not None:
args, kwargs = cls._to_constructor_args(ion_event.value)
else:
# if value is None (i.e. this is a container event), args must be empty or initialization of the
# underlying container will fail.
args, kwargs = (), {}
value = cls(*args, **kwargs)
value.ion_event = ion_event
value.ion_type = ion_event.ion_type
value.ion_annotations = ion_event.annotations
return value | [
"def",
"from_event",
"(",
"cls",
",",
"ion_event",
")",
":",
"if",
"ion_event",
".",
"value",
"is",
"not",
"None",
":",
"args",
",",
"kwargs",
"=",
"cls",
".",
"_to_constructor_args",
"(",
"ion_event",
".",
"value",
")",
"else",
":",
"# if value is None (i.e. this is a container event), args must be empty or initialization of the",
"# underlying container will fail.",
"args",
",",
"kwargs",
"=",
"(",
")",
",",
"{",
"}",
"value",
"=",
"cls",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"value",
".",
"ion_event",
"=",
"ion_event",
"value",
".",
"ion_type",
"=",
"ion_event",
".",
"ion_type",
"value",
".",
"ion_annotations",
"=",
"ion_event",
".",
"annotations",
"return",
"value"
] | Constructs the given native extension from the properties of an event.
Args:
ion_event (IonEvent): The event to construct the native value from. | [
"Constructs",
"the",
"given",
"native",
"extension",
"from",
"the",
"properties",
"of",
"an",
"event",
"."
] | 0b21fa3ba7755f55f745e4aa970d86343b82449d | https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/simple_types.py#L74-L90 | train | 233,842 |
amzn/ion-python | amazon/ion/simple_types.py | _IonNature.from_value | def from_value(cls, ion_type, value, annotations=()):
"""Constructs a value as a copy with an associated Ion type and annotations.
Args:
ion_type (IonType): The associated Ion type.
value (Any): The value to construct from, generally of type ``cls``.
annotations (Sequence[unicode]): The sequence Unicode strings decorating this value.
"""
if value is None:
value = IonPyNull()
else:
args, kwargs = cls._to_constructor_args(value)
value = cls(*args, **kwargs)
value.ion_event = None
value.ion_type = ion_type
value.ion_annotations = annotations
return value | python | def from_value(cls, ion_type, value, annotations=()):
"""Constructs a value as a copy with an associated Ion type and annotations.
Args:
ion_type (IonType): The associated Ion type.
value (Any): The value to construct from, generally of type ``cls``.
annotations (Sequence[unicode]): The sequence Unicode strings decorating this value.
"""
if value is None:
value = IonPyNull()
else:
args, kwargs = cls._to_constructor_args(value)
value = cls(*args, **kwargs)
value.ion_event = None
value.ion_type = ion_type
value.ion_annotations = annotations
return value | [
"def",
"from_value",
"(",
"cls",
",",
"ion_type",
",",
"value",
",",
"annotations",
"=",
"(",
")",
")",
":",
"if",
"value",
"is",
"None",
":",
"value",
"=",
"IonPyNull",
"(",
")",
"else",
":",
"args",
",",
"kwargs",
"=",
"cls",
".",
"_to_constructor_args",
"(",
"value",
")",
"value",
"=",
"cls",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"value",
".",
"ion_event",
"=",
"None",
"value",
".",
"ion_type",
"=",
"ion_type",
"value",
".",
"ion_annotations",
"=",
"annotations",
"return",
"value"
] | Constructs a value as a copy with an associated Ion type and annotations.
Args:
ion_type (IonType): The associated Ion type.
value (Any): The value to construct from, generally of type ``cls``.
annotations (Sequence[unicode]): The sequence Unicode strings decorating this value. | [
"Constructs",
"a",
"value",
"as",
"a",
"copy",
"with",
"an",
"associated",
"Ion",
"type",
"and",
"annotations",
"."
] | 0b21fa3ba7755f55f745e4aa970d86343b82449d | https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/simple_types.py#L93-L109 | train | 233,843 |
amzn/ion-python | amazon/ion/simple_types.py | _IonNature.to_event | def to_event(self, event_type, field_name=None, depth=None):
"""Constructs an IonEvent from this _IonNature value.
Args:
event_type (IonEventType): The type of the resulting event.
field_name (Optional[text]): The field name associated with this value, if any.
depth (Optional[int]): The depth of this value.
Returns:
An IonEvent with the properties from this value.
"""
if self.ion_event is None:
value = self
if isinstance(self, IonPyNull):
value = None
self.ion_event = IonEvent(event_type, ion_type=self.ion_type, value=value, field_name=field_name,
annotations=self.ion_annotations, depth=depth)
return self.ion_event | python | def to_event(self, event_type, field_name=None, depth=None):
"""Constructs an IonEvent from this _IonNature value.
Args:
event_type (IonEventType): The type of the resulting event.
field_name (Optional[text]): The field name associated with this value, if any.
depth (Optional[int]): The depth of this value.
Returns:
An IonEvent with the properties from this value.
"""
if self.ion_event is None:
value = self
if isinstance(self, IonPyNull):
value = None
self.ion_event = IonEvent(event_type, ion_type=self.ion_type, value=value, field_name=field_name,
annotations=self.ion_annotations, depth=depth)
return self.ion_event | [
"def",
"to_event",
"(",
"self",
",",
"event_type",
",",
"field_name",
"=",
"None",
",",
"depth",
"=",
"None",
")",
":",
"if",
"self",
".",
"ion_event",
"is",
"None",
":",
"value",
"=",
"self",
"if",
"isinstance",
"(",
"self",
",",
"IonPyNull",
")",
":",
"value",
"=",
"None",
"self",
".",
"ion_event",
"=",
"IonEvent",
"(",
"event_type",
",",
"ion_type",
"=",
"self",
".",
"ion_type",
",",
"value",
"=",
"value",
",",
"field_name",
"=",
"field_name",
",",
"annotations",
"=",
"self",
".",
"ion_annotations",
",",
"depth",
"=",
"depth",
")",
"return",
"self",
".",
"ion_event"
] | Constructs an IonEvent from this _IonNature value.
Args:
event_type (IonEventType): The type of the resulting event.
field_name (Optional[text]): The field name associated with this value, if any.
depth (Optional[int]): The depth of this value.
Returns:
An IonEvent with the properties from this value. | [
"Constructs",
"an",
"IonEvent",
"from",
"this",
"_IonNature",
"value",
"."
] | 0b21fa3ba7755f55f745e4aa970d86343b82449d | https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/simple_types.py#L111-L128 | train | 233,844 |
XML-Security/signxml | signxml/__init__.py | _remove_sig | def _remove_sig(signature, idempotent=False):
"""
Remove the signature node from its parent, keeping any tail element.
This is needed for eneveloped signatures.
:param signature: Signature to remove from payload
:type signature: XML ElementTree Element
:param idempotent:
If True, don't raise an error if signature is already detached from parent.
:type idempotent: boolean
"""
try:
signaturep = next(signature.iterancestors())
except StopIteration:
if idempotent:
return
raise ValueError("Can't remove the root signature node")
if signature.tail is not None:
try:
signatures = next(signature.itersiblings(preceding=True))
except StopIteration:
if signaturep.text is not None:
signaturep.text = signaturep.text + signature.tail
else:
signaturep.text = signature.tail
else:
if signatures.tail is not None:
signatures.tail = signatures.tail + signature.tail
else:
signatures.tail = signature.tail
signaturep.remove(signature) | python | def _remove_sig(signature, idempotent=False):
"""
Remove the signature node from its parent, keeping any tail element.
This is needed for eneveloped signatures.
:param signature: Signature to remove from payload
:type signature: XML ElementTree Element
:param idempotent:
If True, don't raise an error if signature is already detached from parent.
:type idempotent: boolean
"""
try:
signaturep = next(signature.iterancestors())
except StopIteration:
if idempotent:
return
raise ValueError("Can't remove the root signature node")
if signature.tail is not None:
try:
signatures = next(signature.itersiblings(preceding=True))
except StopIteration:
if signaturep.text is not None:
signaturep.text = signaturep.text + signature.tail
else:
signaturep.text = signature.tail
else:
if signatures.tail is not None:
signatures.tail = signatures.tail + signature.tail
else:
signatures.tail = signature.tail
signaturep.remove(signature) | [
"def",
"_remove_sig",
"(",
"signature",
",",
"idempotent",
"=",
"False",
")",
":",
"try",
":",
"signaturep",
"=",
"next",
"(",
"signature",
".",
"iterancestors",
"(",
")",
")",
"except",
"StopIteration",
":",
"if",
"idempotent",
":",
"return",
"raise",
"ValueError",
"(",
"\"Can't remove the root signature node\"",
")",
"if",
"signature",
".",
"tail",
"is",
"not",
"None",
":",
"try",
":",
"signatures",
"=",
"next",
"(",
"signature",
".",
"itersiblings",
"(",
"preceding",
"=",
"True",
")",
")",
"except",
"StopIteration",
":",
"if",
"signaturep",
".",
"text",
"is",
"not",
"None",
":",
"signaturep",
".",
"text",
"=",
"signaturep",
".",
"text",
"+",
"signature",
".",
"tail",
"else",
":",
"signaturep",
".",
"text",
"=",
"signature",
".",
"tail",
"else",
":",
"if",
"signatures",
".",
"tail",
"is",
"not",
"None",
":",
"signatures",
".",
"tail",
"=",
"signatures",
".",
"tail",
"+",
"signature",
".",
"tail",
"else",
":",
"signatures",
".",
"tail",
"=",
"signature",
".",
"tail",
"signaturep",
".",
"remove",
"(",
"signature",
")"
] | Remove the signature node from its parent, keeping any tail element.
This is needed for eneveloped signatures.
:param signature: Signature to remove from payload
:type signature: XML ElementTree Element
:param idempotent:
If True, don't raise an error if signature is already detached from parent.
:type idempotent: boolean | [
"Remove",
"the",
"signature",
"node",
"from",
"its",
"parent",
"keeping",
"any",
"tail",
"element",
".",
"This",
"is",
"needed",
"for",
"eneveloped",
"signatures",
"."
] | 16503242617e9b25e5c2c9ced5ef18a06ffde146 | https://github.com/XML-Security/signxml/blob/16503242617e9b25e5c2c9ced5ef18a06ffde146/signxml/__init__.py#L39-L69 | train | 233,845 |
cenkalti/github-flask | flask_github.py | GitHub.authorize | def authorize(self, scope=None, redirect_uri=None, state=None):
"""
Redirect to GitHub and request access to a user's data.
:param scope: List of `Scopes`_ for which to request access, formatted
as a string or comma delimited list of scopes as a
string. Defaults to ``None``, resulting in granting
read-only access to public information (includes public
user profile info, public repository info, and gists).
For more information on this, see the examples in
presented in the GitHub API `Scopes`_ documentation, or
see the examples provided below.
:type scope: str
:param redirect_uri: `Redirect URL`_ to which to redirect the user
after authentication. Defaults to ``None``,
resulting in using the default redirect URL for
the OAuth application as defined in GitHub. This
URL can differ from the callback URL defined in
your GitHub application, however it must be a
subdirectory of the specified callback URL,
otherwise raises a :class:`GitHubError`. For more
information on this, see the examples in presented
in the GitHub API `Redirect URL`_ documentation,
or see the example provided below.
:type redirect_uri: str
:param state: An unguessable random string. It is used to protect
against cross-site request forgery attacks.
:type state: str
For example, if we wanted to use this method to get read/write access
to user profile information, in addition to read-write access to code,
commit status, etc., we would need to use the `Scopes`_ ``user`` and
``repo`` when calling this method.
.. code-block:: python
github.authorize(scope="user,repo")
Additionally, if we wanted to specify a different redirect URL
following authorization.
.. code-block:: python
# Our application's callback URL is "http://example.com/callback"
redirect_uri="http://example.com/callback/my/path"
github.authorize(scope="user,repo", redirect_uri=redirect_uri)
.. _Scopes: https://developer.github.com/v3/oauth/#scopes
.. _Redirect URL: https://developer.github.com/v3/oauth/#redirect-urls
"""
_logger.debug("Called authorize()")
params = {'client_id': self.client_id}
if scope:
params['scope'] = scope
if redirect_uri:
params['redirect_uri'] = redirect_uri
if state:
params['state'] = state
url = self.auth_url + 'authorize?' + urlencode(params)
_logger.debug("Redirecting to %s", url)
return redirect(url) | python | def authorize(self, scope=None, redirect_uri=None, state=None):
"""
Redirect to GitHub and request access to a user's data.
:param scope: List of `Scopes`_ for which to request access, formatted
as a string or comma delimited list of scopes as a
string. Defaults to ``None``, resulting in granting
read-only access to public information (includes public
user profile info, public repository info, and gists).
For more information on this, see the examples in
presented in the GitHub API `Scopes`_ documentation, or
see the examples provided below.
:type scope: str
:param redirect_uri: `Redirect URL`_ to which to redirect the user
after authentication. Defaults to ``None``,
resulting in using the default redirect URL for
the OAuth application as defined in GitHub. This
URL can differ from the callback URL defined in
your GitHub application, however it must be a
subdirectory of the specified callback URL,
otherwise raises a :class:`GitHubError`. For more
information on this, see the examples in presented
in the GitHub API `Redirect URL`_ documentation,
or see the example provided below.
:type redirect_uri: str
:param state: An unguessable random string. It is used to protect
against cross-site request forgery attacks.
:type state: str
For example, if we wanted to use this method to get read/write access
to user profile information, in addition to read-write access to code,
commit status, etc., we would need to use the `Scopes`_ ``user`` and
``repo`` when calling this method.
.. code-block:: python
github.authorize(scope="user,repo")
Additionally, if we wanted to specify a different redirect URL
following authorization.
.. code-block:: python
# Our application's callback URL is "http://example.com/callback"
redirect_uri="http://example.com/callback/my/path"
github.authorize(scope="user,repo", redirect_uri=redirect_uri)
.. _Scopes: https://developer.github.com/v3/oauth/#scopes
.. _Redirect URL: https://developer.github.com/v3/oauth/#redirect-urls
"""
_logger.debug("Called authorize()")
params = {'client_id': self.client_id}
if scope:
params['scope'] = scope
if redirect_uri:
params['redirect_uri'] = redirect_uri
if state:
params['state'] = state
url = self.auth_url + 'authorize?' + urlencode(params)
_logger.debug("Redirecting to %s", url)
return redirect(url) | [
"def",
"authorize",
"(",
"self",
",",
"scope",
"=",
"None",
",",
"redirect_uri",
"=",
"None",
",",
"state",
"=",
"None",
")",
":",
"_logger",
".",
"debug",
"(",
"\"Called authorize()\"",
")",
"params",
"=",
"{",
"'client_id'",
":",
"self",
".",
"client_id",
"}",
"if",
"scope",
":",
"params",
"[",
"'scope'",
"]",
"=",
"scope",
"if",
"redirect_uri",
":",
"params",
"[",
"'redirect_uri'",
"]",
"=",
"redirect_uri",
"if",
"state",
":",
"params",
"[",
"'state'",
"]",
"=",
"state",
"url",
"=",
"self",
".",
"auth_url",
"+",
"'authorize?'",
"+",
"urlencode",
"(",
"params",
")",
"_logger",
".",
"debug",
"(",
"\"Redirecting to %s\"",
",",
"url",
")",
"return",
"redirect",
"(",
"url",
")"
] | Redirect to GitHub and request access to a user's data.
:param scope: List of `Scopes`_ for which to request access, formatted
as a string or comma delimited list of scopes as a
string. Defaults to ``None``, resulting in granting
read-only access to public information (includes public
user profile info, public repository info, and gists).
For more information on this, see the examples in
presented in the GitHub API `Scopes`_ documentation, or
see the examples provided below.
:type scope: str
:param redirect_uri: `Redirect URL`_ to which to redirect the user
after authentication. Defaults to ``None``,
resulting in using the default redirect URL for
the OAuth application as defined in GitHub. This
URL can differ from the callback URL defined in
your GitHub application, however it must be a
subdirectory of the specified callback URL,
otherwise raises a :class:`GitHubError`. For more
information on this, see the examples in presented
in the GitHub API `Redirect URL`_ documentation,
or see the example provided below.
:type redirect_uri: str
:param state: An unguessable random string. It is used to protect
against cross-site request forgery attacks.
:type state: str
For example, if we wanted to use this method to get read/write access
to user profile information, in addition to read-write access to code,
commit status, etc., we would need to use the `Scopes`_ ``user`` and
``repo`` when calling this method.
.. code-block:: python
github.authorize(scope="user,repo")
Additionally, if we wanted to specify a different redirect URL
following authorization.
.. code-block:: python
# Our application's callback URL is "http://example.com/callback"
redirect_uri="http://example.com/callback/my/path"
github.authorize(scope="user,repo", redirect_uri=redirect_uri)
.. _Scopes: https://developer.github.com/v3/oauth/#scopes
.. _Redirect URL: https://developer.github.com/v3/oauth/#redirect-urls | [
"Redirect",
"to",
"GitHub",
"and",
"request",
"access",
"to",
"a",
"user",
"s",
"data",
"."
] | 9f58d61b7d328cef857edbb5c64a5d3f716367cb | https://github.com/cenkalti/github-flask/blob/9f58d61b7d328cef857edbb5c64a5d3f716367cb/flask_github.py#L104-L168 | train | 233,846 |
cenkalti/github-flask | flask_github.py | GitHub.authorized_handler | def authorized_handler(self, f):
"""
Decorator for the route that is used as the callback for authorizing
with GitHub. This callback URL can be set in the settings for the app
or passed in during authorization.
"""
@wraps(f)
def decorated(*args, **kwargs):
if 'code' in request.args:
data = self._handle_response()
else:
data = self._handle_invalid_response()
return f(*((data,) + args), **kwargs)
return decorated | python | def authorized_handler(self, f):
"""
Decorator for the route that is used as the callback for authorizing
with GitHub. This callback URL can be set in the settings for the app
or passed in during authorization.
"""
@wraps(f)
def decorated(*args, **kwargs):
if 'code' in request.args:
data = self._handle_response()
else:
data = self._handle_invalid_response()
return f(*((data,) + args), **kwargs)
return decorated | [
"def",
"authorized_handler",
"(",
"self",
",",
"f",
")",
":",
"@",
"wraps",
"(",
"f",
")",
"def",
"decorated",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'code'",
"in",
"request",
".",
"args",
":",
"data",
"=",
"self",
".",
"_handle_response",
"(",
")",
"else",
":",
"data",
"=",
"self",
".",
"_handle_invalid_response",
"(",
")",
"return",
"f",
"(",
"*",
"(",
"(",
"data",
",",
")",
"+",
"args",
")",
",",
"*",
"*",
"kwargs",
")",
"return",
"decorated"
] | Decorator for the route that is used as the callback for authorizing
with GitHub. This callback URL can be set in the settings for the app
or passed in during authorization. | [
"Decorator",
"for",
"the",
"route",
"that",
"is",
"used",
"as",
"the",
"callback",
"for",
"authorizing",
"with",
"GitHub",
".",
"This",
"callback",
"URL",
"can",
"be",
"set",
"in",
"the",
"settings",
"for",
"the",
"app",
"or",
"passed",
"in",
"during",
"authorization",
"."
] | 9f58d61b7d328cef857edbb5c64a5d3f716367cb | https://github.com/cenkalti/github-flask/blob/9f58d61b7d328cef857edbb5c64a5d3f716367cb/flask_github.py#L170-L184 | train | 233,847 |
cenkalti/github-flask | flask_github.py | GitHub._handle_response | def _handle_response(self):
"""
Handles response after the redirect to GitHub. This response
determines if the user has allowed the this application access. If we
were then we send a POST request for the access_key used to
authenticate requests to GitHub.
"""
_logger.debug("Handling response from GitHub")
params = {
'code': request.args.get('code'),
'client_id': self.client_id,
'client_secret': self.client_secret
}
url = self.auth_url + 'access_token'
_logger.debug("POSTing to %s", url)
_logger.debug(params)
response = self.session.post(url, data=params)
data = parse_qs(response.content)
_logger.debug("response.content = %s", data)
for k, v in data.items():
if len(v) == 1:
data[k] = v[0]
token = data.get(b'access_token', None)
if token is not None:
token = token.decode('ascii')
return token | python | def _handle_response(self):
"""
Handles response after the redirect to GitHub. This response
determines if the user has allowed the this application access. If we
were then we send a POST request for the access_key used to
authenticate requests to GitHub.
"""
_logger.debug("Handling response from GitHub")
params = {
'code': request.args.get('code'),
'client_id': self.client_id,
'client_secret': self.client_secret
}
url = self.auth_url + 'access_token'
_logger.debug("POSTing to %s", url)
_logger.debug(params)
response = self.session.post(url, data=params)
data = parse_qs(response.content)
_logger.debug("response.content = %s", data)
for k, v in data.items():
if len(v) == 1:
data[k] = v[0]
token = data.get(b'access_token', None)
if token is not None:
token = token.decode('ascii')
return token | [
"def",
"_handle_response",
"(",
"self",
")",
":",
"_logger",
".",
"debug",
"(",
"\"Handling response from GitHub\"",
")",
"params",
"=",
"{",
"'code'",
":",
"request",
".",
"args",
".",
"get",
"(",
"'code'",
")",
",",
"'client_id'",
":",
"self",
".",
"client_id",
",",
"'client_secret'",
":",
"self",
".",
"client_secret",
"}",
"url",
"=",
"self",
".",
"auth_url",
"+",
"'access_token'",
"_logger",
".",
"debug",
"(",
"\"POSTing to %s\"",
",",
"url",
")",
"_logger",
".",
"debug",
"(",
"params",
")",
"response",
"=",
"self",
".",
"session",
".",
"post",
"(",
"url",
",",
"data",
"=",
"params",
")",
"data",
"=",
"parse_qs",
"(",
"response",
".",
"content",
")",
"_logger",
".",
"debug",
"(",
"\"response.content = %s\"",
",",
"data",
")",
"for",
"k",
",",
"v",
"in",
"data",
".",
"items",
"(",
")",
":",
"if",
"len",
"(",
"v",
")",
"==",
"1",
":",
"data",
"[",
"k",
"]",
"=",
"v",
"[",
"0",
"]",
"token",
"=",
"data",
".",
"get",
"(",
"b'access_token'",
",",
"None",
")",
"if",
"token",
"is",
"not",
"None",
":",
"token",
"=",
"token",
".",
"decode",
"(",
"'ascii'",
")",
"return",
"token"
] | Handles response after the redirect to GitHub. This response
determines if the user has allowed the this application access. If we
were then we send a POST request for the access_key used to
authenticate requests to GitHub. | [
"Handles",
"response",
"after",
"the",
"redirect",
"to",
"GitHub",
".",
"This",
"response",
"determines",
"if",
"the",
"user",
"has",
"allowed",
"the",
"this",
"application",
"access",
".",
"If",
"we",
"were",
"then",
"we",
"send",
"a",
"POST",
"request",
"for",
"the",
"access_key",
"used",
"to",
"authenticate",
"requests",
"to",
"GitHub",
"."
] | 9f58d61b7d328cef857edbb5c64a5d3f716367cb | https://github.com/cenkalti/github-flask/blob/9f58d61b7d328cef857edbb5c64a5d3f716367cb/flask_github.py#L186-L212 | train | 233,848 |
ethereum/pyrlp | rlp/lazy.py | decode_lazy | def decode_lazy(rlp, sedes=None, **sedes_kwargs):
"""Decode an RLP encoded object in a lazy fashion.
If the encoded object is a bytestring, this function acts similar to
:func:`rlp.decode`. If it is a list however, a :class:`LazyList` is
returned instead. This object will decode the string lazily, avoiding
both horizontal and vertical traversing as much as possible.
The way `sedes` is applied depends on the decoded object: If it is a string
`sedes` deserializes it as a whole; if it is a list, each element is
deserialized individually. In both cases, `sedes_kwargs` are passed on.
Note that, if a deserializer is used, only "horizontal" but not
"vertical lazyness" can be preserved.
:param rlp: the RLP string to decode
:param sedes: an object implementing a method ``deserialize(code)`` which
is used as described above, or ``None`` if no
deserialization should be performed
:param \*\*sedes_kwargs: additional keyword arguments that will be passed
to the deserializers
:returns: either the already decoded and deserialized object (if encoded as
a string) or an instance of :class:`rlp.LazyList`
"""
item, end = consume_item_lazy(rlp, 0)
if end != len(rlp):
raise DecodingError('RLP length prefix announced wrong length', rlp)
if isinstance(item, LazyList):
item.sedes = sedes
item.sedes_kwargs = sedes_kwargs
return item
elif sedes:
return sedes.deserialize(item, **sedes_kwargs)
else:
return item | python | def decode_lazy(rlp, sedes=None, **sedes_kwargs):
"""Decode an RLP encoded object in a lazy fashion.
If the encoded object is a bytestring, this function acts similar to
:func:`rlp.decode`. If it is a list however, a :class:`LazyList` is
returned instead. This object will decode the string lazily, avoiding
both horizontal and vertical traversing as much as possible.
The way `sedes` is applied depends on the decoded object: If it is a string
`sedes` deserializes it as a whole; if it is a list, each element is
deserialized individually. In both cases, `sedes_kwargs` are passed on.
Note that, if a deserializer is used, only "horizontal" but not
"vertical lazyness" can be preserved.
:param rlp: the RLP string to decode
:param sedes: an object implementing a method ``deserialize(code)`` which
is used as described above, or ``None`` if no
deserialization should be performed
:param \*\*sedes_kwargs: additional keyword arguments that will be passed
to the deserializers
:returns: either the already decoded and deserialized object (if encoded as
a string) or an instance of :class:`rlp.LazyList`
"""
item, end = consume_item_lazy(rlp, 0)
if end != len(rlp):
raise DecodingError('RLP length prefix announced wrong length', rlp)
if isinstance(item, LazyList):
item.sedes = sedes
item.sedes_kwargs = sedes_kwargs
return item
elif sedes:
return sedes.deserialize(item, **sedes_kwargs)
else:
return item | [
"def",
"decode_lazy",
"(",
"rlp",
",",
"sedes",
"=",
"None",
",",
"*",
"*",
"sedes_kwargs",
")",
":",
"item",
",",
"end",
"=",
"consume_item_lazy",
"(",
"rlp",
",",
"0",
")",
"if",
"end",
"!=",
"len",
"(",
"rlp",
")",
":",
"raise",
"DecodingError",
"(",
"'RLP length prefix announced wrong length'",
",",
"rlp",
")",
"if",
"isinstance",
"(",
"item",
",",
"LazyList",
")",
":",
"item",
".",
"sedes",
"=",
"sedes",
"item",
".",
"sedes_kwargs",
"=",
"sedes_kwargs",
"return",
"item",
"elif",
"sedes",
":",
"return",
"sedes",
".",
"deserialize",
"(",
"item",
",",
"*",
"*",
"sedes_kwargs",
")",
"else",
":",
"return",
"item"
] | Decode an RLP encoded object in a lazy fashion.
If the encoded object is a bytestring, this function acts similar to
:func:`rlp.decode`. If it is a list however, a :class:`LazyList` is
returned instead. This object will decode the string lazily, avoiding
both horizontal and vertical traversing as much as possible.
The way `sedes` is applied depends on the decoded object: If it is a string
`sedes` deserializes it as a whole; if it is a list, each element is
deserialized individually. In both cases, `sedes_kwargs` are passed on.
Note that, if a deserializer is used, only "horizontal" but not
"vertical lazyness" can be preserved.
:param rlp: the RLP string to decode
:param sedes: an object implementing a method ``deserialize(code)`` which
is used as described above, or ``None`` if no
deserialization should be performed
:param \*\*sedes_kwargs: additional keyword arguments that will be passed
to the deserializers
:returns: either the already decoded and deserialized object (if encoded as
a string) or an instance of :class:`rlp.LazyList` | [
"Decode",
"an",
"RLP",
"encoded",
"object",
"in",
"a",
"lazy",
"fashion",
"."
] | bb898f8056da3973204c699621350bf9565e43df | https://github.com/ethereum/pyrlp/blob/bb898f8056da3973204c699621350bf9565e43df/rlp/lazy.py#L8-L41 | train | 233,849 |
ethereum/pyrlp | rlp/lazy.py | consume_item_lazy | def consume_item_lazy(rlp, start):
"""Read an item from an RLP string lazily.
If the length prefix announces a string, the string is read; if it
announces a list, a :class:`LazyList` is created.
:param rlp: the rlp string to read from
:param start: the position at which to start reading
:returns: a tuple ``(item, end)`` where ``item`` is the read string or a
:class:`LazyList` and ``end`` is the position of the first
unprocessed byte.
"""
p, t, l, s = consume_length_prefix(rlp, start)
if t is bytes:
item, _, end = consume_payload(rlp, p, s, bytes, l)
return item, end
else:
assert t is list
return LazyList(rlp, s, s + l), s + l | python | def consume_item_lazy(rlp, start):
"""Read an item from an RLP string lazily.
If the length prefix announces a string, the string is read; if it
announces a list, a :class:`LazyList` is created.
:param rlp: the rlp string to read from
:param start: the position at which to start reading
:returns: a tuple ``(item, end)`` where ``item`` is the read string or a
:class:`LazyList` and ``end`` is the position of the first
unprocessed byte.
"""
p, t, l, s = consume_length_prefix(rlp, start)
if t is bytes:
item, _, end = consume_payload(rlp, p, s, bytes, l)
return item, end
else:
assert t is list
return LazyList(rlp, s, s + l), s + l | [
"def",
"consume_item_lazy",
"(",
"rlp",
",",
"start",
")",
":",
"p",
",",
"t",
",",
"l",
",",
"s",
"=",
"consume_length_prefix",
"(",
"rlp",
",",
"start",
")",
"if",
"t",
"is",
"bytes",
":",
"item",
",",
"_",
",",
"end",
"=",
"consume_payload",
"(",
"rlp",
",",
"p",
",",
"s",
",",
"bytes",
",",
"l",
")",
"return",
"item",
",",
"end",
"else",
":",
"assert",
"t",
"is",
"list",
"return",
"LazyList",
"(",
"rlp",
",",
"s",
",",
"s",
"+",
"l",
")",
",",
"s",
"+",
"l"
] | Read an item from an RLP string lazily.
If the length prefix announces a string, the string is read; if it
announces a list, a :class:`LazyList` is created.
:param rlp: the rlp string to read from
:param start: the position at which to start reading
:returns: a tuple ``(item, end)`` where ``item`` is the read string or a
:class:`LazyList` and ``end`` is the position of the first
unprocessed byte. | [
"Read",
"an",
"item",
"from",
"an",
"RLP",
"string",
"lazily",
"."
] | bb898f8056da3973204c699621350bf9565e43df | https://github.com/ethereum/pyrlp/blob/bb898f8056da3973204c699621350bf9565e43df/rlp/lazy.py#L44-L62 | train | 233,850 |
ethereum/pyrlp | rlp/lazy.py | peek | def peek(rlp, index, sedes=None):
"""Get a specific element from an rlp encoded nested list.
This function uses :func:`rlp.decode_lazy` and, thus, decodes only the
necessary parts of the string.
Usage example::
>>> import rlp
>>> rlpdata = rlp.encode([1, 2, [3, [4, 5]]])
>>> rlp.peek(rlpdata, 0, rlp.sedes.big_endian_int)
1
>>> rlp.peek(rlpdata, [2, 0], rlp.sedes.big_endian_int)
3
:param rlp: the rlp string
:param index: the index of the element to peek at (can be a list for
nested data)
:param sedes: a sedes used to deserialize the peeked at object, or `None`
if no deserialization should be performed
:raises: :exc:`IndexError` if `index` is invalid (out of range or too many
levels)
"""
ll = decode_lazy(rlp)
if not isinstance(index, Iterable):
index = [index]
for i in index:
if isinstance(ll, Atomic):
raise IndexError('Too many indices given')
ll = ll[i]
if sedes:
return sedes.deserialize(ll)
else:
return ll | python | def peek(rlp, index, sedes=None):
"""Get a specific element from an rlp encoded nested list.
This function uses :func:`rlp.decode_lazy` and, thus, decodes only the
necessary parts of the string.
Usage example::
>>> import rlp
>>> rlpdata = rlp.encode([1, 2, [3, [4, 5]]])
>>> rlp.peek(rlpdata, 0, rlp.sedes.big_endian_int)
1
>>> rlp.peek(rlpdata, [2, 0], rlp.sedes.big_endian_int)
3
:param rlp: the rlp string
:param index: the index of the element to peek at (can be a list for
nested data)
:param sedes: a sedes used to deserialize the peeked at object, or `None`
if no deserialization should be performed
:raises: :exc:`IndexError` if `index` is invalid (out of range or too many
levels)
"""
ll = decode_lazy(rlp)
if not isinstance(index, Iterable):
index = [index]
for i in index:
if isinstance(ll, Atomic):
raise IndexError('Too many indices given')
ll = ll[i]
if sedes:
return sedes.deserialize(ll)
else:
return ll | [
"def",
"peek",
"(",
"rlp",
",",
"index",
",",
"sedes",
"=",
"None",
")",
":",
"ll",
"=",
"decode_lazy",
"(",
"rlp",
")",
"if",
"not",
"isinstance",
"(",
"index",
",",
"Iterable",
")",
":",
"index",
"=",
"[",
"index",
"]",
"for",
"i",
"in",
"index",
":",
"if",
"isinstance",
"(",
"ll",
",",
"Atomic",
")",
":",
"raise",
"IndexError",
"(",
"'Too many indices given'",
")",
"ll",
"=",
"ll",
"[",
"i",
"]",
"if",
"sedes",
":",
"return",
"sedes",
".",
"deserialize",
"(",
"ll",
")",
"else",
":",
"return",
"ll"
] | Get a specific element from an rlp encoded nested list.
This function uses :func:`rlp.decode_lazy` and, thus, decodes only the
necessary parts of the string.
Usage example::
>>> import rlp
>>> rlpdata = rlp.encode([1, 2, [3, [4, 5]]])
>>> rlp.peek(rlpdata, 0, rlp.sedes.big_endian_int)
1
>>> rlp.peek(rlpdata, [2, 0], rlp.sedes.big_endian_int)
3
:param rlp: the rlp string
:param index: the index of the element to peek at (can be a list for
nested data)
:param sedes: a sedes used to deserialize the peeked at object, or `None`
if no deserialization should be performed
:raises: :exc:`IndexError` if `index` is invalid (out of range or too many
levels) | [
"Get",
"a",
"specific",
"element",
"from",
"an",
"rlp",
"encoded",
"nested",
"list",
"."
] | bb898f8056da3973204c699621350bf9565e43df | https://github.com/ethereum/pyrlp/blob/bb898f8056da3973204c699621350bf9565e43df/rlp/lazy.py#L138-L171 | train | 233,851 |
ethereum/pyrlp | rlp/sedes/text.py | Text.fixed_length | def fixed_length(cls, l, allow_empty=False):
"""Create a sedes for text data with exactly `l` encoded characters."""
return cls(l, l, allow_empty=allow_empty) | python | def fixed_length(cls, l, allow_empty=False):
"""Create a sedes for text data with exactly `l` encoded characters."""
return cls(l, l, allow_empty=allow_empty) | [
"def",
"fixed_length",
"(",
"cls",
",",
"l",
",",
"allow_empty",
"=",
"False",
")",
":",
"return",
"cls",
"(",
"l",
",",
"l",
",",
"allow_empty",
"=",
"allow_empty",
")"
] | Create a sedes for text data with exactly `l` encoded characters. | [
"Create",
"a",
"sedes",
"for",
"text",
"data",
"with",
"exactly",
"l",
"encoded",
"characters",
"."
] | bb898f8056da3973204c699621350bf9565e43df | https://github.com/ethereum/pyrlp/blob/bb898f8056da3973204c699621350bf9565e43df/rlp/sedes/text.py#L24-L26 | train | 233,852 |
ethereum/pyrlp | rlp/sedes/serializable.py | _eq | def _eq(left, right):
"""
Equality comparison that allows for equality between tuple and list types
with equivalent elements.
"""
if isinstance(left, (tuple, list)) and isinstance(right, (tuple, list)):
return len(left) == len(right) and all(_eq(*pair) for pair in zip(left, right))
else:
return left == right | python | def _eq(left, right):
"""
Equality comparison that allows for equality between tuple and list types
with equivalent elements.
"""
if isinstance(left, (tuple, list)) and isinstance(right, (tuple, list)):
return len(left) == len(right) and all(_eq(*pair) for pair in zip(left, right))
else:
return left == right | [
"def",
"_eq",
"(",
"left",
",",
"right",
")",
":",
"if",
"isinstance",
"(",
"left",
",",
"(",
"tuple",
",",
"list",
")",
")",
"and",
"isinstance",
"(",
"right",
",",
"(",
"tuple",
",",
"list",
")",
")",
":",
"return",
"len",
"(",
"left",
")",
"==",
"len",
"(",
"right",
")",
"and",
"all",
"(",
"_eq",
"(",
"*",
"pair",
")",
"for",
"pair",
"in",
"zip",
"(",
"left",
",",
"right",
")",
")",
"else",
":",
"return",
"left",
"==",
"right"
] | Equality comparison that allows for equality between tuple and list types
with equivalent elements. | [
"Equality",
"comparison",
"that",
"allows",
"for",
"equality",
"between",
"tuple",
"and",
"list",
"types",
"with",
"equivalent",
"elements",
"."
] | bb898f8056da3973204c699621350bf9565e43df | https://github.com/ethereum/pyrlp/blob/bb898f8056da3973204c699621350bf9565e43df/rlp/sedes/serializable.py#L82-L90 | train | 233,853 |
ethereum/pyrlp | rlp/sedes/lists.py | is_sequence | def is_sequence(obj):
"""Check if `obj` is a sequence, but not a string or bytes."""
return isinstance(obj, Sequence) and not (
isinstance(obj, str) or BinaryClass.is_valid_type(obj)) | python | def is_sequence(obj):
"""Check if `obj` is a sequence, but not a string or bytes."""
return isinstance(obj, Sequence) and not (
isinstance(obj, str) or BinaryClass.is_valid_type(obj)) | [
"def",
"is_sequence",
"(",
"obj",
")",
":",
"return",
"isinstance",
"(",
"obj",
",",
"Sequence",
")",
"and",
"not",
"(",
"isinstance",
"(",
"obj",
",",
"str",
")",
"or",
"BinaryClass",
".",
"is_valid_type",
"(",
"obj",
")",
")"
] | Check if `obj` is a sequence, but not a string or bytes. | [
"Check",
"if",
"obj",
"is",
"a",
"sequence",
"but",
"not",
"a",
"string",
"or",
"bytes",
"."
] | bb898f8056da3973204c699621350bf9565e43df | https://github.com/ethereum/pyrlp/blob/bb898f8056da3973204c699621350bf9565e43df/rlp/sedes/lists.py#L32-L35 | train | 233,854 |
ethereum/pyrlp | rlp/codec.py | encode | def encode(obj, sedes=None, infer_serializer=True, cache=True):
"""Encode a Python object in RLP format.
By default, the object is serialized in a suitable way first (using
:func:`rlp.infer_sedes`) and then encoded. Serialization can be explicitly
suppressed by setting `infer_serializer` to ``False`` and not passing an
alternative as `sedes`.
If `obj` has an attribute :attr:`_cached_rlp` (as, notably,
:class:`rlp.Serializable`) and its value is not `None`, this value is
returned bypassing serialization and encoding, unless `sedes` is given (as
the cache is assumed to refer to the standard serialization which can be
replaced by specifying `sedes`).
If `obj` is a :class:`rlp.Serializable` and `cache` is true, the result of
the encoding will be stored in :attr:`_cached_rlp` if it is empty.
:param sedes: an object implementing a function ``serialize(obj)`` which will be used to
serialize ``obj`` before encoding, or ``None`` to use the infered one (if any)
:param infer_serializer: if ``True`` an appropriate serializer will be selected using
:func:`rlp.infer_sedes` to serialize `obj` before encoding
:param cache: cache the return value in `obj._cached_rlp` if possible
(default `True`)
:returns: the RLP encoded item
:raises: :exc:`rlp.EncodingError` in the rather unlikely case that the item is too big to
encode (will not happen)
:raises: :exc:`rlp.SerializationError` if the serialization fails
"""
if isinstance(obj, Serializable):
cached_rlp = obj._cached_rlp
if sedes is None and cached_rlp:
return cached_rlp
else:
really_cache = (
cache and
sedes is None
)
else:
really_cache = False
if sedes:
item = sedes.serialize(obj)
elif infer_serializer:
item = infer_sedes(obj).serialize(obj)
else:
item = obj
result = encode_raw(item)
if really_cache:
obj._cached_rlp = result
return result | python | def encode(obj, sedes=None, infer_serializer=True, cache=True):
"""Encode a Python object in RLP format.
By default, the object is serialized in a suitable way first (using
:func:`rlp.infer_sedes`) and then encoded. Serialization can be explicitly
suppressed by setting `infer_serializer` to ``False`` and not passing an
alternative as `sedes`.
If `obj` has an attribute :attr:`_cached_rlp` (as, notably,
:class:`rlp.Serializable`) and its value is not `None`, this value is
returned bypassing serialization and encoding, unless `sedes` is given (as
the cache is assumed to refer to the standard serialization which can be
replaced by specifying `sedes`).
If `obj` is a :class:`rlp.Serializable` and `cache` is true, the result of
the encoding will be stored in :attr:`_cached_rlp` if it is empty.
:param sedes: an object implementing a function ``serialize(obj)`` which will be used to
serialize ``obj`` before encoding, or ``None`` to use the infered one (if any)
:param infer_serializer: if ``True`` an appropriate serializer will be selected using
:func:`rlp.infer_sedes` to serialize `obj` before encoding
:param cache: cache the return value in `obj._cached_rlp` if possible
(default `True`)
:returns: the RLP encoded item
:raises: :exc:`rlp.EncodingError` in the rather unlikely case that the item is too big to
encode (will not happen)
:raises: :exc:`rlp.SerializationError` if the serialization fails
"""
if isinstance(obj, Serializable):
cached_rlp = obj._cached_rlp
if sedes is None and cached_rlp:
return cached_rlp
else:
really_cache = (
cache and
sedes is None
)
else:
really_cache = False
if sedes:
item = sedes.serialize(obj)
elif infer_serializer:
item = infer_sedes(obj).serialize(obj)
else:
item = obj
result = encode_raw(item)
if really_cache:
obj._cached_rlp = result
return result | [
"def",
"encode",
"(",
"obj",
",",
"sedes",
"=",
"None",
",",
"infer_serializer",
"=",
"True",
",",
"cache",
"=",
"True",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"Serializable",
")",
":",
"cached_rlp",
"=",
"obj",
".",
"_cached_rlp",
"if",
"sedes",
"is",
"None",
"and",
"cached_rlp",
":",
"return",
"cached_rlp",
"else",
":",
"really_cache",
"=",
"(",
"cache",
"and",
"sedes",
"is",
"None",
")",
"else",
":",
"really_cache",
"=",
"False",
"if",
"sedes",
":",
"item",
"=",
"sedes",
".",
"serialize",
"(",
"obj",
")",
"elif",
"infer_serializer",
":",
"item",
"=",
"infer_sedes",
"(",
"obj",
")",
".",
"serialize",
"(",
"obj",
")",
"else",
":",
"item",
"=",
"obj",
"result",
"=",
"encode_raw",
"(",
"item",
")",
"if",
"really_cache",
":",
"obj",
".",
"_cached_rlp",
"=",
"result",
"return",
"result"
] | Encode a Python object in RLP format.
By default, the object is serialized in a suitable way first (using
:func:`rlp.infer_sedes`) and then encoded. Serialization can be explicitly
suppressed by setting `infer_serializer` to ``False`` and not passing an
alternative as `sedes`.
If `obj` has an attribute :attr:`_cached_rlp` (as, notably,
:class:`rlp.Serializable`) and its value is not `None`, this value is
returned bypassing serialization and encoding, unless `sedes` is given (as
the cache is assumed to refer to the standard serialization which can be
replaced by specifying `sedes`).
If `obj` is a :class:`rlp.Serializable` and `cache` is true, the result of
the encoding will be stored in :attr:`_cached_rlp` if it is empty.
:param sedes: an object implementing a function ``serialize(obj)`` which will be used to
serialize ``obj`` before encoding, or ``None`` to use the infered one (if any)
:param infer_serializer: if ``True`` an appropriate serializer will be selected using
:func:`rlp.infer_sedes` to serialize `obj` before encoding
:param cache: cache the return value in `obj._cached_rlp` if possible
(default `True`)
:returns: the RLP encoded item
:raises: :exc:`rlp.EncodingError` in the rather unlikely case that the item is too big to
encode (will not happen)
:raises: :exc:`rlp.SerializationError` if the serialization fails | [
"Encode",
"a",
"Python",
"object",
"in",
"RLP",
"format",
"."
] | bb898f8056da3973204c699621350bf9565e43df | https://github.com/ethereum/pyrlp/blob/bb898f8056da3973204c699621350bf9565e43df/rlp/codec.py#L20-L70 | train | 233,855 |
ethereum/pyrlp | rlp/codec.py | consume_payload | def consume_payload(rlp, prefix, start, type_, length):
"""Read the payload of an item from an RLP string.
:param rlp: the rlp string to read from
:param type_: the type of the payload (``bytes`` or ``list``)
:param start: the position at which to start reading
:param length: the length of the payload in bytes
:returns: a tuple ``(item, per_item_rlp, end)``, where ``item`` is
the read item, per_item_rlp is a list containing the RLP
encoding of each item and ``end`` is the position of the
first unprocessed byte
"""
if type_ is bytes:
item = rlp[start: start + length]
return (item, [prefix + item], start + length)
elif type_ is list:
items = []
per_item_rlp = []
list_rlp = prefix
next_item_start = start
end = next_item_start + length
while next_item_start < end:
p, t, l, s = consume_length_prefix(rlp, next_item_start)
item, item_rlp, next_item_start = consume_payload(rlp, p, s, t, l)
per_item_rlp.append(item_rlp)
# When the item returned above is a single element, item_rlp will also contain a
# single element, but when it's a list, the first element will be the RLP of the
# whole List, which is what we want here.
list_rlp += item_rlp[0]
items.append(item)
per_item_rlp.insert(0, list_rlp)
if next_item_start > end:
raise DecodingError('List length prefix announced a too small '
'length', rlp)
return (items, per_item_rlp, next_item_start)
else:
raise TypeError('Type must be either list or bytes') | python | def consume_payload(rlp, prefix, start, type_, length):
"""Read the payload of an item from an RLP string.
:param rlp: the rlp string to read from
:param type_: the type of the payload (``bytes`` or ``list``)
:param start: the position at which to start reading
:param length: the length of the payload in bytes
:returns: a tuple ``(item, per_item_rlp, end)``, where ``item`` is
the read item, per_item_rlp is a list containing the RLP
encoding of each item and ``end`` is the position of the
first unprocessed byte
"""
if type_ is bytes:
item = rlp[start: start + length]
return (item, [prefix + item], start + length)
elif type_ is list:
items = []
per_item_rlp = []
list_rlp = prefix
next_item_start = start
end = next_item_start + length
while next_item_start < end:
p, t, l, s = consume_length_prefix(rlp, next_item_start)
item, item_rlp, next_item_start = consume_payload(rlp, p, s, t, l)
per_item_rlp.append(item_rlp)
# When the item returned above is a single element, item_rlp will also contain a
# single element, but when it's a list, the first element will be the RLP of the
# whole List, which is what we want here.
list_rlp += item_rlp[0]
items.append(item)
per_item_rlp.insert(0, list_rlp)
if next_item_start > end:
raise DecodingError('List length prefix announced a too small '
'length', rlp)
return (items, per_item_rlp, next_item_start)
else:
raise TypeError('Type must be either list or bytes') | [
"def",
"consume_payload",
"(",
"rlp",
",",
"prefix",
",",
"start",
",",
"type_",
",",
"length",
")",
":",
"if",
"type_",
"is",
"bytes",
":",
"item",
"=",
"rlp",
"[",
"start",
":",
"start",
"+",
"length",
"]",
"return",
"(",
"item",
",",
"[",
"prefix",
"+",
"item",
"]",
",",
"start",
"+",
"length",
")",
"elif",
"type_",
"is",
"list",
":",
"items",
"=",
"[",
"]",
"per_item_rlp",
"=",
"[",
"]",
"list_rlp",
"=",
"prefix",
"next_item_start",
"=",
"start",
"end",
"=",
"next_item_start",
"+",
"length",
"while",
"next_item_start",
"<",
"end",
":",
"p",
",",
"t",
",",
"l",
",",
"s",
"=",
"consume_length_prefix",
"(",
"rlp",
",",
"next_item_start",
")",
"item",
",",
"item_rlp",
",",
"next_item_start",
"=",
"consume_payload",
"(",
"rlp",
",",
"p",
",",
"s",
",",
"t",
",",
"l",
")",
"per_item_rlp",
".",
"append",
"(",
"item_rlp",
")",
"# When the item returned above is a single element, item_rlp will also contain a",
"# single element, but when it's a list, the first element will be the RLP of the",
"# whole List, which is what we want here.",
"list_rlp",
"+=",
"item_rlp",
"[",
"0",
"]",
"items",
".",
"append",
"(",
"item",
")",
"per_item_rlp",
".",
"insert",
"(",
"0",
",",
"list_rlp",
")",
"if",
"next_item_start",
">",
"end",
":",
"raise",
"DecodingError",
"(",
"'List length prefix announced a too small '",
"'length'",
",",
"rlp",
")",
"return",
"(",
"items",
",",
"per_item_rlp",
",",
"next_item_start",
")",
"else",
":",
"raise",
"TypeError",
"(",
"'Type must be either list or bytes'",
")"
] | Read the payload of an item from an RLP string.
:param rlp: the rlp string to read from
:param type_: the type of the payload (``bytes`` or ``list``)
:param start: the position at which to start reading
:param length: the length of the payload in bytes
:returns: a tuple ``(item, per_item_rlp, end)``, where ``item`` is
the read item, per_item_rlp is a list containing the RLP
encoding of each item and ``end`` is the position of the
first unprocessed byte | [
"Read",
"the",
"payload",
"of",
"an",
"item",
"from",
"an",
"RLP",
"string",
"."
] | bb898f8056da3973204c699621350bf9565e43df | https://github.com/ethereum/pyrlp/blob/bb898f8056da3973204c699621350bf9565e43df/rlp/codec.py#L156-L192 | train | 233,856 |
ethereum/pyrlp | rlp/codec.py | consume_item | def consume_item(rlp, start):
"""Read an item from an RLP string.
:param rlp: the rlp string to read from
:param start: the position at which to start reading
:returns: a tuple ``(item, per_item_rlp, end)``, where ``item`` is
the read item, per_item_rlp is a list containing the RLP
encoding of each item and ``end`` is the position of the
first unprocessed byte
"""
p, t, l, s = consume_length_prefix(rlp, start)
return consume_payload(rlp, p, s, t, l) | python | def consume_item(rlp, start):
"""Read an item from an RLP string.
:param rlp: the rlp string to read from
:param start: the position at which to start reading
:returns: a tuple ``(item, per_item_rlp, end)``, where ``item`` is
the read item, per_item_rlp is a list containing the RLP
encoding of each item and ``end`` is the position of the
first unprocessed byte
"""
p, t, l, s = consume_length_prefix(rlp, start)
return consume_payload(rlp, p, s, t, l) | [
"def",
"consume_item",
"(",
"rlp",
",",
"start",
")",
":",
"p",
",",
"t",
",",
"l",
",",
"s",
"=",
"consume_length_prefix",
"(",
"rlp",
",",
"start",
")",
"return",
"consume_payload",
"(",
"rlp",
",",
"p",
",",
"s",
",",
"t",
",",
"l",
")"
] | Read an item from an RLP string.
:param rlp: the rlp string to read from
:param start: the position at which to start reading
:returns: a tuple ``(item, per_item_rlp, end)``, where ``item`` is
the read item, per_item_rlp is a list containing the RLP
encoding of each item and ``end`` is the position of the
first unprocessed byte | [
"Read",
"an",
"item",
"from",
"an",
"RLP",
"string",
"."
] | bb898f8056da3973204c699621350bf9565e43df | https://github.com/ethereum/pyrlp/blob/bb898f8056da3973204c699621350bf9565e43df/rlp/codec.py#L195-L206 | train | 233,857 |
ethereum/pyrlp | rlp/codec.py | decode | def decode(rlp, sedes=None, strict=True, recursive_cache=False, **kwargs):
"""Decode an RLP encoded object.
If the deserialized result `obj` has an attribute :attr:`_cached_rlp` (e.g. if `sedes` is a
subclass of :class:`rlp.Serializable`) it will be set to `rlp`, which will improve performance
on subsequent :func:`rlp.encode` calls. Bear in mind however that `obj` needs to make sure that
this value is updated whenever one of its fields changes or prevent such changes entirely
(:class:`rlp.sedes.Serializable` does the latter).
:param sedes: an object implementing a function ``deserialize(code)`` which will be applied
after decoding, or ``None`` if no deserialization should be performed
:param \*\*kwargs: additional keyword arguments that will be passed to the deserializer
:param strict: if false inputs that are longer than necessary don't cause an exception
:returns: the decoded and maybe deserialized Python object
:raises: :exc:`rlp.DecodingError` if the input string does not end after the root item and
`strict` is true
:raises: :exc:`rlp.DeserializationError` if the deserialization fails
"""
if not is_bytes(rlp):
raise DecodingError('Can only decode RLP bytes, got type %s' % type(rlp).__name__, rlp)
try:
item, per_item_rlp, end = consume_item(rlp, 0)
except IndexError:
raise DecodingError('RLP string too short', rlp)
if end != len(rlp) and strict:
msg = 'RLP string ends with {} superfluous bytes'.format(len(rlp) - end)
raise DecodingError(msg, rlp)
if sedes:
obj = sedes.deserialize(item, **kwargs)
if is_sequence(obj) or hasattr(obj, '_cached_rlp'):
_apply_rlp_cache(obj, per_item_rlp, recursive_cache)
return obj
else:
return item | python | def decode(rlp, sedes=None, strict=True, recursive_cache=False, **kwargs):
"""Decode an RLP encoded object.
If the deserialized result `obj` has an attribute :attr:`_cached_rlp` (e.g. if `sedes` is a
subclass of :class:`rlp.Serializable`) it will be set to `rlp`, which will improve performance
on subsequent :func:`rlp.encode` calls. Bear in mind however that `obj` needs to make sure that
this value is updated whenever one of its fields changes or prevent such changes entirely
(:class:`rlp.sedes.Serializable` does the latter).
:param sedes: an object implementing a function ``deserialize(code)`` which will be applied
after decoding, or ``None`` if no deserialization should be performed
:param \*\*kwargs: additional keyword arguments that will be passed to the deserializer
:param strict: if false inputs that are longer than necessary don't cause an exception
:returns: the decoded and maybe deserialized Python object
:raises: :exc:`rlp.DecodingError` if the input string does not end after the root item and
`strict` is true
:raises: :exc:`rlp.DeserializationError` if the deserialization fails
"""
if not is_bytes(rlp):
raise DecodingError('Can only decode RLP bytes, got type %s' % type(rlp).__name__, rlp)
try:
item, per_item_rlp, end = consume_item(rlp, 0)
except IndexError:
raise DecodingError('RLP string too short', rlp)
if end != len(rlp) and strict:
msg = 'RLP string ends with {} superfluous bytes'.format(len(rlp) - end)
raise DecodingError(msg, rlp)
if sedes:
obj = sedes.deserialize(item, **kwargs)
if is_sequence(obj) or hasattr(obj, '_cached_rlp'):
_apply_rlp_cache(obj, per_item_rlp, recursive_cache)
return obj
else:
return item | [
"def",
"decode",
"(",
"rlp",
",",
"sedes",
"=",
"None",
",",
"strict",
"=",
"True",
",",
"recursive_cache",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"is_bytes",
"(",
"rlp",
")",
":",
"raise",
"DecodingError",
"(",
"'Can only decode RLP bytes, got type %s'",
"%",
"type",
"(",
"rlp",
")",
".",
"__name__",
",",
"rlp",
")",
"try",
":",
"item",
",",
"per_item_rlp",
",",
"end",
"=",
"consume_item",
"(",
"rlp",
",",
"0",
")",
"except",
"IndexError",
":",
"raise",
"DecodingError",
"(",
"'RLP string too short'",
",",
"rlp",
")",
"if",
"end",
"!=",
"len",
"(",
"rlp",
")",
"and",
"strict",
":",
"msg",
"=",
"'RLP string ends with {} superfluous bytes'",
".",
"format",
"(",
"len",
"(",
"rlp",
")",
"-",
"end",
")",
"raise",
"DecodingError",
"(",
"msg",
",",
"rlp",
")",
"if",
"sedes",
":",
"obj",
"=",
"sedes",
".",
"deserialize",
"(",
"item",
",",
"*",
"*",
"kwargs",
")",
"if",
"is_sequence",
"(",
"obj",
")",
"or",
"hasattr",
"(",
"obj",
",",
"'_cached_rlp'",
")",
":",
"_apply_rlp_cache",
"(",
"obj",
",",
"per_item_rlp",
",",
"recursive_cache",
")",
"return",
"obj",
"else",
":",
"return",
"item"
] | Decode an RLP encoded object.
If the deserialized result `obj` has an attribute :attr:`_cached_rlp` (e.g. if `sedes` is a
subclass of :class:`rlp.Serializable`) it will be set to `rlp`, which will improve performance
on subsequent :func:`rlp.encode` calls. Bear in mind however that `obj` needs to make sure that
this value is updated whenever one of its fields changes or prevent such changes entirely
(:class:`rlp.sedes.Serializable` does the latter).
:param sedes: an object implementing a function ``deserialize(code)`` which will be applied
after decoding, or ``None`` if no deserialization should be performed
:param \*\*kwargs: additional keyword arguments that will be passed to the deserializer
:param strict: if false inputs that are longer than necessary don't cause an exception
:returns: the decoded and maybe deserialized Python object
:raises: :exc:`rlp.DecodingError` if the input string does not end after the root item and
`strict` is true
:raises: :exc:`rlp.DeserializationError` if the deserialization fails | [
"Decode",
"an",
"RLP",
"encoded",
"object",
"."
] | bb898f8056da3973204c699621350bf9565e43df | https://github.com/ethereum/pyrlp/blob/bb898f8056da3973204c699621350bf9565e43df/rlp/codec.py#L209-L242 | train | 233,858 |
ethereum/pyrlp | rlp/codec.py | infer_sedes | def infer_sedes(obj):
"""Try to find a sedes objects suitable for a given Python object.
The sedes objects considered are `obj`'s class, `big_endian_int` and
`binary`. If `obj` is a sequence, a :class:`rlp.sedes.List` will be
constructed recursively.
:param obj: the python object for which to find a sedes object
:raises: :exc:`TypeError` if no appropriate sedes could be found
"""
if is_sedes(obj.__class__):
return obj.__class__
elif not isinstance(obj, bool) and isinstance(obj, int) and obj >= 0:
return big_endian_int
elif BinaryClass.is_valid_type(obj):
return binary
elif not isinstance(obj, str) and isinstance(obj, collections.Sequence):
return List(map(infer_sedes, obj))
elif isinstance(obj, bool):
return boolean
elif isinstance(obj, str):
return text
msg = 'Did not find sedes handling type {}'.format(type(obj).__name__)
raise TypeError(msg) | python | def infer_sedes(obj):
"""Try to find a sedes objects suitable for a given Python object.
The sedes objects considered are `obj`'s class, `big_endian_int` and
`binary`. If `obj` is a sequence, a :class:`rlp.sedes.List` will be
constructed recursively.
:param obj: the python object for which to find a sedes object
:raises: :exc:`TypeError` if no appropriate sedes could be found
"""
if is_sedes(obj.__class__):
return obj.__class__
elif not isinstance(obj, bool) and isinstance(obj, int) and obj >= 0:
return big_endian_int
elif BinaryClass.is_valid_type(obj):
return binary
elif not isinstance(obj, str) and isinstance(obj, collections.Sequence):
return List(map(infer_sedes, obj))
elif isinstance(obj, bool):
return boolean
elif isinstance(obj, str):
return text
msg = 'Did not find sedes handling type {}'.format(type(obj).__name__)
raise TypeError(msg) | [
"def",
"infer_sedes",
"(",
"obj",
")",
":",
"if",
"is_sedes",
"(",
"obj",
".",
"__class__",
")",
":",
"return",
"obj",
".",
"__class__",
"elif",
"not",
"isinstance",
"(",
"obj",
",",
"bool",
")",
"and",
"isinstance",
"(",
"obj",
",",
"int",
")",
"and",
"obj",
">=",
"0",
":",
"return",
"big_endian_int",
"elif",
"BinaryClass",
".",
"is_valid_type",
"(",
"obj",
")",
":",
"return",
"binary",
"elif",
"not",
"isinstance",
"(",
"obj",
",",
"str",
")",
"and",
"isinstance",
"(",
"obj",
",",
"collections",
".",
"Sequence",
")",
":",
"return",
"List",
"(",
"map",
"(",
"infer_sedes",
",",
"obj",
")",
")",
"elif",
"isinstance",
"(",
"obj",
",",
"bool",
")",
":",
"return",
"boolean",
"elif",
"isinstance",
"(",
"obj",
",",
"str",
")",
":",
"return",
"text",
"msg",
"=",
"'Did not find sedes handling type {}'",
".",
"format",
"(",
"type",
"(",
"obj",
")",
".",
"__name__",
")",
"raise",
"TypeError",
"(",
"msg",
")"
] | Try to find a sedes objects suitable for a given Python object.
The sedes objects considered are `obj`'s class, `big_endian_int` and
`binary`. If `obj` is a sequence, a :class:`rlp.sedes.List` will be
constructed recursively.
:param obj: the python object for which to find a sedes object
:raises: :exc:`TypeError` if no appropriate sedes could be found | [
"Try",
"to",
"find",
"a",
"sedes",
"objects",
"suitable",
"for",
"a",
"given",
"Python",
"object",
"."
] | bb898f8056da3973204c699621350bf9565e43df | https://github.com/ethereum/pyrlp/blob/bb898f8056da3973204c699621350bf9565e43df/rlp/codec.py#L261-L284 | train | 233,859 |
graphite-project/carbonate | carbonate/config.py | Config.destinations | def destinations(self, cluster='main'):
"""Return a list of destinations for a cluster."""
if not self.config.has_section(cluster):
raise SystemExit("Cluster '%s' not defined in %s"
% (cluster, self.config_file))
destinations = self.config.get(cluster, 'destinations')
return destinations.replace(' ', '').split(',') | python | def destinations(self, cluster='main'):
"""Return a list of destinations for a cluster."""
if not self.config.has_section(cluster):
raise SystemExit("Cluster '%s' not defined in %s"
% (cluster, self.config_file))
destinations = self.config.get(cluster, 'destinations')
return destinations.replace(' ', '').split(',') | [
"def",
"destinations",
"(",
"self",
",",
"cluster",
"=",
"'main'",
")",
":",
"if",
"not",
"self",
".",
"config",
".",
"has_section",
"(",
"cluster",
")",
":",
"raise",
"SystemExit",
"(",
"\"Cluster '%s' not defined in %s\"",
"%",
"(",
"cluster",
",",
"self",
".",
"config_file",
")",
")",
"destinations",
"=",
"self",
".",
"config",
".",
"get",
"(",
"cluster",
",",
"'destinations'",
")",
"return",
"destinations",
".",
"replace",
"(",
"' '",
",",
"''",
")",
".",
"split",
"(",
"','",
")"
] | Return a list of destinations for a cluster. | [
"Return",
"a",
"list",
"of",
"destinations",
"for",
"a",
"cluster",
"."
] | b876a85b321fbd7c18a6721bed2e7807b79b4929 | https://github.com/graphite-project/carbonate/blob/b876a85b321fbd7c18a6721bed2e7807b79b4929/carbonate/config.py#L21-L27 | train | 233,860 |
graphite-project/carbonate | carbonate/config.py | Config.replication_factor | def replication_factor(self, cluster='main'):
"""Return the replication factor for a cluster as an integer."""
if not self.config.has_section(cluster):
raise SystemExit("Cluster '%s' not defined in %s"
% (cluster, self.config_file))
return int(self.config.get(cluster, 'replication_factor')) | python | def replication_factor(self, cluster='main'):
"""Return the replication factor for a cluster as an integer."""
if not self.config.has_section(cluster):
raise SystemExit("Cluster '%s' not defined in %s"
% (cluster, self.config_file))
return int(self.config.get(cluster, 'replication_factor')) | [
"def",
"replication_factor",
"(",
"self",
",",
"cluster",
"=",
"'main'",
")",
":",
"if",
"not",
"self",
".",
"config",
".",
"has_section",
"(",
"cluster",
")",
":",
"raise",
"SystemExit",
"(",
"\"Cluster '%s' not defined in %s\"",
"%",
"(",
"cluster",
",",
"self",
".",
"config_file",
")",
")",
"return",
"int",
"(",
"self",
".",
"config",
".",
"get",
"(",
"cluster",
",",
"'replication_factor'",
")",
")"
] | Return the replication factor for a cluster as an integer. | [
"Return",
"the",
"replication",
"factor",
"for",
"a",
"cluster",
"as",
"an",
"integer",
"."
] | b876a85b321fbd7c18a6721bed2e7807b79b4929 | https://github.com/graphite-project/carbonate/blob/b876a85b321fbd7c18a6721bed2e7807b79b4929/carbonate/config.py#L29-L34 | train | 233,861 |
graphite-project/carbonate | carbonate/config.py | Config.ssh_user | def ssh_user(self, cluster='main'):
"""Return the ssh user for a cluster or current user if undefined."""
if not self.config.has_section(cluster):
raise SystemExit("Cluster '%s' not defined in %s"
% (cluster, self.config_file))
try:
return self.config.get(cluster, 'ssh_user')
except NoOptionError:
return pwd.getpwuid(os.getuid()).pw_name | python | def ssh_user(self, cluster='main'):
"""Return the ssh user for a cluster or current user if undefined."""
if not self.config.has_section(cluster):
raise SystemExit("Cluster '%s' not defined in %s"
% (cluster, self.config_file))
try:
return self.config.get(cluster, 'ssh_user')
except NoOptionError:
return pwd.getpwuid(os.getuid()).pw_name | [
"def",
"ssh_user",
"(",
"self",
",",
"cluster",
"=",
"'main'",
")",
":",
"if",
"not",
"self",
".",
"config",
".",
"has_section",
"(",
"cluster",
")",
":",
"raise",
"SystemExit",
"(",
"\"Cluster '%s' not defined in %s\"",
"%",
"(",
"cluster",
",",
"self",
".",
"config_file",
")",
")",
"try",
":",
"return",
"self",
".",
"config",
".",
"get",
"(",
"cluster",
",",
"'ssh_user'",
")",
"except",
"NoOptionError",
":",
"return",
"pwd",
".",
"getpwuid",
"(",
"os",
".",
"getuid",
"(",
")",
")",
".",
"pw_name"
] | Return the ssh user for a cluster or current user if undefined. | [
"Return",
"the",
"ssh",
"user",
"for",
"a",
"cluster",
"or",
"current",
"user",
"if",
"undefined",
"."
] | b876a85b321fbd7c18a6721bed2e7807b79b4929 | https://github.com/graphite-project/carbonate/blob/b876a85b321fbd7c18a6721bed2e7807b79b4929/carbonate/config.py#L36-L44 | train | 233,862 |
graphite-project/carbonate | carbonate/config.py | Config.whisper_lock_writes | def whisper_lock_writes(self, cluster='main'):
"""Lock whisper files during carbon-sync."""
if not self.config.has_section(cluster):
raise SystemExit("Cluster '%s' not defined in %s"
% (cluster, self.config_file))
try:
return bool(self.config.get(cluster, 'whisper_lock_writes'))
except NoOptionError:
return False | python | def whisper_lock_writes(self, cluster='main'):
"""Lock whisper files during carbon-sync."""
if not self.config.has_section(cluster):
raise SystemExit("Cluster '%s' not defined in %s"
% (cluster, self.config_file))
try:
return bool(self.config.get(cluster, 'whisper_lock_writes'))
except NoOptionError:
return False | [
"def",
"whisper_lock_writes",
"(",
"self",
",",
"cluster",
"=",
"'main'",
")",
":",
"if",
"not",
"self",
".",
"config",
".",
"has_section",
"(",
"cluster",
")",
":",
"raise",
"SystemExit",
"(",
"\"Cluster '%s' not defined in %s\"",
"%",
"(",
"cluster",
",",
"self",
".",
"config_file",
")",
")",
"try",
":",
"return",
"bool",
"(",
"self",
".",
"config",
".",
"get",
"(",
"cluster",
",",
"'whisper_lock_writes'",
")",
")",
"except",
"NoOptionError",
":",
"return",
"False"
] | Lock whisper files during carbon-sync. | [
"Lock",
"whisper",
"files",
"during",
"carbon",
"-",
"sync",
"."
] | b876a85b321fbd7c18a6721bed2e7807b79b4929 | https://github.com/graphite-project/carbonate/blob/b876a85b321fbd7c18a6721bed2e7807b79b4929/carbonate/config.py#L46-L54 | train | 233,863 |
graphite-project/carbonate | carbonate/config.py | Config.hashing_type | def hashing_type(self, cluster='main'):
"""Hashing type of cluster."""
if not self.config.has_section(cluster):
raise SystemExit("Cluster '%s' not defined in %s"
% (cluster, self.config_file))
hashing_type = 'carbon_ch'
try:
return self.config.get(cluster, 'hashing_type')
except NoOptionError:
return hashing_type | python | def hashing_type(self, cluster='main'):
"""Hashing type of cluster."""
if not self.config.has_section(cluster):
raise SystemExit("Cluster '%s' not defined in %s"
% (cluster, self.config_file))
hashing_type = 'carbon_ch'
try:
return self.config.get(cluster, 'hashing_type')
except NoOptionError:
return hashing_type | [
"def",
"hashing_type",
"(",
"self",
",",
"cluster",
"=",
"'main'",
")",
":",
"if",
"not",
"self",
".",
"config",
".",
"has_section",
"(",
"cluster",
")",
":",
"raise",
"SystemExit",
"(",
"\"Cluster '%s' not defined in %s\"",
"%",
"(",
"cluster",
",",
"self",
".",
"config_file",
")",
")",
"hashing_type",
"=",
"'carbon_ch'",
"try",
":",
"return",
"self",
".",
"config",
".",
"get",
"(",
"cluster",
",",
"'hashing_type'",
")",
"except",
"NoOptionError",
":",
"return",
"hashing_type"
] | Hashing type of cluster. | [
"Hashing",
"type",
"of",
"cluster",
"."
] | b876a85b321fbd7c18a6721bed2e7807b79b4929 | https://github.com/graphite-project/carbonate/blob/b876a85b321fbd7c18a6721bed2e7807b79b4929/carbonate/config.py#L56-L65 | train | 233,864 |
graphite-project/carbonate | carbonate/fill.py | fill_archives | def fill_archives(src, dst, startFrom, endAt=0, overwrite=False,
lock_writes=False):
"""
Fills gaps in dst using data from src.
src is the path as a string
dst is the path as a string
startFrom is the latest timestamp (archives are read backward)
endAt is the earliest timestamp (archives are read backward).
if absent, we take the earliest timestamp in the archive
overwrite will write all non null points from src dst.
lock using whisper lock if true
"""
if lock_writes is False:
whisper.LOCK = False
elif whisper.CAN_LOCK and lock_writes is True:
whisper.LOCK = True
header = whisper.info(dst)
archives = header['archives']
archives = sorted(archives, key=lambda t: t['retention'])
for archive in archives:
fromTime = max(endAt, time.time() - archive['retention'])
if fromTime >= startFrom:
continue
(timeInfo, values) = whisper.fetch(dst, fromTime, untilTime=startFrom)
(start, end, step) = timeInfo
gapstart = None
for value in values:
has_value = bool(value and not overwrite)
if not has_value and not gapstart:
gapstart = start
elif has_value and gapstart:
if (start - gapstart) >= archive['secondsPerPoint']:
fill(src, dst, gapstart - step, start)
gapstart = None
start += step
# fill if this gap continues to the end
if gapstart:
fill(src, dst, gapstart - step, end - step)
# The next archive only needs to be filled up to the latest point
# in time we updated.
startFrom = fromTime | python | def fill_archives(src, dst, startFrom, endAt=0, overwrite=False,
lock_writes=False):
"""
Fills gaps in dst using data from src.
src is the path as a string
dst is the path as a string
startFrom is the latest timestamp (archives are read backward)
endAt is the earliest timestamp (archives are read backward).
if absent, we take the earliest timestamp in the archive
overwrite will write all non null points from src dst.
lock using whisper lock if true
"""
if lock_writes is False:
whisper.LOCK = False
elif whisper.CAN_LOCK and lock_writes is True:
whisper.LOCK = True
header = whisper.info(dst)
archives = header['archives']
archives = sorted(archives, key=lambda t: t['retention'])
for archive in archives:
fromTime = max(endAt, time.time() - archive['retention'])
if fromTime >= startFrom:
continue
(timeInfo, values) = whisper.fetch(dst, fromTime, untilTime=startFrom)
(start, end, step) = timeInfo
gapstart = None
for value in values:
has_value = bool(value and not overwrite)
if not has_value and not gapstart:
gapstart = start
elif has_value and gapstart:
if (start - gapstart) >= archive['secondsPerPoint']:
fill(src, dst, gapstart - step, start)
gapstart = None
start += step
# fill if this gap continues to the end
if gapstart:
fill(src, dst, gapstart - step, end - step)
# The next archive only needs to be filled up to the latest point
# in time we updated.
startFrom = fromTime | [
"def",
"fill_archives",
"(",
"src",
",",
"dst",
",",
"startFrom",
",",
"endAt",
"=",
"0",
",",
"overwrite",
"=",
"False",
",",
"lock_writes",
"=",
"False",
")",
":",
"if",
"lock_writes",
"is",
"False",
":",
"whisper",
".",
"LOCK",
"=",
"False",
"elif",
"whisper",
".",
"CAN_LOCK",
"and",
"lock_writes",
"is",
"True",
":",
"whisper",
".",
"LOCK",
"=",
"True",
"header",
"=",
"whisper",
".",
"info",
"(",
"dst",
")",
"archives",
"=",
"header",
"[",
"'archives'",
"]",
"archives",
"=",
"sorted",
"(",
"archives",
",",
"key",
"=",
"lambda",
"t",
":",
"t",
"[",
"'retention'",
"]",
")",
"for",
"archive",
"in",
"archives",
":",
"fromTime",
"=",
"max",
"(",
"endAt",
",",
"time",
".",
"time",
"(",
")",
"-",
"archive",
"[",
"'retention'",
"]",
")",
"if",
"fromTime",
">=",
"startFrom",
":",
"continue",
"(",
"timeInfo",
",",
"values",
")",
"=",
"whisper",
".",
"fetch",
"(",
"dst",
",",
"fromTime",
",",
"untilTime",
"=",
"startFrom",
")",
"(",
"start",
",",
"end",
",",
"step",
")",
"=",
"timeInfo",
"gapstart",
"=",
"None",
"for",
"value",
"in",
"values",
":",
"has_value",
"=",
"bool",
"(",
"value",
"and",
"not",
"overwrite",
")",
"if",
"not",
"has_value",
"and",
"not",
"gapstart",
":",
"gapstart",
"=",
"start",
"elif",
"has_value",
"and",
"gapstart",
":",
"if",
"(",
"start",
"-",
"gapstart",
")",
">=",
"archive",
"[",
"'secondsPerPoint'",
"]",
":",
"fill",
"(",
"src",
",",
"dst",
",",
"gapstart",
"-",
"step",
",",
"start",
")",
"gapstart",
"=",
"None",
"start",
"+=",
"step",
"# fill if this gap continues to the end",
"if",
"gapstart",
":",
"fill",
"(",
"src",
",",
"dst",
",",
"gapstart",
"-",
"step",
",",
"end",
"-",
"step",
")",
"# The next archive only needs to be filled up to the latest point",
"# in time we updated.",
"startFrom",
"=",
"fromTime"
] | Fills gaps in dst using data from src.
src is the path as a string
dst is the path as a string
startFrom is the latest timestamp (archives are read backward)
endAt is the earliest timestamp (archives are read backward).
if absent, we take the earliest timestamp in the archive
overwrite will write all non null points from src dst.
lock using whisper lock if true | [
"Fills",
"gaps",
"in",
"dst",
"using",
"data",
"from",
"src",
"."
] | b876a85b321fbd7c18a6721bed2e7807b79b4929 | https://github.com/graphite-project/carbonate/blob/b876a85b321fbd7c18a6721bed2e7807b79b4929/carbonate/fill.py#L88-L133 | train | 233,865 |
graphite-project/carbonate | carbonate/stale.py | data | def data(path, hours, offset=0):
"""
Does the metric at ``path`` have any whisper data newer than ``hours``?
If ``offset`` is not None, view the ``hours`` prior to ``offset`` hours
ago, instead of from right now.
"""
now = time.time()
end = now - _to_sec(offset) # Will default to now
start = end - _to_sec(hours)
_data = whisper.fetch(path, start, end)
return all(x is None for x in _data[-1]) | python | def data(path, hours, offset=0):
"""
Does the metric at ``path`` have any whisper data newer than ``hours``?
If ``offset`` is not None, view the ``hours`` prior to ``offset`` hours
ago, instead of from right now.
"""
now = time.time()
end = now - _to_sec(offset) # Will default to now
start = end - _to_sec(hours)
_data = whisper.fetch(path, start, end)
return all(x is None for x in _data[-1]) | [
"def",
"data",
"(",
"path",
",",
"hours",
",",
"offset",
"=",
"0",
")",
":",
"now",
"=",
"time",
".",
"time",
"(",
")",
"end",
"=",
"now",
"-",
"_to_sec",
"(",
"offset",
")",
"# Will default to now",
"start",
"=",
"end",
"-",
"_to_sec",
"(",
"hours",
")",
"_data",
"=",
"whisper",
".",
"fetch",
"(",
"path",
",",
"start",
",",
"end",
")",
"return",
"all",
"(",
"x",
"is",
"None",
"for",
"x",
"in",
"_data",
"[",
"-",
"1",
"]",
")"
] | Does the metric at ``path`` have any whisper data newer than ``hours``?
If ``offset`` is not None, view the ``hours`` prior to ``offset`` hours
ago, instead of from right now. | [
"Does",
"the",
"metric",
"at",
"path",
"have",
"any",
"whisper",
"data",
"newer",
"than",
"hours",
"?"
] | b876a85b321fbd7c18a6721bed2e7807b79b4929 | https://github.com/graphite-project/carbonate/blob/b876a85b321fbd7c18a6721bed2e7807b79b4929/carbonate/stale.py#L11-L22 | train | 233,866 |
graphite-project/carbonate | carbonate/stale.py | stat | def stat(path, hours, offset=None):
"""
Has the metric file at ``path`` been modified since ``hours`` ago?
.. note::
``offset`` is only for compatibility with ``data()`` and is ignored.
"""
return os.stat(path).st_mtime < (time.time() - _to_sec(hours)) | python | def stat(path, hours, offset=None):
"""
Has the metric file at ``path`` been modified since ``hours`` ago?
.. note::
``offset`` is only for compatibility with ``data()`` and is ignored.
"""
return os.stat(path).st_mtime < (time.time() - _to_sec(hours)) | [
"def",
"stat",
"(",
"path",
",",
"hours",
",",
"offset",
"=",
"None",
")",
":",
"return",
"os",
".",
"stat",
"(",
"path",
")",
".",
"st_mtime",
"<",
"(",
"time",
".",
"time",
"(",
")",
"-",
"_to_sec",
"(",
"hours",
")",
")"
] | Has the metric file at ``path`` been modified since ``hours`` ago?
.. note::
``offset`` is only for compatibility with ``data()`` and is ignored. | [
"Has",
"the",
"metric",
"file",
"at",
"path",
"been",
"modified",
"since",
"hours",
"ago?"
] | b876a85b321fbd7c18a6721bed2e7807b79b4929 | https://github.com/graphite-project/carbonate/blob/b876a85b321fbd7c18a6721bed2e7807b79b4929/carbonate/stale.py#L25-L32 | train | 233,867 |
holgern/pyedflib | util/refguide_check.py | short_path | def short_path(path, cwd=None):
"""
Return relative or absolute path name, whichever is shortest.
"""
if not isinstance(path, str):
return path
if cwd is None:
cwd = os.getcwd()
abspath = os.path.abspath(path)
relpath = os.path.relpath(path, cwd)
if len(abspath) <= len(relpath):
return abspath
return relpath | python | def short_path(path, cwd=None):
"""
Return relative or absolute path name, whichever is shortest.
"""
if not isinstance(path, str):
return path
if cwd is None:
cwd = os.getcwd()
abspath = os.path.abspath(path)
relpath = os.path.relpath(path, cwd)
if len(abspath) <= len(relpath):
return abspath
return relpath | [
"def",
"short_path",
"(",
"path",
",",
"cwd",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"path",
",",
"str",
")",
":",
"return",
"path",
"if",
"cwd",
"is",
"None",
":",
"cwd",
"=",
"os",
".",
"getcwd",
"(",
")",
"abspath",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"path",
")",
"relpath",
"=",
"os",
".",
"path",
".",
"relpath",
"(",
"path",
",",
"cwd",
")",
"if",
"len",
"(",
"abspath",
")",
"<=",
"len",
"(",
"relpath",
")",
":",
"return",
"abspath",
"return",
"relpath"
] | Return relative or absolute path name, whichever is shortest. | [
"Return",
"relative",
"or",
"absolute",
"path",
"name",
"whichever",
"is",
"shortest",
"."
] | 0f787fc1202b84a6f30d098296acf72666eaeeb4 | https://github.com/holgern/pyedflib/blob/0f787fc1202b84a6f30d098296acf72666eaeeb4/util/refguide_check.py#L74-L86 | train | 233,868 |
holgern/pyedflib | util/refguide_check.py | check_rest | def check_rest(module, names, dots=True):
"""
Check reStructuredText formatting of docstrings
Returns: [(name, success_flag, output), ...]
"""
try:
skip_types = (dict, str, unicode, float, int)
except NameError:
# python 3
skip_types = (dict, str, float, int)
results = []
if module.__name__[6:] not in OTHER_MODULE_DOCS:
results += [(module.__name__,) +
validate_rst_syntax(inspect.getdoc(module),
module.__name__, dots=dots)]
for name in names:
full_name = module.__name__ + '.' + name
obj = getattr(module, name, None)
if obj is None:
results.append((full_name, False, "%s has no docstring" % (full_name,)))
continue
elif isinstance(obj, skip_types):
continue
if inspect.ismodule(obj):
text = inspect.getdoc(obj)
else:
try:
text = str(get_doc_object(obj))
except:
import traceback
results.append((full_name, False,
"Error in docstring format!\n" +
traceback.format_exc()))
continue
m = re.search("([\x00-\x09\x0b-\x1f])", text)
if m:
msg = ("Docstring contains a non-printable character %r! "
"Maybe forgot r\"\"\"?" % (m.group(1),))
results.append((full_name, False, msg))
continue
try:
src_file = short_path(inspect.getsourcefile(obj))
except TypeError:
src_file = None
if src_file:
file_full_name = src_file + ':' + full_name
else:
file_full_name = full_name
results.append((full_name,) +
validate_rst_syntax(text, file_full_name, dots=dots))
return results | python | def check_rest(module, names, dots=True):
"""
Check reStructuredText formatting of docstrings
Returns: [(name, success_flag, output), ...]
"""
try:
skip_types = (dict, str, unicode, float, int)
except NameError:
# python 3
skip_types = (dict, str, float, int)
results = []
if module.__name__[6:] not in OTHER_MODULE_DOCS:
results += [(module.__name__,) +
validate_rst_syntax(inspect.getdoc(module),
module.__name__, dots=dots)]
for name in names:
full_name = module.__name__ + '.' + name
obj = getattr(module, name, None)
if obj is None:
results.append((full_name, False, "%s has no docstring" % (full_name,)))
continue
elif isinstance(obj, skip_types):
continue
if inspect.ismodule(obj):
text = inspect.getdoc(obj)
else:
try:
text = str(get_doc_object(obj))
except:
import traceback
results.append((full_name, False,
"Error in docstring format!\n" +
traceback.format_exc()))
continue
m = re.search("([\x00-\x09\x0b-\x1f])", text)
if m:
msg = ("Docstring contains a non-printable character %r! "
"Maybe forgot r\"\"\"?" % (m.group(1),))
results.append((full_name, False, msg))
continue
try:
src_file = short_path(inspect.getsourcefile(obj))
except TypeError:
src_file = None
if src_file:
file_full_name = src_file + ':' + full_name
else:
file_full_name = full_name
results.append((full_name,) +
validate_rst_syntax(text, file_full_name, dots=dots))
return results | [
"def",
"check_rest",
"(",
"module",
",",
"names",
",",
"dots",
"=",
"True",
")",
":",
"try",
":",
"skip_types",
"=",
"(",
"dict",
",",
"str",
",",
"unicode",
",",
"float",
",",
"int",
")",
"except",
"NameError",
":",
"# python 3",
"skip_types",
"=",
"(",
"dict",
",",
"str",
",",
"float",
",",
"int",
")",
"results",
"=",
"[",
"]",
"if",
"module",
".",
"__name__",
"[",
"6",
":",
"]",
"not",
"in",
"OTHER_MODULE_DOCS",
":",
"results",
"+=",
"[",
"(",
"module",
".",
"__name__",
",",
")",
"+",
"validate_rst_syntax",
"(",
"inspect",
".",
"getdoc",
"(",
"module",
")",
",",
"module",
".",
"__name__",
",",
"dots",
"=",
"dots",
")",
"]",
"for",
"name",
"in",
"names",
":",
"full_name",
"=",
"module",
".",
"__name__",
"+",
"'.'",
"+",
"name",
"obj",
"=",
"getattr",
"(",
"module",
",",
"name",
",",
"None",
")",
"if",
"obj",
"is",
"None",
":",
"results",
".",
"append",
"(",
"(",
"full_name",
",",
"False",
",",
"\"%s has no docstring\"",
"%",
"(",
"full_name",
",",
")",
")",
")",
"continue",
"elif",
"isinstance",
"(",
"obj",
",",
"skip_types",
")",
":",
"continue",
"if",
"inspect",
".",
"ismodule",
"(",
"obj",
")",
":",
"text",
"=",
"inspect",
".",
"getdoc",
"(",
"obj",
")",
"else",
":",
"try",
":",
"text",
"=",
"str",
"(",
"get_doc_object",
"(",
"obj",
")",
")",
"except",
":",
"import",
"traceback",
"results",
".",
"append",
"(",
"(",
"full_name",
",",
"False",
",",
"\"Error in docstring format!\\n\"",
"+",
"traceback",
".",
"format_exc",
"(",
")",
")",
")",
"continue",
"m",
"=",
"re",
".",
"search",
"(",
"\"([\\x00-\\x09\\x0b-\\x1f])\"",
",",
"text",
")",
"if",
"m",
":",
"msg",
"=",
"(",
"\"Docstring contains a non-printable character %r! \"",
"\"Maybe forgot r\\\"\\\"\\\"?\"",
"%",
"(",
"m",
".",
"group",
"(",
"1",
")",
",",
")",
")",
"results",
".",
"append",
"(",
"(",
"full_name",
",",
"False",
",",
"msg",
")",
")",
"continue",
"try",
":",
"src_file",
"=",
"short_path",
"(",
"inspect",
".",
"getsourcefile",
"(",
"obj",
")",
")",
"except",
"TypeError",
":",
"src_file",
"=",
"None",
"if",
"src_file",
":",
"file_full_name",
"=",
"src_file",
"+",
"':'",
"+",
"full_name",
"else",
":",
"file_full_name",
"=",
"full_name",
"results",
".",
"append",
"(",
"(",
"full_name",
",",
")",
"+",
"validate_rst_syntax",
"(",
"text",
",",
"file_full_name",
",",
"dots",
"=",
"dots",
")",
")",
"return",
"results"
] | Check reStructuredText formatting of docstrings
Returns: [(name, success_flag, output), ...] | [
"Check",
"reStructuredText",
"formatting",
"of",
"docstrings"
] | 0f787fc1202b84a6f30d098296acf72666eaeeb4 | https://github.com/holgern/pyedflib/blob/0f787fc1202b84a6f30d098296acf72666eaeeb4/util/refguide_check.py#L310-L372 | train | 233,869 |
holgern/pyedflib | pyedflib/edfwriter.py | EdfWriter.update_header | def update_header(self):
"""
Updates header to edffile struct
"""
set_technician(self.handle, du(self.technician))
set_recording_additional(self.handle, du(self.recording_additional))
set_patientname(self.handle, du(self.patient_name))
set_patientcode(self.handle, du(self.patient_code))
set_patient_additional(self.handle, du(self.patient_additional))
set_equipment(self.handle, du(self.equipment))
set_admincode(self.handle, du(self.admincode))
if isinstance(self.gender, int):
set_gender(self.handle, self.gender)
elif self.gender == "Male":
set_gender(self.handle, 0)
elif self.gender == "Female":
set_gender(self.handle, 1)
set_datarecord_duration(self.handle, self.duration)
set_number_of_annotation_signals(self.handle, self.number_of_annotations)
set_startdatetime(self.handle, self.recording_start_time.year, self.recording_start_time.month,
self.recording_start_time.day, self.recording_start_time.hour,
self.recording_start_time.minute, self.recording_start_time.second)
if isstr(self.birthdate):
if self.birthdate != '':
birthday = datetime.strptime(self.birthdate, '%d %b %Y').date()
set_birthdate(self.handle, birthday.year, birthday.month, birthday.day)
else:
set_birthdate(self.handle, self.birthdate.year, self.birthdate.month, self.birthdate.day)
for i in np.arange(self.n_channels):
set_samplefrequency(self.handle, i, self.channels[i]['sample_rate'])
set_physical_maximum(self.handle, i, self.channels[i]['physical_max'])
set_physical_minimum(self.handle, i, self.channels[i]['physical_min'])
set_digital_maximum(self.handle, i, self.channels[i]['digital_max'])
set_digital_minimum(self.handle, i, self.channels[i]['digital_min'])
set_label(self.handle, i, du(self.channels[i]['label']))
set_physical_dimension(self.handle, i, du(self.channels[i]['dimension']))
set_transducer(self.handle, i, du(self.channels[i]['transducer']))
set_prefilter(self.handle, i, du(self.channels[i]['prefilter'])) | python | def update_header(self):
"""
Updates header to edffile struct
"""
set_technician(self.handle, du(self.technician))
set_recording_additional(self.handle, du(self.recording_additional))
set_patientname(self.handle, du(self.patient_name))
set_patientcode(self.handle, du(self.patient_code))
set_patient_additional(self.handle, du(self.patient_additional))
set_equipment(self.handle, du(self.equipment))
set_admincode(self.handle, du(self.admincode))
if isinstance(self.gender, int):
set_gender(self.handle, self.gender)
elif self.gender == "Male":
set_gender(self.handle, 0)
elif self.gender == "Female":
set_gender(self.handle, 1)
set_datarecord_duration(self.handle, self.duration)
set_number_of_annotation_signals(self.handle, self.number_of_annotations)
set_startdatetime(self.handle, self.recording_start_time.year, self.recording_start_time.month,
self.recording_start_time.day, self.recording_start_time.hour,
self.recording_start_time.minute, self.recording_start_time.second)
if isstr(self.birthdate):
if self.birthdate != '':
birthday = datetime.strptime(self.birthdate, '%d %b %Y').date()
set_birthdate(self.handle, birthday.year, birthday.month, birthday.day)
else:
set_birthdate(self.handle, self.birthdate.year, self.birthdate.month, self.birthdate.day)
for i in np.arange(self.n_channels):
set_samplefrequency(self.handle, i, self.channels[i]['sample_rate'])
set_physical_maximum(self.handle, i, self.channels[i]['physical_max'])
set_physical_minimum(self.handle, i, self.channels[i]['physical_min'])
set_digital_maximum(self.handle, i, self.channels[i]['digital_max'])
set_digital_minimum(self.handle, i, self.channels[i]['digital_min'])
set_label(self.handle, i, du(self.channels[i]['label']))
set_physical_dimension(self.handle, i, du(self.channels[i]['dimension']))
set_transducer(self.handle, i, du(self.channels[i]['transducer']))
set_prefilter(self.handle, i, du(self.channels[i]['prefilter'])) | [
"def",
"update_header",
"(",
"self",
")",
":",
"set_technician",
"(",
"self",
".",
"handle",
",",
"du",
"(",
"self",
".",
"technician",
")",
")",
"set_recording_additional",
"(",
"self",
".",
"handle",
",",
"du",
"(",
"self",
".",
"recording_additional",
")",
")",
"set_patientname",
"(",
"self",
".",
"handle",
",",
"du",
"(",
"self",
".",
"patient_name",
")",
")",
"set_patientcode",
"(",
"self",
".",
"handle",
",",
"du",
"(",
"self",
".",
"patient_code",
")",
")",
"set_patient_additional",
"(",
"self",
".",
"handle",
",",
"du",
"(",
"self",
".",
"patient_additional",
")",
")",
"set_equipment",
"(",
"self",
".",
"handle",
",",
"du",
"(",
"self",
".",
"equipment",
")",
")",
"set_admincode",
"(",
"self",
".",
"handle",
",",
"du",
"(",
"self",
".",
"admincode",
")",
")",
"if",
"isinstance",
"(",
"self",
".",
"gender",
",",
"int",
")",
":",
"set_gender",
"(",
"self",
".",
"handle",
",",
"self",
".",
"gender",
")",
"elif",
"self",
".",
"gender",
"==",
"\"Male\"",
":",
"set_gender",
"(",
"self",
".",
"handle",
",",
"0",
")",
"elif",
"self",
".",
"gender",
"==",
"\"Female\"",
":",
"set_gender",
"(",
"self",
".",
"handle",
",",
"1",
")",
"set_datarecord_duration",
"(",
"self",
".",
"handle",
",",
"self",
".",
"duration",
")",
"set_number_of_annotation_signals",
"(",
"self",
".",
"handle",
",",
"self",
".",
"number_of_annotations",
")",
"set_startdatetime",
"(",
"self",
".",
"handle",
",",
"self",
".",
"recording_start_time",
".",
"year",
",",
"self",
".",
"recording_start_time",
".",
"month",
",",
"self",
".",
"recording_start_time",
".",
"day",
",",
"self",
".",
"recording_start_time",
".",
"hour",
",",
"self",
".",
"recording_start_time",
".",
"minute",
",",
"self",
".",
"recording_start_time",
".",
"second",
")",
"if",
"isstr",
"(",
"self",
".",
"birthdate",
")",
":",
"if",
"self",
".",
"birthdate",
"!=",
"''",
":",
"birthday",
"=",
"datetime",
".",
"strptime",
"(",
"self",
".",
"birthdate",
",",
"'%d %b %Y'",
")",
".",
"date",
"(",
")",
"set_birthdate",
"(",
"self",
".",
"handle",
",",
"birthday",
".",
"year",
",",
"birthday",
".",
"month",
",",
"birthday",
".",
"day",
")",
"else",
":",
"set_birthdate",
"(",
"self",
".",
"handle",
",",
"self",
".",
"birthdate",
".",
"year",
",",
"self",
".",
"birthdate",
".",
"month",
",",
"self",
".",
"birthdate",
".",
"day",
")",
"for",
"i",
"in",
"np",
".",
"arange",
"(",
"self",
".",
"n_channels",
")",
":",
"set_samplefrequency",
"(",
"self",
".",
"handle",
",",
"i",
",",
"self",
".",
"channels",
"[",
"i",
"]",
"[",
"'sample_rate'",
"]",
")",
"set_physical_maximum",
"(",
"self",
".",
"handle",
",",
"i",
",",
"self",
".",
"channels",
"[",
"i",
"]",
"[",
"'physical_max'",
"]",
")",
"set_physical_minimum",
"(",
"self",
".",
"handle",
",",
"i",
",",
"self",
".",
"channels",
"[",
"i",
"]",
"[",
"'physical_min'",
"]",
")",
"set_digital_maximum",
"(",
"self",
".",
"handle",
",",
"i",
",",
"self",
".",
"channels",
"[",
"i",
"]",
"[",
"'digital_max'",
"]",
")",
"set_digital_minimum",
"(",
"self",
".",
"handle",
",",
"i",
",",
"self",
".",
"channels",
"[",
"i",
"]",
"[",
"'digital_min'",
"]",
")",
"set_label",
"(",
"self",
".",
"handle",
",",
"i",
",",
"du",
"(",
"self",
".",
"channels",
"[",
"i",
"]",
"[",
"'label'",
"]",
")",
")",
"set_physical_dimension",
"(",
"self",
".",
"handle",
",",
"i",
",",
"du",
"(",
"self",
".",
"channels",
"[",
"i",
"]",
"[",
"'dimension'",
"]",
")",
")",
"set_transducer",
"(",
"self",
".",
"handle",
",",
"i",
",",
"du",
"(",
"self",
".",
"channels",
"[",
"i",
"]",
"[",
"'transducer'",
"]",
")",
")",
"set_prefilter",
"(",
"self",
".",
"handle",
",",
"i",
",",
"du",
"(",
"self",
".",
"channels",
"[",
"i",
"]",
"[",
"'prefilter'",
"]",
")",
")"
] | Updates header to edffile struct | [
"Updates",
"header",
"to",
"edffile",
"struct"
] | 0f787fc1202b84a6f30d098296acf72666eaeeb4 | https://github.com/holgern/pyedflib/blob/0f787fc1202b84a6f30d098296acf72666eaeeb4/pyedflib/edfwriter.py#L137-L175 | train | 233,870 |
holgern/pyedflib | pyedflib/edfwriter.py | EdfWriter.setHeader | def setHeader(self, fileHeader):
"""
Sets the file header
"""
self.technician = fileHeader["technician"]
self.recording_additional = fileHeader["recording_additional"]
self.patient_name = fileHeader["patientname"]
self.patient_additional = fileHeader["patient_additional"]
self.patient_code = fileHeader["patientcode"]
self.equipment = fileHeader["equipment"]
self.admincode = fileHeader["admincode"]
self.gender = fileHeader["gender"]
self.recording_start_time = fileHeader["startdate"]
self.birthdate = fileHeader["birthdate"]
self.update_header() | python | def setHeader(self, fileHeader):
"""
Sets the file header
"""
self.technician = fileHeader["technician"]
self.recording_additional = fileHeader["recording_additional"]
self.patient_name = fileHeader["patientname"]
self.patient_additional = fileHeader["patient_additional"]
self.patient_code = fileHeader["patientcode"]
self.equipment = fileHeader["equipment"]
self.admincode = fileHeader["admincode"]
self.gender = fileHeader["gender"]
self.recording_start_time = fileHeader["startdate"]
self.birthdate = fileHeader["birthdate"]
self.update_header() | [
"def",
"setHeader",
"(",
"self",
",",
"fileHeader",
")",
":",
"self",
".",
"technician",
"=",
"fileHeader",
"[",
"\"technician\"",
"]",
"self",
".",
"recording_additional",
"=",
"fileHeader",
"[",
"\"recording_additional\"",
"]",
"self",
".",
"patient_name",
"=",
"fileHeader",
"[",
"\"patientname\"",
"]",
"self",
".",
"patient_additional",
"=",
"fileHeader",
"[",
"\"patient_additional\"",
"]",
"self",
".",
"patient_code",
"=",
"fileHeader",
"[",
"\"patientcode\"",
"]",
"self",
".",
"equipment",
"=",
"fileHeader",
"[",
"\"equipment\"",
"]",
"self",
".",
"admincode",
"=",
"fileHeader",
"[",
"\"admincode\"",
"]",
"self",
".",
"gender",
"=",
"fileHeader",
"[",
"\"gender\"",
"]",
"self",
".",
"recording_start_time",
"=",
"fileHeader",
"[",
"\"startdate\"",
"]",
"self",
".",
"birthdate",
"=",
"fileHeader",
"[",
"\"birthdate\"",
"]",
"self",
".",
"update_header",
"(",
")"
] | Sets the file header | [
"Sets",
"the",
"file",
"header"
] | 0f787fc1202b84a6f30d098296acf72666eaeeb4 | https://github.com/holgern/pyedflib/blob/0f787fc1202b84a6f30d098296acf72666eaeeb4/pyedflib/edfwriter.py#L177-L191 | train | 233,871 |
holgern/pyedflib | pyedflib/edfwriter.py | EdfWriter.setSignalHeader | def setSignalHeader(self, edfsignal, channel_info):
"""
Sets the parameter for signal edfsignal.
channel_info should be a dict with
these values:
'label' : channel label (string, <= 16 characters, must be unique)
'dimension' : physical dimension (e.g., mV) (string, <= 8 characters)
'sample_rate' : sample frequency in hertz (int)
'physical_max' : maximum physical value (float)
'physical_min' : minimum physical value (float)
'digital_max' : maximum digital value (int, -2**15 <= x < 2**15)
'digital_min' : minimum digital value (int, -2**15 <= x < 2**15)
"""
if edfsignal < 0 or edfsignal > self.n_channels:
raise ChannelDoesNotExist(edfsignal)
self.channels[edfsignal] = channel_info
self.update_header() | python | def setSignalHeader(self, edfsignal, channel_info):
"""
Sets the parameter for signal edfsignal.
channel_info should be a dict with
these values:
'label' : channel label (string, <= 16 characters, must be unique)
'dimension' : physical dimension (e.g., mV) (string, <= 8 characters)
'sample_rate' : sample frequency in hertz (int)
'physical_max' : maximum physical value (float)
'physical_min' : minimum physical value (float)
'digital_max' : maximum digital value (int, -2**15 <= x < 2**15)
'digital_min' : minimum digital value (int, -2**15 <= x < 2**15)
"""
if edfsignal < 0 or edfsignal > self.n_channels:
raise ChannelDoesNotExist(edfsignal)
self.channels[edfsignal] = channel_info
self.update_header() | [
"def",
"setSignalHeader",
"(",
"self",
",",
"edfsignal",
",",
"channel_info",
")",
":",
"if",
"edfsignal",
"<",
"0",
"or",
"edfsignal",
">",
"self",
".",
"n_channels",
":",
"raise",
"ChannelDoesNotExist",
"(",
"edfsignal",
")",
"self",
".",
"channels",
"[",
"edfsignal",
"]",
"=",
"channel_info",
"self",
".",
"update_header",
"(",
")"
] | Sets the parameter for signal edfsignal.
channel_info should be a dict with
these values:
'label' : channel label (string, <= 16 characters, must be unique)
'dimension' : physical dimension (e.g., mV) (string, <= 8 characters)
'sample_rate' : sample frequency in hertz (int)
'physical_max' : maximum physical value (float)
'physical_min' : minimum physical value (float)
'digital_max' : maximum digital value (int, -2**15 <= x < 2**15)
'digital_min' : minimum digital value (int, -2**15 <= x < 2**15) | [
"Sets",
"the",
"parameter",
"for",
"signal",
"edfsignal",
"."
] | 0f787fc1202b84a6f30d098296acf72666eaeeb4 | https://github.com/holgern/pyedflib/blob/0f787fc1202b84a6f30d098296acf72666eaeeb4/pyedflib/edfwriter.py#L193-L211 | train | 233,872 |
holgern/pyedflib | pyedflib/edfwriter.py | EdfWriter.setSignalHeaders | def setSignalHeaders(self, signalHeaders):
"""
Sets the parameter for all signals
Parameters
----------
signalHeaders : array_like
containing dict with
'label' : str
channel label (string, <= 16 characters, must be unique)
'dimension' : str
physical dimension (e.g., mV) (string, <= 8 characters)
'sample_rate' : int
sample frequency in hertz
'physical_max' : float
maximum physical value
'physical_min' : float
minimum physical value
'digital_max' : int
maximum digital value (-2**15 <= x < 2**15)
'digital_min' : int
minimum digital value (-2**15 <= x < 2**15)
"""
for edfsignal in np.arange(self.n_channels):
self.channels[edfsignal] = signalHeaders[edfsignal]
self.update_header() | python | def setSignalHeaders(self, signalHeaders):
"""
Sets the parameter for all signals
Parameters
----------
signalHeaders : array_like
containing dict with
'label' : str
channel label (string, <= 16 characters, must be unique)
'dimension' : str
physical dimension (e.g., mV) (string, <= 8 characters)
'sample_rate' : int
sample frequency in hertz
'physical_max' : float
maximum physical value
'physical_min' : float
minimum physical value
'digital_max' : int
maximum digital value (-2**15 <= x < 2**15)
'digital_min' : int
minimum digital value (-2**15 <= x < 2**15)
"""
for edfsignal in np.arange(self.n_channels):
self.channels[edfsignal] = signalHeaders[edfsignal]
self.update_header() | [
"def",
"setSignalHeaders",
"(",
"self",
",",
"signalHeaders",
")",
":",
"for",
"edfsignal",
"in",
"np",
".",
"arange",
"(",
"self",
".",
"n_channels",
")",
":",
"self",
".",
"channels",
"[",
"edfsignal",
"]",
"=",
"signalHeaders",
"[",
"edfsignal",
"]",
"self",
".",
"update_header",
"(",
")"
] | Sets the parameter for all signals
Parameters
----------
signalHeaders : array_like
containing dict with
'label' : str
channel label (string, <= 16 characters, must be unique)
'dimension' : str
physical dimension (e.g., mV) (string, <= 8 characters)
'sample_rate' : int
sample frequency in hertz
'physical_max' : float
maximum physical value
'physical_min' : float
minimum physical value
'digital_max' : int
maximum digital value (-2**15 <= x < 2**15)
'digital_min' : int
minimum digital value (-2**15 <= x < 2**15) | [
"Sets",
"the",
"parameter",
"for",
"all",
"signals"
] | 0f787fc1202b84a6f30d098296acf72666eaeeb4 | https://github.com/holgern/pyedflib/blob/0f787fc1202b84a6f30d098296acf72666eaeeb4/pyedflib/edfwriter.py#L213-L238 | train | 233,873 |
holgern/pyedflib | pyedflib/edfwriter.py | EdfWriter.set_number_of_annotation_signals | def set_number_of_annotation_signals(self, number_of_annotations):
"""
Sets the number of annotation signals. The default value is 1
This function is optional and can be called only after opening a file in writemode
and before the first sample write action
Normally you don't need to change the default value. Only when the number of annotations
you want to write is more than the number of seconds of the duration of the recording, you can use
this function to increase the storage space for annotations
Minimum is 1, maximum is 64
Parameters
----------
number_of_annotations : integer
Sets the number of annotation signals
"""
number_of_annotations = max((min((int(number_of_annotations), 64)), 1))
self.number_of_annotations = number_of_annotations
self.update_header() | python | def set_number_of_annotation_signals(self, number_of_annotations):
"""
Sets the number of annotation signals. The default value is 1
This function is optional and can be called only after opening a file in writemode
and before the first sample write action
Normally you don't need to change the default value. Only when the number of annotations
you want to write is more than the number of seconds of the duration of the recording, you can use
this function to increase the storage space for annotations
Minimum is 1, maximum is 64
Parameters
----------
number_of_annotations : integer
Sets the number of annotation signals
"""
number_of_annotations = max((min((int(number_of_annotations), 64)), 1))
self.number_of_annotations = number_of_annotations
self.update_header() | [
"def",
"set_number_of_annotation_signals",
"(",
"self",
",",
"number_of_annotations",
")",
":",
"number_of_annotations",
"=",
"max",
"(",
"(",
"min",
"(",
"(",
"int",
"(",
"number_of_annotations",
")",
",",
"64",
")",
")",
",",
"1",
")",
")",
"self",
".",
"number_of_annotations",
"=",
"number_of_annotations",
"self",
".",
"update_header",
"(",
")"
] | Sets the number of annotation signals. The default value is 1
This function is optional and can be called only after opening a file in writemode
and before the first sample write action
Normally you don't need to change the default value. Only when the number of annotations
you want to write is more than the number of seconds of the duration of the recording, you can use
this function to increase the storage space for annotations
Minimum is 1, maximum is 64
Parameters
----------
number_of_annotations : integer
Sets the number of annotation signals | [
"Sets",
"the",
"number",
"of",
"annotation",
"signals",
".",
"The",
"default",
"value",
"is",
"1",
"This",
"function",
"is",
"optional",
"and",
"can",
"be",
"called",
"only",
"after",
"opening",
"a",
"file",
"in",
"writemode",
"and",
"before",
"the",
"first",
"sample",
"write",
"action",
"Normally",
"you",
"don",
"t",
"need",
"to",
"change",
"the",
"default",
"value",
".",
"Only",
"when",
"the",
"number",
"of",
"annotations",
"you",
"want",
"to",
"write",
"is",
"more",
"than",
"the",
"number",
"of",
"seconds",
"of",
"the",
"duration",
"of",
"the",
"recording",
"you",
"can",
"use",
"this",
"function",
"to",
"increase",
"the",
"storage",
"space",
"for",
"annotations",
"Minimum",
"is",
"1",
"maximum",
"is",
"64"
] | 0f787fc1202b84a6f30d098296acf72666eaeeb4 | https://github.com/holgern/pyedflib/blob/0f787fc1202b84a6f30d098296acf72666eaeeb4/pyedflib/edfwriter.py#L364-L381 | train | 233,874 |
holgern/pyedflib | pyedflib/edfwriter.py | EdfWriter.setStartdatetime | def setStartdatetime(self, recording_start_time):
"""
Sets the recording start Time
Parameters
----------
recording_start_time: datetime object
Sets the recording start Time
"""
if isinstance(recording_start_time,datetime):
self.recording_start_time = recording_start_time
else:
self.recording_start_time = datetime.strptime(recording_start_time,"%d %b %Y %H:%M:%S")
self.update_header() | python | def setStartdatetime(self, recording_start_time):
"""
Sets the recording start Time
Parameters
----------
recording_start_time: datetime object
Sets the recording start Time
"""
if isinstance(recording_start_time,datetime):
self.recording_start_time = recording_start_time
else:
self.recording_start_time = datetime.strptime(recording_start_time,"%d %b %Y %H:%M:%S")
self.update_header() | [
"def",
"setStartdatetime",
"(",
"self",
",",
"recording_start_time",
")",
":",
"if",
"isinstance",
"(",
"recording_start_time",
",",
"datetime",
")",
":",
"self",
".",
"recording_start_time",
"=",
"recording_start_time",
"else",
":",
"self",
".",
"recording_start_time",
"=",
"datetime",
".",
"strptime",
"(",
"recording_start_time",
",",
"\"%d %b %Y %H:%M:%S\"",
")",
"self",
".",
"update_header",
"(",
")"
] | Sets the recording start Time
Parameters
----------
recording_start_time: datetime object
Sets the recording start Time | [
"Sets",
"the",
"recording",
"start",
"Time"
] | 0f787fc1202b84a6f30d098296acf72666eaeeb4 | https://github.com/holgern/pyedflib/blob/0f787fc1202b84a6f30d098296acf72666eaeeb4/pyedflib/edfwriter.py#L383-L396 | train | 233,875 |
holgern/pyedflib | pyedflib/edfwriter.py | EdfWriter.setSamplefrequency | def setSamplefrequency(self, edfsignal, samplefrequency):
"""
Sets the samplefrequency of signal edfsignal.
Notes
-----
This function is required for every signal and can be called only after opening a file in writemode and before the first sample write action.
"""
if edfsignal < 0 or edfsignal > self.n_channels:
raise ChannelDoesNotExist(edfsignal)
self.channels[edfsignal]['sample_rate'] = samplefrequency
self.update_header() | python | def setSamplefrequency(self, edfsignal, samplefrequency):
"""
Sets the samplefrequency of signal edfsignal.
Notes
-----
This function is required for every signal and can be called only after opening a file in writemode and before the first sample write action.
"""
if edfsignal < 0 or edfsignal > self.n_channels:
raise ChannelDoesNotExist(edfsignal)
self.channels[edfsignal]['sample_rate'] = samplefrequency
self.update_header() | [
"def",
"setSamplefrequency",
"(",
"self",
",",
"edfsignal",
",",
"samplefrequency",
")",
":",
"if",
"edfsignal",
"<",
"0",
"or",
"edfsignal",
">",
"self",
".",
"n_channels",
":",
"raise",
"ChannelDoesNotExist",
"(",
"edfsignal",
")",
"self",
".",
"channels",
"[",
"edfsignal",
"]",
"[",
"'sample_rate'",
"]",
"=",
"samplefrequency",
"self",
".",
"update_header",
"(",
")"
] | Sets the samplefrequency of signal edfsignal.
Notes
-----
This function is required for every signal and can be called only after opening a file in writemode and before the first sample write action. | [
"Sets",
"the",
"samplefrequency",
"of",
"signal",
"edfsignal",
"."
] | 0f787fc1202b84a6f30d098296acf72666eaeeb4 | https://github.com/holgern/pyedflib/blob/0f787fc1202b84a6f30d098296acf72666eaeeb4/pyedflib/edfwriter.py#L421-L432 | train | 233,876 |
holgern/pyedflib | pyedflib/edfwriter.py | EdfWriter.setPhysicalMaximum | def setPhysicalMaximum(self, edfsignal, physical_maximum):
"""
Sets the physical_maximum of signal edfsignal.
Parameters
----------
edfsignal: int
signal number
physical_maximum: float
Sets the physical maximum
Notes
-----
This function is required for every signal and can be called only after opening a file in writemode and before the first sample write action.
"""
if edfsignal < 0 or edfsignal > self.n_channels:
raise ChannelDoesNotExist(edfsignal)
self.channels[edfsignal]['physical_max'] = physical_maximum
self.update_header() | python | def setPhysicalMaximum(self, edfsignal, physical_maximum):
"""
Sets the physical_maximum of signal edfsignal.
Parameters
----------
edfsignal: int
signal number
physical_maximum: float
Sets the physical maximum
Notes
-----
This function is required for every signal and can be called only after opening a file in writemode and before the first sample write action.
"""
if edfsignal < 0 or edfsignal > self.n_channels:
raise ChannelDoesNotExist(edfsignal)
self.channels[edfsignal]['physical_max'] = physical_maximum
self.update_header() | [
"def",
"setPhysicalMaximum",
"(",
"self",
",",
"edfsignal",
",",
"physical_maximum",
")",
":",
"if",
"edfsignal",
"<",
"0",
"or",
"edfsignal",
">",
"self",
".",
"n_channels",
":",
"raise",
"ChannelDoesNotExist",
"(",
"edfsignal",
")",
"self",
".",
"channels",
"[",
"edfsignal",
"]",
"[",
"'physical_max'",
"]",
"=",
"physical_maximum",
"self",
".",
"update_header",
"(",
")"
] | Sets the physical_maximum of signal edfsignal.
Parameters
----------
edfsignal: int
signal number
physical_maximum: float
Sets the physical maximum
Notes
-----
This function is required for every signal and can be called only after opening a file in writemode and before the first sample write action. | [
"Sets",
"the",
"physical_maximum",
"of",
"signal",
"edfsignal",
"."
] | 0f787fc1202b84a6f30d098296acf72666eaeeb4 | https://github.com/holgern/pyedflib/blob/0f787fc1202b84a6f30d098296acf72666eaeeb4/pyedflib/edfwriter.py#L434-L452 | train | 233,877 |
holgern/pyedflib | pyedflib/edfwriter.py | EdfWriter.setPhysicalMinimum | def setPhysicalMinimum(self, edfsignal, physical_minimum):
"""
Sets the physical_minimum of signal edfsignal.
Parameters
----------
edfsignal: int
signal number
physical_minimum: float
Sets the physical minimum
Notes
-----
This function is required for every signal and can be called only after opening a file in writemode and before the first sample write action.
"""
if (edfsignal < 0 or edfsignal > self.n_channels):
raise ChannelDoesNotExist(edfsignal)
self.channels[edfsignal]['physical_min'] = physical_minimum
self.update_header() | python | def setPhysicalMinimum(self, edfsignal, physical_minimum):
"""
Sets the physical_minimum of signal edfsignal.
Parameters
----------
edfsignal: int
signal number
physical_minimum: float
Sets the physical minimum
Notes
-----
This function is required for every signal and can be called only after opening a file in writemode and before the first sample write action.
"""
if (edfsignal < 0 or edfsignal > self.n_channels):
raise ChannelDoesNotExist(edfsignal)
self.channels[edfsignal]['physical_min'] = physical_minimum
self.update_header() | [
"def",
"setPhysicalMinimum",
"(",
"self",
",",
"edfsignal",
",",
"physical_minimum",
")",
":",
"if",
"(",
"edfsignal",
"<",
"0",
"or",
"edfsignal",
">",
"self",
".",
"n_channels",
")",
":",
"raise",
"ChannelDoesNotExist",
"(",
"edfsignal",
")",
"self",
".",
"channels",
"[",
"edfsignal",
"]",
"[",
"'physical_min'",
"]",
"=",
"physical_minimum",
"self",
".",
"update_header",
"(",
")"
] | Sets the physical_minimum of signal edfsignal.
Parameters
----------
edfsignal: int
signal number
physical_minimum: float
Sets the physical minimum
Notes
-----
This function is required for every signal and can be called only after opening a file in writemode and before the first sample write action. | [
"Sets",
"the",
"physical_minimum",
"of",
"signal",
"edfsignal",
"."
] | 0f787fc1202b84a6f30d098296acf72666eaeeb4 | https://github.com/holgern/pyedflib/blob/0f787fc1202b84a6f30d098296acf72666eaeeb4/pyedflib/edfwriter.py#L454-L472 | train | 233,878 |
holgern/pyedflib | pyedflib/edfwriter.py | EdfWriter.setDigitalMaximum | def setDigitalMaximum(self, edfsignal, digital_maximum):
"""
Sets the samplefrequency of signal edfsignal.
Usually, the value 32767 is used for EDF+ and 8388607 for BDF+.
Parameters
----------
edfsignal : int
signal number
digital_maximum : int
Sets the maximum digital value
Notes
-----
This function is optional and can be called only after opening a file in writemode and before the first sample write action.
"""
if (edfsignal < 0 or edfsignal > self.n_channels):
raise ChannelDoesNotExist(edfsignal)
self.channels[edfsignal]['digital_max'] = digital_maximum
self.update_header() | python | def setDigitalMaximum(self, edfsignal, digital_maximum):
"""
Sets the samplefrequency of signal edfsignal.
Usually, the value 32767 is used for EDF+ and 8388607 for BDF+.
Parameters
----------
edfsignal : int
signal number
digital_maximum : int
Sets the maximum digital value
Notes
-----
This function is optional and can be called only after opening a file in writemode and before the first sample write action.
"""
if (edfsignal < 0 or edfsignal > self.n_channels):
raise ChannelDoesNotExist(edfsignal)
self.channels[edfsignal]['digital_max'] = digital_maximum
self.update_header() | [
"def",
"setDigitalMaximum",
"(",
"self",
",",
"edfsignal",
",",
"digital_maximum",
")",
":",
"if",
"(",
"edfsignal",
"<",
"0",
"or",
"edfsignal",
">",
"self",
".",
"n_channels",
")",
":",
"raise",
"ChannelDoesNotExist",
"(",
"edfsignal",
")",
"self",
".",
"channels",
"[",
"edfsignal",
"]",
"[",
"'digital_max'",
"]",
"=",
"digital_maximum",
"self",
".",
"update_header",
"(",
")"
] | Sets the samplefrequency of signal edfsignal.
Usually, the value 32767 is used for EDF+ and 8388607 for BDF+.
Parameters
----------
edfsignal : int
signal number
digital_maximum : int
Sets the maximum digital value
Notes
-----
This function is optional and can be called only after opening a file in writemode and before the first sample write action. | [
"Sets",
"the",
"samplefrequency",
"of",
"signal",
"edfsignal",
".",
"Usually",
"the",
"value",
"32767",
"is",
"used",
"for",
"EDF",
"+",
"and",
"8388607",
"for",
"BDF",
"+",
"."
] | 0f787fc1202b84a6f30d098296acf72666eaeeb4 | https://github.com/holgern/pyedflib/blob/0f787fc1202b84a6f30d098296acf72666eaeeb4/pyedflib/edfwriter.py#L474-L493 | train | 233,879 |
holgern/pyedflib | pyedflib/edfwriter.py | EdfWriter.setTransducer | def setTransducer(self, edfsignal, transducer):
"""
Sets the transducer of signal edfsignal
:param edfsignal: int
:param transducer: str
Notes
-----
This function is optional for every signal and can be called only after opening a file in writemode and before the first sample write action.
"""
if (edfsignal < 0 or edfsignal > self.n_channels):
raise ChannelDoesNotExist(edfsignal)
self.channels[edfsignal]['transducer'] = transducer
self.update_header() | python | def setTransducer(self, edfsignal, transducer):
"""
Sets the transducer of signal edfsignal
:param edfsignal: int
:param transducer: str
Notes
-----
This function is optional for every signal and can be called only after opening a file in writemode and before the first sample write action.
"""
if (edfsignal < 0 or edfsignal > self.n_channels):
raise ChannelDoesNotExist(edfsignal)
self.channels[edfsignal]['transducer'] = transducer
self.update_header() | [
"def",
"setTransducer",
"(",
"self",
",",
"edfsignal",
",",
"transducer",
")",
":",
"if",
"(",
"edfsignal",
"<",
"0",
"or",
"edfsignal",
">",
"self",
".",
"n_channels",
")",
":",
"raise",
"ChannelDoesNotExist",
"(",
"edfsignal",
")",
"self",
".",
"channels",
"[",
"edfsignal",
"]",
"[",
"'transducer'",
"]",
"=",
"transducer",
"self",
".",
"update_header",
"(",
")"
] | Sets the transducer of signal edfsignal
:param edfsignal: int
:param transducer: str
Notes
-----
This function is optional for every signal and can be called only after opening a file in writemode and before the first sample write action. | [
"Sets",
"the",
"transducer",
"of",
"signal",
"edfsignal"
] | 0f787fc1202b84a6f30d098296acf72666eaeeb4 | https://github.com/holgern/pyedflib/blob/0f787fc1202b84a6f30d098296acf72666eaeeb4/pyedflib/edfwriter.py#L552-L566 | train | 233,880 |
holgern/pyedflib | pyedflib/edfreader.py | EdfReader.readAnnotations | def readAnnotations(self):
"""
Annotations from a edf-file
Parameters
----------
None
"""
annot = self.read_annotation()
annot = np.array(annot)
if (annot.shape[0] == 0):
return np.array([]), np.array([]), np.array([])
ann_time = self._get_float(annot[:, 0])
ann_text = annot[:, 2]
ann_text_out = ["" for x in range(len(annot[:, 1]))]
for i in np.arange(len(annot[:, 1])):
ann_text_out[i] = self._convert_string(ann_text[i])
if annot[i, 1] == '':
annot[i, 1] = '-1'
ann_duration = self._get_float(annot[:, 1])
return ann_time/10000000, ann_duration, np.array(ann_text_out) | python | def readAnnotations(self):
"""
Annotations from a edf-file
Parameters
----------
None
"""
annot = self.read_annotation()
annot = np.array(annot)
if (annot.shape[0] == 0):
return np.array([]), np.array([]), np.array([])
ann_time = self._get_float(annot[:, 0])
ann_text = annot[:, 2]
ann_text_out = ["" for x in range(len(annot[:, 1]))]
for i in np.arange(len(annot[:, 1])):
ann_text_out[i] = self._convert_string(ann_text[i])
if annot[i, 1] == '':
annot[i, 1] = '-1'
ann_duration = self._get_float(annot[:, 1])
return ann_time/10000000, ann_duration, np.array(ann_text_out) | [
"def",
"readAnnotations",
"(",
"self",
")",
":",
"annot",
"=",
"self",
".",
"read_annotation",
"(",
")",
"annot",
"=",
"np",
".",
"array",
"(",
"annot",
")",
"if",
"(",
"annot",
".",
"shape",
"[",
"0",
"]",
"==",
"0",
")",
":",
"return",
"np",
".",
"array",
"(",
"[",
"]",
")",
",",
"np",
".",
"array",
"(",
"[",
"]",
")",
",",
"np",
".",
"array",
"(",
"[",
"]",
")",
"ann_time",
"=",
"self",
".",
"_get_float",
"(",
"annot",
"[",
":",
",",
"0",
"]",
")",
"ann_text",
"=",
"annot",
"[",
":",
",",
"2",
"]",
"ann_text_out",
"=",
"[",
"\"\"",
"for",
"x",
"in",
"range",
"(",
"len",
"(",
"annot",
"[",
":",
",",
"1",
"]",
")",
")",
"]",
"for",
"i",
"in",
"np",
".",
"arange",
"(",
"len",
"(",
"annot",
"[",
":",
",",
"1",
"]",
")",
")",
":",
"ann_text_out",
"[",
"i",
"]",
"=",
"self",
".",
"_convert_string",
"(",
"ann_text",
"[",
"i",
"]",
")",
"if",
"annot",
"[",
"i",
",",
"1",
"]",
"==",
"''",
":",
"annot",
"[",
"i",
",",
"1",
"]",
"=",
"'-1'",
"ann_duration",
"=",
"self",
".",
"_get_float",
"(",
"annot",
"[",
":",
",",
"1",
"]",
")",
"return",
"ann_time",
"/",
"10000000",
",",
"ann_duration",
",",
"np",
".",
"array",
"(",
"ann_text_out",
")"
] | Annotations from a edf-file
Parameters
----------
None | [
"Annotations",
"from",
"a",
"edf",
"-",
"file"
] | 0f787fc1202b84a6f30d098296acf72666eaeeb4 | https://github.com/holgern/pyedflib/blob/0f787fc1202b84a6f30d098296acf72666eaeeb4/pyedflib/edfreader.py#L44-L64 | train | 233,881 |
holgern/pyedflib | pyedflib/edfreader.py | EdfReader.getHeader | def getHeader(self):
"""
Returns the file header as dict
Parameters
----------
None
"""
return {"technician": self.getTechnician(), "recording_additional": self.getRecordingAdditional(),
"patientname": self.getPatientName(), "patient_additional": self.getPatientAdditional(),
"patientcode": self.getPatientCode(), "equipment": self.getEquipment(),
"admincode": self.getAdmincode(), "gender": self.getGender(), "startdate": self.getStartdatetime(),
"birthdate": self.getBirthdate()} | python | def getHeader(self):
"""
Returns the file header as dict
Parameters
----------
None
"""
return {"technician": self.getTechnician(), "recording_additional": self.getRecordingAdditional(),
"patientname": self.getPatientName(), "patient_additional": self.getPatientAdditional(),
"patientcode": self.getPatientCode(), "equipment": self.getEquipment(),
"admincode": self.getAdmincode(), "gender": self.getGender(), "startdate": self.getStartdatetime(),
"birthdate": self.getBirthdate()} | [
"def",
"getHeader",
"(",
"self",
")",
":",
"return",
"{",
"\"technician\"",
":",
"self",
".",
"getTechnician",
"(",
")",
",",
"\"recording_additional\"",
":",
"self",
".",
"getRecordingAdditional",
"(",
")",
",",
"\"patientname\"",
":",
"self",
".",
"getPatientName",
"(",
")",
",",
"\"patient_additional\"",
":",
"self",
".",
"getPatientAdditional",
"(",
")",
",",
"\"patientcode\"",
":",
"self",
".",
"getPatientCode",
"(",
")",
",",
"\"equipment\"",
":",
"self",
".",
"getEquipment",
"(",
")",
",",
"\"admincode\"",
":",
"self",
".",
"getAdmincode",
"(",
")",
",",
"\"gender\"",
":",
"self",
".",
"getGender",
"(",
")",
",",
"\"startdate\"",
":",
"self",
".",
"getStartdatetime",
"(",
")",
",",
"\"birthdate\"",
":",
"self",
".",
"getBirthdate",
"(",
")",
"}"
] | Returns the file header as dict
Parameters
----------
None | [
"Returns",
"the",
"file",
"header",
"as",
"dict"
] | 0f787fc1202b84a6f30d098296acf72666eaeeb4 | https://github.com/holgern/pyedflib/blob/0f787fc1202b84a6f30d098296acf72666eaeeb4/pyedflib/edfreader.py#L92-L104 | train | 233,882 |
holgern/pyedflib | pyedflib/edfreader.py | EdfReader.getSignalHeader | def getSignalHeader(self, chn):
"""
Returns the header of one signal as dicts
Parameters
----------
None
"""
return {'label': self.getLabel(chn),
'dimension': self.getPhysicalDimension(chn),
'sample_rate': self.getSampleFrequency(chn),
'physical_max':self.getPhysicalMaximum(chn),
'physical_min': self.getPhysicalMinimum(chn),
'digital_max': self.getDigitalMaximum(chn),
'digital_min': self.getDigitalMinimum(chn),
'prefilter':self.getPrefilter(chn),
'transducer': self.getTransducer(chn)} | python | def getSignalHeader(self, chn):
"""
Returns the header of one signal as dicts
Parameters
----------
None
"""
return {'label': self.getLabel(chn),
'dimension': self.getPhysicalDimension(chn),
'sample_rate': self.getSampleFrequency(chn),
'physical_max':self.getPhysicalMaximum(chn),
'physical_min': self.getPhysicalMinimum(chn),
'digital_max': self.getDigitalMaximum(chn),
'digital_min': self.getDigitalMinimum(chn),
'prefilter':self.getPrefilter(chn),
'transducer': self.getTransducer(chn)} | [
"def",
"getSignalHeader",
"(",
"self",
",",
"chn",
")",
":",
"return",
"{",
"'label'",
":",
"self",
".",
"getLabel",
"(",
"chn",
")",
",",
"'dimension'",
":",
"self",
".",
"getPhysicalDimension",
"(",
"chn",
")",
",",
"'sample_rate'",
":",
"self",
".",
"getSampleFrequency",
"(",
"chn",
")",
",",
"'physical_max'",
":",
"self",
".",
"getPhysicalMaximum",
"(",
"chn",
")",
",",
"'physical_min'",
":",
"self",
".",
"getPhysicalMinimum",
"(",
"chn",
")",
",",
"'digital_max'",
":",
"self",
".",
"getDigitalMaximum",
"(",
"chn",
")",
",",
"'digital_min'",
":",
"self",
".",
"getDigitalMinimum",
"(",
"chn",
")",
",",
"'prefilter'",
":",
"self",
".",
"getPrefilter",
"(",
"chn",
")",
",",
"'transducer'",
":",
"self",
".",
"getTransducer",
"(",
"chn",
")",
"}"
] | Returns the header of one signal as dicts
Parameters
----------
None | [
"Returns",
"the",
"header",
"of",
"one",
"signal",
"as",
"dicts"
] | 0f787fc1202b84a6f30d098296acf72666eaeeb4 | https://github.com/holgern/pyedflib/blob/0f787fc1202b84a6f30d098296acf72666eaeeb4/pyedflib/edfreader.py#L106-L122 | train | 233,883 |
holgern/pyedflib | pyedflib/edfreader.py | EdfReader.getSignalHeaders | def getSignalHeaders(self):
"""
Returns the header of all signals as array of dicts
Parameters
----------
None
"""
signalHeader = []
for chn in np.arange(self.signals_in_file):
signalHeader.append(self.getSignalHeader(chn))
return signalHeader | python | def getSignalHeaders(self):
"""
Returns the header of all signals as array of dicts
Parameters
----------
None
"""
signalHeader = []
for chn in np.arange(self.signals_in_file):
signalHeader.append(self.getSignalHeader(chn))
return signalHeader | [
"def",
"getSignalHeaders",
"(",
"self",
")",
":",
"signalHeader",
"=",
"[",
"]",
"for",
"chn",
"in",
"np",
".",
"arange",
"(",
"self",
".",
"signals_in_file",
")",
":",
"signalHeader",
".",
"append",
"(",
"self",
".",
"getSignalHeader",
"(",
"chn",
")",
")",
"return",
"signalHeader"
] | Returns the header of all signals as array of dicts
Parameters
----------
None | [
"Returns",
"the",
"header",
"of",
"all",
"signals",
"as",
"array",
"of",
"dicts"
] | 0f787fc1202b84a6f30d098296acf72666eaeeb4 | https://github.com/holgern/pyedflib/blob/0f787fc1202b84a6f30d098296acf72666eaeeb4/pyedflib/edfreader.py#L124-L135 | train | 233,884 |
holgern/pyedflib | pyedflib/edfreader.py | EdfReader.getStartdatetime | def getStartdatetime(self):
"""
Returns the date and starttime as datetime object
Parameters
----------
None
Examples
--------
>>> import pyedflib
>>> f = pyedflib.data.test_generator()
>>> f.getStartdatetime()
datetime.datetime(2011, 4, 4, 12, 57, 2)
>>> f._close()
>>> del f
"""
return datetime(self.startdate_year, self.startdate_month, self.startdate_day,
self.starttime_hour, self.starttime_minute, self.starttime_second) | python | def getStartdatetime(self):
"""
Returns the date and starttime as datetime object
Parameters
----------
None
Examples
--------
>>> import pyedflib
>>> f = pyedflib.data.test_generator()
>>> f.getStartdatetime()
datetime.datetime(2011, 4, 4, 12, 57, 2)
>>> f._close()
>>> del f
"""
return datetime(self.startdate_year, self.startdate_month, self.startdate_day,
self.starttime_hour, self.starttime_minute, self.starttime_second) | [
"def",
"getStartdatetime",
"(",
"self",
")",
":",
"return",
"datetime",
"(",
"self",
".",
"startdate_year",
",",
"self",
".",
"startdate_month",
",",
"self",
".",
"startdate_day",
",",
"self",
".",
"starttime_hour",
",",
"self",
".",
"starttime_minute",
",",
"self",
".",
"starttime_second",
")"
] | Returns the date and starttime as datetime object
Parameters
----------
None
Examples
--------
>>> import pyedflib
>>> f = pyedflib.data.test_generator()
>>> f.getStartdatetime()
datetime.datetime(2011, 4, 4, 12, 57, 2)
>>> f._close()
>>> del f | [
"Returns",
"the",
"date",
"and",
"starttime",
"as",
"datetime",
"object"
] | 0f787fc1202b84a6f30d098296acf72666eaeeb4 | https://github.com/holgern/pyedflib/blob/0f787fc1202b84a6f30d098296acf72666eaeeb4/pyedflib/edfreader.py#L317-L336 | train | 233,885 |
holgern/pyedflib | pyedflib/edfreader.py | EdfReader.getBirthdate | def getBirthdate(self, string=True):
"""
Returns the birthdate as string object
Parameters
----------
None
Examples
--------
>>> import pyedflib
>>> f = pyedflib.data.test_generator()
>>> f.getBirthdate()=='30 jun 1969'
True
>>> f._close()
>>> del f
"""
if string:
return self._convert_string(self.birthdate.rstrip())
else:
return datetime.strptime(self._convert_string(self.birthdate.rstrip()), "%d %b %Y") | python | def getBirthdate(self, string=True):
"""
Returns the birthdate as string object
Parameters
----------
None
Examples
--------
>>> import pyedflib
>>> f = pyedflib.data.test_generator()
>>> f.getBirthdate()=='30 jun 1969'
True
>>> f._close()
>>> del f
"""
if string:
return self._convert_string(self.birthdate.rstrip())
else:
return datetime.strptime(self._convert_string(self.birthdate.rstrip()), "%d %b %Y") | [
"def",
"getBirthdate",
"(",
"self",
",",
"string",
"=",
"True",
")",
":",
"if",
"string",
":",
"return",
"self",
".",
"_convert_string",
"(",
"self",
".",
"birthdate",
".",
"rstrip",
"(",
")",
")",
"else",
":",
"return",
"datetime",
".",
"strptime",
"(",
"self",
".",
"_convert_string",
"(",
"self",
".",
"birthdate",
".",
"rstrip",
"(",
")",
")",
",",
"\"%d %b %Y\"",
")"
] | Returns the birthdate as string object
Parameters
----------
None
Examples
--------
>>> import pyedflib
>>> f = pyedflib.data.test_generator()
>>> f.getBirthdate()=='30 jun 1969'
True
>>> f._close()
>>> del f | [
"Returns",
"the",
"birthdate",
"as",
"string",
"object"
] | 0f787fc1202b84a6f30d098296acf72666eaeeb4 | https://github.com/holgern/pyedflib/blob/0f787fc1202b84a6f30d098296acf72666eaeeb4/pyedflib/edfreader.py#L338-L360 | train | 233,886 |
holgern/pyedflib | pyedflib/edfreader.py | EdfReader.getSampleFrequencies | def getSampleFrequencies(self):
"""
Returns samplefrequencies of all signals.
Parameters
----------
None
Examples
--------
>>> import pyedflib
>>> f = pyedflib.data.test_generator()
>>> all(f.getSampleFrequencies()==200.0)
True
>>> f._close()
>>> del f
"""
return np.array([round(self.samplefrequency(chn))
for chn in np.arange(self.signals_in_file)]) | python | def getSampleFrequencies(self):
"""
Returns samplefrequencies of all signals.
Parameters
----------
None
Examples
--------
>>> import pyedflib
>>> f = pyedflib.data.test_generator()
>>> all(f.getSampleFrequencies()==200.0)
True
>>> f._close()
>>> del f
"""
return np.array([round(self.samplefrequency(chn))
for chn in np.arange(self.signals_in_file)]) | [
"def",
"getSampleFrequencies",
"(",
"self",
")",
":",
"return",
"np",
".",
"array",
"(",
"[",
"round",
"(",
"self",
".",
"samplefrequency",
"(",
"chn",
")",
")",
"for",
"chn",
"in",
"np",
".",
"arange",
"(",
"self",
".",
"signals_in_file",
")",
"]",
")"
] | Returns samplefrequencies of all signals.
Parameters
----------
None
Examples
--------
>>> import pyedflib
>>> f = pyedflib.data.test_generator()
>>> all(f.getSampleFrequencies()==200.0)
True
>>> f._close()
>>> del f | [
"Returns",
"samplefrequencies",
"of",
"all",
"signals",
"."
] | 0f787fc1202b84a6f30d098296acf72666eaeeb4 | https://github.com/holgern/pyedflib/blob/0f787fc1202b84a6f30d098296acf72666eaeeb4/pyedflib/edfreader.py#L362-L381 | train | 233,887 |
holgern/pyedflib | pyedflib/edfreader.py | EdfReader.getSampleFrequency | def getSampleFrequency(self,chn):
"""
Returns the samplefrequency of signal edfsignal.
Parameters
----------
chn : int
channel number
Examples
--------
>>> import pyedflib
>>> f = pyedflib.data.test_generator()
>>> f.getSampleFrequency(0)==200.0
True
>>> f._close()
>>> del f
"""
if 0 <= chn < self.signals_in_file:
return round(self.samplefrequency(chn))
else:
return 0 | python | def getSampleFrequency(self,chn):
"""
Returns the samplefrequency of signal edfsignal.
Parameters
----------
chn : int
channel number
Examples
--------
>>> import pyedflib
>>> f = pyedflib.data.test_generator()
>>> f.getSampleFrequency(0)==200.0
True
>>> f._close()
>>> del f
"""
if 0 <= chn < self.signals_in_file:
return round(self.samplefrequency(chn))
else:
return 0 | [
"def",
"getSampleFrequency",
"(",
"self",
",",
"chn",
")",
":",
"if",
"0",
"<=",
"chn",
"<",
"self",
".",
"signals_in_file",
":",
"return",
"round",
"(",
"self",
".",
"samplefrequency",
"(",
"chn",
")",
")",
"else",
":",
"return",
"0"
] | Returns the samplefrequency of signal edfsignal.
Parameters
----------
chn : int
channel number
Examples
--------
>>> import pyedflib
>>> f = pyedflib.data.test_generator()
>>> f.getSampleFrequency(0)==200.0
True
>>> f._close()
>>> del f | [
"Returns",
"the",
"samplefrequency",
"of",
"signal",
"edfsignal",
"."
] | 0f787fc1202b84a6f30d098296acf72666eaeeb4 | https://github.com/holgern/pyedflib/blob/0f787fc1202b84a6f30d098296acf72666eaeeb4/pyedflib/edfreader.py#L383-L405 | train | 233,888 |
holgern/pyedflib | pyedflib/edfreader.py | EdfReader.getPhysicalMaximum | def getPhysicalMaximum(self,chn=None):
"""
Returns the maximum physical value of signal edfsignal.
Parameters
----------
chn : int
channel number
Examples
--------
>>> import pyedflib
>>> f = pyedflib.data.test_generator()
>>> f.getPhysicalMaximum(0)==1000.0
True
>>> f._close()
>>> del f
"""
if chn is not None:
if 0 <= chn < self.signals_in_file:
return self.physical_max(chn)
else:
return 0
else:
physMax = np.zeros(self.signals_in_file)
for i in np.arange(self.signals_in_file):
physMax[i] = self.physical_max(i)
return physMax | python | def getPhysicalMaximum(self,chn=None):
"""
Returns the maximum physical value of signal edfsignal.
Parameters
----------
chn : int
channel number
Examples
--------
>>> import pyedflib
>>> f = pyedflib.data.test_generator()
>>> f.getPhysicalMaximum(0)==1000.0
True
>>> f._close()
>>> del f
"""
if chn is not None:
if 0 <= chn < self.signals_in_file:
return self.physical_max(chn)
else:
return 0
else:
physMax = np.zeros(self.signals_in_file)
for i in np.arange(self.signals_in_file):
physMax[i] = self.physical_max(i)
return physMax | [
"def",
"getPhysicalMaximum",
"(",
"self",
",",
"chn",
"=",
"None",
")",
":",
"if",
"chn",
"is",
"not",
"None",
":",
"if",
"0",
"<=",
"chn",
"<",
"self",
".",
"signals_in_file",
":",
"return",
"self",
".",
"physical_max",
"(",
"chn",
")",
"else",
":",
"return",
"0",
"else",
":",
"physMax",
"=",
"np",
".",
"zeros",
"(",
"self",
".",
"signals_in_file",
")",
"for",
"i",
"in",
"np",
".",
"arange",
"(",
"self",
".",
"signals_in_file",
")",
":",
"physMax",
"[",
"i",
"]",
"=",
"self",
".",
"physical_max",
"(",
"i",
")",
"return",
"physMax"
] | Returns the maximum physical value of signal edfsignal.
Parameters
----------
chn : int
channel number
Examples
--------
>>> import pyedflib
>>> f = pyedflib.data.test_generator()
>>> f.getPhysicalMaximum(0)==1000.0
True
>>> f._close()
>>> del f | [
"Returns",
"the",
"maximum",
"physical",
"value",
"of",
"signal",
"edfsignal",
"."
] | 0f787fc1202b84a6f30d098296acf72666eaeeb4 | https://github.com/holgern/pyedflib/blob/0f787fc1202b84a6f30d098296acf72666eaeeb4/pyedflib/edfreader.py#L476-L504 | train | 233,889 |
holgern/pyedflib | pyedflib/edfreader.py | EdfReader.getPhysicalMinimum | def getPhysicalMinimum(self,chn=None):
"""
Returns the minimum physical value of signal edfsignal.
Parameters
----------
chn : int
channel number
Examples
--------
>>> import pyedflib
>>> f = pyedflib.data.test_generator()
>>> f.getPhysicalMinimum(0)==-1000.0
True
>>> f._close()
>>> del f
"""
if chn is not None:
if 0 <= chn < self.signals_in_file:
return self.physical_min(chn)
else:
return 0
else:
physMin = np.zeros(self.signals_in_file)
for i in np.arange(self.signals_in_file):
physMin[i] = self.physical_min(i)
return physMin | python | def getPhysicalMinimum(self,chn=None):
"""
Returns the minimum physical value of signal edfsignal.
Parameters
----------
chn : int
channel number
Examples
--------
>>> import pyedflib
>>> f = pyedflib.data.test_generator()
>>> f.getPhysicalMinimum(0)==-1000.0
True
>>> f._close()
>>> del f
"""
if chn is not None:
if 0 <= chn < self.signals_in_file:
return self.physical_min(chn)
else:
return 0
else:
physMin = np.zeros(self.signals_in_file)
for i in np.arange(self.signals_in_file):
physMin[i] = self.physical_min(i)
return physMin | [
"def",
"getPhysicalMinimum",
"(",
"self",
",",
"chn",
"=",
"None",
")",
":",
"if",
"chn",
"is",
"not",
"None",
":",
"if",
"0",
"<=",
"chn",
"<",
"self",
".",
"signals_in_file",
":",
"return",
"self",
".",
"physical_min",
"(",
"chn",
")",
"else",
":",
"return",
"0",
"else",
":",
"physMin",
"=",
"np",
".",
"zeros",
"(",
"self",
".",
"signals_in_file",
")",
"for",
"i",
"in",
"np",
".",
"arange",
"(",
"self",
".",
"signals_in_file",
")",
":",
"physMin",
"[",
"i",
"]",
"=",
"self",
".",
"physical_min",
"(",
"i",
")",
"return",
"physMin"
] | Returns the minimum physical value of signal edfsignal.
Parameters
----------
chn : int
channel number
Examples
--------
>>> import pyedflib
>>> f = pyedflib.data.test_generator()
>>> f.getPhysicalMinimum(0)==-1000.0
True
>>> f._close()
>>> del f | [
"Returns",
"the",
"minimum",
"physical",
"value",
"of",
"signal",
"edfsignal",
"."
] | 0f787fc1202b84a6f30d098296acf72666eaeeb4 | https://github.com/holgern/pyedflib/blob/0f787fc1202b84a6f30d098296acf72666eaeeb4/pyedflib/edfreader.py#L506-L534 | train | 233,890 |
holgern/pyedflib | pyedflib/edfreader.py | EdfReader.getDigitalMaximum | def getDigitalMaximum(self, chn=None):
"""
Returns the maximum digital value of signal edfsignal.
Parameters
----------
chn : int
channel number
Examples
--------
>>> import pyedflib
>>> f = pyedflib.data.test_generator()
>>> f.getDigitalMaximum(0)
32767
>>> f._close()
>>> del f
"""
if chn is not None:
if 0 <= chn < self.signals_in_file:
return self.digital_max(chn)
else:
return 0
else:
digMax = np.zeros(self.signals_in_file)
for i in np.arange(self.signals_in_file):
digMax[i] = self.digital_max(i)
return digMax | python | def getDigitalMaximum(self, chn=None):
"""
Returns the maximum digital value of signal edfsignal.
Parameters
----------
chn : int
channel number
Examples
--------
>>> import pyedflib
>>> f = pyedflib.data.test_generator()
>>> f.getDigitalMaximum(0)
32767
>>> f._close()
>>> del f
"""
if chn is not None:
if 0 <= chn < self.signals_in_file:
return self.digital_max(chn)
else:
return 0
else:
digMax = np.zeros(self.signals_in_file)
for i in np.arange(self.signals_in_file):
digMax[i] = self.digital_max(i)
return digMax | [
"def",
"getDigitalMaximum",
"(",
"self",
",",
"chn",
"=",
"None",
")",
":",
"if",
"chn",
"is",
"not",
"None",
":",
"if",
"0",
"<=",
"chn",
"<",
"self",
".",
"signals_in_file",
":",
"return",
"self",
".",
"digital_max",
"(",
"chn",
")",
"else",
":",
"return",
"0",
"else",
":",
"digMax",
"=",
"np",
".",
"zeros",
"(",
"self",
".",
"signals_in_file",
")",
"for",
"i",
"in",
"np",
".",
"arange",
"(",
"self",
".",
"signals_in_file",
")",
":",
"digMax",
"[",
"i",
"]",
"=",
"self",
".",
"digital_max",
"(",
"i",
")",
"return",
"digMax"
] | Returns the maximum digital value of signal edfsignal.
Parameters
----------
chn : int
channel number
Examples
--------
>>> import pyedflib
>>> f = pyedflib.data.test_generator()
>>> f.getDigitalMaximum(0)
32767
>>> f._close()
>>> del f | [
"Returns",
"the",
"maximum",
"digital",
"value",
"of",
"signal",
"edfsignal",
"."
] | 0f787fc1202b84a6f30d098296acf72666eaeeb4 | https://github.com/holgern/pyedflib/blob/0f787fc1202b84a6f30d098296acf72666eaeeb4/pyedflib/edfreader.py#L536-L564 | train | 233,891 |
holgern/pyedflib | pyedflib/edfreader.py | EdfReader.getDigitalMinimum | def getDigitalMinimum(self, chn=None):
"""
Returns the minimum digital value of signal edfsignal.
Parameters
----------
chn : int
channel number
Examples
--------
>>> import pyedflib
>>> f = pyedflib.data.test_generator()
>>> f.getDigitalMinimum(0)
-32768
>>> f._close()
>>> del f
"""
if chn is not None:
if 0 <= chn < self.signals_in_file:
return self.digital_min(chn)
else:
return 0
else:
digMin = np.zeros(self.signals_in_file)
for i in np.arange(self.signals_in_file):
digMin[i] = self.digital_min(i)
return digMin | python | def getDigitalMinimum(self, chn=None):
"""
Returns the minimum digital value of signal edfsignal.
Parameters
----------
chn : int
channel number
Examples
--------
>>> import pyedflib
>>> f = pyedflib.data.test_generator()
>>> f.getDigitalMinimum(0)
-32768
>>> f._close()
>>> del f
"""
if chn is not None:
if 0 <= chn < self.signals_in_file:
return self.digital_min(chn)
else:
return 0
else:
digMin = np.zeros(self.signals_in_file)
for i in np.arange(self.signals_in_file):
digMin[i] = self.digital_min(i)
return digMin | [
"def",
"getDigitalMinimum",
"(",
"self",
",",
"chn",
"=",
"None",
")",
":",
"if",
"chn",
"is",
"not",
"None",
":",
"if",
"0",
"<=",
"chn",
"<",
"self",
".",
"signals_in_file",
":",
"return",
"self",
".",
"digital_min",
"(",
"chn",
")",
"else",
":",
"return",
"0",
"else",
":",
"digMin",
"=",
"np",
".",
"zeros",
"(",
"self",
".",
"signals_in_file",
")",
"for",
"i",
"in",
"np",
".",
"arange",
"(",
"self",
".",
"signals_in_file",
")",
":",
"digMin",
"[",
"i",
"]",
"=",
"self",
".",
"digital_min",
"(",
"i",
")",
"return",
"digMin"
] | Returns the minimum digital value of signal edfsignal.
Parameters
----------
chn : int
channel number
Examples
--------
>>> import pyedflib
>>> f = pyedflib.data.test_generator()
>>> f.getDigitalMinimum(0)
-32768
>>> f._close()
>>> del f | [
"Returns",
"the",
"minimum",
"digital",
"value",
"of",
"signal",
"edfsignal",
"."
] | 0f787fc1202b84a6f30d098296acf72666eaeeb4 | https://github.com/holgern/pyedflib/blob/0f787fc1202b84a6f30d098296acf72666eaeeb4/pyedflib/edfreader.py#L566-L594 | train | 233,892 |
holgern/pyedflib | pyedflib/edfreader.py | EdfReader.readSignal | def readSignal(self, chn, start=0, n=None):
"""
Returns the physical data of signal chn. When start and n is set, a subset is returned
Parameters
----------
chn : int
channel number
start : int
start pointer (default is 0)
n : int
length of data to read (default is None, by which the complete data of the channel are returned)
Examples
--------
>>> import pyedflib
>>> f = pyedflib.data.test_generator()
>>> x = f.readSignal(0,0,1000)
>>> int(x.shape[0])
1000
>>> x2 = f.readSignal(0)
>>> int(x2.shape[0])
120000
>>> f._close()
>>> del f
"""
if start < 0:
return np.array([])
if n is not None and n < 0:
return np.array([])
nsamples = self.getNSamples()
if chn < len(nsamples):
if n is None:
n = nsamples[chn]
elif n > nsamples[chn]:
return np.array([])
x = np.zeros(n, dtype=np.float64)
self.readsignal(chn, start, n, x)
return x
else:
return np.array([]) | python | def readSignal(self, chn, start=0, n=None):
"""
Returns the physical data of signal chn. When start and n is set, a subset is returned
Parameters
----------
chn : int
channel number
start : int
start pointer (default is 0)
n : int
length of data to read (default is None, by which the complete data of the channel are returned)
Examples
--------
>>> import pyedflib
>>> f = pyedflib.data.test_generator()
>>> x = f.readSignal(0,0,1000)
>>> int(x.shape[0])
1000
>>> x2 = f.readSignal(0)
>>> int(x2.shape[0])
120000
>>> f._close()
>>> del f
"""
if start < 0:
return np.array([])
if n is not None and n < 0:
return np.array([])
nsamples = self.getNSamples()
if chn < len(nsamples):
if n is None:
n = nsamples[chn]
elif n > nsamples[chn]:
return np.array([])
x = np.zeros(n, dtype=np.float64)
self.readsignal(chn, start, n, x)
return x
else:
return np.array([]) | [
"def",
"readSignal",
"(",
"self",
",",
"chn",
",",
"start",
"=",
"0",
",",
"n",
"=",
"None",
")",
":",
"if",
"start",
"<",
"0",
":",
"return",
"np",
".",
"array",
"(",
"[",
"]",
")",
"if",
"n",
"is",
"not",
"None",
"and",
"n",
"<",
"0",
":",
"return",
"np",
".",
"array",
"(",
"[",
"]",
")",
"nsamples",
"=",
"self",
".",
"getNSamples",
"(",
")",
"if",
"chn",
"<",
"len",
"(",
"nsamples",
")",
":",
"if",
"n",
"is",
"None",
":",
"n",
"=",
"nsamples",
"[",
"chn",
"]",
"elif",
"n",
">",
"nsamples",
"[",
"chn",
"]",
":",
"return",
"np",
".",
"array",
"(",
"[",
"]",
")",
"x",
"=",
"np",
".",
"zeros",
"(",
"n",
",",
"dtype",
"=",
"np",
".",
"float64",
")",
"self",
".",
"readsignal",
"(",
"chn",
",",
"start",
",",
"n",
",",
"x",
")",
"return",
"x",
"else",
":",
"return",
"np",
".",
"array",
"(",
"[",
"]",
")"
] | Returns the physical data of signal chn. When start and n is set, a subset is returned
Parameters
----------
chn : int
channel number
start : int
start pointer (default is 0)
n : int
length of data to read (default is None, by which the complete data of the channel are returned)
Examples
--------
>>> import pyedflib
>>> f = pyedflib.data.test_generator()
>>> x = f.readSignal(0,0,1000)
>>> int(x.shape[0])
1000
>>> x2 = f.readSignal(0)
>>> int(x2.shape[0])
120000
>>> f._close()
>>> del f | [
"Returns",
"the",
"physical",
"data",
"of",
"signal",
"chn",
".",
"When",
"start",
"and",
"n",
"is",
"set",
"a",
"subset",
"is",
"returned"
] | 0f787fc1202b84a6f30d098296acf72666eaeeb4 | https://github.com/holgern/pyedflib/blob/0f787fc1202b84a6f30d098296acf72666eaeeb4/pyedflib/edfreader.py#L644-L685 | train | 233,893 |
holgern/pyedflib | demo/stacklineplot.py | stackplot | def stackplot(marray, seconds=None, start_time=None, ylabels=None):
"""
will plot a stack of traces one above the other assuming
marray.shape = numRows, numSamples
"""
tarray = np.transpose(marray)
stackplot_t(tarray, seconds=seconds, start_time=start_time, ylabels=ylabels)
plt.show() | python | def stackplot(marray, seconds=None, start_time=None, ylabels=None):
"""
will plot a stack of traces one above the other assuming
marray.shape = numRows, numSamples
"""
tarray = np.transpose(marray)
stackplot_t(tarray, seconds=seconds, start_time=start_time, ylabels=ylabels)
plt.show() | [
"def",
"stackplot",
"(",
"marray",
",",
"seconds",
"=",
"None",
",",
"start_time",
"=",
"None",
",",
"ylabels",
"=",
"None",
")",
":",
"tarray",
"=",
"np",
".",
"transpose",
"(",
"marray",
")",
"stackplot_t",
"(",
"tarray",
",",
"seconds",
"=",
"seconds",
",",
"start_time",
"=",
"start_time",
",",
"ylabels",
"=",
"ylabels",
")",
"plt",
".",
"show",
"(",
")"
] | will plot a stack of traces one above the other assuming
marray.shape = numRows, numSamples | [
"will",
"plot",
"a",
"stack",
"of",
"traces",
"one",
"above",
"the",
"other",
"assuming",
"marray",
".",
"shape",
"=",
"numRows",
"numSamples"
] | 0f787fc1202b84a6f30d098296acf72666eaeeb4 | https://github.com/holgern/pyedflib/blob/0f787fc1202b84a6f30d098296acf72666eaeeb4/demo/stacklineplot.py#L10-L17 | train | 233,894 |
holgern/pyedflib | demo/stacklineplot.py | stackplot_t | def stackplot_t(tarray, seconds=None, start_time=None, ylabels=None):
"""
will plot a stack of traces one above the other assuming
tarray.shape = numSamples, numRows
"""
data = tarray
numSamples, numRows = tarray.shape
# data = np.random.randn(numSamples,numRows) # test data
# data.shape = numSamples, numRows
if seconds:
t = seconds * np.arange(numSamples, dtype=float)/numSamples
# import pdb
# pdb.set_trace()
if start_time:
t = t+start_time
xlm = (start_time, start_time+seconds)
else:
xlm = (0,seconds)
else:
t = np.arange(numSamples, dtype=float)
xlm = (0,numSamples)
ticklocs = []
ax = plt.subplot(111)
plt.xlim(*xlm)
# xticks(np.linspace(xlm, 10))
dmin = data.min()
dmax = data.max()
dr = (dmax - dmin)*0.7 # Crowd them a bit.
y0 = dmin
y1 = (numRows-1) * dr + dmax
plt.ylim(y0, y1)
segs = []
for i in range(numRows):
segs.append(np.hstack((t[:,np.newaxis], data[:,i,np.newaxis])))
# print "segs[-1].shape:", segs[-1].shape
ticklocs.append(i*dr)
offsets = np.zeros((numRows,2), dtype=float)
offsets[:,1] = ticklocs
lines = LineCollection(segs, offsets=offsets,
transOffset=None,
)
ax.add_collection(lines)
# set the yticks to use axes coords on the y axis
ax.set_yticks(ticklocs)
# ax.set_yticklabels(['PG3', 'PG5', 'PG7', 'PG9'])
# if not plt.ylabels:
plt.ylabels = ["%d" % ii for ii in range(numRows)]
ax.set_yticklabels(ylabels)
plt.xlabel('time (s)') | python | def stackplot_t(tarray, seconds=None, start_time=None, ylabels=None):
"""
will plot a stack of traces one above the other assuming
tarray.shape = numSamples, numRows
"""
data = tarray
numSamples, numRows = tarray.shape
# data = np.random.randn(numSamples,numRows) # test data
# data.shape = numSamples, numRows
if seconds:
t = seconds * np.arange(numSamples, dtype=float)/numSamples
# import pdb
# pdb.set_trace()
if start_time:
t = t+start_time
xlm = (start_time, start_time+seconds)
else:
xlm = (0,seconds)
else:
t = np.arange(numSamples, dtype=float)
xlm = (0,numSamples)
ticklocs = []
ax = plt.subplot(111)
plt.xlim(*xlm)
# xticks(np.linspace(xlm, 10))
dmin = data.min()
dmax = data.max()
dr = (dmax - dmin)*0.7 # Crowd them a bit.
y0 = dmin
y1 = (numRows-1) * dr + dmax
plt.ylim(y0, y1)
segs = []
for i in range(numRows):
segs.append(np.hstack((t[:,np.newaxis], data[:,i,np.newaxis])))
# print "segs[-1].shape:", segs[-1].shape
ticklocs.append(i*dr)
offsets = np.zeros((numRows,2), dtype=float)
offsets[:,1] = ticklocs
lines = LineCollection(segs, offsets=offsets,
transOffset=None,
)
ax.add_collection(lines)
# set the yticks to use axes coords on the y axis
ax.set_yticks(ticklocs)
# ax.set_yticklabels(['PG3', 'PG5', 'PG7', 'PG9'])
# if not plt.ylabels:
plt.ylabels = ["%d" % ii for ii in range(numRows)]
ax.set_yticklabels(ylabels)
plt.xlabel('time (s)') | [
"def",
"stackplot_t",
"(",
"tarray",
",",
"seconds",
"=",
"None",
",",
"start_time",
"=",
"None",
",",
"ylabels",
"=",
"None",
")",
":",
"data",
"=",
"tarray",
"numSamples",
",",
"numRows",
"=",
"tarray",
".",
"shape",
"# data = np.random.randn(numSamples,numRows) # test data",
"# data.shape = numSamples, numRows",
"if",
"seconds",
":",
"t",
"=",
"seconds",
"*",
"np",
".",
"arange",
"(",
"numSamples",
",",
"dtype",
"=",
"float",
")",
"/",
"numSamples",
"# import pdb",
"# pdb.set_trace()",
"if",
"start_time",
":",
"t",
"=",
"t",
"+",
"start_time",
"xlm",
"=",
"(",
"start_time",
",",
"start_time",
"+",
"seconds",
")",
"else",
":",
"xlm",
"=",
"(",
"0",
",",
"seconds",
")",
"else",
":",
"t",
"=",
"np",
".",
"arange",
"(",
"numSamples",
",",
"dtype",
"=",
"float",
")",
"xlm",
"=",
"(",
"0",
",",
"numSamples",
")",
"ticklocs",
"=",
"[",
"]",
"ax",
"=",
"plt",
".",
"subplot",
"(",
"111",
")",
"plt",
".",
"xlim",
"(",
"*",
"xlm",
")",
"# xticks(np.linspace(xlm, 10))",
"dmin",
"=",
"data",
".",
"min",
"(",
")",
"dmax",
"=",
"data",
".",
"max",
"(",
")",
"dr",
"=",
"(",
"dmax",
"-",
"dmin",
")",
"*",
"0.7",
"# Crowd them a bit.",
"y0",
"=",
"dmin",
"y1",
"=",
"(",
"numRows",
"-",
"1",
")",
"*",
"dr",
"+",
"dmax",
"plt",
".",
"ylim",
"(",
"y0",
",",
"y1",
")",
"segs",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"numRows",
")",
":",
"segs",
".",
"append",
"(",
"np",
".",
"hstack",
"(",
"(",
"t",
"[",
":",
",",
"np",
".",
"newaxis",
"]",
",",
"data",
"[",
":",
",",
"i",
",",
"np",
".",
"newaxis",
"]",
")",
")",
")",
"# print \"segs[-1].shape:\", segs[-1].shape",
"ticklocs",
".",
"append",
"(",
"i",
"*",
"dr",
")",
"offsets",
"=",
"np",
".",
"zeros",
"(",
"(",
"numRows",
",",
"2",
")",
",",
"dtype",
"=",
"float",
")",
"offsets",
"[",
":",
",",
"1",
"]",
"=",
"ticklocs",
"lines",
"=",
"LineCollection",
"(",
"segs",
",",
"offsets",
"=",
"offsets",
",",
"transOffset",
"=",
"None",
",",
")",
"ax",
".",
"add_collection",
"(",
"lines",
")",
"# set the yticks to use axes coords on the y axis",
"ax",
".",
"set_yticks",
"(",
"ticklocs",
")",
"# ax.set_yticklabels(['PG3', 'PG5', 'PG7', 'PG9'])",
"# if not plt.ylabels:",
"plt",
".",
"ylabels",
"=",
"[",
"\"%d\"",
"%",
"ii",
"for",
"ii",
"in",
"range",
"(",
"numRows",
")",
"]",
"ax",
".",
"set_yticklabels",
"(",
"ylabels",
")",
"plt",
".",
"xlabel",
"(",
"'time (s)'",
")"
] | will plot a stack of traces one above the other assuming
tarray.shape = numSamples, numRows | [
"will",
"plot",
"a",
"stack",
"of",
"traces",
"one",
"above",
"the",
"other",
"assuming",
"tarray",
".",
"shape",
"=",
"numSamples",
"numRows"
] | 0f787fc1202b84a6f30d098296acf72666eaeeb4 | https://github.com/holgern/pyedflib/blob/0f787fc1202b84a6f30d098296acf72666eaeeb4/demo/stacklineplot.py#L20-L76 | train | 233,895 |
jrialland/python-astar | src/astar/__init__.py | find_path | def find_path(start, goal, neighbors_fnct, reversePath=False, heuristic_cost_estimate_fnct=lambda a, b: Infinite, distance_between_fnct=lambda a, b: 1.0, is_goal_reached_fnct=lambda a, b: a == b):
"""A non-class version of the path finding algorithm"""
class FindPath(AStar):
def heuristic_cost_estimate(self, current, goal):
return heuristic_cost_estimate_fnct(current, goal)
def distance_between(self, n1, n2):
return distance_between_fnct(n1, n2)
def neighbors(self, node):
return neighbors_fnct(node)
def is_goal_reached(self, current, goal):
return is_goal_reached_fnct(current, goal)
return FindPath().astar(start, goal, reversePath) | python | def find_path(start, goal, neighbors_fnct, reversePath=False, heuristic_cost_estimate_fnct=lambda a, b: Infinite, distance_between_fnct=lambda a, b: 1.0, is_goal_reached_fnct=lambda a, b: a == b):
"""A non-class version of the path finding algorithm"""
class FindPath(AStar):
def heuristic_cost_estimate(self, current, goal):
return heuristic_cost_estimate_fnct(current, goal)
def distance_between(self, n1, n2):
return distance_between_fnct(n1, n2)
def neighbors(self, node):
return neighbors_fnct(node)
def is_goal_reached(self, current, goal):
return is_goal_reached_fnct(current, goal)
return FindPath().astar(start, goal, reversePath) | [
"def",
"find_path",
"(",
"start",
",",
"goal",
",",
"neighbors_fnct",
",",
"reversePath",
"=",
"False",
",",
"heuristic_cost_estimate_fnct",
"=",
"lambda",
"a",
",",
"b",
":",
"Infinite",
",",
"distance_between_fnct",
"=",
"lambda",
"a",
",",
"b",
":",
"1.0",
",",
"is_goal_reached_fnct",
"=",
"lambda",
"a",
",",
"b",
":",
"a",
"==",
"b",
")",
":",
"class",
"FindPath",
"(",
"AStar",
")",
":",
"def",
"heuristic_cost_estimate",
"(",
"self",
",",
"current",
",",
"goal",
")",
":",
"return",
"heuristic_cost_estimate_fnct",
"(",
"current",
",",
"goal",
")",
"def",
"distance_between",
"(",
"self",
",",
"n1",
",",
"n2",
")",
":",
"return",
"distance_between_fnct",
"(",
"n1",
",",
"n2",
")",
"def",
"neighbors",
"(",
"self",
",",
"node",
")",
":",
"return",
"neighbors_fnct",
"(",
"node",
")",
"def",
"is_goal_reached",
"(",
"self",
",",
"current",
",",
"goal",
")",
":",
"return",
"is_goal_reached_fnct",
"(",
"current",
",",
"goal",
")",
"return",
"FindPath",
"(",
")",
".",
"astar",
"(",
"start",
",",
"goal",
",",
"reversePath",
")"
] | A non-class version of the path finding algorithm | [
"A",
"non",
"-",
"class",
"version",
"of",
"the",
"path",
"finding",
"algorithm"
] | 7a3f5b33bedd03bd09792fe0d5b6fe28d50f9514 | https://github.com/jrialland/python-astar/blob/7a3f5b33bedd03bd09792fe0d5b6fe28d50f9514/src/astar/__init__.py#L109-L124 | train | 233,896 |
frictionlessdata/goodtables-py | goodtables/validate.py | validate | def validate(source, **options):
"""Validates a source file and returns a report.
Args:
source (Union[str, Dict, List[Dict], IO]): The source to be validated.
It can be a local file path, URL, dict, list of dicts, or a
file-like object. If it's a list of dicts and the `preset` is
"nested", each of the dict key's will be used as if it was passed
as a keyword argument to this method.
The file can be a CSV, XLS, JSON, and any other format supported by
`tabulator`_.
Keyword Args:
checks (List[str]): List of checks names to be enabled. They can be
individual check names (e.g. `blank-headers`), or check types (e.g.
`structure`).
skip_checks (List[str]): List of checks names to be skipped. They can
be individual check names (e.g. `blank-headers`), or check types
(e.g. `structure`).
infer_schema (bool): Infer schema if one wasn't passed as an argument.
infer_fields (bool): Infer schema for columns not present in the received schema.
order_fields (bool): Order source columns based on schema fields order.
This is useful when you don't want to validate that the data
columns' order is the same as the schema's.
error_limit (int): Stop validation if the number of errors per table
exceeds this value.
table_limit (int): Maximum number of tables to validate.
row_limit (int): Maximum number of rows to validate.
preset (str): Dataset type could be `table` (default), `datapackage`,
`nested` or custom. Usually, the preset can be inferred from the
source, so you don't need to define it.
Any (Any): Any additional arguments not defined here will be passed on,
depending on the chosen `preset`. If the `preset` is `table`, the
extra arguments will be passed on to `tabulator`_, if it is
`datapackage`, they will be passed on to the `datapackage`_
constructor.
# Table preset
schema (Union[str, Dict, IO]): The Table Schema for the
source.
headers (Union[int, List[str]): Either the row number that contains
the headers, or a list with them. If the row number is given, ?????
scheme (str): The scheme used to access the source (e.g. `file`,
`http`). This is usually inferred correctly from the source. See
the `tabulator`_ documentation for the list of supported schemes.
format (str): Format of the source data (`csv`, `datapackage`, ...).
This is usually inferred correctly from the source. See the
the `tabulator`_ documentation for the list of supported formats.
encoding (str): Encoding of the source.
skip_rows (Union[int, List[Union[int, str]]]): Row numbers or a
string. Rows beginning with the string will be ignored (e.g. '#',
'//').
Raises:
GoodtablesException: Raised on any non-tabular error.
Returns:
dict: The validation report.
.. _tabulator:
https://github.com/frictionlessdata/tabulator-py
.. _tabulator_schemes:
https://github.com/frictionlessdata/tabulator-py
.. _tabulator:
https://github.com/frictionlessdata/datapackage-py
"""
source, options, inspector_settings = _parse_arguments(source, **options)
# Validate
inspector = Inspector(**inspector_settings)
report = inspector.inspect(source, **options)
return report | python | def validate(source, **options):
"""Validates a source file and returns a report.
Args:
source (Union[str, Dict, List[Dict], IO]): The source to be validated.
It can be a local file path, URL, dict, list of dicts, or a
file-like object. If it's a list of dicts and the `preset` is
"nested", each of the dict key's will be used as if it was passed
as a keyword argument to this method.
The file can be a CSV, XLS, JSON, and any other format supported by
`tabulator`_.
Keyword Args:
checks (List[str]): List of checks names to be enabled. They can be
individual check names (e.g. `blank-headers`), or check types (e.g.
`structure`).
skip_checks (List[str]): List of checks names to be skipped. They can
be individual check names (e.g. `blank-headers`), or check types
(e.g. `structure`).
infer_schema (bool): Infer schema if one wasn't passed as an argument.
infer_fields (bool): Infer schema for columns not present in the received schema.
order_fields (bool): Order source columns based on schema fields order.
This is useful when you don't want to validate that the data
columns' order is the same as the schema's.
error_limit (int): Stop validation if the number of errors per table
exceeds this value.
table_limit (int): Maximum number of tables to validate.
row_limit (int): Maximum number of rows to validate.
preset (str): Dataset type could be `table` (default), `datapackage`,
`nested` or custom. Usually, the preset can be inferred from the
source, so you don't need to define it.
Any (Any): Any additional arguments not defined here will be passed on,
depending on the chosen `preset`. If the `preset` is `table`, the
extra arguments will be passed on to `tabulator`_, if it is
`datapackage`, they will be passed on to the `datapackage`_
constructor.
# Table preset
schema (Union[str, Dict, IO]): The Table Schema for the
source.
headers (Union[int, List[str]): Either the row number that contains
the headers, or a list with them. If the row number is given, ?????
scheme (str): The scheme used to access the source (e.g. `file`,
`http`). This is usually inferred correctly from the source. See
the `tabulator`_ documentation for the list of supported schemes.
format (str): Format of the source data (`csv`, `datapackage`, ...).
This is usually inferred correctly from the source. See the
the `tabulator`_ documentation for the list of supported formats.
encoding (str): Encoding of the source.
skip_rows (Union[int, List[Union[int, str]]]): Row numbers or a
string. Rows beginning with the string will be ignored (e.g. '#',
'//').
Raises:
GoodtablesException: Raised on any non-tabular error.
Returns:
dict: The validation report.
.. _tabulator:
https://github.com/frictionlessdata/tabulator-py
.. _tabulator_schemes:
https://github.com/frictionlessdata/tabulator-py
.. _tabulator:
https://github.com/frictionlessdata/datapackage-py
"""
source, options, inspector_settings = _parse_arguments(source, **options)
# Validate
inspector = Inspector(**inspector_settings)
report = inspector.inspect(source, **options)
return report | [
"def",
"validate",
"(",
"source",
",",
"*",
"*",
"options",
")",
":",
"source",
",",
"options",
",",
"inspector_settings",
"=",
"_parse_arguments",
"(",
"source",
",",
"*",
"*",
"options",
")",
"# Validate",
"inspector",
"=",
"Inspector",
"(",
"*",
"*",
"inspector_settings",
")",
"report",
"=",
"inspector",
".",
"inspect",
"(",
"source",
",",
"*",
"*",
"options",
")",
"return",
"report"
] | Validates a source file and returns a report.
Args:
source (Union[str, Dict, List[Dict], IO]): The source to be validated.
It can be a local file path, URL, dict, list of dicts, or a
file-like object. If it's a list of dicts and the `preset` is
"nested", each of the dict key's will be used as if it was passed
as a keyword argument to this method.
The file can be a CSV, XLS, JSON, and any other format supported by
`tabulator`_.
Keyword Args:
checks (List[str]): List of checks names to be enabled. They can be
individual check names (e.g. `blank-headers`), or check types (e.g.
`structure`).
skip_checks (List[str]): List of checks names to be skipped. They can
be individual check names (e.g. `blank-headers`), or check types
(e.g. `structure`).
infer_schema (bool): Infer schema if one wasn't passed as an argument.
infer_fields (bool): Infer schema for columns not present in the received schema.
order_fields (bool): Order source columns based on schema fields order.
This is useful when you don't want to validate that the data
columns' order is the same as the schema's.
error_limit (int): Stop validation if the number of errors per table
exceeds this value.
table_limit (int): Maximum number of tables to validate.
row_limit (int): Maximum number of rows to validate.
preset (str): Dataset type could be `table` (default), `datapackage`,
`nested` or custom. Usually, the preset can be inferred from the
source, so you don't need to define it.
Any (Any): Any additional arguments not defined here will be passed on,
depending on the chosen `preset`. If the `preset` is `table`, the
extra arguments will be passed on to `tabulator`_, if it is
`datapackage`, they will be passed on to the `datapackage`_
constructor.
# Table preset
schema (Union[str, Dict, IO]): The Table Schema for the
source.
headers (Union[int, List[str]): Either the row number that contains
the headers, or a list with them. If the row number is given, ?????
scheme (str): The scheme used to access the source (e.g. `file`,
`http`). This is usually inferred correctly from the source. See
the `tabulator`_ documentation for the list of supported schemes.
format (str): Format of the source data (`csv`, `datapackage`, ...).
This is usually inferred correctly from the source. See the
the `tabulator`_ documentation for the list of supported formats.
encoding (str): Encoding of the source.
skip_rows (Union[int, List[Union[int, str]]]): Row numbers or a
string. Rows beginning with the string will be ignored (e.g. '#',
'//').
Raises:
GoodtablesException: Raised on any non-tabular error.
Returns:
dict: The validation report.
.. _tabulator:
https://github.com/frictionlessdata/tabulator-py
.. _tabulator_schemes:
https://github.com/frictionlessdata/tabulator-py
.. _tabulator:
https://github.com/frictionlessdata/datapackage-py | [
"Validates",
"a",
"source",
"file",
"and",
"returns",
"a",
"report",
"."
] | 3e7d6891d2f4e342dfafbe0e951e204ccc252a44 | https://github.com/frictionlessdata/goodtables-py/blob/3e7d6891d2f4e342dfafbe0e951e204ccc252a44/goodtables/validate.py#L13-L87 | train | 233,897 |
frictionlessdata/goodtables-py | goodtables/validate.py | init_datapackage | def init_datapackage(resource_paths):
"""Create tabular data package with resources.
It will also infer the tabular resources' schemas.
Args:
resource_paths (List[str]): Paths to the data package resources.
Returns:
datapackage.Package: The data package.
"""
dp = datapackage.Package({
'name': 'change-me',
'schema': 'tabular-data-package',
})
for path in resource_paths:
dp.infer(path)
return dp | python | def init_datapackage(resource_paths):
"""Create tabular data package with resources.
It will also infer the tabular resources' schemas.
Args:
resource_paths (List[str]): Paths to the data package resources.
Returns:
datapackage.Package: The data package.
"""
dp = datapackage.Package({
'name': 'change-me',
'schema': 'tabular-data-package',
})
for path in resource_paths:
dp.infer(path)
return dp | [
"def",
"init_datapackage",
"(",
"resource_paths",
")",
":",
"dp",
"=",
"datapackage",
".",
"Package",
"(",
"{",
"'name'",
":",
"'change-me'",
",",
"'schema'",
":",
"'tabular-data-package'",
",",
"}",
")",
"for",
"path",
"in",
"resource_paths",
":",
"dp",
".",
"infer",
"(",
"path",
")",
"return",
"dp"
] | Create tabular data package with resources.
It will also infer the tabular resources' schemas.
Args:
resource_paths (List[str]): Paths to the data package resources.
Returns:
datapackage.Package: The data package. | [
"Create",
"tabular",
"data",
"package",
"with",
"resources",
"."
] | 3e7d6891d2f4e342dfafbe0e951e204ccc252a44 | https://github.com/frictionlessdata/goodtables-py/blob/3e7d6891d2f4e342dfafbe0e951e204ccc252a44/goodtables/validate.py#L90-L109 | train | 233,898 |
frictionlessdata/goodtables-py | goodtables/cli.py | init | def init(paths, output, **kwargs):
"""Init data package from list of files.
It will also infer tabular data's schemas from their contents.
"""
dp = goodtables.init_datapackage(paths)
click.secho(
json_module.dumps(dp.descriptor, indent=4),
file=output
)
exit(dp.valid) | python | def init(paths, output, **kwargs):
"""Init data package from list of files.
It will also infer tabular data's schemas from their contents.
"""
dp = goodtables.init_datapackage(paths)
click.secho(
json_module.dumps(dp.descriptor, indent=4),
file=output
)
exit(dp.valid) | [
"def",
"init",
"(",
"paths",
",",
"output",
",",
"*",
"*",
"kwargs",
")",
":",
"dp",
"=",
"goodtables",
".",
"init_datapackage",
"(",
"paths",
")",
"click",
".",
"secho",
"(",
"json_module",
".",
"dumps",
"(",
"dp",
".",
"descriptor",
",",
"indent",
"=",
"4",
")",
",",
"file",
"=",
"output",
")",
"exit",
"(",
"dp",
".",
"valid",
")"
] | Init data package from list of files.
It will also infer tabular data's schemas from their contents. | [
"Init",
"data",
"package",
"from",
"list",
"of",
"files",
"."
] | 3e7d6891d2f4e342dfafbe0e951e204ccc252a44 | https://github.com/frictionlessdata/goodtables-py/blob/3e7d6891d2f4e342dfafbe0e951e204ccc252a44/goodtables/cli.py#L121-L133 | train | 233,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.