Search is not available for this dataset
text stringlengths 75 104k |
|---|
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_state] |
def _worker(reader: DatasetReader,
input_queue: Queue,
output_queue: Queue,
index: int) -> None:
"""
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 file... |
def allowed_transitions(constraint_type: str, labels: Dict[int, str]) -> List[Tuple[int, int]]:
"""
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
... |
def is_transition_allowed(constraint_type: str,
from_tag: str,
from_entity: str,
to_tag: str,
to_entity: str):
"""
Given a constraint type and strings ``from_tag`` and ``to_tag`` that
represent the origin... |
def _input_likelihood(self, logits: torch.Tensor, mask: torch.Tensor) -> torch.Tensor:
"""
Computes the (batch_size,) denominator term for the log-likelihood, which is the
sum of the likelihoods across all possible state sequences.
"""
batch_size, sequence_length, num_tags = logi... |
def _joint_likelihood(self,
logits: torch.Tensor,
tags: torch.Tensor,
mask: torch.LongTensor) -> torch.Tensor:
"""
Computes the numerator term for the log-likelihood, which is just score(inputs, tags)
"""
batch... |
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:
mask = torch.ones(*tags... |
def viterbi_tags(self,
logits: torch.Tensor,
mask: torch.Tensor) -> List[Tuple[List[int], float]]:
"""
Uses viterbi algorithm to find most likely tags for the given inputs.
If constraints are applied, disallows all other transitions.
"""
... |
def search(self,
start_predictions: torch.Tensor,
start_state: StateType,
step: StepFunctionType) -> Tuple[torch.Tensor, torch.Tensor]:
"""
Given a starting state and a step function, apply beam search to find the
most likely target sequences.
... |
def main(data_directory: int, dataset: str = None, filter_by: str = None, verbose: bool = False) -> None:
"""
Parameters
----------
data_directory : str, required.
The path to the data directory of https://github.com/jkkummerfeld/text2sql-data
which has been preprocessed using scripts/re... |
def takes_arg(obj, arg: str) -> bool:
"""
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.
"""
if inspect.isclass(obj):
... |
def takes_kwargs(obj) -> bool:
"""
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
"""
if inspect.isclass(obj):
signature = inspect.sig... |
def remove_optional(annotation: type):
"""
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.
"""
origin = getattr(annotation, '__origin__', None)
args = getattr(annotation, '__args__', (... |
def create_kwargs(cls: Type[T], params: Params, **extras) -> Dict[str, Any]:
"""
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, matchi... |
def create_extras(cls: Type[T],
extras: Dict[str, Any]) -> Dict[str, Any]:
"""
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.
"""
subextras: Dict[str, Any] = {}
if hasat... |
def construct_arg(cls: Type[T], # pylint: disable=inconsistent-return-statements,too-many-return-statements
param_name: str,
annotation: Type,
default: Any,
params: Params,
**extras) -> Any:
"""
Does the work of actually c... |
def from_params(cls: Type[T], params: Params, **extras) -> T:
"""
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 instant... |
def take_step(self,
state: StateType,
max_actions: int = None,
allowed_actions: List[Set] = None) -> List[StateType]:
"""
The main method in the ``TransitionFunction`` API. This function defines the computation
done at each step of decoding ... |
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.
This wrapper allows AllenNLP to (temporarily) work with both 1.0 and 0.4.1.
"""
# pylint: disable=protected-access
try:
return tenso... |
def parse_sentence(sentence_blob: str) -> Tuple[List[Dict[str, str]], List[Tuple[int, int]], List[str]]:
"""
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',
... |
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:
return [int(d) for d in strings]
elif len(strings) == 1:
... |
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,
config_file=args.config_file,
... |
def fine_tune_model_from_file_paths(model_archive_path: str,
config_file: str,
serialization_dir: str,
overrides: str = "",
extend_vocab: bool = False,
... |
def fine_tune_model(model: Model,
params: Params,
serialization_dir: str,
extend_vocab: bool = False,
file_friendly_logging: bool = False,
batch_weight_key: str = "",
embedding_sources_mapping: Dict[s... |
def forward(self, # pylint: disable=arguments-differ
embeddings: torch.FloatTensor,
mask: torch.LongTensor,
num_items_to_keep: Union[int, torch.LongTensor]) -> Tuple[torch.FloatTensor, torch.LongTensor,
... |
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 |
def _take_instances(self,
instances: Iterable[Instance],
max_instances: Optional[int] = None) -> Iterator[Instance]:
"""
Take the next `max_instances` instances from the given dataset.
If `max_instances` is `None`, then just take all instances from... |
def _memory_sized_lists(self,
instances: Iterable[Instance]) -> Iterable[List[Instance]]:
"""
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 alread... |
def _ensure_batch_is_sufficiently_small(
self,
batch_instances: Iterable[Instance],
excess: Deque[Instance]) -> List[List[Instance]]:
"""
If self._maximum_samples_per_batch is specified, then split the batch
into smaller sub-batches if it exceeds the maximum s... |
def get_num_batches(self, instances: Iterable[Instance]) -> int:
"""
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.
"""
if is_lazy(instan... |
def _create_batches(self, instances: Iterable[Instance], shuffle: bool) -> Iterable[Batch]:
"""
This method should return one epoch worth of batches.
"""
raise NotImplementedError |
def replace_cr_with_newline(message: str):
"""
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.
... |
def capture_model_internals(self) -> Iterator[dict]:
"""
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:
... |
def _batch_json_to_instances(self, json_dicts: List[JsonDict]) -> List[Instance]:
"""
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 ... |
def from_path(cls, archive_path: str, predictor_name: str = None) -> 'Predictor':
"""
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
... |
def from_archive(cls, archive: Archive, predictor_name: str = None) -> 'Predictor':
"""
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... |
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 = query.size(-1)
scores = torch.matmu... |
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 |
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) -> TransformerEncoder:
"""Helper: Construct a model... |
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)
if self.return_all_layers:
all_layers[... |
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))) |
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) |
def uniform_unit_scaling(tensor: torch.Tensor, nonlinearity: str = "linear"):
"""
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]) * s... |
def block_orthogonal(tensor: torch.Tensor,
split_sizes: List[int],
gain: float = 1.0) -> None:
"""
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 proje... |
def lstm_hidden_bias(tensor: torch.Tensor) -> None:
"""
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
"""
# gates are (b_hi|b_hf|b_hg|b_ho) of shape (4*hidden_size)
tensor.data.zer... |
def from_params(cls, params: List[Tuple[str, Params]] = None) -> "InitializerApplicator":
"""
Converts a Params object into an InitializerApplicator. The json should
be formatted as follows::
[
["parameter_regex_match1",
{
... |
def read_from_file(cls, filename: str, question: List[Token]) -> 'TableQuestionKnowledgeGraph':
"""
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 TS... |
def read_from_json(cls, json_object: Dict[str, Any]) -> 'TableQuestionKnowledgeGraph':
"""
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"... |
def _get_numbers_from_tokens(tokens: List[Token]) -> List[Tuple[str, str]]:
"""
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 ("7... |
def _get_cell_parts(cls, cell_text: str) -> List[Tuple[str, str]]:
"""
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 correspond... |
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_cells) |
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_text or '\n' in cell_text or '/' in cell_text:
return True
return False |
def get_linked_agenda_items(self) -> List[str]:
"""
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 learni... |
def main(inp_fn: str,
domain: str,
out_fn: str) -> None:
"""
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 ... |
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])],
' '.join(map(str, span))) |
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.span[0], ex.sent) \
: char_to_word_index(ex.rel.span[1], ex.sent) + 1]
if ... |
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_and_args = [("ARG{}".format(arg_ind), arg)
... |
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*)+$",
text_spans)
spans = m.captures(1) + m.captures(2)
int_spans = []
... |
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) |
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())
for elem
in raw_element.split(';')... |
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 same sentence
assert(len(set([ex.sent for ex in sent_ls])) == 1)
toks = sent_ls[0].sent.... |
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_num, word_ind, word, pos, parse, lemma, '-',\
... |
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(map(str, pad_line_to_ontonotes(line, domain)))
for line in conver... |
def deaggregate_record(decoded_data):
'''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... |
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: dict
"""
if not isinstance(uri, string_types):
return None
url = urlparse(uri)
query = parse_qs(url.query)
if url.schem... |
def to_s3_uri(code_dict):
"""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 stri... |
def construct_s3_location_object(location_uri, logical_id, property_name):
"""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 st... |
def _get_policies(self, resource_properties):
"""
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
... |
def _contains_policies(self, resource_properties):
"""
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
"""
return resource_properties is not None \
... |
def _get_type(self, policy):
"""
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
"""
# Must handle intrinsic functions. Policy could be a primitive type or ... |
def _is_policy_template(self, policy):
"""
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 get_thing_shadow(self, **kwargs):
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 o... |
def update_thing_shadow(self, **kwargs):
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``) --
... |
def delete_thing_shadow(self, **kwargs):
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 DeleteThingSha... |
def publish(self, **kwargs):
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... |
def merge(self, resource_type, resource_properties):
"""
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... |
def _parse(self, globals_dict):
"""
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: Invalid... |
def _do_merge(self, global_value, local_value):
"""
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_v... |
def _merge_dict(self, global_dict, local_dict):
"""
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
"""
# Local has... |
def _token_of(self, input):
"""
Returns the token type of the input.
:param input: Input whose type is to be determined
:return TOKENS: Token type of the input
"""
if isinstance(input, dict):
# Intrinsic functions are always dicts
if is_intrinsi... |
def validate(template_dict, schema=None):
"""
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... |
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 pair of locations.
"""
car_types = ['economy', 'standard', 'midsize', 'full size', 'minivan', 'luxury']
base_location_cost ... |
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 pair of location and roomType.
"""
room_types = ['queen', 'king', 'deluxe']
cost_of_living = 0
for i in range(len(location)):
... |
def book_hotel(intent_request):
"""
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... |
def book_car(intent_request):
"""
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 use... |
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_request['currentIntent']['name']
# Dispatch to your bot... |
def to_cloudformation(self, **kwargs):
"""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 func... |
def _link_policy(self, role):
"""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
"""
policy_arn = self.get_polic... |
def add_default_parameter_values(self, sam_template):
"""
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
... |
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:
self.parameter_values['AWS::Region'] = boto3.session.Session().region_name |
def add(self, logical_id, deployment_preference_dict):
"""
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
... |
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 self._resource_preferences.items() if preference.enabled] |
def deployment_group(self, function_logical_id):
"""
:param function_logical_id: logical_id of the function this deployment group belongs to
:return: CodeDeployDeploymentGroup resource
"""
deployment_preference = self.get(function_logical_id)
deployment_group = CodeDeplo... |
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 Alexa Skills Kit sample. " \
"Please tell me your favorite color by sayin... |
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 'Color' in intent['slots']:
favorite_color = intent['slots']['Color']['va... |
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']
intent_name = intent_request['intent']['name']
# ... |
def lambda_handler(event, context):
""" Route the incoming request based on type (LaunchRequest, IntentRequest,
etc.) The JSON body of the request is provided in the event parameter.
"""
print("event.session.application.applicationId=" +
event['session']['application']['applicationId'])
"... |
def gen(self):
"""
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
... |
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 was present
:rtype string
"""
data_hash = ""
if not self.data_str:
return data_hash
encoded_da... |
def _stringify(self, data):
"""
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... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.