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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
abseil/abseil-py | absl/flags/_validators.py | mark_flags_as_mutual_exclusive | def mark_flags_as_mutual_exclusive(flag_names, required=False,
flag_values=_flagvalues.FLAGS):
"""Ensures that only one flag among flag_names is not None.
Important note: This validator checks if flag values are None, and it does not
distinguish between default and explicit values. Therefore, this validator
does not make sense when applied to flags with default values other than None,
including other false values (e.g. False, 0, '', []). That includes multi
flags with a default value of [] instead of None.
Args:
flag_names: [str], names of the flags.
required: bool. If true, exactly one of the flags must have a value other
than None. Otherwise, at most one of the flags can have a value other
than None, and it is valid for all of the flags to be None.
flag_values: flags.FlagValues, optional FlagValues instance where the flags
are defined.
"""
for flag_name in flag_names:
if flag_values[flag_name].default is not None:
warnings.warn(
'Flag --{} has a non-None default value. That does not make sense '
'with mark_flags_as_mutual_exclusive, which checks whether the '
'listed flags have a value other than None.'.format(flag_name))
def validate_mutual_exclusion(flags_dict):
flag_count = sum(1 for val in flags_dict.values() if val is not None)
if flag_count == 1 or (not required and flag_count == 0):
return True
raise _exceptions.ValidationError(
'{} one of ({}) must have a value other than None.'.format(
'Exactly' if required else 'At most', ', '.join(flag_names)))
register_multi_flags_validator(
flag_names, validate_mutual_exclusion, flag_values=flag_values) | python | def mark_flags_as_mutual_exclusive(flag_names, required=False,
flag_values=_flagvalues.FLAGS):
"""Ensures that only one flag among flag_names is not None.
Important note: This validator checks if flag values are None, and it does not
distinguish between default and explicit values. Therefore, this validator
does not make sense when applied to flags with default values other than None,
including other false values (e.g. False, 0, '', []). That includes multi
flags with a default value of [] instead of None.
Args:
flag_names: [str], names of the flags.
required: bool. If true, exactly one of the flags must have a value other
than None. Otherwise, at most one of the flags can have a value other
than None, and it is valid for all of the flags to be None.
flag_values: flags.FlagValues, optional FlagValues instance where the flags
are defined.
"""
for flag_name in flag_names:
if flag_values[flag_name].default is not None:
warnings.warn(
'Flag --{} has a non-None default value. That does not make sense '
'with mark_flags_as_mutual_exclusive, which checks whether the '
'listed flags have a value other than None.'.format(flag_name))
def validate_mutual_exclusion(flags_dict):
flag_count = sum(1 for val in flags_dict.values() if val is not None)
if flag_count == 1 or (not required and flag_count == 0):
return True
raise _exceptions.ValidationError(
'{} one of ({}) must have a value other than None.'.format(
'Exactly' if required else 'At most', ', '.join(flag_names)))
register_multi_flags_validator(
flag_names, validate_mutual_exclusion, flag_values=flag_values) | [
"def",
"mark_flags_as_mutual_exclusive",
"(",
"flag_names",
",",
"required",
"=",
"False",
",",
"flag_values",
"=",
"_flagvalues",
".",
"FLAGS",
")",
":",
"for",
"flag_name",
"in",
"flag_names",
":",
"if",
"flag_values",
"[",
"flag_name",
"]",
".",
"default",
... | Ensures that only one flag among flag_names is not None.
Important note: This validator checks if flag values are None, and it does not
distinguish between default and explicit values. Therefore, this validator
does not make sense when applied to flags with default values other than None,
including other false values (e.g. False, 0, '', []). That includes multi
flags with a default value of [] instead of None.
Args:
flag_names: [str], names of the flags.
required: bool. If true, exactly one of the flags must have a value other
than None. Otherwise, at most one of the flags can have a value other
than None, and it is valid for all of the flags to be None.
flag_values: flags.FlagValues, optional FlagValues instance where the flags
are defined. | [
"Ensures",
"that",
"only",
"one",
"flag",
"among",
"flag_names",
"is",
"not",
"None",
"."
] | 9d73fdaa23a6b6726aa5731390f388c0c6250ee5 | https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/flags/_validators.py#L387-L421 | train | 215,300 |
abseil/abseil-py | absl/flags/_validators.py | mark_bool_flags_as_mutual_exclusive | def mark_bool_flags_as_mutual_exclusive(flag_names, required=False,
flag_values=_flagvalues.FLAGS):
"""Ensures that only one flag among flag_names is True.
Args:
flag_names: [str], names of the flags.
required: bool. If true, exactly one flag must be True. Otherwise, at most
one flag can be True, and it is valid for all flags to be False.
flag_values: flags.FlagValues, optional FlagValues instance where the flags
are defined.
"""
for flag_name in flag_names:
if not flag_values[flag_name].boolean:
raise _exceptions.ValidationError(
'Flag --{} is not Boolean, which is required for flags used in '
'mark_bool_flags_as_mutual_exclusive.'.format(flag_name))
def validate_boolean_mutual_exclusion(flags_dict):
flag_count = sum(bool(val) for val in flags_dict.values())
if flag_count == 1 or (not required and flag_count == 0):
return True
raise _exceptions.ValidationError(
'{} one of ({}) must be True.'.format(
'Exactly' if required else 'At most', ', '.join(flag_names)))
register_multi_flags_validator(
flag_names, validate_boolean_mutual_exclusion, flag_values=flag_values) | python | def mark_bool_flags_as_mutual_exclusive(flag_names, required=False,
flag_values=_flagvalues.FLAGS):
"""Ensures that only one flag among flag_names is True.
Args:
flag_names: [str], names of the flags.
required: bool. If true, exactly one flag must be True. Otherwise, at most
one flag can be True, and it is valid for all flags to be False.
flag_values: flags.FlagValues, optional FlagValues instance where the flags
are defined.
"""
for flag_name in flag_names:
if not flag_values[flag_name].boolean:
raise _exceptions.ValidationError(
'Flag --{} is not Boolean, which is required for flags used in '
'mark_bool_flags_as_mutual_exclusive.'.format(flag_name))
def validate_boolean_mutual_exclusion(flags_dict):
flag_count = sum(bool(val) for val in flags_dict.values())
if flag_count == 1 or (not required and flag_count == 0):
return True
raise _exceptions.ValidationError(
'{} one of ({}) must be True.'.format(
'Exactly' if required else 'At most', ', '.join(flag_names)))
register_multi_flags_validator(
flag_names, validate_boolean_mutual_exclusion, flag_values=flag_values) | [
"def",
"mark_bool_flags_as_mutual_exclusive",
"(",
"flag_names",
",",
"required",
"=",
"False",
",",
"flag_values",
"=",
"_flagvalues",
".",
"FLAGS",
")",
":",
"for",
"flag_name",
"in",
"flag_names",
":",
"if",
"not",
"flag_values",
"[",
"flag_name",
"]",
".",
... | Ensures that only one flag among flag_names is True.
Args:
flag_names: [str], names of the flags.
required: bool. If true, exactly one flag must be True. Otherwise, at most
one flag can be True, and it is valid for all flags to be False.
flag_values: flags.FlagValues, optional FlagValues instance where the flags
are defined. | [
"Ensures",
"that",
"only",
"one",
"flag",
"among",
"flag_names",
"is",
"True",
"."
] | 9d73fdaa23a6b6726aa5731390f388c0c6250ee5 | https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/flags/_validators.py#L424-L450 | train | 215,301 |
abseil/abseil-py | absl/flags/_validators.py | _add_validator | def _add_validator(fv, validator_instance):
"""Register new flags validator to be checked.
Args:
fv: flags.FlagValues, the FlagValues instance to add the validator.
validator_instance: validators.Validator, the validator to add.
Raises:
KeyError: Raised when validators work with a non-existing flag.
"""
for flag_name in validator_instance.get_flags_names():
fv[flag_name].validators.append(validator_instance) | python | def _add_validator(fv, validator_instance):
"""Register new flags validator to be checked.
Args:
fv: flags.FlagValues, the FlagValues instance to add the validator.
validator_instance: validators.Validator, the validator to add.
Raises:
KeyError: Raised when validators work with a non-existing flag.
"""
for flag_name in validator_instance.get_flags_names():
fv[flag_name].validators.append(validator_instance) | [
"def",
"_add_validator",
"(",
"fv",
",",
"validator_instance",
")",
":",
"for",
"flag_name",
"in",
"validator_instance",
".",
"get_flags_names",
"(",
")",
":",
"fv",
"[",
"flag_name",
"]",
".",
"validators",
".",
"append",
"(",
"validator_instance",
")"
] | Register new flags validator to be checked.
Args:
fv: flags.FlagValues, the FlagValues instance to add the validator.
validator_instance: validators.Validator, the validator to add.
Raises:
KeyError: Raised when validators work with a non-existing flag. | [
"Register",
"new",
"flags",
"validator",
"to",
"be",
"checked",
"."
] | 9d73fdaa23a6b6726aa5731390f388c0c6250ee5 | https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/flags/_validators.py#L453-L463 | train | 215,302 |
abseil/abseil-py | absl/flags/_validators.py | Validator.verify | def verify(self, flag_values):
"""Verifies that constraint is satisfied.
flags library calls this method to verify Validator's constraint.
Args:
flag_values: flags.FlagValues, the FlagValues instance to get flags from.
Raises:
Error: Raised if constraint is not satisfied.
"""
param = self._get_input_to_checker_function(flag_values)
if not self.checker(param):
raise _exceptions.ValidationError(self.message) | python | def verify(self, flag_values):
"""Verifies that constraint is satisfied.
flags library calls this method to verify Validator's constraint.
Args:
flag_values: flags.FlagValues, the FlagValues instance to get flags from.
Raises:
Error: Raised if constraint is not satisfied.
"""
param = self._get_input_to_checker_function(flag_values)
if not self.checker(param):
raise _exceptions.ValidationError(self.message) | [
"def",
"verify",
"(",
"self",
",",
"flag_values",
")",
":",
"param",
"=",
"self",
".",
"_get_input_to_checker_function",
"(",
"flag_values",
")",
"if",
"not",
"self",
".",
"checker",
"(",
"param",
")",
":",
"raise",
"_exceptions",
".",
"ValidationError",
"("... | Verifies that constraint is satisfied.
flags library calls this method to verify Validator's constraint.
Args:
flag_values: flags.FlagValues, the FlagValues instance to get flags from.
Raises:
Error: Raised if constraint is not satisfied. | [
"Verifies",
"that",
"constraint",
"is",
"satisfied",
"."
] | 9d73fdaa23a6b6726aa5731390f388c0c6250ee5 | https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/flags/_validators.py#L70-L82 | train | 215,303 |
abseil/abseil-py | absl/flags/_validators.py | MultiFlagsValidator._get_input_to_checker_function | def _get_input_to_checker_function(self, flag_values):
"""Given flag values, returns the input to be given to checker.
Args:
flag_values: flags.FlagValues, the FlagValues instance to get flags from.
Returns:
dict, with keys() being self.lag_names, and value for each key
being the value of the corresponding flag (string, boolean, etc).
"""
return dict([key, flag_values[key].value] for key in self.flag_names) | python | def _get_input_to_checker_function(self, flag_values):
"""Given flag values, returns the input to be given to checker.
Args:
flag_values: flags.FlagValues, the FlagValues instance to get flags from.
Returns:
dict, with keys() being self.lag_names, and value for each key
being the value of the corresponding flag (string, boolean, etc).
"""
return dict([key, flag_values[key].value] for key in self.flag_names) | [
"def",
"_get_input_to_checker_function",
"(",
"self",
",",
"flag_values",
")",
":",
"return",
"dict",
"(",
"[",
"key",
",",
"flag_values",
"[",
"key",
"]",
".",
"value",
"]",
"for",
"key",
"in",
"self",
".",
"flag_names",
")"
] | Given flag values, returns the input to be given to checker.
Args:
flag_values: flags.FlagValues, the FlagValues instance to get flags from.
Returns:
dict, with keys() being self.lag_names, and value for each key
being the value of the corresponding flag (string, boolean, etc). | [
"Given",
"flag",
"values",
"returns",
"the",
"input",
"to",
"be",
"given",
"to",
"checker",
"."
] | 9d73fdaa23a6b6726aa5731390f388c0c6250ee5 | https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/flags/_validators.py#L174-L183 | train | 215,304 |
abseil/abseil-py | absl/flags/_exceptions.py | DuplicateFlagError.from_flag | def from_flag(cls, flagname, flag_values, other_flag_values=None):
"""Creates a DuplicateFlagError by providing flag name and values.
Args:
flagname: str, the name of the flag being redefined.
flag_values: FlagValues, the FlagValues instance containing the first
definition of flagname.
other_flag_values: FlagValues, if it is not None, it should be the
FlagValues object where the second definition of flagname occurs.
If it is None, we assume that we're being called when attempting
to create the flag a second time, and we use the module calling
this one as the source of the second definition.
Returns:
An instance of DuplicateFlagError.
"""
first_module = flag_values.find_module_defining_flag(
flagname, default='<unknown>')
if other_flag_values is None:
second_module = _helpers.get_calling_module()
else:
second_module = other_flag_values.find_module_defining_flag(
flagname, default='<unknown>')
flag_summary = flag_values[flagname].help
msg = ("The flag '%s' is defined twice. First from %s, Second from %s. "
"Description from first occurrence: %s") % (
flagname, first_module, second_module, flag_summary)
return cls(msg) | python | def from_flag(cls, flagname, flag_values, other_flag_values=None):
"""Creates a DuplicateFlagError by providing flag name and values.
Args:
flagname: str, the name of the flag being redefined.
flag_values: FlagValues, the FlagValues instance containing the first
definition of flagname.
other_flag_values: FlagValues, if it is not None, it should be the
FlagValues object where the second definition of flagname occurs.
If it is None, we assume that we're being called when attempting
to create the flag a second time, and we use the module calling
this one as the source of the second definition.
Returns:
An instance of DuplicateFlagError.
"""
first_module = flag_values.find_module_defining_flag(
flagname, default='<unknown>')
if other_flag_values is None:
second_module = _helpers.get_calling_module()
else:
second_module = other_flag_values.find_module_defining_flag(
flagname, default='<unknown>')
flag_summary = flag_values[flagname].help
msg = ("The flag '%s' is defined twice. First from %s, Second from %s. "
"Description from first occurrence: %s") % (
flagname, first_module, second_module, flag_summary)
return cls(msg) | [
"def",
"from_flag",
"(",
"cls",
",",
"flagname",
",",
"flag_values",
",",
"other_flag_values",
"=",
"None",
")",
":",
"first_module",
"=",
"flag_values",
".",
"find_module_defining_flag",
"(",
"flagname",
",",
"default",
"=",
"'<unknown>'",
")",
"if",
"other_fla... | Creates a DuplicateFlagError by providing flag name and values.
Args:
flagname: str, the name of the flag being redefined.
flag_values: FlagValues, the FlagValues instance containing the first
definition of flagname.
other_flag_values: FlagValues, if it is not None, it should be the
FlagValues object where the second definition of flagname occurs.
If it is None, we assume that we're being called when attempting
to create the flag a second time, and we use the module calling
this one as the source of the second definition.
Returns:
An instance of DuplicateFlagError. | [
"Creates",
"a",
"DuplicateFlagError",
"by",
"providing",
"flag",
"name",
"and",
"values",
"."
] | 9d73fdaa23a6b6726aa5731390f388c0c6250ee5 | https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/flags/_exceptions.py#L48-L75 | train | 215,305 |
abseil/abseil-py | absl/logging/__init__.py | set_verbosity | def set_verbosity(v):
"""Sets the logging verbosity.
Causes all messages of level <= v to be logged,
and all messages of level > v to be silently discarded.
Args:
v: int|str, the verbosity level as an integer or string. Legal string values
are those that can be coerced to an integer as well as case-insensitive
'debug', 'info', 'warning', 'error', and 'fatal'.
"""
try:
new_level = int(v)
except ValueError:
new_level = converter.ABSL_NAMES[v.upper()]
FLAGS.verbosity = new_level | python | def set_verbosity(v):
"""Sets the logging verbosity.
Causes all messages of level <= v to be logged,
and all messages of level > v to be silently discarded.
Args:
v: int|str, the verbosity level as an integer or string. Legal string values
are those that can be coerced to an integer as well as case-insensitive
'debug', 'info', 'warning', 'error', and 'fatal'.
"""
try:
new_level = int(v)
except ValueError:
new_level = converter.ABSL_NAMES[v.upper()]
FLAGS.verbosity = new_level | [
"def",
"set_verbosity",
"(",
"v",
")",
":",
"try",
":",
"new_level",
"=",
"int",
"(",
"v",
")",
"except",
"ValueError",
":",
"new_level",
"=",
"converter",
".",
"ABSL_NAMES",
"[",
"v",
".",
"upper",
"(",
")",
"]",
"FLAGS",
".",
"verbosity",
"=",
"new... | Sets the logging verbosity.
Causes all messages of level <= v to be logged,
and all messages of level > v to be silently discarded.
Args:
v: int|str, the verbosity level as an integer or string. Legal string values
are those that can be coerced to an integer as well as case-insensitive
'debug', 'info', 'warning', 'error', and 'fatal'. | [
"Sets",
"the",
"logging",
"verbosity",
"."
] | 9d73fdaa23a6b6726aa5731390f388c0c6250ee5 | https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/logging/__init__.py#L266-L281 | train | 215,306 |
abseil/abseil-py | absl/logging/__init__.py | set_stderrthreshold | def set_stderrthreshold(s):
"""Sets the stderr threshold to the value passed in.
Args:
s: str|int, valid strings values are case-insensitive 'debug',
'info', 'warning', 'error', and 'fatal'; valid integer values are
logging.DEBUG|INFO|WARNING|ERROR|FATAL.
Raises:
ValueError: Raised when s is an invalid value.
"""
if s in converter.ABSL_LEVELS:
FLAGS.stderrthreshold = converter.ABSL_LEVELS[s]
elif isinstance(s, str) and s.upper() in converter.ABSL_NAMES:
FLAGS.stderrthreshold = s
else:
raise ValueError(
'set_stderrthreshold only accepts integer absl logging level '
'from -3 to 1, or case-insensitive string values '
"'debug', 'info', 'warning', 'error', and 'fatal'. "
'But found "{}" ({}).'.format(s, type(s))) | python | def set_stderrthreshold(s):
"""Sets the stderr threshold to the value passed in.
Args:
s: str|int, valid strings values are case-insensitive 'debug',
'info', 'warning', 'error', and 'fatal'; valid integer values are
logging.DEBUG|INFO|WARNING|ERROR|FATAL.
Raises:
ValueError: Raised when s is an invalid value.
"""
if s in converter.ABSL_LEVELS:
FLAGS.stderrthreshold = converter.ABSL_LEVELS[s]
elif isinstance(s, str) and s.upper() in converter.ABSL_NAMES:
FLAGS.stderrthreshold = s
else:
raise ValueError(
'set_stderrthreshold only accepts integer absl logging level '
'from -3 to 1, or case-insensitive string values '
"'debug', 'info', 'warning', 'error', and 'fatal'. "
'But found "{}" ({}).'.format(s, type(s))) | [
"def",
"set_stderrthreshold",
"(",
"s",
")",
":",
"if",
"s",
"in",
"converter",
".",
"ABSL_LEVELS",
":",
"FLAGS",
".",
"stderrthreshold",
"=",
"converter",
".",
"ABSL_LEVELS",
"[",
"s",
"]",
"elif",
"isinstance",
"(",
"s",
",",
"str",
")",
"and",
"s",
... | Sets the stderr threshold to the value passed in.
Args:
s: str|int, valid strings values are case-insensitive 'debug',
'info', 'warning', 'error', and 'fatal'; valid integer values are
logging.DEBUG|INFO|WARNING|ERROR|FATAL.
Raises:
ValueError: Raised when s is an invalid value. | [
"Sets",
"the",
"stderr",
"threshold",
"to",
"the",
"value",
"passed",
"in",
"."
] | 9d73fdaa23a6b6726aa5731390f388c0c6250ee5 | https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/logging/__init__.py#L284-L304 | train | 215,307 |
abseil/abseil-py | absl/logging/__init__.py | log_every_n | def log_every_n(level, msg, n, *args):
"""Logs 'msg % args' at level 'level' once per 'n' times.
Logs the 1st call, (N+1)st call, (2N+1)st call, etc.
Not threadsafe.
Args:
level: int, the absl logging level at which to log.
msg: str, the message to be logged.
n: int, the number of times this should be called before it is logged.
*args: The args to be substitued into the msg.
"""
count = _get_next_log_count_per_token(get_absl_logger().findCaller())
log_if(level, msg, not (count % n), *args) | python | def log_every_n(level, msg, n, *args):
"""Logs 'msg % args' at level 'level' once per 'n' times.
Logs the 1st call, (N+1)st call, (2N+1)st call, etc.
Not threadsafe.
Args:
level: int, the absl logging level at which to log.
msg: str, the message to be logged.
n: int, the number of times this should be called before it is logged.
*args: The args to be substitued into the msg.
"""
count = _get_next_log_count_per_token(get_absl_logger().findCaller())
log_if(level, msg, not (count % n), *args) | [
"def",
"log_every_n",
"(",
"level",
",",
"msg",
",",
"n",
",",
"*",
"args",
")",
":",
"count",
"=",
"_get_next_log_count_per_token",
"(",
"get_absl_logger",
"(",
")",
".",
"findCaller",
"(",
")",
")",
"log_if",
"(",
"level",
",",
"msg",
",",
"not",
"("... | Logs 'msg % args' at level 'level' once per 'n' times.
Logs the 1st call, (N+1)st call, (2N+1)st call, etc.
Not threadsafe.
Args:
level: int, the absl logging level at which to log.
msg: str, the message to be logged.
n: int, the number of times this should be called before it is logged.
*args: The args to be substitued into the msg. | [
"Logs",
"msg",
"%",
"args",
"at",
"level",
"level",
"once",
"per",
"n",
"times",
"."
] | 9d73fdaa23a6b6726aa5731390f388c0c6250ee5 | https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/logging/__init__.py#L367-L380 | train | 215,308 |
abseil/abseil-py | absl/logging/__init__.py | _seconds_have_elapsed | def _seconds_have_elapsed(token, num_seconds):
"""Tests if 'num_seconds' have passed since 'token' was requested.
Not strictly thread-safe - may log with the wrong frequency if called
concurrently from multiple threads. Accuracy depends on resolution of
'timeit.default_timer()'.
Always returns True on the first call for a given 'token'.
Args:
token: The token for which to look up the count.
num_seconds: The number of seconds to test for.
Returns:
Whether it has been >= 'num_seconds' since 'token' was last requested.
"""
now = timeit.default_timer()
then = _log_timer_per_token.get(token, None)
if then is None or (now - then) >= num_seconds:
_log_timer_per_token[token] = now
return True
else:
return False | python | def _seconds_have_elapsed(token, num_seconds):
"""Tests if 'num_seconds' have passed since 'token' was requested.
Not strictly thread-safe - may log with the wrong frequency if called
concurrently from multiple threads. Accuracy depends on resolution of
'timeit.default_timer()'.
Always returns True on the first call for a given 'token'.
Args:
token: The token for which to look up the count.
num_seconds: The number of seconds to test for.
Returns:
Whether it has been >= 'num_seconds' since 'token' was last requested.
"""
now = timeit.default_timer()
then = _log_timer_per_token.get(token, None)
if then is None or (now - then) >= num_seconds:
_log_timer_per_token[token] = now
return True
else:
return False | [
"def",
"_seconds_have_elapsed",
"(",
"token",
",",
"num_seconds",
")",
":",
"now",
"=",
"timeit",
".",
"default_timer",
"(",
")",
"then",
"=",
"_log_timer_per_token",
".",
"get",
"(",
"token",
",",
"None",
")",
"if",
"then",
"is",
"None",
"or",
"(",
"now... | Tests if 'num_seconds' have passed since 'token' was requested.
Not strictly thread-safe - may log with the wrong frequency if called
concurrently from multiple threads. Accuracy depends on resolution of
'timeit.default_timer()'.
Always returns True on the first call for a given 'token'.
Args:
token: The token for which to look up the count.
num_seconds: The number of seconds to test for.
Returns:
Whether it has been >= 'num_seconds' since 'token' was last requested. | [
"Tests",
"if",
"num_seconds",
"have",
"passed",
"since",
"token",
"was",
"requested",
"."
] | 9d73fdaa23a6b6726aa5731390f388c0c6250ee5 | https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/logging/__init__.py#L389-L411 | train | 215,309 |
abseil/abseil-py | absl/logging/__init__.py | log_every_n_seconds | def log_every_n_seconds(level, msg, n_seconds, *args):
"""Logs 'msg % args' at level 'level' iff 'n_seconds' elapsed since last call.
Logs the first call, logs subsequent calls if 'n' seconds have elapsed since
the last logging call from the same call site (file + line). Not thread-safe.
Args:
level: int, the absl logging level at which to log.
msg: str, the message to be logged.
n_seconds: float or int, seconds which should elapse before logging again.
*args: The args to be substitued into the msg.
"""
should_log = _seconds_have_elapsed(get_absl_logger().findCaller(), n_seconds)
log_if(level, msg, should_log, *args) | python | def log_every_n_seconds(level, msg, n_seconds, *args):
"""Logs 'msg % args' at level 'level' iff 'n_seconds' elapsed since last call.
Logs the first call, logs subsequent calls if 'n' seconds have elapsed since
the last logging call from the same call site (file + line). Not thread-safe.
Args:
level: int, the absl logging level at which to log.
msg: str, the message to be logged.
n_seconds: float or int, seconds which should elapse before logging again.
*args: The args to be substitued into the msg.
"""
should_log = _seconds_have_elapsed(get_absl_logger().findCaller(), n_seconds)
log_if(level, msg, should_log, *args) | [
"def",
"log_every_n_seconds",
"(",
"level",
",",
"msg",
",",
"n_seconds",
",",
"*",
"args",
")",
":",
"should_log",
"=",
"_seconds_have_elapsed",
"(",
"get_absl_logger",
"(",
")",
".",
"findCaller",
"(",
")",
",",
"n_seconds",
")",
"log_if",
"(",
"level",
... | Logs 'msg % args' at level 'level' iff 'n_seconds' elapsed since last call.
Logs the first call, logs subsequent calls if 'n' seconds have elapsed since
the last logging call from the same call site (file + line). Not thread-safe.
Args:
level: int, the absl logging level at which to log.
msg: str, the message to be logged.
n_seconds: float or int, seconds which should elapse before logging again.
*args: The args to be substitued into the msg. | [
"Logs",
"msg",
"%",
"args",
"at",
"level",
"level",
"iff",
"n_seconds",
"elapsed",
"since",
"last",
"call",
"."
] | 9d73fdaa23a6b6726aa5731390f388c0c6250ee5 | https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/logging/__init__.py#L414-L427 | train | 215,310 |
abseil/abseil-py | absl/logging/__init__.py | log_if | def log_if(level, msg, condition, *args):
"""Logs 'msg % args' at level 'level' only if condition is fulfilled."""
if condition:
log(level, msg, *args) | python | def log_if(level, msg, condition, *args):
"""Logs 'msg % args' at level 'level' only if condition is fulfilled."""
if condition:
log(level, msg, *args) | [
"def",
"log_if",
"(",
"level",
",",
"msg",
",",
"condition",
",",
"*",
"args",
")",
":",
"if",
"condition",
":",
"log",
"(",
"level",
",",
"msg",
",",
"*",
"args",
")"
] | Logs 'msg % args' at level 'level' only if condition is fulfilled. | [
"Logs",
"msg",
"%",
"args",
"at",
"level",
"level",
"only",
"if",
"condition",
"is",
"fulfilled",
"."
] | 9d73fdaa23a6b6726aa5731390f388c0c6250ee5 | https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/logging/__init__.py#L445-L448 | train | 215,311 |
abseil/abseil-py | absl/logging/__init__.py | log | def log(level, msg, *args, **kwargs):
"""Logs 'msg % args' at absl logging level 'level'.
If no args are given just print msg, ignoring any interpolation specifiers.
Args:
level: int, the absl logging level at which to log the message
(logging.DEBUG|INFO|WARNING|ERROR|FATAL). While some C++ verbose logging
level constants are also supported, callers should prefer explicit
logging.vlog() calls for such purpose.
msg: str, the message to be logged.
*args: The args to be substitued into the msg.
**kwargs: May contain exc_info to add exception traceback to message.
"""
if level > converter.ABSL_DEBUG:
# Even though this function supports level that is greater than 1, users
# should use logging.vlog instead for such cases.
# Treat this as vlog, 1 is equivalent to DEBUG.
standard_level = converter.STANDARD_DEBUG - (level - 1)
else:
if level < converter.ABSL_FATAL:
level = converter.ABSL_FATAL
standard_level = converter.absl_to_standard(level)
_absl_logger.log(standard_level, msg, *args, **kwargs) | python | def log(level, msg, *args, **kwargs):
"""Logs 'msg % args' at absl logging level 'level'.
If no args are given just print msg, ignoring any interpolation specifiers.
Args:
level: int, the absl logging level at which to log the message
(logging.DEBUG|INFO|WARNING|ERROR|FATAL). While some C++ verbose logging
level constants are also supported, callers should prefer explicit
logging.vlog() calls for such purpose.
msg: str, the message to be logged.
*args: The args to be substitued into the msg.
**kwargs: May contain exc_info to add exception traceback to message.
"""
if level > converter.ABSL_DEBUG:
# Even though this function supports level that is greater than 1, users
# should use logging.vlog instead for such cases.
# Treat this as vlog, 1 is equivalent to DEBUG.
standard_level = converter.STANDARD_DEBUG - (level - 1)
else:
if level < converter.ABSL_FATAL:
level = converter.ABSL_FATAL
standard_level = converter.absl_to_standard(level)
_absl_logger.log(standard_level, msg, *args, **kwargs) | [
"def",
"log",
"(",
"level",
",",
"msg",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"level",
">",
"converter",
".",
"ABSL_DEBUG",
":",
"# Even though this function supports level that is greater than 1, users",
"# should use logging.vlog instead for such ... | Logs 'msg % args' at absl logging level 'level'.
If no args are given just print msg, ignoring any interpolation specifiers.
Args:
level: int, the absl logging level at which to log the message
(logging.DEBUG|INFO|WARNING|ERROR|FATAL). While some C++ verbose logging
level constants are also supported, callers should prefer explicit
logging.vlog() calls for such purpose.
msg: str, the message to be logged.
*args: The args to be substitued into the msg.
**kwargs: May contain exc_info to add exception traceback to message. | [
"Logs",
"msg",
"%",
"args",
"at",
"absl",
"logging",
"level",
"level",
"."
] | 9d73fdaa23a6b6726aa5731390f388c0c6250ee5 | https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/logging/__init__.py#L451-L476 | train | 215,312 |
abseil/abseil-py | absl/logging/__init__.py | vlog_is_on | def vlog_is_on(level):
"""Checks if vlog is enabled for the given level in caller's source file.
Args:
level: int, the C++ verbose logging level at which to log the message,
e.g. 1, 2, 3, 4... While absl level constants are also supported,
callers should prefer level_debug|level_info|... calls for
checking those.
Returns:
True if logging is turned on for that level.
"""
if level > converter.ABSL_DEBUG:
# Even though this function supports level that is greater than 1, users
# should use logging.vlog instead for such cases.
# Treat this as vlog, 1 is equivalent to DEBUG.
standard_level = converter.STANDARD_DEBUG - (level - 1)
else:
if level < converter.ABSL_FATAL:
level = converter.ABSL_FATAL
standard_level = converter.absl_to_standard(level)
return _absl_logger.isEnabledFor(standard_level) | python | def vlog_is_on(level):
"""Checks if vlog is enabled for the given level in caller's source file.
Args:
level: int, the C++ verbose logging level at which to log the message,
e.g. 1, 2, 3, 4... While absl level constants are also supported,
callers should prefer level_debug|level_info|... calls for
checking those.
Returns:
True if logging is turned on for that level.
"""
if level > converter.ABSL_DEBUG:
# Even though this function supports level that is greater than 1, users
# should use logging.vlog instead for such cases.
# Treat this as vlog, 1 is equivalent to DEBUG.
standard_level = converter.STANDARD_DEBUG - (level - 1)
else:
if level < converter.ABSL_FATAL:
level = converter.ABSL_FATAL
standard_level = converter.absl_to_standard(level)
return _absl_logger.isEnabledFor(standard_level) | [
"def",
"vlog_is_on",
"(",
"level",
")",
":",
"if",
"level",
">",
"converter",
".",
"ABSL_DEBUG",
":",
"# Even though this function supports level that is greater than 1, users",
"# should use logging.vlog instead for such cases.",
"# Treat this as vlog, 1 is equivalent to DEBUG.",
"s... | Checks if vlog is enabled for the given level in caller's source file.
Args:
level: int, the C++ verbose logging level at which to log the message,
e.g. 1, 2, 3, 4... While absl level constants are also supported,
callers should prefer level_debug|level_info|... calls for
checking those.
Returns:
True if logging is turned on for that level. | [
"Checks",
"if",
"vlog",
"is",
"enabled",
"for",
"the",
"given",
"level",
"in",
"caller",
"s",
"source",
"file",
"."
] | 9d73fdaa23a6b6726aa5731390f388c0c6250ee5 | https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/logging/__init__.py#L493-L515 | train | 215,313 |
abseil/abseil-py | absl/logging/__init__.py | get_log_file_name | def get_log_file_name(level=INFO):
"""Returns the name of the log file.
For Python logging, only one file is used and level is ignored. And it returns
empty string if it logs to stderr/stdout or the log stream has no `name`
attribute.
Args:
level: int, the absl.logging level.
Raises:
ValueError: Raised when `level` has an invalid value.
"""
if level not in converter.ABSL_LEVELS:
raise ValueError('Invalid absl.logging level {}'.format(level))
stream = get_absl_handler().python_handler.stream
if (stream == sys.stderr or stream == sys.stdout or
not hasattr(stream, 'name')):
return ''
else:
return stream.name | python | def get_log_file_name(level=INFO):
"""Returns the name of the log file.
For Python logging, only one file is used and level is ignored. And it returns
empty string if it logs to stderr/stdout or the log stream has no `name`
attribute.
Args:
level: int, the absl.logging level.
Raises:
ValueError: Raised when `level` has an invalid value.
"""
if level not in converter.ABSL_LEVELS:
raise ValueError('Invalid absl.logging level {}'.format(level))
stream = get_absl_handler().python_handler.stream
if (stream == sys.stderr or stream == sys.stdout or
not hasattr(stream, 'name')):
return ''
else:
return stream.name | [
"def",
"get_log_file_name",
"(",
"level",
"=",
"INFO",
")",
":",
"if",
"level",
"not",
"in",
"converter",
".",
"ABSL_LEVELS",
":",
"raise",
"ValueError",
"(",
"'Invalid absl.logging level {}'",
".",
"format",
"(",
"level",
")",
")",
"stream",
"=",
"get_absl_ha... | Returns the name of the log file.
For Python logging, only one file is used and level is ignored. And it returns
empty string if it logs to stderr/stdout or the log stream has no `name`
attribute.
Args:
level: int, the absl.logging level.
Raises:
ValueError: Raised when `level` has an invalid value. | [
"Returns",
"the",
"name",
"of",
"the",
"log",
"file",
"."
] | 9d73fdaa23a6b6726aa5731390f388c0c6250ee5 | https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/logging/__init__.py#L546-L566 | train | 215,314 |
abseil/abseil-py | absl/logging/__init__.py | find_log_dir_and_names | def find_log_dir_and_names(program_name=None, log_dir=None):
"""Computes the directory and filename prefix for log file.
Args:
program_name: str|None, the filename part of the path to the program that
is running without its extension. e.g: if your program is called
'usr/bin/foobar.py' this method should probably be called with
program_name='foobar' However, this is just a convention, you can
pass in any string you want, and it will be used as part of the
log filename. If you don't pass in anything, the default behavior
is as described in the example. In python standard logging mode,
the program_name will be prepended with py_ if it is the program_name
argument is omitted.
log_dir: str|None, the desired log directory.
Returns:
(log_dir, file_prefix, symlink_prefix)
"""
if not program_name:
# Strip the extension (foobar.par becomes foobar, and
# fubar.py becomes fubar). We do this so that the log
# file names are similar to C++ log file names.
program_name = os.path.splitext(os.path.basename(sys.argv[0]))[0]
# Prepend py_ to files so that python code gets a unique file, and
# so that C++ libraries do not try to write to the same log files as us.
program_name = 'py_%s' % program_name
actual_log_dir = find_log_dir(log_dir=log_dir)
try:
username = getpass.getuser()
except KeyError:
# This can happen, e.g. when running under docker w/o passwd file.
if hasattr(os, 'getuid'):
# Windows doesn't have os.getuid
username = str(os.getuid())
else:
username = 'unknown'
hostname = socket.gethostname()
file_prefix = '%s.%s.%s.log' % (program_name, hostname, username)
return actual_log_dir, file_prefix, program_name | python | def find_log_dir_and_names(program_name=None, log_dir=None):
"""Computes the directory and filename prefix for log file.
Args:
program_name: str|None, the filename part of the path to the program that
is running without its extension. e.g: if your program is called
'usr/bin/foobar.py' this method should probably be called with
program_name='foobar' However, this is just a convention, you can
pass in any string you want, and it will be used as part of the
log filename. If you don't pass in anything, the default behavior
is as described in the example. In python standard logging mode,
the program_name will be prepended with py_ if it is the program_name
argument is omitted.
log_dir: str|None, the desired log directory.
Returns:
(log_dir, file_prefix, symlink_prefix)
"""
if not program_name:
# Strip the extension (foobar.par becomes foobar, and
# fubar.py becomes fubar). We do this so that the log
# file names are similar to C++ log file names.
program_name = os.path.splitext(os.path.basename(sys.argv[0]))[0]
# Prepend py_ to files so that python code gets a unique file, and
# so that C++ libraries do not try to write to the same log files as us.
program_name = 'py_%s' % program_name
actual_log_dir = find_log_dir(log_dir=log_dir)
try:
username = getpass.getuser()
except KeyError:
# This can happen, e.g. when running under docker w/o passwd file.
if hasattr(os, 'getuid'):
# Windows doesn't have os.getuid
username = str(os.getuid())
else:
username = 'unknown'
hostname = socket.gethostname()
file_prefix = '%s.%s.%s.log' % (program_name, hostname, username)
return actual_log_dir, file_prefix, program_name | [
"def",
"find_log_dir_and_names",
"(",
"program_name",
"=",
"None",
",",
"log_dir",
"=",
"None",
")",
":",
"if",
"not",
"program_name",
":",
"# Strip the extension (foobar.par becomes foobar, and",
"# fubar.py becomes fubar). We do this so that the log",
"# file names are similar ... | Computes the directory and filename prefix for log file.
Args:
program_name: str|None, the filename part of the path to the program that
is running without its extension. e.g: if your program is called
'usr/bin/foobar.py' this method should probably be called with
program_name='foobar' However, this is just a convention, you can
pass in any string you want, and it will be used as part of the
log filename. If you don't pass in anything, the default behavior
is as described in the example. In python standard logging mode,
the program_name will be prepended with py_ if it is the program_name
argument is omitted.
log_dir: str|None, the desired log directory.
Returns:
(log_dir, file_prefix, symlink_prefix) | [
"Computes",
"the",
"directory",
"and",
"filename",
"prefix",
"for",
"log",
"file",
"."
] | 9d73fdaa23a6b6726aa5731390f388c0c6250ee5 | https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/logging/__init__.py#L569-L611 | train | 215,315 |
abseil/abseil-py | absl/logging/__init__.py | find_log_dir | def find_log_dir(log_dir=None):
"""Returns the most suitable directory to put log files into.
Args:
log_dir: str|None, if specified, the logfile(s) will be created in that
directory. Otherwise if the --log_dir command-line flag is provided,
the logfile will be created in that directory. Otherwise the logfile
will be created in a standard location.
"""
# Get a list of possible log dirs (will try to use them in order).
if log_dir:
# log_dir was explicitly specified as an arg, so use it and it alone.
dirs = [log_dir]
elif FLAGS['log_dir'].value:
# log_dir flag was provided, so use it and it alone (this mimics the
# behavior of the same flag in logging.cc).
dirs = [FLAGS['log_dir'].value]
else:
dirs = ['/tmp/', './']
# Find the first usable log dir.
for d in dirs:
if os.path.isdir(d) and os.access(d, os.W_OK):
return d
_absl_logger.fatal("Can't find a writable directory for logs, tried %s", dirs) | python | def find_log_dir(log_dir=None):
"""Returns the most suitable directory to put log files into.
Args:
log_dir: str|None, if specified, the logfile(s) will be created in that
directory. Otherwise if the --log_dir command-line flag is provided,
the logfile will be created in that directory. Otherwise the logfile
will be created in a standard location.
"""
# Get a list of possible log dirs (will try to use them in order).
if log_dir:
# log_dir was explicitly specified as an arg, so use it and it alone.
dirs = [log_dir]
elif FLAGS['log_dir'].value:
# log_dir flag was provided, so use it and it alone (this mimics the
# behavior of the same flag in logging.cc).
dirs = [FLAGS['log_dir'].value]
else:
dirs = ['/tmp/', './']
# Find the first usable log dir.
for d in dirs:
if os.path.isdir(d) and os.access(d, os.W_OK):
return d
_absl_logger.fatal("Can't find a writable directory for logs, tried %s", dirs) | [
"def",
"find_log_dir",
"(",
"log_dir",
"=",
"None",
")",
":",
"# Get a list of possible log dirs (will try to use them in order).",
"if",
"log_dir",
":",
"# log_dir was explicitly specified as an arg, so use it and it alone.",
"dirs",
"=",
"[",
"log_dir",
"]",
"elif",
"FLAGS",
... | Returns the most suitable directory to put log files into.
Args:
log_dir: str|None, if specified, the logfile(s) will be created in that
directory. Otherwise if the --log_dir command-line flag is provided,
the logfile will be created in that directory. Otherwise the logfile
will be created in a standard location. | [
"Returns",
"the",
"most",
"suitable",
"directory",
"to",
"put",
"log",
"files",
"into",
"."
] | 9d73fdaa23a6b6726aa5731390f388c0c6250ee5 | https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/logging/__init__.py#L614-L638 | train | 215,316 |
abseil/abseil-py | absl/logging/__init__.py | get_absl_log_prefix | def get_absl_log_prefix(record):
"""Returns the absl log prefix for the log record.
Args:
record: logging.LogRecord, the record to get prefix for.
"""
created_tuple = time.localtime(record.created)
created_microsecond = int(record.created % 1.0 * 1e6)
critical_prefix = ''
level = record.levelno
if _is_non_absl_fatal_record(record):
# When the level is FATAL, but not logged from absl, lower the level so
# it's treated as ERROR.
level = logging.ERROR
critical_prefix = _CRITICAL_PREFIX
severity = converter.get_initial_for_level(level)
return '%c%02d%02d %02d:%02d:%02d.%06d %5d %s:%d] %s' % (
severity,
created_tuple.tm_mon,
created_tuple.tm_mday,
created_tuple.tm_hour,
created_tuple.tm_min,
created_tuple.tm_sec,
created_microsecond,
_get_thread_id(),
record.filename,
record.lineno,
critical_prefix) | python | def get_absl_log_prefix(record):
"""Returns the absl log prefix for the log record.
Args:
record: logging.LogRecord, the record to get prefix for.
"""
created_tuple = time.localtime(record.created)
created_microsecond = int(record.created % 1.0 * 1e6)
critical_prefix = ''
level = record.levelno
if _is_non_absl_fatal_record(record):
# When the level is FATAL, but not logged from absl, lower the level so
# it's treated as ERROR.
level = logging.ERROR
critical_prefix = _CRITICAL_PREFIX
severity = converter.get_initial_for_level(level)
return '%c%02d%02d %02d:%02d:%02d.%06d %5d %s:%d] %s' % (
severity,
created_tuple.tm_mon,
created_tuple.tm_mday,
created_tuple.tm_hour,
created_tuple.tm_min,
created_tuple.tm_sec,
created_microsecond,
_get_thread_id(),
record.filename,
record.lineno,
critical_prefix) | [
"def",
"get_absl_log_prefix",
"(",
"record",
")",
":",
"created_tuple",
"=",
"time",
".",
"localtime",
"(",
"record",
".",
"created",
")",
"created_microsecond",
"=",
"int",
"(",
"record",
".",
"created",
"%",
"1.0",
"*",
"1e6",
")",
"critical_prefix",
"=",
... | Returns the absl log prefix for the log record.
Args:
record: logging.LogRecord, the record to get prefix for. | [
"Returns",
"the",
"absl",
"log",
"prefix",
"for",
"the",
"log",
"record",
"."
] | 9d73fdaa23a6b6726aa5731390f388c0c6250ee5 | https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/logging/__init__.py#L641-L670 | train | 215,317 |
abseil/abseil-py | absl/logging/__init__.py | skip_log_prefix | def skip_log_prefix(func):
"""Skips reporting the prefix of a given function or name by ABSLLogger.
This is a convenience wrapper function / decorator for
`ABSLLogger.register_frame_to_skip`.
If a callable function is provided, only that function will be skipped.
If a function name is provided, all functions with the same name in the
file that this is called in will be skipped.
This can be used as a decorator of the intended function to be skipped.
Args:
func: Callable function or its name as a string.
Returns:
func (the input, unchanged).
Raises:
ValueError: The input is callable but does not have a function code object.
TypeError: The input is neither callable nor a string.
"""
if callable(func):
func_code = getattr(func, '__code__', None)
if func_code is None:
raise ValueError('Input callable does not have a function code object.')
file_name = func_code.co_filename
func_name = func_code.co_name
func_lineno = func_code.co_firstlineno
elif isinstance(func, six.string_types):
file_name = get_absl_logger().findCaller()[0]
func_name = func
func_lineno = None
else:
raise TypeError('Input is neither callable nor a string.')
ABSLLogger.register_frame_to_skip(file_name, func_name, func_lineno)
return func | python | def skip_log_prefix(func):
"""Skips reporting the prefix of a given function or name by ABSLLogger.
This is a convenience wrapper function / decorator for
`ABSLLogger.register_frame_to_skip`.
If a callable function is provided, only that function will be skipped.
If a function name is provided, all functions with the same name in the
file that this is called in will be skipped.
This can be used as a decorator of the intended function to be skipped.
Args:
func: Callable function or its name as a string.
Returns:
func (the input, unchanged).
Raises:
ValueError: The input is callable but does not have a function code object.
TypeError: The input is neither callable nor a string.
"""
if callable(func):
func_code = getattr(func, '__code__', None)
if func_code is None:
raise ValueError('Input callable does not have a function code object.')
file_name = func_code.co_filename
func_name = func_code.co_name
func_lineno = func_code.co_firstlineno
elif isinstance(func, six.string_types):
file_name = get_absl_logger().findCaller()[0]
func_name = func
func_lineno = None
else:
raise TypeError('Input is neither callable nor a string.')
ABSLLogger.register_frame_to_skip(file_name, func_name, func_lineno)
return func | [
"def",
"skip_log_prefix",
"(",
"func",
")",
":",
"if",
"callable",
"(",
"func",
")",
":",
"func_code",
"=",
"getattr",
"(",
"func",
",",
"'__code__'",
",",
"None",
")",
"if",
"func_code",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'Input callable does... | Skips reporting the prefix of a given function or name by ABSLLogger.
This is a convenience wrapper function / decorator for
`ABSLLogger.register_frame_to_skip`.
If a callable function is provided, only that function will be skipped.
If a function name is provided, all functions with the same name in the
file that this is called in will be skipped.
This can be used as a decorator of the intended function to be skipped.
Args:
func: Callable function or its name as a string.
Returns:
func (the input, unchanged).
Raises:
ValueError: The input is callable but does not have a function code object.
TypeError: The input is neither callable nor a string. | [
"Skips",
"reporting",
"the",
"prefix",
"of",
"a",
"given",
"function",
"or",
"name",
"by",
"ABSLLogger",
"."
] | 9d73fdaa23a6b6726aa5731390f388c0c6250ee5 | https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/logging/__init__.py#L673-L709 | train | 215,318 |
abseil/abseil-py | absl/logging/__init__.py | use_absl_handler | def use_absl_handler():
"""Uses the ABSL logging handler for logging if not yet configured.
The absl handler is already attached to root if there are no other handlers
attached when importing this module.
Otherwise, this method is called in app.run() so absl handler is used.
"""
absl_handler = get_absl_handler()
if absl_handler not in logging.root.handlers:
logging.root.addHandler(absl_handler)
FLAGS['verbosity']._update_logging_levels() | python | def use_absl_handler():
"""Uses the ABSL logging handler for logging if not yet configured.
The absl handler is already attached to root if there are no other handlers
attached when importing this module.
Otherwise, this method is called in app.run() so absl handler is used.
"""
absl_handler = get_absl_handler()
if absl_handler not in logging.root.handlers:
logging.root.addHandler(absl_handler)
FLAGS['verbosity']._update_logging_levels() | [
"def",
"use_absl_handler",
"(",
")",
":",
"absl_handler",
"=",
"get_absl_handler",
"(",
")",
"if",
"absl_handler",
"not",
"in",
"logging",
".",
"root",
".",
"handlers",
":",
"logging",
".",
"root",
".",
"addHandler",
"(",
"absl_handler",
")",
"FLAGS",
"[",
... | Uses the ABSL logging handler for logging if not yet configured.
The absl handler is already attached to root if there are no other handlers
attached when importing this module.
Otherwise, this method is called in app.run() so absl handler is used. | [
"Uses",
"the",
"ABSL",
"logging",
"handler",
"for",
"logging",
"if",
"not",
"yet",
"configured",
"."
] | 9d73fdaa23a6b6726aa5731390f388c0c6250ee5 | https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/logging/__init__.py#L1114-L1125 | train | 215,319 |
abseil/abseil-py | absl/logging/__init__.py | _initialize | def _initialize():
"""Initializes loggers and handlers."""
global _absl_logger, _absl_handler
if _absl_logger:
return
original_logger_class = logging.getLoggerClass()
logging.setLoggerClass(ABSLLogger)
_absl_logger = logging.getLogger('absl')
logging.setLoggerClass(original_logger_class)
python_logging_formatter = PythonFormatter()
_absl_handler = ABSLHandler(python_logging_formatter)
# The absl handler logs to stderr by default. To prevent double logging to
# stderr, the following code tries its best to remove other handlers that emit
# to stderr. Those handlers are most commonly added when logging.info/debug is
# called before importing this module.
handlers = [
h for h in logging.root.handlers
if isinstance(h, logging.StreamHandler) and h.stream == sys.stderr]
for h in handlers:
logging.root.removeHandler(h)
# The absl handler will always be attached to root, not the absl logger.
if not logging.root.handlers:
# Attach the absl handler at import time when there are no other handlers.
# Otherwise it means users have explicitly configured logging, and the absl
# handler will only be attached later in app.run(). For App Engine apps,
# the absl handler is not used.
logging.root.addHandler(_absl_handler) | python | def _initialize():
"""Initializes loggers and handlers."""
global _absl_logger, _absl_handler
if _absl_logger:
return
original_logger_class = logging.getLoggerClass()
logging.setLoggerClass(ABSLLogger)
_absl_logger = logging.getLogger('absl')
logging.setLoggerClass(original_logger_class)
python_logging_formatter = PythonFormatter()
_absl_handler = ABSLHandler(python_logging_formatter)
# The absl handler logs to stderr by default. To prevent double logging to
# stderr, the following code tries its best to remove other handlers that emit
# to stderr. Those handlers are most commonly added when logging.info/debug is
# called before importing this module.
handlers = [
h for h in logging.root.handlers
if isinstance(h, logging.StreamHandler) and h.stream == sys.stderr]
for h in handlers:
logging.root.removeHandler(h)
# The absl handler will always be attached to root, not the absl logger.
if not logging.root.handlers:
# Attach the absl handler at import time when there are no other handlers.
# Otherwise it means users have explicitly configured logging, and the absl
# handler will only be attached later in app.run(). For App Engine apps,
# the absl handler is not used.
logging.root.addHandler(_absl_handler) | [
"def",
"_initialize",
"(",
")",
":",
"global",
"_absl_logger",
",",
"_absl_handler",
"if",
"_absl_logger",
":",
"return",
"original_logger_class",
"=",
"logging",
".",
"getLoggerClass",
"(",
")",
"logging",
".",
"setLoggerClass",
"(",
"ABSLLogger",
")",
"_absl_log... | Initializes loggers and handlers. | [
"Initializes",
"loggers",
"and",
"handlers",
"."
] | 9d73fdaa23a6b6726aa5731390f388c0c6250ee5 | https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/logging/__init__.py#L1128-L1159 | train | 215,320 |
abseil/abseil-py | absl/logging/__init__.py | _VerbosityFlag._update_logging_levels | def _update_logging_levels(self):
"""Updates absl logging levels to the current verbosity."""
if not _absl_logger:
return
if self._value <= converter.ABSL_DEBUG:
standard_verbosity = converter.absl_to_standard(self._value)
else:
# --verbosity is set to higher than 1 for vlog.
standard_verbosity = logging.DEBUG - (self._value - 1)
# Also update root level when absl_handler is used.
if _absl_handler in logging.root.handlers:
logging.root.setLevel(standard_verbosity) | python | def _update_logging_levels(self):
"""Updates absl logging levels to the current verbosity."""
if not _absl_logger:
return
if self._value <= converter.ABSL_DEBUG:
standard_verbosity = converter.absl_to_standard(self._value)
else:
# --verbosity is set to higher than 1 for vlog.
standard_verbosity = logging.DEBUG - (self._value - 1)
# Also update root level when absl_handler is used.
if _absl_handler in logging.root.handlers:
logging.root.setLevel(standard_verbosity) | [
"def",
"_update_logging_levels",
"(",
"self",
")",
":",
"if",
"not",
"_absl_logger",
":",
"return",
"if",
"self",
".",
"_value",
"<=",
"converter",
".",
"ABSL_DEBUG",
":",
"standard_verbosity",
"=",
"converter",
".",
"absl_to_standard",
"(",
"self",
".",
"_val... | Updates absl logging levels to the current verbosity. | [
"Updates",
"absl",
"logging",
"levels",
"to",
"the",
"current",
"verbosity",
"."
] | 9d73fdaa23a6b6726aa5731390f388c0c6250ee5 | https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/logging/__init__.py#L176-L189 | train | 215,321 |
abseil/abseil-py | absl/logging/__init__.py | PythonHandler.start_logging_to_file | def start_logging_to_file(self, program_name=None, log_dir=None):
"""Starts logging messages to files instead of standard error."""
FLAGS.logtostderr = False
actual_log_dir, file_prefix, symlink_prefix = find_log_dir_and_names(
program_name=program_name, log_dir=log_dir)
basename = '%s.INFO.%s.%d' % (
file_prefix,
time.strftime('%Y%m%d-%H%M%S', time.localtime(time.time())),
os.getpid())
filename = os.path.join(actual_log_dir, basename)
if six.PY2:
self.stream = open(filename, 'a')
else:
self.stream = open(filename, 'a', encoding='utf-8')
# os.symlink is not available on Windows Python 2.
if getattr(os, 'symlink', None):
# Create a symlink to the log file with a canonical name.
symlink = os.path.join(actual_log_dir, symlink_prefix + '.INFO')
try:
if os.path.islink(symlink):
os.unlink(symlink)
os.symlink(os.path.basename(filename), symlink)
except EnvironmentError:
# If it fails, we're sad but it's no error. Commonly, this
# fails because the symlink was created by another user and so
# we can't modify it
pass | python | def start_logging_to_file(self, program_name=None, log_dir=None):
"""Starts logging messages to files instead of standard error."""
FLAGS.logtostderr = False
actual_log_dir, file_prefix, symlink_prefix = find_log_dir_and_names(
program_name=program_name, log_dir=log_dir)
basename = '%s.INFO.%s.%d' % (
file_prefix,
time.strftime('%Y%m%d-%H%M%S', time.localtime(time.time())),
os.getpid())
filename = os.path.join(actual_log_dir, basename)
if six.PY2:
self.stream = open(filename, 'a')
else:
self.stream = open(filename, 'a', encoding='utf-8')
# os.symlink is not available on Windows Python 2.
if getattr(os, 'symlink', None):
# Create a symlink to the log file with a canonical name.
symlink = os.path.join(actual_log_dir, symlink_prefix + '.INFO')
try:
if os.path.islink(symlink):
os.unlink(symlink)
os.symlink(os.path.basename(filename), symlink)
except EnvironmentError:
# If it fails, we're sad but it's no error. Commonly, this
# fails because the symlink was created by another user and so
# we can't modify it
pass | [
"def",
"start_logging_to_file",
"(",
"self",
",",
"program_name",
"=",
"None",
",",
"log_dir",
"=",
"None",
")",
":",
"FLAGS",
".",
"logtostderr",
"=",
"False",
"actual_log_dir",
",",
"file_prefix",
",",
"symlink_prefix",
"=",
"find_log_dir_and_names",
"(",
"pro... | Starts logging messages to files instead of standard error. | [
"Starts",
"logging",
"messages",
"to",
"files",
"instead",
"of",
"standard",
"error",
"."
] | 9d73fdaa23a6b6726aa5731390f388c0c6250ee5 | https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/logging/__init__.py#L733-L763 | train | 215,322 |
abseil/abseil-py | absl/logging/__init__.py | PythonHandler.flush | def flush(self):
"""Flushes all log files."""
self.acquire()
try:
self.stream.flush()
except (EnvironmentError, ValueError):
# A ValueError is thrown if we try to flush a closed file.
pass
finally:
self.release() | python | def flush(self):
"""Flushes all log files."""
self.acquire()
try:
self.stream.flush()
except (EnvironmentError, ValueError):
# A ValueError is thrown if we try to flush a closed file.
pass
finally:
self.release() | [
"def",
"flush",
"(",
"self",
")",
":",
"self",
".",
"acquire",
"(",
")",
"try",
":",
"self",
".",
"stream",
".",
"flush",
"(",
")",
"except",
"(",
"EnvironmentError",
",",
"ValueError",
")",
":",
"# A ValueError is thrown if we try to flush a closed file.",
"p... | Flushes all log files. | [
"Flushes",
"all",
"log",
"files",
"."
] | 9d73fdaa23a6b6726aa5731390f388c0c6250ee5 | https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/logging/__init__.py#L772-L781 | train | 215,323 |
abseil/abseil-py | absl/logging/__init__.py | PythonHandler._log_to_stderr | def _log_to_stderr(self, record):
"""Emits the record to stderr.
This temporarily sets the handler stream to stderr, calls
StreamHandler.emit, then reverts the stream back.
Args:
record: logging.LogRecord, the record to log.
"""
# emit() is protected by a lock in logging.Handler, so we don't need to
# protect here again.
old_stream = self.stream
self.stream = sys.stderr
try:
super(PythonHandler, self).emit(record)
finally:
self.stream = old_stream | python | def _log_to_stderr(self, record):
"""Emits the record to stderr.
This temporarily sets the handler stream to stderr, calls
StreamHandler.emit, then reverts the stream back.
Args:
record: logging.LogRecord, the record to log.
"""
# emit() is protected by a lock in logging.Handler, so we don't need to
# protect here again.
old_stream = self.stream
self.stream = sys.stderr
try:
super(PythonHandler, self).emit(record)
finally:
self.stream = old_stream | [
"def",
"_log_to_stderr",
"(",
"self",
",",
"record",
")",
":",
"# emit() is protected by a lock in logging.Handler, so we don't need to",
"# protect here again.",
"old_stream",
"=",
"self",
".",
"stream",
"self",
".",
"stream",
"=",
"sys",
".",
"stderr",
"try",
":",
"... | Emits the record to stderr.
This temporarily sets the handler stream to stderr, calls
StreamHandler.emit, then reverts the stream back.
Args:
record: logging.LogRecord, the record to log. | [
"Emits",
"the",
"record",
"to",
"stderr",
"."
] | 9d73fdaa23a6b6726aa5731390f388c0c6250ee5 | https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/logging/__init__.py#L783-L799 | train | 215,324 |
abseil/abseil-py | absl/logging/__init__.py | PythonHandler.emit | def emit(self, record):
"""Prints a record out to some streams.
If FLAGS.logtostderr is set, it will print to sys.stderr ONLY.
If FLAGS.alsologtostderr is set, it will print to sys.stderr.
If FLAGS.logtostderr is not set, it will log to the stream
associated with the current thread.
Args:
record: logging.LogRecord, the record to emit.
"""
# People occasionally call logging functions at import time before
# our flags may have even been defined yet, let alone even parsed, as we
# rely on the C++ side to define some flags for us and app init to
# deal with parsing. Match the C++ library behavior of notify and emit
# such messages to stderr. It encourages people to clean-up and does
# not hide the message.
level = record.levelno
if not FLAGS.is_parsed(): # Also implies "before flag has been defined".
global _warn_preinit_stderr
if _warn_preinit_stderr:
sys.stderr.write(
'WARNING: Logging before flag parsing goes to stderr.\n')
_warn_preinit_stderr = False
self._log_to_stderr(record)
elif FLAGS['logtostderr'].value:
self._log_to_stderr(record)
else:
super(PythonHandler, self).emit(record)
stderr_threshold = converter.string_to_standard(
FLAGS['stderrthreshold'].value)
if ((FLAGS['alsologtostderr'].value or level >= stderr_threshold) and
self.stream != sys.stderr):
self._log_to_stderr(record)
# Die when the record is created from ABSLLogger and level is FATAL.
if _is_absl_fatal_record(record):
self.flush() # Flush the log before dying.
# In threaded python, sys.exit() from a non-main thread only
# exits the thread in question.
os.abort() | python | def emit(self, record):
"""Prints a record out to some streams.
If FLAGS.logtostderr is set, it will print to sys.stderr ONLY.
If FLAGS.alsologtostderr is set, it will print to sys.stderr.
If FLAGS.logtostderr is not set, it will log to the stream
associated with the current thread.
Args:
record: logging.LogRecord, the record to emit.
"""
# People occasionally call logging functions at import time before
# our flags may have even been defined yet, let alone even parsed, as we
# rely on the C++ side to define some flags for us and app init to
# deal with parsing. Match the C++ library behavior of notify and emit
# such messages to stderr. It encourages people to clean-up and does
# not hide the message.
level = record.levelno
if not FLAGS.is_parsed(): # Also implies "before flag has been defined".
global _warn_preinit_stderr
if _warn_preinit_stderr:
sys.stderr.write(
'WARNING: Logging before flag parsing goes to stderr.\n')
_warn_preinit_stderr = False
self._log_to_stderr(record)
elif FLAGS['logtostderr'].value:
self._log_to_stderr(record)
else:
super(PythonHandler, self).emit(record)
stderr_threshold = converter.string_to_standard(
FLAGS['stderrthreshold'].value)
if ((FLAGS['alsologtostderr'].value or level >= stderr_threshold) and
self.stream != sys.stderr):
self._log_to_stderr(record)
# Die when the record is created from ABSLLogger and level is FATAL.
if _is_absl_fatal_record(record):
self.flush() # Flush the log before dying.
# In threaded python, sys.exit() from a non-main thread only
# exits the thread in question.
os.abort() | [
"def",
"emit",
"(",
"self",
",",
"record",
")",
":",
"# People occasionally call logging functions at import time before",
"# our flags may have even been defined yet, let alone even parsed, as we",
"# rely on the C++ side to define some flags for us and app init to",
"# deal with parsing. Ma... | Prints a record out to some streams.
If FLAGS.logtostderr is set, it will print to sys.stderr ONLY.
If FLAGS.alsologtostderr is set, it will print to sys.stderr.
If FLAGS.logtostderr is not set, it will log to the stream
associated with the current thread.
Args:
record: logging.LogRecord, the record to emit. | [
"Prints",
"a",
"record",
"out",
"to",
"some",
"streams",
"."
] | 9d73fdaa23a6b6726aa5731390f388c0c6250ee5 | https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/logging/__init__.py#L801-L841 | train | 215,325 |
abseil/abseil-py | absl/logging/__init__.py | PythonHandler.close | def close(self):
"""Closes the stream to which we are writing."""
self.acquire()
try:
self.flush()
try:
# Do not close the stream if it's sys.stderr|stdout. They may be
# redirected or overridden to files, which should be managed by users
# explicitly.
if self.stream not in (sys.stderr, sys.stdout) and (
not hasattr(self.stream, 'isatty') or not self.stream.isatty()):
self.stream.close()
except ValueError:
# A ValueError is thrown if we try to run isatty() on a closed file.
pass
super(PythonHandler, self).close()
finally:
self.release() | python | def close(self):
"""Closes the stream to which we are writing."""
self.acquire()
try:
self.flush()
try:
# Do not close the stream if it's sys.stderr|stdout. They may be
# redirected or overridden to files, which should be managed by users
# explicitly.
if self.stream not in (sys.stderr, sys.stdout) and (
not hasattr(self.stream, 'isatty') or not self.stream.isatty()):
self.stream.close()
except ValueError:
# A ValueError is thrown if we try to run isatty() on a closed file.
pass
super(PythonHandler, self).close()
finally:
self.release() | [
"def",
"close",
"(",
"self",
")",
":",
"self",
".",
"acquire",
"(",
")",
"try",
":",
"self",
".",
"flush",
"(",
")",
"try",
":",
"# Do not close the stream if it's sys.stderr|stdout. They may be",
"# redirected or overridden to files, which should be managed by users",
"#... | Closes the stream to which we are writing. | [
"Closes",
"the",
"stream",
"to",
"which",
"we",
"are",
"writing",
"."
] | 9d73fdaa23a6b6726aa5731390f388c0c6250ee5 | https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/logging/__init__.py#L843-L860 | train | 215,326 |
abseil/abseil-py | absl/logging/__init__.py | PythonFormatter.format | def format(self, record):
"""Appends the message from the record to the results of the prefix.
Args:
record: logging.LogRecord, the record to be formatted.
Returns:
The formatted string representing the record.
"""
if (not FLAGS['showprefixforinfo'].value and
FLAGS['verbosity'].value == converter.ABSL_INFO and
record.levelno == logging.INFO and
_absl_handler.python_handler.stream == sys.stderr):
prefix = ''
else:
prefix = get_absl_log_prefix(record)
return prefix + super(PythonFormatter, self).format(record) | python | def format(self, record):
"""Appends the message from the record to the results of the prefix.
Args:
record: logging.LogRecord, the record to be formatted.
Returns:
The formatted string representing the record.
"""
if (not FLAGS['showprefixforinfo'].value and
FLAGS['verbosity'].value == converter.ABSL_INFO and
record.levelno == logging.INFO and
_absl_handler.python_handler.stream == sys.stderr):
prefix = ''
else:
prefix = get_absl_log_prefix(record)
return prefix + super(PythonFormatter, self).format(record) | [
"def",
"format",
"(",
"self",
",",
"record",
")",
":",
"if",
"(",
"not",
"FLAGS",
"[",
"'showprefixforinfo'",
"]",
".",
"value",
"and",
"FLAGS",
"[",
"'verbosity'",
"]",
".",
"value",
"==",
"converter",
".",
"ABSL_INFO",
"and",
"record",
".",
"levelno",
... | Appends the message from the record to the results of the prefix.
Args:
record: logging.LogRecord, the record to be formatted.
Returns:
The formatted string representing the record. | [
"Appends",
"the",
"message",
"from",
"the",
"record",
"to",
"the",
"results",
"of",
"the",
"prefix",
"."
] | 9d73fdaa23a6b6726aa5731390f388c0c6250ee5 | https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/logging/__init__.py#L912-L928 | train | 215,327 |
abseil/abseil-py | absl/logging/__init__.py | ABSLLogger.findCaller | def findCaller(self, stack_info=False):
"""Finds the frame of the calling method on the stack.
This method skips any frames registered with the
ABSLLogger and any methods from this file, and whatever
method is currently being used to generate the prefix for the log
line. Then it returns the file name, line number, and method name
of the calling method. An optional fourth item may be returned,
callers who only need things from the first three are advised to
always slice or index the result rather than using direct unpacking
assignment.
Args:
stack_info: bool, when True, include the stack trace as a fourth item
returned. On Python 3 there are always four items returned - the
fourth will be None when this is False. On Python 2 the stdlib
base class API only returns three items. We do the same when this
new parameter is unspecified or False for compatibility.
Returns:
(filename, lineno, methodname[, sinfo]) of the calling method.
"""
f_to_skip = ABSLLogger._frames_to_skip
# Use sys._getframe(2) instead of logging.currentframe(), it's slightly
# faster because there is one less frame to traverse.
frame = sys._getframe(2) # pylint: disable=protected-access
while frame:
code = frame.f_code
if (_LOGGING_FILE_PREFIX not in code.co_filename and
(code.co_filename, code.co_name,
code.co_firstlineno) not in f_to_skip and
(code.co_filename, code.co_name) not in f_to_skip):
if six.PY2 and not stack_info:
return (code.co_filename, frame.f_lineno, code.co_name)
else:
sinfo = None
if stack_info:
out = io.StringIO()
out.write(u'Stack (most recent call last):\n')
traceback.print_stack(frame, file=out)
sinfo = out.getvalue().rstrip(u'\n')
return (code.co_filename, frame.f_lineno, code.co_name, sinfo)
frame = frame.f_back | python | def findCaller(self, stack_info=False):
"""Finds the frame of the calling method on the stack.
This method skips any frames registered with the
ABSLLogger and any methods from this file, and whatever
method is currently being used to generate the prefix for the log
line. Then it returns the file name, line number, and method name
of the calling method. An optional fourth item may be returned,
callers who only need things from the first three are advised to
always slice or index the result rather than using direct unpacking
assignment.
Args:
stack_info: bool, when True, include the stack trace as a fourth item
returned. On Python 3 there are always four items returned - the
fourth will be None when this is False. On Python 2 the stdlib
base class API only returns three items. We do the same when this
new parameter is unspecified or False for compatibility.
Returns:
(filename, lineno, methodname[, sinfo]) of the calling method.
"""
f_to_skip = ABSLLogger._frames_to_skip
# Use sys._getframe(2) instead of logging.currentframe(), it's slightly
# faster because there is one less frame to traverse.
frame = sys._getframe(2) # pylint: disable=protected-access
while frame:
code = frame.f_code
if (_LOGGING_FILE_PREFIX not in code.co_filename and
(code.co_filename, code.co_name,
code.co_firstlineno) not in f_to_skip and
(code.co_filename, code.co_name) not in f_to_skip):
if six.PY2 and not stack_info:
return (code.co_filename, frame.f_lineno, code.co_name)
else:
sinfo = None
if stack_info:
out = io.StringIO()
out.write(u'Stack (most recent call last):\n')
traceback.print_stack(frame, file=out)
sinfo = out.getvalue().rstrip(u'\n')
return (code.co_filename, frame.f_lineno, code.co_name, sinfo)
frame = frame.f_back | [
"def",
"findCaller",
"(",
"self",
",",
"stack_info",
"=",
"False",
")",
":",
"f_to_skip",
"=",
"ABSLLogger",
".",
"_frames_to_skip",
"# Use sys._getframe(2) instead of logging.currentframe(), it's slightly",
"# faster because there is one less frame to traverse.",
"frame",
"=",
... | Finds the frame of the calling method on the stack.
This method skips any frames registered with the
ABSLLogger and any methods from this file, and whatever
method is currently being used to generate the prefix for the log
line. Then it returns the file name, line number, and method name
of the calling method. An optional fourth item may be returned,
callers who only need things from the first three are advised to
always slice or index the result rather than using direct unpacking
assignment.
Args:
stack_info: bool, when True, include the stack trace as a fourth item
returned. On Python 3 there are always four items returned - the
fourth will be None when this is False. On Python 2 the stdlib
base class API only returns three items. We do the same when this
new parameter is unspecified or False for compatibility.
Returns:
(filename, lineno, methodname[, sinfo]) of the calling method. | [
"Finds",
"the",
"frame",
"of",
"the",
"calling",
"method",
"on",
"the",
"stack",
"."
] | 9d73fdaa23a6b6726aa5731390f388c0c6250ee5 | https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/logging/__init__.py#L945-L988 | train | 215,328 |
abseil/abseil-py | absl/logging/__init__.py | ABSLLogger.fatal | def fatal(self, msg, *args, **kwargs):
"""Logs 'msg % args' with severity 'FATAL'."""
self.log(logging.FATAL, msg, *args, **kwargs) | python | def fatal(self, msg, *args, **kwargs):
"""Logs 'msg % args' with severity 'FATAL'."""
self.log(logging.FATAL, msg, *args, **kwargs) | [
"def",
"fatal",
"(",
"self",
",",
"msg",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"log",
"(",
"logging",
".",
"FATAL",
",",
"msg",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Logs 'msg % args' with severity 'FATAL'. | [
"Logs",
"msg",
"%",
"args",
"with",
"severity",
"FATAL",
"."
] | 9d73fdaa23a6b6726aa5731390f388c0c6250ee5 | https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/logging/__init__.py#L994-L996 | train | 215,329 |
abseil/abseil-py | absl/logging/__init__.py | ABSLLogger.warn | def warn(self, msg, *args, **kwargs):
"""Logs 'msg % args' with severity 'WARN'."""
if six.PY3:
warnings.warn("The 'warn' method is deprecated, use 'warning' instead",
DeprecationWarning, 2)
self.log(logging.WARN, msg, *args, **kwargs) | python | def warn(self, msg, *args, **kwargs):
"""Logs 'msg % args' with severity 'WARN'."""
if six.PY3:
warnings.warn("The 'warn' method is deprecated, use 'warning' instead",
DeprecationWarning, 2)
self.log(logging.WARN, msg, *args, **kwargs) | [
"def",
"warn",
"(",
"self",
",",
"msg",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"six",
".",
"PY3",
":",
"warnings",
".",
"warn",
"(",
"\"The 'warn' method is deprecated, use 'warning' instead\"",
",",
"DeprecationWarning",
",",
"2",
")",
... | Logs 'msg % args' with severity 'WARN'. | [
"Logs",
"msg",
"%",
"args",
"with",
"severity",
"WARN",
"."
] | 9d73fdaa23a6b6726aa5731390f388c0c6250ee5 | https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/logging/__init__.py#L1002-L1007 | train | 215,330 |
abseil/abseil-py | absl/logging/__init__.py | ABSLLogger.log | def log(self, level, msg, *args, **kwargs):
"""Logs a message at a cetain level substituting in the supplied arguments.
This method behaves differently in python and c++ modes.
Args:
level: int, the standard logging level at which to log the message.
msg: str, the text of the message to log.
*args: The arguments to substitute in the message.
**kwargs: The keyword arguments to substitute in the message.
"""
if level >= logging.FATAL:
# Add property to the LogRecord created by this logger.
# This will be used by the ABSLHandler to determine whether it should
# treat CRITICAL/FATAL logs as really FATAL.
extra = kwargs.setdefault('extra', {})
extra[_ABSL_LOG_FATAL] = True
super(ABSLLogger, self).log(level, msg, *args, **kwargs) | python | def log(self, level, msg, *args, **kwargs):
"""Logs a message at a cetain level substituting in the supplied arguments.
This method behaves differently in python and c++ modes.
Args:
level: int, the standard logging level at which to log the message.
msg: str, the text of the message to log.
*args: The arguments to substitute in the message.
**kwargs: The keyword arguments to substitute in the message.
"""
if level >= logging.FATAL:
# Add property to the LogRecord created by this logger.
# This will be used by the ABSLHandler to determine whether it should
# treat CRITICAL/FATAL logs as really FATAL.
extra = kwargs.setdefault('extra', {})
extra[_ABSL_LOG_FATAL] = True
super(ABSLLogger, self).log(level, msg, *args, **kwargs) | [
"def",
"log",
"(",
"self",
",",
"level",
",",
"msg",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"level",
">=",
"logging",
".",
"FATAL",
":",
"# Add property to the LogRecord created by this logger.",
"# This will be used by the ABSLHandler to determi... | Logs a message at a cetain level substituting in the supplied arguments.
This method behaves differently in python and c++ modes.
Args:
level: int, the standard logging level at which to log the message.
msg: str, the text of the message to log.
*args: The arguments to substitute in the message.
**kwargs: The keyword arguments to substitute in the message. | [
"Logs",
"a",
"message",
"at",
"a",
"cetain",
"level",
"substituting",
"in",
"the",
"supplied",
"arguments",
"."
] | 9d73fdaa23a6b6726aa5731390f388c0c6250ee5 | https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/logging/__init__.py#L1021-L1038 | train | 215,331 |
abseil/abseil-py | absl/logging/__init__.py | ABSLLogger.register_frame_to_skip | def register_frame_to_skip(cls, file_name, function_name, line_number=None):
"""Registers a function name to skip when walking the stack.
The ABSLLogger sometimes skips method calls on the stack
to make the log messages meaningful in their appropriate context.
This method registers a function from a particular file as one
which should be skipped.
Args:
file_name: str, the name of the file that contains the function.
function_name: str, the name of the function to skip.
line_number: int, if provided, only the function with this starting line
number will be skipped. Otherwise, all functions with the same name
in the file will be skipped.
"""
if line_number is not None:
cls._frames_to_skip.add((file_name, function_name, line_number))
else:
cls._frames_to_skip.add((file_name, function_name)) | python | def register_frame_to_skip(cls, file_name, function_name, line_number=None):
"""Registers a function name to skip when walking the stack.
The ABSLLogger sometimes skips method calls on the stack
to make the log messages meaningful in their appropriate context.
This method registers a function from a particular file as one
which should be skipped.
Args:
file_name: str, the name of the file that contains the function.
function_name: str, the name of the function to skip.
line_number: int, if provided, only the function with this starting line
number will be skipped. Otherwise, all functions with the same name
in the file will be skipped.
"""
if line_number is not None:
cls._frames_to_skip.add((file_name, function_name, line_number))
else:
cls._frames_to_skip.add((file_name, function_name)) | [
"def",
"register_frame_to_skip",
"(",
"cls",
",",
"file_name",
",",
"function_name",
",",
"line_number",
"=",
"None",
")",
":",
"if",
"line_number",
"is",
"not",
"None",
":",
"cls",
".",
"_frames_to_skip",
".",
"add",
"(",
"(",
"file_name",
",",
"function_na... | Registers a function name to skip when walking the stack.
The ABSLLogger sometimes skips method calls on the stack
to make the log messages meaningful in their appropriate context.
This method registers a function from a particular file as one
which should be skipped.
Args:
file_name: str, the name of the file that contains the function.
function_name: str, the name of the function to skip.
line_number: int, if provided, only the function with this starting line
number will be skipped. Otherwise, all functions with the same name
in the file will be skipped. | [
"Registers",
"a",
"function",
"name",
"to",
"skip",
"when",
"walking",
"the",
"stack",
"."
] | 9d73fdaa23a6b6726aa5731390f388c0c6250ee5 | https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/logging/__init__.py#L1058-L1076 | train | 215,332 |
abseil/abseil-py | absl/flags/argparse_flags.py | _is_undefok | def _is_undefok(arg, undefok_names):
"""Returns whether we can ignore arg based on a set of undefok flag names."""
if not arg.startswith('-'):
return False
if arg.startswith('--'):
arg_without_dash = arg[2:]
else:
arg_without_dash = arg[1:]
if '=' in arg_without_dash:
name, _ = arg_without_dash.split('=', 1)
else:
name = arg_without_dash
if name in undefok_names:
return True
return False | python | def _is_undefok(arg, undefok_names):
"""Returns whether we can ignore arg based on a set of undefok flag names."""
if not arg.startswith('-'):
return False
if arg.startswith('--'):
arg_without_dash = arg[2:]
else:
arg_without_dash = arg[1:]
if '=' in arg_without_dash:
name, _ = arg_without_dash.split('=', 1)
else:
name = arg_without_dash
if name in undefok_names:
return True
return False | [
"def",
"_is_undefok",
"(",
"arg",
",",
"undefok_names",
")",
":",
"if",
"not",
"arg",
".",
"startswith",
"(",
"'-'",
")",
":",
"return",
"False",
"if",
"arg",
".",
"startswith",
"(",
"'--'",
")",
":",
"arg_without_dash",
"=",
"arg",
"[",
"2",
":",
"]... | Returns whether we can ignore arg based on a set of undefok flag names. | [
"Returns",
"whether",
"we",
"can",
"ignore",
"arg",
"based",
"on",
"a",
"set",
"of",
"undefok",
"flag",
"names",
"."
] | 9d73fdaa23a6b6726aa5731390f388c0c6250ee5 | https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/flags/argparse_flags.py#L358-L372 | train | 215,333 |
abseil/abseil-py | absl/flags/argparse_flags.py | ArgumentParser._define_absl_flags | def _define_absl_flags(self, absl_flags):
"""Defines flags from absl_flags."""
key_flags = set(absl_flags.get_key_flags_for_module(sys.argv[0]))
for name in absl_flags:
if name in _BUILT_IN_FLAGS:
# Do not inherit built-in flags.
continue
flag_instance = absl_flags[name]
# Each flags with short_name appears in FLAGS twice, so only define
# when the dictionary key is equal to the regular name.
if name == flag_instance.name:
# Suppress the flag in the help short message if it's not a main
# module's key flag.
suppress = flag_instance not in key_flags
self._define_absl_flag(flag_instance, suppress) | python | def _define_absl_flags(self, absl_flags):
"""Defines flags from absl_flags."""
key_flags = set(absl_flags.get_key_flags_for_module(sys.argv[0]))
for name in absl_flags:
if name in _BUILT_IN_FLAGS:
# Do not inherit built-in flags.
continue
flag_instance = absl_flags[name]
# Each flags with short_name appears in FLAGS twice, so only define
# when the dictionary key is equal to the regular name.
if name == flag_instance.name:
# Suppress the flag in the help short message if it's not a main
# module's key flag.
suppress = flag_instance not in key_flags
self._define_absl_flag(flag_instance, suppress) | [
"def",
"_define_absl_flags",
"(",
"self",
",",
"absl_flags",
")",
":",
"key_flags",
"=",
"set",
"(",
"absl_flags",
".",
"get_key_flags_for_module",
"(",
"sys",
".",
"argv",
"[",
"0",
"]",
")",
")",
"for",
"name",
"in",
"absl_flags",
":",
"if",
"name",
"i... | Defines flags from absl_flags. | [
"Defines",
"flags",
"from",
"absl_flags",
"."
] | 9d73fdaa23a6b6726aa5731390f388c0c6250ee5 | https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/flags/argparse_flags.py#L196-L210 | train | 215,334 |
abseil/abseil-py | absl/flags/argparse_flags.py | ArgumentParser._define_absl_flag | def _define_absl_flag(self, flag_instance, suppress):
"""Defines a flag from the flag_instance."""
flag_name = flag_instance.name
short_name = flag_instance.short_name
argument_names = ['--' + flag_name]
if short_name:
argument_names.insert(0, '-' + short_name)
if suppress:
helptext = argparse.SUPPRESS
else:
# argparse help string uses %-formatting. Escape the literal %'s.
helptext = flag_instance.help.replace('%', '%%')
if flag_instance.boolean:
# Only add the `no` form to the long name.
argument_names.append('--no' + flag_name)
self.add_argument(
*argument_names, action=_BooleanFlagAction, help=helptext,
metavar=flag_instance.name.upper(),
flag_instance=flag_instance)
else:
self.add_argument(
*argument_names, action=_FlagAction, help=helptext,
metavar=flag_instance.name.upper(),
flag_instance=flag_instance) | python | def _define_absl_flag(self, flag_instance, suppress):
"""Defines a flag from the flag_instance."""
flag_name = flag_instance.name
short_name = flag_instance.short_name
argument_names = ['--' + flag_name]
if short_name:
argument_names.insert(0, '-' + short_name)
if suppress:
helptext = argparse.SUPPRESS
else:
# argparse help string uses %-formatting. Escape the literal %'s.
helptext = flag_instance.help.replace('%', '%%')
if flag_instance.boolean:
# Only add the `no` form to the long name.
argument_names.append('--no' + flag_name)
self.add_argument(
*argument_names, action=_BooleanFlagAction, help=helptext,
metavar=flag_instance.name.upper(),
flag_instance=flag_instance)
else:
self.add_argument(
*argument_names, action=_FlagAction, help=helptext,
metavar=flag_instance.name.upper(),
flag_instance=flag_instance) | [
"def",
"_define_absl_flag",
"(",
"self",
",",
"flag_instance",
",",
"suppress",
")",
":",
"flag_name",
"=",
"flag_instance",
".",
"name",
"short_name",
"=",
"flag_instance",
".",
"short_name",
"argument_names",
"=",
"[",
"'--'",
"+",
"flag_name",
"]",
"if",
"s... | Defines a flag from the flag_instance. | [
"Defines",
"a",
"flag",
"from",
"the",
"flag_instance",
"."
] | 9d73fdaa23a6b6726aa5731390f388c0c6250ee5 | https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/flags/argparse_flags.py#L212-L235 | train | 215,335 |
abseil/abseil-py | absl/flags/_helpers.py | get_module_object_and_name | def get_module_object_and_name(globals_dict):
"""Returns the module that defines a global environment, and its name.
Args:
globals_dict: A dictionary that should correspond to an environment
providing the values of the globals.
Returns:
_ModuleObjectAndName - pair of module object & module name.
Returns (None, None) if the module could not be identified.
"""
name = globals_dict.get('__name__', None)
module = sys.modules.get(name, None)
# Pick a more informative name for the main module.
return _ModuleObjectAndName(module,
(sys.argv[0] if name == '__main__' else name)) | python | def get_module_object_and_name(globals_dict):
"""Returns the module that defines a global environment, and its name.
Args:
globals_dict: A dictionary that should correspond to an environment
providing the values of the globals.
Returns:
_ModuleObjectAndName - pair of module object & module name.
Returns (None, None) if the module could not be identified.
"""
name = globals_dict.get('__name__', None)
module = sys.modules.get(name, None)
# Pick a more informative name for the main module.
return _ModuleObjectAndName(module,
(sys.argv[0] if name == '__main__' else name)) | [
"def",
"get_module_object_and_name",
"(",
"globals_dict",
")",
":",
"name",
"=",
"globals_dict",
".",
"get",
"(",
"'__name__'",
",",
"None",
")",
"module",
"=",
"sys",
".",
"modules",
".",
"get",
"(",
"name",
",",
"None",
")",
"# Pick a more informative name f... | Returns the module that defines a global environment, and its name.
Args:
globals_dict: A dictionary that should correspond to an environment
providing the values of the globals.
Returns:
_ModuleObjectAndName - pair of module object & module name.
Returns (None, None) if the module could not be identified. | [
"Returns",
"the",
"module",
"that",
"defines",
"a",
"global",
"environment",
"and",
"its",
"name",
"."
] | 9d73fdaa23a6b6726aa5731390f388c0c6250ee5 | https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/flags/_helpers.py#L90-L105 | train | 215,336 |
abseil/abseil-py | absl/flags/_helpers.py | create_xml_dom_element | def create_xml_dom_element(doc, name, value):
"""Returns an XML DOM element with name and text value.
Args:
doc: minidom.Document, the DOM document it should create nodes from.
name: str, the tag of XML element.
value: object, whose string representation will be used
as the value of the XML element. Illegal or highly discouraged xml 1.0
characters are stripped.
Returns:
An instance of minidom.Element.
"""
s = str_or_unicode(value)
if six.PY2 and not isinstance(s, unicode):
# Get a valid unicode string.
s = s.decode('utf-8', 'ignore')
if isinstance(value, bool):
# Display boolean values as the C++ flag library does: no caps.
s = s.lower()
# Remove illegal xml characters.
s = _ILLEGAL_XML_CHARS_REGEX.sub(u'', s)
e = doc.createElement(name)
e.appendChild(doc.createTextNode(s))
return e | python | def create_xml_dom_element(doc, name, value):
"""Returns an XML DOM element with name and text value.
Args:
doc: minidom.Document, the DOM document it should create nodes from.
name: str, the tag of XML element.
value: object, whose string representation will be used
as the value of the XML element. Illegal or highly discouraged xml 1.0
characters are stripped.
Returns:
An instance of minidom.Element.
"""
s = str_or_unicode(value)
if six.PY2 and not isinstance(s, unicode):
# Get a valid unicode string.
s = s.decode('utf-8', 'ignore')
if isinstance(value, bool):
# Display boolean values as the C++ flag library does: no caps.
s = s.lower()
# Remove illegal xml characters.
s = _ILLEGAL_XML_CHARS_REGEX.sub(u'', s)
e = doc.createElement(name)
e.appendChild(doc.createTextNode(s))
return e | [
"def",
"create_xml_dom_element",
"(",
"doc",
",",
"name",
",",
"value",
")",
":",
"s",
"=",
"str_or_unicode",
"(",
"value",
")",
"if",
"six",
".",
"PY2",
"and",
"not",
"isinstance",
"(",
"s",
",",
"unicode",
")",
":",
"# Get a valid unicode string.",
"s",
... | Returns an XML DOM element with name and text value.
Args:
doc: minidom.Document, the DOM document it should create nodes from.
name: str, the tag of XML element.
value: object, whose string representation will be used
as the value of the XML element. Illegal or highly discouraged xml 1.0
characters are stripped.
Returns:
An instance of minidom.Element. | [
"Returns",
"an",
"XML",
"DOM",
"element",
"with",
"name",
"and",
"text",
"value",
"."
] | 9d73fdaa23a6b6726aa5731390f388c0c6250ee5 | https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/flags/_helpers.py#L161-L186 | train | 215,337 |
abseil/abseil-py | absl/flags/_helpers.py | get_help_width | def get_help_width():
"""Returns the integer width of help lines that is used in TextWrap."""
if not sys.stdout.isatty() or termios is None or fcntl is None:
return _DEFAULT_HELP_WIDTH
try:
data = fcntl.ioctl(sys.stdout, termios.TIOCGWINSZ, '1234')
columns = struct.unpack('hh', data)[1]
# Emacs mode returns 0.
# Here we assume that any value below 40 is unreasonable.
if columns >= _MIN_HELP_WIDTH:
return columns
# Returning an int as default is fine, int(int) just return the int.
return int(os.getenv('COLUMNS', _DEFAULT_HELP_WIDTH))
except (TypeError, IOError, struct.error):
return _DEFAULT_HELP_WIDTH | python | def get_help_width():
"""Returns the integer width of help lines that is used in TextWrap."""
if not sys.stdout.isatty() or termios is None or fcntl is None:
return _DEFAULT_HELP_WIDTH
try:
data = fcntl.ioctl(sys.stdout, termios.TIOCGWINSZ, '1234')
columns = struct.unpack('hh', data)[1]
# Emacs mode returns 0.
# Here we assume that any value below 40 is unreasonable.
if columns >= _MIN_HELP_WIDTH:
return columns
# Returning an int as default is fine, int(int) just return the int.
return int(os.getenv('COLUMNS', _DEFAULT_HELP_WIDTH))
except (TypeError, IOError, struct.error):
return _DEFAULT_HELP_WIDTH | [
"def",
"get_help_width",
"(",
")",
":",
"if",
"not",
"sys",
".",
"stdout",
".",
"isatty",
"(",
")",
"or",
"termios",
"is",
"None",
"or",
"fcntl",
"is",
"None",
":",
"return",
"_DEFAULT_HELP_WIDTH",
"try",
":",
"data",
"=",
"fcntl",
".",
"ioctl",
"(",
... | Returns the integer width of help lines that is used in TextWrap. | [
"Returns",
"the",
"integer",
"width",
"of",
"help",
"lines",
"that",
"is",
"used",
"in",
"TextWrap",
"."
] | 9d73fdaa23a6b6726aa5731390f388c0c6250ee5 | https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/flags/_helpers.py#L189-L204 | train | 215,338 |
abseil/abseil-py | absl/flags/_helpers.py | get_flag_suggestions | def get_flag_suggestions(attempt, longopt_list):
"""Returns helpful similar matches for an invalid flag."""
# Don't suggest on very short strings, or if no longopts are specified.
if len(attempt) <= 2 or not longopt_list:
return []
option_names = [v.split('=')[0] for v in longopt_list]
# Find close approximations in flag prefixes.
# This also handles the case where the flag is spelled right but ambiguous.
distances = [(_damerau_levenshtein(attempt, option[0:len(attempt)]), option)
for option in option_names]
# t[0] is distance, and sorting by t[1] allows us to have stable output.
distances.sort()
least_errors, _ = distances[0]
# Don't suggest excessively bad matches.
if least_errors >= _SUGGESTION_ERROR_RATE_THRESHOLD * len(attempt):
return []
suggestions = []
for errors, name in distances:
if errors == least_errors:
suggestions.append(name)
else:
break
return suggestions | python | def get_flag_suggestions(attempt, longopt_list):
"""Returns helpful similar matches for an invalid flag."""
# Don't suggest on very short strings, or if no longopts are specified.
if len(attempt) <= 2 or not longopt_list:
return []
option_names = [v.split('=')[0] for v in longopt_list]
# Find close approximations in flag prefixes.
# This also handles the case where the flag is spelled right but ambiguous.
distances = [(_damerau_levenshtein(attempt, option[0:len(attempt)]), option)
for option in option_names]
# t[0] is distance, and sorting by t[1] allows us to have stable output.
distances.sort()
least_errors, _ = distances[0]
# Don't suggest excessively bad matches.
if least_errors >= _SUGGESTION_ERROR_RATE_THRESHOLD * len(attempt):
return []
suggestions = []
for errors, name in distances:
if errors == least_errors:
suggestions.append(name)
else:
break
return suggestions | [
"def",
"get_flag_suggestions",
"(",
"attempt",
",",
"longopt_list",
")",
":",
"# Don't suggest on very short strings, or if no longopts are specified.",
"if",
"len",
"(",
"attempt",
")",
"<=",
"2",
"or",
"not",
"longopt_list",
":",
"return",
"[",
"]",
"option_names",
... | Returns helpful similar matches for an invalid flag. | [
"Returns",
"helpful",
"similar",
"matches",
"for",
"an",
"invalid",
"flag",
"."
] | 9d73fdaa23a6b6726aa5731390f388c0c6250ee5 | https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/flags/_helpers.py#L207-L233 | train | 215,339 |
abseil/abseil-py | absl/flags/_helpers.py | _damerau_levenshtein | def _damerau_levenshtein(a, b):
"""Returns Damerau-Levenshtein edit distance from a to b."""
memo = {}
def distance(x, y):
"""Recursively defined string distance with memoization."""
if (x, y) in memo:
return memo[x, y]
if not x:
d = len(y)
elif not y:
d = len(x)
else:
d = min(
distance(x[1:], y) + 1, # correct an insertion error
distance(x, y[1:]) + 1, # correct a deletion error
distance(x[1:], y[1:]) + (x[0] != y[0])) # correct a wrong character
if len(x) >= 2 and len(y) >= 2 and x[0] == y[1] and x[1] == y[0]:
# Correct a transposition.
t = distance(x[2:], y[2:]) + 1
if d > t:
d = t
memo[x, y] = d
return d
return distance(a, b) | python | def _damerau_levenshtein(a, b):
"""Returns Damerau-Levenshtein edit distance from a to b."""
memo = {}
def distance(x, y):
"""Recursively defined string distance with memoization."""
if (x, y) in memo:
return memo[x, y]
if not x:
d = len(y)
elif not y:
d = len(x)
else:
d = min(
distance(x[1:], y) + 1, # correct an insertion error
distance(x, y[1:]) + 1, # correct a deletion error
distance(x[1:], y[1:]) + (x[0] != y[0])) # correct a wrong character
if len(x) >= 2 and len(y) >= 2 and x[0] == y[1] and x[1] == y[0]:
# Correct a transposition.
t = distance(x[2:], y[2:]) + 1
if d > t:
d = t
memo[x, y] = d
return d
return distance(a, b) | [
"def",
"_damerau_levenshtein",
"(",
"a",
",",
"b",
")",
":",
"memo",
"=",
"{",
"}",
"def",
"distance",
"(",
"x",
",",
"y",
")",
":",
"\"\"\"Recursively defined string distance with memoization.\"\"\"",
"if",
"(",
"x",
",",
"y",
")",
"in",
"memo",
":",
"ret... | Returns Damerau-Levenshtein edit distance from a to b. | [
"Returns",
"Damerau",
"-",
"Levenshtein",
"edit",
"distance",
"from",
"a",
"to",
"b",
"."
] | 9d73fdaa23a6b6726aa5731390f388c0c6250ee5 | https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/flags/_helpers.py#L236-L261 | train | 215,340 |
abseil/abseil-py | absl/flags/_helpers.py | text_wrap | def text_wrap(text, length=None, indent='', firstline_indent=None):
"""Wraps a given text to a maximum line length and returns it.
It turns lines that only contain whitespace into empty lines, keeps new lines,
and expands tabs using 4 spaces.
Args:
text: str, text to wrap.
length: int, maximum length of a line, includes indentation.
If this is None then use get_help_width()
indent: str, indent for all but first line.
firstline_indent: str, indent for first line; if None, fall back to indent.
Returns:
str, the wrapped text.
Raises:
ValueError: Raised if indent or firstline_indent not shorter than length.
"""
# Get defaults where callee used None
if length is None:
length = get_help_width()
if indent is None:
indent = ''
if firstline_indent is None:
firstline_indent = indent
if len(indent) >= length:
raise ValueError('Length of indent exceeds length')
if len(firstline_indent) >= length:
raise ValueError('Length of first line indent exceeds length')
text = text.expandtabs(4)
result = []
# Create one wrapper for the first paragraph and one for subsequent
# paragraphs that does not have the initial wrapping.
wrapper = textwrap.TextWrapper(
width=length, initial_indent=firstline_indent, subsequent_indent=indent)
subsequent_wrapper = textwrap.TextWrapper(
width=length, initial_indent=indent, subsequent_indent=indent)
# textwrap does not have any special treatment for newlines. From the docs:
# "...newlines may appear in the middle of a line and cause strange output.
# For this reason, text should be split into paragraphs (using
# str.splitlines() or similar) which are wrapped separately."
for paragraph in (p.strip() for p in text.splitlines()):
if paragraph:
result.extend(wrapper.wrap(paragraph))
else:
result.append('') # Keep empty lines.
# Replace initial wrapper with wrapper for subsequent paragraphs.
wrapper = subsequent_wrapper
return '\n'.join(result) | python | def text_wrap(text, length=None, indent='', firstline_indent=None):
"""Wraps a given text to a maximum line length and returns it.
It turns lines that only contain whitespace into empty lines, keeps new lines,
and expands tabs using 4 spaces.
Args:
text: str, text to wrap.
length: int, maximum length of a line, includes indentation.
If this is None then use get_help_width()
indent: str, indent for all but first line.
firstline_indent: str, indent for first line; if None, fall back to indent.
Returns:
str, the wrapped text.
Raises:
ValueError: Raised if indent or firstline_indent not shorter than length.
"""
# Get defaults where callee used None
if length is None:
length = get_help_width()
if indent is None:
indent = ''
if firstline_indent is None:
firstline_indent = indent
if len(indent) >= length:
raise ValueError('Length of indent exceeds length')
if len(firstline_indent) >= length:
raise ValueError('Length of first line indent exceeds length')
text = text.expandtabs(4)
result = []
# Create one wrapper for the first paragraph and one for subsequent
# paragraphs that does not have the initial wrapping.
wrapper = textwrap.TextWrapper(
width=length, initial_indent=firstline_indent, subsequent_indent=indent)
subsequent_wrapper = textwrap.TextWrapper(
width=length, initial_indent=indent, subsequent_indent=indent)
# textwrap does not have any special treatment for newlines. From the docs:
# "...newlines may appear in the middle of a line and cause strange output.
# For this reason, text should be split into paragraphs (using
# str.splitlines() or similar) which are wrapped separately."
for paragraph in (p.strip() for p in text.splitlines()):
if paragraph:
result.extend(wrapper.wrap(paragraph))
else:
result.append('') # Keep empty lines.
# Replace initial wrapper with wrapper for subsequent paragraphs.
wrapper = subsequent_wrapper
return '\n'.join(result) | [
"def",
"text_wrap",
"(",
"text",
",",
"length",
"=",
"None",
",",
"indent",
"=",
"''",
",",
"firstline_indent",
"=",
"None",
")",
":",
"# Get defaults where callee used None",
"if",
"length",
"is",
"None",
":",
"length",
"=",
"get_help_width",
"(",
")",
"if"... | Wraps a given text to a maximum line length and returns it.
It turns lines that only contain whitespace into empty lines, keeps new lines,
and expands tabs using 4 spaces.
Args:
text: str, text to wrap.
length: int, maximum length of a line, includes indentation.
If this is None then use get_help_width()
indent: str, indent for all but first line.
firstline_indent: str, indent for first line; if None, fall back to indent.
Returns:
str, the wrapped text.
Raises:
ValueError: Raised if indent or firstline_indent not shorter than length. | [
"Wraps",
"a",
"given",
"text",
"to",
"a",
"maximum",
"line",
"length",
"and",
"returns",
"it",
"."
] | 9d73fdaa23a6b6726aa5731390f388c0c6250ee5 | https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/flags/_helpers.py#L264-L318 | train | 215,341 |
abseil/abseil-py | absl/flags/_helpers.py | trim_docstring | def trim_docstring(docstring):
"""Removes indentation from triple-quoted strings.
This is the function specified in PEP 257 to handle docstrings:
https://www.python.org/dev/peps/pep-0257/.
Args:
docstring: str, a python docstring.
Returns:
str, docstring with indentation removed.
"""
if not docstring:
return ''
# If you've got a line longer than this you have other problems...
max_indent = 1 << 29
# Convert tabs to spaces (following the normal Python rules)
# and split into a list of lines:
lines = docstring.expandtabs().splitlines()
# Determine minimum indentation (first line doesn't count):
indent = max_indent
for line in lines[1:]:
stripped = line.lstrip()
if stripped:
indent = min(indent, len(line) - len(stripped))
# Remove indentation (first line is special):
trimmed = [lines[0].strip()]
if indent < max_indent:
for line in lines[1:]:
trimmed.append(line[indent:].rstrip())
# Strip off trailing and leading blank lines:
while trimmed and not trimmed[-1]:
trimmed.pop()
while trimmed and not trimmed[0]:
trimmed.pop(0)
# Return a single string:
return '\n'.join(trimmed) | python | def trim_docstring(docstring):
"""Removes indentation from triple-quoted strings.
This is the function specified in PEP 257 to handle docstrings:
https://www.python.org/dev/peps/pep-0257/.
Args:
docstring: str, a python docstring.
Returns:
str, docstring with indentation removed.
"""
if not docstring:
return ''
# If you've got a line longer than this you have other problems...
max_indent = 1 << 29
# Convert tabs to spaces (following the normal Python rules)
# and split into a list of lines:
lines = docstring.expandtabs().splitlines()
# Determine minimum indentation (first line doesn't count):
indent = max_indent
for line in lines[1:]:
stripped = line.lstrip()
if stripped:
indent = min(indent, len(line) - len(stripped))
# Remove indentation (first line is special):
trimmed = [lines[0].strip()]
if indent < max_indent:
for line in lines[1:]:
trimmed.append(line[indent:].rstrip())
# Strip off trailing and leading blank lines:
while trimmed and not trimmed[-1]:
trimmed.pop()
while trimmed and not trimmed[0]:
trimmed.pop(0)
# Return a single string:
return '\n'.join(trimmed) | [
"def",
"trim_docstring",
"(",
"docstring",
")",
":",
"if",
"not",
"docstring",
":",
"return",
"''",
"# If you've got a line longer than this you have other problems...",
"max_indent",
"=",
"1",
"<<",
"29",
"# Convert tabs to spaces (following the normal Python rules)",
"# and s... | Removes indentation from triple-quoted strings.
This is the function specified in PEP 257 to handle docstrings:
https://www.python.org/dev/peps/pep-0257/.
Args:
docstring: str, a python docstring.
Returns:
str, docstring with indentation removed. | [
"Removes",
"indentation",
"from",
"triple",
"-",
"quoted",
"strings",
"."
] | 9d73fdaa23a6b6726aa5731390f388c0c6250ee5 | https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/flags/_helpers.py#L359-L398 | train | 215,342 |
alexa/alexa-skills-kit-sdk-for-python | ask-sdk-core/ask_sdk_core/skill.py | CustomSkill.invoke | def invoke(self, request_envelope, context):
# type: (RequestEnvelope, Any) -> ResponseEnvelope
"""Invokes the dispatcher, to handle the request envelope and
return a response envelope.
:param request_envelope: Request Envelope instance containing
request information
:type request_envelope: RequestEnvelope
:param context: Context passed during invocation
:type context: Any
:return: Response Envelope generated by handling the request
:rtype: ResponseEnvelope
"""
if (self.skill_id is not None and
request_envelope.context.system.application.application_id !=
self.skill_id):
raise AskSdkException("Skill ID Verification failed!!")
if self.api_client is not None:
api_token = request_envelope.context.system.api_access_token
api_endpoint = request_envelope.context.system.api_endpoint
api_configuration = ApiConfiguration(
serializer=self.serializer, api_client=self.api_client,
authorization_value=api_token,
api_endpoint=api_endpoint)
factory = ServiceClientFactory(api_configuration=api_configuration)
else:
factory = None
attributes_manager = AttributesManager(
request_envelope=request_envelope,
persistence_adapter=self.persistence_adapter)
handler_input = HandlerInput(
request_envelope=request_envelope,
attributes_manager=attributes_manager,
context=context,
service_client_factory=factory)
response = self.request_dispatcher.dispatch(
handler_input=handler_input)
session_attributes = None
if request_envelope.session is not None:
session_attributes = (
handler_input.attributes_manager.session_attributes)
return ResponseEnvelope(
response=response, version=RESPONSE_FORMAT_VERSION,
session_attributes=session_attributes,
user_agent=user_agent_info(
sdk_version=__version__,
custom_user_agent=self.custom_user_agent)) | python | def invoke(self, request_envelope, context):
# type: (RequestEnvelope, Any) -> ResponseEnvelope
"""Invokes the dispatcher, to handle the request envelope and
return a response envelope.
:param request_envelope: Request Envelope instance containing
request information
:type request_envelope: RequestEnvelope
:param context: Context passed during invocation
:type context: Any
:return: Response Envelope generated by handling the request
:rtype: ResponseEnvelope
"""
if (self.skill_id is not None and
request_envelope.context.system.application.application_id !=
self.skill_id):
raise AskSdkException("Skill ID Verification failed!!")
if self.api_client is not None:
api_token = request_envelope.context.system.api_access_token
api_endpoint = request_envelope.context.system.api_endpoint
api_configuration = ApiConfiguration(
serializer=self.serializer, api_client=self.api_client,
authorization_value=api_token,
api_endpoint=api_endpoint)
factory = ServiceClientFactory(api_configuration=api_configuration)
else:
factory = None
attributes_manager = AttributesManager(
request_envelope=request_envelope,
persistence_adapter=self.persistence_adapter)
handler_input = HandlerInput(
request_envelope=request_envelope,
attributes_manager=attributes_manager,
context=context,
service_client_factory=factory)
response = self.request_dispatcher.dispatch(
handler_input=handler_input)
session_attributes = None
if request_envelope.session is not None:
session_attributes = (
handler_input.attributes_manager.session_attributes)
return ResponseEnvelope(
response=response, version=RESPONSE_FORMAT_VERSION,
session_attributes=session_attributes,
user_agent=user_agent_info(
sdk_version=__version__,
custom_user_agent=self.custom_user_agent)) | [
"def",
"invoke",
"(",
"self",
",",
"request_envelope",
",",
"context",
")",
":",
"# type: (RequestEnvelope, Any) -> ResponseEnvelope",
"if",
"(",
"self",
".",
"skill_id",
"is",
"not",
"None",
"and",
"request_envelope",
".",
"context",
".",
"system",
".",
"applicat... | Invokes the dispatcher, to handle the request envelope and
return a response envelope.
:param request_envelope: Request Envelope instance containing
request information
:type request_envelope: RequestEnvelope
:param context: Context passed during invocation
:type context: Any
:return: Response Envelope generated by handling the request
:rtype: ResponseEnvelope | [
"Invokes",
"the",
"dispatcher",
"to",
"handle",
"the",
"request",
"envelope",
"and",
"return",
"a",
"response",
"envelope",
"."
] | 097b6406aa12d5ca0b825b00c936861b530cbf39 | https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-core/ask_sdk_core/skill.py#L159-L211 | train | 215,343 |
alexa/alexa-skills-kit-sdk-for-python | django-ask-sdk/django_ask_sdk/skill_adapter.py | SkillAdapter.dispatch | def dispatch(self, request, *args, **kwargs):
# type: (HttpRequest, object, object) -> HttpResponse
"""Inspect the HTTP method and delegate to the view method.
This is the default implementation of the
:py:class:`django.views.View` method, which will inspect the
HTTP method in the input request and delegate it to the
corresponding method in the view. The only allowed method on
this view is ``post``.
:param request: The input request sent to the view
:type request: django.http.HttpRequest
:return: The response from the view
:rtype: django.http.HttpResponse
:raises: :py:class:`django.http.HttpResponseNotAllowed` if the
method is invoked for other than HTTP POST request.
:py:class:`django.http.HttpResponseBadRequest` if the
request verification fails.
:py:class:`django.http.HttpResponseServerError` for any
internal exception.
"""
return super(SkillAdapter, self).dispatch(request) | python | def dispatch(self, request, *args, **kwargs):
# type: (HttpRequest, object, object) -> HttpResponse
"""Inspect the HTTP method and delegate to the view method.
This is the default implementation of the
:py:class:`django.views.View` method, which will inspect the
HTTP method in the input request and delegate it to the
corresponding method in the view. The only allowed method on
this view is ``post``.
:param request: The input request sent to the view
:type request: django.http.HttpRequest
:return: The response from the view
:rtype: django.http.HttpResponse
:raises: :py:class:`django.http.HttpResponseNotAllowed` if the
method is invoked for other than HTTP POST request.
:py:class:`django.http.HttpResponseBadRequest` if the
request verification fails.
:py:class:`django.http.HttpResponseServerError` for any
internal exception.
"""
return super(SkillAdapter, self).dispatch(request) | [
"def",
"dispatch",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# type: (HttpRequest, object, object) -> HttpResponse",
"return",
"super",
"(",
"SkillAdapter",
",",
"self",
")",
".",
"dispatch",
"(",
"request",
")"
] | Inspect the HTTP method and delegate to the view method.
This is the default implementation of the
:py:class:`django.views.View` method, which will inspect the
HTTP method in the input request and delegate it to the
corresponding method in the view. The only allowed method on
this view is ``post``.
:param request: The input request sent to the view
:type request: django.http.HttpRequest
:return: The response from the view
:rtype: django.http.HttpResponse
:raises: :py:class:`django.http.HttpResponseNotAllowed` if the
method is invoked for other than HTTP POST request.
:py:class:`django.http.HttpResponseBadRequest` if the
request verification fails.
:py:class:`django.http.HttpResponseServerError` for any
internal exception. | [
"Inspect",
"the",
"HTTP",
"method",
"and",
"delegate",
"to",
"the",
"view",
"method",
"."
] | 097b6406aa12d5ca0b825b00c936861b530cbf39 | https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/django-ask-sdk/django_ask_sdk/skill_adapter.py#L152-L173 | train | 215,344 |
alexa/alexa-skills-kit-sdk-for-python | django-ask-sdk/django_ask_sdk/skill_adapter.py | SkillAdapter.post | def post(self, request, *args, **kwargs):
# type: (HttpRequest, object, object) -> HttpResponse
"""The method that handles HTTP POST request on the view.
This method is called when the view receives a HTTP POST
request, which is generally the request sent from Alexa during
skill invocation. The request is verified through the
registered list of verifiers, before invoking the request
handlers. The method returns a
:py:class:`django.http.JsonResponse` in case of successful
skill invocation.
:param request: The input request sent by Alexa to the skill
:type request: django.http.HttpRequest
:return: The response from the skill to Alexa
:rtype: django.http.JsonResponse
:raises: :py:class:`django.http.HttpResponseBadRequest` if the
request verification fails.
:py:class:`django.http.HttpResponseServerError` for any
internal exception.
"""
try:
content = request.body.decode(
verifier_constants.CHARACTER_ENCODING)
response = self._webservice_handler.verify_request_and_dispatch(
http_request_headers=request.META, http_request_body=content)
return JsonResponse(
data=response, safe=False)
except VerificationException:
logger.exception(msg="Request verification failed")
return HttpResponseBadRequest(
content="Incoming request failed verification")
except AskSdkException:
logger.exception(msg="Skill dispatch exception")
return HttpResponseServerError(
content="Exception occurred during skill dispatch") | python | def post(self, request, *args, **kwargs):
# type: (HttpRequest, object, object) -> HttpResponse
"""The method that handles HTTP POST request on the view.
This method is called when the view receives a HTTP POST
request, which is generally the request sent from Alexa during
skill invocation. The request is verified through the
registered list of verifiers, before invoking the request
handlers. The method returns a
:py:class:`django.http.JsonResponse` in case of successful
skill invocation.
:param request: The input request sent by Alexa to the skill
:type request: django.http.HttpRequest
:return: The response from the skill to Alexa
:rtype: django.http.JsonResponse
:raises: :py:class:`django.http.HttpResponseBadRequest` if the
request verification fails.
:py:class:`django.http.HttpResponseServerError` for any
internal exception.
"""
try:
content = request.body.decode(
verifier_constants.CHARACTER_ENCODING)
response = self._webservice_handler.verify_request_and_dispatch(
http_request_headers=request.META, http_request_body=content)
return JsonResponse(
data=response, safe=False)
except VerificationException:
logger.exception(msg="Request verification failed")
return HttpResponseBadRequest(
content="Incoming request failed verification")
except AskSdkException:
logger.exception(msg="Skill dispatch exception")
return HttpResponseServerError(
content="Exception occurred during skill dispatch") | [
"def",
"post",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# type: (HttpRequest, object, object) -> HttpResponse",
"try",
":",
"content",
"=",
"request",
".",
"body",
".",
"decode",
"(",
"verifier_constants",
".",
"CHARAC... | The method that handles HTTP POST request on the view.
This method is called when the view receives a HTTP POST
request, which is generally the request sent from Alexa during
skill invocation. The request is verified through the
registered list of verifiers, before invoking the request
handlers. The method returns a
:py:class:`django.http.JsonResponse` in case of successful
skill invocation.
:param request: The input request sent by Alexa to the skill
:type request: django.http.HttpRequest
:return: The response from the skill to Alexa
:rtype: django.http.JsonResponse
:raises: :py:class:`django.http.HttpResponseBadRequest` if the
request verification fails.
:py:class:`django.http.HttpResponseServerError` for any
internal exception. | [
"The",
"method",
"that",
"handles",
"HTTP",
"POST",
"request",
"on",
"the",
"view",
"."
] | 097b6406aa12d5ca0b825b00c936861b530cbf39 | https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/django-ask-sdk/django_ask_sdk/skill_adapter.py#L175-L211 | train | 215,345 |
alexa/alexa-skills-kit-sdk-for-python | ask-sdk-core/ask_sdk_core/utils/viewport.py | get_orientation | def get_orientation(width, height):
# type: (int, int) -> Orientation
"""Get viewport orientation from given width and height.
:type width: int
:type height: int
:return: viewport orientation enum
:rtype: Orientation
"""
if width > height:
return Orientation.LANDSCAPE
elif width < height:
return Orientation.PORTRAIT
else:
return Orientation.EQUAL | python | def get_orientation(width, height):
# type: (int, int) -> Orientation
"""Get viewport orientation from given width and height.
:type width: int
:type height: int
:return: viewport orientation enum
:rtype: Orientation
"""
if width > height:
return Orientation.LANDSCAPE
elif width < height:
return Orientation.PORTRAIT
else:
return Orientation.EQUAL | [
"def",
"get_orientation",
"(",
"width",
",",
"height",
")",
":",
"# type: (int, int) -> Orientation",
"if",
"width",
">",
"height",
":",
"return",
"Orientation",
".",
"LANDSCAPE",
"elif",
"width",
"<",
"height",
":",
"return",
"Orientation",
".",
"PORTRAIT",
"el... | Get viewport orientation from given width and height.
:type width: int
:type height: int
:return: viewport orientation enum
:rtype: Orientation | [
"Get",
"viewport",
"orientation",
"from",
"given",
"width",
"and",
"height",
"."
] | 097b6406aa12d5ca0b825b00c936861b530cbf39 | https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-core/ask_sdk_core/utils/viewport.py#L84-L98 | train | 215,346 |
alexa/alexa-skills-kit-sdk-for-python | ask-sdk-core/ask_sdk_core/utils/viewport.py | get_size | def get_size(size):
# type: (int) -> Size
"""Get viewport size from given size.
:type size: int
:return: viewport size enum
:rtype: Size
"""
if size in range(0, 600):
return Size.XSMALL
elif size in range(600, 960):
return Size.SMALL
elif size in range(960, 1280):
return Size.MEDIUM
elif size in range(1280, 1920):
return Size.LARGE
elif size >= 1920:
return Size.XLARGE
raise AskSdkException("Unknown size group value: {}".format(size)) | python | def get_size(size):
# type: (int) -> Size
"""Get viewport size from given size.
:type size: int
:return: viewport size enum
:rtype: Size
"""
if size in range(0, 600):
return Size.XSMALL
elif size in range(600, 960):
return Size.SMALL
elif size in range(960, 1280):
return Size.MEDIUM
elif size in range(1280, 1920):
return Size.LARGE
elif size >= 1920:
return Size.XLARGE
raise AskSdkException("Unknown size group value: {}".format(size)) | [
"def",
"get_size",
"(",
"size",
")",
":",
"# type: (int) -> Size",
"if",
"size",
"in",
"range",
"(",
"0",
",",
"600",
")",
":",
"return",
"Size",
".",
"XSMALL",
"elif",
"size",
"in",
"range",
"(",
"600",
",",
"960",
")",
":",
"return",
"Size",
".",
... | Get viewport size from given size.
:type size: int
:return: viewport size enum
:rtype: Size | [
"Get",
"viewport",
"size",
"from",
"given",
"size",
"."
] | 097b6406aa12d5ca0b825b00c936861b530cbf39 | https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-core/ask_sdk_core/utils/viewport.py#L101-L120 | train | 215,347 |
alexa/alexa-skills-kit-sdk-for-python | ask-sdk-core/ask_sdk_core/utils/viewport.py | get_dpi_group | def get_dpi_group(dpi):
# type: (int) -> Density
"""Get viewport density group from given dpi.
:type dpi: int
:return: viewport density group enum
:rtype: Density
"""
if dpi in range(0, 121):
return Density.XLOW
elif dpi in range(121, 161):
return Density.LOW
elif dpi in range(161, 241):
return Density.MEDIUM
elif dpi in range(241, 321):
return Density.HIGH
elif dpi in range(321, 481):
return Density.XHIGH
elif dpi >= 481:
return Density.XXHIGH
raise AskSdkException("Unknown dpi group value: {}".format(dpi)) | python | def get_dpi_group(dpi):
# type: (int) -> Density
"""Get viewport density group from given dpi.
:type dpi: int
:return: viewport density group enum
:rtype: Density
"""
if dpi in range(0, 121):
return Density.XLOW
elif dpi in range(121, 161):
return Density.LOW
elif dpi in range(161, 241):
return Density.MEDIUM
elif dpi in range(241, 321):
return Density.HIGH
elif dpi in range(321, 481):
return Density.XHIGH
elif dpi >= 481:
return Density.XXHIGH
raise AskSdkException("Unknown dpi group value: {}".format(dpi)) | [
"def",
"get_dpi_group",
"(",
"dpi",
")",
":",
"# type: (int) -> Density",
"if",
"dpi",
"in",
"range",
"(",
"0",
",",
"121",
")",
":",
"return",
"Density",
".",
"XLOW",
"elif",
"dpi",
"in",
"range",
"(",
"121",
",",
"161",
")",
":",
"return",
"Density",... | Get viewport density group from given dpi.
:type dpi: int
:return: viewport density group enum
:rtype: Density | [
"Get",
"viewport",
"density",
"group",
"from",
"given",
"dpi",
"."
] | 097b6406aa12d5ca0b825b00c936861b530cbf39 | https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-core/ask_sdk_core/utils/viewport.py#L123-L144 | train | 215,348 |
alexa/alexa-skills-kit-sdk-for-python | ask-sdk-core/ask_sdk_core/utils/viewport.py | get_viewport_profile | def get_viewport_profile(request_envelope):
# type: (RequestEnvelope) -> ViewportProfile
"""Utility method, to get viewport profile.
The viewport profile is calculated using the shape, current pixel
width and height, along with the dpi.
If there is no `viewport`
value in `request_envelope.context`, then an
`ViewportProfile.UNKNOWN_VIEWPORT_PROFILE` is returned.
:param request_envelope: The alexa request envelope object
:type request_envelope: ask_sdk_model.request_envelope.RequestEnvelope
:return: Calculated Viewport Profile enum
:rtype: ViewportProfile
"""
viewport_state = request_envelope.context.viewport
if viewport_state:
shape = viewport_state.shape
current_pixel_width = int(viewport_state.current_pixel_width)
current_pixel_height = int(viewport_state.current_pixel_height)
dpi = int(viewport_state.dpi)
orientation = get_orientation(
width=current_pixel_width, height=current_pixel_height)
dpi_group = get_dpi_group(dpi=dpi)
pixel_width_size_group = get_size(size=current_pixel_width)
pixel_height_size_group = get_size(size=current_pixel_height)
if (shape is Shape.ROUND
and orientation is Orientation.EQUAL
and dpi_group is Density.LOW
and pixel_width_size_group is Size.XSMALL
and pixel_height_size_group is Size.XSMALL):
return ViewportProfile.HUB_ROUND_SMALL
elif (shape is Shape.RECTANGLE
and orientation is Orientation.LANDSCAPE
and dpi_group is Density.LOW
and pixel_width_size_group <= Size.MEDIUM
and pixel_height_size_group <= Size.SMALL):
return ViewportProfile.HUB_LANDSCAPE_MEDIUM
elif (shape is Shape.RECTANGLE
and orientation is Orientation.LANDSCAPE
and dpi_group is Density.LOW
and pixel_width_size_group >= Size.LARGE
and pixel_height_size_group >= Size.SMALL):
return ViewportProfile.HUB_LANDSCAPE_LARGE
elif (shape is Shape.RECTANGLE
and orientation is Orientation.LANDSCAPE
and dpi_group is Density.MEDIUM
and pixel_width_size_group >= Size.MEDIUM
and pixel_height_size_group >= Size.SMALL):
return ViewportProfile.MOBILE_LANDSCAPE_MEDIUM
elif (shape is Shape.RECTANGLE
and orientation is Orientation.PORTRAIT
and dpi_group is Density.MEDIUM
and pixel_width_size_group >= Size.SMALL
and pixel_height_size_group >= Size.MEDIUM):
return ViewportProfile.MOBILE_PORTRAIT_MEDIUM
elif (shape is Shape.RECTANGLE
and orientation is Orientation.LANDSCAPE
and dpi_group is Density.MEDIUM
and pixel_width_size_group >= Size.SMALL
and pixel_height_size_group >= Size.XSMALL):
return ViewportProfile.MOBILE_LANDSCAPE_SMALL
elif (shape is Shape.RECTANGLE
and orientation is Orientation.PORTRAIT
and dpi_group is Density.MEDIUM
and pixel_width_size_group >= Size.XSMALL
and pixel_height_size_group >= Size.SMALL):
return ViewportProfile.MOBILE_PORTRAIT_SMALL
elif (shape is Shape.RECTANGLE
and orientation is Orientation.LANDSCAPE
and dpi_group >= Density.HIGH
and pixel_width_size_group >= Size.XLARGE
and pixel_height_size_group >= Size.MEDIUM):
return ViewportProfile.TV_LANDSCAPE_XLARGE
elif (shape is Shape.RECTANGLE
and orientation is Orientation.PORTRAIT
and dpi_group >= Density.HIGH
and pixel_width_size_group is Size.XSMALL
and pixel_height_size_group is Size.XLARGE):
return ViewportProfile.TV_PORTRAIT_MEDIUM
elif (shape is Shape.RECTANGLE
and orientation is Orientation.LANDSCAPE
and dpi_group >= Density.HIGH
and pixel_width_size_group is Size.MEDIUM
and pixel_height_size_group is Size.SMALL):
return ViewportProfile.TV_LANDSCAPE_MEDIUM
return ViewportProfile.UNKNOWN_VIEWPORT_PROFILE | python | def get_viewport_profile(request_envelope):
# type: (RequestEnvelope) -> ViewportProfile
"""Utility method, to get viewport profile.
The viewport profile is calculated using the shape, current pixel
width and height, along with the dpi.
If there is no `viewport`
value in `request_envelope.context`, then an
`ViewportProfile.UNKNOWN_VIEWPORT_PROFILE` is returned.
:param request_envelope: The alexa request envelope object
:type request_envelope: ask_sdk_model.request_envelope.RequestEnvelope
:return: Calculated Viewport Profile enum
:rtype: ViewportProfile
"""
viewport_state = request_envelope.context.viewport
if viewport_state:
shape = viewport_state.shape
current_pixel_width = int(viewport_state.current_pixel_width)
current_pixel_height = int(viewport_state.current_pixel_height)
dpi = int(viewport_state.dpi)
orientation = get_orientation(
width=current_pixel_width, height=current_pixel_height)
dpi_group = get_dpi_group(dpi=dpi)
pixel_width_size_group = get_size(size=current_pixel_width)
pixel_height_size_group = get_size(size=current_pixel_height)
if (shape is Shape.ROUND
and orientation is Orientation.EQUAL
and dpi_group is Density.LOW
and pixel_width_size_group is Size.XSMALL
and pixel_height_size_group is Size.XSMALL):
return ViewportProfile.HUB_ROUND_SMALL
elif (shape is Shape.RECTANGLE
and orientation is Orientation.LANDSCAPE
and dpi_group is Density.LOW
and pixel_width_size_group <= Size.MEDIUM
and pixel_height_size_group <= Size.SMALL):
return ViewportProfile.HUB_LANDSCAPE_MEDIUM
elif (shape is Shape.RECTANGLE
and orientation is Orientation.LANDSCAPE
and dpi_group is Density.LOW
and pixel_width_size_group >= Size.LARGE
and pixel_height_size_group >= Size.SMALL):
return ViewportProfile.HUB_LANDSCAPE_LARGE
elif (shape is Shape.RECTANGLE
and orientation is Orientation.LANDSCAPE
and dpi_group is Density.MEDIUM
and pixel_width_size_group >= Size.MEDIUM
and pixel_height_size_group >= Size.SMALL):
return ViewportProfile.MOBILE_LANDSCAPE_MEDIUM
elif (shape is Shape.RECTANGLE
and orientation is Orientation.PORTRAIT
and dpi_group is Density.MEDIUM
and pixel_width_size_group >= Size.SMALL
and pixel_height_size_group >= Size.MEDIUM):
return ViewportProfile.MOBILE_PORTRAIT_MEDIUM
elif (shape is Shape.RECTANGLE
and orientation is Orientation.LANDSCAPE
and dpi_group is Density.MEDIUM
and pixel_width_size_group >= Size.SMALL
and pixel_height_size_group >= Size.XSMALL):
return ViewportProfile.MOBILE_LANDSCAPE_SMALL
elif (shape is Shape.RECTANGLE
and orientation is Orientation.PORTRAIT
and dpi_group is Density.MEDIUM
and pixel_width_size_group >= Size.XSMALL
and pixel_height_size_group >= Size.SMALL):
return ViewportProfile.MOBILE_PORTRAIT_SMALL
elif (shape is Shape.RECTANGLE
and orientation is Orientation.LANDSCAPE
and dpi_group >= Density.HIGH
and pixel_width_size_group >= Size.XLARGE
and pixel_height_size_group >= Size.MEDIUM):
return ViewportProfile.TV_LANDSCAPE_XLARGE
elif (shape is Shape.RECTANGLE
and orientation is Orientation.PORTRAIT
and dpi_group >= Density.HIGH
and pixel_width_size_group is Size.XSMALL
and pixel_height_size_group is Size.XLARGE):
return ViewportProfile.TV_PORTRAIT_MEDIUM
elif (shape is Shape.RECTANGLE
and orientation is Orientation.LANDSCAPE
and dpi_group >= Density.HIGH
and pixel_width_size_group is Size.MEDIUM
and pixel_height_size_group is Size.SMALL):
return ViewportProfile.TV_LANDSCAPE_MEDIUM
return ViewportProfile.UNKNOWN_VIEWPORT_PROFILE | [
"def",
"get_viewport_profile",
"(",
"request_envelope",
")",
":",
"# type: (RequestEnvelope) -> ViewportProfile",
"viewport_state",
"=",
"request_envelope",
".",
"context",
".",
"viewport",
"if",
"viewport_state",
":",
"shape",
"=",
"viewport_state",
".",
"shape",
"curren... | Utility method, to get viewport profile.
The viewport profile is calculated using the shape, current pixel
width and height, along with the dpi.
If there is no `viewport`
value in `request_envelope.context`, then an
`ViewportProfile.UNKNOWN_VIEWPORT_PROFILE` is returned.
:param request_envelope: The alexa request envelope object
:type request_envelope: ask_sdk_model.request_envelope.RequestEnvelope
:return: Calculated Viewport Profile enum
:rtype: ViewportProfile | [
"Utility",
"method",
"to",
"get",
"viewport",
"profile",
"."
] | 097b6406aa12d5ca0b825b00c936861b530cbf39 | https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-core/ask_sdk_core/utils/viewport.py#L147-L246 | train | 215,349 |
alexa/alexa-skills-kit-sdk-for-python | ask-sdk-runtime/ask_sdk_runtime/skill_builder.py | AbstractSkillBuilder.request_handler | def request_handler(self, can_handle_func):
# type: (Callable[[Input], bool]) -> Callable
"""Decorator that can be used to add request handlers easily to
the builder.
The can_handle_func has to be a Callable instance, which takes
a single parameter and no varargs or kwargs. This is because
of the RequestHandler class signature restrictions. The
returned wrapper function can be applied as a decorator on any
function that returns a response object by the skill. The
function should follow the signature of the handle function in
:py:class:`ask_sdk_runtime.dispatch_components.request_components.AbstractRequestHandler`
class.
:param can_handle_func: The function that validates if the
request can be handled.
:type can_handle_func: Callable[[Input], bool]
:return: Wrapper function that can be decorated on a handle
function.
"""
def wrapper(handle_func):
if not callable(can_handle_func) or not callable(handle_func):
raise SkillBuilderException(
"Request Handler can_handle_func and handle_func "
"input parameters should be callable")
class_attributes = {
"can_handle": lambda self, handler_input: can_handle_func(
handler_input),
"handle": lambda self, handler_input: handle_func(
handler_input)
}
request_handler_class = type(
"RequestHandler{}".format(
handle_func.__name__.title().replace("_", "")),
(AbstractRequestHandler,), class_attributes)
self.add_request_handler(request_handler=request_handler_class())
return wrapper | python | def request_handler(self, can_handle_func):
# type: (Callable[[Input], bool]) -> Callable
"""Decorator that can be used to add request handlers easily to
the builder.
The can_handle_func has to be a Callable instance, which takes
a single parameter and no varargs or kwargs. This is because
of the RequestHandler class signature restrictions. The
returned wrapper function can be applied as a decorator on any
function that returns a response object by the skill. The
function should follow the signature of the handle function in
:py:class:`ask_sdk_runtime.dispatch_components.request_components.AbstractRequestHandler`
class.
:param can_handle_func: The function that validates if the
request can be handled.
:type can_handle_func: Callable[[Input], bool]
:return: Wrapper function that can be decorated on a handle
function.
"""
def wrapper(handle_func):
if not callable(can_handle_func) or not callable(handle_func):
raise SkillBuilderException(
"Request Handler can_handle_func and handle_func "
"input parameters should be callable")
class_attributes = {
"can_handle": lambda self, handler_input: can_handle_func(
handler_input),
"handle": lambda self, handler_input: handle_func(
handler_input)
}
request_handler_class = type(
"RequestHandler{}".format(
handle_func.__name__.title().replace("_", "")),
(AbstractRequestHandler,), class_attributes)
self.add_request_handler(request_handler=request_handler_class())
return wrapper | [
"def",
"request_handler",
"(",
"self",
",",
"can_handle_func",
")",
":",
"# type: (Callable[[Input], bool]) -> Callable",
"def",
"wrapper",
"(",
"handle_func",
")",
":",
"if",
"not",
"callable",
"(",
"can_handle_func",
")",
"or",
"not",
"callable",
"(",
"handle_func... | Decorator that can be used to add request handlers easily to
the builder.
The can_handle_func has to be a Callable instance, which takes
a single parameter and no varargs or kwargs. This is because
of the RequestHandler class signature restrictions. The
returned wrapper function can be applied as a decorator on any
function that returns a response object by the skill. The
function should follow the signature of the handle function in
:py:class:`ask_sdk_runtime.dispatch_components.request_components.AbstractRequestHandler`
class.
:param can_handle_func: The function that validates if the
request can be handled.
:type can_handle_func: Callable[[Input], bool]
:return: Wrapper function that can be decorated on a handle
function. | [
"Decorator",
"that",
"can",
"be",
"used",
"to",
"add",
"request",
"handlers",
"easily",
"to",
"the",
"builder",
"."
] | 097b6406aa12d5ca0b825b00c936861b530cbf39 | https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-runtime/ask_sdk_runtime/skill_builder.py#L97-L136 | train | 215,350 |
alexa/alexa-skills-kit-sdk-for-python | ask-sdk-runtime/ask_sdk_runtime/skill_builder.py | AbstractSkillBuilder.exception_handler | def exception_handler(self, can_handle_func):
# type: (Callable[[Input, Exception], bool]) -> Callable
"""Decorator that can be used to add exception handlers easily
to the builder.
The can_handle_func has to be a Callable instance, which takes
two parameters and no varargs or kwargs. This is because of the
ExceptionHandler class signature restrictions. The returned
wrapper function can be applied as a decorator on any function
that processes the exception raised during dispatcher and
returns a response object by the skill. The function should
follow the signature of the handle function in
:py:class:`ask_sdk_runtime.dispatch_components.exception_components.AbstractExceptionHandler`
class.
:param can_handle_func: The function that validates if the
exception can be handled.
:type can_handle_func: Callable[[Input, Exception], bool]
:return: Wrapper function that can be decorated on a handle
function.
"""
def wrapper(handle_func):
if not callable(can_handle_func) or not callable(handle_func):
raise SkillBuilderException(
"Exception Handler can_handle_func and handle_func input "
"parameters should be callable")
class_attributes = {
"can_handle": (
lambda self, handler_input, exception: can_handle_func(
handler_input, exception)),
"handle": lambda self, handler_input, exception: handle_func(
handler_input, exception)
}
exception_handler_class = type(
"ExceptionHandler{}".format(
handle_func.__name__.title().replace("_", "")),
(AbstractExceptionHandler,), class_attributes)
self.add_exception_handler(
exception_handler=exception_handler_class())
return wrapper | python | def exception_handler(self, can_handle_func):
# type: (Callable[[Input, Exception], bool]) -> Callable
"""Decorator that can be used to add exception handlers easily
to the builder.
The can_handle_func has to be a Callable instance, which takes
two parameters and no varargs or kwargs. This is because of the
ExceptionHandler class signature restrictions. The returned
wrapper function can be applied as a decorator on any function
that processes the exception raised during dispatcher and
returns a response object by the skill. The function should
follow the signature of the handle function in
:py:class:`ask_sdk_runtime.dispatch_components.exception_components.AbstractExceptionHandler`
class.
:param can_handle_func: The function that validates if the
exception can be handled.
:type can_handle_func: Callable[[Input, Exception], bool]
:return: Wrapper function that can be decorated on a handle
function.
"""
def wrapper(handle_func):
if not callable(can_handle_func) or not callable(handle_func):
raise SkillBuilderException(
"Exception Handler can_handle_func and handle_func input "
"parameters should be callable")
class_attributes = {
"can_handle": (
lambda self, handler_input, exception: can_handle_func(
handler_input, exception)),
"handle": lambda self, handler_input, exception: handle_func(
handler_input, exception)
}
exception_handler_class = type(
"ExceptionHandler{}".format(
handle_func.__name__.title().replace("_", "")),
(AbstractExceptionHandler,), class_attributes)
self.add_exception_handler(
exception_handler=exception_handler_class())
return wrapper | [
"def",
"exception_handler",
"(",
"self",
",",
"can_handle_func",
")",
":",
"# type: (Callable[[Input, Exception], bool]) -> Callable",
"def",
"wrapper",
"(",
"handle_func",
")",
":",
"if",
"not",
"callable",
"(",
"can_handle_func",
")",
"or",
"not",
"callable",
"(",
... | Decorator that can be used to add exception handlers easily
to the builder.
The can_handle_func has to be a Callable instance, which takes
two parameters and no varargs or kwargs. This is because of the
ExceptionHandler class signature restrictions. The returned
wrapper function can be applied as a decorator on any function
that processes the exception raised during dispatcher and
returns a response object by the skill. The function should
follow the signature of the handle function in
:py:class:`ask_sdk_runtime.dispatch_components.exception_components.AbstractExceptionHandler`
class.
:param can_handle_func: The function that validates if the
exception can be handled.
:type can_handle_func: Callable[[Input, Exception], bool]
:return: Wrapper function that can be decorated on a handle
function. | [
"Decorator",
"that",
"can",
"be",
"used",
"to",
"add",
"exception",
"handlers",
"easily",
"to",
"the",
"builder",
"."
] | 097b6406aa12d5ca0b825b00c936861b530cbf39 | https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-runtime/ask_sdk_runtime/skill_builder.py#L138-L180 | train | 215,351 |
alexa/alexa-skills-kit-sdk-for-python | ask-sdk-runtime/ask_sdk_runtime/skill_builder.py | AbstractSkillBuilder.global_request_interceptor | def global_request_interceptor(self):
# type: () -> Callable
"""Decorator that can be used to add global request
interceptors easily to the builder.
The returned wrapper function can be applied as a decorator on
any function that processes the input. The function should
follow the signature of the process function in
:py:class:`ask_sdk_runtime.dispatch_components.request_components.AbstractRequestInterceptor`
class.
:return: Wrapper function that can be decorated on a
interceptor process function.
"""
def wrapper(process_func):
if not callable(process_func):
raise SkillBuilderException(
"Global Request Interceptor process_func input parameter "
"should be callable")
class_attributes = {
"process": lambda self, handler_input: process_func(
handler_input)
}
request_interceptor = type(
"RequestInterceptor{}".format(
process_func.__name__.title().replace("_", "")),
(AbstractRequestInterceptor,), class_attributes)
self.add_global_request_interceptor(
request_interceptor=request_interceptor())
return wrapper | python | def global_request_interceptor(self):
# type: () -> Callable
"""Decorator that can be used to add global request
interceptors easily to the builder.
The returned wrapper function can be applied as a decorator on
any function that processes the input. The function should
follow the signature of the process function in
:py:class:`ask_sdk_runtime.dispatch_components.request_components.AbstractRequestInterceptor`
class.
:return: Wrapper function that can be decorated on a
interceptor process function.
"""
def wrapper(process_func):
if not callable(process_func):
raise SkillBuilderException(
"Global Request Interceptor process_func input parameter "
"should be callable")
class_attributes = {
"process": lambda self, handler_input: process_func(
handler_input)
}
request_interceptor = type(
"RequestInterceptor{}".format(
process_func.__name__.title().replace("_", "")),
(AbstractRequestInterceptor,), class_attributes)
self.add_global_request_interceptor(
request_interceptor=request_interceptor())
return wrapper | [
"def",
"global_request_interceptor",
"(",
"self",
")",
":",
"# type: () -> Callable",
"def",
"wrapper",
"(",
"process_func",
")",
":",
"if",
"not",
"callable",
"(",
"process_func",
")",
":",
"raise",
"SkillBuilderException",
"(",
"\"Global Request Interceptor process_fu... | Decorator that can be used to add global request
interceptors easily to the builder.
The returned wrapper function can be applied as a decorator on
any function that processes the input. The function should
follow the signature of the process function in
:py:class:`ask_sdk_runtime.dispatch_components.request_components.AbstractRequestInterceptor`
class.
:return: Wrapper function that can be decorated on a
interceptor process function. | [
"Decorator",
"that",
"can",
"be",
"used",
"to",
"add",
"global",
"request",
"interceptors",
"easily",
"to",
"the",
"builder",
"."
] | 097b6406aa12d5ca0b825b00c936861b530cbf39 | https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-runtime/ask_sdk_runtime/skill_builder.py#L182-L214 | train | 215,352 |
alexa/alexa-skills-kit-sdk-for-python | ask-sdk-runtime/ask_sdk_runtime/skill_builder.py | AbstractSkillBuilder.global_response_interceptor | def global_response_interceptor(self):
# type: () -> Callable
"""Decorator that can be used to add global
response interceptors easily to the builder.
The returned wrapper function can be applied as a decorator
on any function that processes the input and the response
generated by the request handler. The function should follow
the signature of the process function in
:py:class:`ask_sdk_runtime.dispatch_components.request_components.AbstractResponseInterceptor`
class.
:return: Wrapper function that can be decorated on a
interceptor process function.
"""
def wrapper(process_func):
if not callable(process_func):
raise SkillBuilderException(
"Global Response Interceptor process_func input "
"parameter should be callable")
class_attributes = {
"process": (
lambda self, handler_input, response: process_func(
handler_input, response))
}
response_interceptor = type(
"ResponseInterceptor{}".format(
process_func.__name__.title().replace("_", "")),
(AbstractResponseInterceptor,), class_attributes)
self.add_global_response_interceptor(
response_interceptor=response_interceptor())
return wrapper | python | def global_response_interceptor(self):
# type: () -> Callable
"""Decorator that can be used to add global
response interceptors easily to the builder.
The returned wrapper function can be applied as a decorator
on any function that processes the input and the response
generated by the request handler. The function should follow
the signature of the process function in
:py:class:`ask_sdk_runtime.dispatch_components.request_components.AbstractResponseInterceptor`
class.
:return: Wrapper function that can be decorated on a
interceptor process function.
"""
def wrapper(process_func):
if not callable(process_func):
raise SkillBuilderException(
"Global Response Interceptor process_func input "
"parameter should be callable")
class_attributes = {
"process": (
lambda self, handler_input, response: process_func(
handler_input, response))
}
response_interceptor = type(
"ResponseInterceptor{}".format(
process_func.__name__.title().replace("_", "")),
(AbstractResponseInterceptor,), class_attributes)
self.add_global_response_interceptor(
response_interceptor=response_interceptor())
return wrapper | [
"def",
"global_response_interceptor",
"(",
"self",
")",
":",
"# type: () -> Callable",
"def",
"wrapper",
"(",
"process_func",
")",
":",
"if",
"not",
"callable",
"(",
"process_func",
")",
":",
"raise",
"SkillBuilderException",
"(",
"\"Global Response Interceptor process_... | Decorator that can be used to add global
response interceptors easily to the builder.
The returned wrapper function can be applied as a decorator
on any function that processes the input and the response
generated by the request handler. The function should follow
the signature of the process function in
:py:class:`ask_sdk_runtime.dispatch_components.request_components.AbstractResponseInterceptor`
class.
:return: Wrapper function that can be decorated on a
interceptor process function. | [
"Decorator",
"that",
"can",
"be",
"used",
"to",
"add",
"global",
"response",
"interceptors",
"easily",
"to",
"the",
"builder",
"."
] | 097b6406aa12d5ca0b825b00c936861b530cbf39 | https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-runtime/ask_sdk_runtime/skill_builder.py#L216-L250 | train | 215,353 |
alexa/alexa-skills-kit-sdk-for-python | ask-sdk-core/ask_sdk_core/utils/request_util.py | get_intent_name | def get_intent_name(handler_input):
# type: (HandlerInput) -> AnyStr
"""Return the name of the intent request.
The method retrieves the intent ``name`` from the input request, only if
the input request is an
:py:class:`ask_sdk_model.intent_request.IntentRequest`. If the input
is not an IntentRequest, a :py:class:`TypeError` is raised.
:param handler_input: The handler input instance that is generally
passed in the sdk's request and exception components
:type handler_input: ask_sdk_core.handler_input.HandlerInput
:return: Name of the intent request
:rtype: str
:raises: TypeError
"""
request = handler_input.request_envelope.request
if isinstance(request, IntentRequest):
return request.intent.name
raise TypeError("The provided request is not an IntentRequest") | python | def get_intent_name(handler_input):
# type: (HandlerInput) -> AnyStr
"""Return the name of the intent request.
The method retrieves the intent ``name`` from the input request, only if
the input request is an
:py:class:`ask_sdk_model.intent_request.IntentRequest`. If the input
is not an IntentRequest, a :py:class:`TypeError` is raised.
:param handler_input: The handler input instance that is generally
passed in the sdk's request and exception components
:type handler_input: ask_sdk_core.handler_input.HandlerInput
:return: Name of the intent request
:rtype: str
:raises: TypeError
"""
request = handler_input.request_envelope.request
if isinstance(request, IntentRequest):
return request.intent.name
raise TypeError("The provided request is not an IntentRequest") | [
"def",
"get_intent_name",
"(",
"handler_input",
")",
":",
"# type: (HandlerInput) -> AnyStr",
"request",
"=",
"handler_input",
".",
"request_envelope",
".",
"request",
"if",
"isinstance",
"(",
"request",
",",
"IntentRequest",
")",
":",
"return",
"request",
".",
"int... | Return the name of the intent request.
The method retrieves the intent ``name`` from the input request, only if
the input request is an
:py:class:`ask_sdk_model.intent_request.IntentRequest`. If the input
is not an IntentRequest, a :py:class:`TypeError` is raised.
:param handler_input: The handler input instance that is generally
passed in the sdk's request and exception components
:type handler_input: ask_sdk_core.handler_input.HandlerInput
:return: Name of the intent request
:rtype: str
:raises: TypeError | [
"Return",
"the",
"name",
"of",
"the",
"intent",
"request",
"."
] | 097b6406aa12d5ca0b825b00c936861b530cbf39 | https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-core/ask_sdk_core/utils/request_util.py#L65-L85 | train | 215,354 |
alexa/alexa-skills-kit-sdk-for-python | ask-sdk-core/ask_sdk_core/utils/request_util.py | get_device_id | def get_device_id(handler_input):
# type: (HandlerInput) -> Optional[AnyStr]
"""Return the device id from the input request.
The method retrieves the `deviceId` property from the input request.
This value uniquely identifies the device and is generally used as
input for some Alexa-specific API calls. More information about this
can be found here :
https://developer.amazon.com/docs/custom-skills/request-and-response-json-reference.html#system-object
If there is no device information in the input request, then a ``None``
is returned.
:param handler_input: The handler input instance that is generally
passed in the sdk's request and exception components
:type handler_input: ask_sdk_core.handler_input.HandlerInput
:return: Unique device id of the device used to send the alexa request
or `None` if device information is not present
:rtype: Optional[str]
"""
device = handler_input.request_envelope.context.system.device
if device:
return device.device_id
else:
return None | python | def get_device_id(handler_input):
# type: (HandlerInput) -> Optional[AnyStr]
"""Return the device id from the input request.
The method retrieves the `deviceId` property from the input request.
This value uniquely identifies the device and is generally used as
input for some Alexa-specific API calls. More information about this
can be found here :
https://developer.amazon.com/docs/custom-skills/request-and-response-json-reference.html#system-object
If there is no device information in the input request, then a ``None``
is returned.
:param handler_input: The handler input instance that is generally
passed in the sdk's request and exception components
:type handler_input: ask_sdk_core.handler_input.HandlerInput
:return: Unique device id of the device used to send the alexa request
or `None` if device information is not present
:rtype: Optional[str]
"""
device = handler_input.request_envelope.context.system.device
if device:
return device.device_id
else:
return None | [
"def",
"get_device_id",
"(",
"handler_input",
")",
":",
"# type: (HandlerInput) -> Optional[AnyStr]",
"device",
"=",
"handler_input",
".",
"request_envelope",
".",
"context",
".",
"system",
".",
"device",
"if",
"device",
":",
"return",
"device",
".",
"device_id",
"e... | Return the device id from the input request.
The method retrieves the `deviceId` property from the input request.
This value uniquely identifies the device and is generally used as
input for some Alexa-specific API calls. More information about this
can be found here :
https://developer.amazon.com/docs/custom-skills/request-and-response-json-reference.html#system-object
If there is no device information in the input request, then a ``None``
is returned.
:param handler_input: The handler input instance that is generally
passed in the sdk's request and exception components
:type handler_input: ask_sdk_core.handler_input.HandlerInput
:return: Unique device id of the device used to send the alexa request
or `None` if device information is not present
:rtype: Optional[str] | [
"Return",
"the",
"device",
"id",
"from",
"the",
"input",
"request",
"."
] | 097b6406aa12d5ca0b825b00c936861b530cbf39 | https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-core/ask_sdk_core/utils/request_util.py#L133-L157 | train | 215,355 |
alexa/alexa-skills-kit-sdk-for-python | ask-sdk-core/ask_sdk_core/utils/request_util.py | get_dialog_state | def get_dialog_state(handler_input):
# type: (HandlerInput) -> Optional[DialogState]
"""Return the dialog state enum from the intent request.
The method retrieves the `dialogState` from the intent request, if
the skill's interaction model includes a dialog model. This can be
used to determine the current status of user conversation and return
the appropriate dialog directives if the conversation is not yet complete.
More information on dialog management can be found here :
https://developer.amazon.com/docs/custom-skills/define-the-dialog-to-collect-and-confirm-required-information.html
The method returns a ``None`` if there is no dialog model added or
if the intent doesn't have dialog management. The method raises a
:py:class:`TypeError` if the input is not an `IntentRequest`.
:param handler_input: The handler input instance that is generally
passed in the sdk's request and exception components.
:type handler_input: ask_sdk_core.handler_input.HandlerInput
:return: State of the dialog model from the intent request.
:rtype: Optional[ask_sdk_model.dialog_state.DialogState]
:raises: TypeError if the input is not an IntentRequest
"""
request = handler_input.request_envelope.request
if isinstance(request, IntentRequest):
return request.dialog_state
raise TypeError("The provided request is not an IntentRequest") | python | def get_dialog_state(handler_input):
# type: (HandlerInput) -> Optional[DialogState]
"""Return the dialog state enum from the intent request.
The method retrieves the `dialogState` from the intent request, if
the skill's interaction model includes a dialog model. This can be
used to determine the current status of user conversation and return
the appropriate dialog directives if the conversation is not yet complete.
More information on dialog management can be found here :
https://developer.amazon.com/docs/custom-skills/define-the-dialog-to-collect-and-confirm-required-information.html
The method returns a ``None`` if there is no dialog model added or
if the intent doesn't have dialog management. The method raises a
:py:class:`TypeError` if the input is not an `IntentRequest`.
:param handler_input: The handler input instance that is generally
passed in the sdk's request and exception components.
:type handler_input: ask_sdk_core.handler_input.HandlerInput
:return: State of the dialog model from the intent request.
:rtype: Optional[ask_sdk_model.dialog_state.DialogState]
:raises: TypeError if the input is not an IntentRequest
"""
request = handler_input.request_envelope.request
if isinstance(request, IntentRequest):
return request.dialog_state
raise TypeError("The provided request is not an IntentRequest") | [
"def",
"get_dialog_state",
"(",
"handler_input",
")",
":",
"# type: (HandlerInput) -> Optional[DialogState]",
"request",
"=",
"handler_input",
".",
"request_envelope",
".",
"request",
"if",
"isinstance",
"(",
"request",
",",
"IntentRequest",
")",
":",
"return",
"request... | Return the dialog state enum from the intent request.
The method retrieves the `dialogState` from the intent request, if
the skill's interaction model includes a dialog model. This can be
used to determine the current status of user conversation and return
the appropriate dialog directives if the conversation is not yet complete.
More information on dialog management can be found here :
https://developer.amazon.com/docs/custom-skills/define-the-dialog-to-collect-and-confirm-required-information.html
The method returns a ``None`` if there is no dialog model added or
if the intent doesn't have dialog management. The method raises a
:py:class:`TypeError` if the input is not an `IntentRequest`.
:param handler_input: The handler input instance that is generally
passed in the sdk's request and exception components.
:type handler_input: ask_sdk_core.handler_input.HandlerInput
:return: State of the dialog model from the intent request.
:rtype: Optional[ask_sdk_model.dialog_state.DialogState]
:raises: TypeError if the input is not an IntentRequest | [
"Return",
"the",
"dialog",
"state",
"enum",
"from",
"the",
"intent",
"request",
"."
] | 097b6406aa12d5ca0b825b00c936861b530cbf39 | https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-core/ask_sdk_core/utils/request_util.py#L160-L186 | train | 215,356 |
alexa/alexa-skills-kit-sdk-for-python | ask-sdk-core/ask_sdk_core/utils/request_util.py | get_slot | def get_slot(handler_input, slot_name):
# type: (HandlerInput, str) -> Optional[Slot]
"""Return the slot information from intent request.
The method retrieves the slot information
:py:class:`ask_sdk_model.slot.Slot` from the input intent request
for the given ``slot_name``. More information on the slots can be
found here :
https://developer.amazon.com/docs/custom-skills/request-types-reference.html#slot-object
If there is no such slot, then a ``None``
is returned. If the input request is not an
:py:class:`ask_sdk_model.intent_request.IntentRequest`, a
:py:class:`TypeError` is raised.
:param handler_input: The handler input instance that is generally
passed in the sdk's request and exception components
:type handler_input: ask_sdk_core.handler_input.HandlerInput
:param slot_name: Name of the slot that needs to be retrieved
:type slot_name: str
:return: Slot information for the provided slot name if it exists,
or a `None` value
:rtype: Optional[ask_sdk_model.slot.Slot]
:raises: TypeError if the input is not an IntentRequest
"""
request = handler_input.request_envelope.request
if isinstance(request, IntentRequest):
if request.intent.slots is not None:
return request.intent.slots.get(slot_name, None)
else:
return None
raise TypeError("The provided request is not an IntentRequest") | python | def get_slot(handler_input, slot_name):
# type: (HandlerInput, str) -> Optional[Slot]
"""Return the slot information from intent request.
The method retrieves the slot information
:py:class:`ask_sdk_model.slot.Slot` from the input intent request
for the given ``slot_name``. More information on the slots can be
found here :
https://developer.amazon.com/docs/custom-skills/request-types-reference.html#slot-object
If there is no such slot, then a ``None``
is returned. If the input request is not an
:py:class:`ask_sdk_model.intent_request.IntentRequest`, a
:py:class:`TypeError` is raised.
:param handler_input: The handler input instance that is generally
passed in the sdk's request and exception components
:type handler_input: ask_sdk_core.handler_input.HandlerInput
:param slot_name: Name of the slot that needs to be retrieved
:type slot_name: str
:return: Slot information for the provided slot name if it exists,
or a `None` value
:rtype: Optional[ask_sdk_model.slot.Slot]
:raises: TypeError if the input is not an IntentRequest
"""
request = handler_input.request_envelope.request
if isinstance(request, IntentRequest):
if request.intent.slots is not None:
return request.intent.slots.get(slot_name, None)
else:
return None
raise TypeError("The provided request is not an IntentRequest") | [
"def",
"get_slot",
"(",
"handler_input",
",",
"slot_name",
")",
":",
"# type: (HandlerInput, str) -> Optional[Slot]",
"request",
"=",
"handler_input",
".",
"request_envelope",
".",
"request",
"if",
"isinstance",
"(",
"request",
",",
"IntentRequest",
")",
":",
"if",
... | Return the slot information from intent request.
The method retrieves the slot information
:py:class:`ask_sdk_model.slot.Slot` from the input intent request
for the given ``slot_name``. More information on the slots can be
found here :
https://developer.amazon.com/docs/custom-skills/request-types-reference.html#slot-object
If there is no such slot, then a ``None``
is returned. If the input request is not an
:py:class:`ask_sdk_model.intent_request.IntentRequest`, a
:py:class:`TypeError` is raised.
:param handler_input: The handler input instance that is generally
passed in the sdk's request and exception components
:type handler_input: ask_sdk_core.handler_input.HandlerInput
:param slot_name: Name of the slot that needs to be retrieved
:type slot_name: str
:return: Slot information for the provided slot name if it exists,
or a `None` value
:rtype: Optional[ask_sdk_model.slot.Slot]
:raises: TypeError if the input is not an IntentRequest | [
"Return",
"the",
"slot",
"information",
"from",
"intent",
"request",
"."
] | 097b6406aa12d5ca0b825b00c936861b530cbf39 | https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-core/ask_sdk_core/utils/request_util.py#L189-L221 | train | 215,357 |
alexa/alexa-skills-kit-sdk-for-python | ask-sdk-core/ask_sdk_core/utils/request_util.py | get_slot_value | def get_slot_value(handler_input, slot_name):
# type: (HandlerInput, str) -> AnyStr
"""Return the slot value from intent request.
The method retrieves the slot value from the input intent request
for the given ``slot_name``. More information on the slots can be
found here :
https://developer.amazon.com/docs/custom-skills/request-types-reference.html#slot-object
If there is no such slot, then a :py:class:`ValueError` is raised.
If the input request is not an
:py:class:`ask_sdk_model.intent_request.IntentRequest`, a
:py:class:`TypeError` is raised.
:param handler_input: The handler input instance that is generally
passed in the sdk's request and exception components
:type handler_input: ask_sdk_core.handler_input.HandlerInput
:param slot_name: Name of the slot for which the value has to be retrieved
:type slot_name: str
:return: Slot value for the provided slot if it exists
:rtype: str
:raises: TypeError if the input is not an IntentRequest. ValueError is
slot doesn't exist
"""
slot = get_slot(handler_input=handler_input, slot_name=slot_name)
if slot is not None:
return slot.value
raise ValueError(
"Provided slot {} doesn't exist in the input request".format(
slot_name)) | python | def get_slot_value(handler_input, slot_name):
# type: (HandlerInput, str) -> AnyStr
"""Return the slot value from intent request.
The method retrieves the slot value from the input intent request
for the given ``slot_name``. More information on the slots can be
found here :
https://developer.amazon.com/docs/custom-skills/request-types-reference.html#slot-object
If there is no such slot, then a :py:class:`ValueError` is raised.
If the input request is not an
:py:class:`ask_sdk_model.intent_request.IntentRequest`, a
:py:class:`TypeError` is raised.
:param handler_input: The handler input instance that is generally
passed in the sdk's request and exception components
:type handler_input: ask_sdk_core.handler_input.HandlerInput
:param slot_name: Name of the slot for which the value has to be retrieved
:type slot_name: str
:return: Slot value for the provided slot if it exists
:rtype: str
:raises: TypeError if the input is not an IntentRequest. ValueError is
slot doesn't exist
"""
slot = get_slot(handler_input=handler_input, slot_name=slot_name)
if slot is not None:
return slot.value
raise ValueError(
"Provided slot {} doesn't exist in the input request".format(
slot_name)) | [
"def",
"get_slot_value",
"(",
"handler_input",
",",
"slot_name",
")",
":",
"# type: (HandlerInput, str) -> AnyStr",
"slot",
"=",
"get_slot",
"(",
"handler_input",
"=",
"handler_input",
",",
"slot_name",
"=",
"slot_name",
")",
"if",
"slot",
"is",
"not",
"None",
":"... | Return the slot value from intent request.
The method retrieves the slot value from the input intent request
for the given ``slot_name``. More information on the slots can be
found here :
https://developer.amazon.com/docs/custom-skills/request-types-reference.html#slot-object
If there is no such slot, then a :py:class:`ValueError` is raised.
If the input request is not an
:py:class:`ask_sdk_model.intent_request.IntentRequest`, a
:py:class:`TypeError` is raised.
:param handler_input: The handler input instance that is generally
passed in the sdk's request and exception components
:type handler_input: ask_sdk_core.handler_input.HandlerInput
:param slot_name: Name of the slot for which the value has to be retrieved
:type slot_name: str
:return: Slot value for the provided slot if it exists
:rtype: str
:raises: TypeError if the input is not an IntentRequest. ValueError is
slot doesn't exist | [
"Return",
"the",
"slot",
"value",
"from",
"intent",
"request",
"."
] | 097b6406aa12d5ca0b825b00c936861b530cbf39 | https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-core/ask_sdk_core/utils/request_util.py#L224-L255 | train | 215,358 |
alexa/alexa-skills-kit-sdk-for-python | ask-sdk-core/ask_sdk_core/utils/request_util.py | is_new_session | def is_new_session(handler_input):
# type: (HandlerInput) -> bool
"""Return if the session is new for the input request.
The method retrieves the ``new`` value from the input request's
session, which indicates if it's a new session or not. The
:py:class:`ask_sdk_model.session.Session` is only included on all
standard requests except ``AudioPlayer``, ``VideoApp`` and
``PlaybackController`` requests. More information can be found here :
https://developer.amazon.com/docs/custom-skills/request-and-response-json-reference.html#session-object
A :py:class:`TypeError` is raised if the input request doesn't have
the ``session`` information.
:param handler_input: The handler input instance that is generally
passed in the sdk's request and exception components
:type handler_input: ask_sdk_core.handler_input.HandlerInput
:return: Boolean if the session is new for the input request
:rtype: bool
:raises: TypeError if the input request doesn't have a session
"""
session = handler_input.request_envelope.session
if session is not None:
return session.new
raise TypeError("The provided request doesn't have a session") | python | def is_new_session(handler_input):
# type: (HandlerInput) -> bool
"""Return if the session is new for the input request.
The method retrieves the ``new`` value from the input request's
session, which indicates if it's a new session or not. The
:py:class:`ask_sdk_model.session.Session` is only included on all
standard requests except ``AudioPlayer``, ``VideoApp`` and
``PlaybackController`` requests. More information can be found here :
https://developer.amazon.com/docs/custom-skills/request-and-response-json-reference.html#session-object
A :py:class:`TypeError` is raised if the input request doesn't have
the ``session`` information.
:param handler_input: The handler input instance that is generally
passed in the sdk's request and exception components
:type handler_input: ask_sdk_core.handler_input.HandlerInput
:return: Boolean if the session is new for the input request
:rtype: bool
:raises: TypeError if the input request doesn't have a session
"""
session = handler_input.request_envelope.session
if session is not None:
return session.new
raise TypeError("The provided request doesn't have a session") | [
"def",
"is_new_session",
"(",
"handler_input",
")",
":",
"# type: (HandlerInput) -> bool",
"session",
"=",
"handler_input",
".",
"request_envelope",
".",
"session",
"if",
"session",
"is",
"not",
"None",
":",
"return",
"session",
".",
"new",
"raise",
"TypeError",
"... | Return if the session is new for the input request.
The method retrieves the ``new`` value from the input request's
session, which indicates if it's a new session or not. The
:py:class:`ask_sdk_model.session.Session` is only included on all
standard requests except ``AudioPlayer``, ``VideoApp`` and
``PlaybackController`` requests. More information can be found here :
https://developer.amazon.com/docs/custom-skills/request-and-response-json-reference.html#session-object
A :py:class:`TypeError` is raised if the input request doesn't have
the ``session`` information.
:param handler_input: The handler input instance that is generally
passed in the sdk's request and exception components
:type handler_input: ask_sdk_core.handler_input.HandlerInput
:return: Boolean if the session is new for the input request
:rtype: bool
:raises: TypeError if the input request doesn't have a session | [
"Return",
"if",
"the",
"session",
"is",
"new",
"for",
"the",
"input",
"request",
"."
] | 097b6406aa12d5ca0b825b00c936861b530cbf39 | https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-core/ask_sdk_core/utils/request_util.py#L284-L310 | train | 215,359 |
alexa/alexa-skills-kit-sdk-for-python | ask-sdk-core/ask_sdk_core/response_helper.py | __set_text_field | def __set_text_field(text, text_type):
# type: (str, str) -> Union[None, PlainText, RichText]
"""Helper method to create text field according to text type.
:type text: str
:param text_type: Type of the primary text field. Allowed values
are `PlainText` and `RichText`.
:type text_type: str
:return: Object of type
:py:class:`ask_sdk_model.interfaces.display.PlainText` or
:py:class:`ask_sdk_model.interfaces.display.RichText` depending
on text_type
:rtype: object
:raises: ValueError
"""
if text:
if text_type not in [PLAIN_TEXT_TYPE, RICH_TEXT_TYPE]:
raise ValueError("Invalid type provided: {}".format(text_type))
if text_type == PLAIN_TEXT_TYPE:
return PlainText(text=text)
else:
return RichText(text=text)
else:
return None | python | def __set_text_field(text, text_type):
# type: (str, str) -> Union[None, PlainText, RichText]
"""Helper method to create text field according to text type.
:type text: str
:param text_type: Type of the primary text field. Allowed values
are `PlainText` and `RichText`.
:type text_type: str
:return: Object of type
:py:class:`ask_sdk_model.interfaces.display.PlainText` or
:py:class:`ask_sdk_model.interfaces.display.RichText` depending
on text_type
:rtype: object
:raises: ValueError
"""
if text:
if text_type not in [PLAIN_TEXT_TYPE, RICH_TEXT_TYPE]:
raise ValueError("Invalid type provided: {}".format(text_type))
if text_type == PLAIN_TEXT_TYPE:
return PlainText(text=text)
else:
return RichText(text=text)
else:
return None | [
"def",
"__set_text_field",
"(",
"text",
",",
"text_type",
")",
":",
"# type: (str, str) -> Union[None, PlainText, RichText]",
"if",
"text",
":",
"if",
"text_type",
"not",
"in",
"[",
"PLAIN_TEXT_TYPE",
",",
"RICH_TEXT_TYPE",
"]",
":",
"raise",
"ValueError",
"(",
"\"I... | Helper method to create text field according to text type.
:type text: str
:param text_type: Type of the primary text field. Allowed values
are `PlainText` and `RichText`.
:type text_type: str
:return: Object of type
:py:class:`ask_sdk_model.interfaces.display.PlainText` or
:py:class:`ask_sdk_model.interfaces.display.RichText` depending
on text_type
:rtype: object
:raises: ValueError | [
"Helper",
"method",
"to",
"create",
"text",
"field",
"according",
"to",
"text",
"type",
"."
] | 097b6406aa12d5ca0b825b00c936861b530cbf39 | https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-core/ask_sdk_core/response_helper.py#L290-L314 | train | 215,360 |
alexa/alexa-skills-kit-sdk-for-python | ask-sdk-core/ask_sdk_core/response_helper.py | ResponseFactory.speak | def speak(self, speech, play_behavior=None):
# type: (str, PlayBehavior) -> 'ResponseFactory'
"""Say the provided speech to the user.
:param speech: the output speech sent back to the user.
:type speech: str
:param play_behavior: attribute to control alexa's speech
interruption
:type play_behavior: ask_sdk_model.ui.play_behavior.PlayBehavior
:return: response factory with partial response being built and
access from self.response.
:rtype: ResponseFactory
"""
ssml = "<speak>{}</speak>".format(self.__trim_outputspeech(
speech_output=speech))
self.response.output_speech = SsmlOutputSpeech(
ssml=ssml, play_behavior=play_behavior)
return self | python | def speak(self, speech, play_behavior=None):
# type: (str, PlayBehavior) -> 'ResponseFactory'
"""Say the provided speech to the user.
:param speech: the output speech sent back to the user.
:type speech: str
:param play_behavior: attribute to control alexa's speech
interruption
:type play_behavior: ask_sdk_model.ui.play_behavior.PlayBehavior
:return: response factory with partial response being built and
access from self.response.
:rtype: ResponseFactory
"""
ssml = "<speak>{}</speak>".format(self.__trim_outputspeech(
speech_output=speech))
self.response.output_speech = SsmlOutputSpeech(
ssml=ssml, play_behavior=play_behavior)
return self | [
"def",
"speak",
"(",
"self",
",",
"speech",
",",
"play_behavior",
"=",
"None",
")",
":",
"# type: (str, PlayBehavior) -> 'ResponseFactory'",
"ssml",
"=",
"\"<speak>{}</speak>\"",
".",
"format",
"(",
"self",
".",
"__trim_outputspeech",
"(",
"speech_output",
"=",
"spe... | Say the provided speech to the user.
:param speech: the output speech sent back to the user.
:type speech: str
:param play_behavior: attribute to control alexa's speech
interruption
:type play_behavior: ask_sdk_model.ui.play_behavior.PlayBehavior
:return: response factory with partial response being built and
access from self.response.
:rtype: ResponseFactory | [
"Say",
"the",
"provided",
"speech",
"to",
"the",
"user",
"."
] | 097b6406aa12d5ca0b825b00c936861b530cbf39 | https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-core/ask_sdk_core/response_helper.py#L55-L72 | train | 215,361 |
alexa/alexa-skills-kit-sdk-for-python | ask-sdk-core/ask_sdk_core/response_helper.py | ResponseFactory.ask | def ask(self, reprompt, play_behavior=None):
# type: (str, PlayBehavior) -> 'ResponseFactory'
"""Provide reprompt speech to the user, if no response for
8 seconds.
The should_end_session value will be set to false except when
the video app launch directive is present in directives.
:param reprompt: the output speech to reprompt.
:type reprompt: str
:param play_behavior: attribute to control alexa's speech
interruption
:type play_behavior: ask_sdk_model.ui.play_behavior.PlayBehavior
:return: response factory with partial response being built and
access from self.response.
:rtype: ResponseFactory
"""
ssml = "<speak>{}</speak>".format(self.__trim_outputspeech(
speech_output=reprompt))
output_speech = SsmlOutputSpeech(
ssml=ssml, play_behavior=play_behavior)
self.response.reprompt = Reprompt(output_speech=output_speech)
if not self.__is_video_app_launch_directive_present():
self.response.should_end_session = False
return self | python | def ask(self, reprompt, play_behavior=None):
# type: (str, PlayBehavior) -> 'ResponseFactory'
"""Provide reprompt speech to the user, if no response for
8 seconds.
The should_end_session value will be set to false except when
the video app launch directive is present in directives.
:param reprompt: the output speech to reprompt.
:type reprompt: str
:param play_behavior: attribute to control alexa's speech
interruption
:type play_behavior: ask_sdk_model.ui.play_behavior.PlayBehavior
:return: response factory with partial response being built and
access from self.response.
:rtype: ResponseFactory
"""
ssml = "<speak>{}</speak>".format(self.__trim_outputspeech(
speech_output=reprompt))
output_speech = SsmlOutputSpeech(
ssml=ssml, play_behavior=play_behavior)
self.response.reprompt = Reprompt(output_speech=output_speech)
if not self.__is_video_app_launch_directive_present():
self.response.should_end_session = False
return self | [
"def",
"ask",
"(",
"self",
",",
"reprompt",
",",
"play_behavior",
"=",
"None",
")",
":",
"# type: (str, PlayBehavior) -> 'ResponseFactory'",
"ssml",
"=",
"\"<speak>{}</speak>\"",
".",
"format",
"(",
"self",
".",
"__trim_outputspeech",
"(",
"speech_output",
"=",
"rep... | Provide reprompt speech to the user, if no response for
8 seconds.
The should_end_session value will be set to false except when
the video app launch directive is present in directives.
:param reprompt: the output speech to reprompt.
:type reprompt: str
:param play_behavior: attribute to control alexa's speech
interruption
:type play_behavior: ask_sdk_model.ui.play_behavior.PlayBehavior
:return: response factory with partial response being built and
access from self.response.
:rtype: ResponseFactory | [
"Provide",
"reprompt",
"speech",
"to",
"the",
"user",
"if",
"no",
"response",
"for",
"8",
"seconds",
"."
] | 097b6406aa12d5ca0b825b00c936861b530cbf39 | https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-core/ask_sdk_core/response_helper.py#L74-L98 | train | 215,362 |
alexa/alexa-skills-kit-sdk-for-python | ask-sdk-core/ask_sdk_core/response_helper.py | ResponseFactory.add_directive | def add_directive(self, directive):
# type: (Directive) -> 'ResponseFactory'
"""Adds directive to response.
:param directive: the directive sent back to Alexa device.
:type directive: ask_sdk_model.directive.Directive
:return: response factory with partial response being built and
access from self.response.
:rtype: ResponseFactory
"""
if self.response.directives is None:
self.response.directives = []
if (directive is not None and
directive.object_type == "VideoApp.Launch"):
self.response.should_end_session = None
self.response.directives.append(directive)
return self | python | def add_directive(self, directive):
# type: (Directive) -> 'ResponseFactory'
"""Adds directive to response.
:param directive: the directive sent back to Alexa device.
:type directive: ask_sdk_model.directive.Directive
:return: response factory with partial response being built and
access from self.response.
:rtype: ResponseFactory
"""
if self.response.directives is None:
self.response.directives = []
if (directive is not None and
directive.object_type == "VideoApp.Launch"):
self.response.should_end_session = None
self.response.directives.append(directive)
return self | [
"def",
"add_directive",
"(",
"self",
",",
"directive",
")",
":",
"# type: (Directive) -> 'ResponseFactory'",
"if",
"self",
".",
"response",
".",
"directives",
"is",
"None",
":",
"self",
".",
"response",
".",
"directives",
"=",
"[",
"]",
"if",
"(",
"directive",... | Adds directive to response.
:param directive: the directive sent back to Alexa device.
:type directive: ask_sdk_model.directive.Directive
:return: response factory with partial response being built and
access from self.response.
:rtype: ResponseFactory | [
"Adds",
"directive",
"to",
"response",
"."
] | 097b6406aa12d5ca0b825b00c936861b530cbf39 | https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-core/ask_sdk_core/response_helper.py#L116-L133 | train | 215,363 |
alexa/alexa-skills-kit-sdk-for-python | ask-sdk-core/ask_sdk_core/response_helper.py | ResponseFactory.__is_video_app_launch_directive_present | def __is_video_app_launch_directive_present(self):
# type: () -> bool
"""Checks if the video app launch directive is present or not.
:return: boolean to show if video app launch directive is
present or not.
:rtype: bool
"""
if self.response.directives is None:
return False
for directive in self.response.directives:
if (directive is not None and
directive.object_type == "VideoApp.Launch"):
return True
return False | python | def __is_video_app_launch_directive_present(self):
# type: () -> bool
"""Checks if the video app launch directive is present or not.
:return: boolean to show if video app launch directive is
present or not.
:rtype: bool
"""
if self.response.directives is None:
return False
for directive in self.response.directives:
if (directive is not None and
directive.object_type == "VideoApp.Launch"):
return True
return False | [
"def",
"__is_video_app_launch_directive_present",
"(",
"self",
")",
":",
"# type: () -> bool",
"if",
"self",
".",
"response",
".",
"directives",
"is",
"None",
":",
"return",
"False",
"for",
"directive",
"in",
"self",
".",
"response",
".",
"directives",
":",
"if"... | Checks if the video app launch directive is present or not.
:return: boolean to show if video app launch directive is
present or not.
:rtype: bool | [
"Checks",
"if",
"the",
"video",
"app",
"launch",
"directive",
"is",
"present",
"or",
"not",
"."
] | 097b6406aa12d5ca0b825b00c936861b530cbf39 | https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-core/ask_sdk_core/response_helper.py#L183-L198 | train | 215,364 |
alexa/alexa-skills-kit-sdk-for-python | ask-sdk-runtime/ask_sdk_runtime/dispatch.py | GenericRequestDispatcher.dispatch | def dispatch(self, handler_input):
# type: (Input) -> Union[Output, None]
"""Dispatches an incoming request to the appropriate
request handler and returns the output.
Before running the request on the appropriate request handler,
dispatcher runs any predefined global request interceptors.
On successful response returned from request handler, dispatcher
runs predefined global response interceptors, before returning
the response.
:param handler_input: generic input to the dispatcher
:type handler_input: Input
:return: generic output handled by the handler, optionally
containing a response
:rtype: Union[None, Output]
:raises: :py:class:`ask_sdk_runtime.exceptions.DispatchException`
"""
try:
for request_interceptor in self.request_interceptors:
request_interceptor.process(handler_input=handler_input)
output = self.__dispatch_request(handler_input) # type: Union[Output, None]
for response_interceptor in self.response_interceptors:
response_interceptor.process(
handler_input=handler_input, dispatch_output=output)
return output
except Exception as e:
if self.exception_mapper is not None:
exception_handler = self.exception_mapper.get_handler(
handler_input, e)
if exception_handler is None:
raise e
return exception_handler.handle(handler_input, e)
else:
raise e | python | def dispatch(self, handler_input):
# type: (Input) -> Union[Output, None]
"""Dispatches an incoming request to the appropriate
request handler and returns the output.
Before running the request on the appropriate request handler,
dispatcher runs any predefined global request interceptors.
On successful response returned from request handler, dispatcher
runs predefined global response interceptors, before returning
the response.
:param handler_input: generic input to the dispatcher
:type handler_input: Input
:return: generic output handled by the handler, optionally
containing a response
:rtype: Union[None, Output]
:raises: :py:class:`ask_sdk_runtime.exceptions.DispatchException`
"""
try:
for request_interceptor in self.request_interceptors:
request_interceptor.process(handler_input=handler_input)
output = self.__dispatch_request(handler_input) # type: Union[Output, None]
for response_interceptor in self.response_interceptors:
response_interceptor.process(
handler_input=handler_input, dispatch_output=output)
return output
except Exception as e:
if self.exception_mapper is not None:
exception_handler = self.exception_mapper.get_handler(
handler_input, e)
if exception_handler is None:
raise e
return exception_handler.handle(handler_input, e)
else:
raise e | [
"def",
"dispatch",
"(",
"self",
",",
"handler_input",
")",
":",
"# type: (Input) -> Union[Output, None]",
"try",
":",
"for",
"request_interceptor",
"in",
"self",
".",
"request_interceptors",
":",
"request_interceptor",
".",
"process",
"(",
"handler_input",
"=",
"handl... | Dispatches an incoming request to the appropriate
request handler and returns the output.
Before running the request on the appropriate request handler,
dispatcher runs any predefined global request interceptors.
On successful response returned from request handler, dispatcher
runs predefined global response interceptors, before returning
the response.
:param handler_input: generic input to the dispatcher
:type handler_input: Input
:return: generic output handled by the handler, optionally
containing a response
:rtype: Union[None, Output]
:raises: :py:class:`ask_sdk_runtime.exceptions.DispatchException` | [
"Dispatches",
"an",
"incoming",
"request",
"to",
"the",
"appropriate",
"request",
"handler",
"and",
"returns",
"the",
"output",
"."
] | 097b6406aa12d5ca0b825b00c936861b530cbf39 | https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-runtime/ask_sdk_runtime/dispatch.py#L96-L133 | train | 215,365 |
alexa/alexa-skills-kit-sdk-for-python | ask-sdk-runtime/ask_sdk_runtime/dispatch.py | GenericRequestDispatcher.__dispatch_request | def __dispatch_request(self, handler_input):
# type: (Input) -> Union[Output, None]
"""Process the request and return handler output.
When the method is invoked, using the registered list of
:py:class:`RequestMapper`, a Handler Chain is found that can
handle the request. The handler invocation is delegated to the
supported :py:class:`HandlerAdapter`. The registered
request interceptors in the handler chain are processed before
executing the handler. The registered response interceptors in
the handler chain are processed after executing the handler.
:param handler_input: generic input to the dispatcher containing
incoming request and other context.
:type handler_input: Input
:return: Output from the 'handle' method execution of the
supporting handler.
:rtype: Union[None, Output]
:raises DispatchException if there is no supporting
handler chain or adapter
"""
request_handler_chain = None
for mapper in self.request_mappers:
request_handler_chain = mapper.get_request_handler_chain(
handler_input)
if request_handler_chain is not None:
break
if request_handler_chain is None:
raise DispatchException(
"Unable to find a suitable request handler")
request_handler = request_handler_chain.request_handler
supported_handler_adapter = None
for adapter in self.handler_adapters:
if adapter.supports(request_handler):
supported_handler_adapter = adapter
break
if supported_handler_adapter is None:
raise DispatchException(
"Unable to find a suitable request adapter")
local_request_interceptors = request_handler_chain.request_interceptors
for interceptor in local_request_interceptors:
interceptor.process(handler_input=handler_input)
output = supported_handler_adapter.execute(
handler_input=handler_input, handler=request_handler) # type: Union[Output, None]
local_response_interceptors = (
request_handler_chain.response_interceptors)
for response_interceptor in local_response_interceptors:
response_interceptor.process(
handler_input=handler_input, dispatch_output=output)
return output | python | def __dispatch_request(self, handler_input):
# type: (Input) -> Union[Output, None]
"""Process the request and return handler output.
When the method is invoked, using the registered list of
:py:class:`RequestMapper`, a Handler Chain is found that can
handle the request. The handler invocation is delegated to the
supported :py:class:`HandlerAdapter`. The registered
request interceptors in the handler chain are processed before
executing the handler. The registered response interceptors in
the handler chain are processed after executing the handler.
:param handler_input: generic input to the dispatcher containing
incoming request and other context.
:type handler_input: Input
:return: Output from the 'handle' method execution of the
supporting handler.
:rtype: Union[None, Output]
:raises DispatchException if there is no supporting
handler chain or adapter
"""
request_handler_chain = None
for mapper in self.request_mappers:
request_handler_chain = mapper.get_request_handler_chain(
handler_input)
if request_handler_chain is not None:
break
if request_handler_chain is None:
raise DispatchException(
"Unable to find a suitable request handler")
request_handler = request_handler_chain.request_handler
supported_handler_adapter = None
for adapter in self.handler_adapters:
if adapter.supports(request_handler):
supported_handler_adapter = adapter
break
if supported_handler_adapter is None:
raise DispatchException(
"Unable to find a suitable request adapter")
local_request_interceptors = request_handler_chain.request_interceptors
for interceptor in local_request_interceptors:
interceptor.process(handler_input=handler_input)
output = supported_handler_adapter.execute(
handler_input=handler_input, handler=request_handler) # type: Union[Output, None]
local_response_interceptors = (
request_handler_chain.response_interceptors)
for response_interceptor in local_response_interceptors:
response_interceptor.process(
handler_input=handler_input, dispatch_output=output)
return output | [
"def",
"__dispatch_request",
"(",
"self",
",",
"handler_input",
")",
":",
"# type: (Input) -> Union[Output, None]",
"request_handler_chain",
"=",
"None",
"for",
"mapper",
"in",
"self",
".",
"request_mappers",
":",
"request_handler_chain",
"=",
"mapper",
".",
"get_reques... | Process the request and return handler output.
When the method is invoked, using the registered list of
:py:class:`RequestMapper`, a Handler Chain is found that can
handle the request. The handler invocation is delegated to the
supported :py:class:`HandlerAdapter`. The registered
request interceptors in the handler chain are processed before
executing the handler. The registered response interceptors in
the handler chain are processed after executing the handler.
:param handler_input: generic input to the dispatcher containing
incoming request and other context.
:type handler_input: Input
:return: Output from the 'handle' method execution of the
supporting handler.
:rtype: Union[None, Output]
:raises DispatchException if there is no supporting
handler chain or adapter | [
"Process",
"the",
"request",
"and",
"return",
"handler",
"output",
"."
] | 097b6406aa12d5ca0b825b00c936861b530cbf39 | https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-runtime/ask_sdk_runtime/dispatch.py#L135-L191 | train | 215,366 |
alexa/alexa-skills-kit-sdk-for-python | ask-sdk-core/ask_sdk_core/skill_builder.py | SkillBuilder.lambda_handler | def lambda_handler(self):
# type: () -> Callable[[RequestEnvelope, T], Dict[str, T]]
"""Create a handler function that can be used as handler in
AWS Lambda console.
The lambda handler provides a handler function, that acts as
an entry point to the AWS Lambda console. Users can set the
lambda_handler output to a variable and set the variable as
AWS Lambda Handler on the console.
:return: Handler function to tag on AWS Lambda console.
"""
def wrapper(event, context):
# type: (RequestEnvelope, T) -> Dict[str, T]
skill = CustomSkill(skill_configuration=self.skill_configuration)
request_envelope = skill.serializer.deserialize(
payload=json.dumps(event), obj_type=RequestEnvelope)
response_envelope = skill.invoke(
request_envelope=request_envelope, context=context)
return skill.serializer.serialize(response_envelope) # type:ignore
return wrapper | python | def lambda_handler(self):
# type: () -> Callable[[RequestEnvelope, T], Dict[str, T]]
"""Create a handler function that can be used as handler in
AWS Lambda console.
The lambda handler provides a handler function, that acts as
an entry point to the AWS Lambda console. Users can set the
lambda_handler output to a variable and set the variable as
AWS Lambda Handler on the console.
:return: Handler function to tag on AWS Lambda console.
"""
def wrapper(event, context):
# type: (RequestEnvelope, T) -> Dict[str, T]
skill = CustomSkill(skill_configuration=self.skill_configuration)
request_envelope = skill.serializer.deserialize(
payload=json.dumps(event), obj_type=RequestEnvelope)
response_envelope = skill.invoke(
request_envelope=request_envelope, context=context)
return skill.serializer.serialize(response_envelope) # type:ignore
return wrapper | [
"def",
"lambda_handler",
"(",
"self",
")",
":",
"# type: () -> Callable[[RequestEnvelope, T], Dict[str, T]]",
"def",
"wrapper",
"(",
"event",
",",
"context",
")",
":",
"# type: (RequestEnvelope, T) -> Dict[str, T]",
"skill",
"=",
"CustomSkill",
"(",
"skill_configuration",
"... | Create a handler function that can be used as handler in
AWS Lambda console.
The lambda handler provides a handler function, that acts as
an entry point to the AWS Lambda console. Users can set the
lambda_handler output to a variable and set the variable as
AWS Lambda Handler on the console.
:return: Handler function to tag on AWS Lambda console. | [
"Create",
"a",
"handler",
"function",
"that",
"can",
"be",
"used",
"as",
"handler",
"in",
"AWS",
"Lambda",
"console",
"."
] | 097b6406aa12d5ca0b825b00c936861b530cbf39 | https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-core/ask_sdk_core/skill_builder.py#L80-L100 | train | 215,367 |
alexa/alexa-skills-kit-sdk-for-python | ask-sdk-webservice-support/ask_sdk_webservice_support/webservice_handler.py | WebserviceSkillHandler.verify_request_and_dispatch | def verify_request_and_dispatch(
self, http_request_headers, http_request_body):
# type: (Dict[str, Any], str) -> str
"""Entry point for webservice skill invocation.
This method takes in the input request headers and request body,
handles the deserialization of the input request to
the :py:class:`ask_sdk_model.request_envelope.RequestEnvelope`
object, run the input through registered verifiers, invoke the
skill and return the serialized response from the
skill invocation.
:param http_request_headers: Request headers of the input
request to the webservice
:type http_request_headers: Dict[str, Any]
:param http_request_body: Raw request body of the input request
to the webservice
:type http_request_body: str
:return: Serialized response object returned by the skill
instance, when invoked with the input request
:rtype: str
:raises: :py:class:`ask_sdk_core.exceptions.AskSdkException`
when skill deserialization, verification, invocation or
serialization fails
"""
request_envelope = self._skill.serializer.deserialize(
payload=http_request_body, obj_type=RequestEnvelope)
for verifier in self._verifiers:
verifier.verify(
headers=http_request_headers,
serialized_request_env=http_request_body,
deserialized_request_env=request_envelope)
response_envelope = self._skill.invoke(
request_envelope=request_envelope, context=None)
return self._skill.serializer.serialize(response_envelope) | python | def verify_request_and_dispatch(
self, http_request_headers, http_request_body):
# type: (Dict[str, Any], str) -> str
"""Entry point for webservice skill invocation.
This method takes in the input request headers and request body,
handles the deserialization of the input request to
the :py:class:`ask_sdk_model.request_envelope.RequestEnvelope`
object, run the input through registered verifiers, invoke the
skill and return the serialized response from the
skill invocation.
:param http_request_headers: Request headers of the input
request to the webservice
:type http_request_headers: Dict[str, Any]
:param http_request_body: Raw request body of the input request
to the webservice
:type http_request_body: str
:return: Serialized response object returned by the skill
instance, when invoked with the input request
:rtype: str
:raises: :py:class:`ask_sdk_core.exceptions.AskSdkException`
when skill deserialization, verification, invocation or
serialization fails
"""
request_envelope = self._skill.serializer.deserialize(
payload=http_request_body, obj_type=RequestEnvelope)
for verifier in self._verifiers:
verifier.verify(
headers=http_request_headers,
serialized_request_env=http_request_body,
deserialized_request_env=request_envelope)
response_envelope = self._skill.invoke(
request_envelope=request_envelope, context=None)
return self._skill.serializer.serialize(response_envelope) | [
"def",
"verify_request_and_dispatch",
"(",
"self",
",",
"http_request_headers",
",",
"http_request_body",
")",
":",
"# type: (Dict[str, Any], str) -> str",
"request_envelope",
"=",
"self",
".",
"_skill",
".",
"serializer",
".",
"deserialize",
"(",
"payload",
"=",
"http_... | Entry point for webservice skill invocation.
This method takes in the input request headers and request body,
handles the deserialization of the input request to
the :py:class:`ask_sdk_model.request_envelope.RequestEnvelope`
object, run the input through registered verifiers, invoke the
skill and return the serialized response from the
skill invocation.
:param http_request_headers: Request headers of the input
request to the webservice
:type http_request_headers: Dict[str, Any]
:param http_request_body: Raw request body of the input request
to the webservice
:type http_request_body: str
:return: Serialized response object returned by the skill
instance, when invoked with the input request
:rtype: str
:raises: :py:class:`ask_sdk_core.exceptions.AskSdkException`
when skill deserialization, verification, invocation or
serialization fails | [
"Entry",
"point",
"for",
"webservice",
"skill",
"invocation",
"."
] | 097b6406aa12d5ca0b825b00c936861b530cbf39 | https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-webservice-support/ask_sdk_webservice_support/webservice_handler.py#L99-L136 | train | 215,368 |
alexa/alexa-skills-kit-sdk-for-python | flask-ask-sdk/flask_ask_sdk/skill_adapter.py | SkillAdapter.init_app | def init_app(self, app):
# type: (Flask) -> None
"""Register the extension on the given Flask application.
Use this function only when no Flask application was provided
in the ``app`` keyword argument to the constructor of this class.
The function sets ``True`` defaults for
:py:const:`VERIFY_SIGNATURE_APP_CONFIG` and
:py:const:`VERIFY_TIMESTAMP_APP_CONFIG` configurations. It adds
the skill id: self instance mapping to the application
extensions, and creates a
:py:class:`ask_sdk_webservice_support.webservice_handler.WebserviceHandler`
instance, for request verification and dispatch.
:param app: A :py:class:`flask.Flask` application instance
:type app: flask.Flask
:rtype: None
"""
app.config.setdefault(VERIFY_SIGNATURE_APP_CONFIG, True)
app.config.setdefault(VERIFY_TIMESTAMP_APP_CONFIG, True)
if EXTENSION_NAME not in app.extensions:
app.extensions[EXTENSION_NAME] = {}
app.extensions[EXTENSION_NAME][self._skill_id] = self
with app.app_context():
self._create_webservice_handler(self._skill, self._verifiers) | python | def init_app(self, app):
# type: (Flask) -> None
"""Register the extension on the given Flask application.
Use this function only when no Flask application was provided
in the ``app`` keyword argument to the constructor of this class.
The function sets ``True`` defaults for
:py:const:`VERIFY_SIGNATURE_APP_CONFIG` and
:py:const:`VERIFY_TIMESTAMP_APP_CONFIG` configurations. It adds
the skill id: self instance mapping to the application
extensions, and creates a
:py:class:`ask_sdk_webservice_support.webservice_handler.WebserviceHandler`
instance, for request verification and dispatch.
:param app: A :py:class:`flask.Flask` application instance
:type app: flask.Flask
:rtype: None
"""
app.config.setdefault(VERIFY_SIGNATURE_APP_CONFIG, True)
app.config.setdefault(VERIFY_TIMESTAMP_APP_CONFIG, True)
if EXTENSION_NAME not in app.extensions:
app.extensions[EXTENSION_NAME] = {}
app.extensions[EXTENSION_NAME][self._skill_id] = self
with app.app_context():
self._create_webservice_handler(self._skill, self._verifiers) | [
"def",
"init_app",
"(",
"self",
",",
"app",
")",
":",
"# type: (Flask) -> None",
"app",
".",
"config",
".",
"setdefault",
"(",
"VERIFY_SIGNATURE_APP_CONFIG",
",",
"True",
")",
"app",
".",
"config",
".",
"setdefault",
"(",
"VERIFY_TIMESTAMP_APP_CONFIG",
",",
"Tru... | Register the extension on the given Flask application.
Use this function only when no Flask application was provided
in the ``app`` keyword argument to the constructor of this class.
The function sets ``True`` defaults for
:py:const:`VERIFY_SIGNATURE_APP_CONFIG` and
:py:const:`VERIFY_TIMESTAMP_APP_CONFIG` configurations. It adds
the skill id: self instance mapping to the application
extensions, and creates a
:py:class:`ask_sdk_webservice_support.webservice_handler.WebserviceHandler`
instance, for request verification and dispatch.
:param app: A :py:class:`flask.Flask` application instance
:type app: flask.Flask
:rtype: None | [
"Register",
"the",
"extension",
"on",
"the",
"given",
"Flask",
"application",
"."
] | 097b6406aa12d5ca0b825b00c936861b530cbf39 | https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/flask-ask-sdk/flask_ask_sdk/skill_adapter.py#L156-L184 | train | 215,369 |
alexa/alexa-skills-kit-sdk-for-python | flask-ask-sdk/flask_ask_sdk/skill_adapter.py | SkillAdapter._create_webservice_handler | def _create_webservice_handler(self, skill, verifiers):
# type: (CustomSkill, List[AbstractVerifier]) -> None
"""Create the handler for request verification and dispatch.
:param skill: A :py:class:`ask_sdk_core.skill.CustomSkill`
instance. If you are using the skill builder from ask-sdk,
then you can use the ``create`` method under it, to create a
skill instance
:type skill: ask_sdk_core.skill.CustomSkill
:param verifiers: A list of verifiers, that needs to
be applied on the input request, before invoking the
request handlers.
:type verifiers:
list[ask_sdk_webservice_support.verifier.AbstractVerifier]
:rtype: None
"""
if verifiers is None:
verifiers = []
self._webservice_handler = WebserviceSkillHandler(
skill=skill,
verify_signature=current_app.config.get(
VERIFY_SIGNATURE_APP_CONFIG, True),
verify_timestamp=current_app.config.get(
VERIFY_TIMESTAMP_APP_CONFIG, True),
verifiers=verifiers) | python | def _create_webservice_handler(self, skill, verifiers):
# type: (CustomSkill, List[AbstractVerifier]) -> None
"""Create the handler for request verification and dispatch.
:param skill: A :py:class:`ask_sdk_core.skill.CustomSkill`
instance. If you are using the skill builder from ask-sdk,
then you can use the ``create`` method under it, to create a
skill instance
:type skill: ask_sdk_core.skill.CustomSkill
:param verifiers: A list of verifiers, that needs to
be applied on the input request, before invoking the
request handlers.
:type verifiers:
list[ask_sdk_webservice_support.verifier.AbstractVerifier]
:rtype: None
"""
if verifiers is None:
verifiers = []
self._webservice_handler = WebserviceSkillHandler(
skill=skill,
verify_signature=current_app.config.get(
VERIFY_SIGNATURE_APP_CONFIG, True),
verify_timestamp=current_app.config.get(
VERIFY_TIMESTAMP_APP_CONFIG, True),
verifiers=verifiers) | [
"def",
"_create_webservice_handler",
"(",
"self",
",",
"skill",
",",
"verifiers",
")",
":",
"# type: (CustomSkill, List[AbstractVerifier]) -> None",
"if",
"verifiers",
"is",
"None",
":",
"verifiers",
"=",
"[",
"]",
"self",
".",
"_webservice_handler",
"=",
"WebserviceS... | Create the handler for request verification and dispatch.
:param skill: A :py:class:`ask_sdk_core.skill.CustomSkill`
instance. If you are using the skill builder from ask-sdk,
then you can use the ``create`` method under it, to create a
skill instance
:type skill: ask_sdk_core.skill.CustomSkill
:param verifiers: A list of verifiers, that needs to
be applied on the input request, before invoking the
request handlers.
:type verifiers:
list[ask_sdk_webservice_support.verifier.AbstractVerifier]
:rtype: None | [
"Create",
"the",
"handler",
"for",
"request",
"verification",
"and",
"dispatch",
"."
] | 097b6406aa12d5ca0b825b00c936861b530cbf39 | https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/flask-ask-sdk/flask_ask_sdk/skill_adapter.py#L186-L211 | train | 215,370 |
alexa/alexa-skills-kit-sdk-for-python | flask-ask-sdk/flask_ask_sdk/skill_adapter.py | SkillAdapter.dispatch_request | def dispatch_request(self):
# type: () -> Response
"""Method that handles request verification and routing.
This method can be used as a function to register on the URL
rule. The request is verified through the registered list of
verifiers, before invoking the request handlers. The method
returns a JSON response for the Alexa service to respond to the
request.
:return: The skill response for the input request
:rtype: flask.Response
:raises: :py:class:`werkzeug.exceptions.MethodNotAllowed` if the
method is invoked for other than HTTP POST request.
:py:class:`werkzeug.exceptions.BadRequest` if the
verification fails.
:py:class:`werkzeug.exceptions.InternalServerError` for any
internal exception.
"""
if flask_request.method != "POST":
raise exceptions.MethodNotAllowed()
try:
content = flask_request.data.decode(
verifier_constants.CHARACTER_ENCODING)
response = self._webservice_handler.verify_request_and_dispatch(
http_request_headers=flask_request.headers,
http_request_body=content)
return jsonify(response)
except VerificationException:
current_app.logger.error(
"Request verification failed", exc_info=True)
raise exceptions.BadRequest(
description="Incoming request failed verification")
except AskSdkException:
current_app.logger.error(
"Skill dispatch exception", exc_info=True)
raise exceptions.InternalServerError(
description="Exception occurred during skill dispatch") | python | def dispatch_request(self):
# type: () -> Response
"""Method that handles request verification and routing.
This method can be used as a function to register on the URL
rule. The request is verified through the registered list of
verifiers, before invoking the request handlers. The method
returns a JSON response for the Alexa service to respond to the
request.
:return: The skill response for the input request
:rtype: flask.Response
:raises: :py:class:`werkzeug.exceptions.MethodNotAllowed` if the
method is invoked for other than HTTP POST request.
:py:class:`werkzeug.exceptions.BadRequest` if the
verification fails.
:py:class:`werkzeug.exceptions.InternalServerError` for any
internal exception.
"""
if flask_request.method != "POST":
raise exceptions.MethodNotAllowed()
try:
content = flask_request.data.decode(
verifier_constants.CHARACTER_ENCODING)
response = self._webservice_handler.verify_request_and_dispatch(
http_request_headers=flask_request.headers,
http_request_body=content)
return jsonify(response)
except VerificationException:
current_app.logger.error(
"Request verification failed", exc_info=True)
raise exceptions.BadRequest(
description="Incoming request failed verification")
except AskSdkException:
current_app.logger.error(
"Skill dispatch exception", exc_info=True)
raise exceptions.InternalServerError(
description="Exception occurred during skill dispatch") | [
"def",
"dispatch_request",
"(",
"self",
")",
":",
"# type: () -> Response",
"if",
"flask_request",
".",
"method",
"!=",
"\"POST\"",
":",
"raise",
"exceptions",
".",
"MethodNotAllowed",
"(",
")",
"try",
":",
"content",
"=",
"flask_request",
".",
"data",
".",
"d... | Method that handles request verification and routing.
This method can be used as a function to register on the URL
rule. The request is verified through the registered list of
verifiers, before invoking the request handlers. The method
returns a JSON response for the Alexa service to respond to the
request.
:return: The skill response for the input request
:rtype: flask.Response
:raises: :py:class:`werkzeug.exceptions.MethodNotAllowed` if the
method is invoked for other than HTTP POST request.
:py:class:`werkzeug.exceptions.BadRequest` if the
verification fails.
:py:class:`werkzeug.exceptions.InternalServerError` for any
internal exception. | [
"Method",
"that",
"handles",
"request",
"verification",
"and",
"routing",
"."
] | 097b6406aa12d5ca0b825b00c936861b530cbf39 | https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/flask-ask-sdk/flask_ask_sdk/skill_adapter.py#L213-L252 | train | 215,371 |
alexa/alexa-skills-kit-sdk-for-python | flask-ask-sdk/flask_ask_sdk/skill_adapter.py | SkillAdapter.register | def register(self, app, route, endpoint=None):
# type: (Flask, str, str) -> None
"""Method to register the routing on the app at provided route.
This is a utility method, that can be used for registering the
``dispatch_request`` on the provided :py:class:`flask.Flask`
application at the provided URL ``route``.
:param app: A :py:class:`flask.Flask` application instance
:type app: flask.Flask
:param route: The URL rule where the skill dispatch has to be
registered
:type route: str
:param endpoint: The endpoint for the registered URL rule.
This can be used to set multiple skill endpoints on same app.
:type endpoint: str
:rtype: None
:raises: :py:class:`TypeError` if ``app`` or `route`` is not
provided or is of an invalid type
"""
if app is None or not isinstance(app, Flask):
raise TypeError("Expected a valid Flask instance")
if route is None or not isinstance(route, str):
raise TypeError("Expected a valid URL rule string")
app.add_url_rule(
route, view_func=self.dispatch_request, methods=["POST"],
endpoint=endpoint) | python | def register(self, app, route, endpoint=None):
# type: (Flask, str, str) -> None
"""Method to register the routing on the app at provided route.
This is a utility method, that can be used for registering the
``dispatch_request`` on the provided :py:class:`flask.Flask`
application at the provided URL ``route``.
:param app: A :py:class:`flask.Flask` application instance
:type app: flask.Flask
:param route: The URL rule where the skill dispatch has to be
registered
:type route: str
:param endpoint: The endpoint for the registered URL rule.
This can be used to set multiple skill endpoints on same app.
:type endpoint: str
:rtype: None
:raises: :py:class:`TypeError` if ``app`` or `route`` is not
provided or is of an invalid type
"""
if app is None or not isinstance(app, Flask):
raise TypeError("Expected a valid Flask instance")
if route is None or not isinstance(route, str):
raise TypeError("Expected a valid URL rule string")
app.add_url_rule(
route, view_func=self.dispatch_request, methods=["POST"],
endpoint=endpoint) | [
"def",
"register",
"(",
"self",
",",
"app",
",",
"route",
",",
"endpoint",
"=",
"None",
")",
":",
"# type: (Flask, str, str) -> None",
"if",
"app",
"is",
"None",
"or",
"not",
"isinstance",
"(",
"app",
",",
"Flask",
")",
":",
"raise",
"TypeError",
"(",
"\... | Method to register the routing on the app at provided route.
This is a utility method, that can be used for registering the
``dispatch_request`` on the provided :py:class:`flask.Flask`
application at the provided URL ``route``.
:param app: A :py:class:`flask.Flask` application instance
:type app: flask.Flask
:param route: The URL rule where the skill dispatch has to be
registered
:type route: str
:param endpoint: The endpoint for the registered URL rule.
This can be used to set multiple skill endpoints on same app.
:type endpoint: str
:rtype: None
:raises: :py:class:`TypeError` if ``app`` or `route`` is not
provided or is of an invalid type | [
"Method",
"to",
"register",
"the",
"routing",
"on",
"the",
"app",
"at",
"provided",
"route",
"."
] | 097b6406aa12d5ca0b825b00c936861b530cbf39 | https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/flask-ask-sdk/flask_ask_sdk/skill_adapter.py#L254-L282 | train | 215,372 |
alexa/alexa-skills-kit-sdk-for-python | ask-sdk-core/ask_sdk_core/serialize.py | DefaultSerializer.serialize | def serialize(self, obj): # type: ignore
# type: (Any) -> Union[Dict[str, Any], List, Tuple, str, int, float, None]
"""Builds a serialized object.
* If obj is None, return None.
* If obj is str, int, long, float, bool, return directly.
* If obj is datetime.datetime, datetime.date convert to
string in iso8601 format.
* If obj is list, serialize each element in the list.
* If obj is dict, return the dict with serialized values.
* If obj is ask sdk model, return the dict with keys resolved
from the union of model's ``attribute_map`` and
``deserialized_types`` and values serialized based on
``deserialized_types``.
* If obj is a generic class instance, return the dict with keys
from instance's ``deserialized_types`` and values serialized
based on ``deserialized_types``.
:param obj: The data to serialize.
:type obj: object
:return: The serialized form of data.
:rtype: Union[Dict[str, Any], List, Tuple, str, int, float, None]
"""
if obj is None:
return None
elif isinstance(obj, self.PRIMITIVE_TYPES):
return obj
elif isinstance(obj, list):
return [self.serialize(sub_obj) for sub_obj in obj]
elif isinstance(obj, tuple):
return tuple(self.serialize(sub_obj) for sub_obj in obj)
elif isinstance(obj, (datetime, date)):
return obj.isoformat()
elif isinstance(obj, Enum):
return obj.value
elif isinstance(obj, decimal.Decimal):
if obj % 1 == 0:
return int(obj)
else:
return float(obj)
if isinstance(obj, dict):
obj_dict = obj
else:
# Convert model obj to dict
# All the non null attributes under `deserialized_types`
# map are considered for serialization.
# The `attribute_map` provides the key names to be used
# in the dict. In case of missing `attribute_map` mapping,
# the original attribute name is retained as the key name.
class_attribute_map = getattr(obj, 'attribute_map', {})
class_attribute_map.update(
{
k: k for k in obj.deserialized_types.keys()
if k not in class_attribute_map
}
)
obj_dict = {
class_attribute_map[attr]: getattr(obj, attr)
for attr, _ in iteritems(obj.deserialized_types)
if getattr(obj, attr) is not None
}
return {key: self.serialize(val) for key, val in iteritems(obj_dict)} | python | def serialize(self, obj): # type: ignore
# type: (Any) -> Union[Dict[str, Any], List, Tuple, str, int, float, None]
"""Builds a serialized object.
* If obj is None, return None.
* If obj is str, int, long, float, bool, return directly.
* If obj is datetime.datetime, datetime.date convert to
string in iso8601 format.
* If obj is list, serialize each element in the list.
* If obj is dict, return the dict with serialized values.
* If obj is ask sdk model, return the dict with keys resolved
from the union of model's ``attribute_map`` and
``deserialized_types`` and values serialized based on
``deserialized_types``.
* If obj is a generic class instance, return the dict with keys
from instance's ``deserialized_types`` and values serialized
based on ``deserialized_types``.
:param obj: The data to serialize.
:type obj: object
:return: The serialized form of data.
:rtype: Union[Dict[str, Any], List, Tuple, str, int, float, None]
"""
if obj is None:
return None
elif isinstance(obj, self.PRIMITIVE_TYPES):
return obj
elif isinstance(obj, list):
return [self.serialize(sub_obj) for sub_obj in obj]
elif isinstance(obj, tuple):
return tuple(self.serialize(sub_obj) for sub_obj in obj)
elif isinstance(obj, (datetime, date)):
return obj.isoformat()
elif isinstance(obj, Enum):
return obj.value
elif isinstance(obj, decimal.Decimal):
if obj % 1 == 0:
return int(obj)
else:
return float(obj)
if isinstance(obj, dict):
obj_dict = obj
else:
# Convert model obj to dict
# All the non null attributes under `deserialized_types`
# map are considered for serialization.
# The `attribute_map` provides the key names to be used
# in the dict. In case of missing `attribute_map` mapping,
# the original attribute name is retained as the key name.
class_attribute_map = getattr(obj, 'attribute_map', {})
class_attribute_map.update(
{
k: k for k in obj.deserialized_types.keys()
if k not in class_attribute_map
}
)
obj_dict = {
class_attribute_map[attr]: getattr(obj, attr)
for attr, _ in iteritems(obj.deserialized_types)
if getattr(obj, attr) is not None
}
return {key: self.serialize(val) for key, val in iteritems(obj_dict)} | [
"def",
"serialize",
"(",
"self",
",",
"obj",
")",
":",
"# type: ignore",
"# type: (Any) -> Union[Dict[str, Any], List, Tuple, str, int, float, None]",
"if",
"obj",
"is",
"None",
":",
"return",
"None",
"elif",
"isinstance",
"(",
"obj",
",",
"self",
".",
"PRIMITIVE_TYPE... | Builds a serialized object.
* If obj is None, return None.
* If obj is str, int, long, float, bool, return directly.
* If obj is datetime.datetime, datetime.date convert to
string in iso8601 format.
* If obj is list, serialize each element in the list.
* If obj is dict, return the dict with serialized values.
* If obj is ask sdk model, return the dict with keys resolved
from the union of model's ``attribute_map`` and
``deserialized_types`` and values serialized based on
``deserialized_types``.
* If obj is a generic class instance, return the dict with keys
from instance's ``deserialized_types`` and values serialized
based on ``deserialized_types``.
:param obj: The data to serialize.
:type obj: object
:return: The serialized form of data.
:rtype: Union[Dict[str, Any], List, Tuple, str, int, float, None] | [
"Builds",
"a",
"serialized",
"object",
"."
] | 097b6406aa12d5ca0b825b00c936861b530cbf39 | https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-core/ask_sdk_core/serialize.py#L61-L125 | train | 215,373 |
alexa/alexa-skills-kit-sdk-for-python | ask-sdk-core/ask_sdk_core/serialize.py | DefaultSerializer.deserialize | def deserialize(self, payload, obj_type):
# type: (str, Union[T, str]) -> Any
"""Deserializes payload into an instance of provided ``obj_type``.
The ``obj_type`` parameter can be a primitive type, a generic
model object or a list / dict of model objects.
The list or dict object type has to be provided as a string
format. For eg:
* ``'list[a.b.C]'`` if the payload is a list of instances of
class ``a.b.C``.
* ``'dict(str, a.b.C)'`` if the payload is a dict containing
mappings of ``str : a.b.C`` class instance types.
The method looks for a ``deserialized_types`` dict in the model
class, that mentions which payload values has to be
deserialized. In case the payload key names are different than
the model attribute names, the corresponding mapping can be
provided in another special dict ``attribute_map``. The model
class should also have the ``__init__`` method with default
values for arguments. Check
:py:class:`ask_sdk_model.request_envelope.RequestEnvelope`
source code for an example implementation.
:param payload: data to be deserialized.
:type payload: str
:param obj_type: resolved class name for deserialized object
:type obj_type: Union[object, str]
:return: deserialized object
:rtype: object
:raises: :py:class:`ask_sdk_core.exceptions.SerializationException`
"""
if payload is None:
return None
try:
payload = json.loads(payload)
except Exception:
raise SerializationException(
"Couldn't parse response body: {}".format(payload))
return self.__deserialize(payload, obj_type) | python | def deserialize(self, payload, obj_type):
# type: (str, Union[T, str]) -> Any
"""Deserializes payload into an instance of provided ``obj_type``.
The ``obj_type`` parameter can be a primitive type, a generic
model object or a list / dict of model objects.
The list or dict object type has to be provided as a string
format. For eg:
* ``'list[a.b.C]'`` if the payload is a list of instances of
class ``a.b.C``.
* ``'dict(str, a.b.C)'`` if the payload is a dict containing
mappings of ``str : a.b.C`` class instance types.
The method looks for a ``deserialized_types`` dict in the model
class, that mentions which payload values has to be
deserialized. In case the payload key names are different than
the model attribute names, the corresponding mapping can be
provided in another special dict ``attribute_map``. The model
class should also have the ``__init__`` method with default
values for arguments. Check
:py:class:`ask_sdk_model.request_envelope.RequestEnvelope`
source code for an example implementation.
:param payload: data to be deserialized.
:type payload: str
:param obj_type: resolved class name for deserialized object
:type obj_type: Union[object, str]
:return: deserialized object
:rtype: object
:raises: :py:class:`ask_sdk_core.exceptions.SerializationException`
"""
if payload is None:
return None
try:
payload = json.loads(payload)
except Exception:
raise SerializationException(
"Couldn't parse response body: {}".format(payload))
return self.__deserialize(payload, obj_type) | [
"def",
"deserialize",
"(",
"self",
",",
"payload",
",",
"obj_type",
")",
":",
"# type: (str, Union[T, str]) -> Any",
"if",
"payload",
"is",
"None",
":",
"return",
"None",
"try",
":",
"payload",
"=",
"json",
".",
"loads",
"(",
"payload",
")",
"except",
"Excep... | Deserializes payload into an instance of provided ``obj_type``.
The ``obj_type`` parameter can be a primitive type, a generic
model object or a list / dict of model objects.
The list or dict object type has to be provided as a string
format. For eg:
* ``'list[a.b.C]'`` if the payload is a list of instances of
class ``a.b.C``.
* ``'dict(str, a.b.C)'`` if the payload is a dict containing
mappings of ``str : a.b.C`` class instance types.
The method looks for a ``deserialized_types`` dict in the model
class, that mentions which payload values has to be
deserialized. In case the payload key names are different than
the model attribute names, the corresponding mapping can be
provided in another special dict ``attribute_map``. The model
class should also have the ``__init__`` method with default
values for arguments. Check
:py:class:`ask_sdk_model.request_envelope.RequestEnvelope`
source code for an example implementation.
:param payload: data to be deserialized.
:type payload: str
:param obj_type: resolved class name for deserialized object
:type obj_type: Union[object, str]
:return: deserialized object
:rtype: object
:raises: :py:class:`ask_sdk_core.exceptions.SerializationException` | [
"Deserializes",
"payload",
"into",
"an",
"instance",
"of",
"provided",
"obj_type",
"."
] | 097b6406aa12d5ca0b825b00c936861b530cbf39 | https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-core/ask_sdk_core/serialize.py#L127-L169 | train | 215,374 |
alexa/alexa-skills-kit-sdk-for-python | ask-sdk-core/ask_sdk_core/serialize.py | DefaultSerializer.__deserialize | def __deserialize(self, payload, obj_type):
# type: (str, Union[T, str]) -> Any
"""Deserializes payload into a model object.
:param payload: data to be deserialized.
:type payload: str
:param obj_type: resolved class name for deserialized object
:type obj_type: Union[object, str]
:return: deserialized object
:rtype: object
"""
if payload is None:
return None
if isinstance(obj_type, str):
if obj_type.startswith('list['):
# Get object type for each item in the list
# Deserialize each item using the object type.
sub_obj_type = re.match(
'list\[(.*)\]', obj_type)
if sub_obj_type is None:
return []
sub_obj_types = sub_obj_type.group(1)
deserialized_list = [] # type: List
if "," in sub_obj_types:
# list contains objects of different types
for sub_payload, sub_obj_types in zip(
payload, sub_obj_types.split(",")):
deserialized_list.append(self.__deserialize(
sub_payload, sub_obj_types.strip()))
else:
for sub_payload in payload:
deserialized_list.append(self.__deserialize(
sub_payload, sub_obj_types.strip()))
return deserialized_list
if obj_type.startswith('dict('):
# Get object type for each k,v pair in the dict
# Deserialize each value using the object type of v.
sub_obj_type = re.match(
'dict\(([^,]*), (.*)\)', obj_type)
if sub_obj_type is None:
return {}
sub_obj_types = sub_obj_type.group(2)
return {
k: self.__deserialize(v, sub_obj_types)
for k, v in iteritems(cast(Any, payload))
}
# convert str to class
if obj_type in self.NATIVE_TYPES_MAPPING:
obj_type = self.NATIVE_TYPES_MAPPING[obj_type] # type: ignore
else:
# deserialize models
obj_type = self.__load_class_from_name(obj_type)
if obj_type in self.PRIMITIVE_TYPES:
return self.__deserialize_primitive(payload, obj_type)
elif obj_type == object:
return payload
elif obj_type == date:
return self.__deserialize_datetime(payload, obj_type)
elif obj_type == datetime:
return self.__deserialize_datetime(payload, obj_type)
else:
return self.__deserialize_model(payload, obj_type) | python | def __deserialize(self, payload, obj_type):
# type: (str, Union[T, str]) -> Any
"""Deserializes payload into a model object.
:param payload: data to be deserialized.
:type payload: str
:param obj_type: resolved class name for deserialized object
:type obj_type: Union[object, str]
:return: deserialized object
:rtype: object
"""
if payload is None:
return None
if isinstance(obj_type, str):
if obj_type.startswith('list['):
# Get object type for each item in the list
# Deserialize each item using the object type.
sub_obj_type = re.match(
'list\[(.*)\]', obj_type)
if sub_obj_type is None:
return []
sub_obj_types = sub_obj_type.group(1)
deserialized_list = [] # type: List
if "," in sub_obj_types:
# list contains objects of different types
for sub_payload, sub_obj_types in zip(
payload, sub_obj_types.split(",")):
deserialized_list.append(self.__deserialize(
sub_payload, sub_obj_types.strip()))
else:
for sub_payload in payload:
deserialized_list.append(self.__deserialize(
sub_payload, sub_obj_types.strip()))
return deserialized_list
if obj_type.startswith('dict('):
# Get object type for each k,v pair in the dict
# Deserialize each value using the object type of v.
sub_obj_type = re.match(
'dict\(([^,]*), (.*)\)', obj_type)
if sub_obj_type is None:
return {}
sub_obj_types = sub_obj_type.group(2)
return {
k: self.__deserialize(v, sub_obj_types)
for k, v in iteritems(cast(Any, payload))
}
# convert str to class
if obj_type in self.NATIVE_TYPES_MAPPING:
obj_type = self.NATIVE_TYPES_MAPPING[obj_type] # type: ignore
else:
# deserialize models
obj_type = self.__load_class_from_name(obj_type)
if obj_type in self.PRIMITIVE_TYPES:
return self.__deserialize_primitive(payload, obj_type)
elif obj_type == object:
return payload
elif obj_type == date:
return self.__deserialize_datetime(payload, obj_type)
elif obj_type == datetime:
return self.__deserialize_datetime(payload, obj_type)
else:
return self.__deserialize_model(payload, obj_type) | [
"def",
"__deserialize",
"(",
"self",
",",
"payload",
",",
"obj_type",
")",
":",
"# type: (str, Union[T, str]) -> Any",
"if",
"payload",
"is",
"None",
":",
"return",
"None",
"if",
"isinstance",
"(",
"obj_type",
",",
"str",
")",
":",
"if",
"obj_type",
".",
"st... | Deserializes payload into a model object.
:param payload: data to be deserialized.
:type payload: str
:param obj_type: resolved class name for deserialized object
:type obj_type: Union[object, str]
:return: deserialized object
:rtype: object | [
"Deserializes",
"payload",
"into",
"a",
"model",
"object",
"."
] | 097b6406aa12d5ca0b825b00c936861b530cbf39 | https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-core/ask_sdk_core/serialize.py#L171-L235 | train | 215,375 |
alexa/alexa-skills-kit-sdk-for-python | ask-sdk-core/ask_sdk_core/serialize.py | DefaultSerializer.__load_class_from_name | def __load_class_from_name(self, class_name):
# type: (str) -> T
"""Load the class from the ``class_name`` provided.
Resolve the class name from the ``class_name`` provided, load
the class on path and return the resolved class. If the module
information is not provided in the ``class_name``, then look
for the class on sys ``modules``.
:param class_name: absolute class name to be loaded
:type class_name: str
:return: Resolved class reference
:rtype: object
:raises: :py:class:`ask_sdk_core.exceptions.SerializationException`
"""
try:
module_class_list = class_name.rsplit(".", 1)
if len(module_class_list) > 1:
module_name = module_class_list[0]
resolved_class_name = module_class_list[1]
module = __import__(
module_name, fromlist=[resolved_class_name])
resolved_class = getattr(module, resolved_class_name)
else:
resolved_class_name = module_class_list[0]
resolved_class = getattr(
sys.modules[__name__], resolved_class_name)
return resolved_class
except Exception as e:
raise SerializationException(
"Unable to resolve class {} from installed "
"modules: {}".format(class_name, str(e))) | python | def __load_class_from_name(self, class_name):
# type: (str) -> T
"""Load the class from the ``class_name`` provided.
Resolve the class name from the ``class_name`` provided, load
the class on path and return the resolved class. If the module
information is not provided in the ``class_name``, then look
for the class on sys ``modules``.
:param class_name: absolute class name to be loaded
:type class_name: str
:return: Resolved class reference
:rtype: object
:raises: :py:class:`ask_sdk_core.exceptions.SerializationException`
"""
try:
module_class_list = class_name.rsplit(".", 1)
if len(module_class_list) > 1:
module_name = module_class_list[0]
resolved_class_name = module_class_list[1]
module = __import__(
module_name, fromlist=[resolved_class_name])
resolved_class = getattr(module, resolved_class_name)
else:
resolved_class_name = module_class_list[0]
resolved_class = getattr(
sys.modules[__name__], resolved_class_name)
return resolved_class
except Exception as e:
raise SerializationException(
"Unable to resolve class {} from installed "
"modules: {}".format(class_name, str(e))) | [
"def",
"__load_class_from_name",
"(",
"self",
",",
"class_name",
")",
":",
"# type: (str) -> T",
"try",
":",
"module_class_list",
"=",
"class_name",
".",
"rsplit",
"(",
"\".\"",
",",
"1",
")",
"if",
"len",
"(",
"module_class_list",
")",
">",
"1",
":",
"modul... | Load the class from the ``class_name`` provided.
Resolve the class name from the ``class_name`` provided, load
the class on path and return the resolved class. If the module
information is not provided in the ``class_name``, then look
for the class on sys ``modules``.
:param class_name: absolute class name to be loaded
:type class_name: str
:return: Resolved class reference
:rtype: object
:raises: :py:class:`ask_sdk_core.exceptions.SerializationException` | [
"Load",
"the",
"class",
"from",
"the",
"class_name",
"provided",
"."
] | 097b6406aa12d5ca0b825b00c936861b530cbf39 | https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-core/ask_sdk_core/serialize.py#L237-L268 | train | 215,376 |
alexa/alexa-skills-kit-sdk-for-python | ask-sdk-core/ask_sdk_core/serialize.py | DefaultSerializer.__deserialize_primitive | def __deserialize_primitive(self, payload, obj_type):
# type: (str, Union[T, str]) -> Any
"""Deserialize primitive datatypes.
:param payload: data to be deserialized
:type payload: str
:param obj_type: primitive datatype str
:type obj_type: Union[object, str]
:return: deserialized primitive datatype object
:rtype: object
:raises: :py:class:`ask_sdk_core.exceptions.SerializationException`
"""
obj_cast = cast(Any, obj_type)
try:
return obj_cast(payload)
except UnicodeEncodeError:
return unicode_type(payload)
except TypeError:
return payload
except ValueError:
raise SerializationException(
"Failed to parse {} into '{}' object".format(
payload, obj_cast.__name__)) | python | def __deserialize_primitive(self, payload, obj_type):
# type: (str, Union[T, str]) -> Any
"""Deserialize primitive datatypes.
:param payload: data to be deserialized
:type payload: str
:param obj_type: primitive datatype str
:type obj_type: Union[object, str]
:return: deserialized primitive datatype object
:rtype: object
:raises: :py:class:`ask_sdk_core.exceptions.SerializationException`
"""
obj_cast = cast(Any, obj_type)
try:
return obj_cast(payload)
except UnicodeEncodeError:
return unicode_type(payload)
except TypeError:
return payload
except ValueError:
raise SerializationException(
"Failed to parse {} into '{}' object".format(
payload, obj_cast.__name__)) | [
"def",
"__deserialize_primitive",
"(",
"self",
",",
"payload",
",",
"obj_type",
")",
":",
"# type: (str, Union[T, str]) -> Any",
"obj_cast",
"=",
"cast",
"(",
"Any",
",",
"obj_type",
")",
"try",
":",
"return",
"obj_cast",
"(",
"payload",
")",
"except",
"UnicodeE... | Deserialize primitive datatypes.
:param payload: data to be deserialized
:type payload: str
:param obj_type: primitive datatype str
:type obj_type: Union[object, str]
:return: deserialized primitive datatype object
:rtype: object
:raises: :py:class:`ask_sdk_core.exceptions.SerializationException` | [
"Deserialize",
"primitive",
"datatypes",
"."
] | 097b6406aa12d5ca0b825b00c936861b530cbf39 | https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-core/ask_sdk_core/serialize.py#L270-L292 | train | 215,377 |
alexa/alexa-skills-kit-sdk-for-python | ask-sdk-core/ask_sdk_core/serialize.py | DefaultSerializer.__deserialize_model | def __deserialize_model(self, payload, obj_type):
# type: (str, Union[T, str]) -> Any
"""Deserialize instance to model object.
:param payload: data to be deserialized
:type payload: str
:param obj_type: sdk model class
:type obj_type: Union[object, str]
:return: deserialized sdk model object
:rtype: object
:raises: :py:class:`ask_sdk_core.exceptions.SerializationException`
"""
try:
obj_cast = cast(Any, obj_type)
if issubclass(obj_cast, Enum):
return obj_cast(payload)
if hasattr(obj_cast, 'deserialized_types'):
if hasattr(obj_cast, 'get_real_child_model'):
obj_cast = self.__get_obj_by_discriminator(
payload, obj_cast)
class_deserialized_types = obj_cast.deserialized_types
class_attribute_map = getattr(obj_cast, 'attribute_map', {})
class_attribute_map.update(
{
k: k for k in obj_cast.deserialized_types.keys()
if k not in class_attribute_map
}
)
deserialized_model = obj_cast()
for class_param_name, payload_param_name in iteritems(
class_attribute_map):
if payload_param_name in payload:
setattr(
deserialized_model,
class_param_name,
self.__deserialize(
payload[payload_param_name],
class_deserialized_types[class_param_name]))
additional_params = [
param for param in payload
if param not in class_attribute_map.values()]
for add_param in additional_params:
setattr(deserialized_model, add_param, payload[cast(Any,add_param)])
return deserialized_model
else:
return payload
except Exception as e:
raise SerializationException(str(e)) | python | def __deserialize_model(self, payload, obj_type):
# type: (str, Union[T, str]) -> Any
"""Deserialize instance to model object.
:param payload: data to be deserialized
:type payload: str
:param obj_type: sdk model class
:type obj_type: Union[object, str]
:return: deserialized sdk model object
:rtype: object
:raises: :py:class:`ask_sdk_core.exceptions.SerializationException`
"""
try:
obj_cast = cast(Any, obj_type)
if issubclass(obj_cast, Enum):
return obj_cast(payload)
if hasattr(obj_cast, 'deserialized_types'):
if hasattr(obj_cast, 'get_real_child_model'):
obj_cast = self.__get_obj_by_discriminator(
payload, obj_cast)
class_deserialized_types = obj_cast.deserialized_types
class_attribute_map = getattr(obj_cast, 'attribute_map', {})
class_attribute_map.update(
{
k: k for k in obj_cast.deserialized_types.keys()
if k not in class_attribute_map
}
)
deserialized_model = obj_cast()
for class_param_name, payload_param_name in iteritems(
class_attribute_map):
if payload_param_name in payload:
setattr(
deserialized_model,
class_param_name,
self.__deserialize(
payload[payload_param_name],
class_deserialized_types[class_param_name]))
additional_params = [
param for param in payload
if param not in class_attribute_map.values()]
for add_param in additional_params:
setattr(deserialized_model, add_param, payload[cast(Any,add_param)])
return deserialized_model
else:
return payload
except Exception as e:
raise SerializationException(str(e)) | [
"def",
"__deserialize_model",
"(",
"self",
",",
"payload",
",",
"obj_type",
")",
":",
"# type: (str, Union[T, str]) -> Any",
"try",
":",
"obj_cast",
"=",
"cast",
"(",
"Any",
",",
"obj_type",
")",
"if",
"issubclass",
"(",
"obj_cast",
",",
"Enum",
")",
":",
"r... | Deserialize instance to model object.
:param payload: data to be deserialized
:type payload: str
:param obj_type: sdk model class
:type obj_type: Union[object, str]
:return: deserialized sdk model object
:rtype: object
:raises: :py:class:`ask_sdk_core.exceptions.SerializationException` | [
"Deserialize",
"instance",
"to",
"model",
"object",
"."
] | 097b6406aa12d5ca0b825b00c936861b530cbf39 | https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-core/ask_sdk_core/serialize.py#L322-L374 | train | 215,378 |
alexa/alexa-skills-kit-sdk-for-python | ask-sdk-core/ask_sdk_core/serialize.py | DefaultSerializer.__get_obj_by_discriminator | def __get_obj_by_discriminator(self, payload, obj_type):
# type: (str, Union[T, str]) -> T
"""Get correct subclass instance using the discriminator in
payload.
:param payload: Payload for deserialization
:type payload: str
:param obj_type: parent class for deserializing payload into
:type obj_type: Union[object, str]
:return: Subclass of provided parent class, that resolves to
the discriminator in payload.
:rtype: object
:raises: :py:class:`ask_sdk_core.exceptions.SerializationException`
"""
obj_cast = cast(Any, obj_type)
namespaced_class_name = obj_cast.get_real_child_model(payload)
if not namespaced_class_name:
raise SerializationException(
"Couldn't resolve object by discriminator type "
"for {} class".format(obj_type))
return self.__load_class_from_name(namespaced_class_name) | python | def __get_obj_by_discriminator(self, payload, obj_type):
# type: (str, Union[T, str]) -> T
"""Get correct subclass instance using the discriminator in
payload.
:param payload: Payload for deserialization
:type payload: str
:param obj_type: parent class for deserializing payload into
:type obj_type: Union[object, str]
:return: Subclass of provided parent class, that resolves to
the discriminator in payload.
:rtype: object
:raises: :py:class:`ask_sdk_core.exceptions.SerializationException`
"""
obj_cast = cast(Any, obj_type)
namespaced_class_name = obj_cast.get_real_child_model(payload)
if not namespaced_class_name:
raise SerializationException(
"Couldn't resolve object by discriminator type "
"for {} class".format(obj_type))
return self.__load_class_from_name(namespaced_class_name) | [
"def",
"__get_obj_by_discriminator",
"(",
"self",
",",
"payload",
",",
"obj_type",
")",
":",
"# type: (str, Union[T, str]) -> T",
"obj_cast",
"=",
"cast",
"(",
"Any",
",",
"obj_type",
")",
"namespaced_class_name",
"=",
"obj_cast",
".",
"get_real_child_model",
"(",
"... | Get correct subclass instance using the discriminator in
payload.
:param payload: Payload for deserialization
:type payload: str
:param obj_type: parent class for deserializing payload into
:type obj_type: Union[object, str]
:return: Subclass of provided parent class, that resolves to
the discriminator in payload.
:rtype: object
:raises: :py:class:`ask_sdk_core.exceptions.SerializationException` | [
"Get",
"correct",
"subclass",
"instance",
"using",
"the",
"discriminator",
"in",
"payload",
"."
] | 097b6406aa12d5ca0b825b00c936861b530cbf39 | https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-core/ask_sdk_core/serialize.py#L376-L397 | train | 215,379 |
alexa/alexa-skills-kit-sdk-for-python | ask-sdk-core/ask_sdk_core/attributes_manager.py | AttributesManager.persistent_attributes | def persistent_attributes(self):
# type: () -> Dict[str, object]
"""Attributes stored at the Persistence level of the skill lifecycle.
:return: persistent_attributes retrieved from persistence adapter
:rtype: Dict[str, object]
:raises: :py:class:`ask_sdk_core.exceptions.AttributesManagerException`
if trying to get persistent attributes without persistence adapter
"""
if not self._persistence_adapter:
raise AttributesManagerException(
"Cannot get PersistentAttributes without Persistence adapter")
if not self._persistent_attributes_set:
self._persistence_attributes = (
self._persistence_adapter.get_attributes(
request_envelope=self._request_envelope))
self._persistent_attributes_set = True
return self._persistence_attributes | python | def persistent_attributes(self):
# type: () -> Dict[str, object]
"""Attributes stored at the Persistence level of the skill lifecycle.
:return: persistent_attributes retrieved from persistence adapter
:rtype: Dict[str, object]
:raises: :py:class:`ask_sdk_core.exceptions.AttributesManagerException`
if trying to get persistent attributes without persistence adapter
"""
if not self._persistence_adapter:
raise AttributesManagerException(
"Cannot get PersistentAttributes without Persistence adapter")
if not self._persistent_attributes_set:
self._persistence_attributes = (
self._persistence_adapter.get_attributes(
request_envelope=self._request_envelope))
self._persistent_attributes_set = True
return self._persistence_attributes | [
"def",
"persistent_attributes",
"(",
"self",
")",
":",
"# type: () -> Dict[str, object]",
"if",
"not",
"self",
".",
"_persistence_adapter",
":",
"raise",
"AttributesManagerException",
"(",
"\"Cannot get PersistentAttributes without Persistence adapter\"",
")",
"if",
"not",
"s... | Attributes stored at the Persistence level of the skill lifecycle.
:return: persistent_attributes retrieved from persistence adapter
:rtype: Dict[str, object]
:raises: :py:class:`ask_sdk_core.exceptions.AttributesManagerException`
if trying to get persistent attributes without persistence adapter | [
"Attributes",
"stored",
"at",
"the",
"Persistence",
"level",
"of",
"the",
"skill",
"lifecycle",
"."
] | 097b6406aa12d5ca0b825b00c936861b530cbf39 | https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-core/ask_sdk_core/attributes_manager.py#L165-L182 | train | 215,380 |
alexa/alexa-skills-kit-sdk-for-python | ask-sdk-core/ask_sdk_core/attributes_manager.py | AttributesManager.persistent_attributes | def persistent_attributes(self, persistent_attributes):
# type: (Dict[str, object]) -> None
"""Overwrites and caches the persistent attributes value.
Note that the persistent attributes will not be saved to
persistence layer until the save_persistent_attributes method
is called.
:param persistent_attributes: attributes in persistence layer
:type persistent_attributes: Dict[str, object]
:raises: :py:class:`ask_sdk_core.exceptions.AttributesManagerException`
if trying to set persistent attributes without persistence adapter
"""
if not self._persistence_adapter:
raise AttributesManagerException(
"Cannot set PersistentAttributes without persistence adapter!")
self._persistence_attributes = persistent_attributes
self._persistent_attributes_set = True | python | def persistent_attributes(self, persistent_attributes):
# type: (Dict[str, object]) -> None
"""Overwrites and caches the persistent attributes value.
Note that the persistent attributes will not be saved to
persistence layer until the save_persistent_attributes method
is called.
:param persistent_attributes: attributes in persistence layer
:type persistent_attributes: Dict[str, object]
:raises: :py:class:`ask_sdk_core.exceptions.AttributesManagerException`
if trying to set persistent attributes without persistence adapter
"""
if not self._persistence_adapter:
raise AttributesManagerException(
"Cannot set PersistentAttributes without persistence adapter!")
self._persistence_attributes = persistent_attributes
self._persistent_attributes_set = True | [
"def",
"persistent_attributes",
"(",
"self",
",",
"persistent_attributes",
")",
":",
"# type: (Dict[str, object]) -> None",
"if",
"not",
"self",
".",
"_persistence_adapter",
":",
"raise",
"AttributesManagerException",
"(",
"\"Cannot set PersistentAttributes without persistence ad... | Overwrites and caches the persistent attributes value.
Note that the persistent attributes will not be saved to
persistence layer until the save_persistent_attributes method
is called.
:param persistent_attributes: attributes in persistence layer
:type persistent_attributes: Dict[str, object]
:raises: :py:class:`ask_sdk_core.exceptions.AttributesManagerException`
if trying to set persistent attributes without persistence adapter | [
"Overwrites",
"and",
"caches",
"the",
"persistent",
"attributes",
"value",
"."
] | 097b6406aa12d5ca0b825b00c936861b530cbf39 | https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-core/ask_sdk_core/attributes_manager.py#L185-L202 | train | 215,381 |
alexa/alexa-skills-kit-sdk-for-python | ask-sdk-core/ask_sdk_core/attributes_manager.py | AttributesManager.save_persistent_attributes | def save_persistent_attributes(self):
# type: () -> None
"""Save persistent attributes to the persistence layer if a
persistence adapter is provided.
:rtype: None
:raises: :py:class:`ask_sdk_core.exceptions.AttributesManagerException`
if trying to save persistence attributes without persistence adapter
"""
if not self._persistence_adapter:
raise AttributesManagerException(
"Cannot save PersistentAttributes without "
"persistence adapter!")
if self._persistent_attributes_set:
self._persistence_adapter.save_attributes(
request_envelope=self._request_envelope,
attributes=self._persistence_attributes) | python | def save_persistent_attributes(self):
# type: () -> None
"""Save persistent attributes to the persistence layer if a
persistence adapter is provided.
:rtype: None
:raises: :py:class:`ask_sdk_core.exceptions.AttributesManagerException`
if trying to save persistence attributes without persistence adapter
"""
if not self._persistence_adapter:
raise AttributesManagerException(
"Cannot save PersistentAttributes without "
"persistence adapter!")
if self._persistent_attributes_set:
self._persistence_adapter.save_attributes(
request_envelope=self._request_envelope,
attributes=self._persistence_attributes) | [
"def",
"save_persistent_attributes",
"(",
"self",
")",
":",
"# type: () -> None",
"if",
"not",
"self",
".",
"_persistence_adapter",
":",
"raise",
"AttributesManagerException",
"(",
"\"Cannot save PersistentAttributes without \"",
"\"persistence adapter!\"",
")",
"if",
"self",... | Save persistent attributes to the persistence layer if a
persistence adapter is provided.
:rtype: None
:raises: :py:class:`ask_sdk_core.exceptions.AttributesManagerException`
if trying to save persistence attributes without persistence adapter | [
"Save",
"persistent",
"attributes",
"to",
"the",
"persistence",
"layer",
"if",
"a",
"persistence",
"adapter",
"is",
"provided",
"."
] | 097b6406aa12d5ca0b825b00c936861b530cbf39 | https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-core/ask_sdk_core/attributes_manager.py#L204-L220 | train | 215,382 |
alexa/alexa-skills-kit-sdk-for-python | ask-sdk-runtime/ask_sdk_runtime/utils.py | user_agent_info | def user_agent_info(sdk_version, custom_user_agent):
# type: (str, str) -> str
"""Return the user agent info along with the SDK and Python
Version information.
:param sdk_version: Version of the SDK being used.
:type sdk_version: str
:param custom_user_agent: Custom User Agent string provided by
the developer.
:type custom_user_agent: str
:return: User Agent Info string
:rtype: str
"""
python_version = ".".join(str(x) for x in sys.version_info[0:3])
user_agent = "ask-python/{} Python/{}".format(
sdk_version, python_version)
if custom_user_agent is None:
return user_agent
else:
return user_agent + " {}".format(custom_user_agent) | python | def user_agent_info(sdk_version, custom_user_agent):
# type: (str, str) -> str
"""Return the user agent info along with the SDK and Python
Version information.
:param sdk_version: Version of the SDK being used.
:type sdk_version: str
:param custom_user_agent: Custom User Agent string provided by
the developer.
:type custom_user_agent: str
:return: User Agent Info string
:rtype: str
"""
python_version = ".".join(str(x) for x in sys.version_info[0:3])
user_agent = "ask-python/{} Python/{}".format(
sdk_version, python_version)
if custom_user_agent is None:
return user_agent
else:
return user_agent + " {}".format(custom_user_agent) | [
"def",
"user_agent_info",
"(",
"sdk_version",
",",
"custom_user_agent",
")",
":",
"# type: (str, str) -> str",
"python_version",
"=",
"\".\"",
".",
"join",
"(",
"str",
"(",
"x",
")",
"for",
"x",
"in",
"sys",
".",
"version_info",
"[",
"0",
":",
"3",
"]",
")... | Return the user agent info along with the SDK and Python
Version information.
:param sdk_version: Version of the SDK being used.
:type sdk_version: str
:param custom_user_agent: Custom User Agent string provided by
the developer.
:type custom_user_agent: str
:return: User Agent Info string
:rtype: str | [
"Return",
"the",
"user",
"agent",
"info",
"along",
"with",
"the",
"SDK",
"and",
"Python",
"Version",
"information",
"."
] | 097b6406aa12d5ca0b825b00c936861b530cbf39 | https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-runtime/ask_sdk_runtime/utils.py#L20-L39 | train | 215,383 |
alexa/alexa-skills-kit-sdk-for-python | ask-sdk-dynamodb-persistence-adapter/ask_sdk_dynamodb/adapter.py | DynamoDbAdapter.get_attributes | def get_attributes(self, request_envelope):
# type: (RequestEnvelope) -> Dict[str, object]
"""Get attributes from table in Dynamodb resource.
Retrieves the attributes from Dynamodb table. If the table
doesn't exist, returns an empty dict if the
``create_table`` variable is set as True, else it raises
PersistenceException. Raises PersistenceException if `get_item`
fails on the table.
:param request_envelope: Request Envelope passed during skill
invocation
:type request_envelope: ask_sdk_model.RequestEnvelope
:return: Attributes stored under the partition keygen mapping
in the table
:rtype: Dict[str, object]
:raises: :py:class:`ask_sdk_core.exceptions.PersistenceException`
"""
try:
table = self.dynamodb.Table(self.table_name)
partition_key_val = self.partition_keygen(request_envelope)
response = table.get_item(
Key={self.partition_key_name: partition_key_val},
ConsistentRead=True)
if "Item" in response:
return response["Item"][self.attribute_name]
else:
return {}
except ResourceNotExistsError:
raise PersistenceException(
"DynamoDb table {} doesn't exist or in the process of "
"being created. Failed to get attributes from "
"DynamoDb table.".format(self.table_name))
except Exception as e:
raise PersistenceException(
"Failed to retrieve attributes from DynamoDb table. "
"Exception of type {} occurred: {}".format(
type(e).__name__, str(e))) | python | def get_attributes(self, request_envelope):
# type: (RequestEnvelope) -> Dict[str, object]
"""Get attributes from table in Dynamodb resource.
Retrieves the attributes from Dynamodb table. If the table
doesn't exist, returns an empty dict if the
``create_table`` variable is set as True, else it raises
PersistenceException. Raises PersistenceException if `get_item`
fails on the table.
:param request_envelope: Request Envelope passed during skill
invocation
:type request_envelope: ask_sdk_model.RequestEnvelope
:return: Attributes stored under the partition keygen mapping
in the table
:rtype: Dict[str, object]
:raises: :py:class:`ask_sdk_core.exceptions.PersistenceException`
"""
try:
table = self.dynamodb.Table(self.table_name)
partition_key_val = self.partition_keygen(request_envelope)
response = table.get_item(
Key={self.partition_key_name: partition_key_val},
ConsistentRead=True)
if "Item" in response:
return response["Item"][self.attribute_name]
else:
return {}
except ResourceNotExistsError:
raise PersistenceException(
"DynamoDb table {} doesn't exist or in the process of "
"being created. Failed to get attributes from "
"DynamoDb table.".format(self.table_name))
except Exception as e:
raise PersistenceException(
"Failed to retrieve attributes from DynamoDb table. "
"Exception of type {} occurred: {}".format(
type(e).__name__, str(e))) | [
"def",
"get_attributes",
"(",
"self",
",",
"request_envelope",
")",
":",
"# type: (RequestEnvelope) -> Dict[str, object]",
"try",
":",
"table",
"=",
"self",
".",
"dynamodb",
".",
"Table",
"(",
"self",
".",
"table_name",
")",
"partition_key_val",
"=",
"self",
".",
... | Get attributes from table in Dynamodb resource.
Retrieves the attributes from Dynamodb table. If the table
doesn't exist, returns an empty dict if the
``create_table`` variable is set as True, else it raises
PersistenceException. Raises PersistenceException if `get_item`
fails on the table.
:param request_envelope: Request Envelope passed during skill
invocation
:type request_envelope: ask_sdk_model.RequestEnvelope
:return: Attributes stored under the partition keygen mapping
in the table
:rtype: Dict[str, object]
:raises: :py:class:`ask_sdk_core.exceptions.PersistenceException` | [
"Get",
"attributes",
"from",
"table",
"in",
"Dynamodb",
"resource",
"."
] | 097b6406aa12d5ca0b825b00c936861b530cbf39 | https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-dynamodb-persistence-adapter/ask_sdk_dynamodb/adapter.py#L104-L141 | train | 215,384 |
alexa/alexa-skills-kit-sdk-for-python | ask-sdk-dynamodb-persistence-adapter/ask_sdk_dynamodb/adapter.py | DynamoDbAdapter.save_attributes | def save_attributes(self, request_envelope, attributes):
# type: (RequestEnvelope, Dict[str, object]) -> None
"""Saves attributes to table in Dynamodb resource.
Saves the attributes into Dynamodb table. Raises
PersistenceException if table doesn't exist or ``put_item`` fails
on the table.
:param request_envelope: Request Envelope passed during skill
invocation
:type request_envelope: ask_sdk_model.RequestEnvelope
:param attributes: Attributes stored under the partition keygen
mapping in the table
:type attributes: Dict[str, object]
:rtype: None
:raises: :py:class:`ask_sdk_core.exceptions.PersistenceException`
"""
try:
table = self.dynamodb.Table(self.table_name)
partition_key_val = self.partition_keygen(request_envelope)
table.put_item(
Item={self.partition_key_name: partition_key_val,
self.attribute_name: attributes})
except ResourceNotExistsError:
raise PersistenceException(
"DynamoDb table {} doesn't exist. Failed to save attributes "
"to DynamoDb table.".format(
self.table_name))
except Exception as e:
raise PersistenceException(
"Failed to save attributes to DynamoDb table. Exception of "
"type {} occurred: {}".format(
type(e).__name__, str(e))) | python | def save_attributes(self, request_envelope, attributes):
# type: (RequestEnvelope, Dict[str, object]) -> None
"""Saves attributes to table in Dynamodb resource.
Saves the attributes into Dynamodb table. Raises
PersistenceException if table doesn't exist or ``put_item`` fails
on the table.
:param request_envelope: Request Envelope passed during skill
invocation
:type request_envelope: ask_sdk_model.RequestEnvelope
:param attributes: Attributes stored under the partition keygen
mapping in the table
:type attributes: Dict[str, object]
:rtype: None
:raises: :py:class:`ask_sdk_core.exceptions.PersistenceException`
"""
try:
table = self.dynamodb.Table(self.table_name)
partition_key_val = self.partition_keygen(request_envelope)
table.put_item(
Item={self.partition_key_name: partition_key_val,
self.attribute_name: attributes})
except ResourceNotExistsError:
raise PersistenceException(
"DynamoDb table {} doesn't exist. Failed to save attributes "
"to DynamoDb table.".format(
self.table_name))
except Exception as e:
raise PersistenceException(
"Failed to save attributes to DynamoDb table. Exception of "
"type {} occurred: {}".format(
type(e).__name__, str(e))) | [
"def",
"save_attributes",
"(",
"self",
",",
"request_envelope",
",",
"attributes",
")",
":",
"# type: (RequestEnvelope, Dict[str, object]) -> None",
"try",
":",
"table",
"=",
"self",
".",
"dynamodb",
".",
"Table",
"(",
"self",
".",
"table_name",
")",
"partition_key_... | Saves attributes to table in Dynamodb resource.
Saves the attributes into Dynamodb table. Raises
PersistenceException if table doesn't exist or ``put_item`` fails
on the table.
:param request_envelope: Request Envelope passed during skill
invocation
:type request_envelope: ask_sdk_model.RequestEnvelope
:param attributes: Attributes stored under the partition keygen
mapping in the table
:type attributes: Dict[str, object]
:rtype: None
:raises: :py:class:`ask_sdk_core.exceptions.PersistenceException` | [
"Saves",
"attributes",
"to",
"table",
"in",
"Dynamodb",
"resource",
"."
] | 097b6406aa12d5ca0b825b00c936861b530cbf39 | https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-dynamodb-persistence-adapter/ask_sdk_dynamodb/adapter.py#L143-L175 | train | 215,385 |
alexa/alexa-skills-kit-sdk-for-python | ask-sdk-dynamodb-persistence-adapter/ask_sdk_dynamodb/adapter.py | DynamoDbAdapter.delete_attributes | def delete_attributes(self, request_envelope):
# type: (RequestEnvelope) -> None
"""Deletes attributes from table in Dynamodb resource.
Deletes the attributes from Dynamodb table. Raises
PersistenceException if table doesn't exist or ``delete_item`` fails
on the table.
:param request_envelope: Request Envelope passed during skill
invocation
:type request_envelope: ask_sdk_model.RequestEnvelope
:rtype: None
:raises: :py:class:`ask_sdk_core.exceptions.PersistenceException`
"""
try:
table = self.dynamodb.Table(self.table_name)
partition_key_val = self.partition_keygen(request_envelope)
table.delete_item(
Key={self.partition_key_name: partition_key_val})
except ResourceNotExistsError:
raise PersistenceException(
"DynamoDb table {} doesn't exist. Failed to delete attributes "
"from DynamoDb table.".format(
self.table_name))
except Exception as e:
raise PersistenceException(
"Failed to delete attributes in DynamoDb table. Exception of "
"type {} occurred: {}".format(
type(e).__name__, str(e))) | python | def delete_attributes(self, request_envelope):
# type: (RequestEnvelope) -> None
"""Deletes attributes from table in Dynamodb resource.
Deletes the attributes from Dynamodb table. Raises
PersistenceException if table doesn't exist or ``delete_item`` fails
on the table.
:param request_envelope: Request Envelope passed during skill
invocation
:type request_envelope: ask_sdk_model.RequestEnvelope
:rtype: None
:raises: :py:class:`ask_sdk_core.exceptions.PersistenceException`
"""
try:
table = self.dynamodb.Table(self.table_name)
partition_key_val = self.partition_keygen(request_envelope)
table.delete_item(
Key={self.partition_key_name: partition_key_val})
except ResourceNotExistsError:
raise PersistenceException(
"DynamoDb table {} doesn't exist. Failed to delete attributes "
"from DynamoDb table.".format(
self.table_name))
except Exception as e:
raise PersistenceException(
"Failed to delete attributes in DynamoDb table. Exception of "
"type {} occurred: {}".format(
type(e).__name__, str(e))) | [
"def",
"delete_attributes",
"(",
"self",
",",
"request_envelope",
")",
":",
"# type: (RequestEnvelope) -> None",
"try",
":",
"table",
"=",
"self",
".",
"dynamodb",
".",
"Table",
"(",
"self",
".",
"table_name",
")",
"partition_key_val",
"=",
"self",
".",
"partiti... | Deletes attributes from table in Dynamodb resource.
Deletes the attributes from Dynamodb table. Raises
PersistenceException if table doesn't exist or ``delete_item`` fails
on the table.
:param request_envelope: Request Envelope passed during skill
invocation
:type request_envelope: ask_sdk_model.RequestEnvelope
:rtype: None
:raises: :py:class:`ask_sdk_core.exceptions.PersistenceException` | [
"Deletes",
"attributes",
"from",
"table",
"in",
"Dynamodb",
"resource",
"."
] | 097b6406aa12d5ca0b825b00c936861b530cbf39 | https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-dynamodb-persistence-adapter/ask_sdk_dynamodb/adapter.py#L177-L205 | train | 215,386 |
alexa/alexa-skills-kit-sdk-for-python | ask-sdk-dynamodb-persistence-adapter/ask_sdk_dynamodb/adapter.py | DynamoDbAdapter.__create_table_if_not_exists | def __create_table_if_not_exists(self):
# type: () -> None
"""Creates table in Dynamodb resource if it doesn't exist and
create_table is set as True.
:rtype: None
:raises: PersistenceException: When `create_table` fails on
dynamodb resource.
"""
if self.create_table:
try:
self.dynamodb.create_table(
TableName=self.table_name,
KeySchema=[
{
'AttributeName': self.partition_key_name,
'KeyType': 'HASH'
}
],
AttributeDefinitions=[
{
'AttributeName': self.partition_key_name,
'AttributeType': 'S'
}
],
ProvisionedThroughput={
'ReadCapacityUnits': 5,
'WriteCapacityUnits': 5
}
)
except Exception as e:
if e.__class__.__name__ != "ResourceInUseException":
raise PersistenceException(
"Create table if not exists request "
"failed: Exception of type {} "
"occurred: {}".format(
type(e).__name__, str(e))) | python | def __create_table_if_not_exists(self):
# type: () -> None
"""Creates table in Dynamodb resource if it doesn't exist and
create_table is set as True.
:rtype: None
:raises: PersistenceException: When `create_table` fails on
dynamodb resource.
"""
if self.create_table:
try:
self.dynamodb.create_table(
TableName=self.table_name,
KeySchema=[
{
'AttributeName': self.partition_key_name,
'KeyType': 'HASH'
}
],
AttributeDefinitions=[
{
'AttributeName': self.partition_key_name,
'AttributeType': 'S'
}
],
ProvisionedThroughput={
'ReadCapacityUnits': 5,
'WriteCapacityUnits': 5
}
)
except Exception as e:
if e.__class__.__name__ != "ResourceInUseException":
raise PersistenceException(
"Create table if not exists request "
"failed: Exception of type {} "
"occurred: {}".format(
type(e).__name__, str(e))) | [
"def",
"__create_table_if_not_exists",
"(",
"self",
")",
":",
"# type: () -> None",
"if",
"self",
".",
"create_table",
":",
"try",
":",
"self",
".",
"dynamodb",
".",
"create_table",
"(",
"TableName",
"=",
"self",
".",
"table_name",
",",
"KeySchema",
"=",
"[",
... | Creates table in Dynamodb resource if it doesn't exist and
create_table is set as True.
:rtype: None
:raises: PersistenceException: When `create_table` fails on
dynamodb resource. | [
"Creates",
"table",
"in",
"Dynamodb",
"resource",
"if",
"it",
"doesn",
"t",
"exist",
"and",
"create_table",
"is",
"set",
"as",
"True",
"."
] | 097b6406aa12d5ca0b825b00c936861b530cbf39 | https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-dynamodb-persistence-adapter/ask_sdk_dynamodb/adapter.py#L207-L244 | train | 215,387 |
alexa/alexa-skills-kit-sdk-for-python | ask-sdk-runtime/ask_sdk_runtime/skill.py | RuntimeConfigurationBuilder.add_request_handler | def add_request_handler(self, request_handler):
# type: (AbstractRequestHandler) -> None
"""Register input to the request handlers list.
:param request_handler: Request Handler instance to be
registered.
:type request_handler: AbstractRequestHandler
:return: None
"""
if request_handler is None:
raise RuntimeConfigException(
"Valid Request Handler instance to be provided")
if not isinstance(request_handler, AbstractRequestHandler):
raise RuntimeConfigException(
"Input should be a RequestHandler instance")
self.request_handler_chains.append(GenericRequestHandlerChain(
request_handler=request_handler)) | python | def add_request_handler(self, request_handler):
# type: (AbstractRequestHandler) -> None
"""Register input to the request handlers list.
:param request_handler: Request Handler instance to be
registered.
:type request_handler: AbstractRequestHandler
:return: None
"""
if request_handler is None:
raise RuntimeConfigException(
"Valid Request Handler instance to be provided")
if not isinstance(request_handler, AbstractRequestHandler):
raise RuntimeConfigException(
"Input should be a RequestHandler instance")
self.request_handler_chains.append(GenericRequestHandlerChain(
request_handler=request_handler)) | [
"def",
"add_request_handler",
"(",
"self",
",",
"request_handler",
")",
":",
"# type: (AbstractRequestHandler) -> None",
"if",
"request_handler",
"is",
"None",
":",
"raise",
"RuntimeConfigException",
"(",
"\"Valid Request Handler instance to be provided\"",
")",
"if",
"not",
... | Register input to the request handlers list.
:param request_handler: Request Handler instance to be
registered.
:type request_handler: AbstractRequestHandler
:return: None | [
"Register",
"input",
"to",
"the",
"request",
"handlers",
"list",
"."
] | 097b6406aa12d5ca0b825b00c936861b530cbf39 | https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-runtime/ask_sdk_runtime/skill.py#L108-L126 | train | 215,388 |
alexa/alexa-skills-kit-sdk-for-python | ask-sdk-runtime/ask_sdk_runtime/skill.py | RuntimeConfigurationBuilder.add_exception_handler | def add_exception_handler(self, exception_handler):
# type: (AbstractExceptionHandler) -> None
"""Register input to the exception handlers list.
:param exception_handler: Exception Handler instance to be
registered.
:type exception_handler: AbstractExceptionHandler
:return: None
"""
if exception_handler is None:
raise RuntimeConfigException(
"Valid Exception Handler instance to be provided")
if not isinstance(exception_handler, AbstractExceptionHandler):
raise RuntimeConfigException(
"Input should be an ExceptionHandler instance")
self.exception_handlers.append(exception_handler) | python | def add_exception_handler(self, exception_handler):
# type: (AbstractExceptionHandler) -> None
"""Register input to the exception handlers list.
:param exception_handler: Exception Handler instance to be
registered.
:type exception_handler: AbstractExceptionHandler
:return: None
"""
if exception_handler is None:
raise RuntimeConfigException(
"Valid Exception Handler instance to be provided")
if not isinstance(exception_handler, AbstractExceptionHandler):
raise RuntimeConfigException(
"Input should be an ExceptionHandler instance")
self.exception_handlers.append(exception_handler) | [
"def",
"add_exception_handler",
"(",
"self",
",",
"exception_handler",
")",
":",
"# type: (AbstractExceptionHandler) -> None",
"if",
"exception_handler",
"is",
"None",
":",
"raise",
"RuntimeConfigException",
"(",
"\"Valid Exception Handler instance to be provided\"",
")",
"if",... | Register input to the exception handlers list.
:param exception_handler: Exception Handler instance to be
registered.
:type exception_handler: AbstractExceptionHandler
:return: None | [
"Register",
"input",
"to",
"the",
"exception",
"handlers",
"list",
"."
] | 097b6406aa12d5ca0b825b00c936861b530cbf39 | https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-runtime/ask_sdk_runtime/skill.py#L140-L157 | train | 215,389 |
alexa/alexa-skills-kit-sdk-for-python | ask-sdk-runtime/ask_sdk_runtime/skill.py | RuntimeConfigurationBuilder.add_global_request_interceptor | def add_global_request_interceptor(self, request_interceptor):
# type: (AbstractRequestInterceptor) -> None
"""Register input to the global request interceptors list.
:param request_interceptor: Request Interceptor instance to be
registered.
:type request_interceptor: AbstractRequestInterceptor
:return: None
"""
if request_interceptor is None:
raise RuntimeConfigException(
"Valid Request Interceptor instance to be provided")
if not isinstance(request_interceptor, AbstractRequestInterceptor):
raise RuntimeConfigException(
"Input should be a RequestInterceptor instance")
self.global_request_interceptors.append(request_interceptor) | python | def add_global_request_interceptor(self, request_interceptor):
# type: (AbstractRequestInterceptor) -> None
"""Register input to the global request interceptors list.
:param request_interceptor: Request Interceptor instance to be
registered.
:type request_interceptor: AbstractRequestInterceptor
:return: None
"""
if request_interceptor is None:
raise RuntimeConfigException(
"Valid Request Interceptor instance to be provided")
if not isinstance(request_interceptor, AbstractRequestInterceptor):
raise RuntimeConfigException(
"Input should be a RequestInterceptor instance")
self.global_request_interceptors.append(request_interceptor) | [
"def",
"add_global_request_interceptor",
"(",
"self",
",",
"request_interceptor",
")",
":",
"# type: (AbstractRequestInterceptor) -> None",
"if",
"request_interceptor",
"is",
"None",
":",
"raise",
"RuntimeConfigException",
"(",
"\"Valid Request Interceptor instance to be provided\"... | Register input to the global request interceptors list.
:param request_interceptor: Request Interceptor instance to be
registered.
:type request_interceptor: AbstractRequestInterceptor
:return: None | [
"Register",
"input",
"to",
"the",
"global",
"request",
"interceptors",
"list",
"."
] | 097b6406aa12d5ca0b825b00c936861b530cbf39 | https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-runtime/ask_sdk_runtime/skill.py#L159-L176 | train | 215,390 |
alexa/alexa-skills-kit-sdk-for-python | ask-sdk-runtime/ask_sdk_runtime/skill.py | RuntimeConfigurationBuilder.add_global_response_interceptor | def add_global_response_interceptor(self, response_interceptor):
# type: (AbstractResponseInterceptor) -> None
"""Register input to the global response interceptors list.
:param response_interceptor: Response Interceptor instance to
be registered.
:type response_interceptor: AbstractResponseInterceptor
:return: None
"""
if response_interceptor is None:
raise RuntimeConfigException(
"Valid Response Interceptor instance to be provided")
if not isinstance(response_interceptor, AbstractResponseInterceptor):
raise RuntimeConfigException(
"Input should be a ResponseInterceptor instance")
self.global_response_interceptors.append(response_interceptor) | python | def add_global_response_interceptor(self, response_interceptor):
# type: (AbstractResponseInterceptor) -> None
"""Register input to the global response interceptors list.
:param response_interceptor: Response Interceptor instance to
be registered.
:type response_interceptor: AbstractResponseInterceptor
:return: None
"""
if response_interceptor is None:
raise RuntimeConfigException(
"Valid Response Interceptor instance to be provided")
if not isinstance(response_interceptor, AbstractResponseInterceptor):
raise RuntimeConfigException(
"Input should be a ResponseInterceptor instance")
self.global_response_interceptors.append(response_interceptor) | [
"def",
"add_global_response_interceptor",
"(",
"self",
",",
"response_interceptor",
")",
":",
"# type: (AbstractResponseInterceptor) -> None",
"if",
"response_interceptor",
"is",
"None",
":",
"raise",
"RuntimeConfigException",
"(",
"\"Valid Response Interceptor instance to be provi... | Register input to the global response interceptors list.
:param response_interceptor: Response Interceptor instance to
be registered.
:type response_interceptor: AbstractResponseInterceptor
:return: None | [
"Register",
"input",
"to",
"the",
"global",
"response",
"interceptors",
"list",
"."
] | 097b6406aa12d5ca0b825b00c936861b530cbf39 | https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-runtime/ask_sdk_runtime/skill.py#L178-L195 | train | 215,391 |
alexa/alexa-skills-kit-sdk-for-python | ask-sdk-runtime/ask_sdk_runtime/skill.py | RuntimeConfigurationBuilder.get_runtime_configuration | def get_runtime_configuration(self):
# type: () -> RuntimeConfiguration
"""Build the runtime configuration object from the registered
components.
:return: Runtime Configuration Object
:rtype: RuntimeConfiguration
"""
request_mapper = GenericRequestMapper(
request_handler_chains=self.request_handler_chains)
exception_mapper = GenericExceptionMapper(
exception_handlers=self.exception_handlers)
handler_adapter = GenericHandlerAdapter()
runtime_configuration = RuntimeConfiguration(
request_mappers=[request_mapper],
handler_adapters=[handler_adapter],
exception_mapper=exception_mapper,
request_interceptors=self.global_request_interceptors,
response_interceptors=self.global_response_interceptors)
return runtime_configuration | python | def get_runtime_configuration(self):
# type: () -> RuntimeConfiguration
"""Build the runtime configuration object from the registered
components.
:return: Runtime Configuration Object
:rtype: RuntimeConfiguration
"""
request_mapper = GenericRequestMapper(
request_handler_chains=self.request_handler_chains)
exception_mapper = GenericExceptionMapper(
exception_handlers=self.exception_handlers)
handler_adapter = GenericHandlerAdapter()
runtime_configuration = RuntimeConfiguration(
request_mappers=[request_mapper],
handler_adapters=[handler_adapter],
exception_mapper=exception_mapper,
request_interceptors=self.global_request_interceptors,
response_interceptors=self.global_response_interceptors)
return runtime_configuration | [
"def",
"get_runtime_configuration",
"(",
"self",
")",
":",
"# type: () -> RuntimeConfiguration",
"request_mapper",
"=",
"GenericRequestMapper",
"(",
"request_handler_chains",
"=",
"self",
".",
"request_handler_chains",
")",
"exception_mapper",
"=",
"GenericExceptionMapper",
"... | Build the runtime configuration object from the registered
components.
:return: Runtime Configuration Object
:rtype: RuntimeConfiguration | [
"Build",
"the",
"runtime",
"configuration",
"object",
"from",
"the",
"registered",
"components",
"."
] | 097b6406aa12d5ca0b825b00c936861b530cbf39 | https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-runtime/ask_sdk_runtime/skill.py#L197-L218 | train | 215,392 |
alexa/alexa-skills-kit-sdk-for-python | ask-sdk-dynamodb-persistence-adapter/ask_sdk_dynamodb/partition_keygen.py | user_id_partition_keygen | def user_id_partition_keygen(request_envelope):
# type: (RequestEnvelope) -> str
"""Retrieve user id from request envelope, to use as partition key.
:param request_envelope: Request Envelope passed during skill
invocation
:type request_envelope: ask_sdk_model.RequestEnvelope
:return: User Id retrieved from request envelope
:rtype: str
:raises: :py:class:`ask_sdk_core.exceptions.PersistenceException`
"""
try:
user_id = request_envelope.context.system.user.user_id
return user_id
except AttributeError:
raise PersistenceException("Couldn't retrieve user id from request "
"envelope, for partition key use") | python | def user_id_partition_keygen(request_envelope):
# type: (RequestEnvelope) -> str
"""Retrieve user id from request envelope, to use as partition key.
:param request_envelope: Request Envelope passed during skill
invocation
:type request_envelope: ask_sdk_model.RequestEnvelope
:return: User Id retrieved from request envelope
:rtype: str
:raises: :py:class:`ask_sdk_core.exceptions.PersistenceException`
"""
try:
user_id = request_envelope.context.system.user.user_id
return user_id
except AttributeError:
raise PersistenceException("Couldn't retrieve user id from request "
"envelope, for partition key use") | [
"def",
"user_id_partition_keygen",
"(",
"request_envelope",
")",
":",
"# type: (RequestEnvelope) -> str",
"try",
":",
"user_id",
"=",
"request_envelope",
".",
"context",
".",
"system",
".",
"user",
".",
"user_id",
"return",
"user_id",
"except",
"AttributeError",
":",
... | Retrieve user id from request envelope, to use as partition key.
:param request_envelope: Request Envelope passed during skill
invocation
:type request_envelope: ask_sdk_model.RequestEnvelope
:return: User Id retrieved from request envelope
:rtype: str
:raises: :py:class:`ask_sdk_core.exceptions.PersistenceException` | [
"Retrieve",
"user",
"id",
"from",
"request",
"envelope",
"to",
"use",
"as",
"partition",
"key",
"."
] | 097b6406aa12d5ca0b825b00c936861b530cbf39 | https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-dynamodb-persistence-adapter/ask_sdk_dynamodb/partition_keygen.py#L26-L42 | train | 215,393 |
alexa/alexa-skills-kit-sdk-for-python | ask-sdk-dynamodb-persistence-adapter/ask_sdk_dynamodb/partition_keygen.py | device_id_partition_keygen | def device_id_partition_keygen(request_envelope):
# type: (RequestEnvelope) -> str
"""Retrieve device id from request envelope, to use as partition key.
:param request_envelope: Request Envelope passed during skill
invocation
:type request_envelope: ask_sdk_model.RequestEnvelope
:return: Device Id retrieved from request envelope
:rtype: str
:raises: :py:class:`ask_sdk_core.exceptions.PersistenceException`
"""
try:
device_id = request_envelope.context.system.device.device_id
return device_id
except AttributeError:
raise PersistenceException("Couldn't retrieve device id from "
"request envelope, for partition key use") | python | def device_id_partition_keygen(request_envelope):
# type: (RequestEnvelope) -> str
"""Retrieve device id from request envelope, to use as partition key.
:param request_envelope: Request Envelope passed during skill
invocation
:type request_envelope: ask_sdk_model.RequestEnvelope
:return: Device Id retrieved from request envelope
:rtype: str
:raises: :py:class:`ask_sdk_core.exceptions.PersistenceException`
"""
try:
device_id = request_envelope.context.system.device.device_id
return device_id
except AttributeError:
raise PersistenceException("Couldn't retrieve device id from "
"request envelope, for partition key use") | [
"def",
"device_id_partition_keygen",
"(",
"request_envelope",
")",
":",
"# type: (RequestEnvelope) -> str",
"try",
":",
"device_id",
"=",
"request_envelope",
".",
"context",
".",
"system",
".",
"device",
".",
"device_id",
"return",
"device_id",
"except",
"AttributeError... | Retrieve device id from request envelope, to use as partition key.
:param request_envelope: Request Envelope passed during skill
invocation
:type request_envelope: ask_sdk_model.RequestEnvelope
:return: Device Id retrieved from request envelope
:rtype: str
:raises: :py:class:`ask_sdk_core.exceptions.PersistenceException` | [
"Retrieve",
"device",
"id",
"from",
"request",
"envelope",
"to",
"use",
"as",
"partition",
"key",
"."
] | 097b6406aa12d5ca0b825b00c936861b530cbf39 | https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-dynamodb-persistence-adapter/ask_sdk_dynamodb/partition_keygen.py#L45-L61 | train | 215,394 |
alexa/alexa-skills-kit-sdk-for-python | ask-sdk-core/ask_sdk_core/utils/predicate.py | is_canfulfill_intent_name | def is_canfulfill_intent_name(name):
# type: (str) -> Callable[[HandlerInput], bool]
"""A predicate function returning a boolean, when name matches the
intent name in a CanFulfill Intent Request.
The function can be applied on a
:py:class:`ask_sdk_core.handler_input.HandlerInput`, to
check if the input is of
:py:class:`ask_sdk_model.intent_request.CanFulfillIntentRequest` type and if the
name of the request matches with the passed name.
:param name: Name to be matched with the CanFulfill Intent Request Name
:type name: str
:return: Predicate function that can be used to check name of the
request
:rtype: Callable[[HandlerInput], bool]
"""
def can_handle_wrapper(handler_input):
# type: (HandlerInput) -> bool
return (isinstance(
handler_input.request_envelope.request, CanFulfillIntentRequest) and
handler_input.request_envelope.request.intent.name == name)
return can_handle_wrapper | python | def is_canfulfill_intent_name(name):
# type: (str) -> Callable[[HandlerInput], bool]
"""A predicate function returning a boolean, when name matches the
intent name in a CanFulfill Intent Request.
The function can be applied on a
:py:class:`ask_sdk_core.handler_input.HandlerInput`, to
check if the input is of
:py:class:`ask_sdk_model.intent_request.CanFulfillIntentRequest` type and if the
name of the request matches with the passed name.
:param name: Name to be matched with the CanFulfill Intent Request Name
:type name: str
:return: Predicate function that can be used to check name of the
request
:rtype: Callable[[HandlerInput], bool]
"""
def can_handle_wrapper(handler_input):
# type: (HandlerInput) -> bool
return (isinstance(
handler_input.request_envelope.request, CanFulfillIntentRequest) and
handler_input.request_envelope.request.intent.name == name)
return can_handle_wrapper | [
"def",
"is_canfulfill_intent_name",
"(",
"name",
")",
":",
"# type: (str) -> Callable[[HandlerInput], bool]",
"def",
"can_handle_wrapper",
"(",
"handler_input",
")",
":",
"# type: (HandlerInput) -> bool",
"return",
"(",
"isinstance",
"(",
"handler_input",
".",
"request_envelo... | A predicate function returning a boolean, when name matches the
intent name in a CanFulfill Intent Request.
The function can be applied on a
:py:class:`ask_sdk_core.handler_input.HandlerInput`, to
check if the input is of
:py:class:`ask_sdk_model.intent_request.CanFulfillIntentRequest` type and if the
name of the request matches with the passed name.
:param name: Name to be matched with the CanFulfill Intent Request Name
:type name: str
:return: Predicate function that can be used to check name of the
request
:rtype: Callable[[HandlerInput], bool] | [
"A",
"predicate",
"function",
"returning",
"a",
"boolean",
"when",
"name",
"matches",
"the",
"intent",
"name",
"in",
"a",
"CanFulfill",
"Intent",
"Request",
"."
] | 097b6406aa12d5ca0b825b00c936861b530cbf39 | https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-core/ask_sdk_core/utils/predicate.py#L28-L50 | train | 215,395 |
alexa/alexa-skills-kit-sdk-for-python | ask-sdk-core/ask_sdk_core/utils/predicate.py | is_intent_name | def is_intent_name(name):
# type: (str) -> Callable[[HandlerInput], bool]
"""A predicate function returning a boolean, when name matches the
name in Intent Request.
The function can be applied on a
:py:class:`ask_sdk_core.handler_input.HandlerInput`, to
check if the input is of
:py:class:`ask_sdk_model.intent_request.IntentRequest` type and if the
name of the request matches with the passed name.
:param name: Name to be matched with the Intent Request Name
:type name: str
:return: Predicate function that can be used to check name of the
request
:rtype: Callable[[HandlerInput], bool]
"""
def can_handle_wrapper(handler_input):
# type: (HandlerInput) -> bool
return (isinstance(
handler_input.request_envelope.request, IntentRequest) and
handler_input.request_envelope.request.intent.name == name)
return can_handle_wrapper | python | def is_intent_name(name):
# type: (str) -> Callable[[HandlerInput], bool]
"""A predicate function returning a boolean, when name matches the
name in Intent Request.
The function can be applied on a
:py:class:`ask_sdk_core.handler_input.HandlerInput`, to
check if the input is of
:py:class:`ask_sdk_model.intent_request.IntentRequest` type and if the
name of the request matches with the passed name.
:param name: Name to be matched with the Intent Request Name
:type name: str
:return: Predicate function that can be used to check name of the
request
:rtype: Callable[[HandlerInput], bool]
"""
def can_handle_wrapper(handler_input):
# type: (HandlerInput) -> bool
return (isinstance(
handler_input.request_envelope.request, IntentRequest) and
handler_input.request_envelope.request.intent.name == name)
return can_handle_wrapper | [
"def",
"is_intent_name",
"(",
"name",
")",
":",
"# type: (str) -> Callable[[HandlerInput], bool]",
"def",
"can_handle_wrapper",
"(",
"handler_input",
")",
":",
"# type: (HandlerInput) -> bool",
"return",
"(",
"isinstance",
"(",
"handler_input",
".",
"request_envelope",
".",... | A predicate function returning a boolean, when name matches the
name in Intent Request.
The function can be applied on a
:py:class:`ask_sdk_core.handler_input.HandlerInput`, to
check if the input is of
:py:class:`ask_sdk_model.intent_request.IntentRequest` type and if the
name of the request matches with the passed name.
:param name: Name to be matched with the Intent Request Name
:type name: str
:return: Predicate function that can be used to check name of the
request
:rtype: Callable[[HandlerInput], bool] | [
"A",
"predicate",
"function",
"returning",
"a",
"boolean",
"when",
"name",
"matches",
"the",
"name",
"in",
"Intent",
"Request",
"."
] | 097b6406aa12d5ca0b825b00c936861b530cbf39 | https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-core/ask_sdk_core/utils/predicate.py#L53-L75 | train | 215,396 |
alexa/alexa-skills-kit-sdk-for-python | ask-sdk-core/ask_sdk_core/utils/predicate.py | is_request_type | def is_request_type(request_type):
# type: (str) -> Callable[[HandlerInput], bool]
"""A predicate function returning a boolean, when request type is
the passed-in type.
The function can be applied on a
:py:class:`ask_sdk_core.handler_input.HandlerInput`, to check
if the input request type is the passed in request type.
:param request_type: request type to be matched with the input's request
:type request_type: str
:return: Predicate function that can be used to check the type of
the request
:rtype: Callable[[HandlerInput], bool]
"""
def can_handle_wrapper(handler_input):
# type: (HandlerInput) -> bool
return (handler_input.request_envelope.request.object_type ==
request_type)
return can_handle_wrapper | python | def is_request_type(request_type):
# type: (str) -> Callable[[HandlerInput], bool]
"""A predicate function returning a boolean, when request type is
the passed-in type.
The function can be applied on a
:py:class:`ask_sdk_core.handler_input.HandlerInput`, to check
if the input request type is the passed in request type.
:param request_type: request type to be matched with the input's request
:type request_type: str
:return: Predicate function that can be used to check the type of
the request
:rtype: Callable[[HandlerInput], bool]
"""
def can_handle_wrapper(handler_input):
# type: (HandlerInput) -> bool
return (handler_input.request_envelope.request.object_type ==
request_type)
return can_handle_wrapper | [
"def",
"is_request_type",
"(",
"request_type",
")",
":",
"# type: (str) -> Callable[[HandlerInput], bool]",
"def",
"can_handle_wrapper",
"(",
"handler_input",
")",
":",
"# type: (HandlerInput) -> bool",
"return",
"(",
"handler_input",
".",
"request_envelope",
".",
"request",
... | A predicate function returning a boolean, when request type is
the passed-in type.
The function can be applied on a
:py:class:`ask_sdk_core.handler_input.HandlerInput`, to check
if the input request type is the passed in request type.
:param request_type: request type to be matched with the input's request
:type request_type: str
:return: Predicate function that can be used to check the type of
the request
:rtype: Callable[[HandlerInput], bool] | [
"A",
"predicate",
"function",
"returning",
"a",
"boolean",
"when",
"request",
"type",
"is",
"the",
"passed",
"-",
"in",
"type",
"."
] | 097b6406aa12d5ca0b825b00c936861b530cbf39 | https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-core/ask_sdk_core/utils/predicate.py#L78-L97 | train | 215,397 |
alexa/alexa-skills-kit-sdk-for-python | ask-sdk-core/ask_sdk_core/api_client.py | DefaultApiClient.invoke | def invoke(self, request):
# type: (ApiClientRequest) -> ApiClientResponse
"""Dispatches a request to an API endpoint described in the
request.
Resolves the method from input request object, converts the
list of header tuples to the required format (dict) for the
`requests` lib call and invokes the method with corresponding
parameters on `requests` library. The response from the call is
wrapped under the `ApiClientResponse` object and the
responsibility of translating a response code and response/
error lies with the caller.
:param request: Request to dispatch to the ApiClient
:type request: ApiClientRequest
:return: Response from the client call
:rtype: ApiClientResponse
:raises: :py:class:`ask_sdk_core.exceptions.ApiClientException`
"""
try:
http_method = self._resolve_method(request)
http_headers = self._convert_list_tuples_to_dict(
headers_list=request.headers)
parsed_url = parse_url(request.url)
if parsed_url.scheme is None or parsed_url.scheme != "https":
raise ApiClientException(
"Requests against non-HTTPS endpoints are not allowed.")
if request.body:
body_content_type = http_headers.get("Content-type", None)
if (body_content_type is not None and
"json" in body_content_type):
raw_data = json.dumps(request.body)
else:
raw_data = request.body
else:
raw_data = None
http_response = http_method(
url=request.url, headers=http_headers, data=raw_data)
return ApiClientResponse(
headers=self._convert_dict_to_list_tuples(
http_response.headers),
status_code=http_response.status_code,
body=http_response.text)
except Exception as e:
raise ApiClientException(
"Error executing the request: {}".format(str(e))) | python | def invoke(self, request):
# type: (ApiClientRequest) -> ApiClientResponse
"""Dispatches a request to an API endpoint described in the
request.
Resolves the method from input request object, converts the
list of header tuples to the required format (dict) for the
`requests` lib call and invokes the method with corresponding
parameters on `requests` library. The response from the call is
wrapped under the `ApiClientResponse` object and the
responsibility of translating a response code and response/
error lies with the caller.
:param request: Request to dispatch to the ApiClient
:type request: ApiClientRequest
:return: Response from the client call
:rtype: ApiClientResponse
:raises: :py:class:`ask_sdk_core.exceptions.ApiClientException`
"""
try:
http_method = self._resolve_method(request)
http_headers = self._convert_list_tuples_to_dict(
headers_list=request.headers)
parsed_url = parse_url(request.url)
if parsed_url.scheme is None or parsed_url.scheme != "https":
raise ApiClientException(
"Requests against non-HTTPS endpoints are not allowed.")
if request.body:
body_content_type = http_headers.get("Content-type", None)
if (body_content_type is not None and
"json" in body_content_type):
raw_data = json.dumps(request.body)
else:
raw_data = request.body
else:
raw_data = None
http_response = http_method(
url=request.url, headers=http_headers, data=raw_data)
return ApiClientResponse(
headers=self._convert_dict_to_list_tuples(
http_response.headers),
status_code=http_response.status_code,
body=http_response.text)
except Exception as e:
raise ApiClientException(
"Error executing the request: {}".format(str(e))) | [
"def",
"invoke",
"(",
"self",
",",
"request",
")",
":",
"# type: (ApiClientRequest) -> ApiClientResponse",
"try",
":",
"http_method",
"=",
"self",
".",
"_resolve_method",
"(",
"request",
")",
"http_headers",
"=",
"self",
".",
"_convert_list_tuples_to_dict",
"(",
"he... | Dispatches a request to an API endpoint described in the
request.
Resolves the method from input request object, converts the
list of header tuples to the required format (dict) for the
`requests` lib call and invokes the method with corresponding
parameters on `requests` library. The response from the call is
wrapped under the `ApiClientResponse` object and the
responsibility of translating a response code and response/
error lies with the caller.
:param request: Request to dispatch to the ApiClient
:type request: ApiClientRequest
:return: Response from the client call
:rtype: ApiClientResponse
:raises: :py:class:`ask_sdk_core.exceptions.ApiClientException` | [
"Dispatches",
"a",
"request",
"to",
"an",
"API",
"endpoint",
"described",
"in",
"the",
"request",
"."
] | 097b6406aa12d5ca0b825b00c936861b530cbf39 | https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-core/ask_sdk_core/api_client.py#L40-L89 | train | 215,398 |
alexa/alexa-skills-kit-sdk-for-python | ask-sdk-core/ask_sdk_core/api_client.py | DefaultApiClient._resolve_method | def _resolve_method(self, request):
# type: (ApiClientRequest) -> Callable
"""Resolve the method from request object to `requests` http
call.
:param request: Request to dispatch to the ApiClient
:type request: ApiClientRequest
:return: The HTTP method that maps to the request call.
:rtype: Callable
:raises :py:class:`ask_sdk_core.exceptions.ApiClientException`
if invalid http request method is being called
"""
try:
return getattr(requests, request.method.lower())
except AttributeError:
raise ApiClientException(
"Invalid request method: {}".format(request.method)) | python | def _resolve_method(self, request):
# type: (ApiClientRequest) -> Callable
"""Resolve the method from request object to `requests` http
call.
:param request: Request to dispatch to the ApiClient
:type request: ApiClientRequest
:return: The HTTP method that maps to the request call.
:rtype: Callable
:raises :py:class:`ask_sdk_core.exceptions.ApiClientException`
if invalid http request method is being called
"""
try:
return getattr(requests, request.method.lower())
except AttributeError:
raise ApiClientException(
"Invalid request method: {}".format(request.method)) | [
"def",
"_resolve_method",
"(",
"self",
",",
"request",
")",
":",
"# type: (ApiClientRequest) -> Callable",
"try",
":",
"return",
"getattr",
"(",
"requests",
",",
"request",
".",
"method",
".",
"lower",
"(",
")",
")",
"except",
"AttributeError",
":",
"raise",
"... | Resolve the method from request object to `requests` http
call.
:param request: Request to dispatch to the ApiClient
:type request: ApiClientRequest
:return: The HTTP method that maps to the request call.
:rtype: Callable
:raises :py:class:`ask_sdk_core.exceptions.ApiClientException`
if invalid http request method is being called | [
"Resolve",
"the",
"method",
"from",
"request",
"object",
"to",
"requests",
"http",
"call",
"."
] | 097b6406aa12d5ca0b825b00c936861b530cbf39 | https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-core/ask_sdk_core/api_client.py#L91-L107 | train | 215,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.