docstring stringlengths 52 499 | function stringlengths 67 35.2k | __index_level_0__ int64 52.6k 1.16M |
|---|---|---|
Translates an apiserving REST response so it's ready to return.
Currently, the only thing that needs to be fixed here is indentation,
so it's consistent with what the live app will return.
Args:
response_body: A string containing the backend response.
Returns:
A reformatted version of the... | def transform_rest_response(self, response_body):
body_json = json.loads(response_body)
return json.dumps(body_json, indent=1, sort_keys=True) | 516,649 |
Handle a request error, converting it to a WSGI response.
Args:
orig_request: An ApiRequest, the original request from the user.
error: A RequestError containing information about the error.
start_response: A function with semantics defined in PEP-333.
Returns:
A string containing the ... | def _handle_request_error(self, orig_request, error, start_response):
headers = [('Content-Type', 'application/json')]
status_code = error.status_code()
body = error.rest_error()
response_status = '%d %s' % (status_code,
httplib.responses.get(status_code,
... | 516,650 |
Write given content to a file in a given directory.
Args:
output_path: The directory to store the file in.
name: The name of the file to store the content in.
content: The content to write to the file.close
Returns:
The full path to the written file. | def _WriteFile(output_path, name, content):
path = os.path.join(output_path, name)
with open(path, 'wb') as f:
f.write(content)
return path | 516,651 |
Generate an api file.
Args:
args: An argparse.Namespace object to extract parameters from.
api_func: A function that generates and returns an API configuration
for a list of services. | def _GenApiConfigCallback(args, api_func=GenApiConfig):
service_configs = api_func(args.service,
hostname=args.hostname,
application_path=args.application)
for api_name_version, config in service_configs.iteritems():
_WriteFile(args.output, api_name_... | 516,659 |
Generate discovery docs and client libraries to files.
Args:
args: An argparse.Namespace object to extract parameters from.
client_func: A function that generates client libraries and stores them to
files, accepting a list of service names, a client library language,
an output directory, a build ... | def _GetClientLibCallback(args, client_func=_GetClientLib):
client_paths = client_func(
args.service, args.language, args.output, args.build_system,
hostname=args.hostname, application_path=args.application)
for client_path in client_paths:
print 'API client library written to %s' % client_path | 516,660 |
Generate discovery docs to files.
Args:
args: An argparse.Namespace object to extract parameters from
discovery_func: A function that generates discovery docs and stores them to
files, accepting a list of service names, a discovery doc format, and an
output directory. | def _GenDiscoveryDocCallback(args, discovery_func=_GenDiscoveryDoc):
discovery_paths = discovery_func(args.service, args.output,
hostname=args.hostname,
application_path=args.application)
for discovery_path in discovery_paths:
print 'API d... | 516,661 |
Generate OpenAPI (Swagger) specs to files.
Args:
args: An argparse.Namespace object to extract parameters from
openapi_func: A function that generates OpenAPI specs and stores them to
files, accepting a list of service names and an output directory. | def _GenOpenApiSpecCallback(args, openapi_func=_GenOpenApiSpec):
openapi_paths = openapi_func(args.service, args.output,
hostname=args.hostname,
application_path=args.application,
x_google_api_name=args.x_google_api_name)
... | 516,662 |
Generate a client library to file.
Args:
args: An argparse.Namespace object to extract parameters from
client_func: A function that generates client libraries and stores them to
files, accepting a path to a discovery doc, a client library language, an
output directory, and a build system for the ... | def _GenClientLibCallback(args, client_func=_GenClientLib):
client_path = client_func(args.discovery_doc[0], args.language, args.output,
args.build_system)
print 'API client library written to %s' % client_path | 516,663 |
Create an argument parser.
Args:
prog: The name of the program to use when outputting help text.
Returns:
An argparse.ArgumentParser built to specification. | def MakeParser(prog):
def AddStandardOptions(parser, *args):
if 'application' in args:
parser.add_argument('-a', '--application', default='.',
help='The path to the Python App Engine App')
if 'format' in args:
# This used to be a valid option, allowing the user t... | 516,664 |
Create a ServerRequestException from a given urllib2.HTTPError.
Args:
http_error: The HTTPError that the ServerRequestException will be
based on. | def __init__(self, http_error):
error_details = None
error_response = None
if http_error.fp:
try:
error_response = http_error.fp.read()
error_body = json.loads(error_response)
error_details = ['%s: %s' % (detail['message'], detail['debug_info'])
fo... | 516,667 |
Utility to generate enum classes used by annotations.
Args:
docstring: Docstring for the generated enum class.
*names: Enum names.
Returns:
A class that contains enum names as attributes. | def _Enum(docstring, *names):
enums = dict(zip(names, range(len(names))))
reverse = dict((value, key) for key, value in enums.iteritems())
enums['reverse_mapping'] = reverse
enums['__doc__'] = docstring
return type('Enum', (object,), enums) | 516,671 |
Check that the type of an object is acceptable.
Args:
value: The object whose type is to be checked.
check_type: The type that the object must be an instance of.
name: Name of the object, to be placed in any error messages.
allow_none: True if value can be None, false if not.
Raises:
TypeError... | def _CheckType(value, check_type, name, allow_none=True):
if value is None and allow_none:
return
if not isinstance(value, check_type):
raise TypeError('%s type doesn\'t match %s.' % (name, check_type)) | 516,672 |
Constructor for ApiFrontEndLimitRule.
Args:
match: string, the matching rule that defines this traffic segment.
qps: int, the aggregate QPS for this segment.
user_qps: int, the per-end-user QPS for this segment.
daily: int, the aggregate daily maximum for this segment.
analytics_id: s... | def __init__(self, match=None, qps=None, user_qps=None, daily=None,
analytics_id=None):
_CheckType(match, basestring, 'match')
_CheckType(qps, int, 'qps')
_CheckType(user_qps, int, 'user_qps')
_CheckType(daily, int, 'daily')
_CheckType(analytics_id, basestring, 'analytics_id')
... | 516,684 |
Converts the field variant type into a string describing the parameter.
Args:
field: An instance of a subclass of messages.Field.
Returns:
A string corresponding to the variant enum of the field, with a few
exceptions. In the case of signed ints, the 's' is dropped; for the BOOL
va... | def __field_to_parameter_type(self, field):
# We use lowercase values for types (e.g. 'string' instead of 'STRING').
variant = field.variant
if variant == messages.Variant.MESSAGE:
raise TypeError('A message variant can\'t be used in a parameter.')
custom_variant_map = {
messages.Var... | 516,691 |
Describes the parameters and body of the request.
Args:
request_kind: The type of request being made.
message_type: messages.Message or ResourceContainer class. The message to
describe.
method_id: string, Unique method identifier (e.g. 'myapi.items.method')
path: string, HTTP path... | def __request_message_descriptor(self, request_kind, message_type, method_id,
path):
descriptor = {}
params, param_order = self.__params_descriptor(message_type, request_kind,
path, method_id)
if isinstance(message_... | 516,700 |
Describes a method.
Args:
service: endpoints.Service, Implementation of the API as a service.
method_info: _MethodInfo, Configuration for the method.
rosy_method: string, ProtoRPC method name prefixed with the
name of the service.
protorpc_method_info: protorpc.remote._RemoteMethodI... | def __method_descriptor(self, service, method_info,
rosy_method, protorpc_method_info):
descriptor = {}
request_message_type = (resource_container.ResourceContainer.
get_request_message(protorpc_method_info.remote))
request_kind = self.__get_reques... | 516,701 |
Descriptor for the all the JSON Schema used.
Args:
services: List of protorpc.remote.Service instances implementing an
api/version.
Returns:
Dictionary containing all the JSON Schema used in the service. | def __schema_descriptor(self, services):
methods_desc = {}
for service in services:
protorpc_methods = service.all_remote_methods()
for protorpc_method_name in protorpc_methods.iterkeys():
rosy_method = '%s.%s' % (service.__name__, protorpc_method_name)
method_id = self.__id_fr... | 516,702 |
Builds a description of an API.
Args:
services: List of protorpc.remote.Service instances implementing an
api/version.
Returns:
The _ApiInfo object to use for the API that the given services implement.
Raises:
ApiConfigurationError: If there's something wrong with the API
... | def __get_merged_api_info(self, services):
merged_api_info = services[0].api_info
# Verify that, if there are multiple classes here, they're allowed to
# implement the same API.
for service in services[1:]:
if not merged_api_info.is_same_api(service.api_info):
raise api_exceptions.Ap... | 516,703 |
Builds an auth descriptor from API info.
Args:
api_info: An _ApiInfo object.
Returns:
A dictionary with 'allowCookieAuth' and/or 'blockedRegions' keys. | def __auth_descriptor(self, api_info):
if api_info.auth is None:
return None
auth_descriptor = {}
if api_info.auth.allow_cookie_auth is not None:
auth_descriptor['allowCookieAuth'] = api_info.auth.allow_cookie_auth
if api_info.auth.blocked_regions:
auth_descriptor['blockedRegions... | 516,704 |
Builds a frontend limit descriptor from API info.
Args:
api_info: An _ApiInfo object.
Returns:
A dictionary with frontend limit information. | def __frontend_limit_descriptor(self, api_info):
if api_info.frontend_limits is None:
return None
descriptor = {}
for propname, descname in (('unregistered_user_qps', 'unregisteredUserQps'),
('unregistered_qps', 'unregisteredQps'),
('... | 516,705 |
Builds a frontend limit rules descriptor from API info.
Args:
api_info: An _ApiInfo object.
Returns:
A list of dictionaries with frontend limit rules information. | def __frontend_limit_rules_descriptor(self, api_info):
if not api_info.frontend_limits.rules:
return None
rules = []
for rule in api_info.frontend_limits.rules:
descriptor = {}
for propname, descname in (('match', 'match'),
('qps', 'qps'),
... | 516,706 |
Gets a default configuration for a service.
Args:
api_info: _ApiInfo object for this service.
hostname: string, Hostname of the API, to override the value set on the
current service. Defaults to None.
Returns:
A dictionary with the default configuration. | def get_descriptor_defaults(self, api_info, hostname=None):
hostname = (hostname or endpoints_util.get_app_hostname() or
api_info.hostname)
protocol = 'http' if ((hostname and hostname.startswith('localhost')) or
endpoints_util.is_running_on_devserver()) else 'http... | 516,708 |
JSON dict description of a protorpc.remote.Service in API format.
Args:
services: Either a single protorpc.remote.Service or a list of them
that implements an api/version.
hostname: string, Hostname of the API, to override the value set on the
current service. Defaults to None.
Ret... | def get_config_dict(self, services, hostname=None):
if not isinstance(services, (tuple, list)):
services = [services]
# The type of a class that inherits from remote.Service is actually
# remote._ServiceClass, thanks to metaclass strangeness.
# pylint: disable=protected-access
endpoints_u... | 516,709 |
JSON string description of a protorpc.remote.Service in API format.
Args:
services: Either a single protorpc.remote.Service or a list of them
that implements an api/version.
hostname: string, Hostname of the API, to override the value set on the
current service. Defaults to None.
R... | def pretty_print_config_to_json(self, services, hostname=None):
descriptor = self.get_config_dict(services, hostname)
return json.dumps(descriptor, sort_keys=True, indent=2,
separators=(',', ': ')) | 516,710 |
Converts the field variant type into a tuple describing the parameter.
Args:
field: An instance of a subclass of messages.Field.
Returns:
A tuple with the type and format of the field, respectively.
Raises:
TypeError: if the field variant is a message variant. | def __field_to_parameter_type_and_format(self, field):
# We use lowercase values for types (e.g. 'string' instead of 'STRING').
variant = field.variant
if variant == messages.Variant.MESSAGE:
raise TypeError('A message variant cannot be used in a parameter.')
# Note that the 64-bit integers ... | 516,712 |
Returns default value of field if it has one.
Args:
field: A simple field.
Returns:
The default value of the field, if any exists, with the exception of an
enum field, which will have its value cast to a string. | def __parameter_default(self, field):
if field.default:
if isinstance(field, messages.EnumField):
return field.default.name
elif isinstance(field, messages.BooleanField):
# The Python standard representation of a boolean value causes problems
# when generating client code.
... | 516,713 |
Returns enum descriptor of a parameter if it is an enum.
An enum descriptor is a list of keys.
Args:
param: A simple field.
Returns:
The enum descriptor for the field, if it's an enum descriptor, else
returns None. | def __parameter_enum(self, param):
if isinstance(param, messages.EnumField):
return [enum_entry[0] for enum_entry in sorted(
param.type.to_dict().items(), key=lambda v: v[1])] | 516,714 |
Creates descriptor for a parameter.
Args:
param: The parameter to be described.
Returns:
Dictionary containing a descriptor for the parameter. | def __parameter_descriptor(self, param):
descriptor = {}
param_type, param_format = self.__field_to_parameter_type_and_format(param)
# Required
if param.required:
descriptor['required'] = True
# Type
descriptor['type'] = param_type
# Format (optional)
if param_format:
... | 516,715 |
Describe the order of path parameters.
Args:
message_type: messages.Message class, Message with parameters to describe.
path: string, HTTP path to method.
is_params_class: boolean, Whether the message represents URL parameters.
Returns:
Descriptor list for the parameter order. | def __params_order_descriptor(self, message_type, path, is_params_class=False):
path_params = []
query_params = []
path_parameter_dict = self.__get_path_parameters(path)
for field in sorted(message_type.all_fields(), key=lambda f: f.number):
matched_path_parameters = path_parameter_dict.get(... | 516,719 |
Describes a method.
Args:
service: endpoints.Service, Implementation of the API as a service.
method_info: _MethodInfo, Configuration for the method.
protorpc_method_info: protorpc.remote._RemoteMethodInfo, ProtoRPC
description of the method.
Returns:
Dictionary describing the ... | def __method_descriptor(self, service, method_info,
protorpc_method_info):
descriptor = {}
request_message_type = (resource_container.ResourceContainer.
get_request_message(protorpc_method_info.remote))
request_kind = self.__get_request_kind(method... | 516,722 |
Describes a resource.
Args:
resource_path: string, the path of the resource (e.g., 'entries.items')
methods: list of tuples of type
(endpoints.Service, protorpc.remote._RemoteMethodInfo), the methods
that serve this resource.
Returns:
Dictionary describing the resource. | def __resource_descriptor(self, resource_path, methods):
descriptor = {}
method_map = {}
sub_resource_index = collections.defaultdict(list)
sub_resource_map = {}
resource_path_tokens = resource_path.split('.')
for service, protorpc_meth_info in methods:
method_info = getattr(protorpc... | 516,723 |
Builds a description of an API.
Args:
services: List of protorpc.remote.Service instances implementing an
api/version.
Returns:
The _ApiInfo object to use for the API that the given services implement. | def __get_merged_api_info(self, services):
base_paths = sorted(set(s.api_info.base_path for s in services))
if len(base_paths) != 1:
raise api_exceptions.ApiConfigurationError(
'Multiple base_paths found: {!r}'.format(base_paths))
names_versions = sorted(set(
(s.api_info.name, s... | 516,725 |
Gets a default configuration for a service.
Args:
api_info: _ApiInfo object for this service.
hostname: string, Hostname of the API, to override the value set on the
current service. Defaults to None.
Returns:
A dictionary with the default configuration. | def get_descriptor_defaults(self, api_info, hostname=None):
if self.__request:
hostname = self.__request.reconstruct_hostname()
protocol = self.__request.url_scheme
else:
hostname = (hostname or util.get_app_hostname() or
api_info.hostname)
protocol = 'http' if ((h... | 516,727 |
JSON dict description of a protorpc.remote.Service in discovery format.
Args:
services: Either a single protorpc.remote.Service or a list of them
that implements an api/version.
hostname: string, Hostname of the API, to override the value set on the
current service. Defaults to None.
... | def get_discovery_doc(self, services, hostname=None):
if not isinstance(services, (tuple, list)):
services = [services]
# The type of a class that inherits from remote.Service is actually
# remote._ServiceClass, thanks to metaclass strangeness.
# pylint: disable=protected-access
util.ch... | 516,728 |
Given a list of headers, put them into environ based on PEP-333.
This converts headers to uppercase, prefixes them with 'HTTP_', and
converts dashes to underscores before adding them to the environ dict.
Args:
headers: A list of (header, value) tuples. The HTTP headers to add to the
environment.
... | def put_headers_in_environ(headers, environ):
for key, value in headers:
environ['HTTP_%s' % key.upper().replace('-', '_')] = value | 516,733 |
Verify that objects in list are of the allowed type or raise TypeError.
Args:
objects: The list of objects to check.
allowed_type: The allowed type of items in 'settings'.
name: Name of the list of objects, added to the exception.
allow_none: If set, None is also allowed.
Raises:
TypeError: if... | def check_list_type(objects, allowed_type, name, allow_none=True):
if objects is None:
if not allow_none:
raise TypeError('%s is None, which is not allowed.' % name)
return objects
if not isinstance(objects, (tuple, list)):
raise TypeError('%s is not a list.' % name)
if not all(isinstance(i, ... | 516,736 |
Convert snake_case to headlessCamelCase.
Args:
snake_string: The string to be converted.
Returns:
The input string converted to headlessCamelCase. | def snake_case_to_headless_camel_case(snake_string):
return ''.join([snake_string.split('_')[0]] +
list(sub_string.capitalize()
for sub_string in snake_string.split('_')[1:])) | 516,737 |
Initializes an instance of the DiscoveryService.
Args:
config_manager: An instance of ApiConfigManager.
backend: An _ApiServer instance for API config generation. | def __init__(self, config_manager, backend):
self._config_manager = config_manager
self._backend = backend | 516,740 |
Sends an HTTP 200 json success response.
This calls start_response and returns the response body.
Args:
response: A string containing the response body to return.
start_response: A function with semantics defined in PEP-333.
Returns:
A string, the response body. | def _send_success_response(self, response, start_response):
headers = [('Content-Type', 'application/json; charset=UTF-8')]
return util.send_wsgi_response('200 OK', headers, response, start_response) | 516,741 |
Sends back HTTP response with API directory.
This calls start_response and returns the response body. It will return
the discovery doc for the requested api/version.
Args:
request: An ApiRequest, the transformed request sent to the Discovery API.
start_response: A function with semantics defi... | def _get_rest_doc(self, request, start_response):
api = request.body_json['api']
version = request.body_json['version']
generator = discovery_generator.DiscoveryGenerator(request=request)
services = [s for s in self._backend.api_services if
s.api_info.name == api and s.api_info.api... | 516,742 |
Generate an API config with a specific root hostname.
This uses the backend object and the ApiConfigGenerator to create an API
config specific to the hostname of the incoming request. This allows for
flexible API configs for non-standard environments, such as localhost.
Args:
request: An ApiRequ... | def _generate_api_config_with_root(self, request):
actual_root = self._get_actual_root(request)
generator = api_config.ApiConfigGenerator()
api = request.body_json['api']
version = request.body_json['version']
lookup_key = (api, version)
service_factories = self._backend.api_name_version_m... | 516,743 |
Sends HTTP response containing the API directory.
This calls start_response and returns the response body.
Args:
request: An ApiRequest, the transformed request sent to the Discovery API.
start_response: A function with semantics defined in PEP-333.
Returns:
A string containing the resp... | def _list(self, request, start_response):
configs = []
generator = directory_list_generator.DirectoryListGenerator(request)
for config in self._config_manager.configs.itervalues():
if config != self.API_CONFIG:
configs.append(config)
directory = generator.pretty_print_config_to_json(c... | 516,745 |
Returns the result of a discovery service request.
This calls start_response and returns the response body.
Args:
path: A string containing the API path (the portion of the path
after /_ah/api/).
request: An ApiRequest, the transformed request sent to the Discovery API.
start_respons... | def handle_discovery_request(self, path, request, start_response):
if path == self._GET_REST_API:
return self._get_rest_doc(request, start_response)
elif path == self._GET_RPC_API:
error_msg = ('RPC format documents are no longer supported with the '
'Endpoints Framework for ... | 516,746 |
Constructor.
Args:
environ: An environ dict for the request as defined in PEP-333.
Raises:
ValueError: If the path for the request is invalid. | def __init__(self, environ, base_paths=None):
self.headers = util.get_headers_from_environ(environ)
self.http_method = environ['REQUEST_METHOD']
self.url_scheme = environ['wsgi.url_scheme']
self.server = environ['SERVER_NAME']
self.port = environ['SERVER_PORT']
self.path = environ['PATH_INF... | 516,747 |
Process the body of the HTTP request.
If the body is valid JSON, return the JSON as a dict.
Else, convert the key=value format to a dict and return that.
Args:
body: The body of the HTTP request. | def _process_req_body(self, body):
try:
return json.loads(body)
except ValueError:
return urlparse.parse_qs(body, keep_blank_values=True) | 516,748 |
Reconstruct the relative URL of this request.
This is based on the URL reconstruction code in Python PEP 333:
http://www.python.org/dev/peps/pep-0333/#url-reconstruction. Rebuild the
URL from the pieces available in the environment.
Args:
environ: An environ dict for the request as defined in P... | def _reconstruct_relative_url(self, environ):
url = urllib.quote(environ.get('SCRIPT_NAME', ''))
url += urllib.quote(environ.get('PATH_INFO', ''))
if environ.get('QUERY_STRING'):
url += '?' + environ['QUERY_STRING']
return url | 516,749 |
Reconstruct the hostname of a request.
This is based on the URL reconstruction code in Python PEP 333:
http://www.python.org/dev/peps/pep-0333/#url-reconstruction. Rebuild the
hostname from the pieces available in the environment.
Args:
port_override: str, An override for the port on the return... | def reconstruct_hostname(self, port_override=None):
url = self.server
port = port_override or self.port
if port and ((self.url_scheme == 'https' and str(port) != '443') or
(self.url_scheme != 'https' and str(port) != '80')):
url += ':{0}'.format(port)
return url | 516,750 |
Reconstruct the full URL of a request.
This is based on the URL reconstruction code in Python PEP 333:
http://www.python.org/dev/peps/pep-0333/#url-reconstruction. Rebuild the
hostname from the pieces available in the environment.
Args:
port_override: str, An override for the port on the return... | def reconstruct_full_url(self, port_override=None):
return '{0}://{1}{2}'.format(self.url_scheme,
self.reconstruct_hostname(port_override),
self.relative_url) | 516,751 |
Recursive method to add relative paths for any $ref objects.
Args:
prop_dict: The property dict to alter.
Side Effects:
Alters prop_dict in-place. | def _add_def_paths(self, prop_dict):
for prop_key, prop_value in prop_dict.iteritems():
if prop_key == '$ref' and not 'prop_value'.startswith('#'):
prop_dict[prop_key] = '#/definitions/' + prop_dict[prop_key]
elif isinstance(prop_value, dict):
self._add_def_paths(prop_value) | 516,754 |
Return an operation id for a service method.
Args:
service_name: The name of the service.
protorpc_method_name: The ProtoRPC method name.
Returns:
A string representing the operation id. | def _construct_operation_id(self, service_name, protorpc_method_name):
# camelCase the ProtoRPC method name
method_name_camel = util.snake_case_to_headless_camel_case(
protorpc_method_name)
return '{0}_{1}'.format(service_name, method_name_camel) | 516,755 |
Converts the field variant type into a tuple describing the parameter.
Args:
field: An instance of a subclass of messages.Field.
Returns:
A tuple with the type and format of the field, respectively.
Raises:
TypeError: if the field variant is a message variant. | def __field_to_parameter_type_and_format(self, field):
# We use lowercase values for types (e.g. 'string' instead of 'STRING').
variant = field.variant
if variant == messages.Variant.MESSAGE:
raise TypeError('A message variant can\'t be used in a parameter.')
# Note that the 64-bit integers ... | 516,756 |
Returns default value of field if it has one.
Args:
field: A simple field.
Returns:
The default value of the field, if any exists, with the exception of an
enum field, which will have its value cast to a string. | def __parameter_default(self, field):
if field.default:
if isinstance(field, messages.EnumField):
return field.default.name
else:
return field.default | 516,757 |
Creates descriptor for a parameter.
Args:
param: The parameter to be described.
Returns:
Dictionary containing a descriptor for the parameter. | def __non_body_parameter_descriptor(self, param):
descriptor = {}
descriptor['name'] = param.name
param_type, param_format = self.__field_to_parameter_type_and_format(param)
# Required
if param.required:
descriptor['required'] = True
# Type
descriptor['type'] = param_type
... | 516,758 |
Describes the parameters and body of the request.
Args:
request_kind: The type of request being made.
message_type: messages.Message or ResourceContainer class. The message to
describe.
method_id: string, Unique method identifier (e.g. 'myapi.items.method')
path: string, HTTP path... | def __request_message_descriptor(self, request_kind, message_type, method_id,
path):
if isinstance(message_type, resource_container.ResourceContainer):
base_message_type = message_type.body_message_class()
if (request_kind == self.__NO_BODY and
base_mess... | 516,764 |
Describes the response.
Args:
message_type: messages.Message class, The message to describe.
method_id: string, Unique method identifier (e.g. 'myapi.items.method')
Returns:
Dictionary describing the response. | def __response_message_descriptor(self, message_type, method_id):
# Skeleton response descriptor, common to all response objects
descriptor = {'200': {'description': 'A successful response'}}
if message_type != message_types.VoidMessage():
self.__parser.add_message(message_type.__class__)
... | 516,766 |
Describes the metric costs for a call.
Args:
metric_costs: Dict of metric definitions to the integer cost value against
that metric.
Returns:
A dict descriptor describing the Quota limits for the endpoint. | def __x_google_quota_descriptor(self, metric_costs):
return {
'metricCosts': {
metric: cost for (metric, cost) in metric_costs.items()
}
} if metric_costs else None | 516,767 |
Describes the quota limit definitions for an API.
Args:
limit_definitions: List of endpoints.LimitDefinition tuples
Returns:
A dict descriptor of the API's quota limit definitions. | def __x_google_quota_definitions_descriptor(self, limit_definitions):
if not limit_definitions:
return None
definitions_list = [{
'name': ld.metric_name,
'metric': ld.metric_name,
'unit': '1/min/{project}',
'values': {'STANDARD': ld.default_limit},
'displayNam... | 516,768 |
Describes a method.
Args:
service: endpoints.Service, Implementation of the API as a service.
method_info: _MethodInfo, Configuration for the method.
operation_id: string, Operation ID of the method
protorpc_method_info: protorpc.remote._RemoteMethodInfo, ProtoRPC
description of the... | def __method_descriptor(self, service, method_info, operation_id,
protorpc_method_info, security_definitions):
descriptor = {}
request_message_type = (resource_container.ResourceContainer.
get_request_message(protorpc_method_info.remote))
request_k... | 516,769 |
Create a descriptor for the security definitions.
Args:
issuers: dict, mapping issuer names to Issuer tuples
Returns:
The dict representing the security definitions descriptor. | def __security_definitions_descriptor(self, issuers):
if not issuers:
result = {
_DEFAULT_SECURITY_DEFINITION: {
'authorizationUrl': '',
'flow': 'implicit',
'type': 'oauth2',
'x-google-issuer': 'https://accounts.google.com',
... | 516,771 |
Gets a default configuration for a service.
Args:
api_info: _ApiInfo object for this service.
hostname: string, Hostname of the API, to override the value set on the
current service. Defaults to None.
Returns:
A dictionary with the default configuration. | def get_descriptor_defaults(self, api_info, hostname=None, x_google_api_name=False):
hostname = (hostname or util.get_app_hostname() or
api_info.hostname)
protocol = 'http' if ((hostname and hostname.startswith('localhost')) or
util.is_running_on_devserver()) else ... | 516,773 |
JSON dict description of a protorpc.remote.Service in OpenAPI format.
Args:
services: Either a single protorpc.remote.Service or a list of them
that implements an api/version.
hostname: string, Hostname of the API, to override the value set on the
current service. Defaults to None.
... | def get_openapi_dict(self, services, hostname=None, x_google_api_name=False):
if not isinstance(services, (tuple, list)):
services = [services]
# The type of a class that inherits from remote.Service is actually
# remote._ServiceClass, thanks to metaclass strangeness.
# pylint: disable=prot... | 516,774 |
JSON string description of a protorpc.remote.Service in OpenAPI format.
Args:
services: Either a single protorpc.remote.Service or a list of them
that implements an api/version.
hostname: string, Hostname of the API, to override the value set on the
current service. Defaults to None.
... | def pretty_print_config_to_json(self, services, hostname=None, x_google_api_name=False):
descriptor = self.get_openapi_dict(services, hostname, x_google_api_name=x_google_api_name)
return json.dumps(descriptor, sort_keys=True, indent=2,
separators=(',', ': ')) | 516,775 |
Encode a python field value to a JSON value.
Args:
field: A ProtoRPC field instance.
value: A python value supported by field.
Returns:
A JSON serializable value appropriate for field. | def encode_field(self, field, value):
# Override the handling of 64-bit integers, so they're always encoded
# as strings.
if (isinstance(field, messages.IntegerField) and
field.variant in (messages.Variant.INT64,
messages.Variant.UINT64,
messa... | 516,776 |
Add padding characters to the value if needed.
Args:
value: The string value to be padded.
pad_len_multiple: Pad the result so its length is a multiple
of pad_len_multiple.
pad_char: The character to use for padding.
Returns:
The string value with padding characters added. | def __pad_value(value, pad_len_multiple, pad_char):
assert pad_len_multiple > 0
assert len(pad_char) == 1
padding_length = (pad_len_multiple -
(len(value) % pad_len_multiple)) % pad_len_multiple
return value + pad_char * padding_length | 516,777 |
Decode a JSON value to a python value.
Args:
field: A ProtoRPC field instance.
value: A serialized JSON value.
Returns:
A Python value compatible with field. | def decode_field(self, field, value):
# Override BytesField handling. Client libraries typically use a url-safe
# encoding. b64decode doesn't handle these gracefully. urlsafe_b64decode
# handles both cases safely. Also add padding if the padding is incorrect.
if isinstance(field, messages.Bytes... | 516,778 |
Add a new message.
Args:
message_type: protorpc.message.Message class to be parsed.
Returns:
string, The JSON Schema id.
Raises:
KeyError if the Schema id for this message_type would collide with the
Schema id of a different message_type that was already added. | def add_message(self, message_type):
name = self.__normalized_name(message_type)
if name not in self.__schemas:
# Set a placeholder to prevent infinite recursion.
self.__schemas[name] = None
schema = self.__message_to_schema(message_type)
self.__schemas[name] = schema
return nam... | 516,779 |
Returns the JSON Schema id for the given message.
Args:
message_type: protorpc.message.Message class to be parsed.
Returns:
string, The JSON Schema id.
Raises:
KeyError: if the message hasn't been parsed via add_message(). | def ref_for_message_type(self, message_type):
name = self.__normalized_name(message_type)
if name not in self.__schemas:
raise KeyError('Message has not been parsed: %s', name)
return name | 516,780 |
Normalized schema name.
Generate a normalized schema name, taking the class name and stripping out
everything but alphanumerics, and camel casing the remaining words.
A normalized schema name is a name that matches [a-zA-Z][a-zA-Z0-9]*
Args:
message_type: protorpc.message.Message class being par... | def __normalized_name(self, message_type):
# Normalization is applied to match the constraints that Discovery applies
# to Schema names.
name = message_type.definition_name()
split_name = re.split(r'[^0-9a-zA-Z]', name)
normalized = ''.join(
part[0].upper() + part[1:] for part in split... | 516,781 |
Parse a single message into JSON Schema.
Will recursively descend the message structure
and also parse other messages references via MessageFields.
Args:
message_type: protorpc.messages.Message class to parse.
Returns:
An object representation of the schema. | def __message_to_schema(self, message_type):
name = self.__normalized_name(message_type)
schema = {
'id': name,
'type': 'object',
}
if message_type.__doc__:
schema['description'] = message_type.__doc__
properties = {}
for field in message_type.all_fields():
d... | 516,782 |
Get information needed to convert the given parameter to its API type.
Args:
parameter_config: The dictionary containing information specific to the
parameter in question. This is retrieved from request.parameters in the
method config.
Returns:
The entry from _PARAM_CONVERSION_MAP with functio... | def _get_parameter_conversion_entry(parameter_config):
entry = _PARAM_CONVERSION_MAP.get(parameter_config.get('type'))
# Special handling for enum parameters. An enum's type is 'string', so we
# need to detect them by the presence of an 'enum' property in their
# configuration.
if entry is None and 'enum... | 516,785 |
Set the roots of the tree in the os environment
Parameters:
uproot_with (str):
A new TREE_DIR path used to override an existing TREE_DIR environment variable | def set_roots(self, uproot_with=None):
# Check for TREE_DIR
self.treedir = os.environ.get('TREE_DIR', None) if not uproot_with else uproot_with
if not self.treedir:
treefilepath = os.path.dirname(os.path.abspath(__file__))
if 'python/' in treefilepath:
... | 517,470 |
loads a config file
Parameters:
config (str):
Optional name of manual config file to load | def load_config(self, config=None):
# Read the config file
cfgname = (config or self.config_name)
cfgname = 'sdsswork' if cfgname is None else cfgname
assert isinstance(cfgname, six.string_types), 'config name must be a string'
config_name = cfgname if cfgname.endswith(... | 517,471 |
Set the individual section branches
This adds the various sections of the config file into the
tree environment for access later. Optically can specify a specific
branch. This does not yet load them into the os environment.
Parameters:
limb (str/list):
The ... | def branch_out(self, limb=None):
# Filter on sections
if not limb:
limbs = self._cfg.sections()
else:
# we must have the general always + secton
limb = limb if isinstance(limb, list) else [limb]
limbs = ['general']
limbs.exten... | 517,472 |
Add a new section from the tree into the existing os environment
Parameters:
key (str):
The section name to grab from the environment | def add_limbs(self, key=None):
self.branch_out(limb=key)
self.add_paths_to_os(key=key) | 517,473 |
Retrieve a set of environment paths from the config
Parameters:
key (str):
The section name to grab from the environment
Returns:
self.environ[newkey] (OrderedDict):
An ordered dict containing all of the paths from the
specified s... | def get_paths(self, key):
newkey = key if key in self.environ else key.upper() if key.upper() \
in self.environ else None
if newkey:
return self.environ[newkey]
else:
raise KeyError('Key {0} not found in tree environment'.format(key)) | 517,474 |
Add the paths in tree environ into the os environ
This code goes through the tree environ and checks
for existence in the os environ, then adds them
Parameters:
key (str):
The section name to check against / add
update (bool):
If True, ov... | def add_paths_to_os(self, key=None, update=None):
if key is not None:
allpaths = key if isinstance(key, list) else [key]
else:
allpaths = [k for k in self.environ.keys() if 'default' not in k]
for key in allpaths:
paths = self.get_paths(key)
... | 517,475 |
Replant the tree with a different config setup
Parameters:
config (str):
The config name to reload
exclude (list):
A list of environment variables to exclude
from forced updates | def replant_tree(self, config=None, exclude=None):
# reinitialize a new Tree with a new config
self.__init__(key=self.key, config=config, update=True, exclude=exclude) | 517,477 |
create an html table
Parameters:
environ (dict):
A tree environment dictionary
envdir (str):
The filepath for the env directory
Returns:
An html table definition string | def create_index_table(environ, envdir):
table_header =
table_footer =
# create table
table = table_header
# loop over the environment
for section, values in environ.items():
if section == 'default':
continue
for tree_name, tree_path in values.items():
... | 517,487 |
create the env index html page
Builds the index.html page containing a table of symlinks
to datamodel directories
Parameters:
environ (dict):
A tree environment dictionary
defaults (dict):
The defaults dictionary from environ['default']
envdir (str):
... | def create_index_page(environ, defaults, envdir):
# header of index file
header =
# footer of index file
footer =
# create index html file
index = header.format(**defaults)
index += create_index_table(environ, envdir)
index += footer.format(**defaults)
return index | 517,488 |
create the env symlink directory structure
Creates the env folder filled with symlinks to datamodel directories
for a given tree config file.
Parameters:
environ (dict):
A tree environment dictionary
mirror (bool):
If True, use the SAM url location
ver... | def create_env(environ, mirror=None, verbose=None):
defaults = environ['default'].copy()
defaults['url'] = "https://data.mirror.sdss.org" if mirror else "https://data.sdss.org"
defaults['location'] = "SDSS-IV Science Archive Mirror (SAM)" if mirror else "SDSS-IV Science Archive Server (SAS)"
if n... | 517,489 |
Check for the SAS_BASE_DIR environment variable
Will set the SAS_BASE_DIR in your local environment
or prompt you to define one if is undefined
Parameters:
root (str):
Optional override of the SAS_BASE_DIR envvar | def check_sas_base_dir(root=None):
sasbasedir = root or os.getenv("SAS_BASE_DIR")
if not sasbasedir:
sasbasedir = input('Enter a path for SAS_BASE_DIR: ')
os.environ['SAS_BASE_DIR'] = sasbasedir | 517,490 |
Write proper file header in a given shell format
Parameters:
term (str):
The type of shell header to write, can be "bash", "tsch", or "modules"
tree_dir (str):
The path to this repository
name (str):
The name of the configuration
Returns:
A s... | def write_header(term='bash', tree_dir=None, name=None):
assert term in ['bash', 'tsch', 'modules'], 'term must be either bash, tsch, or module'
product_dir = tree_dir.rstrip('/')
base = 'export' if term == 'bash' else 'setenv'
if term != 'modules':
hdr = .format(name, term, base, produc... | 517,491 |
Write a tree environment file
Loops over the tree environ and writes them out to a bash, tsch, or
modules file
Parameters:
environ (dict):
The tree dictionary environment
term (str):
The type of shell header to write, can be "bash", "tsch", or "modules"
tree... | def write_file(environ, term='bash', out_dir=None, tree_dir=None):
# get the proper name, header and file extension
name = environ['default']['name']
header = write_header(term=term, name=name, tree_dir=tree_dir)
exts = {'bash': '.sh', 'tsch': '.csh', 'modules': '.module'}
ext = exts[term]
... | 517,492 |
Get the tree for a given config
Parameters:
config (str):
The name of the tree config to load
Returns:
a Python Tree instance | def get_tree(config=None):
path = os.path.dirname(os.path.abspath(__file__))
pypath = os.path.realpath(os.path.join(path, '..', 'python'))
if pypath not in sys.path:
sys.path.append(pypath)
os.chdir(pypath)
from tree.tree import Tree
tree = Tree(config=config)
return tree | 517,493 |
Creates a list-table directive
for a set of defined environment variables
Parameters:
name (str):
The name of the config section
envvars (dict):
A dictionary of the environment variable definitions from the config
base (str):
The SAS_BASE to remove f... | def _format_command(name, envvars, base=None):
yield '.. list-table:: {0}'.format(name)
yield _indent(':widths: 20 50')
yield _indent(':header-rows: 1')
yield ''
yield _indent('* - Name')
yield _indent(' - Path')
for envvar, path in envvars.items():
tail = path.split(base)[1] ... | 517,498 |
Compute the global similarity between two structures A and B.
It uses the Sinkhorn algorithm as reported in:
Phys. Chem. Chem. Phys., 2016, 18, p. 13768
Args:
envkernel: NxM matrix of structure A with
N and structure B with M atoms
gamma: parameter to control between best match ... | def rematch_entry(envkernel, gamma = 0.1, threshold = 1e-6):
n, m = envkernel.shape
K = np.exp(-(1 - envkernel) / gamma)
# initialisation
u = np.ones((n,)) / n
v = np.ones((m,)) / m
en = np.ones((n,)) / float(n)
em = np.ones((m,)) / float(m)
Kp = (1 / en).reshape(-1, 1) * K
... | 517,995 |
Used to calculate discrete vectors for the polynomial basis functions.
Args:
rCut(float): Radial cutoff
nMax(int): Number of polynomial radial functions | def getPoly(rCut, nMax):
rCutVeryHard = rCut+5.0
rx = 0.5*rCutVeryHard*(x + 1)
basisFunctions = []
for i in range(1, nMax + 1):
basisFunctions.append(lambda rr, i=i, rCut=rCut: (rCut - np.clip(rr, 0, rCut))**(i+2))
# Calculate the overlap of the different polynomial functions in a
... | 518,006 |
Takes an ase Atoms object and returns numpy arrays and integers
which are read by the internal clusgeo. Apos is currently a flattened
out numpy array
Args:
obj():
all_atomtypes():
sort(): | def _format_ase2clusgeo(obj, all_atomtypes=None):
#atoms metadata
totalAN = len(obj)
if all_atomtypes is not None:
atomtype_set = set(all_atomtypes)
else:
atomtype_set = set(obj.get_atomic_numbers())
atomtype_lst = np.sort(list(atomtype_set))
n_atoms_per_type_lst = []
p... | 518,007 |
Initialization of the list
Args:
item_cls (str): Object class matching the list items
data (str or dict): A dictionary or raw JSON string that is returned by a request. | def __init__(self, item_cls, data):
super(ResourceList, self).__init__()
if data is not None:
data = json.loads(data) if type(data) is not dict else data
paging = data['list_info']
raw_items = data.get(self.items_keys[item_cls.__name__])
if raw_... | 518,245 |
Verify whether a HelloSign Account exists
Args:
email_address (str): Email address for the account to verify
Returns:
True or False | def verify_account(self, email_address):
request = self._get_request()
resp = request.post(self.ACCOUNT_VERIFY_URL, {
'email_address': email_address
})
return ('account' in resp) | 518,251 |
Get a signature request by its ID
Args:
signature_request_id (str): The id of the SignatureRequest to retrieve
ux_version (int): UX version, either 1 (default) or 2.
Returns:
A SignatureRequest object | def get_signature_request(self, signature_request_id, ux_version=None):
request = self._get_request()
parameters = None
if ux_version is not None:
parameters = {
'ux_version': ux_version
}
return request.get(self.SIGNATURE_REQUEST_INFO_... | 518,252 |
Get a list of SignatureRequest that you can access
This includes SignatureRequests you have sent as well as received, but
not ones that you have been CCed on.
Args:
page (int, optional): Which page number of the SignatureRequest list to return. Defaults to 1.
ux_ver... | def get_signature_request_list(self, page=1, ux_version=None):
request = self._get_request()
parameters = {
"page": page
}
if ux_version is not None:
parameters['ux_version'] = ux_version
return request.get(self.SIGNATURE_REQUEST_LIST_URL, para... | 518,253 |
Cancels a SignatureRequest
Cancels a SignatureRequest. After canceling, no one will be able to sign
or access the SignatureRequest or its documents. Only the requester can
cancel and only before everyone has signed.
Args:
signing_request_id (str): The id of the signature r... | def cancel_signature_request(self, signature_request_id):
request = self._get_request()
request.post(url=self.SIGNATURE_REQUEST_CANCEL_URL + signature_request_id, get_json=False) | 518,258 |
Gets a Template which includes a list of Accounts that can access it
Args:
template_id (str): The id of the template to retrieve
Returns:
A Template object | def get_template(self, template_id):
request = self._get_request()
return request.get(self.TEMPLATE_GET_URL + template_id) | 518,259 |
Gives the specified Account access to the specified Template
Args:
template_id (str): The id of the template to give the account access to
account_id (str): The id of the account to give access to the template. The account id prevails if both account_id and email_address ar... | def add_user_to_template(self, template_id, account_id=None, email_address=None):
return self._add_remove_user_template(self.TEMPLATE_ADD_USER_URL, template_id, account_id, email_address) | 518,261 |
Removes the specified Account's access to the specified Template
Args:
template_id (str): The id of the template to remove the account's access from.
account_id (str): The id of the account to remove access from the template. The account id prevails if both account_id and e... | def remove_user_from_template(self, template_id, account_id=None, email_address=None):
return self._add_remove_user_template(self.TEMPLATE_REMOVE_USER_URL, template_id, account_id, email_address) | 518,262 |
Deletes the specified template
Args:
template_id (str): The id of the template to delete
Returns:
A status code | def delete_template(self, template_id):
url = self.TEMPLATE_DELETE_URL
request = self._get_request()
response = request.post(url + template_id, get_json=False)
return response | 518,263 |
Download a PDF copy of a template's original files
Args:
template_id (str): The id of the template to retrieve.
filename (str): Filename to save the PDF file to. This should be a full path.
Returns:
Returns a PDF file | def get_template_files(self, template_id, filename):
url = self.TEMPLATE_GET_FILES_URL + template_id
request = self._get_request()
return request.get_file(url, filename) | 518,264 |
Creates a new Team
Creates a new Team and makes you a member. You must not currently belong to a team to invoke.
Args:
name (str): The name of your team
Returns:
A Team object | def create_team(self, name):
request = self._get_request()
return request.post(self.TEAM_CREATE_URL, {"name": name}) | 518,266 |
Updates a Team's name
Args:
name (str): The new name of your team
Returns:
A Team object | def update_team_name(self, name):
request = self._get_request()
return request.post(self.TEAM_UPDATE_URL, {"name": name}) | 518,267 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.