_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
31
13.1k
language
stringclasses
1 value
meta_information
dict
q24500
UserDefined.has_documented_fields
train
def has_documented_fields(self, include_inherited_fields=False): """Returns whether at least one field is documented.""" fields = self.all_fields if include_inherited_fields else self.fields
python
{ "resource": "" }
q24501
UserDefined.get_examples
train
def get_examples(self, compact=False): """ Returns an OrderedDict mapping labels to Example objects. Args: compact (bool): If True, union members of void type are converted to their compact representation: no ".tag" key or containing dict, just the ta...
python
{ "resource": "" }
q24502
Struct.all_required_fields
train
def all_required_fields(self): """ Returns an iterator that traverses required fields in all super types first, and then for this type. """ def required_check(f):
python
{ "resource": "" }
q24503
Struct.all_optional_fields
train
def all_optional_fields(self): """ Returns an iterator that traverses optional fields in all super types first, and then for this type. """ def optional_check(f):
python
{ "resource": "" }
q24504
Struct.set_enumerated_subtypes
train
def set_enumerated_subtypes(self, subtype_fields, is_catch_all): """ Sets the list of "enumerated subtypes" for this struct. This differs from regular subtyping in that each subtype is associated with a tag that is used in the serialized format to indicate the subtype. Also, this...
python
{ "resource": "" }
q24505
Struct.get_all_subtypes_with_tags
train
def get_all_subtypes_with_tags(self): """ Unlike other enumerated-subtypes-related functionality, this method returns not just direct subtypes, but all subtypes of this struct. The tag of each subtype is the list of tags from which the type descends. This method only applies to ...
python
{ "resource": "" }
q24506
Struct._get_subtype_tags
train
def _get_subtype_tags(self): """ Returns a list of type tags that refer to this type starting from the base of the struct hierarchy. """ assert self.is_member_of_enumerated_subtypes_tree(), \ 'Not a part of a subtypes tree.' cur = self.parent_type cur_...
python
{ "resource": "" }
q24507
Struct._add_example_enumerated_subtypes_helper
train
def _add_example_enumerated_subtypes_helper(self, example): """Validates examples for structs with enumerated subtypes.""" if len(example.fields) != 1: raise InvalidSpec( 'Example for struct with enumerated subtypes must only ' 'specify one subtype tag.', exa...
python
{ "resource": "" }
q24508
Struct._add_example_helper
train
def _add_example_helper(self, example): """Validates examples for structs without enumerated subtypes.""" # Check for fields in the example that don't belong. for label, example_field in example.fields.items(): if not any(label == f.name for f in self.all_fields): ra...
python
{ "resource": "" }
q24509
Union.all_fields
train
def all_fields(self): """ Returns a list of all fields. Subtype fields come before this type's fields. """ fields = [] if self.parent_type:
python
{ "resource": "" }
q24510
Union._has_example
train
def _has_example(self, label): """Whether this data type has an example with the given ``label``.""" if label in self._raw_examples: return True else: for field in self.all_fields: dt, _ = unwrap_nullable(field.data_type)
python
{ "resource": "" }
q24511
Union.unique_field_data_types
train
def unique_field_data_types(self): """ Checks if all variants have different data types. If so, the selected variant can be determined just by the data type of the value without needing a field name / tag. In some languages, this lets us make a shortcut """ data_...
python
{ "resource": "" }
q24512
ObjCTypesBackend._generate_namespace_types
train
def _generate_namespace_types(self, namespace, jazzy_cfg): """Creates Obj C argument, error, serializer and deserializer types for the given namespace.""" ns_name = fmt_public_name(namespace.name) output_path = os.path.join('ApiObjects', ns_name) output_path_headers = os.path.joi...
python
{ "resource": "" }
q24513
ObjCTypesBackend._generate_struct_class_m
train
def _generate_struct_class_m(self, struct): """Defines an Obj C implementation file that represents a struct in Stone.""" self.emit() self._generate_imports_m( self._get_imports_m( struct, default_imports=['DBStoneSerializers', 'DBStoneValidators'])) ...
python
{ "resource": "" }
q24514
ObjCTypesBackend._generate_struct_class_h
train
def _generate_struct_class_h(self, struct): """Defines an Obj C header file that represents a struct in Stone.""" self._generate_init_imports_h(struct) self._generate_imports_h(self._get_imports_h(struct)) self.emit() self.emit('NS_ASSUME_NONNULL_BEGIN') self.emit() ...
python
{ "resource": "" }
q24515
ObjCTypesBackend._generate_union_class_m
train
def _generate_union_class_m(self, union): """Defines an Obj C implementation file that represents a union in Stone.""" self.emit() self._generate_imports_m( self._get_imports_m( union, default_imports=['DBStoneSerializers', 'DBStoneValidators'])) ...
python
{ "resource": "" }
q24516
ObjCTypesBackend._generate_union_class_h
train
def _generate_union_class_h(self, union): """Defines an Obj C header file that represents a union in Stone.""" self._generate_init_imports_h(union) self._generate_imports_h(self._get_imports_h(union)) self.emit() self.emit('NS_ASSUME_NONNULL_BEGIN') self.emit() ...
python
{ "resource": "" }
q24517
ObjCTypesBackend._generate_struct_cstor
train
def _generate_struct_cstor(self, struct): """Emits struct standard constructor.""" with self.block_func( func=self._cstor_name_from_fields(struct.all_fields), args=fmt_func_args_from_fields(struct.all_fields), return_type='instancetype'): for f...
python
{ "resource": "" }
q24518
ObjCTypesBackend._generate_struct_cstor_default
train
def _generate_struct_cstor_default(self, struct): """Emits struct convenience constructor. Default arguments are omitted.""" if not self._struct_has_defaults(struct): return fields_no_default = [ f for f in struct.all_fields if not f.has_default and not is_nu...
python
{ "resource": "" }
q24519
ObjCTypesBackend._generate_struct_cstor_signature
train
def _generate_struct_cstor_signature(self, struct): """Emits struct standard constructor signature to be used in the struct's header file.""" fields = struct.all_fields self.emit(comment_prefix) description_str = 'Full constructor for the struct (exposes all instance variables).' ...
python
{ "resource": "" }
q24520
ObjCTypesBackend._generate_struct_cstor_signature_default
train
def _generate_struct_cstor_signature_default(self, struct): """Emits struct convenience constructor with default arguments ommitted signature to be used in the struct header file.""" if not self._struct_has_defaults(struct): return fields_no_default = [ f for f i...
python
{ "resource": "" }
q24521
ObjCTypesBackend._generate_union_cstor_funcs
train
def _generate_union_cstor_funcs(self, union): """Emits standard union constructor.""" for field in union.all_fields: enum_field_name = fmt_enum_name(field.name, union) func_args = [] if is_void_type( field.data_type) else fmt_func_args_from_fields([field]) ...
python
{ "resource": "" }
q24522
ObjCTypesBackend._generate_union_cstor_signatures
train
def _generate_union_cstor_signatures(self, union, fields): # pylint: disable=unused-argument """Emits union constructor signatures to be used in the union's header file.""" for field in fields: args = self._cstor_args_from_fields( [field] if not is_void_type(field.data_type)...
python
{ "resource": "" }
q24523
ObjCTypesBackend._generate_union_tag_state
train
def _generate_union_tag_state(self, union): """Emits union tag enum type, which stores union state.""" union_name = fmt_class_prefix(union) tag_type = fmt_enum_name('tag', union) description_str = ('The `{}` enum type represents the possible tag ' 'states with ...
python
{ "resource": "" }
q24524
ObjCTypesBackend._generate_serializer_signatures
train
def _generate_serializer_signatures(self, obj_name): """Emits the signatures of the serializer object's serializing functions.""" serial_signature = fmt_signature( func='serialize', args=fmt_func_args_declaration([( 'instance', '{} *'.format(obj_name))]), ...
python
{ "resource": "" }
q24525
ObjCTypesBackend._cstor_args_from_fields
train
def _cstor_args_from_fields(self, fields, is_struct=False): """Returns a string representing the properly formatted arguments for a constructor.""" if is_struct: args = [(fmt_var(f.name), fmt_type(f.data_type, tag=True, has_default=f.has_default)) for f in fields]
python
{ "resource": "" }
q24526
ObjCTypesBackend._generate_validator
train
def _generate_validator(self, field): """Emits validator if data type has associated validator.""" validator = self._determine_validator_type(field.data_type, fmt_var(field.name), field.has_default) ...
python
{ "resource": "" }
q24527
ObjCTypesBackend._determine_validator_type
train
def _determine_validator_type(self, data_type, value, has_default): """Returns validator string for given data type, else None.""" data_type, nullable = unwrap_nullable(data_type) validator = None if is_list_type(data_type): item_validator = self._determine_validator_type( ...
python
{ "resource": "" }
q24528
ObjCTypesBackend._generate_struct_serializer
train
def _generate_struct_serializer(self, struct): """Emits the serialize method for the serialization object for the given struct.""" struct_name = fmt_class_prefix(struct) with self.block_func( func='serialize', args=fmt_func_args_declaration([('valueObj', ...
python
{ "resource": "" }
q24529
ObjCTypesBackend._generate_struct_deserializer
train
def _generate_struct_deserializer(self, struct): """Emits the deserialize method for the serialization object for the given struct.""" struct_name = fmt_class_prefix(struct) with self.block_func( func='deserialize', args=fmt_func_args_declaration([('valueDict', ...
python
{ "resource": "" }
q24530
ObjCTypesBackend._generate_union_serializer
train
def _generate_union_serializer(self, union): """Emits the serialize method for the serialization object for the given union.""" union_name = fmt_class_prefix(union) with self.block_func( func='serialize', args=fmt_func_args_declaration([('valueObj', ...
python
{ "resource": "" }
q24531
ObjCTypesBackend._generate_union_deserializer
train
def _generate_union_deserializer(self, union): """Emits the deserialize method for the serialization object for the given union.""" union_name = fmt_class_prefix(union) with self.block_func( func='deserialize', args=fmt_func_args_declaration([('valueDict', ...
python
{ "resource": "" }
q24532
ObjCTypesBackend._generate_route_objects_h
train
def _generate_route_objects_h( self, route_schema, # pylint: disable=unused-argument namespace): """Emits header files for Route objects which encapsulate information regarding each route. These objects are passed as parameters when route calls are made.""" ...
python
{ "resource": "" }
q24533
ObjCTypesBackend._generate_union_tag_vars_funcs
train
def _generate_union_tag_vars_funcs(self, union): """Emits the getter methods for retrieving tag-specific state. Setters throw an error in the event an associated tag state variable is accessed without the correct tag state.""" for field in union.all_fields: if not is_void_typ...
python
{ "resource": "" }
q24534
ObjCTypesBackend._generate_struct_properties
train
def _generate_struct_properties(self, fields): """Emits struct instance properties from the given fields.""" for field in fields: doc = self.process_doc(field.doc,
python
{ "resource": "" }
q24535
ObjCTypesBackend._generate_union_properties
train
def _generate_union_properties(self, fields): """Emits union instance properties from the given fields.""" for field in fields: # void types do not need properties to store additional state # information if not is_void_type(field.data_type): doc = self...
python
{ "resource": "" }
q24536
ObjCTypesBackend._generate_union_tag_property
train
def _generate_union_tag_property(self, union): """Emits union instance property representing union state.""" self.emit_wrapped_text( 'Represents the union\'s current tag state.', prefix=comment_prefix) self.emit(
python
{ "resource": "" }
q24537
ObjCTypesBackend._generate_class_comment
train
def _generate_class_comment(self, data_type): """Emits a generic class comment for a union or struct.""" if is_struct_type(data_type): class_type = 'struct' elif is_union_type(data_type): class_type = 'union' else: raise TypeError('Can\'t handle type %...
python
{ "resource": "" }
q24538
ObjCTypesBackend._generate_throw_error
train
def _generate_throw_error(self, name, reason): """Emits a generic error throwing line.""" throw_exc
python
{ "resource": "" }
q24539
PythonClientBackend._generate_route_methods
train
def _generate_route_methods(self, namespaces): """Creates methods for the routes in each namespace. All data types and routes are represented as Python classes.""" self.cur_namespace = None for namespace in namespaces: if namespace.routes:
python
{ "resource": "" }
q24540
PythonClientBackend._generate_routes
train
def _generate_routes(self, namespace): """ Generates Python methods that correspond to routes in the namespace. """ # Hack: needed for _docf() self.cur_namespace = namespace # list of auth_types supported in this base class. # this is passed with the new -w flag ...
python
{ "resource": "" }
q24541
PythonClientBackend._generate_route_helper
train
def _generate_route_helper(self, namespace, route, download_to_file=False): """Generate a Python method that corresponds to a route. :param namespace: Namespace that the route belongs to. :param stone.ir.ApiRoute route: IR node for the route. :param bool download_to_file: Whether a spec...
python
{ "resource": "" }
q24542
PythonClientBackend._generate_route_method_decl
train
def _generate_route_method_decl( self, namespace, route, arg_data_type, request_binary_body, method_name_suffix='', extra_args=None): """Generates the method prototype for a route.""" args = ['self'] if extra_args: args += extra_args if request_binary_...
python
{ "resource": "" }
q24543
PythonClientBackend._generate_docstring_for_func
train
def _generate_docstring_for_func(self, namespace, arg_data_type, result_data_type=None, error_data_type=None, overview=None, extra_request_args=None, extra_return_arg=None, footer=None): """ Ge...
python
{ "resource": "" }
q24544
PythonClientBackend._format_type_in_doc
train
def _format_type_in_doc(self, namespace, data_type): """ Returns a string that can be recognized by Sphinx as a type reference in a docstring. """ if is_void_type(data_type): return 'None' elif is_user_defined_type(data_type):
python
{ "resource": "" }
q24545
ObjCBackend._generate_client_m
train
def _generate_client_m(self, api): """Generates client base implementation file. For each namespace, the client will have an object field that encapsulates each route in the particular namespace.""" self.emit_raw(base_file_comment) import_classes = [self.args.module_name] import...
python
{ "resource": "" }
q24546
ObjCBackend._generate_client_h
train
def _generate_client_h(self, api): """Generates client base header file. For each namespace, the client will have an object field that encapsulates each route in the particular namespace.""" self.emit_raw(stone_warning) self.emit('#import <Foundation/Foundation.h>') import_clas...
python
{ "resource": "" }
q24547
ObjCBackend._generate_routes_m
train
def _generate_routes_m(self, namespace): """Generates implementation file for namespace object that has as methods all routes within the namespace.""" with self.block_m( fmt_routes_class(namespace.name, self.args.auth_type)): init_args = fmt_func_args_declaration([( ...
python
{ "resource": "" }
q24548
ObjCBackend._generate_route_m
train
def _generate_route_m(self, route, namespace, route_args, extra_args, task_type_name, func_suffix): """Generates route method implementation for the given route.""" user_args = list(route_args) transport_args = [ ('route', 'route'), ('arg', 'arg...
python
{ "resource": "" }
q24549
ObjCBackend._generate_route_signature
train
def _generate_route_signature( self, route, namespace, # pylint: disable=unused-argument route_args, extra_args, doc_list, task_type_name, func_suffix): """Generates route method signature for the given route.""" ...
python
{ "resource": "" }
q24550
ParserFactory.get_parser
train
def get_parser(self): """ Returns a ParserFactory with the state reset so it can be used to parse again. :return: ParserFactory """ self.path
python
{ "resource": "" }
q24551
generate_validator_constructor
train
def generate_validator_constructor(ns, data_type): """ Given a Stone data type, returns a string that can be used to construct the appropriate validation object in Python. """ dt, nullable_dt = unwrap_nullable(data_type) if is_list_type(dt): v = generate_func_call( 'bv.List',...
python
{ "resource": "" }
q24552
generate_func_call
train
def generate_func_call(name, args=None, kwargs=None): """ Generates code to call a function. Args: name (str): The function name. args (list[str]): Each positional argument. kwargs (list[tuple]): Each tuple is (arg: str, value: str). If value is None, then the
python
{ "resource": "" }
q24553
PythonTypesBackend._func_args_from_dict
train
def _func_args_from_dict(self, d): """Given a Python dictionary, creates a string representing arguments for invoking a function. All arguments with a value of None are ignored."""
python
{ "resource": "" }
q24554
PythonTypesBackend._generate_struct_class_slots
train
def _generate_struct_class_slots(self, data_type): """Creates a slots declaration for struct classes. Slots are an optimization in Python. They reduce the memory footprint of instances since attributes cannot be added after declaration. """ with self.block('__slots__ =', delim=(...
python
{ "resource": "" }
q24555
PythonTypesBackend._generate_struct_class_init
train
def _generate_struct_class_init(self, data_type): """ Generates constructor. The constructor takes all possible fields as optional arguments. Any argument that is set on construction sets the corresponding field for the instance. """ args = ['self'] for field in ...
python
{ "resource": "" }
q24556
PythonTypesBackend._generate_struct_class_properties
train
def _generate_struct_class_properties(self, ns, data_type): """ Each field of the struct has a corresponding setter and getter. The setter validates the value being set. """ for field in data_type.fields: field_name = fmt_func(field.name) field_name_reserv...
python
{ "resource": "" }
q24557
PythonTypesBackend._generate_custom_annotation_instance
train
def _generate_custom_annotation_instance(self, ns, annotation): """ Generates code to construct an instance of an annotation type object with parameters from the specified annotation. """ annotation_class = class_name_for_annotation_type(annotation.annotation_type, ns) re...
python
{ "resource": "" }
q24558
PythonTypesBackend._generate_enumerated_subtypes_tag_mapping
train
def _generate_enumerated_subtypes_tag_mapping(self, ns, data_type): """ Generates attributes needed for serializing and deserializing structs with enumerated subtypes. These assignments are made after all the Python class definitions to ensure that all references exist. """ ...
python
{ "resource": "" }
q24559
PythonTypesBackend._generate_union_class
train
def _generate_union_class(self, ns, data_type): # type: (ApiNamespace, Union) -> None """Defines a Python class that represents a union in Stone.""" self.emit(self._class_declaration_for_type(ns, data_type)) with self.indent(): self.emit('"""') if data_type.doc: ...
python
{ "resource": "" }
q24560
PythonTypesBackend._generate_union_class_vars
train
def _generate_union_class_vars(self, data_type): """ Adds a _catch_all_ attribute to each class. Also, adds a placeholder attribute for the construction of union members of void type. """ lineno = self.lineno if data_type.catch_all_field: self.emit("_catch_all...
python
{ "resource": "" }
q24561
PythonTypesBackend._generate_union_class_reflection_attributes
train
def _generate_union_class_reflection_attributes(self, ns, data_type): """ Adds a class attribute for each union member assigned to a validator. Also adds an attribute that is a map from tag names to validators. """ class_name = fmt_class(data_type.name) for field in data...
python
{ "resource": "" }
q24562
PythonTypesBackend._generate_union_class_variant_creators
train
def _generate_union_class_variant_creators(self, ns, data_type): """ Each non-symbol, non-any variant has a corresponding class method that can be used to construct a union with that variant selected. """ for field in data_type.fields: if not is_void_type(field.data_t...
python
{ "resource": "" }
q24563
PythonTypesBackend._generate_union_class_get_helpers
train
def _generate_union_class_get_helpers(self, ns, data_type): """ These are the getters used to access the value of a variant, once the tag has been switched on. """ for field in data_type.fields: field_name = fmt_func(field.name) if not is_void_type(field....
python
{ "resource": "" }
q24564
PythonTypesBackend._generate_union_class_symbol_creators
train
def _generate_union_class_symbol_creators(self, data_type): """ Class attributes that represent a symbol are set after the union class definition. """ class_name = fmt_class(data_type.name) lineno = self.lineno for field in data_type.fields: if
python
{ "resource": "" }
q24565
json_encode
train
def json_encode(data_type, obj, caller_permissions=None, alias_validators=None, old_style=False, should_redact=False): """Encodes an object into JSON based on its type. Args: data_type (Validator): Validator for obj. obj (object): Object to be serialized. caller_permissi...
python
{ "resource": "" }
q24566
json_compat_obj_encode
train
def json_compat_obj_encode(data_type, obj, caller_permissions=None, alias_validators=None, old_style=False, for_msgpack=False, should_redact=False): """Encodes an object into a JSON-compatible dict based on its type. Args: data_type (Validator): Validator for obj. obj...
python
{ "resource": "" }
q24567
json_decode
train
def json_decode(data_type, serialized_obj, caller_permissions=None, alias_validators=None, strict=True, old_style=False): """Performs the reverse operation of json_encode. Args: data_type (Validator): Validator for serialized_obj. serialized_obj (str): The JSON string to deseria...
python
{ "resource": "" }
q24568
json_compat_obj_decode
train
def json_compat_obj_decode(data_type, obj, caller_permissions=None, alias_validators=None, strict=True, old_style=False, for_msgpack=False): """ Decodes a JSON-compatible object based on its data type into a representative Python object. Args: ...
python
{ "resource": "" }
q24569
StoneSerializerBase.encode_sub
train
def encode_sub(self, validator, value): # type: (bv.Validator, typing.Any) -> typing.Any """ Callback intended to be called by other ``encode`` methods to delegate encoding of sub-values. Arguments have the same semantics as with the ``encode`` method. """ if isi...
python
{ "resource": "" }
q24570
PythonPrimitiveToStoneDecoder.determine_struct_tree_subtype
train
def determine_struct_tree_subtype(self, data_type, obj): """ Searches through the JSON-object-compatible dict using the data type definition to determine which of the enumerated subtypes `obj` is. """ if '.tag' not in obj: raise bv.ValidationError("missing '.tag' key"...
python
{ "resource": "" }
q24571
PythonPrimitiveToStoneDecoder.make_stone_friendly
train
def make_stone_friendly(self, data_type, val, validate): """ Convert a Python object to a type that will pass validation by its validator. Validation by ``alias_validators`` is performed even if ``validate`` is false. """ if isinstance(data_type, bv.Timestamp): ...
python
{ "resource": "" }
q24572
fmt_camel
train
def fmt_camel(name): """ Converts name to lower camel case. Words are identified by capitalization, dashes, and underscores. """ words = split_words(name)
python
{ "resource": "" }
q24573
check_route_name_conflict
train
def check_route_name_conflict(namespace): """ Check name conflicts among generated route definitions. Raise a runtime exception when a conflict is encountered. """ route_by_name = {} for route in namespace.routes: route_name = fmt_func(route.name, version=route.version) if route...
python
{ "resource": "" }
q24574
generate_imports_for_referenced_namespaces
train
def generate_imports_for_referenced_namespaces( backend, namespace, insert_type_ignore=False): # type: (Backend, ApiNamespace, bool) -> None """ Both the true Python backend and the Python PEP 484 Type Stub backend have to perform the same imports. :param insert_type_ignore: add a MyPy type...
python
{ "resource": "" }
q24575
prefix_with_ns_if_necessary
train
def prefix_with_ns_if_necessary(name, name_ns, source_ns): # type: (typing.Text, ApiNamespace, ApiNamespace) -> typing.Text """ Returns a name that can be used to reference `name` in namespace `name_ns` from `source_ns`. If `source_ns` and
python
{ "resource": "" }
q24576
class_name_for_data_type
train
def class_name_for_data_type(data_type, ns=None): """ Returns the name of the Python class that maps to a user-defined type. The name is identical to the name in the spec. If ``ns`` is set to a Namespace and the namespace of `data_type` does not match, then a namespace prefix is added to the return...
python
{ "resource": "" }
q24577
class_name_for_annotation_type
train
def class_name_for_annotation_type(annotation_type, ns=None): """ Same as class_name_for_data_type, but works with annotation types. """ assert isinstance(annotation_type, AnnotationType) name = fmt_class(annotation_type.name)
python
{ "resource": "" }
q24578
specs_to_ir
train
def specs_to_ir(specs, version='0.1b1', debug=False, route_whitelist_filter=None): """ Converts a collection of Stone specifications into the intermediate representation used by Stone backends. The process is: Lexer -> Parser -> Semantic Analyzer -> IR Generator. The code is structured as: ...
python
{ "resource": "" }
q24579
fmt_type
train
def fmt_type(data_type): """ Returns a JSDoc annotation for a data type. May contain a union of enumerated subtypes. """ if is_struct_type(data_type) and data_type.has_enumerated_subtypes(): possible_types = [] possible_subtypes = data_type.get_all_subtypes_with_tags() for _,...
python
{ "resource": "" }
q24580
TSDTypesBackend._parse_extra_args
train
def _parse_extra_args(self, api, extra_args_raw): """ Parses extra arguments into a map keyed on particular data types. """ extra_args = {} def invalid(msg, extra_arg_raw): print('Invalid --extra-arg:%s: %s' % (msg, extra_arg_raw), file=sys.stderr) ...
python
{ "resource": "" }
q24581
TSDTypesBackend._generate_type
train
def _generate_type(self, data_type, indent_spaces, extra_args): """ Generates a TypeScript type for the given type. """ if is_alias(data_type):
python
{ "resource": "" }
q24582
TSDTypesBackend._generate_alias_type
train
def _generate_alias_type(self, alias_type): """ Generates a TypeScript type for a stone alias. """ namespace = alias_type.namespace self.emit('export type %s = %s;' % (fmt_type_name(alias_type, namespace),
python
{ "resource": "" }
q24583
TSDTypesBackend._generate_struct_type
train
def _generate_struct_type(self, struct_type, indent_spaces, extra_parameters): """ Generates a TypeScript interface for a stone struct. """ namespace = struct_type.namespace if struct_type.doc: self._emit_tsdoc_header(struct_type.doc) parent_type = struct_type...
python
{ "resource": "" }
q24584
TSDTypesBackend._generate_union_type
train
def _generate_union_type(self, union_type, indent_spaces): """ Generates a TypeScript interface for a stone union. """ # Emit an interface for each variant. TypeScript 2.0 supports these tagged unions. # https://github.com/Microsoft/TypeScript/wiki/What%27s-new-in-TypeScript#tagg...
python
{ "resource": "" }
q24585
CodeBackend.generate_multiline_list
train
def generate_multiline_list( self, items, # type: typing.List[typing.Text] before='', # type: typing.Text after='', # type: typing.Text delim=('(', ')'), # type: DelimTuple compact=True, # type: bool sep=',', ...
python
{ "resource": "" }
q24586
CodeBackend.block
train
def block( self, before='', # type: typing.Text after='', # type: typing.Text delim=('{', '}'), # type: DelimTuple dent=None, # type: typing.Optional[int] allman=False # type: bool ): # type: (...) -> typing.Iterator[None] ...
python
{ "resource": "" }
q24587
fmt_type_name
train
def fmt_type_name(data_type, inside_namespace=None): """ Produces a TypeScript type name for the given data type. inside_namespace should be set to the namespace that the reference occurs in, or None if this parameter is not relevant. """ if is_user_defined_type(data_type) or is_alias(data_type)...
python
{ "resource": "" }
q24588
fmt_type
train
def fmt_type(data_type, inside_namespace=None): """ Returns a TypeScript type annotation for a data type. May contain a union of enumerated subtypes. inside_namespace should be set to the namespace that the type reference occurs in, or None if this parameter is not relevant. """ if is_struct...
python
{ "resource": "" }
q24589
fmt_tag
train
def fmt_tag(cur_namespace, tag, val): """ Processes a documentation reference. """ if tag == 'type': fq_val = val if '.' not in val and cur_namespace is not None: fq_val = cur_namespace.name + '.' + fq_val return fq_val elif tag == 'route': if ':' in val: ...
python
{ "resource": "" }
q24590
parse_data_types_from_doc_ref
train
def parse_data_types_from_doc_ref(api, doc, namespace_context, ignore_missing_entries=False): """ Given a documentation string, parse it and return all references to other data types. If there are references to routes, include also the data types of those routes. Args: - api: The API containing...
python
{ "resource": "" }
q24591
parse_route_name_and_version
train
def parse_route_name_and_version(route_repr): """ Parse a route representation string and return the route name and version number. :param route_repr: Route representation string. :return: A tuple containing route name and version number. """ if ':' in route_repr: route_name, version =...
python
{ "resource": "" }
q24592
parse_data_types_and_routes_from_doc_ref
train
def parse_data_types_and_routes_from_doc_ref( api, doc, namespace_context, ignore_missing_entries=False ): """ Given a documentation string, parse it and return all references to other data types and routes. Args: - api: The API containing this doc ref. - doc: The documentation ...
python
{ "resource": "" }
q24593
IRGenerator.generate_IR
train
def generate_IR(self): """Parses the text of each spec and returns an API description. Returns None if an error was encountered during parsing.""" raw_api = [] for partial_ast in self._partial_asts: namespace_ast_node = self._extract_namespace_ast_node(partial_ast) ...
python
{ "resource": "" }
q24594
IRGenerator._extract_namespace_ast_node
train
def _extract_namespace_ast_node(self, desc): """ Checks that the namespace is declared first in the spec, and that only one namespace is declared. Args: desc (List[stone.stone.parser.ASTNode]): All AST nodes in a spec file in the order they were defined. ...
python
{ "resource": "" }
q24595
IRGenerator._add_imports_to_env
train
def _add_imports_to_env(self, raw_api): """ Scans raw parser output for import declarations. Checks if the imports are valid, and then creates a reference to the namespace in the environment. Args: raw_api (Tuple[Namespace, List[stone.stone.parser._Element]]): ...
python
{ "resource": "" }
q24596
IRGenerator._create_type
train
def _create_type(self, env, item): """Create a forward reference for a union or struct.""" if item.name in env: existing_dt = env[item.name] raise InvalidSpec( 'Symbol %s already defined (%s:%d).' % (quote(item.name), existing_dt._ast_node.path, ...
python
{ "resource": "" }
q24597
IRGenerator._merge_patches
train
def _merge_patches(self): """Injects object patches into their original object definitions.""" for patched_item, patched_namespace in self._patch_data_by_canonical_name.values(): patched_item_base_name = self._get_base_name(patched_item.name, patched_namespace.name) if patched_it...
python
{ "resource": "" }
q24598
IRGenerator._check_patch_type_mismatch
train
def _check_patch_type_mismatch(self, patched_item, existing_item): """Enforces that each patch has a corresponding, already-defined data type.""" def raise_mismatch_error(patched_item, existing_item, data_type_name): error_msg = ('Type mismatch. Patch {} corresponds to pre-existing ' ...
python
{ "resource": "" }
q24599
IRGenerator._check_field_names_unique
train
def _check_field_names_unique(self, existing_item, patched_item): """Enforces that patched fields don't already exist.""" existing_fields_by_name = {f.name: f for f in existing_item.fields} for patched_field in patched_item.fields: if patched_field.name in existing_fields_by_name.key...
python
{ "resource": "" }