text stringlengths 81 112k |
|---|
Returns a list of valid actions for each element of the group.
def get_valid_actions(self) -> List[Dict[str, Tuple[torch.Tensor, torch.Tensor, List[int]]]]:
"""
Returns a list of valid actions for each element of the group.
"""
return [state.get_valid_actions() for state in self.grammar... |
A worker that pulls filenames off the input queue, uses the dataset reader
to read them, and places the generated instances on the output queue.
When there are no filenames left on the input queue, it puts its ``index``
on the output queue and doesn't do anything else.
def _worker(reader: DatasetReader,
... |
Given labels and a constraint type, returns the allowed transitions. It will
additionally include transitions for the start and end states, which are used
by the conditional random field.
Parameters
----------
constraint_type : ``str``, required
Indicates which constraint to apply. Current ... |
Given a constraint type and strings ``from_tag`` and ``to_tag`` that
represent the origin and destination of the transition, return whether
the transition is allowed under the given constraint type.
Parameters
----------
constraint_type : ``str``, required
Indicates which constraint to appl... |
Computes the (batch_size,) denominator term for the log-likelihood, which is the
sum of the likelihoods across all possible state sequences.
def _input_likelihood(self, logits: torch.Tensor, mask: torch.Tensor) -> torch.Tensor:
"""
Computes the (batch_size,) denominator term for the log-likelih... |
Computes the numerator term for the log-likelihood, which is just score(inputs, tags)
def _joint_likelihood(self,
logits: torch.Tensor,
tags: torch.Tensor,
mask: torch.LongTensor) -> torch.Tensor:
"""
Computes the numerator t... |
Computes the log likelihood.
def forward(self,
inputs: torch.Tensor,
tags: torch.Tensor,
mask: torch.ByteTensor = None) -> torch.Tensor:
"""
Computes the log likelihood.
"""
# pylint: disable=arguments-differ
if mask is None:
... |
Uses viterbi algorithm to find most likely tags for the given inputs.
If constraints are applied, disallows all other transitions.
def viterbi_tags(self,
logits: torch.Tensor,
mask: torch.Tensor) -> List[Tuple[List[int], float]]:
"""
Uses viterbi algori... |
Given a starting state and a step function, apply beam search to find the
most likely target sequences.
Notes
-----
If your step function returns ``-inf`` for some log probabilities
(like if you're using a masked log-softmax) then some of the "best"
sequences returned ma... |
Parameters
----------
data_directory : str, required.
The path to the data directory of https://github.com/jkkummerfeld/text2sql-data
which has been preprocessed using scripts/reformat_text2sql_data.py.
dataset : str, optional.
The dataset to parse. By default all are parsed.
fil... |
Checks whether the provided obj takes a certain arg.
If it's a class, we're really checking whether its constructor does.
If it's a function or method, we're checking the object itself.
Otherwise, we raise an error.
def takes_arg(obj, arg: str) -> bool:
"""
Checks whether the provided obj takes a c... |
Checks whether a provided object takes in any positional arguments.
Similar to takes_arg, we do this for both the __init__ function of
the class or a function / method
Otherwise, we raise an error
def takes_kwargs(obj) -> bool:
"""
Checks whether a provided object takes in any positional arguments.... |
Optional[X] annotations are actually represented as Union[X, NoneType].
For our purposes, the "Optional" part is not interesting, so here we
throw it away.
def remove_optional(annotation: type):
"""
Optional[X] annotations are actually represented as Union[X, NoneType].
For our purposes, the "Optio... |
Given some class, a `Params` object, and potentially other keyword arguments,
create a dict of keyword args suitable for passing to the class's constructor.
The function does this by finding the class's constructor, matching the constructor
arguments to entries in the `params` object, and instantiating val... |
Given a dictionary of extra arguments, returns a dictionary of
kwargs that actually are a part of the signature of the cls.from_params
(or cls) method.
def create_extras(cls: Type[T],
extras: Dict[str, Any]) -> Dict[str, Any]:
"""
Given a dictionary of extra arguments, returns a dicti... |
Does the work of actually constructing an individual argument for :func:`create_kwargs`.
Here we're in the inner loop of iterating over the parameters to a particular constructor,
trying to construct just one of them. The information we get for that parameter is its name,
its type annotation, and its defa... |
This is the automatic implementation of `from_params`. Any class that subclasses `FromParams`
(or `Registrable`, which itself subclasses `FromParams`) gets this implementation for free.
If you want your class to be instantiated from params in the "obvious" way -- pop off parameters
and hand them... |
The main method in the ``TransitionFunction`` API. This function defines the computation
done at each step of decoding and returns a ranked list of next states.
The input state is `grouped`, to allow for efficient computation, but the output states
should all have a ``group_size`` of 1, to mak... |
In PyTorch 1.0, Tensor._sparse_mask was changed to Tensor.sparse_mask.
This wrapper allows AllenNLP to (temporarily) work with both 1.0 and 0.4.1.
def _safe_sparse_mask(tensor: torch.Tensor, mask: torch.Tensor) -> torch.Tensor:
"""
In PyTorch 1.0, Tensor._sparse_mask was changed to Tensor.sparse_mask.
... |
Parses a chunk of text in the SemEval SDP format.
Each word in the sentence is returned as a dictionary with the following
format:
'id': '1',
'form': 'Pierre',
'lemma': 'Pierre',
'pos': 'NNP',
'head': '2', # Note that this is the `syntactic` head.
'deprel': 'nn',
'top': '-',
'... |
Disambiguates single GPU and multiple GPU settings for cuda_device param.
def parse_cuda_device(cuda_device: Union[str, int, List[int]]) -> Union[int, List[int]]:
"""
Disambiguates single GPU and multiple GPU settings for cuda_device param.
"""
def from_list(strings):
if len(strings) > 1:
... |
Just converts from an ``argparse.Namespace`` object to string paths.
def fine_tune_model_from_args(args: argparse.Namespace):
"""
Just converts from an ``argparse.Namespace`` object to string paths.
"""
fine_tune_model_from_file_paths(model_archive_path=args.model_archive,
... |
A wrapper around :func:`fine_tune_model` which loads the model archive from a file.
Parameters
----------
model_archive_path : ``str``
Path to a saved model archive that is the result of running the ``train`` command.
config_file : ``str``
A configuration file specifying how to continue... |
Fine tunes the given model, using a set of parameters that is largely identical to those used
for :func:`~allennlp.commands.train.train_model`, except that the ``model`` section is ignored,
if it is present (as we are already given a ``Model`` here).
The main difference between the logic done here and the ... |
Extracts the top-k scoring items with respect to the scorer. We additionally return
the indices of the top-k in their original order, not ordered by score, so that downstream
components can rely on the original ordering (e.g., for knowing what spans are valid
antecedents in a coreference resolut... |
Add the epoch number to the batch instances as a MetadataField.
def add_epoch_number(batch: Batch, epoch: int) -> Batch:
"""
Add the epoch number to the batch instances as a MetadataField.
"""
for instance in batch.instances:
instance.fields['epoch_num'] = MetadataField(epoch)
return batch |
Take the next `max_instances` instances from the given dataset.
If `max_instances` is `None`, then just take all instances from the dataset.
If `max_instances` is not `None`, each call resumes where the previous one
left off, and when you get to the end of the dataset you start again from the be... |
Breaks the dataset into "memory-sized" lists of instances,
which it yields up one at a time until it gets through a full epoch.
For example, if the dataset is already an in-memory list, and each epoch
represents one pass through the dataset, it just yields back the dataset.
Whereas if t... |
If self._maximum_samples_per_batch is specified, then split the batch
into smaller sub-batches if it exceeds the maximum size.
Parameters
----------
batch_instances : ``Iterable[Instance]``
A candidate batch.
excess : ``Deque[Instance]``
Instances that we... |
Returns the number of batches that ``dataset`` will be split into; if you want to track
progress through the batch with the generator produced by ``__call__``, this could be
useful.
def get_num_batches(self, instances: Iterable[Instance]) -> int:
"""
Returns the number of batches that `... |
This method should return one epoch worth of batches.
def _create_batches(self, instances: Iterable[Instance], shuffle: bool) -> Iterable[Batch]:
"""
This method should return one epoch worth of batches.
"""
raise NotImplementedError |
TQDM and requests use carriage returns to get the training line to update for each batch
without adding more lines to the terminal output. Displaying those in a file won't work
correctly, so we'll just make sure that each batch shows up on its one line.
:param message: the message to permute
:return: t... |
Context manager that captures the internal-module outputs of
this predictor's model. The idea is that you could use it as follows:
.. code-block:: python
with predictor.capture_model_internals() as internals:
outputs = predictor.predict_json(inputs)
return {**o... |
Converts a list of JSON objects into a list of :class:`~allennlp.data.instance.Instance`s.
By default, this expects that a "batch" consists of a list of JSON blobs which would
individually be predicted by :func:`predict_json`. In order to use this method for
batch prediction, :func:`_json_to_ins... |
Instantiate a :class:`Predictor` from an archive path.
If you need more detailed configuration options, such as running the predictor on the GPU,
please use `from_archive`.
Parameters
----------
archive_path The path to the archive.
Returns
-------
A Pr... |
Instantiate a :class:`Predictor` from an :class:`~allennlp.models.archival.Archive`;
that is, from the result of training a model. Optionally specify which `Predictor`
subclass; otherwise, the default one for the model will be used.
def from_archive(cls, archive: Archive, predictor_name: str = None) ->... |
Compute 'Scaled Dot Product Attention
def attention(query: torch.Tensor,
key: torch.Tensor,
value: torch.Tensor,
mask: torch.Tensor = None,
dropout: Callable = None) -> Tuple[torch.Tensor, torch.Tensor]:
"""Compute 'Scaled Dot Product Attention'"""
d_k = ... |
Mask out subsequent positions.
def subsequent_mask(size: int, device: str = 'cpu') -> torch.Tensor:
"""Mask out subsequent positions."""
mask = torch.tril(torch.ones(size, size, device=device, dtype=torch.int32)).unsqueeze(0)
return mask |
Helper: Construct a model from hyperparameters.
def make_model(num_layers: int = 6,
input_size: int = 512, # Attention size
hidden_size: int = 2048, # FF layer size
heads: int = 8,
dropout: float = 0.1,
return_all_layers: bool = False) -> Tra... |
Pass the input (and mask) through each layer in turn.
def forward(self, x, mask):
"""Pass the input (and mask) through each layer in turn."""
all_layers = []
for layer in self.layers:
x = layer(x, mask)
if self.return_all_layers:
all_layers.append(x)
... |
Apply residual connection to any sublayer with the same size.
def forward(self, x: torch.Tensor, sublayer: Callable[[torch.Tensor], torch.Tensor]) -> torch.Tensor:
"""Apply residual connection to any sublayer with the same size."""
return x + self.dropout(sublayer(self.norm(x))) |
Follow Figure 1 (left) for connections.
def forward(self, x: torch.Tensor, mask: torch.Tensor) -> torch.Tensor:
"""Follow Figure 1 (left) for connections."""
x = self.sublayer[0](x, lambda x: self.self_attn(x, x, x, mask))
return self.sublayer[1](x, self.feed_forward) |
An initaliser which preserves output variance for approximately gaussian
distributed inputs. This boils down to initialising layers using a uniform
distribution in the range ``(-sqrt(3/dim[0]) * scale, sqrt(3 / dim[0]) * scale)``, where
``dim[0]`` is equal to the input dimension of the parameter and the ``s... |
An initializer which allows initializing model parameters in "blocks". This is helpful
in the case of recurrent models which use multiple gates applied to linear projections,
which can be computed efficiently if they are concatenated together. However, they are
separate parameters which should be initialize... |
Initialize the biases of the forget gate to 1, and all other gates to 0,
following Jozefowicz et al., An Empirical Exploration of Recurrent Network Architectures
def lstm_hidden_bias(tensor: torch.Tensor) -> None:
"""
Initialize the biases of the forget gate to 1, and all other gates to 0,
following Jo... |
Converts a Params object into an InitializerApplicator. The json should
be formatted as follows::
[
["parameter_regex_match1",
{
"type": "normal"
"mean": 0.01
"std": 0.1
}... |
We read tables formatted as TSV files here. We assume the first line in the file is a tab
separated list of column headers, and all subsequent lines are content rows. For example if
the TSV file is:
Nation Olympics Medals
USA 1896 8
China 1932 ... |
We read tables formatted as JSON objects (dicts) here. This is useful when you are reading
data from a demo. The expected format is::
{"question": [token1, token2, ...],
"columns": [column1, column2, ...],
"cells": [[row1_cell1, row1_cell2, ...],
[ro... |
Finds numbers in the input tokens and returns them as strings. We do some simple heuristic
number recognition, finding ordinals and cardinals expressed as text ("one", "first",
etc.), as well as numerals ("7th", "3rd"), months (mapping "july" to 7), and units
("1ghz").
We also handle y... |
Splits a cell into parts and returns the parts of the cell. We return a list of
``(entity_name, entity_text)``, where ``entity_name`` is ``fb:part.[something]``, and
``entity_text`` is the text of the cell corresponding to that part. For many cells, there
is only one "part", and we return a li... |
Returns true if there is any cell in this column that can be split.
def _should_split_column_cells(cls, column_cells: List[str]) -> bool:
"""
Returns true if there is any cell in this column that can be split.
"""
return any(cls._should_split_cell(cell_text) for cell_text in column_cell... |
Checks whether the cell should be split. We're just doing the same thing that SEMPRE did
here.
def _should_split_cell(cls, cell_text: str) -> bool:
"""
Checks whether the cell should be split. We're just doing the same thing that SEMPRE did
here.
"""
if ', ' in cell_te... |
Returns entities that can be linked to spans in the question, that should be in the agenda,
for training a coverage based semantic parser. This method essentially does a heuristic
entity linking, to provide weak supervision for a learning to search parser.
def get_linked_agenda_items(self) -> List[str]... |
inp_fn: str, required.
Path to file from which to read Open IE extractions in Open IE4's format.
domain: str, required.
Domain to be used when writing CoNLL format.
out_fn: str, required.
Path to file to which to write the CoNLL format Open IE extractions.
def main(inp_fn: str,
do... |
Return an Element from span (list of spacy toks)
def element_from_span(span: List[int],
span_type: str) -> Element:
"""
Return an Element from span (list of spacy toks)
"""
return Element(span_type,
[span[0].idx,
span[-1].idx + len(span[-1])]... |
Ensure single word predicate
by adding "before-predicate" and "after-predicate"
arguments.
def split_predicate(ex: Extraction) -> Extraction:
"""
Ensure single word predicate
by adding "before-predicate" and "after-predicate"
arguments.
"""
rel_toks = ex.toks[char_to_word_index(ex.rel.s... |
Return a conll representation of a given input Extraction.
def extraction_to_conll(ex: Extraction) -> List[str]:
"""
Return a conll representation of a given input Extraction.
"""
ex = split_predicate(ex)
toks = ex.sent.split(' ')
ret = ['*'] * len(toks)
args = [ex.arg1] + ex.args2
rels... |
Return an integer tuple from
textual representation of closed / open spans.
def interpret_span(text_spans: str) -> List[int]:
"""
Return an integer tuple from
textual representation of closed / open spans.
"""
m = regex.match("^(?:(?:([\(\[]\d+, \d+[\)\]])|({\d+}))[,]?\s*)+$",
... |
Construct an Element instance from regexp
groups.
def interpret_element(element_type: str, text: str, span: str) -> Element:
"""
Construct an Element instance from regexp
groups.
"""
return Element(element_type,
interpret_span(span),
text) |
Parse a raw element into text and indices (integers).
def parse_element(raw_element: str) -> List[Element]:
"""
Parse a raw element into text and indices (integers).
"""
elements = [regex.match("^(([a-zA-Z]+)\(([^;]+),List\(([^;]*)\)\))$",
elem.lstrip().rstrip())
... |
Given a list of extractions for a single sentence -
convert it to conll representation.
def convert_sent_to_conll(sent_ls: List[Extraction]):
"""
Given a list of extractions for a single sentence -
convert it to conll representation.
"""
# Sanity check - make sure all extractions are on the sam... |
Pad line to conform to ontonotes representation.
def pad_line_to_ontonotes(line, domain) -> List[str]:
"""
Pad line to conform to ontonotes representation.
"""
word_ind, word = line[ : 2]
pos = 'XX'
oie_tags = line[2 : ]
line_num = 0
parse = "-"
lemma = "-"
return [domain, line_... |
Given a dictionary from sentence -> extractions,
return a corresponding CoNLL representation.
def convert_sent_dict_to_conll(sent_dic, domain) -> str:
"""
Given a dictionary from sentence -> extractions,
return a corresponding CoNLL representation.
"""
return '\n\n'.join(['\n'.join(['\t'.join(m... |
Given a Kinesis record data that is decoded, deaggregate if it was packed using the
Kinesis Producer Library into individual records. This method will be a no-op for any
records that are not aggregated (but will still return them).
decoded_data - the base64 decoded data that comprises either the KPL a... |
Parses a S3 Uri into a dictionary of the Bucket, Key, and VersionId
:return: a BodyS3Location dict or None if not an S3 Uri
:rtype: dict
def parse_s3_uri(uri):
"""Parses a S3 Uri into a dictionary of the Bucket, Key, and VersionId
:return: a BodyS3Location dict or None if not an S3 Uri
:rtype: di... |
Constructs a S3 URI string from given code dictionary
:param dict code_dict: Dictionary containing Lambda function Code S3 location of the form
{S3Bucket, S3Key, S3ObjectVersion}
:return: S3 URI of form s3://bucket/key?versionId=version
:rtype string
def to_s3_uri(code_dict):
... |
Constructs a Lambda `Code` or `Content` property, from the SAM `CodeUri` or `ContentUri` property.
This follows the current scheme for Lambda Functions and LayerVersions.
:param dict or string location_uri: s3 location dict or string
:param string logical_id: logical_id of the resource calling this functio... |
Returns a list of policies from the resource properties. This method knows how to interpret and handle
polymorphic nature of the policies property.
Policies can be one of the following:
* Managed policy name: string
* List of managed policy names: list of strings
* ... |
Is there policies data in this resource?
:param dict resource_properties: Properties of the resource
:return: True if we can process this resource. False, otherwise
def _contains_policies(self, resource_properties):
"""
Is there policies data in this resource?
:param dict reso... |
Returns the type of the given policy
:param string or dict policy: Policy data
:return PolicyTypes: Type of the given policy. None, if type could not be inferred
def _get_type(self, policy):
"""
Returns the type of the given policy
:param string or dict policy: Policy data
... |
Is the given policy data a policy template? Policy templates is a dictionary with one key which is the name
of the template.
:param dict policy: Policy data
:return: True, if this is a policy template. False if it is not
def _is_policy_template(self, policy):
"""
Is the given p... |
r"""
Call shadow lambda to obtain current shadow state.
:Keyword Arguments:
* *thingName* (``string``) --
[REQUIRED]
The name of the thing.
:returns: (``dict``) --
The output from the GetThingShadow operation
* *payload* (``bytes``) -... |
r"""
Updates the thing shadow for the specified thing.
:Keyword Arguments:
* *thingName* (``string``) --
[REQUIRED]
The name of the thing.
* *payload* (``bytes or seekable file-like object``) --
[REQUIRED]
The state informa... |
r"""
Deletes the thing shadow for the specified thing.
:Keyword Arguments:
* *thingName* (``string``) --
[REQUIRED]
The name of the thing.
:returns: (``dict``) --
The output from the DeleteThingShadow operation
* *payload* (``bytes``)... |
r"""
Publishes state information.
:Keyword Arguments:
* *topic* (``string``) --
[REQUIRED]
The name of the MQTT topic.
* *payload* (``bytes or seekable file-like object``) --
The state information, in JSON format.
:returns: None... |
Adds global properties to the resource, if necessary. This method is a no-op if there are no global properties
for this resource type
:param string resource_type: Type of the resource (Ex: AWS::Serverless::Function)
:param dict resource_properties: Properties of the resource that need to be mer... |
Takes a SAM template as input and parses the Globals section
:param globals_dict: Dictionary representation of the Globals section
:return: Processed globals dictionary which can be used to quickly identify properties to merge
:raises: InvalidResourceException if the input contains properties t... |
Actually perform the merge operation for the given inputs. This method is used as part of the recursion.
Therefore input values can be of any type. So is the output.
:param global_value: Global value to be merged
:param local_value: Local value to be merged
:return: Merged result
def _... |
Merges the two dictionaries together
:param global_dict: Global dictionary to be merged
:param local_dict: Local dictionary to be merged
:return: New merged dictionary with values shallow copied
def _merge_dict(self, global_dict, local_dict):
"""
Merges the two dictionaries tog... |
Returns the token type of the input.
:param input: Input whose type is to be determined
:return TOKENS: Token type of the input
def _token_of(self, input):
"""
Returns the token type of the input.
:param input: Input whose type is to be determined
:return TOKENS: Token... |
Is this a valid SAM template dictionary
:param dict template_dict: Data to be validated
:param dict schema: Optional, dictionary containing JSON Schema representing SAM template
:return: Empty string if there are no validation errors in template
def validate(template_dict, schema=None):
... |
Generates a number within a reasonable range that might be expected for a flight.
The price is fixed for a given pair of locations.
def generate_car_price(location, days, age, car_type):
"""
Generates a number within a reasonable range that might be expected for a flight.
The price is fixed for a given... |
Generates a number within a reasonable range that might be expected for a hotel.
The price is fixed for a pair of location and roomType.
def generate_hotel_price(location, nights, room_type):
"""
Generates a number within a reasonable range that might be expected for a hotel.
The price is fixed for a p... |
Performs dialog management and fulfillment for booking a hotel.
Beyond fulfillment, the implementation for this intent demonstrates the following:
1) Use of elicitSlot in slot validation and re-prompting
2) Use of sessionAttributes to pass information that can be used to guide conversation
def book_hotel(... |
Performs dialog management and fulfillment for booking a car.
Beyond fulfillment, the implementation for this intent demonstrates the following:
1) Use of elicitSlot in slot validation and re-prompting
2) Use of sessionAttributes to pass information that can be used to guide conversation
def book_car(inte... |
Called when the user specifies an intent for this bot.
def dispatch(intent_request):
"""
Called when the user specifies an intent for this bot.
"""
logger.debug('dispatch userId={}, intentName={}'.format(intent_request['userId'], intent_request['currentIntent']['name']))
intent_name = intent_requ... |
Returns the Lambda EventSourceMapping to which this pull event corresponds. Adds the appropriate managed
policy to the function's execution role, if such a role is provided.
:param dict kwargs: a dict containing the execution role generated for the function
:returns: a list of vanilla CloudForm... |
If this source triggers a Lambda function whose execution role is auto-generated by SAM, add the
appropriate managed policy to this Role.
:param model.iam.IAMROle role: the execution role generated for the function
def _link_policy(self, role):
"""If this source triggers a Lambda function whos... |
Method to read default values for template parameters and merge with user supplied values.
Example:
If the template contains the following parameters defined
Parameters:
Param1:
Type: String
Default: default_value
Param2:
... |
Add pseudo parameter values
:return: parameter values that have pseudo parameter in it
def add_pseudo_parameter_values(self):
"""
Add pseudo parameter values
:return: parameter values that have pseudo parameter in it
"""
if 'AWS::Region' not in self.parameter_values:
... |
Add this deployment preference to the collection
:raise ValueError if an existing logical id already exists in the _resource_preferences
:param logical_id: logical id of the resource where this deployment preference applies
:param deployment_preference_dict: the input SAM template deployment pr... |
:return: only the logical id's for the deployment preferences in this collection which are enabled
def enabled_logical_ids(self):
"""
:return: only the logical id's for the deployment preferences in this collection which are enabled
"""
return [logical_id for logical_id, preference in s... |
:param function_logical_id: logical_id of the function this deployment group belongs to
:return: CodeDeployDeploymentGroup resource
def deployment_group(self, function_logical_id):
"""
:param function_logical_id: logical_id of the function this deployment group belongs to
:return: CodeD... |
If we wanted to initialize the session to have some attributes we could
add those here
def get_welcome_response():
""" If we wanted to initialize the session to have some attributes we could
add those here
"""
session_attributes = {}
card_title = "Welcome"
speech_output = "Welcome to the A... |
Sets the color in the session and prepares the speech to reply to the
user.
def set_color_in_session(intent, session):
""" Sets the color in the session and prepares the speech to reply to the
user.
"""
card_title = intent['name']
session_attributes = {}
should_end_session = False
if ... |
Called when the user specifies an intent for this skill
def on_intent(intent_request, session):
""" Called when the user specifies an intent for this skill """
print("on_intent requestId=" + intent_request['requestId'] +
", sessionId=" + session['sessionId'])
intent = intent_request['intent']
... |
Route the incoming request based on type (LaunchRequest, IntentRequest,
etc.) The JSON body of the request is provided in the event parameter.
def lambda_handler(event, context):
""" Route the incoming request based on type (LaunchRequest, IntentRequest,
etc.) The JSON body of the request is provided in th... |
Generate stable LogicalIds based on the prefix and given data. This method ensures that the logicalId is
deterministic and stable based on input prefix & data object. In other words:
logicalId changes *if and only if* either the `prefix` or `data_obj` changes
Internally we simply use a SHA... |
Generate and return a hash of data that can be used as suffix of logicalId
:return: Hash of data if it was present
:rtype string
def get_hash(self, length=HASH_LENGTH):
"""
Generate and return a hash of data that can be used as suffix of logicalId
:return: Hash of data if it w... |
Stable, platform & language-independent stringification of a data with basic Python type.
We use JSON to dump a string instead of `str()` method in order to be language independent.
:param data: Data to be stringified. If this is one of JSON native types like string, dict, array etc, it will
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.