repo
stringlengths
7
55
path
stringlengths
4
223
func_name
stringlengths
1
134
original_string
stringlengths
75
104k
language
stringclasses
1 value
code
stringlengths
75
104k
code_tokens
listlengths
19
28.4k
docstring
stringlengths
1
46.9k
docstring_tokens
listlengths
1
1.97k
sha
stringlengths
40
40
url
stringlengths
87
315
partition
stringclasses
1 value
allenai/allennlp
allennlp/state_machines/states/grammar_based_state.py
GrammarBasedState.get_valid_actions
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]
python
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", "get_valid_actions", "(", "self", ")", "->", "List", "[", "Dict", "[", "str", ",", "Tuple", "[", "torch", ".", "Tensor", ",", "torch", ".", "Tensor", ",", "List", "[", "int", "]", "]", "]", "]", ":", "return", "[", "state", ".", "get_valid_a...
Returns a list of valid actions for each element of the group.
[ "Returns", "a", "list", "of", "valid", "actions", "for", "each", "element", "of", "the", "group", "." ]
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/state_machines/states/grammar_based_state.py#L110-L114
train
allenai/allennlp
allennlp/data/dataset_readers/multiprocess_dataset_reader.py
_worker
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...
python
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", "_worker", "(", "reader", ":", "DatasetReader", ",", "input_queue", ":", "Queue", ",", "output_queue", ":", "Queue", ",", "index", ":", "int", ")", "->", "None", ":", "# Keep going until you get a file_path that's None.", "while", "True", ":", "file_path", ...
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.
[ "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", "fil...
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/dataset_readers/multiprocess_dataset_reader.py#L30-L50
train
allenai/allennlp
allennlp/modules/conditional_random_field.py
allowed_transitions
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 ...
python
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", "allowed_transitions", "(", "constraint_type", ":", "str", ",", "labels", ":", "Dict", "[", "int", ",", "str", "]", ")", "->", "List", "[", "Tuple", "[", "int", ",", "int", "]", "]", ":", "num_labels", "=", "len", "(", "labels", ")", "start_ta...
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", "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", "ra...
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/modules/conditional_random_field.py#L12-L55
train
allenai/allennlp
allennlp/modules/conditional_random_field.py
is_transition_allowed
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...
python
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", "is_transition_allowed", "(", "constraint_type", ":", "str", ",", "from_tag", ":", "str", ",", "from_entity", ":", "str", ",", "to_tag", ":", "str", ",", "to_entity", ":", "str", ")", ":", "# pylint: disable=too-many-return-statements", "if", "to_tag", "=...
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...
[ "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", "constra...
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/modules/conditional_random_field.py#L58-L149
train
allenai/allennlp
allennlp/modules/conditional_random_field.py
ConditionalRandomField._input_likelihood
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...
python
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", "_input_likelihood", "(", "self", ",", "logits", ":", "torch", ".", "Tensor", ",", "mask", ":", "torch", ".", "Tensor", ")", "->", "torch", ".", "Tensor", ":", "batch_size", ",", "sequence_length", ",", "num_tags", "=", "logits", ".", "size", "(",...
Computes the (batch_size,) denominator term for the log-likelihood, which is the sum of the likelihoods across all possible state sequences.
[ "Computes", "the", "(", "batch_size", ")", "denominator", "term", "for", "the", "log", "-", "likelihood", "which", "is", "the", "sum", "of", "the", "likelihoods", "across", "all", "possible", "state", "sequences", "." ]
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/modules/conditional_random_field.py#L207-L251
train
allenai/allennlp
allennlp/modules/conditional_random_field.py
ConditionalRandomField._joint_likelihood
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...
python
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", "_joint_likelihood", "(", "self", ",", "logits", ":", "torch", ".", "Tensor", ",", "tags", ":", "torch", ".", "Tensor", ",", "mask", ":", "torch", ".", "LongTensor", ")", "->", "torch", ".", "Tensor", ":", "batch_size", ",", "sequence_length", ","...
Computes the numerator term for the log-likelihood, which is just score(inputs, tags)
[ "Computes", "the", "numerator", "term", "for", "the", "log", "-", "likelihood", "which", "is", "just", "score", "(", "inputs", "tags", ")" ]
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/modules/conditional_random_field.py#L253-L306
train
allenai/allennlp
allennlp/modules/conditional_random_field.py
ConditionalRandomField.forward
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...
python
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", "forward", "(", "self", ",", "inputs", ":", "torch", ".", "Tensor", ",", "tags", ":", "torch", ".", "Tensor", ",", "mask", ":", "torch", ".", "ByteTensor", "=", "None", ")", "->", "torch", ".", "Tensor", ":", "# pylint: disable=arguments-differ", ...
Computes the log likelihood.
[ "Computes", "the", "log", "likelihood", "." ]
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/modules/conditional_random_field.py#L308-L322
train
allenai/allennlp
allennlp/modules/conditional_random_field.py
ConditionalRandomField.viterbi_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. """ ...
python
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", "viterbi_tags", "(", "self", ",", "logits", ":", "torch", ".", "Tensor", ",", "mask", ":", "torch", ".", "Tensor", ")", "->", "List", "[", "Tuple", "[", "List", "[", "int", "]", ",", "float", "]", "]", ":", "_", ",", "max_seq_length", ",", ...
Uses viterbi algorithm to find most likely tags for the given inputs. If constraints are applied, disallows all other transitions.
[ "Uses", "viterbi", "algorithm", "to", "find", "most", "likely", "tags", "for", "the", "given", "inputs", ".", "If", "constraints", "are", "applied", "disallows", "all", "other", "transitions", "." ]
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/modules/conditional_random_field.py#L324-L384
train
allenai/allennlp
allennlp/nn/beam_search.py
BeamSearch.search
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. ...
python
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", "search", "(", "self", ",", "start_predictions", ":", "torch", ".", "Tensor", ",", "start_state", ":", "StateType", ",", "step", ":", "StepFunctionType", ")", "->", "Tuple", "[", "torch", ".", "Tensor", ",", "torch", ".", "Tensor", "]", ":", "batc...
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...
[ "Given", "a", "starting", "state", "and", "a", "step", "function", "apply", "beam", "search", "to", "find", "the", "most", "likely", "target", "sequences", "." ]
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/nn/beam_search.py#L44-L276
train
allenai/allennlp
scripts/examine_sql_coverage.py
main
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...
python
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", "main", "(", "data_directory", ":", "int", ",", "dataset", ":", "str", "=", "None", ",", "filter_by", ":", "str", "=", "None", ",", "verbose", ":", "bool", "=", "False", ")", "->", "None", ":", "directory_dict", "=", "{", "path", ":", "files",...
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...
[ "Parameters", "----------", "data_directory", ":", "str", "required", ".", "The", "path", "to", "the", "data", "directory", "of", "https", ":", "//", "github", ".", "com", "/", "jkkummerfeld", "/", "text2sql", "-", "data", "which", "has", "been", "preprocess...
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/scripts/examine_sql_coverage.py#L91-L132
train
allenai/allennlp
allennlp/common/from_params.py
takes_arg
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): ...
python
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_arg", "(", "obj", ",", "arg", ":", "str", ")", "->", "bool", ":", "if", "inspect", ".", "isclass", "(", "obj", ")", ":", "signature", "=", "inspect", ".", "signature", "(", "obj", ".", "__init__", ")", "elif", "inspect", ".", "ismethod"...
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.
[ "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", "...
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/from_params.py#L59-L72
train
allenai/allennlp
allennlp/common/from_params.py
takes_kwargs
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...
python
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", "takes_kwargs", "(", "obj", ")", "->", "bool", ":", "if", "inspect", ".", "isclass", "(", "obj", ")", ":", "signature", "=", "inspect", ".", "signature", "(", "obj", ".", "__init__", ")", "elif", "inspect", ".", "ismethod", "(", "obj", ")", "o...
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
[ "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", ...
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/from_params.py#L75-L89
train
allenai/allennlp
allennlp/common/from_params.py
remove_optional
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__', (...
python
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", "remove_optional", "(", "annotation", ":", "type", ")", ":", "origin", "=", "getattr", "(", "annotation", ",", "'__origin__'", ",", "None", ")", "args", "=", "getattr", "(", "annotation", ",", "'__args__'", ",", "(", ")", ")", "if", "origin", "=="...
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.
[ "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", "." ]
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/from_params.py#L92-L103
train
allenai/allennlp
allennlp/common/from_params.py
create_kwargs
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...
python
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_kwargs", "(", "cls", ":", "Type", "[", "T", "]", ",", "params", ":", "Params", ",", "*", "*", "extras", ")", "->", "Dict", "[", "str", ",", "Any", "]", ":", "# Get the signature of the constructor.", "signature", "=", "inspect", ".", "sign...
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", "some", "class", "a", "Params", "object", "and", "potentially", "other", "keyword", "arguments", "create", "a", "dict", "of", "keyword", "args", "suitable", "for", "passing", "to", "the", "class", "s", "constructor", "." ]
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/from_params.py#L105-L136
train
allenai/allennlp
allennlp/common/from_params.py
create_extras
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...
python
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", "create_extras", "(", "cls", ":", "Type", "[", "T", "]", ",", "extras", ":", "Dict", "[", "str", ",", "Any", "]", ")", "->", "Dict", "[", "str", ",", "Any", "]", ":", "subextras", ":", "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.
[ "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", "." ]
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/from_params.py#L139-L166
train
allenai/allennlp
allennlp/common/from_params.py
construct_arg
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...
python
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", "construct_arg", "(", "cls", ":", "Type", "[", "T", "]", ",", "# pylint: disable=inconsistent-return-statements,too-many-return-statements", "param_name", ":", "str", ",", "annotation", ":", "Type", ",", "default", ":", "Any", ",", "params", ":", "Params", ...
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...
[ "Does", "the", "work", "of", "actually", "constructing", "an", "individual", "argument", "for", ":", "func", ":", "create_kwargs", "." ]
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/from_params.py#L169-L318
train
allenai/allennlp
allennlp/common/from_params.py
FromParams.from_params
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...
python
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", "from_params", "(", "cls", ":", "Type", "[", "T", "]", ",", "params", ":", "Params", ",", "*", "*", "extras", ")", "->", "T", ":", "# pylint: disable=protected-access", "from", "allennlp", ".", "common", ".", "registrable", "import", "Registrable", ...
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...
[ "This", "is", "the", "automatic", "implementation", "of", "from_params", ".", "Any", "class", "that", "subclasses", "FromParams", "(", "or", "Registrable", "which", "itself", "subclasses", "FromParams", ")", "gets", "this", "implementation", "for", "free", ".", ...
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/from_params.py#L327-L388
train
allenai/allennlp
allennlp/state_machines/transition_functions/transition_function.py
TransitionFunction.take_step
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 ...
python
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", "take_step", "(", "self", ",", "state", ":", "StateType", ",", "max_actions", ":", "int", "=", "None", ",", "allowed_actions", ":", "List", "[", "Set", "]", "=", "None", ")", "->", "List", "[", "StateType", "]", ":", "raise", "NotImplementedError"...
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...
[ "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", "." ]
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/state_machines/transition_functions/transition_function.py#L23-L82
train
allenai/allennlp
allennlp/training/optimizers.py
_safe_sparse_mask
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...
python
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", "_safe_sparse_mask", "(", "tensor", ":", "torch", ".", "Tensor", ",", "mask", ":", "torch", ".", "Tensor", ")", "->", "torch", ".", "Tensor", ":", "# pylint: disable=protected-access", "try", ":", "return", "tensor", ".", "sparse_mask", "(", "mask", "...
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.
[ "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...
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/training/optimizers.py#L147-L157
train
allenai/allennlp
allennlp/data/dataset_readers/semantic_dependency_parsing.py
parse_sentence
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', ...
python
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_sentence", "(", "sentence_blob", ":", "str", ")", "->", "Tuple", "[", "List", "[", "Dict", "[", "str", ",", "str", "]", "]", ",", "List", "[", "Tuple", "[", "int", ",", "int", "]", "]", ",", "List", "[", "str", "]", "]", ":", "ann...
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': '-', '...
[ "Parses", "a", "chunk", "of", "text", "in", "the", "SemEval", "SDP", "format", "." ]
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/dataset_readers/semantic_dependency_parsing.py#L17-L56
train
allenai/allennlp
allennlp/common/checks.py
parse_cuda_device
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: ...
python
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", "parse_cuda_device", "(", "cuda_device", ":", "Union", "[", "str", ",", "int", ",", "List", "[", "int", "]", "]", ")", "->", "Union", "[", "int", ",", "List", "[", "int", "]", "]", ":", "def", "from_list", "(", "strings", ")", ":", "if", "...
Disambiguates single GPU and multiple GPU settings for cuda_device param.
[ "Disambiguates", "single", "GPU", "and", "multiple", "GPU", "settings", "for", "cuda_device", "param", "." ]
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/checks.py#L51-L71
train
allenai/allennlp
allennlp/commands/fine_tune.py
fine_tune_model_from_args
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, ...
python
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_args", "(", "args", ":", "argparse", ".", "Namespace", ")", ":", "fine_tune_model_from_file_paths", "(", "model_archive_path", "=", "args", ".", "model_archive", ",", "config_file", "=", "args", ".", "config_file", ",", "serialization_dir"...
Just converts from an ``argparse.Namespace`` object to string paths.
[ "Just", "converts", "from", "an", "argparse", ".", "Namespace", "object", "to", "string", "paths", "." ]
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/commands/fine_tune.py#L89-L100
train
allenai/allennlp
allennlp/commands/fine_tune.py
fine_tune_model_from_file_paths
def fine_tune_model_from_file_paths(model_archive_path: str, config_file: str, serialization_dir: str, overrides: str = "", extend_vocab: bool = False, ...
python
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_from_file_paths", "(", "model_archive_path", ":", "str", ",", "config_file", ":", "str", ",", "serialization_dir", ":", "str", ",", "overrides", ":", "str", "=", "\"\"", ",", "extend_vocab", ":", "bool", "=", "False", ",", "file_friendly_...
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...
[ "A", "wrapper", "around", ":", "func", ":", "fine_tune_model", "which", "loads", "the", "model", "archive", "from", "a", "file", "." ]
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/commands/fine_tune.py#L103-L150
train
allenai/allennlp
allennlp/commands/fine_tune.py
fine_tune_model
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...
python
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", "fine_tune_model", "(", "model", ":", "Model", ",", "params", ":", "Params", ",", "serialization_dir", ":", "str", ",", "extend_vocab", ":", "bool", "=", "False", ",", "file_friendly_logging", ":", "bool", "=", "False", ",", "batch_weight_key", ":", "...
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 ...
[ "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"...
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/commands/fine_tune.py#L152-L304
train
allenai/allennlp
allennlp/modules/pruner.py
Pruner.forward
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, ...
python
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", "forward", "(", "self", ",", "# pylint: disable=arguments-differ", "embeddings", ":", "torch", ".", "FloatTensor", ",", "mask", ":", "torch", ".", "LongTensor", ",", "num_items_to_keep", ":", "Union", "[", "int", ",", "torch", ".", "LongTensor", "]", ")...
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...
[ "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", "s...
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/modules/pruner.py#L25-L131
train
allenai/allennlp
allennlp/data/iterators/data_iterator.py
add_epoch_number
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
python
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", "add_epoch_number", "(", "batch", ":", "Batch", ",", "epoch", ":", "int", ")", "->", "Batch", ":", "for", "instance", "in", "batch", ".", "instances", ":", "instance", ".", "fields", "[", "'epoch_num'", "]", "=", "MetadataField", "(", "epoch", ")"...
Add the epoch number to the batch instances as a MetadataField.
[ "Add", "the", "epoch", "number", "to", "the", "batch", "instances", "as", "a", "MetadataField", "." ]
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/iterators/data_iterator.py#L22-L28
train
allenai/allennlp
allennlp/data/iterators/data_iterator.py
DataIterator._take_instances
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...
python
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", "_take_instances", "(", "self", ",", "instances", ":", "Iterable", "[", "Instance", "]", ",", "max_instances", ":", "Optional", "[", "int", "]", "=", "None", ")", "->", "Iterator", "[", "Instance", "]", ":", "# If max_instances isn't specified, just itera...
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...
[ "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", "...
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/iterators/data_iterator.py#L163-L192
train
allenai/allennlp
allennlp/data/iterators/data_iterator.py
DataIterator._memory_sized_lists
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...
python
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", "_memory_sized_lists", "(", "self", ",", "instances", ":", "Iterable", "[", "Instance", "]", ")", "->", "Iterable", "[", "List", "[", "Instance", "]", "]", ":", "lazy", "=", "is_lazy", "(", "instances", ")", "# Get an iterator over the next epoch worth of...
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...
[ "Breaks", "the", "dataset", "into", "memory", "-", "sized", "lists", "of", "instances", "which", "it", "yields", "up", "one", "at", "a", "time", "until", "it", "gets", "through", "a", "full", "epoch", "." ]
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/iterators/data_iterator.py#L194-L228
train
allenai/allennlp
allennlp/data/iterators/data_iterator.py
DataIterator._ensure_batch_is_sufficiently_small
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...
python
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", "_ensure_batch_is_sufficiently_small", "(", "self", ",", "batch_instances", ":", "Iterable", "[", "Instance", "]", ",", "excess", ":", "Deque", "[", "Instance", "]", ")", "->", "List", "[", "List", "[", "Instance", "]", "]", ":", "if", "self", ".", ...
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...
[ "If", "self", ".", "_maximum_samples_per_batch", "is", "specified", "then", "split", "the", "batch", "into", "smaller", "sub", "-", "batches", "if", "it", "exceeds", "the", "maximum", "size", "." ]
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/iterators/data_iterator.py#L230-L297
train
allenai/allennlp
allennlp/data/iterators/data_iterator.py
DataIterator.get_num_batches
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...
python
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", "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 jus...
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.
[ "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", ...
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/iterators/data_iterator.py#L299-L312
train
allenai/allennlp
allennlp/data/iterators/data_iterator.py
DataIterator._create_batches
def _create_batches(self, instances: Iterable[Instance], shuffle: bool) -> Iterable[Batch]: """ This method should return one epoch worth of batches. """ raise NotImplementedError
python
def _create_batches(self, instances: Iterable[Instance], shuffle: bool) -> Iterable[Batch]: """ This method should return one epoch worth of batches. """ raise NotImplementedError
[ "def", "_create_batches", "(", "self", ",", "instances", ":", "Iterable", "[", "Instance", "]", ",", "shuffle", ":", "bool", ")", "->", "Iterable", "[", "Batch", "]", ":", "raise", "NotImplementedError" ]
This method should return one epoch worth of batches.
[ "This", "method", "should", "return", "one", "epoch", "worth", "of", "batches", "." ]
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/iterators/data_iterator.py#L314-L318
train
allenai/allennlp
allennlp/common/tee_logger.py
replace_cr_with_newline
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. ...
python
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", "replace_cr_with_newline", "(", "message", ":", "str", ")", ":", "if", "'\\r'", "in", "message", ":", "message", "=", "message", ".", "replace", "(", "'\\r'", ",", "''", ")", "if", "not", "message", "or", "message", "[", "-", "1", "]", "!=", "...
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...
[ "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", ...
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/tee_logger.py#L8-L20
train
allenai/allennlp
allennlp/predictors/predictor.py
Predictor.capture_model_internals
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: ...
python
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", "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", ":", ...
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...
[ "Context", "manager", "that", "captures", "the", "internal", "-", "module", "outputs", "of", "this", "predictor", "s", "model", ".", "The", "idea", "is", "that", "you", "could", "use", "it", "as", "follows", ":" ]
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/predictors/predictor.py#L61-L92
train
allenai/allennlp
allennlp/predictors/predictor.py
Predictor._batch_json_to_instances
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 ...
python
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", "_batch_json_to_instances", "(", "self", ",", "json_dicts", ":", "List", "[", "JsonDict", "]", ")", "->", "List", "[", "Instance", "]", ":", "instances", "=", "[", "]", "for", "json_dict", "in", "json_dicts", ":", "instances", ".", "append", "(", ...
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...
[ "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...
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/predictors/predictor.py#L114-L126
train
allenai/allennlp
allennlp/predictors/predictor.py
Predictor.from_path
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 ...
python
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_path", "(", "cls", ",", "archive_path", ":", "str", ",", "predictor_name", ":", "str", "=", "None", ")", "->", "'Predictor'", ":", "return", "Predictor", ".", "from_archive", "(", "load_archive", "(", "archive_path", ")", ",", "predictor_name", ...
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", "archive", "path", "." ]
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/predictors/predictor.py#L129-L144
train
allenai/allennlp
allennlp/predictors/predictor.py
Predictor.from_archive
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...
python
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", "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"...
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.
[ "Instantiate", "a", ":", "class", ":", "Predictor", "from", "an", ":", "class", ":", "~allennlp", ".", "models", ".", "archival", ".", "Archive", ";", "that", "is", "from", "the", "result", "of", "training", "a", "model", ".", "Optionally", "specify", "w...
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/predictors/predictor.py#L147-L169
train
allenai/allennlp
allennlp/modules/seq2seq_encoders/bidirectional_language_model_transformer.py
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 = query.size(-1) scores = torch.matmu...
python
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", "attention", "(", "query", ":", "torch", ".", "Tensor", ",", "key", ":", "torch", ".", "Tensor", ",", "value", ":", "torch", ".", "Tensor", ",", "mask", ":", "torch", ".", "Tensor", "=", "None", ",", "dropout", ":", "Callable", "=", "None", ...
Compute 'Scaled Dot Product Attention
[ "Compute", "Scaled", "Dot", "Product", "Attention" ]
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/modules/seq2seq_encoders/bidirectional_language_model_transformer.py#L24-L37
train
allenai/allennlp
allennlp/modules/seq2seq_encoders/bidirectional_language_model_transformer.py
subsequent_mask
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
python
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", "subsequent_mask", "(", "size", ":", "int", ",", "device", ":", "str", "=", "'cpu'", ")", "->", "torch", ".", "Tensor", ":", "mask", "=", "torch", ".", "tril", "(", "torch", ".", "ones", "(", "size", ",", "size", ",", "device", "=", "device"...
Mask out subsequent positions.
[ "Mask", "out", "subsequent", "positions", "." ]
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/modules/seq2seq_encoders/bidirectional_language_model_transformer.py#L40-L43
train
allenai/allennlp
allennlp/modules/seq2seq_encoders/bidirectional_language_model_transformer.py
make_model
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...
python
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", "make_model", "(", "num_layers", ":", "int", "=", "6", ",", "input_size", ":", "int", "=", "512", ",", "# Attention size", "hidden_size", ":", "int", "=", "2048", ",", "# FF layer size", "heads", ":", "int", "=", "8", ",", "dropout", ":", "float",...
Helper: Construct a model from hyperparameters.
[ "Helper", ":", "Construct", "a", "model", "from", "hyperparameters", "." ]
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/modules/seq2seq_encoders/bidirectional_language_model_transformer.py#L175-L192
train
allenai/allennlp
allennlp/modules/seq2seq_encoders/bidirectional_language_model_transformer.py
TransformerEncoder.forward
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[...
python
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", ",", "mask", ")", ":", "all_layers", "=", "[", "]", "for", "layer", "in", "self", ".", "layers", ":", "x", "=", "layer", "(", "x", ",", "mask", ")", "if", "self", ".", "return_all_layers", ":", "all_layers",...
Pass the input (and mask) through each layer in turn.
[ "Pass", "the", "input", "(", "and", "mask", ")", "through", "each", "layer", "in", "turn", "." ]
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/modules/seq2seq_encoders/bidirectional_language_model_transformer.py#L89-L100
train
allenai/allennlp
allennlp/modules/seq2seq_encoders/bidirectional_language_model_transformer.py
SublayerConnection.forward
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)))
python
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", ",", "sublayer", ":", "Callable", "[", "[", "torch", ".", "Tensor", "]", ",", "torch", ".", "Tensor", "]", ")", "->", "torch", ".", "Tensor", ":", "return", "x", "+", "self", "...
Apply residual connection to any sublayer with the same size.
[ "Apply", "residual", "connection", "to", "any", "sublayer", "with", "the", "same", "size", "." ]
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/modules/seq2seq_encoders/bidirectional_language_model_transformer.py#L114-L116
train
allenai/allennlp
allennlp/modules/seq2seq_encoders/bidirectional_language_model_transformer.py
EncoderLayer.forward
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)
python
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", "forward", "(", "self", ",", "x", ":", "torch", ".", "Tensor", ",", "mask", ":", "torch", ".", "Tensor", ")", "->", "torch", ".", "Tensor", ":", "x", "=", "self", ".", "sublayer", "[", "0", "]", "(", "x", ",", "lambda", "x", ":", "self",...
Follow Figure 1 (left) for connections.
[ "Follow", "Figure", "1", "(", "left", ")", "for", "connections", "." ]
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/modules/seq2seq_encoders/bidirectional_language_model_transformer.py#L133-L136
train
allenai/allennlp
allennlp/nn/initializers.py
uniform_unit_scaling
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...
python
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", "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", ...
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", "initaliser", "which", "preserves", "output", "variance", "for", "approximately", "gaussian", "distributed", "inputs", ".", "This", "boils", "down", "to", "initialising", "layers", "using", "a", "uniform", "distribution", "in", "the", "range", "(", "-", "s...
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/nn/initializers.py#L58-L95
train
allenai/allennlp
allennlp/nn/initializers.py
block_orthogonal
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...
python
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", "block_orthogonal", "(", "tensor", ":", "torch", ".", "Tensor", ",", "split_sizes", ":", "List", "[", "int", "]", ",", "gain", ":", "float", "=", "1.0", ")", "->", "None", ":", "data", "=", "tensor", ".", "data", "sizes", "=", "list", "(", "...
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...
[ "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",...
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/nn/initializers.py#L98-L138
train
allenai/allennlp
allennlp/nn/initializers.py
lstm_hidden_bias
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...
python
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", "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", "]",...
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
[ "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" ]
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/nn/initializers.py#L144-L152
train
allenai/allennlp
allennlp/nn/initializers.py
InitializerApplicator.from_params
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", { ...
python
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", "from_params", "(", "cls", ",", "params", ":", "List", "[", "Tuple", "[", "str", ",", "Params", "]", "]", "=", "None", ")", "->", "\"InitializerApplicator\"", ":", "# pylint: disable=arguments-differ", "params", "=", "params", "or", "[", "]", "is_prev...
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 }...
[ "Converts", "a", "Params", "object", "into", "an", "InitializerApplicator", ".", "The", "json", "should", "be", "formatted", "as", "follows", "::" ]
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/nn/initializers.py#L317-L353
train
allenai/allennlp
allennlp/semparse/contexts/table_question_knowledge_graph.py
TableQuestionKnowledgeGraph.read_from_file
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...
python
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_file", "(", "cls", ",", "filename", ":", "str", ",", "question", ":", "List", "[", "Token", "]", ")", "->", "'TableQuestionKnowledgeGraph'", ":", "return", "cls", ".", "read_from_lines", "(", "open", "(", "filename", ")", ".", "readlines", ...
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", "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", ...
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/contexts/table_question_knowledge_graph.py#L101-L114
train
allenai/allennlp
allennlp/semparse/contexts/table_question_knowledge_graph.py
TableQuestionKnowledgeGraph.read_from_json
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"...
python
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", "read_from_json", "(", "cls", ",", "json_object", ":", "Dict", "[", "str", ",", "Any", "]", ")", "->", "'TableQuestionKnowledgeGraph'", ":", "entity_text", ":", "Dict", "[", "str", ",", "str", "]", "=", "{", "}", "neighbors", ":", "DefaultDict", "...
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...
[ "We", "read", "tables", "formatted", "as", "JSON", "objects", "(", "dicts", ")", "here", ".", "This", "is", "useful", "when", "you", "are", "reading", "data", "from", "a", "demo", ".", "The", "expected", "format", "is", "::" ]
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/contexts/table_question_knowledge_graph.py#L129-L203
train
allenai/allennlp
allennlp/semparse/contexts/table_question_knowledge_graph.py
TableQuestionKnowledgeGraph._get_numbers_from_tokens
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...
python
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_numbers_from_tokens", "(", "tokens", ":", "List", "[", "Token", "]", ")", "->", "List", "[", "Tuple", "[", "str", ",", "str", "]", "]", ":", "numbers", "=", "[", "]", "for", "i", ",", "token", "in", "enumerate", "(", "tokens", ")", ":"...
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...
[ "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", ...
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/contexts/table_question_knowledge_graph.py#L246-L306
train
allenai/allennlp
allennlp/semparse/contexts/table_question_knowledge_graph.py
TableQuestionKnowledgeGraph._get_cell_parts
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...
python
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", "_get_cell_parts", "(", "cls", ",", "cell_text", ":", "str", ")", "->", "List", "[", "Tuple", "[", "str", ",", "str", "]", "]", ":", "parts", "=", "[", "]", "for", "part_text", "in", "cls", ".", "cell_part_regex", ".", "split", "(", "cell_text...
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...
[ "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", "]", ...
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/contexts/table_question_knowledge_graph.py#L310-L326
train
allenai/allennlp
allennlp/semparse/contexts/table_question_knowledge_graph.py
TableQuestionKnowledgeGraph._should_split_column_cells
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)
python
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_column_cells", "(", "cls", ",", "column_cells", ":", "List", "[", "str", "]", ")", "->", "bool", ":", "return", "any", "(", "cls", ".", "_should_split_cell", "(", "cell_text", ")", "for", "cell_text", "in", "column_cells", ")" ]
Returns true if there is any cell in this column that can be split.
[ "Returns", "true", "if", "there", "is", "any", "cell", "in", "this", "column", "that", "can", "be", "split", "." ]
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/contexts/table_question_knowledge_graph.py#L329-L333
train
allenai/allennlp
allennlp/semparse/contexts/table_question_knowledge_graph.py
TableQuestionKnowledgeGraph._should_split_cell
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
python
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", "_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" ]
Checks whether the cell should be split. We're just doing the same thing that SEMPRE did here.
[ "Checks", "whether", "the", "cell", "should", "be", "split", ".", "We", "re", "just", "doing", "the", "same", "thing", "that", "SEMPRE", "did", "here", "." ]
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/contexts/table_question_knowledge_graph.py#L336-L343
train
allenai/allennlp
allennlp/semparse/contexts/table_question_knowledge_graph.py
TableQuestionKnowledgeGraph.get_linked_agenda_items
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...
python
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", "get_linked_agenda_items", "(", "self", ")", "->", "List", "[", "str", "]", ":", "agenda_items", ":", "List", "[", "str", "]", "=", "[", "]", "for", "entity", "in", "self", ".", "_get_longest_span_matching_entities", "(", ")", ":", "agenda_items", "...
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.
[ "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",...
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/contexts/table_question_knowledge_graph.py#L345-L358
train
allenai/allennlp
scripts/convert_openie_to_conll.py
main
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 ...
python
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", "main", "(", "inp_fn", ":", "str", ",", "domain", ":", "str", ",", "out_fn", ":", "str", ")", "->", "None", ":", "with", "open", "(", "out_fn", ",", "'w'", ")", "as", "fout", ":", "for", "sent_ls", "in", "read", "(", "inp_fn", ")", ":", ...
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.
[ "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", "C...
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/scripts/convert_openie_to_conll.py#L35-L52
train
allenai/allennlp
scripts/convert_openie_to_conll.py
element_from_span
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)))
python
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", "element_from_span", "(", "span", ":", "List", "[", "int", "]", ",", "span_type", ":", "str", ")", "->", "Element", ":", "return", "Element", "(", "span_type", ",", "[", "span", "[", "0", "]", ".", "idx", ",", "span", "[", "-", "1", "]", "...
Return an Element from span (list of spacy toks)
[ "Return", "an", "Element", "from", "span", "(", "list", "of", "spacy", "toks", ")" ]
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/scripts/convert_openie_to_conll.py#L69-L77
train
allenai/allennlp
scripts/convert_openie_to_conll.py
split_predicate
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 ...
python
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", "split_predicate", "(", "ex", ":", "Extraction", ")", "->", "Extraction", ":", "rel_toks", "=", "ex", ".", "toks", "[", "char_to_word_index", "(", "ex", ".", "rel", ".", "span", "[", "0", "]", ",", "ex", ".", "sent", ")", ":", "char_to_word_inde...
Ensure single word predicate by adding "before-predicate" and "after-predicate" arguments.
[ "Ensure", "single", "word", "predicate", "by", "adding", "before", "-", "predicate", "and", "after", "-", "predicate", "arguments", "." ]
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/scripts/convert_openie_to_conll.py#L79-L109
train
allenai/allennlp
scripts/convert_openie_to_conll.py
extraction_to_conll
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) ...
python
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", "extraction_to_conll", "(", "ex", ":", "Extraction", ")", "->", "List", "[", "str", "]", ":", "ex", "=", "split_predicate", "(", "ex", ")", "toks", "=", "ex", ".", "sent", ".", "split", "(", "' '", ")", "ret", "=", "[", "'*'", "]", "*", "l...
Return a conll representation of a given input Extraction.
[ "Return", "a", "conll", "representation", "of", "a", "given", "input", "Extraction", "." ]
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/scripts/convert_openie_to_conll.py#L111-L133
train
allenai/allennlp
scripts/convert_openie_to_conll.py
interpret_span
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 = [] ...
python
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_span", "(", "text_spans", ":", "str", ")", "->", "List", "[", "int", "]", ":", "m", "=", "regex", ".", "match", "(", "\"^(?:(?:([\\(\\[]\\d+, \\d+[\\)\\]])|({\\d+}))[,]?\\s*)+$\"", ",", "text_spans", ")", "spans", "=", "m", ".", "captures", "...
Return an integer tuple from textual representation of closed / open spans.
[ "Return", "an", "integer", "tuple", "from", "textual", "representation", "of", "closed", "/", "open", "spans", "." ]
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/scripts/convert_openie_to_conll.py#L135-L175
train
allenai/allennlp
scripts/convert_openie_to_conll.py
interpret_element
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)
python
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", "interpret_element", "(", "element_type", ":", "str", ",", "text", ":", "str", ",", "span", ":", "str", ")", "->", "Element", ":", "return", "Element", "(", "element_type", ",", "interpret_span", "(", "span", ")", ",", "text", ")" ]
Construct an Element instance from regexp groups.
[ "Construct", "an", "Element", "instance", "from", "regexp", "groups", "." ]
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/scripts/convert_openie_to_conll.py#L177-L184
train
allenai/allennlp
scripts/convert_openie_to_conll.py
parse_element
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(';')...
python
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", "parse_element", "(", "raw_element", ":", "str", ")", "->", "List", "[", "Element", "]", ":", "elements", "=", "[", "regex", ".", "match", "(", "\"^(([a-zA-Z]+)\\(([^;]+),List\\(([^;]*)\\)\\))$\"", ",", "elem", ".", "lstrip", "(", ")", ".", "rstrip", ...
Parse a raw element into text and indices (integers).
[ "Parse", "a", "raw", "element", "into", "text", "and", "indices", "(", "integers", ")", "." ]
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/scripts/convert_openie_to_conll.py#L186-L196
train
allenai/allennlp
scripts/convert_openie_to_conll.py
convert_sent_to_conll
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....
python
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", "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", "]", ...
Given a list of extractions for a single sentence - convert it to conll representation.
[ "Given", "a", "list", "of", "extractions", "for", "a", "single", "sentence", "-", "convert", "it", "to", "conll", "representation", "." ]
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/scripts/convert_openie_to_conll.py#L237-L249
train
allenai/allennlp
scripts/convert_openie_to_conll.py
pad_line_to_ontonotes
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, '-',\ ...
python
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", "pad_line_to_ontonotes", "(", "line", ",", "domain", ")", "->", "List", "[", "str", "]", ":", "word_ind", ",", "word", "=", "line", "[", ":", "2", "]", "pos", "=", "'XX'", "oie_tags", "=", "line", "[", "2", ":", "]", "line_num", "=", "0", ...
Pad line to conform to ontonotes representation.
[ "Pad", "line", "to", "conform", "to", "ontonotes", "representation", "." ]
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/scripts/convert_openie_to_conll.py#L252-L263
train
allenai/allennlp
scripts/convert_openie_to_conll.py
convert_sent_dict_to_conll
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...
python
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", "convert_sent_dict_to_conll", "(", "sent_dic", ",", "domain", ")", "->", "str", ":", "return", "'\\n\\n'", ".", "join", "(", "[", "'\\n'", ".", "join", "(", "[", "'\\t'", ".", "join", "(", "map", "(", "str", ",", "pad_line_to_ontonotes", "(", "lin...
Given a dictionary from sentence -> extractions, return a corresponding CoNLL representation.
[ "Given", "a", "dictionary", "from", "sentence", "-", ">", "extractions", "return", "a", "corresponding", "CoNLL", "representation", "." ]
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/scripts/convert_openie_to_conll.py#L265-L273
train
awslabs/serverless-application-model
examples/apps/kinesis-analytics-process-kpl-record/aws_kinesis_agg/deaggregator.py
deaggregate_record
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...
python
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", "deaggregate_record", "(", "decoded_data", ")", ":", "is_aggregated", "=", "True", "#Verify the magic header", "data_magic", "=", "None", "if", "(", "len", "(", "decoded_data", ")", ">=", "len", "(", "aws_kinesis_agg", ".", "MAGIC", ")", ")", ":", "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 decoded data that comprises either the KPL a...
[ "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", "f...
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/examples/apps/kinesis-analytics-process-kpl-record/aws_kinesis_agg/deaggregator.py#L26-L72
train
awslabs/serverless-application-model
samtranslator/model/s3_utils/uri_parser.py
parse_s3_uri
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...
python
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", "parse_s3_uri", "(", "uri", ")", ":", "if", "not", "isinstance", "(", "uri", ",", "string_types", ")", ":", "return", "None", "url", "=", "urlparse", "(", "uri", ")", "query", "=", "parse_qs", "(", "url", ".", "query", ")", "if", "url", ".", ...
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
[ "Parses", "a", "S3", "Uri", "into", "a", "dictionary", "of", "the", "Bucket", "Key", "and", "VersionId" ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/model/s3_utils/uri_parser.py#L6-L27
train
awslabs/serverless-application-model
samtranslator/model/s3_utils/uri_parser.py
to_s3_uri
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...
python
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", "to_s3_uri", "(", "code_dict", ")", ":", "try", ":", "uri", "=", "\"s3://{bucket}/{key}\"", ".", "format", "(", "bucket", "=", "code_dict", "[", "\"S3Bucket\"", "]", ",", "key", "=", "code_dict", "[", "\"S3Key\"", "]", ")", "version", "=", "code_dic...
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
[ "Constructs", "a", "S3", "URI", "string", "from", "given", "code", "dictionary" ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/model/s3_utils/uri_parser.py#L30-L48
train
awslabs/serverless-application-model
samtranslator/model/s3_utils/uri_parser.py
construct_s3_location_object
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...
python
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", "construct_s3_location_object", "(", "location_uri", ",", "logical_id", ",", "property_name", ")", ":", "if", "isinstance", "(", "location_uri", ",", "dict", ")", ":", "if", "not", "location_uri", ".", "get", "(", "\"Bucket\"", ")", "or", "not", "locati...
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...
[ "Constructs", "a", "Lambda", "Code", "or", "Content", "property", "from", "the", "SAM", "CodeUri", "or", "ContentUri", "property", ".", "This", "follows", "the", "current", "scheme", "for", "Lambda", "Functions", "and", "LayerVersions", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/model/s3_utils/uri_parser.py#L51-L86
train
awslabs/serverless-application-model
samtranslator/model/function_policies.py
FunctionPolicies._get_policies
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 ...
python
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", "_get_policies", "(", "self", ",", "resource_properties", ")", ":", "policies", "=", "None", "if", "self", ".", "_contains_policies", "(", "resource_properties", ")", ":", "policies", "=", "resource_properties", "[", "self", ".", "POLICIES_PROPERTY_NAME", "...
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 * ...
[ "Returns", "a", "list", "of", "policies", "from", "the", "resource", "properties", ".", "This", "method", "knows", "how", "to", "interpret", "and", "handle", "polymorphic", "nature", "of", "the", "policies", "property", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/model/function_policies.py#L55-L94
train
awslabs/serverless-application-model
samtranslator/model/function_policies.py
FunctionPolicies._contains_policies
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 \ ...
python
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", "_contains_policies", "(", "self", ",", "resource_properties", ")", ":", "return", "resource_properties", "is", "not", "None", "and", "isinstance", "(", "resource_properties", ",", "dict", ")", "and", "self", ".", "POLICIES_PROPERTY_NAME", "in", "resource_pro...
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
[ "Is", "there", "policies", "data", "in", "this", "resource?" ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/model/function_policies.py#L96-L105
train
awslabs/serverless-application-model
samtranslator/model/function_policies.py
FunctionPolicies._get_type
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 ...
python
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", "_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", ",", "...
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
[ "Returns", "the", "type", "of", "the", "given", "policy" ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/model/function_policies.py#L107-L130
train
awslabs/serverless-application-model
samtranslator/model/function_policies.py
FunctionPolicies._is_policy_template
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 """ ...
python
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", "_is_policy_template", "(", "self", ",", "policy", ")", ":", "return", "self", ".", "_policy_template_processor", "is", "not", "None", "and", "isinstance", "(", "policy", ",", "dict", ")", "and", "len", "(", "policy", ")", "==", "1", "and", "self", ...
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
[ "Is", "the", "given", "policy", "data", "a", "policy", "template?", "Policy", "templates", "is", "a", "dictionary", "with", "one", "key", "which", "is", "the", "name", "of", "the", "template", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/model/function_policies.py#L132-L144
train
awslabs/serverless-application-model
examples/apps/greengrass-hello-world/greengrasssdk/IoTDataPlane.py
Client.get_thing_shadow
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...
python
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", "get_thing_shadow", "(", "self", ",", "*", "*", "kwargs", ")", ":", "thing_name", "=", "self", ".", "_get_required_parameter", "(", "'thingName'", ",", "*", "*", "kwargs", ")", "payload", "=", "b''", "return", "self", ".", "_shadow_op", "(", "'get'"...
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", "Call", "shadow", "lambda", "to", "obtain", "current", "shadow", "state", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/examples/apps/greengrass-hello-world/greengrasssdk/IoTDataPlane.py#L28-L45
train
awslabs/serverless-application-model
examples/apps/greengrass-hello-world/greengrasssdk/IoTDataPlane.py
Client.update_thing_shadow
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``) -- ...
python
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", "update_thing_shadow", "(", "self", ",", "*", "*", "kwargs", ")", ":", "thing_name", "=", "self", ".", "_get_required_parameter", "(", "'thingName'", ",", "*", "*", "kwargs", ")", "payload", "=", "self", ".", "_get_required_parameter", "(", "'payload'",...
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", "Updates", "the", "thing", "shadow", "for", "the", "specified", "thing", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/examples/apps/greengrass-hello-world/greengrasssdk/IoTDataPlane.py#L47-L67
train
awslabs/serverless-application-model
examples/apps/greengrass-hello-world/greengrasssdk/IoTDataPlane.py
Client.delete_thing_shadow
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...
python
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", "delete_thing_shadow", "(", "self", ",", "*", "*", "kwargs", ")", ":", "thing_name", "=", "self", ".", "_get_required_parameter", "(", "'thingName'", ",", "*", "*", "kwargs", ")", "payload", "=", "b''", "return", "self", ".", "_shadow_op", "(", "'de...
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", "Deletes", "the", "thing", "shadow", "for", "the", "specified", "thing", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/examples/apps/greengrass-hello-world/greengrasssdk/IoTDataPlane.py#L69-L86
train
awslabs/serverless-application-model
examples/apps/greengrass-hello-world/greengrasssdk/IoTDataPlane.py
Client.publish
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...
python
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", "publish", "(", "self", ",", "*", "*", "kwargs", ")", ":", "topic", "=", "self", ".", "_get_required_parameter", "(", "'topic'", ",", "*", "*", "kwargs", ")", "# payload is an optional parameter", "payload", "=", "kwargs", ".", "get", "(", "'payload'"...
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
[ "r", "Publishes", "state", "information", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/examples/apps/greengrass-hello-world/greengrasssdk/IoTDataPlane.py#L88-L120
train
awslabs/serverless-application-model
samtranslator/plugins/globals/globals.py
Globals.merge
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...
python
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", "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", "=", "s...
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...
[ "Adds", "global", "properties", "to", "the", "resource", "if", "necessary", ".", "This", "method", "is", "a", "no", "-", "op", "if", "there", "are", "no", "global", "properties", "for", "this", "resource", "type" ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/plugins/globals/globals.py#L80-L96
train
awslabs/serverless-application-model
samtranslator/plugins/globals/globals.py
Globals._parse
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...
python
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", "_parse", "(", "self", ",", "globals_dict", ")", ":", "globals", "=", "{", "}", "if", "not", "isinstance", "(", "globals_dict", ",", "dict", ")", ":", "raise", "InvalidGlobalsSectionException", "(", "self", ".", "_KEYWORD", ",", "\"It must be a non-empt...
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...
[ "Takes", "a", "SAM", "template", "as", "input", "and", "parses", "the", "Globals", "section" ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/plugins/globals/globals.py#L110-L149
train
awslabs/serverless-application-model
samtranslator/plugins/globals/globals.py
GlobalProperties._do_merge
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...
python
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", "_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 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
[ "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...
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/plugins/globals/globals.py#L286-L314
train
awslabs/serverless-application-model
samtranslator/plugins/globals/globals.py
GlobalProperties._merge_dict
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...
python
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", "_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"...
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
[ "Merges", "the", "two", "dictionaries", "together" ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/plugins/globals/globals.py#L327-L349
train
awslabs/serverless-application-model
samtranslator/plugins/globals/globals.py
GlobalProperties._token_of
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...
python
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", "_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 ...
Returns the token type of the input. :param input: Input whose type is to be determined :return TOKENS: Token type of the input
[ "Returns", "the", "token", "type", "of", "the", "input", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/plugins/globals/globals.py#L362-L384
train
awslabs/serverless-application-model
samtranslator/validator/validator.py
SamTemplateValidator.validate
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...
python
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", "validate", "(", "template_dict", ",", "schema", "=", "None", ")", ":", "if", "not", "schema", ":", "schema", "=", "SamTemplateValidator", ".", "_read_schema", "(", ")", "validation_errors", "=", "\"\"", "try", ":", "jsonschema", ".", "validate", "(",...
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
[ "Is", "this", "a", "valid", "SAM", "template", "dictionary" ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/validator/validator.py#L12-L35
train
awslabs/serverless-application-model
examples/apps/lex-book-trip-python/lambda_function.py
generate_car_price
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 ...
python
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_car_price", "(", "location", ",", "days", ",", "age", ",", "car_type", ")", ":", "car_types", "=", "[", "'economy'", ",", "'standard'", ",", "'midsize'", ",", "'full size'", ",", "'minivan'", ",", "'luxury'", "]", "base_location_cost", "=", ...
Generates a number within a reasonable range that might be expected for a flight. The price is fixed for a given pair of locations.
[ "Generates", "a", "number", "within", "a", "reasonable", "range", "that", "might", "be", "expected", "for", "a", "flight", ".", "The", "price", "is", "fixed", "for", "a", "given", "pair", "of", "locations", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/examples/apps/lex-book-trip-python/lambda_function.py#L97-L113
train
awslabs/serverless-application-model
examples/apps/lex-book-trip-python/lambda_function.py
generate_hotel_price
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)): ...
python
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", "generate_hotel_price", "(", "location", ",", "nights", ",", "room_type", ")", ":", "room_types", "=", "[", "'queen'", ",", "'king'", ",", "'deluxe'", "]", "cost_of_living", "=", "0", "for", "i", "in", "range", "(", "len", "(", "location", ")", ")...
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.
[ "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", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/examples/apps/lex-book-trip-python/lambda_function.py#L116-L127
train
awslabs/serverless-application-model
examples/apps/lex-book-trip-python/lambda_function.py
book_hotel
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...
python
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_hotel", "(", "intent_request", ")", ":", "location", "=", "try_ex", "(", "lambda", ":", "intent_request", "[", "'currentIntent'", "]", "[", "'slots'", "]", "[", "'Location'", "]", ")", "checkin_date", "=", "try_ex", "(", "lambda", ":", "intent_r...
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
[ "Performs", "dialog", "management", "and", "fulfillment", "for", "booking", "a", "hotel", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/examples/apps/lex-book-trip-python/lambda_function.py#L261-L330
train
awslabs/serverless-application-model
examples/apps/lex-book-trip-python/lambda_function.py
book_car
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...
python
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", "book_car", "(", "intent_request", ")", ":", "slots", "=", "intent_request", "[", "'currentIntent'", "]", "[", "'slots'", "]", "pickup_city", "=", "slots", "[", "'PickUpCity'", "]", "pickup_date", "=", "slots", "[", "'PickUpDate'", "]", "return_date", "...
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
[ "Performs", "dialog", "management", "and", "fulfillment", "for", "booking", "a", "car", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/examples/apps/lex-book-trip-python/lambda_function.py#L333-L484
train
awslabs/serverless-application-model
examples/apps/lex-book-trip-python/lambda_function.py
dispatch
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...
python
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", "dispatch", "(", "intent_request", ")", ":", "logger", ".", "debug", "(", "'dispatch userId={}, intentName={}'", ".", "format", "(", "intent_request", "[", "'userId'", "]", ",", "intent_request", "[", "'currentIntent'", "]", "[", "'name'", "]", ")", ")", ...
Called when the user specifies an intent for this bot.
[ "Called", "when", "the", "user", "specifies", "an", "intent", "for", "this", "bot", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/examples/apps/lex-book-trip-python/lambda_function.py#L490-L505
train
awslabs/serverless-application-model
samtranslator/model/eventsources/pull.py
PullEventSource.to_cloudformation
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...
python
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", "to_cloudformation", "(", "self", ",", "*", "*", "kwargs", ")", ":", "function", "=", "kwargs", ".", "get", "(", "'function'", ")", "if", "not", "function", ":", "raise", "TypeError", "(", "\"Missing required keyword argument: function\"", ")", "resources...
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...
[ "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", "."...
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/model/eventsources/pull.py#L30-L73
train
awslabs/serverless-application-model
samtranslator/model/eventsources/pull.py
PullEventSource._link_policy
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...
python
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", "_link_policy", "(", "self", ",", "role", ")", ":", "policy_arn", "=", "self", ".", "get_policy_arn", "(", ")", "if", "role", "is", "not", "None", "and", "policy_arn", "not", "in", "role", ".", "ManagedPolicyArns", ":", "role", ".", "ManagedPolicyAr...
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
[ "If", "this", "source", "triggers", "a", "Lambda", "function", "whose", "execution", "role", "is", "auto", "-", "generated", "by", "SAM", "add", "the", "appropriate", "managed", "policy", "to", "this", "Role", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/model/eventsources/pull.py#L75-L83
train
awslabs/serverless-application-model
samtranslator/sdk/parameter.py
SamParameterValues.add_default_parameter_values
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 ...
python
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_default_parameter_values", "(", "self", ",", "sam_template", ")", ":", "parameter_definition", "=", "sam_template", ".", "get", "(", "\"Parameters\"", ",", "None", ")", "if", "not", "parameter_definition", "or", "not", "isinstance", "(", "parameter_defin...
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: ...
[ "Method", "to", "read", "default", "values", "for", "template", "parameters", "and", "merge", "with", "user", "supplied", "values", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/sdk/parameter.py#L19-L59
train
awslabs/serverless-application-model
samtranslator/sdk/parameter.py
SamParameterValues.add_pseudo_parameter_values
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
python
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_pseudo_parameter_values", "(", "self", ")", ":", "if", "'AWS::Region'", "not", "in", "self", ".", "parameter_values", ":", "self", ".", "parameter_values", "[", "'AWS::Region'", "]", "=", "boto3", ".", "session", ".", "Session", "(", ")", ".", "r...
Add pseudo parameter values :return: parameter values that have pseudo parameter in it
[ "Add", "pseudo", "parameter", "values", ":", "return", ":", "parameter", "values", "that", "have", "pseudo", "parameter", "in", "it" ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/sdk/parameter.py#L61-L67
train
awslabs/serverless-application-model
samtranslator/model/preferences/deployment_preference_collection.py
DeploymentPreferenceCollection.add
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 ...
python
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", "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\"",...
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...
[ "Add", "this", "deployment", "preference", "to", "the", "collection" ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/model/preferences/deployment_preference_collection.py#L32-L44
train
awslabs/serverless-application-model
samtranslator/model/preferences/deployment_preference_collection.py
DeploymentPreferenceCollection.enabled_logical_ids
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]
python
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", "enabled_logical_ids", "(", "self", ")", ":", "return", "[", "logical_id", "for", "logical_id", ",", "preference", "in", "self", ".", "_resource_preferences", ".", "items", "(", ")", "if", "preference", ".", "enabled", "]" ]
:return: only the logical id's for the deployment preferences in this collection which are enabled
[ ":", "return", ":", "only", "the", "logical", "id", "s", "for", "the", "deployment", "preferences", "in", "this", "collection", "which", "are", "enabled" ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/model/preferences/deployment_preference_collection.py#L66-L70
train
awslabs/serverless-application-model
samtranslator/model/preferences/deployment_preference_collection.py
DeploymentPreferenceCollection.deployment_group
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...
python
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", "deployment_group", "(", "self", ",", "function_logical_id", ")", ":", "deployment_preference", "=", "self", ".", "get", "(", "function_logical_id", ")", "deployment_group", "=", "CodeDeployDeploymentGroup", "(", "self", ".", "deployment_group_logical_id", "(", ...
:param function_logical_id: logical_id of the function this deployment group belongs to :return: CodeDeployDeploymentGroup resource
[ ":", "param", "function_logical_id", ":", "logical_id", "of", "the", "function", "this", "deployment", "group", "belongs", "to", ":", "return", ":", "CodeDeployDeploymentGroup", "resource" ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/model/preferences/deployment_preference_collection.py#L93-L121
train
awslabs/serverless-application-model
examples/apps/alexa-skills-kit-color-expert-python/lambda_function.py
get_welcome_response
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...
python
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", "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 the...
If we wanted to initialize the session to have some attributes we could add those here
[ "If", "we", "wanted", "to", "initialize", "the", "session", "to", "have", "some", "attributes", "we", "could", "add", "those", "here" ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/examples/apps/alexa-skills-kit-color-expert-python/lambda_function.py#L46-L62
train
awslabs/serverless-application-model
examples/apps/alexa-skills-kit-color-expert-python/lambda_function.py
set_color_in_session
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...
python
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", "set_color_in_session", "(", "intent", ",", "session", ")", ":", "card_title", "=", "intent", "[", "'name'", "]", "session_attributes", "=", "{", "}", "should_end_session", "=", "False", "if", "'Color'", "in", "intent", "[", "'slots'", "]", ":", "favo...
Sets the color in the session and prepares the speech to reply to the user.
[ "Sets", "the", "color", "in", "the", "session", "and", "prepares", "the", "speech", "to", "reply", "to", "the", "user", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/examples/apps/alexa-skills-kit-color-expert-python/lambda_function.py#L79-L104
train
awslabs/serverless-application-model
examples/apps/alexa-skills-kit-color-expert-python/lambda_function.py
on_intent
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'] # ...
python
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", "on_intent", "(", "intent_request", ",", "session", ")", ":", "print", "(", "\"on_intent requestId=\"", "+", "intent_request", "[", "'requestId'", "]", "+", "\", sessionId=\"", "+", "session", "[", "'sessionId'", "]", ")", "intent", "=", "intent_request", ...
Called when the user specifies an intent for this skill
[ "Called", "when", "the", "user", "specifies", "an", "intent", "for", "this", "skill" ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/examples/apps/alexa-skills-kit-color-expert-python/lambda_function.py#L148-L167
train
awslabs/serverless-application-model
examples/apps/alexa-skills-kit-color-expert-python/lambda_function.py
lambda_handler
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']) "...
python
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", "lambda_handler", "(", "event", ",", "context", ")", ":", "print", "(", "\"event.session.application.applicationId=\"", "+", "event", "[", "'session'", "]", "[", "'application'", "]", "[", "'applicationId'", "]", ")", "\"\"\"\n Uncomment this if statement and ...
Route the incoming request based on type (LaunchRequest, IntentRequest, etc.) The JSON body of the request is provided in the event parameter.
[ "Route", "the", "incoming", "request", "based", "on", "type", "(", "LaunchRequest", "IntentRequest", "etc", ".", ")", "The", "JSON", "body", "of", "the", "request", "is", "provided", "in", "the", "event", "parameter", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/examples/apps/alexa-skills-kit-color-expert-python/lambda_function.py#L182-L207
train
awslabs/serverless-application-model
samtranslator/translator/logical_id_generator.py
LogicalIdGenerator.gen
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 ...
python
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", "gen", "(", "self", ")", ":", "data_hash", "=", "self", ".", "get_hash", "(", ")", "return", "\"{prefix}{hash}\"", ".", "format", "(", "prefix", "=", "self", ".", "_prefix", ",", "hash", "=", "data_hash", ")" ]
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", "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", ".", "I...
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/translator/logical_id_generator.py#L28-L47
train
awslabs/serverless-application-model
samtranslator/translator/logical_id_generator.py
LogicalIdGenerator.get_hash
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...
python
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", "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", "."...
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
[ "Generate", "and", "return", "a", "hash", "of", "data", "that", "can", "be", "used", "as", "suffix", "of", "logicalId" ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/translator/logical_id_generator.py#L49-L72
train
awslabs/serverless-application-model
samtranslator/translator/logical_id_generator.py
LogicalIdGenerator._stringify
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...
python
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...
[ "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"...
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 ...
[ "Stable", "platform", "&", "language", "-", "independent", "stringification", "of", "a", "data", "with", "basic", "Python", "type", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/translator/logical_id_generator.py#L74-L90
train