Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def take_step(self, state: StateType, max_actions: int = None, allowed_actions: List[Set] = None) -> List[StateType]: raise NotImplementedError
[ "\n The main method in the ``TransitionFunction`` API. This function defines the computation\n done at each step of decoding and returns a ranked list of next states.\n\n The input state is `grouped`, to allow for efficient computation, but the output states\n should all have a ``group_...
Please provide a description of the function:def _safe_sparse_mask(tensor: torch.Tensor, mask: torch.Tensor) -> torch.Tensor: # pylint: disable=protected-access try: return tensor.sparse_mask(mask) except AttributeError: # TODO(joelgrus): remove this and/or warn at some point re...
[ "\n In PyTorch 1.0, Tensor._sparse_mask was changed to Tensor.sparse_mask.\n This wrapper allows AllenNLP to (temporarily) work with both 1.0 and 0.4.1.\n " ]
Please provide a description of the function:def parse_sentence(sentence_blob: str) -> Tuple[List[Dict[str, str]], List[Tuple[int, int]], List[str]]: annotated_sentence = [] arc_indices = [] arc_tags = [] predicates = [] lines = [line.split("\t") for line in sentence_blob.split("\n") ...
[ "\n Parses a chunk of text in the SemEval SDP format.\n\n Each word in the sentence is returned as a dictionary with the following\n format:\n 'id': '1',\n 'form': 'Pierre',\n 'lemma': 'Pierre',\n 'pos': 'NNP',\n 'head': '2', # Note that this is the `syntactic` head.\n 'deprel': 'nn',\n...
Please provide a description of the function:def parse_cuda_device(cuda_device: Union[str, int, List[int]]) -> Union[int, List[int]]: def from_list(strings): if len(strings) > 1: return [int(d) for d in strings] elif len(strings) == 1: return int(strings[0]) else...
[ "\n Disambiguates single GPU and multiple GPU settings for cuda_device param.\n " ]
Please provide a description of the function:def fine_tune_model_from_args(args: argparse.Namespace): fine_tune_model_from_file_paths(model_archive_path=args.model_archive, config_file=args.config_file, serialization_dir=args.serialization...
[ "\n Just converts from an ``argparse.Namespace`` object to string paths.\n " ]
Please provide a description of the function:def fine_tune_model_from_file_paths(model_archive_path: str, config_file: str, serialization_dir: str, overrides: str = "", extend_...
[ "\n A wrapper around :func:`fine_tune_model` which loads the model archive from a file.\n\n Parameters\n ----------\n model_archive_path : ``str``\n Path to a saved model archive that is the result of running the ``train`` command.\n config_file : ``str``\n A configuration file specifyi...
Please provide a description of the function:def fine_tune_model(model: Model, params: Params, serialization_dir: str, extend_vocab: bool = False, file_friendly_logging: bool = False, batch_weight_key: str = "", ...
[ "\n Fine tunes the given model, using a set of parameters that is largely identical to those used\n for :func:`~allennlp.commands.train.train_model`, except that the ``model`` section is ignored,\n if it is present (as we are already given a ``Model`` here).\n\n The main difference between the logic don...
Please provide a description of the function: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, ...
[ "\n Extracts the top-k scoring items with respect to the scorer. We additionally return\n the indices of the top-k in their original order, not ordered by score, so that downstream\n components can rely on the original ordering (e.g., for knowing what spans are valid\n antecedents in a c...
Please provide a description of the function:def add_epoch_number(batch: Batch, epoch: int) -> Batch: for instance in batch.instances: instance.fields['epoch_num'] = MetadataField(epoch) return batch
[ "\n Add the epoch number to the batch instances as a MetadataField.\n " ]
Please provide a description of the function:def _take_instances(self, instances: Iterable[Instance], max_instances: Optional[int] = None) -> Iterator[Instance]: # If max_instances isn't specified, just iterate once over the whole dataset if max_i...
[ "\n Take the next `max_instances` instances from the given dataset.\n If `max_instances` is `None`, then just take all instances from the dataset.\n If `max_instances` is not `None`, each call resumes where the previous one\n left off, and when you get to the end of the dataset you start...
Please provide a description of the function:def _memory_sized_lists(self, instances: Iterable[Instance]) -> Iterable[List[Instance]]: lazy = is_lazy(instances) # Get an iterator over the next epoch worth of instances. iterator = self._take_instances(instanc...
[ "\n Breaks the dataset into \"memory-sized\" lists of instances,\n which it yields up one at a time until it gets through a full epoch.\n\n For example, if the dataset is already an in-memory list, and each epoch\n represents one pass through the dataset, it just yields back the dataset....
Please provide a description of the function:def _ensure_batch_is_sufficiently_small( self, batch_instances: Iterable[Instance], excess: Deque[Instance]) -> List[List[Instance]]: if self._maximum_samples_per_batch is None: assert not excess re...
[ "\n If self._maximum_samples_per_batch is specified, then split the batch\n into smaller sub-batches if it exceeds the maximum size.\n\n Parameters\n ----------\n batch_instances : ``Iterable[Instance]``\n A candidate batch.\n excess : ``Deque[Instance]``\n ...
Please provide a description of the function:def get_num_batches(self, instances: Iterable[Instance]) -> int: if is_lazy(instances) and self._instances_per_epoch is None: # Unable to compute num batches, so just return 1. return 1 elif self._instances_per_epoch is not No...
[ "\n Returns the number of batches that ``dataset`` will be split into; if you want to track\n progress through the batch with the generator produced by ``__call__``, this could be\n useful.\n " ]
Please provide a description of the function:def _create_batches(self, instances: Iterable[Instance], shuffle: bool) -> Iterable[Batch]: raise NotImplementedError
[ "\n This method should return one epoch worth of batches.\n " ]
Please provide a description of the function:def replace_cr_with_newline(message: str): if '\r' in message: message = message.replace('\r', '') if not message or message[-1] != '\n': message += '\n' return message
[ "\n TQDM and requests use carriage returns to get the training line to update for each batch\n without adding more lines to the terminal output. Displaying those in a file won't work\n correctly, so we'll just make sure that each batch shows up on its one line.\n :param message: the message to permute\...
Please provide a description of the function:def capture_model_internals(self) -> Iterator[dict]: results = {} hooks = [] # First we'll register hooks to add the outputs of each module to the results dict. def add_output(idx: int): def _add_output(mod, _, outputs): ...
[ "\n Context manager that captures the internal-module outputs of\n this predictor's model. The idea is that you could use it as follows:\n\n .. code-block:: python\n\n with predictor.capture_model_internals() as internals:\n outputs = predictor.predict_json(inputs)\n\n...
Please provide a description of the function:def _batch_json_to_instances(self, json_dicts: List[JsonDict]) -> List[Instance]: instances = [] for json_dict in json_dicts: instances.append(self._json_to_instance(json_dict)) return instances
[ "\n Converts a list of JSON objects into a list of :class:`~allennlp.data.instance.Instance`s.\n By default, this expects that a \"batch\" consists of a list of JSON blobs which would\n individually be predicted by :func:`predict_json`. In order to use this method for\n batch prediction,...
Please provide a description of the function:def from_path(cls, archive_path: str, predictor_name: str = None) -> 'Predictor': return Predictor.from_archive(load_archive(archive_path), predictor_name)
[ "\n Instantiate a :class:`Predictor` from an archive path.\n\n If you need more detailed configuration options, such as running the predictor on the GPU,\n please use `from_archive`.\n\n Parameters\n ----------\n archive_path The path to the archive.\n\n Returns\n ...
Please provide a description of the function:def from_archive(cls, archive: Archive, predictor_name: str = None) -> 'Predictor': # Duplicate the config so that the config inside the archive doesn't get consumed config = archive.config.duplicate() if not predictor_name: mode...
[ "\n Instantiate a :class:`Predictor` from an :class:`~allennlp.models.archival.Archive`;\n that is, from the result of training a model. Optionally specify which `Predictor`\n subclass; otherwise, the default one for the model will be used.\n " ]
Please provide a description of the function:def attention(query: torch.Tensor, key: torch.Tensor, value: torch.Tensor, mask: torch.Tensor = None, dropout: Callable = None) -> Tuple[torch.Tensor, torch.Tensor]: d_k = query.size(-1) scores = torch.matm...
[ "Compute 'Scaled Dot Product Attention'" ]
Please provide a description of the function:def subsequent_mask(size: int, device: str = 'cpu') -> torch.Tensor: mask = torch.tril(torch.ones(size, size, device=device, dtype=torch.int32)).unsqueeze(0) return mask
[ "Mask out subsequent positions." ]
Please provide a description of the function: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) -> Transfo...
[ "Helper: Construct a model from hyperparameters." ]
Please provide a description of the function:def forward(self, x, mask): 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[-1] = self.nor...
[ "Pass the input (and mask) through each layer in turn." ]
Please provide a description of the function:def forward(self, x: torch.Tensor, sublayer: Callable[[torch.Tensor], torch.Tensor]) -> torch.Tensor: return x + self.dropout(sublayer(self.norm(x)))
[ "Apply residual connection to any sublayer with the same size." ]
Please provide a description of the function:def forward(self, x: torch.Tensor, mask: torch.Tensor) -> torch.Tensor: x = self.sublayer[0](x, lambda x: self.self_attn(x, x, x, mask)) return self.sublayer[1](x, self.feed_forward)
[ "Follow Figure 1 (left) for connections." ]
Please provide a description of the function:def uniform_unit_scaling(tensor: torch.Tensor, nonlinearity: str = "linear"): size = 1. # Estimate the input size. This won't work perfectly, # but it covers almost all use cases where this initialiser # would be expected to be useful, i.e in large linea...
[ "\n An initaliser which preserves output variance for approximately gaussian\n distributed inputs. This boils down to initialising layers using a uniform\n distribution in the range ``(-sqrt(3/dim[0]) * scale, sqrt(3 / dim[0]) * scale)``, where\n ``dim[0]`` is equal to the input dimension of the paramet...
Please provide a description of the function:def block_orthogonal(tensor: torch.Tensor, split_sizes: List[int], gain: float = 1.0) -> None: data = tensor.data sizes = list(tensor.size()) if any([a % b != 0 for a, b in zip(sizes, split_sizes)]): raise Co...
[ "\n An initializer which allows initializing model parameters in \"blocks\". This is helpful\n in the case of recurrent models which use multiple gates applied to linear projections,\n which can be computed efficiently if they are concatenated together. However, they are\n separate parameters which shou...
Please provide a description of the function:def lstm_hidden_bias(tensor: torch.Tensor) -> None: # gates are (b_hi|b_hf|b_hg|b_ho) of shape (4*hidden_size) tensor.data.zero_() hidden_size = tensor.shape[0] // 4 tensor.data[hidden_size:(2 * hidden_size)] = 1.0
[ "\n Initialize the biases of the forget gate to 1, and all other gates to 0,\n following Jozefowicz et al., An Empirical Exploration of Recurrent Network Architectures\n " ]
Please provide a description of the function:def from_params(cls, params: List[Tuple[str, Params]] = None) -> "InitializerApplicator": # pylint: disable=arguments-differ params = params or [] is_prevent = lambda item: item == "prevent" or item == {"type": "prevent"} prevent_rege...
[ "\n Converts a Params object into an InitializerApplicator. The json should\n be formatted as follows::\n\n [\n [\"parameter_regex_match1\",\n {\n \"type\": \"normal\"\n \"mean\": 0.01\n \...
Please provide a description of the function:def read_from_file(cls, filename: str, question: List[Token]) -> 'TableQuestionKnowledgeGraph': return cls.read_from_lines(open(filename).readlines(), question)
[ "\n We read tables formatted as TSV files here. We assume the first line in the file is a tab\n separated list of column headers, and all subsequent lines are content rows. For example if\n the TSV file is:\n\n Nation Olympics Medals\n USA 1896 8\n Ch...
Please provide a description of the function:def read_from_json(cls, json_object: Dict[str, Any]) -> 'TableQuestionKnowledgeGraph': entity_text: Dict[str, str] = {} neighbors: DefaultDict[str, List[str]] = defaultdict(list) # Getting number entities first. Number entities don't have a...
[ "\n We read tables formatted as JSON objects (dicts) here. This is useful when you are reading\n data from a demo. The expected format is::\n\n {\"question\": [token1, token2, ...],\n \"columns\": [column1, column2, ...],\n \"cells\": [[row1_cell1, row1_cell2, ...],\...
Please provide a description of the function:def _get_numbers_from_tokens(tokens: List[Token]) -> List[Tuple[str, str]]: numbers = [] for i, token in enumerate(tokens): number: Union[int, float] = None token_text = token.text text = token.text.replace(',', ''...
[ "\n Finds numbers in the input tokens and returns them as strings. We do some simple heuristic\n number recognition, finding ordinals and cardinals expressed as text (\"one\", \"first\",\n etc.), as well as numerals (\"7th\", \"3rd\"), months (mapping \"july\" to 7), and units\n (\"1ghz...
Please provide a description of the function:def _get_cell_parts(cls, cell_text: str) -> List[Tuple[str, str]]: parts = [] for part_text in cls.cell_part_regex.split(cell_text): part_text = part_text.strip() part_entity = f'fb:part.{cls._normalize_string(part_text)}' ...
[ "\n Splits a cell into parts and returns the parts of the cell. We return a list of\n ``(entity_name, entity_text)``, where ``entity_name`` is ``fb:part.[something]``, and\n ``entity_text`` is the text of the cell corresponding to that part. For many cells, there\n is only one \"part\"...
Please provide a description of the function:def _should_split_column_cells(cls, column_cells: List[str]) -> bool: return any(cls._should_split_cell(cell_text) for cell_text in column_cells)
[ "\n Returns true if there is any cell in this column that can be split.\n " ]
Please provide a description of the function:def _should_split_cell(cls, cell_text: str) -> bool: if ', ' in cell_text or '\n' in cell_text or '/' in cell_text: return True return False
[ "\n Checks whether the cell should be split. We're just doing the same thing that SEMPRE did\n here.\n " ]
Please provide a description of the function:def get_linked_agenda_items(self) -> List[str]: agenda_items: List[str] = [] for entity in self._get_longest_span_matching_entities(): agenda_items.append(entity) # If the entity is a cell, we need to add the column to the age...
[ "\n Returns entities that can be linked to spans in the question, that should be in the agenda,\n for training a coverage based semantic parser. This method essentially does a heuristic\n entity linking, to provide weak supervision for a learning to search parser.\n " ]
Please provide a description of the function:def main(inp_fn: str, domain: str, out_fn: str) -> None: with open(out_fn, 'w') as fout: for sent_ls in read(inp_fn): fout.write("{}\n\n".format('\n'.join(['\t'.join(map(str, ...
[ "\n inp_fn: str, required.\n Path to file from which to read Open IE extractions in Open IE4's format.\n domain: str, required.\n Domain to be used when writing CoNLL format.\n out_fn: str, required.\n Path to file to which to write the CoNLL format Open IE extractions.\n " ]
Please provide a description of the function:def element_from_span(span: List[int], span_type: str) -> Element: return Element(span_type, [span[0].idx, span[-1].idx + len(span[-1])], ' '.join(map(str, span)))
[ "\n Return an Element from span (list of spacy toks)\n " ]
Please provide a description of the function:def split_predicate(ex: Extraction) -> Extraction: 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 not rel_toks: return ex verb_inds = [tok_ind for (tok_in...
[ "\n Ensure single word predicate\n by adding \"before-predicate\" and \"after-predicate\"\n arguments.\n " ]
Please provide a description of the function:def extraction_to_conll(ex: Extraction) -> List[str]: ex = split_predicate(ex) toks = ex.sent.split(' ') ret = ['*'] * len(toks) args = [ex.arg1] + ex.args2 rels_and_args = [("ARG{}".format(arg_ind), arg) for arg_ind, arg in enum...
[ "\n Return a conll representation of a given input Extraction.\n " ]
Please provide a description of the function:def interpret_span(text_spans: str) -> List[int]: m = regex.match("^(?:(?:([\(\[]\d+, \d+[\)\]])|({\d+}))[,]?\s*)+$", text_spans) spans = m.captures(1) + m.captures(2) int_spans = [] for span in spans: ints = list(map(int, ...
[ "\n Return an integer tuple from\n textual representation of closed / open spans.\n " ]
Please provide a description of the function:def interpret_element(element_type: str, text: str, span: str) -> Element: return Element(element_type, interpret_span(span), text)
[ "\n Construct an Element instance from regexp\n groups.\n " ]
Please provide a description of the function:def parse_element(raw_element: str) -> List[Element]: elements = [regex.match("^(([a-zA-Z]+)\(([^;]+),List\(([^;]*)\)\))$", elem.lstrip().rstrip()) for elem in raw_element.split(';')] return [interpret_...
[ "\n Parse a raw element into text and indices (integers).\n " ]
Please provide a description of the function:def convert_sent_to_conll(sent_ls: List[Extraction]): # 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.split(' ') return safe_zip(*[range(len(toks)), ...
[ "\n Given a list of extractions for a single sentence -\n convert it to conll representation.\n " ]
Please provide a description of the function:def pad_line_to_ontonotes(line, domain) -> List[str]: 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, '-',\ '-', '-', '...
[ "\n Pad line to conform to ontonotes representation.\n " ]
Please provide a description of the function:def convert_sent_dict_to_conll(sent_dic, domain) -> str: return '\n\n'.join(['\n'.join(['\t'.join(map(str, pad_line_to_ontonotes(line, domain))) for line in convert_sent_to_conll(sent_ls)]) for sent_ls ...
[ "\n Given a dictionary from sentence -> extractions,\n return a corresponding CoNLL representation.\n " ]
Please provide a description of the function: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 ret...
[]
Please provide a description of the function:def parse_s3_uri(uri): if not isinstance(uri, string_types): return None url = urlparse(uri) query = parse_qs(url.query) if url.scheme == 's3' and url.netloc and url.path: s3_pointer = { 'Bucket': url.netloc, 'Ke...
[ "Parses a S3 Uri into a dictionary of the Bucket, Key, and VersionId\n\n :return: a BodyS3Location dict or None if not an S3 Uri\n :rtype: dict\n " ]
Please provide a description of the function:def to_s3_uri(code_dict): try: uri = "s3://{bucket}/{key}".format(bucket=code_dict["S3Bucket"], key=code_dict["S3Key"]) version = code_dict.get("S3ObjectVersion", None) except (TypeError, AttributeError): raise TypeError("Code location s...
[ "Constructs a S3 URI string from given code dictionary\n\n :param dict code_dict: Dictionary containing Lambda function Code S3 location of the form\n {S3Bucket, S3Key, S3ObjectVersion}\n :return: S3 URI of form s3://bucket/key?versionId=version\n :rtype string\n " ]
Please provide a description of the function:def construct_s3_location_object(location_uri, logical_id, property_name): if isinstance(location_uri, dict): if not location_uri.get("Bucket") or not location_uri.get("Key"): # location_uri is a dictionary but does not contain Bucket or Key prop...
[ "Constructs a Lambda `Code` or `Content` property, from the SAM `CodeUri` or `ContentUri` property.\n This follows the current scheme for Lambda Functions and LayerVersions.\n\n :param dict or string location_uri: s3 location dict or string\n :param string logical_id: logical_id of the resource calling thi...
Please provide a description of the function:def _get_policies(self, resource_properties): policies = None if self._contains_policies(resource_properties): policies = resource_properties[self.POLICIES_PROPERTY_NAME] if not policies: # Policies is None or empty...
[ "\n Returns a list of policies from the resource properties. This method knows how to interpret and handle\n polymorphic nature of the policies property.\n\n Policies can be one of the following:\n\n * Managed policy name: string\n * List of managed policy names: list of s...
Please provide a description of the function:def _contains_policies(self, resource_properties): return resource_properties is not None \ and isinstance(resource_properties, dict) \ and self.POLICIES_PROPERTY_NAME in resource_properties
[ "\n Is there policies data in this resource?\n\n :param dict resource_properties: Properties of the resource\n :return: True if we can process this resource. False, otherwise\n " ]
Please provide a description of the function:def _get_type(self, policy): # Must handle intrinsic functions. Policy could be a primitive type or an intrinsic function # Managed policies are either string or an intrinsic function that resolves to a string if isinstance(policy, string_t...
[ "\n Returns the type of the given policy\n\n :param string or dict policy: Policy data\n :return PolicyTypes: Type of the given policy. None, if type could not be inferred\n " ]
Please provide a description of the function:def _is_policy_template(self, policy): return self._policy_template_processor is not None and \ isinstance(policy, dict) and \ len(policy) == 1 and \ self._policy_template_processor.has(list(policy.keys())[0]) is True
[ "\n Is the given policy data a policy template? Policy templates is a dictionary with one key which is the name\n of the template.\n\n :param dict policy: Policy data\n :return: True, if this is a policy template. False if it is not\n " ]
Please provide a description of the function:def get_thing_shadow(self, **kwargs): r thing_name = self._get_required_parameter('thingName', **kwargs) payload = b'' return self._shadow_op('get', thing_name, payload)
[ "\n Call shadow lambda to obtain current shadow state.\n\n :Keyword Arguments:\n * *thingName* (``string``) --\n [REQUIRED]\n The name of the thing.\n\n :returns: (``dict``) --\n The output from the GetThingShadow operation\n * *payload* (`...
Please provide a description of the function:def update_thing_shadow(self, **kwargs): r thing_name = self._get_required_parameter('thingName', **kwargs) payload = self._get_required_parameter('payload', **kwargs) return self._shadow_op('update', thing_name, payload)
[ "\n Updates the thing shadow for the specified thing.\n\n :Keyword Arguments:\n * *thingName* (``string``) --\n [REQUIRED]\n The name of the thing.\n * *payload* (``bytes or seekable file-like object``) --\n [REQUIRED]\n The sta...
Please provide a description of the function:def delete_thing_shadow(self, **kwargs): r thing_name = self._get_required_parameter('thingName', **kwargs) payload = b'' return self._shadow_op('delete', thing_name, payload)
[ "\n Deletes the thing shadow for the specified thing.\n\n :Keyword Arguments:\n * *thingName* (``string``) --\n [REQUIRED]\n The name of the thing.\n\n :returns: (``dict``) --\n The output from the DeleteThingShadow operation\n * *payload* ...
Please provide a description of the function:def publish(self, **kwargs): r topic = self._get_required_parameter('topic', **kwargs) # payload is an optional parameter payload = kwargs.get('payload', b'') function_arn = ROUTER_FUNCTION_ARN client_context = { ...
[ "\n Publishes state information.\n\n :Keyword Arguments:\n * *topic* (``string``) --\n [REQUIRED]\n The name of the MQTT topic.\n * *payload* (``bytes or seekable file-like object``) --\n The state information, in JSON format.\n\n :re...
Please provide a description of the function:def merge(self, resource_type, resource_properties): if resource_type not in self.template_globals: # Nothing to do. Return the template unmodified return resource_properties global_props = self.template_globals[resource_typ...
[ "\n Adds global properties to the resource, if necessary. This method is a no-op if there are no global properties\n for this resource type\n\n :param string resource_type: Type of the resource (Ex: AWS::Serverless::Function)\n :param dict resource_properties: Properties of the resource ...
Please provide a description of the function:def _parse(self, globals_dict): globals = {} if not isinstance(globals_dict, dict): raise InvalidGlobalsSectionException(self._KEYWORD, "It must be a non-empty dictionary".format(self._KE...
[ "\n Takes a SAM template as input and parses the Globals section\n\n :param globals_dict: Dictionary representation of the Globals section\n :return: Processed globals dictionary which can be used to quickly identify properties to merge\n :raises: InvalidResourceException if the input co...
Please provide a description of the function:def _do_merge(self, global_value, local_value): token_global = self._token_of(global_value) token_local = self._token_of(local_value) # The following statements codify the rules explained in the doctring above if token_global != tok...
[ "\n Actually perform the merge operation for the given inputs. This method is used as part of the recursion.\n Therefore input values can be of any type. So is the output.\n\n :param global_value: Global value to be merged\n :param local_value: Local value to be merged\n :return: ...
Please provide a description of the function:def _merge_dict(self, global_dict, local_dict): # Local has higher priority than global. So iterate over local dict and merge into global if keys are overridden global_dict = global_dict.copy() for key in local_dict.keys(): if ...
[ "\n Merges the two dictionaries together\n\n :param global_dict: Global dictionary to be merged\n :param local_dict: Local dictionary to be merged\n :return: New merged dictionary with values shallow copied\n " ]
Please provide a description of the function:def _token_of(self, input): if isinstance(input, dict): # Intrinsic functions are always dicts if is_intrinsics(input): # Intrinsic functions are handled *exactly* like a primitive type because # they...
[ "\n Returns the token type of the input.\n\n :param input: Input whose type is to be determined\n :return TOKENS: Token type of the input\n " ]
Please provide a description of the function:def validate(template_dict, schema=None): if not schema: schema = SamTemplateValidator._read_schema() validation_errors = "" try: jsonschema.validate(template_dict, schema) except ValidationError as ex: ...
[ "\n Is this a valid SAM template dictionary\n\n :param dict template_dict: Data to be validated\n :param dict schema: Optional, dictionary containing JSON Schema representing SAM template\n :return: Empty string if there are no validation errors in template\n " ]
Please provide a description of the function:def generate_car_price(location, days, age, car_type): car_types = ['economy', 'standard', 'midsize', 'full size', 'minivan', 'luxury'] base_location_cost = 0 for i in range(len(location)): base_location_cost += ord(location.lower()[i]) - 97 ag...
[ "\n Generates a number within a reasonable range that might be expected for a flight.\n The price is fixed for a given pair of locations.\n " ]
Please provide a description of the function:def generate_hotel_price(location, nights, room_type): room_types = ['queen', 'king', 'deluxe'] cost_of_living = 0 for i in range(len(location)): cost_of_living += ord(location.lower()[i]) - 97 return nights * (100 + cost_of_living + (100 + roo...
[ "\n Generates a number within a reasonable range that might be expected for a hotel.\n The price is fixed for a pair of location and roomType.\n " ]
Please provide a description of the function:def book_hotel(intent_request): location = try_ex(lambda: intent_request['currentIntent']['slots']['Location']) checkin_date = try_ex(lambda: intent_request['currentIntent']['slots']['CheckInDate']) nights = safe_int(try_ex(lambda: intent_request['currentIn...
[ "\n Performs dialog management and fulfillment for booking a hotel.\n\n Beyond fulfillment, the implementation for this intent demonstrates the following:\n 1) Use of elicitSlot in slot validation and re-prompting\n 2) Use of sessionAttributes to pass information that can be used to guide conversation\n...
Please provide a description of the function:def book_car(intent_request): slots = intent_request['currentIntent']['slots'] pickup_city = slots['PickUpCity'] pickup_date = slots['PickUpDate'] return_date = slots['ReturnDate'] driver_age = slots['DriverAge'] car_type = slots['CarType'] c...
[ "\n Performs dialog management and fulfillment for booking a car.\n\n Beyond fulfillment, the implementation for this intent demonstrates the following:\n 1) Use of elicitSlot in slot validation and re-prompting\n 2) Use of sessionAttributes to pass information that can be used to guide conversation\n ...
Please provide a description of the function:def dispatch(intent_request): logger.debug('dispatch userId={}, intentName={}'.format(intent_request['userId'], intent_request['currentIntent']['name'])) intent_name = intent_request['currentIntent']['name'] # Dispatch to your bot's intent handlers if...
[ "\n Called when the user specifies an intent for this bot.\n " ]
Please provide a description of the function:def to_cloudformation(self, **kwargs): function = kwargs.get('function') if not function: raise TypeError("Missing required keyword argument: function") resources = [] lambda_eventsourcemapping = LambdaEventSourceMappin...
[ "Returns the Lambda EventSourceMapping to which this pull event corresponds. Adds the appropriate managed\n policy to the function's execution role, if such a role is provided.\n\n :param dict kwargs: a dict containing the execution role generated for the function\n :returns: a list of vanilla ...
Please provide a description of the function:def _link_policy(self, role): policy_arn = self.get_policy_arn() if role is not None and policy_arn not in role.ManagedPolicyArns: role.ManagedPolicyArns.append(policy_arn)
[ "If this source triggers a Lambda function whose execution role is auto-generated by SAM, add the\n appropriate managed policy to this Role.\n\n :param model.iam.IAMROle role: the execution role generated for the function\n " ]
Please provide a description of the function:def add_default_parameter_values(self, sam_template): parameter_definition = sam_template.get("Parameters", None) if not parameter_definition or not isinstance(parameter_definition, dict): return self.parameter_values for param_...
[ "\n Method to read default values for template parameters and merge with user supplied values.\n\n Example:\n If the template contains the following parameters defined\n\n Parameters:\n Param1:\n Type: String\n Default: default_value\n ...
Please provide a description of the function:def add_pseudo_parameter_values(self): if 'AWS::Region' not in self.parameter_values: self.parameter_values['AWS::Region'] = boto3.session.Session().region_name
[ "\n Add pseudo parameter values\n :return: parameter values that have pseudo parameter in it\n " ]
Please provide a description of the function:def add(self, logical_id, deployment_preference_dict): if logical_id in self._resource_preferences: raise ValueError("logical_id {logical_id} previously added to this deployment_preference_collection".format( logical_id=logical_id...
[ "\n Add this deployment preference to the collection\n\n :raise ValueError if an existing logical id already exists in the _resource_preferences\n :param logical_id: logical id of the resource where this deployment preference applies\n :param deployment_preference_dict: the input SAM tem...
Please provide a description of the function:def enabled_logical_ids(self): return [logical_id for logical_id, preference in self._resource_preferences.items() if preference.enabled]
[ "\n :return: only the logical id's for the deployment preferences in this collection which are enabled\n " ]
Please provide a description of the function:def deployment_group(self, function_logical_id): deployment_preference = self.get(function_logical_id) deployment_group = CodeDeployDeploymentGroup(self.deployment_group_logical_id(function_logical_id)) if deployment_preference.alarms is no...
[ "\n :param function_logical_id: logical_id of the function this deployment group belongs to\n :return: CodeDeployDeploymentGroup resource\n " ]
Please provide a description of the function:def get_welcome_response(): session_attributes = {} card_title = "Welcome" speech_output = "Welcome to the Alexa Skills Kit sample. " \ "Please tell me your favorite color by saying, " \ "my favorite color is red" ...
[ " If we wanted to initialize the session to have some attributes we could\n add those here\n " ]
Please provide a description of the function:def set_color_in_session(intent, session): card_title = intent['name'] session_attributes = {} should_end_session = False if 'Color' in intent['slots']: favorite_color = intent['slots']['Color']['value'] session_attributes = create_favo...
[ " Sets the color in the session and prepares the speech to reply to the\n user.\n " ]
Please provide a description of the function:def on_intent(intent_request, session): print("on_intent requestId=" + intent_request['requestId'] + ", sessionId=" + session['sessionId']) intent = intent_request['intent'] intent_name = intent_request['intent']['name'] # Dispatch to your s...
[ " Called when the user specifies an intent for this skill " ]
Please provide a description of the function:def lambda_handler(event, context): print("event.session.application.applicationId=" + event['session']['application']['applicationId']) # if (event['session']['application']['applicationId'] != # "amzn1.echo-sdk-ams.app.[unique-value...
[ " Route the incoming request based on type (LaunchRequest, IntentRequest,\n etc.) The JSON body of the request is provided in the event parameter.\n ", "\n Uncomment this if statement and populate with your skill's application ID to\n prevent someone else from configuring a skill that sends requests t...
Please provide a description of the function:def gen(self): data_hash = self.get_hash() return "{prefix}{hash}".format(prefix=self._prefix, hash=data_hash)
[ "\n Generate stable LogicalIds based on the prefix and given data. This method ensures that the logicalId is\n deterministic and stable based on input prefix & data object. In other words:\n\n logicalId changes *if and only if* either the `prefix` or `data_obj` changes\n\n Internally...
Please provide a description of the function:def get_hash(self, length=HASH_LENGTH): data_hash = "" if not self.data_str: return data_hash encoded_data_str = self.data_str if sys.version_info.major == 2: # In Py2, only unicode needs to be encoded. ...
[ "\n Generate and return a hash of data that can be used as suffix of logicalId\n\n :return: Hash of data if it was present\n :rtype string\n " ]
Please provide a description of the function:def _stringify(self, data): if isinstance(data, string_types): return data # Get the most compact dictionary (separators) and sort the keys recursively to get a stable output return json.dumps(data, separators=(',', ':'), sort_ke...
[ "\n Stable, platform & language-independent stringification of a data with basic Python type.\n\n We use JSON to dump a string instead of `str()` method in order to be language independent.\n\n :param data: Data to be stringified. If this is one of JSON native types like string, dict, array etc...
Please provide a description of the function:def add(self, logical_id, property, value): if not logical_id or not property: raise ValueError("LogicalId and property must be a non-empty string") if not value or not isinstance(value, string_types): raise ValueError("Prop...
[ "\n Add the information that resource with given `logical_id` supports the given `property`, and that a reference\n to `logical_id.property` resolves to given `value.\n\n Example:\n\n \"MyApi.Deployment\" -> \"MyApiDeployment1234567890\"\n\n :param logical_id: Logical ID of th...
Please provide a description of the function:def get(self, logical_id, property): # By defaulting to empty dictionary, we can handle the case where logical_id is not in map without if statements prop_values = self.get_all(logical_id) if prop_values: return prop_values.get(p...
[ "\n Returns the value of the reference for given logical_id at given property. Ex: MyFunction.Alias\n\n :param logical_id: Logical Id of the resource\n :param property: Property of the resource you want to resolve. None if you want to get value of all properties\n :return: Value of this ...
Please provide a description of the function:def encrypt(key, message): '''encrypt leverages KMS encrypt and base64-encode encrypted blob More info on KMS encrypt API: https://docs.aws.amazon.com/kms/latest/APIReference/API_encrypt.html ''' try: ret = kms.encrypt(KeyId=key, Plaintex...
[]
Please provide a description of the function:def get_tag_list(resource_tag_dict): tag_list = [] if resource_tag_dict is None: return tag_list for tag_key, tag_value in resource_tag_dict.items(): tag = {_KEY: tag_key, _VALUE: tag_value if tag_value else ""} tag_list.append(tag)...
[ "\n Transforms the SAM defined Tags into the form CloudFormation is expecting.\n\n SAM Example:\n ```\n ...\n Tags:\n TagKey: TagValue\n ```\n\n\n CloudFormation equivalent:\n - Key: TagKey\n Value: TagValue\n ```\n\n :param resource_tag_di...
Please provide a description of the function:def get_partition_name(cls, region=None): if region is None: # Use Boto3 to get the region where code is running. This uses Boto's regular region resolution # mechanism, starting from AWS_DEFAULT_REGION environment variable. ...
[ "\n Gets the name of the partition given the region name. If region name is not provided, this method will\n use Boto3 to get name of the region where this code is running.\n\n This implementation is borrowed from AWS CLI\n https://github.com/aws/aws-cli/blob/1.11.139/awscli/customizatio...
Please provide a description of the function:def on_before_transform_template(self, template_dict): template = SamTemplate(template_dict) for logicalId, api in template.iterate(SamResourceType.Api.value): if api.properties.get('DefinitionBody') or api.properties.get('DefinitionUri'...
[ "\n Hook method that gets called before the SAM template is processed.\n The template has passed the validation and is guaranteed to contain a non-empty \"Resources\" section.\n\n :param dict template_dict: Dictionary of the SAM template\n :return: Nothing\n " ]
Please provide a description of the function:def has_path(self, path, method=None): method = self._normalize_method_name(method) path_dict = self.get_path(path) path_dict_exists = path_dict is not None if method: return path_dict_exists and method in path_dict ...
[ "\n Returns True if this Swagger has the given path and optional method\n\n :param string path: Path name\n :param string method: HTTP method\n :return: True, if this path/method is present in the document\n " ]
Please provide a description of the function:def method_has_integration(self, method): for method_definition in self.get_method_contents(method): if self.method_definition_has_integration(method_definition): return True return False
[ "\n Returns true if the given method contains a valid method definition.\n This uses the get_method_contents function to handle conditionals.\n\n :param dict method: method dictionary\n :return: true if method has one or multiple integrations\n " ]
Please provide a description of the function:def get_method_contents(self, method): if self._CONDITIONAL_IF in method: return method[self._CONDITIONAL_IF][1:] return [method]
[ "\n Returns the swagger contents of the given method. This checks to see if a conditional block\n has been used inside of the method, and, if so, returns the method contents that are\n inside of the conditional.\n\n :param dict method: method dictionary\n :return: list of swagger ...
Please provide a description of the function:def has_integration(self, path, method): method = self._normalize_method_name(method) path_dict = self.get_path(path) return self.has_path(path, method) and \ isinstance(path_dict[method], dict) and \ self.method_has_...
[ "\n Checks if an API Gateway integration is already present at the given path/method\n\n :param string path: Path name\n :param string method: HTTP method\n :return: True, if an API Gateway integration is already present\n " ]
Please provide a description of the function:def add_path(self, path, method=None): method = self._normalize_method_name(method) path_dict = self.paths.setdefault(path, {}) if not isinstance(path_dict, dict): # Either customers has provided us an invalid Swagger, or this c...
[ "\n Adds the path/method combination to the Swagger, if not already present\n\n :param string path: Path name\n :param string method: HTTP method\n :raises ValueError: If the value of `path` in Swagger is not a dictionary\n " ]
Please provide a description of the function:def add_lambda_integration(self, path, method, integration_uri, method_auth_config=None, api_auth_config=None, condition=None): method = self._normalize_method_name(method) if self.has_integration(path, method): ...
[ "\n Adds aws_proxy APIGW integration to the given path+method.\n\n :param string path: Path name\n :param string method: HTTP Method\n :param string integration_uri: URI for the integration.\n " ]
Please provide a description of the function:def make_path_conditional(self, path, condition): self.paths[path] = make_conditional(condition, self.paths[path])
[ "\n Wrap entire API path definition in a CloudFormation if condition.\n " ]
Please provide a description of the function:def add_cors(self, path, allowed_origins, allowed_headers=None, allowed_methods=None, max_age=None, allow_credentials=None): # Skip if Options is already present if self.has_path(path, self._OPTIONS_METHOD): return ...
[ "\n Add CORS configuration to this path. Specifically, we will add a OPTIONS response config to the Swagger that\n will return headers required for CORS. Since SAM uses aws_proxy integration, we cannot inject the headers\n into the actual response returned from Lambda function. This is somethin...
Please provide a description of the function:def _options_method_response_for_cors(self, allowed_origins, allowed_headers=None, allowed_methods=None, max_age=None, allow_credentials=None): ALLOW_ORIGIN = "Access-Control-Allow-Origin" ALLOW_HEADERS = "A...
[ "\n Returns a Swagger snippet containing configuration for OPTIONS HTTP Method to configure CORS.\n\n This snippet is taken from public documentation:\n https://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-cors.html#enable-cors-for-resource-using-swagger-importer-tool\n\n ...
Please provide a description of the function:def _make_cors_allowed_methods_for_path(self, path): # https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html all_http_methods = ["OPTIONS", "GET", "HEAD", "POST", "PUT", "DELETE", "PATCH"] if not self.has_path(path): return "" ...
[ "\n Creates the value for Access-Control-Allow-Methods header for given path. All HTTP methods defined for this\n path will be included in the result. If the path contains \"ANY\" method, then *all available* HTTP methods will\n be returned as result.\n\n :param string path: Path to gene...
Please provide a description of the function:def add_authorizers(self, authorizers): self.security_definitions = self.security_definitions or {} for authorizer_name, authorizer in authorizers.items(): self.security_definitions[authorizer_name] = authorizer.generate_swagger()
[ "\n Add Authorizer definitions to the securityDefinitions part of Swagger.\n\n :param list authorizers: List of Authorizer configurations which get translated to securityDefinitions.\n " ]