id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
4,980 | from contextlib import contextmanager
from dataclasses import dataclass, field
from typing import Iterable, Iterator, List, Optional, Sequence, TYPE_CHECKING, Union
from libcst._add_slots import add_slots
from libcst._flatten_sentinel import FlattenSentinel
from libcst._maybe_sentinel import MaybeSentinel
from libcst._... | A convenience wrapper for `visit_iterable` that returns a sequence instead of an iterable. |
4,981 | from contextlib import contextmanager
from dataclasses import dataclass, field
from typing import Iterable, Iterator, List, Optional, Sequence, TYPE_CHECKING, Union
from libcst._add_slots import add_slots
from libcst._flatten_sentinel import FlattenSentinel
from libcst._maybe_sentinel import MaybeSentinel
from libcst._... | A convenience wrapper for `visit_body_iterable` that returns a sequence instead of an iterable. |
4,982 | from enum import auto, Enum
from typing import Any, Callable, Iterable, Optional, Sequence, Tuple, Union
from typing_extensions import final
from libcst._parser.parso.pgen2.generator import ReservedString
from libcst._parser.parso.python.token import PythonTokenTypes, TokenType
from libcst._parser.types.token import To... | null |
4,983 | from enum import auto, Enum
from typing import Any, Callable, Iterable, Optional, Sequence, Tuple, Union
from typing_extensions import final
from libcst._parser.parso.pgen2.generator import ReservedString
from libcst._parser.parso.python.token import PythonTokenTypes, TokenType
from libcst._parser.types.token import To... | null |
4,984 | from enum import auto, Enum
class RemovalSentinel(Enum):
"""
A :attr:`RemovalSentinel.REMOVE` value should be returned by a
:meth:`CSTTransformer.on_leave` method when we want to remove that child from its
parent. As a convenience, this can be constructed by calling
:func:`libcst.RemoveFromParent`.
... | A convenience method for requesting that this node be removed by its parent. Use this in place of returning :class:`RemovalSentinel` directly. For example, to remove all arguments unconditionally:: def leave_Arg( self, original_node: cst.Arg, updated_node: cst.Arg ) -> Union[cst.Arg, cst.RemovalSentinel]: return Remove... |
4,985 | import os
from contextlib import contextmanager
from pathlib import Path
from typing import Generator
from libcst._types import StrPath
StrPath = Union[str, PurePath]
The provided code snippet includes necessary dependencies for implementing the `chdir` function. Write a Python function `def chdir(path: StrPath) -> G... | Temporarily chdir to the given path, and then return to the previous path. |
4,986 | from typing import Dict, Mapping, Optional, Set, Union
import libcst as cst
from libcst.helpers.common import ensure_type
TEMPLATE_PREFIX: str = "__LIBCST_MANGLED_NAME_"
TEMPLATE_SUFFIX: str = "_EMAN_DELGNAM_TSCBIL__"
def unmangled_name(var: str) -> Optional[str]:
if TEMPLATE_PREFIX in var and TEMPLATE_SUFFIX in v... | null |
4,987 | from typing import Dict, Mapping, Optional, Set, Union
import libcst as cst
from libcst.helpers.common import ensure_type
ValidReplacementType = Union[
cst.BaseExpression,
cst.Annotation,
cst.AssignTarget,
cst.Param,
cst.Parameters,
cst.Arg,
cst.BaseStatement,
cst.BaseSmallStatement,
... | Accepts an entire python module template, including all leading and trailing whitespace. Any :class:`~libcst.CSTNode` provided as a keyword argument to this function will be inserted into the template at the appropriate location similar to an f-string expansion. For example:: module = parse_template_module("from {mod} ... |
4,988 | from typing import Dict, Mapping, Optional, Set, Union
import libcst as cst
from libcst.helpers.common import ensure_type
ValidReplacementType = Union[
cst.BaseExpression,
cst.Annotation,
cst.AssignTarget,
cst.Param,
cst.Parameters,
cst.Arg,
cst.BaseStatement,
cst.BaseSmallStatement,
... | Accepts a statement template followed by a trailing newline. If a trailing newline is not provided, one will be added. Any :class:`~libcst.CSTNode` provided as a keyword argument to this function will be inserted into the template at the appropriate location similar to an f-string expansion. For example:: statement = p... |
4,989 | from typing import Dict, Mapping, Optional, Set, Union
import libcst as cst
from libcst.helpers.common import ensure_type
ValidReplacementType = Union[
cst.BaseExpression,
cst.Annotation,
cst.AssignTarget,
cst.Param,
cst.Parameters,
cst.Arg,
cst.BaseStatement,
cst.BaseSmallStatement,
... | Accepts an expression template on a single line. Leading and trailing whitespace is not valid (there’s nowhere to store it on the expression node). Any :class:`~libcst.CSTNode` provided as a keyword argument to this function will be inserted into the template at the appropriate location similar to an f-string expansion... |
4,990 | from typing import Optional, Union
import libcst as cst
def get_full_name_for_node(node: Union[str, cst.CSTNode]) -> Optional[str]:
"""Return a dot concatenated full name for str, :class:`~libcst.Name`, :class:`~libcst.Attribute`.
:class:`~libcst.Call`, :class:`~libcst.Subscript`, :class:`~libcst.FunctionDef`, ... | Return a dot concatenated full name for str, :class:`~libcst.Name`, :class:`~libcst.Attribute`. :class:`~libcst.Call`, :class:`~libcst.Subscript`, :class:`~libcst.FunctionDef`, :class:`~libcst.ClassDef`. Raise Exception for not supported Node. |
4,991 | from dataclasses import dataclass
from itertools import islice
from pathlib import PurePath
from typing import List, Optional
from libcst import Comment, EmptyLine, ImportFrom, Module
from libcst._types import StrPath
from libcst.helpers.expression import get_full_name_for_node
The provided code snippet includes neces... | Insert comments after last non-empty line in header. Use this to insert one or more comments after any copyright preamble in a :class:`~libcst.Module`. Each comment in the list of ``comments`` must start with a ``#`` and will be placed on its own line in the appropriate location. |
4,992 | from dataclasses import dataclass
from itertools import islice
from pathlib import PurePath
from typing import List, Optional
from libcst import Comment, EmptyLine, ImportFrom, Module
from libcst._types import StrPath
from libcst.helpers.expression import get_full_name_for_node
def get_absolute_module_for_import(
c... | null |
4,993 | from dataclasses import dataclass
from itertools import islice
from pathlib import PurePath
from typing import List, Optional
from libcst import Comment, EmptyLine, ImportFrom, Module
from libcst._types import StrPath
from libcst.helpers.expression import get_full_name_for_node
def get_absolute_module_from_package_for_... | null |
4,994 | from dataclasses import dataclass
from itertools import islice
from pathlib import PurePath
from typing import List, Optional
from libcst import Comment, EmptyLine, ImportFrom, Module
from libcst._types import StrPath
from libcst.helpers.expression import get_full_name_for_node
class ModuleNameAndPackage:
name: str... | null |
4,995 | from typing import (
Any,
ForwardRef,
Iterable,
Mapping,
MutableMapping,
MutableSequence,
Tuple,
)
from typing_extensions import Literal
from typing_inspect import get_args, get_origin, is_classvar, is_typevar, is_union_type
The provided code snippet includes necessary dependencies for impl... | This method attempts to verify a given value is of a given type. If the type is not supported, it returns True but throws an exception in tests. It is similar to typeguard / enforce pypi modules, but neither of those have permissive options for types they do not support. Supported types for now: - List/Set/Iterable - D... |
4,996 | from typing import Any, Callable, cast, TypeVar
F = TypeVar("F", bound=Callable)
The provided code snippet includes necessary dependencies for implementing the `mark_no_op` function. Write a Python function `def mark_no_op(f: F) -> F` to solve the following problem:
Annotates stubs with a field to indicate they should... | Annotates stubs with a field to indicate they should not be collected by BatchableCSTVisitor.get_visitors() to reduce function call overhead when running a batched visitor pass. |
4,997 | import re
import sys
from pathlib import Path
from subprocess import run
from typing import Iterable, List, Pattern
EXCEPTION_PATTERNS: List[Pattern[str]] = [
re.compile(pattern)
for pattern in (
r"^native/libcst/tests/fixtures/",
r"^libcst/_add_slots\.py$",
r"^libcst/tests/test_(e2e|fuz... | null |
4,998 | from datetime import datetime
from enum import Enum
from io import StringIO
from typing import Optional
from aws_lambda_powertools.shared.types import List
def _format_date(timestamp: datetime) -> str:
# Specification example: Wed, 21 Oct 2015 07:28:00 GMT
return timestamp.strftime("%a, %d %b %Y %H:%M:%S GMT") | null |
4,999 | from __future__ import annotations
import base64
import itertools
import logging
import os
import warnings
from binascii import Error as BinAsciiError
from pathlib import Path
from typing import Any, Dict, Generator, Optional, Union, overload
from aws_lambda_powertools.shared import constants
def resolve_env_var_choic... | null |
5,000 | from __future__ import annotations
import base64
import itertools
import logging
import os
import warnings
from binascii import Error as BinAsciiError
from pathlib import Path
from typing import Any, Dict, Generator, Optional, Union, overload
from aws_lambda_powertools.shared import constants
def resolve_env_var_choic... | null |
5,001 | from __future__ import annotations
import base64
import itertools
import logging
import os
import warnings
from binascii import Error as BinAsciiError
from pathlib import Path
from typing import Any, Dict, Generator, Optional, Union, overload
from aws_lambda_powertools.shared import constants
def resolve_env_var_choic... | null |
5,002 | from __future__ import annotations
import base64
import itertools
import logging
import os
import warnings
from binascii import Error as BinAsciiError
from pathlib import Path
from typing import Any, Dict, Generator, Optional, Union, overload
from aws_lambda_powertools.shared import constants
The provided code snippet... | Pick explicit choice over env, if available, otherwise return env value received NOTE: Environment variable should be resolved by the caller. Parameters ---------- env : str, Optional environment variable actual value choice : str|float, optional explicit choice Returns ------- choice : str, Optional resolved choice as... |
5,003 | from __future__ import annotations
import base64
import itertools
import logging
import os
import warnings
from binascii import Error as BinAsciiError
from pathlib import Path
from typing import Any, Dict, Generator, Optional, Union, overload
from aws_lambda_powertools.shared import constants
logger = logging.getLogger... | null |
5,004 | from __future__ import annotations
import base64
import itertools
import logging
import os
import warnings
from binascii import Error as BinAsciiError
from pathlib import Path
from typing import Any, Dict, Generator, Optional, Union, overload
from aws_lambda_powertools.shared import constants
logger = logging.getLogger... | null |
5,005 | from __future__ import annotations
import base64
import itertools
import logging
import os
import warnings
from binascii import Error as BinAsciiError
from pathlib import Path
from typing import Any, Dict, Generator, Optional, Union, overload
from aws_lambda_powertools.shared import constants
def bytes_to_string(value... | null |
5,006 | from __future__ import annotations
import base64
import itertools
import logging
import os
import warnings
from binascii import Error as BinAsciiError
from pathlib import Path
from typing import Any, Dict, Generator, Optional, Union, overload
from aws_lambda_powertools.shared import constants
def strtobool(value: str) ... | null |
5,007 | from __future__ import annotations
import base64
import itertools
import logging
import os
import warnings
from binascii import Error as BinAsciiError
from pathlib import Path
from typing import Any, Dict, Generator, Optional, Union, overload
from aws_lambda_powertools.shared import constants
def slice_dictionary(data... | null |
5,008 | from __future__ import annotations
import base64
import itertools
import logging
import os
import warnings
from binascii import Error as BinAsciiError
from pathlib import Path
from typing import Any, Dict, Generator, Optional, Union, overload
from aws_lambda_powertools.shared import constants
def is_pydantic(data) -> b... | Extract raw event from common types used in Powertools If event cannot be extracted, return received data as is. Common models: - Event Source Data Classes (DictWrapper) - Python Dataclasses - Pydantic Models (BaseModel) Parameters ---------- data : Any Original event, a potential instance of DictWrapper/BaseModel/Data... |
5,009 | from __future__ import annotations
import base64
import itertools
import logging
import os
import warnings
from binascii import Error as BinAsciiError
from pathlib import Path
from typing import Any, Dict, Generator, Optional, Union, overload
from aws_lambda_powertools.shared import constants
The provided code snippet... | Return the absolute path from the given relative path to lambda handler. Parameters ---------- relative_path : str, optional The relative path to the lambda handler, by default an empty string. Returns ------- str The absolute path generated from the given relative path. If the environment variable LAMBDA_TASK_ROOT is ... |
5,010 | import logging
import os
from aws_lambda_powertools.shared.version import VERSION
logger = logging.getLogger(__name__)
TARGET_SDK_EVENT = "request-created"
def _create_feature_function(feature):
"""
Create and return the `add_powertools_feature` function.
The `add_powertools_feature` function is designed to... | Register the given feature string to the event system of the provided boto3 session and append the feature to the User-Agent header of the request Parameters ---------- session : boto3.session.Session The boto3 session to which the feature will be registered. feature : str The feature string to be appended to the User-... |
5,011 | import logging
import os
from aws_lambda_powertools.shared.version import VERSION
logger = logging.getLogger(__name__)
TARGET_SDK_EVENT = "request-created"
def _create_feature_function(feature):
"""
Create and return the `add_powertools_feature` function.
The `add_powertools_feature` function is designed to... | Register the given feature string to the event system of the provided botocore session Please notice this function is for patching botocore session and is different from previous one which is for patching boto3 session Parameters ---------- botocore_session : botocore.session.Session The botocore session to which the f... |
5,012 | import logging
import os
from aws_lambda_powertools.shared.version import VERSION
logger = logging.getLogger(__name__)
TARGET_SDK_EVENT = "request-created"
def _create_feature_function(feature):
"""
Create and return the `add_powertools_feature` function.
The `add_powertools_feature` function is designed to... | Register the given feature string to the event system of the provided boto3 client and append the feature to the User-Agent header of the request Parameters ---------- client : boto3.session.Session.client The boto3 client to which the feature will be registered. feature : str The feature string to be appended to the U... |
5,013 | import logging
import os
from aws_lambda_powertools.shared.version import VERSION
logger = logging.getLogger(__name__)
TARGET_SDK_EVENT = "request-created"
def _create_feature_function(feature):
"""
Create and return the `add_powertools_feature` function.
The `add_powertools_feature` function is designed to... | Register the given feature string to the event system of the provided boto3 resource and append the feature to the User-Agent header of the request Parameters ---------- resource : boto3.session.Session.resource The boto3 resource to which the feature will be registered. feature : str The feature string to be appended ... |
5,014 | import logging
import os
from aws_lambda_powertools.shared.version import VERSION
inject_header = True
try:
import botocore
except ImportError:
# if botocore failed to import, user might be using custom runtime and we can't inject header
inject_header = False
def _initializer_botocore_session(session):
def... | null |
5,015 | import logging
from typing import Callable, List, Optional, Set, Union
from .logger import Logger
PACKAGE_LOGGER = "aws_lambda_powertools"
def _include_registered_loggers_filter(loggers: Set[str]):
return [logging.getLogger(name) for name in logging.root.manager.loggerDict if "." not in name and name in loggers]
de... | Copies source Logger level and handler to all registered loggers for consistent formatting. Parameters ---------- source_logger : Logger Powertools for AWS Lambda (Python) Logger to copy configuration from log_level : Union[int, str], optional Logging level to set to registered loggers, by default uses source_logger lo... |
5,016 | from typing import Any
class LambdaContextModel:
"""A handful of Lambda Runtime Context fields
Full Lambda Context object: https://docs.aws.amazon.com/lambda/latest/dg/python-context-object.html
Parameters
----------
function_name: str
Lambda function name, by default "UNDEFINED"
e.g... | Captures Lambda function runtime info to be used across all log statements Parameters ---------- context : object Lambda context object Returns ------- LambdaContextModel Lambda context only with select fields |
5,017 | from __future__ import annotations
import functools
import inspect
import logging
import os
import random
import sys
import warnings
from typing import (
IO,
TYPE_CHECKING,
Any,
Callable,
Dict,
Iterable,
List,
Mapping,
Optional,
TypeVar,
Union,
overload,
)
from aws_lambda... | Verifies whether is cold start Returns ------- bool cold start bool value |
5,018 | from __future__ import annotations
import functools
import inspect
import logging
import os
import random
import sys
import warnings
from typing import (
IO,
TYPE_CHECKING,
Any,
Callable,
Dict,
Iterable,
List,
Mapping,
Optional,
TypeVar,
Union,
overload,
)
from aws_lambda... | Callback function for sys.excepthook to use Logger to log uncaught exceptions |
5,019 | from __future__ import annotations
import functools
import inspect
import logging
import os
import random
import sys
import warnings
from typing import (
IO,
TYPE_CHECKING,
Any,
Callable,
Dict,
Iterable,
List,
Mapping,
Optional,
TypeVar,
Union,
overload,
)
from aws_lambda... | Return caller filename by finding the caller frame |
5,020 | import logging
from aws_lambda_powertools.logging.logger import set_package_logger
from aws_lambda_powertools.shared.functions import powertools_debug_is_set
def set_package_logger(
level: Union[str, int] = logging.DEBUG,
stream: Optional[IO[str]] = None,
formatter: Optional[logging.Formatter] = None,
) ->... | Sets up Powertools for AWS Lambda (Python) package logging. By default, we discard any output to not interfere with customers logging. When POWERTOOLS_DEBUG env var is set, we setup `aws_lambda_powertools` logger in DEBUG level. Parameters ---------- stream: sys.stdout log stream, stdout by default |
5,021 | from __future__ import annotations
from aws_lambda_powertools.metrics.provider.cloudwatch_emf.exceptions import (
MetricResolutionError,
MetricUnitError,
)
from aws_lambda_powertools.metrics.provider.cloudwatch_emf.metric_properties import MetricResolution, MetricUnit
from aws_lambda_powertools.shared.types imp... | Return metric value from CloudWatch metric unit whether that's str or MetricResolution enum Parameters ---------- unit : Union[int, MetricResolution] Metric resolution Returns ------- int Metric resolution value must be 1 or 60 Raises ------ MetricResolutionError When metric resolution is not supported by CloudWatch |
5,022 | from __future__ import annotations
from aws_lambda_powertools.metrics.provider.cloudwatch_emf.exceptions import (
MetricResolutionError,
MetricUnitError,
)
from aws_lambda_powertools.metrics.provider.cloudwatch_emf.metric_properties import MetricResolution, MetricUnit
from aws_lambda_powertools.shared.types imp... | Return metric value from CloudWatch metric unit whether that's str or MetricUnit enum Parameters ---------- unit : Union[str, MetricUnit] Metric unit Returns ------- str Metric unit value (e.g. "Seconds", "Count/Second") Raises ------ MetricUnitError When metric unit is not supported by CloudWatch |
5,023 | from __future__ import annotations
is_cold_start = True
def reset_cold_start_flag():
global is_cold_start
if not is_cold_start:
is_cold_start = True | null |
5,024 | from __future__ import annotations
import functools
import logging
from abc import ABC, abstractmethod
from typing import Any
from aws_lambda_powertools.metrics.provider import cold_start
from aws_lambda_powertools.shared.types import AnyCallableT
from aws_lambda_powertools.utilities.typing import LambdaContext
def re... | null |
5,025 | from __future__ import annotations
import datetime
import functools
import json
import logging
import numbers
import os
import warnings
from collections import defaultdict
from contextlib import contextmanager
from typing import Any, Callable, Dict, Generator, List, Optional, Union
from aws_lambda_powertools.metrics.ex... | Context manager to simplify creation of a single metric Example ------- **Creates cold start metric with function_version as dimension** from aws_lambda_powertools import single_metric from aws_lambda_powertools.metrics import MetricUnit from aws_lambda_powertools.metrics import MetricResolution with single_metric(name... |
5,026 | from __future__ import annotations
from typing import Any, Awaitable, Callable, Dict, List
from aws_lambda_powertools.middleware_factory import lambda_handler_decorator
from aws_lambda_powertools.utilities.batch import (
AsyncBatchProcessor,
BasePartialBatchProcessor,
BatchProcessor,
EventType,
)
from a... | Middleware to handle batch event processing Notes ----- Consider using async_process_partial_response function for an easier experience. Parameters ---------- handler: Callable Lambda's handler event: Dict Lambda's Event context: LambdaContext Lambda's Context record_handler: Callable[..., Awaitable[Any]] Callable to p... |
5,027 | from __future__ import annotations
from typing import Any, Awaitable, Callable, Dict, List
from aws_lambda_powertools.middleware_factory import lambda_handler_decorator
from aws_lambda_powertools.utilities.batch import (
AsyncBatchProcessor,
BasePartialBatchProcessor,
BatchProcessor,
EventType,
)
from a... | Middleware to handle batch event processing Notes ----- Consider using process_partial_response function for an easier experience. Parameters ---------- handler: Callable Lambda's handler event: Dict Lambda's Event context: LambdaContext Lambda's Context record_handler: Callable Callable or corutine to process each rec... |
5,028 | from __future__ import annotations
from typing import Any, Awaitable, Callable, Dict, List
from aws_lambda_powertools.middleware_factory import lambda_handler_decorator
from aws_lambda_powertools.utilities.batch import (
AsyncBatchProcessor,
BasePartialBatchProcessor,
BatchProcessor,
EventType,
)
from a... | Higher level function to handle batch event processing. Parameters ---------- event: Dict Lambda's original event record_handler: Callable Callable to process each record from the batch processor: BasePartialBatchProcessor Batch Processor to handle partial failure cases context: LambdaContext Lambda's context, used to ... |
5,029 | from __future__ import annotations
from typing import Any, Awaitable, Callable, Dict, List
from aws_lambda_powertools.middleware_factory import lambda_handler_decorator
from aws_lambda_powertools.utilities.batch import (
AsyncBatchProcessor,
BasePartialBatchProcessor,
BatchProcessor,
EventType,
)
from a... | Higher level function to handle batch event processing asynchronously. Parameters ---------- event: Dict Lambda's original event record_handler: Callable Callable to process each record from the batch processor: AsyncBatchProcessor Batch Processor to handle partial failure cases context: LambdaContext Lambda's context,... |
5,030 | import enum
import re
from typing import Any, Dict, List, Optional, overload
from aws_lambda_powertools.utilities.data_classes.common import (
BaseRequestContext,
BaseRequestContextV2,
DictWrapper,
)
from aws_lambda_powertools.utilities.data_classes.shared_functions import (
get_header_value,
)
class AP... | Parses a gateway route arn as a APIGatewayRouteArn class Parameters ---------- arn : str ARN string for a methodArn or a routeArn Returns ------- APIGatewayRouteArn |
5,031 | import datetime
import time
import uuid
def _formatted_time(now: datetime.date, fmt: str, timezone_offset: int) -> str:
"""String formatted time with optional timezone offset
Parameters
----------
now : datetime.date
Current datetime with zero timezone offset
fmt : str
Data format be... | AWSDate - An extended ISO 8601 date string in the format YYYY-MM-DD. Parameters ---------- timezone_offset : int Timezone offset, defaults to 0 Returns ------- str Returns current time as AWSDate scalar string with optional timezone offset |
5,032 | import datetime
import time
import uuid
def _formatted_time(now: datetime.date, fmt: str, timezone_offset: int) -> str:
"""String formatted time with optional timezone offset
Parameters
----------
now : datetime.date
Current datetime with zero timezone offset
fmt : str
Data format be... | AWSTime - An extended ISO 8601 time string in the format hh:mm:ss.sss. Parameters ---------- timezone_offset : int Timezone offset, defaults to 0 Returns ------- str Returns current time as AWSTime scalar string with optional timezone offset |
5,033 | import datetime
import time
import uuid
def _formatted_time(now: datetime.date, fmt: str, timezone_offset: int) -> str:
"""String formatted time with optional timezone offset
Parameters
----------
now : datetime.date
Current datetime with zero timezone offset
fmt : str
Data format be... | AWSDateTime - An extended ISO 8601 date and time string in the format YYYY-MM-DDThh:mm:ss.sssZ. Parameters ---------- timezone_offset : int Timezone offset, defaults to 0 Returns ------- str Returns current time as AWSDateTime scalar string with optional timezone offset |
5,034 | import datetime
import time
import uuid
The provided code snippet includes necessary dependencies for implementing the `aws_timestamp` function. Write a Python function `def aws_timestamp() -> int` to solve the following problem:
AWSTimestamp - An integer value representing the number of seconds before or after 1970-0... | AWSTimestamp - An integer value representing the number of seconds before or after 1970-01-01-T00:00Z. |
5,035 | from typing import Any, Dict, List, Optional, Union
from aws_lambda_powertools.utilities.data_classes.common import DictWrapper
from aws_lambda_powertools.utilities.data_classes.shared_functions import (
get_header_value,
)
class AppSyncIdentityIAM(DictWrapper):
"""AWS_IAM authorization"""
def source_ip(sel... | Get the identity object based on the best detected type |
5,036 | from typing import Any, Callable, Dict, Type
from aws_lambda_powertools.middleware_factory import lambda_handler_decorator
from aws_lambda_powertools.utilities.data_classes.common import DictWrapper
from aws_lambda_powertools.utilities.typing import LambdaContext
class DictWrapper(Mapping):
"""Provides a single re... | Middleware to create an instance of the passed in event source data class Parameters ---------- handler: Callable Lambda's handler event: Dict Lambda's Event context: Dict Lambda's Context data_class: Type[DictWrapper] Data class type to instantiate Example -------- **Sample usage** from aws_lambda_powertools.utilities... |
5,037 | import base64
import json
import zlib
from typing import Iterator, List
from aws_lambda_powertools.utilities.data_classes.cloud_watch_logs_event import (
CloudWatchLogsDecodedData,
)
from aws_lambda_powertools.utilities.data_classes.common import DictWrapper
class KinesisStreamEvent(DictWrapper):
"""Kinesis str... | null |
5,038 | import base64
import json
import zlib
from typing import Iterator, List
from aws_lambda_powertools.utilities.data_classes.cloud_watch_logs_event import (
CloudWatchLogsDecodedData,
)
from aws_lambda_powertools.utilities.data_classes.common import DictWrapper
class KinesisStreamRecord(DictWrapper):
def aws_regi... | null |
5,039 | from __future__ import annotations
import base64
from typing import Any, Dict
The provided code snippet includes necessary dependencies for implementing the `base64_decode` function. Write a Python function `def base64_decode(value: str) -> str` to solve the following problem:
Decodes a Base64-encoded string and retur... | Decodes a Base64-encoded string and returns the decoded value. Parameters ---------- value: str The Base64-encoded string to decode. Returns ------- str The decoded string value. |
5,040 | from __future__ import annotations
import base64
from typing import Any, Dict
The provided code snippet includes necessary dependencies for implementing the `get_header_value` function. Write a Python function `def get_header_value( headers: dict[str, Any], name: str, default_value: str | None, case_se... | Get the value of a header by its name. Parameters ---------- headers: Dict[str, str] The dictionary of headers. name: str The name of the header to retrieve. default_value: str, optional The default value to return if the header is not found. Default is None. case_sensitive: bool, optional Indicates whether the header ... |
5,041 | from __future__ import annotations
import base64
from typing import Any, Dict
The provided code snippet includes necessary dependencies for implementing the `get_query_string_value` function. Write a Python function `def get_query_string_value( query_string_parameters: Dict[str, str] | None, name: str, def... | Retrieves the value of a query string parameter specified by the given name. Parameters ---------- name: str The name of the query string parameter to retrieve. default_value: str, optional The default value to return if the parameter is not found. Defaults to None. Returns ------- str. optional The value of the query ... |
5,042 | from __future__ import annotations
import base64
from typing import Any, Dict
The provided code snippet includes necessary dependencies for implementing the `get_multi_value_query_string_values` function. Write a Python function `def get_multi_value_query_string_values( multi_value_query_string_parameters: Dict[st... | Retrieves the values of a multi-value string parameters specified by the given name. Parameters ---------- name: str The name of the query string parameter to retrieve. default_value: list[str], optional The default value to return if the parameter is not found. Defaults to None. Returns ------- List[str]. optional The... |
5,043 | from __future__ import annotations
from typing import Any, Dict, List, Optional
from aws_lambda_powertools.utilities.data_classes.common import DictWrapper
class AWSConfigConfigurationChanged(DictWrapper):
def configuration_item_diff(self) -> Dict:
"""The configuration item diff of the ConfigurationItemChan... | Returns the corresponding event object based on the messageType in the invoking event. Parameters ---------- invoking_event: dict The invoking event received. Returns ------- AWSConfigConfigurationChanged | AWSConfigScheduledNotification | AWSConfigOversizedConfiguration: The event object based on the messageType in th... |
5,044 | import base64
import json
from typing import Any, Callable
The provided code snippet includes necessary dependencies for implementing the `base64_encode` function. Write a Python function `def base64_encode(data: str) -> str` to solve the following problem:
Encode a string and returns Base64-encoded encoded value. Par... | Encode a string and returns Base64-encoded encoded value. Parameters ---------- data: str The string to encode. Returns ------- str The Base64-encoded encoded value. |
5,045 | import base64
import json
from typing import Any, Callable
The provided code snippet includes necessary dependencies for implementing the `base64_decode` function. Write a Python function `def base64_decode(data: str) -> str` to solve the following problem:
Decodes a Base64-encoded string and returns the decoded value... | Decodes a Base64-encoded string and returns the decoded value. Parameters ---------- data: str The Base64-encoded string to decode. Returns ------- str The decoded string value. |
5,046 | import os
from typing import TYPE_CHECKING, Any, Dict, Optional, Union
import boto3
from botocore.config import Config
from aws_lambda_powertools.utilities.parameters.types import TransformOptions
from aws_lambda_powertools.shared import constants
from aws_lambda_powertools.shared.functions import (
resolve_env_var... | Retrieve a configuration value from AWS App Config. Parameters ---------- name: str Name of the configuration environment: str Environment of the configuration application: str Application of the configuration transform: str, optional Transforms the content from a JSON object ('json') or base64 binary string ('binary')... |
5,047 | from __future__ import annotations
import os
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union, overload
import boto3
from botocore.config import Config
from aws_lambda_powertools.shared import constants
from aws_lambda_powertools.shared.functions import (
resolve_max_age,
resolve_truthy... | null |
5,048 | from __future__ import annotations
import os
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union, overload
import boto3
from botocore.config import Config
from aws_lambda_powertools.shared import constants
from aws_lambda_powertools.shared.functions import (
resolve_max_age,
resolve_truthy... | null |
5,049 | from __future__ import annotations
import os
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union, overload
import boto3
from botocore.config import Config
from aws_lambda_powertools.shared import constants
from aws_lambda_powertools.shared.functions import (
resolve_max_age,
resolve_truthy... | null |
5,050 | from __future__ import annotations
import os
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union, overload
import boto3
from botocore.config import Config
from aws_lambda_powertools.shared import constants
from aws_lambda_powertools.shared.functions import (
resolve_max_age,
resolve_truthy... | null |
5,051 | from __future__ import annotations
import os
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union, overload
import boto3
from botocore.config import Config
from aws_lambda_powertools.shared import constants
from aws_lambda_powertools.shared.functions import (
resolve_max_age,
resolve_truthy... | Retrieve a parameter value from AWS Systems Manager (SSM) Parameter Store Parameters ---------- name: str Name of the parameter transform: str, optional Transforms the content from a JSON object ('json') or base64 binary string ('binary') decrypt: bool, optional If the parameter values should be decrypted force_fetch: ... |
5,052 | from __future__ import annotations
import os
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union, overload
import boto3
from botocore.config import Config
from aws_lambda_powertools.shared import constants
from aws_lambda_powertools.shared.functions import (
resolve_max_age,
resolve_truthy... | null |
5,053 | from __future__ import annotations
import os
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union, overload
import boto3
from botocore.config import Config
from aws_lambda_powertools.shared import constants
from aws_lambda_powertools.shared.functions import (
resolve_max_age,
resolve_truthy... | null |
5,054 | from __future__ import annotations
import os
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union, overload
import boto3
from botocore.config import Config
from aws_lambda_powertools.shared import constants
from aws_lambda_powertools.shared.functions import (
resolve_max_age,
resolve_truthy... | null |
5,055 | from __future__ import annotations
import os
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union, overload
import boto3
from botocore.config import Config
from aws_lambda_powertools.shared import constants
from aws_lambda_powertools.shared.functions import (
resolve_max_age,
resolve_truthy... | null |
5,056 | from __future__ import annotations
import os
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union, overload
import boto3
from botocore.config import Config
from aws_lambda_powertools.shared import constants
from aws_lambda_powertools.shared.functions import (
resolve_max_age,
resolve_truthy... | Retrieve multiple parameter values from AWS Systems Manager (SSM) Parameter Store For readability, we strip the path prefix name in the response. Parameters ---------- path: str Path to retrieve the parameters transform: str, optional Transforms the content from a JSON object ('json') or base64 binary string ('binary')... |
5,057 | from __future__ import annotations
import base64
import json
import os
from abc import ABC, abstractmethod
from datetime import datetime, timedelta
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
NamedTuple,
Optional,
Tuple,
Type,
Union,
cast,
overload,
)
import boto... | null |
5,058 | from __future__ import annotations
import base64
import json
import os
from abc import ABC, abstractmethod
from datetime import datetime, timedelta
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
NamedTuple,
Optional,
Tuple,
Type,
Union,
cast,
overload,
)
import boto... | null |
5,059 | from __future__ import annotations
import base64
import json
import os
from abc import ABC, abstractmethod
from datetime import datetime, timedelta
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
NamedTuple,
Optional,
Tuple,
Type,
Union,
cast,
overload,
)
import boto... | Transform a value using one of the available options. Parameters --------- value: str Parameter value to transform transform: str Type of transform, supported values are "json", "binary", and "auto" based on suffix (.json, .binary) key: str Parameter key when transform is auto to infer its transform method raise_on_tra... |
5,060 | from __future__ import annotations
import base64
import json
import os
from abc import ABC, abstractmethod
from datetime import datetime, timedelta
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
NamedTuple,
Optional,
Tuple,
Type,
Union,
cast,
overload,
)
import boto... | Clear cached parameter values from all providers |
5,061 | import os
from typing import TYPE_CHECKING, Any, Dict, Literal, Optional, Union, overload
import boto3
from botocore.config import Config
from aws_lambda_powertools.utilities.parameters.types import TransformOptions
from aws_lambda_powertools.shared import constants
from aws_lambda_powertools.shared.functions import re... | null |
5,062 | import os
from typing import TYPE_CHECKING, Any, Dict, Literal, Optional, Union, overload
import boto3
from botocore.config import Config
from aws_lambda_powertools.utilities.parameters.types import TransformOptions
from aws_lambda_powertools.shared import constants
from aws_lambda_powertools.shared.functions import re... | null |
5,063 | import os
from typing import TYPE_CHECKING, Any, Dict, Literal, Optional, Union, overload
import boto3
from botocore.config import Config
from aws_lambda_powertools.utilities.parameters.types import TransformOptions
from aws_lambda_powertools.shared import constants
from aws_lambda_powertools.shared.functions import re... | null |
5,064 | import os
from typing import TYPE_CHECKING, Any, Dict, Literal, Optional, Union, overload
import boto3
from botocore.config import Config
from aws_lambda_powertools.utilities.parameters.types import TransformOptions
from aws_lambda_powertools.shared import constants
from aws_lambda_powertools.shared.functions import re... | null |
5,065 | import os
from typing import TYPE_CHECKING, Any, Dict, Literal, Optional, Union, overload
import boto3
from botocore.config import Config
from aws_lambda_powertools.utilities.parameters.types import TransformOptions
from aws_lambda_powertools.shared import constants
from aws_lambda_powertools.shared.functions import re... | Retrieve a parameter value from AWS Secrets Manager Parameters ---------- name: str Name of the parameter transform: str, optional Transforms the content from a JSON object ('json') or base64 binary string ('binary') force_fetch: bool, optional Force update even before a cached item has expired, defaults to False max_a... |
5,066 | from __future__ import annotations
from datetime import datetime, tzinfo
from typing import Any, Dict, Optional
from dateutil.tz import gettz
from .schema import HOUR_MIN_SEPARATOR, ModuloRangeValues, TimeValues
def _get_now_from_timezone(timezone: Optional[tzinfo]) -> datetime:
"""
Returns now in the specified... | null |
5,067 | from __future__ import annotations
from datetime import datetime, tzinfo
from typing import Any, Dict, Optional
from dateutil.tz import gettz
from .schema import HOUR_MIN_SEPARATOR, ModuloRangeValues, TimeValues
def _get_now_from_timezone(timezone: Optional[tzinfo]) -> datetime:
"""
Returns now in the specified... | null |
5,068 | from __future__ import annotations
from datetime import datetime, tzinfo
from typing import Any, Dict, Optional
from dateutil.tz import gettz
from .schema import HOUR_MIN_SEPARATOR, ModuloRangeValues, TimeValues
def _get_now_from_timezone(timezone: Optional[tzinfo]) -> datetime:
HOUR_MIN_SEPARATOR = ":"
class T... | null |
5,069 | from __future__ import annotations
from datetime import datetime, tzinfo
from typing import Any, Dict, Optional
from dateutil.tz import gettz
from .schema import HOUR_MIN_SEPARATOR, ModuloRangeValues, TimeValues
class ModuloRangeValues(Enum):
"""
Possible values when using modulo range rule
"""
BASE =... | Returns for a given context 'a' and modulo condition 'b' -> b.start <= a % b.base <= b.end |
5,070 | from __future__ import annotations
from datetime import datetime, tzinfo
from typing import Any, Dict, Optional
from dateutil.tz import gettz
from .schema import HOUR_MIN_SEPARATOR, ModuloRangeValues, TimeValues
The provided code snippet includes necessary dependencies for implementing the `compare_any_in_list` functi... | Comparator for ANY_IN_VALUE action Parameters ---------- context_value : list user-defined context for flag evaluation condition_value : list schema value available for condition being evaluated Returns ------- bool Whether any list item in context_value is available in condition_value |
5,071 | from __future__ import annotations
from datetime import datetime, tzinfo
from typing import Any, Dict, Optional
from dateutil.tz import gettz
from .schema import HOUR_MIN_SEPARATOR, ModuloRangeValues, TimeValues
The provided code snippet includes necessary dependencies for implementing the `compare_all_in_list` functi... | Comparator for ALL_IN_VALUE action Parameters ---------- context_value : list user-defined context for flag evaluation condition_value : list schema value available for condition being evaluated Returns ------- bool Whether all list items in context_value are available in condition_value |
5,072 | from __future__ import annotations
from datetime import datetime, tzinfo
from typing import Any, Dict, Optional
from dateutil.tz import gettz
from .schema import HOUR_MIN_SEPARATOR, ModuloRangeValues, TimeValues
The provided code snippet includes necessary dependencies for implementing the `compare_none_in_list` funct... | Comparator for NONE_IN_VALUE action Parameters ---------- context_value : list user-defined context for flag evaluation condition_value : list schema value available for condition being evaluated Returns ------- bool Whether list items in context_value are **not** available in condition_value |
5,073 | import logging
from typing import Any, Callable, Dict, Optional, Union
from aws_lambda_powertools.utilities import jmespath_utils
from ...middleware_factory import lambda_handler_decorator
from .base import validate_data_against_schema
logger = logging.getLogger(__name__)
def validate_data_against_schema(data: Union[D... | Lambda handler decorator to validate incoming/outbound data using a JSON Schema Parameters ---------- handler : Callable Method to annotate on event : Dict Lambda event to be validated context : Any Lambda context object inbound_schema : Dict JSON Schema to validate incoming event outbound_schema : Dict JSON Schema to ... |
5,074 | import logging
from typing import Any, Callable, Dict, Optional, Union
from aws_lambda_powertools.utilities import jmespath_utils
from ...middleware_factory import lambda_handler_decorator
from .base import validate_data_against_schema
def validate_data_against_schema(data: Union[Dict, str], schema: Dict, formats: Opt... | Standalone function to validate event data using a JSON Schema Typically used when you need more control over the validation process. Parameters ---------- event : Dict Lambda event to be validated schema : Dict JSON Schema to validate incoming event envelope : Dict JMESPath expression to filter data against jmespath_o... |
5,075 | import logging
import typing
from typing import Any, Callable, Dict, Optional, Type, overload
from aws_lambda_powertools.utilities.parser.compat import disable_pydantic_v2_warning
from aws_lambda_powertools.utilities.parser.types import EventParserReturnType, Model
from ...middleware_factory import lambda_handler_decor... | Lambda handler decorator to parse & validate events using Pydantic models It requires a model that implements Pydantic BaseModel to parse & validate the event. When an envelope is given, it'll use the following logic: 1. Parse the event against the envelope model first e.g. EnvelopeModel(**event) 2. Envelope will extra... |
5,076 | import json
import zlib
from typing import Dict, List, Type, Union
from pydantic import BaseModel, validator
from aws_lambda_powertools.shared.functions import base64_decode
from aws_lambda_powertools.utilities.parser.models.cloudwatch import (
CloudWatchLogsDecode,
)
from aws_lambda_powertools.utilities.parser.typ... | null |
5,077 | import json
import zlib
from typing import Dict, List, Type, Union
from pydantic import BaseModel, validator
from aws_lambda_powertools.shared.functions import base64_decode
from aws_lambda_powertools.utilities.parser.models.cloudwatch import (
CloudWatchLogsDecode,
)
from aws_lambda_powertools.utilities.parser.typ... | null |
5,078 | import functools
import logging
import os
from inspect import isclass
from typing import Any, Callable, Dict, Optional, Type, Union, cast
from aws_lambda_powertools.middleware_factory import lambda_handler_decorator
from aws_lambda_powertools.shared import constants
from aws_lambda_powertools.shared.types import AnyCal... | Decorator to handle idempotency Parameters ---------- handler: Callable Lambda's handler event: Dict Lambda's Event context: Dict Lambda's Context persistence_store: BasePersistenceLayer Instance of BasePersistenceLayer to store data config: IdempotencyConfig Configuration Examples -------- **Processes Lambda's event i... |
5,079 | import functools
import logging
import os
from inspect import isclass
from typing import Any, Callable, Dict, Optional, Type, Union, cast
from aws_lambda_powertools.middleware_factory import lambda_handler_decorator
from aws_lambda_powertools.shared import constants
from aws_lambda_powertools.shared.types import AnyCal... | Decorator to handle idempotency of any function Parameters ---------- function: Callable Function to be decorated data_keyword_argument: str Keyword parameter name in function's signature that we should hash as idempotency key, e.g. "order" persistence_store: BasePersistenceLayer Instance of BasePersistenceLayer to sto... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.